@kenz1117/dsh-ui-usage-billing 1.8.10 → 1.8.11
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 +3 -3
- package/README.md +3 -3
- package/lib/client.js +1 -1
- package/lib/types/client/footer-lane.d.ts +10 -3
- package/package.json +66 -65
package/lib/client.js
CHANGED
|
@@ -2,5 +2,5 @@ window.__ModuleLoader__.load({id:`@kenz1117/dsh-ui-usage-billing`,factory:e=>{va
|
|
|
2
2
|
`)}function wn(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[bn(xn(n)),r,t.calls,Sn(t.cost)].join(`,`)})].join(`
|
|
3
3
|
`)}function Tn(e){return e===void 0?``:e.split(/[\\/]/).filter(Boolean).pop()??e}function En(e){return[`session_id,title,project,calls,cost_cny,last_active,parent_id,sub_calls,sub_cost_cny`,...e.map(e=>[bn(xn(e.id)),bn(xn(e.title??``)),bn(xn(Tn(e.cwd))),e.calls,Sn(e.cost),e.lastActive>0?new Date(e.lastActive).toISOString():``,e.parentId??``,e.subCalls??``,e.subCost===void 0?``:Sn(e.subCost)].join(`,`))].join(`
|
|
4
4
|
`)}function Dn(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 On(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 kn(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(Math.round(e))}let q={top:14,right:18,bottom:22,left:46},An=`var(--ds-blue)`,jn=`var(--ds-cyan)`,Mn=`var(--ds-amber)`;function Nn(e,t,n,r){return JSON.stringify({days:e,models:t,dayModels:n,total:r},null,2)}function Pn(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:L.shareSegUser},{label:i(`roleAssistant`),value:e.assistant,seg:L.shareSegAssistant},{label:i(`roleTool`),value:e.tool,seg:L.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=G(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=G(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??cn(e).name,color:o.find(t=>t.key===e)?.color??`#8b95a3`}))},[C,o]),T=g!==null&&w.some(e=>e.key===g)?g:null,E=e=>{if(v){if(p!==`model`){h(`model`),_(e);return}_(t=>t===e?null:e)}},ee=(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:cn(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]),te=(0,d.useMemo)(()=>{let e=new Map;for(let n of Object.values(t.byDayModelsSite??{}))for(let[t,r]of Object.entries(n)){let n=e.get(t)??[];for(let[e,t]of Object.entries(r)){let r=n.find(t=>t.siteKey===e);if(r===void 0){n.push({siteKey:e,tokens:t.input+t.output,cost:t.cost});continue}r.tokens+=t.input+t.output,r.cost+=t.cost}e.set(t,n)}for(let[t,n]of e)e.set(t,[...n].sort((e,t)=>t.tokens-e.tokens));return e},[t.byDayModelsSite]),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-q.left-q.right,n=200-q.top-q.bottom,r=Math.max(...p===`model`?C.map(e=>e.total):S.map(e=>e.miss+e.hit+e.output),1),i=e=>q.top+n-e/r*n,a=t/e,o=Math.min(20,a*.6),s=n=>e===1?q.left+t/2:q.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]),ne=()=>{On(`token-daily-${G()}.csv`,Fn(S),`text/csv`)},k=()=>{On(`token-${G()}.json`,Nn(S,ee,C,l),`application/json`)},A=u===null?void 0:S[u],j=u===null?void 0:C[u],re=O===null?0:Math.ceil(80/Math.max(O.groupW,1)),ie=u===null||O===null?void 0:u>=O.n-re?L.chartTooltipAlignRight:u<re?L.chartTooltipAlignLeft:void 0;return(0,m.jsxs)(`div`,{className:L.tokenPanel,"data-testid":`billing-token-panel`,children:[(0,m.jsxs)(`div`,{className:L.exportBar,role:`group`,"aria-label":i(`tokenExport`),children:[(0,m.jsx)(`span`,{className:L.exportLabel,children:i(`export`)}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-token-export-csv`,onClick:ne,children:i(`tokenExportCsv`)}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-token-export-json`,onClick:k,children:i(`exportJson`)})]}),(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-token-daily`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:i(`tokenDaily`)}),(0,m.jsxs)(`span`,{className:L.panelHeadControls,children:[v&&(0,m.jsx)(`span`,{className:L.rangeToggle,role:`group`,"aria-label":i(`tokenDaily`),children:[`structure`,`model`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,p===e&&L.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:L.rangeToggle,role:`group`,"aria-label":i(`tokenDaily`),children:[7,30].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,n===e&&L.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:L.chartEmpty,children:i(`trendEmpty`)}):(0,m.jsxs)(`div`,{className:L.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 200`,className:L.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-q.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:q.left,x2:680-q.right,y1:n,y2:n,className:L.chartGrid}),(0,m.jsx)(`text`,{x:q.left-8,y:n+3,textAnchor:`end`,className:L.chartAxisLabel,children:kn(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:An}),(0,m.jsx)(`rect`,{x:n,y:a,width:O.barW,height:i-a,fill:jn}),(0,m.jsx)(`rect`,{x:n,y:o,width:O.barW,height:a-o,fill:Mn})]},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:L.chartAxisLabel,children:t.date.slice(5)},t.date)}),u!==null&&(0,m.jsx)(`line`,{x1:O.inner(u),x2:O.inner(u),y1:q.top,y2:q.top+O.plotH,className:L.chartCrosshair})]}),u!==null&&p===`structure`&&A!==void 0&&(0,m.jsxs)(`div`,{className:y(L.chartTooltip,ie),"data-testid":`billing-token-tooltip`,style:{left:`${O.inner(u)/680*100}%`,top:`${O.y(A.miss+A.hit+A.output)/200*100}%`},children:[(0,m.jsxs)(`div`,{className:L.chartTooltipHead,children:[(0,m.jsx)(`span`,{className:L.chartTooltipDate,children:A.date}),(0,m.jsx)(`strong`,{children:(A.miss+A.hit+A.output).toLocaleString()})]}),(0,m.jsxs)(`div`,{className:y(L.chartTooltipRow,L.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:L.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:jn}}),i(`tokenHit`)]}),(0,m.jsx)(`strong`,{children:A.hit.toLocaleString()})]}),(0,m.jsxs)(`div`,{className:y(L.chartTooltipRow,L.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:L.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:An}}),i(`tokenMiss`)]}),(0,m.jsx)(`strong`,{children:A.miss.toLocaleString()})]}),(0,m.jsxs)(`div`,{className:y(L.chartTooltipRow,L.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:L.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:Mn}}),i(`tokenOutput`)]}),(0,m.jsx)(`strong`,{children:A.output.toLocaleString()})]})]}),u!==null&&p===`model`&&j!==void 0&&(0,m.jsxs)(`div`,{className:y(L.chartTooltip,ie),"data-testid":`billing-token-tooltip`,style:{left:`${O.inner(u)/680*100}%`,top:`${O.y(j.total)/200*100}%`},children:[(0,m.jsxs)(`div`,{className:L.chartTooltipHead,children:[(0,m.jsx)(`span`,{className:L.chartTooltipDate,children:j.date}),(0,m.jsx)(`strong`,{children:j.total.toLocaleString()})]}),w.map(e=>{let t=j.models[e.key];return t===void 0?null:(0,m.jsxs)(`div`,{children:[(0,m.jsxs)(`div`,{className:y(L.chartTooltipRow,L.chartTooltipSplit),children:[(0,m.jsxs)(`span`,{className:L.chartTooltipLabel,children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:e.color}}),e.name]}),(0,m.jsx)(`strong`,{children:t.total.toLocaleString()})]}),(0,m.jsxs)(`div`,{className:L.chartTooltipModelDetail,children:[i(`tokenHitShort`),` `,t.hit.toLocaleString(),` · `,i(`tokenMissShort`),` `,t.miss.toLocaleString(),` · `,i(`tokenOutput`),` `,t.output.toLocaleString()]})]},e.key)})]}),(0,m.jsx)(`div`,{className:L.chartLegend,children:p===`structure`?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:An}}),i(`tokenMiss`)]}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:jn}}),i(`tokenHit`)]}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:Mn}}),i(`tokenOutput`)]})]}):w.map(e=>(0,m.jsxs)(`button`,{type:`button`,className:y(L.chartLegendItem,T===e.key&&L.chartLegendItemActive),"aria-pressed":T===e.key,"data-testid":`billing-token-legend-${e.key}`,onClick:()=>{E(e.key)},children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:e.color}}),e.name]},e.key))})]})]}),(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-token-models`,children:[(0,m.jsx)(`div`,{className:L.panelHead,children:(0,m.jsx)(`h3`,{className:L.panelTitle,children:i(`tokenByModel`)})}),ee.length===0?(0,m.jsx)(`div`,{className:L.emptyRow,children:i(`noData`)}):(0,m.jsx)(`div`,{className:L.tableScroll,children:(0,m.jsxs)(`table`,{className:L.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:L.numCol,children:i(`inputTokens`)}),(0,m.jsx)(`th`,{className:L.numCol,children:i(`outputTokens`)}),(0,m.jsx)(`th`,{className:L.numCol,children:i(`tokenReasoningShort`)}),(0,m.jsx)(`th`,{className:L.numCol,children:i(`cacheHitRate`)}),(0,m.jsx)(`th`,{className:L.numCol,children:i(`tokenTotal`)}),(0,m.jsx)(`th`,{className:L.numCol,children:i(`tokenShare`)}),(0,m.jsx)(`th`,{className:L.numCol,children:i(`calls`)})]})}),(0,m.jsx)(`tbody`,{children:ee.map(t=>(0,m.jsxs)(`tr`,{"data-testid":`billing-token-model`,className:y(v&&L.modelRowFocusable,T===t.key&&L.modelRowActive),"aria-selected":v?T===t.key:void 0,onClick:v?()=>{E(t.key)}:void 0,tabIndex:v?0:void 0,onKeyDown:v?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),E(t.key))}:void 0,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:L.modelName,children:t.name}),(te.get(t.key)??[]).length>0&&(0,m.jsx)(`span`,{className:L.modelChannels,"data-testid":`billing-token-model-channels-${t.key}`,children:(te.get(t.key)??[]).slice(0,3).map(n=>(0,m.jsxs)(`span`,{className:L.modelChannelTag,title:`${e.channelName?.(n.siteKey)??n.siteKey} · ${K(n.tokens)} token · ${a(n.cost)}`,children:[e.channelName?.(n.siteKey)??n.siteKey,` · `,t.total>0?`${(n.tokens/t.total*100).toFixed(0)}%`:`—`]},n.siteKey))})]}),(0,m.jsx)(`td`,{className:L.numCol,children:K(t.input)}),(0,m.jsx)(`td`,{className:L.numCol,children:K(t.output)}),(0,m.jsx)(`td`,{className:L.numCol,children:t.reasoning>0?K(t.reasoning):(0,m.jsx)(`span`,{className:L.na,children:`—`})}),(0,m.jsxs)(`td`,{className:L.numCol,children:[t.cacheHitRate.toFixed(1),`%`]}),(0,m.jsx)(`td`,{className:L.numCol,children:K(t.total)}),(0,m.jsx)(`td`,{className:L.numCol,children:(0,m.jsxs)(`span`,{className:L.tokenModelShareRow,children:[(0,m.jsx)(`span`,{className:L.tokenModelBar,children:(0,m.jsxs)(`span`,{className:L.tokenModelParts,style:{width:`${(t.share*100).toFixed(2)}%`},children:[(0,m.jsx)(`span`,{className:L.tokenModelPartIn,style:{width:`${t.total>0?t.input/t.total*100:0}%`}}),(0,m.jsx)(`span`,{className:L.tokenModelPartOut,style:{width:`${t.total>0?t.output/t.total*100:0}%`}})]})}),(t.share*100).toFixed(1),`%`]})}),(0,m.jsx)(`td`,{className:L.numCol,children:t.calls.toLocaleString()})]},t.key))})]})})]}),D.totalCalls>0&&(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-token-tools`,children:[(0,m.jsx)(`div`,{className:L.panelHead,children:(0,m.jsx)(`h3`,{className:L.panelTitle,children:i(`toolRank`)})}),(0,m.jsx)(`div`,{className:L.tableScroll,children:(0,m.jsxs)(`table`,{className:L.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:L.numCol,children:i(`calls`)}),(0,m.jsx)(`th`,{className:L.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:L.modelName,children:e})}),(0,m.jsx)(`td`,{className:L.numCol,children:t.toLocaleString()}),(0,m.jsxs)(`td`,{className:L.numCol,children:[(t/D.totalCalls*100).toFixed(1),`%`]})]},e))})]})})]}),x.length>0&&(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-roles`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:i(`roleCost`)}),(0,m.jsx)(`span`,{className:L.panelHint,children:i(`roleHint`)})]}),(0,m.jsx)(`div`,{className:L.shareTrack,"data-testid":`billing-role-track`,children:x.map(e=>(0,m.jsx)(`div`,{className:y(L.shareSeg,e.seg),style:{width:`${e.pct}%`}},e.label))}),(0,m.jsx)(`div`,{className:L.shareLegend,children:x.map(e=>(0,m.jsxs)(`span`,{className:L.shareItem,children:[(0,m.jsx)(`span`,{className:y(L.shareDot,e.seg)}),e.label,(0,m.jsxs)(`span`,{className:L.shareValue,children:[a(e.value),` · `,e.pct.toFixed(1),`%`]})]},e.label))})]})]})}function Fn(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 J={top:18,right:40,bottom:26,left:46};function In(e){let[,t,n]=e.split(`-`);return`${Number(t)}/${Number(n)}`}function Ln(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 Rn={key:`__total__`,name:``,color:``};function zn({data:e,models:t=[],currency:n=`cny`,metric:r=`cost`,t:i}){let a=i??(e=>ot[e]),[o,s]=(0,d.useState)(null),c=e=>W(gn(e,n),n),l=e=>r===`tokens`?kn(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-J.left-J.right,a=220-J.top-J.bottom,o=e=>n===1?J.left+i/2:J.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=>J.top+a-e/s*a,l=Math.max(...e.map(e=>e.calls),1),d=e=>J.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:Rn,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:L.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],E=Ln(p,Math.max(1,Math.ceil(p/8)));return(0,m.jsxs)(`div`,{className:L.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 220`,className:L.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-J.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:J.left,x2:680-J.right,y1:n,y2:n,className:L.chartGrid}),(0,m.jsx)(`text`,{x:J.left-8,y:n+3,textAnchor:`end`,className:L.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===``?L.chartBar:L.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:L.chartBarPlaceholder},`${t.date}-${t.model.key}-placeholder`):null}),(0,m.jsx)(`path`,{d:w,fill:`none`,className:L.chartLine}),(()=>{let t=G(),n=e.findIndex(e=>e.date===t);return n>=0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`defs`,{children:(0,m.jsxs)(`linearGradient`,{id:`chartAreaGrad`,x1:`0%`,y1:`0%`,x2:`0%`,y2:`100%`,children:[(0,m.jsx)(`stop`,{offset:`0%`,stopColor:`var(--ds-blue)`,stopOpacity:`0.35`}),(0,m.jsx)(`stop`,{offset:`100%`,stopColor:`var(--ds-blue)`,stopOpacity:`0`})]})}),(0,m.jsx)(`path`,{d:`${w} L ${_(e.length-1)} ${y(0)} L ${_(0)} ${y(0)} Z`,fill:`url(#chartAreaGrad)`}),(0,m.jsx)(`line`,{x1:_(n),x2:_(n),y1:J.top,y2:J.top+g,stroke:`var(--ds-amber)`,strokeWidth:`1`,strokeDasharray:`3 3`,opacity:`0.6`}),(0,m.jsx)(`text`,{x:_(n)+4,y:J.top-6,fill:`var(--ds-amber)`,fontSize:`10`,fontFamily:`var(--font-num)`,children:In(t)})]}):null})(),C.map((e,t)=>{let n=y(e);return(0,m.jsx)(`text`,{x:680-J.right+8,y:n+3,textAnchor:`start`,className:L.chartAxisLabel,children:kn(e)},`calls-${t}`)}),E.map(t=>{let n=e[t];return n===void 0?null:(0,m.jsx)(`text`,{x:_(t),y:214,textAnchor:`middle`,className:L.chartAxisLabel,children:In(n.date)},n.date)}),o!==null&&(0,m.jsx)(`line`,{x1:_(o),x2:_(o),y1:J.top,y2:J.top+g,className:L.chartCrosshair})]}),T!==void 0&&o!==null&&(0,m.jsxs)(`div`,{className:L.chartTooltip,style:{left:`${_(o)/680*100}%`,top:`${v(T.cost)/220*100}%`},children:[(0,m.jsx)(`div`,{className:L.chartTooltipDate,children:T.date}),r!==`tokens`&&t.filter(e=>(T.byModel?.[e.key]??0)>0).map(e=>(0,m.jsxs)(`div`,{className:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.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:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.chartLegendBar}),a(`trendTotal`),` `,(0,m.jsx)(`strong`,{children:r===`tokens`?kn(T.tokens??0):c(T.cost)})]}),(0,m.jsxs)(`div`,{className:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.chartLegendLine}),a(`calls`),` `,(0,m.jsx)(`strong`,{children:T.calls.toLocaleString()})]})]}),t.length>0&&r!==`tokens`&&(0,m.jsxs)(`div`,{className:L.chartLegend,children:[t.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:e.color}}),e.name]},e.key)),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.chartLegendLine}),a(`calls`)]})]})]})}let Y={top:14,right:42,bottom:22,left:46};function Bn(e){return e.slice(5,13).replace(`T`,` `)}function Vn(e){return String(e>=100?Math.round(e):Number(e.toFixed(1)))}function Hn(e){return e<1e4?`${Math.round(e)} ms`:e<6e4?`${(e/1e3).toFixed(1)} s`:`${(e/6e4).toFixed(1)} min`}function Un(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function Wn(e,t,n){return t===`ttft`?`${Math.round(e)} ms`:`${e.toFixed(1)} ${n(`perfTpsUnit`)}`}function Gn({perf:e,models:t,t:n}){let[r,i]=(0,d.useState)(()=>Ge()),[a,o]=(0,d.useState)(null),s=e=>{i(e),Ke(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-Y.left-Y.right,a=180-Y.top-Y.bottom,o=e=>n===1?Y.left+i/2:Y.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=>Y.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:L.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:[l.length>0&&(()=>{let e=Math.max(...l.map(e=>e.ttftAvg),1),t=Math.max(...l.filter(e=>e.tpsAvg!==void 0).map(e=>e.tpsAvg??0),1),r=Math.max(...l.map(e=>e.latencyAvg),1),i=l.reduce((e,t)=>e+t.samples,0),a=l.length>0?l.reduce((e,t)=>e+t.ttftAvg,0)/l.length:0,o=l.map(e=>e.tpsAvg).filter(e=>e!==void 0),s=o.length>0?o.reduce((e,t)=>e+t,0)/o.length:0,c=l.length>0?l.reduce((e,t)=>e+t.latencyAvg,0)/l.length:0,u=[{lbl:n(`perfSamples`),val:i.toLocaleString(),unit:``,pct:65,color:`var(--ds-blue)`},{lbl:n(`perfTtft`),val:Hn(a),unit:``,pct:a/e*100,color:`var(--ds-green)`},{lbl:n(`perfTps`),val:o.length>0?Un(s):`—`,unit:``,pct:s/t*100,color:`var(--ds-blue)`},{lbl:n(`perfLatency`),val:Hn(c),unit:``,pct:c/r*100,color:`var(--ds-amber)`}];return(0,m.jsx)(`div`,{className:L.perfHero,"data-testid":`billing-perf-hero`,children:u.map((e,t)=>(0,m.jsxs)(`div`,{className:L.perfHeroCell,children:[(0,m.jsx)(`div`,{className:L.perfHeroLbl,children:e.lbl}),(0,m.jsxs)(`div`,{className:L.perfHeroVal,children:[e.val,e.unit!==``&&(0,m.jsx)(`span`,{className:L.perfHeroUnit,children:e.unit})]}),(0,m.jsx)(`div`,{className:L.perfHeroBar,children:(0,m.jsx)(`i`,{style:{width:`${Math.min(100,e.pct)}%`,background:e.color}})})]},t))})})(),(0,m.jsx)(`div`,{className:L.tableScroll,"data-testid":`billing-perf-table`,children:(0,m.jsxs)(`table`,{className:L.modelTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`model`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfSamples`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfTtft`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfP50`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfP90`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfMax`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfTps`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfLatency`)}),(0,m.jsx)(`th`,{className:L.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:L.modelCell,children:[(0,m.jsx)(`span`,{className:L.modelDot,style:{background:e.color}}),(0,m.jsx)(`span`,{className:L.modelName,children:e.name})]})}),(0,m.jsx)(`td`,{className:L.numCol,children:e.samples.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.ttftAvg)}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.ttftP50)}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.ttftP90)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.ttftMax===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):(0,m.jsxs)(`span`,{children:[Hn(e.ttftMax),e.ttftSpikes!==void 0&&e.ttftSpikes>0?` (${e.ttftSpikes}↑)`:``]})}),(0,m.jsx)(`td`,{className:L.numCol,children:e.tpsAvg===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):Un(e.tpsAvg)}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.latencyAvg)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.estimatedSamples>0?e.estimatedSamples:(0,m.jsx)(`span`,{className:L.na,children:`—`})})]},e.key))})]})}),l.length>0&&(()=>{let e=Math.max(...l.map(e=>e.ttftP50),1),t=e=>e<.8?`var(--ds-green)`:e<2?`var(--ds-amber)`:`var(--ds-red)`;return(0,m.jsx)(`div`,{className:L.perfCompareList,"data-testid":`billing-perf-compare`,children:l.map(n=>(0,m.jsxs)(`div`,{className:L.perfCompareRow,children:[(0,m.jsxs)(`div`,{className:L.perfCompareName,children:[(0,m.jsx)(`span`,{className:L.perfCompareDot,style:{background:n.color}}),(0,m.jsx)(`span`,{children:n.name})]}),(0,m.jsx)(`div`,{className:L.perfCompareBar,children:(0,m.jsx)(`i`,{style:{width:`${n.ttftP50/e*100}%`,background:t(n.ttftP50)}})}),(0,m.jsx)(`div`,{className:L.perfCompareNum,children:Hn(n.ttftP50)}),(0,m.jsx)(`div`,{className:L.perfCompareNum,children:n.tpsAvg===void 0?`—`:Un(n.tpsAvg)})]},n.key))})})(),f!==null&&(0,m.jsxs)(`div`,{"data-testid":`billing-perf-hour`,children:[(0,m.jsx)(`div`,{className:L.perfBar,children:(0,m.jsx)(`span`,{className:L.rangeToggle,role:`group`,"aria-label":n(`perfTitle`),children:[`ttft`,`tps`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,r.metric===e&&L.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:L.perfChips,role:`group`,"aria-label":n(`model`),children:[(0,m.jsx)(`button`,{type:`button`,className:L.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(L.perfChip,!t&&L.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:L.perfChipDot,style:{background:t?e.color:`var(--dsw-alias-label-dimmed)`}}),e.name]},e.key)})]}),f.totalPoints>0?(0,m.jsxs)(`div`,{className:L.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 180`,className:L.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-Y.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:Y.left,x2:680-Y.right,y1:n,y2:n,className:L.chartGrid}),(0,m.jsx)(`text`,{x:Y.left-8,y:n+3,textAnchor:`end`,className:L.chartAxisLabel,children:Vn(e)})]},`tick-${t}`)}),f.series.map(e=>e.segments.map((t,n)=>(0,m.jsx)(`path`,{d:t,fill:`none`,className:L.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:L.chartAxisLabel,children:Bn(t)},t)}),a!==null&&(0,m.jsx)(`line`,{x1:f.inner(a),x2:f.inner(a),y1:Y.top,y2:Y.top+f.plotH,className:L.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:L.chartHoverDot},`${e.key}-dot`)})]}),a!==null&&g.length>0&&(0,m.jsxs)(`div`,{className:L.chartTooltip,"data-testid":`billing-perf-tooltip`,style:{left:`${f.inner(a)/680*100}%`,top:`${(Y.top+f.plotH/2)/180*100}%`},children:[(0,m.jsx)(`div`,{className:L.chartTooltipDate,children:Bn(f.hourKeys[a]??``)}),g.map(e=>(0,m.jsxs)(`div`,{className:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:e.color}}),e.name,` `,(0,m.jsx)(`strong`,{children:Wn(e.v,r.metric,n)})]},e.key))]})]}):(0,m.jsx)(`div`,{className:L.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]}),f===null&&(0,m.jsx)(`div`,{className:L.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]})}let Kn=`@kenz1117/dsh-ui-usage-billing`,qn=`kenz1117`;function Jn({t:e,version:t}){return(0,m.jsxs)(`section`,{className:L.setCard,"data-testid":`billing-plugin-info`,children:[(0,m.jsxs)(`div`,{className:L.plgHead,children:[(0,m.jsx)(`span`,{className:L.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:L.plgTitle,children:[(0,m.jsxs)(`div`,{className:L.plgNameRow,children:[(0,m.jsx)(`h3`,{className:L.plgName,children:Kn}),(0,m.jsx)(`span`,{className:L.plgTag,children:t===void 0?`—`:`v${t}`})]}),(0,m.jsx)(`p`,{className:L.plgDesc,children:`Usage billing dashboard for DeepSeek Harness`})]})]}),(0,m.jsxs)(`div`,{className:L.plgGrid,children:[(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginAuthor`)}),(0,m.jsxs)(`a`,{className:L.plgLink,href:`https://github.com/${qn}`,target:`_blank`,rel:`noreferrer`,children:[`KenZ`,` (`,qn,`)`]})]}),(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginRepository`)}),(0,m.jsx)(`a`,{className:L.plgLink,href:`https://github.com/kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:`GitHub`})]}),(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginNpm`)}),(0,m.jsx)(`a`,{className:L.plgLink,href:`https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:Kn})]}),(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginLicense`)}),(0,m.jsx)(`span`,{className:L.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 Xn(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 Zn(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 Qn({rounds:e,flags:t,currency:n,t:r}){let i=(0,d.useMemo)(()=>[...e].sort((e,t)=>e.startedAt-t.startedAt).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:L.roundsEmpty,children:[r(`model`),` —`]});let s=e=>W(gn(e,n),n);return(0,m.jsxs)(`div`,{className:L.rounds,children:[(0,m.jsx)(`div`,{className:L.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=zt(e.model,!1)===`deepseek-metered`&&kt(e.startedAt)===`peak`;return(0,m.jsxs)(`div`,{className:y(L.roundsBarCol,i?L.roundsBarColPeak:L.roundsBarColOff),children:[(0,m.jsx)(`span`,{className:L.roundsBarLabel,style:{bottom:`${n}%`},children:s(e.cost)}),(0,m.jsx)(`div`,{className:L.roundsBarWrap,children:(0,m.jsx)(`div`,{className:t?L.roundsBarFlagged:L.roundsBar,style:{height:`${n}%`},"data-testid":`round-bar`,title:`${r(`model`)} ${e.model} · ${s(e.cost)} · ${Xn(e.startedAt)}${e.endedAt===void 0?``:` → ${Yn(e.endedAt)} (${Zn(e.endedAt-e.startedAt)})`}`,children:t&&(0,m.jsx)(`span`,{className:L.roundsFlagMark,"aria-hidden":`true`})})})]},`${e.sessionId}:${e.turn}`)})}),(0,m.jsxs)(`div`,{className:L.roundsAxis,children:[(0,m.jsxs)(`span`,{children:[r(`costAbbr`),` `,s(o)]}),(0,m.jsxs)(`span`,{children:[i.length,` `,r(`roundsUnit`)]})]})]})}let $n=[`color-mix(in srgb, var(--dsb-3) 70%, transparent)`,`color-mix(in srgb, var(--ds-cyan) 30%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 60%, var(--dsb-3))`,`var(--ds-blue)`,`var(--ds-amber)`],er=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],tr=e=>G(e.getTime());function nr(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:tr(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:tr(e),dayNum:e.getDate(),value:0,level:0,placeholder:!0});continue}let d=new Date(i,a,u),f=tr(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 rr(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=tr(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=tr(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 ir({days:e,currency:t,now:n,t:r,range:i=`month`,unit:a=`cost`}){let[o,s]=(0,d.useState)(null),c=e=>W(gn(e,t),t),l=e=>a===`tokens`?K(e):c(e),u=(0,d.useMemo)(()=>nr(e,n??new Date),[e,n]),f=tr(n??new Date);if(i!==`month`){let t=rr(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:er[n-1]??``}),o=n)}),(0,m.jsxs)(`div`,{className:L.heatmapYear+(i===`half`?` `+L.heatmapHalf:``),"data-testid":i===`half`?`heatmap-half`:`heatmap-year`,children:[(0,m.jsxs)(`div`,{className:L.heatmapYearBody,children:[(0,m.jsx)(`div`,{className:L.heatmapYearWeekdays,"aria-hidden":`true`,children:[{label:`Mon`,row:1},{label:`Wed`,row:3},{label:`Fri`,row:5}].map(e=>(0,m.jsx)(`span`,{className:L.heatmapYearWeekday,style:{gridRow:e.row},children:e.label},e.label))}),(0,m.jsxs)(`div`,{className:L.heatmapYearScroll,children:[(0,m.jsx)(`div`,{className:L.heatmapYearMonths,"aria-hidden":`true`,"data-testid":`heatmap-year-months`,children:a.map(e=>(0,m.jsx)(`span`,{className:L.heatmapYearMonth,style:{gridColumn:e.index+1},children:e.label},e.index))}),(0,m.jsx)(`div`,{className:L.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:L.heatmapYearCell,"data-testid":`heatmap-year-cell`,"data-level":e.level,"data-today":e.date===f?`true`:void 0,style:{background:$n[e.level]},title:`${e.date} · ${l(e.value)}`,"aria-label":`${e.date}: ${l(e.value)}`,tabIndex:-1},e.date))})]})]}),(0,m.jsxs)(`div`,{className:L.heatmapFooter,children:[(0,m.jsx)(`span`,{children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:L.heatmapLegend,children:$n.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{children:r(`heatmapMore`)})]})]})}return(0,m.jsxs)(`div`,{className:L.heatmap,children:[(0,m.jsx)(`div`,{className:L.heatmapGrid,role:`img`,"aria-label":`daily cost heatmap`,children:u.map(e=>e.map(e=>e.placeholder?(0,m.jsx)(`div`,{className:L.heatmapCellEmpty,children:e.dayNum},e.date):(0,m.jsx)(`button`,{type:`button`,className:L.heatmapCell,"data-testid":`heatmap-cell`,"data-level":e.level,"data-today":e.date===f?`true`:void 0,style:{background:$n[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:L.heatmapFooter,children:[(0,m.jsx)(`span`,{children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:L.heatmapLegend,children:$n.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{children:r(`heatmapMore`)}),o!==null&&(0,m.jsxs)(`span`,{className:L.heatmapHover,"data-testid":`heatmap-hover`,children:[o.date,` · `,l(o.value)]})]})]})}let ar={window:6,threshold:2,reasonFactor:1.8,reasonHitDropPp:15};function X(e){if(e.length===0)return null;let t=0;for(let n of e)t+=n;return t/e.length}function or(e){let t=e.cacheHit+e.cacheMiss;return t<=0?null:e.cacheHit/t*100}function sr(e,t){let n=t?.window??ar.window,r=t?.threshold??ar.threshold,i=t?.reasonFactor??ar.reasonFactor,a=t?.reasonHitDropPp??ar.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=or(t),p=X(s),m=[];if(p!==null&&p>0&&t.cost>p*r){let n=X(c),r=X(l),s=X(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}let cr={},lr={};function ur(){return(0,h.defineStore)({init:()=>({enabled:!1,amount:0,tierAlertDays:{},lastBalanceAlertDay:``,lastTierSwitchAt:0,modelBudgets:{},modelTierAlertDays:{}}),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},setModelBudget:(e,t,n)=>{e.modelBudgets??={},Number.isFinite(n)&&n>0?e.modelBudgets[t]=n:delete e.modelBudgets[t]},markModelTierAlerted:(e,t,n)=>{e.modelTierAlertDays??={};for(let r of t)e.modelTierAlertDays[r]=n}}})}function dr(e,t){return e==null?null:Number.isFinite(e.nextSwitchInMs)&&e.nextSwitchInMs<=t?`soon`:e.tier===`peak`?`peak`:`offPeak`}let fr={显式缓存创建:`Explicit cache write`,显式缓存命中:`Explicit cache hit`,长期半价:`Half price`,与标准价一致:`Same as standard`,"限时 5 折":`Limited-time 50% off`};function pr(e,t){return e===void 0||t!==`en`?e:fr[e]??e}function mr(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 hr={"智谱 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 gr(e,t){return t===`en`?hr[e]??e:e}let _r={workbuddy:`WorkBuddy`,"workbuddy-ai":`WorkBuddy AI`},vr={"https://tokenhub.tencentmaas.com":`腾讯云 TokenHub`,"https://api.lkeap.cloud.tencent.com":`腾讯云 Token Plan`,"https://api.deepseek.com":`DeepSeek 官方`},yr={"腾讯云 TokenHub":`Tencent Cloud TokenHub`,"腾讯云 Token Plan":`Tencent Cloud Token Plan`,"DeepSeek 官方":`DeepSeek Official`};function br(e){try{return new URL(e).host}catch{return e}}function xr(e,t=`zh`){if(e.startsWith(`site:`)){let n=e.slice(5),r=vr[n];return r===void 0?br(n):t===`en`?yr[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=_r[n.trim().toLowerCase()];return r===void 0?`${t===`en`?`Direct`:`直连`} · ${n}`:`${t===`en`?`Direct`:`直连`} · ${r}`}}let Sr=[`直连 · `,`Direct · `];function Cr(e){for(let t of Sr)if(e.startsWith(t))return e.slice(t.length)}function wr(e){let t=e;for(;t!==null&&t.parentElement!==null;){let e=t.parentElement;if(e===document.body||e===document.documentElement)return null;let n=getComputedStyle(e);if(n.display!==`contents`&&n.display.includes(`flex`))return e;t=e}return null}function Tr(e,t){let n=e.clientWidth>0,r=0,i=e=>{if(e.contains(t))return;let a=getComputedStyle(e);if(a.display!==`none`&&a.visibility!==`hidden`&&a.position!==`absolute`&&a.position!==`fixed`){if(a.display===`contents`){for(let t of Array.from(e.children))i(t);return}if(n){let t=e.getBoundingClientRect();if(t.width===0&&t.height===0)return}r+=1}};for(let t of Array.from(e.children))i(t);return r}function Er(e){let t=wr(e);return t===null?{row:null,stacked:!1,neighbors:0}:{row:t,stacked:getComputedStyle(t).flexDirection===`column`,neighbors:Tr(t,e)}}function Dr(e){return e.row===null?`card`:e.stacked||e.neighbors>0?`icon`:`card`}function Or(e,t){let n,r=()=>{let r=Dr(Er(e));r!==n&&(n=r,t(r))},i=wr(e),a=typeof ResizeObserver==`function`?new ResizeObserver(()=>r()):void 0,o=typeof MutationObserver==`function`?new MutationObserver(()=>r()):void 0;return a?.observe(e),i!==null&&(a?.observe(i),o?.observe(i,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`class`,`hidden`]})),window.addEventListener(`resize`,r),r(),{dispose(){a?.disconnect(),o?.disconnect(),window.removeEventListener(`resize`,r)}}}let kr=`dsh-billing-peak-alert-v1`,Ar={enabled:!1,leadMin:2,position:`bottom-right`,webNotify:!0,mode:`both`};function jr(e,t,n){return t===null||n<=0?e:e===null?{...t,queueCount:n}:e.atMs===t.atMs&&e.entering===t.entering?{...e,queueCount:n}:e}function Mr(e,t){if(e===null||e.queueCount===void 0)return e;if(t>0)return e.queueCount===t?e:{...e,queueCount:t};let{queueCount:n,...r}=e;return r}function Nr(){try{let e=localStorage.getItem(kr);if(e===null)return{...Ar};let t=JSON.parse(e),n=t.mode===`peak`||t.mode===`offPeak`?t.mode:Ar.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))):Ar.leadMin,position:r,webNotify:t.webNotify!==!1,mode:n}}catch{return{...Ar}}}function Pr(e){try{localStorage.setItem(kr,JSON.stringify(e))}catch{x(`peak-config-storage-unavailable`)}}function Fr(e,t,n,r){if(!t.enabled)return null;let i=Vt(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}}let Ir=[50,80,100],Lr=3e4,Rr=`dsh-billing-root`,zr={total:{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cost:0,reasoning:0},byModel:{},byDay:{},byDayModels:{}},Br=[`#4f8cff`,`#2dd4bf`,`#a78bfa`,`#f59e0b`,`#f472b6`,`#fbbf24`,`#38bdf8`,`#6366f1`,`#f97316`,`#14b8a6`];function Vr({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(L.peakCard,Rr,u?L.peakCardPeak:L.peakCardOff,t.position===`center`?L.peakCardCenter:L.peakCardCorner),"data-testid":`billing-peak-alert`,role:`alert`,children:[(0,m.jsxs)(`div`,{className:L.peakHead,children:[(0,m.jsxs)(`span`,{className:y(L.peakTag,u?L.peakTagPrimary:L.peakTagSuccess),children:[(0,m.jsx)(`span`,{className:y(L.peakDot,u?L.peakDotPrimary:L.peakDotSuccess),"aria-hidden":`true`}),c]}),(0,m.jsx)(`button`,{type:`button`,className:L.peakClose,onClick:r,"aria-label":n(`close`),children:`×`})]}),(0,m.jsxs)(`div`,{className:y(L.peakCount,u?L.peakCountPrimary:L.peakCountSuccess),children:[o,`min`]}),(0,m.jsx)(`p`,{className:L.peakDesc,children:l}),e.queueCount!==void 0&&e.queueCount>0&&(0,m.jsx)(`p`,{className:L.peakDesc,"data-testid":`billing-peak-queue-note`,children:n(s===`peak`?`peakAlertQueuePeak`:`peakAlertQueueOff`,{count:e.queueCount})})]})}let Hr={checked:!1,available:!1,models:0,failures:0,okProviders:[],badProviders:[]},Ur=[{id:`overview`,labelKey:`tabOverview`},{id:`queue`,labelKey:`tabQueue`},{id:`providers`,labelKey:`tabProviders`},{id:`token`,labelKey:`tabToken`},{id:`trends`,labelKey:`tabTrends`},{id:`agents`,labelKey:`tabAgents`},{id:`pricing`,labelKey:`tabPricing`},{id:`settings`,labelKey:`tabSettings`}],Wr={fill:`none`,"aria-hidden":!0,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`},Gr={overview:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:(0,m.jsx)(`path`,{d:`M2 13V3M2 13H14M4 10l4-3 2 2 4-5`})}),queue:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:[(0,m.jsx)(`path`,{d:`M3 4h10M3 8h10M3 12h6`}),(0,m.jsx)(`path`,{d:`M12 10v4m-2-2h4`})]}),agents:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`3.5`,r:`2`}),(0,m.jsx)(`circle`,{cx:`3.5`,cy:`12.5`,r:`2`}),(0,m.jsx)(`circle`,{cx:`12.5`,cy:`12.5`,r:`2`}),(0,m.jsx)(`path`,{d:`M8 5.5v2.5M6.5 10.5L5 11.5M9.5 10.5L11 11.5`})]}),providers:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:[(0,m.jsx)(`rect`,{x:`2`,y:`3`,width:`12`,height:`10`,rx:`1.5`}),(0,m.jsx)(`path`,{d:`M5 7l2 2 4-4`})]}),token:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:[(0,m.jsx)(`circle`,{cx:`6`,cy:`6`,r:`3`}),(0,m.jsx)(`circle`,{cx:`11`,cy:`11`,r:`3`})]}),trends:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:(0,m.jsx)(`path`,{d:`M2 4l4 4 3-3 5 5M11 10h3V7`})}),pricing:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:[(0,m.jsx)(`path`,{d:`M8 2l6 3v6l-6 3-6-3V5z`}),(0,m.jsx)(`path`,{d:`M8 2v12M2 5h12`})]}),settings:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Wr,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`8`,r:`2.5`}),(0,m.jsx)(`path`,{d:`M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2`})]})},Kr=p,qr=Kr.IconChevronDownOutlineMedium??Kr.IconChevronDownOutline14;function Jr(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 Yr(e,t){let n=t.split(`-`),r=new Date(Number(n[0]),Number(n[1])-1,Number(n[2])),i=0;for(let t=0;t<7;t+=1){let t=`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,`0`)}-${String(r.getDate()).padStart(2,`0`)}`;i+=e[t]?.cost??0,r.setDate(r.getDate()-1)}return i/7}function Xr(e,t,n){let r=Object.keys(e).filter(e=>e.startsWith(t)).reduce((t,n)=>t+(e[n]?.cost??0),0),i=t.split(`-`),a=new Date(Number(i[0]),Number(i[1]),0).getDate(),o=n.startsWith(t)?Number(n.slice(8,10)):a,s=Math.max(0,a-o);return r<=0?Jr(e,n)*s:r+Yr(e,n)*s}function Zr(e){return Object.keys(e).length}function Qr(e,t=Date.now()){let n=0,r=new Date(t);for(;G(r.getTime())in e;)n+=1,r.setDate(r.getDate()-1);return n}function $r(e){return e.input+e.output}function ei(e){let t=[];for(let n=6;n>=0;--n){let r=new Date;r.setDate(r.getDate()-n);let i=G(r.getTime());t.push({date:i,cost:e[i]?.cost??0})}return t}function ti(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[G(i.getTime())];o!==void 0&&(a+=n(o))}return a}function ni(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=G(a.getTime()),s=new Date(r);s.setDate(s.getDate()-6);let c=G(s.getTime());return ii(e,e=>n===`today`?e===t:n===`7d`?e>=c&&e<=t:n===`week`?e>=o&&e<=t:e.startsWith(t.slice(0,7)))}function ri(e,t,n){return ii(e,e=>e>=t&&e<=n)}function ii(e,t){let n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0,u,d=0;for(let[f,p]of Object.entries(e)){if(!t(f))continue;n+=p.cost,r+=p.calls,i+=p.input,a+=p.output,o+=p.cacheHit,s+=p.cacheMiss,c+=p.cacheWrite??0,l+=p.reasoning??0;let e=$r(p);e>d&&(d=e,u=f)}return{cost:n,calls:r,input:i,output:a,cacheHit:o,cacheMiss:s,cacheWrite:c,reasoning:l,peakDay:u,peakTokens:d}}function ai(e,t){let n={};if(e===void 0)return n;for(let[r,i]of Object.entries(e))if(r.startsWith(t))for(let[e,t]of Object.entries(i))n[e]=(n[e]??0)+t.cost;return n}let oi=[80,100];function si(e,t){if(!(t>0)||!(e>0))return[];let n=e/t*100;return oi.filter(e=>n>=e)}let ci={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 Z(e){return e.trim().toLowerCase().replace(/[\s_/-]+/g,``)}function li(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 ui(e,t){let n=Z(e),r=Z(t);if(li(n,r))return!0;let i=ci[e];return i!==void 0&&i.some(e=>li(Z(e),r))}function di(e){let t=e.trim().toLowerCase(),n=t.replace(/[\s_/-]+/g,``);if(n.length!==0){for(let[e,n]of Object.entries(ci))for(let r of n){let n=Z(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(ci))for(let r of t){let t=Z(r);if(!(t.length<4)&&n.includes(t))return e}}}let fi={"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 pi(e){let t=fi[e];return t===void 0?di(e)??e:t}let mi=`https://platform.kimi.com/console/pay`,hi=`https://open.bigmodel.cn/finance-center/finance/pay`,gi=`https://bailian.console.aliyun.com/`,_i=`https://console.volcengine.com/ark`,vi=`https://console.anthropic.com/settings/billing`,yi=`https://console.cloud.google.com/billing`,bi=`https://console.x.ai/`,xi=`https://platform.xiaomimimo.com/console/balance`,Si=`https://console.cloud.tencent.com/expense/recharge`,Ci={deepseek:`https://platform.deepseek.com/top_up`,minimax:`https://platform.minimax.cn/console/recharge-records`,moonshot:mi,kimi:mi,zhipu:hi,bigmodel:hi,qwen:gi,dashscope:gi,doubao:_i,volcengine:_i,ark:_i,openai:`https://platform.openai.com/settings/organization/billing`,anthropic:vi,claude:vi,google:yi,gemini:yi,xai:bi,grok:bi,siliconflow:`https://cloud.siliconflow.cn/account/charge`,hunyuan:Si,tencent:Si,腾讯云:Si,xiaomi:xi,mimo:xi,mi:xi,qianfan:`https://console.bce.baidu.com/qianfan/overview`};function wi(e){let t=Ci[e];if(t!==void 0)return t;let n=Object.keys(Ci).find(t=>e.startsWith(t));return n===void 0?void 0:Ci[n]}function Ti(e){let t=Z(e),n=wi(t);if(n!==void 0)return n;for(let[e,n]of Object.entries(ci))if(li(Z(e),t))for(let e of n){let t=wi(Z(e));if(t!==void 0)return t}}function Ei(e){let t=vt();if(t===void 0||e.byDayModels===void 0)return e;let n=Et().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||U(t.key)===U(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)*Ot+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=bt(i)??xt(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:bt(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=>!bt(e)&&!xt(e))}}function Di(){return{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cacheWrite:0,cost:0}}function Oi(e,t){e.calls+=t.calls,e.input+=t.input,e.output+=t.output,e.cacheHit+=t.cacheHit,e.cacheMiss+=t.cacheMiss,e.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost}function ki(e,t){e.calls-=t.calls,e.input-=t.input,e.output-=t.output,e.cacheHit-=t.cacheHit,e.cacheMiss-=t.cacheMiss,e.cacheWrite=(e.cacheWrite??0)-t.cacheWrite,e.cost-=t.cost}function Ai(e){let t=e.byDayModelsSite;if(t===void 0)return[];let n=new Map;for(let e of Object.values(t))for(let t of Object.values(e))for(let[e,r]of Object.entries(t)){let t=n.get(e)??Di();Oi(t,r),n.set(e,t)}return[...n.entries()].map(([e,t])=>({siteKey:e,calls:t.calls,input:t.input,output:t.output,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,cost:t.cost})).sort((e,t)=>t.cost===e.cost?e.siteKey.localeCompare(t.siteKey):t.cost-e.cost)}function ji(e,t){let n=new Map;for(let r of e){let e=t(r.siteKey),i=n.get(e)??{siteKeys:[],calls:0,tokens:0,cost:0};i.siteKeys.push(r.siteKey),i.calls+=r.calls,i.tokens+=r.input+r.output,i.cost+=r.cost,n.set(e,i)}return[...n.entries()].map(([e,t])=>({name:e,...t})).sort((e,t)=>t.cost===e.cost?e.name.localeCompare(t.name,`zh`):t.cost-e.cost)}function Mi(e,t){if(t.size===0)return e;let n=e.byDayModelsSite;if(n===void 0)return e;let r=new Map,i=new Map,a=new Map,o=Di(),s={};for(let[e,c]of Object.entries(n)){let n={};for(let[s,l]of Object.entries(c)){let c={};for(let[n,u]of Object.entries(l)){if(t.has(n)){let t=r.get(e)??new Map,n=t.get(s)??Di();Oi(n,u),t.set(s,n),r.set(e,t);let c=i.get(e)??Di();Oi(c,u),i.set(e,c);let l=a.get(s)??Di();Oi(l,u),a.set(s,l),Oi(o,u);continue}c[n]=u}Object.keys(c).length>0&&(n[s]=c)}s[e]=n}let c={};for(let[t,n]of Object.entries(e.byDay)){let e=i.get(t);if(e===void 0){c[t]=n;continue}let r={...n};ki(r,e),c[t]=r}let l={};for(let[t,n]of Object.entries(e.byDayModels??{})){let e={};for(let[i,a]of Object.entries(n)){let n={...a},o=r.get(t)?.get(i);o!==void 0&&ki(n,o),e[i]=n}l[t]=e}let u={};for(let[t,n]of Object.entries(e.byModel)){let e={...n},r=a.get(t);r!==void 0&&ki(e,r),u[t]=e}let d={};for(let[n,r]of Object.entries(e.bySite??{}))t.has(n)||(d[n]=r);let f={...e.total};return ki(f,o),{...e,total:f,byDay:c,byDayModels:l,byModel:u,bySite:d,byDayModelsSite:s}}async function Q(e,t={}){let{timeoutMs:n=12e3,signal:r,...i}=t,a=new AbortController,o=setTimeout(()=>{a.abort()},n),s=()=>{a.abort()};r!=null&&(r.aborted?a.abort():r.addEventListener(`abort`,s,{once:!0}));try{return await fetch(e,{...i,signal:a.signal})}finally{clearTimeout(o),r?.removeEventListener(`abort`,s)}}let Ni=new Set;function Pi(){return typeof Notification<`u`&&Notification.permission===`granted`}function Fi(e,t){Ni.has(e)||(Ni.add(e),Q(`/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 Ii(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 Li(e){let t=new Map(e.map(e=>[e.id,e])),n=Ii(e.filter(e=>e.parentId===void 0)),r=new Map;for(let e of n){r.set(e.id,e);for(let t of e.children??[])r.set(t.id,e)}let i=new Set,a=new Map,o=(e,t)=>{e.subs===void 0?e.subs=[t]:e.subs.push(t),i.add(t.id),a.set(t.id,e.id)};for(let n of e){if(n.parentId===void 0)continue;let e=t.get(n.parentId);if(e!==void 0&&e.parentId!==void 0&&e.id!==n.id){let t=e.id,r=new Set,i=!1;for(;t!==void 0&&!r.has(t);){if(r.add(t),t===n.id){i=!0;break}t=a.get(t)}if(!i){o(e,n);continue}}let s=new Set,c=n.parentId;for(;c!==void 0&&!s.has(c);){s.add(c);let e=r.get(c);if(e!==void 0){i.has(n.id)||o(e,n);break}c=t.get(c)?.parentId}}let s=e=>e.cost+(e.subCost??0),c=e=>{e.subs?.sort((e,t)=>s(t)-s(e)||t.lastActive-e.lastActive);for(let t of e.subs??[])c(t)};for(let e of n)c(e);let l=e.filter(e=>e.parentId!==void 0&&!i.has(e.id));for(let e of l)c(e);return[...n,...l].sort((e,t)=>t.cost-e.cost||t.lastActive-e.lastActive)}function Ri(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,n);let n=new Map,r=[];for(let i of e){let e=i.parentId;if(e===void 0||!t.has(e)||zi(t,i.id)){r.push(i);continue}let a=n.get(e);a===void 0?n.set(e,[i]):a.push(i)}let i=(e,t,r)=>{let a=new Set(r);a.add(e.id);let o=(n.get(e.id)??[]).filter(e=>!r.has(e.id)).map(e=>i(e,t+1,a)).sort((e,t)=>t.chainCost-e.chainCost),s={id:e.id,...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},calls:e.calls,cost:e.cost,lastActive:e.lastActive,chainCost:e.cost,chainCalls:e.calls,children:o,depth:t};for(let e of o)s.chainCost+=e.chainCost,s.chainCalls+=e.chainCalls;return s};return r.map(e=>i(e,0,new Set)).sort((e,t)=>t.chainCost-e.chainCost)}function zi(e,t){let n=new Set([t]),r=e.get(t)?.parentId;for(;r!==void 0;){if(n.has(r))return!0;n.add(r),r=e.get(r)?.parentId}return!1}function Bi(e){let t=0,n=0,r,i=e=>{t+=1,n+=e.children.length,(r===void 0||e.chainCost>r.chainCost)&&(r=e);for(let t of e.children)i(t)};for(let t of e)i(t);return{agents:t,delegations:n,roots:e.length,...r===void 0?{}:{costliest:r}}}function Vi(e,t){let n=t.trim().toLowerCase();return n===``?e:e.filter(e=>(e.title??``).toLowerCase().includes(n)||(e.cwd??``).toLowerCase().includes(n)||e.id.toLowerCase().includes(n))}function Hi(e,t){let n=e.trim().toLowerCase();return n!==``&&!t.some(e=>e.toLowerCase().includes(n))}function Ui(e,t){return e.checked?e.okProviders.some(e=>ui(t,e))?L.healthOk:e.badProviders.some(e=>ui(t,e))?L.healthBad:L.healthIdle:L.healthIdle}function Wi(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 Gi(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 Ki(e,t){switch(e){case`new-api`:return t(`relayKindNewApi`);case`sub2api`:return t(`relayKindSub2Api`);default:return t(`relayKindUnknown`)}}let qi={"new-api":L.siteKindSite,sub2api:L.siteKindDirect,unknown:L.siteKindUnknown},Ji=e=>e.models.reduce((e,t)=>e+(t.actual??(t.plan===!0?0:t.estimated)),0);function Yi(e){return e.children===void 0?{cost:e.subCost??0,calls:e.subCalls??0}:(e.children??[]).reduce((e,t)=>({cost:e.cost+(t.subCost??0),calls:e.calls+(t.subCalls??0)}),{cost:0,calls:0})}function Xi(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Zi(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;for(let e of[`sessionListError`,`error`]){let t=n[e];if(typeof t==`string`&&t!==``)return t}return}catch{return}}async function Qi(){try{let e=await Q(`/api/billing/usage-stats`),t=await e.text();if(!e.ok)return{ok:!1,reason:Zi(t)??`HTTP ${e.status}`,status:e.status};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{ok:!1,reason:`响应不是统计文档`};if(!(`total`in n))return{ok:!1,reason:Zi(t)??`响应不是统计文档`};let r=n,i=e=>typeof e==`object`&&!!e;return{ok:!0,stats:{total:r.total??zr.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},...r.staleSnapshot===!0?{staleSnapshot:!0}:{},...typeof r.budget==`number`?{budget:r.budget}:{},...typeof r.lowBalanceThreshold==`number`?{lowBalanceThreshold:r.lowBalanceThreshold}:{},...Array.isArray(r.bySession)?{bySession:r.bySession}:{},...typeof r.bySessionTotal==`number`?{bySessionTotal:r.bySessionTotal}:{},...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}:{},...typeof r.sessionListError==`string`?{sessionListError:r.sessionListError}:{}}}}catch(e){return{ok:!1,reason:e instanceof Error?e.message:String(e)}}}async function $i(){try{let e=await Q(`/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},...r.stale===!0?{stale:!0}:{}}}catch{return{balances:[]}}}async function ea(){let e=await Q(`/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){let e=n;return{quotas:e.quotas,...e.stale===!0?{stale:!0}:{}}}throw Error(`subscriptions: invalid response`)}async function ta(){let e=await Q(`/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 na(){try{let e=await Q(`/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 ra(e){try{let t=await Q(`/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 ia=!1,aa=0;async function oa(e=0){try{let t=await Q(`/api/billing/pricing`);if(!t.ok){ia=!1;return}let n=await t.text(),r=JSON.parse(n);if(typeof r!=`object`||!r||!(`source`in r)){ia=!1;return}let i=r;Array.isArray(i.catalog)&&i.catalog.length>0&&i.aliases!==null&&typeof i.aliases==`object`&&Gt(i.catalog,i.aliases);let a=r;if(a.source===`builtin`&&e<3){if(e===0){if(ia)return;ia=!0}setTimeout(()=>{oa(e+1)},2e3);return}ia=!1,aa=a.syncedAt??0,St(a)}catch{ia=!1}}async function sa(){try{return(await Q(`/api/billing/pricing/refresh`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`,timeoutMs:3e4})).ok?(await oa(),!0):!1}catch{return!1}}async function ca(e){try{let t=JSON.parse(await e.text());return typeof t.error==`string`?t.error:`HTTP ${e.status}`}catch{return`HTTP ${e.status}`}}async function la(e=!1){let t=await Q(`/api/billing/task-queue${e?`?refresh=1`:``}`);if(!t.ok)throw Error(await ca(t));return await t.json()}async function ua(){let e=await Q(`/api/billing/task-queue-summary`);if(!e.ok)throw Error(await ca(e));return await e.json()}async function da(e){let t=await Q(`/api/billing/task-queue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok)throw Error(await ca(t));return(await t.json()).snapshot}let fa=`@kenz1117/dsh-ui-usage-billing/TaskQueuePanel.module.css`;if(typeof document<`u`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(fa)+`]`)===null){let e=document.createElement(`style`);e.dataset.plugin=`@kenz1117/dsh-ui-usage-billing`,e.dataset.pluginCss=fa,e.textContent=`.cQSERa_queuePanel{color:var(--ds-t-1);flex-direction:column;flex-shrink:0;gap:12px;display:flex}.cQSERa_queuePanel *{box-sizing:border-box}.cQSERa_queueHero,.cQSERa_queueComposer,.cQSERa_queueListSection,.cQSERa_queueUnsupported{border:1px solid var(--ds-border);border-radius:var(--ds-r-2);background:var(--dsb-2);flex-shrink:0}.cQSERa_queueHero{justify-content:space-between;align-items:center;gap:16px;padding:16px;display:flex}.cQSERa_queueTitleRow{align-items:center;gap:8px;display:flex}.cQSERa_queueTitle,.cQSERa_queueListHead h3,.cQSERa_queueUnsupported h3{margin:0;font-size:15px;font-weight:650}.cQSERa_queuePreview{background:var(--ds-violet-soft);color:var(--ds-violet);text-transform:uppercase;border-radius:5px;padding:2px 6px;font-size:10px;font-weight:700}.cQSERa_queueSubtitle{color:var(--ds-t-2);margin:5px 0 0;font-size:12px;line-height:1.6}.cQSERa_queueBand{color:var(--ds-t-2);flex-direction:column;flex-shrink:0;align-items:flex-end;gap:3px;font-size:11px;display:flex}.cQSERa_queueBand strong{font-size:13px}.cQSERa_queueBandOff strong{color:var(--ds-green)}.cQSERa_queueBandPeak strong{color:var(--ds-amber)}.cQSERa_queueComposer{flex-direction:column;gap:12px;padding:14px;display:flex}.cQSERa_queueSafety{border-radius:var(--ds-r-1);background:color-mix(in srgb, var(--ds-amber) 8%, transparent);color:var(--ds-t-2);padding:9px 11px;font-size:11px;line-height:1.65}.cQSERa_queueSafetyMode{color:var(--ds-t-3);margin-top:4px;display:block}.cQSERa_queueSelectors{grid-template-columns:1fr 1fr;gap:10px;display:grid}.cQSERa_queueField,.cQSERa_queuePromptField{color:var(--ds-t-2);flex-direction:column;gap:6px;font-size:11px;display:flex}.cQSERa_queueField select,.cQSERa_queuePromptField textarea{border:1px solid var(--ds-border);border-radius:var(--ds-r-1);background:var(--dsb);width:100%;color:var(--ds-t-1);font:inherit}.cQSERa_queueField select{height:34px;padding:0 9px}.cQSERa_queuePromptField textarea{resize:vertical;min-height:112px;padding:10px;line-height:1.55}.cQSERa_queueField select:focus,.cQSERa_queuePromptField textarea:focus{outline:2px solid color-mix(in srgb, var(--ds-blue) 35%, transparent);border-color:var(--ds-blue)}.cQSERa_queueField select:disabled,.cQSERa_queuePromptField textarea:disabled{opacity:.55}.cQSERa_queueComposerFooter{color:var(--ds-t-3);justify-content:space-between;align-items:center;gap:12px;font-size:10px;line-height:1.5;display:flex}.cQSERa_queueComposerActions{flex-shrink:0;align-items:center;gap:8px;display:flex}.cQSERa_queueFileInput{display:none}.cQSERa_queuePrimary,.cQSERa_queueSecondary{border-radius:var(--ds-r-1);cursor:pointer;flex-shrink:0;min-height:34px;padding:0 16px;font-weight:600}.cQSERa_queuePrimary{background:var(--ds-blue);color:#fff;border:0}.cQSERa_queueSecondary{border:1px solid var(--ds-border);background:var(--dsb);color:var(--ds-t-1)}.cQSERa_queuePrimary:disabled,.cQSERa_queueSecondary:disabled{opacity:.45;cursor:not-allowed}.cQSERa_queueListSection{padding:12px 14px}.cQSERa_queueListHead{justify-content:space-between;align-items:center;margin-bottom:8px;display:flex}.cQSERa_queueListHead h3 span{color:var(--ds-t-3);margin-left:4px;font-size:11px;font-weight:500}.cQSERa_queueList{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.cQSERa_queueTask{border:1px solid var(--ds-border);border-radius:var(--ds-r-1);background:var(--dsb);padding:10px}.cQSERa_queueTaskHead{align-items:center;gap:8px;min-width:0;display:flex}.cQSERa_queueStatus{background:var(--dsb-3);color:var(--ds-t-2);border-radius:5px;flex-shrink:0;padding:2px 6px;font-size:10px;font-weight:650}.cQSERa_queueStatus_running,.cQSERa_queueStatus_starting{color:var(--ds-blue);background:color-mix(in srgb, var(--ds-blue) 12%, transparent)}.cQSERa_queueStatus_completed{color:var(--ds-green);background:color-mix(in srgb, var(--ds-green) 12%, transparent)}.cQSERa_queueStatus_failed{color:var(--ds-red);background:color-mix(in srgb, var(--ds-red) 10%, transparent)}.cQSERa_queueTaskMeta{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--ds-t-2);font-size:11px;overflow:hidden}.cQSERa_queueTaskTime{color:var(--ds-t-3);flex-shrink:0;margin-left:auto;font-size:10px}.cQSERa_queueTaskTarget{color:var(--ds-t-2);overflow-wrap:anywhere;flex-wrap:wrap;align-items:baseline;gap:6px;margin-top:6px;font-size:11px;line-height:1.5;display:flex}.cQSERa_queueTaskTargetNote{color:var(--ds-t-3);font-size:10px}.cQSERa_queuePrompt{color:var(--ds-t-1);margin-top:8px;font-size:12px;line-height:1.55}.cQSERa_queuePrompt summary{text-overflow:ellipsis;white-space:nowrap;cursor:pointer;overflow:hidden}.cQSERa_queuePrompt pre{background:var(--dsb-2);white-space:pre-wrap;overflow-wrap:anywhere;max-height:240px;font-family:var(--mono);border-radius:6px;margin:8px 0 0;padding:9px;font-size:11px;line-height:1.55;overflow:auto}.cQSERa_queueTaskError{color:var(--ds-red);overflow-wrap:anywhere;margin-top:8px;font-size:11px;line-height:1.5}.cQSERa_queueTaskActions{justify-content:flex-end;gap:10px;margin-top:5px;display:flex}.cQSERa_queueLinkButton{color:var(--ds-blue);cursor:pointer;background:0 0;border:0;padding:2px 0;font-size:11px}.cQSERa_queueLinkButton:disabled{opacity:.45;cursor:not-allowed}.cQSERa_queueEmpty{color:var(--ds-t-3);text-align:center;padding:26px 12px;font-size:12px}.cQSERa_queueUnsupported{padding:22px}.cQSERa_queueUnsupported p{color:var(--ds-t-2);margin:8px 0 0;font-size:12px;line-height:1.7}.cQSERa_queueNotice,.cQSERa_queueNoticeError{border-radius:var(--ds-r-1);overflow-wrap:anywhere;flex-shrink:0;padding:9px 11px;font-size:11px;line-height:1.5}.cQSERa_queueNotice{background:var(--dsb-2);color:var(--ds-t-2)}.cQSERa_queueNoticeError{background:color-mix(in srgb, var(--ds-red) 10%, transparent);color:var(--ds-red)}@media (width<=640px){.cQSERa_queueHero{align-items:flex-start}.cQSERa_queueSelectors{grid-template-columns:1fr}.cQSERa_queueComposerFooter{flex-direction:column;align-items:stretch}.cQSERa_queueComposerActions{flex-wrap:wrap;justify-content:flex-end}.cQSERa_queueTaskTime{display:none}}`,document.head.appendChild(e)}var $={queueBand:`cQSERa_queueBand`,queueBandOff:`cQSERa_queueBandOff`,queueBandPeak:`cQSERa_queueBandPeak`,queueComposer:`cQSERa_queueComposer`,queueComposerActions:`cQSERa_queueComposerActions`,queueComposerFooter:`cQSERa_queueComposerFooter`,queueEmpty:`cQSERa_queueEmpty`,queueField:`cQSERa_queueField`,queueFileInput:`cQSERa_queueFileInput`,queueHero:`cQSERa_queueHero`,queueLinkButton:`cQSERa_queueLinkButton`,queueList:`cQSERa_queueList`,queueListHead:`cQSERa_queueListHead`,queueListSection:`cQSERa_queueListSection`,queueNotice:`cQSERa_queueNotice`,queueNoticeError:`cQSERa_queueNoticeError`,queuePanel:`cQSERa_queuePanel`,queuePreview:`cQSERa_queuePreview`,queuePrimary:`cQSERa_queuePrimary`,queuePrompt:`cQSERa_queuePrompt`,queuePromptField:`cQSERa_queuePromptField`,queueSafety:`cQSERa_queueSafety`,queueSafetyMode:`cQSERa_queueSafetyMode`,queueSecondary:`cQSERa_queueSecondary`,queueSelectors:`cQSERa_queueSelectors`,queueStatus:`cQSERa_queueStatus`,queueStatus_completed:`cQSERa_queueStatus_completed`,queueStatus_failed:`cQSERa_queueStatus_failed`,queueStatus_running:`cQSERa_queueStatus_running`,queueStatus_starting:`cQSERa_queueStatus_starting`,queueSubtitle:`cQSERa_queueSubtitle`,queueTask:`cQSERa_queueTask`,queueTaskActions:`cQSERa_queueTaskActions`,queueTaskError:`cQSERa_queueTaskError`,queueTaskHead:`cQSERa_queueTaskHead`,queueTaskMeta:`cQSERa_queueTaskMeta`,queueTaskTarget:`cQSERa_queueTaskTarget`,queueTaskTargetNote:`cQSERa_queueTaskTargetNote`,queueTaskTime:`cQSERa_queueTaskTime`,queueTitle:`cQSERa_queueTitle`,queueTitleRow:`cQSERa_queueTitleRow`,queueUnsupported:`cQSERa_queueUnsupported`};let pa={queued:`queueStatusQueued`,starting:`queueStatusStarting`,running:`queueStatusRunning`,completed:`queueStatusCompleted`,failed:`queueStatusFailed`};function ma(e){return e.status===`completed`||e.status===`failed`}function ha(e,t){return JSON.stringify([e,t])}function ga(e){let t=e.startsWith(`session-`)?e.slice(8):e;return t.length<=8?t:t.slice(0,8)}function _a(e,t){let n;try{n=JSON.parse(e)}catch{throw Error(`invalid task import`)}if(!Array.isArray(n)||n.length===0)throw Error(`invalid task import`);return n.map(e=>{if(typeof e==`string`)return{prompt:e,...t};if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid task import`);let n=e;return{prompt:n.prompt,cwd:n.cwd??t.cwd,provider:n.provider??t.provider,model:n.model??t.model}})}function va({t:e,language:t,navigateToSession:n,sessionTitleOf:r,reuseSourceSession:i}){let[a,o]=(0,d.useState)(),[s,c]=(0,d.useState)(``),[l,u]=(0,d.useState)(``),[f,p]=(0,d.useState)(``),[h,g]=(0,d.useState)(!1),[_,v]=(0,d.useState)(),[b,x]=(0,d.useState)(),S=(0,d.useRef)(!0),C=(0,d.useRef)(!1),w=(0,d.useRef)(!1),T=(0,d.useRef)(null),E=(0,d.useCallback)(async()=>{if(!C.current){C.current=!0;try{let e=await la();S.current&&o(e)}catch(e){S.current&&v(e instanceof Error?e.message:String(e))}finally{C.current=!1}}},[]),[ee,te]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{te(!document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[]),(0,d.useEffect)(()=>{if(S.current=!0,!ee)return;E();let e=setInterval(()=>{E()},5e3);return()=>{S.current=!1,clearInterval(e)}},[E,ee]),(0,d.useEffect)(()=>{if(_===void 0)return;let e=window.setTimeout(()=>{v(void 0)},8e3);return()=>{window.clearTimeout(e)}},[_]),(0,d.useEffect)(()=>{if(b===void 0)return;let e=window.setTimeout(()=>{x(void 0)},4e3);return()=>{window.clearTimeout(e)}},[b]),(0,d.useEffect)(()=>{a!==void 0&&(a.workspaces.some(e=>e.path===l)||u(a.workspaces[0]?.path??``),a.models.some(e=>ha(e.provider,e.id)===f)||p(a.models[0]===void 0?``:ha(a.models[0].provider,a.models[0].id)))},[a,l,f]);let D=(0,d.useCallback)(async(e,t=!1)=>{if(h||w.current)return!1;w.current=!0,g(!0),v(void 0),x(void 0);try{let n=await da(e);return S.current?(o(n),t&&c(``),!0):!1}catch(e){return S.current&&v(e instanceof Error?e.message:String(e)),!1}finally{w.current=!1,g(!1)}},[h]),O=(0,d.useMemo)(()=>a?.tasks.filter(e=>!ma(e))??[],[a]),ne=(0,d.useMemo)(()=>a?.tasks.filter(ma).slice().reverse()??[],[a]),k=a!==void 0&&a.supported&&a.workspaces.length>0&&a.models.length>0,A=e=>new Date(e).toLocaleString(t===`en`?`en-US`:`zh-CN`),j=()=>{if(s.trim()===``||l===``||f===``)return;let[e,t]=JSON.parse(f);D({action:`enqueue`,prompt:s,cwd:l,provider:e,model:t},!0)},re=async t=>{if(!(t===void 0||!k||h||f===``)){v(void 0),x(void 0);try{if(t.size>10485760){v(e(`queueImportTooLarge`));return}let[n,r]=JSON.parse(f),i=_a(await t.text(),{cwd:l,provider:n,model:r});await D({action:`enqueueMany`,tasks:i})&&S.current&&x(e(`queueImported`,{count:i.length}))}catch{S.current&&v(e(`queueImportFormat`))}}},ie=t=>{let r=n(t);x(r===`opened`?void 0:e(r===`unavailable`?`sessionOpenUnavailable`:`sessionOpenFailed`))},ae=t=>{let n=a?.workspaces.find(e=>e.path===t.cwd),i=t.reuseSource===!0?t.sourceSessionId:void 0,o=t.sourceSessionId!==void 0&&t.sessionId===t.sourceSessionId,s=e=>r?.(e)??ga(e),c=t.fallbackReason===void 0?o?e(`queueReuseDone`,{session:s(t.sessionId)}):i===void 0?void 0:e(`queueReusePlanned`,{session:s(i)}):e(`queueFallbackReason`,{reason:t.fallbackReason}),l=t.fallbackReason===void 0?t.sessionId??i:t.sessionId;return(0,m.jsxs)(`li`,{className:$.queueTask,"data-testid":`queue-task-${t.id}`,children:[(0,m.jsxs)(`div`,{className:$.queueTaskHead,children:[(0,m.jsx)(`span`,{className:y($.queueStatus,$[`queueStatus_${t.status}`]),children:e(pa[t.status])}),(0,m.jsxs)(`span`,{className:$.queueTaskMeta,children:[n?.title??t.cwd,` · `,t.model]}),(0,m.jsx)(`time`,{className:$.queueTaskTime,dateTime:new Date(t.createdAt).toISOString(),children:A(t.createdAt)})]}),c!==void 0&&(0,m.jsxs)(`div`,{className:$.queueTaskTarget,"data-testid":`queue-task-target-${t.id}`,children:[(0,m.jsx)(`span`,{children:c}),o&&(0,m.jsx)(`span`,{className:$.queueTaskTargetNote,children:e(`queueReuseModelNote`)})]}),(0,m.jsxs)(`details`,{className:$.queuePrompt,children:[(0,m.jsx)(`summary`,{children:t.prompt.trim().slice(0,180)||t.prompt.slice(0,180)}),(0,m.jsx)(`pre`,{children:t.prompt})]}),t.error!==void 0&&(0,m.jsx)(`div`,{className:$.queueTaskError,role:`note`,children:t.error}),(0,m.jsxs)(`div`,{className:$.queueTaskActions,children:[l!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:$.queueLinkButton,onClick:()=>{ie(l)},children:e(`queueOpenSession`)}),(t.status===`queued`||ma(t))&&(0,m.jsx)(`button`,{type:`button`,className:$.queueLinkButton,disabled:h,onClick:()=>{D({action:`remove`,id:t.id})},children:e(t.status===`queued`?`queueRemoveQueued`:`queueRemoveHistory`)})]})]},t.id)};return(0,m.jsxs)(`div`,{className:$.queuePanel,"data-testid":`billing-tab-panel-queue`,children:[(0,m.jsxs)(`section`,{className:$.queueHero,children:[(0,m.jsxs)(`div`,{children:[(0,m.jsxs)(`div`,{className:$.queueTitleRow,children:[(0,m.jsx)(`h2`,{className:$.queueTitle,children:e(`tabQueue`)}),(0,m.jsx)(`span`,{className:$.queuePreview,children:`Preview`})]}),(0,m.jsx)(`p`,{className:$.queueSubtitle,children:e(`queueSubtitle`)})]}),a?.supported&&(0,m.jsxs)(`div`,{className:y($.queueBand,a.tier===`offPeak`?$.queueBandOff:$.queueBandPeak),children:[(0,m.jsx)(`strong`,{children:e(a.tier===`offPeak`?`offPeak`:`peak`)}),(0,m.jsxs)(`span`,{children:[e(a.tier===`offPeak`?`queueUntilPeak`:`queueUntilOffPeak`),` `,Ht(a.nextSwitchInMs)]})]})]}),_!==void 0&&(0,m.jsx)(`div`,{className:$.queueNoticeError,role:`alert`,children:_}),b!==void 0&&(0,m.jsx)(`div`,{className:$.queueNotice,role:`status`,children:b}),a===void 0?(0,m.jsx)(`div`,{className:$.queueEmpty,children:e(`queueLoading`)}):a.supported?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`section`,{className:$.queueComposer,children:[(0,m.jsxs)(`div`,{className:$.queueSafety,children:[e(`queueSafety`),(0,m.jsx)(`span`,{className:$.queueSafetyMode,children:e(i===!0?`queueSafetyReuse`:`queueSafetyIsolated`)})]}),(0,m.jsxs)(`div`,{className:$.queueSelectors,children:[(0,m.jsxs)(`label`,{className:$.queueField,children:[(0,m.jsx)(`span`,{children:e(`queueWorkspace`)}),(0,m.jsx)(`select`,{value:l,disabled:!k||h,onChange:e=>{u(e.target.value)},children:a.workspaces.map(e=>(0,m.jsx)(`option`,{value:e.path,children:e.title},e.path))})]}),(0,m.jsxs)(`label`,{className:$.queueField,children:[(0,m.jsx)(`span`,{children:e(`queueModel`)}),(0,m.jsx)(`select`,{value:f,disabled:!k||h,onChange:e=>{p(e.target.value)},children:a.models.map(e=>(0,m.jsxs)(`option`,{value:ha(e.provider,e.id),children:[e.providerName,` / `,e.name]},ha(e.provider,e.id)))})]})]}),!k&&(0,m.jsx)(`div`,{className:$.queueNotice,children:a.optionsError??e(`queueNoOptions`)}),(0,m.jsxs)(`label`,{className:$.queuePromptField,children:[(0,m.jsx)(`span`,{children:e(`queuePromptLabel`)}),(0,m.jsx)(`textarea`,{value:s,disabled:!k||h,maxLength:32e3,rows:5,placeholder:e(`queuePromptPlaceholder`),onChange:e=>{c(e.target.value)}})]}),(0,m.jsxs)(`div`,{className:$.queueComposerFooter,children:[(0,m.jsx)(`span`,{children:e(`queuePrivacy`)}),(0,m.jsxs)(`div`,{className:$.queueComposerActions,children:[(0,m.jsx)(`input`,{ref:T,className:$.queueFileInput,"data-testid":`queue-import-file`,type:`file`,accept:`application/json,.json`,disabled:!k||h,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,re(t)}}),(0,m.jsx)(`button`,{type:`button`,className:$.queueSecondary,title:e(`queueImportHint`),disabled:!k||h,onClick:()=>{T.current?.click()},children:e(`queueImport`)}),(0,m.jsx)(`button`,{type:`button`,className:$.queuePrimary,disabled:!k||h||s.trim()===``,onClick:j,children:e(`queueEnqueue`)})]})]})]}),(0,m.jsxs)(`section`,{className:$.queueListSection,children:[(0,m.jsxs)(`div`,{className:$.queueListHead,children:[(0,m.jsxs)(`h3`,{children:[e(`queueActive`),` `,(0,m.jsx)(`span`,{children:O.length})]}),ne.length>0&&(0,m.jsx)(`button`,{type:`button`,className:$.queueLinkButton,disabled:h,onClick:()=>{D({action:`clearFinished`})},children:e(`queueClearFinished`)})]}),O.length===0&&ne.length===0?(0,m.jsx)(`div`,{className:$.queueEmpty,children:e(`queueEmpty`)}):(0,m.jsxs)(`ul`,{className:$.queueList,children:[O.map(ae),ne.map(ae)]})]})]}):(0,m.jsxs)(`section`,{className:$.queueUnsupported,"data-testid":`queue-unsupported`,children:[(0,m.jsx)(`h3`,{children:e(`queueUnsupportedTitle`)}),(0,m.jsx)(`p`,{children:e(`queueUnsupportedBody`)})]})]})}function ya({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:L.subscriptionWindow,children:[(0,m.jsx)(`span`,{className:L.subscriptionWindowLabel,children:Gi(e.kind,t)}),(0,m.jsx)(`span`,{className:L.subscriptionTrack,"aria-hidden":`true`,children:(0,m.jsx)(`span`,{className:y(L.subscriptionFill,n>=100&&L.subscriptionFillOver,n>=80&&n<100&&L.subscriptionFillWarn),style:{width:`${n}%`}})}),(0,m.jsxs)(`span`,{className:L.subscriptionMeta,children:[(0,m.jsx)(`span`,{className:y(L.subscriptionPct,r&&L.subscriptionExhausted),children:r?t(`subscriptionExhausted`):t(`subscriptionRemaining`).replace(`{pct}`,String(e.remainingPercent))}),e.resetsAt!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionReset,children:t(`subscriptionReset`).replace(`{date}`,`${G(new Date(e.resetsAt).getTime())} ${Xi(new Date(e.resetsAt).getTime())}`)})]})]})}function ba({label:e,t}){return(0,m.jsx)(p.Tooltip,{label:e,side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.helpTip,role:`note`,"aria-label":e,children:`?`})})}function xa(e,t){return e===L.healthOk?t(`healthDotLive`):e===L.healthBad?t(`healthDotFailed`):t(`healthDotUnknown`)}function Sa(e){let t=t=>W(gn(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,deltaPct:S=0,statsError:C}=e,w=(0,d.useMemo)(()=>p.targets.map(e=>h.find(t=>t.provider===e)).filter(e=>e!==void 0),[p.targets,h]),[T,E]=(0,d.useState)(0),ee=w.length===0?0:Math.min(T,w.length-1),te=w[ee],D=(0,d.useRef)(null),[O,ne]=(0,d.useState)(null),k=(0,d.useCallback)(e=>{D.current=e,ne(e)},[]),[A,j]=(0,d.useState)(!1),[re,ie]=(0,d.useState)({left:0,top:0}),[ae,oe]=(0,d.useState)(`card`);(0,d.useLayoutEffect)(()=>{if(O===null)return;let e=Or(O,oe);return()=>e.dispose()},[O]),(0,d.useEffect)(()=>{if(!A||p.mode!==`subscription`||w.length<2)return;let e=setInterval(()=>E(e=>(e+1)%w.length),1500);return()=>clearInterval(e)},[A,p.mode,w.length]);let se=(0,d.useRef)(void 0),ce=(0,d.useCallback)(()=>{window.clearTimeout(se.current),j(!0)},[]),le=(0,d.useCallback)(()=>{window.clearTimeout(se.current),se.current=window.setTimeout(()=>j(!1),120)},[]);(0,d.useEffect)(()=>()=>window.clearTimeout(se.current),[]);let ue=(0,d.useCallback)(()=>{let e=D.current?.getBoundingClientRect();e!==void 0&&ie({left:e.left,top:e.top-8})},[]);(0,d.useEffect)(()=>{if(!A)return;let e=()=>ue();return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,{capture:!0}),window.removeEventListener(`resize`,e)}},[A,ue]);let de=c.length>0?c.reduce((e,t)=>e+t.cost,0)/c.length:0,fe=de>0?Math.max(0,Math.min(1,o/de)):0,pe=-80+fe*160,me=(0,m.jsxs)(`svg`,{viewBox:`3.5 10 34 22`,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*fe).toFixed(2)} 41.9`,className:L.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:L.triggerGaugeNeedle,style:{transform:`rotate(${pe}deg)`,transformOrigin:`20px 29px`}}),(0,m.jsx)(`circle`,{cx:`20`,cy:`29`,r:`1.5`,fill:`currentColor`,stroke:`none`})]}),he=`${r(`title`)} · ${t(g.span===`day`?o:g.span===`week`?s:a)}${C===void 0?``:` · ${r(`statsLoadFailed`)}`}`;if(g.mode===`hidden`)return null;if(!n||g.mode===`compact`)return(0,m.jsx)(`button`,{type:`button`,className:y(L.railButton,Rr,x!==`none`&&L.triggerBudgetPulse,x===`over`&&L.triggerBudgetOver),"data-testid":`billing-rail-button`,onClick:i,title:he,children:me});let M=g.metric===`tokens`,ge=c.map(e=>M?e.tokens:e.cost),_e=Math.max(...ge,0),ve=ge.map(e=>_e>0?4+e/_e*12:4),ye=ae===`icon`;return(0,m.jsxs)(`span`,{ref:k,className:y(L.triggerWrap,ye&&L.triggerWrapShared,Rr),onMouseEnter:()=>{ue(),ce()},onMouseLeave:le,onFocusCapture:()=>{ue(),ce()},onBlurCapture:()=>j(!1),children:[ye?(0,m.jsx)(`button`,{type:`button`,className:y(L.triggerShared,x!==`none`&&L.triggerBudgetPulse,x===`over`&&L.triggerBudgetOver),"data-testid":`billing-trigger-shared`,"aria-label":he,onClick:i,title:he,children:(0,m.jsx)(`span`,{className:y(L.triggerIcon,x!==`none`&&L.triggerBudgetHot,C!==void 0&&L.triggerStatsError),"data-testid":`billing-trigger-icon`,children:me})}):(0,m.jsxs)(`button`,{type:`button`,className:y(L.trigger,x!==`none`&&L.triggerBudgetPulse,x===`over`&&L.triggerBudgetOver),"data-testid":`billing-trigger`,onClick:i,title:he,children:[(0,m.jsx)(`span`,{className:y(L.triggerIcon,x!==`none`&&L.triggerBudgetHot,C!==void 0&&L.triggerStatsError),"data-testid":`billing-trigger-icon`,children:me}),(0,m.jsx)(`span`,{className:L.triggerMain,children:(0,m.jsxs)(`span`,{className:L.triggerPrimary,children:[(0,m.jsx)(`span`,{className:L.triggerLabel,children:M?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`?M?v:o:g.span===`week`?M?b:s:M?_:a,n=g.span===`day`?S:0;return M?(0,m.jsx)(`span`,{className:L.triggerMetric,"data-testid":`billing-trigger-span-tokens`,children:K(e)}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`span`,{className:L.triggerValueRow,children:[(0,m.jsx)(`span`,{className:L.triggerYen,"aria-hidden":`true`,children:t(e).charAt(0)}),(0,m.jsx)(`span`,{className:L.triggerMetric,"data-testid":`billing-trigger-span-money`,children:t(e).slice(1)})]}),g.showDelta&&n!==0&&(0,m.jsxs)(`span`,{className:y(L.triggerDelta,n>0?L.triggerDeltaUp:L.triggerDeltaDown),"data-testid":`billing-trigger-delta`,children:[n>0?`▲`:`▼`,` `,Math.abs(n).toFixed(1),`%`]}),(0,m.jsx)(`span`,{className:L.triggerGlow,"aria-hidden":`true`})]})})()]})}),(0,m.jsx)(`span`,{className:L.triggerSpark,"data-testid":`billing-trigger-spark`,"aria-hidden":`true`,children:ve.map((e,t)=>(0,m.jsx)(`span`,{className:t===ve.length-1?L.triggerSparkHot:L.triggerSparkBar,style:{height:`${e}px`}},c[t]?.date??String(t)))})]}),(0,f.createPortal)((0,m.jsx)(`span`,{className:y(L.triggerPop,Rr,A&&L.triggerPopShown),style:{left:`${re.left}px`,top:`${re.top}px`},"data-testid":`billing-trigger-pop`,"aria-hidden":!A,onMouseEnter:ce,onMouseLeave:le,children:p.mode===`subscription`?(0,m.jsx)(m.Fragment,{children:w.length===0?(0,m.jsx)(`span`,{className:L.triggerPopEmpty,children:r(`floatNoTargets`)}):(0,m.jsxs)(m.Fragment,{children:[te!==void 0&&(0,m.jsxs)(`div`,{className:L.floatSub,"data-testid":`billing-float-subscription`,children:[(0,m.jsxs)(`div`,{className:L.floatSubHead,children:[(0,m.jsx)(`span`,{className:L.floatSubName,children:te.displayName}),te.plan!==void 0&&(0,m.jsx)(`span`,{className:L.floatSubPlan,children:te.plan})]}),te.windows.map(e=>(0,m.jsx)(ya,{window:e,t:r},e.kind))]}),w.length>1&&(0,m.jsx)(`span`,{className:L.triggerPopSwitcher,"data-testid":`billing-float-switcher`,children:(0,m.jsxs)(`span`,{className:L.triggerPopSwitchCount,children:[ee+1,`/`,w.length]})})]})}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:L.popHead,children:(0,m.jsx)(`span`,{className:L.popTitle,children:r(`popTitle`)})}),C!==void 0&&(0,m.jsxs)(`span`,{className:L.popError,"data-testid":`billing-stats-error`,role:`note`,children:[(0,m.jsx)(`span`,{className:L.popErrorTitle,children:r(`statsLoadFailed`)}),(0,m.jsx)(`span`,{className:L.popErrorDetail,children:C})]}),(0,m.jsxs)(`span`,{className:L.metricGrid,children:[(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`floatPrimaryToday`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:t(o)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`floatPrimaryWeek`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:t(s)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`floatPrimaryMonth`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:t(a)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`input`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:K(u.input)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`output`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:K(u.output)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`cacheHit`)}),(0,m.jsx)(`span`,{className:y(L.metricValue,L.metricValueSuccess),children:yn(u.cacheRead+u.cacheMiss>0?u.cacheRead/(u.cacheRead+u.cacheMiss)*100:0)})]})]}),(0,m.jsxs)(`span`,{className:L.popModel,children:[(0,m.jsx)(`span`,{className:L.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:L.popModelRow,children:[(0,m.jsx)(`span`,{className:y(L.popDot,L.popDotDirect),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:L.popTagPrimary,children:r(`popDirectLead`)}),(0,m.jsx)(`span`,{className:L.popModelName,children:l.direct.name}),(0,m.jsx)(`span`,{className:y(L.popModelStatus,l.direct.low&&L.popModelStatusLow),children:l.direct.text})]}),l.sub!==void 0&&(0,m.jsxs)(`span`,{className:L.popModelRow,children:[(0,m.jsx)(`span`,{className:y(L.popDot,L.popDotSub),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:L.popTagSub,children:r(`popSubLead`)}),(0,m.jsx)(`span`,{className:L.popModelName,children:l.sub.name}),(0,m.jsx)(`span`,{className:y(L.popModelStatus,l.sub.low&&L.popModelStatusLow),children:l.sub.text})]})]}):(0,m.jsxs)(`span`,{className:L.popModelRow,children:[(0,m.jsx)(`span`,{className:y(L.popDot,L.popDotNeutral),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:L.popModelStatus,children:r(`popNoConsumption`)})]})]})]})}),document.body)]})}function Ca({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:L.balanceDetailPop,"data-testid":`billing-balance-detail-pop`,onClick:e=>{e.stopPropagation()},children:[(0,m.jsxs)(`span`,{className:L.balanceDetailHead,children:[(0,m.jsx)(`span`,{className:L.balanceDetailTitle,children:e.displayName}),(0,m.jsx)(`button`,{type:`button`,className:L.balanceDetailClose,"aria-label":i(`close`),onClick:a,children:`×`})]}),(0,m.jsxs)(`span`,{className:L.balanceDetailGrid,children:[s!==void 0&&(0,m.jsx)(wa,{label:i(`balance`),value:s}),c!==void 0&&(0,m.jsx)(wa,{label:i(`balanceGranted`),value:c}),l!==void 0&&(0,m.jsx)(wa,{label:i(`balanceTopped`),value:l}),(0,m.jsx)(wa,{label:i(`balanceDaily`),value:r(n)}),(0,m.jsx)(wa,{label:i(`balanceDaysLong`),value:`${t} ${i(`balanceDaysUnit`)}`})]})]})}function wa({label:e,value:t}){return(0,m.jsxs)(`span`,{className:L.balanceDetailRow,children:[(0,m.jsx)(`span`,{className:L.balanceDetailLabel,children:e}),(0,m.jsx)(`span`,{className:L.balanceDetailValue,children:t})]})}function Ta({userPrices:e,onUserPrices:t,t:n,unpricedIds:r}){let[i,a]=(0,d.useState)(()=>[...e]),[o,s]=(0,d.useState)(new Set),c=e=>s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),l=()=>{a(e=>e.filter((e,t)=>!o.has(t))),s(new Set)},u=(e,t)=>a(n=>n.map((n,r)=>r===e?{...n,...t}:n)),f=()=>a(e=>[...e,{key:``,input:0,cacheHit:0,output:0}]),p=e=>{let t=i[e]?.offPeak;return{input:t===void 0?``:String(t.input),cacheHit:t===void 0?``:String(t.cacheHit),output:t===void 0?``:String(t.output)}},h=(e,t,n)=>a(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})),g=()=>t(i.filter(e=>e.key.trim()!==``).map(e=>({...e,key:e.key.trim(),...e.origin===void 0||e.origin.trim()===``?{}:{origin:ht(e.origin.trim())}}))),_=(0,d.useMemo)(()=>{let e=[];for(let t of fn())e.push(t.key);for(let t of r??[])e.includes(t)||e.push(t);return e},[r]),v=(e,t)=>a(n=>n.map((n,r)=>{if(r!==e)return n;let{currency:i,...a}=n;return t===`USD`?{...a,currency:`USD`}:a})),[b,x]=(0,d.useState)({}),S=(e,t,n)=>`${e}:${t}:${n}`,C=(e,t,n)=>x(r=>{let i=S(e,t,n);if(r[i]===void 0)return r;let a={...r};return delete a[i],a}),w=e=>Number.isFinite(e)&&e!==0?String(e):``,T=(e,t,n)=>{if(x(r=>({...r,[S(e,`main`,t)]:n})),n===``){u(e,{[t]:0});return}let r=Number(n);Number.isFinite(r)&&r>=0&&u(e,{[t]:r})};return(0,m.jsxs)(`section`,{className:L.setCard,"data-testid":`billing-user-prices`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`userPrices`),(0,m.jsx)(ba,{label:n(`userPricesHint`),t:n})]})})}),(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsx)(`datalist`,{id:`billing-price-model-keys`,children:_.map(e=>(0,m.jsx)(`option`,{value:e},e))}),i.map((e,t)=>(0,m.jsxs)(`div`,{className:L.userPriceRow,"data-testid":`billing-user-price-row`,children:[(0,m.jsx)(`input`,{type:`checkbox`,className:L.userPriceCheck,"data-testid":`billing-user-price-select`,checked:o.has(t),"aria-label":n(`userPriceSelect`),onChange:()=>c(t)}),(0,m.jsxs)(`div`,{className:L.userPriceBody,children:[(0,m.jsxs)(`div`,{className:L.userPriceLineMeta,children:[(0,m.jsxs)(`div`,{className:L.userPriceField,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`userPriceModel`)}),(0,m.jsx)(`input`,{className:L.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=>u(t,{key:e.target.value})})]}),(0,m.jsxs)(`div`,{className:L.userPriceField,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`userPriceSource`)}),(0,m.jsx)(`input`,{className:L.userPriceInput,"data-testid":`billing-user-price-origin`,type:`text`,value:e.origin??``,placeholder:n(`userPriceSourceHint`),"aria-label":n(`userPriceSource`),onChange:e=>u(t,{origin:e.target.value.trim()})})]}),(0,m.jsxs)(`div`,{className:L.userPriceField,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`userPriceCurrency`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,e.currency!==`USD`&&L.floatModeBtnOn),onClick:()=>v(t,`CNY`),children:`CNY`}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,e.currency===`USD`&&L.floatModeBtnOn),onClick:()=>v(t,`USD`),children:`USD`})]})]})]}),[{scope:`main`,label:n(`userPriceNormal`),testid:`billing-user-price-normal`,valueOf:n=>b[S(t,`main`,n)]??w(e[n]),onChange:(e,n)=>T(t,e,n)},{scope:`off`,label:n(`userPriceOffPeak`),testid:`billing-user-price-offpeak`,valueOf:e=>b[S(t,`off`,e)]??p(t)[e],onChange:(e,n)=>{x(r=>({...r,[S(t,`off`,e)]:n})),h(t,e,n)}}].map(e=>(0,m.jsxs)(`div`,{className:L.userPricePriceLine,"data-testid":e.testid,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:e.label}),[`input`,`cacheHit`,`output`].map(r=>{let i=n(r===`input`?`tokenMiss`:r===`cacheHit`?`tokenHit`:`tokenOutput`);return(0,m.jsx)(`input`,{className:L.userPriceInputNum,type:`number`,min:0,step:.01,placeholder:i,"aria-label":`${e.label} ${i}`,value:e.valueOf(r),onChange:t=>e.onChange(r,t.target.value),onBlur:()=>C(t,e.scope,r)},r)})]},e.testid))]})]},t)),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-user-price-add`,onClick:f,children:n(`userPriceAdd`)}),(0,m.jsxs)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-user-price-remove-selected`,disabled:o.size===0,onClick:l,children:[n(`userPriceRemoveSelected`),o.size>0?` (${o.size})`:``]}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-user-price-save`,onClick:g,children:n(`userPriceSave`)})]})]})]})}function Ea(e,t,n){if(e.length===0)return``;let r=e.slice(0,3).join(n===`zh`?`、`:`, `),i=e.length-3;return i>0?`${r} ${t(`unpricedMore`,{count:i})}`:r}function Da({prefs:e,onPrefs:t,groups:n,t:r,money:i}){let a=new Set(e.hidden),o=(e,n)=>{let r=new Set(a);for(let t of e.siteKeys)n?r.add(t):r.delete(t);t({hidden:[...r]})},s=n.filter(e=>e.siteKeys.some(e=>a.has(e))).length;return(0,m.jsxs)(`div`,{className:y(L.setCell,L.channelVisCell),"data-testid":`billing-channel-visibility-setting`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[r(`channelVisibility`),(0,m.jsx)(ba,{label:r(`channelVisibilityHint`),t:r})]})}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-channel-visibility-reset`,disabled:e.hidden.length===0,onClick:()=>{t({hidden:[]})},children:r(`channelVisibilityShowAll`)})]}),n.length===0?(0,m.jsx)(`div`,{className:L.setHint,children:r(`channelVisibilityEmpty`)}):(0,m.jsx)(`div`,{className:L.channelVisList,children:n.map(e=>{let t=e.siteKeys.some(e=>a.has(e));return(0,m.jsxs)(`div`,{className:L.channelVisRow,"data-testid":`billing-channel-row-${e.name}`,children:[(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":!t,"aria-label":e.name,"data-testid":`billing-channel-toggle-${e.name}`,className:y(L.switch,!t&&L.switchOn),onClick:()=>{o(e,!t)},children:(0,m.jsx)(`span`,{className:L.switchKnob})}),(0,m.jsx)(`span`,{className:L.channelVisName,title:e.name,children:e.name}),(0,m.jsxs)(`span`,{className:L.channelVisUsage,children:[i(e.cost),` · `,K(e.tokens)]})]},e.name)})}),s>0&&(0,m.jsx)(`div`,{className:L.setHint,"data-testid":`billing-channel-visibility-hint`,children:r(`channelVisibilityHidden`).replace(`{count}`,String(s))})]})}function Oa({stats:e,statsError:t,t:n,onClose:r,embeddedSettings:i=!1,userPrices:a,onUserPrices:o,health:s,balances:c,reconcile:l,quotas:u,relayQuotas:f,currency:h,onCurrency:g,language:_,onLanguage:v,turns:b,renderSlot:x,budgetEnabled:S,budgetAmount:C,onToggleBudget:w,onBudgetAmount:T,modelBudgets:E,monthModelCost:ee,onModelBudget:te,peakConfig:D,onPeakConfig:O,onPreviewPeak:ne,floatPrefs:k,onFloatPrefs:A,cardPrefs:j,onCardPrefs:re,recoveryEntryAvailable:ie,sitePrefs:ae,onSitePrefs:ce,channelPrefs:le,onChannelPrefs:fe,channelGroups:pe,liveCostPrefs:me,onLiveCostPrefs:he,quickQueuePrefs:M,onQuickQueuePrefs:ge,quotasStale:_e,balanceStale:ve,navigateToSession:ye,sessionTitleOf:be}){let xe=(0,d.useRef)(null),Se=(0,d.useMemo)(()=>Ri(e.bySession??[]),[e.bySession]),Ce=(0,d.useMemo)(()=>Bi(Se),[Se]),[we,Te]=(0,d.useState)(void 0),Ee=(0,d.useCallback)(e=>{let t=ye(e);if(t===`opened`){Te(void 0);return}Te(n(t===`unavailable`?`sessionOpenUnavailable`:`sessionOpenFailed`))},[ye,n]),[De,Oe]=(0,d.useState)(`cost`),{total:ke,byModel:je,byDay:N}=e,[P,Ie]=(0,d.useState)(i?`settings`:`overview`),[Le,Re]=(0,d.useState)(7),[Be,Ve]=(0,d.useState)(()=>{try{return window.localStorage.getItem(`dsh-billing:reconcile-dismissed`)??``}catch{return``}}),He=()=>{let e=new Date,t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`},Ue=(0,d.useCallback)(()=>{let e=He();Ve(e);try{window.localStorage.setItem(`dsh-billing:reconcile-dismissed`,e)}catch{}},[]),[We,Ge]=(0,d.useState)(()=>{let e=[`unpriced`,`search-estimate`,`unreadable`],t=new Set,n=new Date,r=e=>String(e).padStart(2,`0`),i=`${n.getFullYear()}-${r(n.getMonth()+1)}-${r(n.getDate())}`;try{for(let n of e)window.localStorage.getItem(`dsh-billing:notice-${n}-dismissed`)===i&&t.add(n)}catch{}return t}),Ke=(0,d.useCallback)(e=>{let t=He();Ge(t=>new Set(t).add(e));try{window.localStorage.setItem(`dsh-billing:notice-${e}-dismissed`,t)}catch{}},[]),[qe,Ye]=(0,d.useState)(`month`),[$e,et]=(0,d.useState)(`cost`),[tt,nt]=(0,d.useState)(Je),[rt,it]=(0,d.useState)(Ze),[at,ot]=(0,d.useState)(`budget`),[st,R]=(0,d.useState)(``),z=e=>Hi(st,e);(0,d.useEffect)(()=>{let e=xe.current;if(P!==`settings`||e===null||typeof IntersectionObserver>`u`)return;let t=Array.from(e.querySelectorAll(`[id^="settings-"]`)).filter(e=>!e.closest(`[hidden]`));if(t.length===0)return;let n=new IntersectionObserver(e=>{let t,n=1/0;for(let r of e){if(!r.isIntersecting)continue;let e=r.boundingClientRect.top;e<n&&(n=e,t=r.target.id)}t!==void 0&&ot(t.slice(9))},{rootMargin:`-80px 0px -55% 0px`});for(let e of t)n.observe(e);return()=>{n.disconnect()}},[P]);let ct=(0,d.useCallback)(e=>{ot(e);let t=xe.current?.querySelector(`[id="settings-${e}"]`);if(t==null)return;if(i){t.scrollIntoView({block:`start`,behavior:`smooth`});return}let n=t.closest(`.${L.dashboardBody}`);if(n===null)return;let r=t.getBoundingClientRect().top-n.getBoundingClientRect().top;n.scrollTo({top:n.scrollTop+r,behavior:`smooth`})},[i]),ut=(0,d.useCallback)(e=>{nt(e),I(e)},[]),dt=(0,d.useCallback)(e=>{it(e),Qe(e)},[]);(0,d.useEffect)(()=>{typeof document>`u`||(document.documentElement.dataset.dshBillingDensity=tt,document.documentElement.dataset.dshBillingMotion=rt)},[tt,rt]),(0,d.useEffect)(()=>{if(typeof window>`u`)return;let e=e=>{let t=e.detail;t?.density!==void 0&&nt(t.density)},t=e=>{let t=e.detail;t?.motion!==void 0&&it(t.motion)};return window.addEventListener(F,e),window.addEventListener(Xe,t),()=>{window.removeEventListener(F,e),window.removeEventListener(Xe,t)}},[]);let[B,ft]=(0,d.useState)(oe),[V,pt]=(0,d.useState)(ue),mt=e=>{let t={...V,...e};t.start!==``&&t.end!==``&&(t.start>t.end&&(e.start===void 0?t.start=t.end:t.end=t.start),pt(t),de(t))},ht=(0,d.useMemo)(()=>u.filter(e=>e.status===`ok`&&e.windows.length>0).map(e=>({id:e.provider,label:e.displayName})),[u]),[gt,_t]=(0,d.useState)(),[vt,yt]=(0,d.useState)(new Set),[bt,H]=(0,d.useState)(!1),[xt,St]=(0,d.useState)(``),Ct=(0,d.useCallback)(e=>{yt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),wt=(0,d.useMemo)(()=>Li(e.bySession??[]),[e.bySession]),Tt=e=>(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:L.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:U(e.cost)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.lastActive>0?`${G(e.lastActive)} ${Xi(e.lastActive)}`:`—`})]}),Dt=(e,t)=>(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{className:y(L.sessionChildRow,t>0&&L.sessionSubDeepRow),"data-testid":`billing-session-sub-row`,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),children:n(`sessionSubRow`)}),(e.subCalls??0)>0&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-session-sub-chain`,children:e.subCost!==void 0&&e.subCost>0?n(`sessionSubCost`).replace(`{cost}`,U(e.subCost)):n(`sessionSubCalls`).replace(`{calls}`,(e.subCalls??0).toLocaleString())}),(0,m.jsx)(`span`,{className:L.modelProvider,children:e.title??e.id.slice(0,8)})]}),Tt(e)]}),e.subs?.map(e=>Dt(e,t+1))]},e.id),Ot=(0,d.useMemo)(()=>Vi(e.bySession??[],xt),[e.bySession,xt]),kt=e.bySession?.length??0,At=e.bySessionTotal??kt,jt=At>kt,Mt=(0,d.useMemo)(()=>[...new Set([...Object.keys(ee),...Object.keys(E)])].map(e=>{let t=cn(e);return{key:e,name:t.key===`other`?void 0:t.name,cost:ee[e]??0}}).sort((e,t)=>t.cost-e.cost),[ee,E]),[Nt,Pt]=(0,d.useState)(()=>new Set(Me())),Ft=(0,d.useCallback)(e=>{Pt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Ne([...n]),n})},[]),[It,Lt]=(0,d.useState)(()=>Pe()),Rt=(0,d.useCallback)(()=>{Lt(e=>{let t=!e;return Fe(t),t})},[]),[Vt,Ht]=(0,d.useState)(!1);(0,d.useEffect)(()=>{let e=!0;return na().then(t=>{e&&t!==void 0&&Ht(t)}),()=>{e=!1}},[]);let Ut=(0,d.useCallback)(()=>{let e=!Vt;Ht(e),ra(e).then(t=>{t||Ht(!e)})},[Vt]),Wt=Et(),[Gt,Kt]=(0,d.useState)(!1),qt=(0,d.useCallback)(()=>{Gt||(Kt(!0),sa().finally(()=>{Kt(!1)}))},[Gt]),Jt=aa,U=e=>W(gn(e,h),h),Yt=h===`usd`?`$`:h===`eur`?`€`:`¥`,Xt=_,Zt=e=>gr(e,Xt),[Qt,$t]=(0,d.useState)(``),[en,tn]=(0,d.useState)(()=>Ae()),[nn,rn]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{let e=setInterval(()=>{rn(Date.now())},3e4);return()=>{clearInterval(e)}},[]);let an=u.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),on=D.leadMin*6e4,sn=(e,t)=>e===0?n(`free`):_n(vn(e,t,h,Wt.rate),h===`usd`?`USD`:h===`eur`?`EUR`:`CNY`),ln=(0,d.useMemo)(()=>sr([...b].reverse()),[b]),dn={peak:e.byTier?.peak.cost??0,offPeak:e.byTier?.offPeak.cost??0},pn=dn.peak/2,hn=Jr(N,G()),bn=e=>c.find(t=>Z(t.provider)===Z(e)),xn=e=>e.balance?.error===`unconfigured`&&e.models.length>0&&e.models.every(e=>e.plan),Sn=e=>{if(e===void 0)return(0,m.jsx)(`span`,{className:L.na,children:`—`});if(e.error===`unconfigured`)return n(`balanceUnconfigured`);if(e.error===`unauthorized`)return n(`balanceUnauthorized`);if(e.error===`unreachable`)return n(`balanceUnreachable`);if(e.totalBalance===void 0)return(0,m.jsx)(`span`,{className:L.na,children:`—`});let t=e.currency===`USD`?`$${e.totalBalance.toFixed(2)}`:U(e.totalBalance),r=e.currency===`USD`?e.totalBalance*Wt.rate:e.totalBalance,i=hn>0?Math.floor(r/hn):void 0;return(0,m.jsxs)(`span`,{className:L.balanceCell,children:[(0,m.jsx)(`span`,{children:t}),i!==void 0&&i>=0&&(0,m.jsx)(`button`,{type:`button`,className:y(L.balanceDaysBadge,i<=3&&L.balanceDaysBadgeLow),"data-testid":`billing-balance-days-badge`,title:n(`balanceDays`).replace(`{days}`,String(i)),"aria-label":`${e.displayName} ${n(`balanceDays`).replace(`{days}`,String(i))}`,onClick:t=>{t.stopPropagation(),_t(gt===e.provider?void 0:e.provider)},children:`?`}),gt===e.provider&&(0,m.jsx)(Ca,{balance:e,days:i??0,dailyBurn:hn,money:U,t:n,onClose:()=>{_t(void 0)}})]})},Tn=Object.keys(N).sort(),q=G(),An=N[q]?.cost??0,jn=q.slice(0,7),Mn=q.slice(0,4),Nn=Tn.reduce((e,t)=>e+(t.startsWith(jn)?N[t]?.cost??0:0),0),Fn=Tn.reduce((e,t)=>e+(t.startsWith(Mn)?N[t]?.cost??0:0),0),J=(0,d.useMemo)(()=>Xr(N,jn,q)+u.reduce((e,t)=>e+(t.planType===`code`?t.subscriptionAmount??0:0),0),[N,jn,q,u]),In=(0,d.useMemo)(()=>{if(!(S&&C>0))return null;let e=C-Nn;return{over:e<=0,remainRatio:Math.max(0,Math.min(1,e/C)),remainCny:Math.max(0,e)}},[S,C,Nn]),Ln=(0,d.useMemo)(()=>{let e=[];for(let t=Le-1;t>=0;--t){let n=new Date;n.setDate(n.getDate()-t),e.push(G(n.getTime()))}return e},[Le]),Rn=Ln.at(-1)??q,Y=(0,d.useMemo)(()=>Object.entries(N).map(([e,t])=>({date:e,value:$e===`tokens`?$r(t):t.cost})),[N,$e]),Bn=(0,d.useMemo)(()=>Y.reduce((e,t)=>e+t.value,0),[Y]),Vn=Zr(N),Hn=Qr(N),Un=(0,d.useMemo)(()=>Ln.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=N[t];return{date:t,cost:i?.cost??0,calls:i?.calls??0,byModel:n,tokens:i===void 0?0:$r(i)}}),[Ln,N,e.byDayModels]),Wn=(0,d.useMemo)(()=>Object.entries(je).filter(([,e])=>e.calls>0).map(([e,t])=>{let n=cn(e),r=n.key===`other`,i=r?di(e):void 0,a={input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,cacheWrite:t.cacheWrite??0,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:mn(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:Br[t%Br.length]??`#8b95a3`})),[je]),Kn=(0,d.useMemo)(()=>ae.hideUnidentified?f.filter(e=>e.kind!==`unknown`):f,[f,ae.hideUnidentified]),qn=(0,d.useCallback)(e=>xr(e,Xt)??n(`channelUnknown`),[Xt,n]),Yn=(0,d.useMemo)(()=>{let t=e.byDayModelsSite;if(It){let n=G();t={[n]:e.byDayModelsSite?.[n]??{}}}let r=new Map;for(let n of Object.values(t??{}))for(let[t,i]of Object.entries(n))for(let[n,a]of Object.entries(i)){let i=r.get(n);i===void 0&&(i=new Map,r.set(n,i));let o=i.get(t)??{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cacheWrite: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.cacheWrite+=a.cacheWrite??0,o.cost+=a.cost,o.allPlan=o.allPlan&&(a.plan??e.byModel?.[t]?.plan===!0),i.set(t,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=cn(e),a=i.key===`other`,o=a?di(e)??i.provider:i.provider;return{key:e,name:a?e:i.name,provider:o,color:Br[r%Br.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:mn(i,{input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,cacheWrite:t.cacheWrite,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 a=e=>xr(e,Xt)??n(`channelUnknown`),o=new Map,l=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=a(e),r=o.get(n);if(r===void 0)o.set(n,[...t]),l.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=l.get(n)??`unknown`,a=f(e);p[a]>p[i]&&(l.set(n,a),d.set(n,e))}}let m=new Map,h=new Map;for(let e of u){if(e.status===`not-configured`)continue;let t=e.displayName??pi(e.provider),n=a(`direct:${e.provider}`),r=o.has(t)?t:o.has(n)?n:void 0,i=r??`sub:${pi(e.provider)}`;h.set(i,r??pi(e.provider));let s=m.get(i);s===void 0?m.set(i,[e]):s.push(e)}let g=e=>e===a(`direct:deepseek`)||e===a(`site:https://api.deepseek.com`)?bn(`deepseek`)??bn(e):bn(e),_=[];for(let[e,t]of o)_.push({id:`ch:${d.get(e)??e}`,name:e,models:t,subscriptions:m.get(e)??[],balance:g(e),dot:Ui(s,t[0]?.provider??``),channelKind:l.get(e)??`unknown`});for(let[e,t]of h)o.has(e)||_.push({id:e,name:t,models:[],subscriptions:m.get(e)??[],balance:bn(t),dot:Ui(s,t),channelKind:`vendor`});let v=new Set(_.flatMap(e=>[Z(e.name),...e.balance===void 0?[]:[Z(e.balance.provider)]]));for(let e of c)v.has(Z(e.provider))||(e.error===void 0||e.provider.startsWith(`custom:`))&&_.push({id:`bal:${e.provider}`,name:e.displayName,models:[],subscriptions:[],balance:e,dot:Ui(s,e.displayName),channelKind:`vendor`});return _.filter(e=>ae.hideUnidentified&&e.channelKind===`unknown`?!1:!It||e.models.length>0).sort((e,t)=>{let n=Ji(t)-Ji(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,u,c,s,Xt,n,It,ae.hideUnidentified]),Xn=(0,d.useMemo)(()=>Yn.filter(e=>e.models.length>0||e.subscriptions.length>0).map(e=>e.id),[Yn]),Zn=Xn.length>0&&Xn.every(e=>Nt.has(e)),$n=()=>{let e=new Set(Zn?[]:Xn);Pt(e),Ne([...e])},er=(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`model`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`calls`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`inputTokens`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`outputTokens`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`cacheHitRate`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`actual`)})]})}),tr=e=>(0,m.jsx)(`span`,{className:L.modelCell,children:(0,m.jsxs)(`span`,{children:[(0,m.jsxs)(`span`,{className:L.modelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:L.uncataloguedTag,"data-testid":`billing-uncatalogued-tag`,children:n(`uncatalogued`)}),e.estimatedPricing&&(0,m.jsx)(`span`,{className:L.estimatedTag,"data-testid":`billing-estimated-tag`,children:n(`estimatedPricing`)})]}),(0,m.jsx)(`span`,{className:L.modelProvider,children:Zt(e.provider)})]})}),nr=e.bySite?.unknown?.calls??0,rr=Wn.reduce((e,t)=>e+t.estimated,0),ar=ke.cost>0||nr>0?ke.cost:rr,X=(0,d.useMemo)(()=>{if(B===`all`){let e,t=0;for(let[n,r]of Object.entries(N)){let i=$r(r);i>t&&(t=i,e=n)}return{cost:ar,calls:ke.calls,input:ke.input,output:ke.output,cacheHit:ke.cacheHit,cacheMiss:ke.cacheMiss,cacheWrite:ke.cacheWrite??0,reasoning:ke.reasoning??0,peakDay:e,peakTokens:t}}return B===`custom`?ri(N,V.start,V.end):ni(N,G(),B)},[B,V,ar,ke,N]),or=B===`custom`?V.start===V.end?V.start:`${V.start} – ${V.end}`:n({today:`avgRangeToday`,"7d":`avgRange7d`,week:`avgRangeWeek`,month:`avgRangeMonth`,all:`avgRangeAll`}[B]),cr=(0,d.useMemo)(()=>Wn.map(e=>({key:e.key,name:e.name,color:e.color})),[Wn]),lr=Un.length>=2?Un.at(-2)?.cost??0:0,ur=lr>0?(An-lr)/lr*100:0,fr=(0,m.jsxs)(`div`,{ref:xe,className:y(L.dashboard,Rr,i&&L.nativeSettingsDashboard),"data-testid":i?`native-billing-settings-dashboard`:`billing-dashboard`,children:[!i&&(0,m.jsxs)(`div`,{className:L.dashboardHead,"data-testid":`billing-dashboard-head`,children:[(0,m.jsxs)(`div`,{children:[x(`billing.dashboard.decor`,{position:`head`}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h2`,{className:L.dashboardTitle,children:n(`title`)}),x(`billing.dashboard.decor`,{position:`headTitle`})]}),(0,m.jsxs)(`p`,{className:L.dashboardSubtitle,children:[n(`lastUpdated`),` `,Rn,e.timezone===void 0?null:` · ${e.timezone.name} (${e.timezone.offset})`]})]}),(0,m.jsxs)(`div`,{className:L.dashboardRight,children:[(0,m.jsx)(`span`,{className:L.currencyToggle,role:`group`,"aria-label":n(`language`),children:[`en`,`zh`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.currencyButton,_===e&&L.currencyButtonActive),"aria-pressed":_===e,"data-testid":`billing-language-${e}`,onClick:()=>{v(e)},children:e===`en`?`EN`:`中`},e))}),(0,m.jsx)(`span`,{className:L.currencyToggle,role:`group`,"aria-label":n(`currency`),children:[`cny`,`usd`,`eur`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.currencyButton,h===e&&L.currencyButtonActive),"aria-pressed":h===e,"data-testid":`billing-currency-${e}`,title:n(e===`cny`?`currencyCny`:e===`usd`?`currencyUsd`:`currencyEur`),onClick:()=>{g(e)},children:e===`cny`?`¥ CNY`:e===`usd`?`$ USD`:`€ EUR`},e))}),s.checked&&(0,m.jsxs)(`span`,{className:y(L.healthBadge,s.available?L.healthBadgeOk:L.healthBadgeBad),children:[(0,m.jsx)(`span`,{className:y(L.healthDot,s.available?L.healthOk:L.healthBad),role:`img`,"aria-label":s.available?n(`healthDotLive`):n(`healthDotFailed`),title:s.available?n(`healthDotLive`):n(`healthDotFailed`)}),s.available?`${n(`healthModelsLive`).replace(`{n}`,String(s.models))}${s.failures>0?` · ${n(`healthVendorsDown`).replace(`{n}`,String(s.failures))}`:``}`:n(`healthVendorsUnavailable`).replace(`{n}`,String(s.failures))]}),(0,m.jsx)(`button`,{type:`button`,className:L.closeButton,"aria-label":n(`close`),"data-testid":`billing-close`,onClick:r,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`})]})})]})]}),!i&&t!==void 0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-stats-error`,children:(0,m.jsxs)(`div`,{className:L.staleNoticeBody,children:[(0,m.jsx)(`span`,{children:n(`statsLoadFailed`)}),(0,m.jsx)(`span`,{className:L.staleNoticeSub,children:t})]})}),!i&&e.staleSnapshot===!0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-stale-snapshot`,children:n(`staleSnapshotNotice`)}),!i&&(0,m.jsx)(`nav`,{className:L.tabNav,"data-testid":`billing-tab-nav`,role:`tablist`,"aria-label":n(`title`),children:Ur.map(e=>(0,m.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":P===e.id,"aria-controls":`billing-tab-panel-${e.id}`,className:y(L.tabButton,P===e.id&&L.tabButtonActive),"data-testid":`billing-tab-${e.id}`,onClick:()=>{Ie(e.id)},children:[(0,m.jsx)(`span`,{className:L.tabRailIcon,"aria-hidden":`true`,children:Gr[e.id]}),(0,m.jsx)(`span`,{className:L.tabNavLabel,children:n(e.labelKey)})]},e.id))}),(0,m.jsxs)(`div`,{className:y(L.dashboardBody,i&&L.nativeSettingsBody),children:[P===`queue`&&(0,m.jsx)(va,{t:n,language:_,navigateToSession:ye,...be===void 0?{}:{sessionTitleOf:be},reuseSourceSession:M.reuseSourceSession}),P===`overview`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-overview`,children:[l?.kind===`drift`&&l.spent!==void 0&&Be!==He()&&(0,m.jsxs)(`div`,{className:L.reconcileNotice,"data-testid":`billing-reconcile-notice`,role:`note`,children:[(0,m.jsx)(`span`,{className:L.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:L.reconcileText,children:n(`reconcileDrift`).replace(`{provider}`,l.provider??``).replace(`{spent}`,U(l.spent)).replace(`{today}`,U(l.todayOfficialCost??0))}),(0,m.jsx)(`button`,{type:`button`,className:L.reconcileDismiss,"data-testid":`billing-reconcile-dismiss`,onClick:Ue,children:n(`reconcileDismiss`)})]}),ve===!0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-balance-stale`,children:n(`balanceStaleNotice`)}),(0,m.jsxs)(`section`,{className:L.hero,"data-testid":`billing-hero`,children:[x(`billing.dashboard.decor`,{position:`hero`}),(0,m.jsxs)(`div`,{className:L.heroTop,children:[(0,m.jsxs)(`div`,{className:L.heroMain,children:[(0,m.jsx)(`span`,{className:L.heroLabel,"data-testid":`billing-hero-range-label`,children:or}),(0,m.jsxs)(`div`,{className:L.heroReadout,children:[(0,m.jsx)(`span`,{className:L.heroCurrency,"aria-hidden":`true`,children:Yt}),(0,m.jsx)(`span`,{className:L.heroValue,"data-testid":`billing-hero-range-value`,children:U(X.cost).slice(1)})]}),(0,m.jsxs)(`span`,{className:L.heroMeta,children:[X.calls.toLocaleString(),` `,n(`calls`),B===`month`&&J>0&&(0,m.jsxs)(`span`,{className:L.heroPred,children:[` `,n(`monthProjected`),` `,U(J)]})]})]}),In!==null&&(0,m.jsxs)(`div`,{className:L.heroGauge,"data-testid":`billing-hero-gauge`,children:[(0,m.jsxs)(`div`,{className:L.heroGaugeDial,children:[(0,m.jsxs)(`svg`,{className:L.heroGaugeSvg,viewBox:`0 0 120 120`,"aria-hidden":`true`,children:[(0,m.jsx)(`defs`,{children:(0,m.jsxs)(`linearGradient`,{id:`heroRingGrad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,m.jsx)(`stop`,{offset:`0%`,stopColor:`var(--ds-cyan)`}),(0,m.jsx)(`stop`,{offset:`55%`,stopColor:`var(--ds-blue)`}),(0,m.jsx)(`stop`,{offset:`100%`,stopColor:`var(--ds-amber)`})]})}),(0,m.jsx)(`circle`,{className:L.heroGaugeTrack,cx:`60`,cy:`60`,r:`52`}),(0,m.jsx)(`circle`,{className:y(L.heroGaugeArc,In.over&&L.heroGaugeArcOver),cx:`60`,cy:`60`,r:`52`,style:{strokeDasharray:`${In.remainRatio*326.7} 326.7`},stroke:In.over?void 0:`url(#heroRingGrad)`})]}),(0,m.jsxs)(`span`,{className:L.heroGaugeCenter,children:[(0,m.jsxs)(`span`,{className:y(L.heroGaugeRemain,In.over&&L.heroGaugeRemainOver),children:[Yt,gn(In.remainCny,h).toFixed(2)]}),(0,m.jsx)(`span`,{className:L.heroGaugeLabel,children:n(`budgetRemain`)})]})]}),(0,m.jsxs)(`span`,{className:L.heroGaugeSub,children:[U(Nn),` / `,U(C)]})]})]}),(0,m.jsxs)(`div`,{className:L.heroSide,children:[(0,m.jsxs)(`div`,{className:L.heroSideItem,children:[(0,m.jsx)(`span`,{className:L.heroSideLabel,children:n(`yearCost`)}),(0,m.jsx)(`span`,{className:L.heroSideValue,children:U(Fn)})]}),(0,m.jsxs)(`div`,{className:L.heroSideItem,children:[(0,m.jsx)(`span`,{className:L.heroSideLabel,children:n(`todayCost`)}),(0,m.jsxs)(`span`,{className:L.heroSideValue,children:[U(An),(0,m.jsxs)(`span`,{className:y(L.delta,ur>=0?L.deltaUp:L.deltaDown),children:[ur>=0?`▲`:`▼`,` `,Math.abs(ur).toFixed(1),`%`]})]})]}),J>0&&(0,m.jsxs)(`div`,{className:L.heroSideItem,title:n(`monthProjectedHint`),children:[(0,m.jsx)(`span`,{className:L.heroSideLabel,children:n(`monthProjected`)}),(0,m.jsx)(`span`,{className:L.heroSideValue,children:U(J)})]}),J<=0&&(0,m.jsx)(`span`,{className:L.heroSideSpacer,"aria-hidden":`true`})]})]}),(e.unpricedModels?.length??0)>0&&!We.has(`unpriced`)&&(0,m.jsxs)(`div`,{className:L.unpricedHint,"data-testid":`billing-unpriced-hint`,children:[(0,m.jsx)(`span`,{className:L.unpricedHintBody,children:n(`unpricedHint`).replace(`{count}`,String(e.unpricedModels?.length??0)).replace(`{models}`,Ea(e.unpricedModels??[],n,_))}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeAction,"data-testid":`billing-unpriced-fix`,onClick:()=>{Ie(`settings`),R(_===`zh`?`单价`:`price`)},children:n(`unpricedFix`)}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeDismiss,"data-testid":`billing-unpriced-dismiss`,"aria-label":n(`close`),onClick:()=>{Ke(`unpriced`)},children:`×`})]}),(e.total.searchCalls??0)>0&&!We.has(`search-estimate`)&&(0,m.jsxs)(`div`,{className:L.unpricedHint,"data-testid":`billing-search-estimate-hint`,children:[(0,m.jsx)(`span`,{className:L.unpricedHintBody,children:n(`searchEstimateHint`).replace(`{count}`,String(e.total.searchCalls??0)).replace(`{each}`,U(e.searchCallEstimateCny??0))}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeDismiss,"data-testid":`billing-search-estimate-dismiss`,"aria-label":n(`close`),onClick:()=>{Ke(`search-estimate`)},children:`×`})]}),(e.unreadableSessions??0)>0&&!We.has(`unreadable`)&&(0,m.jsxs)(`div`,{className:L.staleNotice,"data-testid":`billing-sessions-unreadable`,children:[(0,m.jsxs)(`div`,{className:L.staleNoticeBody,children:[n(`unreadableNotice`).replace(`{count}`,String(e.unreadableSessions)),(e.unreadableNoLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:L.staleNoticeSub,"data-testid":`billing-sessions-no-ledger`,children:n(`unreadableNoLedgerNotice`).replace(`{count}`,String(e.unreadableNoLedgerSessions))}),(e.unreadableFormatSessions??0)>0&&(0,m.jsx)(`div`,{className:L.staleNoticeSub,"data-testid":`billing-sessions-format-unsupported`,children:n(`unreadableFormatNotice`).replace(`{count}`,String(e.unreadableFormatSessions))})]}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeDismiss,"data-testid":`billing-unreadable-dismiss`,"aria-label":n(`close`),onClick:()=>{Ke(`unreadable`)},children:`×`})]}),(0,m.jsxs)(`div`,{className:L.kpiZone,children:[(0,m.jsxs)(`div`,{className:L.kpiZoneHead,children:[(0,m.jsx)(`span`,{className:L.kpiZoneLabel,children:n(`kpiRange`)}),(0,m.jsx)(`div`,{className:L.heatmapRangeSwitch,"data-testid":`billing-kpi-range`,role:`group`,"aria-label":n(`kpiRange`),children:[[`today`,`avgRangeToday`],[`7d`,`avgRange7d`],[`week`,`avgRangeWeek`],[`month`,`avgRangeMonth`],[`all`,`avgRangeAll`],[`custom`,`avgRangeCustom`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,className:y(L.heatmapRangeButton,B===e&&L.heatmapRangeButtonActive),"data-testid":`billing-kpi-range-${e}`,"aria-pressed":B===e,onClick:()=>{ft(e),se(e)},children:n(t)},e))})]}),B===`custom`&&(0,m.jsxs)(`div`,{className:L.kpiCustomRange,"data-testid":`billing-kpi-custom-range`,children:[(0,m.jsxs)(`label`,{children:[n(`customRangeStart`),(0,m.jsx)(`input`,{type:`date`,value:V.start,max:G(),"data-testid":`billing-kpi-custom-start`,onChange:e=>{mt({start:e.target.value})}})]}),(0,m.jsxs)(`label`,{children:[n(`customRangeEnd`),(0,m.jsx)(`input`,{type:`date`,value:V.end,max:G(),"data-testid":`billing-kpi-custom-end`,onChange:e=>{mt({end:e.target.value})}})]})]}),(0,m.jsx)(`section`,{className:L.kpiGrid,"data-testid":`billing-kpi-grid`,children:(()=>{let e=Object.keys(N).sort().slice(-7),t=G(),r=e.indexOf(t),i=(e,t)=>e[t]??0,a=e.map(e=>N[e]?.cost??0),o=e.map(e=>N[e]?.calls??0),s=e.map(e=>{let t=N[e];return t===void 0?0:$r(t)}),c=e.map(e=>{let t=N[e];return t!==void 0&&t.cacheHit+t.cacheMiss>0?t.cacheHit/(t.cacheHit+t.cacheMiss)*100:0}),l=r>0&&i(a,r-1)>0?(i(a,r)-i(a,r-1))/i(a,r-1)*100:0,u=r>0&&i(o,r-1)>0?(i(o,r)-i(o,r-1))/i(o,r-1)*100:0,d=r>0&&i(s,r-1)>0?(i(s,r)-i(s,r-1))/i(s,r-1)*100:0,f=r>0&&i(c,r-1)>0?i(c,r)-i(c,r-1):0,h=(e,t)=>B===`custom`?null:(0,m.jsx)(`svg`,{viewBox:`0 0 28 12`,preserveAspectRatio:`none`,style:{display:`block`,width:`100%`,height:`12px`},children:e.map((n,r)=>{let i=n/Math.max(...e,1)*10,a=r*4;return(0,m.jsx)(`rect`,{x:a,y:12-i,width:`2.5`,height:i,fill:t,opacity:r===e.length-1?1:.6},r)})}),g=e=>B===`custom`?null:(0,m.jsxs)(`span`,{className:y(L.kpiDelta,e>0?L.kpiDeltaUp:e<0?L.kpiDeltaDown:L.kpiDeltaFlat),children:[e>0?`▲`:e<0?`▼`:``,` `,Math.abs(e).toFixed(1),`%`]});return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-tile`,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescCacheHit`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`cacheHitRate`)})}),g(f)]}),(0,m.jsx)(`span`,{className:y(L.kpiValue,L.kpiGreen),children:yn(X.cacheHit+X.cacheMiss>0?X.cacheHit/(X.cacheHit+X.cacheMiss)*100:0)}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(c,`var(--ds-cyan)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[K(X.cacheHit),` / `,K(X.cacheHit+X.cacheMiss),X.cacheWrite>0?` · ${n(`tokenCacheWrite`)} ${K(X.cacheWrite)}`:``]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescTokens`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokens`)})}),g(d)]}),(0,m.jsx)(`span`,{className:L.kpiValue,children:K(X.input+X.output)}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(s,`var(--ds-blue)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[n(`inputTokens`),` `,K(X.input),` · `,n(`outputTokens`),` `,K(X.output)]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-avg`,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescAvgCost`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`avgCost`)})}),g(l)]}),(0,m.jsx)(`span`,{className:L.kpiValue,children:U(X.calls>0?X.cost/X.calls:0)}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(a,`var(--ds-blue)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[n(`calls`),` `,X.calls.toLocaleString()]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescCalls`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`calls`)})}),g(u)]}),(0,m.jsx)(`span`,{className:L.kpiValue,children:X.calls.toLocaleString()}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(o,`var(--ds-blue)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[Wn.length,` `,n(`models`)]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-think`,children:[(0,m.jsx)(`div`,{className:L.kpiLabelRow,children:(0,m.jsx)(p.Tooltip,{label:n(`kpiDescReasoning`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokenReasoningShare`)})})}),(0,m.jsx)(`span`,{className:y(L.kpiValue,L.kpiGreen),children:yn(X.output>0?X.reasoning/X.output*100:0)}),(0,m.jsx)(`span`,{className:L.kpiDetail,children:K(X.reasoning)})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-io`,children:[(0,m.jsx)(`div`,{className:L.kpiLabelRow,children:(0,m.jsx)(p.Tooltip,{label:n(`kpiDescIo`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokenIo`)})})}),(0,m.jsx)(`span`,{className:L.kpiValue,children:(X.output>0?X.input/X.output:0).toFixed(2)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[K(X.input),` / `,K(X.output)]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-peak`,children:[(0,m.jsx)(`div`,{className:L.kpiLabelRow,children:(0,m.jsx)(p.Tooltip,{label:n(`kpiDescPeak`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokenPeak`)})})}),(0,m.jsx)(`span`,{className:L.kpiValue,children:X.peakTokens>0?kn(X.peakTokens):`—`}),(0,m.jsx)(`span`,{className:L.kpiDetail,children:X.peakDay??`—`})]})]})})()})]}),(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-heatmap`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`heatmap`)}),(0,m.jsx)(`div`,{className:L.heatmapRangeSwitch,"data-testid":`billing-heatmap-metric`,role:`group`,"aria-label":n(`heatmap`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.heatmapRangeButton,$e===e&&L.heatmapRangeButtonActive),"data-testid":`billing-heatmap-metric-${e}`,"aria-pressed":$e===e,onClick:()=>{et(e)},children:n(e===`cost`?`metricCost`:`metricTokens`)},e))}),(0,m.jsx)(`div`,{className:L.heatmapRangeSwitch,"data-testid":`billing-heatmap-range`,role:`group`,"aria-label":n(`heatmap`),children:[`month`,`half`,`year`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.heatmapRangeButton,qe===e&&L.heatmapRangeButtonActive),"data-testid":`billing-heatmap-range-${e}`,"aria-pressed":qe===e,onClick:()=>{Ye(e)},children:n(e===`month`?`heatmapMonth`:e===`half`?`heatmapHalf`:`heatmapYear`)},e))}),(0,m.jsxs)(`span`,{className:L.panelHint,"data-testid":`billing-heatmap-summary`,children:[n(`heatmapTotal`),` `,$e===`tokens`?K(Bn):U(Bn),` · `,n(`activeDays`),` `,Vn,` · `,n(`streakDays`),` `,Hn]})]}),(0,m.jsx)(ir,{days:Y,currency:h,t:n,range:qe,unit:$e})]})]}),P===`agents`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-agents`,children:[(0,m.jsxs)(`section`,{className:L.agentSummary,"data-testid":`billing-agent-summary`,children:[(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:String(Ce.agents)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsCount`)})]}),(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:String(Ce.delegations)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsDelegations`)})]}),(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:String(Ce.roots)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsRoots`)})]}),Ce.costliest!==void 0&&Ce.costliest.chainCost>0&&(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:U(Ce.costliest.chainCost)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsMostExpensive`)})]})]}),Se.length===0||Ce.delegations===0?(0,m.jsx)(`p`,{className:L.contextEmpty,"data-testid":`billing-agents-empty`,children:n(`agentsNoData`)}):(0,m.jsx)(`div`,{className:L.agentTree,"data-testid":`billing-agent-tree`,children:(()=>{let e=t=>(0,m.jsxs)(`div`,{className:L.agentNode,children:[(0,m.jsxs)(`div`,{className:L.agentRow,style:{paddingLeft:`${String(t.depth*16)}px`},children:[(0,m.jsx)(`span`,{className:L.agentKind,children:t.depth===0?n(`agentsRoot`):n(`agentsSubagent`)}),(0,m.jsx)(`span`,{className:L.agentTitle,children:t.title??`${n(`sessionUntitled`)} · ${t.id.slice(0,8)}`}),(0,m.jsx)(`span`,{className:L.agentCalls,children:t.calls.toLocaleString()}),(0,m.jsx)(`span`,{className:L.agentCost,children:U(t.cost)}),t.children.length>0&&(0,m.jsxs)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-agent-chain`,children:[n(`agentsChainTotal`),` `,U(t.chainCost)]})]}),t.children.map(e)]},t.id);return Se.map(e)})()})]}),P===`settings`&&(0,m.jsx)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-settings`,children:(0,m.jsxs)(`div`,{className:y(L.settingsLayout,i&&L.nativeSettingsLayout),children:[!i&&(0,m.jsx)(`aside`,{className:L.settingsNav,"data-testid":`billing-settings-nav`,role:`navigation`,"aria-label":`settings`,children:[{id:`display-pref`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:[(0,m.jsx)(`path`,{d:`M5 3v10M11 3v10`}),(0,m.jsx)(`circle`,{cx:`5`,cy:`6.5`,r:`1.8`}),(0,m.jsx)(`circle`,{cx:`11`,cy:`9.5`,r:`1.8`})]}),label:n(`settingsNavDisplayPref`)},{id:`budget`,icon:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:(0,m.jsx)(`path`,{d:`M5 3l3 4 3-4M8 7v6M5.5 9.5h5M5.5 12h5`})}),label:n(`settingsNavBudget`)},{id:`alert`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,m.jsx)(`path`,{d:`M8 2a4 4 0 0 1 4 4v3l1.5 2.5h-11L4 9V6a4 4 0 0 1 4-4z`}),(0,m.jsx)(`path`,{d:`M6.5 13.5a1.5 1.5 0 0 0 3 0`})]}),label:n(`settingsNavAlert`)},{id:`display`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`8`,r:`6`}),(0,m.jsx)(`path`,{d:`M8 2a6 6 0 0 1 0 12z`,fill:`currentColor`,stroke:`none`})]}),label:n(`settingsNavDisplay`)},{id:`advanced`,icon:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:(0,m.jsx)(`path`,{d:`M8 2v12M2.8 5l10.4 6M13.2 5L2.8 11`})}),label:n(`settingsNavAdvanced`),advanced:!0},{id:`about`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`8`,r:`6`}),(0,m.jsx)(`path`,{d:`M8 7.5V11`}),(0,m.jsx)(`circle`,{cx:`8`,cy:`5.2`,r:`0.9`,fill:`currentColor`,stroke:`none`})]}),label:n(`settingsNavAbout`)}].map(e=>(0,m.jsxs)(`button`,{type:`button`,className:y(L.settingsNavItem,at===e.id&&L.settingsNavItemActive,e.advanced&&L.settingsNavItemAdvanced),"data-testid":`billing-settings-nav-${e.id}`,onClick:()=>{ct(e.id)},children:[(0,m.jsx)(`span`,{className:L.settingsNavIcon,"aria-hidden":`true`,children:e.icon}),e.label]},e.id))}),(0,m.jsxs)(`div`,{className:L.settingsPane,children:[(0,m.jsx)(`input`,{className:y(L.ubSearch,L.settingsSearch),type:`search`,value:st,placeholder:n(`settingsSearchPlaceholder`),"aria-label":n(`settingsSearchPlaceholder`),"data-testid":`billing-settings-search`,onChange:e=>{R(e.target.value)}}),st.trim()!==``&&ja(st)&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-settings-search-empty`,children:n(`settingsSearchEmpty`).replace(`{query}`,st.trim())}),(0,m.jsxs)(`div`,{hidden:z(Aa.display),className:L.setCard,id:`settings-display-pref`,"data-testid":`billing-density-motion-card`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsx)(`h3`,{className:L.setCardTitle,children:n(`settingsSectionDisplay`)})})}),(0,m.jsxs)(`div`,{className:L.densityRow,children:[(0,m.jsxs)(`div`,{className:L.densityLeft,children:[(0,m.jsx)(`strong`,{children:n(`densityLabel`)}),(0,m.jsx)(`span`,{children:n(`densityHint`)})]}),(0,m.jsx)(`div`,{className:L.densityButtons,"data-testid":`billing-density-buttons`,children:[`compact`,`default`,`comfortable`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.densityButton,tt===e&&L.densityButtonActive,e===`comfortable`&&L.densityButtonComfortable),"data-testid":`billing-density-${e}`,onClick:()=>{ut(e)},children:n(e===`compact`?`densityCompact`:e==="default"?`densityDefault`:`densityComfortable`)},e))})]}),(0,m.jsxs)(`div`,{className:L.densityRow,children:[(0,m.jsxs)(`div`,{className:L.densityLeft,children:[(0,m.jsx)(`strong`,{children:n(`motionLabel`)}),(0,m.jsx)(`span`,{children:n(`motionHint`)})]}),(0,m.jsx)(`div`,{className:L.densityButtons,"data-testid":`billing-motion-buttons`,children:[`off`,`subtle`,`rich`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.densityButton,rt===e&&L.densityButtonActive),"data-testid":`billing-motion-${e}`,onClick:()=>{dt(e)},children:n(e===`off`?`motionOff`:e===`subtle`?`motionSubtle`:`motionRich`)},e))})]})]}),(0,m.jsxs)(`section`,{hidden:z(Aa.budget),className:L.setCard,"data-testid":`billing-budget`,id:`settings-budget`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`budget`),(0,m.jsx)(ba,{label:n(`budgetHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":S,"aria-label":n(`budget`),"data-testid":`billing-budget-toggle`,className:y(L.switch,S&&L.switchOn),onClick:w,children:(0,m.jsx)(`span`,{className:L.switchKnob})})]}),S&&(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`budgetAmount`)}),(0,m.jsxs)(`span`,{className:L.inp,"data-testid":`billing-budget-input-wrap`,children:[(0,m.jsx)(`span`,{className:L.affix,"aria-hidden":`true`,children:`¥`}),(0,m.jsx)(`input`,{className:L.budgetInput,"data-testid":`billing-budget-input`,type:`number`,min:0,step:1,value:C===0?``:C,placeholder:e.budget===void 0?`0`:String(e.budget),"aria-label":`${n(`budget`)}(${h===`usd`?`USD`:h===`eur`?`EUR`:`CNY`})`,title:`${n(`budget`)}(${h===`usd`?`USD`:h===`eur`?`EUR`:`CNY`})`,onChange:e=>{T(e.target.valueAsNumber)}})]})]}),C>0&&(()=>{let e=Nn/C*100;return(0,m.jsx)(`div`,{className:L.ctlRowStretch,children:(0,m.jsx)(`div`,{className:L.prog,role:`progressbar`,"aria-valuenow":Math.min(e,100),"aria-valuemin":0,"aria-valuemax":100,"aria-label":n(`budget`),"data-testid":`billing-budget-track`,children:(0,m.jsx)(`div`,{className:y(L.progFill,e>=100&&L.budgetFillOver,e>=80&&e<100&&L.budgetFillWarn),style:{width:`${Math.min(e,100)}%`}})})})})(),C>0&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-budget-value`,children:n(`budgetSummary`).replace(`{used}`,U(Nn)).replace(`{total}`,U(C))})]}),(0,m.jsxs)(`div`,{className:L.ctlCol,"data-testid":`billing-model-budgets`,children:[(0,m.jsxs)(`span`,{className:L.modelBudgetTitle,children:[n(`modelBudgetTitle`),(0,m.jsx)(ba,{label:n(`modelBudgetHint`),t:n})]}),Mt.length===0&&(0,m.jsx)(`p`,{className:L.modelBudgetHint,children:n(`emptyHint`)}),(0,m.jsx)(`div`,{className:L.modelBudgetList,children:Mt.map(e=>(0,m.jsxs)(`div`,{className:L.modelBudgetRow,children:[(0,m.jsx)(`span`,{className:L.modelBudgetName,title:e.name??e.key,children:e.name??e.key}),(0,m.jsx)(`span`,{className:L.modelBudgetCost,"data-testid":`billing-model-budget-cost-${e.key}`,children:U(e.cost)}),(0,m.jsxs)(`span`,{className:L.inp,children:[(0,m.jsx)(`span`,{className:L.affix,"aria-hidden":`true`,children:`¥`}),(0,m.jsx)(`input`,{className:L.budgetInput,type:`number`,min:0,step:1,value:E[e.key]??``,placeholder:n(`modelBudgetPlaceholder`),"aria-label":`${n(`modelBudgetTitle`)} · ${e.name??e.key}`,"data-testid":`billing-model-budget-${e.key}`,onChange:t=>{te(e.key,t.target.valueAsNumber)}})]})]},e.key))})]})]}),(0,m.jsxs)(`section`,{hidden:z(Aa.alert),className:L.setCard,"data-testid":`billing-peak-alert-settings`,id:`settings-alert`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`peakAlert`),(0,m.jsx)(ba,{label:n(`peakAlertHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":D.enabled,"aria-label":n(`peakAlert`),"data-testid":`billing-peak-alert-toggle`,className:y(L.switch,D.enabled&&L.switchOn),onClick:()=>{O({...D,enabled:!D.enabled})},children:(0,m.jsx)(`span`,{className:L.switchKnob})})]}),D.enabled&&(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`label`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertLeadMin`)}),(0,m.jsx)(`span`,{className:L.inp,children:(0,m.jsx)(`input`,{type:`number`,min:1,max:30,step:1,value:D.leadMin,className:L.budgetInput,"aria-label":n(`peakAlertLeadMin`),onChange:e=>{let t=Number(e.target.valueAsNumber);O({...D,leadMin:Number.isFinite(t)?Math.min(30,Math.max(1,Math.round(t))):D.leadMin})}})})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertPos`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,role:`radiogroup`,"aria-label":n(`peakAlertPos`),children:[`bottom-right`,`center`].map(e=>(0,m.jsxs)(`label`,{className:L.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-pos`,checked:D.position===e,onChange:()=>O({...D,position:e})}),(0,m.jsx)(`span`,{className:L.rdoDot,"aria-hidden":`true`}),n(e===`bottom-right`?`peakAlertPosCorner`:`peakAlertPosCenter`)]},e))})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertMode`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,role:`radiogroup`,"aria-label":n(`peakAlertMode`),children:[`both`,`peak`,`offPeak`].map(e=>(0,m.jsxs)(`label`,{className:L.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-mode`,checked:D.mode===e,onChange:()=>O({...D,mode:e})}),(0,m.jsx)(`span`,{className:L.rdoDot,"aria-hidden":`true`}),n(e===`both`?`peakAlertModeBoth`:e===`peak`?`peakAlertModePeak`:`peakAlertModeOff`)]},e))})]}),(0,m.jsxs)(`label`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertWebNotify`)}),(0,m.jsx)(`input`,{type:`checkbox`,checked:D.webNotify,"aria-label":n(`peakAlertWebNotify`),onChange:e=>{O({...D,webNotify:e.target.checked})}})]}),(0,m.jsx)(`div`,{className:L.ctlRow,children:(0,m.jsx)(`button`,{type:`button`,className:L.btn,onClick:ne,children:n(`peakAlertPreview`)})})]})]}),(0,m.jsx)(`section`,{hidden:z(Aa.toggles),className:L.setCard,"data-testid":`billing-toggle-setting`,id:`settings-display`,children:(0,m.jsxs)(`div`,{className:L.setGrid3,children:[(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-usage-stats-tool-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`usageStatsTool`),(0,m.jsx)(ba,{label:n(`usageStatsToolHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":Vt,"aria-label":n(`usageStatsTool`),"data-testid":`billing-usage-stats-tool-toggle`,className:y(L.switch,Vt&&L.switchOn),onClick:Ut,children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})}),(0,m.jsxs)(`div`,{className:L.setCell,"data-testid":`billing-livecost-setting`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`liveCostBar`),(0,m.jsx)(ba,{label:n(`liveCostBarHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":me.show,"aria-label":n(`liveCostBar`),"data-testid":`billing-livecost-toggle`,className:y(L.switch,me.show&&L.switchOn),onClick:()=>he({...me,show:!me.show}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]}),me.show&&(0,m.jsxs)(`div`,{className:L.rdoRow,"data-testid":`billing-livecost-position`,children:[(0,m.jsx)(`span`,{className:L.rdoLabel,children:n(`liveCostBarPosition`)}),(0,m.jsx)(Na,{liveCostPrefs:me,onLiveCostPrefs:he,t:n})]})]}),(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-site-list-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`siteListDisplay`),(0,m.jsx)(ba,{label:n(`siteListDisplayHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":ae.hideUnidentified,"aria-label":n(`siteListDisplay`),"data-testid":`billing-site-hide-unidentified`,className:y(L.switch,ae.hideUnidentified&&L.switchOn),onClick:()=>ce({hideUnidentified:!ae.hideUnidentified}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})}),(0,m.jsx)(Da,{prefs:le,onPrefs:fe,groups:pe,t:n,money:U}),(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-quick-queue-entry-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`quickQueueEntry`),(0,m.jsx)(ba,{label:n(`quickQueueEntryHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":M.showEntry,"aria-label":n(`quickQueueEntry`),"data-testid":`billing-quick-queue-entry-toggle`,className:y(L.switch,M.showEntry&&L.switchOn),onClick:()=>ge({...M,showEntry:!M.showEntry}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})}),(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-quick-queue-reuse-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`quickQueueReuseEntry`),(0,m.jsx)(ba,{label:n(`quickQueueReuseEntryHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":M.reuseSourceSession,"aria-label":n(`quickQueueReuseEntry`),"data-testid":`billing-quick-queue-reuse-toggle`,className:y(L.switch,M.reuseSourceSession&&L.switchOn),onClick:()=>ge({...M,reuseSourceSession:!M.reuseSourceSession}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})})]})}),(0,m.jsx)(`section`,{hidden:z(Aa.displayExtra),className:L.setCard,"data-testid":`billing-display-setting`,id:`settings-display-extra`,children:(0,m.jsxs)(`div`,{className:L.setGrid2,children:[(0,m.jsxs)(`div`,{className:L.setCell,"data-testid":`billing-float-setting`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`floatWindow`),(0,m.jsx)(ba,{label:n(`floatWindowHint`),t:n})]})})}),(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardMode`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-mode`,children:[[`full`,`cardModeFull`],[`compact`,`cardModeCompact`],[`hidden`,`cardModeHidden`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.mode===e&&L.floatModeBtnOn),"data-testid":`billing-card-mode-${e}`,"aria-pressed":j.mode===e,disabled:e===`hidden`&&!ie,title:e===`hidden`&&!ie?n(`cardModeFallback`):void 0,onClick:()=>re({...j,mode:e}),children:n(t)},e))})]}),!ie&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-card-mode-fallback`,children:n(`cardModeFallback`)}),ie&&j.mode===`hidden`&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-card-mode-hidden-hint`,children:n(`cardModeHiddenHint`)}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`floatMode`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,"data-testid":`billing-float-mode`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,k.mode===`combined`&&L.floatModeBtnOn),"data-testid":`billing-float-mode-combined`,onClick:()=>A({mode:`combined`,targets:k.targets}),children:n(`floatModeCombined`)}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,k.mode===`subscription`&&L.floatModeBtnOn),"data-testid":`billing-float-mode-subscription`,onClick:()=>A({mode:`subscription`,targets:k.targets}),children:n(`floatModeSubscription`)})]})]}),k.mode===`subscription`&&(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`floatTargets`)}),(0,m.jsxs)(`span`,{className:L.ctlGroup,"data-testid":`billing-float-targets`,children:[ht.map(e=>{let t=k.targets.includes(e.id);return(0,m.jsxs)(`label`,{className:L.floatTarget,children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:t,"data-testid":`billing-float-target-${e.id}`,onChange:()=>A({mode:`subscription`,targets:t?k.targets.filter(t=>t!==e.id):[...k.targets,e.id]})}),(0,m.jsx)(`span`,{className:L.floatTargetLabel,children:e.label})]},e.id)}),ht.length===0&&(0,m.jsx)(`span`,{className:L.setCardDesc,children:n(`floatNoTargetsHint`)})]})]})]})]}),(0,m.jsxs)(`div`,{className:L.setCell,"data-testid":`billing-card-setting`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`cardDisplay`),(0,m.jsx)(ba,{label:n(`cardDisplayHint`),t:n})]})})}),(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardMetric`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-metric`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.metric===`money`&&L.floatModeBtnOn),"data-testid":`billing-card-money`,onClick:()=>re({...j,metric:`money`}),children:n(`cardMetricMoney`)}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.metric===`tokens`&&L.floatModeBtnOn),"data-testid":`billing-card-tokens`,onClick:()=>re({...j,metric:`tokens`}),children:n(`cardMetricTokens`)})]})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardSpan`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-span`,children:[[`day`,`cardSpanDay`],[`week`,`cardSpanWeek`],[`month`,`cardSpanMonth`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.span===e&&L.floatModeBtnOn),"data-testid":`billing-card-span-${e}`,"aria-pressed":j.span===e,onClick:()=>re({...j,span:e}),children:n(t)},e))})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardDeltaBadge`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-delta`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.showDelta&&L.floatModeBtnOn),"data-testid":`billing-card-delta-show`,"aria-pressed":j.showDelta,onClick:()=>re({...j,showDelta:!0}),children:n(`cardDeltaShow`)}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,!j.showDelta&&L.floatModeBtnOn),"data-testid":`billing-card-delta-hide`,"aria-pressed":!j.showDelta,onClick:()=>re({...j,showDelta:!1}),children:n(`cardDeltaHide`)})]})]})]})]})]})}),(0,m.jsx)(`div`,{hidden:z(Aa.advanced),id:`settings-advanced`,children:(0,m.jsx)(Ta,{userPrices:a,onUserPrices:o,t:n,unpricedIds:e.unpricedModels??[]})}),(0,m.jsx)(`div`,{hidden:z(Aa.about),id:`settings-about`,children:(0,m.jsx)(Jn,{t:n,version:e.pluginVersion})}),(0,m.jsxs)(`section`,{hidden:z(Aa.about),className:L.setCard,"data-testid":`billing-more-works`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsx)(`h3`,{className:L.setCardTitle,children:n(`moreWorksTitle`)})})}),(0,m.jsxs)(`div`,{className:L.moreWorkList,children:[(0,m.jsxs)(`a`,{className:L.moreWorkRow,href:`https://github.com/kenz1117/dsh-engram`,target:`_blank`,rel:`noreferrer`,"data-testid":`billing-ad-engram`,children:[(0,m.jsx)(`span`,{className:L.moreWorkName,children:n(`adEngramName`)}),(0,m.jsx)(`span`,{className:L.moreWorkDesc,children:n(`adEngramDesc`)})]}),(0,m.jsxs)(`a`,{className:L.moreWorkRow,href:`https://github.com/kenz1117/dsh-ui-rainbowspeak`,target:`_blank`,rel:`noreferrer`,"data-testid":`billing-ad-rainbowspeak`,children:[(0,m.jsx)(`span`,{className:L.moreWorkName,children:n(`adRainbowName`)}),(0,m.jsx)(`span`,{className:L.moreWorkDesc,children:n(`adRainbowDesc`)})]})]})]})]})]})}),P===`trends`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-trends`,children:[(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-trend`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`trend`)}),x(`billing.dashboard.decor`,{position:`trend`}),(0,m.jsxs)(`span`,{className:L.ubCardControlGroup,children:[(0,m.jsx)(`span`,{className:L.rangeToggle,role:`group`,"aria-label":n(`trend`),children:[7,30].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,Le===e&&L.rangeButtonActive),"aria-pressed":Le===e,"data-testid":`billing-trend-${e}d`,onClick:()=>{Re(e)},children:n(e===7?`trend7d`:`trend30d`)},e))}),(0,m.jsx)(`span`,{className:L.rangeToggle,role:`group`,"aria-label":n(`trendMetric`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,De===e&&L.rangeButtonActive),"aria-pressed":De===e,"data-testid":`billing-trend-metric-${e}`,onClick:()=>{Oe(e)},children:n(e===`cost`?`trendMetricCost`:`trendMetricTokens`)},e))})]}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:Rn})]}),(0,m.jsx)(zn,{data:Un,models:cr,currency:h,metric:De,t:n})]}),b.length>0&&(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-rounds`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`rounds`)}),ln.length>0&&(0,m.jsxs)(`span`,{className:L.ubTagError,"data-testid":`billing-rounds-flag-count`,children:[ln.length,` `,n(`anomaly`)]})]}),(0,m.jsx)(`p`,{className:L.ubCardSub,children:n(`roundsHint`).replace(`{count}`,String(b.length))}),(0,m.jsx)(Qn,{rounds:b,flags:ln,currency:h,t:n})]}),e.byTier!==void 0&&(()=>{let e=dn.peak+dn.offPeak;if(e<=0)return null;let t=dn.peak/e*100;return(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-share`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`peakShare`)}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:n(`peakSharePerCall`)})]}),(0,m.jsxs)(`div`,{className:L.shareTrack,"data-testid":`billing-share-track`,children:[(0,m.jsx)(`div`,{className:y(L.shareSeg,L.shareSegPeak),style:{width:`${t}%`}}),(0,m.jsx)(`div`,{className:y(L.shareSeg,L.shareSegOff),style:{width:`${100-t}%`}})]}),(0,m.jsxs)(`div`,{className:L.shareLegend,children:[(0,m.jsxs)(`span`,{className:L.shareItem,children:[(0,m.jsx)(`span`,{className:L.shareDot,style:{background:`var(--ds-blue)`}}),n(`peak`),(0,m.jsxs)(`span`,{className:L.shareValue,"data-testid":`billing-share-peak`,children:[U(dn.peak),` · `,t.toFixed(1),`%`]})]}),(0,m.jsxs)(`span`,{className:L.shareItem,children:[(0,m.jsx)(`span`,{className:L.shareDot,style:{background:`color-mix(in srgb, var(--ds-blue) 30%, var(--dsb-3))`}}),n(`offPeak`),(0,m.jsxs)(`span`,{className:L.shareValue,"data-testid":`billing-share-offpeak`,children:[U(dn.offPeak),` · `,(100-t).toFixed(1),`%`]})]})]}),pn>0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-share-savings`,children:n(`offPeakSavings`).replace(`{amount}`,U(pn))})]})})()]}),P===`providers`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-providers`,children:[Kn.length>0&&(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-relay-quota`,children:[(0,m.jsx)(`div`,{className:L.panelHead,children:(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`panelRelayQuota`)})}),(0,m.jsx)(`div`,{className:L.providerGroupList,"data-testid":`billing-relay-quotas`,children:Kn.map(e=>(0,m.jsxs)(`div`,{className:L.siteRow,"data-testid":`billing-relay-quota`,children:[(0,m.jsxs)(`span`,{className:L.siteRowName,children:[(0,m.jsx)(`span`,{className:y(L.siteKindTag,qi[e.kind]),children:Ki(e.kind,n)}),(0,m.jsx)(`span`,{className:L.siteRowTitle,children:e.origin})]}),(0,m.jsxs)(`span`,{className:L.siteRowMeta,children:[e.balance!==void 0&&(0,m.jsxs)(`span`,{className:L.siteRowCost,children:[n(`relayBalance`),` `,e.balance.toFixed(2)]}),(e.windows?.length??0)>0?e.windows?.map(e=>{let t=e.remainingPercent<20;return(0,m.jsxs)(`span`,{className:y(L.siteRowCalls,t&&L.siteRowCallsLow),children:[n(`relayWindowUsed`),` `,e.usedPercent,`%`]},e.kind)}):(0,m.jsx)(`span`,{className:L.siteRowCalls,children:n(`relayNoQuota`)})]})]},e.route))})]}),(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-providers`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`providerBilling`)}),x(`billing.dashboard.decor`,{position:`models`}),(0,m.jsx)(`span`,{className:L.panelHint,children:e.updatedAt===void 0?``:`${n(`lastUpdated`)} ${Xi(e.updatedAt)}`})]}),_e&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-subscriptions-stale`,children:n(`subscriptionsStale`)}),(0,m.jsxs)(`div`,{className:L.providerCtlRow,"data-testid":`billing-provider-controls`,children:[(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,disabled:Xn.length===0,onClick:$n,children:n(Zn?`collapseAll`:`expandAll`)}),(0,m.jsxs)(`span`,{className:L.providerTodayToggle,children:[(0,m.jsx)(`span`,{children:n(`todayOnly`)}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":It,"data-testid":`billing-provider-today-toggle`,className:y(L.switch,It&&L.switchOn),onClick:Rt,children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})]}),Yn.length===0?(0,m.jsxs)(`div`,{className:L.emptyState,"data-testid":`billing-provider-empty`,children:[(0,m.jsxs)(`span`,{className:L.emptyIll,"aria-hidden":`true`,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 96 64`,fill:`none`,children:[(0,m.jsx)(`line`,{x1:`6`,y1:`58`,x2:`90`,y2:`58`,stroke:`var(--ds-border-strong)`,strokeWidth:`1`}),(0,m.jsx)(`line`,{x1:`6`,y1:`6`,x2:`6`,y2:`58`,stroke:`var(--ds-border-strong)`,strokeWidth:`1`}),(0,m.jsx)(`path`,{d:`M14 50 L28 40 L42 44 L56 26 L70 30 L82 14`,stroke:`var(--ds-border-strong)`,strokeWidth:`1.5`,strokeLinecap:`round`,fill:`none`,strokeDasharray:`3 3`})]}),(0,m.jsx)(`span`,{className:L.emptyIllDot})]}),(0,m.jsx)(`span`,{className:L.emptyTitle,children:n(It?`todayNoConsumption`:`noData`)}),(0,m.jsx)(`span`,{className:L.emptyDesc,children:n(`emptyHint`)})]}):(0,m.jsx)(`div`,{className:L.providerGroupList,"data-testid":`billing-provider-groups`,children:Yn.map(e=>{let t=e.models.length>0||e.subscriptions.length>0,r=t&&Nt.has(e.id);return(0,m.jsxs)(`div`,{className:L.providerGroup,"data-testid":`billing-provider-group`,children:[(0,m.jsxs)(`div`,{className:y(L.providerGroupHead,t&&L.providerGroupCollapsible),"data-testid":`billing-provider-group-head`,"aria-expanded":t?r:void 0,role:t?`button`:void 0,tabIndex:t?0:void 0,onClick:t?()=>{Ft(e.id)}:void 0,onKeyDown:t?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Ft(e.id))}:void 0,children:[(0,m.jsxs)(`span`,{className:L.providerGroupTitle,children:[(0,m.jsx)(`span`,{className:y(L.healthDot,e.dot),role:`img`,"aria-label":xa(e.dot,n),title:xa(e.dot,n)}),(()=>{let t=Zt(e.name),r=e.channelKind===`direct`?Cr(t):void 0,i=e.channelKind===`direct`?n(`directTag`):e.channelKind===`site`?n(`relayTag`):e.channelKind===`unknown`?n(`unknownTag`):void 0;return(0,m.jsxs)(m.Fragment,{children:[i!==void 0&&(0,m.jsx)(`span`,{className:y(L.kindBadge,e.channelKind===`site`&&L.kindBadgeRelay,e.channelKind===`unknown`&&L.kindBadgeUnknown),"data-testid":`billing-kind-badge`,children:i}),e.channelKind!==`unknown`&&(0,m.jsx)(`span`,{className:L.providerGroupName,children:r??t})]})})(),e.subscriptions.length>0&&(0,m.jsxs)(`span`,{className:L.providerGroupBadge,"data-testid":`billing-provider-sub-count`,children:[e.subscriptions.length,` `,n(`planCountUnit`)]})]}),(0,m.jsxs)(`span`,{className:L.providerGroupMeta,children:[(0,m.jsxs)(`span`,{className:L.providerGroupCost,"data-testid":`billing-provider-cost`,children:[(0,m.jsx)(`span`,{className:L.providerGroupCostLabel,children:n(`cost`)}),e.channelKind===`unknown`?(0,m.jsx)(`span`,{className:L.na,children:`—`}):(0,m.jsx)(`span`,{className:L.providerGroupCostValue,children:U(Ji(e))})]}),!xn(e)&&e.balance!==void 0?(0,m.jsxs)(`span`,{className:L.providerGroupBalance,"data-testid":`billing-provider-balance`,children:[(0,m.jsx)(`span`,{className:L.providerGroupBalanceLabel,children:n(`balance`)}),Sn(e.balance)]}):(0,m.jsx)(`span`,{className:L.providerGroupBalance,"aria-hidden":`true`}),Ti(e.name)===void 0?(0,m.jsx)(`span`,{className:L.providerGroupRecharge,"aria-hidden":`true`}):(0,m.jsx)(`a`,{className:L.providerGroupRecharge,"data-testid":`billing-group-recharge`,href:Ti(e.name),target:`_blank`,rel:`noreferrer`,title:n(`rechargeHint`),"aria-label":`${Zt(e.name)} ${n(`recharge`)}`,onClick:e=>{e.stopPropagation()},children:n(`recharge`)})]})]}),e.models.length>0&&(0,m.jsx)(`div`,{className:L.providerStatRow,"data-testid":`billing-provider-stat-row`,children:(()=>{let t=e.models.reduce((e,t)=>({calls:e.calls+t.calls,input:e.input+t.input,output:e.output+t.output}),{calls:0,input:0,output:0}),r=t.input>0?e.models.reduce((e,t)=>e+t.cacheHitRate,0)/e.models.length:0;return[{lbl:n(`calls`),val:t.calls.toLocaleString(),sub:``},{lbl:n(`inputTokens`),val:K(t.input),sub:r>0?`${n(`cacheHitRate`)} ${r.toFixed(0)}%`:``},{lbl:n(`outputTokens`),val:K(t.output),sub:``},{lbl:n(`cost`),val:U(Ji(e)),sub:e.models.length===1?``:`${e.models.length} ${n(`models`)}`}].map((e,t)=>(0,m.jsxs)(`div`,{className:L.providerStatCell,children:[(0,m.jsx)(`div`,{className:L.providerStatLbl,children:e.lbl}),(0,m.jsx)(`div`,{className:L.providerStatVal,children:e.val}),e.sub!==``&&(0,m.jsx)(`div`,{className:L.providerStatSub,children:e.sub})]},t))})()}),r&&(0,m.jsxs)(m.Fragment,{children:[e.channelKind===`unknown`&&(0,m.jsx)(`p`,{className:L.unknownHint,"data-testid":`billing-unknown-hint`,children:n(`unknownChannelHint`)}),e.models.length>0&&(0,m.jsx)(`div`,{className:L.tableScroll,"data-testid":`billing-table-scroll`,children:(0,m.jsxs)(`table`,{className:L.modelTable,children:[er,(0,m.jsx)(`tbody`,{children:e.models.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:tr(e)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:K(e.input)}),(0,m.jsx)(`td`,{className:L.numCol,children:K(e.output)}),(0,m.jsx)(`td`,{className:L.numCol,children:yn(e.cacheHitRate)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.plan?(0,m.jsxs)(`span`,{className:L.planTag,children:[e.estimated>0?(0,m.jsxs)(`span`,{children:[`≈`,U(e.estimated)]}):null,(0,m.jsx)(`span`,{className:L.planTagBadge,"data-testid":`billing-plan-badge`,children:n(`subscriptionTag`)})]}):e.actual===void 0?e.estimated>0?(0,m.jsxs)(`span`,{title:n(`cellEstimateHint`),children:[`≈`,U(e.estimated)]}):(0,m.jsx)(`span`,{className:L.na,children:`—`}):(()=>{let t=e.officialCost,n=e.actual-t;return t>0&&n>0?(0,m.jsxs)(`span`,{className:L.bucketCost,children:[(0,m.jsx)(`span`,{className:L.bucketOfficial,children:U(t)}),(0,m.jsx)(`span`,{className:L.bucketSep,children:`/`}),(0,m.jsx)(`span`,{className:L.bucketThird,children:U(n)})]}):U(e.actual)})()})]},e.key))})]})}),e.subscriptions.length>0&&(0,m.jsx)(`div`,{className:L.subscriptionGrid,"data-testid":`billing-subscriptions-grid`,children:e.subscriptions.map(e=>{let t=Wi(e.status,n);return(0,m.jsxs)(`div`,{className:y(L.subscriptionCard,L.subscriptionCardUpgraded),"data-testid":`billing-subscription-card`,children:[(0,m.jsxs)(`div`,{className:L.subscriptionHead,children:[(0,m.jsx)(`span`,{className:L.subscriptionName,children:Zt(e.displayName)}),e.planType===`code`&&(()=>{let t=lt(e.provider),r=t===void 0?void 0:n(`subscriptionFeePerMonth`).replace(`{amount}`,t.currency===`USD`?`$${t.amount}`:`¥${t.amount}`);return(0,m.jsxs)(`span`,{className:L.subscriptionPlan,"data-kind":`code`,children:[r??(e.subscriptionAmount!==void 0&&e.subscriptionAmount>0?n(`subscriptionFeePerMonth`).replace(`{amount}`,U(e.subscriptionAmount)):n(`planTypeCode`)),t?.label!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionTier,"data-testid":`billing-tier-${e.provider}`,children:t.label}),t!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionAuto,"data-testid":`billing-auto-${e.provider}`,children:n(`subscriptionAutoDetect`)})]})})(),e.planType===`token`&&(0,m.jsx)(`span`,{className:L.subscriptionPlan,"data-kind":`token`,children:n(`planTypeToken`)}),e.plan!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionPlan,children:e.plan})]}),t!==``&&(0,m.jsx)(`div`,{className:L.subscriptionStatus,children:t}),e.windows.length===0&&t===``&&(0,m.jsx)(`div`,{className:L.subscriptionStatus,children:n(`subscriptionNoApi`)}),e.windows.map(e=>(0,m.jsx)(ya,{window:e,t:n},e.kind))]},e.provider)})})]})]},e.id)})})]}),(0,m.jsxs)(`div`,{className:L.exportBar,"data-testid":`billing-export-bar`,role:`group`,"aria-label":n(`export`),children:[(0,m.jsx)(`span`,{className:L.exportLabel,children:n(`export`)}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-day`,onClick:()=>{On(Dn(`usage-daily`,`csv`,Object.keys(N)),Cn(N),`text/csv`)},children:n(`exportCsvDay`)}),e.bySession!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-sessions`,onClick:()=>{On(Dn(`usage-sessions`,`csv`,Object.keys(N)),En(e.bySession??[]),`text/csv`)},children:n(`exportCsvSession`)}),e.bySite!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-sites`,onClick:()=>{On(Dn(`usage-sites`,`csv`,Object.keys(N)),wn(e.bySite??{}),`text/csv`)},children:n(`exportCsvSite`)}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-json`,onClick:()=>{On(Dn(`usage-stats`,`json`,Object.keys(N)),JSON.stringify(e,null,2),`application/json`)},children:n(`exportJson`)})]}),e.bySession!==void 0&&(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-sessions`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`sessions`)}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:e.bySession.length>20?n(`sessionOverflow`).replace(`{limit}`,`20`).replace(`{total}`,String(At)):`${At}`}),e.bySession.length>0&&(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-sessions-view-all`,onClick:()=>{H(!0)},children:n(jt?`sessionsViewTop`:`sessionsViewAll`).replace(`{count}`,String(e.bySession.length))})]}),(e.staleLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-sessions-stale`,children:n(`staleLedgerNotice`).replace(`{count}`,String(e.staleLedgerSessions))}),(0,m.jsxs)(`div`,{className:L.ubTablewrap,"data-testid":`billing-sessions-table`,children:[we!==void 0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-session-nav-notice`,role:`note`,children:we}),(0,m.jsxs)(`table`,{className:L.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`sessionTitle`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`calls`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`actual`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`lastActive`)})]})}),(0,m.jsxs)(`tbody`,{children:[wt.length===0&&(0,m.jsx)(`tr`,{children:(0,m.jsx)(`td`,{colSpan:4,className:L.emptyRow,children:n(`noData`)})}),wt.slice(0,20).map(e=>{let t=e.children!==void 0||e.subs!==void 0,r=t&&vt.has(e.id),i=Yi(e);return(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{className:t?L.sessionGroupRow:void 0,"aria-expanded":t?r:void 0,tabIndex:t?0:void 0,onClick:t?()=>{Ct(e.id)}:void 0,onKeyDown:t?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Ct(e.id))}:void 0,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:L.modelName,children:(0,m.jsxs)(`button`,{type:`button`,className:L.sessionLink,"data-testid":`billing-session-open`,title:n(`sessionOpen`),onClick:t=>{t.stopPropagation(),Ee(e.id)},children:[e.title??`${n(`sessionUntitled`)} · ${e.id.slice(0,8)}`,(e.mergedCount??1)>1?` ×${e.mergedCount}`:``]})}),e.stale===!0&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-session-stale`,children:n(`sessionStaleBadge`)}),(i.calls>0||i.cost>0)&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-session-sub`,children:i.cost>0?n(`sessionSubCost`).replace(`{cost}`,U(i.cost)):n(`sessionSubCalls`).replace(`{calls}`,i.calls.toLocaleString())})]}),Tt(e)]}),r&&e.children?.map(e=>(0,m.jsxs)(`tr`,{className:L.sessionChildRow,children:[(0,m.jsx)(`td`,{children:(0,m.jsx)(`button`,{type:`button`,className:L.sessionLink,"data-testid":`billing-session-open`,title:n(`sessionOpen`),onClick:t=>{t.stopPropagation(),Ee(e.id)},children:(0,m.jsx)(`span`,{className:L.modelProvider,children:e.id.slice(0,8)})})}),Tt(e)]},e.id)),r&&e.subs?.map(e=>Dt(e,0))]},e.id)})]})]})]}),bt&&(0,m.jsxs)(`div`,{className:L.sessionViewer,"data-testid":`billing-session-viewer`,children:[(0,m.jsxs)(`div`,{className:L.sessionViewerHead,children:[(0,m.jsx)(`h3`,{className:L.sessionViewerTitle,children:n(`sessions`)}),(0,m.jsx)(`input`,{className:L.ubSearch,type:`search`,value:xt,placeholder:n(`sessionViewerSearch`),"aria-label":n(`sessionViewerSearch`),"data-testid":`billing-session-viewer-search`,onChange:e=>{St(e.target.value)}}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-session-viewer-close`,onClick:()=>{H(!1),St(``)},children:n(`close`)})]}),(0,m.jsx)(`div`,{className:L.sessionViewerList,"data-testid":`billing-session-viewer-list`,children:(0,m.jsxs)(`table`,{className:L.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`sessionTitle`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`calls`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`actual`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`lastActive`)})]})}),(0,m.jsxs)(`tbody`,{children:[Ot.length===0&&(0,m.jsx)(`tr`,{children:(0,m.jsx)(`td`,{colSpan:4,className:L.emptyRow,children:n(`noData`)})}),Ot.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsxs)(`td`,{children:[(0,m.jsxs)(`span`,{className:L.modelName,children:[e.title??`${n(`sessionUntitled`)} · ${e.id.slice(0,8)}`,(e.mergedCount??1)>1?` ×${e.mergedCount}`:``]}),e.cwd!==void 0&&(0,m.jsx)(`span`,{className:L.modelProvider,children:ka(e.cwd)}),e.stale===!0&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),children:n(`sessionStaleBadge`)})]}),(0,m.jsx)(`td`,{className:L.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:U(e.cost)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.lastActive>0?`${G(e.lastActive)} ${Xi(e.lastActive)}`:`—`})]},e.id))]})]})})]})]})]}),P===`token`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-token`,children:[(0,m.jsx)(Pn,{stats:e,trendDays:Le,onTrendDays:Re,models:cr,money:U,channelName:qn,t:n}),e.perf!==void 0&&(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-perf`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`perfTitle`)}),(0,m.jsx)(`span`,{className:L.panelHint,children:n(`perfHint`)})]}),(0,m.jsx)(Gn,{perf:e.perf,models:cr,t:n})]})]}),P===`pricing`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:L.ubAlert,role:`note`,children:[(0,m.jsxs)(`div`,{className:L.ubAlertLeft,children:[(0,m.jsxs)(`span`,{className:L.ubRate,"data-testid":`billing-rate`,children:[n(`todayRate`),` 1 USD = `,W(Wt.rate)]}),(0,m.jsx)(`span`,{className:y(L.ubTag,Wt.live?L.ubTagSuccess:L.ubTagNeutral),children:Wt.live?n(`rateLive`):n(`rateBuiltin`)}),Jt>0&&(0,m.jsxs)(`span`,{className:L.ubTag,"data-testid":`billing-pricing-synced`,children:[n(`pricingSyncedAt`),` `,new Date(Jt).toLocaleTimeString(Xt===`zh`?`zh-CN`:`en-US`,{hour:`2-digit`,minute:`2-digit`})]}),(0,m.jsx)(`button`,{type:`button`,className:L.heatmapRangeButton,"data-testid":`billing-pricing-sync`,disabled:Gt,onClick:qt,children:n(Gt?`pricingSyncing`:`pricingSyncNow`)})]}),(0,m.jsx)(`p`,{className:L.ubAlertNote,children:n(`pricingTip`)})]}),(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`pricing`)}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:n(`pricingUnit`)}),(0,m.jsx)(`input`,{className:L.ubSearch,type:`search`,value:Qt,placeholder:n(`pricingSearch`),"aria-label":n(`pricingSearch`),"data-testid":`billing-pricing-search`,onChange:e=>{$t(e.target.value)}})]}),(0,m.jsx)(`div`,{className:y(L.ubTablewrap,L.ubTablewrapPricing),"data-testid":`billing-pricing-table`,children:(0,m.jsxs)(`table`,{className:L.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`thModel`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`thInputMiss`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`thInputHit`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`output`)}),(0,m.jsx)(`th`,{className:L.numCol,colSpan:2,children:n(`band`)})]})}),(0,m.jsx)(`tbody`,{children:mr(fn(),Qt).map(e=>{let t=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:L.ubModel,children:[(()=>{let t=dr(Bt(nn,zt(e.key,an)),on);if(t===null)return null;let r=en.includes(e.key),i=`${e.name} · ${n(t===`peak`?`peak`:`offPeak`)} · ${n(`bandPinHint`)}`;return(0,m.jsx)(`button`,{type:`button`,className:y(L.bandDot,L[t],r&&L.bandDotOn),"data-testid":`billing-band-dot`,"aria-pressed":r,"aria-label":i,title:i,onClick:()=>{tn(ze(e.key)),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.pinned-pref`))}})})(),(0,m.jsxs)(`span`,{className:L.ubModelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:L.ubTagAlert,"data-testid":`billing-price-uncatalogued`,children:n(`uncatalogued`)}),e.promo!==void 0&&un(e.promo,Date.now())&&(0,m.jsx)(p.Tooltip,{label:[e.promo.note,e.promo.endsAtMs===void 0?n(`promoOpenEnded`):n(`promoUntil`,{date:new Date(e.promo.endsAtMs).toLocaleDateString()})].filter(Boolean).join(` · `),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.ubTagPromo,"data-testid":`billing-price-promo`,children:n(`promoBadge`)})})]})]})}),(0,m.jsx)(`td`,{className:L.numCol,children:t?sn(e.price.input,e.price.currency):(0,m.jsx)(`span`,{className:L.na,children:`—`})}),(0,m.jsx)(`td`,{className:L.numCol,children:t?sn(e.price.cacheHit,e.price.currency):(0,m.jsx)(`span`,{className:L.na,children:`—`})}),(0,m.jsx)(`td`,{className:L.numCol,children:t?sn(e.price.output,e.price.currency):(0,m.jsx)(`span`,{className:L.na,children:`—`})}),t&&e.price.offPeak!==void 0&&e.peakHours!==void 0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:L.numCol,children:(0,m.jsxs)(`span`,{className:L.ubChipPeak,children:[(0,m.jsx)(`span`,{className:L.ubChipLabel,children:e.tierSemantics===`latency`?n(`ubStd`):n(`ubPeak`)}),(0,m.jsxs)(`span`,{children:[sn(e.price.input,e.price.currency),`/`,sn(e.price.output,e.price.currency)]})]})}),(0,m.jsx)(`td`,{className:L.numCol,children:(0,m.jsxs)(`span`,{className:L.ubChipOff,children:[(0,m.jsx)(`span`,{className:L.ubChipLabel,children:e.tierSemantics===`latency`?`Flex`:n(`ubOff`)}),(0,m.jsxs)(`span`,{children:[sn(e.price.offPeak.input,e.price.currency),` / `,sn(e.price.offPeak.output,e.price.currency)]})]})})]}):(0,m.jsx)(`td`,{className:L.numCol,colSpan:2,children:t?(0,m.jsx)(`span`,{className:L.flatTag,children:n(`flat`)}):(0,m.jsx)(`span`,{className:L.na,children:`—`})})]}),(e.extraRows??[]).map(t=>(0,m.jsxs)(`tr`,{className:L.ubExtraRow,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:L.ubExtraName,children:pr(t.label,Xt)}),t.note!==void 0&&(0,m.jsx)(`span`,{className:L.ubExtraNote,children:pr(t.note,Xt)})]}),(0,m.jsx)(`td`,{className:L.numCol,children:t.input===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):sn(t.input,e.price.currency)}),(0,m.jsx)(`td`,{className:L.numCol,children:(0,m.jsx)(`span`,{className:L.na,children:`—`})}),(0,m.jsx)(`td`,{className:L.numCol,children:t.output===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):sn(t.output,e.price.currency)}),(0,m.jsx)(`td`,{className:L.numCol,colSpan:2,children:(0,m.jsx)(`span`,{className:L.na,children:`—`})})]},`${e.key}:${t.label}`))]},e.key)})})]})})]}),(0,m.jsxs)(`section`,{className:L.ubCard,children:[(0,m.jsx)(`div`,{className:L.ubCardHead,children:(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`pricingNotes`)})}),(0,m.jsxs)(`ul`,{className:L.ubNotes,children:[(0,m.jsxs)(`li`,{className:L.ubNotesItem,children:[(0,m.jsx)(`span`,{className:L.ubNotesTerm,children:n(`cacheHit`)}),(0,m.jsx)(`span`,{className:L.ubNotesDesc,children:n(`noteCache`)})]}),(0,m.jsxs)(`li`,{className:L.ubNotesItem,children:[(0,m.jsx)(`span`,{className:L.ubNotesTerm,children:n(`peakBand`)}),(0,m.jsx)(`span`,{className:L.ubNotesDesc,children:n(`noteBand`)})]}),(0,m.jsxs)(`li`,{className:L.ubNotesItem,children:[(0,m.jsx)(`span`,{className:L.ubNotesTerm,children:n(`pricingSource`)}),(0,m.jsx)(`span`,{className:L.ubNotesDesc,children:n(`noteSource`)})]})]})]})]}),!i&&x(`billing.dashboard.decor`,{position:`footer`})]}),!i&&(0,m.jsxs)(`footer`,{className:L.modalFooter,"data-testid":`billing-footer`,children:[(0,m.jsx)(`span`,{children:n(`footer`)}),(0,m.jsx)(`span`,{children:n(`footerCredit`).replace(`{version}`,e.pluginVersion===void 0?`—`:`v${e.pluginVersion}`)})]})]});return i?fr:(0,m.jsx)(p.Modal,{open:!0,onClose:r,title:n(`title`),headless:!0,className:y(L.dashboardModal,`dsh-billing-modal`,Rr),children:fr})}function ka(e){return e.split(/[\\/]/).filter(Boolean).at(-1)??`—`}let Aa={display:[`显示`,`密度`,`动效`,`紧凑`,`舒适`,`克制`,`丰富`,`display`,`density`,`motion`,`compact`,`comfortable`],budget:[`预算`,`金额`,`本月`,`花费`,`进度`,`budget`,`amount`,`spend`,`progress`],alert:[`峰谷`,`峰`,`谷`,`提醒`,`通知`,`预览`,`切换`,`peak`,`off-peak`,`alert`,`notify`,`preview`],toggles:[`usage_stats`,`工具`,`即时代费`,`胶囊`,`中转站`,`站点`,`隐藏`,`低谷`,`队列`,`relay`,`site`,`live`,`cost`,`hide`,`queue`,`off-peak`],displayExtra:[`悬浮`,`订阅`,`计费卡`,`指标`,`环比`,`主数字`,`侧栏`,`入口`,`隐藏`,`通道`,`可见`,`float`,`subscription`,`card`,`metric`,`delta`,`sidebar`,`trigger`,`hidden`,`channel`,`visibility`],advanced:[`自定义`,`单价`,`价格`,`低谷`,`custom`,`price`],about:[`关于`,`版本`,`作者`,`许可`,`仓库`,`about`,`version`,`author`,`license`,`repo`]};function ja(e){return Object.values(Aa).every(t=>Hi(e,t))}let Ma=[`below`,`above`,`toolbar`];function Na({liveCostPrefs:e,onLiveCostPrefs:t,t:n}){let[r,i]=(0,d.useState)(!1),a={below:n(`liveCostBarPosBelow`),above:n(`liveCostBarPosAbove`),toolbar:n(`liveCostBarPosToolbar`)},o=Ma.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=Ma.find(e=>e===n);r!==void 0&&t({...e,position:r})},onClose:()=>{i(!1)},anchor:(0,m.jsxs)(`button`,{type:`button`,className:L.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(L.rdoChevron,r&&L.rdoChevronOpen),"aria-hidden":!0,children:qr?(0,m.jsx)(qr,{}):null})]})})}function Pa(e){let{t,checkModels:n,publishCosts:r,registerOpen:i,navigateToSession:a,sessionTitleOf:o,renderSlot:s,useStore:c,actions:l,embeddedSettings:u=!1}=e,[f,p]=(0,d.useState)(zr),[h,g]=(0,d.useState)(void 0),[_,v]=(0,d.useState)(Hr),[y,b]=(0,d.useState)([]),[x,S]=(0,d.useState)(void 0),[C,w]=(0,d.useState)(!1),[T,E]=(0,d.useState)([]),[D,O]=(0,d.useState)(!1),[ie,ae]=(0,d.useState)([]),[oe,se]=(0,d.useState)(()=>Ee()),[ce,le]=(0,d.useState)(()=>Le()),ue=(0,d.useCallback)(e=>{le(e),Re(e),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.language-pref`))},[]),de=(0,d.useCallback)(e=>{se(e),De(e),window.dispatchEvent(new CustomEvent(Te))},[]),[fe,pe]=(0,d.useState)(()=>ee()),M=(0,d.useCallback)(e=>{pe(e),te(e)},[]),[ge,ye]=(0,d.useState)(()=>me()),be=(0,d.useCallback)(e=>{ye(e),he(e)},[]),[we,Oe]=(0,d.useState)(()=>Se()),ke=(0,d.useCallback)(e=>{Oe(e),Ce(e),window.dispatchEvent(new CustomEvent(xe))},[]),[Ae,je]=(0,d.useState)(()=>nt());(0,d.useEffect)(()=>{let e=()=>{je(nt())};return window.addEventListener(tt,e),()=>{window.removeEventListener(tt,e)}},[]);let N=(0,d.useCallback)(e=>{let t={...nt(),showEntry:e.showEntry,reuseSourceSession:e.reuseSourceSession};je(t),rt({showEntry:t.showEntry,reuseSourceSession:t.reuseSourceSession})},[]),[Me,Ne]=(0,d.useState)(()=>k());(0,d.useEffect)(()=>j(()=>{Ne(k())}),[]);let P=e.recoveryEntryAvailable,Pe=(0,d.useMemo)(()=>({...Me,mode:re(Me.mode,P)}),[Me,P]),Fe=(0,d.useCallback)(e=>{let t={...e,mode:re(e.mode,P)};Ne(t),A(t),window.dispatchEvent(new CustomEvent(ne))},[P]),[Ie,ze]=(0,d.useState)(()=>{let e=Ve();return _t(e),e}),Be=(0,d.useCallback)(e=>{ze(e),_t(e),He(e)},[]),[Ue,We]=(0,d.useState)(()=>_e()),Ge=(0,d.useCallback)(e=>{We(e),ve(e)},[]),Ke=(0,d.useMemo)(()=>new Set(Ue.hidden),[Ue.hidden]),qe=(0,d.useMemo)(()=>Mi(f,Ke),[f,Ke]),F=(0,d.useMemo)(()=>Ei(qe),[qe,Ie]),Je=ce,I=(0,d.useCallback)((e,n)=>{let r=(Je===`en`?st:ot)[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},[Je,t]),Ye=(0,d.useMemo)(()=>ji(Ai(f),e=>xr(e,Je)??I(`channelUnknown`)),[f,Je,I]),[Xe,Ze]=(0,d.useState)(!1),Qe=(0,d.useCallback)(()=>{Ze(!1)},[]),$e=(0,d.useRef)(!1),et=(0,d.useCallback)((e=!1)=>{$e.current&&!e||($e.current=!0,Promise.all([Qi().then(e=>{e.ok?(p(e.stats),g(e.stats.sessionListError)):g(e.reason)}),$i().then(({balances:e,reconcile:t,stale:n})=>{e.length>0&&b(e),S(t),w(n===!0)}),ea().then(({quotas:e,stale:t})=>{e.length>0?(E(e),O(t===!0)):O(!1)}).catch(()=>{O(!0)}),ta().then(e=>{ae(e)}).catch(()=>{})]).catch(()=>{}).finally(()=>{$e.current=!1}))},[]),it=(0,d.useCallback)(()=>{et(!0),oa(),Ze(!0)},[et]);(0,d.useEffect)(()=>{et(),oa()},[et]);let[L,at]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{at(!document.hidden),document.hidden||(et(!0),oa())};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[et]),(0,d.useEffect)(()=>{if(!L)return;let e=setInterval(()=>{et(),oa()},Xe?Lr:3e5);return()=>{clearInterval(e)}},[et,Xe,L]),(0,d.useEffect)(()=>{let e=!0;return n().then(t=>{e&&(v(t),Ct(t.catalog??[]))}),()=>{e=!1}},[n]);let R=G(),z=Object.entries(F.byDay).filter(([e])=>e.startsWith(R.slice(0,7))).reduce((e,[,t])=>e+t.cost,0),ct=F.byDay[R]?.cost??0,lt=new Date;lt.setDate(lt.getDate()-1);let ut=`${lt.getFullYear()}-${String(lt.getMonth()+1).padStart(2,`0`)}-${String(lt.getDate()).padStart(2,`0`)}`,dt=F.byDay[ut]?.cost??0,B=dt>0?(ct-dt)/dt*100:0,ft=ti(F.byDay,R),V=(0,d.useMemo)(()=>ei(F.byDay).map(e=>{let t=F.byDay[e.date];return{date:e.date,cost:e.cost,tokens:t===void 0?0:$r(t)}}),[F.byDay]),pt=Object.entries(F.byDay).filter(([e])=>e.startsWith(R.slice(0,7))).reduce((e,[,t])=>e+$r(t),0),mt=(()=>{let e=F.byDay[R];return e===void 0?0:$r(e)})(),ht=ti(F.byDay,R,$r),gt=c(e=>e.enabled),vt=c(e=>e.amount),yt=c(e=>e.tierAlertDays),bt=c(e=>e.lastTierSwitchAt),[H,xt]=(0,d.useState)(()=>Nr()),[St,wt]=(0,d.useState)(null),[Tt,Dt]=(0,d.useState)(null),[Ot,At]=(0,d.useState)(0),[jt,Mt]=(0,d.useState)(!1);(0,d.useEffect)(()=>{if(!H.enabled){At(0),Mt(!1);return}let e=!1,t=!1;Mt(!1);let n=()=>{t||(t=!0,ua().then(t=>{e||At(t.supported?t.queuedCount:0)}).catch(()=>{e||At(0)}).finally(()=>{t=!1,e||Mt(!0)}))};n();let r=setInterval(n,Lr);return()=>{e=!0,clearInterval(r)}},[H.enabled]),(0,d.useEffect)(()=>{wt(e=>Mr(e,Ot))},[Ot]);let[Nt,Pt]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{if(!H.enabled)return;let e=setInterval(()=>Pt(Date.now()),Lr);return()=>{clearInterval(e)}},[H.enabled]);let Ft=(0,d.useCallback)(e=>{xt(e),Pr(e)},[]),It=T.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),Lt=zt(f.byTurn?.[0]?.model,It),Rt=(0,d.useCallback)(()=>{Dt({entering:kt(Date.now())===`peak`?`offPeak`:`peak`,atMs:Date.now()+18e4,channel:Lt})},[Lt]),Bt=vt>0?vt:f.budget??0,Vt=gt&&Bt>0?z/Bt>=1?`over`:z/Bt>=.8?`warn`:`none`:`none`,Ht=(0,d.useCallback)(()=>{let e=!gt;l.setEnabled(e),e&&typeof Notification<`u`&&Notification.permission==="default"&&Notification.requestPermission()},[l,gt]);(0,d.useEffect)(()=>{if(!gt||Bt<=0)return;let e=z/Bt*100,t=Ir.filter(t=>e>=t&&yt?.[String(t)]!==R);if(t.length===0)return;let n=t[t.length-1]??100;if(l.markTierAlerted(t,R),!Pi())return;let r=I(`budgetTierBody`).replace(`{cost}`,W(z)).replace(`{budget}`,W(Bt)).replace(`{pct}`,String(n));Fi(`budget:${n}:${R}`,()=>{new Notification(I(`budget`),{body:r})})},[gt,Bt,z,yt,R,l,I]),(0,d.useEffect)(()=>{if(H.enabled&&!jt)return;let e=jr(Fr(Nt,H,bt,Lt),Ot>0?Fr(Nt,H,bt,`deepseek-metered`):null,Ot);if(e===null||(l.markTierSwitchAlerted(e.atMs),wt(e),!H.webNotify||!Pi()))return;let t=Math.max(1,Math.round((e.atMs-Nt)/6e4)),n=I(e.entering===`peak`?`peakAlertTitlePeak`:`peakAlertTitleOff`),r=I(e.channel===`zhipu-coding-plan`?e.entering===`peak`?`tierAlertEnterPeakZhipu`:`tierAlertEnterOffZhipu`:e.entering===`peak`?`tierAlertEnterPeak`:`tierAlertEnterOff`).replace(`{minutes}`,String(t)),i=e.queueCount===void 0?``:` ${I(e.entering===`peak`?`peakAlertQueuePeak`:`peakAlertQueueOff`,{count:e.queueCount})}`;Fi(`peak:${e.atMs}`,()=>{new Notification(n,{body:`${r}${i}`})})},[Nt,bt,H,Lt,Ot,jt,l,I]);let Ut=c(e=>e.lastBalanceAlertDay),Wt=c(e=>e.modelBudgets??cr),Gt=c(e=>e.modelTierAlertDays??lr),Kt=(0,d.useMemo)(()=>ai(F.byDayModels,R.slice(0,7)),[F.byDayModels,R]),qt=F.lowBalanceThreshold??50,Jt=(0,d.useMemo)(()=>{if(y.length===0)return;let e=Jr(F.byDay,R),t=Et().rate;for(let n of y){if(n.totalBalance===void 0||n.error!==void 0)continue;let r=n.currency===`USD`?n.totalBalance*t:n.totalBalance;if(r>=qt)continue;let i=e>0?Math.floor(r/e):void 0;return{name:n.displayName,cny:r,days:i}}},[y,F.lowBalanceThreshold,F.byDay,R]);(0,d.useEffect)(()=>{if(Jt===void 0||Ut===R||(l.markBalanceAlerted(R),!Pi()))return;let e=I(`balanceLowBody`).replace(`{name}`,Jt.name).replace(`{balance}`,W(Jt.cny)).replace(`{days}`,Jt.days===void 0?`—`:String(Jt.days));Fi(`balance:${R}`,()=>{new Notification(I(`balance`),{body:e})})},[Jt,Ut,R,l,I]),(0,d.useEffect)(()=>{let e=[],t;for(let[n,r]of Object.entries(Wt)){if(!(r>0))continue;let i=Kt[n]??0;for(let a of si(i,r)){let o=`${n}:${a}`;Gt[o]!==R&&(e.push(o),(t===void 0||a>t.tier)&&(t={model:n,tier:a,cost:i,budget:r}))}}if(e.length===0||t===void 0||(l.markModelTierAlerted(e,R),!Pi()))return;let n=I(`modelBudgetBody`).replace(`{model}`,t.model).replace(`{cost}`,W(t.cost)).replace(`{budget}`,W(t.budget)).replace(`{pct}`,String(t.tier));Fi(`model-budget:${t.model}:${t.tier}:${R}`,()=>{new Notification(I(`modelBudgetTitle`),{body:n})})},[Wt,Kt,Gt,R,l,I]);let U=(0,d.useMemo)(()=>{let e=R.slice(0,7),t=new Map;for(let[n,r]of Object.entries(F.byDayModels??{}))if(n.startsWith(e))for(let[e,n]of Object.entries(r)){if(n.cost<=0)continue;let r=cn(e).provider,i=F.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=y.find(t=>Z(t.provider)===Z(e));if(t===void 0||t.totalBalance===void 0){if(e===`Custom`){let e=y.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`?I(`balanceUnauthorized`):t?.error===`unreachable`||t?.error===`invalid`?I(`balanceUnreachable`):I(`balanceUnconfigured`),low:!1}}let n=t.currency===`USD`?`$${t.totalBalance.toFixed(2)}`:W(t.totalBalance),r=Et().rate;return{text:n,low:(t.currency===`USD`?t.totalBalance*r:t.totalBalance)<qt}},a=e=>{let t=T.find(t=>t.displayName===e||pi(t.provider)===e);if(t===void 0||t.windows.length===0)return{text:I(`subscriptionNoApi`),low:!1};let n=t.windows.reduce((e,t)=>Math.min(e,t.remainingPercent),100);return{text:n<=0?I(`subscriptionExhausted`):I(`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])}}},[F.byDayModels,F.byModel,F.lowBalanceThreshold,y,T,R,I]),Yt=(0,d.useMemo)(()=>{let e=F.total;return{input:e.input,output:e.output,cacheRead:e.cacheHit,cacheMiss:e.cacheMiss,calls:e.calls}},[F]);(0,d.useEffect)(()=>{r({todayCost:ct,monthCost:z})},[ct,z,r]),(0,d.useEffect)(()=>{if(!u)return i(it)},[u,i,it]);let Xt=(0,d.useMemo)(()=>f.byTurn??[],[f.byTurn]);return(0,m.jsxs)(m.Fragment,{children:[!u&&(0,m.jsx)(Sa,{...e,t:I,currency:oe,onOpen:it,monthCost:z,todayCost:ct,weekCost:ft,days:V,vendorStatus:U,dash:Yt,cardPrefs:Pe,monthTokens:pt,todayTokens:mt,weekTokens:ht,floatPrefs:fe,subscriptions:T,budgetPressure:Vt,deltaPct:B,...h===void 0?{}:{statsError:h}}),(u||Xe)&&(0,m.jsx)(Oa,{stats:F,...h===void 0?{}:{statsError:h},t:I,onClose:Qe,embeddedSettings:u,navigateToSession:a,sessionTitleOf:o,userPrices:Ie,onUserPrices:Be,health:_,balances:y,...x===void 0?{}:{reconcile:x},quotas:T,relayQuotas:ie,currency:oe,onCurrency:de,language:ce,onLanguage:ue,turns:Xt,renderSlot:s,budgetEnabled:gt,budgetAmount:Bt,modelBudgets:Wt,monthModelCost:Kt,onModelBudget:l.setModelBudget,onToggleBudget:Ht,onBudgetAmount:l.setAmount,peakConfig:H,onPeakConfig:Ft,onPreviewPeak:Rt,floatPrefs:fe,onFloatPrefs:M,cardPrefs:Pe,onCardPrefs:Fe,recoveryEntryAvailable:P,sitePrefs:ge,onSitePrefs:be,channelPrefs:Ue,onChannelPrefs:Ge,channelGroups:Ye,liveCostPrefs:we,onLiveCostPrefs:ke,quickQueuePrefs:Ae,onQuickQueuePrefs:N,quotasStale:D,balanceStale:C}),(St!==null||Tt!==null)&&(0,m.jsx)(Vr,{hit:St??Tt,config:H,t:I,onDismiss:()=>{wt(null),Dt(null)}})]})}function Fa(e){return(0,m.jsx)(`div`,{className:y(L.nativeSettingsRoot,Rr),"data-testid":`native-billing-settings`,children:(0,m.jsx)(Pa,{...e,renderSlot:()=>null,wide:!0,embeddedSettings:!0})})}function Ia(e,t){if(t===void 0||e?.bySession===void 0)return 0;let n=e.bySession.find(e=>e.id===t);return(n?.cost??0)+(n?.subCost??0)}function La(e,t){return t===void 0||e?.bySession===void 0?0:e.bySession.find(e=>e.id===t)?.subCost??0}function Ra(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 za(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 Ba(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 Va(){try{let e=await Q(`/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 Ha(){try{let e=await Q(`/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 Ua(e){switch(e){case`session`:return`subscriptionSession`;case`weekly`:return`subscriptionWeekly`;case`monthly`:return`subscriptionMonthly`;default:return`subscriptionBilling`}}function Wa(e){return!e.running&&!e.promptAttempted&&(e.blank||e.awaitingFirstTurn)}function Ga({hasBandPlan:e}){let[t,n]=(0,d.useState)(()=>Ae()),[r,i]=(0,d.useState)(()=>Date.now());if((0,d.useEffect)(()=>{let e=()=>{n(Ae())};window.addEventListener(ke,e),window.addEventListener(`storage`,e);let t=setInterval(()=>{i(Date.now())},3e4);return()=>{window.removeEventListener(ke,e),window.removeEventListener(`storage`,e),clearInterval(t)}},[]),t.length===0)return null;let a=Nr().leadMin*6e4,o=t.map(t=>({key:t,state:dr(Bt(r,zt(t,e)),a)})).filter(e=>e.state!==null);return o.length===0?null:(0,m.jsx)(`span`,{className:L.bandDots,"data-testid":`billing-pinned-dots`,children:o.map(e=>(0,m.jsx)(`span`,{className:y(L.bandDot,L.bandDotOn,L[e.state]),role:`img`,"aria-label":e.key,title:e.key},e.key))})}function Ka(){let[e,t]=(0,d.useState)(()=>Ee());return(0,d.useEffect)(()=>{let e=()=>{t(Ee())};return window.addEventListener(Te,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(Te,e),window.removeEventListener(`storage`,e)}},[]),e}function qa(){let[e,t]=(0,d.useState)(()=>Se().show),[n,r]=(0,d.useState)(()=>Se().position);return(0,d.useEffect)(()=>{let e=()=>{t(Se().show),r(Se().position)};return window.addEventListener(xe,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(xe,e),window.removeEventListener(`storage`,e)}},[]),{visible:e,position:n}}function Ja(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=!1,i=()=>{n||(n=!0,e||s(Date.now()),Promise.all([Va(),Ha()]).then(([t,n])=>{e||(t!==null&&r(t),a(n))}).catch(()=>{}).finally(()=>{n=!1}))};i();let o=setInterval(i,3e4);return()=>{e=!0,clearInterval(o)}},[e,c,t]);let u=(0,d.useMemo)(()=>Ia(n,e),[n,e]),f=(0,d.useMemo)(()=>La(n,e),[n,e]),p=(0,d.useMemo)(()=>Ra(n,e),[n,e]),m=(0,d.useMemo)(()=>za(i),[i]),h=(0,d.useMemo)(()=>zt(Ba(n,e),i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)),[n,e,i]);return{sessionCost:u,subCost:f,turnCost:p,tier:(0,d.useMemo)(()=>Bt(o,h),[o,h]),chips:m,hasBandPlan:i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)}}function Ya({sessionId:e,t,seat:n,session:r}){let{visible:i,position:a}=qa(),o=i&&a===n&&!(n===`above`&&r!==void 0&&Wa(r)),{sessionCost:s,subCost:c,turnCost:l,tier:u,chips:d,hasBandPlan:f}=Ja(e,o),p=Ka(),h=e=>W(gn(e,p),p),g=s>0||l>0,_=u?.tier===`peak`;return o?(0,m.jsxs)(`span`,{className:n===`above`?y(L.feeBar,L.feeBarAbove,Rr):y(L.feeBar,Rr),"data-testid":`billing-live-cost-bar`,"data-seat":n,children:[(0,m.jsx)(Ga,{hasBandPlan:f}),u!==null&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:_?L.feeChipPrimary:L.feeChipOff,"data-testid":`billing-live-tier`,children:t(_?`tierPeak`:`tierOff`)}),(0,m.jsx)(`span`,{className:L.feeCount,children:Ht(u.nextSwitchInMs)}),(0,m.jsx)(`span`,{className:L.feeSuffix,children:t(_?`tierToOff`:`tierToPeak`)})]}),g&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:L.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:L.feeItem,"data-testid":`billing-live-turn`,children:[t(`liveTurn`),` `,(0,m.jsx)(`span`,{className:L.feeNum,"data-tick":`turn`,children:h(l)})]}),(0,m.jsx)(`span`,{className:L.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:L.feeItem,"data-testid":`billing-live-session`,children:[t(`liveSession`),` `,(0,m.jsx)(`span`,{className:L.feeNum,"data-tick":`session`,children:h(s)}),c>0&&(0,m.jsx)(`span`,{className:L.feeSuffix,"data-testid":`billing-live-session-sub`,children:t(`liveSessionSub`).replace(`{cost}`,h(c))})]})]}),d.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:e.pct<=10?L.feeChipError:L.feeChipAlert,"data-testid":`billing-live-quota`,children:[e.name,` `,t(Ua(e.kind)),` `,e.pct,`%`]})]},`${e.name}:${e.kind}`))]}):null}function Xa({sessionId:e,t}){let n=Ka(),r=e=>W(gn(e,n),n),{visible:i,position:a}=qa(),{sessionCost:o,subCost:s,turnCost:c,tier:l,chips:u,hasBandPlan:d}=Ja(e,i&&a===`toolbar`);if(!i||a!==`toolbar`)return null;let f=l?.tier===`peak`,h=u.reduce((e,t)=>Math.min(e,t.pct),100),g=h<=10?L.feeInlineError:h<=20?L.feeInlineAlert:void 0,_=y(L.feeInline,g),v=[...l===null?[]:[`${Ht(l.nextSwitchInMs)} ${t(f?`tierToOff`:`tierToPeak`)}`],`${t(`liveTurn`)} ${r(c)}`,`${t(`liveSession`)} ${r(o)}`,...s>0?[t(`liveSessionSub`).replace(`{cost}`,r(s))]:[],...u.map(e=>`${e.name} ${t(Ua(e.kind))} ${e.pct}%`)].join(` · `);return(0,m.jsx)(p.Tooltip,{label:v,side:`top`,delayMs:500,portal:!0,children:(0,m.jsxs)(`span`,{className:y(_,Rr),"data-testid":`billing-live-cost-chip`,role:`note`,"aria-label":v,children:[(0,m.jsx)(Ga,{hasBandPlan:d}),l!==null&&(0,m.jsx)(`span`,{className:f?L.feeChipPrimary:L.feeChipOff,"data-testid":`billing-live-tier`,children:t(f?`tierPeak`:`tierOff`)}),o>0&&(0,m.jsx)(`span`,{className:L.feeInlineNum,children:r(o)})]})})}let Za=`@kenz1117/dsh-ui-usage-billing/TaskQueueQuick.module.css`;if(typeof document<`u`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(Za)+`]`)===null){let e=document.createElement(`style`);e.dataset.plugin=`@kenz1117/dsh-ui-usage-billing`,e.dataset.pluginCss=Za,e.textContent=`.HRJ8EG_quickQueue{white-space:nowrap;flex-shrink:0;align-self:center;align-items:center;gap:6px;display:inline-flex;position:relative}.HRJ8EG_quickQueueToggle,.HRJ8EG_quickQueueButton{border:1px solid var(--dsw-alias-border-l1);min-height:24px;color:var(--dsw-alias-label-secondary);font:inherit;cursor:pointer;background:0 0;border-radius:999px;justify-content:center;align-items:center;gap:5px;padding:0 8px;font-size:11px;line-height:18px;display:inline-flex}.HRJ8EG_quickQueueToggle:hover,.HRJ8EG_quickQueueButton:hover:not(:disabled){border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary)}.HRJ8EG_quickQueueToggle[aria-checked=true]{border-color:color-mix(in srgb, var(--ds-blue) 45%, transparent);background:color-mix(in srgb, var(--ds-blue) 10%, transparent);color:var(--ds-blue)}.HRJ8EG_quickQueueButton:focus-visible,.HRJ8EG_quickQueueToggle:focus-visible,.HRJ8EG_quickQueueClear input:focus-visible{outline:2px solid var(--ds-blue);outline-offset:2px}.HRJ8EG_quickQueueButton:disabled{cursor:wait;opacity:.65}.HRJ8EG_quickQueueClear{color:var(--dsw-alias-label-tertiary);cursor:pointer;align-items:center;gap:4px;font-size:11px;display:inline-flex}.HRJ8EG_quickQueueClear input{width:13px;height:13px;accent-color:var(--ds-blue);margin:0}.HRJ8EG_quickQueueCount{background:color-mix(in srgb, var(--ds-blue) 14%, transparent);min-width:16px;height:16px;color:var(--ds-blue);font-variant-numeric:tabular-nums;border-radius:999px;justify-content:center;align-items:center;padding:0 4px;font-size:10px;display:inline-flex}.HRJ8EG_quickQueueNotice{z-index:30;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3);width:max-content;max-width:min(320px,75vw);color:var(--dsw-alias-label-primary);white-space:normal;pointer-events:none;border-radius:8px;padding:7px 10px;font-size:12px;line-height:18px;position:absolute;bottom:calc(100% + 8px);right:0;box-shadow:0 8px 24px #00000038}.HRJ8EG_quickQueueNotice[data-kind=error]{border-color:color-mix(in srgb, var(--ds-red) 45%, transparent);color:var(--ds-red)}`,document.head.appendChild(e)}var Qa={quickQueue:`HRJ8EG_quickQueue`,quickQueueButton:`HRJ8EG_quickQueueButton`,quickQueueClear:`HRJ8EG_quickQueueClear`,quickQueueCount:`HRJ8EG_quickQueueCount`,quickQueueNotice:`HRJ8EG_quickQueueNotice`,quickQueueToggle:`HRJ8EG_quickQueueToggle`};let $a=()=>void 0,eo=()=>void 0;function to(e){return e.tasks.filter(e=>e.status===`queued`).length}function no(){let[e,t]=(0,d.useState)(()=>nt());return(0,d.useEffect)(()=>{let e=()=>{t(nt())};return window.addEventListener(tt,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(tt,e),window.removeEventListener(`storage`,e)}},[]),e}function ro(e){let[t,n]=(0,d.useState)(null),[r,i]=(0,d.useState)(()=>typeof document>`u`||!document.hidden),a=(0,d.useRef)(0),o=(0,d.useCallback)(e=>{a.current+=1,n(to(e))},[]);return(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{i(!document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[]),(0,d.useEffect)(()=>{if(!e||!r){n(null);return}let t=!1,i=!1,o=()=>{if(i)return;i=!0;let e=a.current;ua().then(r=>{t||e!==a.current||n(r.supported?r.queuedCount:null)}).catch(()=>{}).finally(()=>{i=!1})};o();let s=window.setInterval(o,3e4);return()=>{t=!0,window.clearInterval(s)}},[e,r]),{count:t,applySnapshot:o}}function io({t:e}){let t=no();return t.showEntry?(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t.enabled,"aria-label":e(`quickQueueToggle`),className:y(Qa.quickQueueToggle,Rr),"data-testid":`quick-queue-toggle`,onClick:()=>{rt({enabled:!t.enabled})},children:e(`quickQueueToggle`)}):null}function ao(e,t){let n=e(t),r=(0,d.useCallback)(e=>n?.subscribe(e)??(()=>{}),[n]),i=(0,d.useCallback)(()=>n?.getSnapshot(),[n]);return(0,d.useSyncExternalStore)(r,i,i)}function oo({sessionId:e,t,useInput:n,inputActions:r,projectionFaceOf:i}){let a=no(),o=(n??$a)(e=>e),s=ao(i??eo,`workingDirectory`),c=ao(i??eo,`modelSelection`)?.next,{count:l,applySnapshot:u}=ro(a.enabled&&a.showEntry),[f,p]=(0,d.useState)(!1),[h,g]=(0,d.useState)(null),_=(0,d.useRef)(!1),v=(0,d.useRef)(!0),b=(0,d.useRef)({sessionId:e,input:o});if(b.current={sessionId:e,input:o},(0,d.useEffect)(()=>(v.current=!0,()=>{v.current=!1}),[]),(0,d.useEffect)(()=>{if(h===null)return;let e=h.kind===`success`?4e3:8e3,t=window.setTimeout(()=>{g(null)},e);return()=>{window.clearTimeout(t)}},[h]),!a.enabled||!a.showEntry)return null;let x=e=>{g({kind:`error`,text:e})},S=async()=>{if(_.current)return;if(g(null),o===void 0){x(t(`quickQueueUnsupported`));return}let n=o.draft;if(n.trim()===``){x(t(`quickQueueEmpty`));return}if(o.phase!==`plain`){x(t(`quickQueueBusy`));return}if(o.attachmentIds.length>0||o.occurrences.length>0){x(t(`quickQueueAttachments`));return}if(typeof s!=`string`||s===``){x(t(`quickQueueContext`));return}let i=a.clearAfterEnqueue;if(i&&r===void 0){x(t(`quickQueueUnsupported`));return}let l={sessionId:e,prompt:n,draftRev:o.draftRev,cwd:s,clearAfterEnqueue:i,reuseSource:a.reuseSourceSession};_.current=!0,p(!0);try{let e=await la(!0);if(!e.supported){x(t(`quickQueueUnsupported`));return}let n=c??e.defaultModel;if(n==null){x(t(`quickQueueContext`));return}let i=e.workspaces.some(e=>e.path===l.cwd),a=e.models.some(e=>e.provider===n.provider&&e.id===n.model);if(!i||!a){x(t(`quickQueueRoute`));return}let o=await da({action:`enqueue`,prompt:l.prompt,cwd:l.cwd,provider:n.provider,model:n.model,sourceSessionId:String(l.sessionId),reuseSource:l.reuseSource});u(o);let s=t(`quickQueueEnqueued`);if(l.clearAfterEnqueue&&r!==void 0){let e=b.current;if(v.current&&e.sessionId===l.sessionId&&e.input?.draft===l.prompt&&e.input.draftRev===l.draftRev&&e.input.phase===`plain`&&e.input.attachmentIds.length===0&&e.input.occurrences.length===0)try{r.setDraft(``)}catch{s=t(`quickQueueDraftChanged`)}else s=t(`quickQueueDraftChanged`)}v.current&&g({kind:`success`,text:s})}catch(e){if(!v.current)return;let n=e instanceof Error?e.message:String(e);x(t(`quickQueueFailed`).replace(`{message}`,n))}finally{_.current=!1,v.current&&p(!1)}};return(0,m.jsxs)(`span`,{className:y(Qa.quickQueue,Rr),"data-testid":`quick-queue-controls`,children:[(0,m.jsxs)(`label`,{className:Qa.quickQueueClear,children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:a.clearAfterEnqueue,disabled:f,onChange:e=>{rt({clearAfterEnqueue:e.target.checked})}}),t(`quickQueueClear`)]}),(0,m.jsxs)(`button`,{type:`button`,className:Qa.quickQueueButton,"aria-label":t(`quickQueueEnqueue`),"aria-busy":f,disabled:f,"data-testid":`quick-queue-enqueue`,onClick:()=>{S()},children:[t(f?`quickQueueEnqueueing`:`quickQueueEnqueue`),l!==null&&l>0&&(0,m.jsx)(`span`,{className:Qa.quickQueueCount,"data-testid":`quick-queue-count`,"aria-label":t(`quickQueueWaiting`).replace(`{count}`,String(l)),children:l})]}),h!==null&&(0,m.jsx)(`span`,{className:Qa.quickQueueNotice,"data-kind":h.kind,role:h.kind===`error`?`alert`:`status`,children:h.text})]})}function so(){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{x(`billing-costs-listener-threw`)}},registerOpen:e=>(t=e,()=>{t===e&&(t=void 0)})}}let co={enabled:!1,timeout:0};function lo(){try{let e=localStorage.getItem(`dsh-billing-completion-notify-v1`);if(e===null)return{...co};let t=JSON.parse(e);return{enabled:t.enabled===!0,timeout:typeof t.timeout==`number`?t.timeout:0}}catch{return{...co}}}function uo(e){return e.completed===!0||e.running===!1}function fo(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)),uo(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{x(`notification-constructor-failed`)}},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=uo(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)}}function po(e){let t=e.get(`uiWorkspace`);if(t!==void 0&&typeof t.openSession==`function`)return t}function mo(e){let t=e.sessions,n=t?.open;return typeof n==`function`?n.bind(t):void 0}function ho(e){return{available:()=>po(e)!==void 0||mo(e)!==void 0,open:t=>{let n=_(t),r=po(e);if(r!==void 0)try{return r.openSession(n),`opened`}catch(e){return x(`session-navigation-open-failed`,e),`failed`}let i=mo(e);if(i!==void 0)try{return i(n),`opened`}catch(e){return x(`session-navigation-legacy-open-failed`,e),`failed`}return`unavailable`}}}function go(e,t){let n=!1,r={name:`usage`,label:t.label,description:t.description,available:()=>!0,ui:{kind:`action`,run:()=>{t.openDashboard()}}};return e.inject([`commandUi`],e=>{e.effect(()=>{try{let t=e.commandUi.register(r);return n=!0,()=>{n=!1,t()}}catch(e){return x(`usage-command-register-failed`,e),()=>{}}},`ui-usage-billing: /usage command`)}),()=>n}let _o=[`slots`,`locale`,`remote`,`sessions`];function vo(e){let t=so();e.provide(`billingMetrics`,t);let n=ur();e.effect(()=>e.locale.register(at,{zh:ot,en:st}),`ui-usage-billing: dictionaries`);let r=ho(e),i=go(e,{openDashboard:()=>{t.openDashboard()},label:()=>Le()===`en`?st.commandUsageLabel:ot.commandUsageLabel,description:()=>Le()===`en`?st.commandUsageDescription:ot.commandUsageDescription});e.inject([`shortcuts`],e=>{e.effect(()=>{try{let n=e.shortcuts.register({id:`usage-billing.open-dashboard`,label:()=>Le()===`en`?st.shortcutOpenDashboard:ot.shortcutOpenDashboard,aliases:[`usage`,`billing`,`dashboard`],defaults:{"desktop:macos":{code:`KeyD`,modifiers:[`primary`,`shift`]},"desktop:windows":{code:`KeyD`,modifiers:[`primary`,`shift`]},"desktop:linux":{code:`KeyD`,modifiers:[`primary`,`shift`]},"web:macos":{code:`KeyD`,modifiers:[`primary`,`shift`]},"web:windows":{code:`KeyD`,modifiers:[`primary`,`shift`]}},regions:[`page`,`editable`],modals:[],resolve:()=>({status:`handled`,run:()=>{t.openDashboard()}})});return()=>{n()}}catch(e){return x(`shortcut-register-failed`,e),()=>{}}},`ui-usage-billing: dashboard shortcut`)});let a=!1,o={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),recoveryEntryAvailable:i()||a,navigateToSession:e=>r.open(e),sessionTitleOf:t=>{try{let n=e.sessions.list;if(n===void 0)return;let r=n.getSnapshot().byId?.[t],i=r?.displayTitle??r?.title;return typeof i==`string`&&i.trim()!==``?i:void 0}catch{return}}})};e.slots.inject(`settings.section`,()=>{a=!0;let t=e.slots.register({name:`settings.section`,id:`usage-billing`,order:30,label:()=>Le()===`en`?st.nativeSettingsNav:ot.nativeSettingsNav,locale:at,...o},Fa);return()=>{a=!1,t()}}),e.slots.inject(`sidebar.footer.action`,()=>e.slots.register({name:`sidebar.footer.action`,id:`usage-billing`,order:25,locale:at,...o,children:{"billing.dashboard.decor":{kind:`list`,scope:`root`}}},Pa)),e.slots.inject(`conversation.composer.dock`,()=>e.slots.register({name:`conversation.composer.dock`,id:`usage-billing-cost`,order:0,locale:at,inject:e=>({sessionId:_(e),seat:`below`})},Ya)),e.slots.inject(`conversation.input.dock`,()=>e.slots.register({name:`conversation.input.dock`,id:`usage-billing-cost-above`,order:100,locale:at,inject:e=>({sessionId:_(e),seat:`above`})},Ya)),e.slots.inject(`conversation.input.right`,()=>e.slots.register({name:`conversation.input.right`,id:`usage-billing-cost-chip`,order:0,locale:at,inject:e=>({sessionId:_(e)})},Xa)),e.slots.inject(`conversation.input.left`,()=>e.slots.register({name:`conversation.input.left`,id:`usage-billing-quick-queue-toggle`,order:20,locale:at},io)),e.slots.inject(`conversation.input.right`,()=>e.slots.register({name:`conversation.input.right`,id:`usage-billing-quick-queue-enqueue`,order:20,locale:at,inject:t=>({sessionId:_(t),projectionFaceOf:n=>{try{return e.sessions.binding?.(_(t))?.session.projections.faceOf(n)}catch{return}}})},oo)),e.effect(()=>fo(e.sessions.list,lo),`ui-usage-billing: completion notifier`)}return n.UsageBilling=Pa,n.apply=vo,n.inject=_o,t.exports}});
|
|
5
|
+
`)}let J={top:18,right:40,bottom:26,left:46};function In(e){let[,t,n]=e.split(`-`);return`${Number(t)}/${Number(n)}`}function Ln(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 Rn={key:`__total__`,name:``,color:``};function zn({data:e,models:t=[],currency:n=`cny`,metric:r=`cost`,t:i}){let a=i??(e=>ot[e]),[o,s]=(0,d.useState)(null),c=e=>W(gn(e,n),n),l=e=>r===`tokens`?kn(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-J.left-J.right,a=220-J.top-J.bottom,o=e=>n===1?J.left+i/2:J.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=>J.top+a-e/s*a,l=Math.max(...e.map(e=>e.calls),1),d=e=>J.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:Rn,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:L.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],E=Ln(p,Math.max(1,Math.ceil(p/8)));return(0,m.jsxs)(`div`,{className:L.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 220`,className:L.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-J.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:J.left,x2:680-J.right,y1:n,y2:n,className:L.chartGrid}),(0,m.jsx)(`text`,{x:J.left-8,y:n+3,textAnchor:`end`,className:L.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===``?L.chartBar:L.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:L.chartBarPlaceholder},`${t.date}-${t.model.key}-placeholder`):null}),(0,m.jsx)(`path`,{d:w,fill:`none`,className:L.chartLine}),(()=>{let t=G(),n=e.findIndex(e=>e.date===t);return n>=0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`defs`,{children:(0,m.jsxs)(`linearGradient`,{id:`chartAreaGrad`,x1:`0%`,y1:`0%`,x2:`0%`,y2:`100%`,children:[(0,m.jsx)(`stop`,{offset:`0%`,stopColor:`var(--ds-blue)`,stopOpacity:`0.35`}),(0,m.jsx)(`stop`,{offset:`100%`,stopColor:`var(--ds-blue)`,stopOpacity:`0`})]})}),(0,m.jsx)(`path`,{d:`${w} L ${_(e.length-1)} ${y(0)} L ${_(0)} ${y(0)} Z`,fill:`url(#chartAreaGrad)`}),(0,m.jsx)(`line`,{x1:_(n),x2:_(n),y1:J.top,y2:J.top+g,stroke:`var(--ds-amber)`,strokeWidth:`1`,strokeDasharray:`3 3`,opacity:`0.6`}),(0,m.jsx)(`text`,{x:_(n)+4,y:J.top-6,fill:`var(--ds-amber)`,fontSize:`10`,fontFamily:`var(--font-num)`,children:In(t)})]}):null})(),C.map((e,t)=>{let n=y(e);return(0,m.jsx)(`text`,{x:680-J.right+8,y:n+3,textAnchor:`start`,className:L.chartAxisLabel,children:kn(e)},`calls-${t}`)}),E.map(t=>{let n=e[t];return n===void 0?null:(0,m.jsx)(`text`,{x:_(t),y:214,textAnchor:`middle`,className:L.chartAxisLabel,children:In(n.date)},n.date)}),o!==null&&(0,m.jsx)(`line`,{x1:_(o),x2:_(o),y1:J.top,y2:J.top+g,className:L.chartCrosshair})]}),T!==void 0&&o!==null&&(0,m.jsxs)(`div`,{className:L.chartTooltip,style:{left:`${_(o)/680*100}%`,top:`${v(T.cost)/220*100}%`},children:[(0,m.jsx)(`div`,{className:L.chartTooltipDate,children:T.date}),r!==`tokens`&&t.filter(e=>(T.byModel?.[e.key]??0)>0).map(e=>(0,m.jsxs)(`div`,{className:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.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:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.chartLegendBar}),a(`trendTotal`),` `,(0,m.jsx)(`strong`,{children:r===`tokens`?kn(T.tokens??0):c(T.cost)})]}),(0,m.jsxs)(`div`,{className:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.chartLegendLine}),a(`calls`),` `,(0,m.jsx)(`strong`,{children:T.calls.toLocaleString()})]})]}),t.length>0&&r!==`tokens`&&(0,m.jsxs)(`div`,{className:L.chartLegend,children:[t.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:e.color}}),e.name]},e.key)),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.chartLegendLine}),a(`calls`)]})]})]})}let Y={top:14,right:42,bottom:22,left:46};function Bn(e){return e.slice(5,13).replace(`T`,` `)}function Vn(e){return String(e>=100?Math.round(e):Number(e.toFixed(1)))}function Hn(e){return e<1e4?`${Math.round(e)} ms`:e<6e4?`${(e/1e3).toFixed(1)} s`:`${(e/6e4).toFixed(1)} min`}function Un(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function Wn(e,t,n){return t===`ttft`?`${Math.round(e)} ms`:`${e.toFixed(1)} ${n(`perfTpsUnit`)}`}function Gn({perf:e,models:t,t:n}){let[r,i]=(0,d.useState)(()=>Ge()),[a,o]=(0,d.useState)(null),s=e=>{i(e),Ke(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-Y.left-Y.right,a=180-Y.top-Y.bottom,o=e=>n===1?Y.left+i/2:Y.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=>Y.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:L.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:[l.length>0&&(()=>{let e=Math.max(...l.map(e=>e.ttftAvg),1),t=Math.max(...l.filter(e=>e.tpsAvg!==void 0).map(e=>e.tpsAvg??0),1),r=Math.max(...l.map(e=>e.latencyAvg),1),i=l.reduce((e,t)=>e+t.samples,0),a=l.length>0?l.reduce((e,t)=>e+t.ttftAvg,0)/l.length:0,o=l.map(e=>e.tpsAvg).filter(e=>e!==void 0),s=o.length>0?o.reduce((e,t)=>e+t,0)/o.length:0,c=l.length>0?l.reduce((e,t)=>e+t.latencyAvg,0)/l.length:0,u=[{lbl:n(`perfSamples`),val:i.toLocaleString(),unit:``,pct:65,color:`var(--ds-blue)`},{lbl:n(`perfTtft`),val:Hn(a),unit:``,pct:a/e*100,color:`var(--ds-green)`},{lbl:n(`perfTps`),val:o.length>0?Un(s):`—`,unit:``,pct:s/t*100,color:`var(--ds-blue)`},{lbl:n(`perfLatency`),val:Hn(c),unit:``,pct:c/r*100,color:`var(--ds-amber)`}];return(0,m.jsx)(`div`,{className:L.perfHero,"data-testid":`billing-perf-hero`,children:u.map((e,t)=>(0,m.jsxs)(`div`,{className:L.perfHeroCell,children:[(0,m.jsx)(`div`,{className:L.perfHeroLbl,children:e.lbl}),(0,m.jsxs)(`div`,{className:L.perfHeroVal,children:[e.val,e.unit!==``&&(0,m.jsx)(`span`,{className:L.perfHeroUnit,children:e.unit})]}),(0,m.jsx)(`div`,{className:L.perfHeroBar,children:(0,m.jsx)(`i`,{style:{width:`${Math.min(100,e.pct)}%`,background:e.color}})})]},t))})})(),(0,m.jsx)(`div`,{className:L.tableScroll,"data-testid":`billing-perf-table`,children:(0,m.jsxs)(`table`,{className:L.modelTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`model`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfSamples`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfTtft`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfP50`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfP90`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfMax`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfTps`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`perfLatency`)}),(0,m.jsx)(`th`,{className:L.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:L.modelCell,children:[(0,m.jsx)(`span`,{className:L.modelDot,style:{background:e.color}}),(0,m.jsx)(`span`,{className:L.modelName,children:e.name})]})}),(0,m.jsx)(`td`,{className:L.numCol,children:e.samples.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.ttftAvg)}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.ttftP50)}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.ttftP90)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.ttftMax===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):(0,m.jsxs)(`span`,{children:[Hn(e.ttftMax),e.ttftSpikes!==void 0&&e.ttftSpikes>0?` (${e.ttftSpikes}↑)`:``]})}),(0,m.jsx)(`td`,{className:L.numCol,children:e.tpsAvg===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):Un(e.tpsAvg)}),(0,m.jsx)(`td`,{className:L.numCol,children:Hn(e.latencyAvg)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.estimatedSamples>0?e.estimatedSamples:(0,m.jsx)(`span`,{className:L.na,children:`—`})})]},e.key))})]})}),l.length>0&&(()=>{let e=Math.max(...l.map(e=>e.ttftP50),1),t=e=>e<.8?`var(--ds-green)`:e<2?`var(--ds-amber)`:`var(--ds-red)`;return(0,m.jsx)(`div`,{className:L.perfCompareList,"data-testid":`billing-perf-compare`,children:l.map(n=>(0,m.jsxs)(`div`,{className:L.perfCompareRow,children:[(0,m.jsxs)(`div`,{className:L.perfCompareName,children:[(0,m.jsx)(`span`,{className:L.perfCompareDot,style:{background:n.color}}),(0,m.jsx)(`span`,{children:n.name})]}),(0,m.jsx)(`div`,{className:L.perfCompareBar,children:(0,m.jsx)(`i`,{style:{width:`${n.ttftP50/e*100}%`,background:t(n.ttftP50)}})}),(0,m.jsx)(`div`,{className:L.perfCompareNum,children:Hn(n.ttftP50)}),(0,m.jsx)(`div`,{className:L.perfCompareNum,children:n.tpsAvg===void 0?`—`:Un(n.tpsAvg)})]},n.key))})})(),f!==null&&(0,m.jsxs)(`div`,{"data-testid":`billing-perf-hour`,children:[(0,m.jsx)(`div`,{className:L.perfBar,children:(0,m.jsx)(`span`,{className:L.rangeToggle,role:`group`,"aria-label":n(`perfTitle`),children:[`ttft`,`tps`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,r.metric===e&&L.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:L.perfChips,role:`group`,"aria-label":n(`model`),children:[(0,m.jsx)(`button`,{type:`button`,className:L.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(L.perfChip,!t&&L.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:L.perfChipDot,style:{background:t?e.color:`var(--dsw-alias-label-dimmed)`}}),e.name]},e.key)})]}),f.totalPoints>0?(0,m.jsxs)(`div`,{className:L.chartWrap,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 680 180`,className:L.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-Y.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:Y.left,x2:680-Y.right,y1:n,y2:n,className:L.chartGrid}),(0,m.jsx)(`text`,{x:Y.left-8,y:n+3,textAnchor:`end`,className:L.chartAxisLabel,children:Vn(e)})]},`tick-${t}`)}),f.series.map(e=>e.segments.map((t,n)=>(0,m.jsx)(`path`,{d:t,fill:`none`,className:L.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:L.chartAxisLabel,children:Bn(t)},t)}),a!==null&&(0,m.jsx)(`line`,{x1:f.inner(a),x2:f.inner(a),y1:Y.top,y2:Y.top+f.plotH,className:L.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:L.chartHoverDot},`${e.key}-dot`)})]}),a!==null&&g.length>0&&(0,m.jsxs)(`div`,{className:L.chartTooltip,"data-testid":`billing-perf-tooltip`,style:{left:`${f.inner(a)/680*100}%`,top:`${(Y.top+f.plotH/2)/180*100}%`},children:[(0,m.jsx)(`div`,{className:L.chartTooltipDate,children:Bn(f.hourKeys[a]??``)}),g.map(e=>(0,m.jsxs)(`div`,{className:L.chartTooltipRow,children:[(0,m.jsx)(`span`,{className:L.chartTooltipSwatch,style:{background:e.color}}),e.name,` `,(0,m.jsx)(`strong`,{children:Wn(e.v,r.metric,n)})]},e.key))]})]}):(0,m.jsx)(`div`,{className:L.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]}),f===null&&(0,m.jsx)(`div`,{className:L.chartEmpty,"data-testid":`billing-perf-chart-empty`,children:n(`perfChartEmpty`)})]})}let Kn=`@kenz1117/dsh-ui-usage-billing`,qn=`kenz1117`;function Jn({t:e,version:t}){return(0,m.jsxs)(`section`,{className:L.setCard,"data-testid":`billing-plugin-info`,children:[(0,m.jsxs)(`div`,{className:L.plgHead,children:[(0,m.jsx)(`span`,{className:L.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:L.plgTitle,children:[(0,m.jsxs)(`div`,{className:L.plgNameRow,children:[(0,m.jsx)(`h3`,{className:L.plgName,children:Kn}),(0,m.jsx)(`span`,{className:L.plgTag,children:t===void 0?`—`:`v${t}`})]}),(0,m.jsx)(`p`,{className:L.plgDesc,children:`Usage billing dashboard for DeepSeek Harness`})]})]}),(0,m.jsxs)(`div`,{className:L.plgGrid,children:[(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginAuthor`)}),(0,m.jsxs)(`a`,{className:L.plgLink,href:`https://github.com/${qn}`,target:`_blank`,rel:`noreferrer`,children:[`KenZ`,` (`,qn,`)`]})]}),(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginRepository`)}),(0,m.jsx)(`a`,{className:L.plgLink,href:`https://github.com/kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:`GitHub`})]}),(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginNpm`)}),(0,m.jsx)(`a`,{className:L.plgLink,href:`https://www.npmjs.com/package/@kenz1117/dsh-ui-usage-billing`,target:`_blank`,rel:`noreferrer`,children:Kn})]}),(0,m.jsxs)(`div`,{className:L.plgItem,children:[(0,m.jsx)(`span`,{className:L.plgLabel,children:e(`pluginLicense`)}),(0,m.jsx)(`span`,{className:L.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 Xn(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 Zn(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 Qn({rounds:e,flags:t,currency:n,t:r}){let i=(0,d.useMemo)(()=>[...e].sort((e,t)=>e.startedAt-t.startedAt).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:L.roundsEmpty,children:[r(`model`),` —`]});let s=e=>W(gn(e,n),n);return(0,m.jsxs)(`div`,{className:L.rounds,children:[(0,m.jsx)(`div`,{className:L.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=zt(e.model,!1)===`deepseek-metered`&&kt(e.startedAt)===`peak`;return(0,m.jsxs)(`div`,{className:y(L.roundsBarCol,i?L.roundsBarColPeak:L.roundsBarColOff),children:[(0,m.jsx)(`span`,{className:L.roundsBarLabel,style:{bottom:`${n}%`},children:s(e.cost)}),(0,m.jsx)(`div`,{className:L.roundsBarWrap,children:(0,m.jsx)(`div`,{className:t?L.roundsBarFlagged:L.roundsBar,style:{height:`${n}%`},"data-testid":`round-bar`,title:`${r(`model`)} ${e.model} · ${s(e.cost)} · ${Xn(e.startedAt)}${e.endedAt===void 0?``:` → ${Yn(e.endedAt)} (${Zn(e.endedAt-e.startedAt)})`}`,children:t&&(0,m.jsx)(`span`,{className:L.roundsFlagMark,"aria-hidden":`true`})})})]},`${e.sessionId}:${e.turn}`)})}),(0,m.jsxs)(`div`,{className:L.roundsAxis,children:[(0,m.jsxs)(`span`,{children:[r(`costAbbr`),` `,s(o)]}),(0,m.jsxs)(`span`,{children:[i.length,` `,r(`roundsUnit`)]})]})]})}let $n=[`color-mix(in srgb, var(--dsb-3) 70%, transparent)`,`color-mix(in srgb, var(--ds-cyan) 30%, var(--dsb-3))`,`color-mix(in srgb, var(--ds-blue) 60%, var(--dsb-3))`,`var(--ds-blue)`,`var(--ds-amber)`],er=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],tr=e=>G(e.getTime());function nr(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:tr(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:tr(e),dayNum:e.getDate(),value:0,level:0,placeholder:!0});continue}let d=new Date(i,a,u),f=tr(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 rr(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=tr(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=tr(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 ir({days:e,currency:t,now:n,t:r,range:i=`month`,unit:a=`cost`}){let[o,s]=(0,d.useState)(null),c=e=>W(gn(e,t),t),l=e=>a===`tokens`?K(e):c(e),u=(0,d.useMemo)(()=>nr(e,n??new Date),[e,n]),f=tr(n??new Date);if(i!==`month`){let t=rr(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:er[n-1]??``}),o=n)}),(0,m.jsxs)(`div`,{className:L.heatmapYear+(i===`half`?` `+L.heatmapHalf:``),"data-testid":i===`half`?`heatmap-half`:`heatmap-year`,children:[(0,m.jsxs)(`div`,{className:L.heatmapYearBody,children:[(0,m.jsx)(`div`,{className:L.heatmapYearWeekdays,"aria-hidden":`true`,children:[{label:`Mon`,row:1},{label:`Wed`,row:3},{label:`Fri`,row:5}].map(e=>(0,m.jsx)(`span`,{className:L.heatmapYearWeekday,style:{gridRow:e.row},children:e.label},e.label))}),(0,m.jsxs)(`div`,{className:L.heatmapYearScroll,children:[(0,m.jsx)(`div`,{className:L.heatmapYearMonths,"aria-hidden":`true`,"data-testid":`heatmap-year-months`,children:a.map(e=>(0,m.jsx)(`span`,{className:L.heatmapYearMonth,style:{gridColumn:e.index+1},children:e.label},e.index))}),(0,m.jsx)(`div`,{className:L.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:L.heatmapYearCell,"data-testid":`heatmap-year-cell`,"data-level":e.level,"data-today":e.date===f?`true`:void 0,style:{background:$n[e.level]},title:`${e.date} · ${l(e.value)}`,"aria-label":`${e.date}: ${l(e.value)}`,tabIndex:-1},e.date))})]})]}),(0,m.jsxs)(`div`,{className:L.heatmapFooter,children:[(0,m.jsx)(`span`,{children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:L.heatmapLegend,children:$n.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{children:r(`heatmapMore`)})]})]})}return(0,m.jsxs)(`div`,{className:L.heatmap,children:[(0,m.jsx)(`div`,{className:L.heatmapGrid,role:`img`,"aria-label":`daily cost heatmap`,children:u.map(e=>e.map(e=>e.placeholder?(0,m.jsx)(`div`,{className:L.heatmapCellEmpty,children:e.dayNum},e.date):(0,m.jsx)(`button`,{type:`button`,className:L.heatmapCell,"data-testid":`heatmap-cell`,"data-level":e.level,"data-today":e.date===f?`true`:void 0,style:{background:$n[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:L.heatmapFooter,children:[(0,m.jsx)(`span`,{children:r(`heatmapLess`)}),(0,m.jsx)(`span`,{className:L.heatmapLegend,children:$n.map((e,t)=>(0,m.jsx)(`i`,{style:{background:e}},t))}),(0,m.jsx)(`span`,{children:r(`heatmapMore`)}),o!==null&&(0,m.jsxs)(`span`,{className:L.heatmapHover,"data-testid":`heatmap-hover`,children:[o.date,` · `,l(o.value)]})]})]})}let ar={window:6,threshold:2,reasonFactor:1.8,reasonHitDropPp:15};function X(e){if(e.length===0)return null;let t=0;for(let n of e)t+=n;return t/e.length}function or(e){let t=e.cacheHit+e.cacheMiss;return t<=0?null:e.cacheHit/t*100}function sr(e,t){let n=t?.window??ar.window,r=t?.threshold??ar.threshold,i=t?.reasonFactor??ar.reasonFactor,a=t?.reasonHitDropPp??ar.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=or(t),p=X(s),m=[];if(p!==null&&p>0&&t.cost>p*r){let n=X(c),r=X(l),s=X(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}let cr={},lr={};function ur(){return(0,h.defineStore)({init:()=>({enabled:!1,amount:0,tierAlertDays:{},lastBalanceAlertDay:``,lastTierSwitchAt:0,modelBudgets:{},modelTierAlertDays:{}}),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},setModelBudget:(e,t,n)=>{e.modelBudgets??={},Number.isFinite(n)&&n>0?e.modelBudgets[t]=n:delete e.modelBudgets[t]},markModelTierAlerted:(e,t,n)=>{e.modelTierAlertDays??={};for(let r of t)e.modelTierAlertDays[r]=n}}})}function dr(e,t){return e==null?null:Number.isFinite(e.nextSwitchInMs)&&e.nextSwitchInMs<=t?`soon`:e.tier===`peak`?`peak`:`offPeak`}let fr={显式缓存创建:`Explicit cache write`,显式缓存命中:`Explicit cache hit`,长期半价:`Half price`,与标准价一致:`Same as standard`,"限时 5 折":`Limited-time 50% off`};function pr(e,t){return e===void 0||t!==`en`?e:fr[e]??e}function mr(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 hr={"智谱 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 gr(e,t){return t===`en`?hr[e]??e:e}let _r={workbuddy:`WorkBuddy`,"workbuddy-ai":`WorkBuddy AI`},vr={"https://tokenhub.tencentmaas.com":`腾讯云 TokenHub`,"https://api.lkeap.cloud.tencent.com":`腾讯云 Token Plan`,"https://api.deepseek.com":`DeepSeek 官方`},yr={"腾讯云 TokenHub":`Tencent Cloud TokenHub`,"腾讯云 Token Plan":`Tencent Cloud Token Plan`,"DeepSeek 官方":`DeepSeek Official`};function br(e){try{return new URL(e).host}catch{return e}}function xr(e,t=`zh`){if(e.startsWith(`site:`)){let n=e.slice(5),r=vr[n];return r===void 0?br(n):t===`en`?yr[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=_r[n.trim().toLowerCase()];return r===void 0?`${t===`en`?`Direct`:`直连`} · ${n}`:`${t===`en`?`Direct`:`直连`} · ${r}`}}let Sr=[`直连 · `,`Direct · `];function Cr(e){for(let t of Sr)if(e.startsWith(t))return e.slice(t.length)}function wr(e){let t=e;for(;t!==null&&t.parentElement!==null;){let e=t.parentElement;if(e===document.body||e===document.documentElement)return null;let n=getComputedStyle(e);if(n.display!==`contents`&&n.display.includes(`flex`))return e;t=e}return null}function Tr(e,t){let n=e.clientWidth>0,r=0,i=e=>{let a=getComputedStyle(e);if(a.display!==`none`&&a.visibility!==`hidden`&&a.position!==`absolute`&&a.position!==`fixed`){if(a.display===`contents`){for(let t of Array.from(e.children))i(t);return}if(!e.contains(t)){if(n){let t=e.getBoundingClientRect();if(t.width===0&&t.height===0)return}r+=1}}};for(let t of Array.from(e.children))i(t);return r}function Er(e,t){let n=t.alignItems;if(n!==``&&n!==`normal`&&n!==`stretch`)return!1;let r=e.clientWidth;return r===0||r>=140}function Dr(e){let t=wr(e);if(t===null)return{row:null,stacked:!1,wideSeat:!1,neighbors:0};let n=getComputedStyle(t),r=n.flexDirection===`column`||n.flexDirection===`column-reverse`;return{row:t,stacked:r,wideSeat:r&&Er(t,n),neighbors:Tr(t,e)}}function Or(e){return e.row===null?`card`:e.stacked?e.wideSeat?`card`:`icon`:e.neighbors>0?`icon`:`card`}function kr(e,t){let n,r=()=>{let r=Or(Dr(e));r!==n&&(n=r,t(r))},i=wr(e),a=typeof ResizeObserver==`function`?new ResizeObserver(()=>r()):void 0,o=typeof MutationObserver==`function`?new MutationObserver(()=>r()):void 0;return a?.observe(e),i!==null&&(a?.observe(i),o?.observe(i,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`class`,`hidden`]})),window.addEventListener(`resize`,r),r(),{dispose(){a?.disconnect(),o?.disconnect(),window.removeEventListener(`resize`,r)}}}let Ar=`dsh-billing-peak-alert-v1`,jr={enabled:!1,leadMin:2,position:`bottom-right`,webNotify:!0,mode:`both`};function Mr(e,t,n){return t===null||n<=0?e:e===null?{...t,queueCount:n}:e.atMs===t.atMs&&e.entering===t.entering?{...e,queueCount:n}:e}function Nr(e,t){if(e===null||e.queueCount===void 0)return e;if(t>0)return e.queueCount===t?e:{...e,queueCount:t};let{queueCount:n,...r}=e;return r}function Pr(){try{let e=localStorage.getItem(Ar);if(e===null)return{...jr};let t=JSON.parse(e),n=t.mode===`peak`||t.mode===`offPeak`?t.mode:jr.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))):jr.leadMin,position:r,webNotify:t.webNotify!==!1,mode:n}}catch{return{...jr}}}function Fr(e){try{localStorage.setItem(Ar,JSON.stringify(e))}catch{x(`peak-config-storage-unavailable`)}}function Ir(e,t,n,r){if(!t.enabled)return null;let i=Vt(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}}let Lr=[50,80,100],Rr=3e4,zr=`dsh-billing-root`,Br={total:{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cost:0,reasoning:0},byModel:{},byDay:{},byDayModels:{}},Vr=[`#4f8cff`,`#2dd4bf`,`#a78bfa`,`#f59e0b`,`#f472b6`,`#fbbf24`,`#38bdf8`,`#6366f1`,`#f97316`,`#14b8a6`];function Hr({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(L.peakCard,zr,u?L.peakCardPeak:L.peakCardOff,t.position===`center`?L.peakCardCenter:L.peakCardCorner),"data-testid":`billing-peak-alert`,role:`alert`,children:[(0,m.jsxs)(`div`,{className:L.peakHead,children:[(0,m.jsxs)(`span`,{className:y(L.peakTag,u?L.peakTagPrimary:L.peakTagSuccess),children:[(0,m.jsx)(`span`,{className:y(L.peakDot,u?L.peakDotPrimary:L.peakDotSuccess),"aria-hidden":`true`}),c]}),(0,m.jsx)(`button`,{type:`button`,className:L.peakClose,onClick:r,"aria-label":n(`close`),children:`×`})]}),(0,m.jsxs)(`div`,{className:y(L.peakCount,u?L.peakCountPrimary:L.peakCountSuccess),children:[o,`min`]}),(0,m.jsx)(`p`,{className:L.peakDesc,children:l}),e.queueCount!==void 0&&e.queueCount>0&&(0,m.jsx)(`p`,{className:L.peakDesc,"data-testid":`billing-peak-queue-note`,children:n(s===`peak`?`peakAlertQueuePeak`:`peakAlertQueueOff`,{count:e.queueCount})})]})}let Ur={checked:!1,available:!1,models:0,failures:0,okProviders:[],badProviders:[]},Wr=[{id:`overview`,labelKey:`tabOverview`},{id:`queue`,labelKey:`tabQueue`},{id:`providers`,labelKey:`tabProviders`},{id:`token`,labelKey:`tabToken`},{id:`trends`,labelKey:`tabTrends`},{id:`agents`,labelKey:`tabAgents`},{id:`pricing`,labelKey:`tabPricing`},{id:`settings`,labelKey:`tabSettings`}],Gr={fill:`none`,"aria-hidden":!0,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`},Kr={overview:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:(0,m.jsx)(`path`,{d:`M2 13V3M2 13H14M4 10l4-3 2 2 4-5`})}),queue:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:[(0,m.jsx)(`path`,{d:`M3 4h10M3 8h10M3 12h6`}),(0,m.jsx)(`path`,{d:`M12 10v4m-2-2h4`})]}),agents:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`3.5`,r:`2`}),(0,m.jsx)(`circle`,{cx:`3.5`,cy:`12.5`,r:`2`}),(0,m.jsx)(`circle`,{cx:`12.5`,cy:`12.5`,r:`2`}),(0,m.jsx)(`path`,{d:`M8 5.5v2.5M6.5 10.5L5 11.5M9.5 10.5L11 11.5`})]}),providers:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:[(0,m.jsx)(`rect`,{x:`2`,y:`3`,width:`12`,height:`10`,rx:`1.5`}),(0,m.jsx)(`path`,{d:`M5 7l2 2 4-4`})]}),token:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:[(0,m.jsx)(`circle`,{cx:`6`,cy:`6`,r:`3`}),(0,m.jsx)(`circle`,{cx:`11`,cy:`11`,r:`3`})]}),trends:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:(0,m.jsx)(`path`,{d:`M2 4l4 4 3-3 5 5M11 10h3V7`})}),pricing:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:[(0,m.jsx)(`path`,{d:`M8 2l6 3v6l-6 3-6-3V5z`}),(0,m.jsx)(`path`,{d:`M8 2v12M2 5h12`})]}),settings:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,...Gr,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`8`,r:`2.5`}),(0,m.jsx)(`path`,{d:`M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2`})]})},qr=p,Jr=qr.IconChevronDownOutlineMedium??qr.IconChevronDownOutline14;function Yr(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){let n=t.split(`-`),r=new Date(Number(n[0]),Number(n[1])-1,Number(n[2])),i=0;for(let t=0;t<7;t+=1){let t=`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,`0`)}-${String(r.getDate()).padStart(2,`0`)}`;i+=e[t]?.cost??0,r.setDate(r.getDate()-1)}return i/7}function Zr(e,t,n){let r=Object.keys(e).filter(e=>e.startsWith(t)).reduce((t,n)=>t+(e[n]?.cost??0),0),i=t.split(`-`),a=new Date(Number(i[0]),Number(i[1]),0).getDate(),o=n.startsWith(t)?Number(n.slice(8,10)):a,s=Math.max(0,a-o);return r<=0?Yr(e,n)*s:r+Xr(e,n)*s}function Qr(e){return Object.keys(e).length}function $r(e,t=Date.now()){let n=0,r=new Date(t);for(;G(r.getTime())in e;)n+=1,r.setDate(r.getDate()-1);return n}function ei(e){return e.input+e.output}function ti(e){let t=[];for(let n=6;n>=0;--n){let r=new Date;r.setDate(r.getDate()-n);let i=G(r.getTime());t.push({date:i,cost:e[i]?.cost??0})}return t}function ni(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[G(i.getTime())];o!==void 0&&(a+=n(o))}return a}function ri(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=G(a.getTime()),s=new Date(r);s.setDate(s.getDate()-6);let c=G(s.getTime());return ai(e,e=>n===`today`?e===t:n===`7d`?e>=c&&e<=t:n===`week`?e>=o&&e<=t:e.startsWith(t.slice(0,7)))}function ii(e,t,n){return ai(e,e=>e>=t&&e<=n)}function ai(e,t){let n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0,u,d=0;for(let[f,p]of Object.entries(e)){if(!t(f))continue;n+=p.cost,r+=p.calls,i+=p.input,a+=p.output,o+=p.cacheHit,s+=p.cacheMiss,c+=p.cacheWrite??0,l+=p.reasoning??0;let e=ei(p);e>d&&(d=e,u=f)}return{cost:n,calls:r,input:i,output:a,cacheHit:o,cacheMiss:s,cacheWrite:c,reasoning:l,peakDay:u,peakTokens:d}}function oi(e,t){let n={};if(e===void 0)return n;for(let[r,i]of Object.entries(e))if(r.startsWith(t))for(let[e,t]of Object.entries(i))n[e]=(n[e]??0)+t.cost;return n}let si=[80,100];function ci(e,t){if(!(t>0)||!(e>0))return[];let n=e/t*100;return si.filter(e=>n>=e)}let li={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 Z(e){return e.trim().toLowerCase().replace(/[\s_/-]+/g,``)}function ui(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 di(e,t){let n=Z(e),r=Z(t);if(ui(n,r))return!0;let i=li[e];return i!==void 0&&i.some(e=>ui(Z(e),r))}function fi(e){let t=e.trim().toLowerCase(),n=t.replace(/[\s_/-]+/g,``);if(n.length!==0){for(let[e,n]of Object.entries(li))for(let r of n){let n=Z(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(li))for(let r of t){let t=Z(r);if(!(t.length<4)&&n.includes(t))return e}}}let pi={"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 mi(e){let t=pi[e];return t===void 0?fi(e)??e:t}let hi=`https://platform.kimi.com/console/pay`,gi=`https://open.bigmodel.cn/finance-center/finance/pay`,_i=`https://bailian.console.aliyun.com/`,vi=`https://console.volcengine.com/ark`,yi=`https://console.anthropic.com/settings/billing`,bi=`https://console.cloud.google.com/billing`,xi=`https://console.x.ai/`,Si=`https://platform.xiaomimimo.com/console/balance`,Ci=`https://console.cloud.tencent.com/expense/recharge`,wi={deepseek:`https://platform.deepseek.com/top_up`,minimax:`https://platform.minimax.cn/console/recharge-records`,moonshot:hi,kimi:hi,zhipu:gi,bigmodel:gi,qwen:_i,dashscope:_i,doubao:vi,volcengine:vi,ark:vi,openai:`https://platform.openai.com/settings/organization/billing`,anthropic:yi,claude:yi,google:bi,gemini:bi,xai:xi,grok:xi,siliconflow:`https://cloud.siliconflow.cn/account/charge`,hunyuan:Ci,tencent:Ci,腾讯云:Ci,xiaomi:Si,mimo:Si,mi:Si,qianfan:`https://console.bce.baidu.com/qianfan/overview`};function Ti(e){let t=wi[e];if(t!==void 0)return t;let n=Object.keys(wi).find(t=>e.startsWith(t));return n===void 0?void 0:wi[n]}function Ei(e){let t=Z(e),n=Ti(t);if(n!==void 0)return n;for(let[e,n]of Object.entries(li))if(ui(Z(e),t))for(let e of n){let t=Ti(Z(e));if(t!==void 0)return t}}function Di(e){let t=vt();if(t===void 0||e.byDayModels===void 0)return e;let n=Et().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||U(t.key)===U(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)*Ot+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=bt(i)??xt(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:bt(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=>!bt(e)&&!xt(e))}}function Oi(){return{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cacheWrite:0,cost:0}}function ki(e,t){e.calls+=t.calls,e.input+=t.input,e.output+=t.output,e.cacheHit+=t.cacheHit,e.cacheMiss+=t.cacheMiss,e.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost}function Ai(e,t){e.calls-=t.calls,e.input-=t.input,e.output-=t.output,e.cacheHit-=t.cacheHit,e.cacheMiss-=t.cacheMiss,e.cacheWrite=(e.cacheWrite??0)-t.cacheWrite,e.cost-=t.cost}function ji(e){let t=e.byDayModelsSite;if(t===void 0)return[];let n=new Map;for(let e of Object.values(t))for(let t of Object.values(e))for(let[e,r]of Object.entries(t)){let t=n.get(e)??Oi();ki(t,r),n.set(e,t)}return[...n.entries()].map(([e,t])=>({siteKey:e,calls:t.calls,input:t.input,output:t.output,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,cost:t.cost})).sort((e,t)=>t.cost===e.cost?e.siteKey.localeCompare(t.siteKey):t.cost-e.cost)}function Mi(e,t){let n=new Map;for(let r of e){let e=t(r.siteKey),i=n.get(e)??{siteKeys:[],calls:0,tokens:0,cost:0};i.siteKeys.push(r.siteKey),i.calls+=r.calls,i.tokens+=r.input+r.output,i.cost+=r.cost,n.set(e,i)}return[...n.entries()].map(([e,t])=>({name:e,...t})).sort((e,t)=>t.cost===e.cost?e.name.localeCompare(t.name,`zh`):t.cost-e.cost)}function Ni(e,t){if(t.size===0)return e;let n=e.byDayModelsSite;if(n===void 0)return e;let r=new Map,i=new Map,a=new Map,o=Oi(),s={};for(let[e,c]of Object.entries(n)){let n={};for(let[s,l]of Object.entries(c)){let c={};for(let[n,u]of Object.entries(l)){if(t.has(n)){let t=r.get(e)??new Map,n=t.get(s)??Oi();ki(n,u),t.set(s,n),r.set(e,t);let c=i.get(e)??Oi();ki(c,u),i.set(e,c);let l=a.get(s)??Oi();ki(l,u),a.set(s,l),ki(o,u);continue}c[n]=u}Object.keys(c).length>0&&(n[s]=c)}s[e]=n}let c={};for(let[t,n]of Object.entries(e.byDay)){let e=i.get(t);if(e===void 0){c[t]=n;continue}let r={...n};Ai(r,e),c[t]=r}let l={};for(let[t,n]of Object.entries(e.byDayModels??{})){let e={};for(let[i,a]of Object.entries(n)){let n={...a},o=r.get(t)?.get(i);o!==void 0&&Ai(n,o),e[i]=n}l[t]=e}let u={};for(let[t,n]of Object.entries(e.byModel)){let e={...n},r=a.get(t);r!==void 0&&Ai(e,r),u[t]=e}let d={};for(let[n,r]of Object.entries(e.bySite??{}))t.has(n)||(d[n]=r);let f={...e.total};return Ai(f,o),{...e,total:f,byDay:c,byDayModels:l,byModel:u,bySite:d,byDayModelsSite:s}}async function Q(e,t={}){let{timeoutMs:n=12e3,signal:r,...i}=t,a=new AbortController,o=setTimeout(()=>{a.abort()},n),s=()=>{a.abort()};r!=null&&(r.aborted?a.abort():r.addEventListener(`abort`,s,{once:!0}));try{return await fetch(e,{...i,signal:a.signal})}finally{clearTimeout(o),r?.removeEventListener(`abort`,s)}}let Pi=new Set;function Fi(){return typeof Notification<`u`&&Notification.permission===`granted`}function Ii(e,t){Pi.has(e)||(Pi.add(e),Q(`/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 Li(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 Ri(e){let t=new Map(e.map(e=>[e.id,e])),n=Li(e.filter(e=>e.parentId===void 0)),r=new Map;for(let e of n){r.set(e.id,e);for(let t of e.children??[])r.set(t.id,e)}let i=new Set,a=new Map,o=(e,t)=>{e.subs===void 0?e.subs=[t]:e.subs.push(t),i.add(t.id),a.set(t.id,e.id)};for(let n of e){if(n.parentId===void 0)continue;let e=t.get(n.parentId);if(e!==void 0&&e.parentId!==void 0&&e.id!==n.id){let t=e.id,r=new Set,i=!1;for(;t!==void 0&&!r.has(t);){if(r.add(t),t===n.id){i=!0;break}t=a.get(t)}if(!i){o(e,n);continue}}let s=new Set,c=n.parentId;for(;c!==void 0&&!s.has(c);){s.add(c);let e=r.get(c);if(e!==void 0){i.has(n.id)||o(e,n);break}c=t.get(c)?.parentId}}let s=e=>e.cost+(e.subCost??0),c=e=>{e.subs?.sort((e,t)=>s(t)-s(e)||t.lastActive-e.lastActive);for(let t of e.subs??[])c(t)};for(let e of n)c(e);let l=e.filter(e=>e.parentId!==void 0&&!i.has(e.id));for(let e of l)c(e);return[...n,...l].sort((e,t)=>t.cost-e.cost||t.lastActive-e.lastActive)}function zi(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,n);let n=new Map,r=[];for(let i of e){let e=i.parentId;if(e===void 0||!t.has(e)||Bi(t,i.id)){r.push(i);continue}let a=n.get(e);a===void 0?n.set(e,[i]):a.push(i)}let i=(e,t,r)=>{let a=new Set(r);a.add(e.id);let o=(n.get(e.id)??[]).filter(e=>!r.has(e.id)).map(e=>i(e,t+1,a)).sort((e,t)=>t.chainCost-e.chainCost),s={id:e.id,...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},calls:e.calls,cost:e.cost,lastActive:e.lastActive,chainCost:e.cost,chainCalls:e.calls,children:o,depth:t};for(let e of o)s.chainCost+=e.chainCost,s.chainCalls+=e.chainCalls;return s};return r.map(e=>i(e,0,new Set)).sort((e,t)=>t.chainCost-e.chainCost)}function Bi(e,t){let n=new Set([t]),r=e.get(t)?.parentId;for(;r!==void 0;){if(n.has(r))return!0;n.add(r),r=e.get(r)?.parentId}return!1}function Vi(e){let t=0,n=0,r,i=e=>{t+=1,n+=e.children.length,(r===void 0||e.chainCost>r.chainCost)&&(r=e);for(let t of e.children)i(t)};for(let t of e)i(t);return{agents:t,delegations:n,roots:e.length,...r===void 0?{}:{costliest:r}}}function Hi(e,t){let n=t.trim().toLowerCase();return n===``?e:e.filter(e=>(e.title??``).toLowerCase().includes(n)||(e.cwd??``).toLowerCase().includes(n)||e.id.toLowerCase().includes(n))}function Ui(e,t){let n=e.trim().toLowerCase();return n!==``&&!t.some(e=>e.toLowerCase().includes(n))}function Wi(e,t){return e.checked?e.okProviders.some(e=>di(t,e))?L.healthOk:e.badProviders.some(e=>di(t,e))?L.healthBad:L.healthIdle:L.healthIdle}function Gi(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 Ki(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 qi(e,t){switch(e){case`new-api`:return t(`relayKindNewApi`);case`sub2api`:return t(`relayKindSub2Api`);default:return t(`relayKindUnknown`)}}let Ji={"new-api":L.siteKindSite,sub2api:L.siteKindDirect,unknown:L.siteKindUnknown},Yi=e=>e.models.reduce((e,t)=>e+(t.actual??(t.plan===!0?0:t.estimated)),0);function Xi(e){return e.children===void 0?{cost:e.subCost??0,calls:e.subCalls??0}:(e.children??[]).reduce((e,t)=>({cost:e.cost+(t.subCost??0),calls:e.calls+(t.subCalls??0)}),{cost:0,calls:0})}function Zi(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Qi(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let n=t;for(let e of[`sessionListError`,`error`]){let t=n[e];if(typeof t==`string`&&t!==``)return t}return}catch{return}}async function $i(){try{let e=await Q(`/api/billing/usage-stats`),t=await e.text();if(!e.ok)return{ok:!1,reason:Qi(t)??`HTTP ${e.status}`,status:e.status};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{ok:!1,reason:`响应不是统计文档`};if(!(`total`in n))return{ok:!1,reason:Qi(t)??`响应不是统计文档`};let r=n,i=e=>typeof e==`object`&&!!e;return{ok:!0,stats:{total:r.total??Br.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},...r.staleSnapshot===!0?{staleSnapshot:!0}:{},...typeof r.budget==`number`?{budget:r.budget}:{},...typeof r.lowBalanceThreshold==`number`?{lowBalanceThreshold:r.lowBalanceThreshold}:{},...Array.isArray(r.bySession)?{bySession:r.bySession}:{},...typeof r.bySessionTotal==`number`?{bySessionTotal:r.bySessionTotal}:{},...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}:{},...typeof r.sessionListError==`string`?{sessionListError:r.sessionListError}:{}}}}catch(e){return{ok:!1,reason:e instanceof Error?e.message:String(e)}}}async function ea(){try{let e=await Q(`/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},...r.stale===!0?{stale:!0}:{}}}catch{return{balances:[]}}}async function ta(){let e=await Q(`/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){let e=n;return{quotas:e.quotas,...e.stale===!0?{stale:!0}:{}}}throw Error(`subscriptions: invalid response`)}async function na(){let e=await Q(`/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 ra(){try{let e=await Q(`/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 ia(e){try{let t=await Q(`/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 aa=!1,oa=0;async function sa(e=0){try{let t=await Q(`/api/billing/pricing`);if(!t.ok){aa=!1;return}let n=await t.text(),r=JSON.parse(n);if(typeof r!=`object`||!r||!(`source`in r)){aa=!1;return}let i=r;Array.isArray(i.catalog)&&i.catalog.length>0&&i.aliases!==null&&typeof i.aliases==`object`&&Gt(i.catalog,i.aliases);let a=r;if(a.source===`builtin`&&e<3){if(e===0){if(aa)return;aa=!0}setTimeout(()=>{sa(e+1)},2e3);return}aa=!1,oa=a.syncedAt??0,St(a)}catch{aa=!1}}async function ca(){try{return(await Q(`/api/billing/pricing/refresh`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`,timeoutMs:3e4})).ok?(await sa(),!0):!1}catch{return!1}}async function la(e){try{let t=JSON.parse(await e.text());return typeof t.error==`string`?t.error:`HTTP ${e.status}`}catch{return`HTTP ${e.status}`}}async function ua(e=!1){let t=await Q(`/api/billing/task-queue${e?`?refresh=1`:``}`);if(!t.ok)throw Error(await la(t));return await t.json()}async function da(){let e=await Q(`/api/billing/task-queue-summary`);if(!e.ok)throw Error(await la(e));return await e.json()}async function fa(e){let t=await Q(`/api/billing/task-queue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok)throw Error(await la(t));return(await t.json()).snapshot}let pa=`@kenz1117/dsh-ui-usage-billing/TaskQueuePanel.module.css`;if(typeof document<`u`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(pa)+`]`)===null){let e=document.createElement(`style`);e.dataset.plugin=`@kenz1117/dsh-ui-usage-billing`,e.dataset.pluginCss=pa,e.textContent=`.cQSERa_queuePanel{color:var(--ds-t-1);flex-direction:column;flex-shrink:0;gap:12px;display:flex}.cQSERa_queuePanel *{box-sizing:border-box}.cQSERa_queueHero,.cQSERa_queueComposer,.cQSERa_queueListSection,.cQSERa_queueUnsupported{border:1px solid var(--ds-border);border-radius:var(--ds-r-2);background:var(--dsb-2);flex-shrink:0}.cQSERa_queueHero{justify-content:space-between;align-items:center;gap:16px;padding:16px;display:flex}.cQSERa_queueTitleRow{align-items:center;gap:8px;display:flex}.cQSERa_queueTitle,.cQSERa_queueListHead h3,.cQSERa_queueUnsupported h3{margin:0;font-size:15px;font-weight:650}.cQSERa_queuePreview{background:var(--ds-violet-soft);color:var(--ds-violet);text-transform:uppercase;border-radius:5px;padding:2px 6px;font-size:10px;font-weight:700}.cQSERa_queueSubtitle{color:var(--ds-t-2);margin:5px 0 0;font-size:12px;line-height:1.6}.cQSERa_queueBand{color:var(--ds-t-2);flex-direction:column;flex-shrink:0;align-items:flex-end;gap:3px;font-size:11px;display:flex}.cQSERa_queueBand strong{font-size:13px}.cQSERa_queueBandOff strong{color:var(--ds-green)}.cQSERa_queueBandPeak strong{color:var(--ds-amber)}.cQSERa_queueComposer{flex-direction:column;gap:12px;padding:14px;display:flex}.cQSERa_queueSafety{border-radius:var(--ds-r-1);background:color-mix(in srgb, var(--ds-amber) 8%, transparent);color:var(--ds-t-2);padding:9px 11px;font-size:11px;line-height:1.65}.cQSERa_queueSafetyMode{color:var(--ds-t-3);margin-top:4px;display:block}.cQSERa_queueSelectors{grid-template-columns:1fr 1fr;gap:10px;display:grid}.cQSERa_queueField,.cQSERa_queuePromptField{color:var(--ds-t-2);flex-direction:column;gap:6px;font-size:11px;display:flex}.cQSERa_queueField select,.cQSERa_queuePromptField textarea{border:1px solid var(--ds-border);border-radius:var(--ds-r-1);background:var(--dsb);width:100%;color:var(--ds-t-1);font:inherit}.cQSERa_queueField select{height:34px;padding:0 9px}.cQSERa_queuePromptField textarea{resize:vertical;min-height:112px;padding:10px;line-height:1.55}.cQSERa_queueField select:focus,.cQSERa_queuePromptField textarea:focus{outline:2px solid color-mix(in srgb, var(--ds-blue) 35%, transparent);border-color:var(--ds-blue)}.cQSERa_queueField select:disabled,.cQSERa_queuePromptField textarea:disabled{opacity:.55}.cQSERa_queueComposerFooter{color:var(--ds-t-3);justify-content:space-between;align-items:center;gap:12px;font-size:10px;line-height:1.5;display:flex}.cQSERa_queueComposerActions{flex-shrink:0;align-items:center;gap:8px;display:flex}.cQSERa_queueFileInput{display:none}.cQSERa_queuePrimary,.cQSERa_queueSecondary{border-radius:var(--ds-r-1);cursor:pointer;flex-shrink:0;min-height:34px;padding:0 16px;font-weight:600}.cQSERa_queuePrimary{background:var(--ds-blue);color:#fff;border:0}.cQSERa_queueSecondary{border:1px solid var(--ds-border);background:var(--dsb);color:var(--ds-t-1)}.cQSERa_queuePrimary:disabled,.cQSERa_queueSecondary:disabled{opacity:.45;cursor:not-allowed}.cQSERa_queueListSection{padding:12px 14px}.cQSERa_queueListHead{justify-content:space-between;align-items:center;margin-bottom:8px;display:flex}.cQSERa_queueListHead h3 span{color:var(--ds-t-3);margin-left:4px;font-size:11px;font-weight:500}.cQSERa_queueList{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.cQSERa_queueTask{border:1px solid var(--ds-border);border-radius:var(--ds-r-1);background:var(--dsb);padding:10px}.cQSERa_queueTaskHead{align-items:center;gap:8px;min-width:0;display:flex}.cQSERa_queueStatus{background:var(--dsb-3);color:var(--ds-t-2);border-radius:5px;flex-shrink:0;padding:2px 6px;font-size:10px;font-weight:650}.cQSERa_queueStatus_running,.cQSERa_queueStatus_starting{color:var(--ds-blue);background:color-mix(in srgb, var(--ds-blue) 12%, transparent)}.cQSERa_queueStatus_completed{color:var(--ds-green);background:color-mix(in srgb, var(--ds-green) 12%, transparent)}.cQSERa_queueStatus_failed{color:var(--ds-red);background:color-mix(in srgb, var(--ds-red) 10%, transparent)}.cQSERa_queueTaskMeta{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--ds-t-2);font-size:11px;overflow:hidden}.cQSERa_queueTaskTime{color:var(--ds-t-3);flex-shrink:0;margin-left:auto;font-size:10px}.cQSERa_queueTaskTarget{color:var(--ds-t-2);overflow-wrap:anywhere;flex-wrap:wrap;align-items:baseline;gap:6px;margin-top:6px;font-size:11px;line-height:1.5;display:flex}.cQSERa_queueTaskTargetNote{color:var(--ds-t-3);font-size:10px}.cQSERa_queuePrompt{color:var(--ds-t-1);margin-top:8px;font-size:12px;line-height:1.55}.cQSERa_queuePrompt summary{text-overflow:ellipsis;white-space:nowrap;cursor:pointer;overflow:hidden}.cQSERa_queuePrompt pre{background:var(--dsb-2);white-space:pre-wrap;overflow-wrap:anywhere;max-height:240px;font-family:var(--mono);border-radius:6px;margin:8px 0 0;padding:9px;font-size:11px;line-height:1.55;overflow:auto}.cQSERa_queueTaskError{color:var(--ds-red);overflow-wrap:anywhere;margin-top:8px;font-size:11px;line-height:1.5}.cQSERa_queueTaskActions{justify-content:flex-end;gap:10px;margin-top:5px;display:flex}.cQSERa_queueLinkButton{color:var(--ds-blue);cursor:pointer;background:0 0;border:0;padding:2px 0;font-size:11px}.cQSERa_queueLinkButton:disabled{opacity:.45;cursor:not-allowed}.cQSERa_queueEmpty{color:var(--ds-t-3);text-align:center;padding:26px 12px;font-size:12px}.cQSERa_queueUnsupported{padding:22px}.cQSERa_queueUnsupported p{color:var(--ds-t-2);margin:8px 0 0;font-size:12px;line-height:1.7}.cQSERa_queueNotice,.cQSERa_queueNoticeError{border-radius:var(--ds-r-1);overflow-wrap:anywhere;flex-shrink:0;padding:9px 11px;font-size:11px;line-height:1.5}.cQSERa_queueNotice{background:var(--dsb-2);color:var(--ds-t-2)}.cQSERa_queueNoticeError{background:color-mix(in srgb, var(--ds-red) 10%, transparent);color:var(--ds-red)}@media (width<=640px){.cQSERa_queueHero{align-items:flex-start}.cQSERa_queueSelectors{grid-template-columns:1fr}.cQSERa_queueComposerFooter{flex-direction:column;align-items:stretch}.cQSERa_queueComposerActions{flex-wrap:wrap;justify-content:flex-end}.cQSERa_queueTaskTime{display:none}}`,document.head.appendChild(e)}var $={queueBand:`cQSERa_queueBand`,queueBandOff:`cQSERa_queueBandOff`,queueBandPeak:`cQSERa_queueBandPeak`,queueComposer:`cQSERa_queueComposer`,queueComposerActions:`cQSERa_queueComposerActions`,queueComposerFooter:`cQSERa_queueComposerFooter`,queueEmpty:`cQSERa_queueEmpty`,queueField:`cQSERa_queueField`,queueFileInput:`cQSERa_queueFileInput`,queueHero:`cQSERa_queueHero`,queueLinkButton:`cQSERa_queueLinkButton`,queueList:`cQSERa_queueList`,queueListHead:`cQSERa_queueListHead`,queueListSection:`cQSERa_queueListSection`,queueNotice:`cQSERa_queueNotice`,queueNoticeError:`cQSERa_queueNoticeError`,queuePanel:`cQSERa_queuePanel`,queuePreview:`cQSERa_queuePreview`,queuePrimary:`cQSERa_queuePrimary`,queuePrompt:`cQSERa_queuePrompt`,queuePromptField:`cQSERa_queuePromptField`,queueSafety:`cQSERa_queueSafety`,queueSafetyMode:`cQSERa_queueSafetyMode`,queueSecondary:`cQSERa_queueSecondary`,queueSelectors:`cQSERa_queueSelectors`,queueStatus:`cQSERa_queueStatus`,queueStatus_completed:`cQSERa_queueStatus_completed`,queueStatus_failed:`cQSERa_queueStatus_failed`,queueStatus_running:`cQSERa_queueStatus_running`,queueStatus_starting:`cQSERa_queueStatus_starting`,queueSubtitle:`cQSERa_queueSubtitle`,queueTask:`cQSERa_queueTask`,queueTaskActions:`cQSERa_queueTaskActions`,queueTaskError:`cQSERa_queueTaskError`,queueTaskHead:`cQSERa_queueTaskHead`,queueTaskMeta:`cQSERa_queueTaskMeta`,queueTaskTarget:`cQSERa_queueTaskTarget`,queueTaskTargetNote:`cQSERa_queueTaskTargetNote`,queueTaskTime:`cQSERa_queueTaskTime`,queueTitle:`cQSERa_queueTitle`,queueTitleRow:`cQSERa_queueTitleRow`,queueUnsupported:`cQSERa_queueUnsupported`};let ma={queued:`queueStatusQueued`,starting:`queueStatusStarting`,running:`queueStatusRunning`,completed:`queueStatusCompleted`,failed:`queueStatusFailed`};function ha(e){return e.status===`completed`||e.status===`failed`}function ga(e,t){return JSON.stringify([e,t])}function _a(e){let t=e.startsWith(`session-`)?e.slice(8):e;return t.length<=8?t:t.slice(0,8)}function va(e,t){let n;try{n=JSON.parse(e)}catch{throw Error(`invalid task import`)}if(!Array.isArray(n)||n.length===0)throw Error(`invalid task import`);return n.map(e=>{if(typeof e==`string`)return{prompt:e,...t};if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`invalid task import`);let n=e;return{prompt:n.prompt,cwd:n.cwd??t.cwd,provider:n.provider??t.provider,model:n.model??t.model}})}function ya({t:e,language:t,navigateToSession:n,sessionTitleOf:r,reuseSourceSession:i}){let[a,o]=(0,d.useState)(),[s,c]=(0,d.useState)(``),[l,u]=(0,d.useState)(``),[f,p]=(0,d.useState)(``),[h,g]=(0,d.useState)(!1),[_,v]=(0,d.useState)(),[b,x]=(0,d.useState)(),S=(0,d.useRef)(!0),C=(0,d.useRef)(!1),w=(0,d.useRef)(!1),T=(0,d.useRef)(null),E=(0,d.useCallback)(async()=>{if(!C.current){C.current=!0;try{let e=await ua();S.current&&o(e)}catch(e){S.current&&v(e instanceof Error?e.message:String(e))}finally{C.current=!1}}},[]),[ee,te]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{te(!document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[]),(0,d.useEffect)(()=>{if(S.current=!0,!ee)return;E();let e=setInterval(()=>{E()},5e3);return()=>{S.current=!1,clearInterval(e)}},[E,ee]),(0,d.useEffect)(()=>{if(_===void 0)return;let e=window.setTimeout(()=>{v(void 0)},8e3);return()=>{window.clearTimeout(e)}},[_]),(0,d.useEffect)(()=>{if(b===void 0)return;let e=window.setTimeout(()=>{x(void 0)},4e3);return()=>{window.clearTimeout(e)}},[b]),(0,d.useEffect)(()=>{a!==void 0&&(a.workspaces.some(e=>e.path===l)||u(a.workspaces[0]?.path??``),a.models.some(e=>ga(e.provider,e.id)===f)||p(a.models[0]===void 0?``:ga(a.models[0].provider,a.models[0].id)))},[a,l,f]);let D=(0,d.useCallback)(async(e,t=!1)=>{if(h||w.current)return!1;w.current=!0,g(!0),v(void 0),x(void 0);try{let n=await fa(e);return S.current?(o(n),t&&c(``),!0):!1}catch(e){return S.current&&v(e instanceof Error?e.message:String(e)),!1}finally{w.current=!1,g(!1)}},[h]),O=(0,d.useMemo)(()=>a?.tasks.filter(e=>!ha(e))??[],[a]),ne=(0,d.useMemo)(()=>a?.tasks.filter(ha).slice().reverse()??[],[a]),k=a!==void 0&&a.supported&&a.workspaces.length>0&&a.models.length>0,A=e=>new Date(e).toLocaleString(t===`en`?`en-US`:`zh-CN`),j=()=>{if(s.trim()===``||l===``||f===``)return;let[e,t]=JSON.parse(f);D({action:`enqueue`,prompt:s,cwd:l,provider:e,model:t},!0)},re=async t=>{if(!(t===void 0||!k||h||f===``)){v(void 0),x(void 0);try{if(t.size>10485760){v(e(`queueImportTooLarge`));return}let[n,r]=JSON.parse(f),i=va(await t.text(),{cwd:l,provider:n,model:r});await D({action:`enqueueMany`,tasks:i})&&S.current&&x(e(`queueImported`,{count:i.length}))}catch{S.current&&v(e(`queueImportFormat`))}}},ie=t=>{let r=n(t);x(r===`opened`?void 0:e(r===`unavailable`?`sessionOpenUnavailable`:`sessionOpenFailed`))},ae=t=>{let n=a?.workspaces.find(e=>e.path===t.cwd),i=t.reuseSource===!0?t.sourceSessionId:void 0,o=t.sourceSessionId!==void 0&&t.sessionId===t.sourceSessionId,s=e=>r?.(e)??_a(e),c=t.fallbackReason===void 0?o?e(`queueReuseDone`,{session:s(t.sessionId)}):i===void 0?void 0:e(`queueReusePlanned`,{session:s(i)}):e(`queueFallbackReason`,{reason:t.fallbackReason}),l=t.fallbackReason===void 0?t.sessionId??i:t.sessionId;return(0,m.jsxs)(`li`,{className:$.queueTask,"data-testid":`queue-task-${t.id}`,children:[(0,m.jsxs)(`div`,{className:$.queueTaskHead,children:[(0,m.jsx)(`span`,{className:y($.queueStatus,$[`queueStatus_${t.status}`]),children:e(ma[t.status])}),(0,m.jsxs)(`span`,{className:$.queueTaskMeta,children:[n?.title??t.cwd,` · `,t.model]}),(0,m.jsx)(`time`,{className:$.queueTaskTime,dateTime:new Date(t.createdAt).toISOString(),children:A(t.createdAt)})]}),c!==void 0&&(0,m.jsxs)(`div`,{className:$.queueTaskTarget,"data-testid":`queue-task-target-${t.id}`,children:[(0,m.jsx)(`span`,{children:c}),o&&(0,m.jsx)(`span`,{className:$.queueTaskTargetNote,children:e(`queueReuseModelNote`)})]}),(0,m.jsxs)(`details`,{className:$.queuePrompt,children:[(0,m.jsx)(`summary`,{children:t.prompt.trim().slice(0,180)||t.prompt.slice(0,180)}),(0,m.jsx)(`pre`,{children:t.prompt})]}),t.error!==void 0&&(0,m.jsx)(`div`,{className:$.queueTaskError,role:`note`,children:t.error}),(0,m.jsxs)(`div`,{className:$.queueTaskActions,children:[l!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:$.queueLinkButton,onClick:()=>{ie(l)},children:e(`queueOpenSession`)}),(t.status===`queued`||ha(t))&&(0,m.jsx)(`button`,{type:`button`,className:$.queueLinkButton,disabled:h,onClick:()=>{D({action:`remove`,id:t.id})},children:e(t.status===`queued`?`queueRemoveQueued`:`queueRemoveHistory`)})]})]},t.id)};return(0,m.jsxs)(`div`,{className:$.queuePanel,"data-testid":`billing-tab-panel-queue`,children:[(0,m.jsxs)(`section`,{className:$.queueHero,children:[(0,m.jsxs)(`div`,{children:[(0,m.jsxs)(`div`,{className:$.queueTitleRow,children:[(0,m.jsx)(`h2`,{className:$.queueTitle,children:e(`tabQueue`)}),(0,m.jsx)(`span`,{className:$.queuePreview,children:`Preview`})]}),(0,m.jsx)(`p`,{className:$.queueSubtitle,children:e(`queueSubtitle`)})]}),a?.supported&&(0,m.jsxs)(`div`,{className:y($.queueBand,a.tier===`offPeak`?$.queueBandOff:$.queueBandPeak),children:[(0,m.jsx)(`strong`,{children:e(a.tier===`offPeak`?`offPeak`:`peak`)}),(0,m.jsxs)(`span`,{children:[e(a.tier===`offPeak`?`queueUntilPeak`:`queueUntilOffPeak`),` `,Ht(a.nextSwitchInMs)]})]})]}),_!==void 0&&(0,m.jsx)(`div`,{className:$.queueNoticeError,role:`alert`,children:_}),b!==void 0&&(0,m.jsx)(`div`,{className:$.queueNotice,role:`status`,children:b}),a===void 0?(0,m.jsx)(`div`,{className:$.queueEmpty,children:e(`queueLoading`)}):a.supported?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`section`,{className:$.queueComposer,children:[(0,m.jsxs)(`div`,{className:$.queueSafety,children:[e(`queueSafety`),(0,m.jsx)(`span`,{className:$.queueSafetyMode,children:e(i===!0?`queueSafetyReuse`:`queueSafetyIsolated`)})]}),(0,m.jsxs)(`div`,{className:$.queueSelectors,children:[(0,m.jsxs)(`label`,{className:$.queueField,children:[(0,m.jsx)(`span`,{children:e(`queueWorkspace`)}),(0,m.jsx)(`select`,{value:l,disabled:!k||h,onChange:e=>{u(e.target.value)},children:a.workspaces.map(e=>(0,m.jsx)(`option`,{value:e.path,children:e.title},e.path))})]}),(0,m.jsxs)(`label`,{className:$.queueField,children:[(0,m.jsx)(`span`,{children:e(`queueModel`)}),(0,m.jsx)(`select`,{value:f,disabled:!k||h,onChange:e=>{p(e.target.value)},children:a.models.map(e=>(0,m.jsxs)(`option`,{value:ga(e.provider,e.id),children:[e.providerName,` / `,e.name]},ga(e.provider,e.id)))})]})]}),!k&&(0,m.jsx)(`div`,{className:$.queueNotice,children:a.optionsError??e(`queueNoOptions`)}),(0,m.jsxs)(`label`,{className:$.queuePromptField,children:[(0,m.jsx)(`span`,{children:e(`queuePromptLabel`)}),(0,m.jsx)(`textarea`,{value:s,disabled:!k||h,maxLength:32e3,rows:5,placeholder:e(`queuePromptPlaceholder`),onChange:e=>{c(e.target.value)}})]}),(0,m.jsxs)(`div`,{className:$.queueComposerFooter,children:[(0,m.jsx)(`span`,{children:e(`queuePrivacy`)}),(0,m.jsxs)(`div`,{className:$.queueComposerActions,children:[(0,m.jsx)(`input`,{ref:T,className:$.queueFileInput,"data-testid":`queue-import-file`,type:`file`,accept:`application/json,.json`,disabled:!k||h,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,re(t)}}),(0,m.jsx)(`button`,{type:`button`,className:$.queueSecondary,title:e(`queueImportHint`),disabled:!k||h,onClick:()=>{T.current?.click()},children:e(`queueImport`)}),(0,m.jsx)(`button`,{type:`button`,className:$.queuePrimary,disabled:!k||h||s.trim()===``,onClick:j,children:e(`queueEnqueue`)})]})]})]}),(0,m.jsxs)(`section`,{className:$.queueListSection,children:[(0,m.jsxs)(`div`,{className:$.queueListHead,children:[(0,m.jsxs)(`h3`,{children:[e(`queueActive`),` `,(0,m.jsx)(`span`,{children:O.length})]}),ne.length>0&&(0,m.jsx)(`button`,{type:`button`,className:$.queueLinkButton,disabled:h,onClick:()=>{D({action:`clearFinished`})},children:e(`queueClearFinished`)})]}),O.length===0&&ne.length===0?(0,m.jsx)(`div`,{className:$.queueEmpty,children:e(`queueEmpty`)}):(0,m.jsxs)(`ul`,{className:$.queueList,children:[O.map(ae),ne.map(ae)]})]})]}):(0,m.jsxs)(`section`,{className:$.queueUnsupported,"data-testid":`queue-unsupported`,children:[(0,m.jsx)(`h3`,{children:e(`queueUnsupportedTitle`)}),(0,m.jsx)(`p`,{children:e(`queueUnsupportedBody`)})]})]})}function ba({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:L.subscriptionWindow,children:[(0,m.jsx)(`span`,{className:L.subscriptionWindowLabel,children:Ki(e.kind,t)}),(0,m.jsx)(`span`,{className:L.subscriptionTrack,"aria-hidden":`true`,children:(0,m.jsx)(`span`,{className:y(L.subscriptionFill,n>=100&&L.subscriptionFillOver,n>=80&&n<100&&L.subscriptionFillWarn),style:{width:`${n}%`}})}),(0,m.jsxs)(`span`,{className:L.subscriptionMeta,children:[(0,m.jsx)(`span`,{className:y(L.subscriptionPct,r&&L.subscriptionExhausted),children:r?t(`subscriptionExhausted`):t(`subscriptionRemaining`).replace(`{pct}`,String(e.remainingPercent))}),e.resetsAt!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionReset,children:t(`subscriptionReset`).replace(`{date}`,`${G(new Date(e.resetsAt).getTime())} ${Zi(new Date(e.resetsAt).getTime())}`)})]})]})}function xa({label:e,t}){return(0,m.jsx)(p.Tooltip,{label:e,side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.helpTip,role:`note`,"aria-label":e,children:`?`})})}function Sa(e,t){return e===L.healthOk?t(`healthDotLive`):e===L.healthBad?t(`healthDotFailed`):t(`healthDotUnknown`)}function Ca(e){let t=t=>W(gn(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,deltaPct:S=0,statsError:C}=e,w=(0,d.useMemo)(()=>p.targets.map(e=>h.find(t=>t.provider===e)).filter(e=>e!==void 0),[p.targets,h]),[T,E]=(0,d.useState)(0),ee=w.length===0?0:Math.min(T,w.length-1),te=w[ee],D=(0,d.useRef)(null),[O,ne]=(0,d.useState)(null),k=(0,d.useCallback)(e=>{D.current=e,ne(e)},[]),[A,j]=(0,d.useState)(!1),[re,ie]=(0,d.useState)({left:0,top:0}),[ae,oe]=(0,d.useState)(`card`);(0,d.useLayoutEffect)(()=>{if(O===null)return;let e=kr(O,oe);return()=>e.dispose()},[O]),(0,d.useEffect)(()=>{if(!A||p.mode!==`subscription`||w.length<2)return;let e=setInterval(()=>E(e=>(e+1)%w.length),1500);return()=>clearInterval(e)},[A,p.mode,w.length]);let se=(0,d.useRef)(void 0),ce=(0,d.useCallback)(()=>{window.clearTimeout(se.current),j(!0)},[]),le=(0,d.useCallback)(()=>{window.clearTimeout(se.current),se.current=window.setTimeout(()=>j(!1),120)},[]);(0,d.useEffect)(()=>()=>window.clearTimeout(se.current),[]);let ue=(0,d.useCallback)(()=>{let e=D.current?.getBoundingClientRect();e!==void 0&&ie({left:e.left,top:e.top-8})},[]);(0,d.useEffect)(()=>{if(!A)return;let e=()=>ue();return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,{capture:!0}),window.removeEventListener(`resize`,e)}},[A,ue]);let de=c.length>0?c.reduce((e,t)=>e+t.cost,0)/c.length:0,fe=de>0?Math.max(0,Math.min(1,o/de)):0,pe=-80+fe*160,me=(0,m.jsxs)(`svg`,{viewBox:`3.5 10 34 22`,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*fe).toFixed(2)} 41.9`,className:L.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:L.triggerGaugeNeedle,style:{transform:`rotate(${pe}deg)`,transformOrigin:`20px 29px`}}),(0,m.jsx)(`circle`,{cx:`20`,cy:`29`,r:`1.5`,fill:`currentColor`,stroke:`none`})]}),he=`${r(`title`)} · ${t(g.span===`day`?o:g.span===`week`?s:a)}${C===void 0?``:` · ${r(`statsLoadFailed`)}`}`;if(g.mode===`hidden`)return null;if(!n||g.mode===`compact`)return(0,m.jsx)(`button`,{type:`button`,className:y(L.railButton,zr,x!==`none`&&L.triggerBudgetPulse,x===`over`&&L.triggerBudgetOver),"data-testid":`billing-rail-button`,onClick:i,title:he,children:me});let M=g.metric===`tokens`,ge=c.map(e=>M?e.tokens:e.cost),_e=Math.max(...ge,0),ve=ge.map(e=>_e>0?4+e/_e*12:4),ye=ae===`icon`;return(0,m.jsxs)(`span`,{ref:k,className:y(L.triggerWrap,ye&&L.triggerWrapShared,zr),onMouseEnter:()=>{ue(),ce()},onMouseLeave:le,onFocusCapture:()=>{ue(),ce()},onBlurCapture:()=>j(!1),children:[ye?(0,m.jsx)(`button`,{type:`button`,className:y(L.triggerShared,x!==`none`&&L.triggerBudgetPulse,x===`over`&&L.triggerBudgetOver),"data-testid":`billing-trigger-shared`,"aria-label":he,onClick:i,title:he,children:(0,m.jsx)(`span`,{className:y(L.triggerIcon,x!==`none`&&L.triggerBudgetHot,C!==void 0&&L.triggerStatsError),"data-testid":`billing-trigger-icon`,children:me})}):(0,m.jsxs)(`button`,{type:`button`,className:y(L.trigger,x!==`none`&&L.triggerBudgetPulse,x===`over`&&L.triggerBudgetOver),"data-testid":`billing-trigger`,onClick:i,title:he,children:[(0,m.jsx)(`span`,{className:y(L.triggerIcon,x!==`none`&&L.triggerBudgetHot,C!==void 0&&L.triggerStatsError),"data-testid":`billing-trigger-icon`,children:me}),(0,m.jsx)(`span`,{className:L.triggerMain,children:(0,m.jsxs)(`span`,{className:L.triggerPrimary,children:[(0,m.jsx)(`span`,{className:L.triggerLabel,children:M?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`?M?v:o:g.span===`week`?M?b:s:M?_:a,n=g.span===`day`?S:0;return M?(0,m.jsx)(`span`,{className:L.triggerMetric,"data-testid":`billing-trigger-span-tokens`,children:K(e)}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`span`,{className:L.triggerValueRow,children:[(0,m.jsx)(`span`,{className:L.triggerYen,"aria-hidden":`true`,children:t(e).charAt(0)}),(0,m.jsx)(`span`,{className:L.triggerMetric,"data-testid":`billing-trigger-span-money`,children:t(e).slice(1)})]}),g.showDelta&&n!==0&&(0,m.jsxs)(`span`,{className:y(L.triggerDelta,n>0?L.triggerDeltaUp:L.triggerDeltaDown),"data-testid":`billing-trigger-delta`,children:[n>0?`▲`:`▼`,` `,Math.abs(n).toFixed(1),`%`]}),(0,m.jsx)(`span`,{className:L.triggerGlow,"aria-hidden":`true`})]})})()]})}),(0,m.jsx)(`span`,{className:L.triggerSpark,"data-testid":`billing-trigger-spark`,"aria-hidden":`true`,children:ve.map((e,t)=>(0,m.jsx)(`span`,{className:t===ve.length-1?L.triggerSparkHot:L.triggerSparkBar,style:{height:`${e}px`}},c[t]?.date??String(t)))})]}),(0,f.createPortal)((0,m.jsx)(`span`,{className:y(L.triggerPop,zr,A&&L.triggerPopShown),style:{left:`${re.left}px`,top:`${re.top}px`},"data-testid":`billing-trigger-pop`,"aria-hidden":!A,onMouseEnter:ce,onMouseLeave:le,children:p.mode===`subscription`?(0,m.jsx)(m.Fragment,{children:w.length===0?(0,m.jsx)(`span`,{className:L.triggerPopEmpty,children:r(`floatNoTargets`)}):(0,m.jsxs)(m.Fragment,{children:[te!==void 0&&(0,m.jsxs)(`div`,{className:L.floatSub,"data-testid":`billing-float-subscription`,children:[(0,m.jsxs)(`div`,{className:L.floatSubHead,children:[(0,m.jsx)(`span`,{className:L.floatSubName,children:te.displayName}),te.plan!==void 0&&(0,m.jsx)(`span`,{className:L.floatSubPlan,children:te.plan})]}),te.windows.map(e=>(0,m.jsx)(ba,{window:e,t:r},e.kind))]}),w.length>1&&(0,m.jsx)(`span`,{className:L.triggerPopSwitcher,"data-testid":`billing-float-switcher`,children:(0,m.jsxs)(`span`,{className:L.triggerPopSwitchCount,children:[ee+1,`/`,w.length]})})]})}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:L.popHead,children:(0,m.jsx)(`span`,{className:L.popTitle,children:r(`popTitle`)})}),C!==void 0&&(0,m.jsxs)(`span`,{className:L.popError,"data-testid":`billing-stats-error`,role:`note`,children:[(0,m.jsx)(`span`,{className:L.popErrorTitle,children:r(`statsLoadFailed`)}),(0,m.jsx)(`span`,{className:L.popErrorDetail,children:C})]}),(0,m.jsxs)(`span`,{className:L.metricGrid,children:[(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`floatPrimaryToday`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:t(o)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`floatPrimaryWeek`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:t(s)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`floatPrimaryMonth`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:t(a)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`input`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:K(u.input)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`output`)}),(0,m.jsx)(`span`,{className:L.metricValue,children:K(u.output)})]}),(0,m.jsxs)(`span`,{className:L.metricCell,children:[(0,m.jsx)(`span`,{className:L.metricLabel,children:r(`cacheHit`)}),(0,m.jsx)(`span`,{className:y(L.metricValue,L.metricValueSuccess),children:yn(u.cacheRead+u.cacheMiss>0?u.cacheRead/(u.cacheRead+u.cacheMiss)*100:0)})]})]}),(0,m.jsxs)(`span`,{className:L.popModel,children:[(0,m.jsx)(`span`,{className:L.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:L.popModelRow,children:[(0,m.jsx)(`span`,{className:y(L.popDot,L.popDotDirect),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:L.popTagPrimary,children:r(`popDirectLead`)}),(0,m.jsx)(`span`,{className:L.popModelName,children:l.direct.name}),(0,m.jsx)(`span`,{className:y(L.popModelStatus,l.direct.low&&L.popModelStatusLow),children:l.direct.text})]}),l.sub!==void 0&&(0,m.jsxs)(`span`,{className:L.popModelRow,children:[(0,m.jsx)(`span`,{className:y(L.popDot,L.popDotSub),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:L.popTagSub,children:r(`popSubLead`)}),(0,m.jsx)(`span`,{className:L.popModelName,children:l.sub.name}),(0,m.jsx)(`span`,{className:y(L.popModelStatus,l.sub.low&&L.popModelStatusLow),children:l.sub.text})]})]}):(0,m.jsxs)(`span`,{className:L.popModelRow,children:[(0,m.jsx)(`span`,{className:y(L.popDot,L.popDotNeutral),"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:L.popModelStatus,children:r(`popNoConsumption`)})]})]})]})}),document.body)]})}function wa({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:L.balanceDetailPop,"data-testid":`billing-balance-detail-pop`,onClick:e=>{e.stopPropagation()},children:[(0,m.jsxs)(`span`,{className:L.balanceDetailHead,children:[(0,m.jsx)(`span`,{className:L.balanceDetailTitle,children:e.displayName}),(0,m.jsx)(`button`,{type:`button`,className:L.balanceDetailClose,"aria-label":i(`close`),onClick:a,children:`×`})]}),(0,m.jsxs)(`span`,{className:L.balanceDetailGrid,children:[s!==void 0&&(0,m.jsx)(Ta,{label:i(`balance`),value:s}),c!==void 0&&(0,m.jsx)(Ta,{label:i(`balanceGranted`),value:c}),l!==void 0&&(0,m.jsx)(Ta,{label:i(`balanceTopped`),value:l}),(0,m.jsx)(Ta,{label:i(`balanceDaily`),value:r(n)}),(0,m.jsx)(Ta,{label:i(`balanceDaysLong`),value:`${t} ${i(`balanceDaysUnit`)}`})]})]})}function Ta({label:e,value:t}){return(0,m.jsxs)(`span`,{className:L.balanceDetailRow,children:[(0,m.jsx)(`span`,{className:L.balanceDetailLabel,children:e}),(0,m.jsx)(`span`,{className:L.balanceDetailValue,children:t})]})}function Ea({userPrices:e,onUserPrices:t,t:n,unpricedIds:r}){let[i,a]=(0,d.useState)(()=>[...e]),[o,s]=(0,d.useState)(new Set),c=e=>s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),l=()=>{a(e=>e.filter((e,t)=>!o.has(t))),s(new Set)},u=(e,t)=>a(n=>n.map((n,r)=>r===e?{...n,...t}:n)),f=()=>a(e=>[...e,{key:``,input:0,cacheHit:0,output:0}]),p=e=>{let t=i[e]?.offPeak;return{input:t===void 0?``:String(t.input),cacheHit:t===void 0?``:String(t.cacheHit),output:t===void 0?``:String(t.output)}},h=(e,t,n)=>a(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})),g=()=>t(i.filter(e=>e.key.trim()!==``).map(e=>({...e,key:e.key.trim(),...e.origin===void 0||e.origin.trim()===``?{}:{origin:ht(e.origin.trim())}}))),_=(0,d.useMemo)(()=>{let e=[];for(let t of fn())e.push(t.key);for(let t of r??[])e.includes(t)||e.push(t);return e},[r]),v=(e,t)=>a(n=>n.map((n,r)=>{if(r!==e)return n;let{currency:i,...a}=n;return t===`USD`?{...a,currency:`USD`}:a})),[b,x]=(0,d.useState)({}),S=(e,t,n)=>`${e}:${t}:${n}`,C=(e,t,n)=>x(r=>{let i=S(e,t,n);if(r[i]===void 0)return r;let a={...r};return delete a[i],a}),w=e=>Number.isFinite(e)&&e!==0?String(e):``,T=(e,t,n)=>{if(x(r=>({...r,[S(e,`main`,t)]:n})),n===``){u(e,{[t]:0});return}let r=Number(n);Number.isFinite(r)&&r>=0&&u(e,{[t]:r})};return(0,m.jsxs)(`section`,{className:L.setCard,"data-testid":`billing-user-prices`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`userPrices`),(0,m.jsx)(xa,{label:n(`userPricesHint`),t:n})]})})}),(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsx)(`datalist`,{id:`billing-price-model-keys`,children:_.map(e=>(0,m.jsx)(`option`,{value:e},e))}),i.map((e,t)=>(0,m.jsxs)(`div`,{className:L.userPriceRow,"data-testid":`billing-user-price-row`,children:[(0,m.jsx)(`input`,{type:`checkbox`,className:L.userPriceCheck,"data-testid":`billing-user-price-select`,checked:o.has(t),"aria-label":n(`userPriceSelect`),onChange:()=>c(t)}),(0,m.jsxs)(`div`,{className:L.userPriceBody,children:[(0,m.jsxs)(`div`,{className:L.userPriceLineMeta,children:[(0,m.jsxs)(`div`,{className:L.userPriceField,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`userPriceModel`)}),(0,m.jsx)(`input`,{className:L.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=>u(t,{key:e.target.value})})]}),(0,m.jsxs)(`div`,{className:L.userPriceField,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`userPriceSource`)}),(0,m.jsx)(`input`,{className:L.userPriceInput,"data-testid":`billing-user-price-origin`,type:`text`,value:e.origin??``,placeholder:n(`userPriceSourceHint`),"aria-label":n(`userPriceSource`),onChange:e=>u(t,{origin:e.target.value.trim()})})]}),(0,m.jsxs)(`div`,{className:L.userPriceField,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`userPriceCurrency`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,e.currency!==`USD`&&L.floatModeBtnOn),onClick:()=>v(t,`CNY`),children:`CNY`}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,e.currency===`USD`&&L.floatModeBtnOn),onClick:()=>v(t,`USD`),children:`USD`})]})]})]}),[{scope:`main`,label:n(`userPriceNormal`),testid:`billing-user-price-normal`,valueOf:n=>b[S(t,`main`,n)]??w(e[n]),onChange:(e,n)=>T(t,e,n)},{scope:`off`,label:n(`userPriceOffPeak`),testid:`billing-user-price-offpeak`,valueOf:e=>b[S(t,`off`,e)]??p(t)[e],onChange:(e,n)=>{x(r=>({...r,[S(t,`off`,e)]:n})),h(t,e,n)}}].map(e=>(0,m.jsxs)(`div`,{className:L.userPricePriceLine,"data-testid":e.testid,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:e.label}),[`input`,`cacheHit`,`output`].map(r=>{let i=n(r===`input`?`tokenMiss`:r===`cacheHit`?`tokenHit`:`tokenOutput`);return(0,m.jsx)(`input`,{className:L.userPriceInputNum,type:`number`,min:0,step:.01,placeholder:i,"aria-label":`${e.label} ${i}`,value:e.valueOf(r),onChange:t=>e.onChange(r,t.target.value),onBlur:()=>C(t,e.scope,r)},r)})]},e.testid))]})]},t)),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-user-price-add`,onClick:f,children:n(`userPriceAdd`)}),(0,m.jsxs)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-user-price-remove-selected`,disabled:o.size===0,onClick:l,children:[n(`userPriceRemoveSelected`),o.size>0?` (${o.size})`:``]}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-user-price-save`,onClick:g,children:n(`userPriceSave`)})]})]})]})}function Da(e,t,n){if(e.length===0)return``;let r=e.slice(0,3).join(n===`zh`?`、`:`, `),i=e.length-3;return i>0?`${r} ${t(`unpricedMore`,{count:i})}`:r}function Oa({prefs:e,onPrefs:t,groups:n,t:r,money:i}){let a=new Set(e.hidden),o=(e,n)=>{let r=new Set(a);for(let t of e.siteKeys)n?r.add(t):r.delete(t);t({hidden:[...r]})},s=n.filter(e=>e.siteKeys.some(e=>a.has(e))).length;return(0,m.jsxs)(`div`,{className:y(L.setCell,L.channelVisCell),"data-testid":`billing-channel-visibility-setting`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[r(`channelVisibility`),(0,m.jsx)(xa,{label:r(`channelVisibilityHint`),t:r})]})}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-channel-visibility-reset`,disabled:e.hidden.length===0,onClick:()=>{t({hidden:[]})},children:r(`channelVisibilityShowAll`)})]}),n.length===0?(0,m.jsx)(`div`,{className:L.setHint,children:r(`channelVisibilityEmpty`)}):(0,m.jsx)(`div`,{className:L.channelVisList,children:n.map(e=>{let t=e.siteKeys.some(e=>a.has(e));return(0,m.jsxs)(`div`,{className:L.channelVisRow,"data-testid":`billing-channel-row-${e.name}`,children:[(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":!t,"aria-label":e.name,"data-testid":`billing-channel-toggle-${e.name}`,className:y(L.switch,!t&&L.switchOn),onClick:()=>{o(e,!t)},children:(0,m.jsx)(`span`,{className:L.switchKnob})}),(0,m.jsx)(`span`,{className:L.channelVisName,title:e.name,children:e.name}),(0,m.jsxs)(`span`,{className:L.channelVisUsage,children:[i(e.cost),` · `,K(e.tokens)]})]},e.name)})}),s>0&&(0,m.jsx)(`div`,{className:L.setHint,"data-testid":`billing-channel-visibility-hint`,children:r(`channelVisibilityHidden`).replace(`{count}`,String(s))})]})}function ka({stats:e,statsError:t,t:n,onClose:r,embeddedSettings:i=!1,userPrices:a,onUserPrices:o,health:s,balances:c,reconcile:l,quotas:u,relayQuotas:f,currency:h,onCurrency:g,language:_,onLanguage:v,turns:b,renderSlot:x,budgetEnabled:S,budgetAmount:C,onToggleBudget:w,onBudgetAmount:T,modelBudgets:E,monthModelCost:ee,onModelBudget:te,peakConfig:D,onPeakConfig:O,onPreviewPeak:ne,floatPrefs:k,onFloatPrefs:A,cardPrefs:j,onCardPrefs:re,recoveryEntryAvailable:ie,sitePrefs:ae,onSitePrefs:ce,channelPrefs:le,onChannelPrefs:fe,channelGroups:pe,liveCostPrefs:me,onLiveCostPrefs:he,quickQueuePrefs:M,onQuickQueuePrefs:ge,quotasStale:_e,balanceStale:ve,navigateToSession:ye,sessionTitleOf:be}){let xe=(0,d.useRef)(null),Se=(0,d.useMemo)(()=>zi(e.bySession??[]),[e.bySession]),Ce=(0,d.useMemo)(()=>Vi(Se),[Se]),[we,Te]=(0,d.useState)(void 0),Ee=(0,d.useCallback)(e=>{let t=ye(e);if(t===`opened`){Te(void 0);return}Te(n(t===`unavailable`?`sessionOpenUnavailable`:`sessionOpenFailed`))},[ye,n]),[De,Oe]=(0,d.useState)(`cost`),{total:ke,byModel:je,byDay:N}=e,[P,Ie]=(0,d.useState)(i?`settings`:`overview`),[Le,Re]=(0,d.useState)(7),[Be,Ve]=(0,d.useState)(()=>{try{return window.localStorage.getItem(`dsh-billing:reconcile-dismissed`)??``}catch{return``}}),He=()=>{let e=new Date,t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`},Ue=(0,d.useCallback)(()=>{let e=He();Ve(e);try{window.localStorage.setItem(`dsh-billing:reconcile-dismissed`,e)}catch{}},[]),[We,Ge]=(0,d.useState)(()=>{let e=[`unpriced`,`search-estimate`,`unreadable`],t=new Set,n=new Date,r=e=>String(e).padStart(2,`0`),i=`${n.getFullYear()}-${r(n.getMonth()+1)}-${r(n.getDate())}`;try{for(let n of e)window.localStorage.getItem(`dsh-billing:notice-${n}-dismissed`)===i&&t.add(n)}catch{}return t}),Ke=(0,d.useCallback)(e=>{let t=He();Ge(t=>new Set(t).add(e));try{window.localStorage.setItem(`dsh-billing:notice-${e}-dismissed`,t)}catch{}},[]),[qe,Ye]=(0,d.useState)(`month`),[$e,et]=(0,d.useState)(`cost`),[tt,nt]=(0,d.useState)(Je),[rt,it]=(0,d.useState)(Ze),[at,ot]=(0,d.useState)(`budget`),[st,R]=(0,d.useState)(``),z=e=>Ui(st,e);(0,d.useEffect)(()=>{let e=xe.current;if(P!==`settings`||e===null||typeof IntersectionObserver>`u`)return;let t=Array.from(e.querySelectorAll(`[id^="settings-"]`)).filter(e=>!e.closest(`[hidden]`));if(t.length===0)return;let n=new IntersectionObserver(e=>{let t,n=1/0;for(let r of e){if(!r.isIntersecting)continue;let e=r.boundingClientRect.top;e<n&&(n=e,t=r.target.id)}t!==void 0&&ot(t.slice(9))},{rootMargin:`-80px 0px -55% 0px`});for(let e of t)n.observe(e);return()=>{n.disconnect()}},[P]);let ct=(0,d.useCallback)(e=>{ot(e);let t=xe.current?.querySelector(`[id="settings-${e}"]`);if(t==null)return;if(i){t.scrollIntoView({block:`start`,behavior:`smooth`});return}let n=t.closest(`.${L.dashboardBody}`);if(n===null)return;let r=t.getBoundingClientRect().top-n.getBoundingClientRect().top;n.scrollTo({top:n.scrollTop+r,behavior:`smooth`})},[i]),ut=(0,d.useCallback)(e=>{nt(e),I(e)},[]),dt=(0,d.useCallback)(e=>{it(e),Qe(e)},[]);(0,d.useEffect)(()=>{typeof document>`u`||(document.documentElement.dataset.dshBillingDensity=tt,document.documentElement.dataset.dshBillingMotion=rt)},[tt,rt]),(0,d.useEffect)(()=>{if(typeof window>`u`)return;let e=e=>{let t=e.detail;t?.density!==void 0&&nt(t.density)},t=e=>{let t=e.detail;t?.motion!==void 0&&it(t.motion)};return window.addEventListener(F,e),window.addEventListener(Xe,t),()=>{window.removeEventListener(F,e),window.removeEventListener(Xe,t)}},[]);let[B,ft]=(0,d.useState)(oe),[V,pt]=(0,d.useState)(ue),mt=e=>{let t={...V,...e};t.start!==``&&t.end!==``&&(t.start>t.end&&(e.start===void 0?t.start=t.end:t.end=t.start),pt(t),de(t))},ht=(0,d.useMemo)(()=>u.filter(e=>e.status===`ok`&&e.windows.length>0).map(e=>({id:e.provider,label:e.displayName})),[u]),[gt,_t]=(0,d.useState)(),[vt,yt]=(0,d.useState)(new Set),[bt,H]=(0,d.useState)(!1),[xt,St]=(0,d.useState)(``),Ct=(0,d.useCallback)(e=>{yt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),wt=(0,d.useMemo)(()=>Ri(e.bySession??[]),[e.bySession]),Tt=e=>(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:L.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:U(e.cost)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.lastActive>0?`${G(e.lastActive)} ${Zi(e.lastActive)}`:`—`})]}),Dt=(e,t)=>(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{className:y(L.sessionChildRow,t>0&&L.sessionSubDeepRow),"data-testid":`billing-session-sub-row`,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),children:n(`sessionSubRow`)}),(e.subCalls??0)>0&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-session-sub-chain`,children:e.subCost!==void 0&&e.subCost>0?n(`sessionSubCost`).replace(`{cost}`,U(e.subCost)):n(`sessionSubCalls`).replace(`{calls}`,(e.subCalls??0).toLocaleString())}),(0,m.jsx)(`span`,{className:L.modelProvider,children:e.title??e.id.slice(0,8)})]}),Tt(e)]}),e.subs?.map(e=>Dt(e,t+1))]},e.id),Ot=(0,d.useMemo)(()=>Hi(e.bySession??[],xt),[e.bySession,xt]),kt=e.bySession?.length??0,At=e.bySessionTotal??kt,jt=At>kt,Mt=(0,d.useMemo)(()=>[...new Set([...Object.keys(ee),...Object.keys(E)])].map(e=>{let t=cn(e);return{key:e,name:t.key===`other`?void 0:t.name,cost:ee[e]??0}}).sort((e,t)=>t.cost-e.cost),[ee,E]),[Nt,Pt]=(0,d.useState)(()=>new Set(Me())),Ft=(0,d.useCallback)(e=>{Pt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Ne([...n]),n})},[]),[It,Lt]=(0,d.useState)(()=>Pe()),Rt=(0,d.useCallback)(()=>{Lt(e=>{let t=!e;return Fe(t),t})},[]),[Vt,Ht]=(0,d.useState)(!1);(0,d.useEffect)(()=>{let e=!0;return ra().then(t=>{e&&t!==void 0&&Ht(t)}),()=>{e=!1}},[]);let Ut=(0,d.useCallback)(()=>{let e=!Vt;Ht(e),ia(e).then(t=>{t||Ht(!e)})},[Vt]),Wt=Et(),[Gt,Kt]=(0,d.useState)(!1),qt=(0,d.useCallback)(()=>{Gt||(Kt(!0),ca().finally(()=>{Kt(!1)}))},[Gt]),Jt=oa,U=e=>W(gn(e,h),h),Yt=h===`usd`?`$`:h===`eur`?`€`:`¥`,Xt=_,Zt=e=>gr(e,Xt),[Qt,$t]=(0,d.useState)(``),[en,tn]=(0,d.useState)(()=>Ae()),[nn,rn]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{let e=setInterval(()=>{rn(Date.now())},3e4);return()=>{clearInterval(e)}},[]);let an=u.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),on=D.leadMin*6e4,sn=(e,t)=>e===0?n(`free`):_n(vn(e,t,h,Wt.rate),h===`usd`?`USD`:h===`eur`?`EUR`:`CNY`),ln=(0,d.useMemo)(()=>sr([...b].reverse()),[b]),dn={peak:e.byTier?.peak.cost??0,offPeak:e.byTier?.offPeak.cost??0},pn=dn.peak/2,hn=Yr(N,G()),bn=e=>c.find(t=>Z(t.provider)===Z(e)),xn=e=>e.balance?.error===`unconfigured`&&e.models.length>0&&e.models.every(e=>e.plan),Sn=e=>{if(e===void 0)return(0,m.jsx)(`span`,{className:L.na,children:`—`});if(e.error===`unconfigured`)return n(`balanceUnconfigured`);if(e.error===`unauthorized`)return n(`balanceUnauthorized`);if(e.error===`unreachable`)return n(`balanceUnreachable`);if(e.totalBalance===void 0)return(0,m.jsx)(`span`,{className:L.na,children:`—`});let t=e.currency===`USD`?`$${e.totalBalance.toFixed(2)}`:U(e.totalBalance),r=e.currency===`USD`?e.totalBalance*Wt.rate:e.totalBalance,i=hn>0?Math.floor(r/hn):void 0;return(0,m.jsxs)(`span`,{className:L.balanceCell,children:[(0,m.jsx)(`span`,{children:t}),i!==void 0&&i>=0&&(0,m.jsx)(`button`,{type:`button`,className:y(L.balanceDaysBadge,i<=3&&L.balanceDaysBadgeLow),"data-testid":`billing-balance-days-badge`,title:n(`balanceDays`).replace(`{days}`,String(i)),"aria-label":`${e.displayName} ${n(`balanceDays`).replace(`{days}`,String(i))}`,onClick:t=>{t.stopPropagation(),_t(gt===e.provider?void 0:e.provider)},children:`?`}),gt===e.provider&&(0,m.jsx)(wa,{balance:e,days:i??0,dailyBurn:hn,money:U,t:n,onClose:()=>{_t(void 0)}})]})},Tn=Object.keys(N).sort(),q=G(),An=N[q]?.cost??0,jn=q.slice(0,7),Mn=q.slice(0,4),Nn=Tn.reduce((e,t)=>e+(t.startsWith(jn)?N[t]?.cost??0:0),0),Fn=Tn.reduce((e,t)=>e+(t.startsWith(Mn)?N[t]?.cost??0:0),0),J=(0,d.useMemo)(()=>Zr(N,jn,q)+u.reduce((e,t)=>e+(t.planType===`code`?t.subscriptionAmount??0:0),0),[N,jn,q,u]),In=(0,d.useMemo)(()=>{if(!(S&&C>0))return null;let e=C-Nn;return{over:e<=0,remainRatio:Math.max(0,Math.min(1,e/C)),remainCny:Math.max(0,e)}},[S,C,Nn]),Ln=(0,d.useMemo)(()=>{let e=[];for(let t=Le-1;t>=0;--t){let n=new Date;n.setDate(n.getDate()-t),e.push(G(n.getTime()))}return e},[Le]),Rn=Ln.at(-1)??q,Y=(0,d.useMemo)(()=>Object.entries(N).map(([e,t])=>({date:e,value:$e===`tokens`?ei(t):t.cost})),[N,$e]),Bn=(0,d.useMemo)(()=>Y.reduce((e,t)=>e+t.value,0),[Y]),Vn=Qr(N),Hn=$r(N),Un=(0,d.useMemo)(()=>Ln.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=N[t];return{date:t,cost:i?.cost??0,calls:i?.calls??0,byModel:n,tokens:i===void 0?0:ei(i)}}),[Ln,N,e.byDayModels]),Wn=(0,d.useMemo)(()=>Object.entries(je).filter(([,e])=>e.calls>0).map(([e,t])=>{let n=cn(e),r=n.key===`other`,i=r?fi(e):void 0,a={input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,cacheWrite:t.cacheWrite??0,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:mn(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`})),[je]),Kn=(0,d.useMemo)(()=>ae.hideUnidentified?f.filter(e=>e.kind!==`unknown`):f,[f,ae.hideUnidentified]),qn=(0,d.useCallback)(e=>xr(e,Xt)??n(`channelUnknown`),[Xt,n]),Yn=(0,d.useMemo)(()=>{let t=e.byDayModelsSite;if(It){let n=G();t={[n]:e.byDayModelsSite?.[n]??{}}}let r=new Map;for(let n of Object.values(t??{}))for(let[t,i]of Object.entries(n))for(let[n,a]of Object.entries(i)){let i=r.get(n);i===void 0&&(i=new Map,r.set(n,i));let o=i.get(t)??{calls:0,input:0,output:0,cacheHit:0,cacheMiss:0,cacheWrite: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.cacheWrite+=a.cacheWrite??0,o.cost+=a.cost,o.allPlan=o.allPlan&&(a.plan??e.byModel?.[t]?.plan===!0),i.set(t,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=cn(e),a=i.key===`other`,o=a?fi(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:mn(i,{input:t.input,cacheHit:t.cacheHit,cacheMiss:t.cacheMiss,cacheWrite:t.cacheWrite,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 a=e=>xr(e,Xt)??n(`channelUnknown`),o=new Map,l=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=a(e),r=o.get(n);if(r===void 0)o.set(n,[...t]),l.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=l.get(n)??`unknown`,a=f(e);p[a]>p[i]&&(l.set(n,a),d.set(n,e))}}let m=new Map,h=new Map;for(let e of u){if(e.status===`not-configured`)continue;let t=e.displayName??mi(e.provider),n=a(`direct:${e.provider}`),r=o.has(t)?t:o.has(n)?n:void 0,i=r??`sub:${mi(e.provider)}`;h.set(i,r??mi(e.provider));let s=m.get(i);s===void 0?m.set(i,[e]):s.push(e)}let g=e=>e===a(`direct:deepseek`)||e===a(`site:https://api.deepseek.com`)?bn(`deepseek`)??bn(e):bn(e),_=[];for(let[e,t]of o)_.push({id:`ch:${d.get(e)??e}`,name:e,models:t,subscriptions:m.get(e)??[],balance:g(e),dot:Wi(s,t[0]?.provider??``),channelKind:l.get(e)??`unknown`});for(let[e,t]of h)o.has(e)||_.push({id:e,name:t,models:[],subscriptions:m.get(e)??[],balance:bn(t),dot:Wi(s,t),channelKind:`vendor`});let v=new Set(_.flatMap(e=>[Z(e.name),...e.balance===void 0?[]:[Z(e.balance.provider)]]));for(let e of c)v.has(Z(e.provider))||(e.error===void 0||e.provider.startsWith(`custom:`))&&_.push({id:`bal:${e.provider}`,name:e.displayName,models:[],subscriptions:[],balance:e,dot:Wi(s,e.displayName),channelKind:`vendor`});return _.filter(e=>ae.hideUnidentified&&e.channelKind===`unknown`?!1:!It||e.models.length>0).sort((e,t)=>{let n=Yi(t)-Yi(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,u,c,s,Xt,n,It,ae.hideUnidentified]),Xn=(0,d.useMemo)(()=>Yn.filter(e=>e.models.length>0||e.subscriptions.length>0).map(e=>e.id),[Yn]),Zn=Xn.length>0&&Xn.every(e=>Nt.has(e)),$n=()=>{let e=new Set(Zn?[]:Xn);Pt(e),Ne([...e])},er=(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`model`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`calls`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`inputTokens`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`outputTokens`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`cacheHitRate`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`actual`)})]})}),tr=e=>(0,m.jsx)(`span`,{className:L.modelCell,children:(0,m.jsxs)(`span`,{children:[(0,m.jsxs)(`span`,{className:L.modelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:L.uncataloguedTag,"data-testid":`billing-uncatalogued-tag`,children:n(`uncatalogued`)}),e.estimatedPricing&&(0,m.jsx)(`span`,{className:L.estimatedTag,"data-testid":`billing-estimated-tag`,children:n(`estimatedPricing`)})]}),(0,m.jsx)(`span`,{className:L.modelProvider,children:Zt(e.provider)})]})}),nr=e.bySite?.unknown?.calls??0,rr=Wn.reduce((e,t)=>e+t.estimated,0),ar=ke.cost>0||nr>0?ke.cost:rr,X=(0,d.useMemo)(()=>{if(B===`all`){let e,t=0;for(let[n,r]of Object.entries(N)){let i=ei(r);i>t&&(t=i,e=n)}return{cost:ar,calls:ke.calls,input:ke.input,output:ke.output,cacheHit:ke.cacheHit,cacheMiss:ke.cacheMiss,cacheWrite:ke.cacheWrite??0,reasoning:ke.reasoning??0,peakDay:e,peakTokens:t}}return B===`custom`?ii(N,V.start,V.end):ri(N,G(),B)},[B,V,ar,ke,N]),or=B===`custom`?V.start===V.end?V.start:`${V.start} – ${V.end}`:n({today:`avgRangeToday`,"7d":`avgRange7d`,week:`avgRangeWeek`,month:`avgRangeMonth`,all:`avgRangeAll`}[B]),cr=(0,d.useMemo)(()=>Wn.map(e=>({key:e.key,name:e.name,color:e.color})),[Wn]),lr=Un.length>=2?Un.at(-2)?.cost??0:0,ur=lr>0?(An-lr)/lr*100:0,fr=(0,m.jsxs)(`div`,{ref:xe,className:y(L.dashboard,zr,i&&L.nativeSettingsDashboard),"data-testid":i?`native-billing-settings-dashboard`:`billing-dashboard`,children:[!i&&(0,m.jsxs)(`div`,{className:L.dashboardHead,"data-testid":`billing-dashboard-head`,children:[(0,m.jsxs)(`div`,{children:[x(`billing.dashboard.decor`,{position:`head`}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h2`,{className:L.dashboardTitle,children:n(`title`)}),x(`billing.dashboard.decor`,{position:`headTitle`})]}),(0,m.jsxs)(`p`,{className:L.dashboardSubtitle,children:[n(`lastUpdated`),` `,Rn,e.timezone===void 0?null:` · ${e.timezone.name} (${e.timezone.offset})`]})]}),(0,m.jsxs)(`div`,{className:L.dashboardRight,children:[(0,m.jsx)(`span`,{className:L.currencyToggle,role:`group`,"aria-label":n(`language`),children:[`en`,`zh`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.currencyButton,_===e&&L.currencyButtonActive),"aria-pressed":_===e,"data-testid":`billing-language-${e}`,onClick:()=>{v(e)},children:e===`en`?`EN`:`中`},e))}),(0,m.jsx)(`span`,{className:L.currencyToggle,role:`group`,"aria-label":n(`currency`),children:[`cny`,`usd`,`eur`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.currencyButton,h===e&&L.currencyButtonActive),"aria-pressed":h===e,"data-testid":`billing-currency-${e}`,title:n(e===`cny`?`currencyCny`:e===`usd`?`currencyUsd`:`currencyEur`),onClick:()=>{g(e)},children:e===`cny`?`¥ CNY`:e===`usd`?`$ USD`:`€ EUR`},e))}),s.checked&&(0,m.jsxs)(`span`,{className:y(L.healthBadge,s.available?L.healthBadgeOk:L.healthBadgeBad),children:[(0,m.jsx)(`span`,{className:y(L.healthDot,s.available?L.healthOk:L.healthBad),role:`img`,"aria-label":s.available?n(`healthDotLive`):n(`healthDotFailed`),title:s.available?n(`healthDotLive`):n(`healthDotFailed`)}),s.available?`${n(`healthModelsLive`).replace(`{n}`,String(s.models))}${s.failures>0?` · ${n(`healthVendorsDown`).replace(`{n}`,String(s.failures))}`:``}`:n(`healthVendorsUnavailable`).replace(`{n}`,String(s.failures))]}),(0,m.jsx)(`button`,{type:`button`,className:L.closeButton,"aria-label":n(`close`),"data-testid":`billing-close`,onClick:r,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`})]})})]})]}),!i&&t!==void 0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-stats-error`,children:(0,m.jsxs)(`div`,{className:L.staleNoticeBody,children:[(0,m.jsx)(`span`,{children:n(`statsLoadFailed`)}),(0,m.jsx)(`span`,{className:L.staleNoticeSub,children:t})]})}),!i&&e.staleSnapshot===!0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-stale-snapshot`,children:n(`staleSnapshotNotice`)}),!i&&(0,m.jsx)(`nav`,{className:L.tabNav,"data-testid":`billing-tab-nav`,role:`tablist`,"aria-label":n(`title`),children:Wr.map(e=>(0,m.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":P===e.id,"aria-controls":`billing-tab-panel-${e.id}`,className:y(L.tabButton,P===e.id&&L.tabButtonActive),"data-testid":`billing-tab-${e.id}`,onClick:()=>{Ie(e.id)},children:[(0,m.jsx)(`span`,{className:L.tabRailIcon,"aria-hidden":`true`,children:Kr[e.id]}),(0,m.jsx)(`span`,{className:L.tabNavLabel,children:n(e.labelKey)})]},e.id))}),(0,m.jsxs)(`div`,{className:y(L.dashboardBody,i&&L.nativeSettingsBody),children:[P===`queue`&&(0,m.jsx)(ya,{t:n,language:_,navigateToSession:ye,...be===void 0?{}:{sessionTitleOf:be},reuseSourceSession:M.reuseSourceSession}),P===`overview`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-overview`,children:[l?.kind===`drift`&&l.spent!==void 0&&Be!==He()&&(0,m.jsxs)(`div`,{className:L.reconcileNotice,"data-testid":`billing-reconcile-notice`,role:`note`,children:[(0,m.jsx)(`span`,{className:L.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:L.reconcileText,children:n(`reconcileDrift`).replace(`{provider}`,l.provider??``).replace(`{spent}`,U(l.spent)).replace(`{today}`,U(l.todayOfficialCost??0))}),(0,m.jsx)(`button`,{type:`button`,className:L.reconcileDismiss,"data-testid":`billing-reconcile-dismiss`,onClick:Ue,children:n(`reconcileDismiss`)})]}),ve===!0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-balance-stale`,children:n(`balanceStaleNotice`)}),(0,m.jsxs)(`section`,{className:L.hero,"data-testid":`billing-hero`,children:[x(`billing.dashboard.decor`,{position:`hero`}),(0,m.jsxs)(`div`,{className:L.heroTop,children:[(0,m.jsxs)(`div`,{className:L.heroMain,children:[(0,m.jsx)(`span`,{className:L.heroLabel,"data-testid":`billing-hero-range-label`,children:or}),(0,m.jsxs)(`div`,{className:L.heroReadout,children:[(0,m.jsx)(`span`,{className:L.heroCurrency,"aria-hidden":`true`,children:Yt}),(0,m.jsx)(`span`,{className:L.heroValue,"data-testid":`billing-hero-range-value`,children:U(X.cost).slice(1)})]}),(0,m.jsxs)(`span`,{className:L.heroMeta,children:[X.calls.toLocaleString(),` `,n(`calls`),B===`month`&&J>0&&(0,m.jsxs)(`span`,{className:L.heroPred,children:[` `,n(`monthProjected`),` `,U(J)]})]})]}),In!==null&&(0,m.jsxs)(`div`,{className:L.heroGauge,"data-testid":`billing-hero-gauge`,children:[(0,m.jsxs)(`div`,{className:L.heroGaugeDial,children:[(0,m.jsxs)(`svg`,{className:L.heroGaugeSvg,viewBox:`0 0 120 120`,"aria-hidden":`true`,children:[(0,m.jsx)(`defs`,{children:(0,m.jsxs)(`linearGradient`,{id:`heroRingGrad`,x1:`0%`,y1:`0%`,x2:`100%`,y2:`100%`,children:[(0,m.jsx)(`stop`,{offset:`0%`,stopColor:`var(--ds-cyan)`}),(0,m.jsx)(`stop`,{offset:`55%`,stopColor:`var(--ds-blue)`}),(0,m.jsx)(`stop`,{offset:`100%`,stopColor:`var(--ds-amber)`})]})}),(0,m.jsx)(`circle`,{className:L.heroGaugeTrack,cx:`60`,cy:`60`,r:`52`}),(0,m.jsx)(`circle`,{className:y(L.heroGaugeArc,In.over&&L.heroGaugeArcOver),cx:`60`,cy:`60`,r:`52`,style:{strokeDasharray:`${In.remainRatio*326.7} 326.7`},stroke:In.over?void 0:`url(#heroRingGrad)`})]}),(0,m.jsxs)(`span`,{className:L.heroGaugeCenter,children:[(0,m.jsxs)(`span`,{className:y(L.heroGaugeRemain,In.over&&L.heroGaugeRemainOver),children:[Yt,gn(In.remainCny,h).toFixed(2)]}),(0,m.jsx)(`span`,{className:L.heroGaugeLabel,children:n(`budgetRemain`)})]})]}),(0,m.jsxs)(`span`,{className:L.heroGaugeSub,children:[U(Nn),` / `,U(C)]})]})]}),(0,m.jsxs)(`div`,{className:L.heroSide,children:[(0,m.jsxs)(`div`,{className:L.heroSideItem,children:[(0,m.jsx)(`span`,{className:L.heroSideLabel,children:n(`yearCost`)}),(0,m.jsx)(`span`,{className:L.heroSideValue,children:U(Fn)})]}),(0,m.jsxs)(`div`,{className:L.heroSideItem,children:[(0,m.jsx)(`span`,{className:L.heroSideLabel,children:n(`todayCost`)}),(0,m.jsxs)(`span`,{className:L.heroSideValue,children:[U(An),(0,m.jsxs)(`span`,{className:y(L.delta,ur>=0?L.deltaUp:L.deltaDown),children:[ur>=0?`▲`:`▼`,` `,Math.abs(ur).toFixed(1),`%`]})]})]}),J>0&&(0,m.jsxs)(`div`,{className:L.heroSideItem,title:n(`monthProjectedHint`),children:[(0,m.jsx)(`span`,{className:L.heroSideLabel,children:n(`monthProjected`)}),(0,m.jsx)(`span`,{className:L.heroSideValue,children:U(J)})]}),J<=0&&(0,m.jsx)(`span`,{className:L.heroSideSpacer,"aria-hidden":`true`})]})]}),(e.unpricedModels?.length??0)>0&&!We.has(`unpriced`)&&(0,m.jsxs)(`div`,{className:L.unpricedHint,"data-testid":`billing-unpriced-hint`,children:[(0,m.jsx)(`span`,{className:L.unpricedHintBody,children:n(`unpricedHint`).replace(`{count}`,String(e.unpricedModels?.length??0)).replace(`{models}`,Da(e.unpricedModels??[],n,_))}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeAction,"data-testid":`billing-unpriced-fix`,onClick:()=>{Ie(`settings`),R(_===`zh`?`单价`:`price`)},children:n(`unpricedFix`)}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeDismiss,"data-testid":`billing-unpriced-dismiss`,"aria-label":n(`close`),onClick:()=>{Ke(`unpriced`)},children:`×`})]}),(e.total.searchCalls??0)>0&&!We.has(`search-estimate`)&&(0,m.jsxs)(`div`,{className:L.unpricedHint,"data-testid":`billing-search-estimate-hint`,children:[(0,m.jsx)(`span`,{className:L.unpricedHintBody,children:n(`searchEstimateHint`).replace(`{count}`,String(e.total.searchCalls??0)).replace(`{each}`,U(e.searchCallEstimateCny??0))}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeDismiss,"data-testid":`billing-search-estimate-dismiss`,"aria-label":n(`close`),onClick:()=>{Ke(`search-estimate`)},children:`×`})]}),(e.unreadableSessions??0)>0&&!We.has(`unreadable`)&&(0,m.jsxs)(`div`,{className:L.staleNotice,"data-testid":`billing-sessions-unreadable`,children:[(0,m.jsxs)(`div`,{className:L.staleNoticeBody,children:[n(`unreadableNotice`).replace(`{count}`,String(e.unreadableSessions)),(e.unreadableNoLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:L.staleNoticeSub,"data-testid":`billing-sessions-no-ledger`,children:n(`unreadableNoLedgerNotice`).replace(`{count}`,String(e.unreadableNoLedgerSessions))}),(e.unreadableFormatSessions??0)>0&&(0,m.jsx)(`div`,{className:L.staleNoticeSub,"data-testid":`billing-sessions-format-unsupported`,children:n(`unreadableFormatNotice`).replace(`{count}`,String(e.unreadableFormatSessions))})]}),(0,m.jsx)(`button`,{type:`button`,className:L.noticeDismiss,"data-testid":`billing-unreadable-dismiss`,"aria-label":n(`close`),onClick:()=>{Ke(`unreadable`)},children:`×`})]}),(0,m.jsxs)(`div`,{className:L.kpiZone,children:[(0,m.jsxs)(`div`,{className:L.kpiZoneHead,children:[(0,m.jsx)(`span`,{className:L.kpiZoneLabel,children:n(`kpiRange`)}),(0,m.jsx)(`div`,{className:L.heatmapRangeSwitch,"data-testid":`billing-kpi-range`,role:`group`,"aria-label":n(`kpiRange`),children:[[`today`,`avgRangeToday`],[`7d`,`avgRange7d`],[`week`,`avgRangeWeek`],[`month`,`avgRangeMonth`],[`all`,`avgRangeAll`],[`custom`,`avgRangeCustom`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,className:y(L.heatmapRangeButton,B===e&&L.heatmapRangeButtonActive),"data-testid":`billing-kpi-range-${e}`,"aria-pressed":B===e,onClick:()=>{ft(e),se(e)},children:n(t)},e))})]}),B===`custom`&&(0,m.jsxs)(`div`,{className:L.kpiCustomRange,"data-testid":`billing-kpi-custom-range`,children:[(0,m.jsxs)(`label`,{children:[n(`customRangeStart`),(0,m.jsx)(`input`,{type:`date`,value:V.start,max:G(),"data-testid":`billing-kpi-custom-start`,onChange:e=>{mt({start:e.target.value})}})]}),(0,m.jsxs)(`label`,{children:[n(`customRangeEnd`),(0,m.jsx)(`input`,{type:`date`,value:V.end,max:G(),"data-testid":`billing-kpi-custom-end`,onChange:e=>{mt({end:e.target.value})}})]})]}),(0,m.jsx)(`section`,{className:L.kpiGrid,"data-testid":`billing-kpi-grid`,children:(()=>{let e=Object.keys(N).sort().slice(-7),t=G(),r=e.indexOf(t),i=(e,t)=>e[t]??0,a=e.map(e=>N[e]?.cost??0),o=e.map(e=>N[e]?.calls??0),s=e.map(e=>{let t=N[e];return t===void 0?0:ei(t)}),c=e.map(e=>{let t=N[e];return t!==void 0&&t.cacheHit+t.cacheMiss>0?t.cacheHit/(t.cacheHit+t.cacheMiss)*100:0}),l=r>0&&i(a,r-1)>0?(i(a,r)-i(a,r-1))/i(a,r-1)*100:0,u=r>0&&i(o,r-1)>0?(i(o,r)-i(o,r-1))/i(o,r-1)*100:0,d=r>0&&i(s,r-1)>0?(i(s,r)-i(s,r-1))/i(s,r-1)*100:0,f=r>0&&i(c,r-1)>0?i(c,r)-i(c,r-1):0,h=(e,t)=>B===`custom`?null:(0,m.jsx)(`svg`,{viewBox:`0 0 28 12`,preserveAspectRatio:`none`,style:{display:`block`,width:`100%`,height:`12px`},children:e.map((n,r)=>{let i=n/Math.max(...e,1)*10,a=r*4;return(0,m.jsx)(`rect`,{x:a,y:12-i,width:`2.5`,height:i,fill:t,opacity:r===e.length-1?1:.6},r)})}),g=e=>B===`custom`?null:(0,m.jsxs)(`span`,{className:y(L.kpiDelta,e>0?L.kpiDeltaUp:e<0?L.kpiDeltaDown:L.kpiDeltaFlat),children:[e>0?`▲`:e<0?`▼`:``,` `,Math.abs(e).toFixed(1),`%`]});return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-tile`,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescCacheHit`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`cacheHitRate`)})}),g(f)]}),(0,m.jsx)(`span`,{className:y(L.kpiValue,L.kpiGreen),children:yn(X.cacheHit+X.cacheMiss>0?X.cacheHit/(X.cacheHit+X.cacheMiss)*100:0)}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(c,`var(--ds-cyan)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[K(X.cacheHit),` / `,K(X.cacheHit+X.cacheMiss),X.cacheWrite>0?` · ${n(`tokenCacheWrite`)} ${K(X.cacheWrite)}`:``]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescTokens`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokens`)})}),g(d)]}),(0,m.jsx)(`span`,{className:L.kpiValue,children:K(X.input+X.output)}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(s,`var(--ds-blue)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[n(`inputTokens`),` `,K(X.input),` · `,n(`outputTokens`),` `,K(X.output)]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-avg`,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescAvgCost`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`avgCost`)})}),g(l)]}),(0,m.jsx)(`span`,{className:L.kpiValue,children:U(X.calls>0?X.cost/X.calls:0)}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(a,`var(--ds-blue)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[n(`calls`),` `,X.calls.toLocaleString()]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,children:[(0,m.jsxs)(`div`,{className:L.kpiLabelRow,children:[(0,m.jsx)(p.Tooltip,{label:n(`kpiDescCalls`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`calls`)})}),g(u)]}),(0,m.jsx)(`span`,{className:L.kpiValue,children:X.calls.toLocaleString()}),(0,m.jsx)(`div`,{className:L.kpiSpark,children:h(o,`var(--ds-blue)`)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[Wn.length,` `,n(`models`)]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-think`,children:[(0,m.jsx)(`div`,{className:L.kpiLabelRow,children:(0,m.jsx)(p.Tooltip,{label:n(`kpiDescReasoning`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokenReasoningShare`)})})}),(0,m.jsx)(`span`,{className:y(L.kpiValue,L.kpiGreen),children:yn(X.output>0?X.reasoning/X.output*100:0)}),(0,m.jsx)(`span`,{className:L.kpiDetail,children:K(X.reasoning)})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-io`,children:[(0,m.jsx)(`div`,{className:L.kpiLabelRow,children:(0,m.jsx)(p.Tooltip,{label:n(`kpiDescIo`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokenIo`)})})}),(0,m.jsx)(`span`,{className:L.kpiValue,children:(X.output>0?X.input/X.output:0).toFixed(2)}),(0,m.jsxs)(`span`,{className:L.kpiDetail,children:[K(X.input),` / `,K(X.output)]})]}),(0,m.jsxs)(`div`,{className:L.kpiTile,"data-testid":`billing-kpi-peak`,children:[(0,m.jsx)(`div`,{className:L.kpiLabelRow,children:(0,m.jsx)(p.Tooltip,{label:n(`kpiDescPeak`),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.kpiLabel,children:n(`tokenPeak`)})})}),(0,m.jsx)(`span`,{className:L.kpiValue,children:X.peakTokens>0?kn(X.peakTokens):`—`}),(0,m.jsx)(`span`,{className:L.kpiDetail,children:X.peakDay??`—`})]})]})})()})]}),(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-heatmap`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`heatmap`)}),(0,m.jsx)(`div`,{className:L.heatmapRangeSwitch,"data-testid":`billing-heatmap-metric`,role:`group`,"aria-label":n(`heatmap`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.heatmapRangeButton,$e===e&&L.heatmapRangeButtonActive),"data-testid":`billing-heatmap-metric-${e}`,"aria-pressed":$e===e,onClick:()=>{et(e)},children:n(e===`cost`?`metricCost`:`metricTokens`)},e))}),(0,m.jsx)(`div`,{className:L.heatmapRangeSwitch,"data-testid":`billing-heatmap-range`,role:`group`,"aria-label":n(`heatmap`),children:[`month`,`half`,`year`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.heatmapRangeButton,qe===e&&L.heatmapRangeButtonActive),"data-testid":`billing-heatmap-range-${e}`,"aria-pressed":qe===e,onClick:()=>{Ye(e)},children:n(e===`month`?`heatmapMonth`:e===`half`?`heatmapHalf`:`heatmapYear`)},e))}),(0,m.jsxs)(`span`,{className:L.panelHint,"data-testid":`billing-heatmap-summary`,children:[n(`heatmapTotal`),` `,$e===`tokens`?K(Bn):U(Bn),` · `,n(`activeDays`),` `,Vn,` · `,n(`streakDays`),` `,Hn]})]}),(0,m.jsx)(ir,{days:Y,currency:h,t:n,range:qe,unit:$e})]})]}),P===`agents`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-agents`,children:[(0,m.jsxs)(`section`,{className:L.agentSummary,"data-testid":`billing-agent-summary`,children:[(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:String(Ce.agents)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsCount`)})]}),(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:String(Ce.delegations)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsDelegations`)})]}),(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:String(Ce.roots)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsRoots`)})]}),Ce.costliest!==void 0&&Ce.costliest.chainCost>0&&(0,m.jsxs)(`span`,{className:L.agentSummaryItem,children:[(0,m.jsx)(`span`,{className:L.agentSummaryValue,children:U(Ce.costliest.chainCost)}),(0,m.jsx)(`span`,{className:L.agentSummaryLabel,children:n(`agentsMostExpensive`)})]})]}),Se.length===0||Ce.delegations===0?(0,m.jsx)(`p`,{className:L.contextEmpty,"data-testid":`billing-agents-empty`,children:n(`agentsNoData`)}):(0,m.jsx)(`div`,{className:L.agentTree,"data-testid":`billing-agent-tree`,children:(()=>{let e=t=>(0,m.jsxs)(`div`,{className:L.agentNode,children:[(0,m.jsxs)(`div`,{className:L.agentRow,style:{paddingLeft:`${String(t.depth*16)}px`},children:[(0,m.jsx)(`span`,{className:L.agentKind,children:t.depth===0?n(`agentsRoot`):n(`agentsSubagent`)}),(0,m.jsx)(`span`,{className:L.agentTitle,children:t.title??`${n(`sessionUntitled`)} · ${t.id.slice(0,8)}`}),(0,m.jsx)(`span`,{className:L.agentCalls,children:t.calls.toLocaleString()}),(0,m.jsx)(`span`,{className:L.agentCost,children:U(t.cost)}),t.children.length>0&&(0,m.jsxs)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-agent-chain`,children:[n(`agentsChainTotal`),` `,U(t.chainCost)]})]}),t.children.map(e)]},t.id);return Se.map(e)})()})]}),P===`settings`&&(0,m.jsx)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-settings`,children:(0,m.jsxs)(`div`,{className:y(L.settingsLayout,i&&L.nativeSettingsLayout),children:[!i&&(0,m.jsx)(`aside`,{className:L.settingsNav,"data-testid":`billing-settings-nav`,role:`navigation`,"aria-label":`settings`,children:[{id:`display-pref`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:[(0,m.jsx)(`path`,{d:`M5 3v10M11 3v10`}),(0,m.jsx)(`circle`,{cx:`5`,cy:`6.5`,r:`1.8`}),(0,m.jsx)(`circle`,{cx:`11`,cy:`9.5`,r:`1.8`})]}),label:n(`settingsNavDisplayPref`)},{id:`budget`,icon:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:(0,m.jsx)(`path`,{d:`M5 3l3 4 3-4M8 7v6M5.5 9.5h5M5.5 12h5`})}),label:n(`settingsNavBudget`)},{id:`alert`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,m.jsx)(`path`,{d:`M8 2a4 4 0 0 1 4 4v3l1.5 2.5h-11L4 9V6a4 4 0 0 1 4-4z`}),(0,m.jsx)(`path`,{d:`M6.5 13.5a1.5 1.5 0 0 0 3 0`})]}),label:n(`settingsNavAlert`)},{id:`display`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`8`,r:`6`}),(0,m.jsx)(`path`,{d:`M8 2a6 6 0 0 1 0 12z`,fill:`currentColor`,stroke:`none`})]}),label:n(`settingsNavDisplay`)},{id:`advanced`,icon:(0,m.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:(0,m.jsx)(`path`,{d:`M8 2v12M2.8 5l10.4 6M13.2 5L2.8 11`})}),label:n(`settingsNavAdvanced`),advanced:!0},{id:`about`,icon:(0,m.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,children:[(0,m.jsx)(`circle`,{cx:`8`,cy:`8`,r:`6`}),(0,m.jsx)(`path`,{d:`M8 7.5V11`}),(0,m.jsx)(`circle`,{cx:`8`,cy:`5.2`,r:`0.9`,fill:`currentColor`,stroke:`none`})]}),label:n(`settingsNavAbout`)}].map(e=>(0,m.jsxs)(`button`,{type:`button`,className:y(L.settingsNavItem,at===e.id&&L.settingsNavItemActive,e.advanced&&L.settingsNavItemAdvanced),"data-testid":`billing-settings-nav-${e.id}`,onClick:()=>{ct(e.id)},children:[(0,m.jsx)(`span`,{className:L.settingsNavIcon,"aria-hidden":`true`,children:e.icon}),e.label]},e.id))}),(0,m.jsxs)(`div`,{className:L.settingsPane,children:[(0,m.jsx)(`input`,{className:y(L.ubSearch,L.settingsSearch),type:`search`,value:st,placeholder:n(`settingsSearchPlaceholder`),"aria-label":n(`settingsSearchPlaceholder`),"data-testid":`billing-settings-search`,onChange:e=>{R(e.target.value)}}),st.trim()!==``&&Ma(st)&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-settings-search-empty`,children:n(`settingsSearchEmpty`).replace(`{query}`,st.trim())}),(0,m.jsxs)(`div`,{hidden:z(ja.display),className:L.setCard,id:`settings-display-pref`,"data-testid":`billing-density-motion-card`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsx)(`h3`,{className:L.setCardTitle,children:n(`settingsSectionDisplay`)})})}),(0,m.jsxs)(`div`,{className:L.densityRow,children:[(0,m.jsxs)(`div`,{className:L.densityLeft,children:[(0,m.jsx)(`strong`,{children:n(`densityLabel`)}),(0,m.jsx)(`span`,{children:n(`densityHint`)})]}),(0,m.jsx)(`div`,{className:L.densityButtons,"data-testid":`billing-density-buttons`,children:[`compact`,`default`,`comfortable`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.densityButton,tt===e&&L.densityButtonActive,e===`comfortable`&&L.densityButtonComfortable),"data-testid":`billing-density-${e}`,onClick:()=>{ut(e)},children:n(e===`compact`?`densityCompact`:e==="default"?`densityDefault`:`densityComfortable`)},e))})]}),(0,m.jsxs)(`div`,{className:L.densityRow,children:[(0,m.jsxs)(`div`,{className:L.densityLeft,children:[(0,m.jsx)(`strong`,{children:n(`motionLabel`)}),(0,m.jsx)(`span`,{children:n(`motionHint`)})]}),(0,m.jsx)(`div`,{className:L.densityButtons,"data-testid":`billing-motion-buttons`,children:[`off`,`subtle`,`rich`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.densityButton,rt===e&&L.densityButtonActive),"data-testid":`billing-motion-${e}`,onClick:()=>{dt(e)},children:n(e===`off`?`motionOff`:e===`subtle`?`motionSubtle`:`motionRich`)},e))})]})]}),(0,m.jsxs)(`section`,{hidden:z(ja.budget),className:L.setCard,"data-testid":`billing-budget`,id:`settings-budget`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`budget`),(0,m.jsx)(xa,{label:n(`budgetHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":S,"aria-label":n(`budget`),"data-testid":`billing-budget-toggle`,className:y(L.switch,S&&L.switchOn),onClick:w,children:(0,m.jsx)(`span`,{className:L.switchKnob})})]}),S&&(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`budgetAmount`)}),(0,m.jsxs)(`span`,{className:L.inp,"data-testid":`billing-budget-input-wrap`,children:[(0,m.jsx)(`span`,{className:L.affix,"aria-hidden":`true`,children:`¥`}),(0,m.jsx)(`input`,{className:L.budgetInput,"data-testid":`billing-budget-input`,type:`number`,min:0,step:1,value:C===0?``:C,placeholder:e.budget===void 0?`0`:String(e.budget),"aria-label":`${n(`budget`)}(${h===`usd`?`USD`:h===`eur`?`EUR`:`CNY`})`,title:`${n(`budget`)}(${h===`usd`?`USD`:h===`eur`?`EUR`:`CNY`})`,onChange:e=>{T(e.target.valueAsNumber)}})]})]}),C>0&&(()=>{let e=Nn/C*100;return(0,m.jsx)(`div`,{className:L.ctlRowStretch,children:(0,m.jsx)(`div`,{className:L.prog,role:`progressbar`,"aria-valuenow":Math.min(e,100),"aria-valuemin":0,"aria-valuemax":100,"aria-label":n(`budget`),"data-testid":`billing-budget-track`,children:(0,m.jsx)(`div`,{className:y(L.progFill,e>=100&&L.budgetFillOver,e>=80&&e<100&&L.budgetFillWarn),style:{width:`${Math.min(e,100)}%`}})})})})(),C>0&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-budget-value`,children:n(`budgetSummary`).replace(`{used}`,U(Nn)).replace(`{total}`,U(C))})]}),(0,m.jsxs)(`div`,{className:L.ctlCol,"data-testid":`billing-model-budgets`,children:[(0,m.jsxs)(`span`,{className:L.modelBudgetTitle,children:[n(`modelBudgetTitle`),(0,m.jsx)(xa,{label:n(`modelBudgetHint`),t:n})]}),Mt.length===0&&(0,m.jsx)(`p`,{className:L.modelBudgetHint,children:n(`emptyHint`)}),(0,m.jsx)(`div`,{className:L.modelBudgetList,children:Mt.map(e=>(0,m.jsxs)(`div`,{className:L.modelBudgetRow,children:[(0,m.jsx)(`span`,{className:L.modelBudgetName,title:e.name??e.key,children:e.name??e.key}),(0,m.jsx)(`span`,{className:L.modelBudgetCost,"data-testid":`billing-model-budget-cost-${e.key}`,children:U(e.cost)}),(0,m.jsxs)(`span`,{className:L.inp,children:[(0,m.jsx)(`span`,{className:L.affix,"aria-hidden":`true`,children:`¥`}),(0,m.jsx)(`input`,{className:L.budgetInput,type:`number`,min:0,step:1,value:E[e.key]??``,placeholder:n(`modelBudgetPlaceholder`),"aria-label":`${n(`modelBudgetTitle`)} · ${e.name??e.key}`,"data-testid":`billing-model-budget-${e.key}`,onChange:t=>{te(e.key,t.target.valueAsNumber)}})]})]},e.key))})]})]}),(0,m.jsxs)(`section`,{hidden:z(ja.alert),className:L.setCard,"data-testid":`billing-peak-alert-settings`,id:`settings-alert`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`peakAlert`),(0,m.jsx)(xa,{label:n(`peakAlertHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":D.enabled,"aria-label":n(`peakAlert`),"data-testid":`billing-peak-alert-toggle`,className:y(L.switch,D.enabled&&L.switchOn),onClick:()=>{O({...D,enabled:!D.enabled})},children:(0,m.jsx)(`span`,{className:L.switchKnob})})]}),D.enabled&&(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`label`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertLeadMin`)}),(0,m.jsx)(`span`,{className:L.inp,children:(0,m.jsx)(`input`,{type:`number`,min:1,max:30,step:1,value:D.leadMin,className:L.budgetInput,"aria-label":n(`peakAlertLeadMin`),onChange:e=>{let t=Number(e.target.valueAsNumber);O({...D,leadMin:Number.isFinite(t)?Math.min(30,Math.max(1,Math.round(t))):D.leadMin})}})})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertPos`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,role:`radiogroup`,"aria-label":n(`peakAlertPos`),children:[`bottom-right`,`center`].map(e=>(0,m.jsxs)(`label`,{className:L.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-pos`,checked:D.position===e,onChange:()=>O({...D,position:e})}),(0,m.jsx)(`span`,{className:L.rdoDot,"aria-hidden":`true`}),n(e===`bottom-right`?`peakAlertPosCorner`:`peakAlertPosCenter`)]},e))})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertMode`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,role:`radiogroup`,"aria-label":n(`peakAlertMode`),children:[`both`,`peak`,`offPeak`].map(e=>(0,m.jsxs)(`label`,{className:L.rdo,children:[(0,m.jsx)(`input`,{type:`radio`,name:`peak-mode`,checked:D.mode===e,onChange:()=>O({...D,mode:e})}),(0,m.jsx)(`span`,{className:L.rdoDot,"aria-hidden":`true`}),n(e===`both`?`peakAlertModeBoth`:e===`peak`?`peakAlertModePeak`:`peakAlertModeOff`)]},e))})]}),(0,m.jsxs)(`label`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`peakAlertWebNotify`)}),(0,m.jsx)(`input`,{type:`checkbox`,checked:D.webNotify,"aria-label":n(`peakAlertWebNotify`),onChange:e=>{O({...D,webNotify:e.target.checked})}})]}),(0,m.jsx)(`div`,{className:L.ctlRow,children:(0,m.jsx)(`button`,{type:`button`,className:L.btn,onClick:ne,children:n(`peakAlertPreview`)})})]})]}),(0,m.jsx)(`section`,{hidden:z(ja.toggles),className:L.setCard,"data-testid":`billing-toggle-setting`,id:`settings-display`,children:(0,m.jsxs)(`div`,{className:L.setGrid3,children:[(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-usage-stats-tool-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`usageStatsTool`),(0,m.jsx)(xa,{label:n(`usageStatsToolHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":Vt,"aria-label":n(`usageStatsTool`),"data-testid":`billing-usage-stats-tool-toggle`,className:y(L.switch,Vt&&L.switchOn),onClick:Ut,children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})}),(0,m.jsxs)(`div`,{className:L.setCell,"data-testid":`billing-livecost-setting`,children:[(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`liveCostBar`),(0,m.jsx)(xa,{label:n(`liveCostBarHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":me.show,"aria-label":n(`liveCostBar`),"data-testid":`billing-livecost-toggle`,className:y(L.switch,me.show&&L.switchOn),onClick:()=>he({...me,show:!me.show}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]}),me.show&&(0,m.jsxs)(`div`,{className:L.rdoRow,"data-testid":`billing-livecost-position`,children:[(0,m.jsx)(`span`,{className:L.rdoLabel,children:n(`liveCostBarPosition`)}),(0,m.jsx)(Pa,{liveCostPrefs:me,onLiveCostPrefs:he,t:n})]})]}),(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-site-list-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`siteListDisplay`),(0,m.jsx)(xa,{label:n(`siteListDisplayHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":ae.hideUnidentified,"aria-label":n(`siteListDisplay`),"data-testid":`billing-site-hide-unidentified`,className:y(L.switch,ae.hideUnidentified&&L.switchOn),onClick:()=>ce({hideUnidentified:!ae.hideUnidentified}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})}),(0,m.jsx)(Oa,{prefs:le,onPrefs:fe,groups:pe,t:n,money:U}),(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-quick-queue-entry-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`quickQueueEntry`),(0,m.jsx)(xa,{label:n(`quickQueueEntryHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":M.showEntry,"aria-label":n(`quickQueueEntry`),"data-testid":`billing-quick-queue-entry-toggle`,className:y(L.switch,M.showEntry&&L.switchOn),onClick:()=>ge({...M,showEntry:!M.showEntry}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})}),(0,m.jsx)(`div`,{className:L.setCell,"data-testid":`billing-quick-queue-reuse-setting`,children:(0,m.jsxs)(`div`,{className:L.setCardHead,children:[(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`quickQueueReuseEntry`),(0,m.jsx)(xa,{label:n(`quickQueueReuseEntryHint`),t:n})]})}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":M.reuseSourceSession,"aria-label":n(`quickQueueReuseEntry`),"data-testid":`billing-quick-queue-reuse-toggle`,className:y(L.switch,M.reuseSourceSession&&L.switchOn),onClick:()=>ge({...M,reuseSourceSession:!M.reuseSourceSession}),children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})})]})}),(0,m.jsx)(`section`,{hidden:z(ja.displayExtra),className:L.setCard,"data-testid":`billing-display-setting`,id:`settings-display-extra`,children:(0,m.jsxs)(`div`,{className:L.setGrid2,children:[(0,m.jsxs)(`div`,{className:L.setCell,"data-testid":`billing-float-setting`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`floatWindow`),(0,m.jsx)(xa,{label:n(`floatWindowHint`),t:n})]})})}),(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardMode`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-mode`,children:[[`full`,`cardModeFull`],[`compact`,`cardModeCompact`],[`hidden`,`cardModeHidden`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.mode===e&&L.floatModeBtnOn),"data-testid":`billing-card-mode-${e}`,"aria-pressed":j.mode===e,disabled:e===`hidden`&&!ie,title:e===`hidden`&&!ie?n(`cardModeFallback`):void 0,onClick:()=>re({...j,mode:e}),children:n(t)},e))})]}),!ie&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-card-mode-fallback`,children:n(`cardModeFallback`)}),ie&&j.mode===`hidden`&&(0,m.jsx)(`p`,{className:L.setCardDesc,"data-testid":`billing-card-mode-hidden-hint`,children:n(`cardModeHiddenHint`)}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`floatMode`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,"data-testid":`billing-float-mode`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,k.mode===`combined`&&L.floatModeBtnOn),"data-testid":`billing-float-mode-combined`,onClick:()=>A({mode:`combined`,targets:k.targets}),children:n(`floatModeCombined`)}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,k.mode===`subscription`&&L.floatModeBtnOn),"data-testid":`billing-float-mode-subscription`,onClick:()=>A({mode:`subscription`,targets:k.targets}),children:n(`floatModeSubscription`)})]})]}),k.mode===`subscription`&&(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`floatTargets`)}),(0,m.jsxs)(`span`,{className:L.ctlGroup,"data-testid":`billing-float-targets`,children:[ht.map(e=>{let t=k.targets.includes(e.id);return(0,m.jsxs)(`label`,{className:L.floatTarget,children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:t,"data-testid":`billing-float-target-${e.id}`,onChange:()=>A({mode:`subscription`,targets:t?k.targets.filter(t=>t!==e.id):[...k.targets,e.id]})}),(0,m.jsx)(`span`,{className:L.floatTargetLabel,children:e.label})]},e.id)}),ht.length===0&&(0,m.jsx)(`span`,{className:L.setCardDesc,children:n(`floatNoTargetsHint`)})]})]})]})]}),(0,m.jsxs)(`div`,{className:L.setCell,"data-testid":`billing-card-setting`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsxs)(`h3`,{className:L.setCardTitle,children:[n(`cardDisplay`),(0,m.jsx)(xa,{label:n(`cardDisplayHint`),t:n})]})})}),(0,m.jsxs)(`div`,{className:L.ctlCol,children:[(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardMetric`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-metric`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.metric===`money`&&L.floatModeBtnOn),"data-testid":`billing-card-money`,onClick:()=>re({...j,metric:`money`}),children:n(`cardMetricMoney`)}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.metric===`tokens`&&L.floatModeBtnOn),"data-testid":`billing-card-tokens`,onClick:()=>re({...j,metric:`tokens`}),children:n(`cardMetricTokens`)})]})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardSpan`)}),(0,m.jsx)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-span`,children:[[`day`,`cardSpanDay`],[`week`,`cardSpanWeek`],[`month`,`cardSpanMonth`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.span===e&&L.floatModeBtnOn),"data-testid":`billing-card-span-${e}`,"aria-pressed":j.span===e,onClick:()=>re({...j,span:e}),children:n(t)},e))})]}),(0,m.jsxs)(`div`,{className:L.ctlRow,children:[(0,m.jsx)(`span`,{className:L.ctlLabel,children:n(`cardDeltaBadge`)}),(0,m.jsxs)(`div`,{className:L.ctlGroup,"data-testid":`billing-card-delta`,children:[(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,j.showDelta&&L.floatModeBtnOn),"data-testid":`billing-card-delta-show`,"aria-pressed":j.showDelta,onClick:()=>re({...j,showDelta:!0}),children:n(`cardDeltaShow`)}),(0,m.jsx)(`button`,{type:`button`,className:y(L.floatModeBtn,!j.showDelta&&L.floatModeBtnOn),"data-testid":`billing-card-delta-hide`,"aria-pressed":!j.showDelta,onClick:()=>re({...j,showDelta:!1}),children:n(`cardDeltaHide`)})]})]})]})]})]})}),(0,m.jsx)(`div`,{hidden:z(ja.advanced),id:`settings-advanced`,children:(0,m.jsx)(Ea,{userPrices:a,onUserPrices:o,t:n,unpricedIds:e.unpricedModels??[]})}),(0,m.jsx)(`div`,{hidden:z(ja.about),id:`settings-about`,children:(0,m.jsx)(Jn,{t:n,version:e.pluginVersion})}),(0,m.jsxs)(`section`,{hidden:z(ja.about),className:L.setCard,"data-testid":`billing-more-works`,children:[(0,m.jsx)(`div`,{className:L.setCardHead,children:(0,m.jsx)(`div`,{className:L.setCardMeta,children:(0,m.jsx)(`h3`,{className:L.setCardTitle,children:n(`moreWorksTitle`)})})}),(0,m.jsxs)(`div`,{className:L.moreWorkList,children:[(0,m.jsxs)(`a`,{className:L.moreWorkRow,href:`https://github.com/kenz1117/dsh-engram`,target:`_blank`,rel:`noreferrer`,"data-testid":`billing-ad-engram`,children:[(0,m.jsx)(`span`,{className:L.moreWorkName,children:n(`adEngramName`)}),(0,m.jsx)(`span`,{className:L.moreWorkDesc,children:n(`adEngramDesc`)})]}),(0,m.jsxs)(`a`,{className:L.moreWorkRow,href:`https://github.com/kenz1117/dsh-ui-rainbowspeak`,target:`_blank`,rel:`noreferrer`,"data-testid":`billing-ad-rainbowspeak`,children:[(0,m.jsx)(`span`,{className:L.moreWorkName,children:n(`adRainbowName`)}),(0,m.jsx)(`span`,{className:L.moreWorkDesc,children:n(`adRainbowDesc`)})]})]})]})]})]})}),P===`trends`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-trends`,children:[(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-trend`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`trend`)}),x(`billing.dashboard.decor`,{position:`trend`}),(0,m.jsxs)(`span`,{className:L.ubCardControlGroup,children:[(0,m.jsx)(`span`,{className:L.rangeToggle,role:`group`,"aria-label":n(`trend`),children:[7,30].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,Le===e&&L.rangeButtonActive),"aria-pressed":Le===e,"data-testid":`billing-trend-${e}d`,onClick:()=>{Re(e)},children:n(e===7?`trend7d`:`trend30d`)},e))}),(0,m.jsx)(`span`,{className:L.rangeToggle,role:`group`,"aria-label":n(`trendMetric`),children:[`cost`,`tokens`].map(e=>(0,m.jsx)(`button`,{type:`button`,className:y(L.rangeButton,De===e&&L.rangeButtonActive),"aria-pressed":De===e,"data-testid":`billing-trend-metric-${e}`,onClick:()=>{Oe(e)},children:n(e===`cost`?`trendMetricCost`:`trendMetricTokens`)},e))})]}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:Rn})]}),(0,m.jsx)(zn,{data:Un,models:cr,currency:h,metric:De,t:n})]}),b.length>0&&(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-rounds`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`rounds`)}),ln.length>0&&(0,m.jsxs)(`span`,{className:L.ubTagError,"data-testid":`billing-rounds-flag-count`,children:[ln.length,` `,n(`anomaly`)]})]}),(0,m.jsx)(`p`,{className:L.ubCardSub,children:n(`roundsHint`).replace(`{count}`,String(b.length))}),(0,m.jsx)(Qn,{rounds:b,flags:ln,currency:h,t:n})]}),e.byTier!==void 0&&(()=>{let e=dn.peak+dn.offPeak;if(e<=0)return null;let t=dn.peak/e*100;return(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-share`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`peakShare`)}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:n(`peakSharePerCall`)})]}),(0,m.jsxs)(`div`,{className:L.shareTrack,"data-testid":`billing-share-track`,children:[(0,m.jsx)(`div`,{className:y(L.shareSeg,L.shareSegPeak),style:{width:`${t}%`}}),(0,m.jsx)(`div`,{className:y(L.shareSeg,L.shareSegOff),style:{width:`${100-t}%`}})]}),(0,m.jsxs)(`div`,{className:L.shareLegend,children:[(0,m.jsxs)(`span`,{className:L.shareItem,children:[(0,m.jsx)(`span`,{className:L.shareDot,style:{background:`var(--ds-blue)`}}),n(`peak`),(0,m.jsxs)(`span`,{className:L.shareValue,"data-testid":`billing-share-peak`,children:[U(dn.peak),` · `,t.toFixed(1),`%`]})]}),(0,m.jsxs)(`span`,{className:L.shareItem,children:[(0,m.jsx)(`span`,{className:L.shareDot,style:{background:`color-mix(in srgb, var(--ds-blue) 30%, var(--dsb-3))`}}),n(`offPeak`),(0,m.jsxs)(`span`,{className:L.shareValue,"data-testid":`billing-share-offpeak`,children:[U(dn.offPeak),` · `,(100-t).toFixed(1),`%`]})]})]}),pn>0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-share-savings`,children:n(`offPeakSavings`).replace(`{amount}`,U(pn))})]})})()]}),P===`providers`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-providers`,children:[Kn.length>0&&(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-relay-quota`,children:[(0,m.jsx)(`div`,{className:L.panelHead,children:(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`panelRelayQuota`)})}),(0,m.jsx)(`div`,{className:L.providerGroupList,"data-testid":`billing-relay-quotas`,children:Kn.map(e=>(0,m.jsxs)(`div`,{className:L.siteRow,"data-testid":`billing-relay-quota`,children:[(0,m.jsxs)(`span`,{className:L.siteRowName,children:[(0,m.jsx)(`span`,{className:y(L.siteKindTag,Ji[e.kind]),children:qi(e.kind,n)}),(0,m.jsx)(`span`,{className:L.siteRowTitle,children:e.origin})]}),(0,m.jsxs)(`span`,{className:L.siteRowMeta,children:[e.balance!==void 0&&(0,m.jsxs)(`span`,{className:L.siteRowCost,children:[n(`relayBalance`),` `,e.balance.toFixed(2)]}),(e.windows?.length??0)>0?e.windows?.map(e=>{let t=e.remainingPercent<20;return(0,m.jsxs)(`span`,{className:y(L.siteRowCalls,t&&L.siteRowCallsLow),children:[n(`relayWindowUsed`),` `,e.usedPercent,`%`]},e.kind)}):(0,m.jsx)(`span`,{className:L.siteRowCalls,children:n(`relayNoQuota`)})]})]},e.route))})]}),(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-providers`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`providerBilling`)}),x(`billing.dashboard.decor`,{position:`models`}),(0,m.jsx)(`span`,{className:L.panelHint,children:e.updatedAt===void 0?``:`${n(`lastUpdated`)} ${Zi(e.updatedAt)}`})]}),_e&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-subscriptions-stale`,children:n(`subscriptionsStale`)}),(0,m.jsxs)(`div`,{className:L.providerCtlRow,"data-testid":`billing-provider-controls`,children:[(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,disabled:Xn.length===0,onClick:$n,children:n(Zn?`collapseAll`:`expandAll`)}),(0,m.jsxs)(`span`,{className:L.providerTodayToggle,children:[(0,m.jsx)(`span`,{children:n(`todayOnly`)}),(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":It,"data-testid":`billing-provider-today-toggle`,className:y(L.switch,It&&L.switchOn),onClick:Rt,children:(0,m.jsx)(`span`,{className:L.switchKnob})})]})]}),Yn.length===0?(0,m.jsxs)(`div`,{className:L.emptyState,"data-testid":`billing-provider-empty`,children:[(0,m.jsxs)(`span`,{className:L.emptyIll,"aria-hidden":`true`,children:[(0,m.jsxs)(`svg`,{viewBox:`0 0 96 64`,fill:`none`,children:[(0,m.jsx)(`line`,{x1:`6`,y1:`58`,x2:`90`,y2:`58`,stroke:`var(--ds-border-strong)`,strokeWidth:`1`}),(0,m.jsx)(`line`,{x1:`6`,y1:`6`,x2:`6`,y2:`58`,stroke:`var(--ds-border-strong)`,strokeWidth:`1`}),(0,m.jsx)(`path`,{d:`M14 50 L28 40 L42 44 L56 26 L70 30 L82 14`,stroke:`var(--ds-border-strong)`,strokeWidth:`1.5`,strokeLinecap:`round`,fill:`none`,strokeDasharray:`3 3`})]}),(0,m.jsx)(`span`,{className:L.emptyIllDot})]}),(0,m.jsx)(`span`,{className:L.emptyTitle,children:n(It?`todayNoConsumption`:`noData`)}),(0,m.jsx)(`span`,{className:L.emptyDesc,children:n(`emptyHint`)})]}):(0,m.jsx)(`div`,{className:L.providerGroupList,"data-testid":`billing-provider-groups`,children:Yn.map(e=>{let t=e.models.length>0||e.subscriptions.length>0,r=t&&Nt.has(e.id);return(0,m.jsxs)(`div`,{className:L.providerGroup,"data-testid":`billing-provider-group`,children:[(0,m.jsxs)(`div`,{className:y(L.providerGroupHead,t&&L.providerGroupCollapsible),"data-testid":`billing-provider-group-head`,"aria-expanded":t?r:void 0,role:t?`button`:void 0,tabIndex:t?0:void 0,onClick:t?()=>{Ft(e.id)}:void 0,onKeyDown:t?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Ft(e.id))}:void 0,children:[(0,m.jsxs)(`span`,{className:L.providerGroupTitle,children:[(0,m.jsx)(`span`,{className:y(L.healthDot,e.dot),role:`img`,"aria-label":Sa(e.dot,n),title:Sa(e.dot,n)}),(()=>{let t=Zt(e.name),r=e.channelKind===`direct`?Cr(t):void 0,i=e.channelKind===`direct`?n(`directTag`):e.channelKind===`site`?n(`relayTag`):e.channelKind===`unknown`?n(`unknownTag`):void 0;return(0,m.jsxs)(m.Fragment,{children:[i!==void 0&&(0,m.jsx)(`span`,{className:y(L.kindBadge,e.channelKind===`site`&&L.kindBadgeRelay,e.channelKind===`unknown`&&L.kindBadgeUnknown),"data-testid":`billing-kind-badge`,children:i}),e.channelKind!==`unknown`&&(0,m.jsx)(`span`,{className:L.providerGroupName,children:r??t})]})})(),e.subscriptions.length>0&&(0,m.jsxs)(`span`,{className:L.providerGroupBadge,"data-testid":`billing-provider-sub-count`,children:[e.subscriptions.length,` `,n(`planCountUnit`)]})]}),(0,m.jsxs)(`span`,{className:L.providerGroupMeta,children:[(0,m.jsxs)(`span`,{className:L.providerGroupCost,"data-testid":`billing-provider-cost`,children:[(0,m.jsx)(`span`,{className:L.providerGroupCostLabel,children:n(`cost`)}),e.channelKind===`unknown`?(0,m.jsx)(`span`,{className:L.na,children:`—`}):(0,m.jsx)(`span`,{className:L.providerGroupCostValue,children:U(Yi(e))})]}),!xn(e)&&e.balance!==void 0?(0,m.jsxs)(`span`,{className:L.providerGroupBalance,"data-testid":`billing-provider-balance`,children:[(0,m.jsx)(`span`,{className:L.providerGroupBalanceLabel,children:n(`balance`)}),Sn(e.balance)]}):(0,m.jsx)(`span`,{className:L.providerGroupBalance,"aria-hidden":`true`}),Ei(e.name)===void 0?(0,m.jsx)(`span`,{className:L.providerGroupRecharge,"aria-hidden":`true`}):(0,m.jsx)(`a`,{className:L.providerGroupRecharge,"data-testid":`billing-group-recharge`,href:Ei(e.name),target:`_blank`,rel:`noreferrer`,title:n(`rechargeHint`),"aria-label":`${Zt(e.name)} ${n(`recharge`)}`,onClick:e=>{e.stopPropagation()},children:n(`recharge`)})]})]}),e.models.length>0&&(0,m.jsx)(`div`,{className:L.providerStatRow,"data-testid":`billing-provider-stat-row`,children:(()=>{let t=e.models.reduce((e,t)=>({calls:e.calls+t.calls,input:e.input+t.input,output:e.output+t.output}),{calls:0,input:0,output:0}),r=t.input>0?e.models.reduce((e,t)=>e+t.cacheHitRate,0)/e.models.length:0;return[{lbl:n(`calls`),val:t.calls.toLocaleString(),sub:``},{lbl:n(`inputTokens`),val:K(t.input),sub:r>0?`${n(`cacheHitRate`)} ${r.toFixed(0)}%`:``},{lbl:n(`outputTokens`),val:K(t.output),sub:``},{lbl:n(`cost`),val:U(Yi(e)),sub:e.models.length===1?``:`${e.models.length} ${n(`models`)}`}].map((e,t)=>(0,m.jsxs)(`div`,{className:L.providerStatCell,children:[(0,m.jsx)(`div`,{className:L.providerStatLbl,children:e.lbl}),(0,m.jsx)(`div`,{className:L.providerStatVal,children:e.val}),e.sub!==``&&(0,m.jsx)(`div`,{className:L.providerStatSub,children:e.sub})]},t))})()}),r&&(0,m.jsxs)(m.Fragment,{children:[e.channelKind===`unknown`&&(0,m.jsx)(`p`,{className:L.unknownHint,"data-testid":`billing-unknown-hint`,children:n(`unknownChannelHint`)}),e.models.length>0&&(0,m.jsx)(`div`,{className:L.tableScroll,"data-testid":`billing-table-scroll`,children:(0,m.jsxs)(`table`,{className:L.modelTable,children:[er,(0,m.jsx)(`tbody`,{children:e.models.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`td`,{children:tr(e)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:K(e.input)}),(0,m.jsx)(`td`,{className:L.numCol,children:K(e.output)}),(0,m.jsx)(`td`,{className:L.numCol,children:yn(e.cacheHitRate)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.plan?(0,m.jsxs)(`span`,{className:L.planTag,children:[e.estimated>0?(0,m.jsxs)(`span`,{children:[`≈`,U(e.estimated)]}):null,(0,m.jsx)(`span`,{className:L.planTagBadge,"data-testid":`billing-plan-badge`,children:n(`subscriptionTag`)})]}):e.actual===void 0?e.estimated>0?(0,m.jsxs)(`span`,{title:n(`cellEstimateHint`),children:[`≈`,U(e.estimated)]}):(0,m.jsx)(`span`,{className:L.na,children:`—`}):(()=>{let t=e.officialCost,n=e.actual-t;return t>0&&n>0?(0,m.jsxs)(`span`,{className:L.bucketCost,children:[(0,m.jsx)(`span`,{className:L.bucketOfficial,children:U(t)}),(0,m.jsx)(`span`,{className:L.bucketSep,children:`/`}),(0,m.jsx)(`span`,{className:L.bucketThird,children:U(n)})]}):U(e.actual)})()})]},e.key))})]})}),e.subscriptions.length>0&&(0,m.jsx)(`div`,{className:L.subscriptionGrid,"data-testid":`billing-subscriptions-grid`,children:e.subscriptions.map(e=>{let t=Gi(e.status,n);return(0,m.jsxs)(`div`,{className:y(L.subscriptionCard,L.subscriptionCardUpgraded),"data-testid":`billing-subscription-card`,children:[(0,m.jsxs)(`div`,{className:L.subscriptionHead,children:[(0,m.jsx)(`span`,{className:L.subscriptionName,children:Zt(e.displayName)}),e.planType===`code`&&(()=>{let t=lt(e.provider),r=t===void 0?void 0:n(`subscriptionFeePerMonth`).replace(`{amount}`,t.currency===`USD`?`$${t.amount}`:`¥${t.amount}`);return(0,m.jsxs)(`span`,{className:L.subscriptionPlan,"data-kind":`code`,children:[r??(e.subscriptionAmount!==void 0&&e.subscriptionAmount>0?n(`subscriptionFeePerMonth`).replace(`{amount}`,U(e.subscriptionAmount)):n(`planTypeCode`)),t?.label!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionTier,"data-testid":`billing-tier-${e.provider}`,children:t.label}),t!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionAuto,"data-testid":`billing-auto-${e.provider}`,children:n(`subscriptionAutoDetect`)})]})})(),e.planType===`token`&&(0,m.jsx)(`span`,{className:L.subscriptionPlan,"data-kind":`token`,children:n(`planTypeToken`)}),e.plan!==void 0&&(0,m.jsx)(`span`,{className:L.subscriptionPlan,children:e.plan})]}),t!==``&&(0,m.jsx)(`div`,{className:L.subscriptionStatus,children:t}),e.windows.length===0&&t===``&&(0,m.jsx)(`div`,{className:L.subscriptionStatus,children:n(`subscriptionNoApi`)}),e.windows.map(e=>(0,m.jsx)(ba,{window:e,t:n},e.kind))]},e.provider)})})]})]},e.id)})})]}),(0,m.jsxs)(`div`,{className:L.exportBar,"data-testid":`billing-export-bar`,role:`group`,"aria-label":n(`export`),children:[(0,m.jsx)(`span`,{className:L.exportLabel,children:n(`export`)}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-day`,onClick:()=>{On(Dn(`usage-daily`,`csv`,Object.keys(N)),Cn(N),`text/csv`)},children:n(`exportCsvDay`)}),e.bySession!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-sessions`,onClick:()=>{On(Dn(`usage-sessions`,`csv`,Object.keys(N)),En(e.bySession??[]),`text/csv`)},children:n(`exportCsvSession`)}),e.bySite!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-sites`,onClick:()=>{On(Dn(`usage-sites`,`csv`,Object.keys(N)),wn(e.bySite??{}),`text/csv`)},children:n(`exportCsvSite`)}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-export-json`,onClick:()=>{On(Dn(`usage-stats`,`json`,Object.keys(N)),JSON.stringify(e,null,2),`application/json`)},children:n(`exportJson`)})]}),e.bySession!==void 0&&(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-sessions`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`sessions`)}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:e.bySession.length>20?n(`sessionOverflow`).replace(`{limit}`,`20`).replace(`{total}`,String(At)):`${At}`}),e.bySession.length>0&&(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-sessions-view-all`,onClick:()=>{H(!0)},children:n(jt?`sessionsViewTop`:`sessionsViewAll`).replace(`{count}`,String(e.bySession.length))})]}),(e.staleLedgerSessions??0)>0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-sessions-stale`,children:n(`staleLedgerNotice`).replace(`{count}`,String(e.staleLedgerSessions))}),(0,m.jsxs)(`div`,{className:L.ubTablewrap,"data-testid":`billing-sessions-table`,children:[we!==void 0&&(0,m.jsx)(`div`,{className:L.staleNotice,"data-testid":`billing-session-nav-notice`,role:`note`,children:we}),(0,m.jsxs)(`table`,{className:L.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`sessionTitle`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`calls`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`actual`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`lastActive`)})]})}),(0,m.jsxs)(`tbody`,{children:[wt.length===0&&(0,m.jsx)(`tr`,{children:(0,m.jsx)(`td`,{colSpan:4,className:L.emptyRow,children:n(`noData`)})}),wt.slice(0,20).map(e=>{let t=e.children!==void 0||e.subs!==void 0,r=t&&vt.has(e.id),i=Xi(e);return(0,m.jsxs)(d.Fragment,{children:[(0,m.jsxs)(`tr`,{className:t?L.sessionGroupRow:void 0,"aria-expanded":t?r:void 0,tabIndex:t?0:void 0,onClick:t?()=>{Ct(e.id)}:void 0,onKeyDown:t?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Ct(e.id))}:void 0,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:L.modelName,children:(0,m.jsxs)(`button`,{type:`button`,className:L.sessionLink,"data-testid":`billing-session-open`,title:n(`sessionOpen`),onClick:t=>{t.stopPropagation(),Ee(e.id)},children:[e.title??`${n(`sessionUntitled`)} · ${e.id.slice(0,8)}`,(e.mergedCount??1)>1?` ×${e.mergedCount}`:``]})}),e.stale===!0&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-session-stale`,children:n(`sessionStaleBadge`)}),(i.calls>0||i.cost>0)&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),"data-testid":`billing-session-sub`,children:i.cost>0?n(`sessionSubCost`).replace(`{cost}`,U(i.cost)):n(`sessionSubCalls`).replace(`{calls}`,i.calls.toLocaleString())})]}),Tt(e)]}),r&&e.children?.map(e=>(0,m.jsxs)(`tr`,{className:L.sessionChildRow,children:[(0,m.jsx)(`td`,{children:(0,m.jsx)(`button`,{type:`button`,className:L.sessionLink,"data-testid":`billing-session-open`,title:n(`sessionOpen`),onClick:t=>{t.stopPropagation(),Ee(e.id)},children:(0,m.jsx)(`span`,{className:L.modelProvider,children:e.id.slice(0,8)})})}),Tt(e)]},e.id)),r&&e.subs?.map(e=>Dt(e,0))]},e.id)})]})]})]}),bt&&(0,m.jsxs)(`div`,{className:L.sessionViewer,"data-testid":`billing-session-viewer`,children:[(0,m.jsxs)(`div`,{className:L.sessionViewerHead,children:[(0,m.jsx)(`h3`,{className:L.sessionViewerTitle,children:n(`sessions`)}),(0,m.jsx)(`input`,{className:L.ubSearch,type:`search`,value:xt,placeholder:n(`sessionViewerSearch`),"aria-label":n(`sessionViewerSearch`),"data-testid":`billing-session-viewer-search`,onChange:e=>{St(e.target.value)}}),(0,m.jsx)(`button`,{type:`button`,className:L.exportButton,"data-testid":`billing-session-viewer-close`,onClick:()=>{H(!1),St(``)},children:n(`close`)})]}),(0,m.jsx)(`div`,{className:L.sessionViewerList,"data-testid":`billing-session-viewer-list`,children:(0,m.jsxs)(`table`,{className:L.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`sessionTitle`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`calls`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`actual`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`lastActive`)})]})}),(0,m.jsxs)(`tbody`,{children:[Ot.length===0&&(0,m.jsx)(`tr`,{children:(0,m.jsx)(`td`,{colSpan:4,className:L.emptyRow,children:n(`noData`)})}),Ot.map(e=>(0,m.jsxs)(`tr`,{children:[(0,m.jsxs)(`td`,{children:[(0,m.jsxs)(`span`,{className:L.modelName,children:[e.title??`${n(`sessionUntitled`)} · ${e.id.slice(0,8)}`,(e.mergedCount??1)>1?` ×${e.mergedCount}`:``]}),e.cwd!==void 0&&(0,m.jsx)(`span`,{className:L.modelProvider,children:Aa(e.cwd)}),e.stale===!0&&(0,m.jsx)(`span`,{className:y(L.ubTag,L.ubTagNeutral),children:n(`sessionStaleBadge`)})]}),(0,m.jsx)(`td`,{className:L.numCol,children:e.calls.toLocaleString()}),(0,m.jsx)(`td`,{className:L.numCol,children:U(e.cost)}),(0,m.jsx)(`td`,{className:L.numCol,children:e.lastActive>0?`${G(e.lastActive)} ${Zi(e.lastActive)}`:`—`})]},e.id))]})]})})]})]})]}),P===`token`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-token`,children:[(0,m.jsx)(Pn,{stats:e,trendDays:Le,onTrendDays:Re,models:cr,money:U,channelName:qn,t:n}),e.perf!==void 0&&(0,m.jsxs)(`section`,{className:L.panel,"data-testid":`billing-panel-perf`,children:[(0,m.jsxs)(`div`,{className:L.panelHead,children:[(0,m.jsx)(`h3`,{className:L.panelTitle,children:n(`perfTitle`)}),(0,m.jsx)(`span`,{className:L.panelHint,children:n(`perfHint`)})]}),(0,m.jsx)(Gn,{perf:e.perf,models:cr,t:n})]})]}),P===`pricing`&&(0,m.jsxs)(`div`,{className:L.tabPanel,"data-testid":`billing-tab-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:L.ubAlert,role:`note`,children:[(0,m.jsxs)(`div`,{className:L.ubAlertLeft,children:[(0,m.jsxs)(`span`,{className:L.ubRate,"data-testid":`billing-rate`,children:[n(`todayRate`),` 1 USD = `,W(Wt.rate)]}),(0,m.jsx)(`span`,{className:y(L.ubTag,Wt.live?L.ubTagSuccess:L.ubTagNeutral),children:Wt.live?n(`rateLive`):n(`rateBuiltin`)}),Jt>0&&(0,m.jsxs)(`span`,{className:L.ubTag,"data-testid":`billing-pricing-synced`,children:[n(`pricingSyncedAt`),` `,new Date(Jt).toLocaleTimeString(Xt===`zh`?`zh-CN`:`en-US`,{hour:`2-digit`,minute:`2-digit`})]}),(0,m.jsx)(`button`,{type:`button`,className:L.heatmapRangeButton,"data-testid":`billing-pricing-sync`,disabled:Gt,onClick:qt,children:n(Gt?`pricingSyncing`:`pricingSyncNow`)})]}),(0,m.jsx)(`p`,{className:L.ubAlertNote,children:n(`pricingTip`)})]}),(0,m.jsxs)(`section`,{className:L.ubCard,"data-testid":`billing-panel-pricing`,children:[(0,m.jsxs)(`div`,{className:L.ubCardHead,children:[(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`pricing`)}),(0,m.jsx)(`span`,{className:L.ubCardSub,children:n(`pricingUnit`)}),(0,m.jsx)(`input`,{className:L.ubSearch,type:`search`,value:Qt,placeholder:n(`pricingSearch`),"aria-label":n(`pricingSearch`),"data-testid":`billing-pricing-search`,onChange:e=>{$t(e.target.value)}})]}),(0,m.jsx)(`div`,{className:y(L.ubTablewrap,L.ubTablewrapPricing),"data-testid":`billing-pricing-table`,children:(0,m.jsxs)(`table`,{className:L.ubTable,children:[(0,m.jsx)(`thead`,{children:(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{children:n(`thModel`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`thInputMiss`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`thInputHit`)}),(0,m.jsx)(`th`,{className:L.numCol,children:n(`output`)}),(0,m.jsx)(`th`,{className:L.numCol,colSpan:2,children:n(`band`)})]})}),(0,m.jsx)(`tbody`,{children:mr(fn(),Qt).map(e=>{let t=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:L.ubModel,children:[(()=>{let t=dr(Bt(nn,zt(e.key,an)),on);if(t===null)return null;let r=en.includes(e.key),i=`${e.name} · ${n(t===`peak`?`peak`:`offPeak`)} · ${n(`bandPinHint`)}`;return(0,m.jsx)(`button`,{type:`button`,className:y(L.bandDot,L[t],r&&L.bandDotOn),"data-testid":`billing-band-dot`,"aria-pressed":r,"aria-label":i,title:i,onClick:()=>{tn(ze(e.key)),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.pinned-pref`))}})})(),(0,m.jsxs)(`span`,{className:L.ubModelName,children:[e.name,e.uncatalogued&&(0,m.jsx)(`span`,{className:L.ubTagAlert,"data-testid":`billing-price-uncatalogued`,children:n(`uncatalogued`)}),e.promo!==void 0&&un(e.promo,Date.now())&&(0,m.jsx)(p.Tooltip,{label:[e.promo.note,e.promo.endsAtMs===void 0?n(`promoOpenEnded`):n(`promoUntil`,{date:new Date(e.promo.endsAtMs).toLocaleDateString()})].filter(Boolean).join(` · `),side:`top`,maxWidth:280,children:(0,m.jsx)(`span`,{className:L.ubTagPromo,"data-testid":`billing-price-promo`,children:n(`promoBadge`)})})]})]})}),(0,m.jsx)(`td`,{className:L.numCol,children:t?sn(e.price.input,e.price.currency):(0,m.jsx)(`span`,{className:L.na,children:`—`})}),(0,m.jsx)(`td`,{className:L.numCol,children:t?sn(e.price.cacheHit,e.price.currency):(0,m.jsx)(`span`,{className:L.na,children:`—`})}),(0,m.jsx)(`td`,{className:L.numCol,children:t?sn(e.price.output,e.price.currency):(0,m.jsx)(`span`,{className:L.na,children:`—`})}),t&&e.price.offPeak!==void 0&&e.peakHours!==void 0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`td`,{className:L.numCol,children:(0,m.jsxs)(`span`,{className:L.ubChipPeak,children:[(0,m.jsx)(`span`,{className:L.ubChipLabel,children:e.tierSemantics===`latency`?n(`ubStd`):n(`ubPeak`)}),(0,m.jsxs)(`span`,{children:[sn(e.price.input,e.price.currency),`/`,sn(e.price.output,e.price.currency)]})]})}),(0,m.jsx)(`td`,{className:L.numCol,children:(0,m.jsxs)(`span`,{className:L.ubChipOff,children:[(0,m.jsx)(`span`,{className:L.ubChipLabel,children:e.tierSemantics===`latency`?`Flex`:n(`ubOff`)}),(0,m.jsxs)(`span`,{children:[sn(e.price.offPeak.input,e.price.currency),` / `,sn(e.price.offPeak.output,e.price.currency)]})]})})]}):(0,m.jsx)(`td`,{className:L.numCol,colSpan:2,children:t?(0,m.jsx)(`span`,{className:L.flatTag,children:n(`flat`)}):(0,m.jsx)(`span`,{className:L.na,children:`—`})})]}),(e.extraRows??[]).map(t=>(0,m.jsxs)(`tr`,{className:L.ubExtraRow,children:[(0,m.jsxs)(`td`,{children:[(0,m.jsx)(`span`,{className:L.ubExtraName,children:pr(t.label,Xt)}),t.note!==void 0&&(0,m.jsx)(`span`,{className:L.ubExtraNote,children:pr(t.note,Xt)})]}),(0,m.jsx)(`td`,{className:L.numCol,children:t.input===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):sn(t.input,e.price.currency)}),(0,m.jsx)(`td`,{className:L.numCol,children:(0,m.jsx)(`span`,{className:L.na,children:`—`})}),(0,m.jsx)(`td`,{className:L.numCol,children:t.output===void 0?(0,m.jsx)(`span`,{className:L.na,children:`—`}):sn(t.output,e.price.currency)}),(0,m.jsx)(`td`,{className:L.numCol,colSpan:2,children:(0,m.jsx)(`span`,{className:L.na,children:`—`})})]},`${e.key}:${t.label}`))]},e.key)})})]})})]}),(0,m.jsxs)(`section`,{className:L.ubCard,children:[(0,m.jsx)(`div`,{className:L.ubCardHead,children:(0,m.jsx)(`h3`,{className:L.ubCardTitle,children:n(`pricingNotes`)})}),(0,m.jsxs)(`ul`,{className:L.ubNotes,children:[(0,m.jsxs)(`li`,{className:L.ubNotesItem,children:[(0,m.jsx)(`span`,{className:L.ubNotesTerm,children:n(`cacheHit`)}),(0,m.jsx)(`span`,{className:L.ubNotesDesc,children:n(`noteCache`)})]}),(0,m.jsxs)(`li`,{className:L.ubNotesItem,children:[(0,m.jsx)(`span`,{className:L.ubNotesTerm,children:n(`peakBand`)}),(0,m.jsx)(`span`,{className:L.ubNotesDesc,children:n(`noteBand`)})]}),(0,m.jsxs)(`li`,{className:L.ubNotesItem,children:[(0,m.jsx)(`span`,{className:L.ubNotesTerm,children:n(`pricingSource`)}),(0,m.jsx)(`span`,{className:L.ubNotesDesc,children:n(`noteSource`)})]})]})]})]}),!i&&x(`billing.dashboard.decor`,{position:`footer`})]}),!i&&(0,m.jsxs)(`footer`,{className:L.modalFooter,"data-testid":`billing-footer`,children:[(0,m.jsx)(`span`,{children:n(`footer`)}),(0,m.jsx)(`span`,{children:n(`footerCredit`).replace(`{version}`,e.pluginVersion===void 0?`—`:`v${e.pluginVersion}`)})]})]});return i?fr:(0,m.jsx)(p.Modal,{open:!0,onClose:r,title:n(`title`),headless:!0,className:y(L.dashboardModal,`dsh-billing-modal`,zr),children:fr})}function Aa(e){return e.split(/[\\/]/).filter(Boolean).at(-1)??`—`}let ja={display:[`显示`,`密度`,`动效`,`紧凑`,`舒适`,`克制`,`丰富`,`display`,`density`,`motion`,`compact`,`comfortable`],budget:[`预算`,`金额`,`本月`,`花费`,`进度`,`budget`,`amount`,`spend`,`progress`],alert:[`峰谷`,`峰`,`谷`,`提醒`,`通知`,`预览`,`切换`,`peak`,`off-peak`,`alert`,`notify`,`preview`],toggles:[`usage_stats`,`工具`,`即时代费`,`胶囊`,`中转站`,`站点`,`隐藏`,`低谷`,`队列`,`relay`,`site`,`live`,`cost`,`hide`,`queue`,`off-peak`],displayExtra:[`悬浮`,`订阅`,`计费卡`,`指标`,`环比`,`主数字`,`侧栏`,`入口`,`隐藏`,`通道`,`可见`,`float`,`subscription`,`card`,`metric`,`delta`,`sidebar`,`trigger`,`hidden`,`channel`,`visibility`],advanced:[`自定义`,`单价`,`价格`,`低谷`,`custom`,`price`],about:[`关于`,`版本`,`作者`,`许可`,`仓库`,`about`,`version`,`author`,`license`,`repo`]};function Ma(e){return Object.values(ja).every(t=>Ui(e,t))}let Na=[`below`,`above`,`toolbar`];function Pa({liveCostPrefs:e,onLiveCostPrefs:t,t:n}){let[r,i]=(0,d.useState)(!1),a={below:n(`liveCostBarPosBelow`),above:n(`liveCostBarPosAbove`),toolbar:n(`liveCostBarPosToolbar`)},o=Na.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=Na.find(e=>e===n);r!==void 0&&t({...e,position:r})},onClose:()=>{i(!1)},anchor:(0,m.jsxs)(`button`,{type:`button`,className:L.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(L.rdoChevron,r&&L.rdoChevronOpen),"aria-hidden":!0,children:Jr?(0,m.jsx)(Jr,{}):null})]})})}function Fa(e){let{t,checkModels:n,publishCosts:r,registerOpen:i,navigateToSession:a,sessionTitleOf:o,renderSlot:s,useStore:c,actions:l,embeddedSettings:u=!1}=e,[f,p]=(0,d.useState)(Br),[h,g]=(0,d.useState)(void 0),[_,v]=(0,d.useState)(Ur),[y,b]=(0,d.useState)([]),[x,S]=(0,d.useState)(void 0),[C,w]=(0,d.useState)(!1),[T,E]=(0,d.useState)([]),[D,O]=(0,d.useState)(!1),[ie,ae]=(0,d.useState)([]),[oe,se]=(0,d.useState)(()=>Ee()),[ce,le]=(0,d.useState)(()=>Le()),ue=(0,d.useCallback)(e=>{le(e),Re(e),window.dispatchEvent(new CustomEvent(`dsh.ui-usage-billing.language-pref`))},[]),de=(0,d.useCallback)(e=>{se(e),De(e),window.dispatchEvent(new CustomEvent(Te))},[]),[fe,pe]=(0,d.useState)(()=>ee()),M=(0,d.useCallback)(e=>{pe(e),te(e)},[]),[ge,ye]=(0,d.useState)(()=>me()),be=(0,d.useCallback)(e=>{ye(e),he(e)},[]),[we,Oe]=(0,d.useState)(()=>Se()),ke=(0,d.useCallback)(e=>{Oe(e),Ce(e),window.dispatchEvent(new CustomEvent(xe))},[]),[Ae,je]=(0,d.useState)(()=>nt());(0,d.useEffect)(()=>{let e=()=>{je(nt())};return window.addEventListener(tt,e),()=>{window.removeEventListener(tt,e)}},[]);let N=(0,d.useCallback)(e=>{let t={...nt(),showEntry:e.showEntry,reuseSourceSession:e.reuseSourceSession};je(t),rt({showEntry:t.showEntry,reuseSourceSession:t.reuseSourceSession})},[]),[Me,Ne]=(0,d.useState)(()=>k());(0,d.useEffect)(()=>j(()=>{Ne(k())}),[]);let P=e.recoveryEntryAvailable,Pe=(0,d.useMemo)(()=>({...Me,mode:re(Me.mode,P)}),[Me,P]),Fe=(0,d.useCallback)(e=>{let t={...e,mode:re(e.mode,P)};Ne(t),A(t),window.dispatchEvent(new CustomEvent(ne))},[P]),[Ie,ze]=(0,d.useState)(()=>{let e=Ve();return _t(e),e}),Be=(0,d.useCallback)(e=>{ze(e),_t(e),He(e)},[]),[Ue,We]=(0,d.useState)(()=>_e()),Ge=(0,d.useCallback)(e=>{We(e),ve(e)},[]),Ke=(0,d.useMemo)(()=>new Set(Ue.hidden),[Ue.hidden]),qe=(0,d.useMemo)(()=>Ni(f,Ke),[f,Ke]),F=(0,d.useMemo)(()=>Di(qe),[qe,Ie]),Je=ce,I=(0,d.useCallback)((e,n)=>{let r=(Je===`en`?st:ot)[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},[Je,t]),Ye=(0,d.useMemo)(()=>Mi(ji(f),e=>xr(e,Je)??I(`channelUnknown`)),[f,Je,I]),[Xe,Ze]=(0,d.useState)(!1),Qe=(0,d.useCallback)(()=>{Ze(!1)},[]),$e=(0,d.useRef)(!1),et=(0,d.useCallback)((e=!1)=>{$e.current&&!e||($e.current=!0,Promise.all([$i().then(e=>{e.ok?(p(e.stats),g(e.stats.sessionListError)):g(e.reason)}),ea().then(({balances:e,reconcile:t,stale:n})=>{e.length>0&&b(e),S(t),w(n===!0)}),ta().then(({quotas:e,stale:t})=>{e.length>0?(E(e),O(t===!0)):O(!1)}).catch(()=>{O(!0)}),na().then(e=>{ae(e)}).catch(()=>{})]).catch(()=>{}).finally(()=>{$e.current=!1}))},[]),it=(0,d.useCallback)(()=>{et(!0),sa(),Ze(!0)},[et]);(0,d.useEffect)(()=>{et(),sa()},[et]);let[L,at]=(0,d.useState)(()=>typeof document>`u`||!document.hidden);(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{at(!document.hidden),document.hidden||(et(!0),sa())};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[et]),(0,d.useEffect)(()=>{if(!L)return;let e=setInterval(()=>{et(),sa()},Xe?Rr:3e5);return()=>{clearInterval(e)}},[et,Xe,L]),(0,d.useEffect)(()=>{let e=!0;return n().then(t=>{e&&(v(t),Ct(t.catalog??[]))}),()=>{e=!1}},[n]);let R=G(),z=Object.entries(F.byDay).filter(([e])=>e.startsWith(R.slice(0,7))).reduce((e,[,t])=>e+t.cost,0),ct=F.byDay[R]?.cost??0,lt=new Date;lt.setDate(lt.getDate()-1);let ut=`${lt.getFullYear()}-${String(lt.getMonth()+1).padStart(2,`0`)}-${String(lt.getDate()).padStart(2,`0`)}`,dt=F.byDay[ut]?.cost??0,B=dt>0?(ct-dt)/dt*100:0,ft=ni(F.byDay,R),V=(0,d.useMemo)(()=>ti(F.byDay).map(e=>{let t=F.byDay[e.date];return{date:e.date,cost:e.cost,tokens:t===void 0?0:ei(t)}}),[F.byDay]),pt=Object.entries(F.byDay).filter(([e])=>e.startsWith(R.slice(0,7))).reduce((e,[,t])=>e+ei(t),0),mt=(()=>{let e=F.byDay[R];return e===void 0?0:ei(e)})(),ht=ni(F.byDay,R,ei),gt=c(e=>e.enabled),vt=c(e=>e.amount),yt=c(e=>e.tierAlertDays),bt=c(e=>e.lastTierSwitchAt),[H,xt]=(0,d.useState)(()=>Pr()),[St,wt]=(0,d.useState)(null),[Tt,Dt]=(0,d.useState)(null),[Ot,At]=(0,d.useState)(0),[jt,Mt]=(0,d.useState)(!1);(0,d.useEffect)(()=>{if(!H.enabled){At(0),Mt(!1);return}let e=!1,t=!1;Mt(!1);let n=()=>{t||(t=!0,da().then(t=>{e||At(t.supported?t.queuedCount:0)}).catch(()=>{e||At(0)}).finally(()=>{t=!1,e||Mt(!0)}))};n();let r=setInterval(n,Rr);return()=>{e=!0,clearInterval(r)}},[H.enabled]),(0,d.useEffect)(()=>{wt(e=>Nr(e,Ot))},[Ot]);let[Nt,Pt]=(0,d.useState)(()=>Date.now());(0,d.useEffect)(()=>{if(!H.enabled)return;let e=setInterval(()=>Pt(Date.now()),Rr);return()=>{clearInterval(e)}},[H.enabled]);let Ft=(0,d.useCallback)(e=>{xt(e),Fr(e)},[]),It=T.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`),Lt=zt(f.byTurn?.[0]?.model,It),Rt=(0,d.useCallback)(()=>{Dt({entering:kt(Date.now())===`peak`?`offPeak`:`peak`,atMs:Date.now()+18e4,channel:Lt})},[Lt]),Bt=vt>0?vt:f.budget??0,Vt=gt&&Bt>0?z/Bt>=1?`over`:z/Bt>=.8?`warn`:`none`:`none`,Ht=(0,d.useCallback)(()=>{let e=!gt;l.setEnabled(e),e&&typeof Notification<`u`&&Notification.permission==="default"&&Notification.requestPermission()},[l,gt]);(0,d.useEffect)(()=>{if(!gt||Bt<=0)return;let e=z/Bt*100,t=Lr.filter(t=>e>=t&&yt?.[String(t)]!==R);if(t.length===0)return;let n=t[t.length-1]??100;if(l.markTierAlerted(t,R),!Fi())return;let r=I(`budgetTierBody`).replace(`{cost}`,W(z)).replace(`{budget}`,W(Bt)).replace(`{pct}`,String(n));Ii(`budget:${n}:${R}`,()=>{new Notification(I(`budget`),{body:r})})},[gt,Bt,z,yt,R,l,I]),(0,d.useEffect)(()=>{if(H.enabled&&!jt)return;let e=Mr(Ir(Nt,H,bt,Lt),Ot>0?Ir(Nt,H,bt,`deepseek-metered`):null,Ot);if(e===null||(l.markTierSwitchAlerted(e.atMs),wt(e),!H.webNotify||!Fi()))return;let t=Math.max(1,Math.round((e.atMs-Nt)/6e4)),n=I(e.entering===`peak`?`peakAlertTitlePeak`:`peakAlertTitleOff`),r=I(e.channel===`zhipu-coding-plan`?e.entering===`peak`?`tierAlertEnterPeakZhipu`:`tierAlertEnterOffZhipu`:e.entering===`peak`?`tierAlertEnterPeak`:`tierAlertEnterOff`).replace(`{minutes}`,String(t)),i=e.queueCount===void 0?``:` ${I(e.entering===`peak`?`peakAlertQueuePeak`:`peakAlertQueueOff`,{count:e.queueCount})}`;Ii(`peak:${e.atMs}`,()=>{new Notification(n,{body:`${r}${i}`})})},[Nt,bt,H,Lt,Ot,jt,l,I]);let Ut=c(e=>e.lastBalanceAlertDay),Wt=c(e=>e.modelBudgets??cr),Gt=c(e=>e.modelTierAlertDays??lr),Kt=(0,d.useMemo)(()=>oi(F.byDayModels,R.slice(0,7)),[F.byDayModels,R]),qt=F.lowBalanceThreshold??50,Jt=(0,d.useMemo)(()=>{if(y.length===0)return;let e=Yr(F.byDay,R),t=Et().rate;for(let n of y){if(n.totalBalance===void 0||n.error!==void 0)continue;let r=n.currency===`USD`?n.totalBalance*t:n.totalBalance;if(r>=qt)continue;let i=e>0?Math.floor(r/e):void 0;return{name:n.displayName,cny:r,days:i}}},[y,F.lowBalanceThreshold,F.byDay,R]);(0,d.useEffect)(()=>{if(Jt===void 0||Ut===R||(l.markBalanceAlerted(R),!Fi()))return;let e=I(`balanceLowBody`).replace(`{name}`,Jt.name).replace(`{balance}`,W(Jt.cny)).replace(`{days}`,Jt.days===void 0?`—`:String(Jt.days));Ii(`balance:${R}`,()=>{new Notification(I(`balance`),{body:e})})},[Jt,Ut,R,l,I]),(0,d.useEffect)(()=>{let e=[],t;for(let[n,r]of Object.entries(Wt)){if(!(r>0))continue;let i=Kt[n]??0;for(let a of ci(i,r)){let o=`${n}:${a}`;Gt[o]!==R&&(e.push(o),(t===void 0||a>t.tier)&&(t={model:n,tier:a,cost:i,budget:r}))}}if(e.length===0||t===void 0||(l.markModelTierAlerted(e,R),!Fi()))return;let n=I(`modelBudgetBody`).replace(`{model}`,t.model).replace(`{cost}`,W(t.cost)).replace(`{budget}`,W(t.budget)).replace(`{pct}`,String(t.tier));Ii(`model-budget:${t.model}:${t.tier}:${R}`,()=>{new Notification(I(`modelBudgetTitle`),{body:n})})},[Wt,Kt,Gt,R,l,I]);let U=(0,d.useMemo)(()=>{let e=R.slice(0,7),t=new Map;for(let[n,r]of Object.entries(F.byDayModels??{}))if(n.startsWith(e))for(let[e,n]of Object.entries(r)){if(n.cost<=0)continue;let r=cn(e).provider,i=F.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=y.find(t=>Z(t.provider)===Z(e));if(t===void 0||t.totalBalance===void 0){if(e===`Custom`){let e=y.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`?I(`balanceUnauthorized`):t?.error===`unreachable`||t?.error===`invalid`?I(`balanceUnreachable`):I(`balanceUnconfigured`),low:!1}}let n=t.currency===`USD`?`$${t.totalBalance.toFixed(2)}`:W(t.totalBalance),r=Et().rate;return{text:n,low:(t.currency===`USD`?t.totalBalance*r:t.totalBalance)<qt}},a=e=>{let t=T.find(t=>t.displayName===e||mi(t.provider)===e);if(t===void 0||t.windows.length===0)return{text:I(`subscriptionNoApi`),low:!1};let n=t.windows.reduce((e,t)=>Math.min(e,t.remainingPercent),100);return{text:n<=0?I(`subscriptionExhausted`):I(`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])}}},[F.byDayModels,F.byModel,F.lowBalanceThreshold,y,T,R,I]),Yt=(0,d.useMemo)(()=>{let e=F.total;return{input:e.input,output:e.output,cacheRead:e.cacheHit,cacheMiss:e.cacheMiss,calls:e.calls}},[F]);(0,d.useEffect)(()=>{r({todayCost:ct,monthCost:z})},[ct,z,r]),(0,d.useEffect)(()=>{if(!u)return i(it)},[u,i,it]);let Xt=(0,d.useMemo)(()=>f.byTurn??[],[f.byTurn]);return(0,m.jsxs)(m.Fragment,{children:[!u&&(0,m.jsx)(Ca,{...e,t:I,currency:oe,onOpen:it,monthCost:z,todayCost:ct,weekCost:ft,days:V,vendorStatus:U,dash:Yt,cardPrefs:Pe,monthTokens:pt,todayTokens:mt,weekTokens:ht,floatPrefs:fe,subscriptions:T,budgetPressure:Vt,deltaPct:B,...h===void 0?{}:{statsError:h}}),(u||Xe)&&(0,m.jsx)(ka,{stats:F,...h===void 0?{}:{statsError:h},t:I,onClose:Qe,embeddedSettings:u,navigateToSession:a,sessionTitleOf:o,userPrices:Ie,onUserPrices:Be,health:_,balances:y,...x===void 0?{}:{reconcile:x},quotas:T,relayQuotas:ie,currency:oe,onCurrency:de,language:ce,onLanguage:ue,turns:Xt,renderSlot:s,budgetEnabled:gt,budgetAmount:Bt,modelBudgets:Wt,monthModelCost:Kt,onModelBudget:l.setModelBudget,onToggleBudget:Ht,onBudgetAmount:l.setAmount,peakConfig:H,onPeakConfig:Ft,onPreviewPeak:Rt,floatPrefs:fe,onFloatPrefs:M,cardPrefs:Pe,onCardPrefs:Fe,recoveryEntryAvailable:P,sitePrefs:ge,onSitePrefs:be,channelPrefs:Ue,onChannelPrefs:Ge,channelGroups:Ye,liveCostPrefs:we,onLiveCostPrefs:ke,quickQueuePrefs:Ae,onQuickQueuePrefs:N,quotasStale:D,balanceStale:C}),(St!==null||Tt!==null)&&(0,m.jsx)(Hr,{hit:St??Tt,config:H,t:I,onDismiss:()=>{wt(null),Dt(null)}})]})}function Ia(e){return(0,m.jsx)(`div`,{className:y(L.nativeSettingsRoot,zr),"data-testid":`native-billing-settings`,children:(0,m.jsx)(Fa,{...e,renderSlot:()=>null,wide:!0,embeddedSettings:!0})})}function La(e,t){if(t===void 0||e?.bySession===void 0)return 0;let n=e.bySession.find(e=>e.id===t);return(n?.cost??0)+(n?.subCost??0)}function Ra(e,t){return t===void 0||e?.bySession===void 0?0:e.bySession.find(e=>e.id===t)?.subCost??0}function za(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 Ba(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 Va(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 Ha(){try{let e=await Q(`/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 Ua(){try{let e=await Q(`/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 Wa(e){switch(e){case`session`:return`subscriptionSession`;case`weekly`:return`subscriptionWeekly`;case`monthly`:return`subscriptionMonthly`;default:return`subscriptionBilling`}}function Ga(e){return!e.running&&!e.promptAttempted&&(e.blank||e.awaitingFirstTurn)}function Ka({hasBandPlan:e}){let[t,n]=(0,d.useState)(()=>Ae()),[r,i]=(0,d.useState)(()=>Date.now());if((0,d.useEffect)(()=>{let e=()=>{n(Ae())};window.addEventListener(ke,e),window.addEventListener(`storage`,e);let t=setInterval(()=>{i(Date.now())},3e4);return()=>{window.removeEventListener(ke,e),window.removeEventListener(`storage`,e),clearInterval(t)}},[]),t.length===0)return null;let a=Pr().leadMin*6e4,o=t.map(t=>({key:t,state:dr(Bt(r,zt(t,e)),a)})).filter(e=>e.state!==null);return o.length===0?null:(0,m.jsx)(`span`,{className:L.bandDots,"data-testid":`billing-pinned-dots`,children:o.map(e=>(0,m.jsx)(`span`,{className:y(L.bandDot,L.bandDotOn,L[e.state]),role:`img`,"aria-label":e.key,title:e.key},e.key))})}function qa(){let[e,t]=(0,d.useState)(()=>Ee());return(0,d.useEffect)(()=>{let e=()=>{t(Ee())};return window.addEventListener(Te,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(Te,e),window.removeEventListener(`storage`,e)}},[]),e}function Ja(){let[e,t]=(0,d.useState)(()=>Se().show),[n,r]=(0,d.useState)(()=>Se().position);return(0,d.useEffect)(()=>{let e=()=>{t(Se().show),r(Se().position)};return window.addEventListener(xe,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(xe,e),window.removeEventListener(`storage`,e)}},[]),{visible:e,position:n}}function Ya(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=!1,i=()=>{n||(n=!0,e||s(Date.now()),Promise.all([Ha(),Ua()]).then(([t,n])=>{e||(t!==null&&r(t),a(n))}).catch(()=>{}).finally(()=>{n=!1}))};i();let o=setInterval(i,3e4);return()=>{e=!0,clearInterval(o)}},[e,c,t]);let u=(0,d.useMemo)(()=>La(n,e),[n,e]),f=(0,d.useMemo)(()=>Ra(n,e),[n,e]),p=(0,d.useMemo)(()=>za(n,e),[n,e]),m=(0,d.useMemo)(()=>Ba(i),[i]),h=(0,d.useMemo)(()=>zt(Va(n,e),i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)),[n,e,i]);return{sessionCost:u,subCost:f,turnCost:p,tier:(0,d.useMemo)(()=>Bt(o,h),[o,h]),chips:m,hasBandPlan:i.some(e=>e.displayName===`Z.ai Coding Plan`&&e.status===`ok`)}}function Xa({sessionId:e,t,seat:n,session:r}){let{visible:i,position:a}=Ja(),o=i&&a===n&&!(n===`above`&&r!==void 0&&Ga(r)),{sessionCost:s,subCost:c,turnCost:l,tier:u,chips:d,hasBandPlan:f}=Ya(e,o),p=qa(),h=e=>W(gn(e,p),p),g=s>0||l>0,_=u?.tier===`peak`;return o?(0,m.jsxs)(`span`,{className:n===`above`?y(L.feeBar,L.feeBarAbove,zr):y(L.feeBar,zr),"data-testid":`billing-live-cost-bar`,"data-seat":n,children:[(0,m.jsx)(Ka,{hasBandPlan:f}),u!==null&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:_?L.feeChipPrimary:L.feeChipOff,"data-testid":`billing-live-tier`,children:t(_?`tierPeak`:`tierOff`)}),(0,m.jsx)(`span`,{className:L.feeCount,children:Ht(u.nextSwitchInMs)}),(0,m.jsx)(`span`,{className:L.feeSuffix,children:t(_?`tierToOff`:`tierToPeak`)})]}),g&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:L.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:L.feeItem,"data-testid":`billing-live-turn`,children:[t(`liveTurn`),` `,(0,m.jsx)(`span`,{className:L.feeNum,"data-tick":`turn`,children:h(l)})]}),(0,m.jsx)(`span`,{className:L.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:L.feeItem,"data-testid":`billing-live-session`,children:[t(`liveSession`),` `,(0,m.jsx)(`span`,{className:L.feeNum,"data-tick":`session`,children:h(s)}),c>0&&(0,m.jsx)(`span`,{className:L.feeSuffix,"data-testid":`billing-live-session-sub`,children:t(`liveSessionSub`).replace(`{cost}`,h(c))})]})]}),d.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`span`,{className:L.feeSep,"aria-hidden":`true`,children:`·`}),(0,m.jsxs)(`span`,{className:e.pct<=10?L.feeChipError:L.feeChipAlert,"data-testid":`billing-live-quota`,children:[e.name,` `,t(Wa(e.kind)),` `,e.pct,`%`]})]},`${e.name}:${e.kind}`))]}):null}function Za({sessionId:e,t}){let n=qa(),r=e=>W(gn(e,n),n),{visible:i,position:a}=Ja(),{sessionCost:o,subCost:s,turnCost:c,tier:l,chips:u,hasBandPlan:d}=Ya(e,i&&a===`toolbar`);if(!i||a!==`toolbar`)return null;let f=l?.tier===`peak`,h=u.reduce((e,t)=>Math.min(e,t.pct),100),g=h<=10?L.feeInlineError:h<=20?L.feeInlineAlert:void 0,_=y(L.feeInline,g),v=[...l===null?[]:[`${Ht(l.nextSwitchInMs)} ${t(f?`tierToOff`:`tierToPeak`)}`],`${t(`liveTurn`)} ${r(c)}`,`${t(`liveSession`)} ${r(o)}`,...s>0?[t(`liveSessionSub`).replace(`{cost}`,r(s))]:[],...u.map(e=>`${e.name} ${t(Wa(e.kind))} ${e.pct}%`)].join(` · `);return(0,m.jsx)(p.Tooltip,{label:v,side:`top`,delayMs:500,portal:!0,children:(0,m.jsxs)(`span`,{className:y(_,zr),"data-testid":`billing-live-cost-chip`,role:`note`,"aria-label":v,children:[(0,m.jsx)(Ka,{hasBandPlan:d}),l!==null&&(0,m.jsx)(`span`,{className:f?L.feeChipPrimary:L.feeChipOff,"data-testid":`billing-live-tier`,children:t(f?`tierPeak`:`tierOff`)}),o>0&&(0,m.jsx)(`span`,{className:L.feeInlineNum,children:r(o)})]})})}let Qa=`@kenz1117/dsh-ui-usage-billing/TaskQueueQuick.module.css`;if(typeof document<`u`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(Qa)+`]`)===null){let e=document.createElement(`style`);e.dataset.plugin=`@kenz1117/dsh-ui-usage-billing`,e.dataset.pluginCss=Qa,e.textContent=`.HRJ8EG_quickQueue{white-space:nowrap;flex-shrink:0;align-self:center;align-items:center;gap:6px;display:inline-flex;position:relative}.HRJ8EG_quickQueueToggle,.HRJ8EG_quickQueueButton{border:1px solid var(--dsw-alias-border-l1);min-height:24px;color:var(--dsw-alias-label-secondary);font:inherit;cursor:pointer;background:0 0;border-radius:999px;justify-content:center;align-items:center;gap:5px;padding:0 8px;font-size:11px;line-height:18px;display:inline-flex}.HRJ8EG_quickQueueToggle:hover,.HRJ8EG_quickQueueButton:hover:not(:disabled){border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary)}.HRJ8EG_quickQueueToggle[aria-checked=true]{border-color:color-mix(in srgb, var(--ds-blue) 45%, transparent);background:color-mix(in srgb, var(--ds-blue) 10%, transparent);color:var(--ds-blue)}.HRJ8EG_quickQueueButton:focus-visible,.HRJ8EG_quickQueueToggle:focus-visible,.HRJ8EG_quickQueueClear input:focus-visible{outline:2px solid var(--ds-blue);outline-offset:2px}.HRJ8EG_quickQueueButton:disabled{cursor:wait;opacity:.65}.HRJ8EG_quickQueueClear{color:var(--dsw-alias-label-tertiary);cursor:pointer;align-items:center;gap:4px;font-size:11px;display:inline-flex}.HRJ8EG_quickQueueClear input{width:13px;height:13px;accent-color:var(--ds-blue);margin:0}.HRJ8EG_quickQueueCount{background:color-mix(in srgb, var(--ds-blue) 14%, transparent);min-width:16px;height:16px;color:var(--ds-blue);font-variant-numeric:tabular-nums;border-radius:999px;justify-content:center;align-items:center;padding:0 4px;font-size:10px;display:inline-flex}.HRJ8EG_quickQueueNotice{z-index:30;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3);width:max-content;max-width:min(320px,75vw);color:var(--dsw-alias-label-primary);white-space:normal;pointer-events:none;border-radius:8px;padding:7px 10px;font-size:12px;line-height:18px;position:absolute;bottom:calc(100% + 8px);right:0;box-shadow:0 8px 24px #00000038}.HRJ8EG_quickQueueNotice[data-kind=error]{border-color:color-mix(in srgb, var(--ds-red) 45%, transparent);color:var(--ds-red)}`,document.head.appendChild(e)}var $a={quickQueue:`HRJ8EG_quickQueue`,quickQueueButton:`HRJ8EG_quickQueueButton`,quickQueueClear:`HRJ8EG_quickQueueClear`,quickQueueCount:`HRJ8EG_quickQueueCount`,quickQueueNotice:`HRJ8EG_quickQueueNotice`,quickQueueToggle:`HRJ8EG_quickQueueToggle`};let eo=()=>void 0,to=()=>void 0;function no(e){return e.tasks.filter(e=>e.status===`queued`).length}function ro(){let[e,t]=(0,d.useState)(()=>nt());return(0,d.useEffect)(()=>{let e=()=>{t(nt())};return window.addEventListener(tt,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(tt,e),window.removeEventListener(`storage`,e)}},[]),e}function io(e){let[t,n]=(0,d.useState)(null),[r,i]=(0,d.useState)(()=>typeof document>`u`||!document.hidden),a=(0,d.useRef)(0),o=(0,d.useCallback)(e=>{a.current+=1,n(no(e))},[]);return(0,d.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{i(!document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[]),(0,d.useEffect)(()=>{if(!e||!r){n(null);return}let t=!1,i=!1,o=()=>{if(i)return;i=!0;let e=a.current;da().then(r=>{t||e!==a.current||n(r.supported?r.queuedCount:null)}).catch(()=>{}).finally(()=>{i=!1})};o();let s=window.setInterval(o,3e4);return()=>{t=!0,window.clearInterval(s)}},[e,r]),{count:t,applySnapshot:o}}function ao({t:e}){let t=ro();return t.showEntry?(0,m.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t.enabled,"aria-label":e(`quickQueueToggle`),className:y($a.quickQueueToggle,zr),"data-testid":`quick-queue-toggle`,onClick:()=>{rt({enabled:!t.enabled})},children:e(`quickQueueToggle`)}):null}function oo(e,t){let n=e(t),r=(0,d.useCallback)(e=>n?.subscribe(e)??(()=>{}),[n]),i=(0,d.useCallback)(()=>n?.getSnapshot(),[n]);return(0,d.useSyncExternalStore)(r,i,i)}function so({sessionId:e,t,useInput:n,inputActions:r,projectionFaceOf:i}){let a=ro(),o=(n??eo)(e=>e),s=oo(i??to,`workingDirectory`),c=oo(i??to,`modelSelection`)?.next,{count:l,applySnapshot:u}=io(a.enabled&&a.showEntry),[f,p]=(0,d.useState)(!1),[h,g]=(0,d.useState)(null),_=(0,d.useRef)(!1),v=(0,d.useRef)(!0),b=(0,d.useRef)({sessionId:e,input:o});if(b.current={sessionId:e,input:o},(0,d.useEffect)(()=>(v.current=!0,()=>{v.current=!1}),[]),(0,d.useEffect)(()=>{if(h===null)return;let e=h.kind===`success`?4e3:8e3,t=window.setTimeout(()=>{g(null)},e);return()=>{window.clearTimeout(t)}},[h]),!a.enabled||!a.showEntry)return null;let x=e=>{g({kind:`error`,text:e})},S=async()=>{if(_.current)return;if(g(null),o===void 0){x(t(`quickQueueUnsupported`));return}let n=o.draft;if(n.trim()===``){x(t(`quickQueueEmpty`));return}if(o.phase!==`plain`){x(t(`quickQueueBusy`));return}if(o.attachmentIds.length>0||o.occurrences.length>0){x(t(`quickQueueAttachments`));return}if(typeof s!=`string`||s===``){x(t(`quickQueueContext`));return}let i=a.clearAfterEnqueue;if(i&&r===void 0){x(t(`quickQueueUnsupported`));return}let l={sessionId:e,prompt:n,draftRev:o.draftRev,cwd:s,clearAfterEnqueue:i,reuseSource:a.reuseSourceSession};_.current=!0,p(!0);try{let e=await ua(!0);if(!e.supported){x(t(`quickQueueUnsupported`));return}let n=c??e.defaultModel;if(n==null){x(t(`quickQueueContext`));return}let i=e.workspaces.some(e=>e.path===l.cwd),a=e.models.some(e=>e.provider===n.provider&&e.id===n.model);if(!i||!a){x(t(`quickQueueRoute`));return}let o=await fa({action:`enqueue`,prompt:l.prompt,cwd:l.cwd,provider:n.provider,model:n.model,sourceSessionId:String(l.sessionId),reuseSource:l.reuseSource});u(o);let s=t(`quickQueueEnqueued`);if(l.clearAfterEnqueue&&r!==void 0){let e=b.current;if(v.current&&e.sessionId===l.sessionId&&e.input?.draft===l.prompt&&e.input.draftRev===l.draftRev&&e.input.phase===`plain`&&e.input.attachmentIds.length===0&&e.input.occurrences.length===0)try{r.setDraft(``)}catch{s=t(`quickQueueDraftChanged`)}else s=t(`quickQueueDraftChanged`)}v.current&&g({kind:`success`,text:s})}catch(e){if(!v.current)return;let n=e instanceof Error?e.message:String(e);x(t(`quickQueueFailed`).replace(`{message}`,n))}finally{_.current=!1,v.current&&p(!1)}};return(0,m.jsxs)(`span`,{className:y($a.quickQueue,zr),"data-testid":`quick-queue-controls`,children:[(0,m.jsxs)(`label`,{className:$a.quickQueueClear,children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:a.clearAfterEnqueue,disabled:f,onChange:e=>{rt({clearAfterEnqueue:e.target.checked})}}),t(`quickQueueClear`)]}),(0,m.jsxs)(`button`,{type:`button`,className:$a.quickQueueButton,"aria-label":t(`quickQueueEnqueue`),"aria-busy":f,disabled:f,"data-testid":`quick-queue-enqueue`,onClick:()=>{S()},children:[t(f?`quickQueueEnqueueing`:`quickQueueEnqueue`),l!==null&&l>0&&(0,m.jsx)(`span`,{className:$a.quickQueueCount,"data-testid":`quick-queue-count`,"aria-label":t(`quickQueueWaiting`).replace(`{count}`,String(l)),children:l})]}),h!==null&&(0,m.jsx)(`span`,{className:$a.quickQueueNotice,"data-kind":h.kind,role:h.kind===`error`?`alert`:`status`,children:h.text})]})}function co(){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{x(`billing-costs-listener-threw`)}},registerOpen:e=>(t=e,()=>{t===e&&(t=void 0)})}}let lo={enabled:!1,timeout:0};function uo(){try{let e=localStorage.getItem(`dsh-billing-completion-notify-v1`);if(e===null)return{...lo};let t=JSON.parse(e);return{enabled:t.enabled===!0,timeout:typeof t.timeout==`number`?t.timeout:0}}catch{return{...lo}}}function fo(e){return e.completed===!0||e.running===!1}function po(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)),fo(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{x(`notification-constructor-failed`)}},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=fo(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)}}function mo(e){let t=e.get(`uiWorkspace`);if(t!==void 0&&typeof t.openSession==`function`)return t}function ho(e){let t=e.sessions,n=t?.open;return typeof n==`function`?n.bind(t):void 0}function go(e){return{available:()=>mo(e)!==void 0||ho(e)!==void 0,open:t=>{let n=_(t),r=mo(e);if(r!==void 0)try{return r.openSession(n),`opened`}catch(e){return x(`session-navigation-open-failed`,e),`failed`}let i=ho(e);if(i!==void 0)try{return i(n),`opened`}catch(e){return x(`session-navigation-legacy-open-failed`,e),`failed`}return`unavailable`}}}function _o(e,t){let n=!1,r={name:`usage`,label:t.label,description:t.description,available:()=>!0,ui:{kind:`action`,run:()=>{t.openDashboard()}}};return e.inject([`commandUi`],e=>{e.effect(()=>{try{let t=e.commandUi.register(r);return n=!0,()=>{n=!1,t()}}catch(e){return x(`usage-command-register-failed`,e),()=>{}}},`ui-usage-billing: /usage command`)}),()=>n}let vo=[`slots`,`locale`,`remote`,`sessions`];function yo(e){let t=co();e.provide(`billingMetrics`,t);let n=ur();e.effect(()=>e.locale.register(at,{zh:ot,en:st}),`ui-usage-billing: dictionaries`);let r=go(e),i=_o(e,{openDashboard:()=>{t.openDashboard()},label:()=>Le()===`en`?st.commandUsageLabel:ot.commandUsageLabel,description:()=>Le()===`en`?st.commandUsageDescription:ot.commandUsageDescription});e.inject([`shortcuts`],e=>{e.effect(()=>{try{let n=e.shortcuts.register({id:`usage-billing.open-dashboard`,label:()=>Le()===`en`?st.shortcutOpenDashboard:ot.shortcutOpenDashboard,aliases:[`usage`,`billing`,`dashboard`],defaults:{"desktop:macos":{code:`KeyD`,modifiers:[`primary`,`shift`]},"desktop:windows":{code:`KeyD`,modifiers:[`primary`,`shift`]},"desktop:linux":{code:`KeyD`,modifiers:[`primary`,`shift`]},"web:macos":{code:`KeyD`,modifiers:[`primary`,`shift`]},"web:windows":{code:`KeyD`,modifiers:[`primary`,`shift`]}},regions:[`page`,`editable`],modals:[],resolve:()=>({status:`handled`,run:()=>{t.openDashboard()}})});return()=>{n()}}catch(e){return x(`shortcut-register-failed`,e),()=>{}}},`ui-usage-billing: dashboard shortcut`)});let a=!1,o={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),recoveryEntryAvailable:i()||a,navigateToSession:e=>r.open(e),sessionTitleOf:t=>{try{let n=e.sessions.list;if(n===void 0)return;let r=n.getSnapshot().byId?.[t],i=r?.displayTitle??r?.title;return typeof i==`string`&&i.trim()!==``?i:void 0}catch{return}}})};e.slots.inject(`settings.section`,()=>{a=!0;let t=e.slots.register({name:`settings.section`,id:`usage-billing`,order:30,label:()=>Le()===`en`?st.nativeSettingsNav:ot.nativeSettingsNav,locale:at,...o},Ia);return()=>{a=!1,t()}}),e.slots.inject(`sidebar.footer.action`,()=>e.slots.register({name:`sidebar.footer.action`,id:`usage-billing`,order:25,locale:at,...o,children:{"billing.dashboard.decor":{kind:`list`,scope:`root`}}},Fa)),e.slots.inject(`conversation.composer.dock`,()=>e.slots.register({name:`conversation.composer.dock`,id:`usage-billing-cost`,order:0,locale:at,inject:e=>({sessionId:_(e),seat:`below`})},Xa)),e.slots.inject(`conversation.input.dock`,()=>e.slots.register({name:`conversation.input.dock`,id:`usage-billing-cost-above`,order:100,locale:at,inject:e=>({sessionId:_(e),seat:`above`})},Xa)),e.slots.inject(`conversation.input.right`,()=>e.slots.register({name:`conversation.input.right`,id:`usage-billing-cost-chip`,order:0,locale:at,inject:e=>({sessionId:_(e)})},Za)),e.slots.inject(`conversation.input.left`,()=>e.slots.register({name:`conversation.input.left`,id:`usage-billing-quick-queue-toggle`,order:20,locale:at},ao)),e.slots.inject(`conversation.input.right`,()=>e.slots.register({name:`conversation.input.right`,id:`usage-billing-quick-queue-enqueue`,order:20,locale:at,inject:t=>({sessionId:_(t),projectionFaceOf:n=>{try{return e.sessions.binding?.(_(t))?.session.projections.faceOf(n)}catch{return}}})},so)),e.effect(()=>po(e.sessions.list,uo),`ui-usage-billing: completion notifier`)}return n.UsageBilling=Fa,n.apply=yo,n.inject=vo,t.exports}});
|
|
6
6
|
//# sourceMappingURL=client.js.map
|