cctally 1.108.0 → 1.110.0

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.
Files changed (85) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +6 -6
  3. package/bin/_cctally_account.py +4 -0
  4. package/bin/_cctally_alerts.py +6 -2
  5. package/bin/_cctally_cache.py +1652 -166
  6. package/bin/_cctally_config.py +3 -2
  7. package/bin/_cctally_core.py +594 -33
  8. package/bin/_cctally_dashboard.py +1585 -201
  9. package/bin/_cctally_dashboard_conversation.py +494 -48
  10. package/bin/_cctally_dashboard_envelope.py +167 -11
  11. package/bin/_cctally_dashboard_share.py +154 -36
  12. package/bin/_cctally_dashboard_sources.py +2615 -422
  13. package/bin/_cctally_db.py +678 -5
  14. package/bin/_cctally_diagnosis_sources.py +238 -26
  15. package/bin/_cctally_doctor.py +99 -18
  16. package/bin/_cctally_five_hour.py +1295 -40
  17. package/bin/_cctally_forecast.py +124 -28
  18. package/bin/_cctally_journal.py +408 -38
  19. package/bin/_cctally_milestone_history.py +150 -14
  20. package/bin/_cctally_parser.py +5 -0
  21. package/bin/_cctally_percent_breakdown.py +6 -1
  22. package/bin/_cctally_project.py +48 -76
  23. package/bin/_cctally_quota.py +39 -7
  24. package/bin/_cctally_quota_model.py +17 -2
  25. package/bin/_cctally_record.py +1647 -443
  26. package/bin/_cctally_rederive.py +899 -30
  27. package/bin/_cctally_refresh.py +2 -1
  28. package/bin/_cctally_share.py +24 -5
  29. package/bin/_cctally_source_analytics.py +1035 -78
  30. package/bin/_cctally_statusline.py +83 -19
  31. package/bin/_cctally_store.py +61 -4
  32. package/bin/_cctally_transcript.py +27 -2
  33. package/bin/_cctally_tui.py +264 -76
  34. package/bin/_cctally_weekrefs.py +28 -5
  35. package/bin/_lib_blocks.py +127 -20
  36. package/bin/_lib_cache_report.py +20 -5
  37. package/bin/_lib_codex_conversation_query.py +297 -64
  38. package/bin/_lib_codex_hooks.py +102 -0
  39. package/bin/_lib_codex_metadata.py +207 -0
  40. package/bin/_lib_conversation.py +119 -0
  41. package/bin/_lib_conversation_dispatch.py +31 -1
  42. package/bin/_lib_conversation_query.py +315 -51
  43. package/bin/_lib_conversation_retention.py +413 -25
  44. package/bin/_lib_dashboard_sources.py +267 -7
  45. package/bin/_lib_diagnosis.py +10 -0
  46. package/bin/_lib_diff_kernel.py +12 -1
  47. package/bin/_lib_doctor.py +230 -8
  48. package/bin/_lib_ingest_frontier.py +1366 -49
  49. package/bin/_lib_journal.py +19 -2
  50. package/bin/_lib_merge_gate.py +307 -0
  51. package/bin/_lib_pricing.py +588 -29
  52. package/bin/_lib_record.py +130 -12
  53. package/bin/_lib_rederive.py +903 -2
  54. package/bin/_lib_render.py +9 -3
  55. package/bin/_lib_retained_size.py +27 -2
  56. package/bin/_lib_segment_summary.py +66 -8
  57. package/bin/_lib_share_templates.py +28 -18
  58. package/bin/_lib_snapshot_cache.py +115 -1
  59. package/bin/_lib_source_retry.py +320 -0
  60. package/bin/_lib_statusline_candidates.py +400 -36
  61. package/bin/_lib_tick_stats.py +119 -0
  62. package/bin/_lib_view_models.py +256 -76
  63. package/bin/cctally +69 -0
  64. package/dashboard/static/assets/ConversationsView-BB9vUiL6.js +72 -0
  65. package/dashboard/static/assets/{DoctorModal-CWn3U4Wl.js → DoctorModal-DFY2iPDf.js} +1 -1
  66. package/dashboard/static/assets/ModalRoot-DvRKHbQE.js +1 -0
  67. package/dashboard/static/assets/ProjectsDrillPanel-DAv39uSo.js +1 -0
  68. package/dashboard/static/assets/SourceDetailModal-DSAWo2Fp.js +1 -0
  69. package/dashboard/static/assets/{UpdateModal-D3m8GG6V.js → UpdateModal-R_9dOVnh.js} +3 -3
  70. package/dashboard/static/assets/dashboardStream.shared-worker-DbG6Ef0T.js +1 -0
  71. package/dashboard/static/assets/index-COhxe3vU.css +1 -0
  72. package/dashboard/static/assets/index-DdU62sov.js +13 -0
  73. package/dashboard/static/assets/outlineNavigation-BOCLcRa6.js +9 -0
  74. package/dashboard/static/assets/useKeymap-CW7Up0Ay.js +1 -0
  75. package/dashboard/static/dashboard.html +3 -3
  76. package/package.json +4 -1
  77. package/dashboard/static/assets/ConversationsView-BOSaBRtu.js +0 -72
  78. package/dashboard/static/assets/ModalRoot-SR070V6c.js +0 -1
  79. package/dashboard/static/assets/ProjectsDrillPanel-QLI9i5mZ.js +0 -1
  80. package/dashboard/static/assets/SourceDetailModal-pv0wlFxl.js +0 -1
  81. package/dashboard/static/assets/dashboardStream.shared-worker-1XTMV3nr.js +0 -1
  82. package/dashboard/static/assets/index-BHu4mxd8.css +0 -1
  83. package/dashboard/static/assets/index-CIWsbux3.js +0 -13
  84. package/dashboard/static/assets/outlineNavigation-CJvKqmLV.js +0 -9
  85. package/dashboard/static/assets/useKeymap-ffqsS5G0.js +0 -1
@@ -1 +1 @@
1
- import{It as e,Nt as t,a as n,b as r,c as i,f as a,t as o,y as s}from"./useKeymap-ffqsS5G0.js";import{kt as c,mt as l,o as u,pt as d,s as f}from"./index-CIWsbux3.js";var p=e(t(),1);function m(){let[e,t]=(0,p.useState)(null),[n,r]=(0,p.useState)(!1),[i,a]=(0,p.useState)(null);return{report:e,loading:n,error:i,refresh:(0,p.useCallback)(async()=>{r(!0),a(null);try{let e=await fetch(`/api/doctor`);if(!e.ok)throw Error(`HTTP ${e.status}`);t(await e.json())}catch(e){a(e instanceof Error?e.message:String(e))}finally{r(!1)}},[])}}var h=n(),g={ok:`✓`,warn:`⚠`,fail:`✗`},_=/(--[A-Za-z0-9][A-Za-z0-9-]*)/g;function v({text:e}){return(0,h.jsx)(h.Fragment,{children:e.split(_).map((e,t)=>e.startsWith(`--`)?(0,h.jsx)(`span`,{className:`doctor-modal__flag`,children:e},`${e}-${t}`):e)})}function y(){let e=(0,p.useSyncExternalStore)(s,()=>a().doctorModalOpen),{report:t,loading:n,error:c,refresh:g}=m(),_=()=>{i({type:`CLOSE_DOCTOR_MODAL`})};o((0,p.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:_,when:()=>a().doctorModalOpen}],[])),(0,p.useEffect)(()=>{e&&g()},[e,g]),(0,p.useEffect)(()=>{if(!t)return;let e=a().doctor,n=e?Date.parse(e.generated_at):NaN,r=Date.parse(t.generated_at);e&&Number.isFinite(n)&&Number.isFinite(r)&&r<=n||i({type:`SET_DOCTOR_AGGREGATE`,doctor:{severity:t.overall.severity,counts:t.overall.counts,generated_at:t.generated_at,fingerprint:`client-reconcile`}})},[t]);let v=(0,p.useRef)(null);return l(v,{active:e,trapEnabled:(0,p.useSyncExternalStore)(s,()=>r(a())===`doctor`),initialFocus:`container`}),d(e),e?(0,h.jsxs)(`div`,{className:`update-modal-root`,onClick:_,children:[(0,h.jsx)(`div`,{className:`modal-backdrop`}),(0,h.jsxs)(`div`,{ref:v,className:`modal-card doctor-modal-card`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`doctor-modal-title`,tabIndex:-1,onClick:e=>e.stopPropagation(),children:[(0,h.jsx)(u,{title:`Doctor`,titleId:`doctor-modal-title`,headerExtras:(0,h.jsxs)(`div`,{className:`doctor-modal__header-actions`,children:[(0,h.jsx)(`button`,{type:`button`,className:`doctor-modal__refresh`,onClick:()=>{g()},disabled:n,"aria-label":`Refresh doctor report`,children:n?`refreshing…`:`↻ refresh`}),(0,h.jsx)(f,{onClose:_})]})}),(0,h.jsxs)(`div`,{className:`modal-body`,children:[n&&!t&&(0,h.jsx)(`p`,{children:`Loading…`}),c&&(0,h.jsxs)(`p`,{className:`doctor-modal__error`,children:[`Error loading report: `,c]}),t&&(0,h.jsx)(b,{report:t})]})]})]}):null}function b({report:e}){let{counts:t}=e.overall;return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(`p`,{className:`doctor-modal__summary`,children:[t.ok,` OK · `,t.warn,` WARN · `,t.fail,` FAIL`]}),e.categories.map(e=>(0,h.jsx)(x,{cat:e,defaultOpen:e.severity!==`ok`},e.id))]})}function x({cat:e,defaultOpen:t}){let[n,r]=(0,p.useState)(t);return(0,h.jsxs)(`section`,{className:`doctor-modal__category doctor-modal__category--${e.severity}`,children:[(0,h.jsxs)(`button`,{type:`button`,className:`doctor-modal__category-header`,onClick:()=>r(e=>!e),"aria-expanded":n,children:[(0,h.jsx)(`span`,{className:`doctor-modal__category-caret`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,h.jsx)(`span`,{className:`doctor-modal__glyph`,"aria-hidden":`true`,children:g[e.severity]}),(0,h.jsx)(`span`,{children:e.title})]}),n&&e.checks.map(e=>(0,h.jsx)(S,{c:e},e.id))]})}function S({c:e}){let[t,n]=(0,p.useState)(!1),r=e.details&&Object.keys(e.details).length>0,i=e.id===`data.latest_snapshot_age`&&typeof e.details?.latest_snapshot_age_s==`number`?c(e.details.latest_snapshot_age_s):e.summary;return(0,h.jsxs)(`div`,{className:`doctor-modal__check doctor-modal__check--${e.severity}`,children:[(0,h.jsxs)(`p`,{children:[(0,h.jsx)(`span`,{className:`doctor-modal__glyph`,"aria-label":e.severity,children:g[e.severity]}),` `,(0,h.jsx)(`strong`,{children:e.title}),`: `,i]}),e.remediation&&(0,h.jsxs)(`p`,{className:`doctor-modal__remediation`,children:[`→ `,(0,h.jsx)(v,{text:e.remediation})]}),e.severity!==`ok`&&!e.remediation&&(0,h.jsxs)(`p`,{className:`doctor-modal__remediation`,children:[`→ Run `,(0,h.jsx)(`code`,{children:`cctally doctor`}),` for the full report`]}),r&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(`button`,{type:`button`,className:`doctor-modal__details-toggle`,onClick:()=>n(e=>!e),"aria-expanded":t,children:[t?`▼`:`▶`,` details`]}),t&&(0,h.jsx)(`pre`,{className:`doctor-modal__details`,children:JSON.stringify(e.details,null,2)})]})]})}export{y as DoctorModal};
1
+ import{Ft as e,Rt as t,a as n,b as r,c as i,f as a,t as o,x as s}from"./useKeymap-CW7Up0Ay.js";import{dt as c,jt as l,o as u,s as d,ut as f}from"./index-DdU62sov.js";var p=t(e(),1);function m(){let[e,t]=(0,p.useState)(null),[n,r]=(0,p.useState)(!1),[i,a]=(0,p.useState)(null);return{report:e,loading:n,error:i,refresh:(0,p.useCallback)(async()=>{r(!0),a(null);try{let e=await fetch(`/api/doctor`);if(!e.ok)throw Error(`HTTP ${e.status}`);t(await e.json())}catch(e){a(e instanceof Error?e.message:String(e))}finally{r(!1)}},[])}}var h=n(),g={ok:`✓`,warn:`⚠`,fail:`✗`},_=/(--[A-Za-z0-9][A-Za-z0-9-]*)/g;function v({text:e}){return(0,h.jsx)(h.Fragment,{children:e.split(_).map((e,t)=>e.startsWith(`--`)?(0,h.jsx)(`span`,{className:`doctor-modal__flag`,children:e},`${e}-${t}`):e)})}function y(){let e=(0,p.useSyncExternalStore)(r,()=>a().doctorModalOpen),{report:t,loading:n,error:l,refresh:g}=m(),_=()=>{i({type:`CLOSE_DOCTOR_MODAL`})};o((0,p.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:_,when:()=>a().doctorModalOpen}],[])),(0,p.useEffect)(()=>{e&&g()},[e,g]),(0,p.useEffect)(()=>{if(!t)return;let e=a().doctor,n=e?Date.parse(e.generated_at):NaN,r=Date.parse(t.generated_at);e&&Number.isFinite(n)&&Number.isFinite(r)&&r<=n||i({type:`SET_DOCTOR_AGGREGATE`,doctor:{severity:t.overall.severity,counts:t.overall.counts,generated_at:t.generated_at,fingerprint:`client-reconcile`}})},[t]);let v=(0,p.useRef)(null);return c(v,{active:e,trapEnabled:(0,p.useSyncExternalStore)(r,()=>s(a())===`doctor`),initialFocus:`container`}),f(e),e?(0,h.jsxs)(`div`,{className:`update-modal-root`,onClick:_,children:[(0,h.jsx)(`div`,{className:`modal-backdrop`}),(0,h.jsxs)(`div`,{ref:v,className:`modal-card doctor-modal-card`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`doctor-modal-title`,tabIndex:-1,onClick:e=>e.stopPropagation(),children:[(0,h.jsx)(u,{title:`Doctor`,titleId:`doctor-modal-title`,headerExtras:(0,h.jsxs)(`div`,{className:`doctor-modal__header-actions`,children:[(0,h.jsx)(`button`,{type:`button`,className:`doctor-modal__refresh`,onClick:()=>{g()},disabled:n,"aria-label":`Refresh doctor report`,children:n?`refreshing…`:`↻ refresh`}),(0,h.jsx)(d,{onClose:_})]})}),(0,h.jsxs)(`div`,{className:`modal-body`,children:[n&&!t&&(0,h.jsx)(`p`,{children:`Loading…`}),l&&(0,h.jsxs)(`p`,{className:`doctor-modal__error`,children:[`Error loading report: `,l]}),t&&(0,h.jsx)(b,{report:t})]})]})]}):null}function b({report:e}){let{counts:t}=e.overall;return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(`p`,{className:`doctor-modal__summary`,children:[t.ok,` OK · `,t.warn,` WARN · `,t.fail,` FAIL`]}),e.categories.map(e=>(0,h.jsx)(x,{cat:e,defaultOpen:e.severity!==`ok`},e.id))]})}function x({cat:e,defaultOpen:t}){let[n,r]=(0,p.useState)(t);return(0,h.jsxs)(`section`,{className:`doctor-modal__category doctor-modal__category--${e.severity}`,children:[(0,h.jsxs)(`button`,{type:`button`,className:`doctor-modal__category-header`,onClick:()=>r(e=>!e),"aria-expanded":n,children:[(0,h.jsx)(`span`,{className:`doctor-modal__category-caret`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,h.jsx)(`span`,{className:`doctor-modal__glyph`,"aria-hidden":`true`,children:g[e.severity]}),(0,h.jsx)(`span`,{children:e.title})]}),n&&e.checks.map(e=>(0,h.jsx)(S,{c:e},e.id))]})}function S({c:e}){let[t,n]=(0,p.useState)(!1),r=e.details&&Object.keys(e.details).length>0,i=e.id===`data.latest_snapshot_age`&&typeof e.details?.latest_snapshot_age_s==`number`?l(e.details.latest_snapshot_age_s):e.summary;return(0,h.jsxs)(`div`,{className:`doctor-modal__check doctor-modal__check--${e.severity}`,children:[(0,h.jsxs)(`p`,{children:[(0,h.jsx)(`span`,{className:`doctor-modal__glyph`,"aria-label":e.severity,children:g[e.severity]}),` `,(0,h.jsx)(`strong`,{children:e.title}),`: `,i]}),e.remediation&&(0,h.jsxs)(`p`,{className:`doctor-modal__remediation`,children:[`→ `,(0,h.jsx)(v,{text:e.remediation})]}),e.severity!==`ok`&&!e.remediation&&(0,h.jsxs)(`p`,{className:`doctor-modal__remediation`,children:[`→ Run `,(0,h.jsx)(`code`,{children:`cctally doctor`}),` for the full report`]}),r&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(`button`,{type:`button`,className:`doctor-modal__details-toggle`,onClick:()=>n(e=>!e),"aria-expanded":t,children:[t?`▼`:`▶`,` details`]}),t&&(0,h.jsx)(`pre`,{className:`doctor-modal__details`,children:JSON.stringify(e.details,null,2)})]})]})}export{y as DoctorModal};
@@ -0,0 +1 @@
1
+ import{Ct as e,Dt as t,Et as n,F as r,Ft as i,L as a,Mt as o,N as s,Nt as c,O as l,Ot as u,Rt as d,U as f,W as p,a as m,b as h,c as g,f as _,it as v,jt as y,kt as b,nt as x,ot as S,st as C,t as w,wt as T,x as E}from"./useKeymap-CW7Up0Ay.js";import{$ as D,A as O,At as k,B as A,C as j,D as M,E as N,Et as P,F,Ft as ee,G as te,H as I,I as ne,J as re,K as ie,L as ae,N as oe,O as se,Ot as ce,Q as le,R as L,S as ue,Tt as de,U as R,V as z,W as fe,X as B,Y as V,Z as pe,_ as H,_t as U,a as me,at as he,bt as W,c as ge,d as _e,et as ve,f as ye,ft as be,g as G,gt as K,h as xe,ht as Se,k as Ce,kt as we,l as Te,lt as q,m as Ee,mt as De,nt as Oe,p as J,pt as ke,q as Ae,rt as je,st as Me,tt as Ne,u as Pe,v as Fe,vt as Ie,w as Le,wt as Re,x as ze,xt as Be,y as Ve,yt as He,z as Ue}from"./index-DdU62sov.js";import{N as We}from"./outlineNavigation-BOCLcRa6.js";import{a as Ge,i as Ke,n as qe,o as Je,s as Y}from"./ProjectsDrillPanel-DAv39uSo.js";var X=d(i(),1);function Ye(e,t=15){return(e??0)>=t}var Xe=new Map;function Ze(e,t,n){if(!e.length||t==null&&n===-1)return null;let r=t==null?(()=>{let t=e.findIndex(e=>e.is_current);return t===-1?0:t})():e.findIndex(e=>e.key===t);if(r===-1)return null;let i=r+n;return i<0||i>=e.length||e[i].is_current?null:e[i].key}async function Qe(e,t,n=null){let r=e===`codex`?n:null,i=`${e}|${r??``}|${t.key}|${t.detail_stamp}`,a=Xe.get(i);if(a)return a;let o=r==null?``:`?account=${encodeURIComponent(r)}`,s=await fetch(`/api/milestones/${e}/week/${encodeURIComponent(t.key)}${o}`);if(!s.ok){let e=await s.json().catch(()=>({}));throw Object.assign(Error(`week fetch failed`),{status:s.status,code:e.code,reason:e.reason})}let c=await s.json();return Xe.set(i,c),c}var Z=m(),$e=[];function et(e){return e==null||!isFinite(e)?0:Math.max(0,Math.min(100,e))}function tt(e,t,n){let r=v.dateShort(t,n);return e||(r?`Resets ${r}`:`—`)}function nt(e,t){let n=v.dateShort(e.start_at_utc,t),r=v.dateShort(e.end_at_utc,t);return n&&r?`${n}–${r}`:e.label}function rt(e){return e!=null&&e.start_at_utc==null&&e.end_at_utc==null}function it(e){let t=e.end_at_utc?Date.parse(e.end_at_utc):NaN,n=e.resets_at_utc?Date.parse(e.resets_at_utc):NaN;return Number.isFinite(t)&&Number.isFinite(n)&&n>t}function at(e){if(e==null||!isFinite(e))return[`—`,``];let t=(+e).toFixed(1),n=t.indexOf(`.`);return n===-1?[t,`.0%`]:[t.slice(0,n),t.slice(n)+`%`]}function ot(e){let t=[],n=[...e].sort((e,t)=>(e.percent??0)-(t.percent??0));for(let e of n)e.percent!=null&&(t.length&&e.percent-(t[t.length-1].percent??0)<3||t.push(e));return t}function st(e){if(!Array.isArray(e)||e.length<2)return null;let t=e.map(e=>e.marginal_usd).filter(e=>e!=null&&isFinite(e)),n=t.length?t.reduce((e,t)=>e+t,0)/t.length:null,r=e[e.length-1].percent,i=[];return n!=null&&i.push(`avg marginal $`+n.toFixed(2)),r!=null&&i.push(`latest at `+r+`%`),i.length?i.join(` · `):null}function ct(e,t){let n=[];for(let t of e)n.push({kind:`milestone`,ts:t.captured_at_utc,data:t});for(let e of t)n.push({kind:`credit`,ts:e.effective_reset_at_utc,data:e});return n.sort((e,t)=>e.ts.localeCompare(t.ts)),n}function lt(e,t){if(e.five_hour_percent!=null)return e.five_hour_percent;let n=Date.parse(e.captured_at),r=t.filter(e=>{let t=Date.parse(e.captured_at),r=e.resets_at?Date.parse(e.resets_at):1/0;return t<=n&&n<r});return r.sort((e,t)=>Date.parse(t.captured_at)-Date.parse(e.captured_at)),r[0]?.percent??null}function ut(e,t,n=null,r=!1){let[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(0),y=(0,X.useMemo)(()=>t.find(e=>e.is_current)??null,[t]),b=(0,X.useMemo)(()=>i==null?y:t.find(e=>e.key===i)??null,[i,t,y]),x=i!=null&&!t.some(e=>e.key===i),S=(0,X.useCallback)(e=>{a(e),s(null),l(!1),d(null),_(null)},[]),C=(0,X.useCallback)(e=>{d(e),l(!0)},[]),w=(0,X.useCallback)(()=>d(null),[]),T=b!=null&&!x&&(i!=null||(b.segment_count??0)>1||b.has_observation_gap===!0||r||c)&&b?`${n??``}|${b.key}|${b.detail_stamp}`:null,E=f?.key===T?f.payload:null;(0,X.useEffect)(()=>{a(null),s(null),l(!1),d(null),_(null)},[n]);let D=(0,X.useCallback)(()=>{if(!b||T==null)return;let t=++v.current;h(!0),_(null),Qe(e,b,n).then(e=>{t===v.current&&(p({key:T,payload:e}),h(!1))}).catch(e=>{t===v.current&&(_({status:e?.status,code:e?.code}),h(!1))})},[e,b,n,T]);return(0,X.useEffect)(()=>{if(T==null){v.current++,p(null),h(!1),_(null);return}D()},[T]),{index:t,weekKey:i,setWeekKey:S,selectedEntry:b,currentEntry:y,detail:E,loading:m,error:g,vanished:x,wantDetail:c,pendingBlockStep:u,requestCurrentDetail:C,clearPendingBlockStep:w,retry:(0,X.useCallback)(()=>D(),[D]),blockSel:o,setBlockSel:s}}function dt({nav:e,pillText:t,accentClass:n,singleId:r,unitNoun:i}){let{index:a,weekKey:o,setWeekKey:s}=e,c=Ze(a,o,1),l=o==null?null:Ze(a,o,-1)??null,u=c!=null,d=o!=null;return(0,Z.jsxs)(`div`,{className:`m-chipstrip mcw-weeknav`,id:r(`mcw-badges`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`m-pill ${n} mcw-weeknav-btn`,"aria-label":`Older ${i}`,disabled:!u,onClick:()=>{c!=null&&s(c)},children:`‹`}),(0,Z.jsx)(`span`,{className:`m-pill ${n}`,id:r(`mcw-week-pill`),children:t}),(0,Z.jsx)(`button`,{type:`button`,className:`m-pill ${n} mcw-weeknav-btn`,"aria-label":`Newer ${i}`,disabled:!d,onClick:()=>{o!=null&&s(l)},children:`›`})]})}function ft({blockCount:e,selectedIndex:t,block:n,onStep:r,ctx:i,singleId:a,accentClass:o}){let s=!!n?.crossed_seven_day_reset,c=v.startedShort(n?.block_start_at,i,{noSuffix:!0}),l=v.startedShort(n?.five_hour_resets_at,i,{noSuffix:!0});return(0,Z.jsxs)(`div`,{className:`mcw-mshead mcw-blocknav`,id:a(`mcw-blocknav`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`m-pill ${o} mcw-blocknav-btn`,"aria-label":`Older block`,disabled:t<=0,onClick:()=>r(-1),children:`‹`}),(0,Z.jsxs)(`span`,{className:`m-pill ${o}`,children:[s?`⚡ `:``,`Block `,t+1,` of `,e]}),(0,Z.jsxs)(`span`,{className:`mcw-ms-sub`,children:[c,` → `,l]}),n?.account_key!=null&&(0,Z.jsx)(`span`,{className:`mcw-ms-sub`,children:n.account_label??n.account_key}),(0,Z.jsx)(`button`,{type:`button`,className:`m-pill ${o} mcw-blocknav-btn`,"aria-label":`Newer block`,disabled:t>=e-1,onClick:()=>r(1),children:`›`})]})}function pt({blocks:e,selectedIndex:t,onStep:n,ctx:r,singleId:i,accentClass:a}){return(0,Z.jsx)(ft,{blockCount:e.length,selectedIndex:t,block:e[t]??null,onStep:n,ctx:r,singleId:i,accentClass:a})}function mt({blockCount:e,block:t,onStep:n,ctx:r,singleId:i,accentClass:a}){return(0,Z.jsx)(ft,{blockCount:e,selectedIndex:e-1,block:t,onStep:n,ctx:r,singleId:i,accentClass:a})}function ht({block:e,ctx:t,singleId:n,accentClass:r}){return(0,Z.jsxs)(`div`,{className:`mcw-mshead mcw-blocknav`,id:n(`mcw-blocknav`),children:[(0,Z.jsx)(`button`,{type:`button`,className:`m-pill ${r} mcw-blocknav-btn`,"aria-label":`Older block`,disabled:!0,children:`‹`}),(0,Z.jsx)(`span`,{className:`m-pill ${r}`,children:`Current block`}),(0,Z.jsxs)(`span`,{className:`mcw-ms-sub`,children:[v.startedShort(e?.block_start_at,t,{noSuffix:!0}),` → `,v.startedShort(e?.five_hour_resets_at,t,{noSuffix:!0})]}),(0,Z.jsx)(`button`,{type:`button`,className:`m-pill ${r} mcw-blocknav-btn`,"aria-label":`Newer block`,disabled:!0,children:`›`})]})}function gt({id:e}){return(0,Z.jsx)(`p`,{className:`empty-state`,id:e,role:`status`,children:`Loading block detail…`})}function _t(e){let t=Date.parse(e??``);return Number.isFinite(t)?new Date(t+300*60*1e3).toISOString():null}function vt({onBack:e}){return(0,Z.jsxs)(`section`,{className:`modal-current-week`,children:[(0,Z.jsx)(`p`,{className:`empty-state`,children:`This cycle is no longer available.`}),(0,Z.jsx)(`p`,{className:`empty-state`,children:(0,Z.jsx)(`button`,{type:`button`,className:`m-pill accent-green`,onClick:e,children:`Back to current`})})]})}function yt({embedded:e,title:t,accentClass:n,headerExtras:r,children:i}){return e?(0,Z.jsx)(Z.Fragment,{children:i}):(0,Z.jsx)(Y,{title:t,accentClass:n,headerExtras:r,triggerId:De,children:i})}function bt(e,t){if(!e||!t)return null;let n=Date.parse(e),r=Date.parse(t);if(!isFinite(n)||!isFinite(r))return null;let i=(r-n)/1e3;if(!(i>0))return null;if(i<60){let e=Math.max(1,Math.trunc(i));return`${e} ${e===1?`second`:`seconds`}`}if(i<3600){let e=Math.floor(i/60);return`${e} ${e===1?`minute`:`minutes`}`}return`${xt(i/3600)} hours`}function xt(e){let t=e*4;if(Number.isInteger(t)&&t%2!=0){let t=Math.floor(e*10);return((t%2==0?t:t+1)/10).toFixed(1)}return e.toFixed(1)}function St(e,t){return!e||e.length===0?[]:e.map(e=>{let n=v.startedShort(e.observed_at_utc,t,{noSuffix:!0}),r=`Observation gap: ${e.first_percent}%-${e.last_percent}% were all recorded from one observation at ${n}`,i=bt(e.previous_crossed_at_utc,e.observed_at_utc);return i!==null&&(r+=`, ${i} after the previous crossing`),`${r}. Their marginal costs are not separable.`})}function Ct(e){let t=[];return e.segments.forEach((n,r)=>{if(r>0){let n=e.dividers[r-1];n&&t.push({kind:`divider`,effectiveAt:n.effective_at_utc,priorPercent:n.prior_percent,key:`div-${r}`})}n.milestones.forEach(e=>{t.push({kind:`ms`,m:e,key:`ms-${n.key}-${e.percent}`})})}),{rows:t,count:e.segments.reduce((e,t)=>e+t.milestones.length,0)}}function wt({accounts:e,codex:t,ctx:n}){return(0,Z.jsxs)(`div`,{"data-testid":`codex-cycle-per-account`,children:[(0,Z.jsx)(`p`,{className:`mcw-ms-sub`,"data-testid":`codex-cycle-per-account-note`,children:`Each account has its own quota cycle, so there is no single merged percentage ladder. Spend and tokens below are each account’s own — pick an account chip to open its milestones.`}),(0,Z.jsxs)(`table`,{className:`m-histable mcw-table mcw-per-account-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:`Account`}),(0,Z.jsx)(`th`,{className:`num`,children:`Used %`}),(0,Z.jsxs)(`th`,{children:[`Resets (`,n.offsetLabel,`)`]}),(0,Z.jsx)(`th`,{className:`num`,children:`Spent`}),(0,Z.jsx)(`th`,{className:`num`,children:`Tokens`})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>{let r=t.account_scopes?.[e.accountKey]?.quota,i=Ae(r),a=r?.histories.find(e=>e.window_minutes===10080&&!e.model_scoped&&i.has(e.key)),o=r?.summary.active.find(e=>e.key===a?.key);return(0,Z.jsxs)(`tr`,{"data-account-key":e.accountKey,className:e.unattributed?`is-unattributed`:void 0,children:[(0,Z.jsx)(`td`,{children:e.label}),(0,Z.jsx)(`td`,{className:`num`,children:v.pct1(o?.current_percent)}),(0,Z.jsx)(`td`,{className:`d`,children:v.datetimeShortZ(o?.resets_at,n)}),(0,Z.jsxs)(`td`,{className:`num`,children:[v.usd2(e.spendUsd),e.spendWindow!=null&&(0,Z.jsx)(`span`,{className:`mcw-spend-window`,"data-testid":`cycle-row-window`,children:C(e.spendWindow)})]}),(0,Z.jsx)(`td`,{className:`num`,children:v.tokens(e.totalTokens)})]},e.accountKey)})})]})]})}function Tt({note:e}){return e==null?null:(0,Z.jsx)(`p`,{className:`mcw-ms-sub`,"data-testid":`codex-ingest-backlog-note`,children:e})}function Et({env:e,ctx:t,embedded:n=!1}){let r=e?.sources?.codex?.data,i=r?.hero,a=i?.cycle,o=Se(r?.ingest_backlog),s=n?`all`:`codex`,c=de(s,Re(s)),l=c.accountKey,u=c.card?.spendWindow??null,d=l==null&&Array.isArray(r?.accounts)&&r.accounts.length>0,p=Array.isArray(r?.quota.cycle_index)?r.quota.cycle_index:[],m=ut(`codex`,p,l),{weekKey:h,setWeekKey:y,selectedEntry:b,detail:x,loading:S,error:T,vanished:D,blockSel:O,setBlockSel:k,requestCurrentDetail:A,wantDetail:j,pendingBlockStep:M,clearPendingBlockStep:N}=m,P=h!=null,F=P?null:u,ee=r?.quota.histories.filter(e=>e.window_minutes===10080).filter(e=>!e.model_scoped)??[],te=Ae(r?.quota),I=[...ee].filter(e=>te.has(e.key)).sort((e,t)=>(t.current_percent??-1)-(e.current_percent??-1)||(t.captured_at??``).localeCompare(e.captured_at??``))[0],ne=r?.quota.summary.active.find(e=>e.key===I?.key),re=I?.current_percent??ne?.current_percent??null,ie=a?.start_at?Date.parse(a.start_at):NaN,ae=a?.resets_at?Date.parse(a.resets_at):NaN,oe=r?.quota.milestones??[],se=e=>{let t=Date.parse(e.captured_at);return Number.isFinite(ie)&&Number.isFinite(ae)?ie<=t&&t<ae:!0},ce=oe.filter(e=>e.window_minutes===10080&&e.quota_key===I?.key&&e.resets_at===a?.resets_at&&se(e)).sort((e,t)=>e.percent-t.percent||e.captured_at.localeCompare(t.captured_at)),le=r?.quota.histories.find(e=>e.window_minutes===300&&!e.model_scoped),L=r?.quota.blocks.find(e=>e.window_minutes===300&&e.is_active&&!e.orphaned&&(le?.forecast.resets_at==null||e.resets_at===le.forecast.resets_at))??null,ue=L?{block_start_at:L.start_at,five_hour_resets_at:L.end_at,crossed_seven_day_reset:!1}:null,R=oe.filter(e=>e.window_minutes===300&&e.quota_key===le?.key&&se(e)),z=P&&x!=null,fe=z?x.segments[0]?.milestones??[]:[],B=z?x.blocks.flatMap(e=>e.milestones):[],V=z?fe:ce,pe=z?B:R,H=z?V.length?V[V.length-1].percent:0:re,U=et(H),[me,he]=at(H),W=z?V.length?V[V.length-1].cumulative_usd??null:null:i?.cost_usd??null,ge=W!=null&&H!=null&&H>0?W/H:null,_e=ot(V.map(e=>({...e,percent:e.percent}))),ve=!P&&(b?.block_count??0)>0,ye=x!=null&&(P||j),G=ye?x.blocks:[],K=G.length>0,xe=P?-1:G.reduce((e,t,n)=>t.is_closed?e:n,-1),Ce=xe>=0?xe:K?G.length-1:-1,we=(()=>{if(!K)return-1;if(O!=null){let e=G.findIndex(e=>(e.key??e.five_hour_window_key)===O);if(e>=0)return e}return Ce})();(0,X.useEffect)(()=>{if(!(M==null||!ye)){if(K){let e=Ce+M;if(e>=0&&e<G.length){let t=G[e];k(t.key??t.five_hour_window_key??null)}}N()}},[G,ye,N,Ce,K,M,k]);let Te=e=>{if(!P&&!ye){A(e);return}if(!K)return;let t=we+e;if(t<0||t>=G.length)return;let n=G[t];k(n.key??n.five_hour_window_key??null)},Ee=P&&b?nt(b,t):a?`${v.dateShort(a.start_at,t)} → ${v.dateShort(a.resets_at,t)}`:`Native 7-day cycle unavailable`,De=P&&b?b.resets_at_utc??b.end_at_utc:a?.resets_at,Oe=P&&b&&it(b)?`nominal reset`:`reset`,J=e=>n?void 0:e,je=n?`h4`:`h3`,Me=(0,X.useMemo)(()=>{let e=()=>E(_())===`panel`&&_().openModal===`current-week`;return[{key:`ArrowDown`,scope:`modal`,when:e,action:()=>{let e=Ze(p,h,1);e!=null&&y(e)}},{key:`ArrowUp`,scope:`modal`,when:e,action:()=>{h!=null&&y(Ze(p,h,-1))}},{key:`ArrowLeft`,scope:`modal`,when:e,action:()=>Te(-1)},{key:`ArrowRight`,scope:`modal`,when:e,action:()=>Te(1)}]},[p,h,we,G.length,ye]);w(n||d?$e:Me);let Ne=h==null?(0,Z.jsx)(q,{panel:`current-week`,panelLabel:`Current cycle`,triggerId:`current-week-modal`,onClick:()=>g(f(`current-week`,`current-week-modal`))}):null;return D?(0,Z.jsx)(yt,{embedded:n,title:`Cycle — per-percent milestones`,accentClass:`accent-orange`,headerExtras:Ne,children:(0,Z.jsx)(vt,{onBack:()=>y(null)})}):d?(0,Z.jsx)(yt,{embedded:n,title:`Current Cycle — per-account quota`,accentClass:`accent-orange`,headerExtras:Ne,children:(0,Z.jsxs)(`section`,{className:`modal-current-week`,"data-source":`codex`,"data-per-account":``,children:[(0,Z.jsxs)(`div`,{className:`m-chipstrip`,id:J(`mcw-badges`),children:[(0,Z.jsx)(`span`,{className:`m-pill accent-orange`,id:J(`mcw-week-pill`),children:`All accounts`}),(0,Z.jsx)(`span`,{className:`m-pill accent-orange`,children:`native 7-day quota`})]}),(0,Z.jsx)(Tt,{note:o}),(0,Z.jsx)(wt,{accounts:r.accounts,codex:r,ctx:t})]})}):(0,Z.jsx)(yt,{embedded:n,title:P?`Cycle — per-percent milestones`:`Current Cycle — per-percent milestones`,accentClass:`accent-orange`,headerExtras:Ne,children:(0,Z.jsxs)(`section`,{className:`modal-current-week`,"data-source":`codex`,children:[p.length>0?(0,Z.jsx)(dt,{nav:m,pillText:Ee,accentClass:`accent-orange`,singleId:J,unitNoun:`cycle`}):(0,Z.jsxs)(`div`,{className:`m-chipstrip`,id:J(`mcw-badges`),children:[(0,Z.jsx)(`span`,{className:`m-pill accent-orange`,id:J(`mcw-week-pill`),children:Ee}),(0,Z.jsx)(`span`,{className:`m-pill accent-orange`,children:`native 7-day quota`})]}),!n&&!P&&i?.update_state===`updating`?(0,Z.jsx)(`p`,{className:`mcw-ms-sub`,"data-testid":`codex-hero-reconciling-note`,children:be}):null,!n&&!P&&i?.cycle_freshness===`stale`?(0,Z.jsx)(`p`,{className:`mcw-ms-sub`,"data-testid":`codex-cycle-stale-note`,children:ke}):null,P?null:(0,Z.jsx)(Tt,{note:o}),(0,Z.jsxs)(`div`,{className:`mcw-herobar`,children:[(0,Z.jsxs)(`div`,{className:`mcw-bignum`,id:J(`mcw-bignum`),children:[(0,Z.jsx)(`span`,{className:`int`,children:me}),(0,Z.jsx)(`span`,{className:`unit`,children:he})]}),(0,Z.jsxs)(`div`,{className:`mcw-pbar-wrap`,children:[(0,Z.jsxs)(`div`,{className:`mcw-pbar`,children:[(0,Z.jsx)(`div`,{className:`fill`,id:J(`mcw-fill`),style:{width:U+`%`}}),Ye(U)&&(0,Z.jsx)(`div`,{className:`ticks`,id:J(`mcw-ticks`),children:_e.map(e=>(0,Z.jsx)(`div`,{className:`tick`,"data-p":String(e.percent),style:{left:et(e.percent)+`%`}},e.key))}),(0,Z.jsx)(`div`,{className:`marker`,id:J(`mcw-marker`),style:{left:U+`%`}})]}),(0,Z.jsxs)(`div`,{className:`mcw-pscale`,children:[(0,Z.jsx)(`span`,{children:`0%`}),(0,Z.jsx)(`span`,{children:`25%`}),(0,Z.jsx)(`span`,{children:`50%`}),(0,Z.jsx)(`span`,{children:`75%`}),(0,Z.jsx)(`span`,{children:`100%`})]})]}),(0,Z.jsxs)(`div`,{className:`mcw-mini`,id:J(`mcw-mini`),children:[(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:F==null?`spent`:`spent · ${C(F)}`}),(0,Z.jsx)(`span`,{className:`v v-magenta`,children:v.usd2(W)})]}),(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`$ / 1%`}),(0,Z.jsx)(`span`,{className:`v v-cyan`,children:v.usd3(ge)})]}),(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:Oe}),(0,Z.jsx)(`span`,{className:`v`,children:v.datetimeShortZ(De,t)})]})]}),P&&rt(b)&&(0,Z.jsx)(`p`,{className:`mcw-bounds-missing`,children:`This cycle’s exact start and reset were never recorded, so its range and reset time cannot be shown. The milestones below are unaffected.`})]}),(0,Z.jsxs)(je,{className:`m-sec sec-ms`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Milestones`]}),(0,Z.jsxs)(`div`,{className:`mcw-mshead`,children:[(0,Z.jsxs)(`span`,{className:`m-pill accent-orange`,id:J(`mcw-ms-count`),children:[V.length,` crossed`]}),(0,Z.jsx)(`span`,{className:`mcw-ms-sub`,children:`Derived from retained OpenAI quota observations`})]}),S?(0,Z.jsx)(`p`,{className:`empty-state`,children:`Loading…`}):T?(0,Z.jsxs)(`p`,{className:`empty-state`,children:[`Couldn’t load this cycle.`,` `,(0,Z.jsx)(`button`,{type:`button`,className:`m-pill accent-orange`,onClick:()=>m.retry(),children:`Retry`})]}):(0,Z.jsxs)(`table`,{className:`m-histable mcw-table`,id:J(`mcw-table`),children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:`%`}),(0,Z.jsxs)(`th`,{children:[`Crossed (`,t.offsetLabel,`)`]}),(0,Z.jsx)(`th`,{className:`num`,children:`Cumulative $`}),(0,Z.jsx)(`th`,{className:`num`,children:`Marginal $`}),(0,Z.jsx)(`th`,{className:`num`,children:`5h %`})]})}),(0,Z.jsx)(`tbody`,{id:J(`mcw-rows`),children:V.length===0?(0,Z.jsx)(`tr`,{children:(0,Z.jsx)(`td`,{colSpan:5,className:`empty-state`,children:`No integer-percent crossing has been retained in this cycle yet.`})}):V.map(e=>(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`span`,{className:`m-pill accent-orange pct-cell`,children:e.percent})}),(0,Z.jsx)(`td`,{className:`d`,children:v.startedShort(e.captured_at,t,{noSuffix:!0})}),(0,Z.jsx)(`td`,{className:`num`,children:v.usd2(e.cumulative_usd)}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(`span`,{className:`m-marginal`,children:v.usd2(e.marginal_usd)})}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(`span`,{className:`m-fh`,children:v.pct0(lt(e,pe))})})]},e.key))})]}),!T&&(K?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(je,{className:`m-sec sec-ms sec-5h`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`5h blocks`]}),(0,Z.jsx)(pt,{blocks:G,selectedIndex:we,onStep:Te,ctx:t,singleId:J,accentClass:`accent-orange`}),S?(0,Z.jsx)(gt,{id:J(`mcw-block-loading`)}):null]}):ve?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(je,{className:`m-sec sec-ms sec-5h`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`5h blocks`]}),(0,Z.jsx)(mt,{blockCount:b?.block_count??0,block:ue,onStep:Te,ctx:t,singleId:J,accentClass:`accent-orange`}),S?(0,Z.jsx)(gt,{id:J(`mcw-block-loading`)}):null]}):(0,Z.jsx)(`p`,{className:`mcw-ms-sub`,children:`No 5h data retained for this cycle.`}))]})})}function Dt({env:e,ctx:t,display:n,embedded:r=!1}){let i=e?.current_week??null,a=e?.header??null,o=Array.isArray(i?.week_index)?i.week_index:[],s=i?.five_hour_block?.account_key,c=ut(`claude`,o,null,s!=null),{weekKey:l,setWeekKey:u,selectedEntry:d,detail:p,loading:m,error:h,vanished:y,blockSel:b,setBlockSel:x,requestCurrentDetail:S,wantDetail:C,pendingBlockStep:T,clearPendingBlockStep:D}=c,O=l!=null,k=Array.isArray(i?.milestones)?i.milestones:[],A=Array.isArray(i?.five_hour_milestones)?i.five_hour_milestones:[],j=ct(A,Array.isArray(i?.five_hour_block?.credits)?i.five_hour_block.credits:[]),M=i?.five_hour_block?.five_hour_window_key??null,N=e=>e.five_hour_window_key==null?null:e.account_key==null?e.five_hour_window_key:JSON.stringify([e.account_key,e.five_hour_window_key]),P=p!=null&&(O||(d?.segment_count??0)>1||d?.has_observation_gap===!0||C),F=P&&p?Ct(p):null,ee=P&&p?St(p.observation_gap_runs,t):[],te=F?F.rows:O?[]:k.map(e=>({kind:`ms`,m:e,key:`ms-${e.percent}`})),I=F?F.count:O?0:k.length,ne=i?.used_pct,re=i?.spent_usd,ie=i?.dollar_per_pct,ae=i?.reset_at_utc;if(O){let e=(p?.segments[p.segments.length-1]?.milestones)?.slice(-1)[0];ne=p?e?.percent??0:null,re=p?e?.cumulative_usd??null:null,ie=p&&re!=null&&(ne??0)>0?re/ne:null,ae=p?.end_at_utc??null}let oe=et(ne),[se,ce]=at(ne),le=!O||p!=null,L=O&&d?nt(d,t):i?tt(a?.week_label,i.reset_at_utc,t):`—`,ue=ot(te.filter(e=>e.kind===`ms`).map(e=>e.m)),de=P||O?null:st(k),R=e=>r?void 0:e,z=r?`h4`:`h3`,fe=p!=null&&(P||s!=null),B=fe&&p?p.blocks:[],V=B.length>0,pe=(()=>{if(!V)return-1;if(!O&&M!=null){let e=B.findIndex(e=>e.five_hour_window_key===M&&e.account_key===s);if(e>=0)return e}return B.length-1})(),H=(()=>{if(!V)return-1;if(b!=null){let e=B.findIndex(e=>N(e)===b);if(e>=0)return e}return pe})();(0,X.useEffect)(()=>{if(!(T==null||!fe)){if(V){let e=pe+T;e>=0&&e<B.length&&x(N(B[e]))}D()}},[D,pe,V,B,T,x,fe]);let U=H>=0?B[H]:null,me=e=>{if(!O&&!fe){S(e);return}if(!V)return;let t=H+e;t<0||t>=B.length||x(N(B[t]))},he=!O&&U!=null&&U.five_hour_window_key===M&&U.account_key===s,W=U?he?j:ct(U.milestones??[],U.credits??[]):O?[]:j,ge=V,_e=!O&&!fe?d?.block_count??0:0,ve=_e>0,ye=ve&&s!=null,be=i?.five_hour_block?{block_start_at:i.five_hour_block.block_start_at,five_hour_resets_at:_t(i.five_hour_block.block_start_at),crossed_seven_day_reset:i.five_hour_block.crossed_seven_day_reset}:null,G=(0,X.useMemo)(()=>{let e=()=>E(_())===`panel`&&_().openModal===`current-week`;return[{key:`ArrowDown`,scope:`modal`,when:e,action:()=>{let e=Ze(o,l,1);e!=null&&u(e)}},{key:`ArrowUp`,scope:`modal`,when:e,action:()=>{l!=null&&u(Ze(o,l,-1))}},{key:`ArrowLeft`,scope:`modal`,when:e,action:()=>me(-1)},{key:`ArrowRight`,scope:`modal`,when:e,action:()=>me(1)}]},[o,l,H,B.length,P]);w(r?$e:G);let K=l==null?(0,Z.jsx)(q,{panel:`current-week`,panelLabel:`Current week`,triggerId:`current-week-modal`,onClick:()=>g(f(`current-week`,`current-week-modal`))}):null;return y?(0,Z.jsx)(yt,{embedded:r,title:`Cycle — per-percent milestones`,accentClass:`accent-green`,headerExtras:K,children:(0,Z.jsx)(vt,{onBack:()=>u(null)})}):(0,Z.jsx)(yt,{embedded:r,title:O?`Cycle — per-percent milestones`:`Current Cycle — per-percent milestones`,accentClass:`accent-green`,headerExtras:K,children:(0,Z.jsxs)(`section`,{className:`modal-current-week`,"data-source":`claude`,children:[o.length>0?(0,Z.jsx)(dt,{nav:c,pillText:L,accentClass:`accent-green`,singleId:R,unitNoun:`cycle`}):(0,Z.jsx)(`div`,{className:`m-chipstrip`,id:R(`mcw-badges`),children:(0,Z.jsx)(`span`,{className:`m-pill accent-green`,id:R(`mcw-week-pill`),children:L})}),le&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`mcw-herobar`,children:[(0,Z.jsxs)(`div`,{className:`mcw-bignum`,id:R(`mcw-bignum`),children:[(0,Z.jsx)(`span`,{className:`int`,children:se}),(0,Z.jsx)(`span`,{className:`unit`,children:ce})]}),(0,Z.jsxs)(`div`,{className:`mcw-pbar-wrap`,children:[(0,Z.jsxs)(`div`,{className:`mcw-pbar`,children:[(0,Z.jsx)(`div`,{className:`fill`,id:R(`mcw-fill`),style:{width:oe+`%`}}),Ye(oe)&&(0,Z.jsx)(`div`,{className:`ticks`,id:R(`mcw-ticks`),children:ue.map(e=>(0,Z.jsx)(`div`,{className:`tick`,"data-p":String(e.percent),style:{left:et(e.percent)+`%`}},e.percent))}),(0,Z.jsx)(`div`,{className:`marker`,id:R(`mcw-marker`),style:{left:oe+`%`}})]}),(0,Z.jsxs)(`div`,{className:`mcw-pscale`,children:[(0,Z.jsx)(`span`,{children:`0%`}),(0,Z.jsx)(`span`,{children:`25%`}),(0,Z.jsx)(`span`,{children:`50%`}),(0,Z.jsx)(`span`,{children:`75%`}),(0,Z.jsx)(`span`,{children:`100%`})]})]}),(0,Z.jsxs)(`div`,{className:`mcw-mini`,id:R(`mcw-mini`),children:[(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`spent`}),(0,Z.jsx)(`span`,{className:`v v-magenta`,id:R(`mcw-spent`),children:v.usd2(re)})]}),(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`$ / 1%`}),(0,Z.jsx)(`span`,{className:`v v-cyan`,id:R(`mcw-dpp`),children:v.usd3(ie)})]}),(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`reset`}),(0,Z.jsx)(`span`,{className:`v`,id:R(`mcw-reset`),children:v.datetimeShortZ(ae,t)})]})]}),O&&rt(d)&&(0,Z.jsx)(`p`,{className:`mcw-bounds-missing`,children:`This cycle’s exact start and reset were never recorded, so its range and reset time cannot be shown. The milestones below are unaffected.`})]}),(0,Z.jsxs)(z,{className:`m-sec sec-ms`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Milestones`]}),(0,Z.jsxs)(`div`,{className:`mcw-mshead`,children:[(0,Z.jsxs)(`span`,{className:`m-pill accent-purple`,id:R(`mcw-ms-count`),children:[I,` crossed`]}),(0,Z.jsx)(`span`,{className:`mcw-ms-sub`,id:R(`mcw-ms-sub`),hidden:!de,children:de??``})]}),ee.length>0&&(0,Z.jsx)(`ul`,{className:`mcw-gap-notes`,id:R(`mcw-gap-notes`),children:ee.map((e,t)=>(0,Z.jsx)(`li`,{children:e},`gap-${t}`))})]}),m||O&&p==null&&!h?(0,Z.jsx)(`p`,{className:`empty-state`,children:`Loading…`}):h?(0,Z.jsxs)(`p`,{className:`empty-state`,id:R(`mcw-error`),children:[`Couldn’t load this cycle.`,` `,(0,Z.jsx)(`button`,{type:`button`,className:`m-pill accent-green`,onClick:()=>c.retry(),children:`Retry`})]}):I===0?(0,Z.jsx)(`p`,{className:`empty-state`,id:R(`mcw-empty`),children:O?`No milestones recorded this cycle`:`No milestones yet — earliest crosses at 1\xA0%.`}):(0,Z.jsxs)(`table`,{className:`m-histable mcw-table`,id:R(`mcw-table`),children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:`%`}),(0,Z.jsxs)(`th`,{children:[`Crossed (`,n.offsetLabel,`)`]}),(0,Z.jsx)(`th`,{className:`num`,children:`Cumulative $`}),(0,Z.jsx)(`th`,{className:`num`,children:`Marginal $`}),(0,Z.jsx)(`th`,{className:`num`,children:`5h %`})]})}),(0,Z.jsx)(`tbody`,{id:R(`mcw-rows`),children:te.map(e=>e.kind===`divider`?(0,Z.jsx)(`tr`,{className:`mcw-5h-credit-row`,children:(0,Z.jsxs)(`td`,{colSpan:5,className:`mcw-5h-credit-cell`,children:[`⚡ CREDIT\xA0@`,` `,v.startedShort(e.effectiveAt,t,{noSuffix:!0}),e.priorPercent==null?``:` · from ${e.priorPercent}%`]})},e.key):(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`span`,{className:`m-pill accent-purple pct-cell`,children:e.m.percent??`—`})}),(0,Z.jsx)(`td`,{className:`d`,children:v.startedShort(e.m.crossed_at_utc,t,{noSuffix:!0})}),(0,Z.jsx)(`td`,{className:`num`,children:e.m.cumulative_usd==null?`—`:`$`+e.m.cumulative_usd.toFixed(2)}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(`span`,{className:`m-marginal`,children:e.m.marginal_usd==null?e.m.marginal_usd_withheld_cause?`observation gap`:`—`:`$`+e.m.marginal_usd.toFixed(2)})}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(`span`,{className:`m-fh`,children:e.m.five_hour_pct_at_cross==null?`—`:Math.round(e.m.five_hour_pct_at_cross)+`%`})})]},e.key))})]}),(!h||!O&&s!=null)&&(ge||ve||W.length>0)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(z,{className:`m-sec sec-ms sec-5h`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`5h milestones`]}),ge?(0,Z.jsx)(pt,{blocks:B,selectedIndex:H,onStep:me,ctx:t,singleId:R,accentClass:`accent-purple`}):ye?(0,Z.jsx)(ht,{block:be,ctx:t,singleId:R,accentClass:`accent-purple`}):ve?(0,Z.jsx)(mt,{blockCount:_e,block:be,onStep:me,ctx:t,singleId:R,accentClass:`accent-purple`}):(0,Z.jsx)(`div`,{className:`mcw-mshead`,children:(0,Z.jsxs)(`span`,{className:`m-pill accent-purple`,id:R(`mcw-5h-count`),children:[A.length,` crossed`]})}),m&&(O||s==null)?(0,Z.jsx)(gt,{id:R(`mcw-5h-loading`)}):W.length===0?(0,Z.jsx)(`p`,{className:`empty-state`,id:R(`mcw-5h-empty`),children:`No integer-percent crossings in this block.`}):(0,Z.jsxs)(`table`,{className:`m-histable mcw-5h-table`,id:R(`mcw-5h-table`),children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:`%`}),(0,Z.jsxs)(`th`,{children:[`When (`,n.offsetLabel,`)`]}),(0,Z.jsx)(`th`,{className:`num`,children:`Block $`}),(0,Z.jsx)(`th`,{className:`num`,children:`Marginal $`}),(0,Z.jsx)(`th`,{className:`num`,children:`7d %`})]})}),(0,Z.jsx)(`tbody`,{children:W.map((e,n)=>{if(e.kind===`credit`)return(0,Z.jsx)(`tr`,{className:`mcw-5h-credit-row`,children:(0,Z.jsxs)(`td`,{colSpan:5,className:`mcw-5h-credit-cell`,children:[`⚡ CREDIT\xA0`,` `,e.data.delta_pp>0?`+`:``,e.data.delta_pp.toFixed(0),`pp\xA0@`,` `,v.startedShort(e.ts,t,{noSuffix:!0})]})},`credit-${n}-${e.ts}`);let r=e.data;return(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`span`,{className:`m-pill accent-purple pct-cell`,children:r.percent_threshold})}),(0,Z.jsx)(`td`,{className:`d`,children:v.startedShort(r.captured_at_utc,t,{noSuffix:!0})}),(0,Z.jsx)(`td`,{className:`num`,children:`$`+r.block_cost_usd.toFixed(2)}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(`span`,{className:`m-marginal`,children:r.marginal_cost_usd==null?`—`:`$`+r.marginal_cost_usd.toFixed(2)})}),(0,Z.jsx)(`td`,{className:`num`,children:(0,Z.jsx)(`span`,{className:`m-fh`,children:r.effective_seven_day_pct_at_crossing==null?`—`:Math.round(r.effective_seven_day_pct_at_crossing)+`%`})})]},`fhms-${r.percent_threshold}-${r.reset_event_id}`)})})]})]})]})})}function Ot(e,t){let n=e?.sources?.[t];if(t===`codex`&&kt(n))return be;let r=we(n?.warnings,`hero`);if(r!=null)return r.message;if(n?.availability===`unavailable`)return`${t===`claude`?`Claude`:`Codex`} source data is unavailable.`;if(n?.capabilities?.hero?.status===`unavailable`)return t===`claude`?`Claude current-week usage is unavailable.`:`Codex native reset cycle is unavailable.`;if(t===`claude`&&e?.current_week==null)return`Claude current-week usage is unavailable.`;let i=n?.data;return t===`codex`&&i?.hero?.cycle==null?`Codex native reset cycle is unavailable.`:null}function kt(e){return(e?.data)?.hero?.update_state===`updating`}function At(e){let t=[];if(e==null)return t;for(let n of[`claude`,`codex`]){let r=e[n];if(r.scope!==`account_cycles`)continue;let i=new Map;for(let e of r.accounts??[]){let t=e.period,r=`${t.kind}\0${t.start_at}\0${t.end_at}`,a=i.get(r);if(a!=null){a.count+=1;continue}i.set(r,{key:`${n}\0${r}`,provider:n===`claude`?`Claude`:`Codex`,periodLabel:t.kind===`subscription_week`?`subscription week`:t.kind===`native_7_day_cycle`?`native 7-day cycle`:`trailing 7-day cycle`,startAt:t.start_at,endAt:t.end_at,count:1})}t.push(...i.values())}return t}function jt({env:e,ctx:t,display:n}){let r=Ot(e,`claude`),i=Ot(e,`codex`),a=e?.sources?.all,o=ce(a??null),s=At(o.legs);return(0,Z.jsxs)(Y,{title:`Current Usage — provider cycles`,accentClass:`accent-blue`,wide:!0,triggerId:De,headerExtras:(0,Z.jsx)(q,{panel:`current-week`,panelLabel:`Current usage`,triggerId:`current-week-modal`,onClick:()=>g(f(`current-week`,`current-week-modal`))}),children:[o.unavailable!=null&&(0,Z.jsxs)(`p`,{className:`provider-section-reason`,"data-testid":`all-current-week-reason`,children:[(0,Z.jsx)(`span`,{className:`panel-degraded-chip`,"data-testid":`all-current-week-withheld-marker`,title:o.unavailable.message,"aria-label":o.unavailable.message,children:`Combined withheld`}),(0,Z.jsx)(`span`,{children:o.unavailable.message})]}),o.qualifications.map(e=>(0,Z.jsx)(`p`,{className:`provider-section-reason`,"data-testid":`all-current-week-qualification`,"data-code":e.code,children:(0,Z.jsx)(`span`,{children:e.message})},e.code+(e.provider??``))),s.length>0&&(0,Z.jsxs)(`section`,{className:`provider-section-reason all-account-cycle-ranges`,"data-testid":`all-account-cycle-ranges`,"aria-labelledby":`all-account-cycle-ranges-heading`,children:[(0,Z.jsx)(`h3`,{id:`all-account-cycle-ranges-heading`,children:`Account cycles`}),(0,Z.jsx)(`ul`,{children:s.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsxs)(`strong`,{children:[e.provider,` `,e.periodLabel,` · `,e.count,` `,e.count===1?`account`:`accounts`]}),` `,(0,Z.jsx)(`time`,{dateTime:e.startAt,children:v.startedShort(e.startAt,t)}),` – `,(0,Z.jsx)(`time`,{dateTime:e.endAt,children:v.startedShort(e.endAt,t)})]},e.key))})]}),(0,Z.jsxs)(`div`,{className:`provider-composition provider-composition--modal current-week-provider-composition`,children:[(0,Z.jsxs)(`section`,{className:`source-provider-section provider-composition-section current-week-provider-section`,"data-provider-section":`claude`,"aria-labelledby":`current-usage-claude-heading`,children:[(0,Z.jsxs)(`div`,{className:`source-provider-head provider-composition-head`,children:[(0,Z.jsx)(`h3`,{className:`sr-only`,id:`current-usage-claude-heading`,children:`Claude subscription week`}),(0,Z.jsx)(ie,{source:`claude`}),(0,Z.jsx)(`span`,{children:`subscription week`})]}),r&&(0,Z.jsx)(`p`,{className:`provider-section-reason`,children:r}),(0,Z.jsx)(Dt,{env:e,ctx:t,display:n,embedded:!0})]}),(0,Z.jsxs)(`section`,{className:`source-provider-section provider-composition-section current-week-provider-section`,"data-provider-section":`codex`,"aria-labelledby":`current-usage-codex-heading`,children:[(0,Z.jsxs)(`div`,{className:`source-provider-head provider-composition-head`,children:[(0,Z.jsx)(`h3`,{className:`sr-only`,id:`current-usage-codex-heading`,children:`Codex native 7-day quota`}),(0,Z.jsx)(ie,{source:`codex`}),(0,Z.jsx)(`span`,{children:`native 7-day quota`})]}),i&&(0,Z.jsx)(`p`,{className:`provider-section-reason`,children:i}),(0,Z.jsx)(Et,{env:e,ctx:t,embedded:!0})]})]})]})}function Mt(){let e=P(),t=(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource),n=W(),r={tz:n.resolvedTz,offsetLabel:n.offsetLabel};return t===`codex`?(0,Z.jsx)(Et,{env:e,ctx:r}):t===`all`?(0,Z.jsx)(jt,{env:e,ctx:r,display:n}):(0,Z.jsx)(Dt,{env:e,ctx:r,display:n})}function Nt({env:e,source:t,verdict:n}){if(n!==`cap`&&n!==`capped`)return null;let r=te(t===`claude`?e?.current_week?.reset_at_utc??null:e?.sources?.codex?.data?.hero?.cycle?.resets_at??null);if(r==null)return null;let i=R({id:``,axis:`weekly`,threshold:0,crossed_at:``,alerted_at:``,context:{week_start_at:new Date(r-168*3600*1e3).toISOString()}},t===`claude`?e:{...e??{},current_week:null},fe(e));if(!i.available||i.target==null){let e=i.explainTarget==null?null:{...i.explainTarget,source:t};return(0,Z.jsxs)(`span`,{className:`alert-row-unresolved`,children:[(0,Z.jsx)(`span`,{className:`alert-row-withheld`,children:i.withheldReason}),e==null?null:(0,Z.jsx)(`button`,{type:`button`,className:`alert-row-explain`,onClick:()=>I(e),children:e.label})]})}let a={...i.target,source:t};return(0,Z.jsx)(`button`,{type:`button`,className:`alert-row-open mfc-explain`,onClick:()=>I(a),children:a.label})}function Pt(e){if(!e)return`—`;let t=e.elapsed_hours,n=e.remaining_hours;if(t==null||n==null)return`—`;let r=t+n;if(r<=0)return`—`;let i=t/r*100;return Math.min(100,i).toFixed(1)+`%`}function Ft(e){return e==null||!isFinite(e)?null:e<0?0:e>110?110:e}function It(e){return e==null||!isFinite(e)?`—`:e<0?`~`+(+e).toFixed(1)+`%`:(+e).toFixed(1)+`%`}function Lt(e,t,n=8){let r=e.map(e=>({...e,trueXPct:e.pos/110*100,resolvedXPct:e.pos/110*100}));if(t<=0)return{collapsed:!1,pins:r};for(let e of r){let n=Math.min(e.pillWidthPx/2,t/2),r=e.trueXPct/100*t;e.resolvedXPct=Math.max(n,Math.min(t-n,r))/t*100}if(r.length<2)return{collapsed:!1,pins:r};let i=e[0],a=e[1];if(i.pillWidthPx+n+a.pillWidthPx>t){let e=Math.min(i.raw,a.raw),t=Math.max(i.raw,a.raw);return{collapsed:!0,rangeText:`${e.toFixed(1)}–${t.toFixed(1)}%`}}let o=r.slice().sort((e,t)=>e.trueXPct-t.trueXPct),s=o[0],c=o[1],l=s.pillWidthPx/2,u=c.pillWidthPx/2,d=l+u+n,f=s.resolvedXPct/100*t,p=c.resolvedXPct/100*t;if(p-f<d){let e=(f+p)/2;f=e-d/2,p=e+d/2;let n=l,r=t-u;f<n&&(f=n,p=Math.max(p,f+d)),p>r&&(p=r,f=Math.min(f,p-d)),f<n&&(f=n)}return s.resolvedXPct=f/t*100,c.resolvedXPct=p/t*100,{collapsed:!1,pins:r}}function Rt(e,t,n,r){let i=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let a=e.current,o=t.current;if(!a||!o||!n)return;let s=a.querySelector(`.mfc-pills`),c=a.querySelector(`.mfc-leaders`),l=o.querySelector(`.mfc-rangeband`);if(!s||!c)return;let u=n.week_avg_projection_pct,d=n.recent_24h_projection_pct,f=Ft(u),p=Ft(d),m=[];f!=null&&u!=null&&m.push({kind:`wa`,pos:f,raw:u}),p!=null&&d!=null&&m.push({kind:`r24`,pos:p,raw:d});let h=new Set(m.map(e=>e.kind));i.current&&h.add(`range`),o.querySelectorAll(`.mfc-chev`).forEach(e=>{let t=e.dataset.kind;(!t||!h.has(t))&&e.remove()}),s.querySelectorAll(`.mfc-pill`).forEach(e=>{let t=e.dataset.kind;(!t||!h.has(t))&&e.remove()});let g=m.map(e=>({...e}));for(let e of g){let t=e.pos/110*100,n=o.querySelector(`.mfc-chev[data-kind="${e.kind}"]`);n||(n=document.createElement(`div`),n.className=`mfc-chev `+e.kind,n.dataset.kind=e.kind,o.appendChild(n)),n.style.left=t+`%`;let r=s.querySelector(`.mfc-pill[data-kind="${e.kind}"]`),i=It(e.raw);r?r.textContent!==i&&(r.textContent=i):(r=document.createElement(`div`),r.className=`mfc-pill `+e.kind,r.dataset.kind=e.kind,r.textContent=i,s.appendChild(r)),e.pillEl=r}if(l){let e=!1;if(g.length===2){let t=g[0].pos/110*100,n=g[1].pos/110*100,r=Math.min(t,n),i=Math.max(t,n)-r;i>=.5&&(l.style.left=r+`%`,l.style.width=i+`%`,e=!0)}l.hidden=!e}{let e=o.querySelector(`.mfc-now`),t=Ft(r);if(t==null)e&&e.remove();else{if(!e){e=document.createElement(`div`),e.className=`mfc-now`;let t=document.createElement(`span`);t.className=`mfc-now-glyph`,t.textContent=`▸`,e.appendChild(t),o.appendChild(e)}e.style.left=t/110*100+`%`}}let _=null,v=()=>{if(!a.isConnected)return;for(let e of g)if(!e.pillEl||!e.pillEl.isConnected)return;let e=a.clientWidth;if(e<=0){y();return}let t=Lt(g.map(e=>({kind:e.kind,pos:e.pos,raw:e.raw,pillWidthPx:e.pillEl.getBoundingClientRect().width})),e);i.current=t.collapsed;let n=o.querySelectorAll(`.mfc-chev`);if(t.collapsed){for(let e of g)e.pillEl.style.display=`none`;for(n.forEach(e=>{e.style.display=`none`});c.firstChild;)c.removeChild(c.firstChild);let e=s.querySelector(`.mfc-pill.range`);e||(e=document.createElement(`div`),e.className=`mfc-pill range`,e.dataset.kind=`range`,s.appendChild(e));let r=t.rangeText??``;e.textContent!==r&&(e.textContent=r),e.style.left=`50%`;return}s.querySelectorAll(`.mfc-pill.range`).forEach(e=>e.remove());for(let e of g)e.pillEl.style.display=``;n.forEach(e=>{e.style.display=``});let r=t.pins??[],l=new Map(r.map(e=>[e.kind,e]));for(let e of g){let t=l.get(e.kind);t&&(e.pillEl.style.left=t.resolvedXPct+`%`)}for(;c.firstChild;)c.removeChild(c.firstChild);for(let e of r){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);t.setAttribute(`class`,e.kind),t.setAttribute(`vector-effect`,`non-scaling-stroke`),t.setAttribute(`d`,`M ${e.resolvedXPct} 0 C ${e.resolvedXPct} 10, ${e.trueXPct} 8, ${e.trueXPct} 18`),c.appendChild(t)}};function y(){_!=null&&cancelAnimationFrame(_),_=requestAnimationFrame(()=>{_=null,v()})}v();let b=null;return typeof ResizeObserver<`u`&&(b=new ResizeObserver(()=>y()),b.observe(a)),()=>{_!=null&&cancelAnimationFrame(_),b&&b.disconnect()}},[e,t,n,r])}function zt({rows:e}){return(0,Z.jsxs)(`div`,{"data-testid":`codex-forecast-per-account`,children:[(0,Z.jsx)(`p`,{className:`mcw-ms-sub`,"data-testid":`codex-forecast-per-account-note`,children:`Each account has its own quota cycle, so there is no single merged projection, rate or daily budget. Every row below is that account’s own — pick an account chip for its full forecast.`}),(0,Z.jsxs)(`table`,{className:`m-histable mcw-table mcw-per-account-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{children:`Account`}),(0,Z.jsx)(`th`,{className:`num`,children:`Projected @ reset`}),(0,Z.jsx)(`th`,{className:`num`,children:`Current quota`}),(0,Z.jsx)(`th`,{children:`Confidence`}),(0,Z.jsx)(`th`,{children:`Verdict`})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>{let t=He(e.verdict);return(0,Z.jsxs)(`tr`,{"data-testid":`forecast-account-row`,"data-account-key":e.accountKey,className:e.unattributed?`is-unattributed`:void 0,children:[(0,Z.jsx)(`td`,{children:e.label}),(0,Z.jsx)(`td`,{className:`num${e.projected==null?` m-unavailable`:``}`,children:v.pct1(e.projected)}),(0,Z.jsx)(`td`,{className:`num${e.current==null?` m-unavailable`:``}`,children:v.pct1(e.current)}),(0,Z.jsx)(`td`,{className:e.confidence==null?`m-unavailable`:void 0,children:e.confidence??`—`}),(0,Z.jsx)(`td`,{children:t?(0,Z.jsxs)(`span`,{className:`fc-verdict-chip is-${t.cls}`,children:[(0,Z.jsx)(`span`,{className:`fc-verdict-glyph`,"aria-hidden":`true`,children:t.glyph}),` `,t.label]}):(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`—`})})]},e.accountKey)})})]})]})}function Bt(e,t){return t!=null||a(e?.sources?.codex??null)==null?null:V(e)}function Vt({section:e,perAccountRows:t}){let n=e.value,r=t==null?He(n?.verdict??null):null;return(0,Z.jsxs)(`section`,{className:`modal-forecast provider-composition-section`,"data-source":e.source,"data-provider-section":e.source,"aria-labelledby":`forecast-modal-${e.source}-heading`,children:[(0,Z.jsxs)(`div`,{className:`source-provider-head provider-composition-head`,children:[(0,Z.jsxs)(`h3`,{className:`sr-only`,id:`forecast-modal-${e.source}-heading`,children:[e.label,` forecast detail`]}),(0,Z.jsx)(ie,{source:e.source}),(0,Z.jsxs)(`strong`,{children:[e.label,` forecast`]}),e.status!==`available`&&t==null&&(0,Z.jsx)(`span`,{className:`provider-section-status`,children:e.status})]}),t==null?n==null?(0,Z.jsx)(`div`,{className:`provider-section-reason m-unavailable`,children:e.reason}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`m-chipstrip`,children:[(0,Z.jsx)(`span`,{className:r?`m-pill ${r.accent}`:`m-pill`,children:r?`${r.glyph} ${r.label}`:`—`}),e.reason&&(0,Z.jsx)(`span`,{className:`m-pill m-unavailable`,children:e.reason})]}),(0,Z.jsxs)(`div`,{className:`m-hero cols-2`,children:[(0,Z.jsxs)(`div`,{className:`m-kv kv-wa`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#gauge`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v${n.projected==null?` m-unavailable`:``}`,children:v.pct1(n.projected)}),(0,Z.jsx)(`div`,{className:`lbl`,children:n.primaryLabel})]})]}),(0,Z.jsxs)(`div`,{className:`m-kv kv-r24`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#zap`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v${n.recent==null?` m-unavailable`:``}`,children:v.pct1(n.recent)}),(0,Z.jsx)(`div`,{className:`lbl`,children:n.recentLabel})]})]})]}),(0,Z.jsx)(`h4`,{className:`m-sec sec-range`,children:`Range vs. caps`}),(0,Z.jsx)(`div`,{className:`mfc-rangewrap provider-range-summary`,role:`group`,"aria-label":`${e.label} projected usage against caps`,children:(0,Z.jsxs)(`div`,{className:`mfc-rangetrack`,children:[(0,Z.jsx)(`div`,{className:`mfc-zone safe`}),(0,Z.jsx)(`div`,{className:`mfc-zone warn`}),(0,Z.jsx)(`div`,{className:`mfc-zone over`}),(0,Z.jsx)(`div`,{className:`provider-range-marker`,style:{left:`${Math.min(100,Math.max(0,n.projected??0))/1.1}%`}}),(0,Z.jsx)(`div`,{className:`mfc-bound b0`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`0%`})}),(0,Z.jsx)(`div`,{className:`mfc-bound b90`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`90%`})}),(0,Z.jsx)(`div`,{className:`mfc-bound b100`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`100%`})}),(0,Z.jsx)(`div`,{className:`mfc-bound b110`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`110%`})})]})}),(0,Z.jsx)(`h4`,{className:`m-sec sec-rates`,children:`Provider-native projection`}),(0,Z.jsxs)(`div`,{className:`mfc-kvgrid`,children:[(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`Projected`}),(0,Z.jsx)(`span`,{className:`v v-cyan`,children:v.pct1(n.projected)})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`Current / recent`}),(0,Z.jsx)(`span`,{className:`v v-green`,children:v.pct1(n.recent)})]})]}),(0,Z.jsx)(`h4`,{className:`m-sec sec-bud`,children:e.source===`claude`?`Daily budgets to the quota caps`:`Forecast confidence`}),(0,Z.jsx)(`div`,{className:`mfc-kvgrid mfc-kvgrid-single`,children:n.foot.map(e=>(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:e.label}),(0,Z.jsx)(`span`,{className:`v${e.value===`—`||e.value===`unavailable`?` m-unavailable`:``}`,children:e.value})]},e.label))})]}):(0,Z.jsx)(zt,{rows:t})]})}function Ht(){let e=P(`all`),t=D(e,`all`),n=Bt(e,de(`all`,Re(`all`)).accountKey);return(0,Z.jsx)(Y,{title:`Forecast — by provider`,accentClass:`accent-purple`,headerExtras:(0,Z.jsx)(q,{panel:`forecast`,panelLabel:`Forecast`,triggerId:`forecast-modal`,onClick:()=>g(f(`forecast`,`forecast-modal`))}),children:(0,Z.jsxs)(`div`,{className:`provider-composition provider-composition--modal`,"aria-label":`Claude and Codex forecast reports`,children:[t.sections.map(e=>(0,Z.jsx)(Vt,{section:e,perAccountRows:e.source===`codex`?n:null},e.source)),(0,Z.jsx)(z,{env:e,selection:`all`,surface:`modal`})]})})}function Ut({env:e}){let t=W(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=e?.forecast?.quota??null;if(r==null)return null;let i=L(r.basis_presentation,r.basis),a=r.rate_change,o=A(a?.previous_units_per_point,a?.new_units_per_point),s=r.observed_minus_modelled_pct;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`h3`,{className:`m-sec sec-quota`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`Quota model`]}),(0,Z.jsxs)(`div`,{className:`mfc-kvgrid`,"data-testid":`mfc-quota`,children:[(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`basis`}),(0,Z.jsx)(`span`,{className:`v`,id:`mfc-quota-basis`,children:i})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`modelled consumption`}),(0,Z.jsx)(`span`,{className:`v${r.calibrated_consumption_pct==null?` m-unavailable`:``}`,children:v.pct1(r.calibrated_consumption_pct)})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`modelled headroom`}),(0,Z.jsx)(`span`,{className:`v${r.calibrated_headroom_pct==null?` m-unavailable`:``}`,children:v.pct1(r.calibrated_headroom_pct)})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`meter reading covers`}),(0,Z.jsx)(`span`,{className:`v`,children:r.corrected_interval==null?`—`:r.corrected_interval.hi==null?`${v.pct1(r.corrected_interval.lo)} or more`:`${v.pct1(r.corrected_interval.lo)} – ${v.pct1(r.corrected_interval.hi)}`})]})]}),r.code&&(0,Z.jsx)(`p`,{className:`mfc-rate-note`,"data-testid":`mfc-quota-code`,children:Ue(r.code_presentation,r.code)}),r.calibration_code&&(0,Z.jsxs)(`p`,{className:`mfc-rate-note`,"data-testid":`mfc-quota-calibration-code`,children:[`The calibrated model was not used: `,Ue(r.calibration_code_presentation,r.calibration_code),`.`]}),a?.active===!0&&(0,Z.jsxs)(`p`,{className:`mfc-rate-note`,"data-testid":`mfc-quota-rate-change`,children:[`The provider changed its metering rate`,a.effective_from?` effective ${v.dateShort(a.effective_from,n)}`:``,o?`: ${o}`:``,`. This is the provider’s behaviour, not a cctally malfunction.`]}),s!=null&&(0,Z.jsxs)(`p`,{className:`mfc-rate-note`,"data-testid":`mfc-quota-residual`,children:[`Observed meter minus modelled local quota:`,` `,(0,Z.jsxs)(`span`,{className:`num`,children:[s>=0?`+`:``,s.toFixed(2)]}),` `,`points, as measured. This is a difference between two quantities, not an identification or an estimate of usage from another machine.`]})]})}function Wt({source:e}){let t=P(e),n=de(),r=e===`claude`,i=r?null:Bt(t,n.accountKey),a=le(t,e),o=(t?.sources?.codex?.data?.quota.histories??[]).filter(e=>!e.model_scoped),s=o.find(e=>e.window_minutes===10080)??o[0],c=s?.forecast,l=s!=null&&Ae(t?.sources?.codex?.data?.quota).has(s.key)?c?.rate_percent_per_hour??null:null,u=c?.remaining_seconds==null?null:c.remaining_seconds/3600,d=s?.window_minutes==null||u==null?null:Math.max(0,s.window_minutes/60-u),p=ve(t,`codex`,`weekly`)[0]?.dollar_per_pct??null,m=s?.current_percent??null,h=u==null?null:u/24,_=p==null||m==null||!h?null:Math.max(0,100-m)*p/h,y=p==null||m==null||!h?null:Math.max(0,90-m)*p/h,b=r?t?.forecast??null:{verdict:a.verdict??`ok`,week_avg_projection_pct:a.projected,recent_24h_projection_pct:a.recent,budget_100_per_day_usd:_,budget_90_per_day_usd:y,confidence:c?.confidence===`high`?`high`:`unknown`,confidence_score:0,explain:{rates:{dollars_per_percent:p,week_average_pct_per_hour:l,recent_24h_pct_per_hour:null},week:{elapsed_hours:d,remaining_hours:u}}},x=b?.explain??null,S=(0,X.useRef)(null),C=(0,X.useRef)(null);Rt(S,C,b,r?t?.header?.used_pct??t?.current_week?.used_pct??null:a.recent);let w=(0,Z.jsx)(q,{panel:`forecast`,panelLabel:`Forecast`,triggerId:`forecast-modal`,onClick:()=>g(f(`forecast`,`forecast-modal`))}),T=He(r?b?.verdict:a.verdict),E=T?`m-pill ${T.accent}`:`m-pill`,D=T?`${T.glyph} ${T.label}`:`—`,O=`m-pill`,k=`—`,A=!0;b?.confidence===`high`?(O=`m-pill accent-blue`,k=`high confidence`,A=!1):b?.confidence===`low`&&(O=`m-pill accent-red`,k=`low confidence`,A=!1);let j=x?.rates,N=x?.week;return i==null?(0,Z.jsxs)(Y,{title:`Forecast — explain`,accentClass:`accent-purple`,headerExtras:w,children:[(0,Z.jsxs)(`section`,{className:`modal-forecast`,"data-source":e,children:[(0,Z.jsxs)(`div`,{className:`m-chipstrip`,id:`mfc-chips`,children:[(0,Z.jsx)(`span`,{className:E,id:`mfc-verdict`,children:D}),(0,Z.jsx)(`span`,{className:O,id:`mfc-confidence`,hidden:A,children:k}),(0,Z.jsx)(Nt,{env:t,source:e,verdict:r?b?.verdict:a.verdict}),!r&&(0,Z.jsx)(`span`,{className:`m-pill ${Je(`codex`)}`,children:`Codex native quota`}),(r&&!b||!r&&c==null)&&(0,Z.jsx)(`span`,{className:`m-pill m-unavailable`,children:`Forecast unavailable`})]}),(0,Z.jsxs)(`div`,{className:`m-hero cols-2`,children:[(0,Z.jsxs)(`div`,{className:`m-kv kv-wa`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#gauge`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v${b?.week_avg_projection_pct==null&&!r?` m-unavailable`:``}`,id:`mfc-wa-pct`,children:v.pct1(b?.week_avg_projection_pct)}),(0,Z.jsx)(`div`,{className:`lbl`,children:r?`Week-avg projection`:a.primaryLabel}),(0,Z.jsx)(`div`,{className:`sub`,id:`mfc-wa-sub`,children:v.ratePctPerHour(j?.week_average_pct_per_hour)})]})]}),(0,Z.jsxs)(`div`,{className:`m-kv kv-r24`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#zap`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v${b?.recent_24h_projection_pct==null&&!r?` m-unavailable`:``}`,id:`mfc-r24-pct`,children:v.pct1(b?.recent_24h_projection_pct)}),(0,Z.jsx)(`div`,{className:`lbl`,children:r?`Recent-24h projection`:a.recentLabel}),(0,Z.jsx)(`div`,{className:`sub`,id:`mfc-r24-sub`,children:v.ratePctPerHour(j?.recent_24h_pct_per_hour)})]})]})]}),(0,Z.jsx)(Ut,{env:t}),(0,Z.jsxs)(`h3`,{className:`m-sec sec-range`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#bar-chart`})}),`Range vs. caps`]}),(0,Z.jsxs)(`div`,{className:`mfc-legend`,id:`mfc-legend`,children:[(0,Z.jsxs)(`span`,{className:`mfc-leg-item`,children:[(0,Z.jsx)(`span`,{className:`mfc-leg-sw wa`}),r?`week-avg`:`projected`]}),(0,Z.jsxs)(`span`,{className:`mfc-leg-item`,children:[(0,Z.jsx)(`span`,{className:`mfc-leg-sw r24`}),r?`recent-24h`:`current`]}),(0,Z.jsxs)(`span`,{className:`mfc-leg-item`,children:[(0,Z.jsx)(`span`,{className:`mfc-leg-now`,children:`▸`}),`now`]})]}),(0,Z.jsxs)(`div`,{className:`mfc-rangewrap`,id:`mfc-rangewrap`,ref:S,children:[(0,Z.jsx)(`div`,{className:`mfc-pills`,id:`mfc-pills`}),(0,Z.jsx)(`svg`,{className:`mfc-leaders`,id:`mfc-leaders`,viewBox:`0 0 100 18`,preserveAspectRatio:`none`,"aria-hidden":`true`}),(0,Z.jsxs)(`div`,{className:`mfc-rangetrack`,id:`mfc-rangetrack`,ref:C,children:[(0,Z.jsx)(`div`,{className:`mfc-zone safe`}),(0,Z.jsx)(`div`,{className:`mfc-zone warn`}),(0,Z.jsx)(`div`,{className:`mfc-zone over`}),(0,Z.jsx)(`div`,{className:`mfc-rangeband`,id:`mfc-rangeband`,hidden:!0}),(0,Z.jsx)(`div`,{className:`mfc-bound b0`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`0%`})}),(0,Z.jsx)(`div`,{className:`mfc-bound b90`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`90%`})}),(0,Z.jsx)(`div`,{className:`mfc-bound b100`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`100%`})}),(0,Z.jsx)(`div`,{className:`mfc-bound b110`,children:(0,Z.jsx)(`div`,{className:`lbl`,children:`110%`})})]})]}),(0,Z.jsxs)(`h3`,{className:`m-sec sec-rates`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`Rates`]}),(0,Z.jsxs)(`div`,{className:`mfc-kvgrid`,children:[(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`$ / 1%`}),(0,Z.jsx)(`span`,{className:`v v-cyan${j?.dollars_per_percent==null?` m-unavailable`:``}`,id:`mfc-dpp`,children:v.usd3(j?.dollars_per_percent)})]}),!r&&(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`Quota rate`}),(0,Z.jsx)(`span`,{className:`v v-cyan${j?.week_average_pct_per_hour==null?` m-unavailable`:``}`,children:v.ratePctPerHour(j?.week_average_pct_per_hour)})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:r?`week done`:`cycle done`}),(0,Z.jsx)(`span`,{className:`v v-green`,id:`mfc-wkdone`,children:Pt(N)})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`elapsed`}),(0,Z.jsx)(`span`,{className:`v v-green`,id:`mfc-elapsed`,children:v.hours1(N?.elapsed_hours)})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`remaining`}),(0,Z.jsx)(`span`,{className:`v`,id:`mfc-remain`,children:v.hours1(N?.remaining_hours)})]})]}),j?.dollars_per_percent==null&&(0,Z.jsx)(`p`,{className:`mfc-rate-note`,children:se(j?.dollars_per_percent_source)}),j?.dollars_per_percent!=null&&M(j?.dollars_per_percent_source)&&(0,Z.jsx)(`p`,{className:`mfc-rate-note`,"data-testid":`mfc-rate-qualification`,children:M(j?.dollars_per_percent_source)}),(0,Z.jsxs)(`h3`,{className:`m-sec sec-bud`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),`Daily budgets to stay under`]}),(0,Z.jsxs)(`div`,{className:`mfc-kvgrid mfc-kvgrid-single`,children:[(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`@ 100% cap`}),(0,Z.jsx)(`span`,{className:`v v-magenta${b?.budget_100_per_day_usd==null?` m-unavailable`:``}`,id:`mfc-bud100`,children:v.usd2PerDay(b?.budget_100_per_day_usd)})]}),(0,Z.jsxs)(`div`,{className:`mfc-krow`,children:[(0,Z.jsx)(`span`,{className:`l`,children:`@ 90% cap`}),(0,Z.jsx)(`span`,{className:`v v-amber${b?.budget_90_per_day_usd==null?` m-unavailable`:``}`,id:`mfc-bud90`,children:v.usd2PerDay(b?.budget_90_per_day_usd)})]})]})]}),(0,Z.jsx)(`div`,{className:`provider-composition provider-composition--modal`,children:(0,Z.jsx)(z,{env:t,selection:e,surface:`modal`})})]}):(0,Z.jsxs)(Y,{title:`Forecast — per account`,accentClass:`accent-purple`,headerExtras:w,children:[(0,Z.jsxs)(`section`,{className:`modal-forecast`,"data-source":e,"data-per-account":``,children:[(0,Z.jsxs)(`div`,{className:`m-chipstrip`,id:`mfc-chips`,children:[(0,Z.jsx)(`span`,{className:`m-pill accent-purple`,children:`All accounts`}),(0,Z.jsx)(`span`,{className:`m-pill ${Je(`codex`)}`,children:`Codex native quota`})]}),(0,Z.jsx)(zt,{rows:i})]}),(0,Z.jsx)(`div`,{className:`provider-composition provider-composition--modal`,children:(0,Z.jsx)(z,{env:t,selection:e,surface:`modal`})})]})}function Gt(){let e=(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource);return e===`all`?(0,Z.jsx)(Ht,{}):(0,Z.jsx)(Wt,{source:e})}function Kt(e,t){if(t.unit===`cycle`)return U(e,t);let n=Math.max(1,Math.round(e/4));return`${e} week${e===1?``:`s`} · ${n} month${n===1?``:`s`}`}function qt(e){let t=e.findIndex(e=>e&&e.is_current);return t>=0?t:e.length-1}function Jt(e,t){let n=e.filter((e,n)=>n!==t).map(e=>e.dollar_per_pct).filter(e=>e!=null&&isFinite(e));if(n.length<4)return null;let r=n.slice(-4).sort((e,t)=>e-t);return(r[1]+r[2])/2}function Yt(e){if(!e.length)return null;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}var Xt=600,Zt=140,Qt={left:44,right:30,top:12,bottom:22},$t=Xt-Qt.left-Qt.right,en=Zt-Qt.top-Qt.bottom;function tn(e,t){return Qt.left+(t===1?$t:e/(t-1)*$t)}function nn(e,t,n){let r=[];if(!e.length)return r;let i=Xt,a=Zt,o=Qt,s=en,c=e.length,l=e=>tn(e,c),u=e.map(e=>e.dollar_per_pct).filter(e=>e!=null&&isFinite(e)),d=u.length?Math.min(...u)*.96:0,f=u.length?Math.max(...u)*1.04:1;f-d<1e-6&&(d-=.01,f+=.01);let p=e=>o.top+s*(1-(e-d)/(f-d)),m=e.map(e=>e.used_pct).filter(e=>e!=null&&isFinite(e)),h=m.length?Math.min(...m)*.96:0,g=m.length?Math.max(...m)*1.04:100;g-h<1e-6&&(--h,g+=1);let _=e=>o.top+s*(1-(e-h)/(g-h));if(r.push({el:`line`,attrs:{class:`mtr-axis`,x1:o.left,y1:o.top+s,x2:i-o.right,y2:o.top+s},key:`axis`}),u.length){let e=Yt(u);e!=null&&(r.push({el:`line`,attrs:{class:`mtr-hl`,x1:o.left,y1:p(e),x2:i-o.right,y2:p(e)},key:`med-line`}),r.push({el:`text`,attrs:{class:`mtr-medlabel`,x:o.left+2,y:p(e)-3},text:`${c}-${n.unit} median $`+e.toFixed(2),key:`med-label`}))}{let t=[];e.forEach((e,n)=>{e.used_pct!=null&&isFinite(e.used_pct)&&t.push(`${l(n)},${_(e.used_pct)}`)}),t.length>=2&&r.push({el:`polyline`,attrs:{class:`mtr-trendline-dim`,points:t.join(` `)},key:`poly-used`})}{let t=[];e.forEach((e,n)=>{e.dollar_per_pct!=null&&isFinite(e.dollar_per_pct)&&t.push(`${l(n)},${p(e.dollar_per_pct)}`)}),t.length>=2&&r.push({el:`polyline`,attrs:{class:`mtr-trendline`,points:t.join(` `)},key:`poly-dpp`})}e.forEach((e,n)=>{if(e.dollar_per_pct==null||!isFinite(e.dollar_per_pct))return;let i=n===t;r.push({el:`circle`,attrs:{class:`mtr-trenddot`+(i?` cur`:``),cx:l(n),cy:p(e.dollar_per_pct),r:i?5:3},key:`dot-${n}`})}),u.length&&(r.push({el:`text`,attrs:{class:`mtr-ylabel`,x:3,y:o.top+8},text:`$`+(f/1.04).toFixed(2),key:`ymax`}),r.push({el:`text`,attrs:{class:`mtr-ylabel`,x:3,y:o.top+s},text:`$`+(d/.96).toFixed(2),key:`ymin`})),m.length&&(r.push({el:`text`,attrs:{class:`mtr-ylabel-right`,x:i-o.right+2,y:o.top+8},text:Math.round(g/1.04)+`%`,key:`umax`}),r.push({el:`text`,attrs:{class:`mtr-ylabel-right`,x:i-o.right+2,y:o.top+s},text:Math.round(h/.96)+`%`,key:`umin`}));let v=e[t];return v&&v.dollar_per_pct!=null&&isFinite(v.dollar_per_pct)&&r.push({el:`text`,attrs:{class:`mtr-curlabel`,x:Math.max(o.left+4,l(t)-22),y:Math.min(a-2,p(v.dollar_per_pct)+16)},text:`$`+v.dollar_per_pct.toFixed(2),key:`curlabel`}),r}function rn(e){return e==null||!isFinite(e)?{cls:`flat`,text:`—`}:e>5e-4?{cls:`up`,text:`+`+e.toFixed(2)}:e<-5e-4?{cls:`down`,text:e.toFixed(2)}:{cls:`flat`,text:`0.00`}}function an(e){return e==null||!isFinite(e)?{cls:`delta-flat`,iconHref:`/static/icons.svg#minus`,text:`—`}:e<-5e-4?{cls:`delta-down`,iconHref:`/static/icons.svg#trending-down`,text:`−$`+Math.abs(e).toFixed(3)}:e>5e-4?{cls:`delta-up`,iconHref:`/static/icons.svg#trending-up`,text:`+$`+e.toFixed(3)}:{cls:`delta-flat`,iconHref:`/static/icons.svg#minus`,text:`$0.000`}}function on({source:e,embedded:t=!1}){let n=P(e),r=e===`claude`,i=Ie(r?`claude`:`codex`),a=je(n,e),o=r?x(n):a.rows.map(e=>({...e,spark_height:e.dollar_per_pct})),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),d=(0,Z.jsx)(q,{panel:`trend`,panelLabel:`Trend`,triggerId:`trend-modal`,onClick:()=>g(f(`trend`,`trend-modal`))}),m=qt(o),h=o[m],_=r?n?.trend?.history_median_dpp:null,y=_!=null&&isFinite(_)?_:Jt(o,m),b=an(h&&h.dollar_per_pct!=null&&y!=null?h.dollar_per_pct-y:null),S=nn(o,m,i),C=o.some(e=>e.used_pct!=null&&isFinite(e.used_pct)),w=o.length,T=n=>t?`${n}-${e}`:n,E=t?`h4`:`h3`,D=o.map((e,t)=>({...e,_chronoIdx:t})),O=ne(i.unit),k=p(D,O,l),A=(0,Z.jsxs)(`div`,{className:`m-kv kv-cur`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v`,id:T(`mtr-cur`),children:h&&h.dollar_per_pct!=null?`$`+h.dollar_per_pct.toFixed(3):(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`—`})}),(0,Z.jsx)(`div`,{className:`lbl`,children:`Current $ / 1%`})]})]}),j=(0,Z.jsxs)(`section`,{className:`modal-trend`,"data-source":e,children:[(0,Z.jsxs)(`div`,{className:`m-chipstrip`,children:[(0,Z.jsx)(`span`,{className:`m-pill accent-amber${w===0?` m-unavailable`:``}`,id:T(`mtr-weeks-pill`),children:w===0?`History unavailable`:Kt(w,i)}),!r&&(0,Z.jsx)(`span`,{className:`m-pill ${e===`all`?`accent-blue`:Je(`codex`)}`,children:e===`all`?`All sources`:`Codex`})]}),(0,Z.jsxs)(`div`,{className:`period-two-pane`,children:[(0,Z.jsxs)(`div`,{className:`period-detail-pane`,children:[y==null?(0,Z.jsxs)(`div`,{className:`m-hero cols-2`,children:[A,(0,Z.jsxs)(`div`,{className:`m-kv kv-med kv-hint`,id:T(`mtr-med-hint`),children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#minus`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`v`,children:[`needs 4 `,i.plural]}),(0,Z.jsx)(`div`,{className:`lbl`,children:`Median`})]})]})]}):(0,Z.jsxs)(`div`,{className:`m-hero cols-3`,children:[A,(0,Z.jsxs)(`div`,{className:`m-kv kv-med`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#minus`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v`,id:T(`mtr-med`),children:`$`+y.toFixed(3)}),(0,Z.jsxs)(`div`,{className:`lbl`,children:[`4-`,i.unit,` median`]})]})]}),(0,Z.jsxs)(`div`,{className:`m-kv kv-delta ${b.cls}`,id:T(`mtr-delta-kv`),children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:b.iconHref})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v`,id:T(`mtr-delta`),children:b.text}),(0,Z.jsx)(`div`,{className:`lbl`,children:`vs median`})]})]})]}),(0,Z.jsxs)(E,{className:`m-sec sec-spark`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#trending-down`})}),w>0?`${w}-${i.unit}`:i.detail,` history · $/1%`,(0,Z.jsxs)(`span`,{className:`mtr-legend`+(C?``:` legend-no-used`),"aria-hidden":`true`,children:[(0,Z.jsx)(`span`,{className:`sw sw-dpp`}),(0,Z.jsx)(`span`,{className:`sw-lbl`,children:`$/1%`}),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`sw sw-used`}),(0,Z.jsx)(`span`,{className:`sw-lbl`,children:`used %`})]})]})]}),(0,Z.jsxs)(`div`,{className:`mtr-sparkhero`,children:[(0,Z.jsxs)(`svg`,{id:T(`mtr-svg`),viewBox:`0 0 600 140`,preserveAspectRatio:`none`,role:`group`,"aria-label":`$ per 1% over the last ${U(w,i)}, with the used % line overlaid`,children:[S.map(e=>{let{el:t,attrs:n,text:r,key:i}=e,a={};for(let e in n)a[e===`class`?`className`:e]=n[e];return t===`line`?(0,Z.jsx)(`line`,{...a},i):t===`polyline`?(0,Z.jsx)(`polyline`,{...a},i):t===`circle`?(0,Z.jsx)(`circle`,{...a},i):(0,Z.jsx)(`text`,{...a,children:r},i)}),o.map((e,t)=>{let n=w>1?$t/(w-1):$t,r=w-1-t,a=e.used_pct!=null&&isFinite(e.used_pct)?Math.round(e.used_pct)+`% used`:`used —`,o=e.dollar_per_pct!=null&&isFinite(e.dollar_per_pct)?`$`+e.dollar_per_pct.toFixed(2)+` / 1%`:`$— / 1%`;return(0,Z.jsx)(`rect`,{className:`mtr-hit`,"data-testid":`mtr-hit`,x:tn(t,w)-n/2,y:Qt.top,width:n,height:en,tabIndex:0,role:`button`,"aria-label":`${K(e.label,r,i)}: ${o}, ${a}`,onMouseEnter:()=>c(t),onFocus:()=>c(t),onMouseLeave:()=>c(null),onBlur:()=>c(null)},`hit-${t}`)})]}),w===0&&(0,Z.jsx)(`div`,{className:`empty-state m-unavailable`,id:T(`mtr-empty`),children:`No history data is available for this source yet.`}),s!=null&&o[s]?(()=>{let e=o[s],t=w-1-s,n=Math.min(92,Math.max(8,tn(s,w)/Xt*100)),r=e.dollar_per_pct!=null&&isFinite(e.dollar_per_pct)?`$`+e.dollar_per_pct.toFixed(2)+` / 1%`:`$— / 1%`,a=e.used_pct!=null&&isFinite(e.used_pct)?Math.round(e.used_pct)+`% used`:`used —`;return(0,Z.jsxs)(`div`,{className:`mtr-tip`,role:`status`,style:{left:n+`%`},children:[(0,Z.jsx)(`span`,{className:`mtr-tip-wk`,children:K(e.label,t,i)}),(0,Z.jsx)(`span`,{className:`mtr-tip-dpp`,children:r}),(0,Z.jsx)(`span`,{className:`mtr-tip-used`,children:a})]})})():null,(0,Z.jsx)(`div`,{className:`mtr-sparkaxis`,id:T(`mtr-sparkaxis`),children:w>0?(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`span`,{children:[i.relativePrefix,`−`,w-1]}),(0,Z.jsxs)(`span`,{children:[i.relativePrefix,`−`,Math.floor((w-1)/2)]}),(0,Z.jsx)(`span`,{children:`Now`})]}):null})]})]}),(0,Z.jsxs)(`div`,{className:`period-table-pane`,children:[(0,Z.jsxs)(E,{className:`m-sec sec-tbl`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#hash`})}),i.detail,` detail`]}),(0,Z.jsxs)(`div`,{className:`mtr-tbl-head`,children:[(0,Z.jsx)(`span`,{className:`m-pill accent-purple`,id:T(`mtr-tbl-count`),children:U(w,i)}),(0,Z.jsxs)(`span`,{className:`mtr-tbl-sub`,children:[`current row highlighted · negative Δ = $/1% down vs prior `,i.unit]})]}),(0,Z.jsxs)(`table`,{className:`m-histable`,id:T(`mtr-table`),children:[(0,Z.jsx)(ae,{columns:O,override:l,onChange:u,accentVar:`--accent-amber`}),(0,Z.jsx)(`tbody`,{id:T(`mtr-rows`),children:k.map(e=>{let t=w-1-e._chronoIdx,n=K(e.label,t,i),r=e.used_pct==null?`Unavailable`:Math.round(e.used_pct)+`%`,a=e.dollar_per_pct==null?`Unavailable`:`$`+e.dollar_per_pct.toFixed(2),o=rn(e.delta);return(0,Z.jsxs)(`tr`,{className:e.is_current?`cur`:void 0,children:[(0,Z.jsxs)(`td`,{children:[(0,Z.jsx)(F,{labels:e.account_labels}),(0,Z.jsx)(`span`,{className:`wlab`,children:n})]}),(0,Z.jsx)(`td`,{className:`num c-cost`,children:v.usd2(e.cost_usd)}),(0,Z.jsx)(`td`,{className:`num usedpct${e.used_pct==null?` m-unavailable`:``}`,children:r}),(0,Z.jsx)(`td`,{className:`num dpp${e.dollar_per_pct==null?` m-unavailable`:``}`,children:a}),(0,Z.jsx)(`td`,{className:`num delta ${o.cls}`,children:o.text})]},e.label+`|`+e._chronoIdx)})})]})]})]})]});return t?j:(0,Z.jsx)(Y,{title:w>0?`Trend — last ${U(w,i)}`:`Trend`,accentClass:`accent-amber`,headerExtras:d,wide:!0,paneScroll:!0,children:j})}function sn(){let e=(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource),t=P(e);if(e!==`all`)return(0,Z.jsx)(on,{source:e});let n=je(t,`all`),r=(0,Z.jsx)(q,{panel:`trend`,panelLabel:`Trend`,triggerId:`trend-modal`,onClick:()=>g(f(`trend`,`trend-modal`))}),i=n.sections.find(e=>e.source===`claude`)?.historyRows.length??0,a=n.sections.find(e=>e.source===`codex`)?.historyRows.length??0;return(0,Z.jsx)(Y,{title:`Trend · Claude ${U(i,Ie(`claude`))} · Codex ${U(a,Ie(`codex`))}`,accentClass:`accent-amber`,headerExtras:r,wide:!0,dataSource:`all`,children:(0,Z.jsx)(`div`,{className:`provider-composition provider-composition--modal trend-modal-composition`,children:n.sections.map(e=>(0,Z.jsxs)(`section`,{className:`provider-composition-section`,"data-provider-section":e.source,"aria-labelledby":`trend-modal-${e.source}-heading`,children:[(0,Z.jsxs)(`div`,{className:`source-provider-head provider-composition-head`,children:[(0,Z.jsxs)(`h3`,{className:`sr-only`,id:`trend-modal-${e.source}-heading`,children:[e.label,` $ per 1% trend history`]}),(0,Z.jsx)(`span`,{className:`source-chip source-chip--${e.source}`,children:e.label}),(0,Z.jsx)(`span`,{className:`provider-summary-label`,children:U(e.historyRows.length,Ie(e.source))})]}),(0,Z.jsx)(on,{source:e.source,embedded:!0})]},e.source))})})}function cn(e,t){return t===`day`?v.calDate(e.key)??e.label:e.label}function ln({rows:e,selectedKey:t,onSelect:n,unit:r,displayUnit:i}){let a=i??r,o=[...e].reverse(),s=o.reduce((e,t)=>Math.max(e,t.cost),0),c=e.find(e=>e.key===t)??null,l=c?cn(c,r):null,u=r===`day`?`· today`:`· now`,d=o.length>0?cn(o[0],r):``,f=o.length>0?o[o.length-1]:null,p=f?cn(f,r):``,m=o.find(e=>e.isCurrent)??null,h=m!=null&&f!=null&&m.key===f.key,g=ue(e,t,`older`),_=ue(e,t,`newer`);return(0,Z.jsxs)(`section`,{className:`daily-modal-bars`,"aria-label":`Cost by ${a}`,children:[(0,Z.jsxs)(`div`,{className:`daily-modal-bars-head`,children:[(0,Z.jsxs)(`span`,{className:`daily-bars-nav`,children:[(0,Z.jsx)(`button`,{type:`button`,className:`daily-step-btn`,"aria-label":`Step to older ${i??`period`}`,disabled:g===null,onClick:()=>{g&&n(g)},children:`‹`}),(0,Z.jsxs)(`span`,{children:[`selected: `,l??`—`]}),(0,Z.jsx)(`button`,{type:`button`,className:`daily-step-btn`,"aria-label":`Step to newer ${i??`period`}`,disabled:_===null,onClick:()=>{_&&n(_)},children:`›`})]}),(0,Z.jsx)(`span`,{className:`hint hint-desktop`,children:`↑↓ navigate · click any bar`}),(0,Z.jsx)(`span`,{className:`hint hint-mobile`,children:`‹ › to step · tap a bar`})]}),(0,Z.jsx)(`div`,{className:`daily-modal-bars-grid`,role:`img`,"aria-label":`Cost by ${a} histogram`,children:o.map(e=>{let r=e.key===t,i=e.isEmpty?4:s>0?e.cost/s*100:0,a=[`bar`,e.isEmpty?`zero`:``,r?`sel`:``,e.isCurrent?`today`:``].filter(Boolean).join(` `);return(0,Z.jsx)(`button`,{"data-key":e.key,className:a,style:{height:`${i}%`},disabled:e.isEmpty,"aria-pressed":r,"aria-label":`${e.label} cost ${e.cost>0?v.usd2(e.cost):`no usage`}`,title:e.cost>0?`${e.label} · ${v.usd2(e.cost)}`:`${e.label} · —`,onClick:()=>{e.isEmpty||n(e.key)}},e.key)})}),o.length>0&&(0,Z.jsxs)(`div`,{className:`daily-modal-bars-axis`,children:[(0,Z.jsx)(`span`,{children:d}),m&&!h&&(0,Z.jsxs)(`span`,{children:[cn(m,r),` `,u]}),(0,Z.jsx)(`span`,{children:h?`${p} ${u}`:p})]})]})}function un({legs:e}){return(0,Z.jsx)(`div`,{className:`daily-provider-legs`,"data-testid":`daily-provider-legs`,children:[`claude`,`codex`].map(t=>({source:t,label:t===`claude`?`Claude`:`Codex`,row:e[t]})).map(({source:e,label:t,row:n})=>(0,Z.jsxs)(`div`,{className:`daily-provider-leg`,"data-provider-leg":e,children:[(0,Z.jsx)(`span`,{className:`source-chip source-chip--${e}`,children:t}),n==null?(0,Z.jsx)(`span`,{className:`muted`,children:`No activity`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`cost`,children:v.usd2(n.cost_usd)}),(0,Z.jsx)(`span`,{className:`models-chips`,children:n.models.map(e=>(0,Z.jsx)(`span`,{className:`chip ${e.chip}`,style:he(e.model),children:e.display},e.model))})]})]},e))})}function dn({row:e,variant:t,accentClass:n,periodNoun:r,windowLabel:i,providerLegs:a}){let o=W(),s={tz:o.resolvedTz,offsetLabel:o.offsetLabel},c=(e,t)=>`${v.datetimeShort(e,s)} → ${v.datetimeShort(t,s)}`,l=e.delta_cost_pct==null?`flat`:e.delta_cost_pct>0?`up`:e.delta_cost_pct<0?`down`:`flat`,u=r??(t===`weekly`?`week`:t===`monthly`?`month`:`day`),d=i??`Subscription window`,f=a?.claude&&!a.codex?`claude`:a?.codex&&!a.claude?`codex`:null,p=f??(e.source===`all`?null:e.source),m=t===`daily`?`Today`:`Now`;return(0,Z.jsxs)(`div`,{className:`detail-card ${n}`,children:[(0,Z.jsxs)(`div`,{className:`head`,children:[(0,Z.jsxs)(`div`,{className:`big`,children:[p!=null&&(0,Z.jsx)(`span`,{className:`source-chip source-chip--${p}`,"data-period-source":p,children:p===`claude`?`Claude`:`Codex`}),e.label,e.is_current&&(0,Z.jsx)(`span`,{className:`pill-current`,children:m})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`cost`,style:{color:`var(--text)`,fontWeight:700},children:v.usd2(e.cost_usd)}),` `,e.delta_cost_pct==null?(0,Z.jsx)(`span`,{className:`delta flat`,children:`—`}):(0,Z.jsxs)(`span`,{className:`delta ${l}`,children:[v.deltaPct(e.delta_cost_pct),` vs prior `,u]})]})]}),t===`weekly`&&e.week_start_at&&e.week_end_at&&(0,Z.jsxs)(`div`,{className:`window`,children:[d,`: `,c(e.week_start_at,e.week_end_at)]}),(0,Z.jsx)(Ge,{rows:e.models.map(e=>({model:e.model,cost_usd:e.cost_usd,label:e.display}))}),a&&!f&&(0,Z.jsx)(un,{legs:a}),(0,Z.jsxs)(`div`,{className:`tokens-row`,children:[e.codex_tokens?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Input`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.codex_tokens.input_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Cached input`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.codex_tokens.cached_input_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Output`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.codex_tokens.output_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Reasoning`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.codex_tokens.reasoning_output_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Total`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.codex_tokens.total_tokens)})]})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Input`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.input_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Output`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.output_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Cache+`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.cache_creation_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Cache-read`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.cache_read_tokens)})]}),(0,Z.jsxs)(`div`,{className:`t`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Total`}),(0,Z.jsx)(`span`,{className:`v`,children:v.compact(e.total_tokens)})]})]}),e.cache_hit_pct!=null&&(0,Z.jsxs)(`div`,{className:`t cache`,children:[(0,Z.jsx)(`span`,{className:`k`,children:H(e.source??`claude`).percentLabel}),(0,Z.jsxs)(`span`,{className:`v`,children:[e.cache_hit_pct.toFixed(1),`%`]}),(0,Z.jsx)(`div`,{className:`bar`,children:(0,Z.jsx)(`div`,{className:`fill`,style:{width:`${Math.min(100,Math.max(0,e.cache_hit_pct))}%`}})})]})]}),t===`weekly`&&(0,Z.jsxs)(`div`,{className:`stats2`,children:[(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Used %`}),(0,Z.jsx)(`span`,{className:`v`,children:v.pct0(e.used_pct)})]}),(0,Z.jsxs)(`div`,{className:`s`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`$/1%`}),(0,Z.jsx)(`span`,{className:`v`,children:v.usd2(e.dollar_per_pct)})]})]})]})}var fn=(e,t)=>e<t?-1:+(e>t);function pn(e,t=!1,n){let r=[{id:`label`,label:n??(e===`week`?`Week`:`Month`),defaultDirection:`asc`,compare:(e,t)=>fn(e.label,t.label)}];return t&&r.push({id:`source`,label:`Source`,defaultDirection:`asc`,compare:(e,t)=>fn(e.source??``,t.source??``)}),r.push({id:`models`,label:`Models`,defaultDirection:`desc`,compare:()=>0},{id:`cost_usd`,label:`Cost (USD)`,defaultDirection:`desc`,numeric:!0,compare:(e,t)=>e.cost_usd-t.cost_usd}),e===`week`&&r.push({id:`used_pct`,label:`Used %`,defaultDirection:`desc`,numeric:!0,nullKey:e=>e.used_pct,compare:(e,t)=>e.used_pct-t.used_pct},{id:`dollar_per_pct`,label:`$/1%`,defaultDirection:`desc`,numeric:!0,nullKey:e=>e.dollar_per_pct,compare:(e,t)=>e.dollar_per_pct-t.dollar_per_pct}),r.push({id:`delta_cost_pct`,label:`Δ cost`,defaultDirection:`desc`,numeric:!0,nullKey:e=>e.delta_cost_pct,compare:(e,t)=>e.delta_cost_pct-t.delta_cost_pct}),r}function mn(e,t){let n=t&&t.cost_usd>0?(e.cost_usd-t.cost_usd)/t.cost_usd:null;return{source:e.source,label:e.label,cost_usd:e.cost_usd,total_tokens:e.total_tokens,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cache_creation_tokens:e.cache_creation_tokens,cache_read_tokens:e.cache_read_tokens,used_pct:null,dollar_per_pct:null,delta_cost_pct:n,is_current:e.is_today,models:e.models,cache_hit_pct:e.cache_hit_pct,codex_tokens:e.codex_tokens}}function hn(e,t){return e.map(e=>({key:ze(e,t),source:e.source,label:e.label,cost_usd:e.cost_usd,used_pct:e.used_pct,dollar_per_pct:e.dollar_per_pct,delta_cost_pct:e.delta_cost_pct,models:e.models,...e.account_labels?{account_labels:e.account_labels}:{}}))}function gn(e){return e==null||e===0?`num`:e>0?`num delta-up`:`num delta-down`}function _n(e){let t=new Set,n=[];for(let r of e){let e=Me(r.model);e&&(t.has(e)||(t.add(e),n.push({key:e,cls:r.chip,label:r.display,model:r.model})))}return n}function vn({models:e}){let t=_n(e),n=t.slice(0,3),r=t.length>3?t.length-3:0;return(0,Z.jsxs)(`span`,{className:`models-chips`,children:[n.map(e=>(0,Z.jsx)(`span`,{className:`chip ${e.cls}`,style:he(e.model),children:e.label},e.key)),r>0&&(0,Z.jsxs)(`span`,{className:`models-chips-more`,children:[`…+`,r]})]})}function yn({rows:e,variant:t,accentClass:n,selectedKey:r,onSelect:i,showSource:a=!1,periodLabel:o}){let s=t===`weekly`?`week`:`month`,c=pn(s,a,o),l=(0,X.useSyncExternalStore)(h,()=>_().prefs.historySortOverrides[s]),u=hn(e,s),d=a?[`claude`,`codex`].flatMap(e=>p(u.filter(t=>t.source===e),c,l)):p(u,c,l);return(0,Z.jsxs)(`table`,{className:`history-table history-table--${t} ${n}`,role:`grid`,"aria-rowcount":d.length,children:[(0,Z.jsx)(ae,{columns:c,override:l,onChange:e=>g({type:`SET_TABLE_SORT`,table:`history`,periodKind:s,override:e}),accentVar:`--${n}`}),(0,Z.jsx)(`tbody`,{children:d.map((e,n)=>{let o=e.key===r;return(0,Z.jsxs)(`tr`,{className:o?`selected`:void 0,"aria-rowindex":n+1,"aria-selected":o,tabIndex:0,onClick:()=>i(e.key),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),t.stopPropagation(),i(e.key))},children:[(0,Z.jsxs)(`td`,{children:[(0,Z.jsx)(F,{labels:e.account_labels}),e.label,o?` ▶`:``]}),a&&(0,Z.jsx)(`td`,{children:(0,Z.jsx)(`span`,{className:`source-chip source-chip--${e.source??`all`}`,children:e.source===`claude`?`Claude`:e.source===`codex`?`Codex`:`Combined`})}),(0,Z.jsx)(`td`,{children:(0,Z.jsx)(vn,{models:e.models})}),(0,Z.jsx)(`td`,{className:`num`,children:v.usd2(e.cost_usd)}),t===`weekly`&&(0,Z.jsx)(`td`,{className:`num`,children:v.pct0(e.used_pct)}),t===`weekly`&&(0,Z.jsx)(`td`,{className:`num`,children:v.usd2(e.dollar_per_pct)}),(0,Z.jsx)(`td`,{className:gn(e.delta_cost_pct),children:v.deltaPct(e.delta_cost_pct)})]},e.key)})})]})}function bn({hints:e,trailing:t,className:n,"data-testid":r}){return(0,Z.jsxs)(`div`,{className:`key-hint-footer ${n??``}`.trim(),"data-testid":r,"aria-live":`off`,children:[e.map((e,t)=>(0,Z.jsxs)(X.Fragment,{children:[t>0&&(0,Z.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`·`}),(0,Z.jsxs)(`span`,{children:[e.keys,` `,e.label]})]},t)),t??(0,Z.jsx)(k,{id:`modal-sync-chip`})]})}var xn={day:`days`,week:`weeks`,month:`months`},Sn={day:`daily`,week:`weekly`,month:`monthly`};function Cn(e){return e===`codex`?{plural:`cycles`,noun:`cycle`,window:`Reset cycle`,column:`Cycle`,nav:`cycle`}:e===`all`?{plural:`provider periods`,noun:`provider period`,window:`Provider window`,column:`Provider period`,nav:`provider period`}:{plural:`cycles`,noun:`cycle`,window:`Reset cycle`,column:`Cycle`,nav:`cycle`}}function wn(e,t,n){if(e===`day`){let e=pe(t,n);if(e.state!==`available`)return{rows:[],withheld:e};let r=e.rows;return{rows:r.map((e,t)=>({key:e.date,nav:{key:e.date,label:e.label,cost:e.cost_usd,isCurrent:e.is_today,isEmpty:e.cost_usd<=0},period:mn(e,r[t+1])})),withheld:null}}let r=ve(t,n,e===`week`?`weekly`:`monthly`),i=e;return{withheld:null,rows:r.map(e=>({key:ze(e,i),nav:{key:ze(e,i),label:n===`all`&&e.source!=null?`${e.source===`claude`?`Claude`:`Codex`} · ${e.label}`:e.label,cost:e.cost_usd,isCurrent:e.is_current,isEmpty:e.cost_usd<=0},period:e}))}}function Tn({variant:e,accentClass:t,sharePanel:n,modalKind:r,panelLabel:i,triggerId:a,wide:o,paneScroll:s}){let c=(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource),l=P(c),[u,d]=(0,X.useState)(()=>e===`day`?_().openDailyDate:null),{rows:p,withheld:m}=wn(e,l,c),v=p.map(e=>e.nav),y=p.map(e=>e.period),b=new Set(p.map(e=>e.key)),x=p[0]?.key??null,S=u!=null&&b.has(u)?u:x,C=p.find(e=>e.key===S)?.period??null,T=Cn(c),D=v.map(e=>({key:e.key})),k=()=>E(_())===`panel`&&_().openModal===r;w([{key:`ArrowDown`,scope:`modal`,when:k,action:()=>{let e=ue(D,S,`older`);e&&d(e)}},{key:`ArrowUp`,scope:`modal`,when:k,action:()=>{let e=ue(D,S,`newer`);e&&d(e)}}]);let A=(0,Z.jsx)(q,{panel:n,panelLabel:i,triggerId:a,onClick:()=>g(f(n,a))}),j=v.length===1?`provider month`:`provider months`,M=v.length>0?c===`all`&&e===`week`?`${i} · ${v.length} ${v.length===1?T.noun:T.plural}`:c===`all`&&e===`month`?`${i} · ${v.length} ${j}`:`${i} · last ${v.length} ${e===`week`?v.length===1?T.noun:T.plural:xn[e]}`:i,N=e===`day`&&c===`all`&&S!=null?B(l,S):void 0,F=C&&(0,Z.jsx)(dn,{row:C,variant:Sn[e],accentClass:t,periodNoun:e===`week`?T.noun:void 0,windowLabel:e===`week`?T.window:void 0,providerLegs:N});return(0,Z.jsxs)(Y,{title:M,accentClass:t,headerExtras:A,wide:o,paneScroll:s,dataSource:c,children:[m?(0,Z.jsx)(`div`,{className:`panel-empty panel-withheld`,"data-withheld-code":m.code,children:O(m,`history`)}):v.length===0?(0,Z.jsx)(`div`,{className:`panel-empty`,children:`No usage history yet.`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ln,{unit:e,displayUnit:e===`week`?T.nav:void 0,rows:v,selectedKey:S,onSelect:d}),e===`day`?F:(0,Z.jsxs)(`div`,{className:`period-two-pane`,children:[(0,Z.jsx)(`div`,{className:`period-detail-pane`,children:F}),(0,Z.jsx)(`div`,{className:`period-table-pane`,children:(0,Z.jsx)(yn,{rows:y,variant:e===`week`?`weekly`:`monthly`,accentClass:t,selectedKey:S,onSelect:d,showSource:c===`all`,periodLabel:e===`week`?T.column:void 0})})]})]}),(0,Z.jsx)(bn,{hints:[{keys:(0,Z.jsx)(`kbd`,{children:`↑↓`}),label:`period`},{keys:(0,Z.jsx)(`kbd`,{children:`Esc`}),label:`close`}]})]})}function En(){return(0,Z.jsx)(Tn,{variant:`day`,accentClass:`accent-indigo`,sharePanel:`daily`,modalKind:`daily`,panelLabel:`Daily`,triggerId:`daily-modal`})}function Dn(){return(0,Z.jsx)(Tn,{variant:`week`,accentClass:`accent-cyan`,sharePanel:`weekly`,modalKind:`weekly`,panelLabel:`Weekly`,triggerId:`weekly-modal`,wide:!0,paneScroll:!0})}function On(){return(0,Z.jsx)(Tn,{variant:`month`,accentClass:`accent-pink`,sharePanel:`monthly`,modalKind:`monthly`,panelLabel:`Monthly`,triggerId:`monthly-modal`,wide:!0,paneScroll:!0})}var kn=720,An=180,Q={left:46,right:20,top:18,bottom:20},jn=`block-retained-facts-note`;function Mn(e){return e===0?`$0`:e<10?`$`+e.toFixed(2):`$`+Math.round(e).toString()}function Nn(){return(0,X.useSyncExternalStore)(h,()=>_().snapshot?.generated_at??``)}function Pn({detail:e}){let t=Nn(),n=W(),r={tz:n.resolvedTz,offsetLabel:n.offsetLabel},i=e.facts_source===`retained`,a=Date.parse(e.start_at),o=Date.parse(e.end_at)-a||1,s=e=>Q.left+(Date.parse(e)-a)/o*(kn-Q.left-Q.right),c=Math.max(e.cost_usd,e.projection?.total_cost_usd??0),l=e=>{let t=Q.top,n=An-Q.bottom;return c<=0?n:n-e/c*(n-t)},u=[];for(let e=0;e<=5;e++)u.push(S(new Date(a+e*36e5).toISOString()));let d=e.samples.length>0?e.samples[e.samples.length-1].cum:0,f=e.is_active?t||new Date().toISOString():null,p=[];if(e.samples.length>0){p.push([s(e.start_at),l(0)]);for(let t of e.samples)p.push([s(t.t),l(t.cum)]);f&&p.push([s(f),l(d)])}let m=p.map(([e,t])=>`${e.toFixed(1)},${t.toFixed(1)}`).join(` `),h=p.length>0?`M ${m.replace(/ /g,` L `)} L ${p[p.length-1][0].toFixed(1)},${l(0).toFixed(1)} Z`:``,g=c<=0?[0]:[0,c/2,c];return(0,Z.jsxs)(`div`,{className:`mblock-timeline`,children:[(0,Z.jsxs)(`svg`,{viewBox:`0 0 ${kn} ${An}`,style:{width:`100%`,height:`auto`},role:`img`,"aria-label":`Cumulative cost over the 5-hour block window`,children:[g.map(e=>(0,Z.jsx)(`text`,{x:8,y:l(e)+4,fill:`var(--text-dim)`,fontSize:10,children:Mn(e)},e)),(0,Z.jsx)(`line`,{x1:Q.left,y1:Q.top,x2:Q.left,y2:An-Q.bottom,stroke:`var(--border-soft)`,strokeWidth:.8}),(0,Z.jsx)(`line`,{x1:Q.left,y1:An-Q.bottom,x2:kn-Q.right,y2:An-Q.bottom,stroke:`var(--border-soft)`,strokeWidth:.8}),u.slice(1,-1).map(e=>(0,Z.jsx)(`line`,{x1:s(e),y1:Q.top,x2:s(e),y2:An-Q.bottom,stroke:`var(--border-soft)`,strokeDasharray:`2 3`,strokeWidth:.5},e)),u.map(e=>(0,Z.jsx)(`text`,{x:s(e)-14,y:An-5,fill:`var(--text-dim)`,fontSize:9,children:v.timeHHmm(e,r,{noSuffix:!0})},e)),p.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`path`,{d:h,fill:`var(--accent-green)`,opacity:.12}),(0,Z.jsx)(`polyline`,{points:m,fill:`none`,stroke:`var(--accent-green)`,strokeWidth:2}),(0,Z.jsx)(`circle`,{cx:p[p.length-1][0],cy:p[p.length-1][1],r:3,fill:`var(--accent-green)`})]}):(0,Z.jsx)(`text`,{x:kn/2,y:An/2,fill:`var(--text-faint)`,fontSize:11,textAnchor:`middle`,children:i?`Cost trajectory unavailable for this block.`:`No spend recorded yet in this block.`}),e.is_active&&e.projection&&f&&p.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`polyline`,{points:`${s(f).toFixed(1)},${l(d).toFixed(1)} ${s(e.end_at).toFixed(1)},${l(e.projection.total_cost_usd).toFixed(1)}`,fill:`none`,stroke:`var(--accent-amber)`,strokeWidth:1.5,strokeDasharray:`5 4`,opacity:.85}),(0,Z.jsx)(`circle`,{cx:s(e.end_at),cy:l(e.projection.total_cost_usd),r:3,fill:`var(--accent-amber)`,opacity:.85}),(0,Z.jsxs)(`text`,{x:s(e.end_at)-50,y:l(e.projection.total_cost_usd)-6,fill:`var(--accent-amber)`,fontSize:9,children:[`proj $`,e.projection.total_cost_usd.toFixed(2)]}),(0,Z.jsx)(`line`,{x1:s(f),y1:Q.top,x2:s(f),y2:An-Q.bottom,stroke:`var(--accent-amber)`,strokeWidth:1.2}),(0,Z.jsx)(`text`,{x:s(f)+4,y:Q.top+10,fill:`var(--accent-amber)`,fontSize:9,children:`now`})]}):null]}),i?(0,Z.jsxs)(`p`,{className:`mblock-timeline-note`,id:jn,children:[`The headline and token figures are facts retained when this block closed.`,` `,e.samples.length===0?`Its entries are no longer in the local cache, so there is no trajectory to draw.`:`The trajectory is drawn from the entries currently in the local cache and totals ${v.usd2(d)}, so it can differ from those figures.`]}):null]})}function Fn(){return(0,X.useSyncExternalStore)(h,()=>_().snapshot?.generated_at??``)}function In(e,t){let n=Date.parse(e.start_at),r=e.is_active?Date.parse(t)||Date.now():e.actual_end_at?Date.parse(e.actual_end_at):Date.parse(e.end_at),i=Math.max(0,Math.floor((r-n)/6e4)),a=Math.floor(i/60),o=i%60;return`${a}h ${String(o).padStart(2,`0`)}m`}function Ln(e,t,n){return`${v.timeHHmm(S(e),n)} → ${v.timeHHmm(S(t),n)}`}function Rn(){let e=(0,X.useSyncExternalStore)(h,()=>_().openBlockStartAt),t=Fn(),n=W(),r={tz:n.resolvedTz,offsetLabel:n.offsetLabel},[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(!1),p=(0,X.useRef)(null);return(0,X.useEffect)(()=>{p.current=e??null,d.current=!1},[e]),(0,X.useEffect)(()=>{let e=p.current;if(!e){s(!1),l(`No block bound.`),a(null),u.current=null;return}let t=u.current!==e||i==null;u.current=e,t&&(s(!0),l(null),a(null));let n=new AbortController;return fetch(`/api/block/${encodeURIComponent(e)}`,{signal:n.signal}).then(async e=>{if(e.status===404){(t||d.current)&&(s(!1),l(`Block not found (the cache may have rolled forward).`),a(null)),d.current=!0;return}if(!e.ok)throw Error(`HTTP `+e.status);let n=await e.json();d.current=!1,a(n),l(null),s(!1)}).catch(e=>{e.name!==`AbortError`&&(d.current=!1,t&&(l(`Failed to load: `+e.message),s(!1)))}),()=>n.abort()},[e,t]),(0,Z.jsx)(Y,{title:i?(0,Z.jsxs)(Z.Fragment,{children:[i.anchor===`heuristic`?`~ `:``,`Block · `,i.label,` `,(0,Z.jsx)(j,{tz:r.tz})]}):`Block`,accentClass:`accent-blue`,cardClassName:`block-modal-card`,headerExtras:(0,Z.jsx)(q,{panel:`blocks`,panelLabel:`5-hour block`,triggerId:`block-modal`,onClick:()=>g(f(`blocks`,`block-modal`))}),children:(0,Z.jsxs)(`section`,{className:`modal-block`,children:[o?(0,Z.jsx)(`div`,{className:`modal-loading`,children:`Loading block detail…`}):null,c?(0,Z.jsx)(`div`,{className:`modal-error`,children:c}):null,!o&&!c&&i?(0,Z.jsx)(zn,{detail:i,generatedAt:t,ctx:r}):null]})})}function zn({detail:e,generatedAt:t,ctx:n}){let r=e.facts_source===`retained`?jn:void 0;return(0,Z.jsxs)(`div`,{className:`modal-content`,children:[(0,Z.jsxs)(`div`,{className:`m-chipstrip`,children:[e.is_active?(0,Z.jsx)(`span`,{className:`m-pill accent-green`,children:`● Active`}):null,e.anchor===`heuristic`?(0,Z.jsx)(`span`,{className:`m-pill accent-amber`,children:`~ heuristic anchor`}):null,(0,Z.jsx)(`span`,{className:`m-pill accent-blue`,children:Ln(e.start_at,e.end_at,n)}),(0,Z.jsx)(j,{tz:n.tz}),(0,Z.jsxs)(`span`,{className:`m-pill`,children:[e.entries_count.toLocaleString(`en-US`),` `,e.entries_count===1?`entry`:`entries`]})]}),(0,Z.jsxs)(`div`,{className:`m-hero `+(e.is_active?`cols-4`:`cols-3`),children:[(0,Z.jsxs)(`div`,{className:`m-kv kv-cost`,role:`group`,"aria-label":`Total cost: ${v.usd2(e.cost_usd)}`,"aria-describedby":r,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v`,children:v.usd2(e.cost_usd)}),(0,Z.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,Z.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v`,children:In(e,t)}),(0,Z.jsx)(`div`,{className:`lbl`,children:`Elapsed`})]})]}),(0,Z.jsxs)(`div`,{className:`m-kv`,role:`group`,"aria-label":`Total tokens: ${e.total_tokens.toLocaleString(`en-US`)}`,"aria-describedby":r,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#hash`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v`,children:e.total_tokens.toLocaleString(`en-US`)}),(0,Z.jsx)(`div`,{className:`lbl`,children:`Total tokens`})]})]}),e.is_active?(0,Z.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#crystal-ball`})}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`v`,children:e.projection?v.usd2(e.projection.total_cost_usd):`—`}),(0,Z.jsxs)(`div`,{className:`lbl`,children:[`Projected`,e.projection?` · ${e.projection.remaining_minutes} min left`:``]})]})]}):null]}),(0,Z.jsx)(Pn,{detail:e}),(0,Z.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Tokens`]}),(0,Z.jsxs)(`div`,{className:`msess-tok-grid mblock-tok-grid`,children:[(0,Z.jsxs)(`div`,{className:`msess-tok-tile`,role:`group`,"aria-label":`Input: ${e.input_tokens.toLocaleString(`en-US`)}`,"aria-describedby":r,children:[(0,Z.jsx)(`div`,{className:`lbl`,children:`Input`}),(0,Z.jsx)(`div`,{className:`n`,children:e.input_tokens.toLocaleString(`en-US`)})]}),(0,Z.jsxs)(`div`,{className:`msess-tok-tile`,role:`group`,"aria-label":`Output: ${e.output_tokens.toLocaleString(`en-US`)}`,"aria-describedby":r,children:[(0,Z.jsx)(`div`,{className:`lbl`,children:`Output`}),(0,Z.jsx)(`div`,{className:`n`,children:e.output_tokens.toLocaleString(`en-US`)})]}),(0,Z.jsxs)(`div`,{className:`msess-tok-tile`,role:`group`,"aria-label":`Cache create: ${e.cache_creation_tokens.toLocaleString(`en-US`)}`,"aria-describedby":r,children:[(0,Z.jsx)(`div`,{className:`lbl`,children:`Cache create`}),(0,Z.jsx)(`div`,{className:`n`,children:e.cache_creation_tokens.toLocaleString(`en-US`)})]}),(0,Z.jsxs)(`div`,{className:`msess-tok-tile`,role:`group`,"aria-label":`Cache read: ${e.cache_read_tokens.toLocaleString(`en-US`)}`,"aria-describedby":r,children:[(0,Z.jsx)(`div`,{className:`lbl`,children:`Cache read`}),(0,Z.jsx)(`div`,{className:`n`,children:e.cache_read_tokens.toLocaleString(`en-US`)})]}),e.cache_hit_pct==null?null:(0,Z.jsxs)(`div`,{className:`msess-tok-tile cache-hit`,role:`group`,"aria-label":`Cache hit %: ${e.cache_hit_pct.toFixed(1)}%`,"aria-describedby":r,children:[(0,Z.jsx)(`div`,{className:`lbl`,children:`Cache hit %`}),(0,Z.jsxs)(`div`,{className:`n`,children:[e.cache_hit_pct.toFixed(1),`%`]}),(0,Z.jsx)(`div`,{className:`bar`,children:(0,Z.jsx)(`div`,{className:`fill`,style:{width:Math.min(100,Math.max(0,e.cache_hit_pct))+`%`}})})]})]}),e.models.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Cost by model`]}),(0,Z.jsx)(Ge,{rows:e.models.map(e=>({model:e.model,cost_usd:e.cost_usd,label:e.display}))})]}):null,e.is_active&&e.burn_rate&&e.projection?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`h3`,{className:`m-sec sec-burn`,children:[(0,Z.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,Z.jsx)(`use`,{href:`/static/icons.svg#crystal-ball`})}),`Burn rate & projection`]}),(0,Z.jsxs)(`div`,{className:`mblock-burn`,children:[(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Burn rate`}),(0,Z.jsx)(`span`,{className:`v amber`,children:v.usd2(e.burn_rate.cost_per_hour)}),(0,Z.jsx)(`span`,{className:`dim`,children:`/ hr`}),(0,Z.jsx)(`span`,{className:`sep`,children:`·`}),(0,Z.jsx)(`span`,{className:`v cyan`,children:Math.round(e.burn_rate.tokens_per_minute).toLocaleString(`en-US`)}),(0,Z.jsx)(`span`,{className:`dim`,children:`tok / min`})]}),(0,Z.jsxs)(`div`,{className:`row`,children:[(0,Z.jsx)(`span`,{className:`k`,children:`Projection`}),(0,Z.jsx)(`span`,{className:`v amber`,children:v.usd2(e.projection.total_cost_usd)}),(0,Z.jsx)(`span`,{className:`dim`,children:`total`}),(0,Z.jsx)(`span`,{className:`sep`,children:`·`}),(0,Z.jsx)(`span`,{className:`v cyan`,children:e.projection.total_tokens.toLocaleString(`en-US`)}),(0,Z.jsx)(`span`,{className:`dim`,children:`tok`}),(0,Z.jsx)(`span`,{className:`sep`,children:`·`}),(0,Z.jsxs)(`span`,{className:`v`,children:[e.projection.remaining_minutes,` min`]}),(0,Z.jsx)(`span`,{className:`dim`,children:`remaining`})]})]})]}):null]})}var Bn=.6,Vn=`(other)`,Hn=[`#d946ef`,`#c084fc`,`#60a5fa`,`#fbbf24`,`#22d3ee`],Un=`#64748b`,Wn=(e,t)=>e===`(other)`?Un:Hn[t]??`#64748b`,Gn=e=>e===`(other)`?Vn:e.split(`/`).filter(Boolean).pop()??e;function Kn(e,t,n=5){let r=Math.max(0,Math.min(t,e.window_weeks)),i=e.weeks.slice(-r),a=e.projects.map(e=>{let t=e.weekly_cost.slice(-r),n=t.reduce((e,t)=>e+t,0);return{key:e.key,bucket_path:e.bucket_path,weekly:t,cost:n}}).sort((e,t)=>t.cost-e.cost),o=a.slice(0,n),s=a.slice(n),c=i.map((e,t)=>s.reduce((e,n)=>e+(n.weekly[t]??0),0)),l=c.reduce((e,t)=>e+t,0),u=[...o];return s.length>0&&l>0&&u.push({key:Vn,bucket_path:Vn,weekly:c,cost:l}),{weeks:i,series:u}}function qn(e,t,n=Bn){let r=Math.max(0,Math.min(t,e.window_weeks)),i=e.projects.map(e=>e.weekly_cost.slice(-r).reduce((e,t)=>e+t,0)),a=i.reduce((e,t)=>e+t,0);return a<=0?!1:Math.max(...i)/a>=n}function Jn({series:e,onProjectSelect:t}){let n=e.reduce((e,t)=>e+t.cost,0)||1,r=Math.max(...e.map(e=>e.cost),.01);return(0,Z.jsx)(`div`,{className:`projects-ranked`,"data-testid":`projects-ranked-bars`,children:e.map((e,i)=>{let a=e.key===Vn,o=Wn(e.key,i),s=e.cost/n*100,c=Math.max(e.cost/r*100,1.5),l=Gn(e.bucket_path);return(0,Z.jsxs)(`button`,{type:`button`,className:`projects-ranked-row`,"data-series-key":e.key,title:e.bucket_path,disabled:a,onClick:()=>{a||t?.(e.key)},children:[(0,Z.jsx)(`span`,{className:`rk-label`,children:l}),(0,Z.jsx)(`span`,{className:`rk-track`,children:(0,Z.jsx)(`span`,{className:`rk-fill`,style:{width:`${c}%`,background:o}})}),(0,Z.jsxs)(`span`,{className:`rk-val`,children:[`$`,e.cost.toFixed(2),` · `,s.toFixed(+(s<10)),`%`]})]},e.key)})})}var Yn=400,Xn=150;function Zn(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,month:`short`,day:`2-digit`}),r=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hour:`2-digit`,minute:`2-digit`,hour12:!1}),i=e.map(e=>e.week_start_at?n.format(new Date(e.week_start_at)):e.week_label),a=new Map;for(let e of i)a.set(e,(a.get(e)??0)+1);return e.map((e,t)=>(a.get(i[t])??0)>1&&e.week_start_at?`${i[t]} ${r.format(new Date(e.week_start_at))}`:i[t])}function Qn({trend:e,yMode:t,windowWeeks:n,onProjectSelect:r}){let i=(0,X.useMemo)(()=>Kn(e,n),[e,n]),a=(0,X.useMemo)(()=>qn(e,n),[e,n]),o=Be(),s=W();if(i.weeks.length===0||i.series.length===0)return(0,Z.jsxs)(`div`,{className:`panel-empty`,children:[`No project activity in the last `,n,` cycle`,n===1?``:`s`,`.`]});let c=i.weeks.length,l=i.weeks.map((e,t)=>i.series.reduce((e,n)=>e+(n.weekly[t]??0),0)),u=t===`share`?100:Math.max(...l,.01),d=(e,t=`left`)=>c<=1?t===`left`?Yn*.1:Yn*.9:e/(c-1)*Yn,f=Array(c).fill(0),p=i.series.map((e,n)=>{let r=[];for(let e=0;e<c;e++){let t=Xn-f[e]/u*Xn;r.push(`${d(e,`left`).toFixed(2)},${t.toFixed(2)}`),c===1&&r.push(`${d(e,`right`).toFixed(2)},${t.toFixed(2)}`)}for(let n=c-1;n>=0;n--){let i=l[n]??0,a=t===`share`?i>0?(e.weekly[n]??0)/i*100:0:e.weekly[n]??0;f[n]+=a;let o=Xn-f[n]/u*Xn;c===1&&r.push(`${d(n,`right`).toFixed(2)},${o.toFixed(2)}`),r.push(`${d(n,`left`).toFixed(2)},${o.toFixed(2)}`)}return{color:Wn(e.key,n),key:e.key,points:r.join(` `)}}),m=Zn(i.weeks,s.resolvedTz),h=i.weeks.map((e,t)=>(0,Z.jsx)(`span`,{children:m[t]},e.week_start_at??`${e.week_start_date}:${t}`)),g=t===`share`?`100%`:`$${u.toFixed(0)}`;return(0,Z.jsxs)(`div`,{className:`projects-trend`,children:[a?(0,Z.jsx)(Jn,{series:i.series,onProjectSelect:r}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`projects-trend-plot`,children:[(0,Z.jsxs)(`div`,{className:`projects-trend-yaxis`,"data-testid":`projects-yaxis`,children:[(0,Z.jsx)(`span`,{children:g}),(0,Z.jsx)(`span`,{children:t===`share`?`0%`:`$0`})]}),(0,Z.jsx)(`svg`,{viewBox:`0 0 ${Yn} ${Xn}`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Stacked area: project ${t===`share`?`share %`:`cost`} over ${c} ${c===1?`cycle`:`cycles`}`,children:p.map(e=>{let t=e.key===Vn;return(0,Z.jsx)(`polygon`,{fill:e.color,opacity:t?.5:.65,points:e.points,"data-series-key":e.key,onClick:()=>{t||r?.(e.key)},style:{cursor:t?`default`:`pointer`}},e.key)})})]}),(0,Z.jsx)(`div`,{className:`projects-trend-xaxis`,children:h})]}),(0,Z.jsx)(`div`,{className:`projects-trend-legend`,children:i.series.map((e,t)=>{let n=e.key===Vn,i=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`sw`,style:{background:Wn(e.key,t)}}),Gn(e.bucket_path)]});return o&&!n?(0,Z.jsx)(`button`,{type:`button`,className:`projects-trend-legend-item`,"data-series-key":e.key,title:e.bucket_path,onClick:()=>r?.(e.key),children:i},e.key):(0,Z.jsx)(`span`,{className:`projects-trend-legend-item`,"data-series-key":e.key,title:e.bucket_path,children:i},e.key)})})]})}function $n(e,t){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),c=We(ee()),l=(0,X.useRef)(0),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(!1),p=(0,X.useRef)(0);return(0,X.useEffect)(()=>{if(!e){r(null),a(!1),s(null),l.current=0,u.current=null,d.current=null,f.current=!1,p.current+=1;return}let i=u.current!==e||d.current!==t,o=i||n==null;if(o&&f.current&&!i)return;o&&(a(!0),s(null)),i&&(l.current=0),u.current=e,d.current=t,f.current=!0;let c=++p.current,m=`/api/project/${encodeURIComponent(e)}?weeks=${t}`;fetch(m).then(async e=>{if(p.current!==c)return;if(e.status===404){l.current+=1,l.current>=2?(r(null),s(`Project no longer in cache — close this drill.`),a(!1)):o&&(s(`Couldn't load project detail — will retry on next update.`),a(!1));return}if(!e.ok){o&&(s(`Couldn't load project detail — will retry on next update.`),a(!1));return}l.current=0;let t=await e.json();p.current===c&&(r(t),s(null),a(!1))}).catch(()=>{p.current===c&&o&&(s(`Couldn't load project detail — will retry on next update.`),a(!1))}).finally(()=>{p.current===c&&(f.current=!1)})},[e,t,c]),{data:n,loading:i,error:o}}var er=[{column:`cost`,direction:`desc`,label:`cost`,arrow:`↓`},{column:`sessions`,direction:`desc`,label:`sessions`,arrow:`↓`},{column:`used_pct`,direction:`desc`,label:`used`,arrow:`↓`},{column:`share_of_window`,direction:`desc`,label:`share`,arrow:`↓`},{column:`first_seen`,direction:`asc`,label:`first`,arrow:`↑`},{column:`last_seen`,direction:`desc`,label:`last`,arrow:`↓`},{column:`project`,direction:`asc`,label:`project`,arrow:`↑`}],tr=[1,4,8,12];function nr({source:e}){let t=P(e),n=e===`claude`,r=(0,X.useMemo)(()=>n?null:Ne(t,e),[t,n,e]),i=r!=null&&r.state===`available`?r.rows:null,a=r!=null&&r.state===`withheld`?O(r,`ranking`):null,o=W(),c={tz:o.resolvedTz,offsetLabel:o.offsetLabel},l=(0,X.useSyncExternalStore)(h,()=>_().openProjectKey),u=(0,X.useSyncExternalStore)(h,()=>_().prefs.projectsWindowWeeks),d=(0,X.useSyncExternalStore)(h,()=>_().prefs.projectsTrendYMode),m=(0,X.useSyncExternalStore)(h,()=>_().prefs.projectsSortOverride),[y,b]=(0,X.useState)(l??null),[x,S]=(0,X.useState)(!1);(0,X.useEffect)(()=>{if(l){b(l);return}y||b(n?t?.projects?.current_week?.rows?.[0]?.key??null:i?.[0]?.key??null)},[l,t?.projects?.current_week?.rows,n,i]),(0,X.useEffect)(()=>{l||y&&((n?(t?.projects?.trend?.projects??[]).some(e=>e.key===y):(i??[]).some(e=>e.key===y))||b(n?t?.projects?.current_week?.rows?.[0]?.key??null:i?.[0]?.key??null))},[l,y,t?.projects?.trend?.projects,t?.projects?.current_week?.rows,n,i]);let C=n?t?.projects?.trend??null:null,T=u,E=C?.window_weeks??0,D=(e,t)=>{g({type:`SAVE_PREFS`,patch:{[e]:t}})},k=e=>{if(!n){let t=i?.find(t=>t.key===e);t&&g({type:`OPEN_SOURCE_DETAIL`,source:t.source,resource:`project`,key:t.key});return}b(t=>t===e?null:e)},A=(C?.projects??[]).map(e=>{let t=e.weekly_cost.slice(-u),n=e.weekly_pct.slice(-u),r=e.sessions_per_week.slice(-u),i=e.first_seen_per_week.slice(-u),a=e.last_seen_per_week.slice(-u),o=t.reduce((e,t)=>e+t,0),s=n.reduce((e,t)=>t==null?e:(e??0)+t,null),c=e.session_counts_by_window?.[String(u)]??r.reduce((e,t)=>e+t,0),l=i.reduce((e,t)=>t==null?e:e==null||t<e?t:e,null),d=a.reduce((e,t)=>t==null?e:e==null||t>e?t:e,null);return{key:e.key,sessionsCount:c,firstSeenAt:l,lastSeenAt:d,windowCost:o,windowPct:s,shareOfWindow:null}}),j=n?A:(i??[]).map(e=>({key:e.key,displayKey:e.label,source:e.source,sessionsCount:e.sessionsCount,firstSeenAt:e.firstSeenAt,lastSeenAt:e.lastSeenAt,windowCost:e.cost,windowPct:null,shareOfWindow:e.pct})),M=j.reduce((e,t)=>e+t.windowCost,0);for(let e of j)e.shareOfWindow=M>0?e.windowCost/M*100:null;let F=m?p(j,Le,m):p(j,Le,{column:`cost`,direction:`desc`}),ee=F.filter(e=>e.windowCost>0).slice(0,10),te=F.length-ee.length,I=x?F:ee,ne=te>0,re=Be(),ie=$n(n?y:null,u),se=(()=>{if(!m)return 0;let e=er.findIndex(e=>e.column===m.column&&e.direction===m.direction);return e===-1?0:e})(),ce=()=>{let e=er[(se+1)%er.length];g({type:`SET_TABLE_SORT`,table:`projects`,override:{column:e.column,direction:e.direction}})},le=er[se],L=()=>_().shareModal===null&&_().composerModal===null;return w([{key:`1`,scope:`modal`,when:L,action:()=>D(`projectsWindowWeeks`,1)},{key:`4`,scope:`modal`,when:L,action:()=>D(`projectsWindowWeeks`,4)},{key:`8`,scope:`modal`,when:L,action:()=>D(`projectsWindowWeeks`,8)},{key:`0`,scope:`modal`,when:L,action:()=>D(`projectsWindowWeeks`,12)},{key:`s`,scope:`modal`,when:L,action:()=>D(`projectsTrendYMode`,d===`share`?`absolute`:`share`)},{key:`ArrowUp`,scope:`modal`,when:L,action:()=>{if(I.length===0)return;let e=I.findIndex(e=>e.key===y);b(I[e<=0?I.length-1:e-1].key)}},{key:`ArrowDown`,scope:`modal`,when:L,action:()=>{if(I.length===0)return;let e=I.findIndex(e=>e.key===y);b(I[e===-1||e===I.length-1?0:e+1].key)}},{key:`Enter`,scope:`modal`,when:L,action:()=>{y?n?b(null):k(y):I.length>0&&b(I[0].key)}}]),(0,Z.jsx)(Y,{title:`Projects · last ${u} ${u===1?`cycle`:`cycles`}`,accentClass:`accent-magenta`,headerExtras:(0,Z.jsx)(q,{panel:`projects`,panelLabel:`Projects`,triggerId:`projects-modal`,dataTestId:`share-icon-projects-modal`,onClick:()=>g(f(`projects`,`projects-modal`,{windowWeeks:u}))}),children:(0,Z.jsxs)(`div`,{className:`projects-modal-body`,children:[(0,Z.jsxs)(`div`,{className:`projects-controls`,children:[(0,Z.jsxs)(`div`,{className:`projects-control-group`,role:`radiogroup`,"aria-label":`Window`,children:[tr.map(e=>(0,Z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":u===e,"aria-label":`${e} ${e===1?`cycle`:`cycles`}`,className:`pill ${u===e?`on`:``}`,disabled:!n,title:n?void 0:`Provider-native project history is unavailable`,onClick:()=>D(`projectsWindowWeeks`,e),children:e},`window-${e}`)),(0,Z.jsx)(`span`,{className:`projects-window-unit`,"aria-hidden":`true`,children:`cycles`})]}),(0,Z.jsx)(`span`,{className:`sep`,"aria-hidden":`true`,children:`|`}),(0,Z.jsxs)(`div`,{className:`projects-control-group`,role:`radiogroup`,"aria-label":`Y-axis`,children:[(0,Z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":d===`share`,className:`pill ${d===`share`?`on`:``}`,onClick:()=>D(`projectsTrendYMode`,`share`),children:`share %`}),(0,Z.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":d===`absolute`,className:`pill ${d===`absolute`?`on`:``}`,onClick:()=>D(`projectsTrendYMode`,`absolute`),children:`$ absolute`})]})]}),(0,Z.jsx)(`p`,{className:`projects-caption`,children:N}),e!==`codex`&&s(t,`claude`)&&(0,Z.jsx)(`p`,{className:`projects-caption projects-merged-note`,children:`Claude accounts are folded into one ranking here. Each account has its own weekly quota, so those percentages are never added across accounts.`}),E>0&&E<T&&(0,Z.jsxs)(`div`,{className:`projects-notice`,children:[`Showing `,E,` cycle`,E===1?``:`s`,` (need more history for the full window).`]}),!n&&(0,Z.jsx)(`div`,{className:`projects-notice m-unavailable`,children:i==null?`Project metadata is unavailable; accounting remains current.`:`Provider-native project totals are available for the current source window; historical window controls are unavailable.`}),n&&C?(0,Z.jsx)(Qn,{trend:C,yMode:d,windowWeeks:u,onProjectSelect:e=>b(e)}):!n&&i&&i.length>0?(0,Z.jsx)(Jn,{series:i.slice(0,6).map(e=>({key:e.key,bucket_path:e.label,weekly:[e.cost],cost:e.cost})),onProjectSelect:k}):(0,Z.jsx)(`div`,{className:`projects-ranked panel-empty m-unavailable`,"data-testid":`projects-ranked-bars`,children:a??(i==null?`Project attribution unavailable.`:`No project activity in this source window.`)}),re&&(0,Z.jsxs)(`button`,{type:`button`,className:`projects-mobile-sort`,"data-testid":`projects-mobile-sort`,onClick:ce,"aria-label":`Cycle sort column`,children:[`Sort: `,le.label,` `,le.arrow]}),(0,Z.jsxs)(`table`,{className:`projects-table`,children:[(0,Z.jsx)(ae,{columns:Le,override:m,onChange:e=>g({type:`SET_TABLE_SORT`,table:`projects`,override:e}),accentVar:`--accent-magenta`}),(0,Z.jsx)(`tbody`,{children:I.map(e=>(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{"data-testid":`projects-table-row`,"data-cost":e.windowCost,"data-sessions":e.sessionsCount,"aria-expanded":n&&y===e.key,className:n&&y===e.key?`selected`:``,tabIndex:0,onClick:()=>k(e.key),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),t.stopPropagation(),k(e.key))},children:[(0,Z.jsxs)(`td`,{className:`project`,children:[e.displayKey??e.key,e.source&&(0,Z.jsx)(`span`,{className:`source-chip source-chip--${e.source}`,children:e.source===`claude`?`Claude`:`Codex`})]}),(0,Z.jsx)(`td`,{children:e.sessionsCount}),(0,Z.jsx)(`td`,{className:`started first-seen${!n&&e.firstSeenAt==null?` m-unavailable`:``}`,children:v.dateShort(e.firstSeenAt,c)??(n?`—`:`Unavailable`)}),(0,Z.jsx)(`td`,{className:`started last-seen${!n&&e.lastSeenAt==null?` m-unavailable`:``}`,children:v.dateShort(e.lastSeenAt,c)??(n?`—`:`Unavailable`)}),(0,Z.jsx)(`td`,{className:oe(e.windowCost),children:v.usd2(e.windowCost)}),(0,Z.jsx)(`td`,{className:!n&&e.windowPct==null?`m-unavailable`:void 0,children:e.windowPct==null?n?`—`:`Unavailable`:v.pct0(e.windowPct)}),(0,Z.jsx)(`td`,{children:e.shareOfWindow==null?`—`:v.pct0(e.shareOfWindow)})]}),n&&re&&y===e.key&&(0,Z.jsx)(`tr`,{className:`projects-drill-row`,"aria-hidden":`false`,children:(0,Z.jsx)(`td`,{colSpan:7,children:(0,Z.jsx)(qe,{projectKey:e.key,windowWeeks:u,detail:ie})})})]},e.key))})]}),ne&&(0,Z.jsx)(`button`,{type:`button`,className:`projects-table-toggle`,"data-testid":`projects-table-toggle`,"aria-expanded":x,onClick:()=>S(e=>!e),children:x?`Show top 10 active`:`Show all ${F.length} projects (+${te})`}),n&&!re&&y&&(0,Z.jsx)(qe,{projectKey:y,windowWeeks:u,detail:ie}),(0,Z.jsx)(bn,{className:`projects-modal-footer-hint`,"data-testid":`projects-modal-footer-hint`,hints:[{keys:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`kbd`,{children:`1`}),`/`,(0,Z.jsx)(`kbd`,{children:`4`}),`/`,(0,Z.jsx)(`kbd`,{children:`8`}),`/`,(0,Z.jsx)(`kbd`,{children:`0`})]}),label:`window`},{keys:(0,Z.jsx)(`kbd`,{children:`↑↓`}),label:`row`},{keys:(0,Z.jsx)(`kbd`,{children:`Enter`}),label:`drill`},{keys:(0,Z.jsx)(`kbd`,{children:`s`}),label:`share/$`},{keys:(0,Z.jsx)(`kbd`,{children:`Esc`}),label:`close`}]})]})})}function rr(){return(0,Z.jsx)(nr,{source:(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource)})}function ir({reason:e}){return(0,Z.jsx)(`span`,{className:`m-unavailable`,"aria-label":e,title:e,children:`n/a`})}function ar({cr:e,source:t}){let n=t??`claude`,r=H(n),i=Fe(e,`wasted_usd`),a=ge(e),{insufficient:o}=a,s=a.chromeAmber,c=a.todayObserved,l=e.days.filter(e=>e.observed!==!1).length,u;u=o?{text:`~ Building baseline · ${e.today.baseline_daily_row_count}/5 days`,cls:`thin`}:s?{text:`⚠ Anomaly`,cls:``}:c?{text:`✓ Healthy`,cls:`ok`}:{text:`· No activity today`,cls:`thin`};let d=e=>c?e:(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`—`}),f=e.today.baseline_median_percent,p=e.today.delta_pp,m;if(p===null)m=`—`;else{let e=v.pctFloor(Math.abs(p));m=`${p<0?`−`:`+`}${e}pp`}return(0,Z.jsxs)(`div`,{className:`crm-section`,children:[(0,Z.jsxs)(`div`,{className:`crm-section-head crm-sh-spotlight`,children:[`Today's spotlight`,(0,Z.jsxs)(`span`,{className:`meta`,children:[v.calDate(e.today.date),` · `,l,` days observed`]})]}),(0,Z.jsxs)(`div`,{className:`crm-spotlight${s?` anom`:``}`,children:[(0,Z.jsxs)(`div`,{className:`crm-spotlight-row`,children:[(0,Z.jsx)(`span`,{className:`pill${u.cls?` `+u.cls:``}`,children:u.text}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`k`,children:r.percentLabel}),` `,(0,Z.jsx)(`strong`,{children:d(G(e.today,n)??(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`Unavailable`}))})]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`k`,children:`14d median`}),` `,(0,Z.jsx)(`strong`,{children:f===null?(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`Unavailable`}):`${v.pctFloor(f)}%`})]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`k`,children:`Δ`}),` `,(0,Z.jsx)(`strong`,{children:d(m)})]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`k`,children:`Net`}),` `,(0,Z.jsx)(`strong`,{children:d(v.usdSigned(e.today.net_usd))})]}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`k`,children:`Saved / Wasted`}),` `,(0,Z.jsx)(`strong`,{children:d(i==null?e.today.wasted_usd==null?`$${e.today.saved_usd.toFixed(2)} / unavailable`:`$${e.today.saved_usd.toFixed(2)} / $${e.today.wasted_usd.toFixed(2)}`:(0,Z.jsxs)(Z.Fragment,{children:[`$${e.today.saved_usd.toFixed(2)} / `,(0,Z.jsx)(ir,{reason:i})]}))})]})]}),s&&e.today.anomaly_reasons.length>0&&(0,Z.jsxs)(`div`,{className:`reasons`,children:[`Reasons:`,` `,e.today.anomaly_reasons.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,(0,Z.jsx)(`code`,{children:r.reasonLabel(e)})]},e)),` | `,`thresholds: `,r.thresholdLegend(e.anomaly_threshold_pp)]})]})]})}function or(e){let t=e.split(`/`).filter(Boolean);return t.length?t[t.length-1]:e}function sr({kind:e,rows:t,source:n}){let r=n??`claude`,i=e===`projects`?`bd-projects`:`bd-models`,a=e===`projects`?`By project`:`By model`,o=e===`projects`?`No project activity in this window`:`No model activity in this window`,s=e===`projects`;return(0,Z.jsxs)(`div`,{className:`crm-bd-card ${i}`,"data-bd-kind":e,children:[(0,Z.jsx)(`div`,{className:`crm-bd-head`,children:a}),t.length===0?(0,Z.jsx)(`div`,{className:`empty`,children:o}):(0,Z.jsx)(`table`,{children:(0,Z.jsx)(`tbody`,{children:t.map(e=>{let t=s?or(e.key):e.key,n=t!==e.key;return(0,Z.jsxs)(`tr`,{"data-testid":`crm-bd-row`,"data-bd-key":e.key,children:[(0,Z.jsx)(`td`,{className:`bd-key`,title:n?e.key:void 0,children:t}),(0,Z.jsx)(`td`,{children:G(e,r)??(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`—`})}),(0,Z.jsx)(`td`,{className:e.net_usd>=0?`net-pos`:`net-neg`,children:v.usdSigned(e.net_usd)})]},e.key)})})})]})}function cr({current_threshold_pp:e,onClose:t}){let[n,r]=(0,X.useState)(String(e)),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(!1),u=(0,X.useRef)(null);(0,X.useEffect)(()=>{function e(e){let n=e.target;n&&n.closest(`[data-cr-settings-toggle]`)||u.current&&!u.current.contains(e.target)&&t()}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t]),(0,X.useEffect)(()=>{function e(e){e.key===`Escape`&&(e.stopPropagation(),t())}return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[t]);async function d(){l(!1);let e=n.trim(),t=/^-?\d+$/.test(e)?parseInt(e,10):NaN;if(!Number.isInteger(t)||t<1||t>100){a(`Must be an integer between 1 and 100`);return}s(!0),a(null);try{let e=await fetch(`/api/settings`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cache_report:{anomaly_threshold_pp:t}})});if(e.ok)l(!0),setTimeout(()=>l(!1),1500);else{let t=await e.json().catch(()=>({}));a(typeof t.error==`string`?t.error:`HTTP ${e.status}`)}}catch(e){a(String(e))}finally{s(!1)}}return(0,Z.jsxs)(`div`,{ref:u,className:`crm-settings-popover`,role:`dialog`,"aria-label":`Cache Report settings`,children:[(0,Z.jsx)(`h4`,{children:`Cache Report settings`}),(0,Z.jsx)(`label`,{htmlFor:`cr-threshold`,children:`Anomaly threshold (pp)`}),(0,Z.jsx)(`input`,{id:`cr-threshold`,"aria-describedby":`cr-threshold-hint`,type:`number`,inputMode:`numeric`,min:1,max:100,value:n,onChange:e=>{r(e.target.value),a(null),l(!1)},className:i?`invalid`:``}),i&&(0,Z.jsx)(`div`,{className:`err`,children:i}),c&&(0,Z.jsx)(`div`,{className:`saved`,children:`Saved · next sync will re-evaluate`}),(0,Z.jsxs)(`p`,{className:`hint`,id:`cr-threshold-hint`,children:[`This threshold applies to the dashboard and the TUI.`,` `,(0,Z.jsx)(`code`,{children:`cctally cache-report`}),` does not read it: that command has its own `,(0,Z.jsx)(`code`,{children:`--anomaly-threshold-pp`}),` flag, which defaults to 15.`]}),(0,Z.jsxs)(`div`,{className:`actions`,children:[(0,Z.jsx)(`button`,{onClick:t,type:`button`,children:`Close`}),(0,Z.jsx)(`button`,{className:`primary`,onClick:d,disabled:o,type:`button`,children:o?`Saving…`:`Save`})]})]})}function lr(e,t,n){let r=xe(e,n),i=t!==null&&r!==null;return{comparable:i,isHitBad:i&&r<t-5,isNetNeg:e.net_usd<0}}function ur(e,t){return Te(ye(e,t).state)}function dr({d:e,predicates:t,reasonLabel:n}){let r=ye(e,t),i=_e(r.state,r.unevaluated,r.observed,n);return(0,Z.jsx)(`span`,{className:`crm-flag-glyph`,"aria-label":i,title:i,children:Pe(r.state)})}function fr({vocab:e}){return(0,Z.jsxs)(`div`,{className:`crm-daily-legend`,"data-testid":`crm-daily-legend`,children:[`Flag: ✓ evaluated, no anomaly — ⚠ anomaly — · not evaluated (each flag's label names what was skipped). `,e.percentColumnHeader,` colour tracks the displayed ±`,5,`pp band around the median, which is deliberately separate from the configurable anomaly threshold.`]})}function $(e,t){return e.observed===!1?(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`—`}):t}function pr(e){return e.filter(e=>e.observed!==!1).length}function mr({section:e}){let t=e.value,n=H(e.source);return(0,Z.jsxs)(`section`,{className:`provider-composition-section cache-provider-detail`,"data-provider-section":e.source,"aria-labelledby":`cache-report-modal-${e.source}-heading`,children:[(0,Z.jsxs)(`div`,{className:`source-provider-head provider-composition-head`,children:[(0,Z.jsxs)(`h3`,{className:`sr-only`,id:`cache-report-modal-${e.source}-heading`,children:[e.label,` cache report detail`]}),(0,Z.jsx)(ie,{source:e.source}),(0,Z.jsxs)(`strong`,{children:[e.label,` cache report`]}),e.status!==`available`&&(0,Z.jsx)(`span`,{className:`provider-section-status`,children:e.status})]}),t==null?(0,Z.jsx)(`div`,{className:`provider-section-reason m-unavailable`,children:e.reason}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`crm-section`,children:(0,Z.jsx)(ar,{cr:t,source:e.source})}),(0,Z.jsxs)(`div`,{className:`crm-section`,children:[(0,Z.jsxs)(`div`,{className:`crm-section-head crm-sh-timeline`,children:[n.timelineHeading,` — `,t.window_days,`-day timeline`,(0,Z.jsx)(`span`,{className:`meta`,children:`provider-local`})]}),(0,Z.jsx)(`div`,{className:`crm-chart-frame timeline`,children:(0,Z.jsx)(Ee,{days:t.days,baseline_median_percent:t.today.baseline_median_percent,today_marker_color:t.today.anomaly_triggered?`var(--accent-amber)`:`var(--accent-green)`,size:`large`,source:e.source})})]}),(0,Z.jsx)(J,{days:t.days,size:`large`,source:e.source}),(0,Z.jsxs)(`div`,{className:`crm-counterfactual`,children:[`Provider-local counterfactual:`,` `,(0,Z.jsxs)(`strong`,{children:[`+$`,t.fourteen_day_counterfactual_usd.toFixed(2)]})]}),(0,Z.jsxs)(`div`,{className:`crm-section`,children:[(0,Z.jsxs)(`div`,{className:`crm-section-head crm-sh-table`,children:[`Daily rows · `,t.window_days,` days`,(0,Z.jsxs)(`span`,{className:`meta`,children:[pr(t.days),` observed`]})]}),(0,Z.jsx)(`div`,{className:`provider-daily-summary`,children:t.days.map(t=>(0,Z.jsxs)(`div`,{className:`provider-daily-summary-row`,children:[(0,Z.jsx)(`span`,{children:v.calDate(t.date)}),(0,Z.jsx)(`span`,{children:$(t,(0,Z.jsx)(Z.Fragment,{children:G(t,e.source)??`—`}))}),(0,Z.jsx)(`span`,{className:t.observed===!1?``:t.net_usd<0?`net-neg`:`net-pos`,children:$(t,(0,Z.jsx)(Z.Fragment,{children:v.usdSigned(t.net_usd)}))})]},t.date))})]}),(0,Z.jsx)(`div`,{className:`crm-section`,children:(0,Z.jsxs)(`div`,{className:`crm-breakdowns`,children:[(0,Z.jsx)(sr,{kind:`projects`,rows:t.by_project,source:e.source}),(0,Z.jsx)(sr,{kind:`models`,rows:t.by_model,source:e.source})]})}),e.reason&&(0,Z.jsx)(`div`,{className:`provider-section-reason`,children:e.reason})]})]})}function hr(){return(0,Z.jsx)(Y,{title:`Cache Report — by provider`,accentClass:`accent-teal`,children:(0,Z.jsx)(`div`,{className:`provider-composition provider-composition--modal`,role:`group`,"aria-label":`Claude and Codex cache reports`,children:re(P(`all`),`all`).sections.map(e=>(0,Z.jsx)(mr,{section:e},e.source))})})}function gr({source:e}){let t=P(e),n=re(t,e).sections[0],r=n?.value??null,i=de(e),a=H(e),o=r==null?null:Fe(r,`wasted_usd`),s=r==null?null:Fe(r,`fourteen_day_efficiency_ratio`),c=n&&n.status!==`available`?(0,Z.jsx)(`span`,{className:`provider-section-status`,children:n.status}):null,l=n?.reason??null,u=r==null&&i.source===e&&i.accountKey!==null&&i.isEmpty,d=n?.status===`empty`||r?.is_empty===!0||u,[f,p]=(0,X.useState)(!1),m=Be();if(d){let e=n?.status===`empty`||u;return(0,Z.jsxs)(Y,{title:`Cache Report`,accentClass:`accent-teal`,headerExtras:(e?null:c)??void 0,children:[(0,Z.jsx)(`div`,{style:{color:`var(--text-dim)`,padding:`20px 0`},children:r==null?`No ${n?.label??`Claude`} activity yet.`:`No ${n?.label??`Claude`} activity in the last ${r.window_days} days.`}),!e&&l&&(0,Z.jsx)(`div`,{className:`provider-section-reason`,children:l})]})}if(!r){let n=Oe(t,e).hydrating;return(0,Z.jsx)(Y,{title:`Cache Report`,accentClass:`accent-teal`,children:(0,Z.jsx)(`div`,{style:{color:`var(--text-dim)`,padding:`20px 0`},children:n?`Loading…`:`Cache Report unavailable — the snapshot could not be built. Retrying on the next sync.`})})}let h=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`sub crm-subtitle`,style:{marginRight:12,color:`var(--text-dim)`},children:m?`${r.window_days}d · ${e===`claude`?`Claude`:e===`codex`?`Codex`:`All`}`:`Last ${r.window_days} days · ${r.anomaly_window_days}d baseline · ${e===`claude`?`Claude only`:e===`codex`?`Codex native cache`:`All sources`}`}),c,(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Cache Report settings`,"data-cr-settings-toggle":!0,onClick:e=>{e.stopPropagation(),p(e=>!e)},style:{background:`transparent`,border:0,color:`var(--text-dim)`,cursor:`pointer`,fontSize:18,padding:`0 8px`},children:`⚙`})]}),g=ge(r).chromeAmber,_=g?`var(--accent-amber)`:`var(--accent-green)`,y=g?`accent-amber`:`accent-teal`,b=r.fourteen_day_efficiency_ratio==null?null:Math.round(r.fourteen_day_efficiency_ratio*100);return(0,Z.jsxs)(Y,{title:`Cache Report`,accentClass:y,headerExtras:h,children:[f&&(0,Z.jsx)(cr,{current_threshold_pp:r.anomaly_threshold_pp,onClose:()=>p(!1)}),l&&(0,Z.jsx)(`div`,{className:`provider-section-reason crm-status-reason`,children:l}),(0,Z.jsx)(ar,{cr:r,source:e}),(0,Z.jsxs)(`div`,{className:`crm-section`,children:[(0,Z.jsxs)(`div`,{className:`crm-section-head crm-sh-timeline`,children:[a.timelineHeading,` — `,r.window_days,`-day timeline`,(0,Z.jsxs)(`span`,{className:`meta`,children:[`band = `,r.anomaly_window_days,`d median ±`,5,`pp`]})]}),(0,Z.jsx)(`div`,{className:`crm-chart-frame timeline`,children:(0,Z.jsx)(Ee,{days:r.days,baseline_median_percent:r.today.baseline_median_percent,today_marker_color:_,size:`large`,source:e})})]}),(0,Z.jsx)(J,{days:r.days,size:`large`,source:e}),(0,Z.jsxs)(`div`,{className:`crm-counterfactual`,children:[a.counterfactualLead,` `,(0,Z.jsxs)(`strong`,{children:[`+$`,r.fourteen_day_counterfactual_usd.toFixed(2),` more`]}),` `,`across `,pr(r.days),` observed days · `,a.efficiencyLabel,` `,s==null?b==null?(0,Z.jsx)(`span`,{className:`m-unavailable`,children:`Unavailable`}):(0,Z.jsxs)(`span`,{title:`saved / (saved + |wasted|) = ${b}%`,children:[b,`%`]}):(0,Z.jsx)(ir,{reason:s})]}),(0,Z.jsxs)(`div`,{className:`crm-section`,children:[(0,Z.jsxs)(`div`,{className:`crm-section-head crm-sh-table`,children:[`Daily rows · `,r.window_days,` days`,(0,Z.jsxs)(`span`,{className:`meta`,children:[pr(r.days),` days observed`]})]}),(0,Z.jsx)(fr,{vocab:a}),m?(0,Z.jsx)(`div`,{className:`crm-daily-cards`,children:r.days.map(t=>{let n=t.date===r.today.date,{comparable:i,isHitBad:s,isNetNeg:c}=lr(t,r.today.baseline_median_percent,e),l=i?s?`hit-bad`:`hit-good`:``,u=[[a.percentColumnHeader,$(t,(0,Z.jsx)(`span`,{className:l,children:G(t,e)??`—`}))],[`Net`,$(t,(0,Z.jsx)(`span`,{className:c?`net-neg`:`net-pos`,children:v.usdSigned(t.net_usd)}))],[`Saved`,$(t,(0,Z.jsx)(`span`,{children:v.usd2(t.saved_usd)}))],[`Wasted`,o==null?$(t,(0,Z.jsx)(`span`,{children:t.wasted_usd==null?`—`:v.usd2(t.wasted_usd)})):(0,Z.jsx)(ir,{reason:o})],[`Tok In`,$(t,(0,Z.jsx)(`span`,{children:v.compact(t.input_tokens,{upper:!0})}))],[`Tok Out`,$(t,(0,Z.jsx)(`span`,{children:v.compact(t.output_tokens,{upper:!0})}))]];return(0,Z.jsxs)(`div`,{className:`crm-daily-card`+(n?` cur`:``),"data-testid":`crm-daily-card`,"data-date":t.date,children:[(0,Z.jsxs)(`div`,{className:`crm-daily-card-head`,children:[(0,Z.jsx)(`span`,{className:`cd-date`,children:v.calDate(t.date)}),(0,Z.jsx)(`span`,{className:`cd-flag ${ur(t,r.anomaly_predicates)}`,children:(0,Z.jsx)(dr,{d:t,predicates:r.anomaly_predicates,reasonLabel:a.reasonLabel})})]}),(0,Z.jsx)(`div`,{className:`crm-daily-card-grid`,children:u.map(([e,t])=>(0,Z.jsxs)(`div`,{className:`cd-cell`,children:[(0,Z.jsx)(`span`,{className:`lbl`,children:e}),(0,Z.jsx)(`span`,{className:`val num`,children:t})]},e))})]},t.date)})}):(0,Z.jsxs)(`table`,{className:`ch-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`c-date`,children:`Date`}),(0,Z.jsx)(`th`,{className:`c-hit num`,children:a.percentColumnHeader}),(0,Z.jsx)(`th`,{className:`c-tokens num`,children:`Tok In`}),(0,Z.jsx)(`th`,{className:`c-tokens num`,children:`Tok Out`}),(0,Z.jsx)(`th`,{className:`c-saved num`,children:`Saved`}),(0,Z.jsx)(`th`,{className:`c-wasted num`,children:`Wasted`}),(0,Z.jsx)(`th`,{className:`c-net num`,children:`Net`}),(0,Z.jsx)(`th`,{className:`c-flag num`,children:`Flag`})]})}),(0,Z.jsx)(`tbody`,{children:r.days.map(t=>{let n=t.date===r.today.date,{comparable:i,isHitBad:s,isNetNeg:c}=lr(t,r.today.baseline_median_percent,e);return(0,Z.jsxs)(`tr`,{className:n?`cur`:``,"data-testid":`crm-daily-row`,"data-date":t.date,children:[(0,Z.jsx)(`td`,{children:v.calDate(t.date)}),(0,Z.jsx)(`td`,{className:`num ${t.observed===!1?``:i?s?`hit-bad`:`hit-good`:``}`.trim(),children:$(t,(0,Z.jsx)(Z.Fragment,{children:G(t,e)??`—`}))}),(0,Z.jsx)(`td`,{className:`num`,children:$(t,(0,Z.jsx)(Z.Fragment,{children:v.compact(t.input_tokens,{upper:!0})}))}),(0,Z.jsx)(`td`,{className:`num`,children:$(t,(0,Z.jsx)(Z.Fragment,{children:v.compact(t.output_tokens,{upper:!0})}))}),(0,Z.jsx)(`td`,{className:`num`,children:$(t,(0,Z.jsx)(Z.Fragment,{children:v.usd2(t.saved_usd)}))}),(0,Z.jsx)(`td`,{className:`num`,children:o==null?$(t,(0,Z.jsx)(Z.Fragment,{children:t.wasted_usd==null?`—`:v.usd2(t.wasted_usd)})):(0,Z.jsx)(ir,{reason:o})}),(0,Z.jsx)(`td`,{className:`num ${t.observed===!1?``:c?`net-neg`:`net-pos`}`.trim(),children:$(t,(0,Z.jsx)(Z.Fragment,{children:v.usdSigned(t.net_usd)}))}),(0,Z.jsx)(`td`,{className:`num ${ur(t,r.anomaly_predicates)}`,children:(0,Z.jsx)(dr,{d:t,predicates:r.anomaly_predicates,reasonLabel:a.reasonLabel})})]},t.date)})})]})]}),(0,Z.jsx)(`div`,{className:`crm-section`,children:(0,Z.jsxs)(`div`,{className:`crm-breakdowns`,children:[(0,Z.jsx)(sr,{kind:`projects`,rows:r.by_project,source:e}),(0,Z.jsx)(sr,{kind:`models`,rows:r.by_model,source:e})]})})]})}function _r(){let e=(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource);return e===`all`?(0,Z.jsx)(hr,{}):(0,Z.jsx)(gr,{source:e})}function vr(e){let t=new URLSearchParams({source:e.source});return e.accountKey!=null&&e.accountKey!==``&&t.set(`account`,e.accountKey),e.windowStartAt!=null&&e.windowEndAt!=null&&(t.set(`start_at`,e.windowStartAt),t.set(`end_at`,e.windowEndAt)),`/api/diagnosis?${t.toString()}`}function yr(e,t){return typeof e!=`number`||!Number.isFinite(e)?!1:e>=t.contributorShareFloor-t.shareFloorEpsilon}function br(e){switch(e){case`provider_unavailable`:return`This provider’s store could not be read, so nothing here was measured.`;case`retained_range_mismatch`:return`The store does not retain this whole window, so it was not measured.`;case`pricing_unavailable`:return`Nothing in this window could be priced, so there are no dollars to divide.`;case`unattributed_evidence`:return`Nothing in this window carried the identity this class groups by.`;case`stale_evidence`:return`Part of this window was pruned from the store, so it cannot be measured.`;case`insufficient_population`:return`There is too little in this window to measure this class.`;case`transcripts_not_visible`:return`This dashboard is not authorized to read transcripts, so this class was not measured.`;case`signal_unavailable`:return`The local transcript store could not answer this class, so the signal could not be established at all.`;case`calculation_failed`:return`This measurement could not be computed.`;case`baseline_insufficient`:return`No comparable earlier window could be established.`;case null:case void 0:case``:return`This measurement is unavailable.`;default:return`This measurement is unavailable (${e}).`}}var xr=`Codex subagent attribution is derived from accounting metadata and needs no transcript access.`;function Sr(e,t){return e.results.some(e=>e.source!==t&&Cr(e,`subagent_fanout`))}function Cr(e,t){return e.contributors.some(e=>e.contributorClass===t)?!0:e.classes.some(e=>e.contributorClass===t&&e.verdict!==`withheld`&&e.verdict!==`not_applicable`)}function wr(e){switch(e){case`insufficient_population`:return`not measured: nothing in this class supplied this figure`;case null:case void 0:case``:return`not measured`;default:return`not measured (${e})`}}function Tr(e,t){switch(e){case`min_distinct_subjects`:return`fewer than ${t?.minDistinctSubjects??2} distinct ${t?.subjectKind??`subject`}s`;case`min_priced_entries`:return`fewer than ${t?.minPricedEntries??20} priced entries`;case`min_usd_coverage`:return`too little of the window’s cost could be measured`;case`no_priced_dollars`:return`no priced dollars to divide by`;case null:case void 0:case``:return``;default:return e}}function Er(e,t){return t?.registry?.find(t=>t.contributorClass===e)?.label??e}function Dr(e,t){return t?.registry?.find(t=>t.contributorClass===e)}function Or(e,t){return Dr(e,t)?.rule!=null}function kr(e){switch(e){case`unknown_context_window`:return`some requests had no known model context window`;case`scan_budget_exhausted`:return`some conversations held more history than the scan budget allows`;case`unresolved_subagent_attribution`:return`some subagent spend could not be joined to exactly one parent`;case`ambiguous_origin_category`:return`some threads carried an origin category this build cannot read`;case`no_retained_transcript`:return`some conversations retained no transcript to count turns in`;case null:case void 0:case``:return``;default:return`${e} (no description in this build)`}}function Ar(e){switch(e){case`flaggedTurnCount`:return`turns that rebuilt their cache`;case`affectedConversationCount`:return`conversations affected`;case`estWastedUsd`:return`estimated wasted cost`;case`conversationCount`:return`qualifying conversations`;case`medianHumanTurns`:return`median human turns`;case`maxContextWindowFraction`:return`largest request as a share of its context window`;case`identifiedSubagentCount`:return`identified subagents`;case`largestSubagentShare`:return`largest subagent as a share of this class`;case`unallocatedUsd`:return`unallocated cost`;default:return e}}var jr=new Set([`estWastedUsd`,`unallocatedUsd`]),Mr=new Set([`largestSubagentShare`,`maxContextWindowFraction`]);function Nr(e,t){return t==null||t.state!==`available`||typeof t.value!=`number`?null:jr.has(e)?`$${t.value.toFixed(2)}`:Mr.has(e)?`${(t.value*100).toFixed(1)}%`:String(t.value)}function Pr(e){return typeof e==`object`&&!!e&&Array.isArray(e.results)}function Fr(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(0),d=(0,X.useCallback)(()=>{u(e=>e+1)},[]),f=vr(e);return(0,X.useEffect)(()=>{let e=!1,t=new AbortController;return i(!0),o(null),c(!1),fetch(f,{signal:t.signal}).then(async t=>{let r=await t.json().catch(()=>null);if(e)return;if(t.ok||t.status===503&&Pr(r)){Pr(r)?(n(r),o(null)):(n(null),o(`The diagnosis response could not be read.`));return}n(null);let i=r;c(i?.code===`generation_incoherent`),o(i?.error??`HTTP ${t.status}`)}).catch(t=>{e||t?.name===`AbortError`||(n(null),o(t instanceof Error?t.message:String(t)))}).finally(()=>{e||i(!1)}),()=>{e=!0,t.abort()}},[f,l]),{report:t,loading:r,error:a,retryable:s,retry:d}}var Ir=`explain-modal-title`;function Lr(e,t){return e?v.datetimeShort(e,t):`—`}function Rr({field:e}){return e.state!==`available`||typeof e.value!=`number`?(0,Z.jsxs)(`span`,{className:`explain-withheld`,children:[br(e.code),e.qualifications.length>0?` ${e.qualifications.join(` `)}`:``]}):(0,Z.jsx)(`span`,{className:`explain-usd`,children:v.usd2(e.value)})}function zr(e){return e.state!==`available`||typeof e.value!=`number`?null:`${(e.value*100).toFixed(1)}%`}function Br({population:e,confidence:t,contributorClass:n,constants:r,excludeGapCodes:i=[]}){if(e==null)return null;let a=[];a.push(e.supportUnits==null?`support not measured`:`support ${e.supportUnits} ${e.supportUnits===1?`unit`:`units`}`),e.usdCoverage!=null&&a.push(`cost coverage ${(e.usdCoverage*100).toFixed(0)}%`),e.identityCoverage!=null&&a.push(`identity coverage ${(e.identityCoverage*100).toFixed(0)}%`),e.pricingCoverage!=null&&a.push(`priced without fallback ${(e.pricingCoverage*100).toFixed(0)}%`),e.retentionCoverage!=null&&a.push(`window retained ${(e.retentionCoverage*100).toFixed(0)}%`),e.evaluabilityCoverage!=null&&a.push(`decidable ${(e.evaluabilityCoverage*100).toFixed(0)}%`),t!=null&&t!==``&&a.push(`confidence ${t}`);let o=new Set(i),s=(Or(n,r)?e.gapCodes??[]:[]).filter(e=>!o.has(e)).map(e=>kr(e)).filter(e=>e!==``);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`explain-coverage`,children:a.join(` · `)}),s.length>0?(0,Z.jsxs)(`p`,{className:`explain-coverage explain-gaps`,children:[`undecided: `,s.join(` · `)]}):null]})}function Vr({evidence:e,stated:t}){let n=Object.keys(e??{}).sort();if(n.length===0)return null;let r=new Set(t);return(0,Z.jsx)(`p`,{className:`explain-row-figures explain-evidence`,children:n.map(t=>{let n=(e??{})[t],i=Nr(t,n),a=(n?.qualifications??[]).filter(e=>!r.has(e));return(0,Z.jsxs)(`span`,{className:`explain-figure`,"data-evidence":t,children:[(0,Z.jsx)(`span`,{className:`explain-figure-label`,children:Ar(t)}),i==null?(0,Z.jsx)(`span`,{className:`explain-withheld`,children:wr(n?.code)}):(0,Z.jsx)(`span`,{className:`explain-usd`,children:i}),a.length>0?(0,Z.jsx)(`span`,{className:`explain-evidence-qualification`,children:a.join(` · `)}):null]},t)})})}function Hr({contributorClass:e,constants:t}){let n=Dr(e,t)?.rule;return n==null?null:(0,Z.jsx)(`p`,{className:`explain-rule`,children:n.sentence})}function Ur({row:e,constants:t}){let n=zr(e.share),r=yr(typeof e.share.value==`number`?e.share.value:null,t),i=e.baseline.state===`available`&&typeof e.baseline.value==`number`?`${(e.baseline.value*100).toFixed(1)}% in the previous window`:br(e.baseline.code);return(0,Z.jsxs)(`li`,{className:`explain-row`,"data-class":e.contributorClass,children:[(0,Z.jsxs)(`p`,{className:`explain-row-head`,children:[(0,Z.jsx)(`span`,{className:`explain-rank`,children:e.rank==null?`—`:`#${e.rank}`}),(0,Z.jsx)(`span`,{className:`explain-row-class`,children:Er(e.contributorClass,t)}),(0,Z.jsx)(`span`,{className:`explain-row-subject`,children:e.subjectLabel}),r?(0,Z.jsx)(`span`,{className:`chip explain-chip-contributor`,children:`contributor`}):null]}),(0,Z.jsxs)(`p`,{className:`explain-row-figures`,children:[(0,Z.jsxs)(`span`,{className:`explain-figure`,children:[(0,Z.jsx)(`span`,{className:`explain-figure-label`,children:`observed cost`}),(0,Z.jsx)(Rr,{field:e.observedUsd})]}),(0,Z.jsxs)(`span`,{className:`explain-figure`,children:[(0,Z.jsx)(`span`,{className:`explain-figure-label`,children:`share of the denominator`}),(0,Z.jsx)(`span`,{className:`explain-share`,children:n??br(e.share.code)})]}),(0,Z.jsxs)(`span`,{className:`explain-figure`,children:[(0,Z.jsx)(`span`,{className:`explain-figure-label`,children:`against the previous window`}),(0,Z.jsx)(`span`,{className:`explain-baseline`,children:i})]})]}),(0,Z.jsxs)(`p`,{className:`explain-row-meta`,children:[`confidence `,e.confidence,e.isFallbackPricing?` · priced through a fallback rate`:``,e.observedUsd.qualifications.map(e=>` · ${e}`).join(``)]}),(0,Z.jsx)(Br,{population:e.observedUsd.population,contributorClass:e.contributorClass,constants:t}),(0,Z.jsx)(Vr,{evidence:e.evidence,stated:e.observedUsd.qualifications}),(0,Z.jsx)(Hr,{contributorClass:e.contributorClass,constants:t}),(0,Z.jsxs)(`p`,{className:`explain-row-next`,children:[(0,Z.jsx)(`span`,{className:`explain-figure-label`,children:`next step`}),(0,Z.jsx)(`code`,{children:e.nextStep})]})]})}function Wr({entry:e,constants:t,withheld:n,asymmetryPresent:r}){let i=n?Tr(e.supportShortfall,Dr(e.contributorClass,t)):``,a=n&&e.contributorClass===`subagent_fanout`&&e.code===`transcripts_not_visible`&&r;return(0,Z.jsxs)(`li`,{className:`explain-class`,"data-class":e.contributorClass,"data-verdict":e.verdict,children:[(0,Z.jsx)(`p`,{className:`explain-class-head`,children:Er(e.contributorClass,t)}),n?(0,Z.jsxs)(`p`,{className:`explain-withheld`,children:[br(e.code),i?` (${i})`:``]}):null,a?(0,Z.jsx)(`p`,{className:`explain-withheld explain-asymmetry`,children:xr}):null,(0,Z.jsx)(Br,{population:e.population,confidence:n?null:e.confidence,contributorClass:e.contributorClass,constants:t,excludeGapCodes:e.code?[e.code]:[]}),(0,Z.jsx)(Hr,{contributorClass:e.contributorClass,constants:t})]})}function Gr({result:e,constants:t,asymmetryPresent:n}){let r=e.classes.filter(e=>e.verdict===`no_contributor`),i=e.classes.filter(e=>e.verdict===`withheld`),a=e.classes.filter(e=>e.verdict===`not_applicable`);return(0,Z.jsxs)(`section`,{className:`explain-provider`,"data-source":e.source,children:[(0,Z.jsxs)(`h3`,{children:[e.source,` · `,e.accountKey??`all accounts`,e.effectiveSpeed?` · ${e.effectiveSpeed}`:``]}),(0,Z.jsxs)(`p`,{className:`explain-denominator`,children:[(0,Z.jsx)(`span`,{className:`explain-figure-label`,children:`Denominator`}),(0,Z.jsx)(`span`,{className:`explain-denominator-identity`,children:e.denominator.identity}),(0,Z.jsx)(Rr,{field:e.denominator.usd}),e.denominator.usd.state===`available`?(0,Z.jsx)(`span`,{className:`explain-denominator-note`,children:`of locally retained cost`}):null]}),e.contributors.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h4`,{children:`Reported contributors, ranked by observed cost`}),(0,Z.jsx)(`ul`,{className:`explain-rows`,children:e.contributors.map(e=>(0,Z.jsx)(Ur,{row:e,constants:t},`${e.contributorClass}:${e.subjectKey}`))})]}):null,r.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h4`,{children:`Classes reporting no contributor`}),(0,Z.jsx)(`ul`,{className:`explain-classes`,children:r.map(e=>(0,Z.jsx)(Wr,{entry:e,constants:t,withheld:!1,asymmetryPresent:n},e.contributorClass))})]}):null,i.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h4`,{children:`Classes with no measurement to report`}),(0,Z.jsx)(`ul`,{className:`explain-classes`,children:i.map(e=>(0,Z.jsx)(Wr,{entry:e,constants:t,withheld:!0,asymmetryPresent:n},e.contributorClass))})]}):null,a.length>0?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h4`,{children:`Classes this provider does not support`}),(0,Z.jsx)(`ul`,{className:`explain-classes`,children:a.map(n=>(0,Z.jsxs)(`li`,{className:`explain-class`,children:[Er(n.contributorClass,t),` — not applicable to `,e.source]},n.contributorClass))})]}):null,(0,Z.jsxs)(`p`,{className:`explain-verdict`,"data-verdict":e.verdict,children:[`Verdict for `,e.source,`: `,e.verdict,e.code?` (${e.code})`:``,` `,(0,Z.jsxs)(`span`,{className:`explain-completeness`,children:[`[`,e.withheldClassCount,` of `,e.applicableClassCount,` applicable`,` `,`classes withheld]`]})]})]})}function Kr({report:e,alertFiredAt:t,ctx:n}){let r=e.constants.contributorShareFloor;return(0,Z.jsxs)(`div`,{className:`explain-body`,children:[(0,Z.jsxs)(`dl`,{className:`explain-instants`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:`Window`}),(0,Z.jsxs)(`dd`,{children:[Lr(e.window.startAt,n),` to`,` `,Lr(e.window.endAt,n),` `,(0,Z.jsx)(j,{tz:n.tz}),` `,(0,Z.jsx)(`span`,{className:`explain-halfopen`,children:`(the start is included, the end is not)`})]})]}),t?(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:`Alert fired`}),(0,Z.jsxs)(`dd`,{children:[Lr(t,n),` `,(0,Z.jsx)(j,{tz:n.tz})]})]}):null,(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`dt`,{children:`Measured`}),(0,Z.jsxs)(`dd`,{children:[Lr(e.measuredAt,n),` `,(0,Z.jsx)(j,{tz:n.tz})]})]})]}),(0,Z.jsx)(`p`,{className:`explain-note`,children:e.notes.scope}),(0,Z.jsx)(`p`,{className:`explain-note`,children:e.notes.overlap}),(0,Z.jsxs)(`p`,{className:`explain-note`,children:[`A subject is reported as a contributor at a share of `,r.toFixed(2),` or more of its named denominator.`]}),e.constants.turnDefinition?(0,Z.jsx)(`p`,{className:`explain-note`,children:e.constants.turnDefinition}):null,e.results.map(t=>(0,Z.jsx)(Gr,{result:t,constants:e.constants,asymmetryPresent:Sr(e,t.source)},t.source)),(0,Z.jsxs)(`p`,{className:`explain-overall`,"data-verdict":e.overallVerdict,children:[`Overall: `,e.overallVerdict,e.overallCode?` (${e.overallCode})`:``,` `,(0,Z.jsxs)(`span`,{className:`explain-completeness`,children:[`[`,e.withheldClassCount,` of `,e.applicableClassCount,` applicable`,` `,`classes withheld]`]})]})]})}function qr(){let e=(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource),t=(0,X.useSyncExternalStore)(h,()=>_().openExplainAccountKey),n=(0,X.useSyncExternalStore)(h,()=>_().openExplainWindowStartAt),r=(0,X.useSyncExternalStore)(h,()=>_().openExplainWindowEndAt),i=(0,X.useSyncExternalStore)(h,()=>_().openExplainAlertFiredAt),a=W(),o={tz:a.resolvedTz,offsetLabel:a.offsetLabel},{report:s,loading:c,error:l,retryable:u,retry:d}=Fr({source:e,accountKey:t,windowStartAt:n,windowEndAt:r}),f=(0,X.useRef)(!1),p=(0,X.useCallback)(e=>{e!=null&&f.current&&(f.current=!1,e.focus())},[]),m=(0,X.useCallback)(()=>{f.current=!0,d()},[d]);return(0,X.useEffect)(()=>{if(c||l!=null&&u||!f.current)return;f.current=!1;let e=document.activeElement;e!=null&&e!==document.body||document.getElementById(Ir)?.focus()},[c,l,u]),(0,Z.jsxs)(Y,{title:`Where the cost went`,accentClass:`accent-indigo`,dataSource:e,rootTestId:`explain-modal`,titleId:Ir,wide:!0,children:[c&&s==null?(0,Z.jsx)(`p`,{className:`explain-status`,children:`Measuring this window…`}):null,l==null?null:(0,Z.jsx)(`div`,{className:`explain-status explain-error`,children:u?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{children:`The store changed while this window was being measured, so no single coherent answer could be published. Nothing is wrong with the data.`}),(0,Z.jsx)(`button`,{type:`button`,className:`explain-retry`,ref:p,onClick:m,children:`Measure again`})]}):(0,Z.jsxs)(`p`,{children:[`The diagnosis could not be requested: `,l]})}),s==null?null:(0,Z.jsx)(Kr,{report:s,alertFiredAt:i,ctx:o})]})}var Jr=100;function Yr({alert:e,ctx:t}){if(e.axis===`weekly`){let n=e.context.week_start_date?v.weekStart(e.context.week_start_date,t):null,r=e.context.dollars_per_percent;return(0,Z.jsxs)(`span`,{className:`alert-context alert-context--weekly`,children:[n?`Week of ${n}`:`Week —`,r!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsxs)(`span`,{className:`num`,children:[`$`,r.toFixed(2),`/1%`]})]})]})}if(e.axis===`budget`){let n=o(e.context.period),r=e.context.period_start_at??e.context.week_start_at,i=r?v.weekStart(r.slice(0,10),t):null,a=e.context.consumption_pct;return(0,Z.jsxs)(`span`,{className:`alert-context alert-context--budget`,children:[i?`${n} of ${i}`:`${n} —`,a!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsxs)(`span`,{className:`num`,children:[Math.round(a),`% of budget`]})]})]})}if(e.axis===`codex_budget`){let n=o(e.context.period),r=e.context.period_start_at,i=r?v.weekStart(r.slice(0,10),t):null,a=e.context.consumption_pct;return(0,Z.jsxs)(`span`,{className:`alert-context alert-context--codex_budget`,children:[i?`${n} of ${i}`:`${n} —`,a!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsxs)(`span`,{className:`num`,children:[Math.round(a),`% of budget`]})]})]})}if(e.axis===`project_budget`){let t=e.context.project??`(project)`,n=e.context.consumption_pct;return(0,Z.jsxs)(`span`,{className:`alert-context alert-context--project_budget`,children:[t,n!=null&&(0,Z.jsxs)(Z.Fragment,{children:[` · `,(0,Z.jsxs)(`span`,{className:`num`,children:[Math.round(n),`% of budget`]})]})]})}return e.axis===`projected`?(0,Z.jsx)(`span`,{className:`alert-context alert-context--projected`,children:c(e)??`Projected —`}):(0,Z.jsxs)(`span`,{className:`alert-context alert-context--five-hour`,children:[`Block `,e.context.block_start_at?v.timeOnly(e.context.block_start_at,t):`—`]})}function Xr({alert:e}){if(e.axis===`projected`)return(0,Z.jsx)(`span`,{className:`num`,children:`—`});let t;return t=e.axis===`weekly`?e.context.cumulative_cost_usd:e.axis===`budget`||e.axis===`project_budget`||e.axis===`codex_budget`?e.context.spent_usd:e.context.block_cost_usd,(0,Z.jsx)(`span`,{className:`num`,children:v.usd2(t??null)})}function Zr({row:e}){if(e.axis===`quota`)return(0,Z.jsx)(`span`,{className:`alert-context alert-context--quota`,children:`Quota threshold`});let t=o(e.period);return(0,Z.jsxs)(`span`,{className:`alert-context alert-context--${e.axis}`,children:[t,` · `,(0,Z.jsxs)(`span`,{className:`num`,children:[Math.round(e.value),`% of budget`]})]})}function Qr(){return(0,Z.jsx)(`span`,{className:`num`,children:`—`})}function $r(e){let t=[],n=Ce(e.withholding_status);n!=null&&t.push({key:`withheld`,label:`Calibration:`,value:n});let r=e.detector_input_causes;r!=null&&r.length>0&&t.push({key:`causes`,label:`Detector input:`,value:r.join(`, `)});let i=e.composition_provenance;i!=null&&i.length>0&&t.push({key:`provenance`,label:`Composition:`,value:i.join(`, `)});let a=e.baseline_withheld_days;return a!=null&&t.push({key:`baseline`,label:`Baseline:`,value:a===0?`clean baseline`:`${a} withheld baseline ${a===1?`day`:`days`}`}),t}function ei({rows:t,ctx:n,showAccountColumn:r}){return(0,Z.jsxs)(`section`,{className:`alerts-rate-change`,"data-testid":`alerts-rate-change`,children:[(0,Z.jsx)(`h3`,{className:`alerts-rate-change-heading`,children:`Metering rate changes`}),(0,Z.jsx)(`p`,{className:`alerts-rate-change-note`,children:`The provider changed how much work one meter point buys. This is the provider’s behaviour, not a cctally malfunction.`}),(0,Z.jsxs)(`table`,{className:`alerts-table alerts-table--rate-change`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{scope:`col`,children:`Provider`}),r&&(0,Z.jsx)(`th`,{scope:`col`,children:`Account`}),(0,Z.jsx)(`th`,{scope:`col`,children:`Change`}),(0,Z.jsx)(`th`,{scope:`col`,children:`Units / point`}),(0,Z.jsx)(`th`,{scope:`col`,children:`Effective`})]})}),(0,Z.jsx)(`tbody`,{children:t.map(t=>{let i=A(t.previous_units_per_point,t.new_units_per_point),a=e(t),o=v.startedShortOrNull(t.effective_from,n),s=v.relativeOrAbsolute(t.effective_from??``,n),c=$r(t);return(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`alert-modal-row`,children:[(0,Z.jsx)(`td`,{className:`alert-cell-source`,children:(0,Z.jsx)(`span`,{className:`source-chip source-chip--${t.provider}`,children:t.provider})}),r&&(0,Z.jsx)(`td`,{className:`alert-cell-account`,children:a!=null&&(0,Z.jsx)(`span`,{className:`alert-account-chip`,title:a.label,children:a.label})}),(0,Z.jsx)(`td`,{className:`alert-cell-axis severity-${t.severity} ${t.severity}`,children:(0,Z.jsx)(`span`,{className:`chip chip-rate-change severity-${t.severity}`,children:i??`rate changed`})}),(0,Z.jsx)(`td`,{className:`alert-cell-cost num`,children:t.previous_units_per_point!=null&&t.new_units_per_point!=null?`${Math.round(t.previous_units_per_point).toLocaleString()} → ${Math.round(t.new_units_per_point).toLocaleString()}`:`—`}),(0,Z.jsxs)(`td`,{className:`alert-cell-when alert-when`,title:o??void 0,children:[s,s===`—`?null:(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(j,{tz:n.tz})]})]})]}),c.length>0&&(0,Z.jsx)(`tr`,{className:`alert-modal-row alerts-rate-change-evidence-row`,children:(0,Z.jsx)(`td`,{className:`alerts-rate-change-evidence`,colSpan:r?5:4,children:c.map(e=>(0,Z.jsxs)(`span`,{className:`alerts-rate-change-evidence-item`,children:[(0,Z.jsx)(`span`,{className:`alerts-rate-change-evidence-label`,children:e.label}),` `,e.value]},e.key))})})]},t.id)})})]})]})}function ti(){let i=(0,X.useSyncExternalStore)(h,()=>_().openModalSource??_().activeSource),a=P(i),o=de(i),s=(0,X.useSyncExternalStore)(h,()=>_().alerts),c=a?.sources!=null,d=t(l(a??null,i),s.map(e=>({...e,source:`claude`,key:e.id})),c),f=(0,X.useSyncExternalStore)(h,()=>_().accountFocus),p=n(d,{claude:r(a,i,`claude`,f),codex:r(a,i,`codex`,f)}),m=W(),g={tz:m.resolvedTz,offsetLabel:m.offsetLabel},x=(0,X.useSyncExternalStore)(h,()=>_().alertsConfig),S=a?.sources?.codex?.data?.quota.summary,C=x.weekly_thresholds?.length?x.weekly_thresholds:[90,95],w=a?.sources?.codex?.data?.alerts.actual_thresholds?.length?a.sources.codex.data.alerts.actual_thresholds:[90,95],E=i===`claude`?a?.header?.used_pct??null:i===`codex`?o.scopesSupported&&o.accountKey==null?null:S?.latest_percent??null:null,D=i===`claude`?C:i===`codex`?w:[...new Set([...C,...w])].sort((e,t)=>e-t),O=p.slice(0,Jr),k=i===`all`,A=O.some(t=>e(t)!=null),M=(a?.meter_rate_changes??[]).filter(e=>i===`all`||e.owner===i),N=M.some(t=>e(t)!=null);return O.length===0&&M.length===0?(0,Z.jsx)(Y,{title:`Recent alerts`,accentClass:`accent-amber`,children:(0,Z.jsx)(Ve,{source:i,usedPct:E,thresholds:D})}):O.length===0?(0,Z.jsx)(Y,{title:`Recent alerts`,accentClass:`accent-amber`,children:(0,Z.jsxs)(`div`,{className:`alerts-modal-body`,children:[(0,Z.jsx)(Ve,{source:i,usedPct:E,thresholds:D}),(0,Z.jsx)(ei,{rows:M,ctx:g,showAccountColumn:N})]})}):(0,Z.jsx)(Y,{title:`Recent alerts`,accentClass:`accent-amber`,children:(0,Z.jsxs)(`div`,{className:`alerts-modal-body`,children:[(0,Z.jsxs)(`table`,{className:`alerts-table`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{scope:`col`,children:`%`}),(0,Z.jsx)(`th`,{scope:`col`,children:`Axis`}),k&&(0,Z.jsx)(`th`,{scope:`col`,children:`Source`}),A&&(0,Z.jsx)(`th`,{scope:`col`,children:`Account`}),(0,Z.jsx)(`th`,{scope:`col`,children:`Cost`}),(0,Z.jsx)(`th`,{scope:`col`,children:`Context`}),(0,Z.jsx)(`th`,{scope:`col`,children:`Alerted`})]})}),(0,Z.jsx)(`tbody`,{children:O.map(t=>{let n=T(t),r=t.source===`claude`,i=r?y(t):n.severity,o=e(t),s=v.startedShortOrNull(n.whenIso,g),c=v.relativeOrAbsolute(n.whenIso??``,g);return(0,Z.jsxs)(`tr`,{className:`alert-modal-row`,children:[(0,Z.jsxs)(`td`,{className:`alert-threshold alert-cell-threshold severity-${i} ${i} num`,children:[n.threshold,`%`]}),(0,Z.jsx)(`td`,{className:`alert-cell-axis`,children:(0,Z.jsx)(`span`,{className:`chip ${n.chipClass}`,children:r?b[t.axis]:n.chipLabel})}),k&&(0,Z.jsx)(`td`,{className:`alert-cell-source`,children:(0,Z.jsx)(`span`,{className:`source-chip source-chip--${n.source}`,children:n.sourceLabel})}),A&&(0,Z.jsx)(`td`,{className:`alert-cell-account`,children:o!=null&&(0,Z.jsx)(`span`,{className:`alert-account-chip`,title:o.label,children:o.label})}),(0,Z.jsx)(`td`,{className:`alert-cell-cost num`,children:r?(0,Z.jsx)(Xr,{alert:t}):(0,Z.jsx)(Qr,{})}),(0,Z.jsxs)(`td`,{className:`alert-cell-context`,children:[r?(0,Z.jsx)(Yr,{alert:t,ctx:g}):(0,Z.jsx)(Zr,{row:t}),r&&(0,Z.jsx)(me,{alert:t,env:a})]}),(0,Z.jsxs)(`td`,{className:`alert-cell-when alert-when`,title:s??void 0,children:[c,c===`—`?null:(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(j,{tz:g.tz})]})]})]},u(t))})})]}),p.length>Jr&&(0,Z.jsxs)(`div`,{className:`alerts-modal-foot`,children:[`Showing `,Jr,` of `,p.length,` most recent`]}),M.length>0&&(0,Z.jsx)(ei,{rows:M,ctx:g,showAccountColumn:N})]})})}function ni(){let e=(0,X.useSyncExternalStore)(h,()=>_().openModal);if(!e)return null;switch(e){case`current-week`:return(0,Z.jsx)(Mt,{});case`forecast`:return(0,Z.jsx)(Gt,{});case`trend`:return(0,Z.jsx)(sn,{});case`session`:return(0,Z.jsx)(Ke,{});case`daily`:return(0,Z.jsx)(En,{});case`weekly`:return(0,Z.jsx)(Dn,{});case`monthly`:return(0,Z.jsx)(On,{});case`block`:return(0,Z.jsx)(Rn,{});case`projects`:return(0,Z.jsx)(rr,{});case`alerts`:return(0,Z.jsx)(ti,{});case`cache-report`:return(0,Z.jsx)(_r,{});case`explain`:return(0,Z.jsx)(qr,{})}}export{ni as ModalRoot};
@@ -0,0 +1 @@
1
+ import{Ft as e,Rt as t,U as n,a as r,b as i,c as a,f as o,gt as s,it as c,rt as l,t as u,ut as d,x as f,y as p}from"./useKeymap-CW7Up0Ay.js";import{Ft as m,M as h,N as g,at as _,bt as v,ct as y,dt as b,it as x,j as S,lt as C,o as w,ut as T}from"./index-DdU62sov.js";import{N as E,a as D,o as O,s as k,t as A}from"./outlineNavigation-BOCLcRa6.js";var j=t(e(),1),M=r();function N({title:e,accentClass:t,children:n,headerExtras:r,wide:s,paneScroll:c,dataSource:l,onClose:d,focusLayer:p=`panel`,rootId:m=`modal-root`,titleId:h=`modal-title`,bodyId:g=`modal-body`,rootTestId:_,cardClassName:v,triggerId:y}){let x=(0,j.useCallback)(()=>{d?d():a({type:`CLOSE_MODAL`})},[d]);u((0,j.useMemo)(()=>[{key:`Escape`,scope:`modal`,layer:p===`source-detail`?150:100,action:x,when:()=>f(o())===p}],[x,p]));let S=(0,j.useRef)(null);return b(S,{active:!0,trapEnabled:(0,j.useSyncExternalStore)(i,()=>f(o())===p),initialFocus:`heading`,triggerId:y}),T(!0),(0,M.jsxs)(`div`,{id:m,..._?{"data-testid":_}:{},children:[(0,M.jsx)(`div`,{className:`modal-backdrop`,onClick:x}),(0,M.jsxs)(`div`,{ref:S,className:`modal-card ${t}${s?` modal-wide`:``}${c?` modal-pane-scroll`:``}${v?` ${v}`:``}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":h,"data-source":l,children:[(0,M.jsx)(w,{title:e,titleId:h,headerExtras:r,onClose:x}),(0,M.jsx)(`div`,{id:g,className:`modal-body`,children:n})]})]})}function P(e){return e===`codex`?`accent-provider-codex`:`accent-provider-claude`}var F=3;function I({sessionId:e}){let t=(0,j.useSyncExternalStore)(i,()=>p(o())),{outline:n}=k(t?e:null),r=m(),u=(0,j.useMemo)(()=>l(r),[r?.display?.resolved_tz,r?.display?.offset_label]),[f,h]=(0,j.useState)(!1);if(!t||!n||!n.stats||!e)return null;let g=n.stats,_=g.cache_failures,v=_?.count??0,y=g.cache_saved_usd??0,b=_?.rebuilds??[],x=f?b:b.slice(0,F),S=e,C=e=>{let t=n.turns??[],r=O(A(t,void 0,n.landmarks),e),i=r===void 0?void 0:t[r],c=o().convFocusMode;i&&c!==`all`&&!D(i,c)&&a({type:`SET_CONV_FOCUS_MODE`,mode:`all`}),a({type:`OPEN_CONVERSATION`,sessionId:S,jump:d(s(S),e,!1)})};return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`h3`,{className:`m-sec sec-rebuild`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#refresh`})}),`Cache rebuilds`]}),v===0?(0,M.jsx)(`div`,{className:`msess-rebuild-none`,id:`msess-rebuild-none`,children:`No cache rebuilds ✓`}):(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`div`,{className:`msess-tok-grid msess-rebuild-tiles`,id:`msess-rebuild-tiles`,children:[(0,M.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,M.jsx)(`div`,{className:`lbl`,children:`Rebuilds`}),(0,M.jsx)(`div`,{className:`n`,children:v})]}),(0,M.jsxs)(`div`,{className:`msess-tok-tile rebuild-wasted`,children:[(0,M.jsx)(`div`,{className:`lbl`,children:`Wasted`}),(0,M.jsx)(`div`,{className:`n`,children:c.usd2(_.est_wasted_usd)})]}),(0,M.jsxs)(`div`,{className:`msess-tok-tile`,children:[(0,M.jsx)(`div`,{className:`lbl`,children:`Re-created`}),(0,M.jsx)(`div`,{className:`n`,children:_.tokens_recreated.toLocaleString(`en-US`)})]})]}),(0,M.jsx)(`ul`,{className:`msess-rebuild-list`,id:`msess-rebuild-list`,children:x.map(e=>(0,M.jsx)(`li`,{className:`rebuild-row`,children:(0,M.jsxs)(`button`,{type:`button`,className:`rebuild-jump`,onClick:()=>C(e.uuid),children:[(0,M.jsx)(`span`,{className:`rb-cost`,children:c.usd2(e.est_wasted_usd)}),(0,M.jsxs)(`span`,{className:`rb-tok`,children:[e.tokens_recreated.toLocaleString(`en-US`),` tok`]}),(0,M.jsx)(`span`,{className:`rb-time`,children:e.ts?c.timeHHmm(e.ts,u,{noSuffix:!0}):``}),e.subagent_key?(0,M.jsx)(`span`,{className:`rb-sub`,children:`subagent`}):null,(0,M.jsx)(`span`,{className:`rb-go`,children:`→ Jump`})]})},e.uuid))}),b.length>F&&!f?(0,M.jsxs)(`button`,{type:`button`,className:`msess-rebuild-more`,onClick:()=>h(!0),children:[`+`,b.length-F,` more`]}):null]}),y>0?(0,M.jsxs)(`div`,{className:`msess-rebuild-saved`,id:`msess-rebuild-saved`,children:[`Cache saved this session `,c.usd2(y),` ✓`]}):null]})}function L({rows:e}){let t=e[0]?.cost_usd??0,n=t>0?t:1;return(0,M.jsx)(M.Fragment,{children:e.map(e=>{let t=e.cost_usd/n*100,r=_(e.model),i={"--w":`${t}%`,"--model-color":r?.backgroundColor};return(0,M.jsxs)(`div`,{className:`drill-bar-row`,children:[(0,M.jsx)(`span`,{className:`chip ${x(e.model)}`,style:r,children:e.label??e.model}),(0,M.jsx)(`div`,{className:`drill-bar`,style:i}),(0,M.jsx)(`span`,{className:`cost ${g(e.cost_usd)}`,children:c.usd2(e.cost_usd)})]},e.model)})})}function R(e){let t=new Set;return(e.models??[]).forEach(e=>t.add(e.name)),(e.cost_per_model??[]).forEach(e=>t.add(e.model)),t.size===1}var z=/(^|\/)(subagents\/|agent-)/;function B(){return(0,j.useSyncExternalStore)(i,()=>E(o().snapshot))}function V(){let e=(0,j.useSyncExternalStore)(i,()=>o().openSessionId),t=B(),r=v(),s={tz:r.resolvedTz,offsetLabel:r.offsetLabel},[c,l]=(0,j.useState)(null),[u,d]=(0,j.useState)(!0),[f,p]=(0,j.useState)(null),m=(0,j.useRef)(null),h=(0,j.useRef)(!1),g=(0,j.useRef)(null);return(0,j.useEffect)(()=>{g.current=e??o().snapshot?.sessions?.rows?.[0]?.session_id??null,h.current=!1},[e]),(0,j.useEffect)(()=>{let e=g.current;if(!e){d(!1),p(`No session available.`),l(null),m.current=null;return}let t=m.current!==e||c==null;m.current=e,t&&(d(!0),p(null),l(null));let n=new AbortController;return fetch(`/api/session/${encodeURIComponent(e)}`,{signal:n.signal}).then(async e=>{if(e.status===404){(t||h.current)&&(d(!1),p(`Session not found (the cache may have rolled forward).`),l(null)),h.current=!0;return}if(!e.ok)throw Error(`HTTP `+e.status);let n=await e.json();h.current=!1,l(n),p(null),d(!1)}).catch(e=>{e.name!==`AbortError`&&(h.current=!1,t&&(p(`Failed to load: `+e.message),d(!1)))}),()=>n.abort()},[e,t]),(0,M.jsx)(N,{title:`Session detail`,accentClass:`accent-orange`,headerExtras:(0,M.jsx)(C,{panel:`sessions`,panelLabel:`Session`,triggerId:`session-modal`,onClick:()=>a(n(`sessions`,`session-modal`))}),children:(0,M.jsxs)(`section`,{className:`modal-sessions`,children:[u?(0,M.jsx)(`div`,{className:`modal-loading`,id:`msess-loading`,children:`Loading session detail…`}):null,f?(0,M.jsx)(`div`,{className:`modal-error`,id:`msess-error`,children:f}):null,!u&&!f&&c?(0,M.jsx)(H,{detail:c,ctx:s}):null]})})}function H({detail:e,ctx:t,identityLabel:n,projectAction:r,privacyNote:i,showCacheRebuilds:a=!0,testId:o}){let s=Array.isArray(e.source_paths)?e.source_paths:[],l=[],u=[];s.forEach(e=>{z.test(e)?u.push(e):l.push(e)});let d=[[`Input`,e.input_tokens,null],[`Output`,e.output_tokens,null],[`Cache creation`,e.cache_creation_tokens,null],[`Cache read`,e.cache_read_tokens,null],[`Cache hit %`,e.cache_hit_pct,`cache-hit`]].filter(e=>e[1]!=null),f=!e.cost_per_model||e.cost_per_model.length===0,p=R(e),m=e.models?.[0]?.name??e.cost_per_model?.[0]?.model??`—`,h=e.cost_per_model?.[0]?.cost_usd??e.cost_total_usd??null;return(0,M.jsxs)(`div`,{className:`modal-content`,id:`msess-content`,"data-testid":o,children:[(0,M.jsx)(`div`,{className:`m-chipstrip`,children:(0,M.jsx)(`span`,{className:`msess-badge`,id:`msess-id`,"aria-label":`Session ID`,children:n??e.session_id??`—`})}),(0,M.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,M.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`v`,id:`msess-cost`,children:e.cost_total_usd==null?`—`:`$`+e.cost_total_usd.toFixed(2)}),(0,M.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,M.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`v`,id:`msess-dur`,children:e.duration_min==null?`—`:e.duration_min+` min`}),(0,M.jsx)(`div`,{className:`lbl`,children:`Duration`})]})]}),(0,M.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#folder`})}),(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`v`,id:`msess-project`,title:e.project_path??``,"aria-label":`Project`,children:r?(0,M.jsx)(`button`,{type:`button`,className:`sd-related-link`,"aria-label":`Open Claude project details: ${r.label}`,onClick:r.onOpen,children:r.label}):e.project_label??e.project_path??`—`}),(0,M.jsx)(`div`,{className:`lbl`,children:`Project`})]})]})]}),(0,M.jsxs)(`div`,{className:`msess-ts`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#calendar`})}),(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`span`,{className:`k`,children:`started`}),(0,M.jsx)(`span`,{className:`v`,id:`msess-started`,children:c.datetimeShort(e.started_utc,t)})]}),(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`span`,{className:`k`,children:`last activity`}),(0,M.jsx)(`span`,{className:`v`,id:`msess-last`,children:c.datetimeShort(e.last_activity_utc,t)})]})]}),(0,M.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Tokens`]}),(0,M.jsx)(`div`,{className:`msess-tok-grid`,id:`msess-tokens`,children:d.map(([e,t,n])=>(0,M.jsxs)(`div`,{className:`msess-tok-tile`+(n?` `+n:``),children:[(0,M.jsx)(`div`,{className:`lbl`,children:e}),(0,M.jsx)(`div`,{className:`n`,children:n===`cache-hit`?t.toFixed(1)+`%`:t.toLocaleString(`en-US`)}),n===`cache-hit`?(0,M.jsx)(`div`,{className:`bar`,children:(0,M.jsx)(`div`,{className:`fill`,style:{width:Math.max(0,Math.min(t,100))+`%`}})}):null]},e))}),a?(0,M.jsx)(I,{sessionId:e.session_id??null},e.session_id??`no-session`):null,i?(0,M.jsx)(`p`,{className:`sd-note sd-privacy-note`,children:i}):null,p?(0,M.jsxs)(`div`,{className:`msess-model-caption`,id:`msess-model-caption`,children:[(0,M.jsx)(`span`,{className:`sw `+x(m),style:_(m),"aria-hidden":`true`}),(0,M.jsx)(`span`,{className:`k`,children:`Model`}),(0,M.jsx)(`span`,{className:`name`,children:m}),(0,M.jsx)(`span`,{className:`dot`,"aria-hidden":`true`,children:`·`}),(0,M.jsx)(`span`,{className:`v`,children:h==null?`—`:`$`+h.toFixed(2)})]}):f?null:(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Cost by model`]}),(0,M.jsx)(L,{rows:(e.cost_per_model||[]).map(e=>({model:e.model,cost_usd:e.cost_usd??0,label:y(e.model)}))})]}),s.length>0?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsxs)(`h3`,{className:`m-sec sec-src`,children:[(0,M.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,M.jsx)(`use`,{href:`/static/icons.svg#file-text`})}),`Source files`]}),(0,M.jsxs)(`div`,{className:`msess-src`,id:`msess-src`,children:[(0,M.jsxs)(`div`,{className:`src-head`,children:[(0,M.jsxs)(`span`,{className:`count-pill`,children:[s.length,` file`,s.length===1?``:`s`]}),(0,M.jsxs)(`span`,{className:`sub`,children:[l.length,` primary`,u.length>0?(0,M.jsxs)(M.Fragment,{children:[` `,(0,M.jsx)(`span`,{className:`dot`,children:`·`}),` `,(0,M.jsxs)(`span`,{className:`subcount`,children:[u.length,` subagent`,u.length===1?``:`s`]})]}):null]})]}),l.length>0?l.map(e=>(0,M.jsx)(`div`,{className:`primary-path`,children:e},e)):u.length>0?(0,M.jsxs)(`div`,{className:`src-empty-primary`,children:[`No primary path resolved · `,u.length,` subagent path`,u.length===1?``:`s`,` below`]}):null,u.length>0?(0,M.jsxs)(`details`,{className:`subagents`,open:l.length===0,children:[(0,M.jsxs)(`summary`,{children:[`Show `,u.length,` subagent path`,u.length===1?``:`s`]}),(0,M.jsx)(`ul`,{className:`paths`,children:u.map(e=>(0,M.jsx)(`li`,{children:e},e))})]}):null]})]}):null]})}function U(e,t){let n=m(),r=v();return h(S(e,t),{tz:r.resolvedTz,offsetLabel:r.offsetLabel},{clampEndTo:n?.generated_at})}function W({projectKey:e,windowWeeks:t,detail:n}){let{data:r,loading:i,error:o}=n,s=r!=null&&(r.key!==e||r.window_weeks!==t);return i&&!r||s?(0,M.jsx)(`div`,{className:`panel-empty`,children:`Loading…`}):o&&!r?(0,M.jsx)(`div`,{className:`panel-empty`,children:o}):r?(0,M.jsx)(G,{data:{...r,label:r.key,sessions:r.sessions.map(e=>({...e,key:e.session_id}))},onOpenSession:e=>a({type:`OPEN_MODAL`,kind:`session`,sessionId:e}),onShowInSessions:()=>{a({type:`SET_FILTER`,text:r.key}),a({type:`CLOSE_MODAL`})}}):null}function G({data:e,onOpenSession:t,onShowInSessions:n,testId:r=`projects-drill`,sessionTestIdPrefix:i=`drill-session`,showInSessionsTestId:a=`drill-show-in-sessions`}){let o=v(),s={tz:o.resolvedTz,offsetLabel:o.offsetLabel},l=Math.max(0,e.sessions_total-e.sessions.length),u=U(e.window_start_at,e.window_end_at),d=(e.window_intervals??[]).reduce((e,t,n,r)=>n>0&&r[n-1].end_at<t.start_at?e+1:e,0);return(0,M.jsxs)(`div`,{className:`projects-drill`,"data-testid":r,"aria-live":`polite`,children:[(0,M.jsx)(`div`,{className:`projects-drill-head`,children:(0,M.jsxs)(`span`,{className:`title`,children:[`▾ `,e.label,` · `,e.sessions_total,` session`,e.sessions_total===1?``:`s`,` · `,c.usd2(e.window_cost_usd),u==null?` (${e.window_weeks} ${e.window_weeks===1?`cycle`:`cycles`})`:` · ${e.window_weeks} ${e.window_weeks===1?`cycle`:`cycles`} · ${u}`,d>0?` · ${d} reset gap${d===1?``:`s`}`:``]})}),(0,M.jsxs)(`div`,{className:`projects-drill-grid`,children:[(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`section-label`,children:`Models (this project)`}),e.models.length===0?(0,M.jsx)(`div`,{className:`muted`,children:`No model data for this window.`}):(0,M.jsx)(L,{rows:e.models.map(e=>({model:e.model,cost_usd:e.cost_usd,label:y(e.model)}))})]}),(0,M.jsxs)(`div`,{children:[(0,M.jsx)(`div`,{className:`section-label`,children:`Recent sessions →`}),e.sessions.length===0?(0,M.jsx)(`div`,{className:`muted`,children:`No sessions for this window.`}):e.sessions.map((e,n)=>(0,M.jsxs)(`button`,{"data-testid":`${i}-${n}`,className:`drill-session-row`,onClick:()=>t(e.key),children:[(0,M.jsx)(`span`,{className:`started`,children:c.datetimeShort(e.last_activity_at,s)}),(0,M.jsx)(`span`,{className:`chip ${x(e.primary_model)}`,style:_(e.primary_model),children:e.primary_model}),(0,M.jsx)(`span`,{className:`cost ${g(e.cost_usd)}`,children:c.usd2(e.cost_usd)})]},e.key)),(0,M.jsxs)(`div`,{className:`drill-session-footer`,children:[l>0&&(0,M.jsxs)(`span`,{className:`muted`,children:[`+`,l,` more`]}),(0,M.jsx)(`button`,{type:`button`,"data-testid":a,className:`drill-show-in-sessions`,onClick:n,children:`Show in Sessions →`})]})]})]})]})}export{L as a,V as i,W as n,P as o,H as r,N as s,G as t};
@@ -0,0 +1 @@
1
+ import{F as e,Ft as t,Rt as n,a as r,b as i,c as a,f as o,it as s}from"./useKeymap-CW7Up0Ay.js";import{Ft as c,M as l,at as u,bt as d,it as f,lt as p}from"./index-DdU62sov.js";import{N as m}from"./outlineNavigation-BOCLcRa6.js";import{a as h,o as g,r as _,s as v,t as y}from"./ProjectsDrillPanel-DAv39uSo.js";var b=n(t(),1);function x(e,t,n,r={}){let[i,a]=(0,b.useState)(null),[o,s]=(0,b.useState)(null),[l,u]=(0,b.useState)(!1),d=m(c()),f=(0,b.useRef)(0),p=(0,b.useRef)(null),h=(0,b.useRef)(!1),g=(0,b.useRef)(0);return(0,b.useEffect)(()=>{if(!n){a(null),s(null),u(!1),f.current=0,p.current=null,h.current=!1,g.current+=1;return}let o=t===`project`?r.windowWeeks:void 0,c=r.account??void 0,l=`${e}/${t}/${n}/${o??``}/${c??``}`,d=p.current!==l,m=d||i==null;if(m&&h.current&&!d)return;m&&(u(!0),s(null)),d&&(f.current=0),p.current=l,h.current=!0;let _=++g.current,v=new URLSearchParams;o!=null&&v.set(`weeks`,String(o)),c!=null&&c!==``&&v.set(`account`,c);let y=v.toString()?`?${v.toString()}`:``,b=`/api/source/${e}/${t}/${encodeURIComponent(n)}${y}`;fetch(b).then(async e=>{if(g.current!==_)return;if(e.status===404){f.current+=1,f.current>=2?(a(null),s({kind:`not-found`,code:`source_resource_not_found`}),u(!1)):m&&(s({kind:`not-found`,code:`source_resource_not_found`}),u(!1));return}if(e.status===400){m&&(s({kind:`capability`,code:`source_capability_unavailable`}),u(!1));return}if(!e.ok){m&&(s({kind:`network`}),u(!1));return}f.current=0;let t=await e.json();g.current===_&&(a(t.data),s(null),u(!1))}).catch(()=>{g.current===_&&m&&(s({kind:`network`}),u(!1))}).finally(()=>{g.current===_&&(h.current=!1)})},[e,t,n,r.windowWeeks,r.account,d]),{data:i,error:o,loading:l}}var S=r();function C(){let t=(0,b.useSyncExternalStore)(i,()=>o().openSourceDetail),n=(0,b.useSyncExternalStore)(i,()=>o().openSourceDetailSelection??o().activeSource),r=(0,b.useSyncExternalStore)(i,()=>o().prefs.projectsWindowWeeks),s=c(),l=t?.source??`codex`,u=(0,b.useSyncExternalStore)(i,()=>o().accountFocus),d=t?.resource===`block`?t.accountKey??e(s,n,l,u):null,f=x(t?.source??`codex`,t?.resource??`session`,t?.key??null,{windowWeeks:t?.resource===`project`?r:void 0,account:d}),m=(0,b.useCallback)(()=>a({type:`CLOSE_SOURCE_DETAIL`}),[]);if(t==null)return null;let h;f.loading&&f.data==null?h=(0,S.jsx)(`p`,{className:`sd-loading`,children:`Loading…`}):f.error?h=(0,S.jsx)(`p`,{className:`sd-error`,"data-testid":`source-detail-error`,children:f.error.kind===`not-found`?`This item is no longer available.`:f.error.kind===`capability`?`This detail is unavailable for this source.`:`Couldn't load this detail — try again.`}):f.data&&(h=(0,S.jsx)(w,{data:f.data}));let g=t.resource===`session`?`sessions`:`${t.resource}s`,_=`${t.resource[0].toUpperCase()}${t.resource.slice(1)}`;return(0,S.jsx)(v,{title:t.resource===`session`?`Session detail`:t.resource===`project`?`Project detail`:`Block detail`,accentClass:t.resource===`block`?`accent-cyan`:`accent-orange`,onClose:m,focusLayer:`source-detail`,rootId:`source-detail-root`,titleId:`source-detail-title`,bodyId:`source-detail-body`,rootTestId:`source-detail-modal`,cardClassName:`source-detail-card`,dataSource:t.source,headerExtras:(0,S.jsx)(p,{panel:g,panelLabel:_,triggerId:`source-detail-share`,onClick:()=>a({type:`OPEN_SHARE`,panel:g,triggerId:`source-detail-share`,source:n})}),children:h},`${t.source}:${t.resource}:${t.key}`)}function w({data:e}){switch(e.detail_kind){case`claude_session`:return(0,S.jsx)(T,{d:e});case`claude_project`:return(0,S.jsx)(E,{d:e});case`claude_block`:return(0,S.jsx)(D,{d:e});case`codex_session`:return(0,S.jsx)(j,{d:e});case`codex_project`:return(0,S.jsx)(M,{d:e});case`codex_block`:return(0,S.jsx)(N,{d:e})}}function T({d:e}){let t=d(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel};return(0,S.jsx)(_,{detail:{session_id:null,started_utc:e.started_utc,last_activity_utc:e.last_activity_utc,duration_min:e.duration_min,cost_total_usd:e.cost_total_usd,project_label:e.project_label,project_path:null,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cache_creation_tokens:e.cache_creation_tokens,cache_read_tokens:e.cache_read_tokens,cache_hit_pct:e.cache_hit_pct,models:e.models,cost_per_model:e.cost_per_model,source_paths:[]},ctx:n,identityLabel:e.label,projectAction:e.project_key&&e.project_label?{label:e.project_label,onOpen:()=>a({type:`OPEN_SOURCE_DETAIL`,source:`claude`,resource:`project`,key:e.project_key})}:void 0,privacyNote:e.privacy_note,showCacheRebuilds:!1,testId:`claude-session-detail`})}function E({d:e}){return(0,S.jsx)(`div`,{className:`sd-claude-project`,"data-testid":`claude-project-detail`,children:(0,S.jsx)(y,{data:e,testId:`qualified-project-drill`,sessionTestIdPrefix:`qualified-project-session`,showInSessionsTestId:`qualified-project-show-in-sessions`,onOpenSession:e=>a({type:`OPEN_SOURCE_DETAIL`,source:`claude`,resource:`session`,key:e}),onShowInSessions:()=>{a({type:`SET_FILTER`,text:e.label}),a({type:`CLOSE_SOURCE_DETAIL`})}})})}function D({d:e}){return(0,S.jsx)(`div`,{className:`sd-claude-block`,children:(0,S.jsxs)(`p`,{children:[s.usd2(e.cost_usd),` · `,s.tokens(e.total_tokens),` tokens · `,e.is_active?`active`:`complete`]})})}function O({items:e,initial:t,noun:n,empty:r,rowTestId:i,itemKey:a,renderItem:o}){let[s,c]=(0,b.useState)(!1);if(e.length===0)return(0,S.jsx)(`p`,{className:`sd-empty-note`,children:r});let l=s?e:e.slice(0,t),u=e.length-Math.min(e.length,t);return(0,S.jsxs)(`div`,{className:`sd-bounded-collection${s?` is-expanded`:``}`,children:[(0,S.jsx)(`ul`,{className:`sd-collection-list`,children:l.map((e,t)=>(0,S.jsx)(`li`,{"data-testid":i,children:o(e,t)},a(e,t)))}),u>0?(0,S.jsx)(`button`,{type:`button`,className:`sd-collection-toggle`,"aria-expanded":s,"aria-label":s?`Show first ${t} ${n}`:`Show all ${e.length} ${n}`,onClick:()=>c(e=>!e),children:s?`Show less`:`+${u} more`}):null]})}function k({totals:e}){let t=e.input_tokens>0?e.cached_input_tokens/e.input_tokens*100:null;return(0,S.jsx)(`div`,{className:`msess-tok-grid`,children:[[`Input`,e.input_tokens,!1],[`Output`,e.output_tokens,!1],[`Cached input`,e.cached_input_tokens,!1],[`Reasoning`,e.reasoning_output_tokens,!1],[`Reuse %`,t,!0]].map(([e,t,n])=>(0,S.jsxs)(`div`,{className:`msess-tok-tile${n?` cache-hit`:``}`,children:[(0,S.jsx)(`div`,{className:`lbl`,children:e}),(0,S.jsx)(`div`,{className:`n`,children:t===null?`—`:n?`${t.toFixed(1)}%`:t.toLocaleString(`en-US`)}),n&&t!==null?(0,S.jsx)(`div`,{className:`bar`,children:(0,S.jsx)(`div`,{className:`fill`,style:{width:`${Math.max(0,Math.min(100,t))}%`}})}):null]},e))})}function A({rows:e,rowTestId:t,initial:n=6}){return(0,S.jsx)(O,{items:e.filter(e=>e.modelName?.trim()),initial:n,noun:`models`,empty:`No model breakdown is available.`,rowTestId:t,itemKey:(e,t)=>`${e.modelName}:${t}`,renderItem:e=>(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`span`,{className:`sd-collection-primary`,children:[(0,S.jsx)(`span`,{className:`sw ${f(e.modelName)}`,style:u(e.modelName),"aria-hidden":`true`}),e.modelName]}),(0,S.jsx)(`span`,{children:s.usd2(e.cost??null)})]})})}function j({d:e}){let t=d(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=e.input_tokens>0?e.cached_input_tokens/e.input_tokens*100:null,i=e.label?.trim()||`Untitled session`,a=e.model_breakdowns.flatMap(e=>{let t=e.modelName?.trim();return t?[{model:t,cost_usd:e.cost??0,label:t.replace(/^gpt-/i,``)}]:[]}),o=a.length===1;return(0,S.jsxs)(`div`,{className:`sd-codex-session modal-content`,"data-testid":`codex-session-detail`,children:[e.metadata_availability===`partial`?(0,S.jsx)(`p`,{className:`sd-note`,children:e.metadata_reason}):null,(0,S.jsxs)(`div`,{className:`m-chipstrip sd-session-chipstrip`,children:[(0,S.jsx)(`span`,{className:`msess-badge sd-prompt-clamp`,"aria-label":`Session prompt`,title:i,children:i}),(0,S.jsx)(`span`,{className:`m-pill ${g(`codex`)}`,children:`Codex`})]}),i.length>96?(0,S.jsxs)(`details`,{className:`sd-prompt-disclosure`,children:[(0,S.jsx)(`summary`,{children:`Show full prompt`}),(0,S.jsx)(`div`,{className:`sd-prompt-full`,tabIndex:0,children:i})]}):null,(0,S.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,S.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:s.usd2(e.cost_usd)}),(0,S.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,S.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:e.duration_min==null?`—`:`${e.duration_min} min`}),(0,S.jsx)(`div`,{className:`lbl`,children:`Duration`})]})]}),(0,S.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#folder`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,title:e.project||``,"aria-label":`Project`,children:e.project||`—`}),(0,S.jsx)(`div`,{className:`lbl`,children:`Project`})]})]})]}),(0,S.jsxs)(`div`,{className:`msess-ts`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#calendar`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`k`,children:`started`}),(0,S.jsx)(`span`,{className:`v`,children:s.datetimeShort(e.started_at??null,n)})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`k`,children:`last activity`}),(0,S.jsx)(`span`,{className:`v`,children:s.datetimeShort(e.last_activity,n)})]})]}),(0,S.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Tokens`]}),(0,S.jsx)(k,{totals:e}),(0,S.jsxs)(`h3`,{className:`m-sec sec-rebuild`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#refresh-cw`})}),`Cache reuse`]}),(0,S.jsx)(`div`,{className:`msess-rebuild-saved`,children:r==null?`No input tokens recorded`:`${r.toFixed(1)}% of input reused from cache ✓`}),o?(0,S.jsxs)(`div`,{className:`msess-model-caption`,children:[(0,S.jsx)(`span`,{className:`sw ${f(a[0].model)}`,style:u(a[0].model),"aria-hidden":`true`}),(0,S.jsx)(`span`,{className:`k`,children:`Model`}),(0,S.jsx)(`span`,{className:`name`,children:a[0].model}),(0,S.jsx)(`span`,{className:`dot`,"aria-hidden":`true`,children:`·`}),(0,S.jsx)(`span`,{className:`v`,children:s.usd2(a[0].cost_usd)})]}):a.length>0?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Cost by model`]}),(0,S.jsx)(`div`,{className:`sd-model-cost-bars`,children:(0,S.jsx)(h,{rows:a})})]}):null,(0,S.jsxs)(`div`,{className:`sd-total-tokens`,children:[`Total tokens `,(0,S.jsx)(`strong`,{children:s.tokens(e.total_tokens)})]})]})}function M({d:e}){let t=d(),n=c(),r={tz:t.resolvedTz,offsetLabel:t.offsetLabel},i=l({startAt:e.range_start,endAt:e.range_end},r,{clampEndTo:n?.generated_at}),a=e.models.map(e=>({modelName:e.model,cost:e.cost_usd,inputTokens:e.input_tokens,cachedInputTokens:e.cached_input_tokens,outputTokens:e.output_tokens,reasoningOutputTokens:e.reasoning_output_tokens,totalTokens:e.total_tokens}));return(0,S.jsxs)(`div`,{className:`sd-codex-project modal-content`,"data-testid":`codex-project-detail`,children:[e.metadata_availability===`partial`?(0,S.jsx)(`p`,{className:`sd-note`,children:e.metadata_reason}):null,(0,S.jsxs)(`div`,{className:`m-chipstrip`,children:[(0,S.jsx)(`span`,{className:`msess-badge sd-project-label`,title:e.label||`Codex project`,children:e.label||`Codex project`}),(0,S.jsx)(`span`,{className:`m-pill ${g(`codex`)}`,children:`Codex`})]}),i&&(0,S.jsxs)(`p`,{className:`sd-window-note`,"data-testid":`codex-project-window`,children:[`Totals cover `,i,` — the retained Codex window this detail reads, which is wider than the shared range a ranked row is priced over.`]}),(0,S.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,S.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:s.usd2(e.cost_usd)}),(0,S.jsx)(`div`,{className:`lbl`,children:`Total cost`})]})]}),(0,S.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#clock`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:e.session_count}),(0,S.jsx)(`div`,{className:`lbl`,children:`Sessions`})]})]}),(0,S.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#hash`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:s.tokens(e.total_tokens)}),(0,S.jsx)(`div`,{className:`lbl`,children:`Total tokens`})]})]})]}),(0,S.jsxs)(`div`,{className:`msess-ts sd-project-ts`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#calendar`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`k`,children:`first seen`}),(0,S.jsx)(`span`,{className:`v`,children:s.datetimeShort(e.first_seen,r)})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`k`,children:`last activity`}),(0,S.jsx)(`span`,{className:`v`,children:s.datetimeShort(e.last_seen,r)})]}),(0,S.jsxs)(`div`,{"data-testid":`codex-project-range`,children:[(0,S.jsx)(`span`,{className:`k`,children:`range`}),(0,S.jsx)(`span`,{className:`v`,children:i??`—`})]})]}),(0,S.jsxs)(`h3`,{className:`m-sec sec-tok`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#hash`})}),`Native token totals`]}),(0,S.jsx)(k,{totals:e}),(0,S.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Models`]}),(0,S.jsx)(A,{rows:a,rowTestId:`codex-project-model-row`}),(0,S.jsxs)(`h3`,{className:`m-sec sec-src`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#clock`})}),`Recent sessions`]}),(0,S.jsx)(O,{items:e.sessions,initial:6,noun:`sessions`,empty:`No retained sessions are available.`,rowTestId:`codex-project-session-row`,itemKey:(e,t)=>`${e.label}:${e.last_activity}:${t}`,renderItem:e=>(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`span`,{className:`sd-collection-primary sd-session-summary`,children:[(0,S.jsx)(`span`,{children:e.label}),(0,S.jsx)(`span`,{className:`sd-collection-meta`,children:s.datetimeShort(e.last_activity,r)})]}),(0,S.jsxs)(`span`,{children:[s.usd2(e.cost_usd),` · `,s.tokens(e.total_tokens)]})]})})]})}function N({d:e}){let t=d(),n={tz:t.resolvedTz,offsetLabel:t.offsetLabel},r=e.model_breakdowns??[],i=e.observations??[],a=e.milestones??[],o=e.freshness??`unavailable`,c=e.forecast??null;return(0,S.jsxs)(`div`,{className:`sd-codex-block modal-content`,"data-testid":`codex-block-detail`,children:[e.metadata_availability===`partial`?(0,S.jsx)(`p`,{className:`sd-note`,children:e.metadata_reason}):null,(0,S.jsxs)(`div`,{className:`m-chipstrip`,children:[(0,S.jsx)(`span`,{className:`msess-badge sd-project-label`,title:e.label,children:e.label}),(0,S.jsx)(`span`,{className:`m-pill ${g(`codex`)}`,children:`Codex`}),(0,S.jsx)(`span`,{className:`m-pill ${e.is_active?`accent-green`:`m-unavailable`}`,children:e.is_active?`Active`:`Complete`}),(0,S.jsx)(`span`,{className:`m-pill accent-cyan`,children:o})]}),(0,S.jsxs)(`div`,{className:`m-hero cols-3`,children:[(0,S.jsxs)(`div`,{className:`m-kv kv-dur`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#activity`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:s.pct0(e.current_percent)}),(0,S.jsx)(`div`,{className:`lbl`,children:`Current usage`})]})]}),(0,S.jsxs)(`div`,{className:`m-kv kv-cost`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#dollar`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:s.usd2(e.cost_usd??null)}),(0,S.jsx)(`div`,{className:`lbl`,children:`Retained cost`})]})]}),(0,S.jsxs)(`div`,{className:`m-kv kv-proj`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#trending-up`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`v`,children:s.pct1(c?.projected_percent??null)}),(0,S.jsx)(`div`,{className:`lbl`,children:`Projected at reset`}),(0,S.jsx)(`div`,{className:`sub`,children:c?.status??`unavailable`})]})]})]}),(0,S.jsxs)(`div`,{className:`msess-ts sd-block-ts`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#calendar`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`k`,children:`window`}),(0,S.jsxs)(`span`,{className:`v`,children:[s.datetimeShort(e.start_at??null,n),` → `,s.datetimeShort(e.end_at??e.resets_at,n)]})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`k`,children:`resets`}),(0,S.jsx)(`span`,{className:`v`,children:s.datetimeShort(e.resets_at,n)})]})]}),(0,S.jsxs)(`h3`,{className:`m-sec sec-costm`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#pie-chart`})}),`Models`]}),(0,S.jsx)(A,{rows:r,rowTestId:`codex-block-model-row`}),(0,S.jsxs)(`h3`,{className:`m-sec sec-prog`,children:[(0,S.jsx)(`svg`,{className:`icon`,"aria-hidden":`true`,children:(0,S.jsx)(`use`,{href:`/static/icons.svg#activity`})}),`Quota progression`]}),(0,S.jsxs)(`p`,{className:`sd-progression-summary`,children:[i.length,` observations · `,a.length,` milestones`]}),(0,S.jsx)(`h4`,{className:`sd-subsection-title`,children:`Observations`}),(0,S.jsx)(O,{items:i,initial:8,noun:`observations`,empty:`No retained quota observations are available.`,rowTestId:`codex-block-observation-row`,itemKey:(e,t)=>`${e.captured_at}:${t}`,renderItem:e=>(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`span`,{className:`sd-collection-primary sd-observation-time`,children:s.datetimeShort(e.captured_at,n)}),(0,S.jsx)(`span`,{className:`sd-observation-value`,children:s.pct1(e.used_percent)}),(0,S.jsx)(`span`,{className:`sd-observation-track`,"aria-hidden":`true`,children:(0,S.jsx)(`span`,{style:{width:`${Math.max(0,Math.min(100,e.used_percent))}%`}})})]})}),(0,S.jsx)(`h4`,{className:`sd-subsection-title`,children:`Milestones`}),(0,S.jsx)(O,{items:a,initial:8,noun:`milestones`,empty:`No quota milestones were crossed in this window.`,rowTestId:`codex-block-milestone-row`,itemKey:(e,t)=>`${e.percent}:${e.captured_at}:${t}`,renderItem:e=>(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`span`,{className:`sd-collection-primary`,children:[`Crossed `,s.pct0(e.percent)]}),(0,S.jsx)(`span`,{children:s.datetimeShort(e.captured_at,n)})]})})]})}export{C as SourceDetailModal};
@@ -1,7 +1,7 @@
1
- import{It as e,Nt as t,a as n,c as r,f as i,t as a,y as o}from"./useKeymap-ffqsS5G0.js";import{At as s,Mt as c,jt as l,o as u,pt as d}from"./index-CIWsbux3.js";var f=e(t(),1),p=n(),m={brew:`Homebrew`,npm:`npm`,unknown:`unknown`};function h(){let e=(0,f.useSyncExternalStore)(o,()=>i().update).state;if(!e)return null;let t=e.method,n=m[t]??t,r=e.update_command??``,a=t===`unknown`||!r,s=e.configured_channel===`beta`;return(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-kv`,children:[(0,p.jsx)(`span`,{className:`k`,children:`Current`}),(0,p.jsx)(`span`,{className:`v`,children:e.current_version??`—`}),(0,p.jsx)(`span`,{className:`k`,children:`Latest`}),(0,p.jsxs)(`span`,{className:`v`,children:[e.latest_version??`—`,s?(0,p.jsx)(`span`,{className:`update-channel-tag`,children:` (beta)`}):null]}),(0,p.jsx)(`span`,{className:`k`,children:`Method`}),(0,p.jsxs)(`span`,{className:`v`,children:[n,(0,p.jsx)(`span`,{className:`muted`,children:` (auto-detected)`})]})]}),a?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-row-label`,children:`Update manually`}),(0,p.jsxs)(`p`,{className:`update-manual-note`,children:[`Couldn't auto-detect this install's package manager. See `,(0,p.jsx)(`a`,{href:`https://github.com/omrikais/cctally#updating`,target:`_blank`,rel:`noopener noreferrer`,children:`Updating`}),` for the manual recipe.`]})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-row-label`,children:`Will run`}),(0,p.jsx)(`code`,{className:`update-cmd`,children:r})]}),e.release_notes_url?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-row-label`,children:`Release notes`}),(0,p.jsx)(`div`,{className:`update-link`,children:(0,p.jsxs)(`a`,{href:e.release_notes_url,target:`_blank`,rel:`noopener noreferrer`,children:[`↗ `,e.release_notes_url.replace(/^https?:\/\//,``)]})})]}):null,e.prerelease_note?(0,p.jsx)(`div`,{className:`update-prerelease-note`,role:`note`,"aria-label":`Prerelease note`,children:e.prerelease_note}):null,(0,p.jsxs)(`div`,{className:`update-actions`,children:[(0,p.jsx)(`button`,{type:`button`,className:`update-btn update-btn-primary`,disabled:a,onClick:()=>c.start(),children:`Update now`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,disabled:!e.latest_version,onClick:()=>c.skip(e.latest_version),children:`Skip this version`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>c.remind(7),children:`Remind in 7 days`})]})]})}function g({events:e,maxLines:t=500}){let n=(0,f.useRef)(null),r=(0,f.useRef)(!0),i=e.filter(e=>e.type===`stdout`||e.type===`stderr`||e.type===`step`||e.type===`exit`),a=i.slice(-t),o=i.length-a.length;(0,f.useEffect)(()=>{let e=n.current;e&&r.current&&(e.scrollTop=e.scrollHeight)},[e.length]);function s(e){let t=e.currentTarget;r.current=t.scrollHeight-t.scrollTop-t.clientHeight<8}return a.length===0?(0,p.jsx)(`pre`,{className:`update-stream`,ref:n,onScroll:s,"aria-live":`polite`,"aria-label":`Update output`,children:(0,p.jsx)(`span`,{className:`update-stream-empty`,children:`Waiting for output…`})}):(0,p.jsxs)(`pre`,{className:`update-stream`,ref:n,onScroll:s,"aria-live":`polite`,"aria-label":`Update output`,children:[o>0?(0,p.jsxs)(`span`,{className:`update-stream-trunc`,children:[`(… `,o,` earlier line`,o===1?``:`s`,` truncated)`,`
1
+ import{Ft as e,Rt as t,a as n,b as r,c as i,f as a,t as o}from"./useKeymap-CW7Up0Ay.js";import{Mt as s,Nt as c,Pt as l,o as u,ut as d}from"./index-DdU62sov.js";var f=t(e(),1),p=n(),m={brew:`Homebrew`,npm:`npm`,unknown:`unknown`};function h(){let e=(0,f.useSyncExternalStore)(r,()=>a().update).state;if(!e)return null;let t=e.method,n=m[t]??t,i=e.update_command??``,o=t===`unknown`||!i,s=e.configured_channel===`beta`;return(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-kv`,children:[(0,p.jsx)(`span`,{className:`k`,children:`Current`}),(0,p.jsx)(`span`,{className:`v`,children:e.current_version??`—`}),(0,p.jsx)(`span`,{className:`k`,children:`Latest`}),(0,p.jsxs)(`span`,{className:`v`,children:[e.latest_version??`—`,s?(0,p.jsx)(`span`,{className:`update-channel-tag`,children:` (beta)`}):null]}),(0,p.jsx)(`span`,{className:`k`,children:`Method`}),(0,p.jsxs)(`span`,{className:`v`,children:[n,(0,p.jsx)(`span`,{className:`muted`,children:` (auto-detected)`})]})]}),o?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-row-label`,children:`Update manually`}),(0,p.jsxs)(`p`,{className:`update-manual-note`,children:[`Couldn't auto-detect this install's package manager. See `,(0,p.jsx)(`a`,{href:`https://github.com/omrikais/cctally#updating`,target:`_blank`,rel:`noopener noreferrer`,children:`Updating`}),` for the manual recipe.`]})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-row-label`,children:`Will run`}),(0,p.jsx)(`code`,{className:`update-cmd`,children:i})]}),e.release_notes_url?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-row-label`,children:`Release notes`}),(0,p.jsx)(`div`,{className:`update-link`,children:(0,p.jsxs)(`a`,{href:e.release_notes_url,target:`_blank`,rel:`noopener noreferrer`,children:[`↗ `,e.release_notes_url.replace(/^https?:\/\//,``)]})})]}):null,e.prerelease_note?(0,p.jsx)(`div`,{className:`update-prerelease-note`,role:`note`,"aria-label":`Prerelease note`,children:e.prerelease_note}):null,(0,p.jsxs)(`div`,{className:`update-actions`,children:[(0,p.jsx)(`button`,{type:`button`,className:`update-btn update-btn-primary`,disabled:o,onClick:()=>l.start(),children:`Update now`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,disabled:!e.latest_version,onClick:()=>l.skip(e.latest_version),children:`Skip this version`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>l.remind(7),children:`Remind in 7 days`})]})]})}function g({events:e,maxLines:t=500}){let n=(0,f.useRef)(null),r=(0,f.useRef)(!0),i=e.filter(e=>e.type===`stdout`||e.type===`stderr`||e.type===`step`||e.type===`exit`),a=i.slice(-t),o=i.length-a.length;(0,f.useEffect)(()=>{let e=n.current;e&&r.current&&(e.scrollTop=e.scrollHeight)},[e.length]);function s(e){let t=e.currentTarget;r.current=t.scrollHeight-t.scrollTop-t.clientHeight<8}return a.length===0?(0,p.jsx)(`pre`,{className:`update-stream`,ref:n,onScroll:s,"aria-live":`polite`,"aria-label":`Update output`,children:(0,p.jsx)(`span`,{className:`update-stream-empty`,children:`Waiting for output…`})}):(0,p.jsxs)(`pre`,{className:`update-stream`,ref:n,onScroll:s,"aria-live":`polite`,"aria-label":`Update output`,children:[o>0?(0,p.jsxs)(`span`,{className:`update-stream-trunc`,children:[`(… `,o,` earlier line`,o===1?``:`s`,` truncated)`,`
2
2
  `]}):null,a.map((e,t)=>e.type===`step`?(0,p.jsxs)(`span`,{className:`update-stream-step`,children:[`==> `,e.name??e.step??e.data??``,`
3
3
  `]},t):e.type===`stderr`?(0,p.jsxs)(`span`,{className:`update-stream-line err`,children:[e.data??``,`
4
4
  `]},t):e.type===`exit`?(0,p.jsxs)(`span`,{className:`update-stream-exit`,children:[`(exited rc=${e.rc??`?`})`,`
5
5
  `]},t):(0,p.jsxs)(`span`,{className:`update-stream-line`,children:[e.data??``,`
6
- `]},t))]})}var _=3e3,v=1e3;function y(e){if(e==null)return`0s`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function b(){let e=(0,f.useSyncExternalStore)(o,()=>i().update),t=e.runId,n=e.startedAt,a=e.state?.update_command??``,c=e.state?.latest_version??``,[,l]=(0,f.useState)(0);(0,f.useEffect)(()=>{let e=window.setInterval(()=>l(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);let u=(0,f.useRef)(!1);return(0,f.useEffect)(()=>{if(!t)return;let e=null,n=null,a=null,o=!1;u.current=!0;function c(){a!=null&&(window.clearTimeout(a),a=null),u.current=!1}function l(t,n){c();let i={};try{t instanceof MessageEvent&&typeof t.data==`string`&&(i=JSON.parse(t.data))}catch{}if(r({type:`APPEND_UPDATE_STREAM`,event:{type:n,data:typeof i.data==`string`?i.data:void 0,name:typeof i.name==`string`?i.name:void 0,version:typeof i.version==`string`?i.version:void 0,command:typeof i.command==`string`?i.command:void 0,rc:typeof i.rc==`number`?i.rc:void 0,step:typeof i.step==`string`?i.step:void 0,message:typeof i.message==`string`?i.message:void 0,ts:typeof i.ts==`number`?i.ts:void 0}}),n===`target`)s();else if(n===`exit`){let e=typeof i.rc==`number`?i.rc:-1;e!==0&&r({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:`subprocess exited with rc=${e}`})}else n===`execvp`?r({type:`SET_UPDATE_STATUS`,status:`success`}):n===`error_event`?r({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:typeof i.message==`string`?i.message:`update worker error`}):n===`done`&&(e&&=(e.close(),null))}function d(){n??=window.setInterval(async()=>{if(!o)try{let e=await fetch(`/api/update/status`);if(!e.ok)return;let t=await e.json(),a=t?.current_run_id??null,o=t?.state??{};if(a===null){let e=o?.current_version,t=o?.latest_version,a=i().update;typeof e==`string`&&typeof t==`string`&&e===t?r({type:`SET_UPDATE_STATUS`,status:`success`}):a.status===`running`&&r({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:`update worker exited (stream unavailable)`}),a.stream.length===0&&r({type:`APPEND_UPDATE_STREAM`,event:{type:`stdout`,data:`(SSE stream unavailable; install completed in background — see ~/.local/share/cctally/update.log for full output)`}}),n!=null&&(window.clearInterval(n),n=null)}}catch{}},v)}a=window.setTimeout(()=>{o||u.current&&(u.current=!1,e&&=(e.close(),null),d())},_);try{e=new EventSource(`/api/update/stream/${encodeURIComponent(t)}`),e.addEventListener(`message`,e=>l(e,`stdout`)),[`stdout`,`stderr`,`target`,`step`,`exit`,`execvp`,`error_event`,`done`,`heartbeat`].forEach(t=>{e.addEventListener(t,e=>l(e,t))}),e.onerror=()=>{u.current&&(c(),e&&=(e.close(),null),d())}}catch{c(),d()}return()=>{o=!0,a!=null&&(window.clearTimeout(a),a=null),n!=null&&(window.clearInterval(n),n=null),e&&=(e.close(),null),u.current=!1,s()}},[t]),(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-running-row`,children:[(0,p.jsx)(`span`,{className:`update-spinner`,"aria-hidden":`true`,children:`⟳`}),(0,p.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:a||`updating cctally`}),(0,p.jsxs)(`span`,{className:`update-elapsed`,children:[y(n),` elapsed`]})]}),(0,p.jsx)(g,{events:e.stream}),(0,p.jsxs)(`p`,{className:`update-stream-cap`,children:[`Output streams over SSE · press Esc to hide (install continues to `,c||`latest`,`)`]})]})}var x=1500,S=20;function C(e){if(e==null)return`—`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function w(){let e=(0,f.useSyncExternalStore)(o,()=>i().update),t=e.startedAt,n=e.state?.update_command??``,a=e.state?.latest_version??``,c=(0,f.useRef)(0),[l,u]=(0,f.useState)(!1);return(0,f.useEffect)(()=>{let e=window.setInterval(()=>{if(c.current>=S){window.clearInterval(e),u(!0);return}c.current+=1,s()},x);return()=>window.clearInterval(e)},[]),(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-running-row update-running-row-success`,children:[(0,p.jsx)(`span`,{className:`update-check`,"aria-hidden":`true`,children:`✓`}),(0,p.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:n||`cctally`}),(0,p.jsxs)(`span`,{className:`update-elapsed`,children:[`finished in `,C(t)]})]}),(0,p.jsxs)(`div`,{className:`update-row-label`,children:[`Restarting dashboard on the new code`,a?` (${a})`:``,`…`]}),l?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-running-row`,children:(0,p.jsx)(`span`,{className:`update-success-reconnect`,children:`Still reconnecting — check update.log`})}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>{r({type:`CLOSE_UPDATE_MODAL`}),r({type:`RESET_UPDATE_RUN`})},children:`Close`})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`div`,{className:`update-running-row`,children:[(0,p.jsx)(`span`,{className:`update-spinner`,"aria-hidden":`true`,children:`⟳`}),(0,p.jsx)(`span`,{className:`update-success-reconnect`,children:`reconnecting (this page will refresh in a moment)`})]}),(0,p.jsx)(`p`,{className:`modal-hint`,children:`Press Esc to close`})]})]})}function T(e,t){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`exit`&&typeof n.rc==`number`)return`exited rc=${n.rc}`;if(n.type===`error_event`)return n.message??`worker error`}return t??`unknown failure`}function E(){let e=(0,f.useSyncExternalStore)(o,()=>i().update),[t,n]=(0,f.useState)(`idle`),a=e.state?.update_command??``,s=e.stream.filter(e=>e.type===`stderr`&&e.data).map(e=>e.data).slice(-12),u=T(e.stream,e.errorMessage);function d(){r({type:`RESET_UPDATE_RUN`}),l()}async function m(){if(a)try{await navigator.clipboard.writeText(a),n(`ok`),window.setTimeout(()=>n(`idle`),1500)}catch{n(`err`),window.setTimeout(()=>n(`idle`),1500)}}return(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-running-row update-running-row-failed`,children:[(0,p.jsx)(`span`,{className:`update-x`,"aria-hidden":`true`,children:`✗`}),(0,p.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:a||`cctally update`}),(0,p.jsx)(`span`,{className:`update-elapsed`,children:u})]}),s.length>0?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`div`,{className:`update-row-label`,children:[`stderr (last `,s.length,` line`,s.length===1?``:`s`,`)`]}),(0,p.jsx)(`pre`,{className:`update-stream update-stream-fail`,children:s.map((e,t)=>(0,p.jsxs)(`span`,{className:`update-stream-line err`,children:[e,`
7
- `]},t))})]}):(0,p.jsx)(`p`,{className:`update-manual-note`,children:e.errorMessage??`See ~/.local/share/cctally/update.log for the full failure log.`}),(0,p.jsxs)(`p`,{className:`update-stream-cap`,children:[`Full log: `,(0,p.jsx)(`code`,{children:`~/.local/share/cctally/update.log`})]}),(0,p.jsxs)(`div`,{className:`update-actions`,children:[(0,p.jsx)(`button`,{type:`button`,className:`update-btn update-btn-primary`,onClick:d,children:`Retry`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:m,disabled:!a,children:t===`ok`?`Copied!`:t===`err`?`Copy failed`:`Copy command`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>c.close(),children:`Close`})]})]})}var D={idle:`Update available`,running:`Updating cctally`,success:`Update complete`,failed:`Update failed`},O={idle:`accent-amber`,running:`accent-amber`,success:`accent-green`,failed:`accent-red`};function k(){let e=(0,f.useSyncExternalStore)(o,()=>i().update),t=()=>r({type:`CLOSE_UPDATE_MODAL`});if(a((0,f.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:t,when:()=>i().update.modalOpen}],[])),d(e.modalOpen&&e.state!=null),!e.modalOpen||!e.state)return null;let n=e.status,s=O[n]??`accent-amber`,c=D[n]??`Update`;n===`running`&&e.state.latest_version?c=`Updating cctally → ${e.state.latest_version}`:n===`success`&&e.state.latest_version&&(c=`Update complete → ${e.state.latest_version}`);let l;switch(n){case`running`:l=(0,p.jsx)(b,{});break;case`success`:l=(0,p.jsx)(w,{});break;case`failed`:l=(0,p.jsx)(E,{});break;default:l=(0,p.jsx)(h,{});break}return(0,p.jsxs)(`div`,{id:`update-modal-root`,className:`update-modal-root`,children:[(0,p.jsx)(`div`,{className:`modal-backdrop`,onClick:t}),(0,p.jsxs)(`div`,{className:`modal-card update-modal-card ${s}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`update-modal-title`,children:[(0,p.jsx)(u,{title:c,titleId:`update-modal-title`,onClose:t}),(0,p.jsx)(`div`,{className:`modal-body`,children:l})]})]})}export{k as UpdateModal};
6
+ `]},t))]})}var _=3e3,v=1e3;function y(e){if(e==null)return`0s`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function b(){let e=(0,f.useSyncExternalStore)(r,()=>a().update),t=e.runId,n=e.startedAt,o=e.state?.update_command??``,c=e.state?.latest_version??``,[,l]=(0,f.useState)(0);(0,f.useEffect)(()=>{let e=window.setInterval(()=>l(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);let u=(0,f.useRef)(!1);return(0,f.useEffect)(()=>{if(!t)return;let e=null,n=null,r=null,o=!1;u.current=!0;function c(){r!=null&&(window.clearTimeout(r),r=null),u.current=!1}function l(t,n){c();let r={};try{t instanceof MessageEvent&&typeof t.data==`string`&&(r=JSON.parse(t.data))}catch{}if(i({type:`APPEND_UPDATE_STREAM`,event:{type:n,data:typeof r.data==`string`?r.data:void 0,name:typeof r.name==`string`?r.name:void 0,version:typeof r.version==`string`?r.version:void 0,command:typeof r.command==`string`?r.command:void 0,rc:typeof r.rc==`number`?r.rc:void 0,step:typeof r.step==`string`?r.step:void 0,message:typeof r.message==`string`?r.message:void 0,ts:typeof r.ts==`number`?r.ts:void 0}}),n===`target`)s();else if(n===`exit`){let e=typeof r.rc==`number`?r.rc:-1;e!==0&&i({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:`subprocess exited with rc=${e}`})}else n===`execvp`?i({type:`SET_UPDATE_STATUS`,status:`success`}):n===`error_event`?i({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:typeof r.message==`string`?r.message:`update worker error`}):n===`done`&&(e&&=(e.close(),null))}function d(){n??=window.setInterval(async()=>{if(!o)try{let e=await fetch(`/api/update/status`);if(!e.ok)return;let t=await e.json(),r=t?.current_run_id??null,o=t?.state??{};if(r===null){let e=o?.current_version,t=o?.latest_version,r=a().update;typeof e==`string`&&typeof t==`string`&&e===t?i({type:`SET_UPDATE_STATUS`,status:`success`}):r.status===`running`&&i({type:`SET_UPDATE_STATUS`,status:`failed`,errorMessage:`update worker exited (stream unavailable)`}),r.stream.length===0&&i({type:`APPEND_UPDATE_STREAM`,event:{type:`stdout`,data:`(SSE stream unavailable; install completed in background — see ~/.local/share/cctally/update.log for full output)`}}),n!=null&&(window.clearInterval(n),n=null)}}catch{}},v)}r=window.setTimeout(()=>{o||u.current&&(u.current=!1,e&&=(e.close(),null),d())},_);try{e=new EventSource(`/api/update/stream/${encodeURIComponent(t)}`),e.addEventListener(`message`,e=>l(e,`stdout`)),[`stdout`,`stderr`,`target`,`step`,`exit`,`execvp`,`error_event`,`done`,`heartbeat`].forEach(t=>{e.addEventListener(t,e=>l(e,t))}),e.onerror=()=>{u.current&&(c(),e&&=(e.close(),null),d())}}catch{c(),d()}return()=>{o=!0,r!=null&&(window.clearTimeout(r),r=null),n!=null&&(window.clearInterval(n),n=null),e&&=(e.close(),null),u.current=!1,s()}},[t]),(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-running-row`,children:[(0,p.jsx)(`span`,{className:`update-spinner`,"aria-hidden":`true`,children:`⟳`}),(0,p.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:o||`updating cctally`}),(0,p.jsxs)(`span`,{className:`update-elapsed`,children:[y(n),` elapsed`]})]}),(0,p.jsx)(g,{events:e.stream}),(0,p.jsxs)(`p`,{className:`update-stream-cap`,children:[`Output streams over SSE · press Esc to hide (install continues to `,c||`latest`,`)`]})]})}var x=1500,S=20;function C(e){if(e==null)return`—`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function w(){let e=(0,f.useSyncExternalStore)(r,()=>a().update),t=e.startedAt,n=e.state?.update_command??``,o=e.state?.latest_version??``,c=(0,f.useRef)(0),[l,u]=(0,f.useState)(!1);return(0,f.useEffect)(()=>{let e=window.setInterval(()=>{if(c.current>=S){window.clearInterval(e),u(!0);return}c.current+=1,s()},x);return()=>window.clearInterval(e)},[]),(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-running-row update-running-row-success`,children:[(0,p.jsx)(`span`,{className:`update-check`,"aria-hidden":`true`,children:`✓`}),(0,p.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:n||`cctally`}),(0,p.jsxs)(`span`,{className:`update-elapsed`,children:[`finished in `,C(t)]})]}),(0,p.jsxs)(`div`,{className:`update-row-label`,children:[`Restarting dashboard on the new code`,o?` (${o})`:``,`…`]}),l?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(`div`,{className:`update-running-row`,children:(0,p.jsx)(`span`,{className:`update-success-reconnect`,children:`Still reconnecting — check update.log`})}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>{i({type:`CLOSE_UPDATE_MODAL`}),i({type:`RESET_UPDATE_RUN`})},children:`Close`})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`div`,{className:`update-running-row`,children:[(0,p.jsx)(`span`,{className:`update-spinner`,"aria-hidden":`true`,children:`⟳`}),(0,p.jsx)(`span`,{className:`update-success-reconnect`,children:`reconnecting (this page will refresh in a moment)`})]}),(0,p.jsx)(`p`,{className:`modal-hint`,children:`Press Esc to close`})]})]})}function T(e,t){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`exit`&&typeof n.rc==`number`)return`exited rc=${n.rc}`;if(n.type===`error_event`)return n.message??`worker error`}return t??`unknown failure`}function E(){let e=(0,f.useSyncExternalStore)(r,()=>a().update),[t,n]=(0,f.useState)(`idle`),o=e.state?.update_command??``,s=e.stream.filter(e=>e.type===`stderr`&&e.data).map(e=>e.data).slice(-12),u=T(e.stream,e.errorMessage);function d(){i({type:`RESET_UPDATE_RUN`}),c()}async function m(){if(o)try{await navigator.clipboard.writeText(o),n(`ok`),window.setTimeout(()=>n(`idle`),1500)}catch{n(`err`),window.setTimeout(()=>n(`idle`),1500)}}return(0,p.jsxs)(`div`,{className:`update-modal-body`,children:[(0,p.jsxs)(`div`,{className:`update-running-row update-running-row-failed`,children:[(0,p.jsx)(`span`,{className:`update-x`,"aria-hidden":`true`,children:`✗`}),(0,p.jsx)(`code`,{className:`update-cmd update-cmd-inline`,children:o||`cctally update`}),(0,p.jsx)(`span`,{className:`update-elapsed`,children:u})]}),s.length>0?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(`div`,{className:`update-row-label`,children:[`stderr (last `,s.length,` line`,s.length===1?``:`s`,`)`]}),(0,p.jsx)(`pre`,{className:`update-stream update-stream-fail`,children:s.map((e,t)=>(0,p.jsxs)(`span`,{className:`update-stream-line err`,children:[e,`
7
+ `]},t))})]}):(0,p.jsx)(`p`,{className:`update-manual-note`,children:e.errorMessage??`See ~/.local/share/cctally/update.log for the full failure log.`}),(0,p.jsxs)(`p`,{className:`update-stream-cap`,children:[`Full log: `,(0,p.jsx)(`code`,{children:`~/.local/share/cctally/update.log`})]}),(0,p.jsxs)(`div`,{className:`update-actions`,children:[(0,p.jsx)(`button`,{type:`button`,className:`update-btn update-btn-primary`,onClick:d,children:`Retry`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:m,disabled:!o,children:t===`ok`?`Copied!`:t===`err`?`Copy failed`:`Copy command`}),(0,p.jsx)(`button`,{type:`button`,className:`update-btn`,onClick:()=>l.close(),children:`Close`})]})]})}var D={idle:`Update available`,running:`Updating cctally`,success:`Update complete`,failed:`Update failed`},O={idle:`accent-amber`,running:`accent-amber`,success:`accent-green`,failed:`accent-red`};function k(){let e=(0,f.useSyncExternalStore)(r,()=>a().update),t=()=>i({type:`CLOSE_UPDATE_MODAL`});if(o((0,f.useMemo)(()=>[{key:`Escape`,scope:`modal`,action:t,when:()=>a().update.modalOpen}],[])),d(e.modalOpen&&e.state!=null),!e.modalOpen||!e.state)return null;let n=e.status,s=O[n]??`accent-amber`,c=D[n]??`Update`;n===`running`&&e.state.latest_version?c=`Updating cctally → ${e.state.latest_version}`:n===`success`&&e.state.latest_version&&(c=`Update complete → ${e.state.latest_version}`);let l;switch(n){case`running`:l=(0,p.jsx)(b,{});break;case`success`:l=(0,p.jsx)(w,{});break;case`failed`:l=(0,p.jsx)(E,{});break;default:l=(0,p.jsx)(h,{});break}return(0,p.jsxs)(`div`,{id:`update-modal-root`,className:`update-modal-root`,children:[(0,p.jsx)(`div`,{className:`modal-backdrop`,onClick:t}),(0,p.jsxs)(`div`,{className:`modal-card update-modal-card ${s}`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`update-modal-title`,children:[(0,p.jsx)(u,{title:c,titleId:`update-modal-title`,onClose:t}),(0,p.jsx)(`div`,{className:`modal-body`,children:l})]})]})}export{k as UpdateModal};
@@ -0,0 +1 @@
1
+ (function(){let e=Object.freeze({state:`unknown`,incomplete_rows:null,retryable:!1}),t=new Set([`healthy`,`malformed_row_partial`,`transient_read_failure`]);function n(n){if(typeof n!=`object`||!n||Array.isArray(n))return e;let r=n,i=r.state;if(typeof i!=`string`||!t.has(i))return e;let a=r.incomplete_rows;return{state:i,incomplete_rows:typeof a==`number`&&Number.isFinite(a)?a:null,retryable:r.retryable===!0}}function r(e){let t=e.sources;if(typeof t!=`object`||!t)return e;for(let e of Object.values(t))typeof e!=`object`||!e||(e.metadata_health=n(e.metadata_health));return e}function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function o(e){if(!i(e)||e.envelope_version!==2||typeof e.generated_at!=`string`||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(e.generated_at)||!Number.isFinite(Date.parse(e.generated_at)))return!1;let t=e=>e==null||i(e);return i(e.header)&&t(e.current_week)&&t(e.forecast)&&t(e.trend)&&i(e.weekly)&&Array.isArray(e.weekly.rows)&&i(e.monthly)&&Array.isArray(e.monthly.rows)&&i(e.blocks)&&Array.isArray(e.blocks.rows)&&i(e.daily)&&Array.isArray(e.daily.rows)&&i(e.sessions)&&Array.isArray(e.sessions.rows)&&t(e.projects)&&i(e.display)&&Array.isArray(e.alerts)&&i(e.alerts_settings)}function s(e){return!i(e)||e.version!==1||!a(e.generation)?!1:e.type===`subscribe`||e.type===`suspend`||e.type===`resume`||e.type===`unsubscribe`}let c=new class{createEventSource;parse;ports=new Map;stream=null;lastSnapshot=null;deliveryGeneration=0;constructor(e,t=JSON.parse){this.createEventSource=e,this.parse=t}connect(e){this.ports.set(e,{port:e,active:!1,generation:0}),e.onmessage=t=>this.onPortMessage(e,t.data);try{e.start()}catch{this.ports.delete(e)}}onPortMessage(e,t){let n=this.ports.get(e);if(n==null||!s(t))return;let r=t;if(!(r.generation<=n.generation)){if(n.generation=r.generation,r.type===`unsubscribe`){this.ports.delete(e),this.reconcileStream();return}n.active=r.type===`subscribe`||r.type===`resume`,this.reconcileStream(),n.active&&this.stream!=null&&(n.port.postMessage({version:1,type:`ready`,generation:n.generation}),this.lastSnapshot!=null&&n.port.postMessage({version:1,type:`snapshot`,generation:n.generation,deliveryGeneration:this.lastSnapshot.deliveryGeneration,snapshot:this.lastSnapshot.snapshot}))}}reconcileStream(){let e=[...this.ports.values()].some(e=>e.active);e&&this.stream==null&&this.openStream(),!e&&this.stream!=null&&(this.stream.close(),this.stream=null)}openStream(){let e;try{e=this.createEventSource()}catch{this.broadcastError();return}this.stream=e,e.addEventListener(`update`,t=>{if(this.stream===e)try{let e=this.parse(t.data);if(!o(e))throw Error(`invalid dashboard envelope`);let n=r(e);this.deliveryGeneration+=1,this.lastSnapshot={snapshot:n,deliveryGeneration:this.deliveryGeneration};for(let e of this.ports.values())e.active&&e.port.postMessage({version:1,type:`snapshot`,generation:e.generation,deliveryGeneration:this.deliveryGeneration,snapshot:n})}catch{console.error(`Dashboard stream frame was rejected.`)}}),e.onerror=()=>{this.stream===e&&this.broadcastError()}}broadcastError(){for(let e of this.ports.values()){if(!e.active)continue;let t={version:1,type:`stream_error`,generation:e.generation};e.port.postMessage(t)}}}(()=>new EventSource(`/api/events`)),l=globalThis;l.onconnect=e=>{for(let t of e.ports)c.connect(t)}})();