@fudrouter/fsrouter 0.6.70 → 0.6.72

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 (178) hide show
  1. package/dist/lib/oauth/providers.js +3 -3
  2. package/package.json +1 -1
  3. package/public/assets/{EndpointPageClient.CGB3HjDe.js → EndpointPageClient.LyNNvZ4z.js} +3 -3
  4. package/public/assets/{Loading.BhEzHe-X.js → Loading.Bj-WGl4k.js} +1 -1
  5. package/public/assets/{NoAuthProxyCard.Buvt0BVH.js → NoAuthProxyCard.qAv57b-0.js} +1 -1
  6. package/public/assets/{index.B-zMpSp_.js → index.CShjRV_B.js} +41 -41
  7. package/public/assets/{page.BINfJPNt.js → page.1qjqvrwX.js} +1 -1
  8. package/public/assets/{page.CfDkX9XZ.js → page.BSLJ4tx5.js} +1 -1
  9. package/public/assets/{page.D6TULIkh.js → page.BbO1pspY.js} +1 -1
  10. package/public/assets/page.BdmJ3yY3.js +5 -0
  11. package/public/assets/{page.Amtgxj_r.js → page.BnmTC5jG.js} +1 -1
  12. package/public/assets/{page.3QwV1pLl.js → page.C72FTTJr.js} +1 -1
  13. package/public/assets/{page.CdbMx9XI.js → page.CPZav1_c.js} +1 -1
  14. package/public/assets/{page.BONoTspJ.js → page.CQlVGoXg.js} +1 -1
  15. package/public/assets/{page.DgnlzpNx.js → page.CSs3-gdt.js} +1 -1
  16. package/public/assets/{page.BV28PqHr.js → page.CXd_R9yU.js} +1 -1
  17. package/public/assets/{page.5Aj6RvuD.js → page.CbkENBd5.js} +1 -1
  18. package/public/assets/{page.BAjUiqtJ.js → page.ChX1NqmC.js} +1 -1
  19. package/public/assets/page.Cj5h09Zo.js +1 -0
  20. package/public/assets/{page.CB__T51y.js → page.CnTop8Zt.js} +1 -1
  21. package/public/assets/{page.BMf0BFTW.js → page.CssmrzTT.js} +1 -1
  22. package/public/assets/{page.CVu_9TAu.js → page.CsxWmPoI.js} +1 -1
  23. package/public/assets/{page.ClXnUNhb.js → page.CzlQTyAL.js} +1 -1
  24. package/public/assets/{page.DAgwiopx.js → page.D1oKew1j.js} +1 -1
  25. package/public/assets/{page.BIG_uMBA.js → page.D5gj98Oe.js} +1 -1
  26. package/public/assets/{page.BW6Rv-_k.js → page.DBhu4Arl.js} +1 -1
  27. package/public/assets/page.DD_czjjP.js +1 -0
  28. package/public/assets/{page.BmOXfa4k.js → page.DPyOkPVo.js} +1 -1
  29. package/public/assets/{page.CTdMdgI4.js → page.DUI8kqOY.js} +1 -1
  30. package/public/assets/{page.BdPGDnx0.js → page.DVIHRbxB.js} +1 -1
  31. package/public/assets/{page.B9r7QI90.js → page.DX4Nno6M.js} +1 -1
  32. package/public/assets/{page.BCPmNscX.js → page.Dh5f0XJC.js} +1 -1
  33. package/public/assets/{page.u7XFxplU.js → page.DibhF7f-.js} +1 -1
  34. package/public/assets/{page.CDVZIbSe.js → page.DxMDTbSx.js} +1 -1
  35. package/public/assets/{page.Bb3E5EzI.js → page.Dx_GRRdT.js} +1 -1
  36. package/public/assets/{page.DhcizW_i.js → page.DzZLqI5Q.js} +1 -1
  37. package/public/assets/{page.CF5pD5lz.js → page.Ir7KvKcF.js} +1 -1
  38. package/public/assets/{page.Bj0au_ka.js → page.O2ddJYoT.js} +3 -3
  39. package/public/assets/{page.DIrcssm-.js → page.Qkkv8roc.js} +1 -1
  40. package/public/assets/{page.CrzjUbZg.js → page.i4KDuWcM.js} +1 -1
  41. package/public/assets/{page.1gncE-Vr.js → page.sOFOrxqq.js} +1 -1
  42. package/public/assets/{page.DskvkVIF.js → page.vla5Mzki.js} +1 -1
  43. package/public/index.html +1 -1
  44. package/public/assets/EndpointPageClient.Cee8kfmV.js +0 -6
  45. package/public/assets/EndpointPageClient.DdAfxJoK.js +0 -6
  46. package/public/assets/EndpointPageClient.GpJ_FKds.js +0 -6
  47. package/public/assets/Loading.DFkQ-Ly9.js +0 -1
  48. package/public/assets/Loading.DaQG3sHF.js +0 -1
  49. package/public/assets/Loading.QMOYJhLu.js +0 -1
  50. package/public/assets/NoAuthProxyCard.C18iZ3Fk.js +0 -89
  51. package/public/assets/NoAuthProxyCard.DyEjms20.js +0 -89
  52. package/public/assets/NoAuthProxyCard.VRP7gDcs.js +0 -89
  53. package/public/assets/index.CoYbjSIL.js +0 -89
  54. package/public/assets/index.DQDDDpp7.js +0 -89
  55. package/public/assets/index.KMEObSAk.js +0 -89
  56. package/public/assets/page.A7FRfarX.js +0 -1
  57. package/public/assets/page.B1a01Vfg.js +0 -1
  58. package/public/assets/page.B7h6EPVo.js +0 -1
  59. package/public/assets/page.BBMJAyy7.js +0 -1
  60. package/public/assets/page.BBSUQskO.js +0 -64
  61. package/public/assets/page.BFENid_V.js +0 -31
  62. package/public/assets/page.BJzBUr1v.js +0 -2
  63. package/public/assets/page.BKM5Up2Y.js +0 -1
  64. package/public/assets/page.BLUEyope.js +0 -1
  65. package/public/assets/page.BMeBT03D.js +0 -5
  66. package/public/assets/page.BQwH91-m.js +0 -1
  67. package/public/assets/page.BRgXbpJe.js +0 -1
  68. package/public/assets/page.BXq7Sixg.js +0 -1
  69. package/public/assets/page.Bbf1xxJj.js +0 -1
  70. package/public/assets/page.BcuklMLO.js +0 -2
  71. package/public/assets/page.Bi5OEfgq.js +0 -1
  72. package/public/assets/page.Bi9gIWN0.js +0 -1
  73. package/public/assets/page.BiLGOe6j.js +0 -1
  74. package/public/assets/page.BicDCwTa.js +0 -1
  75. package/public/assets/page.Bjd38gaf.js +0 -1
  76. package/public/assets/page.Bqk4tX-5.js +0 -1
  77. package/public/assets/page.BrrSjbBJ.js +0 -1
  78. package/public/assets/page.BsUeE2Y_.js +0 -1
  79. package/public/assets/page.BthVvW1e.js +0 -64
  80. package/public/assets/page.BxAWh20c.js +0 -1
  81. package/public/assets/page.C-2GmPmS.js +0 -4
  82. package/public/assets/page.C27wrrub.js +0 -1
  83. package/public/assets/page.C3FwsCq_.js +0 -23
  84. package/public/assets/page.C4RMU4Xv.js +0 -23
  85. package/public/assets/page.C7SC9vwX.js +0 -1
  86. package/public/assets/page.C8gTAwsH.js +0 -5
  87. package/public/assets/page.CECQKY1y.js +0 -5
  88. package/public/assets/page.CEN8xgCA.js +0 -1
  89. package/public/assets/page.CHG9mx5l.js +0 -1
  90. package/public/assets/page.CMUOu9fe.js +0 -1
  91. package/public/assets/page.CRex977Y.js +0 -5
  92. package/public/assets/page.CUsb0F5t.js +0 -1
  93. package/public/assets/page.CXE5AWV3.js +0 -1
  94. package/public/assets/page.CXIP8Wzi.js +0 -4
  95. package/public/assets/page.CXOuLQhq.js +0 -1
  96. package/public/assets/page.CXPMjDX9.js +0 -1
  97. package/public/assets/page.CXPPlybJ.js +0 -6
  98. package/public/assets/page.CYfjd9SF.js +0 -1
  99. package/public/assets/page.CZtbttgE.js +0 -1
  100. package/public/assets/page.CbOSwuwi.js +0 -1
  101. package/public/assets/page.CbWWyTC4.js +0 -1
  102. package/public/assets/page.CfXJWUgA.js +0 -1
  103. package/public/assets/page.CfdTLncK.js +0 -1
  104. package/public/assets/page.ChqEg6y-.js +0 -1
  105. package/public/assets/page.CmbatQd6.js +0 -4
  106. package/public/assets/page.Cp7XaHGI.js +0 -1
  107. package/public/assets/page.CqR-Z0pY.js +0 -1
  108. package/public/assets/page.CsLBZFbk.js +0 -1
  109. package/public/assets/page.CyqTG9Kn.js +0 -2
  110. package/public/assets/page.CzKSjT-r.js +0 -1
  111. package/public/assets/page.D1S50DvR.js +0 -1
  112. package/public/assets/page.D3b1o69R.js +0 -5
  113. package/public/assets/page.D5B_p_2E.js +0 -31
  114. package/public/assets/page.D8X-8LSd.js +0 -2
  115. package/public/assets/page.DA2dX7iN.js +0 -1
  116. package/public/assets/page.DBNjxgJS.js +0 -6
  117. package/public/assets/page.DEBBy5qz.js +0 -1
  118. package/public/assets/page.DEOXc6iv.js +0 -6
  119. package/public/assets/page.DG46DZcu.js +0 -1
  120. package/public/assets/page.DGAKp9YS.js +0 -1
  121. package/public/assets/page.DGico7sP.js +0 -1
  122. package/public/assets/page.DHBHS2oS.js +0 -1
  123. package/public/assets/page.DKdtfq8E.js +0 -2
  124. package/public/assets/page.DKj8qFYb.js +0 -1
  125. package/public/assets/page.DNofNt4p.js +0 -1
  126. package/public/assets/page.DVdv-E5d.js +0 -1
  127. package/public/assets/page.Da-kutqN.js +0 -1
  128. package/public/assets/page.DaW7T6nt.js +0 -1
  129. package/public/assets/page.DhPzWwGm.js +0 -1
  130. package/public/assets/page.Dju6Kwa5.js +0 -1
  131. package/public/assets/page.Dlh3Q_rt.js +0 -1
  132. package/public/assets/page.DmNhmYKk.js +0 -64
  133. package/public/assets/page.Dmvhu2ua.js +0 -1
  134. package/public/assets/page.Dp30ZzXE.js +0 -1
  135. package/public/assets/page.DsY8qNEU.js +0 -1
  136. package/public/assets/page.DtGEStU7.js +0 -1
  137. package/public/assets/page.DuXsnK8A.js +0 -1
  138. package/public/assets/page.DwU6Ubqf.js +0 -1
  139. package/public/assets/page.FmrKiZlG.js +0 -2
  140. package/public/assets/page.GSAm83Cv.js +0 -6
  141. package/public/assets/page.IgH-AWcu.js +0 -1
  142. package/public/assets/page.Ii8wGSnt.js +0 -1
  143. package/public/assets/page.KtURQA9Q.js +0 -1
  144. package/public/assets/page.NFGJtdfx.js +0 -1
  145. package/public/assets/page.QPaIzKAa.js +0 -1
  146. package/public/assets/page.QuBXfL80.js +0 -1
  147. package/public/assets/page.S02TdGZT.js +0 -1
  148. package/public/assets/page.V3CmUOJF.js +0 -1
  149. package/public/assets/page.VClP2n2B.js +0 -1
  150. package/public/assets/page.Vo9Oe8DJ.js +0 -1
  151. package/public/assets/page.WIMFvXoG.js +0 -1
  152. package/public/assets/page.XUya1XZj.js +0 -23
  153. package/public/assets/page.XqKIvnmq.js +0 -31
  154. package/public/assets/page.aAUPKg0H.js +0 -1
  155. package/public/assets/page.aRQdaBbf.js +0 -1
  156. package/public/assets/page.e-Zxfi03.js +0 -1
  157. package/public/assets/page.e-cA5aB5.js +0 -6
  158. package/public/assets/page.eNXd9f58.js +0 -6
  159. package/public/assets/page.gj2B5h2d.js +0 -1
  160. package/public/assets/page.gvZgqycR.js +0 -1
  161. package/public/assets/page.jvowBQYJ.js +0 -1
  162. package/public/assets/page.k_WzlZwU.js +0 -5
  163. package/public/assets/page.qK1RUb_S.js +0 -1
  164. package/public/assets/page.ryYPRTww.js +0 -1
  165. package/public/assets/page.xm98_0dX.js +0 -5
  166. package/public/assets/page.yjCJ-4Uh.js +0 -1
  167. package/public/providers/agentrouter.webp +0 -0
  168. package/public/providers/codebuddy-cn.webp +0 -0
  169. package/public/providers/gigachat.webp +0 -0
  170. package/public/providers/heroku.webp +0 -0
  171. package/public/providers/kimchi.webp +0 -0
  172. package/public/providers/llamagate.webp +0 -0
  173. package/public/providers/mimo-free.webp +0 -0
  174. package/public/providers/nanogpt.webp +0 -0
  175. package/public/providers/nscale.webp +0 -0
  176. package/public/providers/ovhcloud.webp +0 -0
  177. package/public/providers/predibase.webp +0 -0
  178. package/public/providers/zcode.webp +0 -0
@@ -1 +1 @@
1
- import{a as ae,j as e,B as _,b as Y,O as ve,F as ye,c as je,A as Ne,W as Ce,d as we,e as Te,P as re,M as ie,f as i}from"./index.KMEObSAk.js";import{b as c,L as le}from"./router.Cjj1--8t.js";import{C as ne,B as P,T as oe,I as O,S as ke}from"./NoAuthProxyCard.DyEjms20.js";import{C as ee}from"./Loading.DFkQ-Ly9.js";import"./zustand.akaTi5uX.js";function Ae(r){if(!r)return null;const a=r.match(/\b([45]\d{2})\b/);return a?a[1]:"ERR"}function Ie(r){if(!r)return"";const a=Date.now()-new Date(r).getTime(),m=Math.floor(a/6e4);if(m<1)return"just now";if(m<60)return`${m}m ago`;const s=Math.floor(m/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}const te={available:{icon:"check_circle",color:"#22c55e",label:"Available"},cooldown:{icon:"schedule",color:"#f59e0b",label:"Cooldown"},unavailable:{icon:"error",color:"#ef4444",label:"Unavailable"},unknown:{icon:"help",color:"#6b7280",label:"Unknown"}};function Se(){const[r,a]=c.useState(null),[m,s]=c.useState(!0),[l,h]=c.useState(!1),[w,v]=c.useState(null),y=c.useRef(null),u=ae(),N=c.useCallback(async()=>{try{const x=await fetch("/api/models/availability");if(x.ok){const g=await x.json();a(g)}}catch{}finally{s(!1)}},[]);c.useEffect(()=>{N();const x=setInterval(N,3e4);return()=>clearInterval(x)},[N]),c.useEffect(()=>{const x=g=>{y.current&&!y.current.contains(g.target)&&h(!1)};return l&&document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]);const C=async(x,g)=>{v(`${x}:${g}`);try{(await fetch("/api/models/availability",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clearCooldown",provider:x,model:g})})).ok?(u.success(`Cooldown cleared for ${g}`),await N()):u.error("Failed to clear cooldown")}catch{u.error("Failed to clear cooldown")}finally{v(null)}};if(m)return null;const p=(r==null?void 0:r.models)||[],j=((r==null?void 0:r.unavailableCount)||p.filter(x=>x.status!=="available").length)===0,k={};return p.forEach(x=>{if(x.status==="available")return;const g=x.provider||"unknown";k[g]||(k[g]=[]),k[g].push(x)}),e.jsx("div",{className:"relative",ref:y,children:l&&e.jsxs("div",{className:"absolute top-full right-0 mt-2 w-80 bg-surface border border-border rounded-xl shadow-2xl z-50 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-bg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",style:{color:j?"#22c55e":"#f59e0b"},children:j?"verified":"warning"}),e.jsx("span",{className:"text-sm font-semibold text-text-main",children:"Model Status"})]}),e.jsx("button",{onClick:N,className:"p-1 rounded-lg hover:bg-surface text-text-muted hover:text-text-main transition-colors",title:"Refresh",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"refresh"})})]}),e.jsx("div",{className:"px-4 py-3 max-h-60 overflow-y-auto",children:j?e.jsx("p",{className:"text-sm text-text-muted text-center py-2",children:"All models are responding normally."}):e.jsx("div",{className:"flex flex-col gap-2.5",children:Object.entries(k).map(([x,g])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-text-main mb-1.5 capitalize",children:x}),e.jsx("div",{className:"flex flex-col gap-1",children:g.map(o=>{const n=te[o.status]||te.unknown,b=w===`${o.provider}:${o.model}`;return e.jsxs("div",{className:"flex items-center justify-between px-2.5 py-1.5 rounded-lg bg-surface/30",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px] shrink-0",style:{color:n.color},children:n.icon}),e.jsx("span",{className:"font-mono text-xs text-text-main truncate",children:o.model})]}),o.status==="cooldown"&&e.jsx(_,{size:"sm",variant:"ghost",onClick:()=>C(o.provider,o.model),disabled:b,className:"text-[10px] px-1.5! py-0.5! ml-2",children:b?"...":"Clear"})]},`${o.provider}-${o.model}`)})})]},x))})})]})})}function ce(r,a,m){const s=[];if(r>0&&s.push(e.jsxs(P,{variant:"success",size:"sm",dot:!0,children:[r," Connected"]},"connected")),a>0){const l=m?`${a} Error (${m})`:`${a} Error`;s.push(e.jsx(P,{variant:"error",size:"sm",dot:!0,children:l},"error"))}return s.length===0?e.jsx("span",{className:"text-text-muted",children:"No connections"}):s}function Re(r){if(!r)return null;const a=r.lastErrorType;if(a==="runtime_error")return"RUNTIME";if(a==="upstream_auth_error"||a==="auth_missing"||a==="token_refresh_failed"||a==="token_expired")return"AUTH";if(a==="upstream_rate_limited")return"429";if(a==="upstream_unavailable")return"5XX";if(a==="network_error")return"NET";const m=Number(r.errorCode);if(Number.isFinite(m)&&m>=400)return String(m);const s=Ae(r.lastError);if(s==="401"||s==="403")return"AUTH";if(s&&s!=="ERR")return s;const l=(r.lastError||"").toLowerCase();return l.includes("runtime")||l.includes("not runnable")||l.includes("not installed")?"RUNTIME":l.includes("invalid api key")||l.includes("token invalid")||l.includes("revoked")||l.includes("unauthorized")?"AUTH":"ERR"}const se=20;function De(){const[r,a]=c.useState([]),[m,s]=c.useState([]),[l,h]=c.useState(!0),[w,v]=c.useState(!1),[y,u]=c.useState(!1),[N,C]=c.useState(!1),[p,I]=c.useState(null),[j,k]=c.useState(null),x=ae(),g=Y(t=>t.query),o=Y(t=>t.register),n=Y(t=>t.unregister);c.useEffect(()=>(o("Search providers..."),()=>n()),[o,n]);const b=t=>!g.trim()||t.toLowerCase().includes(g.trim().toLowerCase()),K=(t,d)=>[...t].sort(([f,S],[A,R])=>{const q=D(f,d),F=D(A,d),L=q.connected>0?1:0,U=F.connected>0?1:0;return L!==U?U-L:(S.name||"").localeCompare(R.name||"")});c.useEffect(()=>{(async()=>{try{const[d,f]=await Promise.all([fetch("/api/providers"),fetch("/api/provider-nodes")]),S=await d.json(),A=await f.json();d.ok&&a(S.connections||[]),f.ok&&s(A.nodes||[])}catch(d){console.log("Error fetching data:",d)}finally{h(!1)}})()},[]);const D=(t,d)=>{const f=r.filter(T=>T.provider===t&&(T.authType===d||(t==="codebuddy"||t==="kimchi")&&T.authType==="apikey")),S=T=>{const E=Object.entries(T).some(([be,Z])=>be.startsWith("modelLock_")&&Z&&new Date(Z).getTime()>Date.now());return T.testStatus==="unavailable"&&!E?"active":T.testStatus},A=f.filter(T=>{const E=S(T);return E==="active"||E==="success"}).length,R=f.filter(T=>{const E=S(T);return E==="error"||E==="expired"||E==="unavailable"}),q=R.length,F=f.length,L=F>0&&f.every(T=>T.isActive===!1),U=R.sort((T,E)=>new Date(E.lastErrorAt||0)-new Date(T.lastErrorAt||0))[0],fe=U?Re(U):null,ge=U!=null&&U.lastErrorAt?Ie(U.lastErrorAt):null;return{connected:A,error:q,total:F,errorCode:fe,errorTime:ge,allDisabled:L}},$=async(t,d,f)=>{const S=r.filter(A=>A.provider===t&&A.authType===d);a(A=>A.map(R=>R.provider===t&&R.authType===d?{...R,isActive:f}:R)),await Promise.allSettled(S.map(A=>fetch(`/api/providers/${A.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:f})})))},V=async(t,d=null)=>{if(!p){I(t==="provider"?d:t),k(null);try{const S=await(await fetch("/api/providers/test-batch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:t,providerId:d})})).json();if(k(S),S.summary){const{passed:A,failed:R,total:q}=S.summary;R===0?x.success(`All ${q} tests passed`):x.warning(`${A}/${q} passed, ${R} failed`)}}catch{k({error:"Test request failed"}),x.error("Provider test failed")}finally{I(null)}}},B=m.filter(t=>t.type==="openai-compatible").map(t=>({id:t.id,name:t.name||"OpenAI Compatible",color:"#10A37F",textIcon:"OC",apiType:t.apiType})).filter(t=>b(t.name)),W=m.filter(t=>t.type==="anthropic-compatible").map(t=>({id:t.id,name:t.name||"Anthropic Compatible",color:"#D97757",textIcon:"AC"})).filter(t=>b(t.name)),H=Object.entries(ve).filter(([,t])=>!t.hidden&&b(t.name)),J=Object.entries(ye).filter(([,t])=>!t.hidden&&b(t.name)),X=Object.entries(je).filter(([,t])=>!t.hidden&&b(t.name)),M=K(Object.entries(Ne).filter(([,t])=>!t.hidden&&(t.serviceKinds??["llm"]).includes("llm")&&b(t.name)),"apikey"),Q=!!g.trim(),xe=Q||w?M:M.slice(0,se),ue=M.length-se;if(l)return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsx(ee,{}),e.jsx(ee,{})]});const he=H.length>0||J.length>0||X.length>0||M.length>0||B.length>0||W.length>0;return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6 px-1 sm:px-0",children:[!he&&e.jsxs("div",{className:"text-center py-8 border border-dashed border-border rounded-xl",children:[e.jsx("span",{className:"material-symbols-outlined text-[32px] text-text-muted mb-2",children:"search_off"}),e.jsx("p",{className:"text-text-muted text-sm",children:"No providers match your search"})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:["Custom Providers (OpenAI/Anthropic Compatible)"," "]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:flex sm:w-auto",children:[e.jsx(_,{size:"sm",icon:"add",onClick:()=>C(!0),className:"w-full sm:w-auto",children:"Add Anthropic Compatible"}),e.jsx(_,{size:"sm",variant:"secondary",icon:"add",onClick:()=>u(!0),className:"w-full !bg-white !text-black hover:!bg-gray-100 sm:w-auto",children:"Add OpenAI Compatible"})]})]}),B.length===0&&W.length===0?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 border border-dashed border-border rounded-xl text-text-muted text-sm",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"extension"}),e.jsx("span",{children:"No custom providers — use buttons above to add OpenAI/Anthropic compatible endpoints"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:[...B,...W].map(t=>e.jsx(z,{providerId:t.id,provider:t,stats:D(t.id,"apikey"),authType:"compatible",onToggle:d=>$(t.id,"apikey",d)},t.id))})]}),H.length>0&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:"OAuth Providers"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx(Se,{}),e.jsxs("button",{onClick:()=>V("oauth"),disabled:!!p,className:`flex w-full items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-medium transition-colors sm:w-auto sm:py-1.5 ${p==="oauth"?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg border-border text-text-muted hover:text-text-main hover:border-primary/40"}`,title:"Test all OAuth connections","aria-label":"Test all OAuth connections",children:[e.jsx("span",{className:`material-symbols-outlined text-[14px]${p==="oauth"?" animate-spin":""}`,children:"play_arrow"}),p==="oauth"?"Testing...":"Test All"]})]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:H.map(([t,d])=>e.jsx(G,{providerId:t,provider:d,stats:D(t,"oauth"),authType:"oauth",onToggle:f=>$(t,"oauth",f)},t))})]}),(J.length>0||X.length>0)&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:"Free Tier Providers"}),e.jsxs("button",{onClick:()=>V("free"),disabled:!!p,className:`flex w-full items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-medium transition-colors sm:w-auto sm:py-1.5 ${p==="free"?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg border-border text-text-muted hover:text-text-main hover:border-primary/40"}`,title:"Test all Free connections","aria-label":"Test all Free provider connections",children:[e.jsx("span",{className:`material-symbols-outlined text-[14px]${p==="free"?" animate-spin":""}`,children:"play_arrow"}),p==="free"?"Testing...":"Test All"]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:[J.map(([t,d])=>e.jsx(G,{providerId:t,provider:d,stats:D(t,"oauth"),authType:"free",onToggle:f=>$(t,"oauth",f)},t)),X.map(([t,d])=>e.jsx(z,{providerId:t,provider:d,stats:D(t,"apikey"),authType:"apikey",onToggle:f=>$(t,"apikey",f)},t))]})]}),M.length>0&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:["API Key Providers"," "]}),e.jsxs("button",{onClick:()=>V("apikey"),disabled:!!p,className:`flex w-full items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-medium transition-colors sm:w-auto sm:py-1.5 ${p==="apikey"?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg border-border text-text-muted hover:text-text-main hover:border-primary/40"}`,title:"Test all API Key connections","aria-label":"Test all API Key connections",children:[e.jsx("span",{className:`material-symbols-outlined text-[14px]${p==="apikey"?" animate-spin":""}`,children:"play_arrow"}),p==="apikey"?"Testing...":"Test All"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:xe.map(([t,d])=>e.jsx(z,{providerId:t,provider:d,stats:D(t,"apikey"),authType:"apikey",onToggle:f=>$(t,"apikey",f)},t))}),!Q&&!w&&ue>0&&e.jsxs("button",{onClick:()=>v(!0),className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-primary/40 px-3 py-2.5 text-sm font-medium text-primary transition-colors hover:border-primary hover:bg-primary/5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"expand_more"}),"Show all ",M.length," providers"]})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:["Web Cookie Providers"," "]})}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:Object.entries(Ce).map(([t,d])=>e.jsx(z,{providerId:t,provider:d,stats:D(t,"apikey"),authType:"apikey",onToggle:f=>$(t,"apikey",f)},t))})]}),e.jsx(de,{isOpen:y,onClose:()=>u(!1),onCreated:t=>{s(d=>[...d,t]),u(!1)}}),e.jsx(me,{isOpen:N,onClose:()=>C(!1),onCreated:t=>{s(d=>[...d,t]),C(!1)}}),j&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center px-3 pt-[6vh] sm:pt-[10vh]",onClick:()=>k(null),children:[e.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-surface border border-border rounded-xl w-full max-w-[600px] max-h-[86vh] sm:max-h-[80vh] overflow-y-auto shadow-2xl",onClick:t=>t.stopPropagation(),children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-5 py-3 border-b border-border bg-surface/95 backdrop-blur-sm rounded-t-xl",children:[e.jsx("h3",{className:"font-semibold",children:"Test Results"}),e.jsx("button",{onClick:()=>k(null),className:"p-1 rounded-lg hover:bg-bg text-text-muted hover:text-text-main transition-colors","aria-label":"Close test results",children:e.jsx("span",{className:"material-symbols-outlined text-lg",children:"close"})})]}),e.jsx("div",{className:"p-5",children:e.jsx(pe,{results:j})})]})]})]})}function G({providerId:r,provider:a,stats:m,authType:s,onToggle:l}){var C;const{connected:h,error:w,errorCode:v,errorTime:y,allDisabled:u}=m,N=!!a.noAuth;return e.jsx(le,{to:`/dashboard/providers/${r}`,className:"group min-w-0",children:e.jsx(ne,{padding:"xs",className:`h-full hover:bg-black/[0.01] dark:hover:bg-white/[0.01] transition-colors cursor-pointer ${u?"opacity-50":""}`,children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"size-8 shrink-0 rounded-lg flex items-center justify-center",style:{backgroundColor:`${((C=a.color)==null?void 0:C.length)>7?a.color:a.color+"15"}`},children:e.jsx(re,{src:a.id==="codebuddy"||a.id==="cb"?"/providers/codebuddy.svg":`/providers/${a.id}.png`,alt:a.name,size:30,className:"object-contain rounded-lg max-w-[32px] max-h-[32px]",fallbackText:a.textIcon||a.id.slice(0,2).toUpperCase(),fallbackColor:a.color})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate font-semibold",children:a.name}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-xs flex-wrap",children:u?e.jsx(P,{variant:"default",size:"sm",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:"pause_circle"}),"Disabled"]})}):N?e.jsx(P,{variant:"success",size:"sm",dot:!0,children:"Ready"}):e.jsxs(e.Fragment,{children:[ce(h,w,v),y&&e.jsx("span",{className:"text-text-muted",children:y})]})})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:m.total>0&&e.jsx("div",{className:"opacity-100 transition-opacity sm:opacity-0 sm:group-hover:opacity-100",onClick:p=>{p.preventDefault(),p.stopPropagation(),l(!!u)},children:e.jsx(oe,{size:"sm",checked:!u,onChange:()=>{},title:u?"Enable provider":"Disable provider"})})})]})})})}G.propTypes={providerId:i.string.isRequired,provider:i.shape({id:i.string.isRequired,name:i.string.isRequired,color:i.string,textIcon:i.string}).isRequired,stats:i.shape({connected:i.number,error:i.number,errorCode:i.string,errorTime:i.string}).isRequired,authType:i.string,onToggle:i.func};function z({providerId:r,provider:a,stats:m,authType:s,onToggle:l}){var I;const{connected:h,error:w,errorCode:v,errorTime:y,allDisabled:u}=m,N=r.startsWith(we),C=r.startsWith(Te),p=()=>a.id==="codebuddy"||a.id==="cb"?"/providers/codebuddy.svg":N?a.apiType==="responses"?"/providers/oai-r.png":"/providers/oai-cc.png":C?"/providers/anthropic-m.png":`/providers/${a.id}.png`;return e.jsx(le,{to:`/dashboard/providers/${r}`,className:"group min-w-0",children:e.jsx(ne,{padding:"xs",className:`h-full hover:bg-black/[0.01] dark:hover:bg-white/[0.01] transition-colors cursor-pointer ${u?"opacity-50":""}`,children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"size-8 shrink-0 rounded-lg flex items-center justify-center",style:{backgroundColor:`${((I=a.color)==null?void 0:I.length)>7?a.color:a.color+"15"}`},children:e.jsx(re,{src:p(),alt:a.name,size:30,className:"object-contain rounded-lg max-w-[30px] max-h-[30px]",fallbackText:a.textIcon||a.id.slice(0,2).toUpperCase(),fallbackColor:a.color})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate font-semibold",children:a.name}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-xs flex-wrap",children:u?e.jsx(P,{variant:"default",size:"sm",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:"pause_circle"}),"Disabled"]})}):e.jsxs(e.Fragment,{children:[ce(h,w,v),N&&e.jsx(P,{variant:"default",size:"sm",children:a.apiType==="responses"?"Responses":"Chat"}),C&&e.jsx(P,{variant:"default",size:"sm",children:"Messages"}),y&&e.jsx("span",{className:"text-text-muted",children:y})]})})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:m.total>0&&e.jsx("div",{className:"opacity-100 transition-opacity sm:opacity-0 sm:group-hover:opacity-100",onClick:j=>{j.preventDefault(),j.stopPropagation(),l(!!u)},children:e.jsx(oe,{size:"sm",checked:!u,onChange:()=>{},title:u?"Enable provider":"Disable provider"})})})]})})})}z.propTypes={providerId:i.string.isRequired,provider:i.shape({id:i.string.isRequired,name:i.string.isRequired,color:i.string,textIcon:i.string,apiType:i.string}).isRequired,stats:i.shape({connected:i.number,error:i.number,errorCode:i.string,errorTime:i.string}).isRequired,authType:i.string,onToggle:i.func};function de({isOpen:r,onClose:a,onCreated:m}){const[s,l]=c.useState({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1"}),[h,w]=c.useState(!1),[v,y]=c.useState(""),[u,N]=c.useState(""),[C,p]=c.useState(!1),[I,j]=c.useState(null),k=[{value:"chat",label:"Chat Completions"},{value:"responses",label:"Responses API"}];c.useEffect(()=>{const n="https://api.openai.com/v1";l(b=>({...b,baseUrl:n}))},[s.apiType]);const x=async()=>{if(!(!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim())){w(!0);try{const n=await fetch("/api/provider-nodes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s.name,prefix:s.prefix,apiType:s.apiType,baseUrl:s.baseUrl,type:"openai-compatible"})}),b=await n.json();n.ok&&(m(b.node),l({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1"}),y(""),j(null))}catch(n){console.log("Error creating OpenAI Compatible node:",n)}finally{w(!1)}}},g=async()=>{p(!0);try{const b=await(await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:s.baseUrl,apiKey:v,type:"openai-compatible",modelId:u.trim()||void 0})})).json();j(b)}catch{j({valid:!1,error:"Network error"})}finally{p(!1)}},o=()=>{if(!I)return null;const{valid:n,error:b,method:K}=I;return n?e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"success",children:"Valid"}),K==="chat"&&e.jsx("span",{className:"text-sm text-text-muted",children:"(via inference test)"})]}):e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(P,{variant:"error",children:"Invalid"}),b&&e.jsx("span",{className:"text-sm text-red-500",children:b})]})};return e.jsx(ie,{isOpen:r,title:"Add OpenAI Compatible",onClose:a,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(O,{label:"Name",value:s.name,onChange:n=>l({...s,name:n.target.value}),placeholder:"OpenAI Compatible (Prod)",hint:"Required. A friendly label for this node."}),e.jsx(O,{label:"Prefix",value:s.prefix,onChange:n=>l({...s,prefix:n.target.value}),placeholder:"oc-prod",hint:"Required. Used as the provider prefix for model IDs."}),e.jsx(ke,{label:"API Type",options:k,value:s.apiType,onChange:n=>l({...s,apiType:n.target.value})}),e.jsx(O,{label:"Base URL",value:s.baseUrl,onChange:n=>l({...s,baseUrl:n.target.value}),placeholder:"https://api.openai.com/v1",hint:"Use the base URL (ending in /v1) for your OpenAI-compatible API."}),e.jsx(O,{label:"API Key (for Check)",type:"password",value:v,onChange:n=>y(n.target.value)}),e.jsx(O,{label:"Model ID (optional)",value:u,onChange:n=>N(n.target.value),placeholder:"e.g. gpt-4, claude-3-opus",hint:"If provider lacks /models endpoint, enter a model ID to validate via chat/completions instead."}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsx(_,{onClick:g,disabled:!v||C||!s.baseUrl.trim(),variant:"secondary",className:"w-full sm:w-auto",children:C?"Checking...":"Check"}),o()]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(_,{onClick:x,fullWidth:!0,disabled:!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim()||h,children:h?"Creating...":"Create"}),e.jsx(_,{onClick:a,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})})}de.propTypes={isOpen:i.bool.isRequired,onClose:i.func.isRequired,onCreated:i.func.isRequired};function me({isOpen:r,onClose:a,onCreated:m}){const[s,l]=c.useState({name:"",prefix:"",baseUrl:"https://api.anthropic.com/v1"}),[h,w]=c.useState(!1),[v,y]=c.useState(""),[u,N]=c.useState(""),[C,p]=c.useState(!1),[I,j]=c.useState(null);c.useEffect(()=>{r&&(j(null),y(""),N(""))},[r]);const k=async()=>{if(!(!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim())){w(!0);try{const o=await fetch("/api/provider-nodes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s.name,prefix:s.prefix,baseUrl:s.baseUrl,type:"anthropic-compatible"})}),n=await o.json();o.ok&&(m(n.node),l({name:"",prefix:"",baseUrl:"https://api.anthropic.com/v1"}),y(""),j(null))}catch(o){console.log("Error creating Anthropic Compatible node:",o)}finally{w(!1)}}},x=async()=>{p(!0);try{const n=await(await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:s.baseUrl,apiKey:v,type:"anthropic-compatible",modelId:u.trim()||void 0})})).json();j(n)}catch{j({valid:!1,error:"Network error"})}finally{p(!1)}},g=()=>{if(!I)return null;const{valid:o,error:n,method:b}=I;return o?e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"success",children:"Valid"}),b==="chat"&&e.jsx("span",{className:"text-sm text-text-muted",children:"(via inference test)"})]}):e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(P,{variant:"error",children:"Invalid"}),n&&e.jsx("span",{className:"text-sm text-red-500",children:n})]})};return e.jsx(ie,{isOpen:r,title:"Add Anthropic Compatible",onClose:a,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(O,{label:"Name",value:s.name,onChange:o=>l({...s,name:o.target.value}),placeholder:"Anthropic Compatible (Prod)",hint:"Required. A friendly label for this node."}),e.jsx(O,{label:"Prefix",value:s.prefix,onChange:o=>l({...s,prefix:o.target.value}),placeholder:"ac-prod",hint:"Required. Used as the provider prefix for model IDs."}),e.jsx(O,{label:"Base URL",value:s.baseUrl,onChange:o=>l({...s,baseUrl:o.target.value}),placeholder:"https://api.anthropic.com/v1",hint:"Use the base URL (ending in /v1) for your Anthropic-compatible API. The system will append /messages."}),e.jsx(O,{label:"API Key (for Check)",type:"password",value:v,onChange:o=>y(o.target.value)}),e.jsx(O,{label:"Model ID (optional)",value:u,onChange:o=>N(o.target.value),placeholder:"e.g. claude-3-opus",hint:"If provider lacks /models endpoint, enter a model ID to validate via chat/completions instead."}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsx(_,{onClick:x,disabled:!v||C||!s.baseUrl.trim(),variant:"secondary",className:"w-full sm:w-auto",children:C?"Checking...":"Check"}),g()]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(_,{onClick:k,fullWidth:!0,disabled:!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim()||h,children:h?"Creating...":"Create"}),e.jsx(_,{onClick:a,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})})}me.propTypes={isOpen:i.bool.isRequired,onClose:i.func.isRequired,onCreated:i.func.isRequired};function pe({results:r}){if(r.error&&!r.results)return e.jsxs("div",{className:"text-center py-6",children:[e.jsx("span",{className:"material-symbols-outlined text-red-500 text-[32px] mb-2 block",children:"error"}),e.jsx("p",{className:"text-sm text-red-400",children:r.error})]});const{summary:a,mode:m}=r,s=r.results||[],l={oauth:"OAuth",free:"Free",apikey:"API Key",provider:"Provider",all:"All"}[m]||m;return e.jsxs("div",{className:"flex min-w-0 flex-col gap-3",children:[a&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs mb-1 sm:gap-3",children:[e.jsxs("span",{className:"text-text-muted",children:[l," Test"]}),e.jsxs("span",{className:"px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 font-medium",children:[a.passed," passed"]}),a.failed>0&&e.jsxs("span",{className:"px-2 py-0.5 rounded bg-red-500/15 text-red-400 font-medium",children:[a.failed," failed"]}),e.jsxs("span",{className:"text-text-muted sm:ml-auto",children:[a.total," tested"]})]}),s.map((h,w)=>{var v;return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 rounded-lg bg-black/[0.03] px-3 py-2 text-xs dark:bg-white/[0.03] sm:flex-nowrap",children:[e.jsx("span",{className:`material-symbols-outlined text-[16px] ${h.valid?"text-emerald-500":"text-red-500"}`,children:h.valid?"check_circle":"error"}),e.jsxs("div",{className:"min-w-0 flex-[1_1_160px]",children:[e.jsx("span",{className:"block truncate font-medium sm:inline",children:h.connectionName}),e.jsxs("span",{className:"block truncate text-text-muted sm:ml-1.5 sm:inline",children:["(",h.provider,")"]})]}),h.latencyMs!==void 0&&e.jsxs("span",{className:"shrink-0 text-text-muted font-mono tabular-nums",children:[h.latencyMs,"ms"]}),e.jsx("span",{className:`shrink-0 text-[10px] uppercase font-bold px-1.5 py-0.5 rounded ${h.valid?"bg-emerald-500/15 text-emerald-400":"bg-red-500/15 text-red-400"}`,children:h.valid?"OK":((v=h.diagnosis)==null?void 0:v.type)||"ERROR"})]},h.connectionId||w)}),s.length===0&&e.jsx("div",{className:"text-center py-4 text-text-muted text-sm",children:"No active connections found for this group."})]})}pe.propTypes={results:i.shape({mode:i.string,results:i.array,summary:i.shape({total:i.number,passed:i.number,failed:i.number}),error:i.string}).isRequired};export{De as default};
1
+ import{a as ae,j as e,B as _,b as Y,O as ve,F as ye,c as je,A as Ne,W as Ce,d as we,e as Te,P as re,M as ie,f as i}from"./index.CShjRV_B.js";import{b as c,L as le}from"./router.Cjj1--8t.js";import{C as ne,B as P,T as oe,I as O,S as ke}from"./NoAuthProxyCard.qAv57b-0.js";import{C as ee}from"./Loading.Bj-WGl4k.js";import"./zustand.akaTi5uX.js";function Ae(r){if(!r)return null;const a=r.match(/\b([45]\d{2})\b/);return a?a[1]:"ERR"}function Ie(r){if(!r)return"";const a=Date.now()-new Date(r).getTime(),m=Math.floor(a/6e4);if(m<1)return"just now";if(m<60)return`${m}m ago`;const s=Math.floor(m/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}const te={available:{icon:"check_circle",color:"#22c55e",label:"Available"},cooldown:{icon:"schedule",color:"#f59e0b",label:"Cooldown"},unavailable:{icon:"error",color:"#ef4444",label:"Unavailable"},unknown:{icon:"help",color:"#6b7280",label:"Unknown"}};function Se(){const[r,a]=c.useState(null),[m,s]=c.useState(!0),[l,h]=c.useState(!1),[w,v]=c.useState(null),y=c.useRef(null),u=ae(),N=c.useCallback(async()=>{try{const x=await fetch("/api/models/availability");if(x.ok){const g=await x.json();a(g)}}catch{}finally{s(!1)}},[]);c.useEffect(()=>{N();const x=setInterval(N,3e4);return()=>clearInterval(x)},[N]),c.useEffect(()=>{const x=g=>{y.current&&!y.current.contains(g.target)&&h(!1)};return l&&document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]);const C=async(x,g)=>{v(`${x}:${g}`);try{(await fetch("/api/models/availability",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clearCooldown",provider:x,model:g})})).ok?(u.success(`Cooldown cleared for ${g}`),await N()):u.error("Failed to clear cooldown")}catch{u.error("Failed to clear cooldown")}finally{v(null)}};if(m)return null;const p=(r==null?void 0:r.models)||[],j=((r==null?void 0:r.unavailableCount)||p.filter(x=>x.status!=="available").length)===0,k={};return p.forEach(x=>{if(x.status==="available")return;const g=x.provider||"unknown";k[g]||(k[g]=[]),k[g].push(x)}),e.jsx("div",{className:"relative",ref:y,children:l&&e.jsxs("div",{className:"absolute top-full right-0 mt-2 w-80 bg-surface border border-border rounded-xl shadow-2xl z-50 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-bg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",style:{color:j?"#22c55e":"#f59e0b"},children:j?"verified":"warning"}),e.jsx("span",{className:"text-sm font-semibold text-text-main",children:"Model Status"})]}),e.jsx("button",{onClick:N,className:"p-1 rounded-lg hover:bg-surface text-text-muted hover:text-text-main transition-colors",title:"Refresh",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"refresh"})})]}),e.jsx("div",{className:"px-4 py-3 max-h-60 overflow-y-auto",children:j?e.jsx("p",{className:"text-sm text-text-muted text-center py-2",children:"All models are responding normally."}):e.jsx("div",{className:"flex flex-col gap-2.5",children:Object.entries(k).map(([x,g])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-text-main mb-1.5 capitalize",children:x}),e.jsx("div",{className:"flex flex-col gap-1",children:g.map(o=>{const n=te[o.status]||te.unknown,b=w===`${o.provider}:${o.model}`;return e.jsxs("div",{className:"flex items-center justify-between px-2.5 py-1.5 rounded-lg bg-surface/30",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px] shrink-0",style:{color:n.color},children:n.icon}),e.jsx("span",{className:"font-mono text-xs text-text-main truncate",children:o.model})]}),o.status==="cooldown"&&e.jsx(_,{size:"sm",variant:"ghost",onClick:()=>C(o.provider,o.model),disabled:b,className:"text-[10px] px-1.5! py-0.5! ml-2",children:b?"...":"Clear"})]},`${o.provider}-${o.model}`)})})]},x))})})]})})}function ce(r,a,m){const s=[];if(r>0&&s.push(e.jsxs(P,{variant:"success",size:"sm",dot:!0,children:[r," Connected"]},"connected")),a>0){const l=m?`${a} Error (${m})`:`${a} Error`;s.push(e.jsx(P,{variant:"error",size:"sm",dot:!0,children:l},"error"))}return s.length===0?e.jsx("span",{className:"text-text-muted",children:"No connections"}):s}function Re(r){if(!r)return null;const a=r.lastErrorType;if(a==="runtime_error")return"RUNTIME";if(a==="upstream_auth_error"||a==="auth_missing"||a==="token_refresh_failed"||a==="token_expired")return"AUTH";if(a==="upstream_rate_limited")return"429";if(a==="upstream_unavailable")return"5XX";if(a==="network_error")return"NET";const m=Number(r.errorCode);if(Number.isFinite(m)&&m>=400)return String(m);const s=Ae(r.lastError);if(s==="401"||s==="403")return"AUTH";if(s&&s!=="ERR")return s;const l=(r.lastError||"").toLowerCase();return l.includes("runtime")||l.includes("not runnable")||l.includes("not installed")?"RUNTIME":l.includes("invalid api key")||l.includes("token invalid")||l.includes("revoked")||l.includes("unauthorized")?"AUTH":"ERR"}const se=20;function De(){const[r,a]=c.useState([]),[m,s]=c.useState([]),[l,h]=c.useState(!0),[w,v]=c.useState(!1),[y,u]=c.useState(!1),[N,C]=c.useState(!1),[p,I]=c.useState(null),[j,k]=c.useState(null),x=ae(),g=Y(t=>t.query),o=Y(t=>t.register),n=Y(t=>t.unregister);c.useEffect(()=>(o("Search providers..."),()=>n()),[o,n]);const b=t=>!g.trim()||t.toLowerCase().includes(g.trim().toLowerCase()),K=(t,d)=>[...t].sort(([f,S],[A,R])=>{const q=D(f,d),F=D(A,d),L=q.connected>0?1:0,U=F.connected>0?1:0;return L!==U?U-L:(S.name||"").localeCompare(R.name||"")});c.useEffect(()=>{(async()=>{try{const[d,f]=await Promise.all([fetch("/api/providers"),fetch("/api/provider-nodes")]),S=await d.json(),A=await f.json();d.ok&&a(S.connections||[]),f.ok&&s(A.nodes||[])}catch(d){console.log("Error fetching data:",d)}finally{h(!1)}})()},[]);const D=(t,d)=>{const f=r.filter(T=>T.provider===t&&(T.authType===d||(t==="codebuddy"||t==="kimchi")&&T.authType==="apikey")),S=T=>{const E=Object.entries(T).some(([be,Z])=>be.startsWith("modelLock_")&&Z&&new Date(Z).getTime()>Date.now());return T.testStatus==="unavailable"&&!E?"active":T.testStatus},A=f.filter(T=>{const E=S(T);return E==="active"||E==="success"}).length,R=f.filter(T=>{const E=S(T);return E==="error"||E==="expired"||E==="unavailable"}),q=R.length,F=f.length,L=F>0&&f.every(T=>T.isActive===!1),U=R.sort((T,E)=>new Date(E.lastErrorAt||0)-new Date(T.lastErrorAt||0))[0],fe=U?Re(U):null,ge=U!=null&&U.lastErrorAt?Ie(U.lastErrorAt):null;return{connected:A,error:q,total:F,errorCode:fe,errorTime:ge,allDisabled:L}},$=async(t,d,f)=>{const S=r.filter(A=>A.provider===t&&A.authType===d);a(A=>A.map(R=>R.provider===t&&R.authType===d?{...R,isActive:f}:R)),await Promise.allSettled(S.map(A=>fetch(`/api/providers/${A.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:f})})))},V=async(t,d=null)=>{if(!p){I(t==="provider"?d:t),k(null);try{const S=await(await fetch("/api/providers/test-batch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:t,providerId:d})})).json();if(k(S),S.summary){const{passed:A,failed:R,total:q}=S.summary;R===0?x.success(`All ${q} tests passed`):x.warning(`${A}/${q} passed, ${R} failed`)}}catch{k({error:"Test request failed"}),x.error("Provider test failed")}finally{I(null)}}},B=m.filter(t=>t.type==="openai-compatible").map(t=>({id:t.id,name:t.name||"OpenAI Compatible",color:"#10A37F",textIcon:"OC",apiType:t.apiType})).filter(t=>b(t.name)),W=m.filter(t=>t.type==="anthropic-compatible").map(t=>({id:t.id,name:t.name||"Anthropic Compatible",color:"#D97757",textIcon:"AC"})).filter(t=>b(t.name)),H=Object.entries(ve).filter(([,t])=>!t.hidden&&b(t.name)),J=Object.entries(ye).filter(([,t])=>!t.hidden&&b(t.name)),X=Object.entries(je).filter(([,t])=>!t.hidden&&b(t.name)),M=K(Object.entries(Ne).filter(([,t])=>!t.hidden&&(t.serviceKinds??["llm"]).includes("llm")&&b(t.name)),"apikey"),Q=!!g.trim(),xe=Q||w?M:M.slice(0,se),ue=M.length-se;if(l)return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsx(ee,{}),e.jsx(ee,{})]});const he=H.length>0||J.length>0||X.length>0||M.length>0||B.length>0||W.length>0;return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6 px-1 sm:px-0",children:[!he&&e.jsxs("div",{className:"text-center py-8 border border-dashed border-border rounded-xl",children:[e.jsx("span",{className:"material-symbols-outlined text-[32px] text-text-muted mb-2",children:"search_off"}),e.jsx("p",{className:"text-text-muted text-sm",children:"No providers match your search"})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:["Custom Providers (OpenAI/Anthropic Compatible)"," "]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:flex sm:w-auto",children:[e.jsx(_,{size:"sm",icon:"add",onClick:()=>C(!0),className:"w-full sm:w-auto",children:"Add Anthropic Compatible"}),e.jsx(_,{size:"sm",variant:"secondary",icon:"add",onClick:()=>u(!0),className:"w-full !bg-white !text-black hover:!bg-gray-100 sm:w-auto",children:"Add OpenAI Compatible"})]})]}),B.length===0&&W.length===0?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 border border-dashed border-border rounded-xl text-text-muted text-sm",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"extension"}),e.jsx("span",{children:"No custom providers — use buttons above to add OpenAI/Anthropic compatible endpoints"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:[...B,...W].map(t=>e.jsx(z,{providerId:t.id,provider:t,stats:D(t.id,"apikey"),authType:"compatible",onToggle:d=>$(t.id,"apikey",d)},t.id))})]}),H.length>0&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:"OAuth Providers"}),e.jsxs("div",{className:"flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center",children:[e.jsx(Se,{}),e.jsxs("button",{onClick:()=>V("oauth"),disabled:!!p,className:`flex w-full items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-medium transition-colors sm:w-auto sm:py-1.5 ${p==="oauth"?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg border-border text-text-muted hover:text-text-main hover:border-primary/40"}`,title:"Test all OAuth connections","aria-label":"Test all OAuth connections",children:[e.jsx("span",{className:`material-symbols-outlined text-[14px]${p==="oauth"?" animate-spin":""}`,children:"play_arrow"}),p==="oauth"?"Testing...":"Test All"]})]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:H.map(([t,d])=>e.jsx(G,{providerId:t,provider:d,stats:D(t,"oauth"),authType:"oauth",onToggle:f=>$(t,"oauth",f)},t))})]}),(J.length>0||X.length>0)&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:"Free Tier Providers"}),e.jsxs("button",{onClick:()=>V("free"),disabled:!!p,className:`flex w-full items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-medium transition-colors sm:w-auto sm:py-1.5 ${p==="free"?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg border-border text-text-muted hover:text-text-main hover:border-primary/40"}`,title:"Test all Free connections","aria-label":"Test all Free provider connections",children:[e.jsx("span",{className:`material-symbols-outlined text-[14px]${p==="free"?" animate-spin":""}`,children:"play_arrow"}),p==="free"?"Testing...":"Test All"]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:[J.map(([t,d])=>e.jsx(G,{providerId:t,provider:d,stats:D(t,"oauth"),authType:"free",onToggle:f=>$(t,"oauth",f)},t)),X.map(([t,d])=>e.jsx(z,{providerId:t,provider:d,stats:D(t,"apikey"),authType:"apikey",onToggle:f=>$(t,"apikey",f)},t))]})]}),M.length>0&&e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("h2",{className:"text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight",children:["API Key Providers"," "]}),e.jsxs("button",{onClick:()=>V("apikey"),disabled:!!p,className:`flex w-full items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-medium transition-colors sm:w-auto sm:py-1.5 ${p==="apikey"?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg border-border text-text-muted hover:text-text-main hover:border-primary/40"}`,title:"Test all API Key connections","aria-label":"Test all API Key connections",children:[e.jsx("span",{className:`material-symbols-outlined text-[14px]${p==="apikey"?" animate-spin":""}`,children:"play_arrow"}),p==="apikey"?"Testing...":"Test All"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4",children:xe.map(([t,d])=>e.jsx(z,{providerId:t,provider:d,stats:D(t,"apikey"),authType:"apikey",onToggle:f=>$(t,"apikey",f)},t))}),!Q&&!w&&ue>0&&e.jsxs("button",{onClick:()=>v(!0),className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-primary/40 px-3 py-2.5 text-sm font-medium text-primary transition-colors hover:border-primary hover:bg-primary/5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"expand_more"}),"Show all ",M.length," providers"]})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:["Web Cookie Providers"," "]})}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:Object.entries(Ce).map(([t,d])=>e.jsx(z,{providerId:t,provider:d,stats:D(t,"apikey"),authType:"apikey",onToggle:f=>$(t,"apikey",f)},t))})]}),e.jsx(de,{isOpen:y,onClose:()=>u(!1),onCreated:t=>{s(d=>[...d,t]),u(!1)}}),e.jsx(me,{isOpen:N,onClose:()=>C(!1),onCreated:t=>{s(d=>[...d,t]),C(!1)}}),j&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center px-3 pt-[6vh] sm:pt-[10vh]",onClick:()=>k(null),children:[e.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-surface border border-border rounded-xl w-full max-w-[600px] max-h-[86vh] sm:max-h-[80vh] overflow-y-auto shadow-2xl",onClick:t=>t.stopPropagation(),children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-5 py-3 border-b border-border bg-surface/95 backdrop-blur-sm rounded-t-xl",children:[e.jsx("h3",{className:"font-semibold",children:"Test Results"}),e.jsx("button",{onClick:()=>k(null),className:"p-1 rounded-lg hover:bg-bg text-text-muted hover:text-text-main transition-colors","aria-label":"Close test results",children:e.jsx("span",{className:"material-symbols-outlined text-lg",children:"close"})})]}),e.jsx("div",{className:"p-5",children:e.jsx(pe,{results:j})})]})]})]})}function G({providerId:r,provider:a,stats:m,authType:s,onToggle:l}){var C;const{connected:h,error:w,errorCode:v,errorTime:y,allDisabled:u}=m,N=!!a.noAuth;return e.jsx(le,{to:`/dashboard/providers/${r}`,className:"group min-w-0",children:e.jsx(ne,{padding:"xs",className:`h-full hover:bg-black/[0.01] dark:hover:bg-white/[0.01] transition-colors cursor-pointer ${u?"opacity-50":""}`,children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"size-8 shrink-0 rounded-lg flex items-center justify-center",style:{backgroundColor:`${((C=a.color)==null?void 0:C.length)>7?a.color:a.color+"15"}`},children:e.jsx(re,{src:a.id==="codebuddy"||a.id==="cb"?"/providers/codebuddy.svg":`/providers/${a.id}.png`,alt:a.name,size:30,className:"object-contain rounded-lg max-w-[32px] max-h-[32px]",fallbackText:a.textIcon||a.id.slice(0,2).toUpperCase(),fallbackColor:a.color})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate font-semibold",children:a.name}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-xs flex-wrap",children:u?e.jsx(P,{variant:"default",size:"sm",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:"pause_circle"}),"Disabled"]})}):N?e.jsx(P,{variant:"success",size:"sm",dot:!0,children:"Ready"}):e.jsxs(e.Fragment,{children:[ce(h,w,v),y&&e.jsx("span",{className:"text-text-muted",children:y})]})})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:m.total>0&&e.jsx("div",{className:"opacity-100 transition-opacity sm:opacity-0 sm:group-hover:opacity-100",onClick:p=>{p.preventDefault(),p.stopPropagation(),l(!!u)},children:e.jsx(oe,{size:"sm",checked:!u,onChange:()=>{},title:u?"Enable provider":"Disable provider"})})})]})})})}G.propTypes={providerId:i.string.isRequired,provider:i.shape({id:i.string.isRequired,name:i.string.isRequired,color:i.string,textIcon:i.string}).isRequired,stats:i.shape({connected:i.number,error:i.number,errorCode:i.string,errorTime:i.string}).isRequired,authType:i.string,onToggle:i.func};function z({providerId:r,provider:a,stats:m,authType:s,onToggle:l}){var I;const{connected:h,error:w,errorCode:v,errorTime:y,allDisabled:u}=m,N=r.startsWith(we),C=r.startsWith(Te),p=()=>a.id==="codebuddy"||a.id==="cb"?"/providers/codebuddy.svg":N?a.apiType==="responses"?"/providers/oai-r.png":"/providers/oai-cc.png":C?"/providers/anthropic-m.png":`/providers/${a.id}.png`;return e.jsx(le,{to:`/dashboard/providers/${r}`,className:"group min-w-0",children:e.jsx(ne,{padding:"xs",className:`h-full hover:bg-black/[0.01] dark:hover:bg-white/[0.01] transition-colors cursor-pointer ${u?"opacity-50":""}`,children:e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"size-8 shrink-0 rounded-lg flex items-center justify-center",style:{backgroundColor:`${((I=a.color)==null?void 0:I.length)>7?a.color:a.color+"15"}`},children:e.jsx(re,{src:p(),alt:a.name,size:30,className:"object-contain rounded-lg max-w-[30px] max-h-[30px]",fallbackText:a.textIcon||a.id.slice(0,2).toUpperCase(),fallbackColor:a.color})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate font-semibold",children:a.name}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-xs flex-wrap",children:u?e.jsx(P,{variant:"default",size:"sm",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:"pause_circle"}),"Disabled"]})}):e.jsxs(e.Fragment,{children:[ce(h,w,v),N&&e.jsx(P,{variant:"default",size:"sm",children:a.apiType==="responses"?"Responses":"Chat"}),C&&e.jsx(P,{variant:"default",size:"sm",children:"Messages"}),y&&e.jsx("span",{className:"text-text-muted",children:y})]})})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:m.total>0&&e.jsx("div",{className:"opacity-100 transition-opacity sm:opacity-0 sm:group-hover:opacity-100",onClick:j=>{j.preventDefault(),j.stopPropagation(),l(!!u)},children:e.jsx(oe,{size:"sm",checked:!u,onChange:()=>{},title:u?"Enable provider":"Disable provider"})})})]})})})}z.propTypes={providerId:i.string.isRequired,provider:i.shape({id:i.string.isRequired,name:i.string.isRequired,color:i.string,textIcon:i.string,apiType:i.string}).isRequired,stats:i.shape({connected:i.number,error:i.number,errorCode:i.string,errorTime:i.string}).isRequired,authType:i.string,onToggle:i.func};function de({isOpen:r,onClose:a,onCreated:m}){const[s,l]=c.useState({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1"}),[h,w]=c.useState(!1),[v,y]=c.useState(""),[u,N]=c.useState(""),[C,p]=c.useState(!1),[I,j]=c.useState(null),k=[{value:"chat",label:"Chat Completions"},{value:"responses",label:"Responses API"}];c.useEffect(()=>{const n="https://api.openai.com/v1";l(b=>({...b,baseUrl:n}))},[s.apiType]);const x=async()=>{if(!(!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim())){w(!0);try{const n=await fetch("/api/provider-nodes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s.name,prefix:s.prefix,apiType:s.apiType,baseUrl:s.baseUrl,type:"openai-compatible"})}),b=await n.json();n.ok&&(m(b.node),l({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1"}),y(""),j(null))}catch(n){console.log("Error creating OpenAI Compatible node:",n)}finally{w(!1)}}},g=async()=>{p(!0);try{const b=await(await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:s.baseUrl,apiKey:v,type:"openai-compatible",modelId:u.trim()||void 0})})).json();j(b)}catch{j({valid:!1,error:"Network error"})}finally{p(!1)}},o=()=>{if(!I)return null;const{valid:n,error:b,method:K}=I;return n?e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"success",children:"Valid"}),K==="chat"&&e.jsx("span",{className:"text-sm text-text-muted",children:"(via inference test)"})]}):e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(P,{variant:"error",children:"Invalid"}),b&&e.jsx("span",{className:"text-sm text-red-500",children:b})]})};return e.jsx(ie,{isOpen:r,title:"Add OpenAI Compatible",onClose:a,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(O,{label:"Name",value:s.name,onChange:n=>l({...s,name:n.target.value}),placeholder:"OpenAI Compatible (Prod)",hint:"Required. A friendly label for this node."}),e.jsx(O,{label:"Prefix",value:s.prefix,onChange:n=>l({...s,prefix:n.target.value}),placeholder:"oc-prod",hint:"Required. Used as the provider prefix for model IDs."}),e.jsx(ke,{label:"API Type",options:k,value:s.apiType,onChange:n=>l({...s,apiType:n.target.value})}),e.jsx(O,{label:"Base URL",value:s.baseUrl,onChange:n=>l({...s,baseUrl:n.target.value}),placeholder:"https://api.openai.com/v1",hint:"Use the base URL (ending in /v1) for your OpenAI-compatible API."}),e.jsx(O,{label:"API Key (for Check)",type:"password",value:v,onChange:n=>y(n.target.value)}),e.jsx(O,{label:"Model ID (optional)",value:u,onChange:n=>N(n.target.value),placeholder:"e.g. gpt-4, claude-3-opus",hint:"If provider lacks /models endpoint, enter a model ID to validate via chat/completions instead."}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsx(_,{onClick:g,disabled:!v||C||!s.baseUrl.trim(),variant:"secondary",className:"w-full sm:w-auto",children:C?"Checking...":"Check"}),o()]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(_,{onClick:x,fullWidth:!0,disabled:!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim()||h,children:h?"Creating...":"Create"}),e.jsx(_,{onClick:a,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})})}de.propTypes={isOpen:i.bool.isRequired,onClose:i.func.isRequired,onCreated:i.func.isRequired};function me({isOpen:r,onClose:a,onCreated:m}){const[s,l]=c.useState({name:"",prefix:"",baseUrl:"https://api.anthropic.com/v1"}),[h,w]=c.useState(!1),[v,y]=c.useState(""),[u,N]=c.useState(""),[C,p]=c.useState(!1),[I,j]=c.useState(null);c.useEffect(()=>{r&&(j(null),y(""),N(""))},[r]);const k=async()=>{if(!(!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim())){w(!0);try{const o=await fetch("/api/provider-nodes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s.name,prefix:s.prefix,baseUrl:s.baseUrl,type:"anthropic-compatible"})}),n=await o.json();o.ok&&(m(n.node),l({name:"",prefix:"",baseUrl:"https://api.anthropic.com/v1"}),y(""),j(null))}catch(o){console.log("Error creating Anthropic Compatible node:",o)}finally{w(!1)}}},x=async()=>{p(!0);try{const n=await(await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:s.baseUrl,apiKey:v,type:"anthropic-compatible",modelId:u.trim()||void 0})})).json();j(n)}catch{j({valid:!1,error:"Network error"})}finally{p(!1)}},g=()=>{if(!I)return null;const{valid:o,error:n,method:b}=I;return o?e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"success",children:"Valid"}),b==="chat"&&e.jsx("span",{className:"text-sm text-text-muted",children:"(via inference test)"})]}):e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(P,{variant:"error",children:"Invalid"}),n&&e.jsx("span",{className:"text-sm text-red-500",children:n})]})};return e.jsx(ie,{isOpen:r,title:"Add Anthropic Compatible",onClose:a,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(O,{label:"Name",value:s.name,onChange:o=>l({...s,name:o.target.value}),placeholder:"Anthropic Compatible (Prod)",hint:"Required. A friendly label for this node."}),e.jsx(O,{label:"Prefix",value:s.prefix,onChange:o=>l({...s,prefix:o.target.value}),placeholder:"ac-prod",hint:"Required. Used as the provider prefix for model IDs."}),e.jsx(O,{label:"Base URL",value:s.baseUrl,onChange:o=>l({...s,baseUrl:o.target.value}),placeholder:"https://api.anthropic.com/v1",hint:"Use the base URL (ending in /v1) for your Anthropic-compatible API. The system will append /messages."}),e.jsx(O,{label:"API Key (for Check)",type:"password",value:v,onChange:o=>y(o.target.value)}),e.jsx(O,{label:"Model ID (optional)",value:u,onChange:o=>N(o.target.value),placeholder:"e.g. claude-3-opus",hint:"If provider lacks /models endpoint, enter a model ID to validate via chat/completions instead."}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsx(_,{onClick:x,disabled:!v||C||!s.baseUrl.trim(),variant:"secondary",className:"w-full sm:w-auto",children:C?"Checking...":"Check"}),g()]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx(_,{onClick:k,fullWidth:!0,disabled:!s.name.trim()||!s.prefix.trim()||!s.baseUrl.trim()||h,children:h?"Creating...":"Create"}),e.jsx(_,{onClick:a,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})})}me.propTypes={isOpen:i.bool.isRequired,onClose:i.func.isRequired,onCreated:i.func.isRequired};function pe({results:r}){if(r.error&&!r.results)return e.jsxs("div",{className:"text-center py-6",children:[e.jsx("span",{className:"material-symbols-outlined text-red-500 text-[32px] mb-2 block",children:"error"}),e.jsx("p",{className:"text-sm text-red-400",children:r.error})]});const{summary:a,mode:m}=r,s=r.results||[],l={oauth:"OAuth",free:"Free",apikey:"API Key",provider:"Provider",all:"All"}[m]||m;return e.jsxs("div",{className:"flex min-w-0 flex-col gap-3",children:[a&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs mb-1 sm:gap-3",children:[e.jsxs("span",{className:"text-text-muted",children:[l," Test"]}),e.jsxs("span",{className:"px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 font-medium",children:[a.passed," passed"]}),a.failed>0&&e.jsxs("span",{className:"px-2 py-0.5 rounded bg-red-500/15 text-red-400 font-medium",children:[a.failed," failed"]}),e.jsxs("span",{className:"text-text-muted sm:ml-auto",children:[a.total," tested"]})]}),s.map((h,w)=>{var v;return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 rounded-lg bg-black/[0.03] px-3 py-2 text-xs dark:bg-white/[0.03] sm:flex-nowrap",children:[e.jsx("span",{className:`material-symbols-outlined text-[16px] ${h.valid?"text-emerald-500":"text-red-500"}`,children:h.valid?"check_circle":"error"}),e.jsxs("div",{className:"min-w-0 flex-[1_1_160px]",children:[e.jsx("span",{className:"block truncate font-medium sm:inline",children:h.connectionName}),e.jsxs("span",{className:"block truncate text-text-muted sm:ml-1.5 sm:inline",children:["(",h.provider,")"]})]}),h.latencyMs!==void 0&&e.jsxs("span",{className:"shrink-0 text-text-muted font-mono tabular-nums",children:[h.latencyMs,"ms"]}),e.jsx("span",{className:`shrink-0 text-[10px] uppercase font-bold px-1.5 py-0.5 rounded ${h.valid?"bg-emerald-500/15 text-emerald-400":"bg-red-500/15 text-red-400"}`,children:h.valid?"OK":((v=h.diagnosis)==null?void 0:v.type)||"ERROR"})]},h.connectionId||w)}),s.length===0&&e.jsx("div",{className:"text-center py-4 text-text-muted text-sm",children:"No active connections found for this group."})]})}pe.propTypes={results:i.shape({mode:i.string,results:i.array,summary:i.shape({total:i.number,passed:i.number,failed:i.number}),error:i.string}).isRequired};export{De as default};
@@ -1 +1 @@
1
- import{j as s,B as Be,k as je,l as Ie,h as Le}from"./index.CoYbjSIL.js";import{b as d}from"./router.Cjj1--8t.js";import{B as qe}from"./NoAuthProxyCard.Buvt0BVH.js";import"./zustand.akaTi5uX.js";const O={sessions:"basic-chat.sessions",activeSessionId:"basic-chat.activeSessionId",activeProviderId:"basic-chat.activeProviderId",draft:"basic-chat.draft"};function J(){var e;return(e=globalThis.crypto)!=null&&e.randomUUID?globalThis.crypto.randomUUID():`chat_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Fe(e,a){try{return JSON.parse(e)}catch{return a}}function S(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(S).filter(Boolean).join(" ");if(typeof e=="object"){if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function He(e=""){return String(e).replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase()).trim()||"Unknown"}function Je(e){if(!e)return"Now";const a=new Date(e).getTime();if(Number.isNaN(a))return"Now";const m=Math.max(1,Math.round((Date.now()-a)/6e4));if(m<60)return`${m}m`;const u=Math.round(m/60);return u<24?`${u}h`:`${Math.round(u/24)}d`}function Ne(e=""){const a=S(e).replace(/\s+/g," ").trim();return a?a.length>52?`${a.slice(0,52).trimEnd()}…`:a:"New chat"}function Ke(e){const a=S(e.content).trim(),m=Array.isArray(e.attachments)?e.attachments:[];if(m.length===0)return a;const u=[];a&&u.push({type:"text",text:a});for(const w of m)w!=null&&w.dataUrl&&u.push({type:"image_url",image_url:{url:w.dataUrl}});return u.length>0?u:a}function We(e){var w,A;if(!e||typeof e!="object")return"";const a=(w=e.choices)==null?void 0:w[0];return[((a==null?void 0:a.delta)||{}).content,(A=a==null?void 0:a.message)==null?void 0:A.content,e.output_text,e.text].map(S).filter(Boolean)[0]||""}async function Ye(e){return await new Promise((a,m)=>{const u=new FileReader;u.onload=()=>a(String(u.result||"")),u.onerror=()=>m(u.error||new Error("Failed to read file")),u.readAsDataURL(e)})}function Ve(e){return{...e,messages:Array.isArray(e.messages)?e.messages.map(a=>({...a})):[]}}function de(e){return(e==null?void 0:e.name)||He((e==null?void 0:e.provider)||(e==null?void 0:e.id)||"provider")}function Ge(e,a){return e!=null&&e.id?{id:`${a.provider}/${e.id}`,requestModel:`${a.provider}/${e.id}`,name:e.name||e.id,providerId:a.provider,providerName:de(a),source:"static"}:null}function Qe(e,a){const m=typeof e=="string"?e:(e==null?void 0:e.id)||(e==null?void 0:e.name)||(e==null?void 0:e.model)||"";if(!m)return null;const u=typeof e=="string"?e:(e==null?void 0:e.name)||(e==null?void 0:e.displayName)||m;let w=m;return(je(a.provider)||Ie(a.provider))&&!m.includes("/")&&(w=`${a.provider}/${m}`),{id:w,requestModel:w,name:u,providerId:a.provider,providerName:de(a),source:"live"}}function Xe(e){return Array.isArray(e==null?void 0:e.models)?e.models:Array.isArray(e==null?void 0:e.data)?e.data:Array.isArray(e==null?void 0:e.results)?e.results:Array.isArray(e)?e:[]}function Ze(e){const a=new Map;for(const m of e)m!=null&&m.id&&(a.has(m.id)||a.set(m.id,m));return Array.from(a.values())}function et(){const[e,a]=d.useState([]),[m,u]=d.useState(!0),[w,A]=d.useState(""),[h,D]=d.useState(()=>{if(typeof window>"u")return[];try{const t=Fe(globalThis.localStorage.getItem(O.sessions),[]);return Array.isArray(t)?t.map(r=>({...r,messages:Array.isArray(r.messages)?r.messages:[]})):[]}catch{return[]}}),[g,M]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeSessionId)||""),[R,P]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeProviderId)||""),[I,U]=d.useState(""),[_,ce]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.draft)||""),[z,Q]=d.useState([]),[me,ue]=d.useState(!1),[Se,pe]=d.useState(""),[fe,X]=d.useState(""),[K,Ae]=d.useState(!1),[Me,Z]=d.useState(!1),[De,ee]=d.useState(!1),xe=d.useRef(null),B=d.useRef(null),te=d.useRef(!1),se=d.useRef(null),re=d.useRef(null);d.useEffect(()=>{Ae(!0)},[]),d.useEffect(()=>{let t=!1;async function r(){u(!0),A("");try{const n=await(await fetch("/api/providers",{cache:"no-store"})).json().catch(()=>({})),o=Array.isArray(n.connections)?n.connections.filter(c=>(c==null?void 0:c.isActive)!==!1):[];if(o.length===0){t||(a([]),A("No providers connected yet."));return}const x=new Map;for(const c of o){const p=c.provider||c.id,b=de(c),$=je(p)?"openai-compatible":Ie(p)?"anthropic-compatible":p;x.has(p)||x.set(p,{providerId:p,providerName:b,providerType:$,connections:[],models:[]});const N=x.get(p);N.providerName=N.providerName||b,N.providerType=N.providerType||$,N.connections.push(c);const W=Le(p).map(Y=>Ge(Y,c)).filter(Boolean);N.models.push(...W)}const k=await Promise.all(o.map(async c=>{try{const p=await fetch(`/api/providers/${c.id}/models`,{cache:"no-store"}),b=await p.json().catch(()=>({}));if(!p.ok)return{connection:c,models:[]};const $=Xe(b).map(N=>Qe(N,c)).filter(Boolean);return{connection:c,models:$}}catch{return{connection:c,models:[]}}}));for(const c of k){const p=c.connection.provider||c.connection.id,b=x.get(p);b&&b.models.push(...c.models)}const q=Array.from(x.values()).map(c=>({...c,models:Ze(c.models).sort((p,b)=>p.name.localeCompare(b.name))})).filter(c=>c.models.length>0).sort((c,p)=>c.providerName.localeCompare(p.providerName));t||(a(q),q.length===0&&A("Providers connected but no models available."))}catch(i){t||(A(S(i==null?void 0:i.message)||"Failed to load providers/models."),a([]))}finally{t||u(!1)}}return r(),()=>{t=!0}},[]),d.useEffect(()=>{const t=r=>{se.current&&!se.current.contains(r.target)&&Z(!1),re.current&&!re.current.contains(r.target)&&ee(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[]);const y=d.useMemo(()=>{const t=new Map;for(const r of e)for(const i of r.models)t.set(i.id,{...i,providerId:r.providerId,providerName:r.providerName});return t},[e]),E=d.useMemo(()=>e.find(t=>t.providerId===R)||e[0]||null,[e,R]),v=d.useMemo(()=>{var t;if(I&&y.has(I))return y.get(I);if(g){const r=h.find(i=>i.id===g);if(r!=null&&r.modelId&&y.has(r.modelId))return y.get(r.modelId)}return((t=E==null?void 0:E.models)==null?void 0:t[0])||null},[I,y,E,h,g]),ie=d.useMemo(()=>h.find(t=>t.id===g)||null,[h,g]),he=(ie==null?void 0:ie.messages)||[],ge=d.useMemo(()=>[...h].sort((t,r)=>new Date(r.updatedAt).getTime()-new Date(t.updatedAt).getTime()),[h]),ae=!me&&!!v&&(_.trim().length>0||z.length>0);d.useEffect(()=>{if(K)try{globalThis.localStorage.setItem(O.sessions,JSON.stringify(h)),globalThis.localStorage.setItem(O.activeSessionId,g),globalThis.localStorage.setItem(O.activeProviderId,R),globalThis.localStorage.setItem(O.draft,_)}catch{}},[K,h,g,R,_]),d.useEffect(()=>{if(!K||m||te.current||e.length===0)return;const t=e.find(n=>n.providerId===R)||e[0],r=I&&y.has(I)?y.get(I):t.models[0];if(h.length>0){const n=h.find(x=>x.id===g)||h[0],o=n!=null&&n.modelId&&y.has(n.modelId)?y.get(n.modelId):r;te.current=!0,M(n.id),P((o==null?void 0:o.providerId)||t.providerId),U((o==null?void 0:o.id)||r.id);return}const i={id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:r.id,modelName:r.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]};te.current=!0,D([i]),M(i.id),P(t.providerId),U(r.id)},[K,m,e,y,h,g,R,I]);const L=(t,r)=>{D(i=>i.map(n=>n.id===t?r(Ve(n)):n))},ne=t=>t?{id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]}:null,ke=t=>{const r=h.find(i=>i.id===t);r&&(M(t),P(r.providerId||R),U(r.modelId||I),ee(!1))},Te=()=>{if(!g)return;const t=h.filter(i=>i.id!==g),r=t[0]||null;D(t),r?(M(r.id),P(r.providerId),U(r.modelId)):(M(""),P(""),U(""))},Ce=t=>{const r=y.get(t);if(!r)return;const i=h.find(n=>n.id===g);if(i&&i.messages.length>0){const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}else if(i)D(n=>n.map(o=>o.id===i.id?{...o,providerId:r.providerId,providerName:r.providerName,modelId:r.id,modelName:r.name}:o)),M(i.id);else{const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}P(r.providerId),U(r.id),Z(!1)},Oe=async t=>{const r=Array.from(t.target.files||[]);if(r.length===0)return;const i=r.filter(o=>o.type.startsWith("image/"));if(i.length===0){t.target.value="";return}const n=await Promise.all(i.map(async o=>({id:J(),name:o.name,type:o.type,size:o.size,dataUrl:await Ye(o)})));Q(o=>[...o,...n]),t.target.value=""},Re=t=>{Q(r=>r.filter(i=>i.id!==t))},Ee=()=>{var t;(t=B.current)==null||t.abort()},$e=(t,r)=>{const i=Ne(r);L(t,n=>({...n,title:n.title==="New chat"?i:n.title,updatedAt:new Date().toISOString()}))},we=async()=>{var p,b,$,N,W,Y;const t=v||((p=E==null?void 0:E.models)==null?void 0:p[0])||null;if(!t)return;const r=_.trim();if(!r&&z.length===0)return;let i=g,n=h.find(l=>l.id===i);if(!n){if(n=ne(t),!n)return;i=n.id,D(l=>[n,...l]),M(i)}const o={id:J(),role:"user",content:r,attachments:z.map(l=>({id:l.id,name:l.name,type:l.type,dataUrl:l.dataUrl})),createdAt:new Date().toISOString()},x=J(),k={id:x,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"},q=[...n.messages||[],o,k];D(l=>l.map(j=>j.id===i?{...j,providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,messages:q,updatedAt:new Date().toISOString(),title:j.title==="New chat"?Ne(r):j.title}:j)),ce(""),Q([]),ue(!0),pe(x),X(""),(b=B.current)==null||b.abort(),B.current=new AbortController;const c=q.filter(l=>!(l.role==="assistant"&&l.id===x)).map(l=>({role:l.role,content:l.role==="user"?Ke(l):l.content}));try{const l=await fetch("/api/dashboard/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({model:t.requestModel||t.id,messages:c,stream:!0}),signal:B.current.signal});if(!l.ok){const f=await l.json().catch(()=>({}));throw new Error(S(f.error||f.message||`Request failed (${l.status})`))}const j=($=l.body)==null?void 0:$.getReader();if(!j){const f=await l.json().catch(()=>({})),C=S(((Y=(W=(N=f==null?void 0:f.choices)==null?void 0:N[0])==null?void 0:W.message)==null?void 0:Y.content)||(f==null?void 0:f.output_text)||(f==null?void 0:f.error)||(f==null?void 0:f.message)||"");L(i,F=>({...F,messages:F.messages.map(H=>H.id===x?{...H,content:C,status:"done"}:H),updatedAt:new Date().toISOString()}));return}const V=new TextDecoder;let T="",G="";for(;;){const{value:f,done:C}=await j.read();if(C)break;T+=V.decode(f,{stream:!0});const F=T.split(/\r?\n/);T=F.pop()||"";for(const H of F){const ve=H.trim();if(!ve.startsWith("data:"))continue;const oe=ve.slice(5).trim();if(!(!oe||oe==="[DONE]"))try{const ze=JSON.parse(oe),be=We(ze);if(!be)continue;G+=be,X(G),L(i,ye=>({...ye,messages:ye.messages.map(le=>le.id===x?{...le,content:G,status:"streaming"}:le),updatedAt:new Date().toISOString()}))}catch{}}}L(i,f=>({...f,messages:f.messages.map(C=>C.id===x?{...C,content:G||C.content,status:"done"}:C),updatedAt:new Date().toISOString()})),$e(i,r)}catch(l){if(l.name!=="AbortError"){const j=S((l==null?void 0:l.message)||l);L(i,V=>({...V,messages:V.messages.map(T=>T.id===x?{...T,content:T.content||`Error: ${j}`,status:"error"}:T),updatedAt:new Date().toISOString()})),A(j||"Failed to send message.")}}finally{ue(!1),pe(""),X(""),B.current=null}},Pe=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),ae&&we())},Ue=v?`${v.name}`:"Select model",_e=v?v.requestModel:"Choose from connected providers";return s.jsx("div",{className:"relative flex-1 flex flex-col h-full min-h-0 min-w-0 bg-[#212121] text-white overflow-hidden",children:s.jsxs("div",{className:"relative mx-auto flex flex-1 h-full min-h-0 w-full max-w-4xl flex-col",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 px-4 py-3 lg:px-6",children:[s.jsxs("div",{ref:se,className:"relative",children:[s.jsx("button",{type:"button",onClick:()=>Z(t=>!t),className:"flex items-center gap-3 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-left transition hover:bg-white/8",children:s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-white",children:Ue}),s.jsx("span",{className:"material-symbols-outlined text-[18px] text-white/70",children:"expand_more"})]}),s.jsx("p",{className:"truncate text-xs text-white/55",children:_e})]})}),Me?s.jsxs("div",{className:"absolute left-0 top-[calc(100%+10px)] z-30 w-[min(520px,calc(100vw-2rem))] overflow-hidden rounded-[20px] border border-white/10 bg-[#262626] shadow-2xl shadow-black/50",children:[s.jsxs("div",{className:"border-b border-white/10 px-4 py-3",children:[s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Models"}),s.jsx("p",{className:"text-sm text-white/75",children:"Only from connected providers"})]}),s.jsx("div",{className:"max-h-[60vh] overflow-y-auto p-2 custom-scrollbar",children:e.map(t=>s.jsxs("div",{className:"mb-2 rounded-[16px] border border-white/10 bg-black/20 p-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[s.jsx("p",{className:"text-sm font-semibold text-white",children:t.providerName}),s.jsx(qe,{size:"sm",variant:"default",children:t.models.length})]}),s.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:t.models.map(r=>{const i=r.id===I;return s.jsx("button",{type:"button",onClick:()=>Ce(r.id),className:`rounded-[14px] border px-3 py-3 text-left transition ${i?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:r.name}),s.jsx("p",{className:"truncate text-[11px] text-white/45",children:r.requestModel})]}),i?s.jsx("span",{className:"material-symbols-outlined text-[18px] text-blue-300",children:"check_circle"}):null]})},r.id)})})]},t.providerId))})]}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>ee(t=>!t),className:"rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/80 transition hover:bg-white/8",children:"History"}),s.jsx(Be,{variant:"ghost",size:"sm",icon:"delete",onClick:Te,disabled:!g||h.length===0,children:"Clear"})]})]}),De?s.jsxs("div",{ref:re,className:"absolute right-4 top-[72px] z-20 w-[min(360px,calc(100vw-2rem))] rounded-[20px] border border-white/10 bg-[#262626] p-2 shadow-2xl shadow-black/50 lg:right-6",children:[s.jsx("div",{className:"px-3 py-2",children:s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Recent chats"})}),s.jsx("div",{className:"max-h-[48vh] space-y-2 overflow-y-auto p-1 custom-scrollbar",children:ge.length===0?s.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-white/5 p-4 text-sm text-white/55",children:"No conversations yet."}):ge.map(t=>{var n;const r=t.id===g,i=[...t.messages||[]].reverse().find(o=>o.role==="user")||((n=t.messages)==null?void 0:n[0]);return s.jsx("button",{type:"button",onClick:()=>ke(t.id),className:`w-full rounded-[16px] border px-3 py-3 text-left transition ${r?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:t.title}),s.jsx("p",{className:"mt-1 truncate text-xs text-white/50",children:S(i==null?void 0:i.content)||"Empty chat"})]}),s.jsx("span",{className:"text-[10px] text-white/40 shrink-0",children:Je(t.updatedAt)})]})},t.id)})})]}):null,w?s.jsx("div",{className:"mt-4 rounded-[18px] border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-rose-100",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"error"}),s.jsx("p",{className:"text-sm leading-6",children:w})]})}):null,s.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[s.jsxs("div",{className:"flex-1 overflow-y-auto py-4 custom-scrollbar",children:[he.length===0?s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center px-4 text-center",children:s.jsxs("div",{className:"max-w-xl space-y-4",children:[s.jsx("div",{className:"mx-auto flex size-16 items-center justify-center rounded-[20px] border border-white/10 bg-white/5 text-white/80",children:s.jsx("span",{className:"material-symbols-outlined text-[30px]",children:"chat"})}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("h2",{className:"text-2xl font-semibold text-white",children:"Start a conversation"}),s.jsx("p",{className:"text-sm leading-6 text-white/60",children:"Simple chat interface to interact with any AI model from connected providers. Select a model and start chatting!"})]})]})}):null,s.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4 px-4",children:he.map(t=>{var x;const r=t.role==="user",i=t.role==="assistant",n=i&&t.id===Se&&t.status==="streaming",o=S(t.content)||(i?fe:"");return s.jsx("div",{className:`flex w-full ${r?"justify-end":"justify-start"} mb-6`,children:s.jsxs("div",{className:`max-w-[min(88%,42rem)] ${r?"rounded-3xl bg-[#2f2f2f] px-5 py-3.5 text-white":"text-white/90"}`,children:[s.jsx("div",{className:"mb-1 flex items-center justify-between gap-3",children:s.jsx("span",{className:"text-xs font-semibold",children:r?"You":(v==null?void 0:v.name)||"Assistant"})}),(x=t.attachments)!=null&&x.length?s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2 sm:grid-cols-3 mt-2",children:t.attachments.map(k=>s.jsx("a",{href:k.dataUrl,target:"_blank",rel:"noreferrer",className:"overflow-hidden rounded-[18px] border border-white/10 bg-black/20",children:s.jsx("img",{src:k.dataUrl,alt:k.name,className:"h-28 w-full object-cover"})},k.id))}):null,s.jsxs("div",{className:"whitespace-pre-wrap break-words text-[15px] leading-7",children:[o,i&&n&&!fe?s.jsx("span",{className:"inline-block animate-pulse",children:"▋"}):null]})]})},t.id)})})]}),s.jsxs("div",{className:"shrink-0 pt-2",children:[z.length>0?s.jsx("div",{className:"mx-auto mb-3 flex w-full max-w-3xl flex-wrap gap-2 px-4",children:z.map(t=>s.jsxs("div",{className:"flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-2",children:[s.jsx("span",{className:"text-xs text-white/80 max-w-[12rem] truncate",children:t.name}),s.jsx("button",{type:"button",onClick:()=>Re(t.id),className:"text-white/55 hover:text-white","aria-label":"Remove attachment",children:s.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"close"})})]},t.id))}):null,s.jsx("div",{className:"mx-auto w-full max-w-3xl px-4 pb-2",children:s.jsxs("div",{className:"rounded-[26px] bg-[#2f2f2f] px-3 pt-3 pb-2 shadow-[0_0_15px_rgba(0,0,0,0.10)] ring-1 ring-white/5",children:[s.jsx("textarea",{value:_,onChange:t=>ce(t.target.value),onKeyDown:Pe,placeholder:"Message AI",rows:1,className:"w-full resize-none bg-transparent px-2 text-[15px] leading-6 text-white outline-none placeholder:text-white/40 custom-scrollbar max-h-[25vh] overflow-y-auto"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{var t;return(t=xe.current)==null?void 0:t.click()},disabled:!v||m,className:"p-2 text-white/50 hover:text-white transition rounded-full hover:bg-white/5",children:s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"attach_file"})}),s.jsx("input",{ref:xe,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Oe}),s.jsx("span",{className:"text-xs font-medium text-white/30 truncate max-w-[120px]",children:v?v.name:"No model"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[me?s.jsx("button",{type:"button",onClick:Ee,className:"p-2 text-white bg-white/10 hover:bg-white/20 transition rounded-full h-8 w-8 flex items-center justify-center",children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"stop"})}):null,s.jsx("button",{onClick:we,disabled:!ae,className:`h-8 w-8 rounded-full flex items-center justify-center transition ${ae?"bg-white text-black hover:opacity-90":"bg-white/10 text-white/30 cursor-not-allowed"}`,children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"arrow_upward"})})]})]})]})})]}),s.jsx("p",{className:"mx-auto mt-2 max-w-3xl px-4 pb-4 text-center text-[11px] text-white/30",children:"Model list is filtered from connected providers."})]})]})})}function at(){return s.jsx(et,{})}export{at as default};
1
+ import{j as s,B as Be,k as je,l as Ie,h as Le}from"./index.CShjRV_B.js";import{b as d}from"./router.Cjj1--8t.js";import{B as qe}from"./NoAuthProxyCard.qAv57b-0.js";import"./zustand.akaTi5uX.js";const O={sessions:"basic-chat.sessions",activeSessionId:"basic-chat.activeSessionId",activeProviderId:"basic-chat.activeProviderId",draft:"basic-chat.draft"};function J(){var e;return(e=globalThis.crypto)!=null&&e.randomUUID?globalThis.crypto.randomUUID():`chat_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Fe(e,a){try{return JSON.parse(e)}catch{return a}}function S(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(S).filter(Boolean).join(" ");if(typeof e=="object"){if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function He(e=""){return String(e).replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase()).trim()||"Unknown"}function Je(e){if(!e)return"Now";const a=new Date(e).getTime();if(Number.isNaN(a))return"Now";const m=Math.max(1,Math.round((Date.now()-a)/6e4));if(m<60)return`${m}m`;const u=Math.round(m/60);return u<24?`${u}h`:`${Math.round(u/24)}d`}function Ne(e=""){const a=S(e).replace(/\s+/g," ").trim();return a?a.length>52?`${a.slice(0,52).trimEnd()}…`:a:"New chat"}function Ke(e){const a=S(e.content).trim(),m=Array.isArray(e.attachments)?e.attachments:[];if(m.length===0)return a;const u=[];a&&u.push({type:"text",text:a});for(const w of m)w!=null&&w.dataUrl&&u.push({type:"image_url",image_url:{url:w.dataUrl}});return u.length>0?u:a}function We(e){var w,A;if(!e||typeof e!="object")return"";const a=(w=e.choices)==null?void 0:w[0];return[((a==null?void 0:a.delta)||{}).content,(A=a==null?void 0:a.message)==null?void 0:A.content,e.output_text,e.text].map(S).filter(Boolean)[0]||""}async function Ye(e){return await new Promise((a,m)=>{const u=new FileReader;u.onload=()=>a(String(u.result||"")),u.onerror=()=>m(u.error||new Error("Failed to read file")),u.readAsDataURL(e)})}function Ve(e){return{...e,messages:Array.isArray(e.messages)?e.messages.map(a=>({...a})):[]}}function de(e){return(e==null?void 0:e.name)||He((e==null?void 0:e.provider)||(e==null?void 0:e.id)||"provider")}function Ge(e,a){return e!=null&&e.id?{id:`${a.provider}/${e.id}`,requestModel:`${a.provider}/${e.id}`,name:e.name||e.id,providerId:a.provider,providerName:de(a),source:"static"}:null}function Qe(e,a){const m=typeof e=="string"?e:(e==null?void 0:e.id)||(e==null?void 0:e.name)||(e==null?void 0:e.model)||"";if(!m)return null;const u=typeof e=="string"?e:(e==null?void 0:e.name)||(e==null?void 0:e.displayName)||m;let w=m;return(je(a.provider)||Ie(a.provider))&&!m.includes("/")&&(w=`${a.provider}/${m}`),{id:w,requestModel:w,name:u,providerId:a.provider,providerName:de(a),source:"live"}}function Xe(e){return Array.isArray(e==null?void 0:e.models)?e.models:Array.isArray(e==null?void 0:e.data)?e.data:Array.isArray(e==null?void 0:e.results)?e.results:Array.isArray(e)?e:[]}function Ze(e){const a=new Map;for(const m of e)m!=null&&m.id&&(a.has(m.id)||a.set(m.id,m));return Array.from(a.values())}function et(){const[e,a]=d.useState([]),[m,u]=d.useState(!0),[w,A]=d.useState(""),[h,D]=d.useState(()=>{if(typeof window>"u")return[];try{const t=Fe(globalThis.localStorage.getItem(O.sessions),[]);return Array.isArray(t)?t.map(r=>({...r,messages:Array.isArray(r.messages)?r.messages:[]})):[]}catch{return[]}}),[g,M]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeSessionId)||""),[R,P]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeProviderId)||""),[I,U]=d.useState(""),[_,ce]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.draft)||""),[z,Q]=d.useState([]),[me,ue]=d.useState(!1),[Se,pe]=d.useState(""),[fe,X]=d.useState(""),[K,Ae]=d.useState(!1),[Me,Z]=d.useState(!1),[De,ee]=d.useState(!1),xe=d.useRef(null),B=d.useRef(null),te=d.useRef(!1),se=d.useRef(null),re=d.useRef(null);d.useEffect(()=>{Ae(!0)},[]),d.useEffect(()=>{let t=!1;async function r(){u(!0),A("");try{const n=await(await fetch("/api/providers",{cache:"no-store"})).json().catch(()=>({})),o=Array.isArray(n.connections)?n.connections.filter(c=>(c==null?void 0:c.isActive)!==!1):[];if(o.length===0){t||(a([]),A("No providers connected yet."));return}const x=new Map;for(const c of o){const p=c.provider||c.id,b=de(c),$=je(p)?"openai-compatible":Ie(p)?"anthropic-compatible":p;x.has(p)||x.set(p,{providerId:p,providerName:b,providerType:$,connections:[],models:[]});const N=x.get(p);N.providerName=N.providerName||b,N.providerType=N.providerType||$,N.connections.push(c);const W=Le(p).map(Y=>Ge(Y,c)).filter(Boolean);N.models.push(...W)}const k=await Promise.all(o.map(async c=>{try{const p=await fetch(`/api/providers/${c.id}/models`,{cache:"no-store"}),b=await p.json().catch(()=>({}));if(!p.ok)return{connection:c,models:[]};const $=Xe(b).map(N=>Qe(N,c)).filter(Boolean);return{connection:c,models:$}}catch{return{connection:c,models:[]}}}));for(const c of k){const p=c.connection.provider||c.connection.id,b=x.get(p);b&&b.models.push(...c.models)}const q=Array.from(x.values()).map(c=>({...c,models:Ze(c.models).sort((p,b)=>p.name.localeCompare(b.name))})).filter(c=>c.models.length>0).sort((c,p)=>c.providerName.localeCompare(p.providerName));t||(a(q),q.length===0&&A("Providers connected but no models available."))}catch(i){t||(A(S(i==null?void 0:i.message)||"Failed to load providers/models."),a([]))}finally{t||u(!1)}}return r(),()=>{t=!0}},[]),d.useEffect(()=>{const t=r=>{se.current&&!se.current.contains(r.target)&&Z(!1),re.current&&!re.current.contains(r.target)&&ee(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[]);const y=d.useMemo(()=>{const t=new Map;for(const r of e)for(const i of r.models)t.set(i.id,{...i,providerId:r.providerId,providerName:r.providerName});return t},[e]),E=d.useMemo(()=>e.find(t=>t.providerId===R)||e[0]||null,[e,R]),v=d.useMemo(()=>{var t;if(I&&y.has(I))return y.get(I);if(g){const r=h.find(i=>i.id===g);if(r!=null&&r.modelId&&y.has(r.modelId))return y.get(r.modelId)}return((t=E==null?void 0:E.models)==null?void 0:t[0])||null},[I,y,E,h,g]),ie=d.useMemo(()=>h.find(t=>t.id===g)||null,[h,g]),he=(ie==null?void 0:ie.messages)||[],ge=d.useMemo(()=>[...h].sort((t,r)=>new Date(r.updatedAt).getTime()-new Date(t.updatedAt).getTime()),[h]),ae=!me&&!!v&&(_.trim().length>0||z.length>0);d.useEffect(()=>{if(K)try{globalThis.localStorage.setItem(O.sessions,JSON.stringify(h)),globalThis.localStorage.setItem(O.activeSessionId,g),globalThis.localStorage.setItem(O.activeProviderId,R),globalThis.localStorage.setItem(O.draft,_)}catch{}},[K,h,g,R,_]),d.useEffect(()=>{if(!K||m||te.current||e.length===0)return;const t=e.find(n=>n.providerId===R)||e[0],r=I&&y.has(I)?y.get(I):t.models[0];if(h.length>0){const n=h.find(x=>x.id===g)||h[0],o=n!=null&&n.modelId&&y.has(n.modelId)?y.get(n.modelId):r;te.current=!0,M(n.id),P((o==null?void 0:o.providerId)||t.providerId),U((o==null?void 0:o.id)||r.id);return}const i={id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:r.id,modelName:r.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]};te.current=!0,D([i]),M(i.id),P(t.providerId),U(r.id)},[K,m,e,y,h,g,R,I]);const L=(t,r)=>{D(i=>i.map(n=>n.id===t?r(Ve(n)):n))},ne=t=>t?{id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]}:null,ke=t=>{const r=h.find(i=>i.id===t);r&&(M(t),P(r.providerId||R),U(r.modelId||I),ee(!1))},Te=()=>{if(!g)return;const t=h.filter(i=>i.id!==g),r=t[0]||null;D(t),r?(M(r.id),P(r.providerId),U(r.modelId)):(M(""),P(""),U(""))},Ce=t=>{const r=y.get(t);if(!r)return;const i=h.find(n=>n.id===g);if(i&&i.messages.length>0){const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}else if(i)D(n=>n.map(o=>o.id===i.id?{...o,providerId:r.providerId,providerName:r.providerName,modelId:r.id,modelName:r.name}:o)),M(i.id);else{const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}P(r.providerId),U(r.id),Z(!1)},Oe=async t=>{const r=Array.from(t.target.files||[]);if(r.length===0)return;const i=r.filter(o=>o.type.startsWith("image/"));if(i.length===0){t.target.value="";return}const n=await Promise.all(i.map(async o=>({id:J(),name:o.name,type:o.type,size:o.size,dataUrl:await Ye(o)})));Q(o=>[...o,...n]),t.target.value=""},Re=t=>{Q(r=>r.filter(i=>i.id!==t))},Ee=()=>{var t;(t=B.current)==null||t.abort()},$e=(t,r)=>{const i=Ne(r);L(t,n=>({...n,title:n.title==="New chat"?i:n.title,updatedAt:new Date().toISOString()}))},we=async()=>{var p,b,$,N,W,Y;const t=v||((p=E==null?void 0:E.models)==null?void 0:p[0])||null;if(!t)return;const r=_.trim();if(!r&&z.length===0)return;let i=g,n=h.find(l=>l.id===i);if(!n){if(n=ne(t),!n)return;i=n.id,D(l=>[n,...l]),M(i)}const o={id:J(),role:"user",content:r,attachments:z.map(l=>({id:l.id,name:l.name,type:l.type,dataUrl:l.dataUrl})),createdAt:new Date().toISOString()},x=J(),k={id:x,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"},q=[...n.messages||[],o,k];D(l=>l.map(j=>j.id===i?{...j,providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,messages:q,updatedAt:new Date().toISOString(),title:j.title==="New chat"?Ne(r):j.title}:j)),ce(""),Q([]),ue(!0),pe(x),X(""),(b=B.current)==null||b.abort(),B.current=new AbortController;const c=q.filter(l=>!(l.role==="assistant"&&l.id===x)).map(l=>({role:l.role,content:l.role==="user"?Ke(l):l.content}));try{const l=await fetch("/api/dashboard/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({model:t.requestModel||t.id,messages:c,stream:!0}),signal:B.current.signal});if(!l.ok){const f=await l.json().catch(()=>({}));throw new Error(S(f.error||f.message||`Request failed (${l.status})`))}const j=($=l.body)==null?void 0:$.getReader();if(!j){const f=await l.json().catch(()=>({})),C=S(((Y=(W=(N=f==null?void 0:f.choices)==null?void 0:N[0])==null?void 0:W.message)==null?void 0:Y.content)||(f==null?void 0:f.output_text)||(f==null?void 0:f.error)||(f==null?void 0:f.message)||"");L(i,F=>({...F,messages:F.messages.map(H=>H.id===x?{...H,content:C,status:"done"}:H),updatedAt:new Date().toISOString()}));return}const V=new TextDecoder;let T="",G="";for(;;){const{value:f,done:C}=await j.read();if(C)break;T+=V.decode(f,{stream:!0});const F=T.split(/\r?\n/);T=F.pop()||"";for(const H of F){const ve=H.trim();if(!ve.startsWith("data:"))continue;const oe=ve.slice(5).trim();if(!(!oe||oe==="[DONE]"))try{const ze=JSON.parse(oe),be=We(ze);if(!be)continue;G+=be,X(G),L(i,ye=>({...ye,messages:ye.messages.map(le=>le.id===x?{...le,content:G,status:"streaming"}:le),updatedAt:new Date().toISOString()}))}catch{}}}L(i,f=>({...f,messages:f.messages.map(C=>C.id===x?{...C,content:G||C.content,status:"done"}:C),updatedAt:new Date().toISOString()})),$e(i,r)}catch(l){if(l.name!=="AbortError"){const j=S((l==null?void 0:l.message)||l);L(i,V=>({...V,messages:V.messages.map(T=>T.id===x?{...T,content:T.content||`Error: ${j}`,status:"error"}:T),updatedAt:new Date().toISOString()})),A(j||"Failed to send message.")}}finally{ue(!1),pe(""),X(""),B.current=null}},Pe=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),ae&&we())},Ue=v?`${v.name}`:"Select model",_e=v?v.requestModel:"Choose from connected providers";return s.jsx("div",{className:"relative flex-1 flex flex-col h-full min-h-0 min-w-0 bg-[#212121] text-white overflow-hidden",children:s.jsxs("div",{className:"relative mx-auto flex flex-1 h-full min-h-0 w-full max-w-4xl flex-col",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 px-4 py-3 lg:px-6",children:[s.jsxs("div",{ref:se,className:"relative",children:[s.jsx("button",{type:"button",onClick:()=>Z(t=>!t),className:"flex items-center gap-3 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-left transition hover:bg-white/8",children:s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-white",children:Ue}),s.jsx("span",{className:"material-symbols-outlined text-[18px] text-white/70",children:"expand_more"})]}),s.jsx("p",{className:"truncate text-xs text-white/55",children:_e})]})}),Me?s.jsxs("div",{className:"absolute left-0 top-[calc(100%+10px)] z-30 w-[min(520px,calc(100vw-2rem))] overflow-hidden rounded-[20px] border border-white/10 bg-[#262626] shadow-2xl shadow-black/50",children:[s.jsxs("div",{className:"border-b border-white/10 px-4 py-3",children:[s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Models"}),s.jsx("p",{className:"text-sm text-white/75",children:"Only from connected providers"})]}),s.jsx("div",{className:"max-h-[60vh] overflow-y-auto p-2 custom-scrollbar",children:e.map(t=>s.jsxs("div",{className:"mb-2 rounded-[16px] border border-white/10 bg-black/20 p-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[s.jsx("p",{className:"text-sm font-semibold text-white",children:t.providerName}),s.jsx(qe,{size:"sm",variant:"default",children:t.models.length})]}),s.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:t.models.map(r=>{const i=r.id===I;return s.jsx("button",{type:"button",onClick:()=>Ce(r.id),className:`rounded-[14px] border px-3 py-3 text-left transition ${i?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:r.name}),s.jsx("p",{className:"truncate text-[11px] text-white/45",children:r.requestModel})]}),i?s.jsx("span",{className:"material-symbols-outlined text-[18px] text-blue-300",children:"check_circle"}):null]})},r.id)})})]},t.providerId))})]}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>ee(t=>!t),className:"rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/80 transition hover:bg-white/8",children:"History"}),s.jsx(Be,{variant:"ghost",size:"sm",icon:"delete",onClick:Te,disabled:!g||h.length===0,children:"Clear"})]})]}),De?s.jsxs("div",{ref:re,className:"absolute right-4 top-[72px] z-20 w-[min(360px,calc(100vw-2rem))] rounded-[20px] border border-white/10 bg-[#262626] p-2 shadow-2xl shadow-black/50 lg:right-6",children:[s.jsx("div",{className:"px-3 py-2",children:s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Recent chats"})}),s.jsx("div",{className:"max-h-[48vh] space-y-2 overflow-y-auto p-1 custom-scrollbar",children:ge.length===0?s.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-white/5 p-4 text-sm text-white/55",children:"No conversations yet."}):ge.map(t=>{var n;const r=t.id===g,i=[...t.messages||[]].reverse().find(o=>o.role==="user")||((n=t.messages)==null?void 0:n[0]);return s.jsx("button",{type:"button",onClick:()=>ke(t.id),className:`w-full rounded-[16px] border px-3 py-3 text-left transition ${r?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:t.title}),s.jsx("p",{className:"mt-1 truncate text-xs text-white/50",children:S(i==null?void 0:i.content)||"Empty chat"})]}),s.jsx("span",{className:"text-[10px] text-white/40 shrink-0",children:Je(t.updatedAt)})]})},t.id)})})]}):null,w?s.jsx("div",{className:"mt-4 rounded-[18px] border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-rose-100",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"error"}),s.jsx("p",{className:"text-sm leading-6",children:w})]})}):null,s.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[s.jsxs("div",{className:"flex-1 overflow-y-auto py-4 custom-scrollbar",children:[he.length===0?s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center px-4 text-center",children:s.jsxs("div",{className:"max-w-xl space-y-4",children:[s.jsx("div",{className:"mx-auto flex size-16 items-center justify-center rounded-[20px] border border-white/10 bg-white/5 text-white/80",children:s.jsx("span",{className:"material-symbols-outlined text-[30px]",children:"chat"})}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("h2",{className:"text-2xl font-semibold text-white",children:"Start a conversation"}),s.jsx("p",{className:"text-sm leading-6 text-white/60",children:"Simple chat interface to interact with any AI model from connected providers. Select a model and start chatting!"})]})]})}):null,s.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4 px-4",children:he.map(t=>{var x;const r=t.role==="user",i=t.role==="assistant",n=i&&t.id===Se&&t.status==="streaming",o=S(t.content)||(i?fe:"");return s.jsx("div",{className:`flex w-full ${r?"justify-end":"justify-start"} mb-6`,children:s.jsxs("div",{className:`max-w-[min(88%,42rem)] ${r?"rounded-3xl bg-[#2f2f2f] px-5 py-3.5 text-white":"text-white/90"}`,children:[s.jsx("div",{className:"mb-1 flex items-center justify-between gap-3",children:s.jsx("span",{className:"text-xs font-semibold",children:r?"You":(v==null?void 0:v.name)||"Assistant"})}),(x=t.attachments)!=null&&x.length?s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2 sm:grid-cols-3 mt-2",children:t.attachments.map(k=>s.jsx("a",{href:k.dataUrl,target:"_blank",rel:"noreferrer",className:"overflow-hidden rounded-[18px] border border-white/10 bg-black/20",children:s.jsx("img",{src:k.dataUrl,alt:k.name,className:"h-28 w-full object-cover"})},k.id))}):null,s.jsxs("div",{className:"whitespace-pre-wrap break-words text-[15px] leading-7",children:[o,i&&n&&!fe?s.jsx("span",{className:"inline-block animate-pulse",children:"▋"}):null]})]})},t.id)})})]}),s.jsxs("div",{className:"shrink-0 pt-2",children:[z.length>0?s.jsx("div",{className:"mx-auto mb-3 flex w-full max-w-3xl flex-wrap gap-2 px-4",children:z.map(t=>s.jsxs("div",{className:"flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-2",children:[s.jsx("span",{className:"text-xs text-white/80 max-w-[12rem] truncate",children:t.name}),s.jsx("button",{type:"button",onClick:()=>Re(t.id),className:"text-white/55 hover:text-white","aria-label":"Remove attachment",children:s.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"close"})})]},t.id))}):null,s.jsx("div",{className:"mx-auto w-full max-w-3xl px-4 pb-2",children:s.jsxs("div",{className:"rounded-[26px] bg-[#2f2f2f] px-3 pt-3 pb-2 shadow-[0_0_15px_rgba(0,0,0,0.10)] ring-1 ring-white/5",children:[s.jsx("textarea",{value:_,onChange:t=>ce(t.target.value),onKeyDown:Pe,placeholder:"Message AI",rows:1,className:"w-full resize-none bg-transparent px-2 text-[15px] leading-6 text-white outline-none placeholder:text-white/40 custom-scrollbar max-h-[25vh] overflow-y-auto"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{var t;return(t=xe.current)==null?void 0:t.click()},disabled:!v||m,className:"p-2 text-white/50 hover:text-white transition rounded-full hover:bg-white/5",children:s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"attach_file"})}),s.jsx("input",{ref:xe,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Oe}),s.jsx("span",{className:"text-xs font-medium text-white/30 truncate max-w-[120px]",children:v?v.name:"No model"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[me?s.jsx("button",{type:"button",onClick:Ee,className:"p-2 text-white bg-white/10 hover:bg-white/20 transition rounded-full h-8 w-8 flex items-center justify-center",children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"stop"})}):null,s.jsx("button",{onClick:we,disabled:!ae,className:`h-8 w-8 rounded-full flex items-center justify-center transition ${ae?"bg-white text-black hover:opacity-90":"bg-white/10 text-white/30 cursor-not-allowed"}`,children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"arrow_upward"})})]})]})]})})]}),s.jsx("p",{className:"mx-auto mt-2 max-w-3xl px-4 pb-4 text-center text-[11px] text-white/30",children:"Model list is filtered from connected providers."})]})]})})}function at(){return s.jsx(et,{})}export{at as default};
package/public/index.html CHANGED
@@ -10,7 +10,7 @@
10
10
  <link rel="preconnect" href="https://fonts.googleapis.com" />
11
11
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
12
12
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
13
- <script type="module" crossorigin src="/assets/index.KMEObSAk.js"></script>
13
+ <script type="module" crossorigin src="/assets/index.CShjRV_B.js"></script>
14
14
  <link rel="modulepreload" crossorigin href="/assets/router.Cjj1--8t.js">
15
15
  <link rel="modulepreload" crossorigin href="/assets/zustand.akaTi5uX.js">
16
16
  <link rel="stylesheet" crossorigin href="/assets/index.BuPfZebu.css">
@@ -1,6 +0,0 @@
1
- import{p as Lt,q as Us,u as As,j as e,B as c,M as B,C as Rs,f as Is}from"./index.B-zMpSp_.js";import{b as a}from"./router.Cjj1--8t.js";import{C as Ze,I as G,T as L}from"./NoAuthProxyCard.VRP7gDcs.js";import{C as _t}from"./Loading.BhEzHe-X.js";const Ds=["zh-CN","zh-TW"],Os=[{icon:"public",title:"Access Anywhere",desc:"Use your API from any network"},{icon:"group",title:"Share Endpoint",desc:"Share URL with team members"},{icon:"code",title:"Use in Cursor/Cline",desc:"Connect AI tools remotely"},{icon:"lock",title:"Encrypted",desc:"End-to-end TLS via Cloudflare"}],et=2e3,Ut=3e5,Hs=5e3,tt=5,Ms=1e4,Fs=5e3;async function At(h){if(!h)return!1;try{return(await fetch(`${h}/api/health`,{mode:"cors",cache:"no-store",signal:AbortSignal.timeout(Fs)})).ok}catch{return!1}}async function Ks(...h){const d=h.filter(Boolean).map(At);return d.length?new Promise(x=>{let j=d.length;d.forEach(R=>R.then(g=>{g?x(!0):--j===0&&x(!1)}))}):!1}const ve=[{id:"lite",label:"Lite",desc:"Drop filler, keep grammar"},{id:"full",label:"Full",desc:"Drop articles, fragments OK"},{id:"ultra",label:"Ultra",desc:"Telegraphic, max compression"},{id:"wenyan-lite",label:"文 Lite",desc:"Classical Chinese, light compression",wenyan:!0},{id:"wenyan",label:"文 Full",desc:"Maximum 文言文, 80-90% reduction",wenyan:!0},{id:"wenyan-ultra",label:"文 Ultra",desc:"Extreme classical compression",wenyan:!0}];function Ws({machineId:h}){var Pt;const[d,x]=a.useState([]),[j,R]=a.useState(!0),[g,C]=a.useState(!1),[ne,le]=a.useState(""),[Te,Se]=a.useState(null),[w,J]=a.useState(null),[re,st]=a.useState(!1),[V,Rt]=a.useState(!0),[at,It]=a.useState(!0),[nt,lt]=a.useState(!1),[rt,it]=a.useState(!0),[Ee,ot]=a.useState(!1),[ie,Pe]=a.useState("full"),[Le,ct]=a.useState(!1),[_e,Ue]=a.useState(""),[Dt,dt]=a.useState(!1),[I,Ae]=a.useState({installed:!1,running:!1,python:null,loading:!0}),[Bs,Gs]=a.useState(!1),[oe,ce]=a.useState(!1),[Js,mt]=a.useState(""),[Re,ut]=a.useState(!1),[Ie,ht]=a.useState("full"),[De,xt]=a.useState(!1),[Oe,pt]=a.useState("full"),[Ot,ft]=a.useState("en"),[Ht,He]=a.useState(!0),[p,de]=a.useState(!1),[D,me]=a.useState(!1),[O,ue]=a.useState(""),[H,Me]=a.useState(""),[_,T]=a.useState(!1),[Mt,S]=a.useState(""),[he,N]=a.useState(null),[Ft,Y]=a.useState(!1),[Kt,X]=a.useState(!1),[f,M]=a.useState(!1),[F,xe]=a.useState(!1),[K,W]=a.useState(""),[U,Q]=a.useState(!1),[Wt,A]=a.useState(""),[q,m]=a.useState(null),[bt,gt]=a.useState(""),[qt,yt]=a.useState(""),[Fe,pe]=a.useState(null),[fe,Ke]=a.useState(!1),[We,qe]=a.useState([]),[$t,jt]=a.useState(""),[zt,$e]=a.useState(!1),[Bt,$]=a.useState(!1),[Gt,Z]=a.useState(!1),be=a.useRef(null),ee=a.useRef(0),te=a.useRef(0),ge=a.useRef(!1),ye=a.useRef(!1),je=a.useRef(!1),we=a.useRef(!1),[Jt,ze]=a.useState(!1),[Vt,Be]=a.useState(!1),[Ge,wt]=a.useState(new Set),[Yt,Xt]=a.useState(!1);a.useEffect(()=>{typeof window<"u"&&Xt(!["localhost","127.0.0.1","::1"].includes(window.location.hostname))},[]),a.useEffect(()=>(ft(Lt()),Us(()=>ft(Lt()))),[]);const Je=Ds.includes(Ot),Qt=Je?ve:ve.filter(t=>!t.wenyan);a.useEffect(()=>{const t=ve.find(s=>s.id===ie);t!=null&&t.wenyan&&!Je&&(Pe("ultra"),k({cavemanLevel:"ultra"}))},[Je,ie]);const{copied:z,copy:se}=As(),Zt=!V||!at,es=V?"Change the default dashboard password before activating the tunnel.":'Enable "Require login" and set a custom password before activating the tunnel.';a.useEffect(()=>{be.current&&(be.current.scrollTop=be.current.scrollHeight)},[We]),a.useEffect(()=>{kt(),ts()},[]),a.useEffect(()=>{if(!(p||f))return;const n=(!p||D)&&(!f||F),r=()=>{document.hidden||Nt()};if(document.addEventListener("visibilitychange",r),n)return()=>document.removeEventListener("visibilitychange",r);const o=setInterval(()=>{document.hidden||Nt()},Hs);return()=>{clearInterval(o),document.removeEventListener("visibilitychange",r)}},[p,f,D,F]),a.useEffect(()=>{const t=async()=>{if(!document.hidden){if(p&&(O||H)){const o=await Ks(H,O);ge.current=o,o?(ee.current=0,me(!0),je.current||(je.current=!0,ze(!0))):(ee.current+=1,ee.current>=tt&&me(!1))}else ge.current=!1;if(f&&K){const o=await At(K);ye.current=o,o?(te.current=0,xe(!0),we.current||(we.current=!0,Be(!0))):(te.current+=1,te.current>=tt&&xe(!1))}else ye.current=!1}};if(!(p&&(O||H)||f&&K)||(t(),(!p||D)&&(!f||F)))return;const r=setInterval(t,Ms);return()=>clearInterval(r)},[p,O,H,f,K,D,F]);const Ne=a.useCallback((t,s,l,n,r,o)=>{s.current?(l.current=0,n(!0),r.current||(r.current=!0,o(!0))):(l.current+=1,l.current>=tt&&n(!1))},[]),Nt=async()=>{var t,s,l,n,r,o,u;try{const y=await fetch("/api/tunnel/status",{cache:"no-store"});if(!y.ok)return;const b=await y.json(),i=((t=b.tunnel)==null?void 0:t.settingsEnabled)??((s=b.tunnel)==null?void 0:s.enabled)??!1,P=((l=b.tunnel)==null?void 0:l.tunnelUrl)||"";ue(P),Me(((n=b.tunnel)==null?void 0:n.publicUrl)||""),de(i),Ne(null,ge,ee,me,je,ze);const v=((r=b.tailscale)==null?void 0:r.settingsEnabled)??((o=b.tailscale)==null?void 0:o.enabled)??!1,Qe=((u=b.tailscale)==null?void 0:u.tunnelUrl)||"";W(Qe),M(v),Ne(null,ye,te,xe,we,Be)}catch{}},ts=async()=>{var t,s,l,n,r,o,u;He(!0);try{const[y,b]=await Promise.all([fetch("/api/settings"),fetch("/api/tunnel/status",{cache:"no-store"})]);if(y.ok){const i=await y.json();st(i.requireApiKey||!1),Rt(i.requireLogin!==!1),It(i.hasPassword||!1),lt(i.tunnelDashboardAccess||!1),it(i.rtkEnabled!==!1),ot(!!i.cavemanEnabled),Pe(i.cavemanLevel||"full"),ct(!!i.headroomEnabled),Ue(i.headroomUrl||""),dt(!!i.headroomCompressUserMessages),ut(!!i.ponytailEnabled),ht(i.ponytailLevel||"full"),xt(!!i.paleoEnabled),pt(i.paleoLevel||"full"),ae()}if(b.ok){const i=await b.json(),P=((t=i.tunnel)==null?void 0:t.settingsEnabled)??((s=i.tunnel)==null?void 0:s.enabled)??!1,v=((l=i.tunnel)==null?void 0:l.tunnelUrl)||"";ue(v),Me(((n=i.tunnel)==null?void 0:n.publicUrl)||""),de(P),Ne(null,ge,ee,me,je,ze);const Qe=((r=i.tailscale)==null?void 0:r.settingsEnabled)??((o=i.tailscale)==null?void 0:o.enabled)??!1,_s=((u=i.tailscale)==null?void 0:u.tunnelUrl)||"";W(_s),M(Qe),Ne(null,ye,te,xe,we,Be)}}catch(y){console.log("Error loading settings:",y)}finally{He(!1)}},ss=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelDashboardAccess:t})})).ok&&lt(t)}catch(s){console.log("Error updating tunnelDashboardAccess:",s)}},as=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({requireApiKey:t})})).ok&&st(t)}catch(s){console.log("Error updating requireApiKey:",s)}},ns=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({rtkEnabled:t})})).ok&&it(t)}catch(s){console.log("Error updating rtkEnabled:",s)}},k=async t=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(s){console.log("Error updating setting:",s)}},ls=t=>{ot(t),k({cavemanEnabled:t})},rs=t=>{Pe(t),k({cavemanLevel:t})},is=t=>{ct(t),k({headroomEnabled:t})},os=t=>{Ue(t),k({headroomUrl:t})},cs=t=>{dt(t),k({headroomCompressUserMessages:t})},ae=a.useCallback(async()=>{Ae(t=>({...t,loading:!0}));try{const s=await(await fetch("/api/headroom/status",{headers:{"Cache-Control":"no-store"}})).json();Ae({...s,loading:!1}),s.url&&!_e&&Ue(s.url)}catch{Ae({installed:!1,running:!1,python:null,loading:!1})}},[_e]),ds=a.useCallback(async()=>{mt(""),ce(!0);try{const t=await fetch("/api/headroom/start",{method:"POST"}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(s.error||"Failed to start proxy");await ae()}catch(t){mt(t.message)}finally{ce(!1)}},[ae]),ms=a.useCallback(async()=>{ce(!0);try{await fetch("/api/headroom/stop",{method:"POST"}),await ae()}finally{ce(!1)}},[ae]),us=t=>{ut(t),k({ponytailEnabled:t})},hs=t=>{ht(t),k({ponytailLevel:t})},xs=t=>{xt(t),k({paleoEnabled:t})},ps=t=>{pt(t),k({paleoLevel:t})},kt=async()=>{try{const t=await fetch("/api/keys"),s=await t.json();t.ok&&x(s.keys||[])}catch(t){console.log("Error fetching data:",t)}finally{R(!1)}},fs=async(...t)=>{var n;T(!0),S("Waiting for tunnel ready...");const s=t.filter(Boolean).map(r=>`${r}/api/health`),l=Date.now();for(;Date.now()-l<Ut;){if(await new Promise(o=>setTimeout(o,et)),await Promise.any(s.map(async o=>{if((await fetch(o,{mode:"cors",cache:"no-store"})).ok)return!0;throw new Error("not ready")})).catch(()=>!1))return de(!0),T(!1),S(""),!0;if((Date.now()-l)%1e4<et)try{const o=await fetch("/api/tunnel/status");if(o.ok&&!((n=(await o.json()).tunnel)!=null&&n.enabled))return N({type:"error",message:"Tunnel process stopped unexpectedly."}),T(!1),S(""),!1}catch{}}return N({type:"error",message:"Tunnel created but not reachable. Please try again."}),T(!1),S(""),!1},bs=async()=>{Y(!1),T(!0),N(null),S("Creating tunnel...");let t=!0;(async()=>{var l;for(;t;){try{const n=await fetch("/api/tunnel/status");if(n.ok){const r=await n.json();(l=r.download)!=null&&l.downloading?S(`Downloading cloudflared... ${r.download.progress}%`):t&&S("Creating tunnel...")}}catch{}await new Promise(n=>setTimeout(n,1e3))}})();try{const l=await fetch("/api/tunnel/enable",{method:"POST"});t=!1;const n=await l.json();if(!l.ok){N({type:"error",message:n.error||"Failed to enable tunnel"});return}const r=n.tunnelUrl;if(!r){N({type:"error",message:"No tunnel URL returned"});return}ue(r),Me(n.publicUrl||""),await fs(n.publicUrl,r)}catch(l){N({type:"error",message:l.message})}finally{t=!1,T(!1),S("")}},gs=async()=>{T(!0),N(null);try{const t=await fetch("/api/tunnel/disable",{method:"POST"}),s=await t.json();t.ok?(de(!1),ue(""),X(!1),N({type:"success",message:"Tunnel disabled"})):N({type:"error",message:s.error||"Failed to disable tunnel"})}catch(t){N({type:"error",message:t.message})}finally{T(!1)}},ys=async()=>{pe(null);try{const t=await fetch("/api/tunnel/tailscale-check");if(t.ok){const s=await t.json();return pe(s.installed),s}}catch{}return pe(!1),{installed:!1}},js=async()=>{Ke(!0),m(null),qe([]);try{const t=await fetch("/api/tunnel/tailscale-install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sudoPassword:$t})});jt("");const s=t.body.getReader(),l=new TextDecoder;let n="";for(;;){const{done:r,value:o}=await s.read();if(r)break;n+=l.decode(o,{stream:!0});const u=n.split(`
2
-
3
- `);n=u.pop()||"";for(const y of u){const b=y.split(`
4
- `);let i="progress",P=null;for(const v of b)if(v.startsWith("event: ")&&(i=v.slice(7).trim()),v.startsWith("data: "))try{P=JSON.parse(v.slice(6))}catch{}if(P)if(i==="progress")qe(v=>[...v.slice(-50),P.message]);else if(i==="done"){pe(!0),Ke(!1),$(!1),Ye();return}else i==="error"&&m({type:"error",message:P.error||"Install failed"})}}}catch(t){m({type:"error",message:t.message})}finally{Ke(!1)}},Ve=async t=>{A("Waiting for Tailscale ready...");const s=`${t}/api/health`,l=Date.now();for(;Date.now()-l<Ut;){await new Promise(n=>setTimeout(n,et));try{const n=await fetch(s,{mode:"no-cors",cache:"no-store"});if(n.ok||n.type==="opaque")return!0}catch{}}return!1},vt=(t,s)=>{gt(t),yt(s)},E=()=>{gt(""),yt("")},Ye=async()=>{$(!1),$e(!0),Q(!0),m(null),A("Connecting..."),E();try{const t=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),s=await t.json();if(t.ok&&s.success){W(s.tunnelUrl||"");const l=await Ve(s.tunnelUrl);M(!0),m(l?null:{type:"warning",message:"Connected but not reachable yet."});return}if(s.needsLogin&&s.authUrl){vt(s.authUrl,"Open Login Page"),A('Login required — click "Open Login Page" to continue');for(let l=0;l<40;l++){await new Promise(n=>setTimeout(n,3e3));try{const n=await fetch("/api/tunnel/tailscale-check");if(n.ok&&(await n.json()).loggedIn){E(),A("Starting funnel...");const o=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),u=await o.json();if(o.ok&&u.success){W(u.tunnelUrl||"");const y=await Ve(u.tunnelUrl);M(!0),m(y?null:{type:"warning",message:"Connected but not reachable yet."})}else u.funnelNotEnabled&&u.enableUrl?await Ct(u.enableUrl):m({type:"error",message:u.error||"Failed to start funnel"});return}}catch{}}E(),m({type:"error",message:"Login timed out. Please try again."});return}if(s.funnelNotEnabled&&s.enableUrl){await Ct(s.enableUrl);return}m({type:"error",message:s.error||"Failed to connect"})}catch(t){m({type:"error",message:t.message})}finally{Q(!1),$e(!1),A(""),E()}},Ct=async t=>{vt(t,"Open Funnel Settings"),A('Click "Open Funnel Settings" to enable Funnel...');for(let s=0;s<40;s++){await new Promise(l=>setTimeout(l,3e3));try{const l=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),n=await l.json();if(l.ok&&n.success){E(),W(n.tunnelUrl||"");const r=await Ve(n.tunnelUrl);M(!0),m(r?null:{type:"warning",message:"Connected but not reachable yet."});return}if(n.funnelNotEnabled)continue;if(n.error){E(),m({type:"error",message:n.error});return}}catch{}}E(),m({type:"error",message:"Timed out waiting for Funnel to be enabled."})},ws=async()=>{Q(!0),m(null);try{const t=await fetch("/api/tunnel/tailscale-disable",{method:"POST"}),s=await t.json();t.ok?(M(!1),W(""),Z(!1),m({type:"success",message:"Tailscale disabled"})):m({type:"error",message:s.error||"Failed to disable Tailscale"})}catch(t){m({type:"error",message:t.message})}finally{Q(!1)}},Tt=async()=>{m(null),qe([]);const t=await ys();t!=null&&t.installed&&(t!=null&&t.hasCachedPassword)?Ye():$(!0)},Ns=async()=>{if(ne.trim())try{const t=await fetch("/api/keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ne})}),s=await t.json();t.ok&&(Se(s.key),await kt(),le(""),C(!1))}catch(t){console.log("Error creating key:",t)}},ks=async t=>{J({title:"Delete API Key",message:"Delete this API key?",onConfirm:async()=>{J(null);try{(await fetch(`/api/keys/${t}`,{method:"DELETE"})).ok&&(x(d.filter(l=>l.id!==t)),wt(l=>{const n=new Set(l);return n.delete(t),n}))}catch(s){console.log("Error deleting key:",s)}}})},St=async(t,s)=>{try{(await fetch(`/api/keys/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:s})})).ok&&x(n=>n.map(r=>r.id===t?{...r,isActive:s}:r))}catch(l){console.log("Error toggling key:",l)}},vs=t=>t?t.length>8?t.slice(0,8)+"...":t:"",Cs=t=>{wt(s=>{const l=new Set(s);return l.has(t)?l.delete(t):l.add(t),l})},[Ts,Ss]=a.useState("/v1");if(a.useEffect(()=>{typeof window<"u"&&Ss(`${window.location.origin}/v1`)},[]),j)return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsx(_t,{}),e.jsx(_t,{})]});const Es=Ts,ke=!!I.running,Xe=I.localUrl!==!1,Et=!!I.canStart,Ps=Xe&&!!I.managedPid,Ls=I.loading?"Checking…":ke?"Running":Xe&&!I.installed?"Not installed":Xe?"Proxy off":"Unreachable";return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsxs(Ze,{children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"api"}),"API Endpoint"]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(qs,{label:"Local",url:Es,copyId:"local_url",copied:z,onCopy:se}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${p?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:"Tunnel"}),p&&!_&&D?e.jsxs(e.Fragment,{children:[e.jsx(G,{value:`${H||O}/v1`,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>se(`${H||O}/v1`,"tunnel_url"),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:z==="tunnel_url"?"check":"content_copy"})}),e.jsx("button",{onClick:()=>X(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tunnel",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):p&&!_&&!D?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Jt?"Tunnel reconnecting...":"Tunnel checking..."]}),e.jsx("button",{onClick:()=>X(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tunnel",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):_?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Mt||"Creating tunnel..."]}),e.jsx("button",{onClick:()=>{T(!1),S("")},className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):(he==null?void 0:he.type)==="error"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"error"}),he.message]}),e.jsx(c,{size:"sm",icon:"cloud_upload",onClick:()=>Y(!0),children:"Enable"})]}):Ht?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Checking..."]}),e.jsx("button",{onClick:()=>He(!1),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):e.jsx(c,{size:"sm",icon:"cloud_upload",onClick:()=>{Y(!0)},children:"Enable"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${f?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:"Tailscale"}),f&&!U&&F?e.jsxs(e.Fragment,{children:[e.jsx(G,{value:`${K}/v1`,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>se(`${K}/v1`,"ts_url"),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:z==="ts_url"?"check":"content_copy"})}),e.jsx("button",{onClick:()=>Z(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tailscale",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):f&&!U&&!F?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Vt?"Tailscale reconnecting...":"Tailscale checking..."]}),e.jsx("button",{onClick:()=>Z(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tailscale",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):U||zt?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Wt||"Connecting..."]}),bt&&e.jsx(c,{size:"sm",icon:"open_in_new",onClick:()=>window.open(bt,"tailscale_auth","width=600,height=700,noopener,noreferrer"),children:qt||"Open"}),e.jsx("button",{onClick:()=>{Q(!1),$e(!1),A(""),E()},className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):(q==null?void 0:q.type)==="error"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"error"}),q.message]}),e.jsx(c,{size:"sm",icon:"vpn_lock",onClick:Tt,children:"Enable"})]}):e.jsx(c,{size:"sm",icon:"vpn_lock",onClick:()=>{Tt()},className:"bg-linear-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white!",children:"Enable"})]})]}),Zt&&!p&&!f&&e.jsx("div",{className:"mt-4",children:e.jsx(Ce,{message:es,action:{label:"Open settings",href:"/dashboard/profile"}})}),(p||f)&&e.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[!re&&e.jsx(Ce,{message:"Require API key is disabled — your endpoint is publicly accessible without authentication.",action:{label:"Enable",href:"#require-api-key"}}),(!V||!at)&&e.jsx(Ce,{message:V?"Dashboard uses the default password — change it in Profile settings.":"Require login is disabled — anyone can access your dashboard via tunnel.",action:{label:V?"Change password":"Enable",href:"/dashboard/profile"}})]}),(p||f)&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-border flex items-center gap-3",children:[e.jsx(L,{checked:nt,onChange:()=>ss(!nt)}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"font-medium text-sm",children:"Allow dashboard access via tunnel"}),e.jsx(zs,{text:"When enabled, the dashboard can be accessed through your tunnel or Tailscale URL (login still required). When disabled, dashboard access via tunnel/Tailscale is completely blocked."})]})]})]}),e.jsxs(Ze,{id:"rtk",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"bolt"}),"Token Saver"]})}),e.jsxs("div",{className:"flex items-center justify-between pt-2 pb-4 border-b border-border gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Compress tool output"," ",e.jsx("a",{href:"https://github.com/rtk-ai/rtk",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(RTK)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"git/grep/ls/tree/logs → 60-90% fewer input tokens"})]}),e.jsx(L,{checked:rt,onChange:()=>ns(!rt)})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Compress LLM output"," ",e.jsx("a",{href:"https://github.com/JuliusBrussee/caveman",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Caveman)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"Terse-style system prompt → ~65% fewer output tokens (up to 87%)"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[Ee&&e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:Qt.map(t=>e.jsx("button",{onClick:()=>rs(t.id),className:`px-3 py-1.5 rounded text-xs font-medium border transition-colors ${ie===t.id?"bg-primary text-white border-primary":"bg-transparent border-border text-text-muted hover:bg-surface-2"}`,title:t.desc,children:t.label},t.id))}),e.jsx("p",{className:"text-xs text-primary",children:(Pt=ve.find(t=>t.id===ie))==null?void 0:Pt.desc})]}),e.jsx(L,{checked:Ee,onChange:()=>ls(!Ee)})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 pb-4 border-t border-border gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Code minimalism"," ",e.jsx("a",{href:"https://github.com/DietrichGebert/ponytail",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Ponytail)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"Lazy senior dev system prompt → YAGNI / stdlib-first / shortest diff"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[Re&&e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:["lite","full","ultra"].map(t=>e.jsx("button",{onClick:()=>hs(t),className:`px-3 py-1.5 rounded text-xs font-medium border transition-colors ${Ie===t?"bg-primary text-white border-primary":"bg-transparent border-border text-text-muted hover:bg-surface-2"}`,title:t==="lite"?"Build what's asked, name lazier alternative":t==="full"?"Enforce ladder, shortest diff":"YAGNI extremist, deletion before addition",children:t==="lite"?"Lite":t==="full"?"Full":"Ultra"},t))}),e.jsx("p",{className:"text-xs text-primary",children:Ie==="lite"?"Build what's asked, name lazier alternative":Ie==="full"?"Enforce ladder, shortest diff":"YAGNI extremist, deletion before addition"})]}),e.jsx(L,{checked:Re,onChange:()=>us(!Re)})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Token Saver"," ",e.jsx("a",{href:"https://github.com/mocasus/paleo",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Paleo)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"Compress LLM output → ~50-80% fewer output tokens"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[De&&e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:["lite","full","ultra"].map(t=>e.jsx("button",{onClick:()=>ps(t),className:`px-3 py-1.5 rounded text-xs font-medium border transition-colors ${Oe===t?"bg-primary text-white border-primary":"bg-transparent border-border text-text-muted hover:bg-surface-2"}`,title:t==="lite"?"Gentle hints, keep grammar":t==="full"?"Strong compression, fragments OK":"Telegraphic, max savings",children:t==="lite"?"Lite":t==="full"?"Full":"Ultra"},t))}),e.jsx("p",{className:"text-xs text-primary",children:Oe==="lite"?"Gentle hints, keep grammar":Oe==="full"?"Strong compression, fragments OK":"Telegraphic, max savings"})]}),e.jsx(L,{checked:De,onChange:()=>xs(!De)})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Context compression"," ",e.jsx("a",{href:"https://github.com/jerhadf/headroom",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Headroom)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"External proxy compresses input messages → fewer prompt tokens"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[Le&&e.jsxs("div",{className:"flex flex-col items-end gap-2 min-w-[200px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{value:_e,onChange:t=>os(t.target.value),placeholder:"http://localhost:8787",className:"text-xs"}),!ke&&Et&&e.jsx("button",{onClick:ds,disabled:oe,className:"px-2 py-1.5 rounded text-xs font-medium bg-primary text-white hover:opacity-80 disabled:opacity-50",children:oe?"...":"Start"}),ke&&Ps&&e.jsx("button",{onClick:ms,disabled:oe,className:"px-2 py-1.5 rounded text-xs font-medium bg-red-500 text-white hover:opacity-80 disabled:opacity-50",children:oe?"...":"Stop"})]}),e.jsx("p",{className:`text-xs ${ke?"text-green-500":Et?"text-yellow-500":"text-red-500"}`,children:Ls}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-muted cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:Dt,onChange:t=>cs(t.target.checked),className:"rounded"}),"Compress user messages"]})]}),e.jsx(L,{checked:Le,onChange:()=>is(!Le)})]})]})]}),e.jsxs(Ze,{id:"require-api-key",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"vpn_key"}),"API Keys"]}),e.jsx(c,{icon:"add",onClick:()=>C(!0),children:"Create Key"})]}),e.jsxs("div",{className:"flex items-center justify-between pb-4 mb-4 border-b border-border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Require API key"}),e.jsx("p",{className:"text-sm text-text-muted",children:"Requests without a valid key will be rejected"})]}),e.jsx(L,{checked:re,onChange:()=>as(!re)})]}),Yt&&!re&&e.jsx("div",{className:"mb-4 -mt-2",children:e.jsx(Ce,{message:"Endpoint is exposed without an API key."})}),d.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4",children:e.jsx("span",{className:"material-symbols-outlined text-[32px]",children:"vpn_key"})}),e.jsx("p",{className:"text-text-main font-medium mb-1",children:"No API keys yet"}),e.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Create your first API key to get started"}),e.jsx(c,{icon:"add",onClick:()=>C(!0),children:"Create Key"})]}):e.jsx("div",{className:"flex flex-col",children:d.map(t=>e.jsxs("div",{className:`group flex items-center justify-between py-3 border-b border-black/[0.03] dark:border-white/[0.03] last:border-b-0 ${t.isActive===!1?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("code",{className:"text-xs text-text-muted font-mono",children:Ge.has(t.id)?t.key:vs(t.key)}),e.jsx("button",{onClick:()=>Cs(t.id),className:"p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",title:Ge.has(t.id)?"Hide key":"Show key",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:Ge.has(t.id)?"visibility_off":"visibility"})}),e.jsx("button",{onClick:()=>se(t.key,t.id),className:"p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:z===t.id?"check":"content_copy"})})]}),e.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["Created ",new Date(t.createdAt).toLocaleDateString()]}),t.isActive===!1&&e.jsx("p",{className:"text-xs text-orange-500 mt-1",children:"Paused"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(L,{size:"sm",checked:t.isActive??!0,onChange:s=>{t.isActive&&!s?J({title:"Pause API Key",message:`Pause API key "${t.name}"?
5
-
6
- This key will stop working immediately but can be resumed later.`,onConfirm:async()=>{J(null),St(t.id,s)}}):St(t.id,s)},title:t.isActive?"Pause key":"Resume key"}),e.jsx("button",{onClick:()=>ks(t.id),className:"p-2 hover:bg-red-500/10 rounded text-red-500 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"delete"})})]})]},t.id))})]}),e.jsx(B,{isOpen:g,title:"Create API Key",onClose:()=>{C(!1),le("")},children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(G,{label:"Key Name",value:ne,onChange:t=>le(t.target.value),placeholder:"Production Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:Ns,fullWidth:!0,disabled:!ne.trim(),children:"Create"}),e.jsx(c,{onClick:()=>{C(!1),le("")},variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}),e.jsx(B,{isOpen:!!Te,title:"API Key Created",onClose:()=>Se(null),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-yellow-800 dark:text-yellow-200 mb-2 font-medium",children:"Save this key now!"}),e.jsx("p",{className:"text-sm text-yellow-700 dark:text-yellow-300",children:"This is the only time you will see this key. Store it securely."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{value:Te||"",readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx(c,{variant:"secondary",icon:z==="created_key"?"check":"content_copy",onClick:()=>se(Te,"created_key"),children:z==="created_key"?"Copied!":"Copy"})]}),e.jsx(c,{onClick:()=>Se(null),fullWidth:!0,children:"Done"})]})}),e.jsx(B,{isOpen:Ft,title:"Enable Tunnel",onClose:()=>Y(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"bg-surface-2 border border-border-subtle rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"cloud_upload"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-text-main font-medium mb-1",children:"Cloudflare Tunnel"}),e.jsx("p",{className:"text-sm text-text-muted",children:"Expose your local FSRouter to the internet. No port forwarding, no static IP needed. Share endpoint URL with your team or use it in Cursor, Cline, and other AI tools from anywhere."})]})]})}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Os.map(t=>e.jsxs("div",{className:"flex flex-col items-center text-center p-3 rounded-lg bg-sidebar/50",children:[e.jsx("span",{className:"material-symbols-outlined text-xl text-primary mb-1",children:t.icon}),e.jsx("p",{className:"text-xs font-semibold",children:t.title}),e.jsx("p",{className:"text-xs text-text-muted",children:t.desc})]},t.title))}),e.jsx("p",{className:"text-xs text-text-muted",children:"Requires outbound port 7844 (TCP/UDP). Connection may take 10-30s."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:bs,fullWidth:!0,children:"Start Tunnel"}),e.jsx(c,{onClick:()=>Y(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}),e.jsx(B,{isOpen:Kt,title:"Disable Tunnel",onClose:()=>!_&&X(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"The Cloudflare tunnel will be disconnected. Remote access via tunnel URL will stop working."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:gs,fullWidth:!0,disabled:_,variant:"danger",children:_?"Disabling...":"Disable"}),e.jsx(c,{onClick:()=>X(!1),variant:"ghost",fullWidth:!0,disabled:_,children:"Cancel"})]})]})}),e.jsx(B,{isOpen:Bt,title:"Tailscale Funnel",onClose:()=>{fe||($(!1),jt(""),m(null))},children:e.jsxs("div",{className:"flex flex-col gap-4",children:[Fe===null&&e.jsxs("p",{className:"text-sm text-text-muted flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Checking..."]}),Fe===!1&&!fe&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"Tailscale is not installed. Install it to enable Funnel."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:js,fullWidth:!0,children:"Install Tailscale"}),e.jsx(c,{onClick:()=>$(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]}),fe&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Installing Tailscale..."]}),We.length>0&&e.jsx("div",{ref:be,className:"bg-black/5 dark:bg-white/5 rounded p-2 max-h-40 overflow-y-auto font-mono text-xs text-text-muted",children:We.map((t,s)=>e.jsx("div",{children:t},s))})]}),Fe===!0&&!fe&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"check_circle"}),"Tailscale installed"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:()=>Ye(),fullWidth:!0,children:"Connect"}),e.jsx(c,{onClick:()=>$(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]}),q&&e.jsx($s,{status:q})]})}),e.jsx(B,{isOpen:Gt,title:"Disable Tailscale",onClose:()=>!U&&Z(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"Tailscale Funnel will be stopped. Remote access via Tailscale URL will stop working."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:ws,fullWidth:!0,disabled:U,variant:"danger",children:U?"Disabling...":"Disable"}),e.jsx(c,{onClick:()=>Z(!1),variant:"ghost",fullWidth:!0,disabled:U,children:"Cancel"})]})]})}),e.jsx(Rs,{isOpen:!!w,onClose:()=>J(null),onConfirm:w==null?void 0:w.onConfirm,title:(w==null?void 0:w.title)||"Confirm",message:w==null?void 0:w.message,variant:"danger"})]})}function qs({label:h,url:d,copyId:x,copied:j,onCopy:R,badge:g,actions:C}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${g==="CF"||g==="TS"?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:h}),e.jsx(G,{value:d,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>R(d,x),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:j===x?"check":"content_copy"})}),C]})}function $s({status:h,className:d=""}){const x=j=>j.split(/(https?:\/\/[^\s]+)/g).map((g,C)=>/^https?:\/\//.test(g)?e.jsx("a",{href:g,target:"_blank",rel:"noreferrer",className:"underline font-medium",children:g},C):g);return e.jsx("div",{className:`p-2 rounded text-sm ${d} ${h.type==="success"?"bg-green-500/10 text-green-600 dark:text-green-400":h.type==="warning"?"bg-yellow-500/10 text-yellow-600 dark:text-yellow-400":h.type==="info"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-red-500/10 text-red-600 dark:text-red-400"}`,children:x(h.message)})}function zs({text:h}){return e.jsxs("span",{className:"relative group inline-flex items-center",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px] text-text-muted cursor-help",children:"help"}),e.jsx("span",{className:"pointer-events-none absolute left-5 top-1/2 -translate-y-1/2 z-50 w-64 rounded bg-gray-900 dark:bg-gray-800 text-white text-xs px-2.5 py-1.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-lg",children:h})]})}function Ce({message:h,action:d}){return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-700 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] shrink-0 mt-0.5",children:"warning"}),e.jsx("p",{className:"text-xs flex-1",children:h}),d&&e.jsx("a",{href:d.href,className:"text-xs font-medium underline shrink-0 hover:opacity-80",onClick:d.href.startsWith("#")?x=>{var j;x.preventDefault(),(j=document.getElementById(d.href.slice(1)))==null||j.scrollIntoView({behavior:"smooth"})}:void 0,children:d.label})]})}Ws.propTypes={machineId:Is.string.isRequired};export{Ws as A};
@@ -1,6 +0,0 @@
1
- import{p as Lt,q as Us,u as As,j as e,B as c,M as B,C as Rs,f as Is}from"./index.CoYbjSIL.js";import{b as a}from"./router.Cjj1--8t.js";import{C as Ze,I as G,T as L}from"./NoAuthProxyCard.Buvt0BVH.js";import{C as _t}from"./Loading.QMOYJhLu.js";const Ds=["zh-CN","zh-TW"],Os=[{icon:"public",title:"Access Anywhere",desc:"Use your API from any network"},{icon:"group",title:"Share Endpoint",desc:"Share URL with team members"},{icon:"code",title:"Use in Cursor/Cline",desc:"Connect AI tools remotely"},{icon:"lock",title:"Encrypted",desc:"End-to-end TLS via Cloudflare"}],et=2e3,Ut=3e5,Hs=5e3,tt=5,Ms=1e4,Fs=5e3;async function At(h){if(!h)return!1;try{return(await fetch(`${h}/api/health`,{mode:"cors",cache:"no-store",signal:AbortSignal.timeout(Fs)})).ok}catch{return!1}}async function Ks(...h){const d=h.filter(Boolean).map(At);return d.length?new Promise(x=>{let j=d.length;d.forEach(R=>R.then(g=>{g?x(!0):--j===0&&x(!1)}))}):!1}const ve=[{id:"lite",label:"Lite",desc:"Drop filler, keep grammar"},{id:"full",label:"Full",desc:"Drop articles, fragments OK"},{id:"ultra",label:"Ultra",desc:"Telegraphic, max compression"},{id:"wenyan-lite",label:"文 Lite",desc:"Classical Chinese, light compression",wenyan:!0},{id:"wenyan",label:"文 Full",desc:"Maximum 文言文, 80-90% reduction",wenyan:!0},{id:"wenyan-ultra",label:"文 Ultra",desc:"Extreme classical compression",wenyan:!0}];function Ws({machineId:h}){var Pt;const[d,x]=a.useState([]),[j,R]=a.useState(!0),[g,C]=a.useState(!1),[ne,le]=a.useState(""),[Te,Se]=a.useState(null),[w,J]=a.useState(null),[re,st]=a.useState(!1),[V,Rt]=a.useState(!0),[at,It]=a.useState(!0),[nt,lt]=a.useState(!1),[rt,it]=a.useState(!0),[Ee,ot]=a.useState(!1),[ie,Pe]=a.useState("full"),[Le,ct]=a.useState(!1),[_e,Ue]=a.useState(""),[Dt,dt]=a.useState(!1),[I,Ae]=a.useState({installed:!1,running:!1,python:null,loading:!0}),[Bs,Gs]=a.useState(!1),[oe,ce]=a.useState(!1),[Js,mt]=a.useState(""),[Re,ut]=a.useState(!1),[Ie,ht]=a.useState("full"),[De,xt]=a.useState(!1),[Oe,pt]=a.useState("full"),[Ot,ft]=a.useState("en"),[Ht,He]=a.useState(!0),[p,de]=a.useState(!1),[D,me]=a.useState(!1),[O,ue]=a.useState(""),[H,Me]=a.useState(""),[_,T]=a.useState(!1),[Mt,S]=a.useState(""),[he,N]=a.useState(null),[Ft,Y]=a.useState(!1),[Kt,X]=a.useState(!1),[f,M]=a.useState(!1),[F,xe]=a.useState(!1),[K,W]=a.useState(""),[U,Q]=a.useState(!1),[Wt,A]=a.useState(""),[q,m]=a.useState(null),[bt,gt]=a.useState(""),[qt,yt]=a.useState(""),[Fe,pe]=a.useState(null),[fe,Ke]=a.useState(!1),[We,qe]=a.useState([]),[$t,jt]=a.useState(""),[zt,$e]=a.useState(!1),[Bt,$]=a.useState(!1),[Gt,Z]=a.useState(!1),be=a.useRef(null),ee=a.useRef(0),te=a.useRef(0),ge=a.useRef(!1),ye=a.useRef(!1),je=a.useRef(!1),we=a.useRef(!1),[Jt,ze]=a.useState(!1),[Vt,Be]=a.useState(!1),[Ge,wt]=a.useState(new Set),[Yt,Xt]=a.useState(!1);a.useEffect(()=>{typeof window<"u"&&Xt(!["localhost","127.0.0.1","::1"].includes(window.location.hostname))},[]),a.useEffect(()=>(ft(Lt()),Us(()=>ft(Lt()))),[]);const Je=Ds.includes(Ot),Qt=Je?ve:ve.filter(t=>!t.wenyan);a.useEffect(()=>{const t=ve.find(s=>s.id===ie);t!=null&&t.wenyan&&!Je&&(Pe("ultra"),k({cavemanLevel:"ultra"}))},[Je,ie]);const{copied:z,copy:se}=As(),Zt=!V||!at,es=V?"Change the default dashboard password before activating the tunnel.":'Enable "Require login" and set a custom password before activating the tunnel.';a.useEffect(()=>{be.current&&(be.current.scrollTop=be.current.scrollHeight)},[We]),a.useEffect(()=>{kt(),ts()},[]),a.useEffect(()=>{if(!(p||f))return;const n=(!p||D)&&(!f||F),r=()=>{document.hidden||Nt()};if(document.addEventListener("visibilitychange",r),n)return()=>document.removeEventListener("visibilitychange",r);const o=setInterval(()=>{document.hidden||Nt()},Hs);return()=>{clearInterval(o),document.removeEventListener("visibilitychange",r)}},[p,f,D,F]),a.useEffect(()=>{const t=async()=>{if(!document.hidden){if(p&&(O||H)){const o=await Ks(H,O);ge.current=o,o?(ee.current=0,me(!0),je.current||(je.current=!0,ze(!0))):(ee.current+=1,ee.current>=tt&&me(!1))}else ge.current=!1;if(f&&K){const o=await At(K);ye.current=o,o?(te.current=0,xe(!0),we.current||(we.current=!0,Be(!0))):(te.current+=1,te.current>=tt&&xe(!1))}else ye.current=!1}};if(!(p&&(O||H)||f&&K)||(t(),(!p||D)&&(!f||F)))return;const r=setInterval(t,Ms);return()=>clearInterval(r)},[p,O,H,f,K,D,F]);const Ne=a.useCallback((t,s,l,n,r,o)=>{s.current?(l.current=0,n(!0),r.current||(r.current=!0,o(!0))):(l.current+=1,l.current>=tt&&n(!1))},[]),Nt=async()=>{var t,s,l,n,r,o,u;try{const y=await fetch("/api/tunnel/status",{cache:"no-store"});if(!y.ok)return;const b=await y.json(),i=((t=b.tunnel)==null?void 0:t.settingsEnabled)??((s=b.tunnel)==null?void 0:s.enabled)??!1,P=((l=b.tunnel)==null?void 0:l.tunnelUrl)||"";ue(P),Me(((n=b.tunnel)==null?void 0:n.publicUrl)||""),de(i),Ne(null,ge,ee,me,je,ze);const v=((r=b.tailscale)==null?void 0:r.settingsEnabled)??((o=b.tailscale)==null?void 0:o.enabled)??!1,Qe=((u=b.tailscale)==null?void 0:u.tunnelUrl)||"";W(Qe),M(v),Ne(null,ye,te,xe,we,Be)}catch{}},ts=async()=>{var t,s,l,n,r,o,u;He(!0);try{const[y,b]=await Promise.all([fetch("/api/settings"),fetch("/api/tunnel/status",{cache:"no-store"})]);if(y.ok){const i=await y.json();st(i.requireApiKey||!1),Rt(i.requireLogin!==!1),It(i.hasPassword||!1),lt(i.tunnelDashboardAccess||!1),it(i.rtkEnabled!==!1),ot(!!i.cavemanEnabled),Pe(i.cavemanLevel||"full"),ct(!!i.headroomEnabled),Ue(i.headroomUrl||""),dt(!!i.headroomCompressUserMessages),ut(!!i.ponytailEnabled),ht(i.ponytailLevel||"full"),xt(!!i.paleoEnabled),pt(i.paleoLevel||"full"),ae()}if(b.ok){const i=await b.json(),P=((t=i.tunnel)==null?void 0:t.settingsEnabled)??((s=i.tunnel)==null?void 0:s.enabled)??!1,v=((l=i.tunnel)==null?void 0:l.tunnelUrl)||"";ue(v),Me(((n=i.tunnel)==null?void 0:n.publicUrl)||""),de(P),Ne(null,ge,ee,me,je,ze);const Qe=((r=i.tailscale)==null?void 0:r.settingsEnabled)??((o=i.tailscale)==null?void 0:o.enabled)??!1,_s=((u=i.tailscale)==null?void 0:u.tunnelUrl)||"";W(_s),M(Qe),Ne(null,ye,te,xe,we,Be)}}catch(y){console.log("Error loading settings:",y)}finally{He(!1)}},ss=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelDashboardAccess:t})})).ok&&lt(t)}catch(s){console.log("Error updating tunnelDashboardAccess:",s)}},as=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({requireApiKey:t})})).ok&&st(t)}catch(s){console.log("Error updating requireApiKey:",s)}},ns=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({rtkEnabled:t})})).ok&&it(t)}catch(s){console.log("Error updating rtkEnabled:",s)}},k=async t=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(s){console.log("Error updating setting:",s)}},ls=t=>{ot(t),k({cavemanEnabled:t})},rs=t=>{Pe(t),k({cavemanLevel:t})},is=t=>{ct(t),k({headroomEnabled:t})},os=t=>{Ue(t),k({headroomUrl:t})},cs=t=>{dt(t),k({headroomCompressUserMessages:t})},ae=a.useCallback(async()=>{Ae(t=>({...t,loading:!0}));try{const s=await(await fetch("/api/headroom/status",{headers:{"Cache-Control":"no-store"}})).json();Ae({...s,loading:!1}),s.url&&!_e&&Ue(s.url)}catch{Ae({installed:!1,running:!1,python:null,loading:!1})}},[_e]),ds=a.useCallback(async()=>{mt(""),ce(!0);try{const t=await fetch("/api/headroom/start",{method:"POST"}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(s.error||"Failed to start proxy");await ae()}catch(t){mt(t.message)}finally{ce(!1)}},[ae]),ms=a.useCallback(async()=>{ce(!0);try{await fetch("/api/headroom/stop",{method:"POST"}),await ae()}finally{ce(!1)}},[ae]),us=t=>{ut(t),k({ponytailEnabled:t})},hs=t=>{ht(t),k({ponytailLevel:t})},xs=t=>{xt(t),k({paleoEnabled:t})},ps=t=>{pt(t),k({paleoLevel:t})},kt=async()=>{try{const t=await fetch("/api/keys"),s=await t.json();t.ok&&x(s.keys||[])}catch(t){console.log("Error fetching data:",t)}finally{R(!1)}},fs=async(...t)=>{var n;T(!0),S("Waiting for tunnel ready...");const s=t.filter(Boolean).map(r=>`${r}/api/health`),l=Date.now();for(;Date.now()-l<Ut;){if(await new Promise(o=>setTimeout(o,et)),await Promise.any(s.map(async o=>{if((await fetch(o,{mode:"cors",cache:"no-store"})).ok)return!0;throw new Error("not ready")})).catch(()=>!1))return de(!0),T(!1),S(""),!0;if((Date.now()-l)%1e4<et)try{const o=await fetch("/api/tunnel/status");if(o.ok&&!((n=(await o.json()).tunnel)!=null&&n.enabled))return N({type:"error",message:"Tunnel process stopped unexpectedly."}),T(!1),S(""),!1}catch{}}return N({type:"error",message:"Tunnel created but not reachable. Please try again."}),T(!1),S(""),!1},bs=async()=>{Y(!1),T(!0),N(null),S("Creating tunnel...");let t=!0;(async()=>{var l;for(;t;){try{const n=await fetch("/api/tunnel/status");if(n.ok){const r=await n.json();(l=r.download)!=null&&l.downloading?S(`Downloading cloudflared... ${r.download.progress}%`):t&&S("Creating tunnel...")}}catch{}await new Promise(n=>setTimeout(n,1e3))}})();try{const l=await fetch("/api/tunnel/enable",{method:"POST"});t=!1;const n=await l.json();if(!l.ok){N({type:"error",message:n.error||"Failed to enable tunnel"});return}const r=n.tunnelUrl;if(!r){N({type:"error",message:"No tunnel URL returned"});return}ue(r),Me(n.publicUrl||""),await fs(n.publicUrl,r)}catch(l){N({type:"error",message:l.message})}finally{t=!1,T(!1),S("")}},gs=async()=>{T(!0),N(null);try{const t=await fetch("/api/tunnel/disable",{method:"POST"}),s=await t.json();t.ok?(de(!1),ue(""),X(!1),N({type:"success",message:"Tunnel disabled"})):N({type:"error",message:s.error||"Failed to disable tunnel"})}catch(t){N({type:"error",message:t.message})}finally{T(!1)}},ys=async()=>{pe(null);try{const t=await fetch("/api/tunnel/tailscale-check");if(t.ok){const s=await t.json();return pe(s.installed),s}}catch{}return pe(!1),{installed:!1}},js=async()=>{Ke(!0),m(null),qe([]);try{const t=await fetch("/api/tunnel/tailscale-install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sudoPassword:$t})});jt("");const s=t.body.getReader(),l=new TextDecoder;let n="";for(;;){const{done:r,value:o}=await s.read();if(r)break;n+=l.decode(o,{stream:!0});const u=n.split(`
2
-
3
- `);n=u.pop()||"";for(const y of u){const b=y.split(`
4
- `);let i="progress",P=null;for(const v of b)if(v.startsWith("event: ")&&(i=v.slice(7).trim()),v.startsWith("data: "))try{P=JSON.parse(v.slice(6))}catch{}if(P)if(i==="progress")qe(v=>[...v.slice(-50),P.message]);else if(i==="done"){pe(!0),Ke(!1),$(!1),Ye();return}else i==="error"&&m({type:"error",message:P.error||"Install failed"})}}}catch(t){m({type:"error",message:t.message})}finally{Ke(!1)}},Ve=async t=>{A("Waiting for Tailscale ready...");const s=`${t}/api/health`,l=Date.now();for(;Date.now()-l<Ut;){await new Promise(n=>setTimeout(n,et));try{const n=await fetch(s,{mode:"no-cors",cache:"no-store"});if(n.ok||n.type==="opaque")return!0}catch{}}return!1},vt=(t,s)=>{gt(t),yt(s)},E=()=>{gt(""),yt("")},Ye=async()=>{$(!1),$e(!0),Q(!0),m(null),A("Connecting..."),E();try{const t=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),s=await t.json();if(t.ok&&s.success){W(s.tunnelUrl||"");const l=await Ve(s.tunnelUrl);M(!0),m(l?null:{type:"warning",message:"Connected but not reachable yet."});return}if(s.needsLogin&&s.authUrl){vt(s.authUrl,"Open Login Page"),A('Login required — click "Open Login Page" to continue');for(let l=0;l<40;l++){await new Promise(n=>setTimeout(n,3e3));try{const n=await fetch("/api/tunnel/tailscale-check");if(n.ok&&(await n.json()).loggedIn){E(),A("Starting funnel...");const o=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),u=await o.json();if(o.ok&&u.success){W(u.tunnelUrl||"");const y=await Ve(u.tunnelUrl);M(!0),m(y?null:{type:"warning",message:"Connected but not reachable yet."})}else u.funnelNotEnabled&&u.enableUrl?await Ct(u.enableUrl):m({type:"error",message:u.error||"Failed to start funnel"});return}}catch{}}E(),m({type:"error",message:"Login timed out. Please try again."});return}if(s.funnelNotEnabled&&s.enableUrl){await Ct(s.enableUrl);return}m({type:"error",message:s.error||"Failed to connect"})}catch(t){m({type:"error",message:t.message})}finally{Q(!1),$e(!1),A(""),E()}},Ct=async t=>{vt(t,"Open Funnel Settings"),A('Click "Open Funnel Settings" to enable Funnel...');for(let s=0;s<40;s++){await new Promise(l=>setTimeout(l,3e3));try{const l=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),n=await l.json();if(l.ok&&n.success){E(),W(n.tunnelUrl||"");const r=await Ve(n.tunnelUrl);M(!0),m(r?null:{type:"warning",message:"Connected but not reachable yet."});return}if(n.funnelNotEnabled)continue;if(n.error){E(),m({type:"error",message:n.error});return}}catch{}}E(),m({type:"error",message:"Timed out waiting for Funnel to be enabled."})},ws=async()=>{Q(!0),m(null);try{const t=await fetch("/api/tunnel/tailscale-disable",{method:"POST"}),s=await t.json();t.ok?(M(!1),W(""),Z(!1),m({type:"success",message:"Tailscale disabled"})):m({type:"error",message:s.error||"Failed to disable Tailscale"})}catch(t){m({type:"error",message:t.message})}finally{Q(!1)}},Tt=async()=>{m(null),qe([]);const t=await ys();t!=null&&t.installed&&(t!=null&&t.hasCachedPassword)?Ye():$(!0)},Ns=async()=>{if(ne.trim())try{const t=await fetch("/api/keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ne})}),s=await t.json();t.ok&&(Se(s.key),await kt(),le(""),C(!1))}catch(t){console.log("Error creating key:",t)}},ks=async t=>{J({title:"Delete API Key",message:"Delete this API key?",onConfirm:async()=>{J(null);try{(await fetch(`/api/keys/${t}`,{method:"DELETE"})).ok&&(x(d.filter(l=>l.id!==t)),wt(l=>{const n=new Set(l);return n.delete(t),n}))}catch(s){console.log("Error deleting key:",s)}}})},St=async(t,s)=>{try{(await fetch(`/api/keys/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:s})})).ok&&x(n=>n.map(r=>r.id===t?{...r,isActive:s}:r))}catch(l){console.log("Error toggling key:",l)}},vs=t=>t?t.length>8?t.slice(0,8)+"...":t:"",Cs=t=>{wt(s=>{const l=new Set(s);return l.has(t)?l.delete(t):l.add(t),l})},[Ts,Ss]=a.useState("/v1");if(a.useEffect(()=>{typeof window<"u"&&Ss(`${window.location.origin}/v1`)},[]),j)return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsx(_t,{}),e.jsx(_t,{})]});const Es=Ts,ke=!!I.running,Xe=I.localUrl!==!1,Et=!!I.canStart,Ps=Xe&&!!I.managedPid,Ls=I.loading?"Checking…":ke?"Running":Xe&&!I.installed?"Not installed":Xe?"Proxy off":"Unreachable";return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsxs(Ze,{children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"api"}),"API Endpoint"]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(qs,{label:"Local",url:Es,copyId:"local_url",copied:z,onCopy:se}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${p?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:"Tunnel"}),p&&!_&&D?e.jsxs(e.Fragment,{children:[e.jsx(G,{value:`${H||O}/v1`,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>se(`${H||O}/v1`,"tunnel_url"),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:z==="tunnel_url"?"check":"content_copy"})}),e.jsx("button",{onClick:()=>X(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tunnel",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):p&&!_&&!D?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Jt?"Tunnel reconnecting...":"Tunnel checking..."]}),e.jsx("button",{onClick:()=>X(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tunnel",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):_?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Mt||"Creating tunnel..."]}),e.jsx("button",{onClick:()=>{T(!1),S("")},className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):(he==null?void 0:he.type)==="error"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"error"}),he.message]}),e.jsx(c,{size:"sm",icon:"cloud_upload",onClick:()=>Y(!0),children:"Enable"})]}):Ht?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Checking..."]}),e.jsx("button",{onClick:()=>He(!1),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):e.jsx(c,{size:"sm",icon:"cloud_upload",onClick:()=>{Y(!0)},children:"Enable"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${f?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:"Tailscale"}),f&&!U&&F?e.jsxs(e.Fragment,{children:[e.jsx(G,{value:`${K}/v1`,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>se(`${K}/v1`,"ts_url"),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:z==="ts_url"?"check":"content_copy"})}),e.jsx("button",{onClick:()=>Z(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tailscale",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):f&&!U&&!F?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Vt?"Tailscale reconnecting...":"Tailscale checking..."]}),e.jsx("button",{onClick:()=>Z(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tailscale",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):U||zt?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),Wt||"Connecting..."]}),bt&&e.jsx(c,{size:"sm",icon:"open_in_new",onClick:()=>window.open(bt,"tailscale_auth","width=600,height=700,noopener,noreferrer"),children:qt||"Open"}),e.jsx("button",{onClick:()=>{Q(!1),$e(!1),A(""),E()},className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):(q==null?void 0:q.type)==="error"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"error"}),q.message]}),e.jsx(c,{size:"sm",icon:"vpn_lock",onClick:Tt,children:"Enable"})]}):e.jsx(c,{size:"sm",icon:"vpn_lock",onClick:()=>{Tt()},className:"bg-linear-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white!",children:"Enable"})]})]}),Zt&&!p&&!f&&e.jsx("div",{className:"mt-4",children:e.jsx(Ce,{message:es,action:{label:"Open settings",href:"/dashboard/profile"}})}),(p||f)&&e.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[!re&&e.jsx(Ce,{message:"Require API key is disabled — your endpoint is publicly accessible without authentication.",action:{label:"Enable",href:"#require-api-key"}}),(!V||!at)&&e.jsx(Ce,{message:V?"Dashboard uses the default password — change it in Profile settings.":"Require login is disabled — anyone can access your dashboard via tunnel.",action:{label:V?"Change password":"Enable",href:"/dashboard/profile"}})]}),(p||f)&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-border flex items-center gap-3",children:[e.jsx(L,{checked:nt,onChange:()=>ss(!nt)}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"font-medium text-sm",children:"Allow dashboard access via tunnel"}),e.jsx(zs,{text:"When enabled, the dashboard can be accessed through your tunnel or Tailscale URL (login still required). When disabled, dashboard access via tunnel/Tailscale is completely blocked."})]})]})]}),e.jsxs(Ze,{id:"rtk",children:[e.jsx("div",{className:"flex items-center justify-between mb-2",children:e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"bolt"}),"Token Saver"]})}),e.jsxs("div",{className:"flex items-center justify-between pt-2 pb-4 border-b border-border gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Compress tool output"," ",e.jsx("a",{href:"https://github.com/rtk-ai/rtk",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(RTK)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"git/grep/ls/tree/logs → 60-90% fewer input tokens"})]}),e.jsx(L,{checked:rt,onChange:()=>ns(!rt)})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Compress LLM output"," ",e.jsx("a",{href:"https://github.com/JuliusBrussee/caveman",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Caveman)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"Terse-style system prompt → ~65% fewer output tokens (up to 87%)"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[Ee&&e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:Qt.map(t=>e.jsx("button",{onClick:()=>rs(t.id),className:`px-3 py-1.5 rounded text-xs font-medium border transition-colors ${ie===t.id?"bg-primary text-white border-primary":"bg-transparent border-border text-text-muted hover:bg-surface-2"}`,title:t.desc,children:t.label},t.id))}),e.jsx("p",{className:"text-xs text-primary",children:(Pt=ve.find(t=>t.id===ie))==null?void 0:Pt.desc})]}),e.jsx(L,{checked:Ee,onChange:()=>ls(!Ee)})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 pb-4 border-t border-border gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Code minimalism"," ",e.jsx("a",{href:"https://github.com/DietrichGebert/ponytail",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Ponytail)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"Lazy senior dev system prompt → YAGNI / stdlib-first / shortest diff"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[Re&&e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:["lite","full","ultra"].map(t=>e.jsx("button",{onClick:()=>hs(t),className:`px-3 py-1.5 rounded text-xs font-medium border transition-colors ${Ie===t?"bg-primary text-white border-primary":"bg-transparent border-border text-text-muted hover:bg-surface-2"}`,title:t==="lite"?"Build what's asked, name lazier alternative":t==="full"?"Enforce ladder, shortest diff":"YAGNI extremist, deletion before addition",children:t==="lite"?"Lite":t==="full"?"Full":"Ultra"},t))}),e.jsx("p",{className:"text-xs text-primary",children:Ie==="lite"?"Build what's asked, name lazier alternative":Ie==="full"?"Enforce ladder, shortest diff":"YAGNI extremist, deletion before addition"})]}),e.jsx(L,{checked:Re,onChange:()=>us(!Re)})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Token Saver"," ",e.jsx("a",{href:"https://github.com/mocasus/paleo",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Paleo)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"Compress LLM output → ~50-80% fewer output tokens"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[De&&e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:["lite","full","ultra"].map(t=>e.jsx("button",{onClick:()=>ps(t),className:`px-3 py-1.5 rounded text-xs font-medium border transition-colors ${Oe===t?"bg-primary text-white border-primary":"bg-transparent border-border text-text-muted hover:bg-surface-2"}`,title:t==="lite"?"Gentle hints, keep grammar":t==="full"?"Strong compression, fragments OK":"Telegraphic, max savings",children:t==="lite"?"Lite":t==="full"?"Full":"Ultra"},t))}),e.jsx("p",{className:"text-xs text-primary",children:Oe==="lite"?"Gentle hints, keep grammar":Oe==="full"?"Strong compression, fragments OK":"Telegraphic, max savings"})]}),e.jsx(L,{checked:De,onChange:()=>xs(!De)})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"font-medium",children:["Context compression"," ",e.jsx("a",{href:"https://github.com/jerhadf/headroom",target:"_blank",rel:"noreferrer",className:"text-xs font-normal text-primary underline hover:opacity-80",children:"(Headroom)"})]}),e.jsx("p",{className:"text-sm text-text-muted",children:"External proxy compresses input messages → fewer prompt tokens"})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[Le&&e.jsxs("div",{className:"flex flex-col items-end gap-2 min-w-[200px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{value:_e,onChange:t=>os(t.target.value),placeholder:"http://localhost:8787",className:"text-xs"}),!ke&&Et&&e.jsx("button",{onClick:ds,disabled:oe,className:"px-2 py-1.5 rounded text-xs font-medium bg-primary text-white hover:opacity-80 disabled:opacity-50",children:oe?"...":"Start"}),ke&&Ps&&e.jsx("button",{onClick:ms,disabled:oe,className:"px-2 py-1.5 rounded text-xs font-medium bg-red-500 text-white hover:opacity-80 disabled:opacity-50",children:oe?"...":"Stop"})]}),e.jsx("p",{className:`text-xs ${ke?"text-green-500":Et?"text-yellow-500":"text-red-500"}`,children:Ls}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-muted cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:Dt,onChange:t=>cs(t.target.checked),className:"rounded"}),"Compress user messages"]})]}),e.jsx(L,{checked:Le,onChange:()=>is(!Le)})]})]})]}),e.jsxs(Ze,{id:"require-api-key",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"vpn_key"}),"API Keys"]}),e.jsx(c,{icon:"add",onClick:()=>C(!0),children:"Create Key"})]}),e.jsxs("div",{className:"flex items-center justify-between pb-4 mb-4 border-b border-border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Require API key"}),e.jsx("p",{className:"text-sm text-text-muted",children:"Requests without a valid key will be rejected"})]}),e.jsx(L,{checked:re,onChange:()=>as(!re)})]}),Yt&&!re&&e.jsx("div",{className:"mb-4 -mt-2",children:e.jsx(Ce,{message:"Endpoint is exposed without an API key."})}),d.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4",children:e.jsx("span",{className:"material-symbols-outlined text-[32px]",children:"vpn_key"})}),e.jsx("p",{className:"text-text-main font-medium mb-1",children:"No API keys yet"}),e.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Create your first API key to get started"}),e.jsx(c,{icon:"add",onClick:()=>C(!0),children:"Create Key"})]}):e.jsx("div",{className:"flex flex-col",children:d.map(t=>e.jsxs("div",{className:`group flex items-center justify-between py-3 border-b border-black/[0.03] dark:border-white/[0.03] last:border-b-0 ${t.isActive===!1?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("code",{className:"text-xs text-text-muted font-mono",children:Ge.has(t.id)?t.key:vs(t.key)}),e.jsx("button",{onClick:()=>Cs(t.id),className:"p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",title:Ge.has(t.id)?"Hide key":"Show key",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:Ge.has(t.id)?"visibility_off":"visibility"})}),e.jsx("button",{onClick:()=>se(t.key,t.id),className:"p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:z===t.id?"check":"content_copy"})})]}),e.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["Created ",new Date(t.createdAt).toLocaleDateString()]}),t.isActive===!1&&e.jsx("p",{className:"text-xs text-orange-500 mt-1",children:"Paused"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(L,{size:"sm",checked:t.isActive??!0,onChange:s=>{t.isActive&&!s?J({title:"Pause API Key",message:`Pause API key "${t.name}"?
5
-
6
- This key will stop working immediately but can be resumed later.`,onConfirm:async()=>{J(null),St(t.id,s)}}):St(t.id,s)},title:t.isActive?"Pause key":"Resume key"}),e.jsx("button",{onClick:()=>ks(t.id),className:"p-2 hover:bg-red-500/10 rounded text-red-500 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"delete"})})]})]},t.id))})]}),e.jsx(B,{isOpen:g,title:"Create API Key",onClose:()=>{C(!1),le("")},children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(G,{label:"Key Name",value:ne,onChange:t=>le(t.target.value),placeholder:"Production Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:Ns,fullWidth:!0,disabled:!ne.trim(),children:"Create"}),e.jsx(c,{onClick:()=>{C(!1),le("")},variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}),e.jsx(B,{isOpen:!!Te,title:"API Key Created",onClose:()=>Se(null),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-yellow-800 dark:text-yellow-200 mb-2 font-medium",children:"Save this key now!"}),e.jsx("p",{className:"text-sm text-yellow-700 dark:text-yellow-300",children:"This is the only time you will see this key. Store it securely."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{value:Te||"",readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx(c,{variant:"secondary",icon:z==="created_key"?"check":"content_copy",onClick:()=>se(Te,"created_key"),children:z==="created_key"?"Copied!":"Copy"})]}),e.jsx(c,{onClick:()=>Se(null),fullWidth:!0,children:"Done"})]})}),e.jsx(B,{isOpen:Ft,title:"Enable Tunnel",onClose:()=>Y(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"bg-surface-2 border border-border-subtle rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"cloud_upload"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-text-main font-medium mb-1",children:"Cloudflare Tunnel"}),e.jsx("p",{className:"text-sm text-text-muted",children:"Expose your local FSRouter to the internet. No port forwarding, no static IP needed. Share endpoint URL with your team or use it in Cursor, Cline, and other AI tools from anywhere."})]})]})}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Os.map(t=>e.jsxs("div",{className:"flex flex-col items-center text-center p-3 rounded-lg bg-sidebar/50",children:[e.jsx("span",{className:"material-symbols-outlined text-xl text-primary mb-1",children:t.icon}),e.jsx("p",{className:"text-xs font-semibold",children:t.title}),e.jsx("p",{className:"text-xs text-text-muted",children:t.desc})]},t.title))}),e.jsx("p",{className:"text-xs text-text-muted",children:"Requires outbound port 7844 (TCP/UDP). Connection may take 10-30s."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:bs,fullWidth:!0,children:"Start Tunnel"}),e.jsx(c,{onClick:()=>Y(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}),e.jsx(B,{isOpen:Kt,title:"Disable Tunnel",onClose:()=>!_&&X(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"The Cloudflare tunnel will be disconnected. Remote access via tunnel URL will stop working."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:gs,fullWidth:!0,disabled:_,variant:"danger",children:_?"Disabling...":"Disable"}),e.jsx(c,{onClick:()=>X(!1),variant:"ghost",fullWidth:!0,disabled:_,children:"Cancel"})]})]})}),e.jsx(B,{isOpen:Bt,title:"Tailscale Funnel",onClose:()=>{fe||($(!1),jt(""),m(null))},children:e.jsxs("div",{className:"flex flex-col gap-4",children:[Fe===null&&e.jsxs("p",{className:"text-sm text-text-muted flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Checking..."]}),Fe===!1&&!fe&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"Tailscale is not installed. Install it to enable Funnel."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:js,fullWidth:!0,children:"Install Tailscale"}),e.jsx(c,{onClick:()=>$(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]}),fe&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Installing Tailscale..."]}),We.length>0&&e.jsx("div",{ref:be,className:"bg-black/5 dark:bg-white/5 rounded p-2 max-h-40 overflow-y-auto font-mono text-xs text-text-muted",children:We.map((t,s)=>e.jsx("div",{children:t},s))})]}),Fe===!0&&!fe&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"check_circle"}),"Tailscale installed"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:()=>Ye(),fullWidth:!0,children:"Connect"}),e.jsx(c,{onClick:()=>$(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]}),q&&e.jsx($s,{status:q})]})}),e.jsx(B,{isOpen:Gt,title:"Disable Tailscale",onClose:()=>!U&&Z(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"Tailscale Funnel will be stopped. Remote access via Tailscale URL will stop working."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:ws,fullWidth:!0,disabled:U,variant:"danger",children:U?"Disabling...":"Disable"}),e.jsx(c,{onClick:()=>Z(!1),variant:"ghost",fullWidth:!0,disabled:U,children:"Cancel"})]})]})}),e.jsx(Rs,{isOpen:!!w,onClose:()=>J(null),onConfirm:w==null?void 0:w.onConfirm,title:(w==null?void 0:w.title)||"Confirm",message:w==null?void 0:w.message,variant:"danger"})]})}function qs({label:h,url:d,copyId:x,copied:j,onCopy:R,badge:g,actions:C}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${g==="CF"||g==="TS"?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:h}),e.jsx(G,{value:d,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>R(d,x),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:j===x?"check":"content_copy"})}),C]})}function $s({status:h,className:d=""}){const x=j=>j.split(/(https?:\/\/[^\s]+)/g).map((g,C)=>/^https?:\/\//.test(g)?e.jsx("a",{href:g,target:"_blank",rel:"noreferrer",className:"underline font-medium",children:g},C):g);return e.jsx("div",{className:`p-2 rounded text-sm ${d} ${h.type==="success"?"bg-green-500/10 text-green-600 dark:text-green-400":h.type==="warning"?"bg-yellow-500/10 text-yellow-600 dark:text-yellow-400":h.type==="info"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-red-500/10 text-red-600 dark:text-red-400"}`,children:x(h.message)})}function zs({text:h}){return e.jsxs("span",{className:"relative group inline-flex items-center",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px] text-text-muted cursor-help",children:"help"}),e.jsx("span",{className:"pointer-events-none absolute left-5 top-1/2 -translate-y-1/2 z-50 w-64 rounded bg-gray-900 dark:bg-gray-800 text-white text-xs px-2.5 py-1.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-lg",children:h})]})}function Ce({message:h,action:d}){return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-700 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] shrink-0 mt-0.5",children:"warning"}),e.jsx("p",{className:"text-xs flex-1",children:h}),d&&e.jsx("a",{href:d.href,className:"text-xs font-medium underline shrink-0 hover:opacity-80",onClick:d.href.startsWith("#")?x=>{var j;x.preventDefault(),(j=document.getElementById(d.href.slice(1)))==null||j.scrollIntoView({behavior:"smooth"})}:void 0,children:d.label})]})}Ws.propTypes={machineId:Is.string.isRequired};export{Ws as A};