@kenz1117/dsh-ui-usage-billing 1.4.27 → 1.4.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +7 -2
- package/README.md +5 -2
- package/lib/client.js +1 -1
- package/lib/types/aggregate.d.ts +26 -3
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -259,11 +259,16 @@ None. This plugin is a pure UI surface: it registers no tools, injects no system
|
|
|
259
259
|
|
|
260
260
|
## ❤️ Contributors
|
|
261
261
|
|
|
262
|
-
- [@lucagiftzek](https://github.com/lucagiftzek) — rate-table CSS polish (PR #59), `trustedHosts` reverse-proxy support (PR #60), currency preference persistence (PR #58), rate-table search (PR #67), peak/off-peak indicator dots with pin-to-composer (PR #68),
|
|
263
|
-
- [@hwangjunjie](https://github.com/hwangjunjie) — Tencent Cloud TokenHub / Token Plan subscription quota adaptation (`src/tc3.ts`), provider-first channel grouping with gateway badges,
|
|
262
|
+
- [@lucagiftzek](https://github.com/lucagiftzek) — rate-table CSS polish (PR #59), `trustedHosts` reverse-proxy support (PR #60), currency preference persistence (PR #58), rate-table search (PR #67), peak/off-peak indicator dots with pin-to-composer (PR #68), the EUR display currency with language decoupling (PR #70), the first pricing fetch moved ahead of the warmup replay (PR #55), evidence-based models.dev listings (PR #56), and hardcoded UI strings routed through locale dictionaries (PR #61)
|
|
263
|
+
- [@hwangjunjie](https://github.com/hwangjunjie) — Tencent Cloud TokenHub / Token Plan subscription quota adaptation (`src/tc3.ts`), provider-first channel grouping with gateway badges, the `routeAliases` / `modelKeyAliases` config (PR #35), and subscription badges decided per channel on the day × model × site cells (PR #83)
|
|
264
264
|
- [@ciphoo](https://github.com/ciphoo) — MiniMax CN Token Plan quota support (PR #5), `minimax-cn` subscription key wiring (PR #12), a concurrent-ledger-write `MoveFileExW EPERM` fix on Windows (PR #11)
|
|
265
265
|
- [@fabulousyuann-tech](https://github.com/fabulousyuann-tech) — durable ledger that retains usage after session deletion (PR #8)
|
|
266
266
|
- [@hi-fangj](https://github.com/hi-fangj) — hover tooltip with the exact per-day token breakdown on the token daily chart (PR #21), the live-cost capsule toggle (PR #22), the per-model view and legend focus for the token daily chart (PR #23), and the per-model comparison curve in the perf panel (PR #24)
|
|
267
|
+
- [@aizhimoran](https://github.com/aizhimoran) — peak/off-peak tiering for Chinese statutory holidays and shifted workdays: DeepSeek usage-based pricing bills holidays entirely at the off-peak rate (official 2026-09-19), with a 10-day countdown scan window (issue #73, PR #74)
|
|
268
|
+
- [@kidbird](https://github.com/kidbird) — wired up the international Z.ai Coding Plan (`zai-coding`) subscription quota, pinning each route to its own region with split key fields (PR #79)
|
|
269
|
+
- [@yuxu4468-hash](https://github.com/yuxu4468-hash) — cataloging for bare relay-exposed model ids: Grok 4.5/4.6, GPT-5.5, GPT-6.1 Sol, Claude Opus 4.7/4.8 and Fable 5 (PR #87), plus the GPT image models `gpt-image-2` / `gpt-image-2.5-sunburst` (PR #88)
|
|
270
|
+
- [@JinruiWang](https://github.com/JinruiWang) — workbuddy adapter channel pricing and the fold-before-live-catalog dual-caliber fix: the known-channel list, three lazy-reprice gates (ledger, cache hit, incremental cursor) and the stable-stamp reproduction test (issue #90)
|
|
271
|
+
- [@gitfangj](https://github.com/gitfangj) — `sync.sh` brace-variable compatibility under the macOS default bash 3.2
|
|
267
272
|
|
|
268
273
|
## 📄 License
|
|
269
274
|
|
package/README.md
CHANGED
|
@@ -273,12 +273,15 @@ npm publish --access public
|
|
|
273
273
|
|
|
274
274
|
## ❤️ Contributors
|
|
275
275
|
|
|
276
|
-
- [@lucagiftzek](https://github.com/lucagiftzek) — 费率表 CSS 修整(PR #59)、`trustedHosts` 反代支持(PR #60)、币种偏好持久化(PR #58)、费率表搜索(PR #67)、峰谷指示点与固定到输入框(PR #68)、EUR 展示币种与界面语言解耦(PR #70)
|
|
277
|
-
- [@hwangjunjie](https://github.com/hwangjunjie) — 腾讯云 TokenHub / Token Plan 订阅额度适配(`src/tc3.ts`)、提供商优先通道分组与网关徽标、`routeAliases` / `modelKeyAliases` 配置(PR #35)
|
|
276
|
+
- [@lucagiftzek](https://github.com/lucagiftzek) — 费率表 CSS 修整(PR #59)、`trustedHosts` 反代支持(PR #60)、币种偏好持久化(PR #58)、费率表搜索(PR #67)、峰谷指示点与固定到输入框(PR #68)、EUR 展示币种与界面语言解耦(PR #70)、首次价目表拉取前置到预热回放(PR #55)、models.dev 收录按证据取舍(PR #56)、硬编码 UI 文案入词典(PR #61)
|
|
277
|
+
- [@hwangjunjie](https://github.com/hwangjunjie) — 腾讯云 TokenHub / Token Plan 订阅额度适配(`src/tc3.ts`)、提供商优先通道分组与网关徽标、`routeAliases` / `modelKeyAliases` 配置(PR #35)、订阅徽标按三维格逐通道判定(PR #83)
|
|
278
278
|
- [@ciphoo](https://github.com/ciphoo) — MiniMax 国内域 Token Plan 订阅额度支持(PR #5)、`minimax-cn` 订阅凭据接线(PR #12)、Windows 下账本并发写入 `MoveFileExW EPERM` 修复(PR #11)
|
|
279
279
|
- [@fabulousyuann-tech](https://github.com/fabulousyuann-tech) — 会话删除后用量保留的持久 ledger 功能(PR #8)
|
|
280
280
|
- [@hi-fangj](https://github.com/hi-fangj) — Token 每日图悬停精确明细(PR #21)、平价消耗胶囊开关(PR #22)、Token 每日图按模型视角与图例聚焦(PR #23)、性能面板按模型对比曲线(PR #24)
|
|
281
281
|
- [@aizhimoran](https://github.com/aizhimoran) — 峰谷分档支持中国法定节假日与调休:DeepSeek 按量分时把法定节假日全天按空闲时段计费(官方 2026-09-19 口径),含 10 天倒计时扫描窗(issue #73、PR #74)
|
|
282
|
+
- [@kidbird](https://github.com/kidbird) — 接入国际版 Z.ai Coding Plan(`zai-coding`)订阅额度,两条路由各自固定区域与 key 双字段分离(PR #79)
|
|
283
|
+
- [@yuxu4468-hash](https://github.com/yuxu4468-hash) — 中转站裸模型 id 计费补录:Grok 4.5/4.6、GPT-5.5、GPT-6.1 Sol、Claude Opus 4.7/4.8、Fable 5(PR #87),GPT 绘图模型 `gpt-image-2` / `gpt-image-2.5-sunburst`(PR #88)
|
|
284
|
+
- [@JinruiWang](https://github.com/JinruiWang) — workbuddy adapter 通道计价与「折叠早于实时价目表」双口径修复:已知通道名单、惰性补折三门(账本 / cache 命中 / 增量游标)与 stable-stamp 复现测试(issue #90)
|
|
282
285
|
- [@gitfangj](https://github.com/gitfangj) — `sync.sh` 在 macOS 缺省 bash 3.2 下的花括号变量兼容修复
|
|
283
286
|
|
|
284
287
|
## 📄 许可证
|
package/lib/client.js
CHANGED
|
@@ -2,5 +2,5 @@ window.__ModuleLoader__.load({id:`@kenz1117/dsh-ui-usage-billing`,factory:e=>{va
|
|
|
2
2
|
`)}function qt(e){return[`site,kind,calls,cost_cny`,...Object.entries(e).map(([e,t])=>{let n=e.startsWith(`site:`)?e.slice(5):e.startsWith(`direct:`)?e.slice(7):`unknown`,r=e.startsWith(`site:`)?`site`:e.startsWith(`direct:`)?`direct`:`unknown`;return[Y(Wt(n)),r,t.calls,Gt(t.cost)].join(`,`)})].join(`
|
|
3
3
|
`)}function Jt(e){return e===void 0?``:e.split(/[\\/]/).filter(Boolean).pop()??e}function Yt(e){return[`session_id,title,project,calls,cost_cny,last_active`,...e.map(e=>[Y(Wt(e.id)),Y(Wt(e.title??``)),Y(Wt(Jt(e.cwd))),e.calls,Gt(e.cost),e.lastActive>0?new Date(e.lastActive).toISOString():``].join(`,`))].join(`
|
|
4
4
|
`)}function Xt(e,t,n){let r=[...n].sort(),i=r[0],a=r.at(-1);return`${e}${i!==void 0&&a!==void 0?`-${i}_${a}`:``}.${t}`}function Zt(e,t,n){let r=URL.createObjectURL(new Blob([t],{type:n})),i=document.createElement(`a`);i.href=r,i.download=e,i.click(),setTimeout(()=>URL.revokeObjectURL(r),0)}function Qt(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(Math.round(e))}let X={top:14,right:18,bottom:22,left:46},$t=`var(--ds-blue)`,en=`var(--ds-cyan)`,tn=`var(--ds-amber)`;function nn(e,t,n,r){return JSON.stringify({days:e,models:t,dayModels:n,total:r},null,2)}function rn(e){let{stats:t,trendDays:n,onTrendDays:r,t:i}=e,a=e.money,o=e.models??[],{byDay:s,byModel:c,total:l}=t,[u,f]=(0,d.useState)(null),[p,h]=(0,d.useState)(`structure`),[g,_]=(0,d.useState)(null),v=t.byDayModels!==void 0,b=e=>{h(e),_(null)},x=(0,d.useMemo)(()=>{let e=t.byRole;if(e===void 0)return[];let n=e.user+e.assistant+e.tool;return n<=0?[]:[{label:i(`roleUser`),value:e.user,seg:I.shareSegUser},{label:i(`roleAssistant`),value:e.assistant,seg:I.shareSegAssistant},{label:i(`roleTool`),value:e.tool,seg:I.shareSegTool}].map(e=>({...e,pct:e.value/n*100}))},[t.byRole,i]),S=(0,d.useMemo)(()=>{let e=[];for(let t=n-1;t>=0;--t){let n=new Date;n.setDate(n.getDate()-t);let r=q(n.getTime()),i=s[r];e.push({date:r,miss:i?.cacheMiss??0,hit:i?.cacheHit??0,output:i?.output??0,reasoning:i?.reasoning??0})}return e},[s,n]),C=(0,d.useMemo)(()=>{let e=[];for(let r=n-1;r>=0;--r){let n=new Date;n.setDate(n.getDate()-r);let i=q(n.getTime()),a=t.byDayModels?.[i],o={},s=0;if(a!==void 0)for(let[e,t]of Object.entries(a)){let n=t.cacheHit??0,r=t.cacheMiss??0,i=t.output??0,a=n+r+i;a<=0||(o[e]={hit:n,miss:r,output:i,total:a},s+=a)}e.push({date:i,models:o,total:s})}return e},[t.byDayModels,n]),w=(0,d.useMemo)(()=>{let e=new Map;for(let t of C)for(let[n,r]of Object.entries(t.models))e.set(n,(e.get(n)??0)+r.total);return[...e.entries()].sort((e,t)=>t[1]-e[1]).map(([e])=>({key:e,name:o.find(t=>t.key===e)?.name??Mt(e).name,color:o.find(t=>t.key===e)?.color??`#8b95a3`}))},[C,o]),T=g!==null&&w.some(e=>e.key===g)?g:null,ee=e=>{if(v){if(p!==`model`){h(`model`),_(e);return}_(t=>t===e?null:e)}},E=(0,d.useMemo)(()=>{let e=0;return Object.entries(c).filter(([,e])=>e.calls>0).map(([t,n])=>{let r=n.input+n.output;e+=r;let i=n.cacheHit+n.cacheMiss;return{key:t,name:Mt(t).name,input:n.input,output:n.output,reasoning:n.reasoning??0,calls:n.calls,cacheHit:n.cacheHit,cacheMiss:n.cacheMiss,cacheHitRate:i>0?n.cacheHit/i*100:0,total:r,share:0}}).sort((e,t)=>t.total-e.total).map(t=>({...t,share:e>0?t.total/e:0}))},[c]),D=(0,d.useMemo)(()=>{let e=Object.entries(t.byTool??{}),n=e.slice(0,8),r=e.slice(8).reduce((e,[,t])=>e+t,0),i=e.reduce((e,[,t])=>e+t,0);return{top:n,rest:r>0?[[`…`,r]]:[],totalCalls:i}},[t.byTool]),O=(0,d.useMemo)(()=>{let e=S.length;if(e===0)return null;let t=680-X.left-X.right,n=200-X.top-X.bottom,r=Math.max(...p===`model`?C.map(e=>e.total):S.map(e=>e.miss+e.hit+e.output),1),i=e=>X.top+n-e/r*n,a=t/e,o=Math.min(20,a*.6),s=n=>e===1?X.left+t/2:X.left+t*n/(e-1),c=Math.max(1,Math.ceil(e/8)),l=[];for(let t=0;t<e;t+=c)l.push(t);return e>0&&l[l.length-1]!==e-1&&l.push(e-1),{n:e,plotW:t,plotH:n,max:r,y:i,barW:o,inner:s,indices:l,groupW:a}},[S,C,p]),te=()=>{Zt(`token-daily-${q()}.csv`,an(S),`text/csv`)},ne=()=>{Zt(`token-${q()}.json`,nn(S,E,C,l),`application/json`)},k=u===null?void 0:S[u],re=u===null?void 0:C[u],ie=O===null?0:Math.ceil(80/Math.max(O.groupW,1)),A=u===null||O===null?void 0:u>=O.n-ie?I.chartTooltipAlignRight:u<ie?I.chartTooltipAlignLeft:void 0;return(0,m.jsxs)(`div`,{className:I.tokenPanel,"data-testid":`billing-token-panel`,children:[(0,m.jsxs)(`div`,{className:I.exportBar,role:`group`,"aria-label":i(`tokenExport`),children:[(0,m.jsx)(`span`,{className:I.exportLabel,children:i(`export`)}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-token-export-csv`,onClick:te,children:i(`tokenExportCsv`)}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-token-export-json`,onClick:ne,children:i(`exportJson`)})]}),(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-token-daily`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:i(`tokenDaily`)}),(0,m.jsxs)(`span`,{className:I.panelHeadControls,children:[v&&(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":i(`tokenDaily`),children:[`structure`,`model`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,p===e&&I.rangeButtonActive),"aria-pressed":p===e,onClick:()=>{b(e)},"data-testid":`billing-token-view-${e}`,children:i(e===`structure`?`tokenViewStructure`:`tokenViewModel`)},e))}),(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":i(`tokenDaily`),children:[7,30].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,n===e&&I.rangeButtonActive),"aria-pressed":n===e,onClick:()=>{r(e)},"data-testid":`billing-token-${e}d`,children:i(e===7?`trend7d`:`trend30d`)},e))})]})]}),O===null||p===`model`&&w.length===0?(0,m.jsx)(`div`,{className:I.chartEmpty,children:i(`trendEmpty`)}):(0,m.jsxs)(`div`,{className:I.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 200`,className:I.chartSvg,role:`img`,"aria-label":i(`tokenDaily`),onMouseLeave:()=>{f(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect(),n=((e.clientX-t.left)/t.width*680-X.left)/O.plotW,r=Math.round(n*(O.n-1));f(Math.min(Math.max(r,0),O.n-1))},children:[[0,.5,1].map(e=>{let t=O.max*e,n=O.y(t);return(0,m.jsxs)(`g`,{children:[(0,m.jsx)(`line`,{x1:X.left,x2:680-X.right,y1:n,y2:n,className:I.chartGrid}),(0,m.jsx)(`text`,{x:X.left-8,y:n+3,textAnchor:`end`,className:I.chartAxisLabel,children:Qt(t)})]},e)}),p===`structure`?S.map((e,t)=>{let n=O.inner(t)-O.barW/2,r=O.y(0),i=O.y(e.miss),a=O.y(e.miss+e.hit),o=O.y(e.miss+e.hit+e.output);return(0,m.jsxs)(`g`,{children:[(0,m.jsx)(`rect`,{x:n,y:i,width:O.barW,height:r-i,fill:$t}),(0,m.jsx)(`rect`,{x:n,y:a,width:O.barW,height:i-a,fill:en}),(0,m.jsx)(`rect`,{x:n,y:o,width:O.barW,height:a-o,fill:tn})]},e.date)}):C.map((e,t)=>{let n=O.inner(t)-O.barW/2,r=0;return(0,m.jsx)(`g`,{children:w.map(t=>{let i=e.models[t.key];if(i===void 0)return null;let a=O.y(r);r+=i.total;let o=O.y(r),s=T!==null&&t.key!==T;return(0,m.jsx)(`rect`,{x:n,y:o,width:O.barW,height:a-o,fill:t.color,opacity:s?.15:1},t.key)})},e.date)}),O.indices.map(e=>{let t=S[e];return t===void 0?null:(0,m.jsx)(`text`,{x:O.inner(e),y:194,textAnchor:`middle`,className:I.chartAxisLabel,children:t.date.slice(5)},t.date)}),u!==null&&(0,m.jsx)(`line`,{x1:O.inner(u),x2:O.inner(u),y1:X.top,y2:X.top+O.plotH,className:I.chartCrosshair})]}),u!==null&&p===`structure`&&k!==void 0&&(0,m.jsxs)(`div`,{className:y(I.chartTooltip,A),"data-testid":`billing-token-tooltip`,style:{left:`${O.inner(u)/680*100}%`,top:`${O.y(k.miss+k.hit+k.output)/200*100}%`},children:[(0,m.jsxs)(`div`,{className:I.chartTooltipHead,children:[(0,m.jsx)(`span`,{className:I.chartTooltipDate,children:k.date}),(0,m.jsx)(`strong`,{children:(k.miss+k.hit+k.output).toLocaleString()})]}),(0,m.jsxs)(`div`,{className:y(I.chartTooltipRow,I.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:I.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:en}}),i(`tokenHit`)]}),(0,m.jsx)(`strong`,{children:k.hit.toLocaleString()})]}),(0,m.jsxs)(`div`,{className:y(I.chartTooltipRow,I.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:I.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:$t}}),i(`tokenMiss`)]}),(0,m.jsx)(`strong`,{children:k.miss.toLocaleString()})]}),(0,m.jsxs)(`div`,{className:y(I.chartTooltipRow,I.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:I.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:tn}}),i(`tokenOutput`)]}),(0,m.jsx)(`strong`,{children:k.output.toLocaleString()})]})]}),u!==null&&p===`model`&&re!==void 0&&(0,m.jsxs)(`div`,{className:y(I.chartTooltip,A),"data-testid":`billing-token-tooltip`,style:{left:`${O.inner(u)/680*100}%`,top:`${O.y(re.total)/200*100}%`},children:[(0,m.jsxs)(`div`,{className:I.chartTooltipHead,children:[(0,m.jsx)(`span`,{className:I.chartTooltipDate,children:re.date}),(0,m.jsx)(`strong`,{children:re.total.toLocaleString()})]}),w.map(e=>{let t=re.models[e.key];return t===void 0?null:(0,m.jsxs)(`div`,{className:I.chartTooltipModel,children:[(0,m.jsxs)(`div`,{className:y(I.chartTooltipRow,I.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:I.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name]}),(0,m.jsx)(`strong`,{children:t.total.toLocaleString()})]}),(0,m.jsxs)(`div`,{className:I.chartTooltipModelDetail,children:[i(`tokenHitShort`),` `,t.hit.toLocaleString(),` · `,i(`tokenMissShort`),` `,t.miss.toLocaleString(),` · `,i(`tokenOutput`),` `,t.output.toLocaleString()]})]},e.key)})]}),(0,m.jsx)(`div`,{className:I.chartLegend,children:p===`structure`?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:$t}}),i(`tokenMiss`)]}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:en}}),i(`tokenHit`)]}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:tn}}),i(`tokenOutput`)]})]}):w.map(e=>(0,m.jsxs)(`button`,{type:`button`,className:y(I.chartLegendItem,T===e.key&&I.chartLegendItemActive),"aria-pressed":T===e.key,"data-testid":`billing-token-legend-${e.key}`,onClick:()=>{ee(e.key)},children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name]},e.key))})]})]}),(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-token-models`,children:[(0,m.jsx)(`div`,{className:I.panelHead,children:(0,m.jsx)(`h3`,{className:I.panelTitle,children:i(`tokenByModel`)})}),E.length===0?(0,m.jsx)(`div`,{className:I.emptyRow,children:i(`noData`)}):(0,m.jsx)(`div`,{className:I.tableScroll,children:(0,m.jsxs)(`table`,{className:I.modelTable,"data-testid":`billing-token-model-table`,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:i(`model`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`inputTokens`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`outputTokens`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`tokenReasoningShort`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`cacheHitRate`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`tokenTotal`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`tokenShare`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`calls`)})]})}),(0,m.jsx)(`tbody`,{children:E.map(e=>(0,m.jsxs)(`tr`,{"data-testid":`billing-token-model`,className:y(v&&I.modelRowFocusable,T===e.key&&I.modelRowActive),"aria-selected":v?T===e.key:void 0,onClick:v?()=>{ee(e.key)}:void 0,tabIndex:v?0:void 0,onKeyDown:v?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),ee(e.key))}:void 0,children:[(0,m.jsx)(`td`,{children:(0,m.jsx)(`span`,{className:I.modelName,children:e.name})}),(0,m.jsx)(`td`,{className:I.numCol,children:J(e.input)}),(0,m.jsx)(`td`,{className:I.numCol,children:J(e.output)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.reasoning>0?J(e.reasoning):(0,m.jsx)(`span`,{className:I.na,children:`—`})}),(0,m.jsxs)(`td`,{className:I.numCol,children:[e.cacheHitRate.toFixed(1),`%`]}),(0,m.jsx)(`td`,{className:I.numCol,children:J(e.total)}),(0,m.jsx)(`td`,{className:I.numCol,children:(0,m.jsxs)(`span`,{className:I.tokenModelShareRow,children:[(0,m.jsx)(`span`,{className:I.tokenModelBar,children:(0,m.jsxs)(`span`,{className:I.tokenModelParts,style:{width:`${(e.share*100).toFixed(2)}%`},children:[(0,m.jsx)(`span`,{className:I.tokenModelPartIn,style:{width:`${e.total>0?e.input/e.total*100:0}%`}}),(0,m.jsx)(`span`,{className:I.tokenModelPartOut,style:{width:`${e.total>0?e.output/e.total*100:0}%`}})]})}),(e.share*100).toFixed(1),`%`]})}),(0,m.jsx)(`td`,{className:I.numCol,children:e.calls.toLocaleString()})]},e.key))})]})})]}),D.totalCalls>0&&(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-token-tools`,children:[(0,m.jsx)(`div`,{className:I.panelHead,children:(0,m.jsx)(`h3`,{className:I.panelTitle,children:i(`toolRank`)})}),(0,m.jsx)(`div`,{className:I.tableScroll,children:(0,m.jsxs)(`table`,{className:I.modelTable,"data-testid":`billing-tool-table`,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:i(`toolName`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`calls`)}),(0,m.jsx)(`th`,{className:I.numCol,children:i(`tokenShare`)})]})}),(0,m.jsx)(`tbody`,{children:[...D.top,...D.rest].map(([e,t])=>(0,m.jsxs)(`tr`,{"data-testid":`billing-tool-row`,children:[(0,m.jsx)(`td`,{children:(0,m.jsx)(`span`,{className:I.modelName,children:e})}),(0,m.jsx)(`td`,{className:I.numCol,children:t.toLocaleString()}),(0,m.jsxs)(`td`,{className:I.numCol,children:[(t/D.totalCalls*100).toFixed(1),`%`]})]},e))})]})})]}),x.length>0&&(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-roles`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:i(`roleCost`)}),(0,m.jsx)(`span`,{className:I.panelHint,children:i(`roleHint`)})]}),(0,m.jsx)(`div`,{className:I.shareTrack,"data-testid":`billing-role-track`,children:x.map(e=>(0,m.jsx)(`div`,{className:y(I.shareSeg,e.seg),style:{width:`${e.pct}%`}},e.label))}),(0,m.jsx)(`div`,{className:I.shareLegend,children:x.map(e=>(0,m.jsxs)(`span`,{className:I.shareItem,children:[(0,m.jsx)(`span`,{className:y(I.shareDot,e.seg)}),e.label,(0,m.jsxs)(`span`,{className:I.shareValue,children:[a(e.value),` · `,e.pct.toFixed(1),`%`]})]},e.label))})]})]})}function an(e){return[`date,missInput,cacheHit,output,reasoning,total`,...e.map(e=>`${e.date},${e.miss},${e.hit},${e.output},${e.reasoning},${e.miss+e.hit+e.output}`)].join(`
|
|
5
|
-
`)}let Z={top:18,right:40,bottom:26,left:46};function on(e){let[,t,n]=e.split(`-`);return`${Number(t)}/${Number(n)}`}function sn(e,t){let n=[];for(let r=0;r<e;r+=t)n.push(r);return e>0&&n[n.length-1]!==e-1&&n.push(e-1),n}let cn={key:`__total__`,name:``,color:``};function ln({data:e,models:t=[],currency:n=`cny`,metric:r=`cost`,t:i}){let a=i??(e=>Pe[e]),[o,s]=(0,d.useState)(null),c=e=>K(Bt(e,n),n),l=e=>r===`tokens`?Qt(e):c(e),u=e=>r===`tokens`?e.tokens??0:e.cost,f=(0,d.useMemo)(()=>{let n=e.length;if(n===0)return null;let i=680-Z.left-Z.right,a=220-Z.top-Z.bottom,o=e=>n===1?Z.left+i/2:Z.left+i*e/(n-1),s=Math.max(...r===`tokens`?e.map(e=>e.tokens??0):e.map(e=>Math.max(e.cost,Object.values(e.byModel??{}).reduce((e,t)=>e+t,0))),1e-4),c=e=>Z.top+a-e/s*a,l=Math.max(...e.map(e=>e.calls),1),d=e=>Z.top+a-e/l*a,f=i/n,p=Math.min(18,f*.6);return{n,plotW:i,plotH:a,inner:o,yCost:c,yCalls:d,barW:p,bars:e.flatMap((e,n)=>{let i=o(n)-p/2;if(t.length===0||r===`tokens`)return[{date:e.date,model:cn,x:i,base:0,value:u(e),topRounded:!0}];let a=null;for(let n of t)(e.byModel?.[n.key]??0)>0&&(a=n.key);let s=0;return t.map(t=>{let n=e.byModel?.[t.key]??0,r={date:e.date,model:t,x:i,base:s,value:n,topRounded:t.key===a};return s+=n,r})}),costTicks:[0,.25,.5,.75,1].map(e=>s*e).reverse(),callsTicks:[0,.25,.5,.75,1].map(e=>l*e).reverse(),linePath:e.map((e,t)=>{let n=d(e.calls);return`${t===0?`M`:`L`}${o(t)} ${n}`}).join(` `)}},[e,t,r]);if(f===null)return(0,m.jsx)(`div`,{className:I.chartEmpty,children:a(`trendEmpty`)});let{n:p,plotW:h,plotH:g,inner:_,yCost:v,yCalls:y,barW:b,bars:x,costTicks:S,callsTicks:C,linePath:w}=f,T=o===null?void 0:e[o],ee=sn(p,Math.max(1,Math.ceil(p/8)));return(0,m.jsxs)(`div`,{className:I.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 220`,className:I.chartSvg,role:`img`,"aria-label":`Daily cost by model and total calls`,onMouseLeave:()=>{s(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect(),n=((e.clientX-t.left)/t.width*680-Z.left)/h,r=Math.round(n*(p-1));s(Math.min(Math.max(r,0),p-1))},children:[S.map((e,t)=>{let n=v(e);return(0,m.jsxs)(`g`,{children:[(0,m.jsx)(`line`,{x1:Z.left,x2:680-Z.right,y1:n,y2:n,className:I.chartGrid}),(0,m.jsx)(`text`,{x:Z.left-8,y:n+3,textAnchor:`end`,className:I.chartAxisLabel,children:l(e)})]},`cost-${t}`)}),x.map(t=>{if(t.value>0)return(0,m.jsx)(`rect`,{x:t.x,y:v(t.base+t.value),width:b,height:v(t.base)-v(t.base+t.value),rx:t.topRounded?2:0,className:t.model.color===``?I.chartBar:I.chartStack,style:t.model.color===``?void 0:{fill:t.model.color}},`${t.date}-${t.model.key}`);let n=e.find(e=>e.date===t.date);return n!==void 0&&n.calls>0&&t.base===0?(0,m.jsx)(`rect`,{x:t.x,y:v(0)-1,width:b,height:1,rx:0,className:I.chartBarPlaceholder},`${t.date}-${t.model.key}-placeholder`):null}),(0,m.jsx)(`path`,{d:w,fill:`none`,className:I.chartLine}),C.map((e,t)=>{let n=y(e);return(0,m.jsx)(`text`,{x:680-Z.right+8,y:n+3,textAnchor:`start`,className:I.chartAxisLabel,children:Qt(e)},`calls-${t}`)}),ee.map(t=>{let n=e[t];return n===void 0?null:(0,m.jsx)(`text`,{x:_(t),y:214,textAnchor:`middle`,className:I.chartAxisLabel,children:on(n.date)},n.date)}),o!==null&&(0,m.jsx)(`line`,{x1:_(o),x2:_(o),y1:Z.top,y2:Z.top+g,className:I.chartCrosshair})]}),T!==void 0&&o!==null&&(0,m.jsxs)(`div`,{className:I.chartTooltip,style:{left:`${_(o)/680*100}%`,top:`${v(T.cost)/220*100}%`},children:[(0,m.jsx)(`div`,{className:I.chartTooltipDate,children:T.date}),r!==`tokens`&&t.filter(e=>(T.byModel?.[e.key]??0)>0).map(e=>(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name,` `,(0,m.jsx)(`strong`,{children:c(T.byModel?.[e.key]??0)})]},e.key)),(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartLegendBar}),a(`trendTotal`),` `,(0,m.jsx)(`strong`,{children:r===`tokens`?Qt(T.tokens??0):c(T.cost)})]}),(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartLegendLine}),a(`calls`),` `,(0,m.jsx)(`strong`,{children:T.calls.toLocaleString()})]})]}),t.length>0&&r!==`tokens`&&(0,m.jsxs)(`div`,{className:I.chartLegend,children:[t.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name]},e.key)),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.chartLegendLine}),a(`calls`)]})]})]})}let Q={top:14,right:42,bottom:22,left:46};function un(e){return e.slice(5,13).replace(`T`,` `)}function dn(e){return String(e>=100?Math.round(e):Number(e.toFixed(1)))}function fn(e){return e<1e4?`${Math.round(e)} ms`:e<6e4?`${(e/1e3).toFixed(1)} s`:`${(e/6e4).toFixed(1)} min`}function pn(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function mn(e,t,n){return t===`ttft`?`${Math.round(e)} ms`:`${e.toFixed(1)} ${n(`perfTpsUnit`)}`}function hn({perf:e,models:t,t:n}){let[r,i]=(0,d.useState)(()=>Ae()),[a,o]=(0,d.useState)(null),s=e=>{i(e),je(e)},c=e=>t.find(t=>t.key===e)?.color??`#8b95a3`,l=(0,d.useMemo)(()=>e===void 0?[]:Object.entries(e.byModel).map(([e,n])=>({key:e,name:t.find(t=>t.key===e)?.name??e,color:c(e),samples:n.samples,ttftAvg:n.ttftAvg,ttftP50:n.ttftP50,ttftP90:n.ttftP90,...n.ttftMax===void 0?{}:{ttftMax:n.ttftMax},...n.ttftSpikes===void 0?{}:{ttftSpikes:n.ttftSpikes},...n.tpsAvg===void 0?{}:{tpsAvg:n.tpsAvg},latencyAvg:n.latencyAvg,estimatedSamples:n.estimatedSamples})).sort((e,t)=>t.samples-e.samples||t.ttftP90-e.ttftP90),[e,t]),u=(0,d.useMemo)(()=>{if(e===void 0)return[];if(r.models!==void 0){let t=new Set(Object.keys(e.byModel));return r.models.filter(e=>t.has(e))}return l.slice(0,5).map(e=>e.key)},[e,l,r.models]),f=(0,d.useMemo)(()=>{if(e===void 0)return null;let t=Object.keys(e.byHourModel).sort().slice(-48);if(t.length===0)return null;let n=t.length,i=680-Q.left-Q.right,a=180-Q.top-Q.bottom,o=e=>n===1?Q.left+i/2:Q.left+i*e/(n-1),s=new Set(u),c=e=>r.metric===`ttft`?e?.ttftAvg:e?.tpsAvg,d=[],f=0;for(let r of l){if(!s.has(r.key))continue;let i=[];for(let a=0;a<n;a++){let n=t[a];if(n===void 0)continue;let s=c(e.byHourModel[n]?.[r.key]);s===void 0||!Number.isFinite(s)||(i.push({i:a,x:o(a),y:0,v:s}),s>f&&(f=s))}d.push({key:r.key,name:r.name,color:r.color,segments:[],points:i})}let p=d.reduce((e,t)=>e+t.points.length,0);f=Math.max(f,1);let m=e=>Q.top+a-e/f*a;for(let e of d){let t=``,n=-2;for(let r of e.points)r.y=m(r.v),t!==``&&r.i!==n+1&&(e.segments.push(t),t=``),t+=`${t===``?`M`:`L`}${r.x} ${r.y} `,n=r.i;t!==``&&e.segments.push(t)}let h=Math.max(1,Math.ceil(n/8)),g=[];for(let e=0;e<n;e+=h)g.push(e);return g[g.length-1]!==n-1&&g.push(n-1),{hourKeys:t,n,plotW:i,plotH:a,inner:o,yOf:m,series:d,ticks:[0,.5,1].map(e=>f*e).reverse(),xTicks:g,totalPoints:p}},[e,l,u,r.metric]);if(e===void 0||l.length===0)return(0,m.jsx)(`div`,{className:I.chartEmpty,"data-testid":`billing-perf-empty`,children:n(`perfEmpty`)});let p=e=>{let t=u.includes(e)?u.filter(t=>t!==e):[...u,e];s({metric:r.metric,models:t})},h=e=>{s({metric:e,...r.models===void 0?{}:{models:r.models}})},g=a===null||f===null?[]:f.series.flatMap(e=>{let t=e.points.find(e=>e.i===a);return t===void 0?[]:[{key:e.key,name:e.name,color:e.color,v:t.v}]});return(0,m.jsxs)(`div`,{"data-testid":`billing-perf-panel`,children:[(0,m.jsx)(`div`,{className:I.tableScroll,"data-testid":`billing-perf-table`,children:(0,m.jsxs)(`table`,{className:I.modelTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`model`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfSamples`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfTtft`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfP50`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfP90`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfMax`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfTps`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfLatency`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfEstimated`)})]})}),(0,m.jsx)(`tbody`,{children:l.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:(0,m.jsxs)(`span`,{className:I.modelCell,children:[(0,m.jsx)(`span`,{className:I.modelDot,style:{background:e.color}}),(0,m.jsx)(`span`,{className:I.modelName,children:e.name})]})}),(0,m.jsx)(`td`,{className:I.numCol,children:e.samples.toLocaleString()}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.ttftAvg)}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.ttftP50)}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.ttftP90)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.ttftMax===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):(0,m.jsxs)(`span`,{children:[fn(e.ttftMax),e.ttftSpikes!==void 0&&e.ttftSpikes>0?` (${e.ttftSpikes}↑)`:``]})}),(0,m.jsx)(`td`,{className:I.numCol,children:e.tpsAvg===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):pn(e.tpsAvg)}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.latencyAvg)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.estimatedSamples>0?e.estimatedSamples:(0,m.jsx)(`span`,{className:I.na,children:`—`})})]},e.key))})]})}),f!==null&&(0,m.jsxs)(`div`,{"data-testid":`billing-perf-hour`,children:[(0,m.jsx)(`div`,{className:I.perfBar,children:(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":n(`perfTitle`),children:[`ttft`,`tps`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,r.metric===e&&I.rangeButtonActive),"aria-pressed":r.metric===e,"data-testid":`billing-perf-tab-${e}`,onClick:()=>{h(e)},children:e===`ttft`?`${n(`perfTtft`)} (ms)`:`${n(`perfTps`)} (${n(`perfTpsUnit`)})`},e))})}),(0,m.jsxs)(`div`,{className:I.perfChips,role:`group`,"aria-label":n(`model`),children:[(0,m.jsx)(`button`,{type:`button`,className:I.perfChip,"data-testid":`billing-perf-chip-all`,onClick:()=>{s({metric:r.metric,models:l.map(e=>e.key)})},children:n(`perfAll`)}),l.map(e=>{let t=u.includes(e.key);return(0,m.jsxs)(`button`,{type:`button`,className:y(I.perfChip,!t&&I.perfChipOff),style:t?{color:e.color,borderColor:`color-mix(in srgb, ${e.color} 45%, transparent)`}:void 0,"aria-pressed":t,"data-testid":`billing-perf-chip-${e.key}`,onClick:()=>{p(e.key)},children:[(0,m.jsx)(`span`,{className:I.perfChipDot,style:{background:t?e.color:`var(--dsw-alias-label-dimmed)`}}),e.name]},e.key)})]}),f.totalPoints>0?(0,m.jsxs)(`div`,{className:I.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 180`,className:I.chartSvg,role:`img`,"aria-label":`Hourly perf comparison by model`,onMouseLeave:()=>{o(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect(),n=((e.clientX-t.left)/t.width*680-Q.left)/f.plotW,r=Math.round(n*(f.n-1));o(Math.min(Math.max(r,0),f.n-1))},children:[f.ticks.map((e,t)=>{let n=f.yOf(e);return(0,m.jsxs)(`g`,{children:[(0,m.jsx)(`line`,{x1:Q.left,x2:680-Q.right,y1:n,y2:n,className:I.chartGrid}),(0,m.jsx)(`text`,{x:Q.left-8,y:n+3,textAnchor:`end`,className:I.chartAxisLabel,children:dn(e)})]},`tick-${t}`)}),f.series.map(e=>e.segments.map((t,n)=>(0,m.jsx)(`path`,{d:t,fill:`none`,className:I.chartLine,style:{stroke:e.color}},`${e.key}-${n}`))),f.xTicks.map(e=>{let t=f.hourKeys[e];return t===void 0?null:(0,m.jsx)(`text`,{x:f.inner(e),y:174,textAnchor:`middle`,className:I.chartAxisLabel,children:un(t)},t)}),a!==null&&(0,m.jsx)(`line`,{x1:f.inner(a),x2:f.inner(a),y1:Q.top,y2:Q.top+f.plotH,className:I.chartCrosshair}),a!==null&&f.series.map(e=>{let t=e.points.find(e=>e.i===a);return t===void 0?null:(0,m.jsx)(`circle`,{cx:t.x,cy:t.y,r:3.5,fill:e.color,className:I.chartHoverDot},`${e.key}-dot`)})]}),a!==null&&g.length>0&&(0,m.jsxs)(`div`,{className:I.chartTooltip,"data-testid":`billing-perf-tooltip`,style:{left:`${f.inner(a)/680*100}%`,top:`${(Q.top+f.plotH/2)/180*100}%`},children:[(0,m.jsx)(`div`,{className:I.chartTooltipDate,children:un(f.hourKeys[a]??``)}),g.map(e=>(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name,` `,(0,m.jsx)(`strong`,{children:mn(e.v,r.metric,n)})]},e.key))]})]}):(0,m.jsx)(`div`,{className:I.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]}),f===null&&(0,m.jsx)(`div`,{className:I.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]})}let gn=`@kenz1117/dsh-ui-usage-billing`,_n=`kenz1117`;function vn({t:e,version:t}){return(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-plugin-info`,children:[(0,m.jsxs)(`div`,{className:I.plgHead,children:[(0,m.jsx)(`span`,{className:I.plgIcon,"aria-hidden":`true`,children:(0,m.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,m.jsx)(`path`,{d:`M10 3a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v2a2 2 0 0 0 4 0V4a1 1 0 0 1 1-1h1a1 1 0 0 1 1 1v1a2 2 0 0 0 4 0 1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-1a2 2 0 0 0 0 4h1a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-1a2 2 0 0 0-4 0v1a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1v-2a2 2 0 0 0-4 0v1a1 1 0 0 1-1 1h-1a1 1 0 0 1-1-1v-1a2 2 0 0 0-4 0 1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-2a1 1 0 0 1 1-1h1a2 2 0 0 0 0-4H3a1 1 0 0 1-1-1v-2a1 1 0 0 1 1-1h1a2 2 0 0 0 4 0z`})})}),(0,m.jsxs)(`div`,{className:I.plgTitle,children:[(0,m.jsxs)(`div`,{className:I.plgNameRow,children:[(0,m.jsx)(`h3`,{className:I.plgName,children:gn}),(0,m.jsx)(`span`,{className:I.plgTag,children:t===void 0?`—`:`v${t}`})]}),(0,m.jsx)(`p`,{className:I.plgDesc,children:`Usage billing dashboard for DeepSeek Harness`})]})]}),(0,m.jsxs)(`div`,{className:I.plgGrid,children:[(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginAuthor`)}),(0,m.jsxs)(`a`,{className:I.plgLink,href:`https://github.com/${_n}`,target:`_blank`,rel:`noreferrer`,children:[`KenZ`,` (`,_n,`)`]})]}),(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginRepository`)}),(0,m.jsx)(`a`,{className:I.plgLink,href:`https://github.com/kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:`GitHub`})]}),(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginNpm`)}),(0,m.jsx)(`a`,{className:I.plgLink,href:`https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:gn})]}),(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginLicense`)}),(0,m.jsx)(`span`,{className:I.plgVal,children:`MIT`})]})]})]})}function yn(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}`}function bn(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function xn(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${String(t%60).padStart(2,`0`)}s`}function Sn({rounds:e,flags:t,currency:n,t:r}){let i=(0,d.useMemo)(()=>e.slice(-40),[e]),a=(0,d.useMemo)(()=>new Set(t.map(e=>`${e.sessionId}:${e.turn}`)),[t]),o=(0,d.useMemo)(()=>Math.max(1e-4,...i.map(e=>e.cost)),[i]);if(i.length===0)return(0,m.jsxs)(`div`,{className:I.roundsEmpty,children:[r(`model`),` —`]});let s=e=>K(Bt(e,n),n);return(0,m.jsxs)(`div`,{className:I.rounds,children:[(0,m.jsx)(`div`,{className:I.roundsBars,role:`img`,"aria-label":`cost per turn`,children:i.map(e=>{let t=a.has(`${e.sessionId}:${e.turn}`),n=Math.max(1,e.cost/o*100),i=U(e.startedAt)===`peak`;return(0,m.jsxs)(`div`,{className:y(I.roundsBarCol,i?I.roundsBarColPeak:I.roundsBarColOff),children:[(0,m.jsx)(`span`,{className:I.roundsBarLabel,style:{bottom:`${n}%`},children:s(e.cost)}),(0,m.jsx)(`div`,{className:I.roundsBarWrap,children:(0,m.jsx)(`div`,{className:t?I.roundsBarFlagged:I.roundsBar,style:{height:`${n}%`},"data-testid":`round-bar`,title:`${r(`model`)} ${e.model} · ${s(e.cost)} · ${bn(e.startedAt)}${e.endedAt===void 0?``:` → ${yn(e.endedAt)} (${xn(e.endedAt-e.startedAt)})`}`,children:t&&(0,m.jsx)(`span`,{className:I.roundsFlagMark,"aria-hidden":`true`})})})]},`${e.sessionId}:${e.turn}`)})}),(0,m.jsxs)(`div`,{className:I.roundsAxis,children:[(0,m.jsxs)(`span`,{children:[r(`costAbbr`),` `,s(o)]}),(0,m.jsxs)(`span`,{children:[i.length,` `,r(`roundsUnit`)]})]})]})}let Cn=[`color-mix(in srgb, var(--ds-blue) 10%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 30%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 60%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 90%, var(--dsb-3))`,`var(--ds-blue)`],wn=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Tn=e=>q(e.getTime());function En(e,t){let n=new Map;for(let t of e)n.set(t.date,t.value);let r=0;for(let e of n.values())e>r&&(r=e);let i=t.getFullYear(),a=t.getMonth(),o=t.getDate(),s=new Date(i,a+1,0).getDate(),c=new Date(i,a,1).getDay(),l=c+s,u=Math.ceil(l/7),d=[];for(let e=0;e<u;e+=1){let t=[];for(let l=0;l<7;l+=1){let u=e*7+l-c+1;if(u<1){let e=new Date(i,a,u);t.push({date:Tn(e),dayNum:e.getDate(),value:0,level:0,placeholder:!0});continue}if(u>s){let e=new Date(i,a+1,u-s);t.push({date:Tn(e),dayNum:e.getDate(),value:0,level:0,placeholder:!0});continue}let d=new Date(i,a,u),f=Tn(d),p=n.get(f)??0,m=0;if(p>0&&r>0){let e=Math.ceil(p/r*4);m=Math.min(4,Math.max(1,e))}let h=u>o;t.push({date:f,dayNum:u,value:h?0:p,level:h?0:m,placeholder:h})}d.push(t)}return d}function Dn(e,t,n=52){let r=new Map;for(let t of e)r.set(t.date,t.value);let i=0;for(let e of r.values())e>i&&(i=e);let a=Tn(t),o=new Date(t);o.setHours(0,0,0,0),o.setDate(o.getDate()-o.getDay());let s=new Date(o);s.setDate(o.getDate()-(n-1)*7);let c=[];for(let e=0;e<n;e+=1){let t=[];for(let n=0;n<7;n+=1){let o=new Date(s);o.setDate(s.getDate()+e*7+n);let c=Tn(o),l=c>a,u=l?0:r.get(c)??0,d=0;if(!l&&u>0&&i>0){let e=Math.ceil(u/i*4);d=Math.min(4,Math.max(1,e))}t.push({date:c,dayNum:o.getDate(),value:u,level:d,placeholder:l})}c.push(t)}return c}function On({days:e,currency:t,now:n,t:r,range:i=`month`,unit:a=`cost`}){let[o,s]=(0,d.useState)(null),c=e=>K(Bt(e,t),t),l=e=>a===`tokens`?J(e):c(e),u=(0,d.useMemo)(()=>En(e,n??new Date),[e,n]);if(i!==`month`){let t=Dn(e,n??new Date,i===`half`?26:52),a=[],o=-1;return t.forEach((e,t)=>{let n=Number(e[0]?.date.slice(5,7)??0);n!==o&&(a.push({index:t,label:wn[n-1]??``}),o=n)}),(0,m.jsxs)(`div`,{className:I.heatmapYear+(i===`half`?` `+I.heatmapHalf:``),"data-testid":i===`half`?`heatmap-half`:`heatmap-year`,children:[(0,m.jsxs)(`div`,{className:I.heatmapYearBody,children:[(0,m.jsx)(`div`,{className:I.heatmapYearWeekdays,"aria-hidden":`true`,children:[{label:`Mon`,row:1},{label:`Wed`,row:3},{label:`Fri`,row:5}].map(e=>(0,m.jsx)(`span`,{className:I.heatmapYearWeekday,style:{gridRow:e.row},children:e.label},e.label))}),(0,m.jsxs)(`div`,{className:I.heatmapYearScroll,children:[(0,m.jsx)(`div`,{className:I.heatmapYearMonths,"aria-hidden":`true`,"data-testid":`heatmap-year-months`,children:a.map(e=>(0,m.jsx)(`span`,{className:I.heatmapYearMonth,style:{gridColumn:e.index+1},children:e.label},e.index))}),(0,m.jsx)(`div`,{className:I.heatmapYearGrid,role:`img`,"aria-label":`yearly cost heatmap`,"data-testid":`heatmap-year-grid`,children:t.flat().map(e=>(0,m.jsx)(`button`,{type:`button`,className:I.heatmapYearCell,"data-testid":`heatmap-year-cell`,"data-level":e.level,style:{background:Cn[e.level]},title:`${e.date} · ${l(e.value)}`,"aria-label":`${e.date}: ${l(e.value)}`,tabIndex:-1},e.date))})]})]}),(0,m.jsxs)(`div`,{className:I.heatmapFooter,children:[(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:I.heatmapLegend,children:Cn.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapMore`)})]})]})}return(0,m.jsxs)(`div`,{className:I.heatmap,children:[(0,m.jsx)(`div`,{className:I.heatmapGrid,role:`img`,"aria-label":`daily cost heatmap`,children:u.map(e=>e.map(e=>e.placeholder?(0,m.jsx)(`div`,{className:I.heatmapCellEmpty,children:e.dayNum},e.date):(0,m.jsx)(`button`,{type:`button`,className:I.heatmapCell,"data-testid":`heatmap-cell`,"data-level":e.level,style:{background:Cn[e.level]},title:`${e.date} · ${l(e.value)}`,"aria-label":`${e.date}: ${l(e.value)}`,onMouseEnter:()=>{s(e)},onMouseLeave:()=>{s(null)},onFocus:()=>{s(e)},onBlur:()=>{s(null)},children:e.dayNum},e.date)))}),(0,m.jsxs)(`div`,{className:I.heatmapFooter,children:[(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:I.heatmapLegend,children:Cn.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapMore`)}),o!==null&&(0,m.jsxs)(`span`,{className:I.heatmapHover,"data-testid":`heatmap-hover`,children:[o.date,` · `,l(o.value)]})]})]})}let kn={window:6,threshold:2,reasonFactor:1.8,reasonHitDropPp:15};function An(e){if(e.length===0)return null;let t=0;for(let n of e)t+=n;return t/e.length}function jn(e){let t=e.cacheHit+e.cacheMiss;return t<=0?null:e.cacheHit/t*100}function Mn(e,t){let n=t?.window??kn.window,r=t?.threshold??kn.threshold,i=t?.reasonFactor??kn.reasonFactor,a=t?.reasonHitDropPp??kn.reasonHitDropPp,o=[];if(n<=0||r<=0)return o;let s=[],c=[],l=[],u=[];for(let t of e){if(t.cost<=0)continue;let e=t.output,d=t.input,f=jn(t),p=An(s),m=[];if(p!==null&&p>0&&t.cost>p*r){let n=An(c),r=An(l),s=An(u);n!==null&&n>0&&e>n*i&&m.push(`output-growth`),r!==null&&r>0&&d>r*i&&m.push(`context-bloat`),s!==null&&f!==null&&f<s-a&&m.push(`cache-hit-drop`),o.push({sessionId:t.sessionId,turn:t.turn,cost:t.cost,reasons:m})}for(s.push(t.cost),c.push(e),l.push(d),f!==null&&u.push(f);s.length>n;)s.shift();for(;c.length>n;)c.shift();for(;l.length>n;)l.shift();for(;u.length>n;)u.shift()}return o}function Nn(e,t){return e==null?null:Number.isFinite(e.nextSwitchInMs)&&e.nextSwitchInMs<=t?`soon`:e.tier===`peak`?`peak`:`offPeak`}let Pn={显式缓存创建:`Explicit cache write`,显式缓存命中:`Explicit cache hit`,长期半价:`Half price`,与标准价一致:`Same as standard`,"限时 5 折":`Limited-time 50% off`};function Fn(e,t){return e===void 0||t!==`en`?e:Pn[e]??e}function In(e,t){let n=t.trim().toLowerCase();return n===``?e:e.filter(e=>e.key.toLowerCase().includes(n)||(e.name??``).toLowerCase().includes(n)||(e.provider??``).toLowerCase().includes(n))}let Ln={"智谱 AI":`Zhipu AI`,阿里通义:`Alibaba Qwen`,字节豆包:`ByteDance Doubao`,月之暗面:`Moonshot AI`,小米:`Xiaomi`,百度文心:`Baidu ERNIE`,腾讯混元:`Tencent Hunyuan`,零一万物:`01.AI`,阶跃星辰:`StepFun`,科大讯飞:`iFlytek Spark`,商汤:`SenseNova`,百川智能:`Baichuan`,"小米 Token Plan(海外)":`Xiaomi Token Plan (Global)`,"小米 Token Plan(国内)":`Xiaomi Token Plan (CN)`,"小米 Token Plan(新加坡)":`Xiaomi Token Plan (SG)`,"火山引擎 Token Plan":`Volcengine Token Plan`,"火山方舟 Token Plan":`Volcengine Ark Token Plan`,"豆包 Token Plan":`Doubao Token Plan`,"百度文心 Plan":`Baidu ERNIE Plan`,"MiniMax Token Plan(国内)":`MiniMax Token Plan (CN)`};function Rn(e,t){return t===`en`?Ln[e]??e:e}let zn={"https://tokenhub.tencentmaas.com":`腾讯云 TokenHub`,"https://api.lkeap.cloud.tencent.com":`腾讯云 Token Plan`,"https://api.deepseek.com":`DeepSeek 官方`},Bn={"腾讯云 TokenHub":`Tencent Cloud TokenHub`,"腾讯云 Token Plan":`Tencent Cloud Token Plan`,"DeepSeek 官方":`DeepSeek Official`};function Vn(e){try{return new URL(e).host}catch{return e}}function Hn(e,t=`zh`){if(e.startsWith(`site:`)){let n=e.slice(5),r=zn[n];return r===void 0?Vn(n):t===`en`?Bn[r]??r:r}if(e.startsWith(`direct:`)){let n=e.slice(7);return/^deepseek(?:-[a-z0-9-]+)?$/i.test(n)?t===`en`?`DeepSeek Official`:`DeepSeek 官方`:`${t===`en`?`Direct`:`直连`} · ${n}`}}let Un=[`直连 · `,`Direct · `];function Wn(e){for(let t of Un)if(e.startsWith(t))return e.slice(t.length)}let Gn=`dsh-billing-peak-alert-v1`,Kn={enabled:!1,leadMin:2,position:`bottom-right`,webNotify:!0,mode:`both`};function qn(){try{let e=localStorage.getItem(Gn);if(e===null)return{...Kn};let t=JSON.parse(e),n=t.mode===`peak`||t.mode===`offPeak`?t.mode:Kn.mode,r=t.position===`center`?`center`:`bottom-right`;return{enabled:t.enabled===!0,leadMin:typeof t.leadMin==`number`&&Number.isFinite(t.leadMin)?Math.min(30,Math.max(1,Math.round(t.leadMin))):Kn.leadMin,position:r,webNotify:t.webNotify!==!1,mode:n}}catch{return{...Kn}}}function Jn(e){try{localStorage.setItem(Gn,JSON.stringify(e))}catch{}}function Yn(e,t,n,r){if(!t.enabled)return null;let i=ft(e,r,t.leadMin*6e4);return i===null||t.mode===`peak`&&i.entering!==`peak`||t.mode===`offPeak`&&i.entering!==`offPeak`||i.atMs===n?null:{...i,channel:r}}function Xn({hit:e,config:t,t:n,onDismiss:r}){let[i,a]=(0,d.useState)(()=>Date.now());if((0,d.useEffect)(()=>{let e=setInterval(()=>a(Date.now()),3e4);return()=>clearInterval(e)},[]),(0,d.useEffect)(()=>{i>=e.atMs&&r()},[i,e.atMs,r]),i>=e.atMs)return null;let o=Math.max(1,Math.round((e.atMs-i)/6e4)),s=e.entering,c=n(s===`peak`?`tierPeak`:`tierOff`),l=n(e.channel===`zhipu-coding-plan`?s===`peak`?`peakAlertDescPeakZhipu`:`peakAlertDescOffZhipu`:s===`peak`?`peakAlertDescPeak`:`peakAlertDescOff`),u=s===`peak`;return(0,m.jsxs)(`div`,{className:y(I.peakCard,u?I.peakCardPeak:I.peakCardOff,t.position===`center`?I.peakCardCenter:I.peakCardCorner),"data-testid":`billing-peak-alert`,role:`alert`,children:[(0,m.jsxs)(`div`,{className:I.peakHead,children:[(0,m.jsxs)(`span`,{className:y(I.peakTag,u?I.peakTagPrimary:I.peakTagSuccess),children:[(0,m.jsx)(`span`,{className:y(I.peakDot,u?I.peakDotPrimary:I.peakDotSuccess),"aria-hidden":`true`}),c]}),(0,m.jsx)(`button`,{type:`button`,className:I.peakClose,onClick:r,"aria-label":n(`close`),children:`×`})]}),(0,m.jsxs)(`div`,{className:y(I.peakCount,u?I.peakCountPrimary:I.peakCountSuccess),children:[o,`min`]}),(0,m.jsx)(`p`,{className:I.peakDesc,children:l})]})}let Zn=p,Qn=Zn.IconChevronDownOutlineMedium??Zn.IconChevronDownOutline14,$n=[{id:`overview`,labelKey:`tabOverview`},{id:`providers`,labelKey:`tabProviders`},{id:`token`,labelKey:`tabToken`},{id:`trends`,labelKey:`tabTrends`},{id:`pricing`,labelKey:`tabPricing`},{id:`settings`,labelKey:`tabSettings`}],er=[50,80,100],tr={checked:!1,available:!1,models:0,failures:0,okProviders:[],badProviders:[]},nr={DeepSeek:[`deepseek`],"智谱 AI":[`zhipu`,`glm`,`z.ai`],阿里通义:[`qwen`,`tongyi`,`dashscope`,`aliyun`],字节豆包:[`doubao`,`volcengine`,`ark`],月之暗面:[`moonshot`,`kimi`],小米:[`xiaomi`,`mi`,`mimo`],MiniMax:[`minimax`],百度文心:[`ernie`,`wenxin`,`qianfan`,`baidu`],腾讯混元:[`hunyuan`,`tencent`],零一万物:[`01.ai`,`lingyi`,`yi`],阶跃星辰:[`step`,`stepfun`,`step-3.7`],科大讯飞:[`spark`,`xfyun`,`iflytek`],商汤:[`sensenova`,`sensetime`],百川智能:[`baichuan`],OpenAI:[`openai`],Google:[`google`,`gemini`],xAI:[`xai`,`grok`],Meta:[`meta`,`llama`],Anthropic:[`claude`,`anthropic`],"Mistral AI":[`mistral`,`ministral`,`devstral`],Cohere:[`cohere`,`command`],美团:[`longcat`,`meituan`],面壁智能:[`minicpm`,`modelbest`],小红书:[`dots`,`rednote`,`xiaohongshu`],云知声:[`unisound`,`u2`]};function $(e){return e.trim().toLowerCase().replace(/[\s_/-]+/g,``)}function rr(e,t){if(e.length===0||t.length===0)return!1;if(e===t)return!0;let[n,r]=e.length<=t.length?[e,t]:[t,e];return n.length>=3&&r.includes(n)}function ir(e,t){let n=$(e),r=$(t);if(rr(n,r))return!0;let i=nr[e];return i!==void 0&&i.some(e=>rr($(e),r))}function ar(e){let t=e.trim().toLowerCase(),n=t.replace(/[\s_/-]+/g,``);if(n.length!==0){for(let[e,n]of Object.entries(nr))for(let r of n){let n=$(r);if(n.length!==0&&(t===n||t.startsWith(`${n}-`)||t.startsWith(`${n}/`)||t.startsWith(`${n}_`)||t.includes(`${n}-`)||t.includes(`${n}/`)||t.includes(`${n}_`)))return e}for(let[e,t]of Object.entries(nr))for(let r of t){let t=$(r);if(!(t.length<4)&&n.includes(t))return e}}}let or={"kimi-coding":`月之暗面`,"zai-coding-cn":`智谱 AI`,"zai-coding":`智谱 AI`,"qwen-token-plan":`阿里通义`,"qwen-token-plan-cn":`阿里通义`,"xiaomi-token-plan-ams":`小米`,"xiaomi-token-plan-cn":`小米`,"xiaomi-token-plan-sgp":`小米`,"volcengine-token-plan":`字节豆包`,"ark-token-plan":`字节豆包`,"doubao-token-plan":`字节豆包`,ernie:`百度文心`,baidu:`百度文心`,wenxin:`百度文心`,minimax:`MiniMax`,"minimax-cn":`MiniMax`,"minimax-token-plan":`MiniMax`,"minimax-token-plan-cn":`MiniMax`,"hunyuan-token-plan":`腾讯混元`,"tencent-token-plan":`腾讯混元`,"hy-token-plan":`腾讯混元`,"xinghuo-token-plan":`讯飞星火`,"xfyun-coding":`讯飞星火`,"spark-coding":`讯飞星火`,"huawei-token-plan":`华为云`,"pangu-token-plan":`华为云`,"huawei-maas-token-plan":`华为云`,"volcengine-agent-plan":`字节豆包`,"ark-agent-plan":`字节豆包`,"baidu-token-plan":`百度文心`,"ernie-token-plan":`百度文心`,"wenxin-token-plan":`百度文心`,opencode:`OpenCode`,"opencode-go":`OpenCode`};function sr(e){let t=or[e];return t===void 0?ar(e)??e:t}let cr=`https://platform.kimi.com/console/pay`,lr=`https://open.bigmodel.cn/finance-center/finance/pay`,ur=`https://bailian.console.aliyun.com/`,dr=`https://console.volcengine.com/ark`,fr=`https://console.anthropic.com/settings/billing`,pr=`https://console.cloud.google.com/billing`,mr=`https://console.x.ai/`,hr=`https://platform.xiaomimimo.com/console/balance`,gr=`https://console.cloud.tencent.com/expense/recharge`,_r={deepseek:`https://platform.deepseek.com/top_up`,minimax:`https://platform.minimax.cn/console/recharge-records`,moonshot:cr,kimi:cr,zhipu:lr,bigmodel:lr,qwen:ur,dashscope:ur,doubao:dr,volcengine:dr,ark:dr,openai:`https://platform.openai.com/settings/organization/billing`,anthropic:fr,claude:fr,google:pr,gemini:pr,xai:mr,grok:mr,siliconflow:`https://cloud.siliconflow.cn/account/charge`,hunyuan:gr,tencent:gr,腾讯云:gr,xiaomi:hr,mimo:hr,mi:hr,qianfan:`https://console.bce.baidu.com/qianfan/overview`};function vr(e){let t=_r[e];if(t!==void 0)return t;let n=Object.keys(_r).find(t=>e.startsWith(t));return n===void 0?void 0:_r[n]}function yr(e){let t=$(e),n=vr(t);if(n!==void 0)return n;for(let[e,n]of Object.entries(nr))if(rr($(e),t))for(let e of n){let t=vr($(e));if(t!==void 0)return t}}function br(e,t){let n=Object.keys(e).filter(e=>e<=t).sort().slice(-7);return n.length===0?0:n.reduce((t,n)=>t+(e[n]?.cost??0),0)/n.length}function xr(e,t,n){let r=Object.keys(e).filter(e=>e.startsWith(t)),i=t.split(`-`),a=new Date(Number(i[0]),Number(i[1]),0).getDate(),o=r.length>0?r.reduce((t,n)=>t+(e[n]?.cost??0),0)/r.length:br(e,n);return o<=0?0:o*a}function Sr(e){let t=Ke();if(t===void 0||e.byDayModels===void 0)return e;let n=$e().rate,r=e.byDayModelsSite!==void 0,i={},a={},o=new Map,s=0,c=e=>t.some(t=>t.origin!==void 0&&t.origin!==``&&(t.key===e||G(t.key)===G(e))),l=(e,t,r)=>{if(e===void 0)return r;let i=Math.min(t.cacheHit,t.cacheMiss+t.cacheHit),a=r=>{let a=(t.cacheMiss*r.input+i*r.cacheHit+t.output*r.output)/1e6;return e.currency===`USD`?a*n:a};return e.offPeak===void 0?a(e):a(e)*tt+a(e.offPeak)*.5};for(let[t,n]of Object.entries(e.byDayModels)){let u=0,d={};for(let[i,a]of Object.entries(n)){let n=H(i)??Je(i),s=r&&c(i),f;if(s&&e.byDayModelsSite?.[t]?.[i]!==void 0){let r=0;for(let[a,o]of Object.entries(e.byDayModelsSite[t][i])){let e=a.startsWith(`site:`)?a.slice(5):void 0,t=e===void 0?void 0:H(i,e);r+=l(t??n,o,o.cost)}f=r}else f=l(n,a,a.cost);u+=f,d[i]={...a,cost:f},o.set(i,(o.get(i)??0)+f)}let f=e.byDay[t];f!==void 0&&(i[t]={...f,cost:u}),a[t]=d,s+=u}return{...e,total:{...e.total,cost:s},byDay:i,byDayModels:a,byModel:Object.fromEntries(Object.entries(e.byModel).map(([e,t])=>{let n=o.get(e);return[e,n===void 0?t:{...t,cost:n}]})),unpricedModels:(e.unpricedModels??[]).filter(e=>!H(e)&&!Je(e))}}function Cr(){return typeof Notification<`u`&&Notification.permission===`granted`}let wr=new Set;function Tr(e,t){wr.has(e)||(wr.add(e),fetch(`/api/billing/notify-claim`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({key:e})}).then(e=>e.json()).then(e=>{e.claimed!==!1&&t()}).catch(()=>t()))}function Er(e){return Object.keys(e).length}function Dr(e,t=Date.now()){let n=0,r=new Date(t);for(;q(r.getTime())in e;)n+=1,r.setDate(r.getDate()-1);return n}function Or(e){return e.input+e.output}function kr(e){let t=[];for(let n=6;n>=0;--n){let r=new Date;r.setDate(r.getDate()-n);let i=q(r.getTime());t.push({date:i,cost:e[i]?.cost??0})}return t}function Ar(e,t,n=e=>e.cost){let r=new Date(`${t}T00:00:00`),i=(r.getDay()+6)%7,a=0;for(let t=0;t<=i;t+=1){let i=new Date(r);i.setDate(i.getDate()-t);let o=e[q(i.getTime())];o!==void 0&&(a+=n(o))}return a}function jr(e,t,n){let r=new Date(`${t}T00:00:00`),i=(r.getDay()+6)%7,a=new Date(r);a.setDate(a.getDate()-i);let o=q(a.getTime()),s=new Date(r);s.setDate(s.getDate()-6);let c=q(s.getTime()),l=0,u=0,d=0,f=0,p=0,m=0,h=0,g,_=0;for(let[r,i]of Object.entries(e)){if(!(n===`today`?r===t:n===`7d`?r>=c&&r<=t:n===`week`?r>=o&&r<=t:r.startsWith(t.slice(0,7))))continue;l+=i.cost,u+=i.calls,d+=i.input,f+=i.output,p+=i.cacheHit,m+=i.cacheMiss,h+=i.reasoning??0;let e=Or(i);e>_&&(_=e,g=r)}return{cost:l,calls:u,input:d,output:f,cacheHit:p,cacheMiss:m,reasoning:h,peakDay:g,peakTokens:_}}function Mr(e,t){return e.checked?e.okProviders.some(e=>ir(t,e))?I.healthOk:e.badProviders.some(e=>ir(t,e))?I.healthBad:I.healthIdle:I.healthIdle}function Nr(e){let t=new Map,n=[];for(let r of e){if(r.title===void 0||r.title===``){n.push(r);continue}let e=t.get(r.title);if(e===void 0){let e={...r,mergedCount:1};t.set(r.title,e),n.push(e);continue}e.children===void 0&&(e.children=[{...e}]),e.children.push({...r}),e.calls+=r.calls,e.cost+=r.cost,e.lastActive=Math.max(e.lastActive,r.lastActive),r.stale===!0&&(e.stale=!0),e.mergedCount=(e.mergedCount??1)+1}return n.sort((e,t)=>t.cost-e.cost||t.lastActive-e.lastActive)}function Pr(e,t){switch(e){case`ok`:return``;case`not-configured`:return t(`subscriptionNotConfigured`);case`unauthorized`:return t(`subscriptionUnauthorized`);case`rate-limited`:return t(`subscriptionRateLimited`);case`invalid-response`:return t(`subscriptionInvalid`);default:return t(`subscriptionUnavailable`)}}function Fr({window:e,t}){let n=Math.min(100,Math.max(0,e.usedPercent)),r=Math.min(100,Math.max(0,e.remainingPercent))<=0;return(0,m.jsxs)(`div`,{className:I.subscriptionWindow,children:[(0,m.jsx)(`span`,{className:I.subscriptionWindowLabel,children:Ir(e.kind,t)}),(0,m.jsx)(`span`,{className:I.subscriptionTrack,"aria-hidden":`true`,children:(0,m.jsx)(`span`,{className:y(I.subscriptionFill,n>=100&&I.subscriptionFillOver,n>=80&&n<100&&I.subscriptionFillWarn),style:{width:`${n}%`}})}),(0,m.jsxs)(`span`,{className:I.subscriptionMeta,children:[(0,m.jsx)(`span`,{className:y(I.subscriptionPct,r&&I.subscriptionExhausted),children:r?t(`subscriptionExhausted`):t(`subscriptionRemaining`).replace(`{pct}`,String(e.remainingPercent))}),e.resetsAt!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionReset,children:t(`subscriptionReset`).replace(`{date}`,`${q(new Date(e.resetsAt).getTime())} ${Br(new Date(e.resetsAt).getTime())}`)})]})]})}function Ir(e,t){switch(e){case`session`:return t(`subscriptionSession`);case`weekly`:return t(`subscriptionWeekly`);case`monthly`:return t(`subscriptionMonthly`);case`billing`:return t(`subscriptionBilling`)}}function Lr(e,t){switch(e){case`new-api`:return t(`relayKindNewApi`);case`sub2api`:return t(`relayKindSub2Api`);default:return t(`relayKindUnknown`)}}let Rr={"new-api":I.siteKindSite,sub2api:I.siteKindDirect,unknown:I.siteKindUnknown},zr=3e4;function Br(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}let Vr=[`#4f8cff`,`#2dd4bf`,`#a78bfa`,`#f59e0b`,`#f472b6`,`#fbbf24`,`#38bdf8`,`#6366f1`,`#f97316`,`#14b8a6`],Hr={total:{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cost:0,reasoning:0},byModel:{},byDay:{},byDayModels:{}};async function Ur(){try{let e=await fetch(`/api/billing/usage-stats`);if(!e.ok)return null;let t=await e.text(),n=JSON.parse(t);if(typeof n!=`object`||!n||!(`total`in n))return null;let r=n,i=e=>typeof e==`object`&&!!e;return{total:r.total??Hr.total,byModel:r.byModel??{},byDay:r.byDay??{},...r.byDayModels===void 0?{}:{byDayModels:r.byDayModels},...i(r.byDayModelsSite)?{byDayModelsSite:r.byDayModelsSite}:{},...r.updatedAt===void 0?{}:{updatedAt:r.updatedAt},...typeof r.budget==`number`?{budget:r.budget}:{},...typeof r.lowBalanceThreshold==`number`?{lowBalanceThreshold:r.lowBalanceThreshold}:{},...Array.isArray(r.bySession)?{bySession:r.bySession}:{},...Array.isArray(r.byTurn)?{byTurn:r.byTurn}:{},...Array.isArray(r.byWorkspace)?{byWorkspace:r.byWorkspace}:{},...i(r.bySite)?{bySite:r.bySite}:{},...i(r.byTier)?{byTier:r.byTier}:{},...i(r.byTool)?{byTool:r.byTool}:{},...Array.isArray(r.unpricedModels)?{unpricedModels:r.unpricedModels}:{},...typeof r.staleLedgerSessions==`number`?{staleLedgerSessions:r.staleLedgerSessions}:{},...typeof r.unreadableSessions==`number`?{unreadableSessions:r.unreadableSessions}:{},...typeof r.unreadableFormatSessions==`number`?{unreadableFormatSessions:r.unreadableFormatSessions}:{},...typeof r.unreadableNoLedgerSessions==`number`?{unreadableNoLedgerSessions:r.unreadableNoLedgerSessions}:{},...typeof r.searchCallEstimateCny==`number`?{searchCallEstimateCny:r.searchCallEstimateCny}:{},...r.byRole!==null&&typeof r.byRole==`object`?{byRole:r.byRole}:{},...r.perf!==null&&typeof r.perf==`object`&&r.perf.byModel!==null&&typeof r.perf.byModel==`object`&&r.perf.byHourModel!==null&&typeof r.perf.byHourModel==`object`?{perf:r.perf}:{},...typeof r.pluginVersion==`string`?{pluginVersion:r.pluginVersion}:{}}}catch{return null}}let Wr=!1,Gr=0;async function Kr(e=0){try{let t=await fetch(`/api/billing/pricing`);if(!t.ok){Wr=!1;return}let n=await t.text(),r=JSON.parse(n);if(typeof r!=`object`||!r||!(`source`in r)){Wr=!1;return}let i=r;Array.isArray(i.catalog)&&i.catalog.length>0&&i.aliases!==null&&typeof i.aliases==`object`&>(i.catalog,i.aliases);let a=r;if(a.source===`builtin`&&e<3){if(e===0){if(Wr)return;Wr=!0}setTimeout(()=>{Kr(e+1)},2e3);return}Wr=!1,Gr=a.syncedAt??0,Ye(a)}catch{Wr=!1}}async function qr(){try{return(await fetch(`/api/billing/pricing/refresh`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`})).ok?(await Kr(),!0):!1}catch{return!1}}async function Jr(){try{let e=await fetch(`/api/billing/balance`);if(!e.ok)return{balances:[]};let t=await e.text(),n=JSON.parse(t);if(typeof n!=`object`||!n)return{balances:[]};let r=n;return{balances:Array.isArray(r.balances)?r.balances:[],...r.reconcile===void 0?{}:{reconcile:r.reconcile}}}catch{return{balances:[]}}}async function Yr(){let e=await fetch(`/api/billing/subscriptions`);if(!e.ok)throw Error(`subscriptions HTTP ${String(e.status)}`);let t=await e.text(),n=JSON.parse(t);if(typeof n==`object`&&n&&`quotas`in n)return n.quotas;throw Error(`subscriptions: invalid response`)}async function Xr(){let e=await fetch(`/api/billing/relay-quotas`);if(!e.ok)throw Error(`relay-quotas HTTP ${String(e.status)}`);let t=await e.text(),n=JSON.parse(t);if(typeof n==`object`&&n&&`quotas`in n)return n.quotas;throw Error(`relay-quotas: invalid response`)}async function Zr(){try{let e=await fetch(`/api/billing/usage-tool`);if(!e.ok)return;let t=JSON.parse(await e.text());return typeof t.enabled==`boolean`?t.enabled:void 0}catch{return}}async function Qr(e){try{let t=await fetch(`/api/billing/usage-tool`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e})});return t.ok?JSON.parse(await t.text()).ok===!0:!1}catch{return!1}}let $r=e=>e.models.reduce((e,t)=>e+(t.actual??(t.plan===!0?0:t.estimated)),0);function ei(e){let t=t=>K(Bt(t,e.currency),e.currency),{wide:n,t:r,onOpen:i,monthCost:a,todayCost:o,weekCost:s,days:c,vendorStatus:l,dash:u,floatPrefs:p,subscriptions:h,cardPrefs:g,monthTokens:_,todayTokens:v,weekTokens:b,budgetPressure:x}=e,S=(0,d.useMemo)(()=>p.targets.map(e=>h.find(t=>t.provider===e)).filter(e=>e!==void 0),[p.targets,h]),[C,w]=(0,d.useState)(0),T=S.length===0?0:Math.min(C,S.length-1),ee=S[T],E=(0,d.useRef)(null),[D,O]=(0,d.useState)(!1),[te,ne]=(0,d.useState)({left:0,top:0});(0,d.useEffect)(()=>{if(!D||p.mode!==`subscription`||S.length<2)return;let e=setInterval(()=>w(e=>(e+1)%S.length),1500);return()=>clearInterval(e)},[D,p.mode,S.length]);let k=(0,d.useRef)(void 0),re=(0,d.useCallback)(()=>{window.clearTimeout(k.current),O(!0)},[]),ie=(0,d.useCallback)(()=>{window.clearTimeout(k.current),k.current=window.setTimeout(()=>O(!1),120)},[]);(0,d.useEffect)(()=>()=>window.clearTimeout(k.current),[]);let A=(0,d.useCallback)(()=>{let e=E.current?.getBoundingClientRect();e!==void 0&&ne({left:e.left,top:e.top-8})},[]);(0,d.useEffect)(()=>{if(!D)return;let e=()=>A();return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,{capture:!0}),window.removeEventListener(`resize`,e)}},[D,A]);let ae=c.length>0?c.reduce((e,t)=>e+t.cost,0)/c.length:0,oe=ae>0?Math.max(0,Math.min(1,o/ae)):0,se=-80+oe*160,ce=(0,m.jsxs)(`svg`,{viewBox:`0 0 40 40`,fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,"aria-hidden":`true`,children:[(0,m.jsx)(`path`,{d:`M5.23 26.4A15 15 0 0 1 34.77 26.4`,strokeWidth:3,opacity:.16}),(0,m.jsx)(`path`,{d:`M5.23 26.4A15 15 0 0 1 34.77 26.4`,strokeWidth:3,strokeDasharray:`${(41.9*oe).toFixed(2)} 41.9`,className:I.triggerGaugeArc}),(0,m.jsx)(`path`,{d:`M5.23 26.4 8.18 26.92M10.36 17.51 12.29 19.81M20 14v3M27.71 19.81 29.64 17.51M31.82 26.92 34.77 26.4`,strokeWidth:1.6,opacity:.7}),(0,m.jsx)(`path`,{d:`M7.01 21.5 8.31 22.25M14.87 14.91 15.38 16.31M24.62 16.31 25.13 14.91M31.69 22.25 32.99 21.5`,strokeWidth:1.2,opacity:.38}),(0,m.jsx)(`line`,{x1:`20`,y1:`29`,x2:`20`,y2:`19.5`,strokeWidth:2,className:I.triggerGaugeNeedle,style:{transform:`rotate(${se}deg)`,transformOrigin:`20px 29px`}}),(0,m.jsx)(`circle`,{cx:`20`,cy:`29`,r:`1.5`,fill:`currentColor`,stroke:`none`})]});if(!n)return(0,m.jsx)(`button`,{type:`button`,className:y(I.railButton,x!==`none`&&I.triggerBudgetPulse,x===`over`&&I.triggerBudgetOver),"data-testid":`billing-rail-button`,onClick:i,title:`${r(`title`)} · ${t(g.span===`day`?o:g.span===`week`?s:a)}`,children:ce});let j=g.metric===`tokens`,le=c.map(e=>j?e.tokens:e.cost),M=Math.max(...le,0),N=le.map(e=>M>0?4+e/M*12:4);return(0,m.jsxs)(`span`,{ref:E,className:I.triggerWrap,onMouseEnter:()=>{A(),re()},onMouseLeave:ie,onFocusCapture:()=>{A(),re()},onBlurCapture:()=>O(!1),children:[(0,m.jsxs)(`button`,{type:`button`,className:y(I.trigger,x!==`none`&&I.triggerBudgetPulse,x===`over`&&I.triggerBudgetOver),"data-testid":`billing-trigger`,onClick:i,title:`${r(`title`)} · ${t(g.span===`day`?o:g.span===`week`?s:a)}`,children:[(0,m.jsx)(`span`,{className:y(I.triggerIcon,x!==`none`&&I.triggerBudgetHot),"data-testid":`billing-trigger-icon`,children:ce}),(0,m.jsx)(`span`,{className:I.triggerMain,children:(0,m.jsxs)(`span`,{className:I.triggerPrimary,children:[(0,m.jsx)(`span`,{className:I.triggerLabel,children:j?g.span===`day`?r(`triggerTodayTokens`):g.span===`week`?r(`triggerWeekTokens`):r(`triggerMonthTokens`):g.span===`day`?r(`triggerToday`):g.span===`week`?r(`weekCost`):r(`triggerMonth`)}),(()=>{let e=g.span===`day`?j?v:o:g.span===`week`?j?b:s:j?_:a;return j?(0,m.jsx)(`span`,{className:I.triggerMetric,"data-testid":`billing-trigger-span-tokens`,children:J(e)}):(0,m.jsxs)(`span`,{className:I.triggerValueRow,children:[(0,m.jsx)(`span`,{className:I.triggerYen,"aria-hidden":`true`,children:t(e).charAt(0)}),(0,m.jsx)(`span`,{className:I.triggerMetric,"data-testid":`billing-trigger-span-money`,children:t(e).slice(1)})]})})()]})}),(0,m.jsx)(`span`,{className:I.triggerSpark,"data-testid":`billing-trigger-spark`,"aria-hidden":`true`,children:N.map((e,t)=>(0,m.jsx)(`span`,{className:t===N.length-1?I.triggerSparkHot:I.triggerSparkBar,style:{height:`${e}px`}},c[t]?.date??String(t)))})]}),(0,f.createPortal)((0,m.jsx)(`span`,{className:y(I.triggerPop,D&&I.triggerPopShown),style:{left:`${te.left}px`,top:`${te.top}px`},"data-testid":`billing-trigger-pop`,"aria-hidden":!D,onMouseEnter:re,onMouseLeave:ie,children:p.mode===`subscription`?(0,m.jsx)(m.Fragment,{children:S.length===0?(0,m.jsx)(`span`,{className:I.triggerPopEmpty,children:r(`floatNoTargets`)}):(0,m.jsxs)(m.Fragment,{children:[ee!==void 0&&(0,m.jsxs)(`div`,{className:I.floatSub,"data-testid":`billing-float-subscription`,children:[(0,m.jsxs)(`div`,{className:I.floatSubHead,children:[(0,m.jsx)(`span`,{className:I.floatSubName,children:ee.displayName}),ee.plan!==void 0&&(0,m.jsx)(`span`,{className:I.floatSubPlan,children:ee.plan})]}),ee.windows.map(e=>(0,m.jsx)(Fr,{window:e,t:r},e.kind))]}),S.length>1&&(0,m.jsx)(`span`,{className:I.triggerPopSwitcher,"data-testid":`billing-float-switcher`,children:(0,m.jsxs)(`span`,{className:I.triggerPopSwitchCount,children:[T+1,`/`,S.length]})})]})}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:I.popHead,children:(0,m.jsx)(`span`,{className:I.popTitle,children:r(`popTitle`)})}),(0,m.jsxs)(`span`,{className:I.metricGrid,children:[(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`floatPrimaryToday`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:t(o)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`floatPrimaryWeek`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:t(s)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`floatPrimaryMonth`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:t(a)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`input`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:J(u.input)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`output`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:J(u.output)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`cacheHit`)}),(0,m.jsx)(`span`,{className:y(I.metricValue,I.metricValueSuccess),children:Ut(u.cacheRead+u.cacheMiss>0?u.cacheRead/(u.cacheRead+u.cacheMiss)*100:0)})]})]}),(0,m.jsxs)(`span`,{className:I.popModel,children:[(0,m.jsx)(`span`,{className:I.popModelLabel,children:r(`popTodayModel`)}),l.direct!==void 0||l.sub!==void 0?(0,m.jsxs)(m.Fragment,{children:[l.direct!==void 0&&(0,m.jsxs)(`span`,{className:I.popModelRow,children:[(0,m.jsx)(`span`,{className:y(I.popDot,I.popDotDirect),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:I.popTagPrimary,children:r(`popDirectLead`)}),(0,m.jsx)(`span`,{className:I.popModelName,children:l.direct.name}),(0,m.jsx)(`span`,{className:y(I.popModelStatus,l.direct.low&&I.popModelStatusLow),children:l.direct.text})]}),l.sub!==void 0&&(0,m.jsxs)(`span`,{className:I.popModelRow,children:[(0,m.jsx)(`span`,{className:y(I.popDot,I.popDotSub),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:I.popTagSub,children:r(`popSubLead`)}),(0,m.jsx)(`span`,{className:I.popModelName,children:l.sub.name}),(0,m.jsx)(`span`,{className:y(I.popModelStatus,l.sub.low&&I.popModelStatusLow),children:l.sub.text})]})]}):(0,m.jsxs)(`span`,{className:I.popModelRow,children:[(0,m.jsx)(`span`,{className:y(I.popDot,I.popDotNeutral),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:I.popModelStatus,children:r(`popNoConsumption`)})]})]})]})}),document.body)]})}function ti({balance:e,days:t,dailyBurn:n,money:r,t:i,onClose:a}){let o=t=>t===void 0?void 0:e.currency===`USD`?`$${t.toFixed(2)}`:r(t),s=o(e.totalBalance),c=o(e.grantedBalance),l=o(e.toppedUpBalance);return(0,m.jsxs)(`span`,{className:I.balanceDetailPop,"data-testid":`billing-balance-detail-pop`,onClick:e=>{e.stopPropagation()},children:[(0,m.jsxs)(`span`,{className:I.balanceDetailHead,children:[(0,m.jsx)(`span`,{className:I.balanceDetailTitle,children:e.displayName}),(0,m.jsx)(`button`,{type:`button`,className:I.balanceDetailClose,"aria-label":i(`close`),onClick:a,children:`×`})]}),(0,m.jsxs)(`span`,{className:I.balanceDetailGrid,children:[s!==void 0&&(0,m.jsx)(ni,{label:i(`balance`),value:s}),c!==void 0&&(0,m.jsx)(ni,{label:i(`balanceGranted`),value:c}),l!==void 0&&(0,m.jsx)(ni,{label:i(`balanceTopped`),value:l}),(0,m.jsx)(ni,{label:i(`balanceDaily`),value:r(n)}),(0,m.jsx)(ni,{label:i(`balanceDaysLong`),value:`${t} ${i(`balanceDaysUnit`)}`})]})]})}function ni({label:e,value:t}){return(0,m.jsxs)(`span`,{className:I.balanceDetailRow,children:[(0,m.jsx)(`span`,{className:I.balanceDetailLabel,children:e}),(0,m.jsx)(`span`,{className:I.balanceDetailValue,children:t})]})}function ri({userPrices:e,onUserPrices:t,t:n}){let[r,i]=(0,d.useState)(()=>[...e]),[a,o]=(0,d.useState)(new Set),s=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),c=()=>{i(e=>e.filter((e,t)=>!a.has(t))),o(new Set)},l=(e,t)=>i(n=>n.map((n,r)=>r===e?{...n,...t}:n)),u=()=>i(e=>[...e,{key:``,input:0,cacheHit:0,output:0}]),f=e=>{let t=r[e]?.offPeak;return{input:t===void 0?``:String(t.input),cacheHit:t===void 0?``:String(t.cacheHit),output:t===void 0?``:String(t.output)}},p=(e,t,n)=>i(r=>r.map((r,i)=>{if(i!==e)return r;let a=r.offPeak,o={input:a===void 0?``:String(a.input),cacheHit:a===void 0?``:String(a.cacheHit),output:a===void 0?``:String(a.output),[t]:n},s=[o.input,o.cacheHit,o.output].some(e=>e.trim()!==``),c=[o.input,o.cacheHit,o.output].map(e=>Number(e)),l=s&&c.every(e=>Number.isFinite(e)&&e>=0)&&c.some(e=>e>0),{offPeak:u,...d}=r;return l?{...d,offPeak:{input:c[0]??0,cacheHit:c[1]??0,output:c[2]??0}}:d})),h=()=>t(r.filter(e=>e.key.trim()!==``).map(e=>({...e,key:e.key.trim(),...e.origin===void 0||e.origin.trim()===``?{}:{origin:We(e.origin.trim())}}))),g=It().map(e=>e.key),_=(e,t)=>i(n=>n.map((n,r)=>{if(r!==e)return n;let{currency:i,...a}=n;return t===`USD`?{...a,currency:`USD`}:a})),v=e=>Number.isFinite(e)&&e!==0?String(e):``,b=(e,t,n)=>{let r=Number(n);l(e,{[t]:Number.isFinite(r)&&r>=0?r:0})};return(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-user-prices`,children:[(0,m.jsx)(`div`,{className:I.setCardHead,children:(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:n(`userPrices`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:n(`userPricesHint`)})]})}),(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsx)(`datalist`,{id:`billing-price-model-keys`,children:g.map(e=>(0,m.jsx)(`option`,{value:e},e))}),r.map((e,t)=>(0,m.jsxs)(`div`,{className:I.userPriceRow,"data-testid":`billing-user-price-row`,children:[(0,m.jsx)(`input`,{type:`checkbox`,className:I.userPriceCheck,"data-testid":`billing-user-price-select`,checked:a.has(t),"aria-label":n(`userPriceSelect`),onChange:()=>s(t)}),(0,m.jsxs)(`div`,{className:I.userPriceBody,children:[(0,m.jsxs)(`div`,{className:I.userPriceLineMeta,children:[(0,m.jsxs)(`div`,{className:I.userPriceField,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:n(`userPriceModel`)}),(0,m.jsx)(`input`,{className:I.userPriceInput,"data-testid":`billing-user-price-model`,type:`text`,list:`billing-price-model-keys`,value:e.key,placeholder:`flash`,"aria-label":n(`userPriceModel`),onChange:e=>l(t,{key:e.target.value})})]}),(0,m.jsxs)(`div`,{className:I.userPriceField,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:n(`userPriceSource`)}),(0,m.jsx)(`input`,{className:I.userPriceInput,"data-testid":`billing-user-price-origin`,type:`text`,value:e.origin??``,placeholder:n(`userPriceSourceHint`),"aria-label":n(`userPriceSource`),onChange:e=>l(t,{origin:e.target.value.trim()})})]}),(0,m.jsxs)(`div`,{className:I.userPriceField,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:n(`userPriceCurrency`)}),(0,m.jsxs)(`div`,{className:I.ctlGroup,children:[(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,e.currency!==`USD`&&I.floatModeBtnOn),onClick:()=>_(t,`CNY`),children:`CNY`}),(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,e.currency===`USD`&&I.floatModeBtnOn),onClick:()=>_(t,`USD`),children:`USD`})]})]})]}),[{label:n(`userPriceNormal`),testid:`billing-user-price-normal`,valueOf:t=>v(e[t]),onChange:(e,n)=>b(t,e,n)},{label:n(`userPriceOffPeak`),testid:`billing-user-price-offpeak`,valueOf:e=>f(t)[e],onChange:(e,n)=>p(t,e,n)}].map(e=>(0,m.jsxs)(`div`,{className:I.userPricePriceLine,"data-testid":e.testid,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:e.label}),[`input`,`cacheHit`,`output`].map(t=>{let r=n(t===`input`?`tokenMiss`:t===`cacheHit`?`tokenHit`:`tokenOutput`);return(0,m.jsx)(`input`,{className:I.userPriceInputNum,type:`number`,min:0,step:.01,placeholder:r,"aria-label":`${e.label} ${r}`,value:e.valueOf(t),onChange:n=>e.onChange(t,n.target.value)},t)})]},e.testid))]})]},t)),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-user-price-add`,onClick:u,children:n(`userPriceAdd`)}),(0,m.jsxs)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-user-price-remove-selected`,disabled:a.size===0,onClick:c,children:[n(`userPriceRemoveSelected`),a.size>0?` (${a.size})`:``]}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-user-price-save`,onClick:h,children:n(`userPriceSave`)})]})]})]})}function ii({stats:e,t,onClose:n,userPrices:r,onUserPrices:i,health:a,balances:o,reconcile:s,quotas:c,relayQuotas:l,currency:u,onCurrency:f,language:h,onLanguage:g,turns:_,renderSlot:v,budgetEnabled:b,budgetAmount:x,onToggleBudget:S,onBudgetAmount:C,peakConfig:w,onPeakConfig:T,onPreviewPeak:ee,floatPrefs:E,onFloatPrefs:D,cardPrefs:O,onCardPrefs:te,sitePrefs:ne,onSitePrefs:ie,liveCostPrefs:A,onLiveCostPrefs:ae,quotasStale:oe}){let[se,ce]=(0,d.useState)(`cost`),{total:j,byModel:le,byDay:M}=e,[N,ue]=(0,d.useState)(`overview`),[de,fe]=(0,d.useState)(7),[pe,me]=(0,d.useState)(()=>{try{return window.localStorage.getItem(`dsh-billing:reconcile-dismissed`)??``}catch{return``}}),ge=()=>{let e=new Date,t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`},_e=(0,d.useCallback)(()=>{let e=ge();me(e);try{window.localStorage.setItem(`dsh-billing:reconcile-dismissed`,e)}catch{}},[]),[be,P]=(0,d.useState)(`month`),[Ce,we]=(0,d.useState)(`cost`),[F,Ee]=(0,d.useState)(k),De=(0,d.useMemo)(()=>c.filter(e=>e.status===`ok`&&e.windows.length>0).map(e=>({id:e.provider,label:e.displayName})),[c]),[Oe,ke]=(0,d.useState)(),[Ae,je]=(0,d.useState)(new Set),Me=(0,d.useCallback)(e=>{je(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ne=(0,d.useMemo)(()=>Nr(e.bySession??[]),[e.bySession]),[Pe,Fe]=(0,d.useState)(()=>new Set(ve())),L=(0,d.useCallback)(e=>{Fe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),ye([...n]),n})},[]),[R,Ie]=(0,d.useState)(()=>xe()),Re=(0,d.useCallback)(()=>{Ie(e=>{let t=!e;return Se(t),t})},[]),[ze,Be]=(0,d.useState)(!1);(0,d.useEffect)(()=>{let e=!0;return Zr().then(t=>{e&&t!==void 0&&Be(t)}),()=>{e=!1}},[]);let Ve=(0,d.useCallback)(()=>{let e=!ze;Be(e),Qr(e).then(t=>{t||Be(!e)})},[ze]),z=$e(),[He,Ue]=(0,d.useState)(!1),We=(0,d.useCallback)(()=>{He||(Ue(!0),qr().finally(()=>{Ue(!1)}))},[He]),Ge=Gr,B=e=>K(Bt(e,u),u),Ke=u===`usd`?`$`:u===`eur`?`€`:`¥`,V=h,H=e=>Rn(e,V),[qe,Je]=(0,d.useState)(``),[Ye,Xe]=(0,d.useState)(()=>he()),[Ze,Qe]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{let e=setInterval(()=>{Qe(Date.now())},3e4);return()=>{clearInterval(e)}},[]);let et=c.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),tt=w.leadMin*6e4,U=(e,n)=>e===0?t(`free`):Vt(Ht(e,n,u,z.rate),u===`usd`?`USD`:u===`eur`?`EUR`:`CNY`),nt=(0,d.useMemo)(()=>Mn([..._].reverse()),[_]),W={peak:e.byTier?.peak.cost??0,offPeak:e.byTier?.offPeak.cost??0},rt=W.peak/2,it=br(M,q()),at=e=>o.find(t=>$(t.provider)===$(e)),ot=e=>e.balance?.error===`unconfigured`&&e.models.length>0&&e.models.every(e=>e.plan),st=e=>{if(e===void 0)return(0,m.jsx)(`span`,{className:I.na,children:`—`});if(e.error===`unconfigured`)return t(`balanceUnconfigured`);if(e.error===`unauthorized`)return t(`balanceUnauthorized`);if(e.error===`unreachable`)return t(`balanceUnreachable`);if(e.totalBalance===void 0)return(0,m.jsx)(`span`,{className:I.na,children:`—`});let n=e.currency===`USD`?`$${e.totalBalance.toFixed(2)}`:B(e.totalBalance),r=e.currency===`USD`?e.totalBalance*z.rate:e.totalBalance,i=it>0?Math.floor(r/it):void 0;return(0,m.jsxs)(`span`,{className:I.balanceCell,children:[(0,m.jsx)(`span`,{children:n}),i!==void 0&&i>=0&&(0,m.jsx)(`button`,{type:`button`,className:y(I.balanceDaysBadge,i<=3&&I.balanceDaysBadgeLow),"data-testid":`billing-balance-days-badge`,title:t(`balanceDays`).replace(`{days}`,String(i)),"aria-label":`${e.displayName} ${t(`balanceDays`).replace(`{days}`,String(i))}`,onClick:t=>{t.stopPropagation(),ke(Oe===e.provider?void 0:e.provider)},children:`?`}),Oe===e.provider&&(0,m.jsx)(ti,{balance:e,days:i??0,dailyBurn:it,money:B,t,onClose:()=>{ke(void 0)}})]})},ct=Object.keys(M).sort(),lt=q(),ft=M[lt]?.cost??0,pt=lt.slice(0,7),mt=lt.slice(0,4),ht=ct.reduce((e,t)=>e+(t.startsWith(pt)?M[t]?.cost??0:0),0),gt=ct.reduce((e,t)=>e+(t.startsWith(mt)?M[t]?.cost??0:0),0),_t=(0,d.useMemo)(()=>xr(M,pt,lt)+c.reduce((e,t)=>e+(t.planType===`code`?t.subscriptionAmount??0:0),0),[M,pt,lt,c]),vt=(0,d.useMemo)(()=>{if(!(b&&x>0))return null;let e=x-ht;return{over:e<=0,remainRatio:Math.max(0,Math.min(1,e/x)),remainCny:Math.max(0,e)}},[b,x,ht]),yt=(0,d.useMemo)(()=>{let e=[];for(let t=de-1;t>=0;--t){let n=new Date;n.setDate(n.getDate()-t),e.push(q(n.getTime()))}return e},[de]),G=yt.at(-1)??lt,bt=(0,d.useMemo)(()=>Object.entries(M).map(([e,t])=>({date:e,value:Ce===`tokens`?Or(t):t.cost})),[M,Ce]),xt=(0,d.useMemo)(()=>bt.reduce((e,t)=>e+t.value,0),[bt]),St=Er(M),Ct=Dr(M),wt=(0,d.useMemo)(()=>yt.map(t=>{let n={},r=e.byDayModels?.[t];if(r!==void 0)for(let[e,t]of Object.entries(r))t.cost>0&&(n[e]=t.cost);let i=M[t];return{date:t,cost:i?.cost??0,calls:i?.calls??0,byModel:n,tokens:i===void 0?0:Or(i)}}),[yt,M,e.byDayModels]),Tt=(0,d.useMemo)(()=>Object.entries(le).filter(([,e])=>e.calls>0).map(([e,t])=>{let n=Mt(e),r=n.key===`other`,i=r?ar(e):void 0,a={input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,output:t.output};return{key:e,name:r?e:n.name,provider:i??n.provider,calls:t.calls,input:t.input,output:t.output,cacheHitRate:t.cacheHit+t.cacheMiss>0?t.cacheHit/(t.cacheHit+t.cacheMiss)*100:0,estimated:Rt(n,a),plan:t.plan===!0,...t.cost>0?{actual:t.cost}:{},uncatalogued:r,estimatedPricing:n.estimated===!0,officialCalls:t.officialCalls??0,officialCost:t.officialCost??0}}).sort((e,t)=>(t.actual??t.estimated)-(e.actual??e.estimated)).map((e,t)=>({...e,color:Vr[t%Vr.length]??`#8b95a3`})),[le]),Et=(0,d.useMemo)(()=>ne.hideUnidentified?l.filter(e=>e.kind!==`unknown`):l,[l,ne.hideUnidentified]),Dt=(0,d.useMemo)(()=>{let n=e.byDayModelsSite;if(R){let t=q();n={[t]:e.byDayModelsSite?.[t]??{}}}let r=new Map;for(let t of Object.values(n??{}))for(let[n,i]of Object.entries(t))for(let[t,a]of Object.entries(i)){let i=r.get(t);i===void 0&&(i=new Map,r.set(t,i));let o=i.get(n)??{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cost:0,allPlan:!0};o.calls+=a.calls,o.input+=a.input,o.output+=a.output,o.cacheHit+=a.cacheHit,o.cacheMiss+=a.cacheMiss,o.cost+=a.cost,o.allPlan=o.allPlan&&(a.plan??e.byModel?.[n]?.plan===!0),i.set(n,o)}let i=new Map;for(let[e,t]of r){let n=!e.startsWith(`direct:`)&&!e.startsWith(`site:`),r=[...t.entries()].filter(([,e])=>e.calls>0).map(([e,t],r)=>{let i=Mt(e),a=i.key===`other`,o=a?ar(e)??i.provider:i.provider;return{key:e,name:a?e:i.name,provider:o,color:Vr[r%Vr.length]??`#8b95a3`,calls:t.calls,input:t.input,output:t.output,cacheHitRate:t.cacheHit+t.cacheMiss>0?t.cacheHit/(t.cacheHit+t.cacheMiss)*100:0,estimated:n?0:Rt(i,{input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,output:t.output}),plan:t.allPlan,...t.cost>0?{actual:t.cost}:{},uncatalogued:a,estimatedPricing:i.estimated===!0,officialCalls:0,officialCost:0}}).sort((e,t)=>(t.actual??t.estimated)-(e.actual??e.estimated));r.length>0&&i.set(e,r)}let s=e=>Hn(e,V)??t(`channelUnknown`),l=new Map,u=new Map,d=new Map,f=e=>e.startsWith(`direct:`)?`direct`:e.startsWith(`site:`)?`site`:`unknown`,p={direct:2,site:1,unknown:0,vendor:0};for(let[e,t]of i){let n=s(e),r=l.get(n);if(r===void 0)l.set(n,[...t]),u.set(n,f(e)),d.set(n,e);else{r.push(...t),r.sort((e,t)=>(t.actual??t.estimated)-(e.actual??e.estimated));let i=u.get(n)??`unknown`,a=f(e);p[a]>p[i]&&(u.set(n,a),d.set(n,e))}}let m=new Map,h=new Map;for(let e of c){if(e.status===`not-configured`)continue;let t=e.displayName??sr(e.provider),n=s(`direct:${e.provider}`),r=l.has(t)?t:l.has(n)?n:void 0,i=r??`sub:${sr(e.provider)}`;h.set(i,r??sr(e.provider));let a=m.get(i);a===void 0?m.set(i,[e]):a.push(e)}let g=e=>e===s(`direct:deepseek`)||e===s(`site:https://api.deepseek.com`)?at(`deepseek`)??at(e):at(e),_=[];for(let[e,t]of l)_.push({id:`ch:${d.get(e)??e}`,name:e,models:t,subscriptions:m.get(e)??[],balance:g(e),dot:Mr(a,t[0]?.provider??``),channelKind:u.get(e)??`unknown`});for(let[e,t]of h)l.has(e)||_.push({id:e,name:t,models:[],subscriptions:m.get(e)??[],balance:at(t),dot:Mr(a,t),channelKind:`vendor`});let v=new Set(_.flatMap(e=>[$(e.name),...e.balance===void 0?[]:[$(e.balance.provider)]]));for(let e of o)v.has($(e.provider))||(e.error===void 0||e.provider.startsWith(`custom:`))&&_.push({id:`bal:${e.provider}`,name:e.displayName,models:[],subscriptions:[],balance:e,dot:Mr(a,e.displayName),channelKind:`vendor`});return(R?_.filter(e=>e.models.length>0):_).sort((e,t)=>{let n=$r(t)-$r(e);return n===0?e.models.length===0&&t.models.length===0?0:t.models.length===0?-1:e.models.length===0?1:e.name.localeCompare(t.name,`zh`):n})},[e.byDayModelsSite,e.byModel,c,o,a,V,t,R]),Ot=(0,d.useMemo)(()=>Dt.filter(e=>e.models.length>0||e.subscriptions.length>0).map(e=>e.id),[Dt]),kt=Ot.length>0&&Ot.every(e=>Pe.has(e)),At=()=>{let e=new Set(kt?[]:Ot);Fe(e),ye([...e])},jt=(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:t(`model`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`calls`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`inputTokens`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`outputTokens`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`cacheHitRate`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`actual`)})]})}),Nt=e=>(0,m.jsx)(`span`,{className:I.modelCell,children:(0,m.jsxs)(`span`,{children:[(0,m.jsxs)(`span`,{className:I.modelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:I.uncataloguedTag,"data-testid":`billing-uncatalogued-tag`,children:t(`uncatalogued`)}),e.estimatedPricing&&(0,m.jsx)(`span`,{className:I.estimatedTag,"data-testid":`billing-estimated-tag`,children:t(`estimatedPricing`)})]}),(0,m.jsx)(`span`,{className:I.modelProvider,children:H(e.provider)})]})}),Ft=e.bySite?.unknown?.calls??0,Lt=Tt.reduce((e,t)=>e+t.estimated,0),zt=j.cost>0||Ft>0?j.cost:Lt,Y=(0,d.useMemo)(()=>{if(F===`all`){let e,t=0;for(let[n,r]of Object.entries(M)){let i=Or(r);i>t&&(t=i,e=n)}return{cost:zt,calls:j.calls,input:j.input,output:j.output,cacheHit:j.cacheHit,cacheMiss:j.cacheMiss,reasoning:j.reasoning??0,peakDay:e,peakTokens:t}}return jr(M,q(),F)},[F,zt,j,M]),Wt=(0,d.useMemo)(()=>Tt.map(e=>({key:e.key,name:e.name,color:e.color})),[Tt]),Gt=wt.length>=2?wt.at(-2)?.cost??0:0,Jt=Gt>0?(ft-Gt)/Gt*100:0;return(0,m.jsx)(p.Modal,{open:!0,onClose:n,title:t(`title`),headless:!0,className:y(I.dashboardModal,`dsh-billing-modal`),children:(0,m.jsxs)(`div`,{className:I.dashboard,"data-testid":`billing-dashboard`,children:[(0,m.jsxs)(`div`,{className:I.dashboardHead,"data-testid":`billing-dashboard-head`,children:[(0,m.jsxs)(`div`,{children:[v(`billing.dashboard.decor`,{position:`head`}),(0,m.jsxs)(`div`,{className:I.headTitleRow,children:[(0,m.jsx)(`h2`,{className:I.dashboardTitle,children:t(`title`)}),v(`billing.dashboard.decor`,{position:`headTitle`})]}),(0,m.jsxs)(`p`,{className:I.dashboardSubtitle,children:[t(`lastUpdated`),` `,G,e.timezone===void 0?null:` · ${e.timezone.name} (${e.timezone.offset})`]})]}),(0,m.jsxs)(`div`,{className:I.dashboardRight,children:[(0,m.jsx)(`span`,{className:I.currencyToggle,role:`group`,"aria-label":t(`language`),children:[`en`,`zh`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.currencyButton,h===e&&I.currencyButtonActive),"aria-pressed":h===e,"data-testid":`billing-language-${e}`,onClick:()=>{g(e)},children:e===`en`?`EN`:`中`},e))}),(0,m.jsx)(`span`,{className:I.currencyToggle,role:`group`,"aria-label":t(`currency`),children:[`cny`,`usd`,`eur`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.currencyButton,u===e&&I.currencyButtonActive),"aria-pressed":u===e,"data-testid":`billing-currency-${e}`,title:t(e===`cny`?`currencyCny`:e===`usd`?`currencyUsd`:`currencyEur`),onClick:()=>{f(e)},children:e===`cny`?`¥ CNY`:e===`usd`?`$ USD`:`€ EUR`},e))}),a.checked&&(0,m.jsxs)(`span`,{className:y(I.healthBadge,a.available?I.healthBadgeOk:I.healthBadgeBad),children:[(0,m.jsx)(`span`,{className:y(I.healthDot,a.available?I.healthOk:I.healthBad),"aria-hidden":`true`}),a.available?`${t(`healthModelsLive`).replace(`{n}`,String(a.models))}${a.failures>0?` · ${t(`healthVendorsDown`).replace(`{n}`,String(a.failures))}`:``}`:t(`healthVendorsUnavailable`).replace(`{n}`,String(a.failures))]}),(0,m.jsx)(`button`,{type:`button`,className:I.closeButton,"aria-label":t(`close`),"data-testid":`billing-close`,onClick:n,children:(0,m.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"aria-hidden":`true`,children:[(0,m.jsx)(`path`,{d:`M18 6 6 18`}),(0,m.jsx)(`path`,{d:`m6 6 12 12`})]})})]})]}),(0,m.jsx)(`nav`,{className:I.tabNav,"data-testid":`billing-tab-nav`,role:`tablist`,"aria-label":t(`title`),children:$n.map(e=>(0,m.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":N===e.id,className:y(I.tabButton,N===e.id&&I.tabButtonActive),"data-testid":`billing-tab-${e.id}`,onClick:()=>{ue(e.id)},children:t(e.labelKey)},e.id))}),(0,m.jsxs)(`div`,{className:I.dashboardBody,children:[N===`overview`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-overview`,children:[s?.kind===`drift`&&s.spent!==void 0&&pe!==ge()&&(0,m.jsxs)(`div`,{className:I.reconcileNotice,"data-testid":`billing-reconcile-notice`,role:`note`,children:[(0,m.jsx)(`span`,{className:I.reconcileIcon,"aria-hidden":`true`,children:(0,m.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,m.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`}),(0,m.jsx)(`line`,{x1:`12`,y1:`10`,x2:`12`,y2:`16`}),(0,m.jsx)(`line`,{x1:`12`,y1:`7.5`,x2:`12.01`,y2:`7.5`})]})}),(0,m.jsx)(`span`,{className:I.reconcileText,children:t(`reconcileDrift`).replace(`{provider}`,s.provider??``).replace(`{spent}`,B(s.spent)).replace(`{today}`,B(s.todayOfficialCost??0))}),(0,m.jsx)(`button`,{type:`button`,className:I.reconcileDismiss,"data-testid":`billing-reconcile-dismiss`,onClick:_e,children:t(`reconcileDismiss`)})]}),(0,m.jsxs)(`section`,{className:I.hero,"data-testid":`billing-hero`,children:[v(`billing.dashboard.decor`,{position:`hero`}),(0,m.jsxs)(`div`,{className:I.heroTop,children:[(0,m.jsxs)(`div`,{className:I.heroMain,children:[(0,m.jsx)(`span`,{className:I.heroLabel,children:t(`monthCost`)}),(0,m.jsxs)(`div`,{className:I.heroReadout,children:[(0,m.jsx)(`span`,{className:I.heroCurrency,"aria-hidden":`true`,children:Ke}),(0,m.jsx)(`span`,{className:I.heroValue,children:B(ht).slice(1)})]}),(0,m.jsxs)(`span`,{className:I.heroMeta,children:[j.calls.toLocaleString(),` `,t(`calls`)]})]}),vt!==null&&(0,m.jsxs)(`div`,{className:I.heroGauge,"data-testid":`billing-hero-gauge`,children:[(0,m.jsxs)(`div`,{className:I.heroGaugeDial,children:[(0,m.jsxs)(`svg`,{className:I.heroGaugeSvg,viewBox:`0 0 120 120`,"aria-hidden":`true`,children:[(0,m.jsx)(`circle`,{className:I.heroGaugeTrack,cx:`60`,cy:`60`,r:`52`}),(0,m.jsx)(`circle`,{className:y(I.heroGaugeArc,vt.over&&I.heroGaugeArcOver),cx:`60`,cy:`60`,r:`52`,style:{strokeDasharray:`${vt.remainRatio*326.7} 326.7`}})]}),(0,m.jsxs)(`span`,{className:I.heroGaugeCenter,children:[(0,m.jsxs)(`span`,{className:y(I.heroGaugeRemain,vt.over&&I.heroGaugeRemainOver),children:[Ke,Bt(vt.remainCny,u).toFixed(2)]}),(0,m.jsx)(`span`,{className:I.heroGaugeLabel,children:t(`budgetRemain`)})]})]}),(0,m.jsxs)(`span`,{className:I.heroGaugeSub,children:[B(ht),` / `,B(x)]})]})]}),(0,m.jsxs)(`div`,{className:I.heroSide,children:[(0,m.jsxs)(`div`,{className:I.heroSideItem,children:[(0,m.jsx)(`span`,{className:I.heroSideLabel,children:t(`yearCost`)}),(0,m.jsx)(`span`,{className:I.heroSideValue,children:B(gt)})]}),(0,m.jsxs)(`div`,{className:I.heroSideItem,children:[(0,m.jsx)(`span`,{className:I.heroSideLabel,children:t(`todayCost`)}),(0,m.jsxs)(`span`,{className:I.heroSideValue,children:[B(ft),(0,m.jsxs)(`span`,{className:y(I.delta,Jt>=0?I.deltaUp:I.deltaDown),children:[Jt>=0?`▲`:`▼`,` `,Math.abs(Jt).toFixed(1),`%`]})]})]}),_t>0&&(0,m.jsxs)(`div`,{className:I.heroSideItem,children:[(0,m.jsx)(`span`,{className:I.heroSideLabel,children:t(`monthProjected`)}),(0,m.jsx)(`span`,{className:I.heroSideValue,children:B(_t)})]}),_t<=0&&(0,m.jsx)(`span`,{className:I.heroSideSpacer,"aria-hidden":`true`})]})]}),(e.unpricedModels?.length??0)>0&&(0,m.jsx)(`div`,{className:I.unpricedHint,"data-testid":`billing-unpriced-hint`,children:t(`unpricedHint`).replace(`{count}`,String(e.unpricedModels?.length??0))}),(e.total.searchCalls??0)>0&&(0,m.jsx)(`div`,{className:I.unpricedHint,"data-testid":`billing-search-estimate-hint`,children:t(`searchEstimateHint`).replace(`{count}`,String(e.total.searchCalls??0)).replace(`{each}`,B(e.searchCallEstimateCny??0))}),(e.unreadableSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-sessions-unreadable`,children:(0,m.jsxs)(`div`,{className:I.staleNoticeBody,children:[t(`unreadableNotice`).replace(`{count}`,String(e.unreadableSessions)),(e.unreadableNoLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNoticeSub,"data-testid":`billing-sessions-no-ledger`,children:t(`unreadableNoLedgerNotice`).replace(`{count}`,String(e.unreadableNoLedgerSessions))}),(e.unreadableFormatSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNoticeSub,"data-testid":`billing-sessions-format-unsupported`,children:t(`unreadableFormatNotice`).replace(`{count}`,String(e.unreadableFormatSessions))})]})}),(0,m.jsxs)(`div`,{className:I.kpiZone,children:[(0,m.jsxs)(`div`,{className:I.kpiZoneHead,children:[(0,m.jsx)(`span`,{className:I.kpiZoneLabel,children:t(`kpiRange`)}),(0,m.jsx)(`div`,{className:I.heatmapRangeSwitch,"data-testid":`billing-kpi-range`,role:`group`,"aria-label":t(`kpiRange`),children:[[`today`,`avgRangeToday`],[`7d`,`avgRange7d`],[`week`,`avgRangeWeek`],[`month`,`avgRangeMonth`],[`all`,`avgRangeAll`]].map(([e,n])=>(0,m.jsx)(`button`,{type:`button`,className:y(I.heatmapRangeButton,F===e&&I.heatmapRangeButtonActive),"data-testid":`billing-kpi-range-${e}`,"aria-pressed":F===e,onClick:()=>{Ee(e),re(e)},children:t(n)},e))})]}),(0,m.jsxs)(`section`,{className:I.kpiGrid,"data-testid":`billing-kpi-grid`,children:[(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-tile`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`cacheHitRate`)}),(0,m.jsx)(`span`,{className:y(I.kpiValue,I.kpiGreen),children:Ut(Y.cacheHit+Y.cacheMiss>0?Y.cacheHit/(Y.cacheHit+Y.cacheMiss)*100:0)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[J(Y.cacheHit),` / `,J(Y.cacheHit+Y.cacheMiss),(j.cacheWrite??0)>0?` · ${t(`tokenCacheWrite`)} ${J(j.cacheWrite??0)}`:``]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokens`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:J(Y.input+Y.output)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[t(`inputTokens`),` `,J(Y.input),` · `,t(`outputTokens`),` `,J(Y.output)]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-avg`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`avgCost`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:B(Y.calls>0?Y.cost/Y.calls:0)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[t(`calls`),` `,Y.calls.toLocaleString()]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`calls`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:Y.calls.toLocaleString()}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[Tt.length,` `,t(`models`)]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-think`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokenReasoningShare`)}),(0,m.jsx)(`span`,{className:y(I.kpiValue,I.kpiGreen),children:Ut(Y.output>0?Y.reasoning/Y.output*100:0)}),(0,m.jsx)(`span`,{className:I.kpiDetail,children:J(Y.reasoning)})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-io`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokenIo`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:(Y.output>0?Y.input/Y.output:0).toFixed(2)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[J(Y.input),` / `,J(Y.output)]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-peak`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokenPeak`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:Y.peakTokens>0?Qt(Y.peakTokens):`—`}),(0,m.jsx)(`span`,{className:I.kpiDetail,children:Y.peakDay??`—`})]})]})]}),(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-heatmap`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`heatmap`)}),(0,m.jsx)(`div`,{className:I.heatmapRangeSwitch,"data-testid":`billing-heatmap-metric`,role:`group`,"aria-label":t(`heatmap`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.heatmapRangeButton,Ce===e&&I.heatmapRangeButtonActive),"data-testid":`billing-heatmap-metric-${e}`,"aria-pressed":Ce===e,onClick:()=>{we(e)},children:t(e===`cost`?`metricCost`:`metricTokens`)},e))}),(0,m.jsx)(`div`,{className:I.heatmapRangeSwitch,"data-testid":`billing-heatmap-range`,role:`group`,"aria-label":t(`heatmap`),children:[`month`,`half`,`year`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.heatmapRangeButton,be===e&&I.heatmapRangeButtonActive),"data-testid":`billing-heatmap-range-${e}`,"aria-pressed":be===e,onClick:()=>{P(e)},children:t(e===`month`?`heatmapMonth`:e===`half`?`heatmapHalf`:`heatmapYear`)},e))}),(0,m.jsxs)(`span`,{className:I.panelHint,"data-testid":`billing-heatmap-summary`,children:[t(`heatmapTotal`),` `,Ce===`tokens`?J(xt):B(xt),` · `,t(`activeDays`),` `,St,` · `,t(`streakDays`),` `,Ct]})]}),(0,m.jsx)(On,{days:bt,currency:u,t,range:be,unit:Ce})]})]}),N===`settings`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-settings`,children:[(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-budget`,children:[(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`budget`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`budgetHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":b,"aria-label":t(`budget`),"data-testid":`billing-budget-toggle`,className:y(I.switch,b&&I.switchOn),onClick:S,children:(0,m.jsx)(`span`,{className:I.switchKnob})})]}),b&&(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`budgetAmount`)}),(0,m.jsxs)(`span`,{className:I.inp,"data-testid":`billing-budget-input-wrap`,children:[(0,m.jsx)(`span`,{className:I.affix,"aria-hidden":`true`,children:`¥`}),(0,m.jsx)(`input`,{className:I.budgetInput,"data-testid":`billing-budget-input`,type:`number`,min:0,step:1,value:x===0?``:x,placeholder:e.budget===void 0?`0`:String(e.budget),"aria-label":`${t(`budget`)}(${u===`usd`?`USD`:u===`eur`?`EUR`:`CNY`})`,title:`${t(`budget`)}(${u===`usd`?`USD`:u===`eur`?`EUR`:`CNY`})`,onChange:e=>{C(e.target.valueAsNumber)}})]})]}),x>0&&(()=>{let e=ht/x*100;return(0,m.jsx)(`div`,{className:I.ctlRowStretch,children:(0,m.jsx)(`div`,{className:I.prog,role:`progressbar`,"aria-valuenow":Math.min(e,100),"aria-valuemin":0,"aria-valuemax":100,"aria-label":t(`budget`),"data-testid":`billing-budget-track`,children:(0,m.jsx)(`div`,{className:y(I.progFill,e>=100&&I.budgetFillOver,e>=80&&e<100&&I.budgetFillWarn),style:{width:`${Math.min(e,100)}%`}})})})})(),x>0&&(0,m.jsx)(`p`,{className:I.setCardDesc,"data-testid":`billing-budget-value`,children:t(`budgetSummary`).replace(`{used}`,B(ht)).replace(`{total}`,B(x))})]})]}),(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-peak-alert-settings`,children:[(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`peakAlert`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`peakAlertHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":w.enabled,"aria-label":t(`peakAlert`),"data-testid":`billing-peak-alert-toggle`,className:y(I.switch,w.enabled&&I.switchOn),onClick:()=>{T({...w,enabled:!w.enabled})},children:(0,m.jsx)(`span`,{className:I.switchKnob})})]}),w.enabled&&(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`label`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertLeadMin`)}),(0,m.jsx)(`span`,{className:I.inp,children:(0,m.jsx)(`input`,{type:`number`,min:1,max:30,step:1,value:w.leadMin,className:I.budgetInput,"aria-label":t(`peakAlertLeadMin`),onChange:e=>{let t=Number(e.target.valueAsNumber);T({...w,leadMin:Number.isFinite(t)?Math.min(30,Math.max(1,Math.round(t))):w.leadMin})}})})]}),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertPos`)}),(0,m.jsx)(`div`,{className:I.ctlGroup,role:`radiogroup`,"aria-label":t(`peakAlertPos`),children:[`bottom-right`,`center`].map(e=>(0,m.jsxs)(`label`,{className:I.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-pos`,checked:w.position===e,onChange:()=>T({...w,position:e})}),(0,m.jsx)(`span`,{className:I.rdoDot,"aria-hidden":`true`}),t(e===`bottom-right`?`peakAlertPosCorner`:`peakAlertPosCenter`)]},e))})]}),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertMode`)}),(0,m.jsx)(`div`,{className:I.ctlGroup,role:`radiogroup`,"aria-label":t(`peakAlertMode`),children:[`both`,`peak`,`offPeak`].map(e=>(0,m.jsxs)(`label`,{className:I.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-mode`,checked:w.mode===e,onChange:()=>T({...w,mode:e})}),(0,m.jsx)(`span`,{className:I.rdoDot,"aria-hidden":`true`}),t(e===`both`?`peakAlertModeBoth`:e===`peak`?`peakAlertModePeak`:`peakAlertModeOff`)]},e))})]}),(0,m.jsxs)(`label`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertWebNotify`)}),(0,m.jsx)(`input`,{type:`checkbox`,checked:w.webNotify,"aria-label":t(`peakAlertWebNotify`),onChange:e=>{T({...w,webNotify:e.target.checked})}})]}),(0,m.jsx)(`div`,{className:I.ctlRow,children:(0,m.jsx)(`button`,{type:`button`,className:I.btn,onClick:ee,children:t(`peakAlertPreview`)})})]})]}),(0,m.jsx)(`section`,{className:I.setCard,"data-testid":`billing-toggle-setting`,children:(0,m.jsxs)(`div`,{className:I.setGrid3,children:[(0,m.jsx)(`div`,{className:I.setCell,"data-testid":`billing-usage-stats-tool-setting`,children:(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`usageStatsTool`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`usageStatsToolHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":ze,"aria-label":t(`usageStatsTool`),"data-testid":`billing-usage-stats-tool-toggle`,className:y(I.switch,ze&&I.switchOn),onClick:Ve,children:(0,m.jsx)(`span`,{className:I.switchKnob})})]})}),(0,m.jsxs)(`div`,{className:I.setCell,"data-testid":`billing-livecost-setting`,children:[(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`liveCostBar`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`liveCostBarHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":A.show,"aria-label":t(`liveCostBar`),"data-testid":`billing-livecost-toggle`,className:y(I.switch,A.show&&I.switchOn),onClick:()=>ae({...A,show:!A.show}),children:(0,m.jsx)(`span`,{className:I.switchKnob})})]}),A.show&&(0,m.jsxs)(`div`,{className:I.rdoRow,"data-testid":`billing-livecost-position`,children:[(0,m.jsx)(`span`,{className:I.rdoLabel,children:t(`liveCostBarPosition`)}),(0,m.jsx)(oi,{liveCostPrefs:A,onLiveCostPrefs:ae,t})]})]}),(0,m.jsx)(`div`,{className:I.setCell,"data-testid":`billing-site-list-setting`,children:(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`siteListDisplay`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`siteListDisplayHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":ne.hideUnidentified,"aria-label":t(`siteListDisplay`),"data-testid":`billing-site-hide-unidentified`,className:y(I.switch,ne.hideUnidentified&&I.switchOn),onClick:()=>ie({hideUnidentified:!ne.hideUnidentified}),children:(0,m.jsx)(`span`,{className:I.switchKnob})})]})})]})}),(0,m.jsx)(`section`,{className:I.setCard,"data-testid":`billing-display-setting`,children:(0,m.jsxs)(`div`,{className:I.setGrid2,children:[(0,m.jsxs)(`div`,{className:I.setCell,"data-testid":`billing-float-setting`,children:[(0,m.jsx)(`div`,{className:I.setCardHead,children:(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`floatWindow`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`floatWindowHint`)})]})}),(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`floatMode`)}),(0,m.jsxs)(`div`,{className:I.ctlGroup,"data-testid":`billing-float-mode`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,E.mode===`combined`&&I.floatModeBtnOn),"data-testid":`billing-float-mode-combined`,onClick:()=>D({mode:`combined`,targets:E.targets}),children:t(`floatModeCombined`)}),(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,E.mode===`subscription`&&I.floatModeBtnOn),"data-testid":`billing-float-mode-subscription`,onClick:()=>D({mode:`subscription`,targets:E.targets}),children:t(`floatModeSubscription`)})]})]}),E.mode===`subscription`&&(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`floatTargets`)}),(0,m.jsxs)(`span`,{className:I.ctlGroup,"data-testid":`billing-float-targets`,children:[De.map(e=>{let t=E.targets.includes(e.id);return(0,m.jsxs)(`label`,{className:I.floatTarget,children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:t,"data-testid":`billing-float-target-${e.id}`,onChange:()=>D({mode:`subscription`,targets:t?E.targets.filter(t=>t!==e.id):[...E.targets,e.id]})}),(0,m.jsx)(`span`,{className:I.floatTargetLabel,children:e.label})]},e.id)}),De.length===0&&(0,m.jsx)(`span`,{className:I.setCardDesc,children:t(`floatNoTargetsHint`)})]})]})]})]}),(0,m.jsxs)(`div`,{className:I.setCell,"data-testid":`billing-card-setting`,children:[(0,m.jsx)(`div`,{className:I.setCardHead,children:(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`cardDisplay`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`cardDisplayHint`)})]})}),(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`cardMetric`)}),(0,m.jsxs)(`div`,{className:I.ctlGroup,"data-testid":`billing-card-metric`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,O.metric===`money`&&I.floatModeBtnOn),"data-testid":`billing-card-money`,onClick:()=>te({...O,metric:`money`}),children:t(`cardMetricMoney`)}),(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,O.metric===`tokens`&&I.floatModeBtnOn),"data-testid":`billing-card-tokens`,onClick:()=>te({...O,metric:`tokens`}),children:t(`cardMetricTokens`)})]})]}),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`cardSpan`)}),(0,m.jsx)(`div`,{className:I.ctlGroup,"data-testid":`billing-card-span`,children:[[`day`,`cardSpanDay`],[`week`,`cardSpanWeek`],[`month`,`cardSpanMonth`]].map(([e,n])=>(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,O.span===e&&I.floatModeBtnOn),"data-testid":`billing-card-span-${e}`,"aria-pressed":O.span===e,onClick:()=>te({...O,span:e}),children:t(n)},e))})]})]})]})]})}),(0,m.jsx)(ri,{userPrices:r,onUserPrices:i,t}),(0,m.jsx)(vn,{t,version:e.pluginVersion})]}),N===`trends`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-trends`,children:[(0,m.jsxs)(`section`,{className:y(I.ubCard,I.trendPanel),"data-testid":`billing-panel-trend`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`trend`)}),v(`billing.dashboard.decor`,{position:`trend`}),(0,m.jsxs)(`span`,{className:I.ubCardControlGroup,children:[(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":t(`trend`),children:[7,30].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,de===e&&I.rangeButtonActive),"aria-pressed":de===e,"data-testid":`billing-trend-${e}d`,onClick:()=>{fe(e)},children:t(e===7?`trend7d`:`trend30d`)},e))}),(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":t(`trendMetric`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,se===e&&I.rangeButtonActive),"aria-pressed":se===e,"data-testid":`billing-trend-metric-${e}`,onClick:()=>{ce(e)},children:t(e===`cost`?`trendMetricCost`:`trendMetricTokens`)},e))})]}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:G})]}),(0,m.jsx)(ln,{data:wt,models:Wt,currency:u,metric:se,t})]}),_.length>0&&(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-rounds`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`rounds`)}),nt.length>0&&(0,m.jsxs)(`span`,{className:I.ubTagError,"data-testid":`billing-rounds-flag-count`,children:[nt.length,` `,t(`anomaly`)]})]}),(0,m.jsx)(`p`,{className:I.ubCardSub,children:t(`roundsHint`).replace(`{count}`,String(_.length))}),(0,m.jsx)(Sn,{rounds:_,flags:nt,currency:u,t})]}),e.byTier!==void 0&&(()=>{let e=W.peak+W.offPeak;if(e<=0)return null;let n=W.peak/e*100;return(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-share`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`peakShare`)}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:t(`peakSharePerCall`)})]}),(0,m.jsxs)(`div`,{className:I.shareTrack,"data-testid":`billing-share-track`,children:[(0,m.jsx)(`div`,{className:y(I.shareSeg,I.shareSegPeak),style:{width:`${n}%`}}),(0,m.jsx)(`div`,{className:y(I.shareSeg,I.shareSegOff),style:{width:`${100-n}%`}})]}),(0,m.jsxs)(`div`,{className:I.shareLegend,children:[(0,m.jsxs)(`span`,{className:I.shareItem,children:[(0,m.jsx)(`span`,{className:I.shareDot,style:{background:`var(--ds-blue)`}}),t(`peak`),(0,m.jsxs)(`span`,{className:I.shareValue,"data-testid":`billing-share-peak`,children:[B(W.peak),` · `,n.toFixed(1),`%`]})]}),(0,m.jsxs)(`span`,{className:I.shareItem,children:[(0,m.jsx)(`span`,{className:I.shareDot,style:{background:`color-mix(in srgb, var(--ds-blue) 30%, var(--dsb-3))`}}),t(`offPeak`),(0,m.jsxs)(`span`,{className:I.shareValue,"data-testid":`billing-share-offpeak`,children:[B(W.offPeak),` · `,(100-n).toFixed(1),`%`]})]})]}),rt>0&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-share-savings`,children:t(`offPeakSavings`).replace(`{amount}`,B(rt))})]})})()]}),N===`providers`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-providers`,children:[Et.length>0&&(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-relay-quota`,children:[(0,m.jsx)(`div`,{className:I.panelHead,children:(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`panelRelayQuota`)})}),(0,m.jsx)(`div`,{className:I.providerGroupList,"data-testid":`billing-relay-quotas`,children:Et.map(e=>(0,m.jsxs)(`div`,{className:I.siteRow,"data-testid":`billing-relay-quota`,children:[(0,m.jsxs)(`span`,{className:I.siteRowName,children:[(0,m.jsx)(`span`,{className:y(I.siteKindTag,Rr[e.kind]),children:Lr(e.kind,t)}),(0,m.jsx)(`span`,{className:I.siteRowTitle,children:e.origin})]}),(0,m.jsxs)(`span`,{className:I.siteRowMeta,children:[e.balance!==void 0&&(0,m.jsxs)(`span`,{className:I.siteRowCost,children:[t(`relayBalance`),` `,e.balance.toFixed(2)]}),(e.windows?.length??0)>0?e.windows?.map(e=>{let n=e.remainingPercent<20;return(0,m.jsxs)(`span`,{className:y(I.siteRowCalls,n&&I.siteRowCallsLow),children:[t(`relayWindowUsed`),` `,e.usedPercent,`%`]},e.kind)}):(0,m.jsx)(`span`,{className:I.siteRowCalls,children:t(`relayNoQuota`)})]})]},e.route))})]}),(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-providers`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`providerBilling`)}),v(`billing.dashboard.decor`,{position:`models`}),(0,m.jsx)(`span`,{className:I.panelHint,children:e.updatedAt===void 0?``:`${t(`lastUpdated`)} ${Br(e.updatedAt)}`})]}),oe&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-subscriptions-stale`,children:t(`subscriptionsStale`)}),(0,m.jsxs)(`div`,{className:I.providerCtlRow,"data-testid":`billing-provider-controls`,children:[(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,disabled:Ot.length===0,onClick:At,children:t(kt?`collapseAll`:`expandAll`)}),(0,m.jsxs)(`span`,{className:I.providerTodayToggle,children:[(0,m.jsx)(`span`,{children:t(`todayOnly`)}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":R,"data-testid":`billing-provider-today-toggle`,className:y(I.switch,R&&I.switchOn),onClick:Re,children:(0,m.jsx)(`span`,{className:I.switchKnob})})]})]}),Dt.length===0?(0,m.jsx)(`div`,{className:I.emptyRow,"data-testid":`billing-provider-empty`,children:t(R?`todayNoConsumption`:`noData`)}):(0,m.jsx)(`div`,{className:I.providerGroupList,"data-testid":`billing-provider-groups`,children:Dt.map(e=>{let n=e.models.length>0||e.subscriptions.length>0,r=n&&Pe.has(e.id);return(0,m.jsxs)(`div`,{className:I.providerGroup,"data-testid":`billing-provider-group`,children:[(0,m.jsxs)(`div`,{className:y(I.providerGroupHead,n&&I.providerGroupCollapsible),"data-testid":`billing-provider-group-head`,"aria-expanded":n?r:void 0,role:n?`button`:void 0,tabIndex:n?0:void 0,onClick:n?()=>{L(e.id)}:void 0,onKeyDown:n?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),L(e.id))}:void 0,children:[(0,m.jsxs)(`span`,{className:I.providerGroupTitle,children:[(0,m.jsx)(`span`,{className:y(I.healthDot,e.dot),"aria-hidden":`true`}),(()=>{let n=H(e.name),r=e.channelKind===`direct`?Wn(n):void 0,i=e.channelKind===`direct`?t(`directTag`):e.channelKind===`site`?t(`relayTag`):e.channelKind===`unknown`?t(`unknownTag`):void 0;return(0,m.jsxs)(m.Fragment,{children:[i!==void 0&&(0,m.jsx)(`span`,{className:y(I.kindBadge,e.channelKind===`direct`&&I.kindBadgeDirect,e.channelKind===`site`&&I.kindBadgeRelay,e.channelKind===`unknown`&&I.kindBadgeUnknown),"data-testid":`billing-kind-badge`,children:i}),e.channelKind!==`unknown`&&(0,m.jsx)(`span`,{className:I.providerGroupName,children:r??n})]})})(),e.subscriptions.length>0&&(0,m.jsxs)(`span`,{className:I.providerGroupBadge,"data-testid":`billing-provider-sub-count`,children:[e.subscriptions.length,` `,t(`planCountUnit`)]})]}),(0,m.jsxs)(`span`,{className:I.providerGroupMeta,children:[(0,m.jsxs)(`span`,{className:I.providerGroupCost,"data-testid":`billing-provider-cost`,children:[(0,m.jsx)(`span`,{className:I.providerGroupCostLabel,children:t(`cost`)}),e.channelKind===`unknown`?(0,m.jsx)(`span`,{className:I.na,children:`—`}):(0,m.jsx)(`span`,{className:I.providerGroupCostValue,children:B($r(e))})]}),!ot(e)&&e.balance!==void 0?(0,m.jsxs)(`span`,{className:I.providerGroupBalance,"data-testid":`billing-provider-balance`,children:[(0,m.jsx)(`span`,{className:I.providerGroupBalanceLabel,children:t(`balance`)}),st(e.balance)]}):(0,m.jsx)(`span`,{className:I.providerGroupBalance,"aria-hidden":`true`}),yr(e.name)===void 0?(0,m.jsx)(`span`,{className:I.providerGroupRecharge,"aria-hidden":`true`}):(0,m.jsx)(`a`,{className:I.providerGroupRecharge,"data-testid":`billing-group-recharge`,href:yr(e.name),target:`_blank`,rel:`noreferrer`,title:t(`rechargeHint`),"aria-label":`${H(e.name)} ${t(`recharge`)}`,onClick:e=>{e.stopPropagation()},children:t(`recharge`)})]})]}),r&&(0,m.jsxs)(m.Fragment,{children:[e.channelKind===`unknown`&&(0,m.jsx)(`p`,{className:I.unknownHint,"data-testid":`billing-unknown-hint`,children:t(`unknownChannelHint`)}),e.models.length>0&&(0,m.jsx)(`div`,{className:y(I.tableScroll,I.modelTableScroll),"data-testid":`billing-table-scroll`,children:(0,m.jsxs)(`table`,{className:I.modelTable,children:[jt,(0,m.jsx)(`tbody`,{children:e.models.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:Nt(e)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:I.numCol,children:J(e.input)}),(0,m.jsx)(`td`,{className:I.numCol,children:J(e.output)}),(0,m.jsx)(`td`,{className:I.numCol,children:Ut(e.cacheHitRate)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.plan?(0,m.jsxs)(`span`,{className:I.planTag,children:[e.estimated>0?(0,m.jsxs)(`span`,{children:[`≈`,B(e.estimated)]}):null,(0,m.jsx)(`span`,{className:I.planTagBadge,"data-testid":`billing-plan-badge`,children:t(`subscriptionTag`)})]}):e.actual===void 0?e.estimated>0?(0,m.jsxs)(`span`,{title:t(`cellEstimateHint`),children:[`≈`,B(e.estimated)]}):(0,m.jsx)(`span`,{className:I.na,children:`—`}):(()=>{let t=e.officialCost,n=e.actual-t;return t>0&&n>0?(0,m.jsxs)(`span`,{className:I.bucketCost,children:[(0,m.jsx)(`span`,{className:I.bucketOfficial,children:B(t)}),(0,m.jsx)(`span`,{className:I.bucketSep,children:`/`}),(0,m.jsx)(`span`,{className:I.bucketThird,children:B(n)})]}):B(e.actual)})()})]},e.key))})]})}),e.subscriptions.length>0&&(0,m.jsx)(`div`,{className:I.subscriptionGrid,"data-testid":`billing-subscriptions-grid`,children:e.subscriptions.map(e=>{let n=Pr(e.status,t);return(0,m.jsxs)(`div`,{className:I.subscriptionCard,"data-testid":`billing-subscription-card`,children:[(0,m.jsxs)(`div`,{className:I.subscriptionHead,children:[(0,m.jsx)(`span`,{className:I.subscriptionName,children:H(e.displayName)}),e.planType===`code`&&(()=>{let n=Le(e.provider),r=n===void 0?void 0:t(`subscriptionFeePerMonth`).replace(`{amount}`,n.currency===`USD`?`$${n.amount}`:`¥${n.amount}`);return(0,m.jsxs)(`span`,{className:I.subscriptionPlan,"data-kind":`code`,children:[r??(e.subscriptionAmount!==void 0&&e.subscriptionAmount>0?t(`subscriptionFeePerMonth`).replace(`{amount}`,B(e.subscriptionAmount)):t(`planTypeCode`)),n?.label!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionTier,"data-testid":`billing-tier-${e.provider}`,children:n.label}),n!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionAuto,"data-testid":`billing-auto-${e.provider}`,children:t(`subscriptionAutoDetect`)})]})})(),e.planType===`token`&&(0,m.jsx)(`span`,{className:I.subscriptionPlan,"data-kind":`token`,children:t(`planTypeToken`)}),e.plan!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionPlan,children:e.plan})]}),n!==``&&(0,m.jsx)(`div`,{className:I.subscriptionStatus,children:n}),e.windows.length===0&&n===``&&(0,m.jsx)(`div`,{className:I.subscriptionStatus,children:t(`subscriptionNoApi`)}),e.windows.map(e=>(0,m.jsx)(Fr,{window:e,t},e.kind))]},e.provider)})})]})]},e.id)})})]}),(0,m.jsxs)(`div`,{className:I.exportBar,"data-testid":`billing-export-bar`,role:`group`,"aria-label":t(`export`),children:[(0,m.jsx)(`span`,{className:I.exportLabel,children:t(`export`)}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-day`,onClick:()=>{Zt(Xt(`usage-daily`,`csv`,Object.keys(M)),Kt(M),`text/csv`)},children:t(`exportCsvDay`)}),e.bySession!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-sessions`,onClick:()=>{Zt(Xt(`usage-sessions`,`csv`,Object.keys(M)),Yt(e.bySession??[]),`text/csv`)},children:t(`exportCsvSession`)}),e.bySite!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-sites`,onClick:()=>{Zt(Xt(`usage-sites`,`csv`,Object.keys(M)),qt(e.bySite??{}),`text/csv`)},children:t(`exportCsvSite`)}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-json`,onClick:()=>{Zt(Xt(`usage-stats`,`json`,Object.keys(M)),JSON.stringify(e,null,2),`application/json`)},children:t(`exportJson`)})]}),e.bySession!==void 0&&(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-sessions`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`sessions`)}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:e.bySession.length>20?t(`sessionOverflow`).replace(`{limit}`,`20`).replace(`{total}`,String(e.bySession.length)):`${e.bySession.length}`})]}),(e.staleLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-sessions-stale`,children:t(`staleLedgerNotice`).replace(`{count}`,String(e.staleLedgerSessions))}),(0,m.jsx)(`div`,{className:I.ubTablewrap,"data-testid":`billing-sessions-table`,children:(0,m.jsxs)(`table`,{className:I.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:t(`sessionTitle`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`calls`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`actual`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`lastActive`)})]})}),(0,m.jsxs)(`tbody`,{children:[Ne.length===0&&(0,m.jsx)(`tr`,{children:(0,m.jsx)(`td`,{colSpan:4,className:I.emptyRow,children:t(`noData`)})}),Ne.slice(0,20).map(e=>{let n=e.children!==void 0,r=n&&Ae.has(e.id),i=e=>(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:I.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:I.numCol,children:B(e.cost)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.lastActive>0?`${q(e.lastActive)} ${Br(e.lastActive)}`:`—`})]});return(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{className:n?I.sessionGroupRow:void 0,"aria-expanded":n?r:void 0,tabIndex:n?0:void 0,onClick:n?()=>{Me(e.id)}:void 0,onKeyDown:n?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Me(e.id))}:void 0,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsxs)(`span`,{className:I.modelName,children:[e.title??`${t(`sessionUntitled`)} · ${e.id.slice(0,8)}`,(e.mergedCount??1)>1?` ×${e.mergedCount}`:``]}),e.stale===!0&&(0,m.jsx)(`span`,{className:y(I.ubTag,I.ubTagNeutral),"data-testid":`billing-session-stale`,children:t(`sessionStaleBadge`)})]}),i(e)]}),r&&e.children?.map(e=>(0,m.jsxs)(`tr`,{className:I.sessionChildRow,children:[(0,m.jsx)(`td`,{children:(0,m.jsx)(`span`,{className:I.modelProvider,children:e.id.slice(0,8)})}),i(e)]},e.id))]},e.id)})]})]})})]})]}),N===`token`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-token`,children:[(0,m.jsx)(rn,{stats:e,trendDays:de,onTrendDays:fe,models:Wt,money:B,t}),e.perf!==void 0&&(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-perf`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`perfTitle`)}),(0,m.jsx)(`span`,{className:I.panelHint,children:t(`perfHint`)})]}),(0,m.jsx)(hn,{perf:e.perf,models:Wt,t})]})]}),N===`pricing`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:I.ubAlert,role:`note`,children:[(0,m.jsxs)(`div`,{className:I.ubAlertLeft,children:[(0,m.jsxs)(`span`,{className:I.ubRate,"data-testid":`billing-rate`,children:[t(`todayRate`),` 1 USD = `,K(z.rate)]}),(0,m.jsx)(`span`,{className:y(I.ubTag,z.live?I.ubTagSuccess:I.ubTagNeutral),children:z.live?t(`rateLive`):t(`rateBuiltin`)}),Ge>0&&(0,m.jsxs)(`span`,{className:I.ubTag,"data-testid":`billing-pricing-synced`,children:[t(`pricingSyncedAt`),` `,new Date(Ge).toLocaleTimeString(V===`zh`?`zh-CN`:`en-US`,{hour:`2-digit`,minute:`2-digit`})]}),(0,m.jsx)(`button`,{type:`button`,className:I.heatmapRangeButton,"data-testid":`billing-pricing-sync`,disabled:He,onClick:We,children:t(He?`pricingSyncing`:`pricingSyncNow`)})]}),(0,m.jsx)(`p`,{className:I.ubAlertNote,children:t(`pricingTip`)})]}),(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`pricing`)}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:t(`pricingUnit`)}),(0,m.jsx)(`input`,{className:I.ubSearch,type:`search`,value:qe,placeholder:t(`pricingSearch`),"aria-label":t(`pricingSearch`),"data-testid":`billing-pricing-search`,onChange:e=>{Je(e.target.value)}})]}),(0,m.jsx)(`div`,{className:I.ubTablewrap,children:(0,m.jsxs)(`table`,{className:I.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:t(`thModel`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`thInputMiss`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`thInputHit`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`output`)}),(0,m.jsx)(`th`,{className:I.numCol,colSpan:2,children:t(`band`)})]})}),(0,m.jsx)(`tbody`,{children:In(It(),qe).map(e=>{let n=e.price.input>0||e.price.output>0;return(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:(0,m.jsxs)(`span`,{className:I.ubModel,children:[(()=>{let n=Nn(dt(Ze,ut(e.key,et)),tt);if(n===null)return null;let r=Ye.includes(e.key),i=`${e.name} · ${t(n===`peak`?`peak`:`offPeak`)} · ${t(`bandPinHint`)}`;return(0,m.jsx)(`button`,{type:`button`,className:y(I.bandDot,I[n],r&&I.bandDotOn),"data-testid":`billing-band-dot`,"aria-pressed":r,"aria-label":i,title:i,onClick:()=>{Xe(Te(e.key)),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.pinned-pref`))}})})(),(0,m.jsxs)(`span`,{className:I.ubModelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:I.ubTagAlert,"data-testid":`billing-price-uncatalogued`,children:t(`uncatalogued`)}),e.promo!==void 0&&Pt(e.promo,Date.now())&&(0,m.jsx)(p.Tooltip,{label:[e.promo.note,e.promo.endsAtMs===void 0?t(`promoOpenEnded`):t(`promoUntil`,{date:new Date(e.promo.endsAtMs).toLocaleDateString()})].filter(Boolean).join(` · `),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:I.ubTagPromo,"data-testid":`billing-price-promo`,children:t(`promoBadge`)})})]})]})}),(0,m.jsx)(`td`,{className:I.numCol,children:n?U(e.price.input,e.price.currency):(0,m.jsx)(`span`,{className:I.na,children:`—`})}),(0,m.jsx)(`td`,{className:I.numCol,children:n?U(e.price.cacheHit,e.price.currency):(0,m.jsx)(`span`,{className:I.na,children:`—`})}),(0,m.jsx)(`td`,{className:I.numCol,children:n?U(e.price.output,e.price.currency):(0,m.jsx)(`span`,{className:I.na,children:`—`})}),n&&e.price.offPeak!==void 0&&e.peakHours!==void 0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:I.numCol,children:(0,m.jsxs)(`span`,{className:I.ubChipPeak,children:[(0,m.jsx)(`span`,{className:I.ubChipLabel,children:e.tierSemantics===`latency`?t(`ubStd`):t(`ubPeak`)}),(0,m.jsxs)(`span`,{className:I.num,children:[U(e.price.input,e.price.currency),`/`,U(e.price.output,e.price.currency)]})]})}),(0,m.jsx)(`td`,{className:I.numCol,children:(0,m.jsxs)(`span`,{className:I.ubChipOff,children:[(0,m.jsx)(`span`,{className:I.ubChipLabel,children:e.tierSemantics===`latency`?`Flex`:t(`ubOff`)}),(0,m.jsxs)(`span`,{className:I.num,children:[U(e.price.offPeak.input,e.price.currency),` / `,U(e.price.offPeak.output,e.price.currency)]})]})})]}):(0,m.jsx)(`td`,{className:I.numCol,colSpan:2,children:n?(0,m.jsx)(`span`,{className:I.flatTag,children:t(`flat`)}):(0,m.jsx)(`span`,{className:I.na,children:`—`})})]}),(e.extraRows??[]).map(t=>(0,m.jsxs)(`tr`,{className:I.ubExtraRow,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:I.ubExtraName,children:Fn(t.label,V)}),t.note!==void 0&&(0,m.jsx)(`span`,{className:I.ubExtraNote,children:Fn(t.note,V)})]}),(0,m.jsx)(`td`,{className:I.numCol,children:t.input===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):U(t.input,e.price.currency)}),(0,m.jsx)(`td`,{className:I.numCol,children:(0,m.jsx)(`span`,{className:I.na,children:`—`})}),(0,m.jsx)(`td`,{className:I.numCol,children:t.output===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):U(t.output,e.price.currency)}),(0,m.jsx)(`td`,{className:I.numCol,colSpan:2,children:(0,m.jsx)(`span`,{className:I.na,children:`—`})})]},`${e.key}:${t.label}`))]},e.key)})})]})})]}),(0,m.jsxs)(`section`,{className:I.ubCard,children:[(0,m.jsx)(`div`,{className:I.ubCardHead,children:(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`pricingNotes`)})}),(0,m.jsxs)(`ul`,{className:I.ubNotes,children:[(0,m.jsxs)(`li`,{className:I.ubNotesItem,children:[(0,m.jsx)(`span`,{className:I.ubNotesTerm,children:t(`cacheHit`)}),(0,m.jsx)(`span`,{className:I.ubNotesDesc,children:t(`noteCache`)})]}),(0,m.jsxs)(`li`,{className:I.ubNotesItem,children:[(0,m.jsx)(`span`,{className:I.ubNotesTerm,children:t(`peakBand`)}),(0,m.jsx)(`span`,{className:I.ubNotesDesc,children:t(`noteBand`)})]}),(0,m.jsxs)(`li`,{className:I.ubNotesItem,children:[(0,m.jsx)(`span`,{className:I.ubNotesTerm,children:t(`pricingSource`)}),(0,m.jsx)(`span`,{className:I.ubNotesDesc,children:t(`noteSource`)})]})]})]})]}),v(`billing.dashboard.decor`,{position:`footer`})]}),(0,m.jsxs)(`footer`,{className:I.modalFooter,"data-testid":`billing-footer`,children:[(0,m.jsx)(`span`,{children:t(`footer`)}),(0,m.jsx)(`span`,{children:t(`footerCredit`).replace(`{version}`,e.pluginVersion===void 0?`—`:`v${e.pluginVersion}`)})]})]})})}let ai=[`below`,`above`,`toolbar`];function oi({liveCostPrefs:e,onLiveCostPrefs:t,t:n}){let[r,i]=(0,d.useState)(!1),a={below:n(`liveCostBarPosBelow`),above:n(`liveCostBarPosAbove`),toolbar:n(`liveCostBarPosToolbar`)},o=ai.map(e=>({id:e,label:a[e]}));return(0,m.jsx)(p.Menu,{open:r,align:`end`,portal:!0,compact:!0,items:o,selectedId:e.position,onSelect:n=>{i(!1);let r=ai.find(e=>e===n);r!==void 0&&t({...e,position:r})},onClose:()=>{i(!1)},anchor:(0,m.jsxs)(`button`,{type:`button`,className:I.rdoSelect,"data-testid":`billing-livecost-position-select`,"aria-haspopup":`menu`,"aria-expanded":r,onClick:()=>{i(!r)},children:[(0,m.jsx)(`span`,{children:a[e.position]}),(0,m.jsx)(`span`,{className:y(I.rdoChevron,r&&I.rdoChevronOpen),"aria-hidden":!0,children:Qn?(0,m.jsx)(Qn,{}):null})]})})}function si(e){let{t,checkModels:n,publishCosts:r,registerOpen:i,renderSlot:a,useStore:o,actions:s}=e,[c,l]=(0,d.useState)(Hr),[u,f]=(0,d.useState)(tr),[p,h]=(0,d.useState)([]),[g,_]=(0,d.useState)(void 0),[v,y]=(0,d.useState)([]),[b,x]=(0,d.useState)(!1),[S,C]=(0,d.useState)([]),[w,E]=(0,d.useState)(()=>de()),[D,ne]=(0,d.useState)(()=>Ce()),k=(0,d.useCallback)(e=>{ne(e),we(e),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.language-pref`))},[]),re=(0,d.useCallback)(e=>{E(e),fe(e),window.dispatchEvent(new CustomEvent(ue))},[]),[ie,A]=(0,d.useState)(()=>T()),se=(0,d.useCallback)(e=>{A(e),ee(e)},[]),[ce,N]=(0,d.useState)(()=>ae()),pe=(0,d.useCallback)(e=>{N(e),oe(e)},[]),[me,he]=(0,d.useState)(()=>le()),ge=(0,d.useCallback)(e=>{he(e),M(e),window.dispatchEvent(new CustomEvent(j))},[]),[_e,ve]=(0,d.useState)(()=>O()),ye=(0,d.useCallback)(e=>{ve(e),te(e)},[]),[be,xe]=(0,d.useState)(()=>{let e=Ee();return B(e),e}),Se=(0,d.useCallback)(e=>{xe(e),B(e),De(e)},[]),P=(0,d.useMemo)(()=>Sr(c),[c,be]),Te=D,F=(0,d.useCallback)((e,n)=>{let r=(Te===`en`?Fe:Pe)[e]??t(e);if(n===void 0)return r;let i=r;for(let[e,t]of Object.entries(n))i=i.replaceAll(`{${e}}`,String(t));return i},[Te,t]),[Oe,ke]=(0,d.useState)(!1),Ae=(0,d.useCallback)(()=>{ke(!1)},[]),je=(0,d.useCallback)(()=>{Ur().then(e=>{e!==null&&l(e)}),Jr().then(({balances:e,reconcile:t})=>{e.length>0&&h(e),_(t)}),Yr().then(e=>{e.length>0&&y(e),x(!1)}).catch(()=>{x(!0)}),Xr().then(e=>{C(e)}).catch(()=>{})},[]),Me=(0,d.useCallback)(()=>{je(),Kr(),ke(!0)},[je]);(0,d.useEffect)(()=>{je(),Kr()},[je]);let[I,Ne]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{Ne(!document.hidden),document.hidden||(je(),Kr())};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[je]),(0,d.useEffect)(()=>{if(!I)return;let e=setInterval(()=>{je(),Kr()},Oe?zr:3e5);return()=>{clearInterval(e)}},[je,Oe,I]),(0,d.useEffect)(()=>{let e=!0;return n().then(t=>{e&&(f(t),Xe(t.catalog??[]))}),()=>{e=!1}},[n]);let L=q(),R=Object.entries(P.byDay).filter(([e])=>e.startsWith(L.slice(0,7))).reduce((e,[,t])=>e+t.cost,0),Ie=P.byDay[L]?.cost??0,Le=Ar(P.byDay,L),Re=(0,d.useMemo)(()=>kr(P.byDay).map(e=>{let t=P.byDay[e.date];return{date:e.date,cost:e.cost,tokens:t===void 0?0:Or(t)}}),[P.byDay]),ze=Object.entries(P.byDay).filter(([e])=>e.startsWith(L.slice(0,7))).reduce((e,[,t])=>e+Or(t),0),Be=(()=>{let e=P.byDay[L];return e===void 0?0:Or(e)})(),Ve=Ar(P.byDay,L,Or),z=o(e=>e.enabled),He=o(e=>e.amount),Ue=o(e=>e.tierAlertDays),We=o(e=>e.lastTierSwitchAt),[Ge,Ke]=(0,d.useState)(()=>qn()),[V,H]=(0,d.useState)(null),[qe,Je]=(0,d.useState)(null),[Ye,Ze]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{if(!Ge.enabled)return;let e=setInterval(()=>Ze(Date.now()),zr);return()=>{clearInterval(e)}},[Ge.enabled]);let Qe=(0,d.useCallback)(e=>{Ke(e),Jn(e)},[]),et=v.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),tt=ut(c.byTurn?.[0]?.model,et),nt=(0,d.useCallback)(()=>{Je({entering:U(Date.now())===`peak`?`offPeak`:`peak`,atMs:Date.now()+18e4,channel:tt})},[tt]),W=He>0?He:c.budget??0,rt=z&&W>0?R/W>=1?`over`:R/W>=.8?`warn`:`none`:`none`,it=(0,d.useCallback)(()=>{let e=!z;s.setEnabled(e),e&&typeof Notification<`u`&&Notification.permission==="default"&&Notification.requestPermission()},[s,z]);(0,d.useEffect)(()=>{if(!z||W<=0)return;let e=R/W*100,t=er.filter(t=>e>=t&&Ue?.[String(t)]!==L);if(t.length===0)return;let n=t[t.length-1]??100;if(s.markTierAlerted(t,L),!Cr())return;let r=F(`budgetTierBody`).replace(`{cost}`,K(R)).replace(`{budget}`,K(W)).replace(`{pct}`,String(n));Tr(`budget:${n}:${L}`,()=>{new Notification(F(`budget`),{body:r})})},[z,W,R,Ue,L,s,F]),(0,d.useEffect)(()=>{let e=Yn(Ye,Ge,We,tt);if(e===null||(s.markTierSwitchAlerted(e.atMs),H(e),!Ge.webNotify||!Cr()))return;let t=Math.max(1,Math.round((e.atMs-Ye)/6e4)),n=F(e.entering===`peak`?`peakAlertTitlePeak`:`peakAlertTitleOff`),r=F(e.channel===`zhipu-coding-plan`?e.entering===`peak`?`tierAlertEnterPeakZhipu`:`tierAlertEnterOffZhipu`:e.entering===`peak`?`tierAlertEnterPeak`:`tierAlertEnterOff`).replace(`{minutes}`,String(t));Tr(`peak:${e.atMs}`,()=>{new Notification(n,{body:r})})},[Ye,We,Ge,tt,s,F]);let at=o(e=>e.lastBalanceAlertDay),ot=P.lowBalanceThreshold??50,st=(0,d.useMemo)(()=>{if(p.length===0)return;let e=br(P.byDay,L),t=$e().rate;for(let n of p){if(n.totalBalance===void 0||n.error!==void 0)continue;let r=n.currency===`USD`?n.totalBalance*t:n.totalBalance;if(r>=ot)continue;let i=e>0?Math.floor(r/e):void 0;return{name:n.displayName,cny:r,days:i}}},[p,P.lowBalanceThreshold,P.byDay,L]);(0,d.useEffect)(()=>{if(st===void 0||at===L||(s.markBalanceAlerted(L),!Cr()))return;let e=F(`balanceLowBody`).replace(`{name}`,st.name).replace(`{balance}`,K(st.cny)).replace(`{days}`,st.days===void 0?`—`:String(st.days));Tr(`balance:${L}`,()=>{new Notification(F(`balance`),{body:e})})},[st,at,L,s,F]);let ct=(0,d.useMemo)(()=>{let e=L.slice(0,7),t=new Map;for(let[n,r]of Object.entries(P.byDayModels??{}))if(n.startsWith(e))for(let[e,n]of Object.entries(r)){if(n.cost<=0)continue;let r=Mt(e).provider,i=P.byModel?.[e]?.plan===!0,a=t.get(r)??{cost:0,plan:i};a.cost+=n.cost,i||(a.plan=!1),t.set(r,a)}let n,r;for(let e of t){let t=e[1].plan?r:n;(t===void 0||e[1].cost>t[1].cost)&&(e[1].plan?r=e:n=e)}let i=e=>{let t=p.find(t=>$(t.provider)===$(e));if(t===void 0||t.totalBalance===void 0){if(e===`Custom`){let e=p.filter(e=>e.totalBalance!==void 0&&e.error===void 0),t=e[0];return t!==void 0&&e.length===1?i(t.provider):void 0}return{text:t?.error===`unauthorized`?F(`balanceUnauthorized`):t?.error===`unreachable`||t?.error===`invalid`?F(`balanceUnreachable`):F(`balanceUnconfigured`),low:!1}}let n=t.currency===`USD`?`$${t.totalBalance.toFixed(2)}`:K(t.totalBalance),r=$e().rate;return{text:n,low:(t.currency===`USD`?t.totalBalance*r:t.totalBalance)<ot}},a=e=>{let t=v.find(t=>t.displayName===e||sr(t.provider)===e);if(t===void 0||t.windows.length===0)return{text:F(`subscriptionNoApi`),low:!1};let n=t.windows.reduce((e,t)=>Math.min(e,t.remainingPercent),100);return{text:n<=0?F(`subscriptionExhausted`):F(`subscriptionRemaining`).replace(`{pct}`,String(n)),low:n<20}},o=n===void 0?void 0:i(n[0]);return{direct:n===void 0||o===void 0?void 0:{name:n[0],...o},sub:r===void 0?void 0:{name:r[0],...a(r[0])}}},[P.byDayModels,P.byModel,P.lowBalanceThreshold,p,v,L,F]),lt=(0,d.useMemo)(()=>{let e=P.total;return{input:e.input,output:e.output,cacheRead:e.cacheHit,cacheMiss:e.cacheMiss,calls:e.calls}},[P]);(0,d.useEffect)(()=>{r({todayCost:Ie,monthCost:R})},[Ie,R,r]),(0,d.useEffect)(()=>i(Me),[i,Me]);let dt=(0,d.useMemo)(()=>c.byTurn??[],[c.byTurn]);return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(ei,{...e,t:F,currency:w,onOpen:Me,monthCost:R,todayCost:Ie,weekCost:Le,days:Re,vendorStatus:ct,dash:lt,cardPrefs:_e,monthTokens:ze,todayTokens:Be,weekTokens:Ve,floatPrefs:ie,subscriptions:v,budgetPressure:rt}),Oe&&(0,m.jsx)(ii,{stats:P,t:F,onClose:Ae,userPrices:be,onUserPrices:Se,health:u,balances:p,...g===void 0?{}:{reconcile:g},quotas:v,relayQuotas:S,currency:w,onCurrency:re,language:D,onLanguage:k,turns:dt,renderSlot:a,budgetEnabled:z,budgetAmount:W,onToggleBudget:it,onBudgetAmount:s.setAmount,peakConfig:Ge,onPeakConfig:Qe,onPreviewPeak:nt,floatPrefs:ie,onFloatPrefs:se,cardPrefs:_e,onCardPrefs:ye,sitePrefs:ce,onSitePrefs:pe,liveCostPrefs:me,onLiveCostPrefs:ge,quotasStale:b}),(V!==null||qe!==null)&&(0,m.jsx)(Xn,{hit:V??qe,config:Ge,t:F,onDismiss:()=>{H(null),Je(null)}})]})}function ci(e,t){return t===void 0||e?.bySession===void 0?0:e.bySession.find(e=>e.id===t)?.cost??0}function li(e,t){if(t===void 0||e?.byTurn===void 0)return 0;let n=0,r=-1;for(let i of e.byTurn)i.sessionId===t&&(r===-1||i.turn>r)&&(r=i.turn,n=i.cost);return n}function ui(e,t=20){let n=[];for(let r of e)if(r.status===`ok`)for(let e of r.windows)e.remainingPercent>t||n.push({name:r.displayName,kind:e.kind,pct:e.remainingPercent});return n.sort((e,t)=>e.pct-t.pct).slice(0,3)}function di(e,t){if(t===void 0||e?.byTurn===void 0)return;let n=-1,r;for(let i of e.byTurn)i.sessionId===t&&(n===-1||i.turn>n)&&(n=i.turn,r=i.model);return r}async function fi(){try{let e=await fetch(`/api/billing/usage-stats`);if(!e.ok)return null;let t=await e.text(),n=JSON.parse(t);if(typeof n!=`object`||!n)return null;let r=n;return{...Array.isArray(r.bySession)?{bySession:r.bySession}:{},...Array.isArray(r.byTurn)?{byTurn:r.byTurn}:{}}}catch{return null}}async function pi(){try{let e=await fetch(`/api/billing/subscriptions`);if(!e.ok)return[];let t=JSON.parse(await e.text());if(typeof t!=`object`||!t||!(`quotas`in t))return[];let n=t.quotas;return Array.isArray(n)?n:[]}catch{return[]}}function mi(e){switch(e){case`session`:return`subscriptionSession`;case`weekly`:return`subscriptionWeekly`;case`monthly`:return`subscriptionMonthly`;default:return`subscriptionBilling`}}function hi({hasBandPlan:e}){let[t,n]=(0,d.useState)(()=>he()),[r,i]=(0,d.useState)(()=>Date.now());if((0,d.useEffect)(()=>{let e=()=>{n(he())};window.addEventListener(me,e),window.addEventListener(`storage`,e);let t=setInterval(()=>{i(Date.now())},3e4);return()=>{window.removeEventListener(me,e),window.removeEventListener(`storage`,e),clearInterval(t)}},[]),t.length===0)return null;let a=qn().leadMin*6e4,o=t.map(t=>({key:t,state:Nn(dt(r,ut(t,e)),a)})).filter(e=>e.state!==null);return o.length===0?null:(0,m.jsx)(`span`,{className:I.bandDots,"data-testid":`billing-pinned-dots`,children:o.map(e=>(0,m.jsx)(`span`,{className:y(I.bandDot,I.bandDotOn,I[e.state]),role:`img`,"aria-label":e.key,title:e.key},e.key))})}function gi(){let[e,t]=(0,d.useState)(()=>de());return(0,d.useEffect)(()=>{let e=()=>{t(de())};return window.addEventListener(ue,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(ue,e),window.removeEventListener(`storage`,e)}},[]),e}function _i(){let[e,t]=(0,d.useState)(()=>le().show),[n,r]=(0,d.useState)(()=>le().position);return(0,d.useEffect)(()=>{let e=()=>{t(le().show),r(le().position)};return window.addEventListener(j,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(j,e),window.removeEventListener(`storage`,e)}},[]),{visible:e,position:n}}function vi(e,t){let[n,r]=(0,d.useState)(null),[i,a]=(0,d.useState)([]),[o,s]=(0,d.useState)(()=>Date.now()),[c,l]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{l(!document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[]),(0,d.useEffect)(()=>{if(!c||!t)return;let e=!1,n=()=>{fi().then(t=>{!e&&t!==null&&r(t)}),pi().then(t=>{e||a(t)}),e||s(Date.now())};n();let i=setInterval(n,3e4);return()=>{e=!0,clearInterval(i)}},[e,c,t]);let u=(0,d.useMemo)(()=>ci(n,e),[n,e]),f=(0,d.useMemo)(()=>li(n,e),[n,e]),p=(0,d.useMemo)(()=>ui(i),[i]),m=(0,d.useMemo)(()=>ut(di(n,e),i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)),[n,e,i]);return{sessionCost:u,turnCost:f,tier:(0,d.useMemo)(()=>dt(o,m),[o,m]),chips:p,hasBandPlan:i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)}}function yi({sessionId:e,t}){let{visible:n,position:r}=_i(),{sessionCost:i,turnCost:a,tier:o,chips:s,hasBandPlan:c}=vi(e,n&&r!==`toolbar`),l=gi(),u=e=>K(Bt(e,l),l),d=i>0||a>0,f=o?.tier===`peak`;return!n||r===`toolbar`?null:(0,m.jsxs)(`span`,{className:r===`above`?y(I.feeBar,I.feeBarAbove):I.feeBar,"data-testid":`billing-live-cost-bar`,children:[(0,m.jsx)(hi,{hasBandPlan:c}),o!==null&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:f?I.feeChipPrimary:I.feeChipOff,"data-testid":`billing-live-tier`,children:t(f?`tierPeak`:`tierOff`)}),(0,m.jsx)(`span`,{className:I.feeCount,children:pt(o.nextSwitchInMs)}),(0,m.jsx)(`span`,{className:I.feeSuffix,children:t(f?`tierToOff`:`tierToPeak`)})]}),d&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:I.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:I.feeItem,"data-testid":`billing-live-turn`,children:[t(`liveTurn`),` `,(0,m.jsx)(`span`,{className:I.feeNum,children:u(a)})]}),(0,m.jsx)(`span`,{className:I.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:I.feeItem,"data-testid":`billing-live-session`,children:[t(`liveSession`),` `,(0,m.jsx)(`span`,{className:I.feeNum,children:u(i)})]})]}),s.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:e.pct<=10?I.feeChipError:I.feeChipAlert,"data-testid":`billing-live-quota`,children:[e.name,` `,t(mi(e.kind)),` `,e.pct,`%`]})]},`${e.name}:${e.kind}`))]})}function bi({sessionId:e,t}){let n=gi(),r=e=>K(Bt(e,n),n),{visible:i,position:a}=_i(),{sessionCost:o,turnCost:s,tier:c,chips:l,hasBandPlan:u}=vi(e,i&&a===`toolbar`);if(!i||a!==`toolbar`)return null;let d=c?.tier===`peak`,f=l.reduce((e,t)=>Math.min(e,t.pct),100),h=f<=10?I.feeInlineError:f<=20?I.feeInlineAlert:I.feeInline,g=[...c===null?[]:[`${pt(c.nextSwitchInMs)} ${t(d?`tierToOff`:`tierToPeak`)}`],`${t(`liveTurn`)} ${r(s)}`,`${t(`liveSession`)} ${r(o)}`,...l.map(e=>`${e.name} ${t(mi(e.kind))} ${e.pct}%`)].join(` · `);return(0,m.jsx)(p.Tooltip,{label:g,side:`top`,delayMs:500,children:(0,m.jsxs)(`span`,{className:h,"data-testid":`billing-live-cost-chip`,role:`note`,"aria-label":g,children:[(0,m.jsx)(hi,{hasBandPlan:u}),c!==null&&(0,m.jsx)(`span`,{className:d?I.feeChipPrimary:I.feeChipOff,"data-testid":`billing-live-tier`,children:t(d?`tierPeak`:`tierOff`)}),o>0&&(0,m.jsx)(`span`,{className:I.feeInlineNum,children:r(o)})]})})}function xi(){let e,t,n=new Set;return{readCosts:()=>e,subscribeCosts:t=>(t(e),n.add(t),()=>{n.delete(t)}),openDashboard:()=>{t?.()},publishCosts:t=>{e=t;for(let e of n)try{e(t)}catch{}},registerOpen:e=>(t=e,()=>{t===e&&(t=void 0)})}}function Si(){return(0,h.defineStore)({init:()=>({enabled:!1,amount:0,tierAlertDays:{},lastBalanceAlertDay:``,lastTierSwitchAt:0}),persist:`dsh.ui-usage-billing.budget`,actions:{setEnabled:(e,t)=>{e.enabled=t},setAmount:(e,t)=>{e.amount=Number.isFinite(t)&&t>0?t:0},markTierAlerted:(e,t,n)=>{e.tierAlertDays??={};for(let r of t)e.tierAlertDays[String(r)]=n},markBalanceAlerted:(e,t)=>{e.lastBalanceAlertDay=t},markTierSwitchAlerted:(e,t)=>{e.lastTierSwitchAt=t}}})}let Ci={enabled:!1,timeout:0};function wi(){try{let e=localStorage.getItem(`dsh-billing-completion-notify-v1`);if(e===null)return{...Ci};let t=JSON.parse(e);return{enabled:t.enabled===!0,timeout:typeof t.timeout==`number`?t.timeout:0}}catch{return{...Ci}}}function Ti(e){return e.completed===!0||e.running===!1}function Ei(e,t){let n=new Set,r=new Set,i,a=e.getSnapshot();for(let e of a.ids){let t=a.byId[e];t!==void 0&&(r.add(String(e)),Ti(t)&&n.add(String(e)))}let o=e=>{let{enabled:n,timeout:r}=t();if(n&&!(typeof Notification>`u`)&&Notification.permission===`granted`)try{let t=new Notification(e,{body:e,tag:`dsh-billing-completion`,requireInteraction:r===0});r>0&&(i!==void 0&&clearTimeout(i),i=setTimeout(()=>t.close(),r*1e3))}catch{}},s=e.subscribe(()=>{let t=e.getSnapshot(),i=[];for(let e of t.ids){let a=t.byId[e];if(a===void 0)continue;let o=String(e),s=Ti(a),c=!r.has(o);c&&r.add(o),s&&!c&&!n.has(o)&&i.push(a.title??a.id??o),s?n.add(o):n.delete(o)}if(i.length>0){let e=i.length===1?i[0]:`${i.length} 个会话已完成`;e!==void 0&&o(e)}});return()=>{s(),i!==void 0&&clearTimeout(i)}}let Di=[`slots`,`locale`,`remote`,`sessions`];function Oi(e){let t=xi();e.provide(`billingMetrics`,t);let n=Si();e.effect(()=>e.locale.register(Ne,{zh:Pe,en:Fe}),`ui-usage-billing: dictionaries`),e.slots.inject(`sidebar.footer.action`,()=>e.slots.register({name:`sidebar.footer.action`,id:`usage-billing`,order:-10,locale:Ne,children:{"billing.dashboard.decor":{kind:`list`,scope:`root`}},store:n,inject:()=>({checkModels:async()=>{try{let[t,n]=await Promise.all([e.remote.llm.listProviders(),e.remote.llm.listConfigurableProviders()]);if(!t.ok||!n.ok)return{checked:!0,available:!1,models:0,failures:0,okProviders:[],badProviders:[]};let r=new Map(n.value.map(e=>[e.provider,e])),i=await Promise.all(t.value.map(async t=>{let n=r.get(t.id);if(n===void 0)return{provider:t,models:[]};let i=await e.remote.llm.discoverModels(n.settingsNs,{provider:t.id});return i.ok?{provider:t,models:i.value}:{provider:t,failed:!0}})),a=[],o=[],s=[],c=0;for(let e of i){if(`failed`in e){s.push(e.provider.name);continue}o.push(e.provider.name),c+=e.models.length;for(let t of e.models)a.push({id:t.id,...typeof t.name==`string`&&t.name!==``?{name:t.name}:{},provider:e.provider.name})}return{checked:!0,available:o.length>0,models:c,failures:s.length,okProviders:o,badProviders:s,catalog:a}}catch{return{checked:!1,available:!1,models:0,failures:0,okProviders:[],badProviders:[]}}},publishCosts:e=>{t.publishCosts(e)},registerOpen:e=>t.registerOpen(e)})},si)),e.slots.inject(`conversation.composer.dock`,()=>e.slots.register({name:`conversation.composer.dock`,id:`usage-billing-cost`,order:0,locale:Ne,inject:e=>({sessionId:_(e)})},yi)),e.slots.inject(`conversation.input.right`,()=>e.slots.register({name:`conversation.input.right`,id:`usage-billing-cost-chip`,order:0,locale:Ne,inject:e=>({sessionId:_(e)})},bi)),e.effect(()=>Ei(e.sessions.list,wi),`ui-usage-billing: completion notifier`)}return n.UsageBilling=si,n.apply=Oi,n.inject=Di,t.exports}});
|
|
5
|
+
`)}let Z={top:18,right:40,bottom:26,left:46};function on(e){let[,t,n]=e.split(`-`);return`${Number(t)}/${Number(n)}`}function sn(e,t){let n=[];for(let r=0;r<e;r+=t)n.push(r);return e>0&&n[n.length-1]!==e-1&&n.push(e-1),n}let cn={key:`__total__`,name:``,color:``};function ln({data:e,models:t=[],currency:n=`cny`,metric:r=`cost`,t:i}){let a=i??(e=>Pe[e]),[o,s]=(0,d.useState)(null),c=e=>K(Bt(e,n),n),l=e=>r===`tokens`?Qt(e):c(e),u=e=>r===`tokens`?e.tokens??0:e.cost,f=(0,d.useMemo)(()=>{let n=e.length;if(n===0)return null;let i=680-Z.left-Z.right,a=220-Z.top-Z.bottom,o=e=>n===1?Z.left+i/2:Z.left+i*e/(n-1),s=Math.max(...r===`tokens`?e.map(e=>e.tokens??0):e.map(e=>Math.max(e.cost,Object.values(e.byModel??{}).reduce((e,t)=>e+t,0))),1e-4),c=e=>Z.top+a-e/s*a,l=Math.max(...e.map(e=>e.calls),1),d=e=>Z.top+a-e/l*a,f=i/n,p=Math.min(18,f*.6);return{n,plotW:i,plotH:a,inner:o,yCost:c,yCalls:d,barW:p,bars:e.flatMap((e,n)=>{let i=o(n)-p/2;if(t.length===0||r===`tokens`)return[{date:e.date,model:cn,x:i,base:0,value:u(e),topRounded:!0}];let a=null;for(let n of t)(e.byModel?.[n.key]??0)>0&&(a=n.key);let s=0;return t.map(t=>{let n=e.byModel?.[t.key]??0,r={date:e.date,model:t,x:i,base:s,value:n,topRounded:t.key===a};return s+=n,r})}),costTicks:[0,.25,.5,.75,1].map(e=>s*e).reverse(),callsTicks:[0,.25,.5,.75,1].map(e=>l*e).reverse(),linePath:e.map((e,t)=>{let n=d(e.calls);return`${t===0?`M`:`L`}${o(t)} ${n}`}).join(` `)}},[e,t,r]);if(f===null)return(0,m.jsx)(`div`,{className:I.chartEmpty,children:a(`trendEmpty`)});let{n:p,plotW:h,plotH:g,inner:_,yCost:v,yCalls:y,barW:b,bars:x,costTicks:S,callsTicks:C,linePath:w}=f,T=o===null?void 0:e[o],ee=sn(p,Math.max(1,Math.ceil(p/8)));return(0,m.jsxs)(`div`,{className:I.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 220`,className:I.chartSvg,role:`img`,"aria-label":`Daily cost by model and total calls`,onMouseLeave:()=>{s(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect(),n=((e.clientX-t.left)/t.width*680-Z.left)/h,r=Math.round(n*(p-1));s(Math.min(Math.max(r,0),p-1))},children:[S.map((e,t)=>{let n=v(e);return(0,m.jsxs)(`g`,{children:[(0,m.jsx)(`line`,{x1:Z.left,x2:680-Z.right,y1:n,y2:n,className:I.chartGrid}),(0,m.jsx)(`text`,{x:Z.left-8,y:n+3,textAnchor:`end`,className:I.chartAxisLabel,children:l(e)})]},`cost-${t}`)}),x.map(t=>{if(t.value>0)return(0,m.jsx)(`rect`,{x:t.x,y:v(t.base+t.value),width:b,height:v(t.base)-v(t.base+t.value),rx:t.topRounded?2:0,className:t.model.color===``?I.chartBar:I.chartStack,style:t.model.color===``?void 0:{fill:t.model.color}},`${t.date}-${t.model.key}`);let n=e.find(e=>e.date===t.date);return n!==void 0&&n.calls>0&&t.base===0?(0,m.jsx)(`rect`,{x:t.x,y:v(0)-1,width:b,height:1,rx:0,className:I.chartBarPlaceholder},`${t.date}-${t.model.key}-placeholder`):null}),(0,m.jsx)(`path`,{d:w,fill:`none`,className:I.chartLine}),C.map((e,t)=>{let n=y(e);return(0,m.jsx)(`text`,{x:680-Z.right+8,y:n+3,textAnchor:`start`,className:I.chartAxisLabel,children:Qt(e)},`calls-${t}`)}),ee.map(t=>{let n=e[t];return n===void 0?null:(0,m.jsx)(`text`,{x:_(t),y:214,textAnchor:`middle`,className:I.chartAxisLabel,children:on(n.date)},n.date)}),o!==null&&(0,m.jsx)(`line`,{x1:_(o),x2:_(o),y1:Z.top,y2:Z.top+g,className:I.chartCrosshair})]}),T!==void 0&&o!==null&&(0,m.jsxs)(`div`,{className:I.chartTooltip,style:{left:`${_(o)/680*100}%`,top:`${v(T.cost)/220*100}%`},children:[(0,m.jsx)(`div`,{className:I.chartTooltipDate,children:T.date}),r!==`tokens`&&t.filter(e=>(T.byModel?.[e.key]??0)>0).map(e=>(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name,` `,(0,m.jsx)(`strong`,{children:c(T.byModel?.[e.key]??0)})]},e.key)),(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartLegendBar}),a(`trendTotal`),` `,(0,m.jsx)(`strong`,{children:r===`tokens`?Qt(T.tokens??0):c(T.cost)})]}),(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartLegendLine}),a(`calls`),` `,(0,m.jsx)(`strong`,{children:T.calls.toLocaleString()})]})]}),t.length>0&&r!==`tokens`&&(0,m.jsxs)(`div`,{className:I.chartLegend,children:[t.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name]},e.key)),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.chartLegendLine}),a(`calls`)]})]})]})}let Q={top:14,right:42,bottom:22,left:46};function un(e){return e.slice(5,13).replace(`T`,` `)}function dn(e){return String(e>=100?Math.round(e):Number(e.toFixed(1)))}function fn(e){return e<1e4?`${Math.round(e)} ms`:e<6e4?`${(e/1e3).toFixed(1)} s`:`${(e/6e4).toFixed(1)} min`}function pn(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function mn(e,t,n){return t===`ttft`?`${Math.round(e)} ms`:`${e.toFixed(1)} ${n(`perfTpsUnit`)}`}function hn({perf:e,models:t,t:n}){let[r,i]=(0,d.useState)(()=>Ae()),[a,o]=(0,d.useState)(null),s=e=>{i(e),je(e)},c=e=>t.find(t=>t.key===e)?.color??`#8b95a3`,l=(0,d.useMemo)(()=>e===void 0?[]:Object.entries(e.byModel).map(([e,n])=>({key:e,name:t.find(t=>t.key===e)?.name??e,color:c(e),samples:n.samples,ttftAvg:n.ttftAvg,ttftP50:n.ttftP50,ttftP90:n.ttftP90,...n.ttftMax===void 0?{}:{ttftMax:n.ttftMax},...n.ttftSpikes===void 0?{}:{ttftSpikes:n.ttftSpikes},...n.tpsAvg===void 0?{}:{tpsAvg:n.tpsAvg},latencyAvg:n.latencyAvg,estimatedSamples:n.estimatedSamples})).sort((e,t)=>t.samples-e.samples||t.ttftP90-e.ttftP90),[e,t]),u=(0,d.useMemo)(()=>{if(e===void 0)return[];if(r.models!==void 0){let t=new Set(Object.keys(e.byModel));return r.models.filter(e=>t.has(e))}return l.slice(0,5).map(e=>e.key)},[e,l,r.models]),f=(0,d.useMemo)(()=>{if(e===void 0)return null;let t=Object.keys(e.byHourModel).sort().slice(-48);if(t.length===0)return null;let n=t.length,i=680-Q.left-Q.right,a=180-Q.top-Q.bottom,o=e=>n===1?Q.left+i/2:Q.left+i*e/(n-1),s=new Set(u),c=e=>r.metric===`ttft`?e?.ttftAvg:e?.tpsAvg,d=[],f=0;for(let r of l){if(!s.has(r.key))continue;let i=[];for(let a=0;a<n;a++){let n=t[a];if(n===void 0)continue;let s=c(e.byHourModel[n]?.[r.key]);s===void 0||!Number.isFinite(s)||(i.push({i:a,x:o(a),y:0,v:s}),s>f&&(f=s))}d.push({key:r.key,name:r.name,color:r.color,segments:[],points:i})}let p=d.reduce((e,t)=>e+t.points.length,0);f=Math.max(f,1);let m=e=>Q.top+a-e/f*a;for(let e of d){let t=``,n=-2;for(let r of e.points)r.y=m(r.v),t!==``&&r.i!==n+1&&(e.segments.push(t),t=``),t+=`${t===``?`M`:`L`}${r.x} ${r.y} `,n=r.i;t!==``&&e.segments.push(t)}let h=Math.max(1,Math.ceil(n/8)),g=[];for(let e=0;e<n;e+=h)g.push(e);return g[g.length-1]!==n-1&&g.push(n-1),{hourKeys:t,n,plotW:i,plotH:a,inner:o,yOf:m,series:d,ticks:[0,.5,1].map(e=>f*e).reverse(),xTicks:g,totalPoints:p}},[e,l,u,r.metric]);if(e===void 0||l.length===0)return(0,m.jsx)(`div`,{className:I.chartEmpty,"data-testid":`billing-perf-empty`,children:n(`perfEmpty`)});let p=e=>{let t=u.includes(e)?u.filter(t=>t!==e):[...u,e];s({metric:r.metric,models:t})},h=e=>{s({metric:e,...r.models===void 0?{}:{models:r.models}})},g=a===null||f===null?[]:f.series.flatMap(e=>{let t=e.points.find(e=>e.i===a);return t===void 0?[]:[{key:e.key,name:e.name,color:e.color,v:t.v}]});return(0,m.jsxs)(`div`,{"data-testid":`billing-perf-panel`,children:[(0,m.jsx)(`div`,{className:I.tableScroll,"data-testid":`billing-perf-table`,children:(0,m.jsxs)(`table`,{className:I.modelTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`model`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfSamples`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfTtft`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfP50`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfP90`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfMax`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfTps`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfLatency`)}),(0,m.jsx)(`th`,{className:I.numCol,children:n(`perfEstimated`)})]})}),(0,m.jsx)(`tbody`,{children:l.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:(0,m.jsxs)(`span`,{className:I.modelCell,children:[(0,m.jsx)(`span`,{className:I.modelDot,style:{background:e.color}}),(0,m.jsx)(`span`,{className:I.modelName,children:e.name})]})}),(0,m.jsx)(`td`,{className:I.numCol,children:e.samples.toLocaleString()}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.ttftAvg)}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.ttftP50)}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.ttftP90)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.ttftMax===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):(0,m.jsxs)(`span`,{children:[fn(e.ttftMax),e.ttftSpikes!==void 0&&e.ttftSpikes>0?` (${e.ttftSpikes}↑)`:``]})}),(0,m.jsx)(`td`,{className:I.numCol,children:e.tpsAvg===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):pn(e.tpsAvg)}),(0,m.jsx)(`td`,{className:I.numCol,children:fn(e.latencyAvg)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.estimatedSamples>0?e.estimatedSamples:(0,m.jsx)(`span`,{className:I.na,children:`—`})})]},e.key))})]})}),f!==null&&(0,m.jsxs)(`div`,{"data-testid":`billing-perf-hour`,children:[(0,m.jsx)(`div`,{className:I.perfBar,children:(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":n(`perfTitle`),children:[`ttft`,`tps`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,r.metric===e&&I.rangeButtonActive),"aria-pressed":r.metric===e,"data-testid":`billing-perf-tab-${e}`,onClick:()=>{h(e)},children:e===`ttft`?`${n(`perfTtft`)} (ms)`:`${n(`perfTps`)} (${n(`perfTpsUnit`)})`},e))})}),(0,m.jsxs)(`div`,{className:I.perfChips,role:`group`,"aria-label":n(`model`),children:[(0,m.jsx)(`button`,{type:`button`,className:I.perfChip,"data-testid":`billing-perf-chip-all`,onClick:()=>{s({metric:r.metric,models:l.map(e=>e.key)})},children:n(`perfAll`)}),l.map(e=>{let t=u.includes(e.key);return(0,m.jsxs)(`button`,{type:`button`,className:y(I.perfChip,!t&&I.perfChipOff),style:t?{color:e.color,borderColor:`color-mix(in srgb, ${e.color} 45%, transparent)`}:void 0,"aria-pressed":t,"data-testid":`billing-perf-chip-${e.key}`,onClick:()=>{p(e.key)},children:[(0,m.jsx)(`span`,{className:I.perfChipDot,style:{background:t?e.color:`var(--dsw-alias-label-dimmed)`}}),e.name]},e.key)})]}),f.totalPoints>0?(0,m.jsxs)(`div`,{className:I.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 180`,className:I.chartSvg,role:`img`,"aria-label":`Hourly perf comparison by model`,onMouseLeave:()=>{o(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect(),n=((e.clientX-t.left)/t.width*680-Q.left)/f.plotW,r=Math.round(n*(f.n-1));o(Math.min(Math.max(r,0),f.n-1))},children:[f.ticks.map((e,t)=>{let n=f.yOf(e);return(0,m.jsxs)(`g`,{children:[(0,m.jsx)(`line`,{x1:Q.left,x2:680-Q.right,y1:n,y2:n,className:I.chartGrid}),(0,m.jsx)(`text`,{x:Q.left-8,y:n+3,textAnchor:`end`,className:I.chartAxisLabel,children:dn(e)})]},`tick-${t}`)}),f.series.map(e=>e.segments.map((t,n)=>(0,m.jsx)(`path`,{d:t,fill:`none`,className:I.chartLine,style:{stroke:e.color}},`${e.key}-${n}`))),f.xTicks.map(e=>{let t=f.hourKeys[e];return t===void 0?null:(0,m.jsx)(`text`,{x:f.inner(e),y:174,textAnchor:`middle`,className:I.chartAxisLabel,children:un(t)},t)}),a!==null&&(0,m.jsx)(`line`,{x1:f.inner(a),x2:f.inner(a),y1:Q.top,y2:Q.top+f.plotH,className:I.chartCrosshair}),a!==null&&f.series.map(e=>{let t=e.points.find(e=>e.i===a);return t===void 0?null:(0,m.jsx)(`circle`,{cx:t.x,cy:t.y,r:3.5,fill:e.color,className:I.chartHoverDot},`${e.key}-dot`)})]}),a!==null&&g.length>0&&(0,m.jsxs)(`div`,{className:I.chartTooltip,"data-testid":`billing-perf-tooltip`,style:{left:`${f.inner(a)/680*100}%`,top:`${(Q.top+f.plotH/2)/180*100}%`},children:[(0,m.jsx)(`div`,{className:I.chartTooltipDate,children:un(f.hourKeys[a]??``)}),g.map(e=>(0,m.jsxs)(`div`,{className:I.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:I.chartTooltipSwatch,style:{background:e.color}}),e.name,` `,(0,m.jsx)(`strong`,{children:mn(e.v,r.metric,n)})]},e.key))]})]}):(0,m.jsx)(`div`,{className:I.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]}),f===null&&(0,m.jsx)(`div`,{className:I.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]})}let gn=`@kenz1117/dsh-ui-usage-billing`,_n=`kenz1117`;function vn({t:e,version:t}){return(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-plugin-info`,children:[(0,m.jsxs)(`div`,{className:I.plgHead,children:[(0,m.jsx)(`span`,{className:I.plgIcon,"aria-hidden":`true`,children:(0,m.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,m.jsx)(`path`,{d:`M10 3a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v2a2 2 0 0 0 4 0V4a1 1 0 0 1 1-1h1a1 1 0 0 1 1 1v1a2 2 0 0 0 4 0 1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-1a2 2 0 0 0 0 4h1a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-1a2 2 0 0 0-4 0v1a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1v-2a2 2 0 0 0-4 0v1a1 1 0 0 1-1 1h-1a1 1 0 0 1-1-1v-1a2 2 0 0 0-4 0 1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-2a1 1 0 0 1 1-1h1a2 2 0 0 0 0-4H3a1 1 0 0 1-1-1v-2a1 1 0 0 1 1-1h1a2 2 0 0 0 4 0z`})})}),(0,m.jsxs)(`div`,{className:I.plgTitle,children:[(0,m.jsxs)(`div`,{className:I.plgNameRow,children:[(0,m.jsx)(`h3`,{className:I.plgName,children:gn}),(0,m.jsx)(`span`,{className:I.plgTag,children:t===void 0?`—`:`v${t}`})]}),(0,m.jsx)(`p`,{className:I.plgDesc,children:`Usage billing dashboard for DeepSeek Harness`})]})]}),(0,m.jsxs)(`div`,{className:I.plgGrid,children:[(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginAuthor`)}),(0,m.jsxs)(`a`,{className:I.plgLink,href:`https://github.com/${_n}`,target:`_blank`,rel:`noreferrer`,children:[`KenZ`,` (`,_n,`)`]})]}),(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginRepository`)}),(0,m.jsx)(`a`,{className:I.plgLink,href:`https://github.com/kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:`GitHub`})]}),(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginNpm`)}),(0,m.jsx)(`a`,{className:I.plgLink,href:`https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:gn})]}),(0,m.jsxs)(`div`,{className:I.plgItem,children:[(0,m.jsx)(`span`,{className:I.plgLabel,children:e(`pluginLicense`)}),(0,m.jsx)(`span`,{className:I.plgVal,children:`MIT`})]})]})]})}function yn(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}`}function bn(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function xn(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${String(t%60).padStart(2,`0`)}s`}function Sn({rounds:e,flags:t,currency:n,t:r}){let i=(0,d.useMemo)(()=>e.slice(-40),[e]),a=(0,d.useMemo)(()=>new Set(t.map(e=>`${e.sessionId}:${e.turn}`)),[t]),o=(0,d.useMemo)(()=>Math.max(1e-4,...i.map(e=>e.cost)),[i]);if(i.length===0)return(0,m.jsxs)(`div`,{className:I.roundsEmpty,children:[r(`model`),` —`]});let s=e=>K(Bt(e,n),n);return(0,m.jsxs)(`div`,{className:I.rounds,children:[(0,m.jsx)(`div`,{className:I.roundsBars,role:`img`,"aria-label":`cost per turn`,children:i.map(e=>{let t=a.has(`${e.sessionId}:${e.turn}`),n=Math.max(1,e.cost/o*100),i=U(e.startedAt)===`peak`;return(0,m.jsxs)(`div`,{className:y(I.roundsBarCol,i?I.roundsBarColPeak:I.roundsBarColOff),children:[(0,m.jsx)(`span`,{className:I.roundsBarLabel,style:{bottom:`${n}%`},children:s(e.cost)}),(0,m.jsx)(`div`,{className:I.roundsBarWrap,children:(0,m.jsx)(`div`,{className:t?I.roundsBarFlagged:I.roundsBar,style:{height:`${n}%`},"data-testid":`round-bar`,title:`${r(`model`)} ${e.model} · ${s(e.cost)} · ${bn(e.startedAt)}${e.endedAt===void 0?``:` → ${yn(e.endedAt)} (${xn(e.endedAt-e.startedAt)})`}`,children:t&&(0,m.jsx)(`span`,{className:I.roundsFlagMark,"aria-hidden":`true`})})})]},`${e.sessionId}:${e.turn}`)})}),(0,m.jsxs)(`div`,{className:I.roundsAxis,children:[(0,m.jsxs)(`span`,{children:[r(`costAbbr`),` `,s(o)]}),(0,m.jsxs)(`span`,{children:[i.length,` `,r(`roundsUnit`)]})]})]})}let Cn=[`color-mix(in srgb, var(--ds-blue) 10%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 30%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 60%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 90%, var(--dsb-3))`,`var(--ds-blue)`],wn=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Tn=e=>q(e.getTime());function En(e,t){let n=new Map;for(let t of e)n.set(t.date,t.value);let r=0;for(let e of n.values())e>r&&(r=e);let i=t.getFullYear(),a=t.getMonth(),o=t.getDate(),s=new Date(i,a+1,0).getDate(),c=new Date(i,a,1).getDay(),l=c+s,u=Math.ceil(l/7),d=[];for(let e=0;e<u;e+=1){let t=[];for(let l=0;l<7;l+=1){let u=e*7+l-c+1;if(u<1){let e=new Date(i,a,u);t.push({date:Tn(e),dayNum:e.getDate(),value:0,level:0,placeholder:!0});continue}if(u>s){let e=new Date(i,a+1,u-s);t.push({date:Tn(e),dayNum:e.getDate(),value:0,level:0,placeholder:!0});continue}let d=new Date(i,a,u),f=Tn(d),p=n.get(f)??0,m=0;if(p>0&&r>0){let e=Math.ceil(p/r*4);m=Math.min(4,Math.max(1,e))}let h=u>o;t.push({date:f,dayNum:u,value:h?0:p,level:h?0:m,placeholder:h})}d.push(t)}return d}function Dn(e,t,n=52){let r=new Map;for(let t of e)r.set(t.date,t.value);let i=0;for(let e of r.values())e>i&&(i=e);let a=Tn(t),o=new Date(t);o.setHours(0,0,0,0),o.setDate(o.getDate()-o.getDay());let s=new Date(o);s.setDate(o.getDate()-(n-1)*7);let c=[];for(let e=0;e<n;e+=1){let t=[];for(let n=0;n<7;n+=1){let o=new Date(s);o.setDate(s.getDate()+e*7+n);let c=Tn(o),l=c>a,u=l?0:r.get(c)??0,d=0;if(!l&&u>0&&i>0){let e=Math.ceil(u/i*4);d=Math.min(4,Math.max(1,e))}t.push({date:c,dayNum:o.getDate(),value:u,level:d,placeholder:l})}c.push(t)}return c}function On({days:e,currency:t,now:n,t:r,range:i=`month`,unit:a=`cost`}){let[o,s]=(0,d.useState)(null),c=e=>K(Bt(e,t),t),l=e=>a===`tokens`?J(e):c(e),u=(0,d.useMemo)(()=>En(e,n??new Date),[e,n]);if(i!==`month`){let t=Dn(e,n??new Date,i===`half`?26:52),a=[],o=-1;return t.forEach((e,t)=>{let n=Number(e[0]?.date.slice(5,7)??0);n!==o&&(a.push({index:t,label:wn[n-1]??``}),o=n)}),(0,m.jsxs)(`div`,{className:I.heatmapYear+(i===`half`?` `+I.heatmapHalf:``),"data-testid":i===`half`?`heatmap-half`:`heatmap-year`,children:[(0,m.jsxs)(`div`,{className:I.heatmapYearBody,children:[(0,m.jsx)(`div`,{className:I.heatmapYearWeekdays,"aria-hidden":`true`,children:[{label:`Mon`,row:1},{label:`Wed`,row:3},{label:`Fri`,row:5}].map(e=>(0,m.jsx)(`span`,{className:I.heatmapYearWeekday,style:{gridRow:e.row},children:e.label},e.label))}),(0,m.jsxs)(`div`,{className:I.heatmapYearScroll,children:[(0,m.jsx)(`div`,{className:I.heatmapYearMonths,"aria-hidden":`true`,"data-testid":`heatmap-year-months`,children:a.map(e=>(0,m.jsx)(`span`,{className:I.heatmapYearMonth,style:{gridColumn:e.index+1},children:e.label},e.index))}),(0,m.jsx)(`div`,{className:I.heatmapYearGrid,role:`img`,"aria-label":`yearly cost heatmap`,"data-testid":`heatmap-year-grid`,children:t.flat().map(e=>(0,m.jsx)(`button`,{type:`button`,className:I.heatmapYearCell,"data-testid":`heatmap-year-cell`,"data-level":e.level,style:{background:Cn[e.level]},title:`${e.date} · ${l(e.value)}`,"aria-label":`${e.date}: ${l(e.value)}`,tabIndex:-1},e.date))})]})]}),(0,m.jsxs)(`div`,{className:I.heatmapFooter,children:[(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:I.heatmapLegend,children:Cn.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapMore`)})]})]})}return(0,m.jsxs)(`div`,{className:I.heatmap,children:[(0,m.jsx)(`div`,{className:I.heatmapGrid,role:`img`,"aria-label":`daily cost heatmap`,children:u.map(e=>e.map(e=>e.placeholder?(0,m.jsx)(`div`,{className:I.heatmapCellEmpty,children:e.dayNum},e.date):(0,m.jsx)(`button`,{type:`button`,className:I.heatmapCell,"data-testid":`heatmap-cell`,"data-level":e.level,style:{background:Cn[e.level]},title:`${e.date} · ${l(e.value)}`,"aria-label":`${e.date}: ${l(e.value)}`,onMouseEnter:()=>{s(e)},onMouseLeave:()=>{s(null)},onFocus:()=>{s(e)},onBlur:()=>{s(null)},children:e.dayNum},e.date)))}),(0,m.jsxs)(`div`,{className:I.heatmapFooter,children:[(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:I.heatmapLegend,children:Cn.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{className:I.heatmapLegendText,children:r(`heatmapMore`)}),o!==null&&(0,m.jsxs)(`span`,{className:I.heatmapHover,"data-testid":`heatmap-hover`,children:[o.date,` · `,l(o.value)]})]})]})}let kn={window:6,threshold:2,reasonFactor:1.8,reasonHitDropPp:15};function An(e){if(e.length===0)return null;let t=0;for(let n of e)t+=n;return t/e.length}function jn(e){let t=e.cacheHit+e.cacheMiss;return t<=0?null:e.cacheHit/t*100}function Mn(e,t){let n=t?.window??kn.window,r=t?.threshold??kn.threshold,i=t?.reasonFactor??kn.reasonFactor,a=t?.reasonHitDropPp??kn.reasonHitDropPp,o=[];if(n<=0||r<=0)return o;let s=[],c=[],l=[],u=[];for(let t of e){if(t.cost<=0)continue;let e=t.output,d=t.input,f=jn(t),p=An(s),m=[];if(p!==null&&p>0&&t.cost>p*r){let n=An(c),r=An(l),s=An(u);n!==null&&n>0&&e>n*i&&m.push(`output-growth`),r!==null&&r>0&&d>r*i&&m.push(`context-bloat`),s!==null&&f!==null&&f<s-a&&m.push(`cache-hit-drop`),o.push({sessionId:t.sessionId,turn:t.turn,cost:t.cost,reasons:m})}for(s.push(t.cost),c.push(e),l.push(d),f!==null&&u.push(f);s.length>n;)s.shift();for(;c.length>n;)c.shift();for(;l.length>n;)l.shift();for(;u.length>n;)u.shift()}return o}function Nn(e,t){return e==null?null:Number.isFinite(e.nextSwitchInMs)&&e.nextSwitchInMs<=t?`soon`:e.tier===`peak`?`peak`:`offPeak`}let Pn={显式缓存创建:`Explicit cache write`,显式缓存命中:`Explicit cache hit`,长期半价:`Half price`,与标准价一致:`Same as standard`,"限时 5 折":`Limited-time 50% off`};function Fn(e,t){return e===void 0||t!==`en`?e:Pn[e]??e}function In(e,t){let n=t.trim().toLowerCase();return n===``?e:e.filter(e=>e.key.toLowerCase().includes(n)||(e.name??``).toLowerCase().includes(n)||(e.provider??``).toLowerCase().includes(n))}let Ln={"智谱 AI":`Zhipu AI`,阿里通义:`Alibaba Qwen`,字节豆包:`ByteDance Doubao`,月之暗面:`Moonshot AI`,小米:`Xiaomi`,百度文心:`Baidu ERNIE`,腾讯混元:`Tencent Hunyuan`,零一万物:`01.AI`,阶跃星辰:`StepFun`,科大讯飞:`iFlytek Spark`,商汤:`SenseNova`,百川智能:`Baichuan`,"小米 Token Plan(海外)":`Xiaomi Token Plan (Global)`,"小米 Token Plan(国内)":`Xiaomi Token Plan (CN)`,"小米 Token Plan(新加坡)":`Xiaomi Token Plan (SG)`,"火山引擎 Token Plan":`Volcengine Token Plan`,"火山方舟 Token Plan":`Volcengine Ark Token Plan`,"豆包 Token Plan":`Doubao Token Plan`,"百度文心 Plan":`Baidu ERNIE Plan`,"MiniMax Token Plan(国内)":`MiniMax Token Plan (CN)`};function Rn(e,t){return t===`en`?Ln[e]??e:e}let zn={workbuddy:`WorkBuddy`,"workbuddy-ai":`WorkBuddy AI`},Bn={"https://tokenhub.tencentmaas.com":`腾讯云 TokenHub`,"https://api.lkeap.cloud.tencent.com":`腾讯云 Token Plan`,"https://api.deepseek.com":`DeepSeek 官方`},Vn={"腾讯云 TokenHub":`Tencent Cloud TokenHub`,"腾讯云 Token Plan":`Tencent Cloud Token Plan`,"DeepSeek 官方":`DeepSeek Official`};function Hn(e){try{return new URL(e).host}catch{return e}}function Un(e,t=`zh`){if(e.startsWith(`site:`)){let n=e.slice(5),r=Bn[n];return r===void 0?Hn(n):t===`en`?Vn[r]??r:r}if(e.startsWith(`direct:`)){let n=e.slice(7);if(/^deepseek(?:-[a-z0-9-]+)?$/i.test(n))return t===`en`?`DeepSeek Official`:`DeepSeek 官方`;let r=zn[n.trim().toLowerCase()];return r===void 0?`${t===`en`?`Direct`:`直连`} · ${n}`:`${t===`en`?`Direct`:`直连`} · ${r}`}}let Wn=[`直连 · `,`Direct · `];function Gn(e){for(let t of Wn)if(e.startsWith(t))return e.slice(t.length)}let Kn=`dsh-billing-peak-alert-v1`,qn={enabled:!1,leadMin:2,position:`bottom-right`,webNotify:!0,mode:`both`};function Jn(){try{let e=localStorage.getItem(Kn);if(e===null)return{...qn};let t=JSON.parse(e),n=t.mode===`peak`||t.mode===`offPeak`?t.mode:qn.mode,r=t.position===`center`?`center`:`bottom-right`;return{enabled:t.enabled===!0,leadMin:typeof t.leadMin==`number`&&Number.isFinite(t.leadMin)?Math.min(30,Math.max(1,Math.round(t.leadMin))):qn.leadMin,position:r,webNotify:t.webNotify!==!1,mode:n}}catch{return{...qn}}}function Yn(e){try{localStorage.setItem(Kn,JSON.stringify(e))}catch{}}function Xn(e,t,n,r){if(!t.enabled)return null;let i=ft(e,r,t.leadMin*6e4);return i===null||t.mode===`peak`&&i.entering!==`peak`||t.mode===`offPeak`&&i.entering!==`offPeak`||i.atMs===n?null:{...i,channel:r}}function Zn({hit:e,config:t,t:n,onDismiss:r}){let[i,a]=(0,d.useState)(()=>Date.now());if((0,d.useEffect)(()=>{let e=setInterval(()=>a(Date.now()),3e4);return()=>clearInterval(e)},[]),(0,d.useEffect)(()=>{i>=e.atMs&&r()},[i,e.atMs,r]),i>=e.atMs)return null;let o=Math.max(1,Math.round((e.atMs-i)/6e4)),s=e.entering,c=n(s===`peak`?`tierPeak`:`tierOff`),l=n(e.channel===`zhipu-coding-plan`?s===`peak`?`peakAlertDescPeakZhipu`:`peakAlertDescOffZhipu`:s===`peak`?`peakAlertDescPeak`:`peakAlertDescOff`),u=s===`peak`;return(0,m.jsxs)(`div`,{className:y(I.peakCard,u?I.peakCardPeak:I.peakCardOff,t.position===`center`?I.peakCardCenter:I.peakCardCorner),"data-testid":`billing-peak-alert`,role:`alert`,children:[(0,m.jsxs)(`div`,{className:I.peakHead,children:[(0,m.jsxs)(`span`,{className:y(I.peakTag,u?I.peakTagPrimary:I.peakTagSuccess),children:[(0,m.jsx)(`span`,{className:y(I.peakDot,u?I.peakDotPrimary:I.peakDotSuccess),"aria-hidden":`true`}),c]}),(0,m.jsx)(`button`,{type:`button`,className:I.peakClose,onClick:r,"aria-label":n(`close`),children:`×`})]}),(0,m.jsxs)(`div`,{className:y(I.peakCount,u?I.peakCountPrimary:I.peakCountSuccess),children:[o,`min`]}),(0,m.jsx)(`p`,{className:I.peakDesc,children:l})]})}let Qn=p,$n=Qn.IconChevronDownOutlineMedium??Qn.IconChevronDownOutline14,er=[{id:`overview`,labelKey:`tabOverview`},{id:`providers`,labelKey:`tabProviders`},{id:`token`,labelKey:`tabToken`},{id:`trends`,labelKey:`tabTrends`},{id:`pricing`,labelKey:`tabPricing`},{id:`settings`,labelKey:`tabSettings`}],tr=[50,80,100],nr={checked:!1,available:!1,models:0,failures:0,okProviders:[],badProviders:[]},rr={DeepSeek:[`deepseek`],"智谱 AI":[`zhipu`,`glm`,`z.ai`],阿里通义:[`qwen`,`tongyi`,`dashscope`,`aliyun`],字节豆包:[`doubao`,`volcengine`,`ark`],月之暗面:[`moonshot`,`kimi`],小米:[`xiaomi`,`mi`,`mimo`],MiniMax:[`minimax`],百度文心:[`ernie`,`wenxin`,`qianfan`,`baidu`],腾讯混元:[`hunyuan`,`tencent`],零一万物:[`01.ai`,`lingyi`,`yi`],阶跃星辰:[`step`,`stepfun`,`step-3.7`],科大讯飞:[`spark`,`xfyun`,`iflytek`],商汤:[`sensenova`,`sensetime`],百川智能:[`baichuan`],OpenAI:[`openai`],Google:[`google`,`gemini`],xAI:[`xai`,`grok`],Meta:[`meta`,`llama`],Anthropic:[`claude`,`anthropic`],"Mistral AI":[`mistral`,`ministral`,`devstral`],Cohere:[`cohere`,`command`],美团:[`longcat`,`meituan`],面壁智能:[`minicpm`,`modelbest`],小红书:[`dots`,`rednote`,`xiaohongshu`],云知声:[`unisound`,`u2`]};function $(e){return e.trim().toLowerCase().replace(/[\s_/-]+/g,``)}function ir(e,t){if(e.length===0||t.length===0)return!1;if(e===t)return!0;let[n,r]=e.length<=t.length?[e,t]:[t,e];return n.length>=3&&r.includes(n)}function ar(e,t){let n=$(e),r=$(t);if(ir(n,r))return!0;let i=rr[e];return i!==void 0&&i.some(e=>ir($(e),r))}function or(e){let t=e.trim().toLowerCase(),n=t.replace(/[\s_/-]+/g,``);if(n.length!==0){for(let[e,n]of Object.entries(rr))for(let r of n){let n=$(r);if(n.length!==0&&(t===n||t.startsWith(`${n}-`)||t.startsWith(`${n}/`)||t.startsWith(`${n}_`)||t.includes(`${n}-`)||t.includes(`${n}/`)||t.includes(`${n}_`)))return e}for(let[e,t]of Object.entries(rr))for(let r of t){let t=$(r);if(!(t.length<4)&&n.includes(t))return e}}}let sr={"kimi-coding":`月之暗面`,"zai-coding-cn":`智谱 AI`,"zai-coding":`智谱 AI`,"qwen-token-plan":`阿里通义`,"qwen-token-plan-cn":`阿里通义`,"xiaomi-token-plan-ams":`小米`,"xiaomi-token-plan-cn":`小米`,"xiaomi-token-plan-sgp":`小米`,"volcengine-token-plan":`字节豆包`,"ark-token-plan":`字节豆包`,"doubao-token-plan":`字节豆包`,ernie:`百度文心`,baidu:`百度文心`,wenxin:`百度文心`,minimax:`MiniMax`,"minimax-cn":`MiniMax`,"minimax-token-plan":`MiniMax`,"minimax-token-plan-cn":`MiniMax`,"hunyuan-token-plan":`腾讯混元`,"tencent-token-plan":`腾讯混元`,"hy-token-plan":`腾讯混元`,"xinghuo-token-plan":`讯飞星火`,"xfyun-coding":`讯飞星火`,"spark-coding":`讯飞星火`,"huawei-token-plan":`华为云`,"pangu-token-plan":`华为云`,"huawei-maas-token-plan":`华为云`,"volcengine-agent-plan":`字节豆包`,"ark-agent-plan":`字节豆包`,"baidu-token-plan":`百度文心`,"ernie-token-plan":`百度文心`,"wenxin-token-plan":`百度文心`,opencode:`OpenCode`,"opencode-go":`OpenCode`};function cr(e){let t=sr[e];return t===void 0?or(e)??e:t}let lr=`https://platform.kimi.com/console/pay`,ur=`https://open.bigmodel.cn/finance-center/finance/pay`,dr=`https://bailian.console.aliyun.com/`,fr=`https://console.volcengine.com/ark`,pr=`https://console.anthropic.com/settings/billing`,mr=`https://console.cloud.google.com/billing`,hr=`https://console.x.ai/`,gr=`https://platform.xiaomimimo.com/console/balance`,_r=`https://console.cloud.tencent.com/expense/recharge`,vr={deepseek:`https://platform.deepseek.com/top_up`,minimax:`https://platform.minimax.cn/console/recharge-records`,moonshot:lr,kimi:lr,zhipu:ur,bigmodel:ur,qwen:dr,dashscope:dr,doubao:fr,volcengine:fr,ark:fr,openai:`https://platform.openai.com/settings/organization/billing`,anthropic:pr,claude:pr,google:mr,gemini:mr,xai:hr,grok:hr,siliconflow:`https://cloud.siliconflow.cn/account/charge`,hunyuan:_r,tencent:_r,腾讯云:_r,xiaomi:gr,mimo:gr,mi:gr,qianfan:`https://console.bce.baidu.com/qianfan/overview`};function yr(e){let t=vr[e];if(t!==void 0)return t;let n=Object.keys(vr).find(t=>e.startsWith(t));return n===void 0?void 0:vr[n]}function br(e){let t=$(e),n=yr(t);if(n!==void 0)return n;for(let[e,n]of Object.entries(rr))if(ir($(e),t))for(let e of n){let t=yr($(e));if(t!==void 0)return t}}function xr(e,t){let n=Object.keys(e).filter(e=>e<=t).sort().slice(-7);return n.length===0?0:n.reduce((t,n)=>t+(e[n]?.cost??0),0)/n.length}function Sr(e,t,n){let r=Object.keys(e).filter(e=>e.startsWith(t)),i=t.split(`-`),a=new Date(Number(i[0]),Number(i[1]),0).getDate(),o=r.length>0?r.reduce((t,n)=>t+(e[n]?.cost??0),0)/r.length:xr(e,n);return o<=0?0:o*a}function Cr(e){let t=Ke();if(t===void 0||e.byDayModels===void 0)return e;let n=$e().rate,r=e.byDayModelsSite!==void 0,i={},a={},o=new Map,s=0,c=e=>t.some(t=>t.origin!==void 0&&t.origin!==``&&(t.key===e||G(t.key)===G(e))),l=(e,t,r)=>{if(e===void 0)return r;let i=Math.min(t.cacheHit,t.cacheMiss+t.cacheHit),a=r=>{let a=(t.cacheMiss*r.input+i*r.cacheHit+t.output*r.output)/1e6;return e.currency===`USD`?a*n:a};return e.offPeak===void 0?a(e):a(e)*tt+a(e.offPeak)*.5};for(let[t,n]of Object.entries(e.byDayModels)){let u=0,d={};for(let[i,a]of Object.entries(n)){let n=H(i)??Je(i),s=r&&c(i),f;if(s&&e.byDayModelsSite?.[t]?.[i]!==void 0){let r=0;for(let[a,o]of Object.entries(e.byDayModelsSite[t][i])){let e=a.startsWith(`site:`)?a.slice(5):void 0,t=e===void 0?void 0:H(i,e);r+=l(t??n,o,o.cost)}f=r}else f=l(n,a,a.cost);u+=f,d[i]={...a,cost:f},o.set(i,(o.get(i)??0)+f)}let f=e.byDay[t];f!==void 0&&(i[t]={...f,cost:u}),a[t]=d,s+=u}return{...e,total:{...e.total,cost:s},byDay:i,byDayModels:a,byModel:Object.fromEntries(Object.entries(e.byModel).map(([e,t])=>{let n=o.get(e);return[e,n===void 0?t:{...t,cost:n}]})),unpricedModels:(e.unpricedModels??[]).filter(e=>!H(e)&&!Je(e))}}function wr(){return typeof Notification<`u`&&Notification.permission===`granted`}let Tr=new Set;function Er(e,t){Tr.has(e)||(Tr.add(e),fetch(`/api/billing/notify-claim`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({key:e})}).then(e=>e.json()).then(e=>{e.claimed!==!1&&t()}).catch(()=>t()))}function Dr(e){return Object.keys(e).length}function Or(e,t=Date.now()){let n=0,r=new Date(t);for(;q(r.getTime())in e;)n+=1,r.setDate(r.getDate()-1);return n}function kr(e){return e.input+e.output}function Ar(e){let t=[];for(let n=6;n>=0;--n){let r=new Date;r.setDate(r.getDate()-n);let i=q(r.getTime());t.push({date:i,cost:e[i]?.cost??0})}return t}function jr(e,t,n=e=>e.cost){let r=new Date(`${t}T00:00:00`),i=(r.getDay()+6)%7,a=0;for(let t=0;t<=i;t+=1){let i=new Date(r);i.setDate(i.getDate()-t);let o=e[q(i.getTime())];o!==void 0&&(a+=n(o))}return a}function Mr(e,t,n){let r=new Date(`${t}T00:00:00`),i=(r.getDay()+6)%7,a=new Date(r);a.setDate(a.getDate()-i);let o=q(a.getTime()),s=new Date(r);s.setDate(s.getDate()-6);let c=q(s.getTime()),l=0,u=0,d=0,f=0,p=0,m=0,h=0,g,_=0;for(let[r,i]of Object.entries(e)){if(!(n===`today`?r===t:n===`7d`?r>=c&&r<=t:n===`week`?r>=o&&r<=t:r.startsWith(t.slice(0,7))))continue;l+=i.cost,u+=i.calls,d+=i.input,f+=i.output,p+=i.cacheHit,m+=i.cacheMiss,h+=i.reasoning??0;let e=kr(i);e>_&&(_=e,g=r)}return{cost:l,calls:u,input:d,output:f,cacheHit:p,cacheMiss:m,reasoning:h,peakDay:g,peakTokens:_}}function Nr(e,t){return e.checked?e.okProviders.some(e=>ar(t,e))?I.healthOk:e.badProviders.some(e=>ar(t,e))?I.healthBad:I.healthIdle:I.healthIdle}function Pr(e){let t=new Map,n=[];for(let r of e){if(r.title===void 0||r.title===``){n.push(r);continue}let e=t.get(r.title);if(e===void 0){let e={...r,mergedCount:1};t.set(r.title,e),n.push(e);continue}e.children===void 0&&(e.children=[{...e}]),e.children.push({...r}),e.calls+=r.calls,e.cost+=r.cost,e.lastActive=Math.max(e.lastActive,r.lastActive),r.stale===!0&&(e.stale=!0),e.mergedCount=(e.mergedCount??1)+1}return n.sort((e,t)=>t.cost-e.cost||t.lastActive-e.lastActive)}function Fr(e,t){switch(e){case`ok`:return``;case`not-configured`:return t(`subscriptionNotConfigured`);case`unauthorized`:return t(`subscriptionUnauthorized`);case`rate-limited`:return t(`subscriptionRateLimited`);case`invalid-response`:return t(`subscriptionInvalid`);default:return t(`subscriptionUnavailable`)}}function Ir({window:e,t}){let n=Math.min(100,Math.max(0,e.usedPercent)),r=Math.min(100,Math.max(0,e.remainingPercent))<=0;return(0,m.jsxs)(`div`,{className:I.subscriptionWindow,children:[(0,m.jsx)(`span`,{className:I.subscriptionWindowLabel,children:Lr(e.kind,t)}),(0,m.jsx)(`span`,{className:I.subscriptionTrack,"aria-hidden":`true`,children:(0,m.jsx)(`span`,{className:y(I.subscriptionFill,n>=100&&I.subscriptionFillOver,n>=80&&n<100&&I.subscriptionFillWarn),style:{width:`${n}%`}})}),(0,m.jsxs)(`span`,{className:I.subscriptionMeta,children:[(0,m.jsx)(`span`,{className:y(I.subscriptionPct,r&&I.subscriptionExhausted),children:r?t(`subscriptionExhausted`):t(`subscriptionRemaining`).replace(`{pct}`,String(e.remainingPercent))}),e.resetsAt!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionReset,children:t(`subscriptionReset`).replace(`{date}`,`${q(new Date(e.resetsAt).getTime())} ${Vr(new Date(e.resetsAt).getTime())}`)})]})]})}function Lr(e,t){switch(e){case`session`:return t(`subscriptionSession`);case`weekly`:return t(`subscriptionWeekly`);case`monthly`:return t(`subscriptionMonthly`);case`billing`:return t(`subscriptionBilling`)}}function Rr(e,t){switch(e){case`new-api`:return t(`relayKindNewApi`);case`sub2api`:return t(`relayKindSub2Api`);default:return t(`relayKindUnknown`)}}let zr={"new-api":I.siteKindSite,sub2api:I.siteKindDirect,unknown:I.siteKindUnknown},Br=3e4;function Vr(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}let Hr=[`#4f8cff`,`#2dd4bf`,`#a78bfa`,`#f59e0b`,`#f472b6`,`#fbbf24`,`#38bdf8`,`#6366f1`,`#f97316`,`#14b8a6`],Ur={total:{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cost:0,reasoning:0},byModel:{},byDay:{},byDayModels:{}};async function Wr(){try{let e=await fetch(`/api/billing/usage-stats`);if(!e.ok)return null;let t=await e.text(),n=JSON.parse(t);if(typeof n!=`object`||!n||!(`total`in n))return null;let r=n,i=e=>typeof e==`object`&&!!e;return{total:r.total??Ur.total,byModel:r.byModel??{},byDay:r.byDay??{},...r.byDayModels===void 0?{}:{byDayModels:r.byDayModels},...i(r.byDayModelsSite)?{byDayModelsSite:r.byDayModelsSite}:{},...r.updatedAt===void 0?{}:{updatedAt:r.updatedAt},...typeof r.budget==`number`?{budget:r.budget}:{},...typeof r.lowBalanceThreshold==`number`?{lowBalanceThreshold:r.lowBalanceThreshold}:{},...Array.isArray(r.bySession)?{bySession:r.bySession}:{},...Array.isArray(r.byTurn)?{byTurn:r.byTurn}:{},...Array.isArray(r.byWorkspace)?{byWorkspace:r.byWorkspace}:{},...i(r.bySite)?{bySite:r.bySite}:{},...i(r.byTier)?{byTier:r.byTier}:{},...i(r.byTool)?{byTool:r.byTool}:{},...Array.isArray(r.unpricedModels)?{unpricedModels:r.unpricedModels}:{},...typeof r.staleLedgerSessions==`number`?{staleLedgerSessions:r.staleLedgerSessions}:{},...typeof r.unreadableSessions==`number`?{unreadableSessions:r.unreadableSessions}:{},...typeof r.unreadableFormatSessions==`number`?{unreadableFormatSessions:r.unreadableFormatSessions}:{},...typeof r.unreadableNoLedgerSessions==`number`?{unreadableNoLedgerSessions:r.unreadableNoLedgerSessions}:{},...typeof r.searchCallEstimateCny==`number`?{searchCallEstimateCny:r.searchCallEstimateCny}:{},...r.byRole!==null&&typeof r.byRole==`object`?{byRole:r.byRole}:{},...r.perf!==null&&typeof r.perf==`object`&&r.perf.byModel!==null&&typeof r.perf.byModel==`object`&&r.perf.byHourModel!==null&&typeof r.perf.byHourModel==`object`?{perf:r.perf}:{},...typeof r.pluginVersion==`string`?{pluginVersion:r.pluginVersion}:{}}}catch{return null}}let Gr=!1,Kr=0;async function qr(e=0){try{let t=await fetch(`/api/billing/pricing`);if(!t.ok){Gr=!1;return}let n=await t.text(),r=JSON.parse(n);if(typeof r!=`object`||!r||!(`source`in r)){Gr=!1;return}let i=r;Array.isArray(i.catalog)&&i.catalog.length>0&&i.aliases!==null&&typeof i.aliases==`object`&>(i.catalog,i.aliases);let a=r;if(a.source===`builtin`&&e<3){if(e===0){if(Gr)return;Gr=!0}setTimeout(()=>{qr(e+1)},2e3);return}Gr=!1,Kr=a.syncedAt??0,Ye(a)}catch{Gr=!1}}async function Jr(){try{return(await fetch(`/api/billing/pricing/refresh`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`})).ok?(await qr(),!0):!1}catch{return!1}}async function Yr(){try{let e=await fetch(`/api/billing/balance`);if(!e.ok)return{balances:[]};let t=await e.text(),n=JSON.parse(t);if(typeof n!=`object`||!n)return{balances:[]};let r=n;return{balances:Array.isArray(r.balances)?r.balances:[],...r.reconcile===void 0?{}:{reconcile:r.reconcile}}}catch{return{balances:[]}}}async function Xr(){let e=await fetch(`/api/billing/subscriptions`);if(!e.ok)throw Error(`subscriptions HTTP ${String(e.status)}`);let t=await e.text(),n=JSON.parse(t);if(typeof n==`object`&&n&&`quotas`in n)return n.quotas;throw Error(`subscriptions: invalid response`)}async function Zr(){let e=await fetch(`/api/billing/relay-quotas`);if(!e.ok)throw Error(`relay-quotas HTTP ${String(e.status)}`);let t=await e.text(),n=JSON.parse(t);if(typeof n==`object`&&n&&`quotas`in n)return n.quotas;throw Error(`relay-quotas: invalid response`)}async function Qr(){try{let e=await fetch(`/api/billing/usage-tool`);if(!e.ok)return;let t=JSON.parse(await e.text());return typeof t.enabled==`boolean`?t.enabled:void 0}catch{return}}async function $r(e){try{let t=await fetch(`/api/billing/usage-tool`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e})});return t.ok?JSON.parse(await t.text()).ok===!0:!1}catch{return!1}}let ei=e=>e.models.reduce((e,t)=>e+(t.actual??(t.plan===!0?0:t.estimated)),0);function ti(e){let t=t=>K(Bt(t,e.currency),e.currency),{wide:n,t:r,onOpen:i,monthCost:a,todayCost:o,weekCost:s,days:c,vendorStatus:l,dash:u,floatPrefs:p,subscriptions:h,cardPrefs:g,monthTokens:_,todayTokens:v,weekTokens:b,budgetPressure:x}=e,S=(0,d.useMemo)(()=>p.targets.map(e=>h.find(t=>t.provider===e)).filter(e=>e!==void 0),[p.targets,h]),[C,w]=(0,d.useState)(0),T=S.length===0?0:Math.min(C,S.length-1),ee=S[T],E=(0,d.useRef)(null),[D,O]=(0,d.useState)(!1),[te,ne]=(0,d.useState)({left:0,top:0});(0,d.useEffect)(()=>{if(!D||p.mode!==`subscription`||S.length<2)return;let e=setInterval(()=>w(e=>(e+1)%S.length),1500);return()=>clearInterval(e)},[D,p.mode,S.length]);let k=(0,d.useRef)(void 0),re=(0,d.useCallback)(()=>{window.clearTimeout(k.current),O(!0)},[]),ie=(0,d.useCallback)(()=>{window.clearTimeout(k.current),k.current=window.setTimeout(()=>O(!1),120)},[]);(0,d.useEffect)(()=>()=>window.clearTimeout(k.current),[]);let A=(0,d.useCallback)(()=>{let e=E.current?.getBoundingClientRect();e!==void 0&&ne({left:e.left,top:e.top-8})},[]);(0,d.useEffect)(()=>{if(!D)return;let e=()=>A();return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,{capture:!0}),window.removeEventListener(`resize`,e)}},[D,A]);let ae=c.length>0?c.reduce((e,t)=>e+t.cost,0)/c.length:0,oe=ae>0?Math.max(0,Math.min(1,o/ae)):0,se=-80+oe*160,ce=(0,m.jsxs)(`svg`,{viewBox:`0 0 40 40`,fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,"aria-hidden":`true`,children:[(0,m.jsx)(`path`,{d:`M5.23 26.4A15 15 0 0 1 34.77 26.4`,strokeWidth:3,opacity:.16}),(0,m.jsx)(`path`,{d:`M5.23 26.4A15 15 0 0 1 34.77 26.4`,strokeWidth:3,strokeDasharray:`${(41.9*oe).toFixed(2)} 41.9`,className:I.triggerGaugeArc}),(0,m.jsx)(`path`,{d:`M5.23 26.4 8.18 26.92M10.36 17.51 12.29 19.81M20 14v3M27.71 19.81 29.64 17.51M31.82 26.92 34.77 26.4`,strokeWidth:1.6,opacity:.7}),(0,m.jsx)(`path`,{d:`M7.01 21.5 8.31 22.25M14.87 14.91 15.38 16.31M24.62 16.31 25.13 14.91M31.69 22.25 32.99 21.5`,strokeWidth:1.2,opacity:.38}),(0,m.jsx)(`line`,{x1:`20`,y1:`29`,x2:`20`,y2:`19.5`,strokeWidth:2,className:I.triggerGaugeNeedle,style:{transform:`rotate(${se}deg)`,transformOrigin:`20px 29px`}}),(0,m.jsx)(`circle`,{cx:`20`,cy:`29`,r:`1.5`,fill:`currentColor`,stroke:`none`})]});if(!n)return(0,m.jsx)(`button`,{type:`button`,className:y(I.railButton,x!==`none`&&I.triggerBudgetPulse,x===`over`&&I.triggerBudgetOver),"data-testid":`billing-rail-button`,onClick:i,title:`${r(`title`)} · ${t(g.span===`day`?o:g.span===`week`?s:a)}`,children:ce});let j=g.metric===`tokens`,le=c.map(e=>j?e.tokens:e.cost),M=Math.max(...le,0),N=le.map(e=>M>0?4+e/M*12:4);return(0,m.jsxs)(`span`,{ref:E,className:I.triggerWrap,onMouseEnter:()=>{A(),re()},onMouseLeave:ie,onFocusCapture:()=>{A(),re()},onBlurCapture:()=>O(!1),children:[(0,m.jsxs)(`button`,{type:`button`,className:y(I.trigger,x!==`none`&&I.triggerBudgetPulse,x===`over`&&I.triggerBudgetOver),"data-testid":`billing-trigger`,onClick:i,title:`${r(`title`)} · ${t(g.span===`day`?o:g.span===`week`?s:a)}`,children:[(0,m.jsx)(`span`,{className:y(I.triggerIcon,x!==`none`&&I.triggerBudgetHot),"data-testid":`billing-trigger-icon`,children:ce}),(0,m.jsx)(`span`,{className:I.triggerMain,children:(0,m.jsxs)(`span`,{className:I.triggerPrimary,children:[(0,m.jsx)(`span`,{className:I.triggerLabel,children:j?g.span===`day`?r(`triggerTodayTokens`):g.span===`week`?r(`triggerWeekTokens`):r(`triggerMonthTokens`):g.span===`day`?r(`triggerToday`):g.span===`week`?r(`weekCost`):r(`triggerMonth`)}),(()=>{let e=g.span===`day`?j?v:o:g.span===`week`?j?b:s:j?_:a;return j?(0,m.jsx)(`span`,{className:I.triggerMetric,"data-testid":`billing-trigger-span-tokens`,children:J(e)}):(0,m.jsxs)(`span`,{className:I.triggerValueRow,children:[(0,m.jsx)(`span`,{className:I.triggerYen,"aria-hidden":`true`,children:t(e).charAt(0)}),(0,m.jsx)(`span`,{className:I.triggerMetric,"data-testid":`billing-trigger-span-money`,children:t(e).slice(1)})]})})()]})}),(0,m.jsx)(`span`,{className:I.triggerSpark,"data-testid":`billing-trigger-spark`,"aria-hidden":`true`,children:N.map((e,t)=>(0,m.jsx)(`span`,{className:t===N.length-1?I.triggerSparkHot:I.triggerSparkBar,style:{height:`${e}px`}},c[t]?.date??String(t)))})]}),(0,f.createPortal)((0,m.jsx)(`span`,{className:y(I.triggerPop,D&&I.triggerPopShown),style:{left:`${te.left}px`,top:`${te.top}px`},"data-testid":`billing-trigger-pop`,"aria-hidden":!D,onMouseEnter:re,onMouseLeave:ie,children:p.mode===`subscription`?(0,m.jsx)(m.Fragment,{children:S.length===0?(0,m.jsx)(`span`,{className:I.triggerPopEmpty,children:r(`floatNoTargets`)}):(0,m.jsxs)(m.Fragment,{children:[ee!==void 0&&(0,m.jsxs)(`div`,{className:I.floatSub,"data-testid":`billing-float-subscription`,children:[(0,m.jsxs)(`div`,{className:I.floatSubHead,children:[(0,m.jsx)(`span`,{className:I.floatSubName,children:ee.displayName}),ee.plan!==void 0&&(0,m.jsx)(`span`,{className:I.floatSubPlan,children:ee.plan})]}),ee.windows.map(e=>(0,m.jsx)(Ir,{window:e,t:r},e.kind))]}),S.length>1&&(0,m.jsx)(`span`,{className:I.triggerPopSwitcher,"data-testid":`billing-float-switcher`,children:(0,m.jsxs)(`span`,{className:I.triggerPopSwitchCount,children:[T+1,`/`,S.length]})})]})}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:I.popHead,children:(0,m.jsx)(`span`,{className:I.popTitle,children:r(`popTitle`)})}),(0,m.jsxs)(`span`,{className:I.metricGrid,children:[(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`floatPrimaryToday`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:t(o)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`floatPrimaryWeek`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:t(s)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`floatPrimaryMonth`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:t(a)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`input`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:J(u.input)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`output`)}),(0,m.jsx)(`span`,{className:I.metricValue,children:J(u.output)})]}),(0,m.jsxs)(`span`,{className:I.metricCell,children:[(0,m.jsx)(`span`,{className:I.metricLabel,children:r(`cacheHit`)}),(0,m.jsx)(`span`,{className:y(I.metricValue,I.metricValueSuccess),children:Ut(u.cacheRead+u.cacheMiss>0?u.cacheRead/(u.cacheRead+u.cacheMiss)*100:0)})]})]}),(0,m.jsxs)(`span`,{className:I.popModel,children:[(0,m.jsx)(`span`,{className:I.popModelLabel,children:r(`popTodayModel`)}),l.direct!==void 0||l.sub!==void 0?(0,m.jsxs)(m.Fragment,{children:[l.direct!==void 0&&(0,m.jsxs)(`span`,{className:I.popModelRow,children:[(0,m.jsx)(`span`,{className:y(I.popDot,I.popDotDirect),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:I.popTagPrimary,children:r(`popDirectLead`)}),(0,m.jsx)(`span`,{className:I.popModelName,children:l.direct.name}),(0,m.jsx)(`span`,{className:y(I.popModelStatus,l.direct.low&&I.popModelStatusLow),children:l.direct.text})]}),l.sub!==void 0&&(0,m.jsxs)(`span`,{className:I.popModelRow,children:[(0,m.jsx)(`span`,{className:y(I.popDot,I.popDotSub),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:I.popTagSub,children:r(`popSubLead`)}),(0,m.jsx)(`span`,{className:I.popModelName,children:l.sub.name}),(0,m.jsx)(`span`,{className:y(I.popModelStatus,l.sub.low&&I.popModelStatusLow),children:l.sub.text})]})]}):(0,m.jsxs)(`span`,{className:I.popModelRow,children:[(0,m.jsx)(`span`,{className:y(I.popDot,I.popDotNeutral),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:I.popModelStatus,children:r(`popNoConsumption`)})]})]})]})}),document.body)]})}function ni({balance:e,days:t,dailyBurn:n,money:r,t:i,onClose:a}){let o=t=>t===void 0?void 0:e.currency===`USD`?`$${t.toFixed(2)}`:r(t),s=o(e.totalBalance),c=o(e.grantedBalance),l=o(e.toppedUpBalance);return(0,m.jsxs)(`span`,{className:I.balanceDetailPop,"data-testid":`billing-balance-detail-pop`,onClick:e=>{e.stopPropagation()},children:[(0,m.jsxs)(`span`,{className:I.balanceDetailHead,children:[(0,m.jsx)(`span`,{className:I.balanceDetailTitle,children:e.displayName}),(0,m.jsx)(`button`,{type:`button`,className:I.balanceDetailClose,"aria-label":i(`close`),onClick:a,children:`×`})]}),(0,m.jsxs)(`span`,{className:I.balanceDetailGrid,children:[s!==void 0&&(0,m.jsx)(ri,{label:i(`balance`),value:s}),c!==void 0&&(0,m.jsx)(ri,{label:i(`balanceGranted`),value:c}),l!==void 0&&(0,m.jsx)(ri,{label:i(`balanceTopped`),value:l}),(0,m.jsx)(ri,{label:i(`balanceDaily`),value:r(n)}),(0,m.jsx)(ri,{label:i(`balanceDaysLong`),value:`${t} ${i(`balanceDaysUnit`)}`})]})]})}function ri({label:e,value:t}){return(0,m.jsxs)(`span`,{className:I.balanceDetailRow,children:[(0,m.jsx)(`span`,{className:I.balanceDetailLabel,children:e}),(0,m.jsx)(`span`,{className:I.balanceDetailValue,children:t})]})}function ii({userPrices:e,onUserPrices:t,t:n}){let[r,i]=(0,d.useState)(()=>[...e]),[a,o]=(0,d.useState)(new Set),s=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),c=()=>{i(e=>e.filter((e,t)=>!a.has(t))),o(new Set)},l=(e,t)=>i(n=>n.map((n,r)=>r===e?{...n,...t}:n)),u=()=>i(e=>[...e,{key:``,input:0,cacheHit:0,output:0}]),f=e=>{let t=r[e]?.offPeak;return{input:t===void 0?``:String(t.input),cacheHit:t===void 0?``:String(t.cacheHit),output:t===void 0?``:String(t.output)}},p=(e,t,n)=>i(r=>r.map((r,i)=>{if(i!==e)return r;let a=r.offPeak,o={input:a===void 0?``:String(a.input),cacheHit:a===void 0?``:String(a.cacheHit),output:a===void 0?``:String(a.output),[t]:n},s=[o.input,o.cacheHit,o.output].some(e=>e.trim()!==``),c=[o.input,o.cacheHit,o.output].map(e=>Number(e)),l=s&&c.every(e=>Number.isFinite(e)&&e>=0)&&c.some(e=>e>0),{offPeak:u,...d}=r;return l?{...d,offPeak:{input:c[0]??0,cacheHit:c[1]??0,output:c[2]??0}}:d})),h=()=>t(r.filter(e=>e.key.trim()!==``).map(e=>({...e,key:e.key.trim(),...e.origin===void 0||e.origin.trim()===``?{}:{origin:We(e.origin.trim())}}))),g=It().map(e=>e.key),_=(e,t)=>i(n=>n.map((n,r)=>{if(r!==e)return n;let{currency:i,...a}=n;return t===`USD`?{...a,currency:`USD`}:a})),v=e=>Number.isFinite(e)&&e!==0?String(e):``,b=(e,t,n)=>{let r=Number(n);l(e,{[t]:Number.isFinite(r)&&r>=0?r:0})};return(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-user-prices`,children:[(0,m.jsx)(`div`,{className:I.setCardHead,children:(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:n(`userPrices`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:n(`userPricesHint`)})]})}),(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsx)(`datalist`,{id:`billing-price-model-keys`,children:g.map(e=>(0,m.jsx)(`option`,{value:e},e))}),r.map((e,t)=>(0,m.jsxs)(`div`,{className:I.userPriceRow,"data-testid":`billing-user-price-row`,children:[(0,m.jsx)(`input`,{type:`checkbox`,className:I.userPriceCheck,"data-testid":`billing-user-price-select`,checked:a.has(t),"aria-label":n(`userPriceSelect`),onChange:()=>s(t)}),(0,m.jsxs)(`div`,{className:I.userPriceBody,children:[(0,m.jsxs)(`div`,{className:I.userPriceLineMeta,children:[(0,m.jsxs)(`div`,{className:I.userPriceField,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:n(`userPriceModel`)}),(0,m.jsx)(`input`,{className:I.userPriceInput,"data-testid":`billing-user-price-model`,type:`text`,list:`billing-price-model-keys`,value:e.key,placeholder:`flash`,"aria-label":n(`userPriceModel`),onChange:e=>l(t,{key:e.target.value})})]}),(0,m.jsxs)(`div`,{className:I.userPriceField,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:n(`userPriceSource`)}),(0,m.jsx)(`input`,{className:I.userPriceInput,"data-testid":`billing-user-price-origin`,type:`text`,value:e.origin??``,placeholder:n(`userPriceSourceHint`),"aria-label":n(`userPriceSource`),onChange:e=>l(t,{origin:e.target.value.trim()})})]}),(0,m.jsxs)(`div`,{className:I.userPriceField,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:n(`userPriceCurrency`)}),(0,m.jsxs)(`div`,{className:I.ctlGroup,children:[(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,e.currency!==`USD`&&I.floatModeBtnOn),onClick:()=>_(t,`CNY`),children:`CNY`}),(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,e.currency===`USD`&&I.floatModeBtnOn),onClick:()=>_(t,`USD`),children:`USD`})]})]})]}),[{label:n(`userPriceNormal`),testid:`billing-user-price-normal`,valueOf:t=>v(e[t]),onChange:(e,n)=>b(t,e,n)},{label:n(`userPriceOffPeak`),testid:`billing-user-price-offpeak`,valueOf:e=>f(t)[e],onChange:(e,n)=>p(t,e,n)}].map(e=>(0,m.jsxs)(`div`,{className:I.userPricePriceLine,"data-testid":e.testid,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:e.label}),[`input`,`cacheHit`,`output`].map(t=>{let r=n(t===`input`?`tokenMiss`:t===`cacheHit`?`tokenHit`:`tokenOutput`);return(0,m.jsx)(`input`,{className:I.userPriceInputNum,type:`number`,min:0,step:.01,placeholder:r,"aria-label":`${e.label} ${r}`,value:e.valueOf(t),onChange:n=>e.onChange(t,n.target.value)},t)})]},e.testid))]})]},t)),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-user-price-add`,onClick:u,children:n(`userPriceAdd`)}),(0,m.jsxs)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-user-price-remove-selected`,disabled:a.size===0,onClick:c,children:[n(`userPriceRemoveSelected`),a.size>0?` (${a.size})`:``]}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-user-price-save`,onClick:h,children:n(`userPriceSave`)})]})]})]})}function ai({stats:e,t,onClose:n,userPrices:r,onUserPrices:i,health:a,balances:o,reconcile:s,quotas:c,relayQuotas:l,currency:u,onCurrency:f,language:h,onLanguage:g,turns:_,renderSlot:v,budgetEnabled:b,budgetAmount:x,onToggleBudget:S,onBudgetAmount:C,peakConfig:w,onPeakConfig:T,onPreviewPeak:ee,floatPrefs:E,onFloatPrefs:D,cardPrefs:O,onCardPrefs:te,sitePrefs:ne,onSitePrefs:ie,liveCostPrefs:A,onLiveCostPrefs:ae,quotasStale:oe}){let[se,ce]=(0,d.useState)(`cost`),{total:j,byModel:le,byDay:M}=e,[N,ue]=(0,d.useState)(`overview`),[de,fe]=(0,d.useState)(7),[pe,me]=(0,d.useState)(()=>{try{return window.localStorage.getItem(`dsh-billing:reconcile-dismissed`)??``}catch{return``}}),ge=()=>{let e=new Date,t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`},_e=(0,d.useCallback)(()=>{let e=ge();me(e);try{window.localStorage.setItem(`dsh-billing:reconcile-dismissed`,e)}catch{}},[]),[be,P]=(0,d.useState)(`month`),[Ce,we]=(0,d.useState)(`cost`),[F,Ee]=(0,d.useState)(k),De=(0,d.useMemo)(()=>c.filter(e=>e.status===`ok`&&e.windows.length>0).map(e=>({id:e.provider,label:e.displayName})),[c]),[Oe,ke]=(0,d.useState)(),[Ae,je]=(0,d.useState)(new Set),Me=(0,d.useCallback)(e=>{je(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ne=(0,d.useMemo)(()=>Pr(e.bySession??[]),[e.bySession]),[Pe,Fe]=(0,d.useState)(()=>new Set(ve())),L=(0,d.useCallback)(e=>{Fe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),ye([...n]),n})},[]),[R,Ie]=(0,d.useState)(()=>xe()),Re=(0,d.useCallback)(()=>{Ie(e=>{let t=!e;return Se(t),t})},[]),[ze,Be]=(0,d.useState)(!1);(0,d.useEffect)(()=>{let e=!0;return Qr().then(t=>{e&&t!==void 0&&Be(t)}),()=>{e=!1}},[]);let Ve=(0,d.useCallback)(()=>{let e=!ze;Be(e),$r(e).then(t=>{t||Be(!e)})},[ze]),z=$e(),[He,Ue]=(0,d.useState)(!1),We=(0,d.useCallback)(()=>{He||(Ue(!0),Jr().finally(()=>{Ue(!1)}))},[He]),Ge=Kr,B=e=>K(Bt(e,u),u),Ke=u===`usd`?`$`:u===`eur`?`€`:`¥`,V=h,H=e=>Rn(e,V),[qe,Je]=(0,d.useState)(``),[Ye,Xe]=(0,d.useState)(()=>he()),[Ze,Qe]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{let e=setInterval(()=>{Qe(Date.now())},3e4);return()=>{clearInterval(e)}},[]);let et=c.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),tt=w.leadMin*6e4,U=(e,n)=>e===0?t(`free`):Vt(Ht(e,n,u,z.rate),u===`usd`?`USD`:u===`eur`?`EUR`:`CNY`),nt=(0,d.useMemo)(()=>Mn([..._].reverse()),[_]),W={peak:e.byTier?.peak.cost??0,offPeak:e.byTier?.offPeak.cost??0},rt=W.peak/2,it=xr(M,q()),at=e=>o.find(t=>$(t.provider)===$(e)),ot=e=>e.balance?.error===`unconfigured`&&e.models.length>0&&e.models.every(e=>e.plan),st=e=>{if(e===void 0)return(0,m.jsx)(`span`,{className:I.na,children:`—`});if(e.error===`unconfigured`)return t(`balanceUnconfigured`);if(e.error===`unauthorized`)return t(`balanceUnauthorized`);if(e.error===`unreachable`)return t(`balanceUnreachable`);if(e.totalBalance===void 0)return(0,m.jsx)(`span`,{className:I.na,children:`—`});let n=e.currency===`USD`?`$${e.totalBalance.toFixed(2)}`:B(e.totalBalance),r=e.currency===`USD`?e.totalBalance*z.rate:e.totalBalance,i=it>0?Math.floor(r/it):void 0;return(0,m.jsxs)(`span`,{className:I.balanceCell,children:[(0,m.jsx)(`span`,{children:n}),i!==void 0&&i>=0&&(0,m.jsx)(`button`,{type:`button`,className:y(I.balanceDaysBadge,i<=3&&I.balanceDaysBadgeLow),"data-testid":`billing-balance-days-badge`,title:t(`balanceDays`).replace(`{days}`,String(i)),"aria-label":`${e.displayName} ${t(`balanceDays`).replace(`{days}`,String(i))}`,onClick:t=>{t.stopPropagation(),ke(Oe===e.provider?void 0:e.provider)},children:`?`}),Oe===e.provider&&(0,m.jsx)(ni,{balance:e,days:i??0,dailyBurn:it,money:B,t,onClose:()=>{ke(void 0)}})]})},ct=Object.keys(M).sort(),lt=q(),ft=M[lt]?.cost??0,pt=lt.slice(0,7),mt=lt.slice(0,4),ht=ct.reduce((e,t)=>e+(t.startsWith(pt)?M[t]?.cost??0:0),0),gt=ct.reduce((e,t)=>e+(t.startsWith(mt)?M[t]?.cost??0:0),0),_t=(0,d.useMemo)(()=>Sr(M,pt,lt)+c.reduce((e,t)=>e+(t.planType===`code`?t.subscriptionAmount??0:0),0),[M,pt,lt,c]),vt=(0,d.useMemo)(()=>{if(!(b&&x>0))return null;let e=x-ht;return{over:e<=0,remainRatio:Math.max(0,Math.min(1,e/x)),remainCny:Math.max(0,e)}},[b,x,ht]),yt=(0,d.useMemo)(()=>{let e=[];for(let t=de-1;t>=0;--t){let n=new Date;n.setDate(n.getDate()-t),e.push(q(n.getTime()))}return e},[de]),G=yt.at(-1)??lt,bt=(0,d.useMemo)(()=>Object.entries(M).map(([e,t])=>({date:e,value:Ce===`tokens`?kr(t):t.cost})),[M,Ce]),xt=(0,d.useMemo)(()=>bt.reduce((e,t)=>e+t.value,0),[bt]),St=Dr(M),Ct=Or(M),wt=(0,d.useMemo)(()=>yt.map(t=>{let n={},r=e.byDayModels?.[t];if(r!==void 0)for(let[e,t]of Object.entries(r))t.cost>0&&(n[e]=t.cost);let i=M[t];return{date:t,cost:i?.cost??0,calls:i?.calls??0,byModel:n,tokens:i===void 0?0:kr(i)}}),[yt,M,e.byDayModels]),Tt=(0,d.useMemo)(()=>Object.entries(le).filter(([,e])=>e.calls>0).map(([e,t])=>{let n=Mt(e),r=n.key===`other`,i=r?or(e):void 0,a={input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,output:t.output};return{key:e,name:r?e:n.name,provider:i??n.provider,calls:t.calls,input:t.input,output:t.output,cacheHitRate:t.cacheHit+t.cacheMiss>0?t.cacheHit/(t.cacheHit+t.cacheMiss)*100:0,estimated:Rt(n,a),plan:t.plan===!0,...t.cost>0?{actual:t.cost}:{},uncatalogued:r,estimatedPricing:n.estimated===!0,officialCalls:t.officialCalls??0,officialCost:t.officialCost??0}}).sort((e,t)=>(t.actual??t.estimated)-(e.actual??e.estimated)).map((e,t)=>({...e,color:Hr[t%Hr.length]??`#8b95a3`})),[le]),Et=(0,d.useMemo)(()=>ne.hideUnidentified?l.filter(e=>e.kind!==`unknown`):l,[l,ne.hideUnidentified]),Dt=(0,d.useMemo)(()=>{let n=e.byDayModelsSite;if(R){let t=q();n={[t]:e.byDayModelsSite?.[t]??{}}}let r=new Map;for(let t of Object.values(n??{}))for(let[n,i]of Object.entries(t))for(let[t,a]of Object.entries(i)){let i=r.get(t);i===void 0&&(i=new Map,r.set(t,i));let o=i.get(n)??{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cost:0,allPlan:!0};o.calls+=a.calls,o.input+=a.input,o.output+=a.output,o.cacheHit+=a.cacheHit,o.cacheMiss+=a.cacheMiss,o.cost+=a.cost,o.allPlan=o.allPlan&&(a.plan??e.byModel?.[n]?.plan===!0),i.set(n,o)}let i=new Map;for(let[e,t]of r){let n=!e.startsWith(`direct:`)&&!e.startsWith(`site:`),r=[...t.entries()].filter(([,e])=>e.calls>0).map(([e,t],r)=>{let i=Mt(e),a=i.key===`other`,o=a?or(e)??i.provider:i.provider;return{key:e,name:a?e:i.name,provider:o,color:Hr[r%Hr.length]??`#8b95a3`,calls:t.calls,input:t.input,output:t.output,cacheHitRate:t.cacheHit+t.cacheMiss>0?t.cacheHit/(t.cacheHit+t.cacheMiss)*100:0,estimated:n?0:Rt(i,{input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,output:t.output}),plan:t.allPlan,...t.cost>0?{actual:t.cost}:{},uncatalogued:a,estimatedPricing:i.estimated===!0,officialCalls:0,officialCost:0}}).sort((e,t)=>(t.actual??t.estimated)-(e.actual??e.estimated));r.length>0&&i.set(e,r)}let s=e=>Un(e,V)??t(`channelUnknown`),l=new Map,u=new Map,d=new Map,f=e=>e.startsWith(`direct:`)?`direct`:e.startsWith(`site:`)?`site`:`unknown`,p={direct:2,site:1,unknown:0,vendor:0};for(let[e,t]of i){let n=s(e),r=l.get(n);if(r===void 0)l.set(n,[...t]),u.set(n,f(e)),d.set(n,e);else{r.push(...t),r.sort((e,t)=>(t.actual??t.estimated)-(e.actual??e.estimated));let i=u.get(n)??`unknown`,a=f(e);p[a]>p[i]&&(u.set(n,a),d.set(n,e))}}let m=new Map,h=new Map;for(let e of c){if(e.status===`not-configured`)continue;let t=e.displayName??cr(e.provider),n=s(`direct:${e.provider}`),r=l.has(t)?t:l.has(n)?n:void 0,i=r??`sub:${cr(e.provider)}`;h.set(i,r??cr(e.provider));let a=m.get(i);a===void 0?m.set(i,[e]):a.push(e)}let g=e=>e===s(`direct:deepseek`)||e===s(`site:https://api.deepseek.com`)?at(`deepseek`)??at(e):at(e),_=[];for(let[e,t]of l)_.push({id:`ch:${d.get(e)??e}`,name:e,models:t,subscriptions:m.get(e)??[],balance:g(e),dot:Nr(a,t[0]?.provider??``),channelKind:u.get(e)??`unknown`});for(let[e,t]of h)l.has(e)||_.push({id:e,name:t,models:[],subscriptions:m.get(e)??[],balance:at(t),dot:Nr(a,t),channelKind:`vendor`});let v=new Set(_.flatMap(e=>[$(e.name),...e.balance===void 0?[]:[$(e.balance.provider)]]));for(let e of o)v.has($(e.provider))||(e.error===void 0||e.provider.startsWith(`custom:`))&&_.push({id:`bal:${e.provider}`,name:e.displayName,models:[],subscriptions:[],balance:e,dot:Nr(a,e.displayName),channelKind:`vendor`});return(R?_.filter(e=>e.models.length>0):_).sort((e,t)=>{let n=ei(t)-ei(e);return n===0?e.models.length===0&&t.models.length===0?0:t.models.length===0?-1:e.models.length===0?1:e.name.localeCompare(t.name,`zh`):n})},[e.byDayModelsSite,e.byModel,c,o,a,V,t,R]),Ot=(0,d.useMemo)(()=>Dt.filter(e=>e.models.length>0||e.subscriptions.length>0).map(e=>e.id),[Dt]),kt=Ot.length>0&&Ot.every(e=>Pe.has(e)),At=()=>{let e=new Set(kt?[]:Ot);Fe(e),ye([...e])},jt=(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:t(`model`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`calls`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`inputTokens`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`outputTokens`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`cacheHitRate`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`actual`)})]})}),Nt=e=>(0,m.jsx)(`span`,{className:I.modelCell,children:(0,m.jsxs)(`span`,{children:[(0,m.jsxs)(`span`,{className:I.modelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:I.uncataloguedTag,"data-testid":`billing-uncatalogued-tag`,children:t(`uncatalogued`)}),e.estimatedPricing&&(0,m.jsx)(`span`,{className:I.estimatedTag,"data-testid":`billing-estimated-tag`,children:t(`estimatedPricing`)})]}),(0,m.jsx)(`span`,{className:I.modelProvider,children:H(e.provider)})]})}),Ft=e.bySite?.unknown?.calls??0,Lt=Tt.reduce((e,t)=>e+t.estimated,0),zt=j.cost>0||Ft>0?j.cost:Lt,Y=(0,d.useMemo)(()=>{if(F===`all`){let e,t=0;for(let[n,r]of Object.entries(M)){let i=kr(r);i>t&&(t=i,e=n)}return{cost:zt,calls:j.calls,input:j.input,output:j.output,cacheHit:j.cacheHit,cacheMiss:j.cacheMiss,reasoning:j.reasoning??0,peakDay:e,peakTokens:t}}return Mr(M,q(),F)},[F,zt,j,M]),Wt=(0,d.useMemo)(()=>Tt.map(e=>({key:e.key,name:e.name,color:e.color})),[Tt]),Gt=wt.length>=2?wt.at(-2)?.cost??0:0,Jt=Gt>0?(ft-Gt)/Gt*100:0;return(0,m.jsx)(p.Modal,{open:!0,onClose:n,title:t(`title`),headless:!0,className:y(I.dashboardModal,`dsh-billing-modal`),children:(0,m.jsxs)(`div`,{className:I.dashboard,"data-testid":`billing-dashboard`,children:[(0,m.jsxs)(`div`,{className:I.dashboardHead,"data-testid":`billing-dashboard-head`,children:[(0,m.jsxs)(`div`,{children:[v(`billing.dashboard.decor`,{position:`head`}),(0,m.jsxs)(`div`,{className:I.headTitleRow,children:[(0,m.jsx)(`h2`,{className:I.dashboardTitle,children:t(`title`)}),v(`billing.dashboard.decor`,{position:`headTitle`})]}),(0,m.jsxs)(`p`,{className:I.dashboardSubtitle,children:[t(`lastUpdated`),` `,G,e.timezone===void 0?null:` · ${e.timezone.name} (${e.timezone.offset})`]})]}),(0,m.jsxs)(`div`,{className:I.dashboardRight,children:[(0,m.jsx)(`span`,{className:I.currencyToggle,role:`group`,"aria-label":t(`language`),children:[`en`,`zh`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.currencyButton,h===e&&I.currencyButtonActive),"aria-pressed":h===e,"data-testid":`billing-language-${e}`,onClick:()=>{g(e)},children:e===`en`?`EN`:`中`},e))}),(0,m.jsx)(`span`,{className:I.currencyToggle,role:`group`,"aria-label":t(`currency`),children:[`cny`,`usd`,`eur`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.currencyButton,u===e&&I.currencyButtonActive),"aria-pressed":u===e,"data-testid":`billing-currency-${e}`,title:t(e===`cny`?`currencyCny`:e===`usd`?`currencyUsd`:`currencyEur`),onClick:()=>{f(e)},children:e===`cny`?`¥ CNY`:e===`usd`?`$ USD`:`€ EUR`},e))}),a.checked&&(0,m.jsxs)(`span`,{className:y(I.healthBadge,a.available?I.healthBadgeOk:I.healthBadgeBad),children:[(0,m.jsx)(`span`,{className:y(I.healthDot,a.available?I.healthOk:I.healthBad),"aria-hidden":`true`}),a.available?`${t(`healthModelsLive`).replace(`{n}`,String(a.models))}${a.failures>0?` · ${t(`healthVendorsDown`).replace(`{n}`,String(a.failures))}`:``}`:t(`healthVendorsUnavailable`).replace(`{n}`,String(a.failures))]}),(0,m.jsx)(`button`,{type:`button`,className:I.closeButton,"aria-label":t(`close`),"data-testid":`billing-close`,onClick:n,children:(0,m.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"aria-hidden":`true`,children:[(0,m.jsx)(`path`,{d:`M18 6 6 18`}),(0,m.jsx)(`path`,{d:`m6 6 12 12`})]})})]})]}),(0,m.jsx)(`nav`,{className:I.tabNav,"data-testid":`billing-tab-nav`,role:`tablist`,"aria-label":t(`title`),children:er.map(e=>(0,m.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":N===e.id,className:y(I.tabButton,N===e.id&&I.tabButtonActive),"data-testid":`billing-tab-${e.id}`,onClick:()=>{ue(e.id)},children:t(e.labelKey)},e.id))}),(0,m.jsxs)(`div`,{className:I.dashboardBody,children:[N===`overview`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-overview`,children:[s?.kind===`drift`&&s.spent!==void 0&&pe!==ge()&&(0,m.jsxs)(`div`,{className:I.reconcileNotice,"data-testid":`billing-reconcile-notice`,role:`note`,children:[(0,m.jsx)(`span`,{className:I.reconcileIcon,"aria-hidden":`true`,children:(0,m.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,m.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`}),(0,m.jsx)(`line`,{x1:`12`,y1:`10`,x2:`12`,y2:`16`}),(0,m.jsx)(`line`,{x1:`12`,y1:`7.5`,x2:`12.01`,y2:`7.5`})]})}),(0,m.jsx)(`span`,{className:I.reconcileText,children:t(`reconcileDrift`).replace(`{provider}`,s.provider??``).replace(`{spent}`,B(s.spent)).replace(`{today}`,B(s.todayOfficialCost??0))}),(0,m.jsx)(`button`,{type:`button`,className:I.reconcileDismiss,"data-testid":`billing-reconcile-dismiss`,onClick:_e,children:t(`reconcileDismiss`)})]}),(0,m.jsxs)(`section`,{className:I.hero,"data-testid":`billing-hero`,children:[v(`billing.dashboard.decor`,{position:`hero`}),(0,m.jsxs)(`div`,{className:I.heroTop,children:[(0,m.jsxs)(`div`,{className:I.heroMain,children:[(0,m.jsx)(`span`,{className:I.heroLabel,children:t(`monthCost`)}),(0,m.jsxs)(`div`,{className:I.heroReadout,children:[(0,m.jsx)(`span`,{className:I.heroCurrency,"aria-hidden":`true`,children:Ke}),(0,m.jsx)(`span`,{className:I.heroValue,children:B(ht).slice(1)})]}),(0,m.jsxs)(`span`,{className:I.heroMeta,children:[j.calls.toLocaleString(),` `,t(`calls`)]})]}),vt!==null&&(0,m.jsxs)(`div`,{className:I.heroGauge,"data-testid":`billing-hero-gauge`,children:[(0,m.jsxs)(`div`,{className:I.heroGaugeDial,children:[(0,m.jsxs)(`svg`,{className:I.heroGaugeSvg,viewBox:`0 0 120 120`,"aria-hidden":`true`,children:[(0,m.jsx)(`circle`,{className:I.heroGaugeTrack,cx:`60`,cy:`60`,r:`52`}),(0,m.jsx)(`circle`,{className:y(I.heroGaugeArc,vt.over&&I.heroGaugeArcOver),cx:`60`,cy:`60`,r:`52`,style:{strokeDasharray:`${vt.remainRatio*326.7} 326.7`}})]}),(0,m.jsxs)(`span`,{className:I.heroGaugeCenter,children:[(0,m.jsxs)(`span`,{className:y(I.heroGaugeRemain,vt.over&&I.heroGaugeRemainOver),children:[Ke,Bt(vt.remainCny,u).toFixed(2)]}),(0,m.jsx)(`span`,{className:I.heroGaugeLabel,children:t(`budgetRemain`)})]})]}),(0,m.jsxs)(`span`,{className:I.heroGaugeSub,children:[B(ht),` / `,B(x)]})]})]}),(0,m.jsxs)(`div`,{className:I.heroSide,children:[(0,m.jsxs)(`div`,{className:I.heroSideItem,children:[(0,m.jsx)(`span`,{className:I.heroSideLabel,children:t(`yearCost`)}),(0,m.jsx)(`span`,{className:I.heroSideValue,children:B(gt)})]}),(0,m.jsxs)(`div`,{className:I.heroSideItem,children:[(0,m.jsx)(`span`,{className:I.heroSideLabel,children:t(`todayCost`)}),(0,m.jsxs)(`span`,{className:I.heroSideValue,children:[B(ft),(0,m.jsxs)(`span`,{className:y(I.delta,Jt>=0?I.deltaUp:I.deltaDown),children:[Jt>=0?`▲`:`▼`,` `,Math.abs(Jt).toFixed(1),`%`]})]})]}),_t>0&&(0,m.jsxs)(`div`,{className:I.heroSideItem,children:[(0,m.jsx)(`span`,{className:I.heroSideLabel,children:t(`monthProjected`)}),(0,m.jsx)(`span`,{className:I.heroSideValue,children:B(_t)})]}),_t<=0&&(0,m.jsx)(`span`,{className:I.heroSideSpacer,"aria-hidden":`true`})]})]}),(e.unpricedModels?.length??0)>0&&(0,m.jsx)(`div`,{className:I.unpricedHint,"data-testid":`billing-unpriced-hint`,children:t(`unpricedHint`).replace(`{count}`,String(e.unpricedModels?.length??0))}),(e.total.searchCalls??0)>0&&(0,m.jsx)(`div`,{className:I.unpricedHint,"data-testid":`billing-search-estimate-hint`,children:t(`searchEstimateHint`).replace(`{count}`,String(e.total.searchCalls??0)).replace(`{each}`,B(e.searchCallEstimateCny??0))}),(e.unreadableSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-sessions-unreadable`,children:(0,m.jsxs)(`div`,{className:I.staleNoticeBody,children:[t(`unreadableNotice`).replace(`{count}`,String(e.unreadableSessions)),(e.unreadableNoLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNoticeSub,"data-testid":`billing-sessions-no-ledger`,children:t(`unreadableNoLedgerNotice`).replace(`{count}`,String(e.unreadableNoLedgerSessions))}),(e.unreadableFormatSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNoticeSub,"data-testid":`billing-sessions-format-unsupported`,children:t(`unreadableFormatNotice`).replace(`{count}`,String(e.unreadableFormatSessions))})]})}),(0,m.jsxs)(`div`,{className:I.kpiZone,children:[(0,m.jsxs)(`div`,{className:I.kpiZoneHead,children:[(0,m.jsx)(`span`,{className:I.kpiZoneLabel,children:t(`kpiRange`)}),(0,m.jsx)(`div`,{className:I.heatmapRangeSwitch,"data-testid":`billing-kpi-range`,role:`group`,"aria-label":t(`kpiRange`),children:[[`today`,`avgRangeToday`],[`7d`,`avgRange7d`],[`week`,`avgRangeWeek`],[`month`,`avgRangeMonth`],[`all`,`avgRangeAll`]].map(([e,n])=>(0,m.jsx)(`button`,{type:`button`,className:y(I.heatmapRangeButton,F===e&&I.heatmapRangeButtonActive),"data-testid":`billing-kpi-range-${e}`,"aria-pressed":F===e,onClick:()=>{Ee(e),re(e)},children:t(n)},e))})]}),(0,m.jsxs)(`section`,{className:I.kpiGrid,"data-testid":`billing-kpi-grid`,children:[(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-tile`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`cacheHitRate`)}),(0,m.jsx)(`span`,{className:y(I.kpiValue,I.kpiGreen),children:Ut(Y.cacheHit+Y.cacheMiss>0?Y.cacheHit/(Y.cacheHit+Y.cacheMiss)*100:0)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[J(Y.cacheHit),` / `,J(Y.cacheHit+Y.cacheMiss),(j.cacheWrite??0)>0?` · ${t(`tokenCacheWrite`)} ${J(j.cacheWrite??0)}`:``]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokens`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:J(Y.input+Y.output)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[t(`inputTokens`),` `,J(Y.input),` · `,t(`outputTokens`),` `,J(Y.output)]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-avg`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`avgCost`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:B(Y.calls>0?Y.cost/Y.calls:0)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[t(`calls`),` `,Y.calls.toLocaleString()]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`calls`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:Y.calls.toLocaleString()}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[Tt.length,` `,t(`models`)]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-think`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokenReasoningShare`)}),(0,m.jsx)(`span`,{className:y(I.kpiValue,I.kpiGreen),children:Ut(Y.output>0?Y.reasoning/Y.output*100:0)}),(0,m.jsx)(`span`,{className:I.kpiDetail,children:J(Y.reasoning)})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-io`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokenIo`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:(Y.output>0?Y.input/Y.output:0).toFixed(2)}),(0,m.jsxs)(`span`,{className:I.kpiDetail,children:[J(Y.input),` / `,J(Y.output)]})]}),(0,m.jsxs)(`div`,{className:I.kpiTile,"data-testid":`billing-kpi-peak`,children:[(0,m.jsx)(`span`,{className:I.kpiLabel,children:t(`tokenPeak`)}),(0,m.jsx)(`span`,{className:I.kpiValue,children:Y.peakTokens>0?Qt(Y.peakTokens):`—`}),(0,m.jsx)(`span`,{className:I.kpiDetail,children:Y.peakDay??`—`})]})]})]}),(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-heatmap`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`heatmap`)}),(0,m.jsx)(`div`,{className:I.heatmapRangeSwitch,"data-testid":`billing-heatmap-metric`,role:`group`,"aria-label":t(`heatmap`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.heatmapRangeButton,Ce===e&&I.heatmapRangeButtonActive),"data-testid":`billing-heatmap-metric-${e}`,"aria-pressed":Ce===e,onClick:()=>{we(e)},children:t(e===`cost`?`metricCost`:`metricTokens`)},e))}),(0,m.jsx)(`div`,{className:I.heatmapRangeSwitch,"data-testid":`billing-heatmap-range`,role:`group`,"aria-label":t(`heatmap`),children:[`month`,`half`,`year`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.heatmapRangeButton,be===e&&I.heatmapRangeButtonActive),"data-testid":`billing-heatmap-range-${e}`,"aria-pressed":be===e,onClick:()=>{P(e)},children:t(e===`month`?`heatmapMonth`:e===`half`?`heatmapHalf`:`heatmapYear`)},e))}),(0,m.jsxs)(`span`,{className:I.panelHint,"data-testid":`billing-heatmap-summary`,children:[t(`heatmapTotal`),` `,Ce===`tokens`?J(xt):B(xt),` · `,t(`activeDays`),` `,St,` · `,t(`streakDays`),` `,Ct]})]}),(0,m.jsx)(On,{days:bt,currency:u,t,range:be,unit:Ce})]})]}),N===`settings`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-settings`,children:[(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-budget`,children:[(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`budget`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`budgetHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":b,"aria-label":t(`budget`),"data-testid":`billing-budget-toggle`,className:y(I.switch,b&&I.switchOn),onClick:S,children:(0,m.jsx)(`span`,{className:I.switchKnob})})]}),b&&(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`budgetAmount`)}),(0,m.jsxs)(`span`,{className:I.inp,"data-testid":`billing-budget-input-wrap`,children:[(0,m.jsx)(`span`,{className:I.affix,"aria-hidden":`true`,children:`¥`}),(0,m.jsx)(`input`,{className:I.budgetInput,"data-testid":`billing-budget-input`,type:`number`,min:0,step:1,value:x===0?``:x,placeholder:e.budget===void 0?`0`:String(e.budget),"aria-label":`${t(`budget`)}(${u===`usd`?`USD`:u===`eur`?`EUR`:`CNY`})`,title:`${t(`budget`)}(${u===`usd`?`USD`:u===`eur`?`EUR`:`CNY`})`,onChange:e=>{C(e.target.valueAsNumber)}})]})]}),x>0&&(()=>{let e=ht/x*100;return(0,m.jsx)(`div`,{className:I.ctlRowStretch,children:(0,m.jsx)(`div`,{className:I.prog,role:`progressbar`,"aria-valuenow":Math.min(e,100),"aria-valuemin":0,"aria-valuemax":100,"aria-label":t(`budget`),"data-testid":`billing-budget-track`,children:(0,m.jsx)(`div`,{className:y(I.progFill,e>=100&&I.budgetFillOver,e>=80&&e<100&&I.budgetFillWarn),style:{width:`${Math.min(e,100)}%`}})})})})(),x>0&&(0,m.jsx)(`p`,{className:I.setCardDesc,"data-testid":`billing-budget-value`,children:t(`budgetSummary`).replace(`{used}`,B(ht)).replace(`{total}`,B(x))})]})]}),(0,m.jsxs)(`section`,{className:I.setCard,"data-testid":`billing-peak-alert-settings`,children:[(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`peakAlert`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`peakAlertHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":w.enabled,"aria-label":t(`peakAlert`),"data-testid":`billing-peak-alert-toggle`,className:y(I.switch,w.enabled&&I.switchOn),onClick:()=>{T({...w,enabled:!w.enabled})},children:(0,m.jsx)(`span`,{className:I.switchKnob})})]}),w.enabled&&(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`label`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertLeadMin`)}),(0,m.jsx)(`span`,{className:I.inp,children:(0,m.jsx)(`input`,{type:`number`,min:1,max:30,step:1,value:w.leadMin,className:I.budgetInput,"aria-label":t(`peakAlertLeadMin`),onChange:e=>{let t=Number(e.target.valueAsNumber);T({...w,leadMin:Number.isFinite(t)?Math.min(30,Math.max(1,Math.round(t))):w.leadMin})}})})]}),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertPos`)}),(0,m.jsx)(`div`,{className:I.ctlGroup,role:`radiogroup`,"aria-label":t(`peakAlertPos`),children:[`bottom-right`,`center`].map(e=>(0,m.jsxs)(`label`,{className:I.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-pos`,checked:w.position===e,onChange:()=>T({...w,position:e})}),(0,m.jsx)(`span`,{className:I.rdoDot,"aria-hidden":`true`}),t(e===`bottom-right`?`peakAlertPosCorner`:`peakAlertPosCenter`)]},e))})]}),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertMode`)}),(0,m.jsx)(`div`,{className:I.ctlGroup,role:`radiogroup`,"aria-label":t(`peakAlertMode`),children:[`both`,`peak`,`offPeak`].map(e=>(0,m.jsxs)(`label`,{className:I.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-mode`,checked:w.mode===e,onChange:()=>T({...w,mode:e})}),(0,m.jsx)(`span`,{className:I.rdoDot,"aria-hidden":`true`}),t(e===`both`?`peakAlertModeBoth`:e===`peak`?`peakAlertModePeak`:`peakAlertModeOff`)]},e))})]}),(0,m.jsxs)(`label`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`peakAlertWebNotify`)}),(0,m.jsx)(`input`,{type:`checkbox`,checked:w.webNotify,"aria-label":t(`peakAlertWebNotify`),onChange:e=>{T({...w,webNotify:e.target.checked})}})]}),(0,m.jsx)(`div`,{className:I.ctlRow,children:(0,m.jsx)(`button`,{type:`button`,className:I.btn,onClick:ee,children:t(`peakAlertPreview`)})})]})]}),(0,m.jsx)(`section`,{className:I.setCard,"data-testid":`billing-toggle-setting`,children:(0,m.jsxs)(`div`,{className:I.setGrid3,children:[(0,m.jsx)(`div`,{className:I.setCell,"data-testid":`billing-usage-stats-tool-setting`,children:(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`usageStatsTool`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`usageStatsToolHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":ze,"aria-label":t(`usageStatsTool`),"data-testid":`billing-usage-stats-tool-toggle`,className:y(I.switch,ze&&I.switchOn),onClick:Ve,children:(0,m.jsx)(`span`,{className:I.switchKnob})})]})}),(0,m.jsxs)(`div`,{className:I.setCell,"data-testid":`billing-livecost-setting`,children:[(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`liveCostBar`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`liveCostBarHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":A.show,"aria-label":t(`liveCostBar`),"data-testid":`billing-livecost-toggle`,className:y(I.switch,A.show&&I.switchOn),onClick:()=>ae({...A,show:!A.show}),children:(0,m.jsx)(`span`,{className:I.switchKnob})})]}),A.show&&(0,m.jsxs)(`div`,{className:I.rdoRow,"data-testid":`billing-livecost-position`,children:[(0,m.jsx)(`span`,{className:I.rdoLabel,children:t(`liveCostBarPosition`)}),(0,m.jsx)(si,{liveCostPrefs:A,onLiveCostPrefs:ae,t})]})]}),(0,m.jsx)(`div`,{className:I.setCell,"data-testid":`billing-site-list-setting`,children:(0,m.jsxs)(`div`,{className:I.setCardHead,children:[(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`siteListDisplay`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`siteListDisplayHint`)})]}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":ne.hideUnidentified,"aria-label":t(`siteListDisplay`),"data-testid":`billing-site-hide-unidentified`,className:y(I.switch,ne.hideUnidentified&&I.switchOn),onClick:()=>ie({hideUnidentified:!ne.hideUnidentified}),children:(0,m.jsx)(`span`,{className:I.switchKnob})})]})})]})}),(0,m.jsx)(`section`,{className:I.setCard,"data-testid":`billing-display-setting`,children:(0,m.jsxs)(`div`,{className:I.setGrid2,children:[(0,m.jsxs)(`div`,{className:I.setCell,"data-testid":`billing-float-setting`,children:[(0,m.jsx)(`div`,{className:I.setCardHead,children:(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`floatWindow`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`floatWindowHint`)})]})}),(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`floatMode`)}),(0,m.jsxs)(`div`,{className:I.ctlGroup,"data-testid":`billing-float-mode`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,E.mode===`combined`&&I.floatModeBtnOn),"data-testid":`billing-float-mode-combined`,onClick:()=>D({mode:`combined`,targets:E.targets}),children:t(`floatModeCombined`)}),(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,E.mode===`subscription`&&I.floatModeBtnOn),"data-testid":`billing-float-mode-subscription`,onClick:()=>D({mode:`subscription`,targets:E.targets}),children:t(`floatModeSubscription`)})]})]}),E.mode===`subscription`&&(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`floatTargets`)}),(0,m.jsxs)(`span`,{className:I.ctlGroup,"data-testid":`billing-float-targets`,children:[De.map(e=>{let t=E.targets.includes(e.id);return(0,m.jsxs)(`label`,{className:I.floatTarget,children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:t,"data-testid":`billing-float-target-${e.id}`,onChange:()=>D({mode:`subscription`,targets:t?E.targets.filter(t=>t!==e.id):[...E.targets,e.id]})}),(0,m.jsx)(`span`,{className:I.floatTargetLabel,children:e.label})]},e.id)}),De.length===0&&(0,m.jsx)(`span`,{className:I.setCardDesc,children:t(`floatNoTargetsHint`)})]})]})]})]}),(0,m.jsxs)(`div`,{className:I.setCell,"data-testid":`billing-card-setting`,children:[(0,m.jsx)(`div`,{className:I.setCardHead,children:(0,m.jsxs)(`div`,{className:I.setCardMeta,children:[(0,m.jsx)(`h3`,{className:I.setCardTitle,children:t(`cardDisplay`)}),(0,m.jsx)(`p`,{className:I.setCardDesc,children:t(`cardDisplayHint`)})]})}),(0,m.jsxs)(`div`,{className:I.ctlCol,children:[(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`cardMetric`)}),(0,m.jsxs)(`div`,{className:I.ctlGroup,"data-testid":`billing-card-metric`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,O.metric===`money`&&I.floatModeBtnOn),"data-testid":`billing-card-money`,onClick:()=>te({...O,metric:`money`}),children:t(`cardMetricMoney`)}),(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,O.metric===`tokens`&&I.floatModeBtnOn),"data-testid":`billing-card-tokens`,onClick:()=>te({...O,metric:`tokens`}),children:t(`cardMetricTokens`)})]})]}),(0,m.jsxs)(`div`,{className:I.ctlRow,children:[(0,m.jsx)(`span`,{className:I.ctlLabel,children:t(`cardSpan`)}),(0,m.jsx)(`div`,{className:I.ctlGroup,"data-testid":`billing-card-span`,children:[[`day`,`cardSpanDay`],[`week`,`cardSpanWeek`],[`month`,`cardSpanMonth`]].map(([e,n])=>(0,m.jsx)(`button`,{type:`button`,className:y(I.floatModeBtn,O.span===e&&I.floatModeBtnOn),"data-testid":`billing-card-span-${e}`,"aria-pressed":O.span===e,onClick:()=>te({...O,span:e}),children:t(n)},e))})]})]})]})]})}),(0,m.jsx)(ii,{userPrices:r,onUserPrices:i,t}),(0,m.jsx)(vn,{t,version:e.pluginVersion})]}),N===`trends`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-trends`,children:[(0,m.jsxs)(`section`,{className:y(I.ubCard,I.trendPanel),"data-testid":`billing-panel-trend`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`trend`)}),v(`billing.dashboard.decor`,{position:`trend`}),(0,m.jsxs)(`span`,{className:I.ubCardControlGroup,children:[(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":t(`trend`),children:[7,30].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,de===e&&I.rangeButtonActive),"aria-pressed":de===e,"data-testid":`billing-trend-${e}d`,onClick:()=>{fe(e)},children:t(e===7?`trend7d`:`trend30d`)},e))}),(0,m.jsx)(`span`,{className:I.rangeToggle,role:`group`,"aria-label":t(`trendMetric`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(I.rangeButton,se===e&&I.rangeButtonActive),"aria-pressed":se===e,"data-testid":`billing-trend-metric-${e}`,onClick:()=>{ce(e)},children:t(e===`cost`?`trendMetricCost`:`trendMetricTokens`)},e))})]}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:G})]}),(0,m.jsx)(ln,{data:wt,models:Wt,currency:u,metric:se,t})]}),_.length>0&&(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-rounds`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`rounds`)}),nt.length>0&&(0,m.jsxs)(`span`,{className:I.ubTagError,"data-testid":`billing-rounds-flag-count`,children:[nt.length,` `,t(`anomaly`)]})]}),(0,m.jsx)(`p`,{className:I.ubCardSub,children:t(`roundsHint`).replace(`{count}`,String(_.length))}),(0,m.jsx)(Sn,{rounds:_,flags:nt,currency:u,t})]}),e.byTier!==void 0&&(()=>{let e=W.peak+W.offPeak;if(e<=0)return null;let n=W.peak/e*100;return(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-share`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`peakShare`)}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:t(`peakSharePerCall`)})]}),(0,m.jsxs)(`div`,{className:I.shareTrack,"data-testid":`billing-share-track`,children:[(0,m.jsx)(`div`,{className:y(I.shareSeg,I.shareSegPeak),style:{width:`${n}%`}}),(0,m.jsx)(`div`,{className:y(I.shareSeg,I.shareSegOff),style:{width:`${100-n}%`}})]}),(0,m.jsxs)(`div`,{className:I.shareLegend,children:[(0,m.jsxs)(`span`,{className:I.shareItem,children:[(0,m.jsx)(`span`,{className:I.shareDot,style:{background:`var(--ds-blue)`}}),t(`peak`),(0,m.jsxs)(`span`,{className:I.shareValue,"data-testid":`billing-share-peak`,children:[B(W.peak),` · `,n.toFixed(1),`%`]})]}),(0,m.jsxs)(`span`,{className:I.shareItem,children:[(0,m.jsx)(`span`,{className:I.shareDot,style:{background:`color-mix(in srgb, var(--ds-blue) 30%, var(--dsb-3))`}}),t(`offPeak`),(0,m.jsxs)(`span`,{className:I.shareValue,"data-testid":`billing-share-offpeak`,children:[B(W.offPeak),` · `,(100-n).toFixed(1),`%`]})]})]}),rt>0&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-share-savings`,children:t(`offPeakSavings`).replace(`{amount}`,B(rt))})]})})()]}),N===`providers`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-providers`,children:[Et.length>0&&(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-relay-quota`,children:[(0,m.jsx)(`div`,{className:I.panelHead,children:(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`panelRelayQuota`)})}),(0,m.jsx)(`div`,{className:I.providerGroupList,"data-testid":`billing-relay-quotas`,children:Et.map(e=>(0,m.jsxs)(`div`,{className:I.siteRow,"data-testid":`billing-relay-quota`,children:[(0,m.jsxs)(`span`,{className:I.siteRowName,children:[(0,m.jsx)(`span`,{className:y(I.siteKindTag,zr[e.kind]),children:Rr(e.kind,t)}),(0,m.jsx)(`span`,{className:I.siteRowTitle,children:e.origin})]}),(0,m.jsxs)(`span`,{className:I.siteRowMeta,children:[e.balance!==void 0&&(0,m.jsxs)(`span`,{className:I.siteRowCost,children:[t(`relayBalance`),` `,e.balance.toFixed(2)]}),(e.windows?.length??0)>0?e.windows?.map(e=>{let n=e.remainingPercent<20;return(0,m.jsxs)(`span`,{className:y(I.siteRowCalls,n&&I.siteRowCallsLow),children:[t(`relayWindowUsed`),` `,e.usedPercent,`%`]},e.kind)}):(0,m.jsx)(`span`,{className:I.siteRowCalls,children:t(`relayNoQuota`)})]})]},e.route))})]}),(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-providers`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`providerBilling`)}),v(`billing.dashboard.decor`,{position:`models`}),(0,m.jsx)(`span`,{className:I.panelHint,children:e.updatedAt===void 0?``:`${t(`lastUpdated`)} ${Vr(e.updatedAt)}`})]}),oe&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-subscriptions-stale`,children:t(`subscriptionsStale`)}),(0,m.jsxs)(`div`,{className:I.providerCtlRow,"data-testid":`billing-provider-controls`,children:[(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,disabled:Ot.length===0,onClick:At,children:t(kt?`collapseAll`:`expandAll`)}),(0,m.jsxs)(`span`,{className:I.providerTodayToggle,children:[(0,m.jsx)(`span`,{children:t(`todayOnly`)}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":R,"data-testid":`billing-provider-today-toggle`,className:y(I.switch,R&&I.switchOn),onClick:Re,children:(0,m.jsx)(`span`,{className:I.switchKnob})})]})]}),Dt.length===0?(0,m.jsx)(`div`,{className:I.emptyRow,"data-testid":`billing-provider-empty`,children:t(R?`todayNoConsumption`:`noData`)}):(0,m.jsx)(`div`,{className:I.providerGroupList,"data-testid":`billing-provider-groups`,children:Dt.map(e=>{let n=e.models.length>0||e.subscriptions.length>0,r=n&&Pe.has(e.id);return(0,m.jsxs)(`div`,{className:I.providerGroup,"data-testid":`billing-provider-group`,children:[(0,m.jsxs)(`div`,{className:y(I.providerGroupHead,n&&I.providerGroupCollapsible),"data-testid":`billing-provider-group-head`,"aria-expanded":n?r:void 0,role:n?`button`:void 0,tabIndex:n?0:void 0,onClick:n?()=>{L(e.id)}:void 0,onKeyDown:n?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),L(e.id))}:void 0,children:[(0,m.jsxs)(`span`,{className:I.providerGroupTitle,children:[(0,m.jsx)(`span`,{className:y(I.healthDot,e.dot),"aria-hidden":`true`}),(()=>{let n=H(e.name),r=e.channelKind===`direct`?Gn(n):void 0,i=e.channelKind===`direct`?t(`directTag`):e.channelKind===`site`?t(`relayTag`):e.channelKind===`unknown`?t(`unknownTag`):void 0;return(0,m.jsxs)(m.Fragment,{children:[i!==void 0&&(0,m.jsx)(`span`,{className:y(I.kindBadge,e.channelKind===`direct`&&I.kindBadgeDirect,e.channelKind===`site`&&I.kindBadgeRelay,e.channelKind===`unknown`&&I.kindBadgeUnknown),"data-testid":`billing-kind-badge`,children:i}),e.channelKind!==`unknown`&&(0,m.jsx)(`span`,{className:I.providerGroupName,children:r??n})]})})(),e.subscriptions.length>0&&(0,m.jsxs)(`span`,{className:I.providerGroupBadge,"data-testid":`billing-provider-sub-count`,children:[e.subscriptions.length,` `,t(`planCountUnit`)]})]}),(0,m.jsxs)(`span`,{className:I.providerGroupMeta,children:[(0,m.jsxs)(`span`,{className:I.providerGroupCost,"data-testid":`billing-provider-cost`,children:[(0,m.jsx)(`span`,{className:I.providerGroupCostLabel,children:t(`cost`)}),e.channelKind===`unknown`?(0,m.jsx)(`span`,{className:I.na,children:`—`}):(0,m.jsx)(`span`,{className:I.providerGroupCostValue,children:B(ei(e))})]}),!ot(e)&&e.balance!==void 0?(0,m.jsxs)(`span`,{className:I.providerGroupBalance,"data-testid":`billing-provider-balance`,children:[(0,m.jsx)(`span`,{className:I.providerGroupBalanceLabel,children:t(`balance`)}),st(e.balance)]}):(0,m.jsx)(`span`,{className:I.providerGroupBalance,"aria-hidden":`true`}),br(e.name)===void 0?(0,m.jsx)(`span`,{className:I.providerGroupRecharge,"aria-hidden":`true`}):(0,m.jsx)(`a`,{className:I.providerGroupRecharge,"data-testid":`billing-group-recharge`,href:br(e.name),target:`_blank`,rel:`noreferrer`,title:t(`rechargeHint`),"aria-label":`${H(e.name)} ${t(`recharge`)}`,onClick:e=>{e.stopPropagation()},children:t(`recharge`)})]})]}),r&&(0,m.jsxs)(m.Fragment,{children:[e.channelKind===`unknown`&&(0,m.jsx)(`p`,{className:I.unknownHint,"data-testid":`billing-unknown-hint`,children:t(`unknownChannelHint`)}),e.models.length>0&&(0,m.jsx)(`div`,{className:y(I.tableScroll,I.modelTableScroll),"data-testid":`billing-table-scroll`,children:(0,m.jsxs)(`table`,{className:I.modelTable,children:[jt,(0,m.jsx)(`tbody`,{children:e.models.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:Nt(e)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:I.numCol,children:J(e.input)}),(0,m.jsx)(`td`,{className:I.numCol,children:J(e.output)}),(0,m.jsx)(`td`,{className:I.numCol,children:Ut(e.cacheHitRate)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.plan?(0,m.jsxs)(`span`,{className:I.planTag,children:[e.estimated>0?(0,m.jsxs)(`span`,{children:[`≈`,B(e.estimated)]}):null,(0,m.jsx)(`span`,{className:I.planTagBadge,"data-testid":`billing-plan-badge`,children:t(`subscriptionTag`)})]}):e.actual===void 0?e.estimated>0?(0,m.jsxs)(`span`,{title:t(`cellEstimateHint`),children:[`≈`,B(e.estimated)]}):(0,m.jsx)(`span`,{className:I.na,children:`—`}):(()=>{let t=e.officialCost,n=e.actual-t;return t>0&&n>0?(0,m.jsxs)(`span`,{className:I.bucketCost,children:[(0,m.jsx)(`span`,{className:I.bucketOfficial,children:B(t)}),(0,m.jsx)(`span`,{className:I.bucketSep,children:`/`}),(0,m.jsx)(`span`,{className:I.bucketThird,children:B(n)})]}):B(e.actual)})()})]},e.key))})]})}),e.subscriptions.length>0&&(0,m.jsx)(`div`,{className:I.subscriptionGrid,"data-testid":`billing-subscriptions-grid`,children:e.subscriptions.map(e=>{let n=Fr(e.status,t);return(0,m.jsxs)(`div`,{className:I.subscriptionCard,"data-testid":`billing-subscription-card`,children:[(0,m.jsxs)(`div`,{className:I.subscriptionHead,children:[(0,m.jsx)(`span`,{className:I.subscriptionName,children:H(e.displayName)}),e.planType===`code`&&(()=>{let n=Le(e.provider),r=n===void 0?void 0:t(`subscriptionFeePerMonth`).replace(`{amount}`,n.currency===`USD`?`$${n.amount}`:`¥${n.amount}`);return(0,m.jsxs)(`span`,{className:I.subscriptionPlan,"data-kind":`code`,children:[r??(e.subscriptionAmount!==void 0&&e.subscriptionAmount>0?t(`subscriptionFeePerMonth`).replace(`{amount}`,B(e.subscriptionAmount)):t(`planTypeCode`)),n?.label!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionTier,"data-testid":`billing-tier-${e.provider}`,children:n.label}),n!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionAuto,"data-testid":`billing-auto-${e.provider}`,children:t(`subscriptionAutoDetect`)})]})})(),e.planType===`token`&&(0,m.jsx)(`span`,{className:I.subscriptionPlan,"data-kind":`token`,children:t(`planTypeToken`)}),e.plan!==void 0&&(0,m.jsx)(`span`,{className:I.subscriptionPlan,children:e.plan})]}),n!==``&&(0,m.jsx)(`div`,{className:I.subscriptionStatus,children:n}),e.windows.length===0&&n===``&&(0,m.jsx)(`div`,{className:I.subscriptionStatus,children:t(`subscriptionNoApi`)}),e.windows.map(e=>(0,m.jsx)(Ir,{window:e,t},e.kind))]},e.provider)})})]})]},e.id)})})]}),(0,m.jsxs)(`div`,{className:I.exportBar,"data-testid":`billing-export-bar`,role:`group`,"aria-label":t(`export`),children:[(0,m.jsx)(`span`,{className:I.exportLabel,children:t(`export`)}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-day`,onClick:()=>{Zt(Xt(`usage-daily`,`csv`,Object.keys(M)),Kt(M),`text/csv`)},children:t(`exportCsvDay`)}),e.bySession!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-sessions`,onClick:()=>{Zt(Xt(`usage-sessions`,`csv`,Object.keys(M)),Yt(e.bySession??[]),`text/csv`)},children:t(`exportCsvSession`)}),e.bySite!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-sites`,onClick:()=>{Zt(Xt(`usage-sites`,`csv`,Object.keys(M)),qt(e.bySite??{}),`text/csv`)},children:t(`exportCsvSite`)}),(0,m.jsx)(`button`,{type:`button`,className:I.exportButton,"data-testid":`billing-export-json`,onClick:()=>{Zt(Xt(`usage-stats`,`json`,Object.keys(M)),JSON.stringify(e,null,2),`application/json`)},children:t(`exportJson`)})]}),e.bySession!==void 0&&(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-sessions`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`sessions`)}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:e.bySession.length>20?t(`sessionOverflow`).replace(`{limit}`,`20`).replace(`{total}`,String(e.bySession.length)):`${e.bySession.length}`})]}),(e.staleLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:I.staleNotice,"data-testid":`billing-sessions-stale`,children:t(`staleLedgerNotice`).replace(`{count}`,String(e.staleLedgerSessions))}),(0,m.jsx)(`div`,{className:I.ubTablewrap,"data-testid":`billing-sessions-table`,children:(0,m.jsxs)(`table`,{className:I.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:t(`sessionTitle`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`calls`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`actual`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`lastActive`)})]})}),(0,m.jsxs)(`tbody`,{children:[Ne.length===0&&(0,m.jsx)(`tr`,{children:(0,m.jsx)(`td`,{colSpan:4,className:I.emptyRow,children:t(`noData`)})}),Ne.slice(0,20).map(e=>{let n=e.children!==void 0,r=n&&Ae.has(e.id),i=e=>(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:I.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:I.numCol,children:B(e.cost)}),(0,m.jsx)(`td`,{className:I.numCol,children:e.lastActive>0?`${q(e.lastActive)} ${Vr(e.lastActive)}`:`—`})]});return(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{className:n?I.sessionGroupRow:void 0,"aria-expanded":n?r:void 0,tabIndex:n?0:void 0,onClick:n?()=>{Me(e.id)}:void 0,onKeyDown:n?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Me(e.id))}:void 0,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsxs)(`span`,{className:I.modelName,children:[e.title??`${t(`sessionUntitled`)} · ${e.id.slice(0,8)}`,(e.mergedCount??1)>1?` ×${e.mergedCount}`:``]}),e.stale===!0&&(0,m.jsx)(`span`,{className:y(I.ubTag,I.ubTagNeutral),"data-testid":`billing-session-stale`,children:t(`sessionStaleBadge`)})]}),i(e)]}),r&&e.children?.map(e=>(0,m.jsxs)(`tr`,{className:I.sessionChildRow,children:[(0,m.jsx)(`td`,{children:(0,m.jsx)(`span`,{className:I.modelProvider,children:e.id.slice(0,8)})}),i(e)]},e.id))]},e.id)})]})]})})]})]}),N===`token`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-token`,children:[(0,m.jsx)(rn,{stats:e,trendDays:de,onTrendDays:fe,models:Wt,money:B,t}),e.perf!==void 0&&(0,m.jsxs)(`section`,{className:I.panel,"data-testid":`billing-panel-perf`,children:[(0,m.jsxs)(`div`,{className:I.panelHead,children:[(0,m.jsx)(`h3`,{className:I.panelTitle,children:t(`perfTitle`)}),(0,m.jsx)(`span`,{className:I.panelHint,children:t(`perfHint`)})]}),(0,m.jsx)(hn,{perf:e.perf,models:Wt,t})]})]}),N===`pricing`&&(0,m.jsxs)(`div`,{className:I.tabPanel,"data-testid":`billing-tab-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:I.ubAlert,role:`note`,children:[(0,m.jsxs)(`div`,{className:I.ubAlertLeft,children:[(0,m.jsxs)(`span`,{className:I.ubRate,"data-testid":`billing-rate`,children:[t(`todayRate`),` 1 USD = `,K(z.rate)]}),(0,m.jsx)(`span`,{className:y(I.ubTag,z.live?I.ubTagSuccess:I.ubTagNeutral),children:z.live?t(`rateLive`):t(`rateBuiltin`)}),Ge>0&&(0,m.jsxs)(`span`,{className:I.ubTag,"data-testid":`billing-pricing-synced`,children:[t(`pricingSyncedAt`),` `,new Date(Ge).toLocaleTimeString(V===`zh`?`zh-CN`:`en-US`,{hour:`2-digit`,minute:`2-digit`})]}),(0,m.jsx)(`button`,{type:`button`,className:I.heatmapRangeButton,"data-testid":`billing-pricing-sync`,disabled:He,onClick:We,children:t(He?`pricingSyncing`:`pricingSyncNow`)})]}),(0,m.jsx)(`p`,{className:I.ubAlertNote,children:t(`pricingTip`)})]}),(0,m.jsxs)(`section`,{className:I.ubCard,"data-testid":`billing-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:I.ubCardHead,children:[(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`pricing`)}),(0,m.jsx)(`span`,{className:I.ubCardSub,children:t(`pricingUnit`)}),(0,m.jsx)(`input`,{className:I.ubSearch,type:`search`,value:qe,placeholder:t(`pricingSearch`),"aria-label":t(`pricingSearch`),"data-testid":`billing-pricing-search`,onChange:e=>{Je(e.target.value)}})]}),(0,m.jsx)(`div`,{className:I.ubTablewrap,children:(0,m.jsxs)(`table`,{className:I.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:t(`thModel`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`thInputMiss`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`thInputHit`)}),(0,m.jsx)(`th`,{className:I.numCol,children:t(`output`)}),(0,m.jsx)(`th`,{className:I.numCol,colSpan:2,children:t(`band`)})]})}),(0,m.jsx)(`tbody`,{children:In(It(),qe).map(e=>{let n=e.price.input>0||e.price.output>0;return(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:(0,m.jsxs)(`span`,{className:I.ubModel,children:[(()=>{let n=Nn(dt(Ze,ut(e.key,et)),tt);if(n===null)return null;let r=Ye.includes(e.key),i=`${e.name} · ${t(n===`peak`?`peak`:`offPeak`)} · ${t(`bandPinHint`)}`;return(0,m.jsx)(`button`,{type:`button`,className:y(I.bandDot,I[n],r&&I.bandDotOn),"data-testid":`billing-band-dot`,"aria-pressed":r,"aria-label":i,title:i,onClick:()=>{Xe(Te(e.key)),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.pinned-pref`))}})})(),(0,m.jsxs)(`span`,{className:I.ubModelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:I.ubTagAlert,"data-testid":`billing-price-uncatalogued`,children:t(`uncatalogued`)}),e.promo!==void 0&&Pt(e.promo,Date.now())&&(0,m.jsx)(p.Tooltip,{label:[e.promo.note,e.promo.endsAtMs===void 0?t(`promoOpenEnded`):t(`promoUntil`,{date:new Date(e.promo.endsAtMs).toLocaleDateString()})].filter(Boolean).join(` · `),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:I.ubTagPromo,"data-testid":`billing-price-promo`,children:t(`promoBadge`)})})]})]})}),(0,m.jsx)(`td`,{className:I.numCol,children:n?U(e.price.input,e.price.currency):(0,m.jsx)(`span`,{className:I.na,children:`—`})}),(0,m.jsx)(`td`,{className:I.numCol,children:n?U(e.price.cacheHit,e.price.currency):(0,m.jsx)(`span`,{className:I.na,children:`—`})}),(0,m.jsx)(`td`,{className:I.numCol,children:n?U(e.price.output,e.price.currency):(0,m.jsx)(`span`,{className:I.na,children:`—`})}),n&&e.price.offPeak!==void 0&&e.peakHours!==void 0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:I.numCol,children:(0,m.jsxs)(`span`,{className:I.ubChipPeak,children:[(0,m.jsx)(`span`,{className:I.ubChipLabel,children:e.tierSemantics===`latency`?t(`ubStd`):t(`ubPeak`)}),(0,m.jsxs)(`span`,{className:I.num,children:[U(e.price.input,e.price.currency),`/`,U(e.price.output,e.price.currency)]})]})}),(0,m.jsx)(`td`,{className:I.numCol,children:(0,m.jsxs)(`span`,{className:I.ubChipOff,children:[(0,m.jsx)(`span`,{className:I.ubChipLabel,children:e.tierSemantics===`latency`?`Flex`:t(`ubOff`)}),(0,m.jsxs)(`span`,{className:I.num,children:[U(e.price.offPeak.input,e.price.currency),` / `,U(e.price.offPeak.output,e.price.currency)]})]})})]}):(0,m.jsx)(`td`,{className:I.numCol,colSpan:2,children:n?(0,m.jsx)(`span`,{className:I.flatTag,children:t(`flat`)}):(0,m.jsx)(`span`,{className:I.na,children:`—`})})]}),(e.extraRows??[]).map(t=>(0,m.jsxs)(`tr`,{className:I.ubExtraRow,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:I.ubExtraName,children:Fn(t.label,V)}),t.note!==void 0&&(0,m.jsx)(`span`,{className:I.ubExtraNote,children:Fn(t.note,V)})]}),(0,m.jsx)(`td`,{className:I.numCol,children:t.input===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):U(t.input,e.price.currency)}),(0,m.jsx)(`td`,{className:I.numCol,children:(0,m.jsx)(`span`,{className:I.na,children:`—`})}),(0,m.jsx)(`td`,{className:I.numCol,children:t.output===void 0?(0,m.jsx)(`span`,{className:I.na,children:`—`}):U(t.output,e.price.currency)}),(0,m.jsx)(`td`,{className:I.numCol,colSpan:2,children:(0,m.jsx)(`span`,{className:I.na,children:`—`})})]},`${e.key}:${t.label}`))]},e.key)})})]})})]}),(0,m.jsxs)(`section`,{className:I.ubCard,children:[(0,m.jsx)(`div`,{className:I.ubCardHead,children:(0,m.jsx)(`h3`,{className:I.ubCardTitle,children:t(`pricingNotes`)})}),(0,m.jsxs)(`ul`,{className:I.ubNotes,children:[(0,m.jsxs)(`li`,{className:I.ubNotesItem,children:[(0,m.jsx)(`span`,{className:I.ubNotesTerm,children:t(`cacheHit`)}),(0,m.jsx)(`span`,{className:I.ubNotesDesc,children:t(`noteCache`)})]}),(0,m.jsxs)(`li`,{className:I.ubNotesItem,children:[(0,m.jsx)(`span`,{className:I.ubNotesTerm,children:t(`peakBand`)}),(0,m.jsx)(`span`,{className:I.ubNotesDesc,children:t(`noteBand`)})]}),(0,m.jsxs)(`li`,{className:I.ubNotesItem,children:[(0,m.jsx)(`span`,{className:I.ubNotesTerm,children:t(`pricingSource`)}),(0,m.jsx)(`span`,{className:I.ubNotesDesc,children:t(`noteSource`)})]})]})]})]}),v(`billing.dashboard.decor`,{position:`footer`})]}),(0,m.jsxs)(`footer`,{className:I.modalFooter,"data-testid":`billing-footer`,children:[(0,m.jsx)(`span`,{children:t(`footer`)}),(0,m.jsx)(`span`,{children:t(`footerCredit`).replace(`{version}`,e.pluginVersion===void 0?`—`:`v${e.pluginVersion}`)})]})]})})}let oi=[`below`,`above`,`toolbar`];function si({liveCostPrefs:e,onLiveCostPrefs:t,t:n}){let[r,i]=(0,d.useState)(!1),a={below:n(`liveCostBarPosBelow`),above:n(`liveCostBarPosAbove`),toolbar:n(`liveCostBarPosToolbar`)},o=oi.map(e=>({id:e,label:a[e]}));return(0,m.jsx)(p.Menu,{open:r,align:`end`,portal:!0,compact:!0,items:o,selectedId:e.position,onSelect:n=>{i(!1);let r=oi.find(e=>e===n);r!==void 0&&t({...e,position:r})},onClose:()=>{i(!1)},anchor:(0,m.jsxs)(`button`,{type:`button`,className:I.rdoSelect,"data-testid":`billing-livecost-position-select`,"aria-haspopup":`menu`,"aria-expanded":r,onClick:()=>{i(!r)},children:[(0,m.jsx)(`span`,{children:a[e.position]}),(0,m.jsx)(`span`,{className:y(I.rdoChevron,r&&I.rdoChevronOpen),"aria-hidden":!0,children:$n?(0,m.jsx)($n,{}):null})]})})}function ci(e){let{t,checkModels:n,publishCosts:r,registerOpen:i,renderSlot:a,useStore:o,actions:s}=e,[c,l]=(0,d.useState)(Ur),[u,f]=(0,d.useState)(nr),[p,h]=(0,d.useState)([]),[g,_]=(0,d.useState)(void 0),[v,y]=(0,d.useState)([]),[b,x]=(0,d.useState)(!1),[S,C]=(0,d.useState)([]),[w,E]=(0,d.useState)(()=>de()),[D,ne]=(0,d.useState)(()=>Ce()),k=(0,d.useCallback)(e=>{ne(e),we(e),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.language-pref`))},[]),re=(0,d.useCallback)(e=>{E(e),fe(e),window.dispatchEvent(new CustomEvent(ue))},[]),[ie,A]=(0,d.useState)(()=>T()),se=(0,d.useCallback)(e=>{A(e),ee(e)},[]),[ce,N]=(0,d.useState)(()=>ae()),pe=(0,d.useCallback)(e=>{N(e),oe(e)},[]),[me,he]=(0,d.useState)(()=>le()),ge=(0,d.useCallback)(e=>{he(e),M(e),window.dispatchEvent(new CustomEvent(j))},[]),[_e,ve]=(0,d.useState)(()=>O()),ye=(0,d.useCallback)(e=>{ve(e),te(e)},[]),[be,xe]=(0,d.useState)(()=>{let e=Ee();return B(e),e}),Se=(0,d.useCallback)(e=>{xe(e),B(e),De(e)},[]),P=(0,d.useMemo)(()=>Cr(c),[c,be]),Te=D,F=(0,d.useCallback)((e,n)=>{let r=(Te===`en`?Fe:Pe)[e]??t(e);if(n===void 0)return r;let i=r;for(let[e,t]of Object.entries(n))i=i.replaceAll(`{${e}}`,String(t));return i},[Te,t]),[Oe,ke]=(0,d.useState)(!1),Ae=(0,d.useCallback)(()=>{ke(!1)},[]),je=(0,d.useCallback)(()=>{Wr().then(e=>{e!==null&&l(e)}),Yr().then(({balances:e,reconcile:t})=>{e.length>0&&h(e),_(t)}),Xr().then(e=>{e.length>0&&y(e),x(!1)}).catch(()=>{x(!0)}),Zr().then(e=>{C(e)}).catch(()=>{})},[]),Me=(0,d.useCallback)(()=>{je(),qr(),ke(!0)},[je]);(0,d.useEffect)(()=>{je(),qr()},[je]);let[I,Ne]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{Ne(!document.hidden),document.hidden||(je(),qr())};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[je]),(0,d.useEffect)(()=>{if(!I)return;let e=setInterval(()=>{je(),qr()},Oe?Br:3e5);return()=>{clearInterval(e)}},[je,Oe,I]),(0,d.useEffect)(()=>{let e=!0;return n().then(t=>{e&&(f(t),Xe(t.catalog??[]))}),()=>{e=!1}},[n]);let L=q(),R=Object.entries(P.byDay).filter(([e])=>e.startsWith(L.slice(0,7))).reduce((e,[,t])=>e+t.cost,0),Ie=P.byDay[L]?.cost??0,Le=jr(P.byDay,L),Re=(0,d.useMemo)(()=>Ar(P.byDay).map(e=>{let t=P.byDay[e.date];return{date:e.date,cost:e.cost,tokens:t===void 0?0:kr(t)}}),[P.byDay]),ze=Object.entries(P.byDay).filter(([e])=>e.startsWith(L.slice(0,7))).reduce((e,[,t])=>e+kr(t),0),Be=(()=>{let e=P.byDay[L];return e===void 0?0:kr(e)})(),Ve=jr(P.byDay,L,kr),z=o(e=>e.enabled),He=o(e=>e.amount),Ue=o(e=>e.tierAlertDays),We=o(e=>e.lastTierSwitchAt),[Ge,Ke]=(0,d.useState)(()=>Jn()),[V,H]=(0,d.useState)(null),[qe,Je]=(0,d.useState)(null),[Ye,Ze]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{if(!Ge.enabled)return;let e=setInterval(()=>Ze(Date.now()),Br);return()=>{clearInterval(e)}},[Ge.enabled]);let Qe=(0,d.useCallback)(e=>{Ke(e),Yn(e)},[]),et=v.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),tt=ut(c.byTurn?.[0]?.model,et),nt=(0,d.useCallback)(()=>{Je({entering:U(Date.now())===`peak`?`offPeak`:`peak`,atMs:Date.now()+18e4,channel:tt})},[tt]),W=He>0?He:c.budget??0,rt=z&&W>0?R/W>=1?`over`:R/W>=.8?`warn`:`none`:`none`,it=(0,d.useCallback)(()=>{let e=!z;s.setEnabled(e),e&&typeof Notification<`u`&&Notification.permission==="default"&&Notification.requestPermission()},[s,z]);(0,d.useEffect)(()=>{if(!z||W<=0)return;let e=R/W*100,t=tr.filter(t=>e>=t&&Ue?.[String(t)]!==L);if(t.length===0)return;let n=t[t.length-1]??100;if(s.markTierAlerted(t,L),!wr())return;let r=F(`budgetTierBody`).replace(`{cost}`,K(R)).replace(`{budget}`,K(W)).replace(`{pct}`,String(n));Er(`budget:${n}:${L}`,()=>{new Notification(F(`budget`),{body:r})})},[z,W,R,Ue,L,s,F]),(0,d.useEffect)(()=>{let e=Xn(Ye,Ge,We,tt);if(e===null||(s.markTierSwitchAlerted(e.atMs),H(e),!Ge.webNotify||!wr()))return;let t=Math.max(1,Math.round((e.atMs-Ye)/6e4)),n=F(e.entering===`peak`?`peakAlertTitlePeak`:`peakAlertTitleOff`),r=F(e.channel===`zhipu-coding-plan`?e.entering===`peak`?`tierAlertEnterPeakZhipu`:`tierAlertEnterOffZhipu`:e.entering===`peak`?`tierAlertEnterPeak`:`tierAlertEnterOff`).replace(`{minutes}`,String(t));Er(`peak:${e.atMs}`,()=>{new Notification(n,{body:r})})},[Ye,We,Ge,tt,s,F]);let at=o(e=>e.lastBalanceAlertDay),ot=P.lowBalanceThreshold??50,st=(0,d.useMemo)(()=>{if(p.length===0)return;let e=xr(P.byDay,L),t=$e().rate;for(let n of p){if(n.totalBalance===void 0||n.error!==void 0)continue;let r=n.currency===`USD`?n.totalBalance*t:n.totalBalance;if(r>=ot)continue;let i=e>0?Math.floor(r/e):void 0;return{name:n.displayName,cny:r,days:i}}},[p,P.lowBalanceThreshold,P.byDay,L]);(0,d.useEffect)(()=>{if(st===void 0||at===L||(s.markBalanceAlerted(L),!wr()))return;let e=F(`balanceLowBody`).replace(`{name}`,st.name).replace(`{balance}`,K(st.cny)).replace(`{days}`,st.days===void 0?`—`:String(st.days));Er(`balance:${L}`,()=>{new Notification(F(`balance`),{body:e})})},[st,at,L,s,F]);let ct=(0,d.useMemo)(()=>{let e=L.slice(0,7),t=new Map;for(let[n,r]of Object.entries(P.byDayModels??{}))if(n.startsWith(e))for(let[e,n]of Object.entries(r)){if(n.cost<=0)continue;let r=Mt(e).provider,i=P.byModel?.[e]?.plan===!0,a=t.get(r)??{cost:0,plan:i};a.cost+=n.cost,i||(a.plan=!1),t.set(r,a)}let n,r;for(let e of t){let t=e[1].plan?r:n;(t===void 0||e[1].cost>t[1].cost)&&(e[1].plan?r=e:n=e)}let i=e=>{let t=p.find(t=>$(t.provider)===$(e));if(t===void 0||t.totalBalance===void 0){if(e===`Custom`){let e=p.filter(e=>e.totalBalance!==void 0&&e.error===void 0),t=e[0];return t!==void 0&&e.length===1?i(t.provider):void 0}return{text:t?.error===`unauthorized`?F(`balanceUnauthorized`):t?.error===`unreachable`||t?.error===`invalid`?F(`balanceUnreachable`):F(`balanceUnconfigured`),low:!1}}let n=t.currency===`USD`?`$${t.totalBalance.toFixed(2)}`:K(t.totalBalance),r=$e().rate;return{text:n,low:(t.currency===`USD`?t.totalBalance*r:t.totalBalance)<ot}},a=e=>{let t=v.find(t=>t.displayName===e||cr(t.provider)===e);if(t===void 0||t.windows.length===0)return{text:F(`subscriptionNoApi`),low:!1};let n=t.windows.reduce((e,t)=>Math.min(e,t.remainingPercent),100);return{text:n<=0?F(`subscriptionExhausted`):F(`subscriptionRemaining`).replace(`{pct}`,String(n)),low:n<20}},o=n===void 0?void 0:i(n[0]);return{direct:n===void 0||o===void 0?void 0:{name:n[0],...o},sub:r===void 0?void 0:{name:r[0],...a(r[0])}}},[P.byDayModels,P.byModel,P.lowBalanceThreshold,p,v,L,F]),lt=(0,d.useMemo)(()=>{let e=P.total;return{input:e.input,output:e.output,cacheRead:e.cacheHit,cacheMiss:e.cacheMiss,calls:e.calls}},[P]);(0,d.useEffect)(()=>{r({todayCost:Ie,monthCost:R})},[Ie,R,r]),(0,d.useEffect)(()=>i(Me),[i,Me]);let dt=(0,d.useMemo)(()=>c.byTurn??[],[c.byTurn]);return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(ti,{...e,t:F,currency:w,onOpen:Me,monthCost:R,todayCost:Ie,weekCost:Le,days:Re,vendorStatus:ct,dash:lt,cardPrefs:_e,monthTokens:ze,todayTokens:Be,weekTokens:Ve,floatPrefs:ie,subscriptions:v,budgetPressure:rt}),Oe&&(0,m.jsx)(ai,{stats:P,t:F,onClose:Ae,userPrices:be,onUserPrices:Se,health:u,balances:p,...g===void 0?{}:{reconcile:g},quotas:v,relayQuotas:S,currency:w,onCurrency:re,language:D,onLanguage:k,turns:dt,renderSlot:a,budgetEnabled:z,budgetAmount:W,onToggleBudget:it,onBudgetAmount:s.setAmount,peakConfig:Ge,onPeakConfig:Qe,onPreviewPeak:nt,floatPrefs:ie,onFloatPrefs:se,cardPrefs:_e,onCardPrefs:ye,sitePrefs:ce,onSitePrefs:pe,liveCostPrefs:me,onLiveCostPrefs:ge,quotasStale:b}),(V!==null||qe!==null)&&(0,m.jsx)(Zn,{hit:V??qe,config:Ge,t:F,onDismiss:()=>{H(null),Je(null)}})]})}function li(e,t){return t===void 0||e?.bySession===void 0?0:e.bySession.find(e=>e.id===t)?.cost??0}function ui(e,t){if(t===void 0||e?.byTurn===void 0)return 0;let n=0,r=-1;for(let i of e.byTurn)i.sessionId===t&&(r===-1||i.turn>r)&&(r=i.turn,n=i.cost);return n}function di(e,t=20){let n=[];for(let r of e)if(r.status===`ok`)for(let e of r.windows)e.remainingPercent>t||n.push({name:r.displayName,kind:e.kind,pct:e.remainingPercent});return n.sort((e,t)=>e.pct-t.pct).slice(0,3)}function fi(e,t){if(t===void 0||e?.byTurn===void 0)return;let n=-1,r;for(let i of e.byTurn)i.sessionId===t&&(n===-1||i.turn>n)&&(n=i.turn,r=i.model);return r}async function pi(){try{let e=await fetch(`/api/billing/usage-stats`);if(!e.ok)return null;let t=await e.text(),n=JSON.parse(t);if(typeof n!=`object`||!n)return null;let r=n;return{...Array.isArray(r.bySession)?{bySession:r.bySession}:{},...Array.isArray(r.byTurn)?{byTurn:r.byTurn}:{}}}catch{return null}}async function mi(){try{let e=await fetch(`/api/billing/subscriptions`);if(!e.ok)return[];let t=JSON.parse(await e.text());if(typeof t!=`object`||!t||!(`quotas`in t))return[];let n=t.quotas;return Array.isArray(n)?n:[]}catch{return[]}}function hi(e){switch(e){case`session`:return`subscriptionSession`;case`weekly`:return`subscriptionWeekly`;case`monthly`:return`subscriptionMonthly`;default:return`subscriptionBilling`}}function gi({hasBandPlan:e}){let[t,n]=(0,d.useState)(()=>he()),[r,i]=(0,d.useState)(()=>Date.now());if((0,d.useEffect)(()=>{let e=()=>{n(he())};window.addEventListener(me,e),window.addEventListener(`storage`,e);let t=setInterval(()=>{i(Date.now())},3e4);return()=>{window.removeEventListener(me,e),window.removeEventListener(`storage`,e),clearInterval(t)}},[]),t.length===0)return null;let a=Jn().leadMin*6e4,o=t.map(t=>({key:t,state:Nn(dt(r,ut(t,e)),a)})).filter(e=>e.state!==null);return o.length===0?null:(0,m.jsx)(`span`,{className:I.bandDots,"data-testid":`billing-pinned-dots`,children:o.map(e=>(0,m.jsx)(`span`,{className:y(I.bandDot,I.bandDotOn,I[e.state]),role:`img`,"aria-label":e.key,title:e.key},e.key))})}function _i(){let[e,t]=(0,d.useState)(()=>de());return(0,d.useEffect)(()=>{let e=()=>{t(de())};return window.addEventListener(ue,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(ue,e),window.removeEventListener(`storage`,e)}},[]),e}function vi(){let[e,t]=(0,d.useState)(()=>le().show),[n,r]=(0,d.useState)(()=>le().position);return(0,d.useEffect)(()=>{let e=()=>{t(le().show),r(le().position)};return window.addEventListener(j,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(j,e),window.removeEventListener(`storage`,e)}},[]),{visible:e,position:n}}function yi(e,t){let[n,r]=(0,d.useState)(null),[i,a]=(0,d.useState)([]),[o,s]=(0,d.useState)(()=>Date.now()),[c,l]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{l(!document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[]),(0,d.useEffect)(()=>{if(!c||!t)return;let e=!1,n=()=>{pi().then(t=>{!e&&t!==null&&r(t)}),mi().then(t=>{e||a(t)}),e||s(Date.now())};n();let i=setInterval(n,3e4);return()=>{e=!0,clearInterval(i)}},[e,c,t]);let u=(0,d.useMemo)(()=>li(n,e),[n,e]),f=(0,d.useMemo)(()=>ui(n,e),[n,e]),p=(0,d.useMemo)(()=>di(i),[i]),m=(0,d.useMemo)(()=>ut(fi(n,e),i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)),[n,e,i]);return{sessionCost:u,turnCost:f,tier:(0,d.useMemo)(()=>dt(o,m),[o,m]),chips:p,hasBandPlan:i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)}}function bi({sessionId:e,t}){let{visible:n,position:r}=vi(),{sessionCost:i,turnCost:a,tier:o,chips:s,hasBandPlan:c}=yi(e,n&&r!==`toolbar`),l=_i(),u=e=>K(Bt(e,l),l),d=i>0||a>0,f=o?.tier===`peak`;return!n||r===`toolbar`?null:(0,m.jsxs)(`span`,{className:r===`above`?y(I.feeBar,I.feeBarAbove):I.feeBar,"data-testid":`billing-live-cost-bar`,children:[(0,m.jsx)(gi,{hasBandPlan:c}),o!==null&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:f?I.feeChipPrimary:I.feeChipOff,"data-testid":`billing-live-tier`,children:t(f?`tierPeak`:`tierOff`)}),(0,m.jsx)(`span`,{className:I.feeCount,children:pt(o.nextSwitchInMs)}),(0,m.jsx)(`span`,{className:I.feeSuffix,children:t(f?`tierToOff`:`tierToPeak`)})]}),d&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:I.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:I.feeItem,"data-testid":`billing-live-turn`,children:[t(`liveTurn`),` `,(0,m.jsx)(`span`,{className:I.feeNum,children:u(a)})]}),(0,m.jsx)(`span`,{className:I.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:I.feeItem,"data-testid":`billing-live-session`,children:[t(`liveSession`),` `,(0,m.jsx)(`span`,{className:I.feeNum,children:u(i)})]})]}),s.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:I.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:e.pct<=10?I.feeChipError:I.feeChipAlert,"data-testid":`billing-live-quota`,children:[e.name,` `,t(hi(e.kind)),` `,e.pct,`%`]})]},`${e.name}:${e.kind}`))]})}function xi({sessionId:e,t}){let n=_i(),r=e=>K(Bt(e,n),n),{visible:i,position:a}=vi(),{sessionCost:o,turnCost:s,tier:c,chips:l,hasBandPlan:u}=yi(e,i&&a===`toolbar`);if(!i||a!==`toolbar`)return null;let d=c?.tier===`peak`,f=l.reduce((e,t)=>Math.min(e,t.pct),100),h=f<=10?I.feeInlineError:f<=20?I.feeInlineAlert:I.feeInline,g=[...c===null?[]:[`${pt(c.nextSwitchInMs)} ${t(d?`tierToOff`:`tierToPeak`)}`],`${t(`liveTurn`)} ${r(s)}`,`${t(`liveSession`)} ${r(o)}`,...l.map(e=>`${e.name} ${t(hi(e.kind))} ${e.pct}%`)].join(` · `);return(0,m.jsx)(p.Tooltip,{label:g,side:`top`,delayMs:500,children:(0,m.jsxs)(`span`,{className:h,"data-testid":`billing-live-cost-chip`,role:`note`,"aria-label":g,children:[(0,m.jsx)(gi,{hasBandPlan:u}),c!==null&&(0,m.jsx)(`span`,{className:d?I.feeChipPrimary:I.feeChipOff,"data-testid":`billing-live-tier`,children:t(d?`tierPeak`:`tierOff`)}),o>0&&(0,m.jsx)(`span`,{className:I.feeInlineNum,children:r(o)})]})})}function Si(){let e,t,n=new Set;return{readCosts:()=>e,subscribeCosts:t=>(t(e),n.add(t),()=>{n.delete(t)}),openDashboard:()=>{t?.()},publishCosts:t=>{e=t;for(let e of n)try{e(t)}catch{}},registerOpen:e=>(t=e,()=>{t===e&&(t=void 0)})}}function Ci(){return(0,h.defineStore)({init:()=>({enabled:!1,amount:0,tierAlertDays:{},lastBalanceAlertDay:``,lastTierSwitchAt:0}),persist:`dsh.ui-usage-billing.budget`,actions:{setEnabled:(e,t)=>{e.enabled=t},setAmount:(e,t)=>{e.amount=Number.isFinite(t)&&t>0?t:0},markTierAlerted:(e,t,n)=>{e.tierAlertDays??={};for(let r of t)e.tierAlertDays[String(r)]=n},markBalanceAlerted:(e,t)=>{e.lastBalanceAlertDay=t},markTierSwitchAlerted:(e,t)=>{e.lastTierSwitchAt=t}}})}let wi={enabled:!1,timeout:0};function Ti(){try{let e=localStorage.getItem(`dsh-billing-completion-notify-v1`);if(e===null)return{...wi};let t=JSON.parse(e);return{enabled:t.enabled===!0,timeout:typeof t.timeout==`number`?t.timeout:0}}catch{return{...wi}}}function Ei(e){return e.completed===!0||e.running===!1}function Di(e,t){let n=new Set,r=new Set,i,a=e.getSnapshot();for(let e of a.ids){let t=a.byId[e];t!==void 0&&(r.add(String(e)),Ei(t)&&n.add(String(e)))}let o=e=>{let{enabled:n,timeout:r}=t();if(n&&!(typeof Notification>`u`)&&Notification.permission===`granted`)try{let t=new Notification(e,{body:e,tag:`dsh-billing-completion`,requireInteraction:r===0});r>0&&(i!==void 0&&clearTimeout(i),i=setTimeout(()=>t.close(),r*1e3))}catch{}},s=e.subscribe(()=>{let t=e.getSnapshot(),i=[];for(let e of t.ids){let a=t.byId[e];if(a===void 0)continue;let o=String(e),s=Ei(a),c=!r.has(o);c&&r.add(o),s&&!c&&!n.has(o)&&i.push(a.title??a.id??o),s?n.add(o):n.delete(o)}if(i.length>0){let e=i.length===1?i[0]:`${i.length} 个会话已完成`;e!==void 0&&o(e)}});return()=>{s(),i!==void 0&&clearTimeout(i)}}let Oi=[`slots`,`locale`,`remote`,`sessions`];function ki(e){let t=Si();e.provide(`billingMetrics`,t);let n=Ci();e.effect(()=>e.locale.register(Ne,{zh:Pe,en:Fe}),`ui-usage-billing: dictionaries`),e.slots.inject(`sidebar.footer.action`,()=>e.slots.register({name:`sidebar.footer.action`,id:`usage-billing`,order:-10,locale:Ne,children:{"billing.dashboard.decor":{kind:`list`,scope:`root`}},store:n,inject:()=>({checkModels:async()=>{try{let[t,n]=await Promise.all([e.remote.llm.listProviders(),e.remote.llm.listConfigurableProviders()]);if(!t.ok||!n.ok)return{checked:!0,available:!1,models:0,failures:0,okProviders:[],badProviders:[]};let r=new Map(n.value.map(e=>[e.provider,e])),i=await Promise.all(t.value.map(async t=>{let n=r.get(t.id);if(n===void 0)return{provider:t,models:[]};let i=await e.remote.llm.discoverModels(n.settingsNs,{provider:t.id});return i.ok?{provider:t,models:i.value}:{provider:t,failed:!0}})),a=[],o=[],s=[],c=0;for(let e of i){if(`failed`in e){s.push(e.provider.name);continue}o.push(e.provider.name),c+=e.models.length;for(let t of e.models)a.push({id:t.id,...typeof t.name==`string`&&t.name!==``?{name:t.name}:{},provider:e.provider.name})}return{checked:!0,available:o.length>0,models:c,failures:s.length,okProviders:o,badProviders:s,catalog:a}}catch{return{checked:!1,available:!1,models:0,failures:0,okProviders:[],badProviders:[]}}},publishCosts:e=>{t.publishCosts(e)},registerOpen:e=>t.registerOpen(e)})},ci)),e.slots.inject(`conversation.composer.dock`,()=>e.slots.register({name:`conversation.composer.dock`,id:`usage-billing-cost`,order:0,locale:Ne,inject:e=>({sessionId:_(e)})},bi)),e.slots.inject(`conversation.input.right`,()=>e.slots.register({name:`conversation.input.right`,id:`usage-billing-cost-chip`,order:0,locale:Ne,inject:e=>({sessionId:_(e)})},xi)),e.effect(()=>Di(e.sessions.list,Ti),`ui-usage-billing: completion notifier`)}return n.UsageBilling=ci,n.apply=ki,n.inject=Oi,t.exports}});
|
|
6
6
|
//# sourceMappingURL=client.js.map
|
package/lib/types/aggregate.d.ts
CHANGED
|
@@ -34,6 +34,27 @@ export declare const DEFAULT_SUBSCRIPTION_PROVIDERS: readonly string[];
|
|
|
34
34
|
* 调用与费用分桶展示;部署可由配置覆盖(见 {@link AggregateOptions})。
|
|
35
35
|
*/
|
|
36
36
|
export declare function isOfficialProvider(provider: string): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* 已知的「第三方插件注册 adapter」通道名单:这些 provider 由别的插件经
|
|
39
|
+
* `ctx.llm.registerAdapter` 注册,**不经 llm-pi-ai 路由表**,因此
|
|
40
|
+
* {@link siteRefOf} 的路由查询必然 miss。与订阅豁免(issue #37 的 grok
|
|
41
|
+
* build)同构:显式列出、不做「猜通道」的通用发现——猜错会把来源不明的
|
|
42
|
+
* 路由也归位成可计价通道,违背 issue #82「支出主体无法核实不计价」的初衷。
|
|
43
|
+
*
|
|
44
|
+
* 收录语义:这些通道的支出主体是可核实的(WorkBuddy = 腾讯 WorkBuddy
|
|
45
|
+
* 桌面 App 账号),计费用模型官方目录价折算 Token 成本,与积分制解耦。
|
|
46
|
+
* 它们**不是** DeepSeek 官方渠道——{@link isOfficialProvider} 与
|
|
47
|
+
* {@link officialChannelOf} 都不会因本名单把调用算进官方口径。
|
|
48
|
+
*/
|
|
49
|
+
export declare const KNOWN_ADAPTER_PROVIDERS: ReadonlySet<string>;
|
|
50
|
+
/**
|
|
51
|
+
* 一个 provider 是否命中已知 adapter 通道名单。判定与 {@link isOfficialProvider}
|
|
52
|
+
* 同姿态:trim + 大小写不敏感——dsh-workbuddy-connect 注册的是小写 id
|
|
53
|
+
*(`workbuddy` / `workbuddy-ai`),宿主不强制 route 小写,按大小写归一化可避免
|
|
54
|
+
* 日志里出现大小写变体时静默落回 unknown 桶。路由表命中仍优先于本名单
|
|
55
|
+
*(见 {@link siteRefOf}),用户自配的大小写变体走配置路径。
|
|
56
|
+
*/
|
|
57
|
+
export declare function isKnownAdapterProvider(provider: string): boolean;
|
|
37
58
|
/** DeepSeek 官方直连端点的归一化 origin(`siteOriginOf` 口径):有 baseURL 的路由只有它算官方。 */
|
|
38
59
|
export declare const OFFICIAL_DEEPSEEK_ORIGIN = "https://api.deepseek.com";
|
|
39
60
|
/**
|
|
@@ -78,8 +99,10 @@ export declare function siteOriginOf(baseURL: string): string;
|
|
|
78
99
|
* 网关)按 `direct` 归位——unknown 一刀切会把官方直连的费用堆进「未知路由」组、
|
|
79
100
|
* 且不算官方渠道(回归修复);订阅豁免命中的通道(显式 `subscriptionProviders`
|
|
80
101
|
* 配置或判定函数)同样按 `direct` 归位——订阅管理类插件注册的通道不经路由表,
|
|
81
|
-
* unknown 桶既掩盖归属又按 token 误计费(issue #37 的 grok build
|
|
82
|
-
*
|
|
102
|
+
* unknown 桶既掩盖归属又按 token 误计费(issue #37 的 grok build);已知的第三方
|
|
103
|
+
* 插件注册 adapter 通道({@link KNOWN_ADAPTER_PROVIDERS},如 workbuddy)同样按
|
|
104
|
+
* `direct` 归位——支出主体可核实、按模型官方目录价计 Token 成本,unknown 桶会让
|
|
105
|
+
* 费用恒为 0;其余配置外名称保留 unknown(无法核实通道)。
|
|
83
106
|
* @param provider - 会话日志里的 provider 路由名(request/header 的 `config.provider`)。
|
|
84
107
|
* @param routes - 当前 provider 路由视图(来自 llm-pi-ai providers)。
|
|
85
108
|
* @param opts - `subscription`:该调用是否已被订阅豁免判定命中。
|
|
@@ -568,7 +591,7 @@ export interface UsageLedgerDocument {
|
|
|
568
591
|
* 会话费用只剩最近一段,issue #29)。
|
|
569
592
|
* 持久账本行据此区分新旧算法:日志已删/不可读而只能沿用旧行时,UI 标注置信度提示。
|
|
570
593
|
*/
|
|
571
|
-
export declare const FOLD_VERSION =
|
|
594
|
+
export declare const FOLD_VERSION = 21;
|
|
572
595
|
/**
|
|
573
596
|
* 一次性账本迁移:id 唯一,apply 在加载边界对原始文档执行,已应用过的跳过。
|
|
574
597
|
* 未来账本/schema 字段变更(重命名、拆桶、语义调整)时,在此追加一条迁移并
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kenz1117/dsh-ui-usage-billing",
|
|
3
3
|
"description": "Usage billing dashboard for DeepSeek Harness: sidebar cost metrics plus a full dashboard modal, priced from a current multi-provider catalog with real usage aggregated from session logs.",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.29",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"deepseek-harness",
|
|
7
7
|
"deepseek",
|