mapigate 0.5.136 → 0.5.141

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 (76) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/commands/logs.js +0 -1
  3. package/dist/core/adapters/anthropic/requestOpenAiToAnthropic.js +1 -1
  4. package/dist/core/adapters/helpers/toolCallRescue.js +1 -1
  5. package/dist/core/adapters/responsesAdapter.js +11 -0
  6. package/dist/core/capabilities/modelDictionary.js +1 -0
  7. package/dist/core/scanner/modelScanner.js +2 -1
  8. package/dist/core/scanner/payloadExtractor.js +1 -1
  9. package/dist/core/scanner/urlResolver.js +16 -0
  10. package/dist/core/tokenSaver/methods/rtk/autodetect.js +1 -1
  11. package/dist/core/tokenSaver/methods/rtk/filters/gitLog.js +1 -1
  12. package/dist/core/usage/pricing.js +98 -42
  13. package/dist/core/usage/tokenExtractor.js +59 -0
  14. package/dist/mitm/handlers/antigravity/config.js +22 -0
  15. package/dist/mitm/handlers/antigravity/modelInjector.js +2 -2
  16. package/dist/providers/catalog/iflow/provider.js +1 -1
  17. package/dist/providers/catalog/iteracompute/metadata.js +154 -13
  18. package/dist/providers/catalog/iteracompute/provider.js +111 -0
  19. package/dist/providers/catalog/opencode-go/responsesPayload.js +1 -1
  20. package/dist/providers/catalog/openrouter/metadata.js +1 -0
  21. package/dist/providers/core/base/baseProvider.js +5 -3
  22. package/dist/providers/runtime/antigravity/executor.js +2 -2
  23. package/dist/providers/runtime/antigravity/metadata.js +2 -2
  24. package/dist/providers/runtime/antigravity/models.js +9 -0
  25. package/dist/providers/runtime/antigravity/provider.js +2 -2
  26. package/dist/providers/runtime/antigravity/routes.js +2 -2
  27. package/dist/providers/runtime/antigravity/schema.js +1 -1
  28. package/dist/providers/runtime/antigravity/types.js +10 -2
  29. package/dist/providers/runtime/gemini/provider.js +77 -0
  30. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  31. package/dist/providers/runtime/github/routes.js +1 -1
  32. package/dist/providers/runtime/grok/provider.js +1 -1
  33. package/dist/providers/runtime/kiro/provider.js +1 -1
  34. package/dist/providers/runtime/minimax/routes.js +0 -1
  35. package/dist/providers/runtime/opencode/tools.js +1 -1
  36. package/dist/providers/runtime/windsurf/routes.js +0 -2
  37. package/dist/providers/runtime/xkiro/quota.js +4 -1
  38. package/dist/server/proxy/executorHelpers.js +1 -1
  39. package/dist/server/proxy/index.js +1 -1
  40. package/dist/server/proxy/pipeline.js +12 -6
  41. package/dist/server/proxy/responseHandlers.js +2 -18
  42. package/dist/server/proxy/singleModelExecutor.js +1 -1
  43. package/dist/server/proxy/streaming/sseStreamer.js +3 -10
  44. package/dist/server/routes/apiMitm.js +1 -1
  45. package/dist/server/routes/apiModels.js +17 -12
  46. package/dist/server/utils/consoleLogBuffer.js +3 -3
  47. package/dist/shared/constants/index.js +2 -2
  48. package/dist/shared/logger.js +2 -2
  49. package/dist/storage/repositories/logRepo.js +3 -23
  50. package/dist/storage/repositories/requestDetailsRepo.js +1 -1
  51. package/dist/storage/repositories/usageRepo.js +136 -74
  52. package/dist/web/assets/{CliToolsTab-CkzwuwaC.js → CliToolsTab-rKSWLJC3.js} +1 -1
  53. package/dist/web/assets/CombosTab-D1_cfssh.js +1 -0
  54. package/dist/web/assets/{ConfirmModal-DGvcf0gB.js → ConfirmModal-OWeauwYv.js} +1 -1
  55. package/dist/web/assets/{ConsoleLogTab-84Ens8T5.js → ConsoleLogTab-rZe8zCb_.js} +1 -1
  56. package/dist/web/assets/{EditAccountModal-D-_omvev.js → EditAccountModal-CAg-yIOn.js} +1 -1
  57. package/dist/web/assets/{EndpointTab-7nBfEdYE.js → EndpointTab-B-Jb4wAG.js} +1 -1
  58. package/dist/web/assets/{MitmTab-CqS6mXHZ.js → MitmTab-5dKeNi4T.js} +5 -5
  59. package/dist/web/assets/{ModelAutocompleteInput-B9syrV1O.js → ModelAutocompleteInput-CoinzdsW.js} +1 -1
  60. package/dist/web/assets/{ProviderDetailPage-DGZceQ2d.js → ProviderDetailPage-D-fodBhz.js} +2 -2
  61. package/dist/web/assets/ProvidersTab-yzmb4w0D.js +1 -0
  62. package/dist/web/assets/{QuotaTab-DFr0DWAU.js → QuotaTab-BXevQzen.js} +1 -1
  63. package/dist/web/assets/{SettingsTab-4c0ksNJa.js → SettingsTab-LkByv4Sg.js} +1 -1
  64. package/dist/web/assets/UsageTab-Hr8XPZD4.js +1 -0
  65. package/dist/web/assets/index-CKuvklEr.js +2 -0
  66. package/dist/web/assets/metadataRegistry-NuDSSkP9.js +1 -0
  67. package/dist/web/assets/providers/openrouter/icon.png +0 -0
  68. package/dist/web/assets/{providersData-DkVCRBsJ.js → providersData-DS1-ETBi.js} +1 -1
  69. package/dist/web/index.html +1 -1
  70. package/package.json +9 -1
  71. package/dist/web/assets/CombosTab-C5RzRwwr.js +0 -1
  72. package/dist/web/assets/ProvidersTab-CiYbqRou.js +0 -1
  73. package/dist/web/assets/UsageTab-BQcPmvtQ.js +0 -1
  74. package/dist/web/assets/index-C4NTQZ40.js +0 -2
  75. package/dist/web/assets/metadataRegistry-B91sal4r.js +0 -1
  76. package/dist/web/assets/providers/openrouter/openrouter.png +0 -0
@@ -0,0 +1 @@
1
+ import{r as l,j as e}from"./vendor-BcOI2aZ9.js";import{P as ae}from"./index-CKuvklEr.js";import{C as ne}from"./ConfirmModal-OWeauwYv.js";import{i as Q}from"./ModelAutocompleteInput-CoinzdsW.js";import{g as X}from"./metadataRegistry-NuDSSkP9.js";import{T as Z}from"./ToolIcon-Cp4gSgFt.js";import{C as ie,O as ee,F as te,A as se}from"./providersData-DS1-ETBi.js";import"./lucide-Cc35htxl.js";const ce=({isOpen:N,existingProviderIds:z,onClose:o,onImportSuccess:g})=>{const[u,w]=l.useState([]),[_,y]=l.useState(!1),[h,j]=l.useState(""),[p,q]=l.useState("all"),[C,b]=l.useState(null),[I,k]=l.useState(""),[d,T]=l.useState(""),[v,P]=l.useState("Default Account"),[D,O]=l.useState(!1),[f,A]=l.useState(null);l.useEffect(()=>{N&&(y(!0),fetch("/api/providers/community-catalog").then(a=>a.json()).then(a=>{a&&Array.isArray(a.catalog)&&w(a.catalog)}).catch(a=>{console.error("Failed to load community catalog:",a)}).finally(()=>{y(!1)}))},[N]);const W=l.useMemo(()=>{const a=new Set;for(const n of u)n.category&&a.add(n.category);return["all",...Array.from(a).sort()]},[u]),B=l.useMemo(()=>{const a=h.toLowerCase().trim();return u.filter(n=>{var S;return p!=="all"&&n.category!==p?!1:a?n.name.toLowerCase().includes(a)||n.id.toLowerCase().includes(a)||n.baseUrl.toLowerCase().includes(a)||((S=n.models)==null?void 0:S.some(U=>U.id.toLowerCase().includes(a))):!0})},[u,h,p]),L=a=>{b(a),k(a.baseUrl||"https://api.openai.com"),T(""),P("Default Account"),A(null)},$=async()=>{if(C){O(!0),A(null);try{const a=await fetch("/api/providers/community-catalog/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:C.id,customBaseUrl:I.trim(),apiKey:d.trim()||void 0,accountName:v.trim()||"Default Account"})}),n=await a.json();if(!a.ok||!n.success)throw new Error(n.error||"Failed to import provider");g(C.id),b(null)}catch(a){A(a.message||"Import failed")}finally{O(!1)}}};return N?e.jsx(ae,{isOpen:N,onClose:o,maxWidthClass:"w-full max-w-4xl",children:e.jsxs("div",{className:"relative w-full max-w-4xl bg-[#0B0F19] border border-[#1E293B] rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[88vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[#1E293B] bg-[#0F1420]/70 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-500/10 border border-blue-500/20 flex items-center justify-center text-blue-400",children:e.jsx("span",{className:"material-symbols-outlined text-[22px]",children:"explore"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-base font-bold text-white",children:"Community Providers Catalog"}),e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-blue-500/10 border border-blue-500/20 text-blue-400 text-[11px] font-mono",children:[u.length," Available"]})]}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Browse on-demand multi-gateways, token resellers, and community inference proxies. Import directly into active providers."})]})]}),e.jsx("button",{onClick:o,className:"p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/5 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"close"})})]}),e.jsxs("div",{className:"p-4 border-b border-[#1E293B] bg-[#0A0D14]/80 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px]",children:[e.jsx("span",{className:"material-symbols-outlined absolute left-3 top-2.5 text-slate-500 text-[18px]",children:"search"}),e.jsx("input",{type:"text",value:h,onChange:a=>j(a.target.value),placeholder:"Search community provider by name, ID, endpoint...",className:"w-full pl-9 pr-3 py-2 text-xs bg-[#0F1420] border border-[#1E293B] rounded-xl text-white placeholder-slate-500 focus:outline-none focus:border-blue-500/60 transition-colors"}),h&&e.jsx("button",{onClick:()=>j(""),className:"absolute right-3 top-2.5 text-slate-500 hover:text-white text-xs",children:"✕"})]}),e.jsx("div",{className:"flex items-center gap-1.5 overflow-x-auto pb-1 max-w-full",children:W.map(a=>e.jsx("button",{onClick:()=>q(a),className:`px-2.5 py-1 rounded-lg text-[11px] font-medium capitalize transition-colors cursor-pointer ${p===a?"bg-blue-600 text-white shadow-xs":"bg-[#0F1420] text-slate-400 border border-[#1E293B] hover:text-white"}`,children:a},a))})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-2.5 min-h-[300px]",children:_?e.jsxs("div",{className:"py-20 flex flex-col items-center justify-center text-slate-500 text-xs gap-3",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-[28px] text-blue-400",children:"sync"}),e.jsx("span",{children:"Loading community catalog..."})]}):B.length===0?e.jsxs("div",{className:"py-16 text-center text-slate-500 text-xs flex flex-col items-center justify-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[32px] text-slate-600",children:"search_off"}),e.jsx("span",{children:"No community providers match your filter query."})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:B.map(a=>{const n=z.includes(a.id);return e.jsxs("div",{className:"p-3.5 rounded-xl bg-[#0F1420]/80 border border-[#1E293B] hover:border-slate-700 transition-all flex flex-col justify-between gap-3 group",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-xs text-white",children:a.name}),e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-[#1E293B] text-slate-400 font-mono",children:a.id})]}),e.jsx("div",{className:"text-[11px] text-slate-500 font-mono truncate max-w-[280px] mt-1",title:a.baseUrl||"Custom Base URL required",children:a.baseUrl||e.jsx("span",{className:"italic text-amber-500/80",children:"Requires custom URL"})})]}),e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono uppercase font-semibold ${a.format==="claude"?"bg-amber-500/10 text-amber-400 border border-amber-500/20":"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"}`,children:a.format})})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-3 text-[11px] text-slate-400",children:[a.models&&a.models.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[13px] text-slate-500",children:"memory"}),a.models.length," preset models"]}),a.website&&e.jsxs("a",{href:a.website,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-blue-400/80 hover:text-blue-300 transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-[13px]",children:"open_in_new"}),"Docs"]})]})]}),e.jsxs("div",{className:"pt-2 border-t border-[#1E293B]/60 flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-slate-500 capitalize",children:a.category}),n?e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-emerald-400 font-medium px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20",children:[e.jsx("span",{className:"material-symbols-outlined text-[13px]",children:"check_circle"}),"Active"]}):e.jsxs("button",{onClick:()=>L(a),className:"flex items-center gap-1 px-3 py-1 rounded-lg bg-blue-600 hover:bg-blue-500 text-white text-[11px] font-semibold transition-colors cursor-pointer shadow-xs",children:[e.jsx("span",{className:"material-symbols-outlined text-[13px]",children:"download"}),"Import"]})]})]},a.id)})})}),e.jsxs("div",{className:"p-3 border-t border-[#1E293B] bg-[#0A0D14] flex items-center justify-between text-xs text-slate-500",children:[e.jsxs("span",{children:["Showing ",B.length," of ",u.length," community providers"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px] text-blue-400",children:"info"}),"Imported providers are saved locally in SQLite and support load balancing."]})]}),C&&e.jsx("div",{className:"absolute inset-0 bg-black/75 backdrop-blur-xs flex items-center justify-center p-4 z-50 animate-rt-fade-in",children:e.jsxs("div",{className:"w-full max-w-md bg-[#0F1420] border border-[#1E293B] rounded-2xl p-5 shadow-2xl space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-[#1E293B] pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[18px]",children:"add_task"}),e.jsxs("h3",{className:"text-sm font-bold text-white",children:["Import ",C.name]})]}),e.jsx("button",{onClick:()=>b(null),className:"text-slate-400 hover:text-white text-xs cursor-pointer",children:"✕"})]}),f&&e.jsxs("div",{className:"p-2.5 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-xs flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"error"}),e.jsx("span",{children:f})]}),e.jsxs("div",{className:"space-y-3 text-xs",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-slate-300 font-semibold mb-1",children:"Base URL"}),e.jsx("input",{type:"text",value:I,onChange:a=>k(a.target.value),placeholder:"https://api.example.com/v1",className:"w-full px-3 py-2 bg-[#0A0D14] border border-[#1E293B] rounded-xl text-white placeholder-slate-600 focus:outline-none focus:border-blue-500/60"}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-1",children:"API endpoint prefix where request completions will be routed."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-slate-300 font-semibold mb-1",children:"Account Name"}),e.jsx("input",{type:"text",value:v,onChange:a=>P(a.target.value),placeholder:"Default Account",className:"w-full px-3 py-2 bg-[#0A0D14] border border-[#1E293B] rounded-xl text-white placeholder-slate-600 focus:outline-none focus:border-blue-500/60"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-slate-300 font-semibold mb-1",children:"API Key (Optional)"}),e.jsx("input",{type:"password",value:d,onChange:a=>T(a.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 bg-[#0A0D14] border border-[#1E293B] rounded-xl text-white placeholder-slate-600 focus:outline-none focus:border-blue-500/60"}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-1",children:"Encrypted with AES-256-GCM hardware vault. You can also configure it later."})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-3 border-t border-[#1E293B]",children:[e.jsx("button",{onClick:()=>b(null),disabled:D,className:"px-3.5 py-1.5 rounded-xl border border-[#1E293B] text-slate-400 hover:text-white text-xs font-semibold cursor-pointer",children:"Cancel"}),e.jsx("button",{onClick:$,disabled:D||!I.trim(),className:"px-4 py-1.5 rounded-xl bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white text-xs font-semibold flex items-center gap-1.5 cursor-pointer shadow-xs",children:D?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-[14px]",children:"sync"}),"Importing..."]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"check"}),"Save & Activate"]})})]})]})})]})}):null},ge=({searchQuery:N,onSelectProvider:z})=>{const[o,g]=l.useState(null),[u,w]=l.useState(""),[_,y]=l.useState("Default Account"),[h,j]=l.useState(""),[p,q]=l.useState([]),[C,b]=l.useState(new Set),[I,k]=l.useState({}),[d,T]=l.useState(null),[v,P]=l.useState("all"),[D,O]=l.useState(!1),[f,A]=l.useState(null),[W,B]=l.useState(!1),[L,$]=l.useState(!1),[a,n]=l.useState(null),S=async()=>{try{const t=await fetch("/api/providers");if(t.ok){const s=await t.json(),r=Array.isArray(s)?s.filter(x=>x.id!=="combo"&&x.category!=="composite"):[];q(r)}}catch{}};l.useEffect(()=>{S()},[]);const U=t=>{const s=t.baseUrl||t.defaultBaseUrl||"";return s.startsWith("devin://")||s.startsWith("auggie://")||s.startsWith("zcode://")||s.includes("://")&&s.endsWith("/stdio")},F=t=>U(t)?!1:!!t.noAuth||t.requiresApiKey===!1||t.authType==="none"||t.id==="opencode"||t.id==="oc"||t.id==="ollama-local"||t.id==="lm-studio"||t.id==="jan",G=t=>{const s=p.find(x=>x.id===t),r=X(t);return r&&U(r)?(s==null?void 0:s.accountsCount)??0:t==="opencode"||t==="oc"||s!=null&&s.noAuth||r!=null&&r.noAuth||(r==null?void 0:r.requiresApiKey)===!1||(r==null?void 0:r.authType)==="none"?Math.max(1,(s==null?void 0:s.accountsCount)??0):(s==null?void 0:s.accountsCount)??0},M=t=>{const s=!N||t.name.toLowerCase().includes(N.toLowerCase()),r=G(t.id);return v==="connected"?s&&(r>0||F(t)):v==="not_connected"?s&&r===0&&!F(t):s},re=async()=>{if(o){$(!0),n(null);try{const t=p.find(s=>s.id===o.id);if(!t||h.trim()&&h.trim()!==t.baseUrl){const s={id:o.id,name:(t==null?void 0:t.name)||o.name,baseUrl:h.trim()||o.baseUrl||(t==null?void 0:t.baseUrl)||"https://api.openai.com",format:(t==null?void 0:t.format)||o.format||"openai"};t&&(s.models=t.models,s.customHeaders=t.customHeaders,s.proxyUrl=t.proxyUrl,s.thinkingMode=t.thinkingMode,s.strategy=t.strategy,s.stickyLimit=t.stickyLimit);const r=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const x=await r.json().catch(()=>({}));throw new Error(x.error||`Failed to save provider (${r.status})`)}}if(u.trim()||F(o)){const s=await fetch(`/api/providers/${o.id}/accounts`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:_||`${o.name} Connection`,apiKey:u.trim()||(o.id==="opencode"||o.id==="oc"?"public":"")})});if(!s.ok){const r=await s.json().catch(()=>({}));throw new Error(r.error||`Failed to add account (${s.status})`)}}await S(),Q(),w(""),y("Default Account"),j(""),n(null),g(null)}catch(t){console.error(t),n(t.message||"Failed to save connection.")}finally{$(!1)}}},H=async t=>{b(s=>new Set(s).add(t));try{const r=await(await fetch(`/api/providers/${t}/test`,{method:"POST"})).json();k(x=>({...x,[t]:{success:!!r.success,msg:r.message||(r.success?"Connected successfully":"Connection failed"),latencyMs:r.latencyMs}}))}catch(s){k(r=>({...r,[t]:{success:!1,msg:s.message||"Failed to reach gateway"}}))}finally{b(s=>{const r=new Set(s);return r.delete(t),r})}},J=async(t,s)=>{const r=t.filter(c=>G(c.id)>0||F(c));if(r.length===0){alert(`No configured or ready accounts found in ${s}.`);return}T(s);const x=r.map(c=>c.id);b(c=>{const m=new Set(c);return x.forEach(i=>m.add(i)),m});try{const c=await fetch("/api/providers/test-bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerIds:x})});if(c.ok){const m=await c.json();m.results&&k(i=>{const E={...i};for(const[oe,K]of Object.entries(m.results))E[oe]={success:!!K.success,msg:K.message||(K.success?"Connected successfully":"Connection failed"),latencyMs:K.latencyMs};return E})}else for(const m of r)await H(m.id)}catch{for(const c of r)await H(c.id)}finally{b(c=>{const m=new Set(c);return x.forEach(i=>m.delete(i)),m}),T(null)}},le=async()=>{if(f){B(!0);try{(await fetch(`/api/providers/${f.id}`,{method:"DELETE"})).ok&&(await S(),Q())}catch{}finally{B(!1),A(null)}}},Y=new Set(ie.map(t=>t.id)),V=p.filter(t=>!Y.has(t.id)).map(t=>{const s=X(t.id);return{id:t.id,name:t.name,image:(s==null?void 0:s.image)||(t.format==="anthropic"?"/assets/providers/anthropic/icon.png":"/assets/providers/openai/icon.png"),color:(s==null?void 0:s.color)||(t.format==="anthropic"?"#D97706":"#10A37F"),iconBg:(s==null?void 0:s.iconBg)||"#ffffff",category:"custom",format:t.format||"openai",baseUrl:t.baseUrl,models:t.models,thinkingMode:t.thinkingMode}}),R=(t,s=!1)=>{const r=t.category==="custom"||!Y.has(t.id),x=!!s&&r,c=G(t.id),m=C.has(t.id),i=I[t.id];return e.jsxs("div",{onClick:()=>z(t),className:"rt-card stagger-item group flex flex-col justify-between cursor-pointer relative overflow-hidden min-w-[300px] hover:border-blue-500/30 transition-all",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Z,{src:t.image,name:t.name,color:t.color,iconBg:t.iconBg,size:"md",className:"group-hover:border-blue-500/40 transition-colors shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"text-xs font-bold text-slate-100 truncate group-hover:text-blue-400 transition-colors",children:t.name}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap",children:[U(t)?e.jsx("span",{className:"rt-badge rt-badge--muted text-[10px]",children:"CLI Bridge"}):F(t)?e.jsxs("span",{className:"rt-badge rt-badge--success",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-emerald-400"}),t.isLocal?"Ready (Local)":"Ready (Free)"]}):c>0?e.jsxs("span",{className:"rt-badge rt-badge--success",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-emerald-400 animate-pulse"}),c," Connected"]}):e.jsx("span",{className:"rt-badge rt-badge--muted",children:"No connections"}),i&&e.jsx("span",{className:`rt-badge text-[10px] ${i.success?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-red-500/10 text-red-400 border border-red-500/20"}`,title:i.msg,children:i.success?`● ${i.latencyMs?`${i.latencyMs}ms`:"Active"}`:"● Error"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:E=>{E.stopPropagation(),H(t.id)},disabled:m,title:"Test Connection",className:"p-2 rounded-lg bg-white/5 hover:bg-blue-500/20 text-slate-400 hover:text-blue-400 transition-colors cursor-pointer",children:e.jsx("span",{className:`material-symbols-outlined text-[16px] ${m?"animate-spin text-blue-400":""}`,children:m?"sync":"speed"})}),x&&e.jsx("button",{onClick:E=>{E.stopPropagation(),A(t)},title:"Delete Provider",className:"p-2 rounded-lg bg-white/5 hover:bg-red-500/20 text-slate-400 hover:text-red-400 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"delete"})})]})]}),i&&e.jsx("div",{className:`w-full py-1 px-3 text-[10px] font-mono border-t truncate ${i.success?"bg-emerald-500/10 text-emerald-400 border-emerald-500/20":"bg-red-500/10 text-red-400 border-red-500/20"}`,title:i.msg,children:i.success?`✓ ${i.msg}`:`✗ ${i.msg}`})]},t.id)};return e.jsxs("div",{className:"space-y-8 w-full px-2 sm:px-4 pb-16 animate-rt-fade-in",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4 rounded-2xl bg-[#0F1420]/70 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsx("span",{className:"font-semibold text-slate-300",children:"Filter Status:"}),e.jsxs("div",{className:"flex items-center bg-[#0A0D14] p-1 rounded-xl border border-[#1E293B]",children:[e.jsx("button",{onClick:()=>P("all"),className:`px-3 py-1 rounded-lg transition-colors font-medium ${v==="all"?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:"All Providers"}),e.jsx("button",{onClick:()=>P("connected"),className:`px-3 py-1 rounded-lg transition-colors font-medium ${v==="connected"?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:"Connected Only"}),e.jsx("button",{onClick:()=>P("not_connected"),className:`px-3 py-1 rounded-lg transition-colors font-medium ${v==="not_connected"?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:"Unconfigured"})]})]}),e.jsxs("div",{className:"text-xs text-slate-400 font-mono flex items-center gap-2",children:[e.jsx("span",{children:"Active Accounts:"}),e.jsx("span",{className:"px-2 py-0.5 rounded-md bg-blue-500/10 text-blue-400 border border-blue-500/20 font-bold",children:p.reduce((t,s)=>t+(s.accountsCount||0),0)})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-bold text-white flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[18px]",children:"add_circle"}),"Custom Providers (OpenAI & Anthropic Compatible)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>{w(""),y("Default Account"),j("https://api.anthropic.com"),g({id:`custom-anthropic-${Date.now().toString().slice(-4)}`,name:"Custom Anthropic",image:"/assets/providers/anthropic/icon.png",category:"custom",format:"anthropic",baseUrl:"https://api.anthropic.com"})},className:"rt-btn rt-btn--primary",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"add"}),"Add Anthropic Compatible"]}),e.jsxs("button",{onClick:()=>{w(""),y("Default Account"),j("https://api.openai.com"),g({id:`custom-openai-${Date.now().toString().slice(-4)}`,name:"Custom OpenAI",image:"/assets/providers/openai/icon.png",category:"custom",format:"openai",baseUrl:"https://api.openai.com"})},className:"rt-btn rt-btn--secondary",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"add"}),"Add OpenAI Compatible"]}),e.jsxs("button",{onClick:()=>O(!0),className:"rt-btn rt-btn--secondary hover:border-blue-500/50",title:"Browse 124 community-curated routers & gateways",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[16px]",children:"explore"}),"Community Catalog"]})]})]}),V.filter(M).length>0?e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(290px,1fr))] gap-3",children:V.filter(M).map(t=>R(t,!0))}):e.jsxs("div",{className:"border border-dashed border-[#1E293B] bg-[#0E1320]/60 rounded-2xl p-5 text-center text-xs text-slate-400 flex items-center justify-center gap-2 hover:border-blue-500/30 transition-colors",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[18px]",children:"cloud_sync"}),e.jsx("span",{children:V.length>0?"No custom providers match the current filter.":"Use the buttons above to register self-hosted vLLM, Ollama, LM Studio, or local API proxies."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-bold text-white flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[18px]",children:"verified"}),"OAuth & Managed IDE Providers"]}),e.jsxs("button",{onClick:()=>J(ee,"OAuth Providers"),disabled:d==="OAuth Providers",className:"flex items-center gap-1.5 text-xs text-slate-400 hover:text-blue-400 px-3 py-1.5 rounded-lg hover:bg-white/5 transition-colors cursor-pointer font-medium disabled:opacity-50",children:[e.jsx("span",{className:`material-symbols-outlined text-[15px] ${d==="OAuth Providers"?"animate-spin text-blue-400":""}`,children:d==="OAuth Providers"?"sync":"play_arrow"}),d==="OAuth Providers"?"Testing...":"Test All"]})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(290px,1fr))] gap-3",children:ee.filter(M).map(t=>R(t,!1))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-bold text-white flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-emerald-400 text-[18px]",children:"redeem"}),"Free Tier & Community Gateways"]}),e.jsxs("button",{onClick:()=>J(te,"Free Tier Providers"),disabled:d==="Free Tier Providers",className:"flex items-center gap-1.5 text-xs text-slate-400 hover:text-blue-400 px-3 py-1.5 rounded-lg hover:bg-white/5 transition-colors cursor-pointer font-medium disabled:opacity-50",children:[e.jsx("span",{className:`material-symbols-outlined text-[15px] ${d==="Free Tier Providers"?"animate-spin text-emerald-400":""}`,children:d==="Free Tier Providers"?"sync":"play_arrow"}),d==="Free Tier Providers"?"Testing...":"Test All"]})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(290px,1fr))] gap-3",children:te.filter(M).map(t=>R(t,!1))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-bold text-white flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[18px]",children:"key"}),"Direct API Key Providers"]}),e.jsxs("button",{onClick:()=>J(se,"API Key Providers"),disabled:d==="API Key Providers",className:"flex items-center gap-1.5 text-xs text-slate-400 hover:text-blue-400 px-3 py-1.5 rounded-lg hover:bg-white/5 transition-colors cursor-pointer font-medium disabled:opacity-50",children:[e.jsx("span",{className:`material-symbols-outlined text-[15px] ${d==="API Key Providers"?"animate-spin text-blue-400":""}`,children:d==="API Key Providers"?"sync":"play_arrow"}),d==="API Key Providers"?"Testing...":"Test All"]})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(290px,1fr))] gap-3",children:se.filter(M).map(t=>R(t,!1))})]}),e.jsx(ae,{isOpen:!!o,onClose:()=>{g(null),w(""),y("Default Account"),j(""),n(null)},maxWidthClass:"max-w-md",children:o&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Z,{src:o.image,name:o.name,color:o.color,iconBg:o.iconBg,size:"sm"}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:o.name}),e.jsxs("span",{className:"text-[11px] text-blue-400 font-mono",children:[o.format||"openai"," protocol"]})]})]}),e.jsx("button",{onClick:()=>g(null),className:"text-slate-400 hover:text-white p-1 rounded-lg hover:bg-white/10",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"close"})})]}),a&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-xs text-red-400 flex items-start gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-red-400 shrink-0 mt-0.5",children:"error"}),e.jsx("span",{children:a})]}),e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-300 mb-1",children:"Account Label / Nickname"}),e.jsx("input",{type:"text",value:_,onChange:t=>y(t.target.value),placeholder:"e.g. Work Pro Key 1",className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-300 mb-1",children:"Base URL Override"}),e.jsx("input",{type:"text",value:h,onChange:t=>j(t.target.value),placeholder:o.format==="anthropic"?"https://api.anthropic.com":o.baseUrl||"https://api.openai.com",className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-300 mb-1",children:"API Key / Secret Token (AES-256-GCM Hardware Encrypted)"}),e.jsx("input",{type:"password",value:u,onChange:t=>w(t.target.value),placeholder:"sk-...",className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30"})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B] text-[11px] text-slate-400 flex items-start gap-2.5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-emerald-400 shrink-0 mt-0.5",children:"enhanced_encryption"}),e.jsx("span",{className:"leading-relaxed",children:"Keys are securely locked with your PC's machine ID salt. No cloud upload, no telemetry."})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-3 border-t border-[#1E293B]",children:[e.jsx("button",{onClick:()=>g(null),disabled:L,className:"px-4 py-2 text-xs text-slate-400 hover:text-white transition-colors cursor-pointer disabled:opacity-50",children:"Cancel"}),e.jsx("button",{onClick:re,disabled:L,className:"rt-btn rt-btn--primary disabled:opacity-50",children:L?"Saving...":"Save & Connect"})]})]})}),e.jsx(ce,{isOpen:D,existingProviderIds:p.map(t=>t.id),onClose:()=>O(!1),onImportSuccess:async()=>{await S(),Q()}}),e.jsx(ne,{isOpen:!!f,title:"Delete Provider",message:`Are you sure you want to delete "${f==null?void 0:f.name}"? This will permanently remove the provider configuration and all associated accounts/credentials.`,confirmText:W?"Deleting...":"Delete",variant:"danger",onConfirm:le,onCancel:()=>A(null)})]})};export{ge as ProvidersTab};
@@ -1 +1 @@
1
- import{j as e,r as x}from"./vendor-BcOI2aZ9.js";import{g as D}from"./metadataRegistry-B91sal4r.js";import{T as V}from"./ToolIcon-Cp4gSgFt.js";import{S as F}from"./Select-BNRH8LIG.js";import{C as Y,E as K}from"./EditAccountModal-D-_omvev.js";import{C as X}from"./ConfirmModal-DGvcf0gB.js";import"./index-C4NTQZ40.js";import"./lucide-Cc35htxl.js";const Z={antigravity:["Gemini (5h)","Gemini (Weekly)","Claude & GPT (5h)","Claude & GPT (Weekly)","Gemini 4 Argon (Weekly)"],github:["Chat","Completions","Premium Interactions"],copilot:["Chat","Completions","Premium Interactions"],claude:["5-Hour Window","5h Session","Session","7-Day Window","Weekly"],codex:["Session","Weekly","Credits","Balance"],openai:["Session","Weekly","Credits","Balance"],gemini:["Requests (RPM)","Requests (Daily)","Tokens (TPM)","Tokens (Daily)"],"gemini-cli":["Gemini (5h)","Gemini (Weekly)","Requests (RPM)","Requests (Daily)","Tokens (TPM)","Tokens (Daily)"],grok:["Session","Weekly","Requests","Tokens","Balance"],"grok-cli":["Session","Weekly","Requests","Tokens","Balance"],kiro:["Session","Weekly","Monthly","Credits"],deepseek:["Balance","Total Grants","Topped-up Balance"],minimax:["Coding Tokens","Standard Tokens","Balance"],"minimax-cn":["Coding Tokens","Standard Tokens","Balance"],glm:["Session","Weekly","Balance"],"glm-cn":["Session","Weekly","Balance"],qoder:["Daily","Weekly","Monthly","Balance"],"qoder-cn":["Daily","Weekly","Monthly","Balance"],xkiro:["Session (5h)","Weekly (7d)","Free Tokens (Daily)","Wallet Balance"],"xiaomi-tokenplan":["Monthly Tokens","Weekly Quota"],xmtp:["Monthly Tokens","Weekly Quota"],"xiaomi-mimo":["Monthly Tokens","Weekly Quota"],mimo:["Monthly Tokens","Weekly Quota"]},ee=new Proxy(Z,{get(o,n){if(typeof n!="string")return;const c=n.toLowerCase(),l=D(c);return l!=null&&l.quotaOrder?l.quotaOrder:o[c]},has(o,n){if(typeof n!="string")return!1;const c=n.toLowerCase(),l=D(c);return!!(l!=null&&l.quotaOrder)||c in o}});function te(o,n){if(!n||n.length<=1)return n?[...n]:[];const c=(o||"").toLowerCase(),l=D(c),h=(l==null?void 0:l.quotaOrder)||ee[c]||[];return[...n].sort((v,b)=>{const d=y=>{const m=(y||"").trim().toLowerCase(),u=h.findIndex(j=>{const p=j.toLowerCase();return m===p||m.startsWith(p)||p.startsWith(m)||m.includes(p)});return u===-1?9999:u},g=d(v.label),f=d(b.label);return g!==f?g-f:(v.label||"").localeCompare(b.label||"")})}function re(o,n,c,l){const h=c.toLowerCase(),v=(l==null?void 0:l.toLowerCase())==="kiro",b=h.includes("token"),d=h.includes("credit")||v&&!h.includes("request");if(b){if(n>=1e9){const g=`${(n/1e9).toFixed(1)}B`;return`${o>=1e9?`${(o/1e9).toFixed(2)}B`:o>=1e6?`${(o/1e6).toFixed(1)}M`:o.toLocaleString()} / ${g} tokens`}if(n>=1e6){const g=`${(n/1e6).toFixed(0)}M`;return`${o>=1e6?`${(o/1e6).toFixed(2)}M`:o.toLocaleString()} / ${g} tokens`}return n>0?`${o.toLocaleString()} / ${n.toLocaleString()} tokens`:`${o.toLocaleString()} tokens`}if(d){const g=n===1?"credit":"credits";return n>0?`${o.toLocaleString()} / ${n.toLocaleString()} ${g}`:`${o.toLocaleString()} ${g}`}return n===100&&!h.includes("req")?`${o}% used`:n>0?`${o.toLocaleString()} / ${n.toLocaleString()} reqs`:`${o.toLocaleString()} reqs`}const se=({label:o,used:n,total:c,percentage:l,resetInText:h="-",unlimited:v=!1,recurring:b=!0,providerId:d})=>{const f=(m=>m>=50?{text:"text-emerald-400",bg:"bg-emerald-500",bgTrack:"bg-emerald-500/15",emoji:"🟢"}:m>0?{text:"text-amber-400",bg:"bg-amber-500",bgTrack:"bg-amber-500/15",emoji:"🟡"}:{text:"text-red-400",bg:"bg-red-500",bgTrack:"bg-red-500/15",emoji:"🔴"})(l),y=b?"Reset":"Expires";return e.jsxs("div",{className:"space-y-1.5 py-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-medium text-slate-200 truncate pr-2",title:o,children:o}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("span",{className:"text-[10px]",children:f.emoji}),e.jsx("span",{className:`font-semibold ${f.text}`,children:v?"100%":`${l}%`})]})]}),!v&&e.jsx("div",{className:`h-2 rounded-full overflow-hidden ${f.bgTrack} w-full`,children:e.jsx("div",{className:`h-full transition-all duration-300 rounded-full ${f.bg}`,style:{width:`${Math.min(100,Math.max(0,l))}%`}})}),e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-slate-400",children:[e.jsx("span",{children:v?"Unlimited":re(n,c,o,d)}),h&&h!=="-"&&e.jsxs("div",{className:"flex items-center gap-1 font-mono text-[10px] text-slate-400",children:[e.jsx("span",{children:"•"}),e.jsxs("span",{children:[y," in ",h]})]})]})]})},ae={antigravity:"#4285F4",gemini:"#1A73E8","gemini-cli":"#1A73E8",claude:"#D97757",codex:"#10A37F",openai:"#10A37F",github:"#24292F",copilot:"#24292F",kiro:"#FF9900",deepseek:"#4D6BFE",grok:"#E11D48","grok-cli":"#E11D48",minimax:"#7C3AED","minimax-cn":"#7C3AED",qoder:"#EC4899","qoder-cn":"#EC4899",glm:"#0055FF","glm-cn":"#0055FF"},P=({account:o,loading:n=!1,onRefresh:c,onEdit:l,onToggle:h})=>{const[v,b]=x.useState(!1),d=D(o.providerId),g=(d==null?void 0:d.color)||ae[o.providerId.toLowerCase()]||"#3B82F6",f=async()=>{if(!(v||n)){b(!0);try{await c(o.accountId)}finally{b(!1)}}},y=n||v,m=x.useMemo(()=>{var p;let u=o.quotas||[];const j=(p=o.providerId)==null?void 0:p.toLowerCase();if(j==="antigravity"||j==="gemini-cli"){const $=["gemini (5h)","gemini (weekly)","claude & gpt (5h)","claude & gpt (weekly)","gemini 4 argon (weekly)"],S=u.filter(C=>$.some(I=>(C.label||"").toLowerCase().trim()===I));S.length>0&&(u=S)}return te(o.providerId,u)},[o.providerId,o.quotas]);return e.jsxs("div",{className:`flex flex-col justify-between bg-[#0F1420]/80 border border-[#1E293B] hover:border-slate-700/80 rounded-2xl p-4 sm:p-5 transition-all duration-200 shadow-lg min-w-[400px] ${o.isActive?"":"opacity-60 bg-[#0B0E17]/60"}`,children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 pb-3 border-b border-[#1E293B]/70",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(V,{src:(d==null?void 0:d.image)||`/assets/providers/${o.providerId}/icon.png`,name:o.providerId,color:g,iconBg:d==null?void 0:d.iconBg,size:"md"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-slate-100 text-xs sm:text-sm capitalize truncate",children:o.providerId}),o.plan&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-md font-medium bg-blue-500/10 text-blue-400 border border-blue-500/20",children:o.plan})]}),e.jsx("div",{className:"text-[11px] text-slate-400 truncate max-w-[170px]",title:o.accountName,children:o.accountName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:f,disabled:y,title:"Refresh Quota",className:"p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-[#1E293B]/70 transition-colors disabled:opacity-50 cursor-pointer",children:e.jsx("span",{className:`material-symbols-outlined text-[18px] ${y?"animate-spin text-blue-400":""}`,children:"refresh"})}),e.jsx("button",{onClick:()=>l(o),title:"Edit Account",className:"p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-[#1E293B]/70 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"edit"})}),e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer ml-1",title:"Toggle active status",children:[e.jsx("input",{type:"checkbox",checked:o.isActive,onChange:u=>h(o.accountId,u.target.checked),className:"sr-only peer"}),e.jsx("div",{className:"w-8 h-4.5 bg-slate-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-3.5 after:w-3.5 after:transition-all peer-checked:bg-blue-600"})]})]})]}),y&&m.length===0?e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx("div",{className:"h-4 bg-slate-800/60 rounded animate-pulse w-3/4"}),e.jsx("div",{className:"h-2 bg-slate-800/60 rounded-full animate-pulse w-full"}),e.jsx("div",{className:"h-4 bg-slate-800/60 rounded animate-pulse w-2/3"}),e.jsx("div",{className:"h-2 bg-slate-800/60 rounded-full animate-pulse w-full"})]}):m.length>0?e.jsx("div",{className:"space-y-2.5",children:m.map((u,j)=>e.jsx(se,{label:u.label,used:u.used,total:u.total,percentage:u.remainingPercentage,resetInText:u.resetInText,unlimited:u.unlimited,recurring:u.recurring,providerId:o.providerId},`${u.label}-${j}`))}):e.jsx("div",{className:"py-4 text-center text-xs text-slate-400 bg-[#0A0D14]/50 rounded-xl border border-[#1E293B]/50 px-3",children:o.error?e.jsx("span",{className:"text-red-400/90",children:o.error}):o.message||"No quota data available."})]}),e.jsxs("div",{className:"pt-3 mt-2 border-t border-[#1E293B]/50 flex items-center justify-between text-[10px] text-slate-500 font-mono",children:[e.jsx("span",{children:o.isActive?e.jsx("span",{className:"text-emerald-400 font-medium",children:"Active"}):e.jsx("span",{className:"text-slate-400",children:"Inactive"})}),o.lastFetchedAt&&e.jsxs("span",{children:["Updated ",new Date(o.lastFetchedAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]})},oe=({providers:o,selectedProvider:n,onSelectProvider:c,statusFilter:l,onSelectStatusFilter:h,sortMode:v,onSelectSortMode:b,autoRefresh:d,onToggleAutoRefresh:g,countdownSeconds:f,isRefreshingAll:y,onRefreshAll:m,onTurnOffEmpty:u,onTurnOnAvailable:j})=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-xs p-4 rounded-2xl bg-[#0F1420]/80 border border-[#1E293B] shadow-lg w-full",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[e.jsx(F,{value:n,onChange:c,options:[{value:"all",label:"All providers"},...o.map(p=>({value:p,label:p.toUpperCase()}))],className:"min-w-[140px]"}),e.jsx(F,{value:l,onChange:p=>h(p),options:[{value:"all",label:"All accounts"},{value:"active",label:"Active only"},{value:"inactive",label:"Turned off"}],className:"min-w-[130px]"}),e.jsx(F,{value:v,onChange:p=>b(p),options:[{value:"fixed",label:"Fixed order (Providers)"},{value:"expiring-first",label:"Expiring first"},{value:"quota-asc",label:"% Quota: low to high"},{value:"quota-desc",label:"% Quota: high to low"}],className:"min-w-[175px]"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[e.jsxs("button",{onClick:u,title:"Turn off all accounts with depleted (0%) quota",className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-red-500/20 bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer font-medium active:scale-95",children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"block"}),"Turn off Empty"]}),e.jsxs("button",{onClick:j,title:"Turn on accounts with available (>0%) quota",className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-emerald-500/20 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20 transition-colors cursor-pointer font-medium active:scale-95",children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"check_circle"}),"Turn on Available"]}),e.jsxs("div",{className:"flex items-center gap-2 bg-[#0A0D14] border border-[#1E293B] px-3 py-1.5 rounded-xl select-none",children:[e.jsx(Y,{size:"sm",checked:d,onChange:p=>g(p),label:"Autorefresh"}),d&&e.jsxs("span",{className:"font-mono text-[10px] text-blue-400 font-semibold bg-blue-500/10 px-1.5 py-0.5 rounded border border-blue-500/20",children:[f,"s"]})]}),e.jsx("button",{onClick:m,disabled:y,title:"Refresh all quotas",className:"p-1.5 rounded-xl border border-[#1E293B] bg-[#0A0D14] text-slate-400 hover:text-white hover:border-slate-600 transition-colors cursor-pointer disabled:opacity-50",children:e.jsx("span",{className:`material-symbols-outlined text-[17px] ${y?"animate-spin text-blue-400":""}`,children:"refresh"})})]})]}),B=60,W="mapigate_cached_quota_accounts",_="mapigate_quota_sort_mode",pe=({searchQuery:o=""})=>{const[n,c]=x.useState(()=>{try{const s=localStorage.getItem(W);if(s){const t=JSON.parse(s);if(Array.isArray(t)&&t.length>0)return t}}catch{}return[]}),[l,h]=x.useState(()=>n.length===0),[v,b]=x.useState(!1),[d,g]=x.useState("all"),[f,y]=x.useState("all"),[m,u]=x.useState(()=>{try{const s=localStorage.getItem(_);if(s==="fixed"||s==="expiring-first"||s==="quota-asc"||s==="quota-desc")return s}catch{}return"fixed"}),[j,p]=x.useState(!0),[$,S]=x.useState(B),[C,I]=x.useState(null),[T,E]=x.useState(null),k=x.useCallback(async(s=!1)=>{try{s&&b(!0);const r=await fetch(s?"/api/quota?force=true":"/api/quota");if(!r.ok)throw new Error(`HTTP error ${r.status}`);const a=await r.json();c(a);try{localStorage.setItem(W,JSON.stringify(a))}catch{}}catch(t){console.error("[QuotaTab] Failed to fetch quotas:",t)}finally{h(!1),b(!1)}},[]);x.useEffect(()=>{k(!1).then(()=>{k(!0)})},[k]),x.useEffect(()=>{if(!j)return;const s=setInterval(()=>{document.hidden||S(t=>t<=1?(k(!1),B):t-1)},1e3);return()=>clearInterval(s)},[j,k]);const Q=async()=>{b(!0),S(B),await k(!0)},R=async s=>{try{const t=await fetch(`/api/quota/${s}`);if(!t.ok)throw new Error(`HTTP error ${t.status}`);const r=await t.json();c(a=>a.map(i=>i.accountId===s?{...i,...r,sortOrder:i.sortOrder??r.sortOrder,createdAt:i.createdAt??r.createdAt}:i))}catch(t){console.error(`[QuotaTab] Failed to refresh account ${s}:`,t)}},M=async(s,t)=>{c(r=>r.map(a=>a.accountId===s?{...a,isActive:t}:a));try{(await fetch(`/api/quota/accounts/${s}/toggle`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:t})})).ok||c(a=>a.map(i=>i.accountId===s?{...i,isActive:!t}:i))}catch{c(a=>a.map(i=>i.accountId===s?{...i,isActive:!t}:i))}},G=async s=>{if(!C)return;const t=await fetch(`/api/quota/accounts/${C.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!t.ok){const a=await t.json().catch(()=>({}));throw new Error(a.error||"Failed to update account.")}const{account:r}=await t.json();r?c(a=>a.map(i=>i.accountId===C.id?r:i)):await k(!0)},U=()=>{const s=n.filter(t=>t.isActive&&t.quotas.length>0&&t.quotas.some(r=>!r.unlimited&&r.remainingPercentage===0));if(s.length===0){alert("No active accounts with depleted (0%) quota found.");return}E({isOpen:!0,title:"Turn off Depleted Accounts",message:`Are you sure you want to turn off ${s.length} account(s) with 0% quota? This will prevent upstream 429 rate limit errors.`,variant:"danger",confirmText:`Turn off (${s.length})`,onConfirm:async()=>{const t=s.map(r=>r.accountId);c(r=>r.map(a=>t.includes(a.accountId)?{...a,isActive:!1}:a)),E(null);try{await fetch("/api/quota/toggle-batch",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountIds:t,isActive:!1})})}catch(r){console.error("[QuotaTab] Failed to turn off depleted accounts:",r)}}})},z=()=>{const s=n.filter(t=>!t.isActive&&t.quotas.length>0&&t.quotas.every(r=>r.unlimited||r.remainingPercentage>0));if(s.length===0){alert("No inactive accounts with available (>0%) quota found.");return}E({isOpen:!0,title:"Turn on Available Accounts",message:`Activate ${s.length} account(s) that have recovered capacity?`,variant:"emerald",confirmText:`Turn on (${s.length})`,onConfirm:async()=>{const t=s.map(r=>r.accountId);c(r=>r.map(a=>t.includes(a.accountId)?{...a,isActive:!0}:a)),E(null);try{await fetch("/api/quota/toggle-batch",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountIds:t,isActive:!0})})}catch(r){console.error("[QuotaTab] Failed to turn on available accounts:",r)}}})},H=x.useMemo(()=>{const s=new Set;return n.forEach(t=>{t.providerId&&s.add(t.providerId.toLowerCase())}),Array.from(s).sort()},[n]),L=x.useMemo(()=>{let s=[...n];if(d!=="all"&&(s=s.filter(t=>t.providerId.toLowerCase()===d.toLowerCase())),f==="active"?s=s.filter(t=>t.isActive):f==="inactive"&&(s=s.filter(t=>!t.isActive)),o.trim()){const t=o.toLowerCase().trim();s=s.filter(r=>r.accountName.toLowerCase().includes(t)||r.providerId.toLowerCase().includes(t)||r.accountId.toLowerCase().includes(t))}if(m==="fixed")s.sort((t,r)=>{const a=t.providerId.localeCompare(r.providerId);if(a!==0)return a;const i=(t.sortOrder??0)-(r.sortOrder??0);if(i!==0)return i;if(t.createdAt&&r.createdAt&&t.createdAt!==r.createdAt)return t.createdAt-r.createdAt;const N=t.accountName.localeCompare(r.accountName);return N!==0?N:t.accountId.localeCompare(r.accountId)});else if(m==="expiring-first"){const t=r=>{const a=r.quotas.map(i=>i.resetAt).filter(i=>typeof i=="number"&&i>0);return a.length>0?Math.min(...a):Number.POSITIVE_INFINITY};s.sort((r,a)=>{const i=t(r)-t(a);if(i!==0)return i;const N=r.providerId.localeCompare(a.providerId);if(N!==0)return N;const A=(r.sortOrder??0)-(a.sortOrder??0);if(A!==0)return A;if(r.createdAt&&a.createdAt&&r.createdAt!==a.createdAt)return r.createdAt-a.createdAt;const w=r.accountName.localeCompare(a.accountName);return w!==0?w:r.accountId.localeCompare(a.accountId)})}else if(m==="quota-asc"){const t=r=>r.quotas.length===0?Number.POSITIVE_INFINITY:Math.min(...r.quotas.map(a=>a.remainingPercentage));s.sort((r,a)=>{const i=t(r)-t(a);if(i!==0)return i;const N=r.providerId.localeCompare(a.providerId);if(N!==0)return N;const A=(r.sortOrder??0)-(a.sortOrder??0);if(A!==0)return A;if(r.createdAt&&a.createdAt&&r.createdAt!==a.createdAt)return r.createdAt-a.createdAt;const w=r.accountName.localeCompare(a.accountName);return w!==0?w:r.accountId.localeCompare(a.accountId)})}else if(m==="quota-desc"){const t=r=>r.quotas.length===0?Number.NEGATIVE_INFINITY:Math.max(...r.quotas.map(a=>a.remainingPercentage));s.sort((r,a)=>{const i=t(a)-t(r);if(i!==0)return i;const N=r.providerId.localeCompare(a.providerId);if(N!==0)return N;const A=(r.sortOrder??0)-(a.sortOrder??0);if(A!==0)return A;if(r.createdAt&&a.createdAt&&r.createdAt!==a.createdAt)return r.createdAt-a.createdAt;const w=r.accountName.localeCompare(a.accountName);return w!==0?w:r.accountId.localeCompare(a.accountId)})}return s},[n,d,f,m,o]),{accountsWithData:q,accountsWithoutData:O}=x.useMemo(()=>{const s=[],t=[];for(const r of L)Array.isArray(r.quotas)&&r.quotas.length>0||r.error?s.push(r):t.push(r);return{accountsWithData:s,accountsWithoutData:t}},[L]),J=s=>{u(s);try{localStorage.setItem(_,s)}catch{}};return e.jsxs("div",{className:"space-y-6 w-full px-2 sm:px-4 pb-16 animate-rt-fade-in",children:[e.jsx(oe,{providers:H,selectedProvider:d,onSelectProvider:g,statusFilter:f,onSelectStatusFilter:y,sortMode:m,onSelectSortMode:J,autoRefresh:j,onToggleAutoRefresh:p,countdownSeconds:$,isRefreshingAll:v,onRefreshAll:Q,onTurnOffEmpty:U,onTurnOnAvailable:z}),l?e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(400px,1fr))] gap-4 w-full",children:[...Array(6)].map((s,t)=>e.jsxs("div",{className:"bg-[#0F1420]/80 border border-[#1E293B] rounded-2xl p-5 space-y-4 animate-pulse shadow-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 bg-slate-800 rounded-xl"}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx("div",{className:"h-4 bg-slate-800 rounded w-1/2"}),e.jsx("div",{className:"h-3 bg-slate-800 rounded w-3/4"})]})]}),e.jsxs("div",{className:"space-y-3 pt-2",children:[e.jsx("div",{className:"h-3 bg-slate-800 rounded w-full"}),e.jsx("div",{className:"h-2 bg-slate-800 rounded-full w-full"}),e.jsx("div",{className:"h-3 bg-slate-800 rounded w-5/6"}),e.jsx("div",{className:"h-2 bg-slate-800 rounded-full w-full"})]})]},t))}):L.length===0?e.jsxs("div",{className:"p-12 text-center rounded-2xl bg-[#0F1420]/50 border border-[#1E293B] text-slate-400 space-y-3",children:[e.jsx("span",{className:"material-symbols-outlined text-[36px] text-slate-500",children:"account_balance_wallet"}),e.jsx("div",{className:"text-sm font-medium text-slate-300",children:"No matching accounts found"}),e.jsx("p",{className:"text-xs text-slate-500 max-w-sm mx-auto",children:n.length===0?"Connect provider accounts in the Providers tab to track real-time quota.":"Try adjusting your provider, status, or search filters above."})]}):e.jsxs("div",{className:"space-y-8 w-full",children:[q.length>0&&e.jsxs("div",{className:"space-y-3",children:[O.length>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-slate-300",children:[e.jsx("span",{className:"size-2 rounded-full bg-emerald-400"}),e.jsxs("span",{children:["Accounts With Quota (",q.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(400px,1fr))] gap-4 w-full",children:q.map(s=>e.jsx(P,{account:s,onRefresh:R,onEdit:t=>I({id:t.accountId,providerId:t.providerId,name:t.accountName,isActive:t.isActive,providerSpecificData:t.providerSpecificData}),onToggle:M},s.accountId))})]}),O.length>0&&e.jsxs("div",{className:`space-y-3 ${q.length>0?"pt-6 border-t border-[#1E293B]/70":""}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pb-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-slate-400",children:[e.jsx("span",{className:"size-2 rounded-full bg-slate-500"}),e.jsxs("span",{children:["Accounts Without Quota Data (",O.length,")"]})]}),e.jsx("span",{className:"text-[11px] text-slate-500 font-mono",children:"No active quota or unsupported metrics"})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(400px,1fr))] gap-4 w-full",children:O.map(s=>e.jsx(P,{account:s,onRefresh:R,onEdit:t=>I({id:t.accountId,providerId:t.providerId,name:t.accountName,isActive:t.isActive,providerSpecificData:t.providerSpecificData}),onToggle:M},s.accountId))})]})]}),e.jsx(K,{isOpen:!!C,account:C,onClose:()=>I(null),onSave:G}),T&&e.jsx(X,{isOpen:T.isOpen,title:T.title,message:T.message,variant:T.variant,confirmText:T.confirmText,onConfirm:T.onConfirm,onCancel:()=>E(null)})]})};export{pe as QuotaTab};
1
+ import{j as e,r as x}from"./vendor-BcOI2aZ9.js";import{g as D}from"./metadataRegistry-NuDSSkP9.js";import{T as V}from"./ToolIcon-Cp4gSgFt.js";import{S as F}from"./Select-BNRH8LIG.js";import{C as Y,E as K}from"./EditAccountModal-CAg-yIOn.js";import{C as X}from"./ConfirmModal-OWeauwYv.js";import"./index-CKuvklEr.js";import"./lucide-Cc35htxl.js";const Z={antigravity:["Gemini (5h)","Gemini (Weekly)","Claude & GPT (5h)","Claude & GPT (Weekly)","Gemini 4 Argon (Weekly)"],github:["Chat","Completions","Premium Interactions"],copilot:["Chat","Completions","Premium Interactions"],claude:["5-Hour Window","5h Session","Session","7-Day Window","Weekly"],codex:["Session","Weekly","Credits","Balance"],openai:["Session","Weekly","Credits","Balance"],gemini:["Requests (RPM)","Requests (Daily)","Tokens (TPM)","Tokens (Daily)"],"gemini-cli":["Gemini (5h)","Gemini (Weekly)","Requests (RPM)","Requests (Daily)","Tokens (TPM)","Tokens (Daily)"],grok:["Session","Weekly","Requests","Tokens","Balance"],"grok-cli":["Session","Weekly","Requests","Tokens","Balance"],kiro:["Session","Weekly","Monthly","Credits"],deepseek:["Balance","Total Grants","Topped-up Balance"],minimax:["Coding Tokens","Standard Tokens","Balance"],"minimax-cn":["Coding Tokens","Standard Tokens","Balance"],glm:["Session","Weekly","Balance"],"glm-cn":["Session","Weekly","Balance"],qoder:["Daily","Weekly","Monthly","Balance"],"qoder-cn":["Daily","Weekly","Monthly","Balance"],xkiro:["Session (5h)","Weekly (7d)","Free Tokens (Daily)","Wallet Balance"],"xiaomi-tokenplan":["Monthly Tokens","Weekly Quota"],xmtp:["Monthly Tokens","Weekly Quota"],"xiaomi-mimo":["Monthly Tokens","Weekly Quota"],mimo:["Monthly Tokens","Weekly Quota"]},ee=new Proxy(Z,{get(o,n){if(typeof n!="string")return;const c=n.toLowerCase(),l=D(c);return l!=null&&l.quotaOrder?l.quotaOrder:o[c]},has(o,n){if(typeof n!="string")return!1;const c=n.toLowerCase(),l=D(c);return!!(l!=null&&l.quotaOrder)||c in o}});function te(o,n){if(!n||n.length<=1)return n?[...n]:[];const c=(o||"").toLowerCase(),l=D(c),h=(l==null?void 0:l.quotaOrder)||ee[c]||[];return[...n].sort((v,b)=>{const d=y=>{const m=(y||"").trim().toLowerCase(),u=h.findIndex(j=>{const p=j.toLowerCase();return m===p||m.startsWith(p)||p.startsWith(m)||m.includes(p)});return u===-1?9999:u},g=d(v.label),f=d(b.label);return g!==f?g-f:(v.label||"").localeCompare(b.label||"")})}function re(o,n,c,l){const h=c.toLowerCase(),v=(l==null?void 0:l.toLowerCase())==="kiro",b=h.includes("token"),d=h.includes("credit")||v&&!h.includes("request");if(b){if(n>=1e9){const g=`${(n/1e9).toFixed(1)}B`;return`${o>=1e9?`${(o/1e9).toFixed(2)}B`:o>=1e6?`${(o/1e6).toFixed(1)}M`:o.toLocaleString()} / ${g} tokens`}if(n>=1e6){const g=`${(n/1e6).toFixed(0)}M`;return`${o>=1e6?`${(o/1e6).toFixed(2)}M`:o.toLocaleString()} / ${g} tokens`}return n>0?`${o.toLocaleString()} / ${n.toLocaleString()} tokens`:`${o.toLocaleString()} tokens`}if(d){const g=n===1?"credit":"credits";return n>0?`${o.toLocaleString()} / ${n.toLocaleString()} ${g}`:`${o.toLocaleString()} ${g}`}return n===100&&!h.includes("req")?`${o}% used`:n>0?`${o.toLocaleString()} / ${n.toLocaleString()} reqs`:`${o.toLocaleString()} reqs`}const se=({label:o,used:n,total:c,percentage:l,resetInText:h="-",unlimited:v=!1,recurring:b=!0,providerId:d})=>{const f=(m=>m>=50?{text:"text-emerald-400",bg:"bg-emerald-500",bgTrack:"bg-emerald-500/15",emoji:"🟢"}:m>0?{text:"text-amber-400",bg:"bg-amber-500",bgTrack:"bg-amber-500/15",emoji:"🟡"}:{text:"text-red-400",bg:"bg-red-500",bgTrack:"bg-red-500/15",emoji:"🔴"})(l),y=b?"Reset":"Expires";return e.jsxs("div",{className:"space-y-1.5 py-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-medium text-slate-200 truncate pr-2",title:o,children:o}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("span",{className:"text-[10px]",children:f.emoji}),e.jsx("span",{className:`font-semibold ${f.text}`,children:v?"100%":`${l}%`})]})]}),!v&&e.jsx("div",{className:`h-2 rounded-full overflow-hidden ${f.bgTrack} w-full`,children:e.jsx("div",{className:`h-full transition-all duration-300 rounded-full ${f.bg}`,style:{width:`${Math.min(100,Math.max(0,l))}%`}})}),e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-slate-400",children:[e.jsx("span",{children:v?"Unlimited":re(n,c,o,d)}),h&&h!=="-"&&e.jsxs("div",{className:"flex items-center gap-1 font-mono text-[10px] text-slate-400",children:[e.jsx("span",{children:"•"}),e.jsxs("span",{children:[y," in ",h]})]})]})]})},ae={antigravity:"#4285F4",gemini:"#1A73E8","gemini-cli":"#1A73E8",claude:"#D97757",codex:"#10A37F",openai:"#10A37F",github:"#24292F",copilot:"#24292F",kiro:"#FF9900",deepseek:"#4D6BFE",grok:"#E11D48","grok-cli":"#E11D48",minimax:"#7C3AED","minimax-cn":"#7C3AED",qoder:"#EC4899","qoder-cn":"#EC4899",glm:"#0055FF","glm-cn":"#0055FF"},P=({account:o,loading:n=!1,onRefresh:c,onEdit:l,onToggle:h})=>{const[v,b]=x.useState(!1),d=D(o.providerId),g=(d==null?void 0:d.color)||ae[o.providerId.toLowerCase()]||"#3B82F6",f=async()=>{if(!(v||n)){b(!0);try{await c(o.accountId)}finally{b(!1)}}},y=n||v,m=x.useMemo(()=>{var p;let u=o.quotas||[];const j=(p=o.providerId)==null?void 0:p.toLowerCase();if(j==="antigravity"||j==="gemini-cli"){const $=["gemini (5h)","gemini (weekly)","claude & gpt (5h)","claude & gpt (weekly)","gemini 4 argon (weekly)"],S=u.filter(C=>$.some(I=>(C.label||"").toLowerCase().trim()===I));S.length>0&&(u=S)}return te(o.providerId,u)},[o.providerId,o.quotas]);return e.jsxs("div",{className:`flex flex-col justify-between bg-[#0F1420]/80 border border-[#1E293B] hover:border-slate-700/80 rounded-2xl p-4 sm:p-5 transition-all duration-200 shadow-lg min-w-[400px] ${o.isActive?"":"opacity-60 bg-[#0B0E17]/60"}`,children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 pb-3 border-b border-[#1E293B]/70",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(V,{src:(d==null?void 0:d.image)||`/assets/providers/${o.providerId}/icon.png`,name:o.providerId,color:g,iconBg:d==null?void 0:d.iconBg,size:"md"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-slate-100 text-xs sm:text-sm capitalize truncate",children:o.providerId}),o.plan&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-md font-medium bg-blue-500/10 text-blue-400 border border-blue-500/20",children:o.plan})]}),e.jsx("div",{className:"text-[11px] text-slate-400 truncate max-w-[170px]",title:o.accountName,children:o.accountName})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:f,disabled:y,title:"Refresh Quota",className:"p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-[#1E293B]/70 transition-colors disabled:opacity-50 cursor-pointer",children:e.jsx("span",{className:`material-symbols-outlined text-[18px] ${y?"animate-spin text-blue-400":""}`,children:"refresh"})}),e.jsx("button",{onClick:()=>l(o),title:"Edit Account",className:"p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-[#1E293B]/70 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"edit"})}),e.jsxs("label",{className:"relative inline-flex items-center cursor-pointer ml-1",title:"Toggle active status",children:[e.jsx("input",{type:"checkbox",checked:o.isActive,onChange:u=>h(o.accountId,u.target.checked),className:"sr-only peer"}),e.jsx("div",{className:"w-8 h-4.5 bg-slate-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-3.5 after:w-3.5 after:transition-all peer-checked:bg-blue-600"})]})]})]}),y&&m.length===0?e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx("div",{className:"h-4 bg-slate-800/60 rounded animate-pulse w-3/4"}),e.jsx("div",{className:"h-2 bg-slate-800/60 rounded-full animate-pulse w-full"}),e.jsx("div",{className:"h-4 bg-slate-800/60 rounded animate-pulse w-2/3"}),e.jsx("div",{className:"h-2 bg-slate-800/60 rounded-full animate-pulse w-full"})]}):m.length>0?e.jsx("div",{className:"space-y-2.5",children:m.map((u,j)=>e.jsx(se,{label:u.label,used:u.used,total:u.total,percentage:u.remainingPercentage,resetInText:u.resetInText,unlimited:u.unlimited,recurring:u.recurring,providerId:o.providerId},`${u.label}-${j}`))}):e.jsx("div",{className:"py-4 text-center text-xs text-slate-400 bg-[#0A0D14]/50 rounded-xl border border-[#1E293B]/50 px-3",children:o.error?e.jsx("span",{className:"text-red-400/90",children:o.error}):o.message||"No quota data available."})]}),e.jsxs("div",{className:"pt-3 mt-2 border-t border-[#1E293B]/50 flex items-center justify-between text-[10px] text-slate-500 font-mono",children:[e.jsx("span",{children:o.isActive?e.jsx("span",{className:"text-emerald-400 font-medium",children:"Active"}):e.jsx("span",{className:"text-slate-400",children:"Inactive"})}),o.lastFetchedAt&&e.jsxs("span",{children:["Updated ",new Date(o.lastFetchedAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})]})]})]})},oe=({providers:o,selectedProvider:n,onSelectProvider:c,statusFilter:l,onSelectStatusFilter:h,sortMode:v,onSelectSortMode:b,autoRefresh:d,onToggleAutoRefresh:g,countdownSeconds:f,isRefreshingAll:y,onRefreshAll:m,onTurnOffEmpty:u,onTurnOnAvailable:j})=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 text-xs p-4 rounded-2xl bg-[#0F1420]/80 border border-[#1E293B] shadow-lg w-full",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[e.jsx(F,{value:n,onChange:c,options:[{value:"all",label:"All providers"},...o.map(p=>({value:p,label:p.toUpperCase()}))],className:"min-w-[140px]"}),e.jsx(F,{value:l,onChange:p=>h(p),options:[{value:"all",label:"All accounts"},{value:"active",label:"Active only"},{value:"inactive",label:"Turned off"}],className:"min-w-[130px]"}),e.jsx(F,{value:v,onChange:p=>b(p),options:[{value:"fixed",label:"Fixed order (Providers)"},{value:"expiring-first",label:"Expiring first"},{value:"quota-asc",label:"% Quota: low to high"},{value:"quota-desc",label:"% Quota: high to low"}],className:"min-w-[175px]"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[e.jsxs("button",{onClick:u,title:"Turn off all accounts with depleted (0%) quota",className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-red-500/20 bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer font-medium active:scale-95",children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"block"}),"Turn off Empty"]}),e.jsxs("button",{onClick:j,title:"Turn on accounts with available (>0%) quota",className:"flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-emerald-500/20 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20 transition-colors cursor-pointer font-medium active:scale-95",children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"check_circle"}),"Turn on Available"]}),e.jsxs("div",{className:"flex items-center gap-2 bg-[#0A0D14] border border-[#1E293B] px-3 py-1.5 rounded-xl select-none",children:[e.jsx(Y,{size:"sm",checked:d,onChange:p=>g(p),label:"Autorefresh"}),d&&e.jsxs("span",{className:"font-mono text-[10px] text-blue-400 font-semibold bg-blue-500/10 px-1.5 py-0.5 rounded border border-blue-500/20",children:[f,"s"]})]}),e.jsx("button",{onClick:m,disabled:y,title:"Refresh all quotas",className:"p-1.5 rounded-xl border border-[#1E293B] bg-[#0A0D14] text-slate-400 hover:text-white hover:border-slate-600 transition-colors cursor-pointer disabled:opacity-50",children:e.jsx("span",{className:`material-symbols-outlined text-[17px] ${y?"animate-spin text-blue-400":""}`,children:"refresh"})})]})]}),B=60,W="mapigate_cached_quota_accounts",_="mapigate_quota_sort_mode",pe=({searchQuery:o=""})=>{const[n,c]=x.useState(()=>{try{const s=localStorage.getItem(W);if(s){const r=JSON.parse(s);if(Array.isArray(r)&&r.length>0)return r}}catch{}return[]}),[l,h]=x.useState(()=>n.length===0),[v,b]=x.useState(!1),[d,g]=x.useState("all"),[f,y]=x.useState("all"),[m,u]=x.useState(()=>{try{const s=localStorage.getItem(_);if(s==="fixed"||s==="expiring-first"||s==="quota-asc"||s==="quota-desc")return s}catch{}return"fixed"}),[j,p]=x.useState(!0),[$,S]=x.useState(B),[C,I]=x.useState(null),[T,E]=x.useState(null),k=x.useCallback(async(s=!1)=>{try{s&&b(!0);const t=await fetch(s?"/api/quota?force=true":"/api/quota");if(!t.ok)throw new Error(`HTTP error ${t.status}`);const a=await t.json();c(a);try{localStorage.setItem(W,JSON.stringify(a))}catch{}}catch(r){console.error("[QuotaTab] Failed to fetch quotas:",r)}finally{h(!1),b(!1)}},[]);x.useEffect(()=>{k(!1).then(()=>{k(!0)})},[k]),x.useEffect(()=>{if(!j)return;const s=setInterval(()=>{document.hidden||S(r=>r<=1?(k(!1),B):r-1)},1e3);return()=>clearInterval(s)},[j,k]);const Q=async()=>{b(!0),S(B),await k(!0)},R=async s=>{try{const r=await fetch(`/api/quota/${s}`);if(!r.ok)throw new Error(`HTTP error ${r.status}`);const t=await r.json();c(a=>a.map(i=>i.accountId===s?{...i,...t,sortOrder:i.sortOrder??t.sortOrder,createdAt:i.createdAt??t.createdAt}:i))}catch(r){console.error(`[QuotaTab] Failed to refresh account ${s}:`,r)}},M=async(s,r)=>{c(t=>t.map(a=>a.accountId===s?{...a,isActive:r}:a));try{(await fetch(`/api/quota/accounts/${s}/toggle`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:r})})).ok||c(a=>a.map(i=>i.accountId===s?{...i,isActive:!r}:i))}catch{c(t=>t.map(a=>a.accountId===s?{...a,isActive:!r}:a))}},G=async s=>{if(!C)return;const r=await fetch(`/api/quota/accounts/${C.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const a=await r.json().catch(()=>({}));throw new Error(a.error||"Failed to update account.")}const{account:t}=await r.json();t?c(a=>a.map(i=>i.accountId===C.id?t:i)):await k(!0)},U=()=>{const s=n.filter(r=>r.isActive&&r.quotas.length>0&&r.quotas.some(t=>!t.unlimited&&t.remainingPercentage===0));if(s.length===0){alert("No active accounts with depleted (0%) quota found.");return}E({isOpen:!0,title:"Turn off Depleted Accounts",message:`Are you sure you want to turn off ${s.length} account(s) with 0% quota? This will prevent upstream 429 rate limit errors.`,variant:"danger",confirmText:`Turn off (${s.length})`,onConfirm:async()=>{const r=s.map(t=>t.accountId);c(t=>t.map(a=>r.includes(a.accountId)?{...a,isActive:!1}:a)),E(null);try{await fetch("/api/quota/toggle-batch",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountIds:r,isActive:!1})})}catch(t){console.error("[QuotaTab] Failed to turn off depleted accounts:",t)}}})},z=()=>{const s=n.filter(r=>!r.isActive&&r.quotas.length>0&&r.quotas.every(t=>t.unlimited||t.remainingPercentage>0));if(s.length===0){alert("No inactive accounts with available (>0%) quota found.");return}E({isOpen:!0,title:"Turn on Available Accounts",message:`Activate ${s.length} account(s) that have recovered capacity?`,variant:"emerald",confirmText:`Turn on (${s.length})`,onConfirm:async()=>{const r=s.map(t=>t.accountId);c(t=>t.map(a=>r.includes(a.accountId)?{...a,isActive:!0}:a)),E(null);try{await fetch("/api/quota/toggle-batch",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountIds:r,isActive:!0})})}catch(t){console.error("[QuotaTab] Failed to turn on available accounts:",t)}}})},H=x.useMemo(()=>{const s=new Set;return n.forEach(r=>{r.providerId&&s.add(r.providerId.toLowerCase())}),Array.from(s).sort()},[n]),L=x.useMemo(()=>{let s=[...n];if(d!=="all"&&(s=s.filter(r=>r.providerId.toLowerCase()===d.toLowerCase())),f==="active"?s=s.filter(r=>r.isActive):f==="inactive"&&(s=s.filter(r=>!r.isActive)),o.trim()){const r=o.toLowerCase().trim();s=s.filter(t=>t.accountName.toLowerCase().includes(r)||t.providerId.toLowerCase().includes(r)||t.accountId.toLowerCase().includes(r))}if(m==="fixed")s.sort((r,t)=>{const a=r.providerId.localeCompare(t.providerId);if(a!==0)return a;const i=(r.sortOrder??0)-(t.sortOrder??0);if(i!==0)return i;if(r.createdAt&&t.createdAt&&r.createdAt!==t.createdAt)return r.createdAt-t.createdAt;const N=r.accountName.localeCompare(t.accountName);return N!==0?N:r.accountId.localeCompare(t.accountId)});else if(m==="expiring-first"){const r=t=>{const a=t.quotas.map(i=>i.resetAt).filter(i=>typeof i=="number"&&i>0);return a.length>0?Math.min(...a):Number.POSITIVE_INFINITY};s.sort((t,a)=>{const i=r(t)-r(a);if(i!==0)return i;const N=t.providerId.localeCompare(a.providerId);if(N!==0)return N;const A=(t.sortOrder??0)-(a.sortOrder??0);if(A!==0)return A;if(t.createdAt&&a.createdAt&&t.createdAt!==a.createdAt)return t.createdAt-a.createdAt;const w=t.accountName.localeCompare(a.accountName);return w!==0?w:t.accountId.localeCompare(a.accountId)})}else if(m==="quota-asc"){const r=t=>t.quotas.length===0?Number.POSITIVE_INFINITY:Math.min(...t.quotas.map(a=>a.remainingPercentage));s.sort((t,a)=>{const i=r(t)-r(a);if(i!==0)return i;const N=t.providerId.localeCompare(a.providerId);if(N!==0)return N;const A=(t.sortOrder??0)-(a.sortOrder??0);if(A!==0)return A;if(t.createdAt&&a.createdAt&&t.createdAt!==a.createdAt)return t.createdAt-a.createdAt;const w=t.accountName.localeCompare(a.accountName);return w!==0?w:t.accountId.localeCompare(a.accountId)})}else if(m==="quota-desc"){const r=t=>t.quotas.length===0?Number.NEGATIVE_INFINITY:Math.max(...t.quotas.map(a=>a.remainingPercentage));s.sort((t,a)=>{const i=r(a)-r(t);if(i!==0)return i;const N=t.providerId.localeCompare(a.providerId);if(N!==0)return N;const A=(t.sortOrder??0)-(a.sortOrder??0);if(A!==0)return A;if(t.createdAt&&a.createdAt&&t.createdAt!==a.createdAt)return t.createdAt-a.createdAt;const w=t.accountName.localeCompare(a.accountName);return w!==0?w:t.accountId.localeCompare(a.accountId)})}return s},[n,d,f,m,o]),{accountsWithData:q,accountsWithoutData:O}=x.useMemo(()=>{const s=[],r=[];for(const t of L)Array.isArray(t.quotas)&&t.quotas.length>0||t.error?s.push(t):r.push(t);return{accountsWithData:s,accountsWithoutData:r}},[L]),J=s=>{u(s);try{localStorage.setItem(_,s)}catch{}};return e.jsxs("div",{className:"space-y-6 w-full px-2 sm:px-4 pb-16 animate-rt-fade-in",children:[e.jsx(oe,{providers:H,selectedProvider:d,onSelectProvider:g,statusFilter:f,onSelectStatusFilter:y,sortMode:m,onSelectSortMode:J,autoRefresh:j,onToggleAutoRefresh:p,countdownSeconds:$,isRefreshingAll:v,onRefreshAll:Q,onTurnOffEmpty:U,onTurnOnAvailable:z}),l?e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(400px,1fr))] gap-4 w-full",children:[...Array(6)].map((s,r)=>e.jsxs("div",{className:"bg-[#0F1420]/80 border border-[#1E293B] rounded-2xl p-5 space-y-4 animate-pulse shadow-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 bg-slate-800 rounded-xl"}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx("div",{className:"h-4 bg-slate-800 rounded w-1/2"}),e.jsx("div",{className:"h-3 bg-slate-800 rounded w-3/4"})]})]}),e.jsxs("div",{className:"space-y-3 pt-2",children:[e.jsx("div",{className:"h-3 bg-slate-800 rounded w-full"}),e.jsx("div",{className:"h-2 bg-slate-800 rounded-full w-full"}),e.jsx("div",{className:"h-3 bg-slate-800 rounded w-5/6"}),e.jsx("div",{className:"h-2 bg-slate-800 rounded-full w-full"})]})]},r))}):L.length===0?e.jsxs("div",{className:"p-12 text-center rounded-2xl bg-[#0F1420]/50 border border-[#1E293B] text-slate-400 space-y-3",children:[e.jsx("span",{className:"material-symbols-outlined text-[36px] text-slate-500",children:"account_balance_wallet"}),e.jsx("div",{className:"text-sm font-medium text-slate-300",children:"No matching accounts found"}),e.jsx("p",{className:"text-xs text-slate-500 max-w-sm mx-auto",children:n.length===0?"Connect provider accounts in the Providers tab to track real-time quota.":"Try adjusting your provider, status, or search filters above."})]}):e.jsxs("div",{className:"space-y-8 w-full",children:[q.length>0&&e.jsxs("div",{className:"space-y-3",children:[O.length>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-slate-300",children:[e.jsx("span",{className:"size-2 rounded-full bg-emerald-400"}),e.jsxs("span",{children:["Accounts With Quota (",q.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(400px,1fr))] gap-4 w-full",children:q.map(s=>e.jsx(P,{account:s,onRefresh:R,onEdit:r=>I({id:r.accountId,providerId:r.providerId,name:r.accountName,isActive:r.isActive,providerSpecificData:r.providerSpecificData}),onToggle:M},s.accountId))})]}),O.length>0&&e.jsxs("div",{className:`space-y-3 ${q.length>0?"pt-6 border-t border-[#1E293B]/70":""}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pb-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-slate-400",children:[e.jsx("span",{className:"size-2 rounded-full bg-slate-500"}),e.jsxs("span",{children:["Accounts Without Quota Data (",O.length,")"]})]}),e.jsx("span",{className:"text-[11px] text-slate-500 font-mono",children:"No active quota or unsupported metrics"})]}),e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(400px,1fr))] gap-4 w-full",children:O.map(s=>e.jsx(P,{account:s,onRefresh:R,onEdit:r=>I({id:r.accountId,providerId:r.providerId,name:r.accountName,isActive:r.isActive,providerSpecificData:r.providerSpecificData}),onToggle:M},s.accountId))})]})]}),e.jsx(K,{isOpen:!!C,account:C,onClose:()=>I(null),onSave:G}),T&&e.jsx(X,{isOpen:T.isOpen,title:T.title,message:T.message,variant:T.variant,confirmText:T.confirmText,onConfirm:T.onConfirm,onCancel:()=>E(null)})]})};export{pe as QuotaTab};
@@ -1 +1 @@
1
- import{r as t,j as e}from"./vendor-BcOI2aZ9.js";import{f as q,P as _,A as F,D as z,R as L}from"./index-C4NTQZ40.js";import{G as U}from"./lucide-Cc35htxl.js";const G=({mode:a,onClose:j,onSuccess:r})=>{const[u,v]=t.useState(""),[d,A]=t.useState(""),[k,m]=t.useState(""),[y,D]=t.useState(!1),[b,x]=t.useState(!1),[h,p]=t.useState(!1),[g,i]=t.useState(null),l=q(c=>c.checkAuth);if(!a)return null;const f=()=>{v(""),A(""),m(""),D(!1),x(!1),i(null),p(!1)},S=()=>{h||(f(),j())},M=async c=>{if(c.preventDefault(),i(null),a==="setup"||a==="change"){if(!d||d.length<4){i("New password must be at least 4 characters long");return}if(d!==k){i("Passwords do not match");return}}if((a==="change"||a==="remove")&&!u){i("Current password is required");return}p(!0);try{if(a==="setup"){const o=await F.setup(d);if(!o.success){i(o.error||"Failed to setup master password"),p(!1);return}}else if(a==="change"){const o=await F.changePassword(u,d);if(!o.success){i(o.error||"Failed to change master password"),p(!1);return}}else if(a==="remove"){const o=await F.removePassword(u);if(!o.success){i(o.error||"Failed to remove master password"),p(!1);return}}await l(),f(),j(),r==null||r()}catch(o){i(o.message||"An unexpected error occurred"),p(!1)}};return e.jsx(_,{isOpen:!!a,onClose:S,maxWidthClass:"max-w-md",children:e.jsxs("form",{onSubmit:M,className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`size-10 rounded-xl flex items-center justify-center shrink-0 border ${a==="remove"?"bg-rose-500/10 border-rose-500/30 text-rose-400":"bg-blue-500/10 border-blue-500/30 text-blue-400"}`,children:e.jsx("span",{className:"material-symbols-outlined text-[22px]",children:a==="remove"?"lock_open":a==="change"?"key":"lock"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:a==="setup"?"Set Master Password":a==="change"?"Change Master Password":"Remove Master Password"}),e.jsx("p",{className:"text-xs text-slate-400",children:a==="setup"?"Protect Mapigate dashboard and management APIs":a==="change"?"Update your existing dashboard password":"Disable authentication requirement"})]})]}),a==="remove"?e.jsxs("div",{className:"p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-xs text-rose-300 leading-relaxed space-y-1",children:[e.jsx("p",{className:"font-semibold",children:"Warning: Disabling Master Password"}),e.jsx("p",{className:"text-[11px] text-rose-200/80",children:"Anyone with access to this machine or network will be able to view and manage your AI providers, API keys, and configurations without logging in."})]}):e.jsx("div",{className:"p-3 rounded-xl bg-[#0A0D14] border border-[#1E293B] text-xs text-slate-300 leading-relaxed space-y-1",children:e.jsxs("p",{className:"text-slate-400 text-[11px]",children:["AI coding assistant proxy routes (",e.jsx("code",{className:"text-blue-400 font-mono",children:"/v1/*"}),") remain completely untouched and unauthenticated. Only web dashboard management is protected."]})}),e.jsxs("div",{className:"space-y-3 pt-1",children:[(a==="change"||a==="remove")&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[11px] font-semibold text-slate-300",children:"Current Master Password"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:y?"text":"password",value:u,onChange:c=>{v(c.target.value),g&&i(null)},placeholder:"Enter current password...",required:!0,className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30 transition-all font-mono"}),e.jsx("button",{type:"button",onClick:()=>D(!y),tabIndex:-1,className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:y?"visibility_off":"visibility"})})]})]}),(a==="setup"||a==="change")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[11px] font-semibold text-slate-300",children:a==="setup"?"Master Password":"New Master Password"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:b?"text":"password",value:d,onChange:c=>{A(c.target.value),g&&i(null)},placeholder:"At least 4 characters...",required:!0,minLength:4,className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30 transition-all font-mono"}),e.jsx("button",{type:"button",onClick:()=>x(!b),tabIndex:-1,className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:b?"visibility_off":"visibility"})})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-[11px] font-semibold text-slate-300",children:["Confirm ",a==="setup"?"Password":"New Password"]}),e.jsx("input",{type:b?"text":"password",value:k,onChange:c=>{m(c.target.value),g&&i(null)},placeholder:"Re-enter password...",required:!0,className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30 transition-all font-mono"})]})]})]}),g&&e.jsxs("div",{className:"p-2.5 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[15px] shrink-0 text-rose-400",children:"error"}),e.jsx("span",{children:g})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{type:"button",onClick:S,disabled:h,className:"rt-btn rt-btn--secondary text-xs py-2 px-4 cursor-pointer",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:h,className:`text-xs py-2 px-4 flex items-center gap-1.5 cursor-pointer font-semibold rounded-xl ${a==="remove"?"rt-btn rt-btn--danger":"rt-btn rt-btn--primary"}`,children:h?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px] animate-spin",children:"progress_activity"}),"Processing..."]}):a==="setup"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"lock"}),"Set Password"]}):a==="change"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"check"}),"Save Changes"]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"lock_open"}),"Remove Protection"]})})]})]})})},$=()=>{const[a,j]=t.useState(!1),[r,u]=t.useState(!1),[v,d]=t.useState(!1),[A,k]=t.useState(""),[m,y]=t.useState(!1),[D,b]=t.useState(null),[x,h]=t.useState(null),[p,g]=t.useState(""),[i,l]=t.useState("merge"),[f,S]=t.useState(!1),[M,c]=t.useState(null),[o,R]=t.useState(null),B=t.useRef(null),I=async()=>{y(!0),b(null);try{const n=await fetch("/api/settings/backup/export",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({includeCredentials:v,password:A.trim()||void 0})});if(!n.ok){const T=await n.json().catch(()=>({}));throw new Error(T.error||"Failed to generate backup")}const N=await n.json(),w=`mapigate-backup-${new Date().toISOString().split("T")[0]}.json`,s=new Blob([JSON.stringify(N,null,2)],{type:"application/json"}),E=URL.createObjectURL(s),P=document.createElement("a");P.href=E,P.download=w,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(E),j(!1),k("")}catch(n){b(n.message||"Export failed")}finally{y(!1)}},O=async()=>{if(x){S(!0),c(null),R(null);try{const n=await x.text();let N;try{N=JSON.parse(n)}catch{throw new Error("Selected file is not valid JSON.")}const C=await fetch("/api/settings/backup/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backup:N,password:p.trim()||void 0,mode:i})}),w=await C.json();if(!C.ok)throw new Error(w.error||"Failed to restore backup");R(`Restored ${w.restored.providersCount} providers, ${w.restored.accountsCount} accounts, ${w.restored.combosCount} combos, and ${w.restored.mappingsCount} model mappings!`),h(null),g(""),setTimeout(()=>{u(!1),R(null),window.location.reload()},2e3)}catch(n){c(n.message||"Import failed")}finally{S(!1)}}};return e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"settings_backup_restore"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Configuration Backup & Migration"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Export providers, combos, and model mappings to JSON or migrate to another machine"})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("button",{type:"button",onClick:()=>{b(null),j(!0)},className:"rt-btn rt-btn--secondary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"file_download"}),"Export Backup"]}),e.jsxs("button",{type:"button",onClick:()=>{c(null),R(null),u(!0)},className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"file_upload"}),"Import Backup"]})]})]}),e.jsx("p",{className:"text-xs text-slate-400 leading-relaxed",children:"Backups include all your custom providers, multi-model combos, global model aliases, per-tool mappings, and engine preferences. If credentials are included, they are safely encrypted with your password using AES-256-GCM."}),e.jsx(_,{isOpen:a,onClose:()=>!m&&j(!1),maxWidthClass:"max-w-md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 rounded-xl bg-emerald-500/15 border border-emerald-500/30 text-emerald-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[24px]",children:"file_download"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:"Export Configuration Backup"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Generate a portable JSON backup file"})]})]}),e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("label",{className:"flex items-start gap-2.5 cursor-pointer bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B]",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:n=>d(n.target.checked),className:"mt-0.5 rounded border-slate-700 text-blue-600 focus:ring-0 cursor-pointer"}),e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsx("span",{className:"font-semibold text-white block",children:"Include API Keys & Secrets"}),e.jsx("span",{className:"text-slate-400 text-[11px] block",children:"If unchecked, a zero-secrets template will be exported (safe for public sharing or team presets)."})]})]}),v&&e.jsxs("div",{className:"space-y-1.5 animate-rt-fade-in",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-300 block",children:"Encryption Password (Recommended)"}),e.jsx("input",{type:"password",value:A,onChange:n=>k(n.target.value),placeholder:"Enter a password to encrypt credentials",className:"rt-input w-full text-xs py-2 px-3"}),e.jsx("span",{className:"text-[11px] text-slate-500 block",children:"If set, API keys will be encrypted via AES-256-GCM and will require this password when importing."})]}),D&&e.jsx("div",{className:"p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300",children:D})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:()=>j(!1),disabled:m,className:"rt-btn rt-btn--secondary text-xs py-2 px-4",children:"Cancel"}),e.jsx("button",{onClick:I,disabled:m,className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-1.5",children:m?"Generating...":"Download JSON"})]})]})}),e.jsx(_,{isOpen:r,onClose:()=>!f&&u(!1),maxWidthClass:"max-w-md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 rounded-xl bg-blue-500/15 border border-blue-500/30 text-blue-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[24px]",children:"file_upload"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:"Import Configuration Backup"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Restore or migrate settings from a JSON file"})]})]}),e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{onClick:()=>{var n;return(n=B.current)==null?void 0:n.click()},className:"border-2 border-dashed border-[#1E293B] hover:border-blue-500/50 p-4 rounded-xl text-center cursor-pointer bg-[#0A0D14] space-y-1 transition-colors",children:[e.jsx("input",{ref:B,type:"file",accept:".json",className:"hidden",onChange:n=>{var C;const N=(C=n.target.files)==null?void 0:C[0];N&&h(N)}}),e.jsx("span",{className:"material-symbols-outlined text-[28px] text-blue-400",children:"upload_file"}),e.jsx("p",{className:"text-xs font-semibold text-white",children:x?x.name:"Click to select backup .json file"}),e.jsx("p",{className:"text-[11px] text-slate-500",children:x?`${(x.size/1024).toFixed(1)} KB`:"Supports any Mapigate backup export"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-300 block",children:"Decryption Password (If Encrypted)"}),e.jsx("input",{type:"password",value:p,onChange:n=>g(n.target.value),placeholder:"Enter password if backup was encrypted",className:"rt-input w-full text-xs py-2 px-3"})]}),e.jsxs("div",{className:"flex items-center justify-between bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B] text-xs",children:[e.jsx("span",{className:"text-slate-400",children:"Import Mode"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer text-slate-300",children:[e.jsx("input",{type:"radio",name:"importMode",value:"merge",checked:i==="merge",onChange:()=>l("merge"),className:"text-blue-600 focus:ring-0"}),"Merge"]}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer text-slate-300",children:[e.jsx("input",{type:"radio",name:"importMode",value:"overwrite",checked:i==="overwrite",onChange:()=>l("overwrite"),className:"text-blue-600 focus:ring-0"}),"Overwrite"]})]})]}),M&&e.jsx("div",{className:"p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300",children:M}),o&&e.jsxs("div",{className:"p-3 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-xs text-emerald-300 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"check_circle"}),e.jsx("span",{children:o})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:()=>u(!1),disabled:f,className:"rt-btn rt-btn--secondary text-xs py-2 px-4",children:"Cancel"}),e.jsx("button",{onClick:O,disabled:f||!x,className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-1.5",children:f?"Restoring...":"Restore Configuration"})]})]})})]})},V=({onRestartClick:a,onUpgradeClick:j})=>{const[r,u]=t.useState(null),[v,d]=t.useState(!1),[A,k]=t.useState(!1),[m,y]=t.useState(!1),[D,b]=t.useState(!1),[x,h]=t.useState(null),p=q(s=>s.isPasswordSet),[g,i]=t.useState(null),[l,f]=t.useState(null),[S,M]=t.useState(!1),[c,o]=t.useState(10),[R,B]=t.useState(!1),[I,O]=t.useState(!1),n=a||(()=>k(!0));t.useEffect(()=>{fetch("/api/settings/system-info").then(s=>s.json()).then(s=>{s&&(s.dbPath||s.dataDir)&&u(s)}).catch(()=>{}),fetch("/api/settings/autostart").then(s=>s.json()).then(s=>{s&&typeof s.enabled=="boolean"&&f(s)}).catch(()=>{}),fetch("/api/settings/logging").then(s=>s.json()).then(s=>{s&&typeof s.logRetentionDays=="number"&&o(s.logRetentionDays)}).catch(()=>{})},[]);const N=async()=>{if(!l||S)return;const s=!l.enabled;M(!0);try{const E=await fetch("/api/settings/autostart",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:s})});if(E.ok){const P=await E.json();f(T=>T?{...T,enabled:P.enabled}:P)}}catch{}finally{M(!1)}},C=async s=>{o(s),B(!0),O(!1);try{(await fetch("/api/settings/logging",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({logRetentionDays:s})})).ok&&(O(!0),setTimeout(()=>O(!1),2e3))}catch{}finally{B(!1)}},w=async()=>{y(!0),h(null);try{const s=await fetch("/api/server/shutdown",{method:"POST",headers:{"Content-Type":"application/json"}});if(s.ok)b(!0),d(!1);else{const E=await s.json().catch(()=>({}));h(E.error||"Failed to initiate server shutdown."),y(!1)}}catch{b(!0),d(!1)}};return D?e.jsx("div",{className:"w-full px-2 sm:px-4 py-8 animate-rt-fade-in",children:e.jsxs("div",{className:"max-w-xl mx-auto rt-card p-8 text-center space-y-4 border border-rose-500/20 bg-[#0F1420]",children:[e.jsx("div",{className:"size-14 mx-auto rounded-2xl bg-rose-500/10 border border-rose-500/30 text-rose-400 flex items-center justify-center",children:e.jsx("span",{className:"material-symbols-outlined text-[32px]",children:"power_off"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:"Mapigate Gateway Server Stopped"}),e.jsx("p",{className:"text-xs text-slate-400",children:"The local server has shut down and will no longer accept proxy requests."})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B] text-xs font-mono text-slate-300",children:["To restart, run in terminal: ",e.jsx("code",{className:"text-blue-400",children:"mpg"})," or ",e.jsx("code",{className:"text-blue-400",children:"mapigate start"})]}),e.jsx("p",{className:"text-[11px] text-slate-500",children:"You may now safely close this browser tab."})]})}):e.jsxs("div",{className:"w-full px-2 sm:px-4 space-y-6 animate-rt-fade-in pb-16",children:[e.jsxs("div",{className:"rt-card p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[22px]",children:"tune"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"System & Storage Preferences"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Local SQLite database and hardware encryption status"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 text-xs",children:[e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"App Version & Gateway"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("p",{className:"text-white font-mono font-semibold",children:["Mapigate v",(r==null?void 0:r.version)||"0.3.3"]}),(r==null?void 0:r.hasUpdate)&&r.latestVersion&&e.jsxs("button",{type:"button",onClick:j,className:"inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-md bg-amber-500/15 text-amber-300 border border-amber-500/35 font-mono font-semibold hover:bg-amber-500/25 transition-all cursor-pointer",title:`Upgrade to v${r.latestVersion}`,children:[e.jsxs("span",{children:["v",r.latestVersion]}),e.jsx("span",{className:"text-[9px] text-amber-400",children:"↑ Upgrade"})]})]}),e.jsxs("p",{className:"text-blue-400 font-mono text-[11px]",children:["Active on port ",(r==null?void 0:r.port)||z]})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"Storage Engine"}),e.jsx("p",{className:"text-white font-mono font-semibold",children:"SQLite WAL (node:sqlite)"}),e.jsx("p",{className:"text-slate-400 text-[11px]",children:"Concurrent read/write without locks"})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"Credential Vault"}),e.jsx("p",{className:"text-emerald-400 font-mono font-semibold",children:"AES-256-GCM Hardware-salted"}),e.jsx("p",{className:"text-slate-400 text-[11px]",children:"Tied to this machine ID"})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1 flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"Open Source"}),e.jsx("p",{className:"text-white font-mono font-semibold",children:"GitHub Repository"})]}),e.jsxs("a",{href:"https://github.com/joutvhu/mapigate",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-blue-400 hover:text-blue-300 text-[11px] font-medium hover:underline pt-1",children:[e.jsx(U,{className:"size-3.5"}),e.jsx("span",{children:"joutvhu/mapigate"}),e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:"open_in_new"})]})]})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] text-xs font-mono text-slate-300 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold block font-sans",children:"Local Data Directory:"}),(r==null?void 0:r.isDevelopmentMode)&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded bg-amber-500/10 border border-amber-500/30 text-amber-400 font-sans font-medium",children:"Development Mode (.mapigate local)"})]}),e.jsx("code",{className:"text-blue-400 block bg-[#0F1420] p-2.5 rounded-lg border border-[#1E293B] break-all select-all",children:(r==null?void 0:r.dbPath)||(r==null?void 0:r.dataDir)||"~/.mapigate/mapigate.sqlite"})]})]}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-purple-500/10 border border-purple-500/20 text-purple-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"rocket_launch"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"System Startup (Autostart on Boot)"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Launch Mapigate gateway automatically in the background on computer boot"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:N,disabled:S||!l,className:`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${l!=null&&l.enabled?"bg-blue-600":"bg-slate-700"}`,title:l!=null&&l.enabled?"Click to disable autostart":"Click to enable autostart",children:e.jsx("span",{className:`pointer-events-none inline-block size-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${l!=null&&l.enabled?"translate-x-5":"translate-x-0"}`})}),e.jsx("span",{className:`text-xs font-semibold ${l!=null&&l.enabled?"text-emerald-400":"text-slate-400"}`,children:l!=null&&l.enabled?"Enabled":"Disabled"})]})]}),e.jsxs("div",{className:"space-y-2 text-xs text-slate-400 leading-relaxed",children:[e.jsx("p",{children:"When enabled, Mapigate will automatically start as a silent background daemon with system tray icon whenever you log in to this computer. Coding assistants (Claude Code, Cursor, Cline, Copilot) can access AI endpoints without having to manually start the gateway."}),(l==null?void 0:l.targetPath)&&e.jsxs("div",{className:"bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B] text-slate-300 font-mono text-[11px] flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-slate-500 uppercase text-[10px] font-bold font-sans shrink-0",children:["Startup Target (",l.platform,"):"]}),e.jsx("code",{className:"text-blue-400 truncate select-all",children:l.targetPath})]})]})]}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-blue-500/20",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-blue-500/10 border border-blue-500/20 text-blue-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"lock"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Master Password Protection"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Lock the Web Dashboard and guard management REST APIs"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:p?e.jsxs("span",{className:"px-2.5 py-1 rounded-full text-[11px] font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-1.5",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-emerald-400 animate-pulse"}),"Protected"]}):e.jsx("span",{className:"px-2.5 py-1 rounded-full text-[11px] font-semibold bg-slate-500/10 text-slate-400 border border-slate-500/20 flex items-center gap-1.5",children:"Disabled (No Auth Required)"})})]}),e.jsx("p",{className:"text-xs text-slate-400 leading-relaxed",children:p?"Master Password protection is active. Accessing the Mapigate dashboard requires entering your password. AI coding assistant proxy endpoints (/v1/*) remain 100% unauthenticated and fast.":"By default, Mapigate requires no login. Set a master password if you want to protect your dashboard settings, provider credentials, and management APIs from unauthorized access."}),e.jsx("div",{className:"flex flex-wrap items-center gap-3 pt-1",children:p?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>i("change"),className:"rt-btn rt-btn--secondary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"key"}),"Change Password"]}),e.jsxs("button",{type:"button",onClick:()=>i("remove"),className:"rt-btn rt-btn--danger text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"lock_open"}),"Remove Password"]})]}):e.jsxs("button",{type:"button",onClick:()=>i("setup"),className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"lock"}),"Set Master Password"]})})]}),e.jsx($,{}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"database"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Usage & Request Log Retention"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Configure how long detailed request payloads and debug logs are kept"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:I&&e.jsxs("span",{className:"text-[11px] font-semibold text-emerald-400 animate-rt-fade-in flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"check_circle"}),"Saved"]})})]}),e.jsxs("div",{className:"space-y-3 text-xs text-slate-400 leading-relaxed",children:[e.jsx("p",{children:"Mapigate stores data in 3 tiers to maximize performance and prevent SQLite database bloat:"}),e.jsxs("ul",{className:"list-disc pl-5 space-y-1 text-slate-400 text-[11px]",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-white",children:"Tier 1 (Detailed Request Payloads):"})," Kept according to the retention window below for debugging and inspection."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-white",children:"Tier 2 (Daily Usage Analytics):"})," Compact daily rollups by model, provider, account, and API key kept for 365+ days."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-white",children:"Tier 3 (All-Time Totals):"})," Total tokens saved, aggregate request counts, and cost metrics kept permanently."]})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-slate-300 font-semibold block text-xs mb-2",children:"Detailed Request Log Retention Period:"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:[{label:"7 Days",value:7},{label:"10 Days (Default)",value:10},{label:"30 Days",value:30},{label:"90 Days",value:90},{label:"Keep All (No Auto-Prune)",value:0}].map(s=>e.jsx("button",{type:"button",disabled:R,onClick:()=>C(s.value),className:`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all cursor-pointer ${c===s.value?"bg-blue-600 text-white shadow-xs border border-blue-500":"bg-[#0A0D14] border border-[#1E293B] text-slate-400 hover:text-white hover:bg-slate-800"}`,children:s.label},s.value))})]})]})]}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-blue-500/10 border border-blue-500/20 text-blue-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"power_settings_new"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Gateway Server Control"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Manage running server lifecycle, hot restart, and daemon"})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("button",{type:"button",onClick:n,className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-2 font-semibold cursor-pointer",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"restart_alt"}),"Restart Gateway"]}),e.jsxs("button",{type:"button",onClick:()=>d(!0),className:"rt-btn rt-btn--danger text-xs py-2 px-4 flex items-center gap-2 cursor-pointer",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"power_settings_new"}),"Shutdown Server"]})]})]}),e.jsxs("p",{className:"text-xs text-slate-400 leading-relaxed",children:["Restarting the gateway applies any newly installed updates, re-initializes provider modules, and clears active sockets without needing to run terminal commands. Shutting down the server stops all active proxy routing, terminates the background process, and releases port ",(r==null?void 0:r.port)||z,"."]}),x&&e.jsx("div",{className:"p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300",children:x})]}),e.jsx(_,{isOpen:v,onClose:()=>!m&&d(!1),maxWidthClass:"max-w-md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 rounded-xl bg-rose-500/15 border border-rose-500/30 text-rose-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[24px]",children:"warning"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:"Shutdown Mapigate Gateway?"}),e.jsx("p",{className:"text-xs text-slate-400",children:"This will terminate the server process."})]})]}),e.jsxs("div",{className:"p-3.5 rounded-xl bg-[#0A0D14] border border-[#1E293B] text-xs text-slate-300 space-y-2 leading-relaxed",children:[e.jsx("p",{children:"Are you sure you want to shut down the server? Active connections from coding assistants (Claude Code, Cursor, Kiro, etc.) will be disconnected immediately."}),e.jsxs("p",{className:"text-slate-400 text-[11px]",children:["To restart later, run ",e.jsx("span",{className:"text-blue-400 font-mono",children:"mapigate"})," in your terminal."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:()=>d(!1),disabled:m,className:"rt-btn rt-btn--secondary text-xs py-2 px-4",children:"Cancel"}),e.jsx("button",{onClick:w,disabled:m,className:"rt-btn rt-btn--danger text-xs py-2 px-4 flex items-center gap-1.5",children:m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"animate-spin text-[14px]",children:"⠋"}),"Shutting Down..."]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"power_settings_new"}),"Confirm Shutdown"]})})]})]})}),e.jsx(G,{mode:g,onClose:()=>i(null)}),!a&&e.jsx(L,{isOpen:A,onClose:()=>k(!1)})]})};export{V as SettingsTab};
1
+ import{r as t,j as e}from"./vendor-BcOI2aZ9.js";import{f as q,P as _,A as F,D as z,R as L}from"./index-CKuvklEr.js";import{G as U}from"./lucide-Cc35htxl.js";const G=({mode:a,onClose:j,onSuccess:r})=>{const[u,v]=t.useState(""),[d,A]=t.useState(""),[k,m]=t.useState(""),[y,D]=t.useState(!1),[b,x]=t.useState(!1),[h,p]=t.useState(!1),[g,i]=t.useState(null),l=q(c=>c.checkAuth);if(!a)return null;const f=()=>{v(""),A(""),m(""),D(!1),x(!1),i(null),p(!1)},S=()=>{h||(f(),j())},M=async c=>{if(c.preventDefault(),i(null),a==="setup"||a==="change"){if(!d||d.length<4){i("New password must be at least 4 characters long");return}if(d!==k){i("Passwords do not match");return}}if((a==="change"||a==="remove")&&!u){i("Current password is required");return}p(!0);try{if(a==="setup"){const o=await F.setup(d);if(!o.success){i(o.error||"Failed to setup master password"),p(!1);return}}else if(a==="change"){const o=await F.changePassword(u,d);if(!o.success){i(o.error||"Failed to change master password"),p(!1);return}}else if(a==="remove"){const o=await F.removePassword(u);if(!o.success){i(o.error||"Failed to remove master password"),p(!1);return}}await l(),f(),j(),r==null||r()}catch(o){i(o.message||"An unexpected error occurred"),p(!1)}};return e.jsx(_,{isOpen:!!a,onClose:S,maxWidthClass:"max-w-md",children:e.jsxs("form",{onSubmit:M,className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`size-10 rounded-xl flex items-center justify-center shrink-0 border ${a==="remove"?"bg-rose-500/10 border-rose-500/30 text-rose-400":"bg-blue-500/10 border-blue-500/30 text-blue-400"}`,children:e.jsx("span",{className:"material-symbols-outlined text-[22px]",children:a==="remove"?"lock_open":a==="change"?"key":"lock"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:a==="setup"?"Set Master Password":a==="change"?"Change Master Password":"Remove Master Password"}),e.jsx("p",{className:"text-xs text-slate-400",children:a==="setup"?"Protect Mapigate dashboard and management APIs":a==="change"?"Update your existing dashboard password":"Disable authentication requirement"})]})]}),a==="remove"?e.jsxs("div",{className:"p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-xs text-rose-300 leading-relaxed space-y-1",children:[e.jsx("p",{className:"font-semibold",children:"Warning: Disabling Master Password"}),e.jsx("p",{className:"text-[11px] text-rose-200/80",children:"Anyone with access to this machine or network will be able to view and manage your AI providers, API keys, and configurations without logging in."})]}):e.jsx("div",{className:"p-3 rounded-xl bg-[#0A0D14] border border-[#1E293B] text-xs text-slate-300 leading-relaxed space-y-1",children:e.jsxs("p",{className:"text-slate-400 text-[11px]",children:["AI coding assistant proxy routes (",e.jsx("code",{className:"text-blue-400 font-mono",children:"/v1/*"}),") remain completely untouched and unauthenticated. Only web dashboard management is protected."]})}),e.jsxs("div",{className:"space-y-3 pt-1",children:[(a==="change"||a==="remove")&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[11px] font-semibold text-slate-300",children:"Current Master Password"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:y?"text":"password",value:u,onChange:c=>{v(c.target.value),g&&i(null)},placeholder:"Enter current password...",required:!0,className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30 transition-all font-mono"}),e.jsx("button",{type:"button",onClick:()=>D(!y),tabIndex:-1,className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:y?"visibility_off":"visibility"})})]})]}),(a==="setup"||a==="change")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[11px] font-semibold text-slate-300",children:a==="setup"?"Master Password":"New Master Password"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:b?"text":"password",value:d,onChange:c=>{A(c.target.value),g&&i(null)},placeholder:"At least 4 characters...",required:!0,minLength:4,className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30 transition-all font-mono"}),e.jsx("button",{type:"button",onClick:()=>x(!b),tabIndex:-1,className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors cursor-pointer",children:e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:b?"visibility_off":"visibility"})})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-[11px] font-semibold text-slate-300",children:["Confirm ",a==="setup"?"Password":"New Password"]}),e.jsx("input",{type:b?"text":"password",value:k,onChange:c=>{m(c.target.value),g&&i(null)},placeholder:"Re-enter password...",required:!0,className:"w-full bg-[#0A0D14] border border-[#1E293B] rounded-xl px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/30 transition-all font-mono"})]})]})]}),g&&e.jsxs("div",{className:"p-2.5 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[15px] shrink-0 text-rose-400",children:"error"}),e.jsx("span",{children:g})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{type:"button",onClick:S,disabled:h,className:"rt-btn rt-btn--secondary text-xs py-2 px-4 cursor-pointer",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:h,className:`text-xs py-2 px-4 flex items-center gap-1.5 cursor-pointer font-semibold rounded-xl ${a==="remove"?"rt-btn rt-btn--danger":"rt-btn rt-btn--primary"}`,children:h?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px] animate-spin",children:"progress_activity"}),"Processing..."]}):a==="setup"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"lock"}),"Set Password"]}):a==="change"?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"check"}),"Save Changes"]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"lock_open"}),"Remove Protection"]})})]})]})})},$=()=>{const[a,j]=t.useState(!1),[r,u]=t.useState(!1),[v,d]=t.useState(!1),[A,k]=t.useState(""),[m,y]=t.useState(!1),[D,b]=t.useState(null),[x,h]=t.useState(null),[p,g]=t.useState(""),[i,l]=t.useState("merge"),[f,S]=t.useState(!1),[M,c]=t.useState(null),[o,R]=t.useState(null),B=t.useRef(null),I=async()=>{y(!0),b(null);try{const n=await fetch("/api/settings/backup/export",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({includeCredentials:v,password:A.trim()||void 0})});if(!n.ok){const T=await n.json().catch(()=>({}));throw new Error(T.error||"Failed to generate backup")}const N=await n.json(),w=`mapigate-backup-${new Date().toISOString().split("T")[0]}.json`,s=new Blob([JSON.stringify(N,null,2)],{type:"application/json"}),E=URL.createObjectURL(s),P=document.createElement("a");P.href=E,P.download=w,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(E),j(!1),k("")}catch(n){b(n.message||"Export failed")}finally{y(!1)}},O=async()=>{if(x){S(!0),c(null),R(null);try{const n=await x.text();let N;try{N=JSON.parse(n)}catch{throw new Error("Selected file is not valid JSON.")}const C=await fetch("/api/settings/backup/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backup:N,password:p.trim()||void 0,mode:i})}),w=await C.json();if(!C.ok)throw new Error(w.error||"Failed to restore backup");R(`Restored ${w.restored.providersCount} providers, ${w.restored.accountsCount} accounts, ${w.restored.combosCount} combos, and ${w.restored.mappingsCount} model mappings!`),h(null),g(""),setTimeout(()=>{u(!1),R(null),window.location.reload()},2e3)}catch(n){c(n.message||"Import failed")}finally{S(!1)}}};return e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"settings_backup_restore"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Configuration Backup & Migration"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Export providers, combos, and model mappings to JSON or migrate to another machine"})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("button",{type:"button",onClick:()=>{b(null),j(!0)},className:"rt-btn rt-btn--secondary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"file_download"}),"Export Backup"]}),e.jsxs("button",{type:"button",onClick:()=>{c(null),R(null),u(!0)},className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"file_upload"}),"Import Backup"]})]})]}),e.jsx("p",{className:"text-xs text-slate-400 leading-relaxed",children:"Backups include all your custom providers, multi-model combos, global model aliases, per-tool mappings, and engine preferences. If credentials are included, they are safely encrypted with your password using AES-256-GCM."}),e.jsx(_,{isOpen:a,onClose:()=>!m&&j(!1),maxWidthClass:"max-w-md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 rounded-xl bg-emerald-500/15 border border-emerald-500/30 text-emerald-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[24px]",children:"file_download"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:"Export Configuration Backup"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Generate a portable JSON backup file"})]})]}),e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("label",{className:"flex items-start gap-2.5 cursor-pointer bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B]",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:n=>d(n.target.checked),className:"mt-0.5 rounded border-slate-700 text-blue-600 focus:ring-0 cursor-pointer"}),e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsx("span",{className:"font-semibold text-white block",children:"Include API Keys & Secrets"}),e.jsx("span",{className:"text-slate-400 text-[11px] block",children:"If unchecked, a zero-secrets template will be exported (safe for public sharing or team presets)."})]})]}),v&&e.jsxs("div",{className:"space-y-1.5 animate-rt-fade-in",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-300 block",children:"Encryption Password (Recommended)"}),e.jsx("input",{type:"password",value:A,onChange:n=>k(n.target.value),placeholder:"Enter a password to encrypt credentials",className:"rt-input w-full text-xs py-2 px-3"}),e.jsx("span",{className:"text-[11px] text-slate-500 block",children:"If set, API keys will be encrypted via AES-256-GCM and will require this password when importing."})]}),D&&e.jsx("div",{className:"p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300",children:D})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:()=>j(!1),disabled:m,className:"rt-btn rt-btn--secondary text-xs py-2 px-4",children:"Cancel"}),e.jsx("button",{onClick:I,disabled:m,className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-1.5",children:m?"Generating...":"Download JSON"})]})]})}),e.jsx(_,{isOpen:r,onClose:()=>!f&&u(!1),maxWidthClass:"max-w-md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 rounded-xl bg-blue-500/15 border border-blue-500/30 text-blue-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[24px]",children:"file_upload"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:"Import Configuration Backup"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Restore or migrate settings from a JSON file"})]})]}),e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{onClick:()=>{var n;return(n=B.current)==null?void 0:n.click()},className:"border-2 border-dashed border-[#1E293B] hover:border-blue-500/50 p-4 rounded-xl text-center cursor-pointer bg-[#0A0D14] space-y-1 transition-colors",children:[e.jsx("input",{ref:B,type:"file",accept:".json",className:"hidden",onChange:n=>{var C;const N=(C=n.target.files)==null?void 0:C[0];N&&h(N)}}),e.jsx("span",{className:"material-symbols-outlined text-[28px] text-blue-400",children:"upload_file"}),e.jsx("p",{className:"text-xs font-semibold text-white",children:x?x.name:"Click to select backup .json file"}),e.jsx("p",{className:"text-[11px] text-slate-500",children:x?`${(x.size/1024).toFixed(1)} KB`:"Supports any Mapigate backup export"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-300 block",children:"Decryption Password (If Encrypted)"}),e.jsx("input",{type:"password",value:p,onChange:n=>g(n.target.value),placeholder:"Enter password if backup was encrypted",className:"rt-input w-full text-xs py-2 px-3"})]}),e.jsxs("div",{className:"flex items-center justify-between bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B] text-xs",children:[e.jsx("span",{className:"text-slate-400",children:"Import Mode"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer text-slate-300",children:[e.jsx("input",{type:"radio",name:"importMode",value:"merge",checked:i==="merge",onChange:()=>l("merge"),className:"text-blue-600 focus:ring-0"}),"Merge"]}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer text-slate-300",children:[e.jsx("input",{type:"radio",name:"importMode",value:"overwrite",checked:i==="overwrite",onChange:()=>l("overwrite"),className:"text-blue-600 focus:ring-0"}),"Overwrite"]})]})]}),M&&e.jsx("div",{className:"p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300",children:M}),o&&e.jsxs("div",{className:"p-3 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-xs text-emerald-300 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"check_circle"}),e.jsx("span",{children:o})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:()=>u(!1),disabled:f,className:"rt-btn rt-btn--secondary text-xs py-2 px-4",children:"Cancel"}),e.jsx("button",{onClick:O,disabled:f||!x,className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-1.5",children:f?"Restoring...":"Restore Configuration"})]})]})})]})},V=({onRestartClick:a,onUpgradeClick:j})=>{const[r,u]=t.useState(null),[v,d]=t.useState(!1),[A,k]=t.useState(!1),[m,y]=t.useState(!1),[D,b]=t.useState(!1),[x,h]=t.useState(null),p=q(s=>s.isPasswordSet),[g,i]=t.useState(null),[l,f]=t.useState(null),[S,M]=t.useState(!1),[c,o]=t.useState(10),[R,B]=t.useState(!1),[I,O]=t.useState(!1),n=a||(()=>k(!0));t.useEffect(()=>{fetch("/api/settings/system-info").then(s=>s.json()).then(s=>{s&&(s.dbPath||s.dataDir)&&u(s)}).catch(()=>{}),fetch("/api/settings/autostart").then(s=>s.json()).then(s=>{s&&typeof s.enabled=="boolean"&&f(s)}).catch(()=>{}),fetch("/api/settings/logging").then(s=>s.json()).then(s=>{s&&typeof s.logRetentionDays=="number"&&o(s.logRetentionDays)}).catch(()=>{})},[]);const N=async()=>{if(!l||S)return;const s=!l.enabled;M(!0);try{const E=await fetch("/api/settings/autostart",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:s})});if(E.ok){const P=await E.json();f(T=>T?{...T,enabled:P.enabled}:P)}}catch{}finally{M(!1)}},C=async s=>{o(s),B(!0),O(!1);try{(await fetch("/api/settings/logging",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({logRetentionDays:s})})).ok&&(O(!0),setTimeout(()=>O(!1),2e3))}catch{}finally{B(!1)}},w=async()=>{y(!0),h(null);try{const s=await fetch("/api/server/shutdown",{method:"POST",headers:{"Content-Type":"application/json"}});if(s.ok)b(!0),d(!1);else{const E=await s.json().catch(()=>({}));h(E.error||"Failed to initiate server shutdown."),y(!1)}}catch{b(!0),d(!1)}};return D?e.jsx("div",{className:"w-full px-2 sm:px-4 py-8 animate-rt-fade-in",children:e.jsxs("div",{className:"max-w-xl mx-auto rt-card p-8 text-center space-y-4 border border-rose-500/20 bg-[#0F1420]",children:[e.jsx("div",{className:"size-14 mx-auto rounded-2xl bg-rose-500/10 border border-rose-500/30 text-rose-400 flex items-center justify-center",children:e.jsx("span",{className:"material-symbols-outlined text-[32px]",children:"power_off"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:"Mapigate Gateway Server Stopped"}),e.jsx("p",{className:"text-xs text-slate-400",children:"The local server has shut down and will no longer accept proxy requests."})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B] text-xs font-mono text-slate-300",children:["To restart, run in terminal: ",e.jsx("code",{className:"text-blue-400",children:"mpg"})," or ",e.jsx("code",{className:"text-blue-400",children:"mapigate start"})]}),e.jsx("p",{className:"text-[11px] text-slate-500",children:"You may now safely close this browser tab."})]})}):e.jsxs("div",{className:"w-full px-2 sm:px-4 space-y-6 animate-rt-fade-in pb-16",children:[e.jsxs("div",{className:"rt-card p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsx("span",{className:"material-symbols-outlined text-blue-400 text-[22px]",children:"tune"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"System & Storage Preferences"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Local SQLite database and hardware encryption status"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 text-xs",children:[e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"App Version & Gateway"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("p",{className:"text-white font-mono font-semibold",children:["Mapigate v",(r==null?void 0:r.version)||"0.3.3"]}),(r==null?void 0:r.hasUpdate)&&r.latestVersion&&e.jsxs("button",{type:"button",onClick:j,className:"inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-md bg-amber-500/15 text-amber-300 border border-amber-500/35 font-mono font-semibold hover:bg-amber-500/25 transition-all cursor-pointer",title:`Upgrade to v${r.latestVersion}`,children:[e.jsxs("span",{children:["v",r.latestVersion]}),e.jsx("span",{className:"text-[9px] text-amber-400",children:"↑ Upgrade"})]})]}),e.jsxs("p",{className:"text-blue-400 font-mono text-[11px]",children:["Active on port ",(r==null?void 0:r.port)||z]})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"Storage Engine"}),e.jsx("p",{className:"text-white font-mono font-semibold",children:"SQLite WAL (node:sqlite)"}),e.jsx("p",{className:"text-slate-400 text-[11px]",children:"Concurrent read/write without locks"})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"Credential Vault"}),e.jsx("p",{className:"text-emerald-400 font-mono font-semibold",children:"AES-256-GCM Hardware-salted"}),e.jsx("p",{className:"text-slate-400 text-[11px]",children:"Tied to this machine ID"})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] space-y-1 flex flex-col justify-between",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold",children:"Open Source"}),e.jsx("p",{className:"text-white font-mono font-semibold",children:"GitHub Repository"})]}),e.jsxs("a",{href:"https://github.com/joutvhu/mapigate",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-blue-400 hover:text-blue-300 text-[11px] font-medium hover:underline pt-1",children:[e.jsx(U,{className:"size-3.5"}),e.jsx("span",{children:"joutvhu/mapigate"}),e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:"open_in_new"})]})]})]}),e.jsxs("div",{className:"bg-[#0A0D14] p-4 rounded-xl border border-[#1E293B] text-xs font-mono text-slate-300 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-slate-500 uppercase text-[10px] font-bold block font-sans",children:"Local Data Directory:"}),(r==null?void 0:r.isDevelopmentMode)&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded bg-amber-500/10 border border-amber-500/30 text-amber-400 font-sans font-medium",children:"Development Mode (.mapigate local)"})]}),e.jsx("code",{className:"text-blue-400 block bg-[#0F1420] p-2.5 rounded-lg border border-[#1E293B] break-all select-all",children:(r==null?void 0:r.dbPath)||(r==null?void 0:r.dataDir)||"~/.mapigate/mapigate.sqlite"})]})]}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-purple-500/10 border border-purple-500/20 text-purple-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"rocket_launch"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"System Startup (Autostart on Boot)"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Launch Mapigate gateway automatically in the background on computer boot"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:N,disabled:S||!l,className:`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${l!=null&&l.enabled?"bg-blue-600":"bg-slate-700"}`,title:l!=null&&l.enabled?"Click to disable autostart":"Click to enable autostart",children:e.jsx("span",{className:`pointer-events-none inline-block size-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${l!=null&&l.enabled?"translate-x-5":"translate-x-0"}`})}),e.jsx("span",{className:`text-xs font-semibold ${l!=null&&l.enabled?"text-emerald-400":"text-slate-400"}`,children:l!=null&&l.enabled?"Enabled":"Disabled"})]})]}),e.jsxs("div",{className:"space-y-2 text-xs text-slate-400 leading-relaxed",children:[e.jsx("p",{children:"When enabled, Mapigate will automatically start as a silent background daemon with system tray icon whenever you log in to this computer. Coding assistants (Claude Code, Cursor, Cline, Copilot) can access AI endpoints without having to manually start the gateway."}),(l==null?void 0:l.targetPath)&&e.jsxs("div",{className:"bg-[#0A0D14] p-3 rounded-xl border border-[#1E293B] text-slate-300 font-mono text-[11px] flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-slate-500 uppercase text-[10px] font-bold font-sans shrink-0",children:["Startup Target (",l.platform,"):"]}),e.jsx("code",{className:"text-blue-400 truncate select-all",children:l.targetPath})]})]})]}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-blue-500/20",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-blue-500/10 border border-blue-500/20 text-blue-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"lock"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Master Password Protection"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Lock the Web Dashboard and guard management REST APIs"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:p?e.jsxs("span",{className:"px-2.5 py-1 rounded-full text-[11px] font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-1.5",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-emerald-400 animate-pulse"}),"Protected"]}):e.jsx("span",{className:"px-2.5 py-1 rounded-full text-[11px] font-semibold bg-slate-500/10 text-slate-400 border border-slate-500/20 flex items-center gap-1.5",children:"Disabled (No Auth Required)"})})]}),e.jsx("p",{className:"text-xs text-slate-400 leading-relaxed",children:p?"Master Password protection is active. Accessing the Mapigate dashboard requires entering your password. AI coding assistant proxy endpoints (/v1/*) remain 100% unauthenticated and fast.":"By default, Mapigate requires no login. Set a master password if you want to protect your dashboard settings, provider credentials, and management APIs from unauthorized access."}),e.jsx("div",{className:"flex flex-wrap items-center gap-3 pt-1",children:p?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>i("change"),className:"rt-btn rt-btn--secondary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"key"}),"Change Password"]}),e.jsxs("button",{type:"button",onClick:()=>i("remove"),className:"rt-btn rt-btn--danger text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"lock_open"}),"Remove Password"]})]}):e.jsxs("button",{type:"button",onClick:()=>i("setup"),className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-2 cursor-pointer font-semibold",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"lock"}),"Set Master Password"]})})]}),e.jsx($,{}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"database"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Usage & Request Log Retention"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Configure how long detailed request payloads and debug logs are kept"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:I&&e.jsxs("span",{className:"text-[11px] font-semibold text-emerald-400 animate-rt-fade-in flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"check_circle"}),"Saved"]})})]}),e.jsxs("div",{className:"space-y-3 text-xs text-slate-400 leading-relaxed",children:[e.jsx("p",{children:"Mapigate stores data in 3 tiers to maximize performance and prevent SQLite database bloat:"}),e.jsxs("ul",{className:"list-disc pl-5 space-y-1 text-slate-400 text-[11px]",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-white",children:"Tier 1 (Detailed Request Payloads):"})," Kept according to the retention window below for debugging and inspection."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-white",children:"Tier 2 (Daily Usage Analytics):"})," Compact daily rollups by model, provider, account, and API key kept for 365+ days."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-white",children:"Tier 3 (All-Time Totals):"})," Total tokens saved, aggregate request counts, and cost metrics kept permanently."]})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-slate-300 font-semibold block text-xs mb-2",children:"Detailed Request Log Retention Period:"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:[{label:"7 Days",value:7},{label:"10 Days (Default)",value:10},{label:"30 Days",value:30},{label:"90 Days",value:90},{label:"Keep All (No Auto-Prune)",value:0}].map(s=>e.jsx("button",{type:"button",disabled:R,onClick:()=>C(s.value),className:`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all cursor-pointer ${c===s.value?"bg-blue-600 text-white shadow-xs border border-blue-500":"bg-[#0A0D14] border border-[#1E293B] text-slate-400 hover:text-white hover:bg-slate-800"}`,children:s.label},s.value))})]})]})]}),e.jsxs("div",{className:"rt-card p-6 space-y-4 border border-[#1E293B]",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-[#1E293B]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-9 rounded-xl bg-blue-500/10 border border-blue-500/20 text-blue-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"power_settings_new"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-bold text-white",children:"Gateway Server Control"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Manage running server lifecycle, hot restart, and daemon"})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("button",{type:"button",onClick:n,className:"rt-btn rt-btn--primary text-xs py-2 px-4 flex items-center gap-2 font-semibold cursor-pointer",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"restart_alt"}),"Restart Gateway"]}),e.jsxs("button",{type:"button",onClick:()=>d(!0),className:"rt-btn rt-btn--danger text-xs py-2 px-4 flex items-center gap-2 cursor-pointer",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"power_settings_new"}),"Shutdown Server"]})]})]}),e.jsxs("p",{className:"text-xs text-slate-400 leading-relaxed",children:["Restarting the gateway applies any newly installed updates, re-initializes provider modules, and clears active sockets without needing to run terminal commands. Shutting down the server stops all active proxy routing, terminates the background process, and releases port ",(r==null?void 0:r.port)||z,"."]}),x&&e.jsx("div",{className:"p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300",children:x})]}),e.jsx(_,{isOpen:v,onClose:()=>!m&&d(!1),maxWidthClass:"max-w-md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-10 rounded-xl bg-rose-500/15 border border-rose-500/30 text-rose-400 flex items-center justify-center shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[24px]",children:"warning"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-bold text-white",children:"Shutdown Mapigate Gateway?"}),e.jsx("p",{className:"text-xs text-slate-400",children:"This will terminate the server process."})]})]}),e.jsxs("div",{className:"p-3.5 rounded-xl bg-[#0A0D14] border border-[#1E293B] text-xs text-slate-300 space-y-2 leading-relaxed",children:[e.jsx("p",{children:"Are you sure you want to shut down the server? Active connections from coding assistants (Claude Code, Cursor, Kiro, etc.) will be disconnected immediately."}),e.jsxs("p",{className:"text-slate-400 text-[11px]",children:["To restart later, run ",e.jsx("span",{className:"text-blue-400 font-mono",children:"mapigate"})," in your terminal."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:()=>d(!1),disabled:m,className:"rt-btn rt-btn--secondary text-xs py-2 px-4",children:"Cancel"}),e.jsx("button",{onClick:w,disabled:m,className:"rt-btn rt-btn--danger text-xs py-2 px-4 flex items-center gap-1.5",children:m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"animate-spin text-[14px]",children:"⠋"}),"Shutting Down..."]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"power_settings_new"}),"Confirm Shutdown"]})})]})]})}),e.jsx(G,{mode:g,onClose:()=>i(null)}),!a&&e.jsx(L,{isOpen:A,onClose:()=>k(!1)})]})};export{V as SettingsTab};
@@ -0,0 +1 @@
1
+ import{j as e,r as i,a as ie}from"./vendor-BcOI2aZ9.js";import{Z as ce,A as de,D as xe,a as me,S as Q,b as pe,N as Z,c as he,d as ue,R as be,C as ee,e as te,T as fe,L as je,f as J,g as V,X as se,h as ge,i as ve,j as Ne,k as ae,l as we,F as ye,m as le,n as ke,o as Ce,p as Se,q as Te}from"./lucide-Cc35htxl.js";import{T as W}from"./ToolIcon-Cp4gSgFt.js";import{g as X}from"./metadataRegistry-NuDSSkP9.js";import{R as Ee,A as Le,C as Re,X as $e,Y as qe,T as Me,a as Be}from"./recharts-X4_nm3od.js";import{a as Fe,A as De}from"./index-CKuvklEr.js";import{S as Y}from"./Select-BNRH8LIG.js";const Ae=({stats:t,loading:p})=>{const d=r=>(r||0).toLocaleString("en-US"),u=r=>`$${(r||0).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`,c=(t==null?void 0:t.totalRequests)??0,h=(t==null?void 0:t.totalPromptTokens)??0,o=(t==null?void 0:t.totalCachedTokens)??0,x=(t==null?void 0:t.totalCompletionTokens)??0,g=(t==null?void 0:t.totalCost)??0,s=(t==null?void 0:t.totalTokensSaved)??0;return e.jsxs("div",{className:"w-full grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4",children:[e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 flex flex-col justify-between hover:border-blue-500/30 transition-all shadow-xs",children:[e.jsxs("div",{className:"flex items-center justify-between text-slate-400 mb-2",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",children:"Total Requests"}),e.jsx(ce,{className:"w-4 h-4 text-blue-400"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-black text-white truncate",title:d(c),children:p?"...":d(c)}),e.jsx("span",{className:"text-[10px] text-slate-500 mt-0.5 block",children:"API Invocations"})]})]}),e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 flex flex-col justify-between hover:border-blue-500/30 transition-all shadow-xs",children:[e.jsxs("div",{className:"flex items-center justify-between text-blue-400 mb-2",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",children:"Input Tokens"}),e.jsx(de,{className:"w-4 h-4 text-blue-400"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-black text-blue-400 truncate",title:d(h),children:p?"...":d(h)}),e.jsx("span",{className:"text-[10px] text-slate-500 mt-0.5 block",children:"Prompt & context"})]})]}),e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 flex flex-col justify-between hover:border-cyan-500/30 transition-all shadow-xs",children:[e.jsxs("div",{className:"flex items-center justify-between text-cyan-400 mb-2",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",children:"Cached Tokens"}),e.jsx(xe,{className:"w-4 h-4 text-cyan-400"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-black text-cyan-400 truncate",title:d(o),children:p?"...":d(o)}),e.jsx("span",{className:"text-[10px] text-slate-500 mt-0.5 block",children:"Prompt cache hits"})]})]}),e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 flex flex-col justify-between hover:border-emerald-500/30 transition-all shadow-xs",children:[e.jsxs("div",{className:"flex items-center justify-between text-emerald-400 mb-2",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",children:"Output Tokens"}),e.jsx(me,{className:"w-4 h-4 text-emerald-400"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-black text-emerald-400 truncate",title:d(x),children:p?"...":d(x)}),e.jsx("span",{className:"text-[10px] text-slate-500 mt-0.5 block",children:"Generated output"})]})]}),e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 flex flex-col justify-between hover:border-purple-500/30 transition-all shadow-xs",children:[e.jsxs("div",{className:"flex items-center justify-between text-purple-400 mb-2",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",children:"Tokens Saved"}),e.jsx(Q,{className:"w-4 h-4 text-purple-400"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-black text-purple-400 truncate",title:d(s),children:p?"...":d(s)}),e.jsx("span",{className:"text-[10px] text-slate-500 mt-0.5 block",children:"Token Saver optimized"})]})]}),e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 flex flex-col justify-between hover:border-amber-500/30 transition-all shadow-xs",children:[e.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-2",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",children:"Est. Cost"}),e.jsx(pe,{className:"w-4 h-4 text-amber-400"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xl sm:text-2xl font-black text-amber-400 truncate",title:u(g),children:p?"...":`~${u(g)}`}),e.jsx("span",{className:"text-[10px] text-slate-500 mt-0.5 block",title:"Estimated, not actual billing",children:"Estimated, not actual"})]})]})]})},Pe={"github-copilot":"github",copilot:"github","devin-cli":"devin","devin-desktop":"devin","devin-cli-agentic":"devin",dvd:"devin"};function H(t){if(!t)return{id:"unknown",name:"Unknown",color:"#64748B"};const p=t.toLowerCase().trim(),d=Pe[p]||p,u=X(d)||X(p);return u?{id:u.id,name:u.name,color:u.color||"#64748B",image:u.image,iconBg:u.iconBg}:{id:t,name:t.charAt(0).toUpperCase()+t.slice(1),color:"#64748B"}}const Oe=5,Ue=({providers:t=[],activeRequests:p=[]})=>{const[d,u]=i.useState(null),[c,h]=i.useState(1),[o,x]=i.useState({x:0,y:0}),[g,s]=i.useState(!1),r=i.useRef({x:0,y:0}),k=i.useRef({x:0,y:0}),m=i.useRef(!1),C=i.useRef(null),B=i.useCallback(()=>{h(1),x({x:0,y:0})},[]),$=i.useCallback(()=>{h(a=>Math.min(2.5,+(a+.2).toFixed(2)))},[]),R=i.useCallback(()=>{h(a=>Math.max(.4,+(a-.2).toFixed(2)))},[]);i.useEffect(()=>{const a=C.current;if(!a)return;const N=b=>{if(!b.ctrlKey&&!b.metaKey)return;b.preventDefault();const j=b.deltaY<0?1.1:.9;h(w=>{const F=+(w*j).toFixed(2);return Math.min(2.5,Math.max(.4,F))})};return a.addEventListener("wheel",N,{passive:!1}),()=>{a.removeEventListener("wheel",N)}},[]);const T=i.useCallback(a=>{a.button===0&&(s(!0),m.current=!1,r.current={x:a.clientX,y:a.clientY},k.current={...o})},[o]);i.useEffect(()=>{const a=b=>{if(!g)return;const j=b.clientX-r.current.x,w=b.clientY-r.current.y;(Math.abs(j)>3||Math.abs(w)>3)&&(m.current=!0),x({x:k.current.x+j,y:k.current.y+w})},N=()=>{s(!1)};return g&&(window.addEventListener("mousemove",a),window.addEventListener("mouseup",N)),()=>{window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",N)}},[g]);const S=i.useMemo(()=>{const a=new Set;for(const N of p)if(N.provider){const b=N.provider.toLowerCase();a.add(b);const j=H(b);a.add(j.id.toLowerCase())}return a},[p]),{displayProviders:E,totalCount:L}=i.useMemo(()=>{const a=[...t];for(const j of p)j.provider&&a.push(j.provider);const b=Array.from(new Set(a)).filter(j=>{if(!j)return!1;const w=j.toLowerCase().trim();return w!=="unknown"&&w!=="null"&&w!=="undefined"}).sort((j,w)=>{const F=S.has(j.toLowerCase()),D=S.has(w.toLowerCase());return F&&!D?-1:!F&&D?1:j.localeCompare(w)});return{displayProviders:b.slice(0,10),totalCount:b.length}},[t,p,S]),y=400,n=220,v=i.useMemo(()=>{const a=E.length;if(a===0)return{items:[]};const N=Math.min(300,160+a*15),b=Math.min(150,90+a*8);return{items:E.map((w,F)=>{const D=H(w),q=S.has(w.toLowerCase())||S.has(D.id.toLowerCase()),A=(d==null?void 0:d.toLowerCase())===w.toLowerCase()||(d==null?void 0:d.toLowerCase())===D.id.toLowerCase(),P=-Math.PI/2+2*Math.PI*F/a,M=y+N*Math.cos(P),O=n+b*Math.sin(P),oe=Math.abs(M-y)<20,U=O<n?-1:1,re=M<y?-1:1;let I,_,K,z;if(oe)I=y,_=n+U*Math.min(b*.5,50),K=M,z=O-U*Math.min(b*.5,50);else{const G=Math.abs(Math.sin(P))>.35;I=G?y:y+(M-y)*.5,_=G?n+U*Math.min(b*.7,75):n,K=M-re*Math.min(N*.45,60),z=O}const ne=`M ${y} ${n} C ${I.toFixed(1)} ${_.toFixed(1)}, ${K.toFixed(1)} ${z.toFixed(1)}, ${M.toFixed(1)} ${O.toFixed(1)}`;return{id:w,meta:D,isActive:q,isFocused:A,px:M,py:O,pathData:ne}})}},[E,S,d]),l=p.length,f=l>0;return e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 sm:p-5 flex flex-col shadow-xs w-full",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Z,{className:"w-4 h-4 text-cyan-400"}),e.jsx("h3",{className:"text-sm sm:text-base font-bold text-white",children:"Active Routing Topology"}),e.jsx("span",{className:"text-xs text-slate-500",children:L>10?`(Top 10 of ${L} Mesh)`:"(Real-time Mesh)"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center bg-[#070A11] border border-[#1E293B] rounded-lg p-0.5 mr-1",title:"Ctrl + Scroll or use buttons to Zoom",children:[e.jsx("button",{type:"button",onClick:$,className:"p-1 hover:text-white text-slate-400 hover:bg-slate-800 rounded transition-colors cursor-pointer",title:"Zoom In","aria-label":"Zoom In",children:e.jsx(he,{className:"w-3.5 h-3.5"})}),e.jsxs("span",{className:"px-1.5 text-[10px] font-mono text-slate-400 select-none min-w-[34px] text-center",children:[Math.round(c*100),"%"]}),e.jsx("button",{type:"button",onClick:R,className:"p-1 hover:text-white text-slate-400 hover:bg-slate-800 rounded transition-colors cursor-pointer",title:"Zoom Out","aria-label":"Zoom Out",children:e.jsx(ue,{className:"w-3.5 h-3.5"})}),(c!==1||o.x!==0||o.y!==0)&&e.jsx("button",{type:"button",onClick:B,className:"p-1 hover:text-cyan-400 text-slate-400 hover:bg-slate-800 rounded transition-colors cursor-pointer ml-0.5 border-l border-[#1E293B]",title:"Reset View","aria-label":"Reset View",children:e.jsx(be,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-400",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-slate-600"}),e.jsx("span",{children:"Idle"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-cyan-400 font-semibold",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-cyan-400 animate-ping"}),e.jsx("span",{children:"Active Stream"})]})]})]}),e.jsx("div",{ref:C,onMouseDown:T,className:`relative h-72 sm:h-80 w-full rounded-lg overflow-hidden bg-[#070A11] border border-[#162032] flex items-center justify-center select-none ${g?"cursor-grabbing":"cursor-grab"}`,children:E.length===0?e.jsxs("div",{className:"text-center p-6 text-slate-500 text-xs sm:text-sm",children:[e.jsx(Z,{className:"w-8 h-8 text-slate-600 mx-auto mb-2 opacity-60"}),e.jsx("p",{children:"No upstream provider traffic recorded yet"})]}):e.jsxs("div",{className:"relative w-full h-full will-change-transform",style:{transform:`translate(${o.x}px, ${o.y}px) scale(${c})`,transformOrigin:"center center",transition:g?"none":"transform 0.15s ease-out"},children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full pointer-events-none",viewBox:"0 0 800 440",preserveAspectRatio:"xMidYMid meet",children:[e.jsx("defs",{children:e.jsxs("filter",{id:"plasma-glow",x:"-30%",y:"-30%",width:"160%",height:"160%",children:[e.jsx("feGaussianBlur",{stdDeviation:"3.5",result:"blur"}),e.jsx("feComposite",{in:"SourceGraphic",in2:"blur",operator:"over"})]})}),v.items.map(a=>a.isActive?e.jsxs("g",{children:[e.jsx("path",{d:a.pathData,fill:"none",stroke:"#22d3ee",strokeWidth:"6",strokeOpacity:"0.25",strokeLinecap:"round",filter:"url(#plasma-glow)"}),e.jsx("path",{d:a.pathData,fill:"none",stroke:"#38bdf8",strokeWidth:"2.5",strokeOpacity:"0.85",strokeLinecap:"round"}),e.jsx("path",{d:a.pathData,fill:"none",stroke:"#ffffff",strokeWidth:"1.2",strokeLinecap:"round"}),Array.from({length:Oe},(N,b)=>e.jsx("circle",{r:b%2===0?3.5:2,fill:b%2===0?"#22d3ee":"#ffffff",opacity:"0.9",children:e.jsx("animateMotion",{dur:`${.8+b*.15}s`,repeatCount:"indefinite",path:a.pathData,begin:`${b*.12}s`})},`orb-${a.id}-${b}`))]},`edge-active-${a.id}`):e.jsx("path",{d:a.pathData,fill:"none",stroke:"#1E293B",strokeWidth:"1.5",strokeDasharray:"4 5",strokeLinecap:"round"},`edge-${a.id}`))]}),e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:e.jsxs("svg",{className:"w-full h-full",viewBox:"0 0 800 440",preserveAspectRatio:"xMidYMid meet",children:[e.jsx("foreignObject",{x:y-80,y:n-26,width:"160",height:"54",className:"overflow-visible pointer-events-auto",children:e.jsxs("div",{className:`flex items-center justify-center gap-2.5 px-3.5 py-2.5 rounded-2xl border-2 transition-all duration-300 select-none ${f?"border-cyan-400 bg-gradient-to-br from-blue-900/80 via-cyan-900/50 to-blue-950 shadow-[0_0_24px_rgba(34,211,238,0.5)]":"border-blue-500/40 bg-[#0A0E18] shadow-lg"}`,children:[e.jsx(W,{src:"/favicon.svg",name:"Mapigate",color:"#38BDF8",size:"sm",fallback:e.jsx("span",{className:"material-symbols-outlined text-[18px] text-cyan-400",children:"graph_5"}),className:f?"shadow-[0_0_14px_rgba(34,211,238,0.7)] border-cyan-400":""}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-black tracking-wide text-white",children:"MAPIGATE"}),e.jsx("div",{className:"text-[9px] text-slate-400 font-mono",children:"Gateway"})]}),l>0&&e.jsx("span",{className:"ml-1 px-1.5 py-0.5 rounded-full bg-cyan-400 text-black text-[10px] font-black animate-pulse",children:l})]})}),v.items.map(a=>e.jsx("foreignObject",{x:a.px-75,y:a.py-22,width:"150",height:"44",className:"overflow-visible pointer-events-auto",children:e.jsxs("div",{onClick:N=>{N.stopPropagation(),!m.current&&u(b=>b===a.id?null:a.id)},className:`flex items-center gap-2 px-2.5 py-1.5 rounded-xl border-2 transition-all duration-300 cursor-pointer select-none bg-[#0B0F19] ${a.isActive?"shadow-[0_0_18px_rgba(56,189,248,0.4)]":a.isFocused?"border-blue-500/70 bg-[#0F1626]":"border-[#1E293B] hover:border-slate-500"}`,style:{borderColor:a.isActive?a.meta.color:a.isFocused?"#3B82F6":void 0},children:[e.jsx(W,{src:a.meta.image,name:a.meta.name,color:a.meta.color,iconBg:a.meta.iconBg,size:"sm"}),e.jsxs("div",{className:"min-w-0 flex-1 truncate",children:[e.jsx("span",{className:"text-xs font-bold block truncate",style:{color:a.isActive?a.meta.color:a.isFocused?"#93C5FD":"#E2E8F0"},title:a.meta.name,children:a.meta.name}),e.jsx("span",{className:"text-[9px] text-slate-500 font-mono block",children:"Upstream"})]}),a.isActive&&e.jsxs("span",{className:"relative flex h-2 w-2 ml-auto shrink-0",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",style:{backgroundColor:a.meta.color}}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2",style:{backgroundColor:a.meta.color}})]})]})},`node-${a.id}`))]})})]})})]})},Ie=({data:t,period:p,loading:d})=>{const[u,c]=i.useState("tokens"),h=s=>u==="cost"?`$${s>=10?s.toFixed(0):s.toFixed(2)}`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}k`:String(s),x={tokens:{stroke:"#38BDF8",fill:"#0284C7",label:"Total Tokens"},requests:{stroke:"#A855F7",fill:"#7E22CE",label:"Requests"},cost:{stroke:"#F59E0B",fill:"#B45309",label:"Estimated Cost ($)"}}[u],g=t.reduce((s,r)=>s+(r[u]||0),0);return e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 sm:p-5 flex flex-col shadow-xs w-full",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm sm:text-base font-bold text-white flex items-center gap-2",children:["Usage Trend",e.jsxs("span",{className:"text-xs font-normal text-slate-500",children:["(",p.toUpperCase(),")"]})]}),e.jsxs("span",{className:"text-xs text-slate-400 mt-0.5 block",children:["Aggregated ",x.label.toLowerCase(),":"," ",e.jsx("span",{className:"font-semibold text-slate-200",children:u==="cost"?`$${g.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`:g.toLocaleString("en-US")})]})]}),e.jsx("div",{className:"bg-[#151C2C] p-0.5 rounded-lg border border-[#243048] flex items-center text-xs",children:["tokens","requests","cost"].map(s=>e.jsx("button",{onClick:()=>c(s),className:`px-3 py-1.5 rounded-md font-semibold capitalize transition-all ${u===s?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:s},s))})]}),e.jsx("div",{className:"h-64 sm:h-72 w-full",children:d?e.jsx("div",{className:"h-full w-full flex items-center justify-center text-slate-500 text-sm",children:"Loading metrics..."}):t.length===0?e.jsx("div",{className:"h-full w-full flex items-center justify-center text-slate-500 text-sm",children:"No request activity recorded for this period."}):e.jsx(Ee,{width:"100%",height:"100%",children:e.jsxs(Le,{data:t,margin:{top:10,right:10,left:-10,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:`gradient-${u}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:x.stroke,stopOpacity:.35}),e.jsx("stop",{offset:"95%",stopColor:x.stroke,stopOpacity:0})]})}),e.jsx(Re,{strokeDasharray:"3 3",stroke:"#1E293B",vertical:!1}),e.jsx($e,{dataKey:"label",stroke:"#64748B",fontSize:11,tickLine:!1,axisLine:{stroke:"#1E293B"}}),e.jsx(qe,{stroke:"#64748B",fontSize:11,tickFormatter:h,tickLine:!1,axisLine:{stroke:"#1E293B"},width:45}),e.jsx(Me,{content:({active:s,payload:r,label:k})=>{if(s&&r&&r.length){const m=r[0].payload;return e.jsxs("div",{className:"bg-[#0B0F19]/95 backdrop-blur-md border border-[#2A374F] rounded-lg p-3 text-xs shadow-xl min-w-[160px]",children:[e.jsx("p",{className:"font-bold text-slate-200 mb-1.5 border-b border-slate-800 pb-1",children:m.time||k}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center text-cyan-400",children:[e.jsx("span",{children:"Tokens:"}),e.jsx("span",{className:"font-mono font-semibold",children:m.tokens.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between items-center text-purple-400",children:[e.jsx("span",{children:"Requests:"}),e.jsx("span",{className:"font-mono font-semibold",children:m.requests.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between items-center text-amber-400",children:[e.jsx("span",{children:"Cost:"}),e.jsxs("span",{className:"font-mono font-semibold",children:["$",m.cost.toLocaleString("en-US",{minimumFractionDigits:4,maximumFractionDigits:4})]})]})]})]})}return null}}),e.jsx(Be,{type:"monotone",dataKey:u,stroke:x.stroke,strokeWidth:2.5,fillOpacity:1,fill:`url(#gradient-${u})`,dot:!1,activeDot:{r:5,fill:x.stroke,stroke:"#0E1320",strokeWidth:2}})]})})})]})},_e=({byModel:t})=>{const[p,d]=i.useState("tokens"),c=Object.entries(t||{}).map(([o,x])=>{const g=(x.promptTokens||0)+(x.completionTokens||0);return{key:o,name:x.rawModel||o,provider:x.provider||"default",requests:x.requests||0,totalTokens:g,promptTokens:x.promptTokens||0,completionTokens:x.completionTokens||0,cost:x.cost||0}}).sort((o,x)=>p==="tokens"?x.totalTokens-o.totalTokens:x.requests-o.requests).slice(0,5),h=c.length>0?p==="tokens"?c[0].totalTokens:c[0].requests:1;return e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 sm:p-5 flex flex-col justify-between shadow-xs w-full h-full",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-sm sm:text-base font-bold text-white flex items-center gap-2",children:[e.jsx(ee,{className:"w-4 h-4 text-blue-400"}),"Top Models"]}),e.jsxs("div",{className:"bg-[#151C2C] p-0.5 rounded-lg border border-[#243048] flex items-center text-xs",children:[e.jsx("button",{onClick:()=>d("tokens"),className:`px-2.5 py-1 rounded-md font-semibold transition-all ${p==="tokens"?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:"Tokens"}),e.jsx("button",{onClick:()=>d("requests"),className:`px-2.5 py-1 rounded-md font-semibold transition-all ${p==="requests"?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:"Requests"})]})]}),c.length===0?e.jsx("div",{className:"py-12 text-center text-slate-500 text-xs",children:"No model usage recorded yet."}):e.jsx("div",{className:"space-y-3.5",children:c.map((o,x)=>{const g=p==="tokens"?o.totalTokens:o.requests,s=h>0?Math.round(g/h*100):0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 truncate max-w-[70%]",children:[e.jsx("span",{className:"w-4.5 h-4.5 rounded-sm bg-slate-800 text-slate-300 font-bold text-[10px] flex items-center justify-center shrink-0",children:x+1}),e.jsx("span",{className:"font-semibold text-slate-200 truncate",title:o.name,children:o.name}),e.jsx("span",{className:"px-1.5 py-0.2 rounded text-[10px] bg-slate-800/80 text-slate-400 border border-slate-700/50 shrink-0",children:o.provider})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("span",{className:"font-mono font-bold text-slate-200",children:p==="tokens"?o.totalTokens.toLocaleString():o.requests.toLocaleString()}),e.jsx("span",{className:"text-[10px] text-slate-500 ml-1",children:p==="tokens"?"tok":"req"})]})]}),e.jsx("div",{className:"w-full bg-[#151D2F] h-2 rounded-full overflow-hidden",children:e.jsx("div",{className:"bg-gradient-to-r from-blue-500 to-cyan-400 h-full rounded-full transition-all duration-500",style:{width:`${Math.max(4,s)}%`}})})]},o.key)})})]})},Ke=({byProvider:t})=>{const p=Object.entries(t||{}).map(([h,o])=>{const x=(o.promptTokens||0)+(o.completionTokens||0);return{id:h,requests:o.requests||0,totalTokens:x,cost:o.cost||0}}),d=p.reduce((h,o)=>h+o.requests,0)||1,u=p.sort((h,o)=>o.requests-h.requests),c={antigravity:"#3B82F6",claude:"#F97316",anthropic:"#F97316",openai:"#10B981",github:"#6366F1",gemini:"#38BDF8",deepseek:"#8B5CF6",default:"#64748B"};return e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 sm:p-5 flex flex-col justify-between shadow-xs w-full h-full",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-sm sm:text-base font-bold text-white flex items-center gap-2",children:[e.jsx(te,{className:"w-4 h-4 text-cyan-400"}),"By Provider"]}),e.jsxs("span",{className:"text-xs text-slate-400",children:[u.length," ",u.length===1?"provider":"providers"," active"]})]}),u.length===0?e.jsx("div",{className:"py-12 text-center text-slate-500 text-xs",children:"No provider activity recorded yet."}):e.jsx("div",{className:"space-y-3.5",children:u.map(h=>{const o=Math.round(h.requests/d*100),x=c[h.id.toLowerCase()]||c.default;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 truncate",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0",style:{backgroundColor:x}}),e.jsx("span",{className:"font-semibold text-slate-200 uppercase tracking-wide truncate",children:h.id})]}),e.jsxs("div",{className:"flex items-center gap-3 text-right shrink-0",children:[e.jsxs("span",{className:"font-mono text-slate-400",children:[h.requests.toLocaleString()," reqs (",o,"%)"]}),e.jsxs("span",{className:"font-mono text-xs font-semibold text-slate-200",children:["$",h.cost.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})]})]})]}),e.jsx("div",{className:"w-full bg-[#151D2F] h-2 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${Math.max(4,o)}%`,backgroundColor:x}})})]},h.id)})})]})},ze=({byProvider:t,byModel:p,byAccount:d,byApiKey:u})=>{const[c,h]=i.useState("model");let o=[];if(c==="provider")o=Object.entries(t||{}).map(([s,r])=>({id:s,name:s.toUpperCase(),sublabel:"Provider Gateway",requests:r.requests||0,promptTokens:r.promptTokens||0,cachedTokens:r.cachedTokens||0,completionTokens:r.completionTokens||0,cost:r.cost||0}));else if(c==="model")o=Object.entries(p||{}).map(([s,r])=>({id:s,name:r.rawModel||s,sublabel:r.provider?`Provider: ${r.provider}`:void 0,requests:r.requests||0,promptTokens:r.promptTokens||0,cachedTokens:r.cachedTokens||0,completionTokens:r.completionTokens||0,cost:r.cost||0,lastUsed:r.lastUsed}));else if(c==="account"){const s=Object.entries(d||{}),r=new Map;for(const[k,m]of s){if((m.promptTokens||0)+(m.completionTokens||0)<=0)continue;const C=`${m.accountName||m.accountId||k}::${m.rawModel||""}::${m.provider||""}`;r.set(C,(r.get(C)||0)+1)}o=s.map(([k,m])=>{const C=m.accountName||m.accountId||k,B=`${C}::${m.rawModel||""}::${m.provider||""}`,$=(r.get(B)||0)>1,R=m.rawModel?`${m.rawModel} (${m.provider||"default"})`:void 0,T=$&&m.accountId?[R,m.accountId].filter(Boolean).join(" · "):R;return{id:k,name:C,sublabel:T,requests:m.requests||0,promptTokens:m.promptTokens||0,cachedTokens:m.cachedTokens||0,completionTokens:m.completionTokens||0,cost:m.cost||0,lastUsed:m.lastUsed}})}else o=Object.entries(u||{}).map(([s,r])=>({id:s,name:r.apiKeyName||(s==="no_key"?"Direct / No Key":s),sublabel:s==="no_key"?"Unauthenticated / Local Ping":`Key ID: ${s}`,requests:r.requests||0,promptTokens:r.promptTokens||0,cachedTokens:r.cachedTokens||0,completionTokens:r.completionTokens||0,cost:r.cost||0,lastUsed:r.lastUsed}));o=o.filter(s=>s.promptTokens+s.completionTokens>0),o.sort((s,r)=>r.requests-s.requests);const x=s=>(s||0).toLocaleString("en-US"),g=s=>`$${(s||0).toLocaleString("en-US",{minimumFractionDigits:4,maximumFractionDigits:4})}`;return e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 sm:p-5 flex flex-col shadow-xs w-full",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{className:"w-4 h-4 text-blue-400"}),e.jsx("h3",{className:"text-sm sm:text-base font-bold text-white",children:"Usage Breakdown"}),e.jsxs("span",{className:"text-xs text-slate-500",children:["(",o.length," records)"]})]}),e.jsxs("div",{className:"bg-[#151C2C] p-0.5 rounded-lg border border-[#243048] flex items-center text-xs",children:[e.jsxs("span",{className:"px-2 text-slate-500 flex items-center gap-1",children:[e.jsx(je,{className:"w-3 h-3"})," Group:"]}),["model","provider","account","apiKey"].map(s=>e.jsx("button",{onClick:()=>h(s),className:`px-3 py-1.5 rounded-md font-semibold capitalize transition-all ${c===s?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:s==="apiKey"?"API Key":s},s))]})]}),o.length===0?e.jsx("div",{className:"py-12 text-center text-slate-500 text-sm",children:"No usage records found for this period."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left text-xs border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-slate-800 text-slate-400 uppercase text-[10px] tracking-wider",children:[e.jsx("th",{className:"py-2.5 px-3",children:"Name"}),e.jsx("th",{className:"py-2.5 px-3 text-right",children:"Requests"}),e.jsx("th",{className:"py-2.5 px-3 text-right text-blue-400",children:"Input Tokens"}),e.jsx("th",{className:"py-2.5 px-3 text-right text-cyan-400",children:"Cached"}),e.jsx("th",{className:"py-2.5 px-3 text-right text-emerald-400",children:"Output Tokens"}),e.jsx("th",{className:"py-2.5 px-3 text-right text-amber-400",children:"Est. Cost"}),e.jsx("th",{className:"py-2.5 px-3 text-right",children:"Last Used"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-800/60",children:o.map(s=>e.jsxs("tr",{className:"hover:bg-slate-800/25 transition-colors",children:[e.jsxs("td",{className:"py-2.5 px-3",children:[e.jsx("div",{className:"font-semibold text-slate-200",children:s.name}),s.sublabel&&e.jsx("div",{className:"text-[10px] text-slate-500 mt-0.5",children:s.sublabel})]}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono font-medium text-slate-300",children:x(s.requests)}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono text-blue-400/90",children:x(s.promptTokens)}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono text-cyan-400/90",children:x(s.cachedTokens)}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono text-emerald-400/90",children:x(s.completionTokens)}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono font-semibold text-amber-400/90",children:g(s.cost)}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono text-slate-400 text-[11px]",children:s.lastUsed?new Date(s.lastUsed).toLocaleDateString():"-"})]},s.id))})]})})]})},Ye=({detail:t,isOpen:p,onClose:d})=>{var T,S,E,L,y,n,v,l,f,a,N,b,j,w,F,D;const[u,c]=i.useState(!1),[h,o]=i.useState(null),[x,g]=i.useState(!1),[s,r]=i.useState("client"),{backdropProps:k}=Fe(d,!p);if(i.useEffect(()=>{if(!p)return;const q=P=>{P.key==="Escape"&&d()};document.addEventListener("keydown",q);const A=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",q),document.body.style.overflow=A}},[p,d]),!p||!t||typeof document>"u")return null;const m=(q,A)=>{navigator.clipboard.writeText(q),A==="id"?(c(!0),setTimeout(()=>c(!1),2e3)):(o(A),setTimeout(()=>o(null),2e3))},C=Number(t.status),B=C>=200&&C<300||t.status==="success"||t.status==="ok",$=C===429||t.status==="rate_limited",R=()=>$?e.jsx("span",{className:"px-2.5 py-1 rounded-md text-xs font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30",children:"429 Rate Limit"}):B?e.jsx("span",{className:"px-2.5 py-1 rounded-md text-xs font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",children:t.status==="success"||t.status==="ok"?"200 OK":`${t.status} OK`}):e.jsx("span",{className:"px-2.5 py-1 rounded-md text-xs font-bold bg-red-500/20 text-red-400 border border-red-500/30",children:t.status||"500 Error"});return ie.createPortal(e.jsx("div",{className:"fixed inset-0 z-[9999] flex justify-end bg-black/70 backdrop-blur-xs animate-rt-fade-in",...k,children:e.jsxs("div",{className:"w-full max-w-2xl sm:max-w-3xl h-full bg-[#0D121F] border-l border-[#1E293B] shadow-2xl flex flex-col text-slate-100 overflow-hidden animate-rt-slide-in-right",onClick:q=>q.stopPropagation(),children:[e.jsxs("div",{className:"p-4 sm:p-5 border-b border-[#1E293B] flex items-center justify-between bg-[#0A0E18]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[R(),e.jsxs("div",{children:[e.jsxs("h2",{className:"text-sm sm:text-base font-bold text-white flex items-center gap-2",children:[e.jsx("span",{children:t.model||"Unknown Model"}),t.provider&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-slate-800 text-slate-300 font-mono",children:t.provider})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400 mt-0.5",children:[e.jsx("span",{className:"font-mono text-[11px] truncate max-w-[200px]",title:t.id,children:t.id}),e.jsx("button",{onClick:()=>m(t.id,"id"),className:"p-1 hover:text-white transition-colors",title:"Copy Request ID",children:u?e.jsx(J,{className:"w-3.5 h-3.5 text-emerald-400"}):e.jsx(V,{className:"w-3.5 h-3.5"})})]})]})]}),e.jsx("button",{onClick:d,className:"p-2 rounded-lg bg-slate-800/60 hover:bg-slate-700 text-slate-400 hover:text-white transition-colors",children:e.jsx(se,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 sm:p-6 space-y-5 text-xs",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 bg-[#111726] border border-[#1E293B] rounded-xl p-3.5",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"text-slate-500 uppercase tracking-wider text-[10px] block font-semibold flex items-center gap-1",children:[e.jsx(ge,{className:"w-3 h-3"})," Latency"]}),e.jsx("span",{className:"font-mono text-sm font-bold text-slate-200 mt-1 block",children:((T=t.latency)==null?void 0:T.totalMs)!=null?`${t.latency.totalMs} ms`:"-"}),((S=t.latency)==null?void 0:S.ttftMs)!=null&&e.jsxs("span",{className:"text-[10px] text-slate-500 font-mono",children:["TTFT: ",t.latency.ttftMs,"ms"]})]}),e.jsxs("div",{children:[e.jsxs("span",{className:"text-slate-500 uppercase tracking-wider text-[10px] block font-semibold flex items-center gap-1",children:[e.jsx(te,{className:"w-3 h-3"})," Account"]}),e.jsx("span",{className:"font-mono text-xs font-semibold text-slate-200 mt-1 block truncate",children:t.accountName||t.connectionId||"Default"}),e.jsx("span",{className:"text-[10px] text-slate-500 font-mono",children:t.provider||"-"})]}),e.jsxs("div",{children:[e.jsxs("span",{className:"text-slate-500 uppercase tracking-wider text-[10px] block font-semibold flex items-center gap-1",children:[e.jsx(ve,{className:"w-3 h-3"})," Client Tool"]}),e.jsx("span",{className:"font-mono text-xs font-semibold text-slate-200 mt-1 block truncate",title:t.clientTool,children:t.clientTool||"unknown"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 uppercase tracking-wider text-[10px] block font-semibold",children:"Cost Est."}),e.jsxs("span",{className:"font-mono text-sm font-bold text-amber-400 mt-1 block",children:["$",t.cost!=null?t.cost.toLocaleString("en-US",{minimumFractionDigits:4,maximumFractionDigits:4}):"0.0000"]})]})]}),e.jsxs("div",{className:"bg-[#111726] border border-[#1E293B] rounded-xl p-4",children:[e.jsxs("h4",{className:"text-xs font-bold uppercase tracking-wider text-slate-400 mb-3 flex items-center gap-1.5",children:[e.jsx(ee,{className:"w-3.5 h-3.5 text-blue-400"})," Token Breakdown"]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{className:"bg-[#0B0F19] p-2.5 rounded-lg border border-slate-800",children:[e.jsx("span",{className:"text-[10px] text-slate-400 block uppercase font-semibold",children:"Input"}),e.jsx("span",{className:"font-mono text-base font-bold text-blue-400 mt-1 block",children:(((E=t.tokens)==null?void 0:E.promptTokens)||0).toLocaleString()})]}),e.jsxs("div",{className:"bg-[#0B0F19] p-2.5 rounded-lg border border-slate-800",children:[e.jsx("span",{className:"text-[10px] text-slate-400 block uppercase font-semibold",children:"Cached"}),e.jsx("span",{className:"font-mono text-base font-bold text-cyan-400 mt-1 block",children:(((L=t.tokens)==null?void 0:L.cachedTokens)||0).toLocaleString()})]}),e.jsxs("div",{className:"bg-[#0B0F19] p-2.5 rounded-lg border border-slate-800",children:[e.jsx("span",{className:"text-[10px] text-slate-400 block uppercase font-semibold",children:"Output"}),e.jsx("span",{className:"font-mono text-base font-bold text-emerald-400 mt-1 block",children:(((y=t.tokens)==null?void 0:y.completionTokens)||0).toLocaleString()})]}),e.jsxs("div",{className:"bg-[#0B0F19] p-2.5 rounded-lg border border-slate-800",children:[e.jsx("span",{className:"text-[10px] text-slate-400 block uppercase font-semibold",children:"Tokens Saved"}),e.jsx("span",{className:"font-mono text-base font-bold text-purple-400 mt-1 block",children:(((n=t.tokens)==null?void 0:n.tokensSavedByRtk)||0).toLocaleString()})]})]})]}),e.jsxs("div",{className:"bg-[#111726] border border-[#1E293B] rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>g(!x),className:"w-full p-3.5 flex items-center justify-between text-left hover:bg-slate-800/40 transition-colors",children:[e.jsxs("span",{className:"font-bold text-xs text-slate-300 flex items-center gap-2",children:[e.jsx(Q,{className:"w-4 h-4 text-emerald-400"}),"HTTP Headers (Sanitized)"]}),x?e.jsx(Ne,{className:"w-4 h-4 text-slate-400"}):e.jsx(ae,{className:"w-4 h-4 text-slate-400"})]}),x&&e.jsxs("div",{className:"p-3.5 border-t border-[#1E293B] space-y-3 bg-[#0B0F19]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-1",children:"Client Inbound Headers:"}),e.jsx("pre",{className:"font-mono text-[11px] p-2.5 rounded bg-[#070A11] border border-slate-800/80 overflow-x-auto text-slate-300",children:JSON.stringify(((v=t.request)==null?void 0:v.headers)||{},null,2)})]}),((l=t.providerRequest)==null?void 0:l.headers)&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-1",children:"Provider Outbound Headers:"}),e.jsx("pre",{className:"font-mono text-[11px] p-2.5 rounded bg-[#070A11] border border-slate-800/80 overflow-x-auto text-slate-300",children:JSON.stringify(t.providerRequest.headers,null,2)})]}),(((f=t.response)==null?void 0:f.headers)||((a=t.providerResponse)==null?void 0:a.headers))&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-1",children:"Response Headers:"}),e.jsx("pre",{className:"font-mono text-[11px] p-2.5 rounded bg-[#070A11] border border-slate-800/80 overflow-x-auto text-slate-300",children:JSON.stringify(((N=t.response)==null?void 0:N.headers)||((b=t.providerResponse)==null?void 0:b.headers),null,2)})]})]})]}),e.jsxs("div",{className:"bg-[#111726] border border-[#1E293B] rounded-xl p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1 bg-[#0B0F19] p-1 rounded-lg border border-slate-800",children:[e.jsx("button",{onClick:()=>r("client"),className:`px-3 py-1 rounded text-xs font-semibold transition-all ${s==="client"?"bg-blue-600 text-white":"text-slate-400 hover:text-white"}`,children:"Client Request"}),e.jsx("button",{onClick:()=>r("providerReq"),className:`px-3 py-1 rounded text-xs font-semibold transition-all ${s==="providerReq"?"bg-blue-600 text-white":"text-slate-400 hover:text-white"}`,children:"Provider Request"}),e.jsx("button",{onClick:()=>r("response"),className:`px-3 py-1 rounded text-xs font-semibold transition-all ${s==="response"?"bg-blue-600 text-white":"text-slate-400 hover:text-white"}`,children:"Response Output"})]}),e.jsx("button",{onClick:()=>{var A,P,M,O;const q=s==="client"?(A=t.request)==null?void 0:A.body:s==="providerReq"?(P=t.providerRequest)==null?void 0:P.body:((M=t.response)==null?void 0:M.body)||((O=t.providerResponse)==null?void 0:O.body);m(JSON.stringify(q,null,2),s)},className:"px-2.5 py-1 rounded-md bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white flex items-center gap-1.5 transition-colors text-xs",children:h===s?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"w-3.5 h-3.5 text-emerald-400"}),e.jsx("span",{children:"Copied"})]}):e.jsxs(e.Fragment,{children:[e.jsx(V,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Copy JSON"})]})})]}),e.jsx("div",{className:"relative rounded-lg bg-[#070A11] border border-slate-800/80 p-3 max-h-96 overflow-y-auto",children:e.jsx("pre",{className:"font-mono text-[11px] text-slate-300 whitespace-pre-wrap leading-relaxed",children:JSON.stringify(s==="client"?((j=t.request)==null?void 0:j.body)||{message:"No request body captured"}:s==="providerReq"?((w=t.providerRequest)==null?void 0:w.body)||{message:"Same as client or pass-through"}:((F=t.response)==null?void 0:F.body)||((D=t.providerResponse)==null?void 0:D.body)||{message:"Stream completed successfully"},null,2)})})]})]})]})}),document.body)},Ge=()=>{const[t,p]=i.useState(null),[d,u]=i.useState(!1),[c,h]=i.useState(1),[o,x]=i.useState(20),[g,s]=i.useState(""),[r,k]=i.useState("all"),[m,C]=i.useState("all"),[B,$]=i.useState([]),[R,T]=i.useState(null),[S,E]=i.useState(!1),L=i.useCallback(async()=>{try{const l=await fetch("/api/usage/providers");if(l.ok){const f=await l.json();Array.isArray(f)&&$(f)}}catch{}},[]),y=i.useCallback(async()=>{u(!0);try{const l=new URLSearchParams;l.set("page",String(c)),l.set("pageSize",String(o)),r!=="all"&&l.set("provider",r),m!=="all"&&l.set("status",m),g.trim()&&l.set("search",g.trim());const f=await fetch(`/api/usage/request-details?${l.toString()}`);if(f.ok){const a=await f.json();p(a)}}catch(l){console.error("Failed to fetch request details:",l)}finally{u(!1)}},[c,o,r,m,g]);i.useEffect(()=>{L()},[L]),i.useEffect(()=>{y()},[y]);const n=async l=>{try{const f=await fetch(`/api/usage/request-details/${l.id}`);if(f.ok){const a=await f.json();T(a)}else T(l)}catch{T(l)}E(!0)},v=l=>{const f=String(l||"");return f==="200"||f==="success"||f==="ok"?e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",children:"200 OK"}):f==="429"||f==="rate_limited"?e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30",children:"429"}):e.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-bold bg-red-500/20 text-red-400 border border-red-500/30",children:f||"500"})};return e.jsxs("div",{className:"w-full space-y-4",children:[e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl p-3.5 flex flex-wrap items-center justify-between gap-3 shadow-xs",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 flex-1 min-w-[280px]",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(we,{className:"w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx("input",{type:"text",placeholder:"Search by model, ID, provider, tool...",value:g,onChange:l=>{s(l.target.value),h(1)},className:"w-full pl-9 pr-8 py-1.5 rounded-lg bg-[#070A11] border border-slate-800 text-xs text-slate-200 placeholder-slate-500 focus:outline-hidden focus:border-blue-500"}),g&&e.jsx("button",{type:"button",onClick:()=>{s(""),h(1)},className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white transition-colors cursor-pointer flex items-center justify-center",title:"Clear search",children:e.jsx(se,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(ye,{className:"w-3.5 h-3.5 text-slate-500"}),e.jsx(Y,{value:r,onChange:l=>{k(l),h(1)},options:[{value:"all",label:"All Providers"},...B.map(l=>({value:l,label:l.toUpperCase()}))],className:"min-w-[140px]"})]}),e.jsx("div",{className:"flex items-center text-xs",children:e.jsx(Y,{value:m,onChange:l=>{C(l),h(1)},options:[{value:"all",label:"All Statuses"},{value:"200",label:"200 OK"},{value:"429",label:"429 Rate Limit"},{value:"500",label:"500 Error"}],className:"min-w-[130px]"})})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>y(),disabled:d,className:"p-1.5 rounded-lg bg-[#151D2F] border border-slate-700/60 text-slate-300 hover:text-white hover:bg-slate-800 transition-colors",title:"Refresh logs",children:e.jsx(le,{className:`w-4 h-4 ${d?"animate-spin text-blue-400":""}`})}),e.jsx("span",{className:"text-xs text-slate-400 font-mono",children:t!=null&&t.pagination?`${t.pagination.totalItems} records`:""})]})]}),e.jsxs("div",{className:"bg-[#0E1320] border border-[#1E293B] rounded-xl overflow-hidden shadow-xs",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left text-xs border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-slate-800 text-slate-400 uppercase text-[10px] tracking-wider bg-[#0A0E18]",children:[e.jsx("th",{className:"py-3 px-3.5",children:"Status"}),e.jsx("th",{className:"py-3 px-3.5",children:"Time"}),e.jsx("th",{className:"py-3 px-3.5",children:"Model"}),e.jsx("th",{className:"py-3 px-3.5",children:"Provider"}),e.jsx("th",{className:"py-3 px-3.5",children:"Tool / Client"}),e.jsx("th",{className:"py-3 px-3.5 text-right text-blue-400",children:"In Tok"}),e.jsx("th",{className:"py-3 px-3.5 text-right text-emerald-400",children:"Out Tok"}),e.jsx("th",{className:"py-3 px-3.5 text-right",children:"Latency"}),e.jsx("th",{className:"py-3 px-3.5 text-right text-amber-400",children:"Cost"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-800/60",children:d&&(!(t!=null&&t.details)||t.details.length===0)?e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"py-12 text-center text-slate-500",children:"Loading request records..."})}):!(t!=null&&t.details)||t.details.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"py-12 text-center text-slate-500",children:"No matching request logs found."})}):t.details.map(l=>{var f,a,N;return e.jsxs("tr",{onClick:()=>n(l),className:"hover:bg-blue-600/10 cursor-pointer transition-colors group",children:[e.jsx("td",{className:"py-2.5 px-3.5",children:v(l.status)}),e.jsx("td",{className:"py-2.5 px-3.5 font-mono text-[11px] text-slate-400 whitespace-nowrap",children:new Date(l.timestamp).toLocaleTimeString()}),e.jsx("td",{className:"py-2.5 px-3.5 font-semibold text-slate-200 group-hover:text-blue-400 transition-colors truncate max-w-[180px]",children:l.model||"unknown"}),e.jsx("td",{className:"py-2.5 px-3.5",children:e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-mono",children:l.provider||"-"})}),e.jsx("td",{className:"py-2.5 px-3.5 font-mono text-slate-400 truncate max-w-[140px]",title:l.clientTool,children:l.clientTool||"-"}),e.jsx("td",{className:"py-2.5 px-3.5 text-right font-mono text-blue-400/90",children:(((f=l.tokens)==null?void 0:f.promptTokens)||0).toLocaleString()}),e.jsx("td",{className:"py-2.5 px-3.5 text-right font-mono text-emerald-400/90",children:(((a=l.tokens)==null?void 0:a.completionTokens)||0).toLocaleString()}),e.jsx("td",{className:"py-2.5 px-3.5 text-right font-mono text-slate-300",children:((N=l.latency)==null?void 0:N.totalMs)!=null?`${l.latency.totalMs}ms`:"-"}),e.jsxs("td",{className:"py-2.5 px-3.5 text-right font-mono font-semibold text-amber-400/90",children:["$",l.cost!=null?l.cost.toLocaleString("en-US",{minimumFractionDigits:4,maximumFractionDigits:4}):"0.0000"]})]},l.id)})})]})}),(t==null?void 0:t.pagination)&&t.pagination.totalPages>1&&e.jsxs("div",{className:"p-3 border-t border-slate-800 bg-[#0A0E18] flex items-center justify-between text-xs text-slate-400",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Rows per page:"}),e.jsx(Y,{value:String(o),onChange:l=>{x(Number(l)),h(1)},options:[{value:"10",label:"10"},{value:"20",label:"20"},{value:"50",label:"50"}],className:"w-20"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{children:["Page ",e.jsx("span",{className:"font-bold text-slate-200",children:t.pagination.page})," of"," ",e.jsx("span",{className:"font-bold text-slate-200",children:t.pagination.totalPages})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{disabled:!t.pagination.hasPrev,onClick:()=>h(l=>Math.max(1,l-1)),className:"p-1.5 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:e.jsx(ke,{className:"w-4 h-4"})}),e.jsx("button",{disabled:!t.pagination.hasNext,onClick:()=>h(l=>l+1),className:"p-1.5 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:e.jsx(ae,{className:"w-4 h-4"})})]})]})]})]}),e.jsx(Ye,{detail:R,isOpen:S,onClose:()=>E(!1)})]})},et=()=>{const[t,p]=i.useState("overview"),[d,u]=i.useState("7d"),[c,h]=i.useState(null),[o,x]=i.useState([]),[g,s]=i.useState([]),[r,k]=i.useState([]),[m,C]=i.useState(!0),[B,$]=i.useState(!0),[R,T]=i.useState(!1),S=i.useRef(null),E=i.useCallback(async n=>{try{C(!0);const v=await fetch(`/api/usage/stats?period=${n}`);if(v.ok){const l=await v.json();h(l),l.activeRequests&&s(l.activeRequests),l.recentRequests&&k(l.recentRequests)}}catch(v){console.error("Failed to fetch stats:",v)}finally{C(!1)}},[]),L=i.useCallback(async n=>{try{$(!0);const v=await fetch(`/api/usage/chart?period=${n}`);if(v.ok){const l=await v.json();x(l)}}catch(v){console.error("Failed to fetch chart data:",v)}finally{$(!1)}},[]);i.useEffect(()=>{E(d),L(d)},[d,E,L]),i.useEffect(()=>{let n=null,v=null;const l=()=>{try{const f=De.getToken(),a=`/api/usage/stream?period=${encodeURIComponent(d)}`,N=f?`${a}&token=${encodeURIComponent(f)}`:a;n=new EventSource(N),S.current=n,n.onopen=()=>{T(!0)},n.addEventListener("stats",b=>{try{const j=JSON.parse(b.data);h(j),j.activeRequests&&s(j.activeRequests),j.recentRequests&&k(j.recentRequests)}catch{}}),n.addEventListener("pending",b=>{try{const j=JSON.parse(b.data);j.activeRequests&&s(j.activeRequests)}catch{}}),n.onerror=()=>{T(!1),n==null||n.close(),S.current=null,v=setTimeout(l,5e3)}}catch{T(!1)}};return l(),()=>{v&&clearTimeout(v),n&&n.close(),S.current=null}},[d]);const y=Object.keys((c==null?void 0:c.byProvider)||{});return e.jsxs("div",{className:"w-full min-w-0 space-y-6 px-2 sm:px-4 lg:px-6 pb-20 animate-rt-fade-in",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 bg-[#0B0F19] border border-[#1E293B] rounded-2xl p-2 sm:p-2.5 shadow-sm",children:[e.jsxs("div",{className:"bg-[#151C2C] p-1 rounded-xl border border-[#243048] flex items-center",children:[e.jsxs("button",{onClick:()=>p("overview"),className:`px-3.5 py-1.5 rounded-lg text-xs font-bold flex items-center gap-2 transition-all ${t==="overview"?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:[e.jsx(Ce,{className:"w-3.5 h-3.5"}),"Overview"]}),e.jsxs("button",{onClick:()=>p("details"),className:`px-3.5 py-1.5 rounded-lg text-xs font-bold flex items-center gap-2 transition-all ${t==="details"?"bg-blue-600 text-white shadow-xs":"text-slate-400 hover:text-white"}`,children:[e.jsx(Se,{className:"w-3.5 h-3.5"}),"Details (Inspector)"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[e.jsxs("div",{className:"hidden sm:flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-[#151C2C] border border-slate-800 text-[11px] text-slate-400",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${R?"bg-emerald-400 shadow-[0_0_8px_#34d399]":"bg-amber-400"}`}),e.jsx("span",{className:"font-mono text-[10px]",children:R?"LIVE TELEMETRY":"POLLING"})]}),t==="overview"&&e.jsx("div",{className:"bg-[#151C2C] p-1 rounded-xl border border-[#243048] flex items-center text-xs",children:["today","24h","7d","30d","60d","90d","all"].map(n=>e.jsx("button",{onClick:()=>u(n),className:`px-2.5 sm:px-3 py-1 rounded-lg uppercase font-semibold transition-all ${d===n?"bg-blue-600/30 text-blue-400 border border-blue-500/40 shadow-xs":"text-slate-400 hover:text-white"}`,children:n},n))}),e.jsx("button",{onClick:()=>{E(d),L(d)},className:"p-2 rounded-xl bg-[#151C2C] border border-[#243048] text-slate-300 hover:text-white hover:bg-slate-800 transition-colors",title:"Refresh statistics",children:e.jsx(le,{className:`w-3.5 h-3.5 ${m?"animate-spin text-blue-400":""}`})})]})]}),t==="overview"&&e.jsxs("div",{className:"space-y-6 w-full",children:[e.jsx(Ae,{stats:c,loading:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-5 w-full",children:[e.jsx("div",{className:"lg:col-span-7 w-full flex",children:e.jsx(Ue,{providers:y,activeRequests:g})}),e.jsxs("div",{className:"lg:col-span-5 w-full bg-[#0E1320] border border-[#1E293B] rounded-xl p-4 sm:p-5 flex flex-col justify-between shadow-xs",children:[e.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-[#1E293B] shrink-0",children:[e.jsxs("span",{className:"text-sm font-bold text-slate-200 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Te,{className:"w-4 h-4 text-blue-400"}),"Recent Requests"]}),e.jsxs("span",{className:"text-[10px] text-cyan-400 font-mono bg-cyan-500/10 border border-cyan-500/20 px-2 py-0.5 rounded-full flex items-center gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-cyan-400 animate-pulse"}),"Live Stream"]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto mt-2 min-h-[220px] max-h-[300px] pr-1",children:r.length===0?e.jsx("div",{className:"py-16 text-center text-slate-500 text-xs",children:"No recent proxy requests yet. Call /v1/messages or /v1/chat/completions to see live logs."}):e.jsxs("table",{className:"w-full text-left text-xs font-mono border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-slate-500 text-[10px] uppercase border-b border-[#1E293B]",children:[e.jsx("th",{className:"pb-2 font-semibold pr-2",children:"Model / Provider"}),e.jsx("th",{className:"pb-2 font-semibold text-right px-2 w-[125px]",children:"In / Out"}),e.jsx("th",{className:"pb-2 font-semibold text-right pl-2 pr-2 w-[95px]",children:"When"})]})}),e.jsx("tbody",{className:"divide-y divide-[#1E293B]/50",children:r.slice(0,15).map((n,v)=>{const l=n.status==="success"||n.status==="ok",f=n.requestedModel&&n.requestedModel!==n.model?`${n.model} (via ${n.requestedModel}) · ${n.provider||"unknown"}`:`${n.model} · ${n.provider||"unknown"}`;return e.jsxs("tr",{className:"hover:bg-slate-800/30 transition-colors",children:[e.jsx("td",{className:"py-2 pr-2 overflow-hidden",title:f,children:e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${l?"bg-emerald-400":"bg-red-400"}`}),e.jsx("span",{className:"text-slate-200 text-xs truncate font-medium",children:n.model}),n.provider&&e.jsx("span",{className:"text-[9px] text-slate-400 font-mono uppercase px-1 py-0.5 rounded bg-slate-800 border border-slate-700/50 shrink-0",children:n.provider})]})}),e.jsxs("td",{className:"py-2 text-right whitespace-nowrap px-2 text-[11px] w-[125px]",children:[e.jsxs("span",{className:"text-blue-400",children:[n.promptTokens.toLocaleString(),"↑"]})," ",e.jsxs("span",{className:"text-emerald-400",children:[n.completionTokens.toLocaleString(),"↓"]})]}),e.jsx("td",{className:"py-2 text-right text-[10px] text-slate-400 whitespace-nowrap pl-2 pr-2 w-[95px]",children:typeof n.timestamp=="number"?new Date(n.timestamp).toLocaleTimeString():new Date(String(n.timestamp)).toLocaleTimeString()})]},n.id||v)})})]})})]})]}),e.jsx(Ie,{data:o,period:d,loading:B}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-5 w-full",children:[e.jsx(_e,{byModel:(c==null?void 0:c.byModel)||{}}),e.jsx(Ke,{byProvider:(c==null?void 0:c.byProvider)||{}})]}),e.jsx(ze,{byProvider:(c==null?void 0:c.byProvider)||{},byModel:(c==null?void 0:c.byModel)||{},byAccount:(c==null?void 0:c.byAccount)||{},byApiKey:(c==null?void 0:c.byApiKey)||{}})]}),t==="details"&&e.jsx(Ge,{})]})};export{et as UsageTab};