limixbot 0.3.149 → 0.3.151

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 (166) hide show
  1. package/dist/assets/{ActivityPanel-BtjpbSCG.js → ActivityPanel-CF1_YqWK.js} +1 -1
  2. package/dist/assets/{App-26INIo6C.js → App-C105qZ2Q.js} +112 -112
  3. package/dist/assets/{AppEventEditor-DtY2Zgk3.js → AppEventEditor-Baqu8KL7.js} +1 -1
  4. package/dist/assets/{BotSettingsDialog-CIAkenzY.js → BotSettingsDialog-7Mp_GgGa.js} +4 -4
  5. package/dist/assets/{BrowserPanel-CKCdXmHX.js → BrowserPanel-CEokTHdk.js} +2 -2
  6. package/dist/assets/{BrowserProfilesManager-CY3fpWTL.js → BrowserProfilesManager-D5p3tzU_.js} +1 -1
  7. package/dist/assets/CloudAddDialog-bQrip-Jy.js +1 -0
  8. package/dist/assets/{ComputerFilesPane-BU-s7BlY.js → ComputerFilesPane-BCu5Rj8d.js} +1 -1
  9. package/dist/assets/ComputerPanel-CczHIs03.js +2 -0
  10. package/dist/assets/{DataPanel-VJJAqxxu.js → DataPanel-Bk3L3TrE.js} +1 -1
  11. package/dist/assets/{DesktopViewer-uyCSG2he.js → DesktopViewer-DzTcedLr.js} +1 -1
  12. package/dist/assets/{GrokMoveDialog-w4WKHjBN.js → GrokMoveDialog-CnQiC3hB.js} +1 -1
  13. package/dist/assets/{InspectorPanel-KeN8Krv4.js → InspectorPanel-DUSlsD3M.js} +1 -1
  14. package/dist/assets/{KeyboardShortcutsModal-B0axO0UW.js → KeyboardShortcutsModal-DnpyGtD2.js} +1 -1
  15. package/dist/assets/{KnowledgePanel-DahTsWA8.js → KnowledgePanel-BY5Mps13.js} +1 -1
  16. package/dist/assets/LimixResizeHandles-C29m-_Io.js +1 -0
  17. package/dist/assets/{LiveDesktop-6_ms70VN.js → LiveDesktop-hGL5Vc_Z.js} +1 -1
  18. package/dist/assets/{LocalVmWorkspace-Ck4LV7UQ.js → LocalVmWorkspace-B_kTCMkz.js} +1 -1
  19. package/dist/assets/{MacLocalControl-C-9MRdET.js → MacLocalControl-DNO_TehG.js} +1 -1
  20. package/dist/assets/{MarkdownFilePreview-DYzQsZt1.js → MarkdownFilePreview-CL7juyHq.js} +1 -1
  21. package/dist/assets/{MenuMotion-B0aZnuh_.js → MenuMotion-CkN_cwFK.js} +1 -1
  22. package/dist/assets/{NewBotDialog-Bx1yEPRI.js → NewBotDialog-CbkCu3Tq.js} +1 -1
  23. package/dist/assets/PhoneAppDialog-BFCCrIuS.js +1 -0
  24. package/dist/assets/PlacesRail-CiDy67dg.js +1 -0
  25. package/dist/assets/{PluginsPanel-DV_bvv9b.js → PluginsPanel-DnV0nnd0.js} +5 -5
  26. package/dist/assets/{ProIntroduction-Mbg0N0IP.js → ProIntroduction-BqrTHZHe.js} +1 -1
  27. package/dist/assets/{RemoteAgentSettingsPanel-CAyTUKX7.js → RemoteAgentSettingsPanel-CeUWRt9h.js} +1 -1
  28. package/dist/assets/{RoomPanel-CnZn0T2L.js → RoomPanel-C9ujF99f.js} +1 -1
  29. package/dist/assets/{RoutinesPage-X1fycmDS.js → RoutinesPage-CLqcYU0g.js} +3 -3
  30. package/dist/assets/SettingsModal-9llKQ2Mj.js +20 -0
  31. package/dist/assets/{ShareTeamDialog-BTYzF7-V.js → ShareTeamDialog-qYnUdjLc.js} +1 -1
  32. package/dist/assets/{SignedInSites-BJlXZ7-O.js → SignedInSites-zx_Bqomx.js} +1 -1
  33. package/dist/assets/{TeamLibraryPanel-ZYJ8Q0ap.js → TeamLibraryPanel-DJzG9O6f.js} +2 -2
  34. package/dist/assets/TeamMapPage-B6o-uzsU.js +1 -0
  35. package/dist/assets/{TriggersPage-RuEkgSPb.js → TriggersPage-xi-wECUl.js} +1 -1
  36. package/dist/assets/VisibilitySection-Bzsk343C.js +22 -0
  37. package/dist/assets/{WebhookTrigger-C6Y8whIS.js → WebhookTrigger-B3Zjfv6_.js} +1 -1
  38. package/dist/assets/WorksOnGrid-e75OUZ5l.js +1 -0
  39. package/dist/assets/{abnfDiagram-YUKMZFIV-DDXPrZzl.js → abnfDiagram-YUKMZFIV-DmMlye8h.js} +1 -1
  40. package/dist/assets/{activity-BlL5ycb5.js → activity-BwL7R1oZ.js} +1 -1
  41. package/dist/assets/{architectureDiagram-47P4ROYG-BiqBgMDV.js → architectureDiagram-47P4ROYG-CsJT_rlj.js} +1 -1
  42. package/dist/assets/{blockDiagram-E7TT5TSB-vc1neoFp.js → blockDiagram-E7TT5TSB-DQZPKSCM.js} +1 -1
  43. package/dist/assets/{c4Diagram-CRA5TL53-CQbtBKOv.js → c4Diagram-CRA5TL53-CFwJMSZU.js} +1 -1
  44. package/dist/assets/{calendar-days-_dtxyR4U.js → calendar-days-B6JEXMKZ.js} +1 -1
  45. package/dist/assets/channel--G0H2dDa.js +1 -0
  46. package/dist/assets/{chunk-2Q5K7J3B-Dq_aCCIt.js → chunk-2Q5K7J3B-5GjI6Cta.js} +1 -1
  47. package/dist/assets/{chunk-5VM5RSS4-EcX_ZXzF.js → chunk-5VM5RSS4-DYH4c-ax.js} +1 -1
  48. package/dist/assets/{chunk-7TKQ45FW-BA7CgKU2.js → chunk-7TKQ45FW-BmQUAA8g.js} +1 -1
  49. package/dist/assets/{chunk-AW2ZBBNX-DkvVwaph.js → chunk-AW2ZBBNX-DaPEyZZ8.js} +1 -1
  50. package/dist/assets/{chunk-FVRAUYC3-CdyGRg6v.js → chunk-FVRAUYC3-B2zv-RDx.js} +2 -2
  51. package/dist/assets/{chunk-HTAEGDNF-CS-veEVV.js → chunk-HTAEGDNF-BBigAiMr.js} +1 -1
  52. package/dist/assets/{chunk-JWPE2WC7-BiUYpinX.js → chunk-JWPE2WC7-nGpkrDer.js} +1 -1
  53. package/dist/assets/{chunk-KQW6MTUR-DDPkIuwB.js → chunk-KQW6MTUR-RtfxoMR0.js} +1 -1
  54. package/dist/assets/{chunk-XXDRQBXY-C4YyKEem.js → chunk-XXDRQBXY-D0Z9X15P.js} +1 -1
  55. package/dist/assets/{classDiagram-v2-K4WV4PDN-BjmVbVHi.js → classDiagram-v2-K4WV4PDN-DjLi8cTy.js} +1 -1
  56. package/dist/assets/{coins-Cu3qn-3t.js → coins-DU5eeEgg.js} +1 -1
  57. package/dist/assets/{core-ClKcQma9.js → core-Dkz8aucx.js} +1 -1
  58. package/dist/assets/{cose-bilkent-JH36ORCC-Bra0B-5z.js → cose-bilkent-JH36ORCC-BV5TslYh.js} +1 -1
  59. package/dist/assets/{cynefin-EF2NZ3EQ-BRMKNbnx.js → cynefin-EF2NZ3EQ-Xj-A7F3v.js} +1 -1
  60. package/dist/assets/{cynefinDiagram-3GCD6N5R-DMhNix9A.js → cynefinDiagram-3GCD6N5R-DwA9mpkS.js} +1 -1
  61. package/dist/assets/{dagre-W4DXFKR2-BWwdFKCx.js → dagre-W4DXFKR2-CJyrR1La.js} +1 -1
  62. package/dist/assets/{diagram-2UJZ2QOL-D_4J-D-V.js → diagram-2UJZ2QOL-D5e65aZj.js} +1 -1
  63. package/dist/assets/{diagram-OVF4WLC6-CQ4l30Dm.js → diagram-OVF4WLC6-BqZTYg6g.js} +1 -1
  64. package/dist/assets/{diagram-PFPMY2P6-D3W2IEHX.js → diagram-PFPMY2P6-DrjnFbqK.js} +1 -1
  65. package/dist/assets/{diagram-UMYRVEAY-C9cpNhET.js → diagram-UMYRVEAY-BaV0xK5l.js} +1 -1
  66. package/dist/assets/{diagram-YEKJPTXX-DIyquCXt.js → diagram-YEKJPTXX-DQgBrrT_.js} +1 -1
  67. package/dist/assets/{diagram-ZIFT7M5P-CO6216kK.js → diagram-ZIFT7M5P-BkV-KgMI.js} +1 -1
  68. package/dist/assets/{ebnfDiagram-VR2GEFS7-BeHXJPN4.js → ebnfDiagram-VR2GEFS7-IpsTZnQN.js} +1 -1
  69. package/dist/assets/{elk-IJKZMXRS-BdT_tK3j.js → elk-IJKZMXRS-DDQNuM9u.js} +1 -1
  70. package/dist/assets/{erDiagram-O2IAPWRE-Cz_TiHab.js → erDiagram-O2IAPWRE-D9TBYgl3.js} +1 -1
  71. package/dist/assets/{file-up-flw1aUka.js → file-up-ws1KLV4X.js} +1 -1
  72. package/dist/assets/{flowDiagram-OXPTDLAJ-BXLr0anm.js → flowDiagram-OXPTDLAJ-DbpnsdSz.js} +1 -1
  73. package/dist/assets/{ganttDiagram-R7TSEDQI-C37QIpaR.js → ganttDiagram-R7TSEDQI-CuOV8r9U.js} +1 -1
  74. package/dist/assets/{gitGraphDiagram-XJZIOB7I-Cs8fTfJZ.js → gitGraphDiagram-XJZIOB7I--DnV2JAf.js} +1 -1
  75. package/dist/assets/{import-name-Cw10r2vZ.js → import-name-C9VPs36v.js} +1 -1
  76. package/dist/assets/{index-CJ2k9T6W.js → index-BEFKyXpE.js} +1 -1
  77. package/dist/assets/{index-C7YXnZFx.js → index-D-YzdU6W.js} +3 -3
  78. package/dist/assets/{infoDiagram-5W2HQ5XZ-BpliNVPR.js → infoDiagram-5W2HQ5XZ-DFH8qIB_.js} +1 -1
  79. package/dist/assets/{ishikawaDiagram-K3B6WC7H-Dov7w4qz.js → ishikawaDiagram-K3B6WC7H-CWVJRxcE.js} +1 -1
  80. package/dist/assets/{journeyDiagram-COXZFDF6-DoihiGaK.js → journeyDiagram-COXZFDF6-CF5SHpVJ.js} +1 -1
  81. package/dist/assets/{kanban-definition-P3RFRI5V-D_gNx8dG.js → kanban-definition-P3RFRI5V-Dqcr-efW.js} +1 -1
  82. package/dist/assets/{mermaid.core-BYPxVPn-.js → mermaid.core-DyBxnq9f.js} +4 -4
  83. package/dist/assets/{mindmap-definition-LZFPQGKD-wH2aKxFy.js → mindmap-definition-LZFPQGKD-DUHqiBBP.js} +1 -1
  84. package/dist/assets/{minimize-sGQL0Xsy.js → minimize-Gt19QuOt.js} +1 -1
  85. package/dist/assets/{monitor-zecPzfR5.js → monitor-8xvlipPX.js} +1 -1
  86. package/dist/assets/{new-bot-CBPOqYyC.js → new-bot-D_AMnybb.js} +2 -2
  87. package/dist/assets/org-library-SbjlI2xi.js +1 -0
  88. package/dist/assets/{package-format-ClUc1sA7.js → package-format-B1_4B6uw.js} +1 -1
  89. package/dist/assets/{pegDiagram-BGZESJAR-B7RTZksQ.js → pegDiagram-BGZESJAR-B0ZD60O8.js} +1 -1
  90. package/dist/assets/{pieDiagram-CAPJLFHJ-B5mPB7O-.js → pieDiagram-CAPJLFHJ-D85g95l8.js} +1 -1
  91. package/dist/assets/{pt-br-D-uO3BNY.js → pt-br-DW318t9V.js} +1 -1
  92. package/dist/assets/{quadrantDiagram-GDMTTRAM-CZqo7j7U.js → quadrantDiagram-GDMTTRAM-BJSfbIDU.js} +1 -1
  93. package/dist/assets/{rail-Ok0cs7cA.js → rail-BGOSUsWI.js} +1 -1
  94. package/dist/assets/{railroadDiagram-SM67HX2B-MFpfIts_.js → railroadDiagram-SM67HX2B-COsfytW7.js} +1 -1
  95. package/dist/assets/{remote-desktop-panel-D3PotAlF.js → remote-desktop-panel-DIQTDq-1.js} +1 -1
  96. package/dist/assets/{requirementDiagram-X7JNWC4A-CJ49gC_q.js → requirementDiagram-X7JNWC4A-Cvm3p_V4.js} +1 -1
  97. package/dist/assets/{sankeyDiagram-UM26HJRW-DxpTSw3D.js → sankeyDiagram-UM26HJRW-B2qdUsyi.js} +1 -1
  98. package/dist/assets/{sequenceDiagram-ZO4K6R2Y-XEyCx2Ue.js → sequenceDiagram-ZO4K6R2Y-DuHG0mPh.js} +1 -1
  99. package/dist/assets/{sizeCapture-INFHLROL-1Fx1tcNn.js → sizeCapture-INFHLROL-DIQvdFqx.js} +1 -1
  100. package/dist/assets/{stateDiagram-v2-TBUQTH76-CwxyNDK4.js → stateDiagram-v2-TBUQTH76-Bn18bSq5.js} +1 -1
  101. package/dist/assets/{styles-DO3EUxm2.js → styles-dQeXpYRh.js} +7 -7
  102. package/dist/assets/{swimlanes-N4OXWK64-BuwwuENy.js → swimlanes-N4OXWK64-BTBQ3Ghn.js} +1 -1
  103. package/dist/assets/swimlanesDiagram-K3J5GTZL-DJ2h-u90.js +8 -0
  104. package/dist/assets/{team-share-CL18_anr.js → team-share-C_9b-rWK.js} +1 -1
  105. package/dist/assets/{timeline-definition-YOQAKGHF-CauwqKMA.js → timeline-definition-YOQAKGHF-yrVM6nx1.js} +1 -1
  106. package/dist/assets/{usecaseDiagram-VIAY4XPW-YZ3Cf2do.js → usecaseDiagram-VIAY4XPW-D7zK8Lsl.js} +1 -1
  107. package/dist/assets/{vennDiagram-BLWOH2XV-CDX8i7ID.js → vennDiagram-BLWOH2XV-DXEv5byx.js} +1 -1
  108. package/dist/assets/{wardleyDiagram-YMQ3BMBF-CCdRrEMh.js → wardleyDiagram-YMQ3BMBF-pMqwXr4k.js} +1 -1
  109. package/dist/assets/{xychartDiagram-TAQBALBS-Vz4NaN0U.js → xychartDiagram-TAQBALBS-DX7g4R5N.js} +1 -1
  110. package/dist/index.html +2 -2
  111. package/dist/rail.html +4 -4
  112. package/dist-server/drivers/agents-proxy.js +6 -6
  113. package/dist-server/drivers/pi-mcp-extension.ts +3 -3
  114. package/dist-server/index.js +158 -154
  115. package/dist-server/limixbot.js +117 -116
  116. package/dist-server/package.json +1 -1
  117. package/dist-server/pair-cli.js +117 -116
  118. package/dist-server/server/app-settings/host.js +1 -1
  119. package/dist-server/server/app-settings/registry-config.js +1 -1
  120. package/dist-server/server/app-settings/registry-window.js +4 -4
  121. package/dist-server/server/app-settings/registry.js +3 -3
  122. package/dist-server/server/checkpoints.js +3 -2
  123. package/dist-server/server/cli-setup.js +1 -1
  124. package/dist-server/server/cloud-health.js +1 -1
  125. package/dist-server/server/drivers/agents-app-settings-tool.js +1 -1
  126. package/dist-server/server/drivers/agents-catalog.js +1 -1
  127. package/dist-server/server/drivers/codex-shared-home.js +1 -1
  128. package/dist-server/server/drivers/codex.js +23 -9
  129. package/dist-server/server/environment.js +1 -1
  130. package/dist-server/server/first-reply-rescue.js +10 -3
  131. package/dist-server/server/fleet-cli.js +2 -2
  132. package/dist-server/server/fleet-client.js +2 -2
  133. package/dist-server/server/headless/client.js +2 -2
  134. package/dist-server/server/headless/commands.js +8 -8
  135. package/dist-server/server/headless/connect.js +1 -1
  136. package/dist-server/server/headless/context.js +4 -4
  137. package/dist-server/server/headless/engine.js +1 -1
  138. package/dist-server/server/headless/export.js +1 -1
  139. package/dist-server/server/headless/run.js +3 -3
  140. package/dist-server/server/headless/team-apply.js +4 -4
  141. package/dist-server/server/headless/token.js +6 -6
  142. package/dist-server/server/index.js +1 -1
  143. package/dist-server/server/lent-computers.js +2 -2
  144. package/dist-server/server/login-handoff.js +1 -1
  145. package/dist-server/server/phone-link.js +1 -1
  146. package/dist-server/server/phone-relay.js +1 -1
  147. package/dist-server/server/routes/config.js +14 -0
  148. package/dist-server/server/routes/status.js +1 -1
  149. package/dist-server/server/routes/x-research.js +1 -1
  150. package/dist-server/server/sentinel/cli.js +6 -6
  151. package/dist-server/server/themes/routes.js +1 -1
  152. package/dist-server/server/thread-events.js +2 -0
  153. package/dist-server/shared/theme.js +1 -1
  154. package/package.json +1 -1
  155. package/dist/assets/CloudAddDialog-kWU09Ad1.js +0 -1
  156. package/dist/assets/ComputerPanel-BIFlIGlF.js +0 -2
  157. package/dist/assets/LimixResizeHandles-D850ftBI.js +0 -1
  158. package/dist/assets/PhoneAppDialog-fCMJgYOZ.js +0 -1
  159. package/dist/assets/PlacesRail-tZyNm-l3.js +0 -1
  160. package/dist/assets/SettingsModal-D6mYhjwS.js +0 -20
  161. package/dist/assets/TeamMapPage-D7x-_Igr.js +0 -1
  162. package/dist/assets/VisibilitySection-CHIMRzr1.js +0 -22
  163. package/dist/assets/WorksOnGrid-Ho88FaNW.js +0 -1
  164. package/dist/assets/channel-BzyEyDo_.js +0 -1
  165. package/dist/assets/org-library-DIJ4T2-a.js +0 -1
  166. package/dist/assets/swimlanesDiagram-K3J5GTZL-CcmXEgRh.js +0 -8
@@ -0,0 +1,20 @@
1
+ import{c as ut,j as e,t,r as l,a as z,S as mt,d as be,p as Ns,l as R,k as Rt,X as $e,i as ws,C as Fr,af as Sa,L as St,aP as Dr,a_ as _r,a9 as $r,T as Kr,m as Me,a$ as Hr,b0 as Wr,ac as Gr,b1 as qr,b2 as Lt,ay as Zs,z as Vr,av as Jr,A as en,az as Ca,b as Xr,b3 as Yr,D as Qr,b4 as Zr,B as el,aE as tl,b5 as tn,aD as sl,b6 as nl,b7 as sn,b8 as nn,b9 as an,ba as al,bb as il,ai as rl,bc as ll}from"./styles-dQeXpYRh.js";import{L as ol}from"./LimixResizeHandles-C29m-_Io.js";import{L as J,P as we,v as pt,E as cl,ah as dl,ai as ul,$ as ml,W as pl,l as Ss,C as Ea,B as Bt,aj as xl,ak as gl,al as hl,d as Aa,r as fl,h as rn,g as ln,i as bl,am as yl,an as vl,ao as jl,ap as Wt,A as kl,p as Nl,aq as wl,ar as Ia,as as Sl,R as Pa,c as Cl,at as El,au as Al,M as Il,ab as Pl,av as Tl,aw as ls,b as Rl,t as Ll,U as Bl,N as Gt,f as Ol}from"./PlacesRail-CiDy67dg.js";import{b_ as Ot,u as G,S as me,j as M,hl as Be,T as Se,dD as Qe,w as ge,cX as Ml,cT as Ta,eU as Ze,hm as zl,X as Oe,eS as Ul,eT as Fl,hn as os,ho as lt,hp as Ra,hq as Cs,hr as Es,hs as Dl,eb as on,ht as La,hu as Ba,hv as _l,hw as $l,hx as Kl,a1 as de,c9 as Y,ej as cs,eR as Hl,hy as Oa,hz as Nt,hA as Mt,hB as Ma,hC as za,hD as Le,hE as _e,hF as Wl,hG as Gl,hH as ql,hI as Vl,hJ as Jl,hK as Ua,hL as Xl,hM as Yl,hN as Fa,hO as Da,hP as ye,hQ as ve,dz as cn,hR as zt,hS as Ql,hT as Zl,hU as eo,hV as to,hW as so,he as _a,bt as no,hX as rt,R as ao,dS as io,hY as ro,hZ as dn,aP as Ct,fL as ot,fM as ct,h_ as lo,J as Ye,r as oo,cw as co,h3 as uo,h$ as Ut,i0 as $a,i1 as mo,i2 as po,i3 as un,i4 as Ka,i5 as Ft,i6 as Ha,i7 as xo,i8 as go,i9 as ho,ia as fo,G as bo,ib as yo,ic as dt,ep as Dt,id as vo,ie as jo,ig as ko,ih as No,fT as wo,ii as mn,ij as So,ik as Co,D as Eo,il as pn,im as Ao,en as Wa,io as Io,ip as Po,iq as To,ir as Ro,is as Lo,it as Bo,iu as Ga,iv as Oo,iw as Mo,ix as zo,iy as Uo,iz as Fo,iA as Do,iB as qa,iC as _o,iD as $o,dY as Ko,iE as Ho,ek as Wo,iF as Go,iG as qo,iH as Vo,iI as Jo,iJ as Xo,iK as Yo,iL as xn,iM as Qo,iN as Zo,iO as gn,l as ec,iP as tc,iQ as sc,iR as nc,bQ as ac,iS as ic,iT as rc,iU as lc,iV as oc,iW as Va,fJ as nt,iX as cc,fI as dc,iY as Ja,iZ as uc,i_ as Xa,i$ as mc,j0 as hn,i as pc,j1 as ds,j2 as fn,j3 as bn,j4 as xc,j5 as gc,j6 as hc,j7 as fc,j8 as bc,j9 as yc,ja as vc,jb as jc,jc as kc,jd as As,je as Nc,fv as Ya,h as wc,jf as Sc,jg as Cc,jh as yn,ji as Ec,jj as Ac,jk as vn,jl as Ic,b8 as Pc,jm as Tc,jn as Rc,jo as Lc,bI as Bc,jp as Oc,jq as jn,jr as Mc,bD as Is,js as zc,bE as Uc,jt as Fc,ju as Dc,jv as _c,jw as $c,jx as Kc,jy as Hc,jz as Wc,jA as Gc,jB as kn,gP as qc,jC as Vc,jD as Jc,jE as Qa,jF as Xc,jG as Yc,jH as Qc,jI as Za,jJ as ei,jK as ti,jL as Zc,jM as ed,jN as td,dg as sd,I as nd,jO as si,eM as ad,c7 as Nn,jP as id,jQ as wn,fd as Sn,ea as rd,Z as ld,ay as od,jR as cd,jS as dd,jT as ud}from"./App-C105qZ2Q.js";import{C as Ps,a as md,R as Ae}from"./MenuMotion-CkN_cwFK.js";import{l as ni,M as pd,w as Cn}from"./MacLocalControl-DNO_TehG.js";import{Q as ai}from"./VisibilitySection-Bzsk343C.js";import{a as xd,r as gd,C as hd,s as ii,b as fd,c as bd,w as yd,t as vd,T as jd,l as Ts,d as En,e as kd,f as Nd}from"./index-D-YzdU6W.js";import{c as wd,A as Sd,w as Cd,d as Ed,e as An}from"./activity-BwL7R1oZ.js";import{U as ri,R as li,B as oi,S as ci,a as di,D as ui,T as mi,C as pi,L as us,b as xi,c as gi,F as hi,A as ms,E as Ad,d as Id,P as Pd,e as Td,f as Rd,N as Ld}from"./NewBotDialog-CbkCu3Tq.js";import{a as Bd,u as fi,C as bi,b as Od,P as Md}from"./ProIntroduction-BqrTHZHe.js";import{M as yi}from"./monitor-8xvlipPX.js";import{C as zd}from"./coins-DU5eeEgg.js";import"./org-library-SbjlI2xi.js";import"./package-format-B1_4B6uw.js";import"./WorksOnGrid-e75OUZ5l.js";import"./new-bot-D_AMnybb.js";import"./RoutinesPage-CLqcYU0g.js";import"./remote-desktop-DDRRx8uY.js";import"./team-share-C_9b-rWK.js";import"./BrowserProfilesManager-D5p3tzU_.js";import"./SignedInSites-zx_Bqomx.js";const Ud=[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]],Fd=ut("cloud-download",Ud);const Dd=[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]],_d=ut("palette",Dd);const $d=[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]],Kd=ut("scroll-text",$d);const Hd=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Wd=ut("terminal",Hd);const Gd=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],qd=ut("unplug",Gd);function Rs(s){return s.filter(n=>n.driverKind==="openai-compat"&&n.instanceId.startsWith("openai-compat-"))}function je({children:s,note:n="settings.adminOnly.change"}){return Ot()===!1?e.jsx("p",{"data-admin-only":!0,className:"text-[13px] text-ink-secondary",children:t(n)}):s}function Ls(s,n,a="start",i=0){const r=n.getBoundingClientRect().top-s.getBoundingClientRect().top+s.scrollTop;s.scrollTop=Math.max(0,a==="center"?r-(s.clientHeight-(n.offsetHeight??0))/2:r-i)}function Vd(s){for(let n=s.parentElement;n;n=n.parentElement){const a=getComputedStyle(n).overflowY;if((a==="auto"||a==="scroll")&&n.scrollHeight>n.clientHeight)return n}return null}function Jd(){const{state:s,dispatch:n}=G(),[a,i]=l.useState(!1),[r,c]=l.useState(null),o=s.config?.tts?.everyReply===!0,d=()=>{i(!0),c(null),M("/api/config",{method:"PUT",body:JSON.stringify({tts:{everyReply:!o}})}).then(m=>n({type:"configStatus",config:m})).catch(m=>c(m.message)).finally(()=>i(!1))};return e.jsxs("div",{"data-voice-every-reply":!0,className:"flex items-center justify-between gap-4 px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-medium leading-5 text-ink",children:t("voice.everyReply")}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-4 text-ink-secondary",children:t("voice.everyReply.allHelp")}),r&&e.jsx("div",{role:"alert",className:"mt-1 text-[12px] text-danger",children:r})]}),e.jsx(me,{checked:o,disabled:a,"aria-label":t("voice.everyReply"),onClick:d})]})}const Xd="https://api.xingchiapi.com/v1",Yd={claude:{url:"https://api.anthropic.com",model:"deepseek-chat"},codex:{url:"https://api.openai.com/v1",model:""}},ft=z(Be,"font-sans"),In={name:"",url:"",token:"",model:""},Qd=s=>({name:s.displayName,url:(s.claudeEndpoint??s.codexEndpoint)?.baseUrl??"",token:"",model:(s.claudeEndpoint??s.codexEndpoint)?.model??""});function Bs({instance:s,engine:n,onDone:a,xingchi:i=!1}){const{dispatch:r}=G(),c=Yd[n],[o,d]=l.useState(s?Qd(s):i?{...In,name:"Xingchi (Codex Responses)",url:Xd}:In),[m,u]=l.useState(!1),[x,p]=l.useState(null),g=b=>({value:o[b],onChange:h=>d(k=>({...k,[b]:h.target.value})),spellCheck:!1,disabled:m}),f=!!(o.name.trim()&&(o.url.trim()||n==="codex")&&(s||o.token.trim())),y=async()=>{if(m||!f)return;u(!0),p(null);const b={displayName:o.name.trim(),...i&&!s?{profile:"xingchi"}:{},baseUrl:o.url.trim()||c.url,...o.token.trim()?{token:o.token.trim()}:{},...o.model.trim()?{model:o.model.trim()}:{}};try{const h=s?await M(`/api/instances/${encodeURIComponent(s.instanceId)}/${n}-endpoint`,{method:"PATCH",body:JSON.stringify(b)}):await M(`/api/instances/${n}-endpoint`,{method:"POST",body:JSON.stringify(b)});Array.isArray(h.instances)&&r({type:"instances",instances:h.instances}),a()}catch(h){const k=h instanceof Error?h.message:"";p(k.includes("HTTP 403, client_not_allowed")?t("agentEndpoints.modelListClientDenied"):k||t("claudeEndpoints.failed"))}finally{u(!1)}};return e.jsxs("form",{"data-claude-endpoint-form":n==="claude"?s?.instanceId??"new":void 0,"data-codex-endpoint-form":n==="codex"?s?.instanceId??"new":void 0,className:"flex flex-col gap-2 rounded-xl border border-hairline/50 bg-inset p-3",onSubmit:b=>{b.preventDefault(),y()},children:[e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t(n==="codex"?"agentEndpoints.responses":"agentEndpoints.messages")}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeEndpoints.name"),e.jsx("input",{...g("name"),maxLength:80,autoFocus:!0,"aria-label":t("claudeEndpoints.name"),className:ft})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeEndpoints.baseUrl"),e.jsx("input",{...g("url"),readOnly:i||s?.codexEndpoint?.profile==="xingchi",type:"url",maxLength:2048,placeholder:c.url,"aria-label":t("claudeEndpoints.baseUrl"),className:z(ft,"font-mono")})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeEndpoints.token"),e.jsx("input",{...g("token"),type:"password",maxLength:4096,autoComplete:"off","aria-label":t("claudeEndpoints.token"),className:z(ft,"font-mono"),placeholder:s?t("claudeEndpoints.tokenKeep"):""})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeEndpoints.model"),e.jsx("input",{...g("model"),maxLength:160,placeholder:c.model,"aria-label":t("claudeEndpoints.model"),className:z(ft,"font-mono")})]}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("claudeEndpoints.modelHint")}),x&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:x}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:a,disabled:m,className:"rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-control disabled:opacity-50",children:t("common.cancel")}),e.jsxs("button",{type:"submit",disabled:m||!f,className:"flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-[12px] font-semibold text-white hover:brightness-110 disabled:opacity-50",children:[m&&e.jsx(J,{size:13,className:"animate-spin"}),t("common.save")]})]})]})}function vi({instance:s,showName:n=!1}){const{state:a,dispatch:i}=G(),[r,c]=l.useState(!1),[o,d]=l.useState(!1),[m,u]=l.useState(!1),[x,p]=l.useState(null),g=a.bots.filter(b=>b.modelSelection.instanceId===s.instanceId||b.fallback?.some(h=>h.instanceId===s.instanceId)||b.tasks?.some(h=>h.modelSelection?.instanceId===s.instanceId)).length,f=s.claudeEndpoint??s.codexEndpoint;if(!f||s.readOnly)return null;const y=async()=>{d(!1),u(!0),p(null);try{const b=await M(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"DELETE"});Array.isArray(b.instances)&&i({type:"instances",instances:b.instances})}catch(b){p(b instanceof Error?b.message:String(b))}finally{u(!1)}};return r?e.jsx(Bs,{instance:s,engine:s.codexEndpoint?"codex":"claude",onDone:()=>c(!1)}):e.jsxs("div",{"data-claude-endpoint":s.claudeEndpoint?s.instanceId:void 0,"data-codex-endpoint":s.codexEndpoint?s.instanceId:void 0,children:[e.jsxs("div",{className:"flex min-h-9 flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[n&&e.jsx("div",{className:"truncate text-[13px] font-medium text-ink",title:s.displayName,children:s.displayName}),e.jsx("div",{className:"truncate font-mono text-[11px] text-ink-secondary",title:f.baseUrl,children:f.baseUrl}),f.model&&e.jsx("div",{className:"truncate font-mono text-[11px] text-ink-secondary",title:f.model,children:f.model})]}),e.jsx("button",{type:"button",onClick:()=>c(!0),disabled:m,className:"ui-button shrink-0",children:t("claudeEndpoints.edit")}),e.jsxs("button",{type:"button",disabled:m||g>0,onClick:()=>d(!0),title:g>0?t("accounts.inUse",{count:String(g)}):t("accounts.remove"),"aria-label":t("claudeEndpoints.remove",{name:s.displayName}),className:"flex min-h-8 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2.5 text-[12px] font-medium text-danger hover:bg-danger/10 disabled:cursor-not-allowed disabled:opacity-50",children:[m?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(Se,{size:14}),t("common.delete")]})]}),g>0&&e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:t("accounts.inUse",{count:String(g)})}),x&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:x}),e.jsx(Qe,{open:o,title:t("accounts.removeTitle",{name:s.displayName}),body:t("claudeEndpoints.removeBody"),confirmLabel:t("common.delete"),pending:m,onCancel:()=>d(!1),onConfirm:()=>{y()}})]})}function ji({engine:s}){const{state:n}=G(),a=n.instances.filter(c=>!c.readOnly&&(s==="claude"?c.claudeEndpoint:c.codexEndpoint)),[i,r]=l.useState(!1);return e.jsxs("div",{"data-claude-endpoints":s==="claude"?"":void 0,"data-codex-endpoints":s==="codex"?"":void 0,className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-[13px] leading-[18px] text-ink",children:t(s==="claude"?"claudeEndpoints.title":"agentEndpoints.codexTitle")}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t(s==="claude"?"claudeEndpoints.hint":"agentEndpoints.codexHint")}),a.length===0?e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("claudeEndpoints.empty")}):e.jsx("ul",{className:"divide-y divide-hairline/40 rounded-xl border border-hairline/50 bg-panel/40",children:a.map(c=>e.jsx("li",{className:"px-3 py-2.5",children:e.jsx(vi,{instance:c,showName:!0})},c.instanceId))}),i?e.jsx(Bs,{engine:s,onDone:()=>r(!1)}):e.jsxs("button",{type:"button",onClick:()=>r(!0),className:"flex min-h-8 w-fit items-center gap-1.5 rounded-lg px-2 py-1.5 text-[13px] font-medium text-ink-secondary outline-none hover:bg-control hover:text-ink focus-visible:ring-2 focus-visible:ring-accent",children:[e.jsx(we,{size:14}),t("claudeEndpoints.add")]})]})}function qt(){return e.jsx(ji,{engine:"claude"})}function wt(){return e.jsx(ji,{engine:"codex"})}function Vt(s){return[...new Set(s.split(/[,,、\s]+/).map(n=>n.trim()).filter(Boolean))]}const De=z(Be,"font-sans"),Zd=[5,10,20,30,60],Jt="ui-icon-button shrink-0 hover:text-ink",Xt={name:"Google Gemini",url:"https://generativelanguage.googleapis.com/v1beta/openai"},ps={count:64,length:200},eu=s=>s.length<=ps.count&&s.every(n=>n.length<=ps.length),xs=(s,n)=>M(`/api/instances/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(n)});function ki({server:s,disabled:n,onPick:a}){return e.jsxs(ge,{size:"sm",className:"shrink-0",value:s.replyWaitMinutes??"",onChange:i=>a(i.target.value?Number(i.target.value):null),disabled:n,"aria-label":t("apiInstances.replyWaitFor",{name:s.displayName}),title:t("apiInstances.replyWaitHint"),children:[e.jsx("option",{value:"",children:t("apiInstances.replyWaitDefault")}),[...new Set([...Zd,...s.replyWaitMinutes?[s.replyWaitMinutes]:[]])].sort((i,r)=>i-r).map(i=>e.jsx("option",{value:i,children:t("apiInstances.replyWaitMinutes",{minutes:String(i)})},i))]})}function tu(){const{state:s,dispatch:n,refreshInstances:a}=G(),[i,r]=l.useState(!1),[c,o]=l.useState(null),d=s.instances.find(u=>u.instanceId==="openaiCompat"&&u.driverKind==="openai-compat");if(!d||!s.config?.openaiCompat?.url)return null;const m=u=>{i||(r(!0),o(null),xs(d.instanceId,{replyWaitMinutes:u}).then(async({instances:x})=>{Array.isArray(x)?n({type:"instances",instances:x}):await a({reportErrors:!0})}).catch(x=>o(x.message||t("apiInstances.failed"))).finally(()=>r(!1)))};return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(ki,{server:d,disabled:i,onPick:m}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("apiInstances.replyWaitHint")}),c&&e.jsx("div",{role:"alert",className:"text-[12px] leading-4 text-danger",children:c})]})}function su(){const{state:s}=G();return e.jsxs(e.Fragment,{children:[e.jsx(nu,{servers:Rs(s.instances)}),e.jsxs("details",{className:"mt-3 rounded-lg border border-hairline/60 bg-inset px-3 py-2",children:[e.jsx("summary",{className:"cursor-pointer text-[13px] text-ink",children:t("agentEndpoints.codexConnect")}),e.jsx(wt,{})]})]})}function nu({servers:s}){const{dispatch:n,refreshInstances:a}=G(),[i,r]=l.useState(""),[c,o]=l.useState(""),[d,m]=l.useState(""),[u,x]=l.useState(""),[p,g]=l.useState(null),[f,y]=l.useState(null),[b,h]=l.useState(null),[k,S]=l.useState(""),E=!!(i.trim()&&c.trim()&&d.trim()),N=(j,B,v,A)=>{p||(g(j),y(null),B().then(async({instances:T})=>{Array.isArray(T)?n({type:"instances",instances:T}):await a({reportErrors:!0}),v?.()}).catch(T=>y({text:T.message||t("apiInstances.failed"),at:A})).finally(()=>g(null)))},P=()=>E&&N("add",()=>M("/api/instances/openai-compat",{method:"POST",body:JSON.stringify({displayName:i.trim(),url:c.trim(),key:d.trim(),...Vt(u).length?{models:Vt(u)}:{}})}).then(j=>(Ze("custom_endpoint","settings","unverified"),j),j=>{throw Ze("custom_endpoint","settings","error"),j}),()=>{r(""),o(""),m(""),x("")});return e.jsxs("div",{"data-api-keys-other":!0,children:[e.jsx("div",{className:"mb-0.5 text-[13px] leading-[18px] text-ink",children:t("apiInstances.title")}),e.jsx("p",{className:"mb-2 text-[12px] leading-4 text-ink-secondary",children:t("apiInstances.subtitle")}),s.length===0&&e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("apiInstances.empty")}),s.map(j=>e.jsxs("div",{className:"mb-1.5 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[12px] text-ink",children:j.displayName}),j.url&&e.jsx("div",{className:"truncate font-mono text-[11px] text-ink-secondary",children:j.url})]}),e.jsx(ki,{server:j,disabled:p!==null,onPick:B=>N("other",()=>xs(j.instanceId,{replyWaitMinutes:B}))}),e.jsx("button",{type:"button",onClick:()=>{S((j.managedModels??[]).join(", ")),h(b===j.instanceId?null:j.instanceId),y(null)},disabled:p!==null,"aria-label":t("apiInstances.editModels",{name:j.displayName}),"aria-expanded":b===j.instanceId,title:t("apiInstances.editModels",{name:j.displayName}),className:Jt,children:e.jsx(Ml,{size:13,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>N("other",()=>M(`/api/instances/${encodeURIComponent(j.instanceId)}/refresh-models`,{method:"POST"})),disabled:p!==null,"aria-label":t("apiInstances.refreshModels",{name:j.displayName}),title:t("apiInstances.refreshModels",{name:j.displayName}),className:Jt,children:e.jsx(Ta,{size:13,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>N("other",()=>M(`/api/instances/${encodeURIComponent(j.instanceId)}`,{method:"DELETE"})),disabled:p!==null,"aria-label":t("apiInstances.remove",{name:j.displayName}),title:t("apiInstances.remove",{name:j.displayName}),className:`${Jt} hover:bg-danger/10 hover:text-danger`,children:e.jsx(Se,{size:13,"aria-hidden":"true"})})]}),b===j.instanceId&&e.jsxs("div",{className:"mt-1.5 flex flex-col gap-1.5",children:[e.jsx("input",{value:k,onChange:B=>S(B.target.value),placeholder:t("apiInstances.models"),"aria-label":t("apiInstances.modelsFor",{name:j.displayName}),spellCheck:!1,disabled:p!==null,className:z(De,"font-mono")}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("apiInstances.editModelsHint")}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>{const B=Vt(k);if(!eu(B)){y({text:t("apiInstances.modelsLimit",ps),at:j.instanceId});return}N("other",()=>xs(j.instanceId,{models:B}),()=>h(null),j.instanceId)},disabled:p!==null,className:"ui-button",children:t("common.save")}),e.jsx("button",{type:"button",onClick:()=>h(null),disabled:p!==null,className:"ui-button",children:t("common.cancel")})]}),f?.at===j.instanceId&&e.jsx("div",{role:"alert",className:"text-[12px] leading-4 text-danger",children:f.text})]})]},j.instanceId)),e.jsxs("div",{className:"mt-2 flex flex-col gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>{r(Xt.name),o(Xt.url)},disabled:p!==null,className:"ui-button self-start",children:t("apiInstances.geminiPreset")}),c.trim()===Xt.url&&e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("apiInstances.geminiKeyHint")}),e.jsx("input",{value:i,onChange:j=>r(j.target.value),placeholder:t("apiInstances.name"),"aria-label":t("apiInstances.name"),spellCheck:!1,disabled:p!==null,className:De}),e.jsx("input",{type:"url",value:c,onChange:j=>o(j.target.value),placeholder:"https://api.example.com/v1","aria-label":t("apiInstances.url"),spellCheck:!1,disabled:p!==null,className:z(De,"font-mono")}),e.jsx("input",{type:"password",value:d,onChange:j=>m(j.target.value),placeholder:t("apiInstances.key"),"aria-label":t("apiInstances.key"),autoComplete:"off",disabled:p!==null,className:z(De,"font-mono")}),e.jsx("input",{value:u,onChange:j=>x(j.target.value),placeholder:t("apiInstances.models"),"aria-label":t("apiInstances.models"),spellCheck:!1,disabled:p!==null,className:z(De,"font-mono")}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("apiInstances.modelsHint")}),e.jsxs("button",{type:"button",onClick:P,disabled:p!==null||!E,className:"ui-button self-start",children:[p==="add"?e.jsx(J,{size:12,"aria-hidden":"true",className:"animate-spin"}):e.jsx(we,{size:12,"aria-hidden":"true"}),p==="add"?t("apiInstances.adding"):t("apiInstances.add")]})]}),f&&!f.at&&e.jsx("div",{className:"mt-1 text-[12px] text-danger",children:f.text})]})}const au="lm-studio";function iu(s){const n=s.trim();if(!/^[1-9]\d{0,4}$/.test(n))return null;const a=Number(n);return a>65535?null:`http://127.0.0.1:${a}/v1`}function ru({heading:s=!0}={}){const{state:n,dispatch:a,refreshInstances:i}=G(),r=Rs(n.instances),[c,o]=l.useState("1234"),[d,m]=l.useState(""),[u,x]=l.useState(!1),[p,g]=l.useState(null),f=iu(c),y=!!(f&&r.some(h=>h.url===f)),b=()=>{u||!f||y||(x(!0),g(null),M("/api/instances/openai-compat",{method:"POST",body:JSON.stringify({displayName:"LM Studio",url:f,key:d.trim()||au,catalog:"lmstudio"})}).then(async h=>{Ze("custom_endpoint","settings","unverified"),Array.isArray(h.instances)?a({type:"instances",instances:h.instances}):await i({reportErrors:!0}),m("")},h=>{Ze("custom_endpoint","settings","error"),g(h instanceof Error&&h.message?h.message:t("apiInstances.failed"))}).finally(()=>x(!1)))};return e.jsxs("div",{className:z(s&&"rounded-lg border border-hairline/40 bg-inset px-3 py-2"),children:[s&&e.jsx("div",{className:"text-[13px] text-ink",children:t("lmStudio.title")}),e.jsx("p",{className:z("text-[12px] leading-4 text-ink-secondary",s&&"mt-1"),children:t("lmStudio.desc")}),e.jsxs("div",{className:"mt-2 flex flex-col gap-1.5",children:[e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] leading-4 text-ink-secondary",children:[t("lmStudio.port"),e.jsx("input",{inputMode:"numeric",value:c,onChange:h=>o(h.target.value),"aria-label":t("lmStudio.port"),spellCheck:!1,disabled:u,className:z(De,"font-mono")})]}),e.jsx("input",{type:"password",value:d,onChange:h=>m(h.target.value),placeholder:t("lmStudio.token"),"aria-label":t("lmStudio.token"),autoComplete:"off",disabled:u,className:z(De,"font-mono")}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("lmStudio.tokenHint")}),f&&e.jsx("p",{className:"truncate font-mono text-[12px] leading-4 text-ink-secondary",children:f}),e.jsxs("button",{type:"button",onClick:b,disabled:u||!f||y,className:"ui-button self-start",children:[u?e.jsx(J,{size:12,"aria-hidden":"true",className:"animate-spin"}):e.jsx(we,{size:12,"aria-hidden":"true"}),u?t("lmStudio.adding"):t("lmStudio.add")]}),y&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("lmStudio.added")})]}),p&&e.jsx("div",{className:"mt-1 text-[12px] text-danger",children:p})]})}const lu="ollama",ou="https://ollama.com/download",cu=s=>`${s.replace(/\/+$/,"")}/v1`,du=(s,n)=>s?.trim().replace(/\/+$/,"")===n;function uu({visible:s}){const{state:n,dispatch:a,refreshInstances:i}=G(),[r,c]=l.useState(""),[o,d]=l.useState(null),[m,u]=l.useState(!1),[x,p]=l.useState(!1),[g,f]=l.useState(null),y=l.useRef(0),b=l.useRef(!1),h=l.useCallback(P=>{const j=++y.current;u(!0),f(null),M(`/api/instances/ollama${P?`?url=${encodeURIComponent(P)}`:""}`).then(B=>{j===y.current&&d(B.status)}).catch(B=>{j===y.current&&(d(null),f(B.message||t("apiInstances.failed")))}).finally(()=>{j===y.current&&u(!1)})},[]);l.useEffect(()=>{!s||b.current||(b.current=!0,h(""))},[s,h]);const k=o?cu(o.url):null,S=!!(k&&(Rs(n.instances).some(P=>P.url===k)||du(n.config?.openaiCompat?.url,k))),E=!!(k&&!S&&!x&&!m&&(o?.state==="ready"||o?.state==="no-models")),N=()=>{!E||!k||(p(!0),f(null),M("/api/instances/openai-compat",{method:"POST",body:JSON.stringify({displayName:"Ollama",url:k,key:lu,catalog:"ollama"})}).then(async P=>{Ze("custom_endpoint","settings","unverified"),Array.isArray(P.instances)?a({type:"instances",instances:P.instances}):await i({reportErrors:!0})},P=>{Ze("custom_endpoint","settings","error"),f(P instanceof Error&&P.message?P.message:t("apiInstances.failed"))}).finally(()=>p(!1)))};return e.jsxs("div",{"data-ollama-server":!0,children:[e.jsx("div",{role:"status","aria-live":"polite",children:m?e.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] leading-4 text-ink-secondary",children:[e.jsx(J,{size:12,className:"animate-spin","aria-hidden":"true"}),t("ollama.checking")]}):o&&e.jsx(zl,{status:o})}),!m&&o?.state==="not-running"&&e.jsx("a",{href:ou,target:"_blank",rel:"noopener noreferrer",className:"mt-1 inline-block text-[12px] font-medium text-accent-text hover:underline",children:t("ollama.download")}),e.jsxs("div",{className:"mt-2 flex flex-col gap-1.5",children:[e.jsx("input",{type:"url",value:r,onChange:P=>c(P.target.value),onKeyDown:P=>{P.key==="Enter"&&h(r.trim())},placeholder:"http://127.0.0.1:11434","aria-label":t("ollama.address"),spellCheck:!1,disabled:x,className:z(Be,"font-mono")}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("ollama.addressHint")}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs("button",{type:"button",onClick:N,disabled:!E,className:"ui-button",children:[x?e.jsx(J,{size:12,"aria-hidden":"true",className:"animate-spin"}):e.jsx(we,{size:12,"aria-hidden":"true"}),x?t("ollama.adding"):t("ollama.add")]}),e.jsxs("button",{type:"button",onClick:()=>h(r.trim()),disabled:m||x,className:"ui-button",children:[e.jsx(Ta,{size:12,"aria-hidden":"true"}),t("common.checkAgain")]})]}),S&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("ollama.added")})]}),g&&e.jsx("div",{role:"alert",className:"mt-1 text-[12px] text-danger",children:g})]})}function mu(){const{state:s,dispatch:n}=G(),a=s.config?.opencodeGo?.providerKeys??[],[i,r]=l.useState(""),[c,o]=l.useState(""),[d,m]=l.useState(!1),[u,x]=l.useState(null),[p,g]=l.useState(null),f=d||u!==null,y=(k,S)=>M("/api/config",{method:"PUT",body:JSON.stringify({opencodeGo:{providerKeys:{[k]:S}}})}).then(E=>n({type:"configStatus",config:E})),b=()=>{const k=i.trim().toUpperCase(),S=Ul(c);if(!(f||!k||!S)){if(!Fl(S)){g(t("keys.notAKey"));return}m(!0),g(null),y(k,S).then(()=>{r(""),o("")}).catch(E=>g(E.message)).finally(()=>m(!1))}},h=k=>{f||(x(k),g(null),y(k,"").catch(S=>g(S.message)).finally(()=>x(null)))};return e.jsxs("div",{"data-opencode-provider-keys":!0,className:"flex flex-col gap-2",children:[e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("keys.opencode.otherProviders.hint")}),s.config?.cloudHome!==!0&&e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("keys.opencode.providersHint").split("{command}").flatMap((k,S)=>S===0?[k]:[e.jsx("code",{className:"font-mono",children:"opencode auth login"},S),k])}),a.map(k=>e.jsxs("div",{"data-opencode-provider-key":k,className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:z(Be,"block flex-1 truncate text-ink"),children:k}),e.jsx("button",{type:"button",onClick:()=>h(k),disabled:f,"aria-label":t("keys.opencode.otherProviders.removeAria",{name:k}),className:"ui-button shrink-0",children:u===k?e.jsx(J,{size:13,className:"animate-spin","aria-hidden":"true"}):t("keys.row.remove")})]},k)),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{type:"text",value:i,onChange:k=>{g(null),r(k.target.value)},onKeyDown:k=>k.key==="Enter"&&b(),disabled:f,placeholder:"VENICE_API_KEY","aria-label":t("keys.opencode.otherProviders.name"),autoComplete:"off",spellCheck:!1,className:z(Be,"w-auto min-w-[min(100%,10rem)] flex-1 uppercase placeholder:normal-case")}),e.jsx("input",{type:"password",value:c,onChange:k=>{g(null),o(k.target.value)},onKeyDown:k=>k.key==="Enter"&&b(),disabled:f,placeholder:t("keys.opencode.otherProviders.keyPlaceholder"),"aria-label":t("keys.opencode.otherProviders.key"),autoComplete:"off",className:z(Be,"w-auto min-w-[min(100%,10rem)] flex-1")}),e.jsx("button",{type:"button",onClick:b,disabled:f||!i.trim()||!c.trim(),className:"ui-button ui-button-primary shrink-0",children:d?e.jsx(J,{size:13,className:"animate-spin","aria-hidden":"true"}):t("common.save")})]}),p&&e.jsx("div",{role:"alert",className:"text-[12px] leading-4 text-danger",children:p})]})}function pu(){const{state:s,dispatch:n}=G(),[a,i]=l.useState(!1),[r,c]=l.useState(null);if(!s.config?.anthropic?.configured)return null;const o=s.config.anthropic.everyClaudeBot===!0,d=()=>{a||(i(!0),c(null),M("/api/config",{method:"PUT",body:JSON.stringify({anthropic:{everyClaudeBot:!o}})}).then(m=>n({type:"configStatus",config:m})).catch(m=>c(m.message)).finally(()=>i(!1)))};return e.jsxs("div",{"data-anthropic-every-claude-bot":!0,className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] leading-[18px] text-ink",children:t("keys.anthropic.everyBot")}),e.jsx("div",{className:"text-[12px] leading-4 text-ink-secondary",children:o?t("keys.anthropic.everyBotOn"):t("keys.anthropic.everyBotOff")})]}),e.jsx(me,{checked:o,disabled:a,onClick:d,"aria-label":t("keys.anthropic.everyBot")})]}),o&&e.jsxs("p",{className:"flex gap-1.5 text-[12px] leading-4 text-warning",children:[e.jsx(Oe,{size:13,className:"mt-px shrink-0","aria-hidden":"true"}),e.jsx("span",{children:t("keys.anthropic.warning")})]}),r&&e.jsx("div",{role:"alert",className:"text-[12px] leading-4 text-danger",children:r})]})}function xu(){const{state:s,dispatch:n}=G(),[a,i]=l.useState(""),[r,c]=l.useState(!1),[o,d]=l.useState(null),m=!!s.config?.vps?.configured,u=!a.trim()&&m;l.useEffect(()=>{i(s.config?.vps?.sshAlias??"")},[s.config?.vps?.sshAlias]);const x=()=>{r||!a.trim()&&!m||(c(!0),d(null),M("/api/config",{method:"PUT",body:JSON.stringify({vps:{sshAlias:a.trim()}})}).then(p=>{n({type:"configStatus",config:p}),i(p.vps?.sshAlias??"")}).catch(p=>d(p.message)).finally(()=>c(!1)))};return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("p",{className:"text-[12px] leading-4 text-ink-secondary",children:[t("keys.vps.descBefore"),e.jsx("a",{href:"https://github.com/leomieo/limix-bot/blob/main/docs/byo-vps.md",target:"_blank",rel:"noopener noreferrer",className:"text-accent-text hover:underline",children:t("keys.vps.descLink")}),t("keys.vps.descAfter")]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{type:"text","data-key-input":!0,value:a,onChange:p=>i(p.target.value),onKeyDown:p=>p.key==="Enter"&&x(),placeholder:"my-vps","aria-label":t("keys.vps.aria"),autoComplete:"off",spellCheck:!1,className:z(Be,"w-auto min-w-[min(100%,12rem)] flex-1")}),e.jsx("button",{type:"button",onClick:x,disabled:r||!a.trim()&&!m||a.trim()===(s.config?.vps?.sshAlias??""),className:z("ui-button shrink-0",!u&&"ui-button-primary"),title:u?t("keys.vps.removeAlias"):void 0,children:r?e.jsx(J,{size:13,className:"animate-spin","aria-hidden":"true"}):u?t("keys.row.remove"):t("common.save")})]}),o&&e.jsx("div",{role:"alert",className:"text-[12px] leading-4 text-danger",children:o})]})}function gu(){const{state:s,dispatch:n}=G(),a=s.config?.openaiCompat?.url??"",[i,r]=l.useState(a),[c,o]=l.useState(!1),[d,m]=l.useState(null),u=l.useRef(!1);l.useEffect(()=>{r(a)},[a]);const x=i.trim()!==a,p=()=>{u.current||!x||(u.current=!0,o(!0),m(null),M("/api/config",{method:"PUT",body:JSON.stringify({openaiCompat:{url:i.trim()}})}).then(g=>n({type:"configStatus",config:g})).catch(g=>m(g.message)).finally(()=>{u.current=!1,o(!1)}))};return e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("div",{className:"text-[13px] leading-[18px] text-ink",children:t("keys.openaiCompat.url")}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"url",value:i,onChange:g=>r(g.target.value),onBlur:p,onKeyDown:g=>g.key==="Enter"&&p(),placeholder:"https://api.groq.com/openai/v1","aria-label":t("keys.openaiCompat.url"),spellCheck:!1,className:z(Be,"pr-8")}),c&&e.jsx(J,{size:13,"aria-hidden":"true",className:"absolute right-2.5 top-1/2 -translate-y-1/2 animate-spin text-ink-secondary"})]}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("keys.openaiCompat.urlHint")}),d&&e.jsx("div",{role:"alert",className:"text-[12px] leading-4 text-danger",children:d})]})}const hu="rounded-xl bg-card in-data-[settings-look=simple]:rounded-[12px] in-data-[settings-look=simple]:border-[0.5px] in-data-[settings-look=simple]:border-(--settings-edge) in-data-[settings-look=simple]:bg-menu",fu=1600,bu={opencodeProviders:()=>e.jsx(mu,{}),ollama:s=>e.jsx(uu,{visible:s}),lmStudio:()=>e.jsx(ru,{heading:!1}),vps:()=>e.jsx(xu,{})},yu={anthropic:()=>e.jsx(pu,{}),openaiCompat:()=>e.jsxs(e.Fragment,{children:[e.jsx(gu,{}),e.jsx(tu,{}),e.jsx(su,{})]}),box:()=>e.jsx(Kl,{}),liveKey:()=>e.jsx($l,{})};function Ni(s,n){if(s.kind==="uses")return!1;const a=Es(s,n);return a.configured||a.included===!0}function vu({entry:s,visible:n}){const{state:a}=G(),i=l.useId(),c=Es(s,a.config).configured?{tone:"ok",text:t("keys.connected")}:null;return e.jsxs("div",{"data-key-row":s.id,role:"group","aria-labelledby":i,className:La,children:[e.jsx(Ba,{entry:s,status:c,titleId:i}),e.jsx("div",{className:"flex flex-col gap-2 pl-8",children:bu[s.id]?.(n)})]})}function ju({entry:s}){const{state:n,dispatch:a}=G(),i=l.useId(),r=s.opens,c=Es(s,n.config),o=c.configured?{tone:"ok",text:t("keys.connected")}:null;return e.jsxs("div",{"data-key-row":s.id,role:"group","aria-labelledby":i,className:La,children:[e.jsx(Ba,{entry:s,status:o,titleId:i}),e.jsxs("div",{className:"flex flex-col gap-2 pl-8",children:[c.configured&&e.jsx("div",{className:"flex",children:e.jsx(_l,{saved:c,label:t(s.labelKey)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[s.whereKey&&e.jsx("span",{className:"min-w-0 flex-1 text-[12px] leading-4 text-ink-secondary",children:t(s.whereKey)}),r&&e.jsx("button",{type:"button","data-key-open":!0,className:"ui-button shrink-0",onClick:()=>a({type:"toggleAppSettings",open:!0,section:r}),children:t("keys.row.open")})]})]})]})}function ku({entry:s,visible:n}){return s.kind==="uses"&&s.uses?e.jsx(on,{id:s.uses,row:s.id}):s.kind==="panel"?e.jsx(vu,{entry:s,visible:n}):s.kind==="elsewhere"?e.jsx(ju,{entry:s}):e.jsx(on,{id:s.id,children:yu[s.id]?.()})}function Nu({id:s,rows:n,open:a,onToggle:i}){const{state:r}=G(),c=os.find(u=>u.id===s),o=l.useId(),d=l.useId(),m=n.filter(u=>Ni(u,r.config)).length;return e.jsxs("section",{"data-keys-section":s,"aria-labelledby":o,className:hu,children:[e.jsxs("button",{type:"button","aria-expanded":a,"aria-controls":d,onClick:i,className:"flex w-full cursor-pointer items-center gap-3 rounded-[inherit] px-4 py-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus/60",children:[e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[e.jsx("span",{id:o,className:"text-[14px] font-medium leading-5 text-ink",children:t(c.titleKey)}),e.jsx("span",{className:"text-[13px] leading-[18px] text-ink-secondary",children:t(c.purposeKey)})]}),m>0&&e.jsx("span",{className:"shrink-0 text-[12px] leading-4 text-ink-secondary",children:t("keys.section.connected",{count:m})}),e.jsx(Ps,{size:14,"aria-hidden":"true",className:z("shrink-0 text-ink-secondary transition-transform motion-reduce:transition-none",a&&"rotate-90")})]}),e.jsxs("div",{id:d,hidden:!a,className:"flex flex-col gap-0.5 border-t border-hairline/40 px-1 py-1.5 in-data-[settings-look=simple]:border-t-[0.5px] in-data-[settings-look=simple]:border-(--settings-edge)",children:[n.map(u=>e.jsx(ku,{entry:u,visible:a},u.id)),s==="voice"&&e.jsx(Jd,{})]})]})}function wu(s,n,a){const i=n.row?s?.querySelector(`[data-key-row="${n.row}"]`):s?.querySelector(`[data-keys-section="${a}"]`);if(!i||i.closest("[hidden]"))return!1;const r=Vd(i);return r&&Ls(r,i,n.row?"center":"start",16),n.row&&(i.querySelector("[data-key-input], [data-key-replace], [data-key-own], [data-key-open], input, button")?.focus({preventScroll:!0}),i.setAttribute("data-key-highlight",""),window.setTimeout(()=>i.removeAttribute("data-key-highlight"),fu)),!0}function Su(){const{state:s}=G(),[n,a]=l.useState(""),[i,r]=l.useState(()=>new Set(os.filter(p=>p.id==="ai"||lt.some(g=>g.section===p.id&&Ni(g,s.config))).map(p=>p.id))),c=l.useRef(null),o=Ra(),d=n.trim().toLowerCase();l.useEffect(()=>{if(!o)return;const p=lt.find(b=>b.id===o.row)?.section??"ai";a(""),r(b=>b.has(p)?b:new Set([...b,p]));let g=0,f=0;const y=()=>{wu(c.current,o,p)||++f>60?Dl(o):g=window.requestAnimationFrame(y)};return g=window.requestAnimationFrame(y),()=>window.cancelAnimationFrame(g)},[o]);const m=s.config?.live?.provider==="azure",u=lt.filter(p=>Cs(p,d)&&!(m&&p.id==="liveCalls")),x=os.flatMap(p=>{const g=u.filter(f=>f.section===p.id);return g.length>0?[{id:p.id,rows:g}]:[]});return e.jsxs("div",{ref:c,"data-keys-page":!0,className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-[13px] leading-[18px] text-ink-secondary",children:t("settings.connections.subtitle")}),e.jsxs("div",{className:"flex h-8 items-center gap-2 rounded-lg bg-ink/[0.05] px-[9px] focus-within:ring-2 focus-within:ring-focus/60",children:[e.jsx(mt,{size:15,"aria-hidden":"true",className:"shrink-0 text-ink-secondary"}),e.jsx("input",{"data-keys-search":!0,type:"text",value:n,onChange:p=>a(p.target.value),onKeyDown:p=>{p.key!=="Escape"||!n||(p.preventDefault(),p.stopPropagation(),a(""))},placeholder:t("keys.search.placeholder"),"aria-label":t("keys.search.aria"),autoComplete:"off",spellCheck:!1,className:"w-full min-w-0 bg-transparent text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"})]}),x.length===0?e.jsx("p",{"data-keys-empty":!0,className:"px-1 text-[13px] leading-[18px] text-ink-secondary",children:t("keys.search.none",{query:n.trim()})}):x.map(({id:p,rows:g})=>e.jsx(Nu,{id:p,rows:g,open:d!==""||i.has(p),onToggle:()=>r(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},p))]})}function wi({simple:s=!1}){return null}function Si({simple:s=!1}){const n=window.ogb?.openAtLogin,[a,i]=l.useState(null),[r,c]=l.useState(!1),[o,d]=l.useState(!1);if(l.useEffect(()=>{let u=!0;return n?.state().then(x=>{u&&i(x)}).catch(()=>{}),()=>{u=!1}},[n]),!n||!a?.available)return null;const m=u=>{c(!0),d(!1),n.set(u).then(x=>{i(x),d(x.on!==u)},()=>d(!0)).finally(()=>c(!1))};return e.jsx(de,{title:t("settings.openAtLogin.title"),subtitle:t(s?"settings.simple.openAtLogin":"settings.openAtLogin.subtitle"),message:o?e.jsx("span",{role:"alert",className:"text-danger",children:t("settings.openAtLogin.failed")}):void 0,children:e.jsx(me,{checked:a.on,disabled:r,"aria-label":t("settings.openAtLogin.title"),onClick:()=>m(!a.on)})})}function Cu(s=typeof window>"u"?void 0:window.ogb){return s?.platform==="darwin"&&s.talkShortcut?["talk","voice","shortcut","hotkey","hold to talk","push to talk","quick asks"]:[]}function Ci(){const s=window.ogb?.talkShortcut,[n,a]=l.useState(null),[i,r]=l.useState(!1),[c,o]=l.useState(!1);if(l.useEffect(()=>{let p=!0;return s?.state().then(g=>{p&&a(g)}).catch(()=>{}),()=>{p=!1}},[s]),!s||!n?.available)return null;const d=n.keys.find(p=>p.id===n.key)?.label??"",m=p=>{r(!0),o(!1),s.set(p).then(a,()=>o(!0)).finally(()=>r(!1))},u=c?t("settings.talk.failed"):n.enabled&&n.taken?t("settings.talk.taken",{key:d}):null,x=e.jsxs(e.Fragment,{children:[n.enabled&&e.jsx(ge,{size:"sm",className:"w-full max-w-[240px]",value:n.key,disabled:i,"aria-label":t("settings.talk.keyAria"),onChange:p=>m({key:p.target.value}),children:n.keys.map(p=>e.jsx("option",{value:p.id,children:p.label},p.id))}),u&&e.jsx("div",{role:"alert",className:n.enabled?"mt-2 text-danger":"text-danger",children:u})]});return e.jsx(de,{title:t("settings.talk.title"),subtitle:t("settings.talk.subtitle",{key:d}),message:n.enabled||u?x:null,children:e.jsx(me,{checked:n.enabled,disabled:i,"aria-label":t("settings.talk.aria"),onClick:()=>m({enabled:!n.enabled})})})}const Yt=s=>s===0||s>=1024*1024?`${Math.round(s/(1024*1024))} MB`:`${Math.ceil(s/1024)} KB`;function Ei(){const[s,n]=l.useState(null),[a,i]=l.useState(!1),[r,c]=l.useState(!1),[o,d]=l.useState(null);if(l.useEffect(()=>{let u=!0;return M("/api/attachment-storage").then(x=>{u&&n(x)}).catch(()=>{}),()=>{u=!1}},[]),!s)return null;const m=async()=>{c(!0),d(null);try{const u=await M("/api/attachment-storage",{method:"POST"});n(u);const x=t("settings.attachments.cleared",{count:u.removed,freed:Yt(u.freedBytes)});d(u.failed>0?{kind:"error",message:`${x} ${t("settings.attachments.failed",{count:u.failed})}`}:{kind:"success",message:x})}catch(u){d({kind:"error",message:u instanceof Error?u.message:String(u)})}finally{c(!1),i(!1)}};return e.jsx(de,{title:t("settings.attachments.title"),subtitle:e.jsxs(e.Fragment,{children:[e.jsx("span",{"data-attachments-used":!0,className:"block",children:t("settings.attachments.used",{used:Yt(s.usedBytes),max:Yt(s.maxBytes)})}),e.jsx("span",{className:"block",children:t(a?"settings.attachments.confirmText":"settings.attachments.help")})]}),message:o&&e.jsx("p",{role:o.kind==="error"?"alert":"status",className:z(o.kind==="error"?"text-danger":"text-success"),children:o.message}),children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>i(!1),disabled:r,className:"ui-button",children:t("settings.attachments.cancel")}),e.jsx("button",{type:"button",onClick:()=>{m()},disabled:r,className:"ui-button text-danger",children:r?t("settings.attachments.clearing"):t("settings.attachments.confirm")})]}):e.jsx("button",{type:"button",onClick:()=>{d(null),i(!0)},className:"ui-button",children:t("settings.attachments.clear")})})})}function Ai({simple:s=!1}){const[n,a]=l.useState(!1),[i,r]=l.useState(null),[c,o]=l.useState(null),d=async()=>{if(!(!window.ogb?.exportDiagnostics||n)){a(!0),r(null);try{const x=await window.ogb.exportDiagnostics();x&&r({kind:"success",message:t("settings.diagnostics.saved",{path:x})})}catch(x){r({kind:"error",message:x instanceof Error?x.message:String(x)})}finally{a(!1)}}},m=async()=>{if(window.ogb?.openLogsFolder){r(null);try{const x=await window.ogb.openLogsFolder();o(x.folder),x.opened||r({kind:"error",message:t("settings.diagnostics.openFailed",{folder:x.folder})})}catch(x){r({kind:"error",message:x instanceof Error?x.message:String(x)})}}},u=!!window.ogb?.exportDiagnostics;return e.jsx(de,{title:t("settings.diagnostics.title"),subtitle:t(s?"settings.simple.diagnostics":"settings.diagnostics.subtitle"),message:e.jsxs(e.Fragment,{children:[c&&i?.kind!=="error"&&e.jsx("p",{role:"status","data-logs-folder":!0,className:"break-all text-ink-secondary",children:t("settings.diagnostics.logsAt",{folder:c})}),i&&e.jsx("p",{role:i.kind==="error"?"alert":"status",className:z("break-all",i.kind==="error"?"text-danger":"text-success"),children:i.message}),e.jsx("p",{"data-logs-help":!0,className:"text-ink-tertiary",children:t(u?"settings.diagnostics.logsHelp":"settings.diagnostics.elsewhere")})]}),children:u&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[window.ogb?.openLogsFolder&&e.jsx("button",{type:"button",onClick:()=>{m()},className:"ui-button",children:t("settings.diagnostics.openLogs")}),e.jsx("button",{onClick:()=>{d()},disabled:n,"aria-label":t("settings.diagnostics.aria"),className:"ui-button",children:n?t("settings.diagnostics.exporting"):t("settings.diagnostics.export")})]})})}const Eu="https://dash.cloudflare.com/profile/api-tokens",Au=/^[0-9a-f]{32}$/i,Pn="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none";function Iu({failureText:s}){const{state:n,dispatch:a}=G(),i=n.config?.helpers,r=i?.own.workersAi===!0,c=i?.workersAiAccountId??"",[o,d]=l.useState(null),[m,u]=l.useState(""),[x,p]=l.useState(!1),[g,f]=l.useState(!1),[y,b]=l.useState(null),[h,k]=l.useState(null),S=(o??c).trim(),E=m.trim(),N=!E&&r&&o===null,P=o!==null&&S!==c,j=A=>a({type:"configStatus",config:A}),B=async()=>{if(!(x||!E&&!r&&!P)){if(E&&!Au.test(S))return b(t("decider.workersAi.needsAccount"));p(!0),b(null),k(null);try{(P||E&&!c)&&j(await M("/api/config",{method:"PUT",body:JSON.stringify({decider:{workersAiAccountId:S}})})),(E||N)&&j(window.ogb?.setCredential?await window.ogb.setCredential("workersAiToken",E):await M("/api/config",{method:"PUT",body:JSON.stringify({decider:{workersAiToken:E}})})),u(""),d(null)}catch(A){b(A instanceof Error?A.message:String(A))}finally{p(!1)}}},v=async()=>{if(!(g||x||!E&&!r)){f(!0),k(null),b(null);try{const A=await M("/api/decider/test",{method:"POST",body:JSON.stringify({provider:"workersai",...E?{key:E,accountId:S}:{}})}),T=A.extraction?[t(A.extraction.ok?"decider.test.extractionOk":"decider.test.extractionFailed")]:[];k(A.ok?{ok:A.extraction?.ok!==!1,text:[t("decider.workersAi.test.ok",{ms:String(A.latencyMs)}),...T].join(" ")}:{ok:!1,text:s(A)})}catch(A){k({ok:!1,text:A instanceof Error?A.message:String(A)})}finally{f(!1)}}};return e.jsxs(Y,{title:t("decider.workersAi.title"),children:[e.jsx("p",{className:"mb-2 text-[12px] leading-relaxed text-ink-secondary",children:t("decider.workersAi.detail")}),r&&e.jsxs("div",{role:"status",className:"mb-2 flex items-center gap-2 text-[13px] text-success",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-success"}),e.jsx("span",{children:t("decider.status.connected")})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("input",{type:"text","data-testid":"workers-ai-account",value:o??c,onChange:A=>{k(null),b(null),d(A.target.value)},disabled:x,placeholder:t("decider.workersAi.accountIdPlaceholder"),"aria-label":t("decider.workersAi.accountId"),autoComplete:"off",spellCheck:!1,className:Pn}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"password","data-testid":"workers-ai-token",value:m,onChange:A=>{k(null),b(null),u(A.target.value)},onKeyDown:A=>A.key==="Enter"&&void B(),disabled:x,placeholder:r?t("keys.replace"):t("decider.workersAi.tokenPlaceholder"),"aria-label":t("decider.workersAi.token"),autoComplete:"off",spellCheck:!1,className:Pn}),e.jsx("button",{type:"button","data-testid":"workers-ai-save",onClick:()=>{B()},disabled:x||!E&&!r&&!P,title:N?t("keys.removeKey"):t("common.save"),className:z("flex w-[72px] shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-lg bg-control py-2 text-[13px] hover:bg-raised-hover disabled:cursor-not-allowed disabled:opacity-50",N?"text-danger":"text-ink"),children:x?e.jsx(J,{size:13,className:"animate-spin"}):N?t("keys.clear"):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:13}),t("common.save")]})}),e.jsx("button",{type:"button","data-testid":"workers-ai-test",onClick:()=>{v()},disabled:g||x||!E&&!r,className:"flex shrink-0 cursor-pointer items-center justify-center rounded-lg border border-hairline/40 px-3 py-2 text-[13px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:cursor-not-allowed disabled:opacity-50",children:g?t("keys.testing"):t("keys.test")})]})]}),y&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:y}),h&&e.jsx("p",{role:"status",className:z("mt-1 text-[12px]",h.ok?"text-success":"text-danger"),children:h.text}),e.jsxs("a",{href:Eu,target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-flex cursor-pointer items-center gap-1 text-[12px] text-accent hover:underline",children:[t("decider.workersAi.getKey"),e.jsx(pt,{size:11,"aria-hidden":"true"})]})]})}const Pu={jev:"https://typesafe.ai",openrouter:"https://openrouter.ai/keys"},Tu=1500,Os={rejected:"decider.error.rejected",unreachable:"decider.error.unreachable",timeout:"decider.error.timeout",rate_limited:"decider.error.rateLimited",overloaded:"decider.error.overloaded",malformed:"decider.error.malformed",no_key:"decider.error.noKey",misconfigured:"decider.error.misconfigured"},Tn={rejected:"decider.included.error.rejected",rate_limited:"decider.included.error.limited"},Ru={...Os,rejected:"decider.openrouter.error.rejected",unreachable:"decider.openrouter.error.unreachable",timeout:"decider.openrouter.error.timeout",rate_limited:"decider.openrouter.error.rateLimited",overloaded:"decider.openrouter.error.overloaded",malformed:"decider.openrouter.error.malformed"},Lu={...Os,rejected:"decider.workersAi.error.rejected",unreachable:"decider.workersAi.error.unreachable",timeout:"decider.workersAi.error.timeout",rate_limited:"decider.workersAi.error.rateLimited",overloaded:"decider.workersAi.error.overloaded",malformed:"decider.workersAi.error.malformed"},Qt={jev:"decider.status.byJev",workersai:"decider.status.byWorkersAi",openrouter:"decider.status.byOpenRouter"};function Bu(s){const n=s?.decider,a=s?.helpers?.extraction,i=n?.configured?n.included?t("decider.status.byCloud"):t(Qt[n.provider]??Qt.jev):t("decider.status.notSetUp"),r=a?.provider?a.included?t("decider.status.byCloud"):t(Qt[a.provider]):t("decider.status.notSetUp");return t("decider.status.line",{decisions:i,extraction:r})}function Rn(s,n=!1,a="jev"){if(a==="workersai"){if(s.reason==="http_error")return t("decider.workersAi.error.http",{status:String(s.status??"?")});const r=Lu[s.reason];return r?t(r):t("decider.error.other")}if(a==="openrouter"){if(s.reason==="http_error"&&s.status===402)return t("decider.openrouter.error.credits");if(s.reason==="http_error")return t("decider.openrouter.error.http",{status:String(s.status??"?")});const r=Ru[s.reason];return r?t(r):t("decider.error.other")}if(n&&s.reason==="http_error"&&s.status===402)return t("decider.included.error.subscription");if(n&&Tn[s.reason])return t(Tn[s.reason]);if(s.reason==="http_error")return t("decider.error.http",{status:String(s.status??"?")});const i=Os[s.reason];return i?t(i):t("decider.error.other")}const Ou=["decider.jobs.browserClicks","decider.jobs.toolSelection","decider.jobs.placement"];function Mu(){const{state:s,dispatch:n}=G(),a=s.config?.decider,i=a?.selectedProvider??(a?.provider==="openrouter"?"openrouter":"jev"),r=i==="workersai",c=i==="openrouter",o=a?.configured??!1,d=o&&a?.included===!0,m=c&&o&&a?.keySource==="shared",u=c&&a?.sharedKey===!0,x=o&&!d&&!m,p=a?.enabled??!1,g=a?.jobs.roomRouting??!0,[f,y]=l.useState(""),[b,h]=l.useState(!1),[k,S]=l.useState(!1),[E,N]=l.useState(!1),[P,j]=l.useState(null),[B,v]=l.useState(null),[A,T]=l.useState(null),$=f.trim(),U=!$&&x,Z=!c||d?null:m?"decider.openrouter.status.sharedHint":o?u?"decider.openrouter.status.ownFallbackHint":null:"decider.openrouter.status.notConnectedHint",H=L=>n({type:"configStatus",config:L}),ne=async L=>{if(!k){S(!0),j(null);try{H(await M("/api/config",{method:"PUT",body:JSON.stringify({decider:L})}))}catch(X){j(X instanceof Error?X.message:String(X))}finally{S(!1)}}};l.useEffect(()=>{if(!c||A)return;let L=!1;return M("/api/decider/models").then(X=>{L||T(X)},()=>{}),()=>{L=!0}},[c,A]);const ae=L=>{y(""),v(null),ne(L)},oe=async()=>{if(!(b||!$&&!x)){h(!0),j(null),v(null);try{const L=window.ogb?.setCredential?await window.ogb.setCredential(c?"openrouterDeciderKey":"jevApiKey",$):await M("/api/config",{method:"PUT",body:JSON.stringify({decider:{[c?"openrouterKey":"key"]:$}})});H(L),y("")}catch(L){j(L instanceof Error?L.message:String(L))}finally{h(!1)}}},F=async()=>{if(E||b||!$&&!o)return;N(!0),v(null),j(null);const L=!$&&d,X=!$&&m;try{const se=await M("/api/decider/test",{method:"POST",body:JSON.stringify($?{key:$}:{})});v(se.ok?{ok:!0,text:c?[t(X?"decider.openrouter.test.okShared":"decider.openrouter.test.ok",{ms:String(se.latencyMs)}),...se.latencyMs>Tu?[t("decider.test.slow")]:[]].join(" "):t("decider.test.ok",{ms:String(se.latencyMs)})}:{ok:!1,text:Rn(se,L,i)})}catch(se){v({ok:!1,text:se instanceof Error?se.message:String(se)})}finally{N(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-2 px-4",children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("decider.intro")}),e.jsx("p",{role:"status","data-testid":"helpers-status",className:"text-[13px] font-medium text-ink",children:Bu(s.config)})]}),e.jsx(Iu,{failureText:L=>Rn(L,!1,"workersai")}),e.jsx(de,{title:t("decider.provider.label"),children:e.jsxs(ge,{className:"w-48","data-testid":"decider-provider",value:i,onChange:L=>ae({provider:L.target.value}),disabled:k||!s.config,"aria-label":t("decider.provider.label"),children:[e.jsx("option",{value:"jev",children:t("decider.provider.jev")}),e.jsx("option",{value:"workersai",children:"Cloudflare Workers AI"}),e.jsx("option",{value:"openrouter",children:t("decider.provider.openrouter")})]})}),c&&e.jsx(de,{title:t("decider.model.label"),subtitle:A?.source==="builtin"?t("decider.model.builtinNote"):void 0,children:e.jsxs(ge,{className:"w-64 max-w-full","data-testid":"decider-model",value:a?.model??"",onChange:L=>ae({openrouterModel:L.target.value,openrouterApi:A?.models.find(X=>X.id===L.target.value)?.api??"chat"}),disabled:k,"aria-label":t("decider.model.label"),children:[a?.model&&!A?.models.some(L=>L.id===a.model)&&e.jsx("option",{value:a.model,children:a.model}),["recommended","more"].map(L=>{const X=A?.models.filter(se=>se.group===L)??[];return X.length>0&&e.jsx("optgroup",{label:t(L==="recommended"?"decider.model.recommended":"decider.model.more"),children:X.map(se=>e.jsx("option",{value:se.id,children:se.name},se.id))},L)})]})}),e.jsx(de,{title:t(c?"decider.openrouter.master":"decider.master"),subtitle:o?void 0:t(r?"decider.workersAi.needsAccount":c?"decider.masterNeedsKey.openrouter":"decider.masterNeedsKey"),children:e.jsx(me,{"data-testid":"decider-master","aria-label":t(c?"decider.openrouter.master":"decider.master"),checked:p,disabled:!o||k||!s.config,onClick:()=>{ne({enabled:!p})},className:"cursor-pointer"})}),!r&&e.jsxs(Y,{title:t(c?"decider.openrouter.key.label":"decider.key.label"),children:[e.jsxs("div",{role:"status",className:"mb-2 flex items-center gap-2 text-[13px] text-ink-secondary",children:[e.jsx("span",{className:z("size-1.5 rounded-full",o?"bg-success":"bg-raised-hover")}),e.jsx("span",{className:o?"text-success":void 0,children:d?t("keys.includedWithCloudPro"):m?t("decider.openrouter.status.shared"):o?t(u?"decider.openrouter.status.own":"decider.status.connected"):t("decider.status.notConnected")})]}),Z&&e.jsxs("p",{className:"mb-2 text-[12px] leading-relaxed text-ink-secondary",children:[t(Z),!x&&e.jsxs(e.Fragment,{children:[" ",e.jsx("button",{type:"button","data-testid":"decider-manage-keys",onClick:()=>n(cs("openrouter")),className:"cursor-pointer text-accent hover:underline",children:t("decider.openrouter.key.manageLink")})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"password",value:f,onChange:L=>{v(null),j(null),y(L.target.value)},onKeyDown:L=>L.key==="Enter"&&void oe(),disabled:b,placeholder:x?t("keys.replace"):t(m?"decider.openrouter.key.overridePlaceholder":c?"decider.openrouter.key.placeholder":"decider.key.placeholder"),"aria-label":t(c?"decider.openrouter.key.label":"decider.key.label"),autoComplete:"off",spellCheck:!1,className:"w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"}),e.jsx("button",{type:"button","data-testid":"decider-save",onClick:()=>{oe()},disabled:b||!$&&!x,title:U?t("keys.removeKey"):t("common.save"),className:z("flex w-[72px] shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-lg bg-control py-2 text-[13px] hover:bg-raised-hover disabled:cursor-not-allowed disabled:opacity-50",U?"text-danger":"text-ink"),children:b?e.jsx(J,{size:13,className:"animate-spin"}):U?t("keys.clear"):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:13}),t("common.save")]})}),e.jsx("button",{type:"button","data-testid":"decider-test",onClick:()=>{F()},disabled:E||b||!$&&!o,className:"flex shrink-0 cursor-pointer items-center justify-center rounded-lg border border-hairline/40 px-3 py-2 text-[13px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:cursor-not-allowed disabled:opacity-50",children:E?t("keys.testing"):t("keys.test")})]}),P&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:P}),B&&e.jsx("p",{role:"status",className:z("mt-1 text-[12px]",B.ok?"text-success":"text-danger"),children:B.text}),!m&&e.jsxs("a",{href:Pu[i],target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-flex cursor-pointer items-center gap-1 text-[12px] text-accent hover:underline",children:[t(c?"decider.openrouter.key.getKey":"decider.key.getKey"),e.jsx(pt,{size:11,"aria-hidden":"true"})]})]}),r&&P&&e.jsx("p",{role:"alert",className:"px-4 text-[12px] text-danger",children:P}),e.jsx(Y,{title:t("decider.jobs.title"),children:e.jsxs("ul",{className:"flex flex-col",children:[e.jsxs("li",{className:"flex items-start justify-between gap-4 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13px] font-medium text-ink",children:t("decider.jobs.roomRouting")}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-relaxed text-ink-secondary",children:t("decider.jobs.roomRoutingDetail")})]}),e.jsx(me,{"data-testid":"decider-job-roomRouting","aria-label":t("decider.jobs.roomRouting"),checked:p&&g,disabled:!p||k,onClick:()=>{ne({jobs:{roomRouting:!g}})},className:"cursor-pointer"})]}),Ou.map(L=>e.jsxs("li",{"data-testid":"decider-coming-soon","aria-disabled":"true",className:"flex items-center justify-between gap-4 border-t border-hairline/40 py-2 opacity-50",children:[e.jsx("span",{className:"text-[13px] text-ink-secondary",children:t(L)}),e.jsx("span",{className:"rounded bg-control px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-ink-secondary",children:t("decider.jobs.comingSoon")})]},L))]})})]})}const zu=["openai","xai","gemini","openrouter","custom"],Uu=4,Ii={openai:"gpt-image-2",xai:"grok-imagine-image-2.0",gemini:"gemini-2.5-flash-image",openrouter:"google/gemini-2.5-flash-image",custom:""},Fu={openai:[{id:"gpt-image-2",name:"GPT Image 2"},{id:"gpt-image-1",name:"GPT Image 1"},{id:"gpt-image-1-mini",name:"GPT Image 1 Mini"}],xai:[{id:"grok-imagine-image-2.0",name:"Grok Imagine Image 2.0"}],gemini:[{id:"gemini-2.5-flash-image",name:"Nano Banana (Gemini 2.5 Flash Image)"}],openrouter:[{id:"google/gemini-2.5-flash-image",name:"Google: Nano Banana (Gemini 2.5 Flash Image)"},{id:"google/gemini-3.1-flash-image",name:"Google: Nano Banana 2 (Gemini 3.1 Flash Image)"},{id:"google/gemini-3-pro-image",name:"Google: Nano Banana Pro (Gemini 3 Pro Image)"},{id:"openai/gpt-image-2",name:"OpenAI: GPT Image 2"},{id:"black-forest-labs/flux-3-image",name:"Black Forest Labs: FLUX 3 Image"},{id:"bytedance-seed/seedream-5-0-pro",name:"ByteDance Seed: Seedream 5.0 Pro"},{id:"x-ai/grok-imagine-image-2.0",name:"xAI: Grok Imagine Image 2.0"},{id:"qwen/qwen-image-3",name:"Qwen: Qwen Image 3"}],custom:[]};function Du(s){const n="Use an HTTPS API base URL, or HTTP for a local router, without passwords, query parameters or fragments";let a;try{a=new URL(s.trim())}catch{throw new Error(n)}if(s.length>2048||a.username||a.password||a.search||a.hash)throw new Error(n);const i=a.hostname.toLowerCase(),r=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(i),c=i==="localhost"||i.endsWith(".localhost")||i.endsWith(".local")||i==="host.docker.internal"||i==="host.containers.internal"||i==="[::1]"||/^\[f[cd][0-9a-f]{2}:/.test(i)||r&&(Number(r[1])===127||Number(r[1])===10||Number(r[1])===192&&Number(r[2])===168||Number(r[1])===172&&Number(r[2])>=16&&Number(r[2])<=31);if(a.protocol!=="https:"&&!(a.protocol==="http:"&&c))throw new Error(n);if(r&&(Number(r[1])===0||Number(r[1])===169&&Number(r[2])===254))throw new Error(n);return a.pathname=a.pathname.replace(/\/+$/,"").replace(/\/(images\/generations|responses)$/,""),a.toString().replace(/\/+$/,"")}const Et={openai:"OpenAI",xai:"Grok (xAI)",gemini:"Gemini",openrouter:"OpenRouter",custom:"Custom"},_u={openai:{credential:"openaiImageApiKey",patch:s=>({imageGen:{key:s}}),label:"imageGen.key.openai"},gemini:{credential:"geminiImageApiKey",patch:s=>({imageGen:{geminiKey:s}}),label:"imageGen.key.gemini"},custom:{credential:"customImageApiKey",patch:s=>({imageGen:{customApiKey:s}}),label:"imageGen.key.custom"}},$u={xai:{label:"imageGen.key.xai",note:"imageGen.key.sharedXai"},openrouter:{label:"imageGen.key.openrouter",note:"imageGen.key.sharedOpenrouter"}},Ln={openai:"https://platform.openai.com/api-keys",gemini:"https://aistudio.google.com/apikey",xai:"https://console.x.ai",openrouter:"https://openrouter.ai/keys"},gs="w-full min-w-0 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none disabled:opacity-50",At="flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:cursor-not-allowed disabled:opacity-50",Zt="\0other";function Ku(s,n){return n.ok?n.freeTier?{ok:!1,text:t("imageGen.test.noCredit")}:{ok:!0,text:t(s==="openrouter"?"imageGen.test.okOpenrouter":"imageGen.test.ok")}:n.reason==="model_missing"?{ok:!1,text:t("imageGen.test.modelMissing",{model:n.model})}:n.reason==="rejected"?{ok:!1,text:t("imageGen.test.rejected")}:n.reason==="unreachable"?{ok:!1,text:t("imageGen.test.unreachable")}:n.reason==="no_key"?{ok:!1,text:t("imageGen.key.missing")}:n.reason==="no_url"?{ok:!1,text:t("imageGen.test.noUrl")}:{ok:!1,text:t("imageGen.test.unexpected")}}function Hu(s,n){return n==="openai"?s?.openaiConfigured===!0:n==="xai"?s?.xaiConfigured===!0:n==="gemini"?s?.geminiConfigured===!0:n==="openrouter"?s?.openrouterConfigured===!0:s?.customKeyConfigured===!0}function Wu(){const{state:s,dispatch:n}=G(),a=s.config?.imageGen,i=a?.primary??{provider:a?.provider??"openai",model:a?.model??Ii.openai,configured:a?.configured===!0},r=a?.fallback??null,[c,o]=l.useState(!1),[d,m]=l.useState(null),[u,x]=l.useState(null),p=i.provider==="openrouter"||r?.provider==="openrouter";l.useEffect(()=>{if(!p||u)return;let b=!1;return M("/api/images/openrouter-models").then(h=>{b||x(Array.isArray(h?.models)?h:{source:"builtin",models:[]})},()=>{b||x({source:"builtin",models:[]})}),()=>{b=!0}},[p,u]);const g=async b=>{o(!0),m(null);try{const h=await M("/api/config",{method:"PUT",body:JSON.stringify(b)});n({type:"configStatus",config:h})}catch(h){m(h instanceof Error?h.message:String(h))}finally{o(!1)}},f=(b,h)=>{if(b==="fallback"&&h==="")return void g({imageGen:{fallback:null}});const k=h,S=b==="primary"&&r?.provider===k;g({imageGen:{[b]:{provider:k},...S?{fallback:null}:{}}})},y=[i.provider,...r?[r.provider]:[]].filter((b,h,k)=>k.indexOf(b)===h);return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-2 px-4",children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("imageGen.intro")}),e.jsxs("p",{role:"status","data-testid":"image-gen-status",className:"flex items-center gap-2 text-[13px] font-medium text-ink",children:[e.jsx("span",{className:z("size-1.5 shrink-0 rounded-full",a?.ready?i.configured?"bg-success":"bg-warning":"bg-raised-hover")}),a?.ready?i.configured?t("imageGen.status.ready",{provider:Et[i.provider]}):t("imageGen.status.backupOnly",{provider:Et[r.provider]}):t("imageGen.status.notReady")]})]}),e.jsx(Gu,{disabled:c}),e.jsx(Bn,{slot:"primary",provider:i.provider,model:i.model,configured:i.configured,openrouterModels:u,disabled:c||!s.config,onProvider:f,onModel:b=>{g({imageGen:{primary:{provider:i.provider,model:b}}})}}),e.jsx(Bn,{slot:"fallback",provider:r?.provider??null,model:r?.model??"",configured:r?.configured===!0,exclude:i.provider,openrouterModels:u,disabled:c||!s.config,onProvider:f,onModel:b=>r&&void g({imageGen:{fallback:{provider:r.provider,model:b}}})}),e.jsx(de,{title:t("imageGen.maxPerTurn.label"),subtitle:t("imageGen.maxPerTurn.help"),children:e.jsx(ge,{className:"w-20","data-testid":"image-gen-max",value:String(a?.maxPerTurn??Uu),onChange:b=>{g({imageGen:{maxPerTurn:Number(b.target.value)}})},disabled:c||!s.config,"aria-label":t("imageGen.maxPerTurn.label"),children:Array.from({length:10},(b,h)=>h+1).map(b=>e.jsx("option",{value:b,children:b},b))})}),d&&e.jsx("p",{role:"alert",className:"px-4 text-[12px] text-danger",children:d}),y.map(b=>e.jsx(Vu,{provider:b,status:a},b))]})}function Gu({disabled:s}){const{dispatch:n}=G(),[a,i]=l.useState(null),[r,c]=l.useState(""),[o,d]=l.useState(!1),[m,u]=l.useState(""),x=async p=>{d(!0),u("");try{if(p){const g=await M("/api/images/connections",{method:"POST",body:JSON.stringify({id:r})});n({type:"configStatus",config:g}),i(null),c("")}else{const g=await M("/api/images/connections");i(g.connections),c(g.connections[0]?.id??"")}}catch(g){u(g instanceof Error?g.message:String(g))}finally{d(!1)}};return e.jsxs(Y,{title:t("imageGen.saved.title"),children:[e.jsx("p",{className:"mb-2 text-[12px] text-ink-secondary",children:t("imageGen.saved.help")}),a===null?e.jsx("button",{type:"button",className:At,disabled:o||s,onClick:()=>{x(!1)},children:t("imageGen.saved.title")}):a.length?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ge,{"aria-label":t("imageGen.saved.title"),value:r,disabled:o,onChange:p=>c(p.target.value),children:a.map(p=>e.jsxs("option",{value:p.id,children:[p.name," · ",p.url]},p.id))}),e.jsx("button",{type:"button",className:At,disabled:o||s||!r,onClick:()=>{x(!0)},children:t("imageGen.saved.apply")})]}):e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("imageGen.saved.empty")}),m&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:m})]})}function Bn({slot:s,provider:n,model:a,configured:i,exclude:r,openrouterModels:c,disabled:o,onProvider:d,onModel:m}){const u=t(s==="primary"?"imageGen.primary.label":"imageGen.fallback.label");return e.jsxs(e.Fragment,{children:[e.jsx(de,{title:u,subtitle:n&&!i?t(n==="custom"?"imageGen.slot.needsConnection":"imageGen.slot.needsKey"):t(s==="primary"?"imageGen.primary.help":"imageGen.fallback.help"),children:e.jsxs(ge,{className:"w-48","data-testid":`image-gen-${s}`,value:n??"",onChange:x=>d(s,x.target.value),disabled:o,"aria-label":u,children:[s==="fallback"&&e.jsx("option",{value:"",children:t("imageGen.fallback.none")}),zu.filter(x=>x!==r).map(x=>e.jsx("option",{value:x,children:Et[x]},x))]})}),n&&e.jsx(qu,{slot:s,slotLabel:u,provider:n,model:a,openrouterModels:c,disabled:o,onModel:m})]})}function qu({slot:s,slotLabel:n,provider:a,model:i,openrouterModels:r,disabled:c,onModel:o}){const[d,m]=l.useState(null),{state:u}=G(),x=a==="custom"&&u.config?.imageGen?.customApi==="responses",g=(a==="openrouter"&&r?.source==="openrouter"?r.models:null)??(x?[{id:"gpt-6.1-sol",name:"GPT-6.1 Sol"},{id:"gpt-6-astra",name:"GPT-6 Astra"}]:Fu[a]).map(h=>({...h,group:"recommended"})),f=d!==null||g.length===0,y=()=>{d!==null&&(m(null),d.trim()&&d.trim()!==i&&o(d.trim()))},b=h=>{if(h===Zt)return m(i);m(null),o(h)};return e.jsx(de,{title:t("decider.model.label"),subtitle:a==="openrouter"&&r?.source==="builtin"?t("decider.model.builtinNote"):void 0,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[g.length>0&&e.jsxs(ge,{className:"w-64 max-w-full","data-testid":`image-gen-${s}-model`,value:f?Zt:i,onChange:h=>b(h.target.value),disabled:c,"aria-label":t("imageGen.model.label",{slot:n}),children:[!i&&e.jsx("option",{value:"",disabled:!0,children:t("imageGen.model.placeholder")}),i&&!g.some(h=>h.id===i)&&e.jsx("option",{value:i,children:i}),["recommended","more"].map(h=>{const k=g.filter(S=>S.group===h);return k.length>0&&e.jsx("optgroup",{label:t(h==="recommended"?"decider.model.recommended":"decider.model.more"),children:k.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))},h)}),e.jsx("option",{value:Zt,children:t("imageGen.model.other")})]}),f&&e.jsx("input",{value:d??i,onChange:h=>m(h.target.value),onBlur:y,onKeyDown:h=>h.key==="Enter"&&y(),disabled:c,placeholder:Ii[a]||t("imageGen.model.placeholder"),"aria-label":t("imageGen.model.idLabel",{slot:n}),autoComplete:"off",spellCheck:!1,className:z(gs,"w-64 max-w-full")})]})})}function Vu({provider:s,status:n}){const{dispatch:a}=G(),[i,r]=l.useState(""),[c,o]=l.useState(null),[d,m]=l.useState(!1),[u,x]=l.useState(null),[p,g]=l.useState(!1),[f,y]=l.useState(null),b=s==="openrouter"?[n?.primary,n?.fallback].filter(T=>T?.provider===s).map(T=>T?.model).join(" "):"",h=f?.models===b?f:null,k=T=>y(T&&{...T,models:b}),S=Hu(n,s),E=s==="openai"||s==="gemini"||s==="custom"?_u[s]:null,N=s==="xai"||s==="openrouter"?$u[s]:null,P=c??n?.customUrl??"",j=async T=>{m(!0),x(null),k(null);try{a({type:"configStatus",config:await T()}),r(""),o(null)}catch($){x($ instanceof Error?$.message:String($))}finally{m(!1)}},B=T=>j(async()=>s==="xai"||s==="openrouter"?Hl(s,T,!1):window.ogb?.setCredential&&E?window.ogb.setCredential(E.credential,T):M("/api/config",{method:"PUT",body:JSON.stringify(E.patch(T))})),v=()=>j(async()=>{const T=P.trim()?Du(P.trim()):"";return M("/api/config",{method:"PUT",body:JSON.stringify({imageGen:{customUrl:T}})})}),A=async()=>{g(!0),k(null);try{k(Ku(s,await M("/api/images/test",{method:"POST",body:JSON.stringify({provider:s})})))}catch(T){k({ok:!1,text:T instanceof Error?T.message:String(T)})}finally{g(!1)}};return e.jsxs(Y,{title:Et[s],children:[e.jsx(Ju,{configured:S,optional:s==="custom"}),N&&e.jsxs("p",{className:"mb-2 text-[12px] leading-relaxed text-ink-secondary",children:[t(N.note)," ",e.jsx("button",{type:"button",onClick:()=>a({type:"toggleAppSettings",open:!0,section:"connections"}),className:"cursor-pointer text-accent hover:underline",children:t("imageGen.key.manage")})]}),s==="custom"&&e.jsxs("div",{className:"mb-3 space-y-2",children:[e.jsx("label",{className:"block text-[13px] text-ink-secondary",children:t("imageGen.custom.api")}),e.jsxs(ge,{"aria-label":t("imageGen.custom.api"),value:n?.customApi??"images",disabled:d,onChange:T=>{j(()=>M("/api/config",{method:"PUT",body:JSON.stringify({imageGen:{customApi:T.target.value}})}))},children:[e.jsx("option",{value:"images",children:"Images API"}),e.jsx("option",{value:"responses",children:"Responses API · image_generation"})]}),e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("imageGen.custom.apiHelp")}),n?.customApi==="responses"&&e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-ink-secondary",children:[e.jsx("input",{type:"checkbox",checked:n.customLocalImageExtension===!0,disabled:d,onChange:T=>{j(()=>M("/api/config",{method:"PUT",body:JSON.stringify({imageGen:{customLocalImageExtension:T.target.checked}})}))}}),t("imageGen.custom.extension")]})]}),s==="custom"&&e.jsxs("div",{className:"mb-2 flex gap-2",children:[e.jsx("input",{type:"url",value:P,onChange:T=>o(T.target.value),onKeyDown:T=>T.key==="Enter"&&void v(),disabled:d,placeholder:"http://127.0.0.1:4000/v1","aria-label":t("imageGen.custom.url"),autoComplete:"off",className:gs}),e.jsxs("button",{type:"button",onClick:()=>{v()},disabled:d||c===null,className:At,children:[d?e.jsx(J,{size:13,className:"animate-spin"}):e.jsx(be,{size:13}),t("common.save")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"password",value:i,onChange:T=>r(T.target.value),onKeyDown:T=>T.key==="Enter"&&i.trim()&&void B(i.trim()),disabled:d,placeholder:S?t("keys.replace"):t("imageGen.key.paste"),"aria-label":t((E??N).label),autoComplete:"off",spellCheck:!1,className:gs}),e.jsxs("button",{type:"button",onClick:()=>{B(i.trim())},disabled:d||!i.trim(),className:At,children:[d?e.jsx(J,{size:13,className:"animate-spin"}):e.jsx(be,{size:13}),t("common.save")]}),S&&e.jsx("button",{type:"button",onClick:()=>{A()},disabled:p||d,className:"flex shrink-0 cursor-pointer items-center justify-center rounded-lg border border-hairline/40 px-3 py-2 text-[13px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:cursor-not-allowed disabled:opacity-50",children:p?t("keys.testing"):t("keys.test")})]}),h&&e.jsx("p",{role:"status",className:z("mt-1 text-[12px]",h.ok?"text-success":"text-danger"),children:h.text}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 text-[12px] text-ink-secondary",children:[Ln[s]?e.jsx("a",{href:Ln[s],target:"_blank",rel:"noreferrer",className:"text-accent hover:underline",children:t("imageGen.key.get")}):e.jsx("span",{children:t("imageGen.custom.help",{app:Ns()})}),S&&e.jsx("button",{type:"button",onClick:()=>{B("")},disabled:d,className:"cursor-pointer hover:text-danger disabled:opacity-50",children:t("keys.removeKey")})]}),u&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:u})]})}function Ju({configured:s,optional:n=!1}){return e.jsxs("div",{role:"status",className:"mb-2 flex items-center gap-2 text-[13px] text-ink-secondary",children:[e.jsx("span",{className:z("size-1.5 rounded-full",s?"bg-success":"bg-raised-hover")}),e.jsx("span",{className:s?"text-success":void 0,children:t(s?"imageGen.key.saved":n?"imageGen.key.optional":"imageGen.key.missing")})]})}function es(s){if(s.readOnly||s.trialCredit||s.access==="custom"||s.access==="api")return null;if(s.driverKind==="claudeAgent")return"claude";const n=s.authentication?.method;return s.snapshot.chatgptPlan===!0||(n==="device-code"||n==="browser-pkce")&&Oa(s.driverKind)==="codex"?"chatgpt":null}function Ms(s){return s.snapshot.state!=="available"?"unavailable":s.snapshot.authenticated===!0?"signedIn":s.snapshot.authenticated===!1?"signedOut":"unknown"}const zs={claude:{title:"accounts.claude",add:"accounts.addClaude",removeBody:"accounts.removeBodyClaude"},chatgpt:{title:"accounts.chatgpt",add:"accounts.addChatgpt",removeBody:"accounts.removeBodyChatgpt"}};function Xu(s,n){return{signOut:Ms(n)==="signedIn"&&n.authentication?.signOut===!0&&n.snapshot.account?.method!=="api-key",remove:s==="claude"?n.instanceId!=="claude"&&n.claudeAccount?.isDefault!==!0:n.instanceId.startsWith("chatgpt-")}}function Pi(s){return s.some(Le)}function Yu(s,n){const a=n.filter(o=>Ms(o)==="signedIn"),i=Pi(n),r=n.some(o=>o.snapshot.state==="available"),c=n.length>1?t("accounts.count",{count:String(n.length),signedIn:String(a.length)}):a[0]?.snapshot.account?.email??Jl(n[0]);return{title:t(zs[s].title),subtitle:c,ready:i,status:i?t("onboarding.engines.ready"):r?t("model.signInRequired"):t("onboarding.engines.needsSetup"),action:i?t("engines.library.manage"):r?t("accounts.signIn"):t("engines.library.setup")}}function Qu({group:s,instance:n,onRename:a}){const{state:i,dispatch:r,refreshInstances:c}=G(),[o,d]=l.useState(!1),[m,u]=l.useState(null),[x,p]=l.useState(!1),[g,f]=l.useState(null),y=l.useRef(null),{signOut:b,remove:h}=Xu(s,n),k=i.bots.filter(N=>N.modelSelection.instanceId===n.instanceId).length;l.useEffect(()=>{if(!o)return;const N=j=>{j.key==="Escape"&&(j.stopPropagation(),d(!1))},P=j=>{j.target instanceof Node&&!y.current?.contains(j.target)&&d(!1)};return window.addEventListener("keydown",N,!0),window.addEventListener("pointerdown",P),()=>{window.removeEventListener("keydown",N,!0),window.removeEventListener("pointerdown",P)}},[o]);const S=async N=>{u(null),p(!0),f(null);try{const P=`/api/instances/${encodeURIComponent(n.instanceId)}${N==="signOut"?"/auth/sign-out":""}`,{instances:j}=await M(P,N==="signOut"?{method:"POST"}:{method:"DELETE"});Array.isArray(j)?r({type:"instances",instances:j}):await c().catch(()=>{})}catch(P){f(P instanceof Error?P.message:String(P))}finally{p(!1)}},E="ui-menu-row w-full text-left disabled:cursor-not-allowed disabled:opacity-50";return e.jsxs("div",{ref:y,className:"relative flex items-center gap-1",children:[h&&e.jsx("button",{type:"button",disabled:x||k>0,onClick:()=>u("remove"),title:k>0?t("accounts.inUse",{count:String(k)}):void 0,className:"rounded-lg px-2.5 py-1.5 text-[12px] font-medium text-danger hover:bg-danger/10 disabled:cursor-not-allowed disabled:opacity-50",children:t("accounts.remove")}),e.jsx("button",{type:"button",onClick:()=>d(N=>!N),disabled:x,"aria-haspopup":"menu","aria-expanded":o,"aria-label":t("accounts.menu",{name:_e(n)}),className:"flex size-8 items-center justify-center rounded-lg text-ink-secondary outline-none hover:bg-control hover:text-ink focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50",children:x?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(cl,{size:16})}),o&&e.jsxs("div",{role:"menu",className:z("absolute right-0 top-full z-40 mt-1 w-[220px] overflow-hidden text-[13px]",dl),children:[e.jsx("button",{type:"button",role:"menuitem",className:z(E,"text-ink"),onClick:()=>{d(!1),a()},children:t("accounts.rename")}),b&&e.jsx("button",{type:"button",role:"menuitem",className:z(E,"text-ink"),onClick:()=>{d(!1),u("signOut")},children:t("accounts.signOut")}),h&&k>0&&e.jsx("p",{className:"px-3 pb-1 pt-0.5 text-[11px] leading-snug text-ink-secondary",children:t("accounts.inUse",{count:String(k)})})]}),g&&e.jsx("p",{role:"alert",className:"absolute right-0 top-full z-30 mt-1 w-[260px] rounded-lg bg-card p-2 text-[12px] text-danger shadow-lg",children:g}),e.jsx(Qe,{open:m==="signOut",title:t("accounts.signOutTitle",{name:_e(n)}),body:t("accounts.signOutBody"),confirmLabel:t("accounts.signOut"),onCancel:()=>u(null),onConfirm:()=>{S("signOut")}}),e.jsx(Qe,{open:m==="remove",title:t("accounts.removeTitle",{name:_e(n)}),body:t(zs[s].removeBody),confirmLabel:t("accounts.remove"),tone:"neutral",onCancel:()=>u(null),onConfirm:()=>{S("remove")}})]})}function Zu({instance:s,onDone:n}){const{dispatch:a}=G(),[i,r]=l.useState(_e(s)),[c,o]=l.useState(!1),[d,m]=l.useState(null),u=async()=>{const x=i.trim();if(!x||x===_e(s))return n();o(!0),m(null);try{const{instances:p}=await M(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"PATCH",body:JSON.stringify({displayName:x})});Array.isArray(p)&&a({type:"instances",instances:p}),n()}catch(p){m(p instanceof Error?p.message:String(p))}finally{o(!1)}};return e.jsxs("form",{className:"flex min-w-0 flex-1 flex-col gap-1",onSubmit:x=>{x.preventDefault(),u()},children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:i,onChange:x=>r(x.target.value),maxLength:80,autoFocus:!0,disabled:c,"aria-label":t("accounts.nameLabel"),onKeyDown:x=>{x.key==="Escape"&&(x.stopPropagation(),n())},className:"min-w-0 flex-1 rounded-lg border border-hairline/40 bg-inset px-2.5 py-1.5 text-[13px] text-ink outline-none focus:border-accent-border disabled:opacity-50"}),e.jsx("button",{type:"submit",disabled:c||!i.trim(),className:"rounded-lg bg-raised px-3 py-1.5 text-[12px] font-medium text-ink hover:bg-raised-hover disabled:opacity-50",children:c?e.jsx(J,{size:13,className:"animate-spin"}):t("common.save")}),e.jsx("button",{type:"button",onClick:n,disabled:c,className:"rounded-lg px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-control",children:t("common.cancel")})]}),d&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:d})]})}function em({group:s,instance:n,signingIn:a,onSignIn:i,onSignInDone:r}){const[c,o]=l.useState(!1),d=Ms(n),m=n.snapshot.account,u=n.snapshot.authenticationUnavailableReason,x=u&&d!=="signedIn"?u:d==="signedIn"?m?.method==="api-key"?t("accounts.apiKey"):[m?.email,m?.organization].filter(Boolean).join(" · ")||t("accounts.signedIn"):d==="signedOut"?t("accounts.notSignedIn"):d==="unknown"?t("accounts.unknown"):n.snapshot.reason??t("onboarding.engines.needsSetup");return e.jsxs("li",{"data-account":n.instanceId,"data-account-state":d,className:"px-3 py-2.5",children:[e.jsxs("div",{className:"flex min-h-9 items-center gap-3",children:[e.jsx("span",{"aria-hidden":"true",className:z("flex size-6 shrink-0 items-center justify-center rounded-full",d==="signedIn"?"bg-success/15 text-success":"bg-control text-ink-secondary"),children:d==="signedIn"?e.jsx(be,{size:13}):e.jsx("span",{className:z("size-1.5 rounded-full",d==="signedOut"?"bg-warning":"bg-ink-tertiary")})}),c?e.jsx(Zu,{instance:n,onDone:()=>o(!1)}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] font-medium text-ink",title:_e(n),children:_e(n)}),e.jsx("div",{className:"truncate text-[12px] text-ink-secondary",title:x,children:x})]}),d!=="signedIn"&&d!=="unavailable"&&!u&&!a&&e.jsx("button",{type:"button",onClick:i,className:z("shrink-0 rounded-lg px-3 py-1.5 text-[12px] font-semibold",d==="signedOut"?"bg-accent text-white hover:brightness-110":"bg-control text-ink hover:bg-raised-hover"),children:t("accounts.signIn")}),e.jsx(Qu,{group:s,instance:n,onRename:()=>o(!0)})]})]}),a&&e.jsx("div",{className:"pl-9",children:s==="claude"?e.jsxs(e.Fragment,{children:[e.jsx(Wl,{instanceId:n.instanceId,autoStart:!0,onDone:r}),n.claudeAccount?.signInCommand&&e.jsxs("details",{className:"mt-2 text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"cursor-pointer select-none hover:text-ink",children:t("engineSetup.preferTerminal")}),e.jsx(Gl,{command:n.claudeAccount.signInCommand,actionLabel:t("engineSetup.openSignIn"),compact:!0})]})]}):e.jsx(ql,{instanceId:n.instanceId,provider:"codex",browserPkce:n.authentication?.method==="browser-pkce",autoStart:!0,onDone:r})}),s==="chatgpt"&&d==="signedIn"&&n.snapshot.chatgptPlan&&e.jsx("div",{className:"pl-9",children:e.jsx(Vl,{instanceId:n.instanceId,welcome:!1})})]})}function Ti({label:s,endpoint:n,extra:a,folder:i=!1,describedBy:r,onAdded:c}){const{dispatch:o}=G(),[d,m]=l.useState(!1),[u,x]=l.useState(""),[p,g]=l.useState(""),[f,y]=l.useState(!1),[b,h]=l.useState(null),k=async()=>{if(!(f||!u.trim())){y(!0),h(null);try{const S={displayName:u.trim(),...a,...i&&p.trim()?{configDir:p.trim()}:{}},E=await M(n,{method:"POST",body:JSON.stringify(S)});Array.isArray(E.instances)&&o({type:"instances",instances:E.instances}),m(!1),x(""),g(""),typeof E.instanceId=="string"&&c(E.instanceId)}catch(S){h(S instanceof Error?S.message:String(S))}finally{y(!1)}}};return d?e.jsxs("form",{"data-add-account":n,className:"space-y-2.5 rounded-xl border border-hairline/50 bg-app p-3",onSubmit:S=>{S.preventDefault(),k()},children:[e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("accounts.nameLabel"),e.jsx("input",{value:u,onChange:S=>x(S.target.value),placeholder:t("accounts.namePlaceholder"),maxLength:80,autoFocus:!0,required:!0,disabled:f,"aria-describedby":r,className:"rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] font-normal text-ink outline-none focus:border-accent-border disabled:opacity-50"})]}),i&&e.jsxs("details",{className:"text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"cursor-pointer select-none hover:text-ink",children:t("accounts.folderToggle")}),e.jsx("input",{value:p,onChange:S=>g(S.target.value),placeholder:"~/.claude-work",maxLength:4096,spellCheck:!1,disabled:f,"aria-label":t("accounts.folderToggle"),className:"mt-2 w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 font-mono text-[12px] text-ink outline-none focus:border-accent-border disabled:opacity-50"}),e.jsx("p",{className:"mt-1 leading-relaxed",children:t("accounts.folderHint")})]}),b&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:b}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>{m(!1),h(null)},disabled:f,className:"rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-control disabled:opacity-50",children:t("common.cancel")}),e.jsxs("button",{type:"submit",disabled:f||!u.trim(),className:"flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-[12px] font-semibold text-white hover:brightness-110 disabled:opacity-50",children:[f&&e.jsx(J,{size:13,className:"animate-spin"}),t("accounts.addSubmit")]})]})]}):e.jsxs("button",{type:"button",onClick:()=>m(!0),"aria-describedby":r,className:"flex min-h-8 w-fit items-center gap-1.5 rounded-lg px-2 py-1.5 text-[13px] font-medium text-ink-secondary outline-none hover:bg-control hover:text-ink focus-visible:ring-2 focus-visible:ring-accent",children:[e.jsx(we,{size:14}),s]})}function tm({group:s,accounts:n,advanced:a,bare:i=!1}){const[r,c]=l.useState(null),o=n[0],d=n.some(x=>x.snapshot.state==="available"),m=n.find(x=>x.policy)?.policy,u=l.useId();return e.jsxs(Nt,{instance:o,summary:Yu(s,n),bare:i,children:[m&&e.jsxs("p",{className:"mb-3 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx("span",{className:"font-medium text-ink",children:t("policy.managedBy",{organization:m.organizationName})})," · ",m.reason]}),d?e.jsxs("div",{className:"space-y-2",children:[e.jsx("ul",{"data-accounts":s,className:"divide-y divide-hairline/40 rounded-xl border border-hairline/50 bg-panel/40",children:n.map(x=>e.jsx(em,{group:s,instance:x,signingIn:r===x.instanceId,onSignIn:()=>c(x.instanceId),onSignInDone:()=>c(p=>p===x.instanceId?null:p)},x.instanceId))}),!o.snapshot.authenticationUnavailableReason&&e.jsxs(e.Fragment,{children:[e.jsx(Ti,{label:t(zs[s].add),endpoint:`/api/instances/${s}-accounts`,folder:s==="claude",describedBy:s==="chatgpt"?u:void 0,onAdded:c}),s==="chatgpt"&&e.jsx("p",{id:u,className:"px-2 text-[12px] leading-relaxed text-ink-secondary",children:t("accounts.addChatgptWorkspaceNote")})]})]}):e.jsx(Mt,{instance:o,unframed:!0}),o.snapshot.update&&e.jsx(Ma,{update:o.snapshot.update,instance:o,className:"mt-3",quiet:!0}),o.snapshot.warning&&e.jsx(za,{warning:o.snapshot.warning,className:"mt-3"}),a]})}const at=z(Be,"font-sans"),sm={opusModel:"global.anthropic.claude-opus-5-5",sonnetModel:"global.anthropic.claude-sonnet-5-5",haikuModel:"global.anthropic.claude-haiku-5-5",smallFastModel:"global.anthropic.claude-haiku-5-5"},On=["opusModel","sonnetModel","haikuModel","smallFastModel"],nm={name:"Claude on Bedrock",awsProfile:"default",awsRegion:"",model:"",opusModel:"",sonnetModel:"",haikuModel:"",smallFastModel:""},am=s=>{const n=s.claudeBedrock;return{name:s.displayName,awsProfile:n?.awsProfile||"default",awsRegion:n?.awsRegion??"",model:n?.model??"",opusModel:n?.opusModel??"",sonnetModel:n?.sonnetModel??"",haikuModel:n?.haikuModel??"",smallFastModel:n?.smallFastModel??""}},Mn={opusModel:"claudeBedrock.opus",sonnetModel:"claudeBedrock.sonnet",haikuModel:"claudeBedrock.haiku",smallFastModel:"claudeBedrock.smallFast"};function zn({instance:s,onDone:n}){const{dispatch:a}=G(),[i,r]=l.useState(s?am(s):nm),[c,o]=l.useState(!1),[d,m]=l.useState(null),u=g=>({value:i[g],onChange:f=>r(y=>({...y,[g]:f.target.value})),spellCheck:!1,disabled:c}),x=!!(i.name.trim()&&i.awsProfile.trim()&&i.awsRegion.trim()&&i.model.trim()),p=async()=>{if(c||!x)return;o(!0),m(null);const g={displayName:i.name.trim(),awsProfile:i.awsProfile.trim(),awsRegion:i.awsRegion.trim(),model:i.model.trim(),...Object.fromEntries(On.map(f=>[f,i[f].trim()]))};try{const f=s?await M(`/api/instances/${encodeURIComponent(s.instanceId)}/claude-bedrock`,{method:"PATCH",body:JSON.stringify(g)}):await M("/api/instances/claude-bedrock",{method:"POST",body:JSON.stringify(g)});Array.isArray(f.instances)&&a({type:"instances",instances:f.instances}),n()}catch(f){m(f instanceof Error&&f.message?f.message:t("claudeBedrock.failed"))}finally{o(!1)}};return e.jsxs("form",{"data-claude-bedrock-form":s?.instanceId??"new",className:"flex flex-col gap-2 rounded-xl border border-hairline/50 bg-inset p-3",onSubmit:g=>{g.preventDefault(),p()},children:[e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("claudeBedrock.awsHint")}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeBedrock.name"),e.jsx("input",{...u("name"),maxLength:80,autoFocus:!0,"aria-label":t("claudeBedrock.name"),className:at})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeBedrock.profile"),e.jsx("input",{...u("awsProfile"),maxLength:128,placeholder:"default","aria-label":t("claudeBedrock.profile"),className:z(at,"font-mono")})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeBedrock.region"),e.jsx("input",{...u("awsRegion"),maxLength:32,placeholder:"us-east-1","aria-label":t("claudeBedrock.region"),className:z(at,"font-mono")})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeBedrock.model"),e.jsx("input",{...u("model"),maxLength:160,placeholder:"global.anthropic.claude-sonnet-5-5","aria-label":t("claudeBedrock.model"),className:z(at,"font-mono")})]}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("claudeBedrock.modelHint")}),e.jsxs("details",{className:"rounded-lg border border-hairline/40 px-2.5 py-2",children:[e.jsx("summary",{className:"cursor-pointer text-[12px] font-medium text-ink-secondary outline-none hover:text-ink",children:t("claudeBedrock.tiers")}),e.jsx("div",{className:"mt-2 flex flex-col gap-2",children:On.map(g=>e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t(Mn[g]),e.jsx("input",{...u(g),maxLength:160,placeholder:sm[g],"aria-label":t(Mn[g]),className:z(at,"font-mono")})]},g))})]}),d&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:d}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:n,disabled:c,className:"rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-control disabled:opacity-50",children:t("common.cancel")}),e.jsxs("button",{type:"submit",disabled:c||!x,className:"flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-[12px] font-semibold text-white hover:brightness-110 disabled:opacity-50",children:[c&&e.jsx(J,{size:13,className:"animate-spin"}),t("common.save")]})]})]})}function im({instance:s,onEdit:n}){const{state:a,dispatch:i}=G(),[r,c]=l.useState(!1),[o,d]=l.useState(!1),[m,u]=l.useState(null),x=a.bots.filter(f=>f.modelSelection.instanceId===s.instanceId||f.fallback?.some(y=>y.instanceId===s.instanceId)||f.tasks?.some(y=>y.modelSelection?.instanceId===s.instanceId)).length,p=s.claudeBedrock,g=async()=>{c(!1),d(!0),u(null);try{const f=await M(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"DELETE"});Array.isArray(f.instances)&&i({type:"instances",instances:f.instances})}catch(f){u(f instanceof Error?f.message:String(f))}finally{d(!1)}};return e.jsxs("li",{"data-claude-bedrock":s.instanceId,className:"px-3 py-2.5",children:[e.jsxs("div",{className:"flex min-h-9 items-center gap-3",children:[e.jsx(Ua,{preset:"aws",size:16,className:"shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] font-medium text-ink",title:s.displayName,children:s.displayName}),e.jsx("div",{className:"truncate font-mono text-[11px] text-ink-secondary",children:t("claudeBedrock.rowSubtitle",{profile:p?.awsProfile??"",region:p?.awsRegion??""})})]}),e.jsx("button",{type:"button",onClick:n,disabled:o,className:"shrink-0 rounded-lg px-2.5 py-1.5 text-[12px] font-medium text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50",children:t("claudeBedrock.edit")}),e.jsx("button",{type:"button",disabled:o||x>0,onClick:()=>c(!0),title:x>0?t("accounts.inUse",{count:String(x)}):t("accounts.remove"),"aria-label":t("claudeBedrock.remove",{name:s.displayName}),className:"flex size-8 shrink-0 items-center justify-center rounded-lg text-danger hover:bg-danger/10 disabled:cursor-not-allowed disabled:opacity-50",children:o?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(Se,{size:14})})]}),m&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:m}),e.jsx(Qe,{open:r,title:t("accounts.removeTitle",{name:s.displayName}),body:t("claudeBedrock.removeBody"),confirmLabel:t("accounts.remove"),tone:"neutral",pending:o,onCancel:()=>c(!1),onConfirm:()=>{g()}})]})}function ts(){const{state:s}=G(),n=s.instances.filter(r=>r.claudeBedrock),[a,i]=l.useState(null);return e.jsxs("div",{"data-claude-bedrock-endpoints":"",className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-[13px] leading-[18px] text-ink",children:t("claudeBedrock.title")}),e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("claudeBedrock.hint")}),n.length===0?e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("claudeBedrock.empty")}):e.jsx("ul",{className:"divide-y divide-hairline/40 rounded-xl border border-hairline/50 bg-panel/40",children:n.map(r=>a===r.instanceId?e.jsx("li",{className:"p-3",children:e.jsx(zn,{instance:r,onDone:()=>i(null)})},r.instanceId):e.jsx(im,{instance:r,onEdit:()=>i(r.instanceId)},r.instanceId))}),a==="new"?e.jsx(zn,{onDone:()=>i(null)}):e.jsxs("button",{type:"button",onClick:()=>i("new"),className:"flex min-h-8 w-fit items-center gap-1.5 rounded-lg px-2 py-1.5 text-[13px] font-medium text-ink-secondary outline-none hover:bg-control hover:text-ink focus-visible:ring-2 focus-visible:ring-accent",children:[e.jsx(we,{size:14}),t("claudeBedrock.add")]})]})}function Un(s){const n=s/1048576;return n<1?t("engines.freeSpace.underOneMb"):n<1024?`${Math.round(n)} MB`:`${(n/1024).toFixed(1)} GB`}function rm({instance:s,initial:n={kind:"idle"}}){const[a,i]=l.useState(n),[r,c]=l.useState(null),o=`/api/instances/${encodeURIComponent(s.instanceId)}/leftover-files`,d=async()=>{c(null),i({kind:"scanning"});try{const x=await M(o);i(x.folders>0?{kind:"found",bytes:x.bytes,complete:x.complete}:{kind:"none"})}catch(x){c(x instanceof Error?x.message:String(x)),i({kind:"idle"})}},m=async()=>{c(null),i({kind:"deleting"});try{const x=await M(`${o}/remove`,{method:"POST",body:JSON.stringify({})});i({kind:"done",freedBytes:x.freedBytes,remaining:x.remaining})}catch(x){c(x instanceof Error?x.message:String(x)),i({kind:"idle"})}},u=a.kind==="scanning"||a.kind==="deleting";return e.jsxs("section",{className:"mt-3 rounded-xl border border-hairline/40 px-3 py-2.5","aria-label":t("engines.freeSpace.title"),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ul,{size:13,"aria-hidden":"true",className:"shrink-0 text-ink-secondary"}),e.jsx("span",{className:"text-[12px] font-medium text-ink",children:t("engines.freeSpace.title")}),e.jsx("span",{className:"flex-1"}),(a.kind==="idle"||a.kind==="none"||a.kind==="done"||u)&&e.jsxs("button",{type:"button",onClick:()=>{d()},disabled:u,className:"flex shrink-0 items-center gap-1 rounded-lg border border-hairline/40 px-3 py-1 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:opacity-50",children:[u&&e.jsx(J,{size:12,className:"animate-spin"}),t("engines.freeSpace.action")]})]}),e.jsx("p",{className:"mt-1.5 text-[12px] leading-relaxed text-ink-secondary",children:t("engines.freeSpace.intro")}),a.kind==="scanning"&&e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t("engines.freeSpace.scanning")}),a.kind==="deleting"&&e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t("engines.freeSpace.deleting")}),a.kind==="none"&&e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t("engines.freeSpace.none")}),a.kind==="found"&&e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx("p",{role:"status",className:"flex-1 text-[12px] text-ink",children:t(a.complete?"engines.freeSpace.found":"engines.freeSpace.foundAtLeast",{size:Un(a.bytes)})}),e.jsx("button",{type:"button",onClick:()=>i({kind:"idle"}),className:"rounded-lg px-3 py-1 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink",children:t("common.cancel")}),e.jsx("button",{type:"button",onClick:()=>{m()},className:"rounded-lg bg-raised px-3 py-1 text-[12px] text-ink hover:bg-raised-hover",children:t("engines.freeSpace.delete")})]}),a.kind==="done"&&e.jsxs("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:[(a.freedBytes>0||a.remaining===0)&&e.jsxs("span",{className:"text-success",children:[t("engines.freeSpace.freed",{size:Un(a.freedBytes)})," "]}),a.remaining>0&&t("engines.freeSpace.someLeft")]}),r&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:r})]})}const ss=[60,120,180,360,720];function Ri(){const{state:s,dispatch:n}=G(),[a,i]=l.useState(!1),[r,c]=l.useState(""),o=l.useRef(!1),d=s.config?.cacheKeepWarm;if(!d)return null;const m=async x=>{if(!o.current){o.current=!0,i(!0),c("");try{const p=await M("/api/config",{method:"PUT",body:JSON.stringify({cacheKeepWarm:{enabled:x.enabled,windowMinutes:x.windowMinutes}})});n({type:"configStatus",config:p})}catch(p){c(p instanceof Error?p.message:t("settings.keepWarm.error"))}finally{o.current=!1,i(!1)}}},u=ss.includes(d.windowMinutes)?[...ss]:[...ss,d.windowMinutes].sort((x,p)=>x-p);return e.jsxs(Y,{title:t("settings.keepWarm.title"),subtitle:t("settings.keepWarm.subtitle"),children:[e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-4",children:[e.jsx("label",{htmlFor:"cache-keepwarm-enabled",className:"text-[13px] font-medium text-ink",children:t("settings.keepWarm.enable")}),e.jsx(me,{id:"cache-keepwarm-enabled",checked:d.enabled,disabled:a,"aria-describedby":"cache-keepwarm-help cache-keepwarm-cost",onClick:()=>{m({...d,enabled:!d.enabled})}})]}),e.jsx("p",{id:"cache-keepwarm-help",className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("settings.keepWarm.help")}),e.jsx("p",{id:"cache-keepwarm-cost",className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("settings.keepWarm.cost")}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-4",children:[e.jsx("label",{htmlFor:"cache-keepwarm-window",className:"text-[13px] font-medium text-ink",children:t("settings.keepWarm.window")}),e.jsx(ge,{id:"cache-keepwarm-window",value:d.windowMinutes,disabled:a||!d.enabled,onChange:x=>{m({...d,windowMinutes:Number(x.target.value)})},children:u.map(x=>e.jsx("option",{value:x,children:t("settings.keepWarm.hours",{hours:Number((x/60).toFixed(2))})},x))})]}),a&&e.jsx("span",{role:"status",className:"sr-only",children:t("settings.threads.saving")}),r&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:r})]})}function lm({instance:s,cliDefault:n,onClose:a,onSaved:i}){const[r,c]=l.useState(s.cliCandidates??null),[o,d]=l.useState(""),[m,u]=l.useState(s.cli&&!(s.cliCandidates??[]).includes(s.cli)?s.cli:""),[x,p]=l.useState(!1),[g,f]=l.useState(null),[y,b]=l.useState(!1),[h,k]=l.useState(null),S=l.useRef(!1);l.useEffect(()=>{S.current||(S.current=!0,M(`/api/cli-candidates?name=${encodeURIComponent(n??"")}`).then(({candidates:v})=>{c(v),s.cli&&(v.includes(s.cli)?d(s.cli):u(s.cli))}).catch(()=>c(v=>v??[])))},[n,s.cli]);const E=m.trim()||o,N=E!==(s.cli??""),P=x||y;l.useEffect(()=>{f(null)},[E]);const j=()=>{if(P||!E||!N)return;b(!0),k(null);const v=E;M(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"PATCH",body:JSON.stringify({cli:v})}).then(()=>Promise.resolve(i()).catch(()=>{})).then(a).catch(A=>k(A.message)).finally(()=>b(!1))},B=()=>{P||!E||!N||(p(!0),k(null),M("/api/cli-test",{method:"POST",body:JSON.stringify({cli:E,driver:s.driverKind})}).then(v=>{f(v),v.ok&&j()}).catch(v=>k(v.message)).finally(()=>p(!1)))};return e.jsxs("div",{className:"mt-2.5 flex flex-col gap-2",children:[r!==null&&r.length>0&&e.jsxs(ge,{className:"w-full font-mono",value:m.trim()?"":o,onChange:v=>{d(v.target.value),u("")},"aria-label":t("engines.detectedAria",{name:s.displayName}),disabled:P,children:[e.jsx("option",{value:"",children:t("engines.selectBinary")}),r.map(v=>e.jsx("option",{value:v,children:v},v))]}),e.jsx("input",{type:"text",value:m,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),!(!E||!N)&&B())},placeholder:r?.length?t("engines.manualPath"):"/absolute/path/to/cli","aria-label":t("engines.customAria",{name:s.displayName}),spellCheck:!1,disabled:P,className:"w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 font-mono text-[12px] text-ink placeholder:font-sans placeholder:text-ink-secondary focus:outline-none disabled:opacity-50"}),g&&!g.ok&&g.message&&e.jsxs("div",{role:"alert",className:"flex gap-1.5 rounded-lg border border-warning/25 bg-warning/10 px-2.5 py-2 text-[12px] leading-relaxed text-warning",children:[e.jsx(Oe,{size:13,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:t("engines.testFailed",{message:g.message})})]}),g?.ok&&g.version&&e.jsx("div",{className:"text-[12px] text-success",children:t("engines.testPassed",{version:g.version})}),h&&e.jsx("div",{role:"alert",className:"text-[12px] text-danger",children:h}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:a,disabled:P,className:"rounded-lg px-3 py-1.5 text-[13px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:opacity-50",children:t("common.cancel")}),g&&!g.ok?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>f(null),disabled:P,className:"rounded-lg px-3 py-1.5 text-[13px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:opacity-50",children:t("engines.editPath")}),e.jsx("button",{onClick:()=>j(),disabled:P,className:"flex items-center gap-1.5 rounded-lg bg-raised px-3 py-1.5 text-[13px] text-danger hover:bg-raised-hover disabled:opacity-50",children:y?e.jsx(J,{size:13,className:"animate-spin"}):t("engines.saveAnyway")})]}):e.jsx("button",{onClick:B,disabled:P||!E||!N,className:z("flex w-[72px] items-center justify-center gap-1.5 rounded-lg py-1.5 text-[13px]","bg-raised text-ink hover:bg-raised-hover","disabled:cursor-not-allowed disabled:opacity-50"),children:P?e.jsx(J,{size:13,className:"animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:13}),t("common.save")]})})]})]})}function Li({instance:s}){const{refreshInstances:n}=G(),[a,i]=l.useState(!1),r=md(a),[c,o]=l.useState(!1),[d,m]=l.useState(!1),[u,x]=l.useState(null),[p,g]=l.useState(null),f=l.useRef(null);l.useEffect(()=>{f.current!==null&&f.current!==s.cli&&i(!1),f.current=s.cli??null},[s.cli]);const y=()=>{c||d||(o(!0),g(null),M(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"PATCH",body:JSON.stringify({cli:""})}).then(()=>Promise.resolve(n()).catch(()=>{})).catch(k=>g(k.message)).finally(()=>o(!1)))},b=()=>{c||d||(o(!0),g(null),M(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"PATCH",body:JSON.stringify({hidden:!0})}).then(()=>Promise.resolve(n()).catch(()=>{})).catch(k=>g(k.message)).finally(()=>o(!1)))},h=()=>{c||d||(m(!0),x(null),g(null),M(`/api/instances/${encodeURIComponent(s.instanceId)}/claude-update`,{method:"POST",body:JSON.stringify({})}).then(async({version:k})=>{x(k),await Promise.resolve(n()).catch(()=>{})}).catch(k=>g(k.message)).finally(()=>m(!1)))};return e.jsxs("details",{className:"mt-4 border-t border-hairline/40 pt-3",children:[e.jsx("summary",{className:"cursor-pointer rounded-md py-1 text-[12px] font-medium text-ink-secondary outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-accent",children:t("engines.library.advanced")}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("engines.footer")}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-[13px]",children:[s.cli?e.jsx("span",{className:"w-full break-all font-mono text-[12px] text-ink-secondary",title:s.cli,children:s.cli}):s.cliDefault&&e.jsx("span",{className:"break-all font-mono text-[11px] text-ink-secondary",children:s.cliDefault}),s.snapshot.version&&e.jsx("span",{className:"break-all text-[11px] text-ink-secondary",title:s.snapshot.version,children:s.snapshot.version}),e.jsx("span",{className:"flex-1"}),s.driverKind==="claudeAgent"&&e.jsxs("button",{onClick:h,disabled:c||d,className:"flex shrink-0 items-center gap-1 text-[12px] text-ink-secondary hover:text-ink disabled:opacity-50",children:[d?e.jsx(J,{size:12,className:"animate-spin"}):e.jsx(Ae,{size:12}),d?t("engines.updating"):t("engines.updateClaude")]}),s.cli&&e.jsx("button",{onClick:y,disabled:c||d,className:"shrink-0 text-[12px] text-ink-secondary hover:text-ink disabled:opacity-50",children:c?t("engines.resetting"):t("engines.reset")}),e.jsx("button",{type:"button","data-hide-engine":s.instanceId,onClick:b,disabled:c||d,title:t("engines.hideHint"),className:"shrink-0 text-[12px] text-ink-secondary hover:text-ink disabled:opacity-50",children:t("engines.hide")}),e.jsx("button",{onClick:()=>i(k=>!k),disabled:d,"aria-expanded":a,className:z("shrink-0 rounded-lg border border-hairline/40 px-3 py-1 text-[12px]",a?"bg-accent/15 text-accent":"text-ink-secondary hover:bg-raised/50 hover:text-ink","disabled:opacity-50"),children:t("engines.setCli")})]}),u&&e.jsx("div",{role:"status",className:"mt-1 text-[12px] text-success",children:t("engines.claudeUpdated",{version:u})}),p&&e.jsx("div",{role:"alert",className:"mt-1 text-[12px] text-danger",children:p}),r.shown&&e.jsx("div",{className:r.className,...r.exitProps,children:e.jsx(lm,{instance:s,cliDefault:s.cliDefault,onClose:()=>i(!1),onSaved:n})})]})}function Fn({instance:s,action:n}){const{state:a,dispatch:i,refreshInstances:r}=G(),[c,o]=l.useState(!1),[d,m]=l.useState(!1),[u,x]=l.useState(null),p=n==="remove",g=p?a.bots.filter(b=>b.modelSelection.instanceId===s.instanceId).length:0,f=t(p?"accounts.remove":"accounts.signOut"),y=async()=>{o(!1),m(!0),x(null);try{const b=`/api/instances/${encodeURIComponent(s.instanceId)}${p?"":"/auth/sign-out"}`,{instances:h}=await M(b,{method:p?"DELETE":"POST"});Array.isArray(h)?i({type:"instances",instances:h}):await r()}catch(b){x(b instanceof Error?b.message:String(b))}finally{m(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",disabled:d||g>0,onClick:()=>o(!0),className:z("rounded-lg px-2.5 py-1.5 text-[12px] font-medium disabled:cursor-not-allowed disabled:opacity-50",p?"text-danger hover:bg-danger/10":"text-ink-secondary hover:bg-raised hover:text-ink"),children:d?e.jsx(J,{size:13,className:"animate-spin"}):f}),g>0&&e.jsx("p",{className:"text-[11px] text-ink-secondary",children:t("accounts.inUse",{count:String(g)})})]}),u&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:u}),e.jsx(Qe,{open:c,title:t(p?"accounts.removeTitle":"accounts.signOutTitle",{name:s.displayName}),body:t(p?"accounts.removeBodyAntigravity":"accounts.signOutBody"),confirmLabel:f,tone:"neutral",pending:d,onCancel:()=>{d||o(!1)},onConfirm:()=>{y()}})]})}function om({source:s}){const{state:n}=G(),[a,i]=l.useState(null),r=a?n.instances.find(c=>c.instanceId===a&&c.snapshot.authenticated!==!0):void 0;return e.jsxs(e.Fragment,{children:[e.jsx(Ti,{label:t("engineSetup.antigravity.addAccount"),endpoint:"/api/instances/antigravity-accounts",extra:{sourceInstanceId:s.instanceId},onAdded:i}),r&&e.jsx("div",{"data-antigravity-added":r.instanceId,children:e.jsx(Mt,{instance:r,unframed:!0})})]})}function cm({instance:s,bare:n=!1}){const a=s.policy&&e.jsxs("p",{className:"mb-2 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx("span",{className:"font-medium text-ink",children:t("policy.managedBy",{organization:s.policy.organizationName})})," · ",s.policy.reason]});return s.trialCredit?e.jsx(Nt,{instance:s,bare:n,children:e.jsx("p",{"data-trial-credit":s.trialCredit,className:"text-[13px] leading-relaxed text-ink-secondary",children:t(s.trialCredit==="used_up"?"engines.trialCreditUsedUp":s.trialCredit==="ended"?"engines.trialCreditEnded":Le(s)?"engines.trialCredit":"engines.trialCreditOwn")})}):s.readOnly?e.jsxs(Nt,{instance:s,bare:n,children:[a,e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("organization.managedEngine")}),!Le(s)&&e.jsx("p",{className:"mt-2 text-[12px] text-ink-secondary",children:t("organization.engineUnavailable")})]}):e.jsxs(Nt,{instance:s,bare:n,children:[a,(s.codexEndpoint||s.claudeEndpoint)&&e.jsx(vi,{instance:s},s.instanceId),!Le(s)&&e.jsx(Mt,{instance:s,intent:s.access==="custom"?"inject":"cloud",description:s.codexEndpoint?t("agentEndpoints.codexHint"):void 0,unframed:!0}),Le(s)&&e.jsx(Zl,{instance:s,className:"mt-3"}),Le(s)&&s.serverKind==="ollama"&&e.jsx(eo,{instance:s,className:"mt-3"}),Le(s)&&e.jsx(to,{instance:s,className:"mt-3"}),s.snapshot.update&&e.jsx(Ma,{update:s.snapshot.update,instance:s,className:"mt-3",quiet:!0}),s.snapshot.warning&&e.jsx(za,{warning:s.snapshot.warning,className:"mt-3"}),Le(s)&&s.snapshot.authenticated===!0&&(s.authentication?.method==="device-code"?e.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-success",children:[e.jsx(be,{size:13}),t(so[Oa(s.driverKind)].connectedAccount)]}):s.authentication?.method==="paste-code"&&e.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-success",children:[e.jsx(be,{size:13}),t("engineSetup.claude.connectedAccount")]})),s.freeUpSpace&&e.jsx(rm,{instance:s}),s.driverKind==="antigravityAgent"&&e.jsxs("div",{className:"mt-3 space-y-3",children:[s.snapshot.authenticated&&e.jsx("p",{className:"break-words text-[12px] text-ink-secondary",children:s.snapshot.account?.email??t("engineSetup.antigravity.emailUnavailable")}),e.jsx(om,{source:s}),s.snapshot.authenticated===!0&&s.authentication?.signOut===!0&&e.jsx(Fn,{instance:s,action:"signOut"}),s.instanceId.startsWith("antigravity-")&&e.jsx(Fn,{instance:s,action:"remove"})]}),e.jsx(Li,{instance:s})]})}function dm(s,n){return n?s.snapshot.authenticated===!0&&s.snapshot.account?.email?s.snapshot.account.email:t("onboarding.engines.ready"):s.snapshot.ollama?Ql(s.snapshot.ollama):s.snapshot.state==="available"&&s.snapshot.authenticated===!1?t("model.signInRequired"):t("onboarding.engines.needsSetup")}function um({rows:s,isReady:n,renderEngine:a,more:i}){const[r,c]=l.useState(null),o=s.filter(p=>n(p)||p.authentication!==void 0||p.codexEndpoint||p.claudeEndpoint),[d,m]=l.useState(!1),u=!s.length||s.some(p=>!p.readOnly),x=s.filter(p=>!o.includes(p));return e.jsxs(e.Fragment,{children:[e.jsx(ye,{label:t("settings.simple.ai.yours"),actions:e.jsx(Fa,{}),children:e.jsx(ve,{children:o.map(p=>{const g=n(p),f=r===p.instanceId;return e.jsxs("div",{"data-simple-engine":p.instanceId,className:"group",children:[e.jsxs("div",{className:"flex min-h-11 flex-wrap items-center gap-x-5 gap-y-2 px-4 py-2.5",children:[e.jsxs("span",{className:"flex min-w-[min(100%,15rem)] flex-1 items-center gap-3",children:[e.jsx(cn,{instance:p,size:14,subtle:!0}),e.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[e.jsx("span",{className:"truncate text-[14px] leading-5 text-ink",children:p.displayName}),e.jsx("span",{className:"truncate text-[13px] leading-[18px] text-ink-secondary",children:dm(p,g)})]})]}),e.jsx("button",{type:"button","aria-expanded":f,className:"ui-button ml-auto shrink-0",onClick:()=>c(f?null:p.instanceId),children:t(f?"common.done":g||p.codexEndpoint||p.claudeEndpoint?"settings.simple.ai.manage":"settings.simple.ai.setUp")})]}),f&&e.jsx("div",{className:"px-4 pb-3",children:a(p,!0)})]},p.instanceId)})})}),(x.length>0||u)&&e.jsxs(zt,{title:t("settings.simple.ai.more",{count:String(x.length+Number(u))}),trailing:e.jsx("span",{"aria-hidden":"true",className:"flex items-center -space-x-1",children:x.slice(0,4).map(p=>e.jsx("span",{className:"flex size-[18px] items-center justify-center rounded-full bg-menu",children:e.jsx(cn,{instance:p,size:14,subtle:!0})},p.instanceId))}),...i,children:[u&&e.jsxs("div",{className:"rounded-xl border border-hairline/50 bg-inset p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("strong",{className:"text-sm",children:"Xingchi (Codex Responses)"}),!d&&e.jsx("button",{type:"button",className:"ui-button",onClick:()=>m(!0),children:t("settings.simple.ai.setUp")})]}),d&&e.jsx(Bs,{engine:"codex",xingchi:!0,onDone:()=>m(!1)})]}),e.jsx(Da,{instances:x,isReady:n,renderEngine:p=>a(p)})]})]})}function mm(){const{state:s,refreshInstances:n}=G(),[a,i]=l.useState([]),[r,c]=l.useState(null),[o,d]=l.useState(null);if(l.useEffect(()=>{let u=!0;return M("/api/instances/hidden").then(x=>{u&&i(Array.isArray(x?.instances)?x.instances:[])}).catch(()=>{}),()=>{u=!1}},[s.instances]),a.length===0)return null;const m=u=>{c(u),d(null),M(`/api/instances/${encodeURIComponent(u)}`,{method:"PATCH",body:JSON.stringify({hidden:!1})}).then(()=>Promise.resolve(n()).catch(()=>{})).catch(x=>d(x.message)).finally(()=>c(null))};return e.jsxs("details",{"data-hidden-engines":!0,className:"px-4",children:[e.jsx("summary",{className:"cursor-pointer text-[13px] font-medium text-ink-secondary hover:text-ink",children:t("engines.hiddenTitle",{count:String(a.length)})}),e.jsx("p",{className:"mt-2 text-[12px] text-ink-secondary",children:t("engines.hiddenHint")}),e.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:a.map(u=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-hairline/40 bg-inset px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-[13px] text-ink",children:u.displayName}),e.jsx("button",{type:"button","data-unhide-engine":u.instanceId,disabled:r!==null,onClick:()=>m(u.instanceId),className:"shrink-0 text-[12px] font-medium text-accent hover:underline disabled:opacity-50",children:r===u.instanceId?t("engines.unhiding"):t("engines.unhide")})]},u.instanceId))}),o&&e.jsx("div",{role:"alert",className:"mt-1 text-[12px] text-danger",children:o})]})}function Bi({simple:s=!1,more:n}){const{state:a}=G();l.useEffect(()=>Xl,[]);const i=a.instances.filter(g=>g.readOnly||g.cli!==void 0||g.cliDefault!==void 0||g.snapshot.state==="unavailable"||Yl(g)||g.claudeEndpoint!==void 0||g.claudeBedrock!==void 0||g.codexEndpoint!==void 0),r=new Map;for(const g of i){const f=es(g);f&&r.set(f,[...r.get(f)??[],g])}const c=g=>{const f=es(g);return f&&r.get(f)?.[0]===g?f:null},o=i.filter(g=>!es(g)||c(g)),d=o.length>0&&o.every(g=>g.readOnly),m=!r.has("chatgpt")&&!d,u=!r.has("claude")&&!d,x=g=>{const f=c(g);return f?Pi(r.get(f)):Le(g)},p=(g,f=!1)=>{const y=c(g);return y?e.jsx(tm,{group:y,accounts:r.get(y),bare:f,advanced:e.jsxs(e.Fragment,{children:[y==="claude"?e.jsxs(e.Fragment,{children:[e.jsx(qt,{}),e.jsx(ts,{})]}):e.jsx(wt,{}),e.jsx(Li,{instance:g})]})}):e.jsx(cm,{instance:g,bare:f})};return s&&n?e.jsxs(e.Fragment,{children:[e.jsx(um,{rows:o,isReady:x,renderEngine:p,more:n}),u&&e.jsxs("div",{className:"px-4",children:[e.jsx(qt,{}),e.jsx(ts,{})]}),m&&e.jsx("div",{className:"px-4",children:e.jsx(wt,{})})]}):e.jsxs("div",{className:"flex min-w-0 flex-col gap-6 pb-2",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1 basis-60 space-y-2 px-4",children:[e.jsx("h1",{className:"text-[22px] font-semibold tracking-tight text-ink",children:t("settings.engines.title")}),e.jsx("p",{className:"mt-2 max-w-lg text-[13px] leading-relaxed text-ink-secondary",children:t("engines.library.intro")})]}),e.jsx(Fa,{})]}),e.jsx(Da,{instances:o,isReady:x,renderEngine:p}),u&&e.jsxs("div",{className:"px-4",children:[e.jsx(qt,{}),e.jsx(ts,{})]}),m&&e.jsx("div",{className:"px-4",children:e.jsx(wt,{})}),e.jsx(mm,{}),e.jsx(Ri,{})]})}const pm={status:"/api/local-computer","local-vms":"/api/local-computer/instances",cloud:"/api/computers/boxes",vps:"/api/computers/vps"};function bt(s,n){return[pm[s],{signal:n}]}function Us(s,n){return[s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}]}function xm({instances:s,configured:n,aliases:a,loading:i,removingName:r,error:c,unavailableReason:o,onRefresh:d,onRemove:m}){return e.jsxs(Y,{title:t("vm.vps.title"),subtitle:t("vm.vps.subtitle"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[12px] text-ink-secondary",children:n===!0?t("vm.vps.sshHost",{alias:a.join(", ")||t("vm.vps.configuredFallback")}):n===!1?e.jsxs(e.Fragment,{children:[t("vm.vps.needsAlias")," ",e.jsx(_a,{id:"vps"})]}):t("vm.vps.refreshHint")}),e.jsxs("button",{type:"button",onClick:d,disabled:i||r!==null,"aria-label":t("vm.vps.refreshAria"),className:"flex shrink-0 items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-40",children:[e.jsx(Ae,{size:12,className:z(i&&"animate-spin")})," ",t("vm.refresh")]})]}),c&&e.jsx("div",{role:"alert",className:"mt-3 rounded-lg bg-danger/10 px-3 py-2 text-[12px] text-danger",children:c}),e.jsx("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:i?t("vm.vps.checking"):o?t("vm.vps.unavailable",{reason:o}):n===!1?t("vm.vps.notConfigured"):s.length===1?t("vm.vps.foundOne"):t("vm.vps.foundMany",{count:s.length})}),!(n===!1&&!i&&!o)&&e.jsxs("div",{"aria-busy":i||r!==null,className:"mt-3 overflow-hidden rounded-xl border border-hairline/40",children:[o&&s.length>0&&e.jsxs("div",{className:"flex items-center gap-2 border-b border-hairline/35 px-3 py-2.5 text-[12px] text-ink-secondary",children:[e.jsx(Oe,{size:14,className:"shrink-0 text-warning"})," ",o]}),i&&s.length===0?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:13,className:"animate-spin"})," ",t("vm.vps.checkingList")]}):o&&s.length===0?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(Oe,{size:14,className:"shrink-0 text-warning"})," ",o]}):n===!1?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(ml,{size:14,className:"shrink-0"})," ",t("vm.vps.notConfigured")]}):s.length===0?e.jsx("div",{className:"px-3 py-4 text-[13px] text-ink-secondary",children:t("vm.vps.noneFound")}):s.map((u,x)=>{const p=wm(u),g=Fs(p),f=r===u.name,y=Ds(u.name);return e.jsxs("div",{className:z("flex items-start justify-between gap-3 px-3 py-3",x>0&&"border-t border-hairline/35"),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"truncate text-[14px] font-medium text-ink",children:u.orphaned?t("vm.vps.orphan",{id:y}):u.ownerName}),e.jsx("span",{className:z("rounded-full px-2 py-0.5 text-[11px]",u.inUse||p==="running"?"bg-success/15 text-success":p==="stopped"||p==="paused"?"bg-control text-ink-secondary":"bg-warning/15 text-warning"),children:g}),a.length>1&&e.jsx("span",{className:"rounded-full bg-control px-2 py-0.5 font-mono text-[11px] text-ink-secondary",children:u.vpsAlias})]}),e.jsx("div",{className:"mt-1 text-[12px] text-ink-secondary",children:u.orphaned?t("vm.owner.gone"):t("vm.owner.owned")}),u.inUse&&e.jsx("div",{className:"mt-1 text-[12px] text-ink-secondary",children:t("vm.vps.stopFirst")})]}),e.jsxs("button",{type:"button",onClick:()=>m(u),disabled:i||u.inUse||r!==null,"aria-busy":f||void 0,title:t("vm.vps.removeTitle"),className:"flex shrink-0 items-center gap-1.5 rounded-lg bg-danger/10 px-2.5 py-1.5 text-[12px] font-medium text-danger hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-40",children:[f?e.jsx(J,{size:12,className:"animate-spin"}):e.jsx(Se,{size:12}),t("vm.vps.remove")]})]},`${u.vpsAlias??""}:${u.name}`)})]})]})}const gm=[1e3,2e3,4e3];function hm(s){return new Promise(n=>window.setTimeout(n,s))}const fm={auto:"vm.dest.auto",cloud:"place.cloud",vm:"vm.dest.vm",local:"vm.dest.local",browser:"vm.dest.browser",off:"vm.dest.off"},bm={unmanaged:"vm.state.notManaged","in-use":"vm.state.inUse",stopped:"vm.state.stopped",running:"vm.state.running",attention:"vm.state.attention",sleeping:"vm.state.sleeping","going-to-sleep":"vm.state.goingToSleep",starting:"vm.state.starting",restarting:"vm.state.restarting",removing:"vm.state.removing",paused:"vm.state.paused"};function Fs(s){return t(bm[s])}function ym(s){return s.managed?s.inUse?"in-use":s.container==="stopped"?"stopped":s.ready?"running":"attention":"unmanaged"}function vm(s){return Fs(ym(s))}function jm(s){return s.inUse?"in-use":s.state==="removing"?"removing":s.state==="archived"?"sleeping":s.state==="archiving"?"going-to-sleep":["idle","ready","running"].includes(s.state)?"running":["init","provisioning","provisioned","cloning"].includes(s.state)?"starting":"attention"}function Oi(s,n,a){const i={...a},r=new Set(s.map(o=>o.boxId)),c=s.flatMap(o=>{const d=a[o.boxId];return d==="deleted"?[]:d==="deleting"?[{...o,state:"removing"}]:d!=="sleeping"?[o]:o.state==="archived"?(delete i[o.boxId],[o]):[{...o,state:"archived"}]});for(const o of n)a[o.boxId]!=="sleeping"||r.has(o.boxId)||c.push({...o,state:"archived"});for(const[o,d]of Object.entries(a))(d==="deleted"||d==="deleting")&&!r.has(o)&&delete i[o];return{instances:c,overrides:i}}function km(s,n,a){return s.configured!==!0||s.available!==!0?{instances:n,overrides:{...a}}:Oi(Array.isArray(s.instances)?s.instances:[],n,a)}function Nm(s){return["idle","ready","running"].includes(s.state)}function wm(s){return s.inUse?"in-use":s.state==="running"?"running":s.state==="restarting"?"restarting":s.state==="removing"?"removing":["created","exited"].includes(s.state)?"stopped":s.state==="paused"?"paused":"attention"}function Ds(s){const n=/-([a-f0-9]{12})$/i.exec(s)?.[1];return n?n.slice(-8).toLowerCase():"unknown"}function Sm(s){return{confirmation:t("vm.confirm.deleteBotVm",{name:s.name}),request:Us(`/api/bots/${s.botId}/local-computer/remove`,{})}}function Cm(s,n){return{confirmation:s==="delete"?t("vm.confirm.deleteCloud",{subject:n.orphaned?t("vm.confirm.orphanCloud"):t("vm.confirm.ownedCloud",{name:n.ownerName??""})}):null,request:Us(`/api/computers/boxes/${encodeURIComponent(n.boxId)}/${s}`,s==="delete"?{confirmName:n.name}:{})}}function Em(s){const n=Ds(s.name);return{confirmation:t("vm.confirm.removeVps",{subject:s.orphaned?t("vm.confirm.orphanVps",{id:n}):t("vm.confirm.ownedVps",{name:s.ownerName??""})}),request:Us(`/api/computers/vps/${encodeURIComponent(s.name)}/remove`,{confirmName:s.name,alias:s.vpsAlias})}}function ns(s,n){return s.confirmation!==null&&!n(s.confirmation)?null:s.request}function Am({instances:s,configured:n,loading:a,pending:i,error:r,unavailableReason:c,onRefresh:o,onSleep:d,onDelete:m}){return e.jsxs(Y,{title:t("vm.cloud.title"),subtitle:t("vm.cloud.subtitle"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[12px] text-ink-secondary",children:n===!0?t("vm.cloud.includesOrphans"):n===!1?e.jsxs(e.Fragment,{children:[t("vm.cloud.needsKey")," ",e.jsx(_a,{id:"box"})]}):t("vm.cloud.refreshHint")}),e.jsxs("button",{type:"button",onClick:o,disabled:a||i!==null,"aria-label":t("vm.cloud.refreshAria"),className:"flex shrink-0 items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-40",children:[e.jsx(Ae,{size:12,className:z(a&&"animate-spin")})," ",t("vm.refresh")]})]}),r&&e.jsx("div",{role:"alert",className:"mt-3 rounded-lg bg-danger/10 px-3 py-2 text-[12px] text-danger",children:r}),e.jsx("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:a?t("vm.cloud.checking"):c?t("vm.cloud.unavailable",{reason:c}):n===!1?t("vm.cloud.notConnected"):s.length===1?t("vm.cloud.foundOne"):t("vm.cloud.foundMany",{count:s.length})}),!(n===!1&&!a&&!c)&&e.jsx("div",{"aria-busy":a||i!==null,className:"mt-3 overflow-hidden rounded-xl border border-hairline/40",children:a&&s.length===0?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:13,className:"animate-spin"})," ",t("vm.cloud.checkingList")]}):c?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(Oe,{size:14,className:"shrink-0 text-warning"})," ",c]}):n===!1?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(Rt,{size:14,className:"shrink-0"})," ",t("vm.cloud.notConnected")]}):s.length===0?e.jsx("div",{className:"px-3 py-4 text-[13px] text-ink-secondary",children:t("vm.cloud.noneFound")}):s.map((u,x)=>{const p=jm(u),g=Fs(p),f=i?.boxId===u.boxId,y=Nm(u),b=p==="removing";return e.jsxs("div",{className:z("flex items-start justify-between gap-3 px-3 py-3",x>0&&"border-t border-hairline/35"),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"truncate text-[14px] font-medium text-ink",children:u.orphaned?t("vm.cloud.orphan"):t("vm.cloud.ofBot",{name:u.ownerName??""})}),e.jsx("span",{className:z("rounded-full px-2 py-0.5 text-[11px]",u.inUse||p==="running"?"bg-success/15 text-success":p==="sleeping"||p==="going-to-sleep"?"bg-control text-ink-secondary":"bg-warning/15 text-warning"),children:g})]}),e.jsx("div",{className:"mt-1 break-all text-[12px] text-ink-secondary",children:u.orphaned?t("vm.owner.gone"):t("vm.cloud.machineId",{id:u.name})}),u.inUse&&e.jsx("div",{className:"mt-1 text-[12px] text-ink-secondary",children:t("vm.cloud.stopFirst")})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("button",{type:"button",onClick:()=>d(u),disabled:a||u.inUse||i!==null||!y,"aria-busy":f&&i?.action==="sleep"?!0:void 0,title:y?t("vm.cloud.sleepTitle"):t("vm.cloud.sleepBlocked",{state:g.toLowerCase()}),className:"flex items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:[f&&i?.action==="sleep"?e.jsx(J,{size:12,className:"animate-spin"}):e.jsx(pl,{size:12}),t("vm.cloud.sleep")]}),e.jsxs("button",{type:"button",onClick:()=>m(u),disabled:a||u.inUse||i!==null||b,"aria-busy":f&&i?.action==="delete"?!0:void 0,title:t("vm.cloud.deleteTitle"),className:"flex items-center gap-1.5 rounded-lg bg-danger/10 px-2.5 py-1.5 text-[12px] font-medium text-danger hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-40",children:[f&&i?.action==="delete"?e.jsx(J,{size:12,className:"animate-spin"}):e.jsx(Se,{size:12}),t("common.delete")]})]})]},u.boxId)})})]})}function Im({instances:s,maxInstances:n,loading:a,deletingBotId:i,error:r,unavailableReason:c,onRefresh:o,onDelete:d,runningInstances:m,powerPending:u,onPower:x}){return e.jsxs(Y,{title:t("vm.perBot.title"),subtitle:t("vm.perBot.subtitle",{count:c?t("vm.perBot.inventoryUnavailable"):m===void 0?t("vm.perBot.created",{count:s.length,max:n}):R(`Đã tạo ${s.length} máy · Đang chạy ${m}/${n}`,`${s.length} desktops created · ${m}/${n} running`)}),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[12px] text-ink-secondary",children:m===void 0?t("vm.perBot.deleteHint"):R("Ứng dụng không giới hạn số máy đã tạo; số lượng thực tế phụ thuộc dung lượng ổ đĩa. Dừng một máy để giải phóng tài nguyên cho máy khác.","The app does not cap created desktops; their number depends on disk space. Stop a desktop to free resources for another.")}),e.jsxs("button",{type:"button",onClick:o,disabled:a||i!==null||!!u,"aria-label":t("vm.perBot.refreshAria"),className:"flex shrink-0 items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-40",children:[e.jsx(Ae,{size:12,className:z(a&&"animate-spin")})," ",t("vm.refresh")]})]}),r&&e.jsx("div",{role:"alert",className:"mt-3 rounded-lg bg-danger/10 px-3 py-2 text-[12px] text-danger",children:r}),e.jsx("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:a?t("vm.perBot.checking"):c?t("vm.perBot.unavailable",{reason:c}):s.length===1?t("vm.perBot.foundOne"):t("vm.perBot.foundMany",{count:s.length})}),e.jsx("div",{"aria-busy":a||i!==null||!!u,className:"mt-3 overflow-hidden rounded-xl border border-hairline/40",children:a&&s.length===0?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:13,className:"animate-spin"})," ",t("vm.perBot.checkingList")]}):c?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-[13px] text-ink-secondary",children:[e.jsx(Oe,{size:14,className:"shrink-0 text-warning"})," ",c]}):s.length===0?e.jsx("div",{className:"px-3 py-4 text-[13px] text-ink-secondary",children:t("vm.perBot.none")}):s.map((p,g)=>{const f=vm(p),y=i===p.botId,b=p.managed===!0;return e.jsxs("div",{className:z("flex items-start justify-between gap-3 px-3 py-3",g>0&&"border-t border-hairline/35"),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"truncate text-[14px] font-medium text-ink",children:p.name}),e.jsx("span",{className:z("rounded-full px-2 py-0.5 text-[11px]",b?p.inUse||p.ready?"bg-success/15 text-success":p.container==="stopped"?"bg-control text-ink-secondary":"bg-warning/15 text-warning":"bg-warning/15 text-warning"),children:f})]}),e.jsx("div",{className:"mt-1 text-[12px] text-ink-secondary",children:t("vm.perBot.destination",{destination:t(fm[p.destination])})}),!b&&e.jsx("div",{className:"mt-1 text-[12px] text-warning",children:t("vm.perBot.unmanaged")}),b&&p.problem&&!p.inUse&&e.jsx("div",{className:"mt-1 text-[12px] text-warning",children:ni(p.problem)}),b&&p.inUse&&e.jsx("div",{className:"mt-1 text-[12px] text-ink-secondary",children:t("vm.perBot.stopFirst")})]}),b&&e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[x&&e.jsxs("button",{type:"button",onClick:()=>x(p,p.container==="running"?"stop":"start"),disabled:a||p.inUse||i!==null||!!u||p.container==="stopped"&&m!==void 0&&m>=n,"aria-busy":u?.botId===p.botId||void 0,className:"flex items-center gap-1.5 rounded-lg bg-control px-2.5 py-1.5 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-40",children:[u?.botId===p.botId&&e.jsx(J,{size:12,className:"animate-spin"}),p.container==="running"?R("Dừng","Stop"):R("Bật","Start")]}),e.jsxs("button",{type:"button",onClick:()=>d(p),disabled:a||p.inUse||i!==null||!!u,"aria-busy":y||void 0,title:p.inUse?t("vm.perBot.deleteBlocked"):t("vm.perBot.deleteTitle",{name:p.name}),className:"flex shrink-0 items-center gap-1.5 rounded-lg bg-danger/10 px-2.5 py-1.5 text-[12px] font-medium text-danger hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-40",children:[y?e.jsx(J,{size:12,className:"animate-spin"}):e.jsx(Se,{size:12}),t("common.delete")]})]})]},p.botId)})})]})}function yt({n:s,title:n,done:a,children:i}){return e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:z("mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full text-[11px]",a?"bg-success/20 text-success":"border border-hairline/50 text-ink-secondary"),children:a?e.jsx(be,{size:12}):s}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:z("text-[14px]",a?"text-ink-secondary line-through":"text-ink"),children:n}),!a&&i&&e.jsx("div",{className:"mt-2 flex flex-col items-start gap-2 [&>*]:max-w-full",children:i})]})]})}function Ve({action:s,pending:n,children:a,onClick:i,danger:r=!1}){return e.jsxs("button",{onClick:i,"aria-busy":n===s,disabled:n!==null,className:z("flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] font-medium disabled:opacity-50",r?"bg-danger/15 text-danger hover:bg-danger/20":"bg-accent text-white hover:brightness-110"),children:[n===s&&e.jsx(J,{size:13,className:"animate-spin"}),a]})}const Mi=5,zi=1440,Pm=480;function Tm(s){const n=s.trim();if(!/^\d+$/.test(n))return null;const a=Number(n);return a>=Mi&&a<=zi?a:null}function Rm({minutes:s,disabled:n,onSave:a}){const[i,r]=l.useState(String(s)),[c,o]=l.useState(!1),[d,m]=l.useState(""),[u,x]=l.useState(!1);l.useEffect(()=>{c||r(String(s))},[s,c]);const p=async()=>{if(!c||u)return;const g=Tm(i);if(g===null){m(t("vm.idle.range"));return}x(!0);try{await a(g),r(String(g)),o(!1),m("")}catch(f){m(f instanceof Error?f.message:t("vm.idle.error"))}finally{x(!1)}};return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"local-vm-idle-timeout",className:"text-[13px] text-ink",children:t("vm.idle.label")}),e.jsx("div",{id:"local-vm-idle-timeout-help",className:"text-[12px] text-ink-secondary",children:t("vm.idle.detail")})]}),e.jsxs("div",{className:z("flex w-[150px] shrink-0 items-center rounded-lg border bg-control",d?"border-danger/60":"border-hairline/40 focus-within:border-focus"),children:[e.jsx("input",{id:"local-vm-idle-timeout",type:"number",min:Mi,max:zi,step:1,inputMode:"numeric",value:i,disabled:n||u,"aria-invalid":!!d,"aria-describedby":d?"local-vm-idle-timeout-error local-vm-idle-timeout-help":"local-vm-idle-timeout-help",onChange:g=>{r(g.target.value),o(!0),m("")},onBlur:()=>{p()},onKeyDown:g=>{g.key==="Enter"&&g.currentTarget.blur()},className:"min-w-0 flex-1 bg-transparent px-2.5 py-1.5 text-[13px] tabular-nums text-ink focus:outline-none disabled:opacity-50"}),e.jsx("span",{className:"pr-2.5 text-[13px] text-ink-secondary",children:t("vm.idle.minutes")})]})]}),d?e.jsx("p",{id:"local-vm-idle-timeout-error",role:"alert",className:"mt-1.5 text-[12px] text-danger",children:d}):null]})}function Ui(){const s=G().state.config?.cloudHome===!0,[n,a]=l.useState(null),[i,r]=l.useState(!0),[c,o]=l.useState(null),d=l.useRef(null);l.useEffect(()=>()=>d.current?.abort(),[]);const[m,u]=l.useState(null),[x,p]=l.useState(!1),[g,f]=l.useState(0),[y,b]=l.useState([]),[h,k]=l.useState(2),[S,E]=l.useState(!1),[N,P]=l.useState(null),[j,B]=l.useState(null),[v,A]=l.useState(null),[T,$]=l.useState(null),[U,Z]=l.useState(0),[H,ne]=l.useState([]),[ae,oe]=l.useState(null),[F,L]=l.useState(!0),[X,se]=l.useState(null),[he,pe]=l.useState(null),[ce,ue]=l.useState(null),[w,re]=l.useState(0),te=l.useRef([]),ee=l.useRef({}),[K,le]=l.useState([]),[_,ie]=l.useState(null),[I,C]=l.useState([]),[W,xe]=l.useState(!0),[V,ke]=l.useState(null),[Ie,et]=l.useState(null),[tt,ze]=l.useState(null),[Tr,Rr]=l.useState(0),[Lr,Fe]=l.useState(""),Ke=l.useCallback(async O=>{const D=await fetch(...bt("status",O)),Q=await D.json().catch(()=>({}));if(!O?.aborted){if(!D.ok)throw new Error(Q.error??t("vm.err.status",{code:D.status}));return a(Q),u(null),Q}},[]),xt=l.useCallback(async O=>{const D=await fetch(...bt("local-vms",O)),Q=await D.json().catch(()=>({}));if(!D.ok)throw new Error(Q.error??t("vm.err.inventory",{code:D.status}));const q=Q;b(q.instances),k(q.maxInstances),B(q.available?null:ni(q.problem)??t("vm.err.runtimeUnavailable")),P(null)},[]),st=l.useCallback(async O=>{const D=await fetch(...bt("cloud",O)),Q=await D.json().catch(()=>({}));if(!D.ok)throw new Error(Q.error??t("vm.err.cloudInventory",{code:D.status}));const q=Q,fe=km(q,te.current,ee.current);ee.current=fe.overrides,te.current=fe.instances,ne(fe.instances),oe(q.configured===!0),pe(q.available||!q.configured?null:q.problem??t("vm.err.cloudUnavailable")),se(null)},[]),_t=l.useCallback(async O=>{const D=await fetch(...bt("vps",O)),Q=await D.json().catch(()=>({}));if(!D.ok)throw new Error(Q.error??t("vm.err.vpsInventory",{code:D.status}));const q=Q;le(Array.isArray(q.instances)?q.instances:[]),ie(q.configured===!0),C(Array.isArray(q.vpsAliases)?q.vpsAliases:[]),et(q.available||!q.configured?null:q.problem??t("vm.err.vpsUnavailable")),ke(null)},[]);l.useEffect(()=>{if(s)return;let O=!0,D,Q;const q=async()=>{Q=new AbortController;try{await Ke(Q.signal)}catch(fe){O&&!(fe instanceof DOMException&&fe.name==="AbortError")&&(a(null),u(fe instanceof Error?fe.message:String(fe)))}finally{O&&(r(!1),D=window.setTimeout(()=>{q()},5e3))}};return q(),()=>{O=!1,Q?.abort(),D!==void 0&&window.clearTimeout(D)}},[s,Ke,g]),l.useEffect(()=>{if(n?.mode!=="per-bot"){b([]),E(!1),P(null),B(null);return}const O=new AbortController;return E(!0),xt(O.signal).catch(D=>{D instanceof DOMException&&D.name==="AbortError"||P(D instanceof Error?D.message:String(D))}).finally(()=>{O.signal.aborted||E(!1)}),()=>O.abort()},[U,xt,n?.mode]),l.useEffect(()=>{const O=new AbortController;return L(!0),st(O.signal).catch(D=>{D instanceof DOMException&&D.name==="AbortError"||pe(D instanceof Error?D.message:String(D))}).finally(()=>{O.signal.aborted||L(!1)}),()=>O.abort()},[w,st]),l.useEffect(()=>{const O=new AbortController;return xe(!0),_t(O.signal).catch(D=>{D instanceof DOMException&&D.name==="AbortError"||et(D instanceof Error?D.message:String(D))}).finally(()=>{O.signal.aborted||xe(!1)}),()=>O.abort()},[_t,Tr]);const $t=async(O,D)=>{const Q=await fetch(`/api/local-computer/${O}`,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:D}),q=await Q.json().catch(()=>({})),fe={pull:"vm.err.prepare",run:"vm.err.create",start:"vm.err.start",stop:"vm.err.stop",remove:"vm.deleteError"};if(!Q.ok)throw new Error(q.error??t(fe[O]));return D.throwIfAborted(),a(q),q},Gs=O=>window.ogb?.confirm?window.ogb.confirm(O):window.confirm(O),He=async O=>{if(c!==null||d.current)return;const D=new AbortController;d.current=D,o(O),u(null);try{if(O==="remove"&&!await Gs(t("vm.confirm.deleteShared"))||O==="recreate"&&!await Gs(t("vm.confirm.recreate")))return;let Q;if(O==="recreate"?(await $t("remove",D.signal),Q=await $t("run",D.signal)):Q=await $t(O,D.signal),(O==="run"||O==="start"||O==="recreate")&&(Q=await Cn(Q,async()=>await Ke(D.signal)??Q,D.signal),!Q.ready&&!Q.capacity_limited))throw new Error(Q.problem??t("vm.err.start"));await Ke(),Fe(O==="remove"?t("vm.announce.deleted"):O==="stop"?t("vm.announce.stopped"):t("vm.announce.updated"))}catch(Q){if(D.signal.aborted)return;u(Q instanceof Error?Q.message:String(Q))}finally{d.current=null,D.signal.aborted||o(null)}},Br=async(O,D)=>{if(T||v)return;$({botId:O.botId,action:D}),P(null);const Q=new AbortController;try{const q=`/api/bots/${encodeURIComponent(O.botId)}/local-computer`,fe=await fetch(`${q}/${D}`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"});let Te=await fe.json();if(!fe.ok)throw new Error(Te.error??t("vm.err.start"));if(D==="start"&&(Te=await Cn(Te,async()=>{const We=await fetch(q);if(!We.ok)throw new Error(t("vm.err.start"));return We.json()},Q.signal)),D==="start"&&!Te.ready)throw new Error(Te.problem??t("vm.err.start"));await Promise.all([xt(),Ke()])}catch(q){P(q instanceof Error?q.message:String(q))}finally{$(null)}},qs=async O=>{p(!0),u(null);try{const D=await fetch("/api/config",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({localVm:{mode:O,automaticCapacity:!0}})}),Q=await D.json().catch(()=>({}));if(!D.ok)throw new Error(Q.error??t("vm.policyError"));a(q=>q&&{...q,mode:O}),await Ke()}catch(D){u(D instanceof Error?D.message:String(D))}finally{p(!1)}},Or=async O=>{const D=await fetch("/api/config",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({localVm:{idleTimeoutMinutes:O}})}),Q=await D.json().catch(()=>({}));if(!D.ok)throw new Error(Q.error??t("vm.idle.error"));a(q=>q&&{...q,idle_timeout_ms:O*6e4})},Mr=async O=>{if(!O.managed){P(t("vm.unmanagedError"));return}const D=ns(Sm(O),Q=>window.confirm(Q));if(D){A(O.botId),P(null);try{const Q=await fetch(...D),q=await Q.json().catch(()=>({}));if(!Q.ok)throw new Error(q.error??t("vm.deleteError"));await xt(),Fe(t("vm.announce.deletedBot",{name:O.name}))}catch(Q){P(Q instanceof Error?Q.message:String(Q))}finally{A(null)}}},Vs=async(O,D)=>{const Q=ns(Cm(O,D),q=>window.confirm(q));if(Q){ue({boxId:D.boxId,action:O}),se(null),Fe("");try{const q=await fetch(...Q),fe=await q.json().catch(()=>({}));if(!q.ok)throw new Error(fe.error??t(O==="delete"?"vm.cloud.deleteError":"vm.cloud.sleepError"));const Te=O==="delete"&&fe?.pending===!0;ee.current={...ee.current,[D.boxId]:O==="delete"?Te?"deleting":"deleted":"sleeping"};const We=Oi(te.current,te.current,ee.current);ee.current=We.overrides,te.current=We.instances,ne(We.instances);const Ge=D.orphaned?t("vm.announce.orphanCloud"):t("vm.confirm.ownedCloud",{name:D.ownerName??""});if(Fe(Te?`${Ge}: ${t("vm.state.removing")}.`:t(O==="delete"?"vm.announce.cloudDeleted":"vm.announce.cloudSleeping",{subject:Ge})),Te){for(const Ce of gm){await hm(Ce);try{await st()}catch{}if(ee.current[D.boxId]!=="deleting"){Fe(t("vm.announce.cloudDeleted",{subject:Ge}));return}}const qe={...ee.current};delete qe[D.boxId],ee.current=qe;const ht=te.current.map(Ce=>Ce.boxId===D.boxId?{...Ce,state:D.state}:Ce);te.current=ht,ne(ht);try{await st(),te.current.some(Ce=>Ce.boxId===D.boxId)||Fe(t("vm.announce.cloudDeleted",{subject:Ge}))}catch(Ce){const Ur=Ce instanceof Error?Ce.message:String(Ce);se(`${Ge}: ${t("vm.state.removing")}. ${Ur}`)}return}try{await st()}catch(qe){const ht=qe instanceof Error?qe.message:String(qe);se(t(O==="delete"?"vm.cloud.deletedRefreshError":"vm.cloud.sleepRefreshError",{subject:Ge,detail:ht}))}}catch(q){se(q instanceof Error?q.message:String(q))}finally{ue(null)}}},zr=async O=>{const D=Ds(O.name),Q=ns(Em(O),q=>window.confirm(q));if(Q){ze(O.name),ke(null);try{const q=await fetch(...Q),fe=await q.json().catch(()=>({}));if(!q.ok)throw new Error(fe.error??t("vm.vpsRemoveError"));await _t(),Fe(t("vm.announce.vpsRemoved",{subject:O.orphaned?t("vm.announce.orphanVps",{id:D}):t("vm.confirm.ownedVps",{name:O.ownerName??""})}))}catch(q){ke(q instanceof Error?q.message:String(q))}finally{ze(null)}}},Pe=n?.commands,gt=n?.ready===!0,Js=n?.container!=="missing",Xs=!!(Js&&(!n?.imageMatches||!n?.managed||n?.network==="unsafe"||n?.security==="unsafe"||n?.persistence==="unsafe")),Ys=!i&&!n,Qs=n?.platform==="darwin"?t("vm.host.mac"):t("vm.host.computer"),Ne=n?.mode==="per-bot",Kt=Ne&&n?.runtime==="container",Ht=Ne?!!(n?.daemonUp&&n?.image&&!Kt):gt;return e.jsxs(e.Fragment,{children:[e.jsx("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:Lr}),e.jsx(Am,{instances:H,configured:ae,loading:F,pending:ce,error:X,unavailableReason:he,onRefresh:()=>re(O=>O+1),onSleep:O=>{Vs("sleep",O)},onDelete:O=>{Vs("delete",O)}}),e.jsx(xm,{instances:K,configured:_,aliases:I,loading:W,removingName:tt,error:V,unavailableReason:Ie,onRefresh:()=>Rr(O=>O+1),onRemove:O=>{zr(O)}}),e.jsx(pd,{}),!s&&e.jsxs(e.Fragment,{children:[e.jsxs(Y,{title:t("vm.main.title"),subtitle:Ne?t("vm.main.perBotSubtitle",{host:Qs}):t("vm.main.sharedSubtitle",{host:Qs}),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{"aria-live":"polite",className:z("flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px]",Ht?"bg-success/15 text-success":"bg-control text-ink-secondary"),children:[i?e.jsx(J,{size:12,className:"animate-spin"}):Ht?e.jsx(be,{size:12}):e.jsx(no,{size:9}),i?t("common.checking"):Ys?t("vm.main.statusUnavailable"):Ne&&Ht?t("vm.main.readyPerBot"):Kt?t("vm.main.perBotUnsupported"):gt?t("vm.main.ready"):n?.problem??t("vm.main.notReady")]}),e.jsxs("button",{onClick:()=>{r(!0),f(O=>O+1),Z(O=>O+1)},disabled:i||c!==null,className:"flex items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-40",children:[e.jsx(Ae,{size:12})," ",t("vm.main.recheck")]}),gt&&!Ne&&e.jsxs("a",{href:n?.viewer_url??Pe?.view,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1 text-[13px] text-ink hover:bg-control",children:[e.jsx(pt,{size:12})," ",t("vm.main.watch")]})]}),m&&e.jsx("div",{role:"alert",className:"mt-3 rounded-lg bg-danger/10 px-3 py-2 text-[12px] text-danger",children:m})]}),e.jsxs(Y,{title:t("vm.isolation.title"),subtitle:t("vm.isolation.subtitle"),children:[e.jsx("div",{className:"flex overflow-hidden rounded-lg border border-hairline/40",children:["shared","per-bot"].map((O,D)=>e.jsx("button",{type:"button",disabled:!n||x,onClick:()=>{qs(O)},className:z("flex-1 px-3 py-2 text-[13px] disabled:opacity-50",D>0&&"border-l border-hairline/40",n?.mode===O?"bg-control text-ink":"text-ink-secondary hover:text-ink"),children:O==="shared"?t("vm.isolation.shared"):t("vm.isolation.perBot")},O))}),Ne&&e.jsxs("div",{className:"mt-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13px] text-ink",children:R("Số máy ảo chạy cùng lúc tối đa","Maximum desktops running at once")}),e.jsx("div",{className:"text-[12px] text-ink-secondary",children:R("Không giới hạn số máy đã tạo trong ứng dụng. Giới hạn chạy cùng lúc tự tính theo RAM/CPU cấp cho Docker hoặc Podman, có dự phòng cho hệ thống. Khi đủ chỗ đang chạy, máy mới vẫn được tạo ở trạng thái dừng.","The app does not cap created desktops. The running limit is calculated from Docker or Podman memory/CPU with a system reserve. When running slots are full, new desktops are still created in a stopped state.")}),n?.capacity&&e.jsxs("div",{className:"mt-1 text-[12px] text-ink-secondary",children:[n.capacity.source==="host"?R("Ước tính từ máy chủ; chưa đọc được tài nguyên Docker/Podman","Host estimate; Docker/Podman resources have not been read"):n.capacity.source==="docker"?"Docker":"Podman",` · ${n.capacity.memoryGb.toFixed(1)} GB RAM · ${n.capacity.cpus} CPU`,` · ${R("Mỗi máy","Each desktop")}: ${n.capacity.perVmMemoryGb} GB / ${n.capacity.perVmCpus} CPU`,` · ${R("Dành cho hệ thống","System reserve")}: ${n.capacity.reservedMemoryGb.toFixed(1)} GB / ${n.capacity.reservedCpus} CPU`]}),n?.automatic_capacity===!1&&e.jsx("button",{type:"button",disabled:x,onClick:()=>{qs(n.mode)},className:"mt-1 text-[12px] text-accent hover:underline",children:R("Chuyển sang tự động","Switch to automatic")}),n&&(n.running_instances??0)>n.max_instances&&e.jsx("div",{className:"mt-1 text-[12px] text-warning",children:R("Số máy đang chạy vượt mức ước tính mới. Ứng dụng giữ nguyên chúng; dừng bớt máy trước khi bật máy khác.","The running desktops exceed the new estimate. They are kept; stop some before starting another.")})]}),e.jsxs("div",{className:"shrink-0 rounded-lg bg-control px-3 py-2 text-center text-[13px] text-ink",children:[e.jsx("div",{className:"text-[11px] text-ink-secondary",children:n?.automatic_capacity===!1?R("Thủ công","Manual"):R("Tự động","Automatic")}),e.jsx("div",{className:"font-semibold tabular-nums",children:n?.max_instances??"…"})]})]}),e.jsx(Rm,{minutes:n?Math.round(n.idle_timeout_ms/6e4):Pm,disabled:!n||x,onSave:Or}),x&&e.jsxs("div",{className:"mt-2 flex items-center gap-1.5 text-[12px] text-ink-secondary",children:[e.jsx(J,{size:12,className:"animate-spin"})," ",t("vm.saving")]})]}),e.jsx(Y,{title:t("vm.setup.title"),subtitle:t("vm.setup.subtitle"),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs(yt,{n:1,title:t("vm.setup.step1"),done:!!n?.runtime,children:[e.jsx("div",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("vm.setup.step1Detail")}),Pe?.install?e.jsx(rt,{command:Pe.install}):e.jsx("a",{href:"https://podman.io/docs/installation",target:"_blank",rel:"noreferrer",className:"text-[13px] text-accent hover:underline",children:t("vm.setup.podmanGuide")})]}),e.jsx(yt,{n:2,title:n?.runtime&&!n.daemonUp?t("vm.setup.step2Open",{runtime:n.runtime}):t("vm.setup.step2"),done:!!n?.daemonUp,children:n?.runtime?Pe?.runtimeStart?e.jsx(rt,{command:Pe.runtimeStart}):e.jsx("div",{className:"text-[13px] text-ink-secondary",children:t("vm.setup.step2Detail")}):null}),e.jsxs(yt,{n:3,title:t("vm.setup.step3"),done:!!n?.image,children:[n?.daemonUp&&e.jsx(Ve,{action:"pull",pending:c,onClick:()=>{He("pull")},children:t("vm.setup.prepare")}),Pe?.pull&&e.jsxs("details",{className:"text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"cursor-pointer",children:t("vm.setup.showPull")}),e.jsx("div",{className:"mt-2",children:e.jsx(rt,{command:Pe.pull})})]})]}),e.jsxs(yt,{n:4,title:Ne?t("vm.setup.step4PerBot"):Xs?t("vm.setup.step4Recreate"):t("vm.setup.step4"),done:Ne?y.some(O=>O.managed):gt,children:[Ne?e.jsx("div",{className:"text-[13px] leading-relaxed text-ink-secondary",children:Kt?t("vm.setup.applePort"):t("vm.setup.perBotHint")}):Xs?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2 text-[13px] text-warning",children:[e.jsx(Oe,{size:15,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:n?.problem})]}),n?.image?e.jsxs(Ve,{action:"recreate",pending:c,onClick:()=>{He("recreate")},danger:!0,children:[e.jsx(ao,{size:13})," ",t("vm.setup.recreate")]}):e.jsx("div",{className:"text-[13px] text-ink-secondary",children:t("vm.setup.prepareFirst")})]}):n?.container==="stopped"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t(n.stop_reason==="idle"?"vm.stopped.idle":"vm.stopped.detail")}),e.jsx(Ve,{action:"start",pending:c,onClick:()=>{He("start")},children:t("vm.setup.start")})]}):n?.container==="running"?e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:13,className:"animate-spin"})," ",t("vm.setup.waiting")]}):n?.image?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{action:"run",pending:c,onClick:()=>{He("run")},children:t("vm.setup.start")}),e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("vm.setup.idleHint")})]}):null,Pe?.run&&e.jsxs("details",{className:"text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"cursor-pointer",children:t("vm.setup.showCommand")}),e.jsx("div",{className:"mt-2",children:e.jsx(rt,{command:Pe.run})})]})]})]})}),Ne&&e.jsx(Im,{instances:y,maxInstances:n?.max_instances??h,runningInstances:n?.running_instances,powerPending:T,onPower:(O,D)=>{Br(O,D)},loading:S,deletingBotId:v,error:N,unavailableReason:j,onRefresh:()=>Z(O=>O+1),onDelete:O=>{Mr(O)}}),Ys&&e.jsx(Y,{children:e.jsxs("div",{className:"flex gap-2 text-[13px] text-ink-secondary",children:[e.jsx(Oe,{size:15,className:"mt-0.5 shrink-0 text-warning"}),e.jsx("span",{children:t("vm.inspectFailed")})]})}),e.jsxs(Y,{title:t("vm.safety.title"),subtitle:Ne?t("vm.safety.perBot",{path:n?.workspace_guest_path??"/home/cua/workspace"}):t("vm.safety.shared",{path:n?.workspace_guest_path??"/home/cua/workspace"}),children:[Js&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n?.container==="running"&&e.jsxs(Ve,{action:"stop",pending:c,onClick:()=>{He("stop")},children:[e.jsx(io,{size:12})," ",t("vm.safety.stop")]}),e.jsxs(Ve,{action:"remove",pending:c,onClick:()=>{He("remove")},danger:!0,children:[e.jsx(Se,{size:12})," ",Ne?t("vm.safety.deleteLegacy"):t("vm.safety.deleteVm")]})]}),e.jsxs("div",{className:"mt-3 break-all text-[11px] text-ink-secondary",children:[t("vm.safety.workspace",{path:n?.workspace_path??t("vm.safety.notCreated"),driver:n?.driver_version??"0.37.0",image:n?.image_ref??t("vm.safety.notPrepared")}),n?.base_image_ref?e.jsxs(e.Fragment,{children:[" · ",t("vm.safety.baseImage",{image:n.base_image_ref})]}):null]})]})]})]})}function Lm({profileEmail:s="",focusRequest:n=0,simple:a=!1}){return e.jsx(ro,{})}function Bm(s){const n=s.trim().toLowerCase();return!n||/\s/.test(n)?null:n.startsWith("@")?/^@[^@\s]+\.[^@\s]+$/.test(n)?n:null:/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(n)?n:null}function Dn(s,n,a){const i=s.admins.filter(c=>c!==n),r=s.members.filter(c=>c!==n);return a==="admin"?{admins:[...i,n],members:r}:{admins:i,members:[...r,n]}}function Om(s,n){return{admins:s.admins.filter(a=>a!==n),members:s.members.filter(a=>a!==n)}}function _n(s,n){const a=s.replace(/\/+$/,"");return n.startsWith("@")?`${a}/pair`:`${a}/pair?email=${encodeURIComponent(n)}`}function Mm(s,n,a){const i=[],r=new Set,c=(o,d)=>{const m=o.trim().toLowerCase();if(!m||r.has(m))return;r.add(m);const u=n.filter(p=>p.email?.toLowerCase()===m),x=a.find(p=>p.key===`user:${m}`);i.push({entry:m,role:d,isDomain:m.startsWith("@"),lastSeenAt:u.length?Math.max(...u.map(p=>p.lastSeenAt)):null,devices:u.length,turns:x?.turns??0,costUsd:x?.costUsd??null,...ot(x?.estimatedUsd)&&x.estimatedUsd>0?{estimated:!0}:{}})};for(const o of s.admins)c(o,"admin");for(const o of s.members)c(o,"member");return i}function zm(s,n){const a=new Map;for(const i of s){const r=i.email?.trim().toLowerCase();r&&a.set(r,[...a.get(r)??[],i])}return[...a.entries()].map(([i,r])=>{const c=n.find(o=>o.key===`user:${i}`);return{entry:i,role:r.some(o=>o.scopes?.includes("admin"))?"admin":"member",isDomain:!1,lastSeenAt:Math.max(...r.map(o=>o.lastSeenAt)),devices:r.length,turns:c?.turns??0,costUsd:c?.costUsd??null}}).sort((i,r)=>i.role===r.role?i.entry.localeCompare(r.entry):i.role==="admin"?-1:1)}function Um(s,n=Date.now()){return s===null?t("people.never"):n-s<1440*6e4?t("people.today"):new Date(s).toISOString().slice(0,10)}function Fi({people:s,busy:n,onRole:a,onRemove:i,onLink:r,readOnly:c=!1}){if(s.length===0)return e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t(c?"people.portal.empty":"people.empty")});const o="grid grid-cols-[1fr_auto_auto_auto_auto] items-center gap-x-4";return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:z(o,"border-b border-hairline/40 pb-2 text-[12px] font-medium uppercase tracking-wide text-ink-secondary"),children:[e.jsx("span",{children:t("people.colPerson")}),e.jsx("span",{children:t("people.colRole")}),e.jsx("span",{className:"text-right",children:t("people.colLastSeen")}),e.jsx("span",{className:"text-right",children:t("people.colMonth")}),e.jsx("span",{})]}),s.map(d=>e.jsxs("div",{className:z(o,"border-b border-hairline/20 py-2 text-[13px]"),children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-ink",children:d.isDomain?t("people.everyoneAt",{domain:d.entry.slice(1)}):d.entry}),d.devices>0&&e.jsx("span",{className:"block text-[12px] text-ink-secondary",children:t("people.devices",{count:String(d.devices)})})]}),e.jsx("span",{className:z("rounded-full px-2 py-0.5 text-[11px] font-medium",d.role==="admin"?"bg-accent/15 text-accent":"bg-control text-ink-secondary"),children:d.role==="admin"?t("people.roleAdmin"):t("people.roleMember")}),e.jsx("span",{className:"text-right tabular-nums text-ink-secondary",children:d.isDomain?"—":Um(d.lastSeenAt)}),e.jsx("span",{className:"text-right tabular-nums text-ink",title:t("people.turns",{turns:String(d.turns)}),children:ot(d.costUsd)?`${d.estimated?"~":""}${ct(d.costUsd)}`:"—"}),c?e.jsx("span",{}):e.jsxs("span",{className:"flex items-center justify-end gap-2 text-[12px]",children:[e.jsx("button",{type:"button",disabled:n,onClick:()=>r(d),"aria-label":t("people.link"),title:t("people.link"),className:"rounded-md p-1 text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50",children:e.jsx(lo,{size:13})}),e.jsx("button",{type:"button",disabled:n,onClick:()=>a(d,d.role==="admin"?"member":"admin"),className:"text-ink-secondary hover:text-ink disabled:opacity-50",children:d.role==="admin"?t("people.makeMember"):t("people.makeAdmin")}),e.jsx("button",{type:"button",disabled:n,onClick:()=>i(d),className:"text-danger hover:underline disabled:opacity-50",children:t("people.remove")})]})]},d.entry))]})}function Di({link:s}){const{state:n,copy:a}=Ss(s);return e.jsxs("div",{className:"mt-3 rounded-lg border border-hairline/40 bg-inset p-3 text-[13px]",children:[e.jsx("div",{className:"mb-1 text-ink-secondary",children:t("people.link")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"min-w-0 flex-1 select-all break-all text-ink",children:s}),e.jsxs("button",{type:"button",onClick:a,className:"flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[12px] text-ink-secondary hover:bg-control hover:text-ink",children:[n==="copied"?e.jsx(be,{size:13,className:"text-success"}):n==="failed"?e.jsx($e,{size:13,className:"text-danger"}):e.jsx(Ea,{size:13}),t(n==="copied"?"people.copied":n==="failed"?"common.copyFailed":"people.copy")]})]}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("people.linkHint")})]})}function Fm({peopleUrl:s,people:n}){const a=()=>{};return e.jsxs(Y,{title:t("people.title"),subtitle:t("people.portal.subtitle"),children:[e.jsxs("div",{"data-people-portal":!0,className:"flex flex-col gap-3 text-[13px] leading-relaxed text-ink-secondary",children:[e.jsx("p",{children:t("people.portal.managed")}),s&&e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"flex w-fit items-center gap-2 rounded-lg bg-control px-3 py-2 font-medium text-ink hover:bg-control/70",children:[t("people.portal.open")," ",e.jsx(pt,{size:14,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Fi,{people:n,busy:!1,readOnly:!0,onRole:a,onRemove:a,onLink:a})}),e.jsx("p",{className:"mt-3 text-[12px] leading-relaxed text-ink-secondary",children:t("people.portal.note")})]})}function _i({simple:s=!1,startOpen:n=!1}){const[a,i]=l.useState(n),[r,c]=l.useState(!1),[o,d]=l.useState(null),[m,u]=l.useState(null),[x,p]=l.useState(null),[g,f]=l.useState([]),[y,b]=l.useState(typeof window<"u"?window.location.origin:""),[h,k]=l.useState(null),[S,E]=l.useState(""),[N,P]=l.useState("member"),[j,B]=l.useState(null),[v,A]=l.useState(!1),[T,$]=l.useState(!1),[U,Z]=l.useState(null),H=l.useCallback(async()=>{$(!0),Z(null);try{const[L,X,se,he,pe]=await Promise.all([M("/api/config"),M("/api/auth/sessions").catch(()=>({sessions:[]})),M("/api/usage?groupBy=user").catch(()=>({groups:[]})),M("/api/settings/custom-domain").catch(()=>null),fetch("/.well-known/openmausbot/environment").then(te=>te.ok?te.json():null).catch(()=>null)]),ce={admins:Array.isArray(L?.signIn?.admins)?L.signIn.admins:[],members:Array.isArray(L?.signIn?.members)?L.signIn.members:[]},ue=xd(L);u(ue),p(ce);const w=Array.isArray(X?.sessions)?X.sessions:[],re=Array.isArray(se?.groups)?se.groups:[];f(ue.authority==="portal"?zm(w,re):Mm(ce,w,re)),typeof he?.publicUrl=="string"&&he.publicUrl&&b(he.publicUrl),k(pe?.capabilities?.emailSignIn===!0?!0:pe?!1:null)}catch(L){Z(L instanceof Error?L.message:String(L))}finally{$(!1)}},[]);l.useEffect(()=>{gd().then(L=>{d(L),dn(L)&&H()})},[H]);const ne=async L=>{A(!0),Z(null);try{await M("/api/config",{method:"PUT",body:JSON.stringify({signIn:L})}),await H()}catch(X){Z(X instanceof Error?X.message:String(X))}finally{A(!1)}},ae=async()=>{if(c(!0),!x||v)return;const L=Bm(S);if(!L){Z(t("remote.signInAccess.invalid"));return}await ne(Dn(x,L,N)),E(""),B(_n(y,L))};if(!dn(o))return null;const oe=m?.authority==="portal"?e.jsx(Fm,{peopleUrl:m.peopleUrl,people:g}):null,F=e.jsxs(e.Fragment,{children:[h===!1&&(!s||r)&&e.jsx("p",{className:"mb-3 rounded-lg border border-warning/25 bg-warning/5 px-3 py-2 text-[13px] text-ink-secondary",children:t(m?.pairingCodes===!1?"people.portalSignIn":"people.notHosted")}),e.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:L=>{L.preventDefault(),ae()},children:[e.jsx("input",{value:S,onChange:L=>E(L.target.value),placeholder:t("remote.signInAccess.placeholder"),"aria-label":t("people.inviteEmail"),disabled:v,className:"min-w-[16rem] flex-1 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none disabled:opacity-50"}),e.jsxs(ge,{value:N,onChange:L=>P(L.target.value),"aria-label":t("people.colRole"),disabled:v,children:[e.jsx("option",{value:"member",children:t("people.roleMember")}),e.jsx("option",{value:"admin",children:t("people.roleAdmin")})]}),e.jsxs("button",{type:"submit",disabled:v||!S.trim(),className:"ui-button ui-button-primary",children:[v?e.jsx(J,{size:13,className:"animate-spin"}):e.jsx(we,{size:13}),t("people.invite")]}),e.jsx("button",{type:"button",onClick:()=>{H()},disabled:T||v,"aria-label":t("people.refresh"),title:t("people.refresh"),className:"rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50",children:e.jsx(Ae,{size:13,className:z(T&&"animate-spin")})})]}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("people.inviteHint")}),j&&e.jsx(Di,{link:j}),U&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:U}),e.jsx("div",{className:"mt-4",children:e.jsx(Fi,{people:g,busy:v,onRole:(L,X)=>{x&&ne(Dn(x,L.entry,X))},onRemove:L=>{x&&ne(Om(x,L.entry))},onLink:L=>B(_n(y,L.entry))})}),!s&&e.jsx("p",{className:"mt-3 text-[12px] leading-relaxed text-ink-secondary",children:t("people.note")})]});return s?e.jsxs("div",{"data-people-summary":"",children:[e.jsxs("div",{role:"group","aria-label":t("people.title"),className:"flex min-w-0 items-center gap-3 px-4 py-[13px]",children:[e.jsx("span",{"aria-hidden":"true",className:"flex size-11 shrink-0 items-center justify-center rounded-full bg-ink/[0.06] text-ink-secondary",children:e.jsx(Ct,{size:20})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[14px] leading-5 text-ink",children:t("people.title")}),e.jsx("div",{className:"text-[13px] leading-[18px] text-ink-secondary",children:t("settings.simple.people")})]}),e.jsx("button",{type:"button","aria-expanded":a,className:"ui-button shrink-0",onClick:()=>i(!a),children:a?t("common.done"):t("settings.simple.people.invite")})]}),a&&e.jsx("div",{className:"px-3.5 pb-3.5 pt-1",children:oe??F})]}):oe??e.jsx(Y,{title:t("people.title"),subtitle:t("people.subtitle"),children:F})}const as="rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none [color-scheme:dark]";function Dm({entry:s}){const[n,a]=l.useState(!1),i=s.type==="admin"&&(s.changed?.length||s.before||s.after);return e.jsx("li",{className:"border-b border-hairline/20 py-2 text-[13px]","data-activity-entry":s.type,children:e.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-start gap-x-3",children:[e.jsx("time",{className:"whitespace-nowrap tabular-nums text-ink-secondary",dateTime:s.at,children:new Date(s.at).toLocaleString(ws())}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2",children:[e.jsx("span",{className:"font-medium text-ink",children:Cd(s.who)}),e.jsx("span",{className:"min-w-0 break-words text-ink",children:Ed(s)})]}),s.type==="approval"&&s.summary&&e.jsx("div",{className:"mt-0.5 truncate text-[12px] text-ink-secondary",children:oo(s.summaryCode,s.summary,s.summaryParams)}),i&&e.jsxs("button",{type:"button",onClick:()=>a(!n),"aria-expanded":n,className:"cursor-pointer mt-0.5 flex items-center gap-1 text-[12px] text-ink-secondary hover:text-ink",children:[e.jsx(Ps,{size:12,className:z("transition-transform",n&&"rotate-90")}),t("activity.changed",{paths:(s.changed??[]).join(", ")||"—"})]}),i&&n&&s.type==="admin"&&e.jsxs("dl",{className:"mt-1 grid grid-cols-[auto_1fr_1fr] gap-x-3 gap-y-0.5 rounded-lg bg-inset p-2 text-[12px]",children:[e.jsx("dt",{}),e.jsx("dd",{className:"text-ink-secondary",children:t("activity.before")}),e.jsx("dd",{className:"text-ink-secondary",children:t("activity.after")}),(s.changed??Object.keys({...s.before,...s.after})).map(r=>e.jsxs("div",{className:"contents",children:[e.jsx("dt",{className:"font-mono text-ink-secondary",children:r}),e.jsx("dd",{className:"min-w-0 break-all font-mono text-ink",children:An(s.before?.[r])}),e.jsx("dd",{className:"min-w-0 break-all font-mono text-ink",children:An(s.after?.[r])})]},r))]})]})]})})}function $i(){const[s,n]=l.useState({who:"",what:"all",from:"",to:""}),[a,i]=l.useState([]),[r,c]=l.useState(0),[o,d]=l.useState(null),[m,u]=l.useState(!1),[x,p]=l.useState(null),g=wd(s),f=l.useCallback(async()=>{u(!0),p(null);try{const b=await M(`/api/admin-activity${g}`);i(b.entries),c(b.total),d(b.retentionDays)}catch(b){p(b instanceof Error?b.message:String(b))}finally{u(!1)}},[g]);l.useEffect(()=>{const b=window.setTimeout(()=>{f()},250);return()=>window.clearTimeout(b)},[f]);const y=b=>n(h=>({...h,...b}));return e.jsxs(Y,{title:t("activity.title"),subtitle:t("activity.subtitle",{days:String(o??180)}),children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("activity.who"),e.jsx("input",{value:s.who,onChange:b=>y({who:b.target.value}),placeholder:t("activity.whoPlaceholder"),className:z(as,"w-44")})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("activity.what"),e.jsx(ge,{value:s.what,onChange:b=>y({what:b.target.value}),children:Sd.map(b=>e.jsx("option",{value:b,children:t(`activity.what.${b}`)},b))})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("activity.from"),e.jsx("input",{type:"date",value:s.from,max:s.to||void 0,onChange:b=>y({from:b.target.value}),className:as})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("activity.to"),e.jsx("input",{type:"date",value:s.to,min:s.from||void 0,onChange:b=>y({to:b.target.value}),className:as})]}),e.jsx("button",{type:"button",onClick:()=>{f()},disabled:m,"aria-label":t("activity.refresh"),title:t("activity.refresh"),className:"cursor-pointer rounded-md p-2 text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50",children:m?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(Ae,{size:14})}),e.jsxs("a",{href:`/api/admin-activity.csv${g}`,download:!0,className:"ui-button hover:bg-raised-hover",children:[e.jsx(Ye,{size:13,"aria-hidden":"true"}),t("activity.export")]})]}),x&&e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:t("activity.error",{message:x})}),!x&&a.length===0&&!m&&e.jsx("p",{className:"mt-4 text-[13px] text-ink-secondary",children:t("activity.empty")}),a.length>0&&e.jsx("ul",{className:"mt-3 flex flex-col",children:a.map((b,h)=>e.jsx(Dm,{entry:b},`${b.at}-${h}`))}),r>a.length&&e.jsx("p",{className:"mt-3 text-[12px] text-ink-secondary",children:t("activity.more",{shown:String(a.length),total:String(r)})})]})}const $n=4,_s="flex w-full min-w-0 items-center gap-3 px-3 py-2 text-start",$s="flex flex-col divide-y divide-hairline/30 overflow-hidden rounded-xl border border-hairline/40 bg-card",_m=s=>s.filter(n=>!n.hidden&&!n.defaultBot?.person).sort((n,a)=>n.name.localeCompare(a.name)),Ki=(s,n)=>Ut(s)===n||Ha(Ft(s),n)!=="none",Hi=(s,n)=>{const a=$a(s,n);return a?t("lookedAfter.line",{name:a.name}):t("lookedAfter.nobody")},Kn=(s,...n)=>n.some(a=>a?.toLowerCase().includes(s));function $m(){const{state:s}=G(),n=co(),a=uo(),i=l.useRef(null),[r,c]=l.useState("bot"),[o,d]=l.useState(""),[m,u]=l.useState(null),[x,p]=l.useState(null),g=l.useRef(null),[f,y]=l.useState(null),[b,h]=l.useState(""),k=l.useCallback(()=>y(null),[]);if(l.useEffect(()=>{x||!g.current||([...i.current?.querySelectorAll("[data-access-person]")??[]].find(v=>v.dataset.accessPerson===g.current)?.focus(),g.current=null)},[x]),!n||!a)return null;const S=n.people.filter(v=>v.role==="member").sort((v,A)=>v.name.localeCompare(A.name)),E=_m(s.bots),N=m?E.find(v=>v.id===m):void 0,P=x?S.find(v=>v.email===x):void 0,j=o.trim().toLowerCase(),B=async(v,A,T)=>{h("");const $=Ft(v);try{await un(v.id,A),y({botId:v.id,before:$,after:A,text:T})}catch(U){h(U instanceof Error?U.message:String(U))}};return e.jsxs("div",{ref:i,className:"flex min-w-0 flex-col gap-3","data-access-overview":!0,children:[P?e.jsx(Gm,{person:P,bots:E.filter(v=>Ki(v,P.email)),team:n,teamName:a,apply:B,onBack:()=>{g.current=P.email,p(null)}}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"ps-4 text-[13px] leading-relaxed text-ink-secondary",children:t("botAccess.overview.introUse",{team:a})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[180px] flex-1",children:[e.jsx(mt,{size:14,"aria-hidden":"true",className:"pointer-events-none absolute start-2.5 top-1/2 -translate-y-1/2 text-ink-secondary"}),e.jsx("input",{type:"search",value:o,"data-access-search":!0,"aria-label":t(r==="bot"?"botAccess.overview.searchBots":"botAccess.overview.searchPeople"),placeholder:t(r==="bot"?"botAccess.overview.searchBots":"botAccess.overview.searchPeople"),onChange:v=>d(v.target.value),onKeyDown:v=>{v.key==="Escape"&&o&&(v.preventDefault(),d(""))},className:"w-full rounded-lg border border-hairline/50 bg-transparent py-1.5 pe-2.5 ps-8 text-[13px] text-ink placeholder:text-ink-secondary focus:border-focus focus:outline-none"})]}),e.jsx("div",{role:"group","aria-label":t("botAccess.overview.listBy"),className:"flex shrink-0 rounded-full bg-raised/70 p-0.5",children:["bot","person"].map(v=>e.jsx("button",{type:"button","aria-pressed":r===v,"data-access-listing":v,onClick:()=>{c(v),d("")},className:z("rounded-full px-3 py-1 text-[13px] leading-[18px]",r===v?"bg-menu font-medium text-ink shadow-sm":"text-ink-secondary hover:text-ink"),children:t(v==="bot"?"botAccess.overview.byBot":"botAccess.overview.byPerson")},v))})]}),r==="bot"?e.jsx(Km,{bots:E.filter(v=>!j||Kn(j,v.name,$a(v,n)?.name,Ut(v)??void 0)),anyBots:E.length>0,team:n,onOpen:u}):e.jsx(Wm,{people:S.filter(v=>!j||Kn(j,v.name,v.email)),anyPeople:S.length>0,bots:E,onOpen:p}),e.jsx("p",{className:"ps-4 text-[12px] text-ink-secondary",children:t("botAccess.admins")})]}),b&&e.jsx("p",{role:"alert",className:"text-[13px] text-danger",children:b}),N&&e.jsx(mo,{bot:N,teamName:a,onClose:()=>u(null),onChanged:v=>y({botId:N.id,...v})}),f&&e.jsx(po,{text:f.text,onUndo:()=>un(f.botId,f.before),onDone:k},`${f.botId}:${f.text}:${JSON.stringify(f.after)}`)]})}function Km({bots:s,anyBots:n,team:a,onOpen:i}){return n?s.length?e.jsx("ul",{className:$s,children:s.map(r=>{const c=Ft(r),o=Ut(r);return e.jsx("li",{className:"min-w-0",children:e.jsxs("button",{type:"button","aria-haspopup":"dialog","data-access-row":r.id,onClick:()=>i(r.id),className:z(_s,"hover:bg-ink/[0.06] focus-visible:bg-ink/[0.06] focus-visible:outline-none"),children:[e.jsx(Bt,{bot:r,size:32}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[14px] leading-[18px] text-ink",children:r.name}),e.jsx("span",{className:"block truncate text-[12px] leading-4 text-ink-secondary",children:Hi(r,a)})]}),e.jsx("span",{className:"min-w-0 max-w-[40%] truncate text-[13px] text-ink-secondary","data-access-summary":!0,children:c.everyone==="none"?t("botAccess.onlyAdded"):t("botAccess.overview.everyoneUses")}),e.jsx(Hm,{entries:Object.keys(c.people).filter(d=>d!==o),team:a})]})},r.id)})}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("botAccess.overview.noBotMatch")}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("botAccess.overview.noBots")})}function Hm({entries:s,team:n}){if(!s.length)return null;const a=s.map(r=>go(r,n)).join(", "),i=s.length-$n;return e.jsxs("span",{role:"img","aria-label":a,title:a,"data-access-stack":s.length,className:"flex shrink-0 -space-x-0.5 rtl:space-x-reverse",children:[s.slice(0,$n).map(r=>e.jsx("span",{className:"flex rounded-full ring-2 ring-card",children:e.jsx(ho,{person:fo(r,n),size:22})},r)),i>0&&e.jsxs("span",{className:"flex h-[22px] min-w-[22px] items-center justify-center rounded-full bg-card px-1 text-[11px] font-medium text-ink-secondary ring-2 ring-card",children:["+",i]})]})}function Wm({people:s,anyPeople:n,bots:a,onOpen:i}){return n?s.length?e.jsx("ul",{className:$s,children:s.map(r=>{const c=a.filter(o=>Ki(o,r.email)).length;return e.jsx("li",{className:"min-w-0",children:e.jsxs("button",{type:"button","data-access-person":r.email,onClick:()=>i(r.email),className:z(_s,"hover:bg-ink/[0.06] focus-visible:bg-ink/[0.06] focus-visible:outline-none"),children:[e.jsx(Ka,{person:r,size:32}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[14px] leading-[18px] text-ink",children:r.name}),e.jsx("span",{className:"block truncate text-[12px] leading-4 text-ink-secondary",children:r.email})]}),e.jsx("span",{className:"shrink-0 text-[13px] text-ink-secondary",children:c===1?t("botAccess.overview.botCount.one"):t("botAccess.overview.botCount.other",{count:c})})]})},r.email)})}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("botAccess.noMatch")}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("botAccess.overview.noPeople")})}function Gm({person:s,bots:n,team:a,teamName:i,apply:r,onBack:c}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{children:e.jsxs("button",{type:"button",autoFocus:!0,"data-access-back":!0,onClick:c,className:"-ms-2 flex items-center gap-1 rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-ink/[0.06] hover:text-ink",children:[e.jsx(Fr,{size:14,"aria-hidden":"true",className:"rtl:-scale-x-100"}),t("botAccess.overview.allPeople")]})}),e.jsxs("div",{className:"flex min-w-0 items-center gap-3 px-3",children:[e.jsx(Ka,{person:s,size:32}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[14px] font-medium leading-[18px] text-ink",children:s.name}),e.jsx("span",{className:"block truncate text-[12px] leading-4 text-ink-secondary",children:s.email})]})]}),n.length===0?e.jsx("p",{className:"px-3 text-[13px] text-ink-secondary",children:t("botAccess.overview.noBotsForPerson",{name:s.name})}):e.jsx("ul",{className:$s,children:n.map(o=>e.jsx(qm,{bot:o,person:s,team:a,teamName:i,apply:r},o.id))})]})}function qm({bot:s,person:n,team:a,teamName:i,apply:r}){const c=Ft(s),o=Ut(s)===n.email,d=c.people[n.email],m=Ha(c,n.email);return e.jsxs("li",{className:_s,"data-access-person-bot":s.id,children:[e.jsx(Bt,{bot:s,size:32}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[14px] leading-[18px] text-ink",children:s.name}),e.jsx("span",{className:"block truncate text-[12px] leading-4 text-ink-secondary",children:!d&&!o&&m===c.everyone?t("botAccess.everyoneUse",{team:i}):Hi(s,a)})]}),e.jsx("span",{className:"min-w-0 shrink-0 text-[13px] text-ink-secondary",children:o?e.jsx("span",{className:"px-2",children:t("lookedAfter.badge")}):d?e.jsx("button",{type:"button","data-access-remove":s.id,"aria-label":t("botAccess.overview.removeFrom",{name:n.name,bot:s.name}),onClick:()=>{r(s,xo(c,n.email,null),t("botAccess.overview.toastRemoved",{name:n.name,bot:s.name}))},className:"rounded-md px-2 py-1 hover:bg-ink/[0.06] hover:text-ink",children:t("botAccess.remove")}):null})]})}function Vm(s){const n=s.trim();if(!n||/[\s\\?#@%]/.test(n))return null;try{const a=new URL(n.includes("://")?n:`https://${n}`),i=a.hostname.replace(/\.$/,"");return a.protocol!=="https:"||a.port||a.pathname!=="/"||!i.includes(".")||i.length>253||/^[\d.]+$/.test(i)||!i.split(".").every(r=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))||/(?:^|\.)(?:localhost|local|internal|invalid|test)$/.test(i)?null:i}catch{return null}}function Jm({domain:s,serverIpv4:n}){const a=Vm(s);if(!a)return e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("settings.domain.enterDomain")});const i=[[t("settings.domain.recordType"),"A"],[t("settings.domain.recordName"),a],[t("settings.domain.recordValue"),n]];return e.jsxs("section",{"aria-label":t("settings.domain.dnsRecord"),className:"space-y-2 rounded-lg border border-hairline/50 p-3",children:[e.jsx("p",{className:"text-[12px] font-medium text-ink",children:t("settings.domain.dnsRecord")}),e.jsx("dl",{className:"space-y-2",children:i.map(([r,c])=>e.jsxs("div",{className:"grid grid-cols-[80px_minmax(0,1fr)] items-center gap-2",children:[e.jsx("dt",{className:"text-[12px] text-ink-secondary",children:r}),e.jsx("dd",{className:"min-w-0",children:c?e.jsx(rt,{command:c,copyLabel:t("settings.domain.copyField",{field:r})},c):e.jsx("p",{className:"text-[12px] text-warning",children:t("settings.domain.missingIp")})})]},r))}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.domain.recordHint")})]})}function Xm(s){return`bots.example.com {
2
+ handle /hooks/* {
3
+ reverse_proxy 127.0.0.1:${s.webhookPort}
4
+ }
5
+ handle {
6
+ reverse_proxy 127.0.0.1:${s.appPort} {
7
+ flush_interval -1
8
+ }
9
+ }
10
+ }`}function Ym({status:s}){return e.jsxs("details",{className:"rounded-lg border border-hairline/50 bg-inset px-3 py-2.5 text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"cursor-pointer font-medium text-ink",children:t("settings.domain.guide")}),e.jsxs("ol",{className:"mt-3 list-decimal space-y-3 pl-4 leading-relaxed",children:[e.jsx("li",{children:t("settings.domain.dns")}),e.jsxs("li",{children:[t("settings.domain.proxy"),e.jsx("pre",{className:"mt-2 overflow-x-auto rounded-md bg-app p-3 text-[11px] leading-relaxed text-ink",children:e.jsx("code",{children:Xm(s)})}),e.jsx("p",{className:"mt-2",children:t("settings.domain.proxyHint")})]}),e.jsx("li",{children:t("settings.domain.verifyHint")})]}),e.jsx("p",{className:"mt-3 text-warning",children:t("settings.domain.loopbackWarning")}),!s.serverIpv4&&e.jsx("p",{className:"mt-3",children:t("settings.domain.ipAdminHint")}),e.jsx("p",{className:"mt-3",children:t("settings.domain.scope")}),e.jsxs("a",{className:"mt-3 inline-flex items-center gap-1.5 text-accent hover:underline",href:"https://github.com/leomieo/limix-bot/blob/main/docs/self-hosting.md#connect-a-custom-domain-in-settings",target:"_blank",rel:"noopener noreferrer",children:[t("settings.domain.fullGuide")," ",e.jsx(pt,{size:12})]})]})}function Qm(){const[s,n]=l.useState(null),[a,i]=l.useState(""),[r,c]=l.useState("loading"),[o,d]=l.useState(null),[m,u]=l.useState(null);l.useEffect(()=>{const p=new AbortController;return M("/api/settings/custom-domain",{signal:p.signal}).then(g=>{p.signal.aborted||(n(g),i(g.customDomain??""))}).catch(g=>{p.signal.aborted||d(g instanceof Error?g.message:t("settings.domain.failed"))}).finally(()=>{p.signal.aborted||c(null)}),()=>p.abort()},[]);const x=async p=>{c(p?"removing":"saving"),d(null),u(null);try{const g=await M("/api/settings/custom-domain",{method:p?"DELETE":"POST",...p?{}:{body:JSON.stringify({domain:a.trim()})}});n(g),i(g.customDomain??""),u(p?t("settings.domain.removed"):t("settings.domain.saved"))}catch(g){d(g instanceof Error?g.message:t("settings.domain.failed"))}finally{c(null)}};return e.jsx(Y,{title:t("settings.domain.title"),subtitle:t("settings.domain.subtitle"),children:e.jsxs("div",{className:"space-y-3","data-custom-domain-settings":!0,children:[r==="loading"&&e.jsxs("p",{role:"status",className:"flex items-center gap-2 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:14,className:"animate-spin"}),t("settings.domain.loading")]}),s&&!s.supported&&e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("settings.domain.serverOnly")}),s?.supported&&e.jsxs(e.Fragment,{children:[e.jsxs("form",{onSubmit:p=>{p.preventDefault(),a.trim()&&!r&&x(!1)},className:"space-y-2",children:[e.jsx("label",{htmlFor:"custom-domain",className:"block text-[13px] font-medium text-ink",children:t("settings.domain.label")}),e.jsx("input",{id:"custom-domain",type:"text",value:a,disabled:r!==null,onChange:p=>{i(p.target.value),u(null),d(null)},placeholder:"bots.yourcompany.com",autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,className:"w-full rounded-lg border border-hairline/50 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:border-accent focus:outline-none disabled:opacity-50"}),e.jsx(Jm,{domain:a,serverIpv4:s.serverIpv4}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.domain.httpsNeeded")}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs("button",{type:"submit",disabled:!a.trim()||r!==null,className:"ui-button ui-button-primary",children:[r==="saving"?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(bo,{size:14}),r==="saving"?t("settings.domain.verifying"):t("settings.domain.verify")]}),s.customDomain&&e.jsx("button",{type:"button",disabled:r!==null,onClick:()=>{x(!0)},className:"rounded-lg bg-control px-3 py-2 text-[12px] font-medium text-ink hover:bg-raised-hover disabled:opacity-50",children:r==="removing"?t("settings.domain.removing"):t("settings.domain.remove")})]})]}),s.publicUrl&&e.jsxs("p",{className:"break-all text-[12px] text-ink-secondary",children:[t("settings.domain.current"),": ",e.jsx("span",{className:"text-ink",children:s.publicUrl})]}),s.customDomain&&e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:s.fallbackUrl?t("settings.domain.fallback",{url:s.fallbackUrl}):t("settings.domain.noFallback")}),e.jsx(Ym,{status:s})]}),m&&e.jsxs("p",{role:"status",className:"flex items-start gap-1.5 text-[12px] leading-relaxed text-success",children:[e.jsx(be,{size:14,className:"mt-0.5 shrink-0"}),m]}),o&&e.jsx("p",{role:"alert",className:"text-[12px] leading-relaxed text-danger",children:o})]})})}const Zm=yo,hs="w-full min-w-0 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5 text-[13px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent disabled:opacity-60",fs="flex flex-col gap-1 text-[12px] font-medium text-ink-secondary";function Wi({onSubmit:s,onCancel:n,pending:a,error:i,submitLabel:r,children:c,form:o}){return e.jsxs("form",{onSubmit:s,className:"flex flex-col gap-2.5","aria-busy":a,[`data-${o}`]:"",children:[c,e.jsxs("p",{className:"flex items-start gap-1 text-[12px] leading-snug text-ink-tertiary",children:[e.jsx(Dt,{size:11,"aria-hidden":"true",className:"mt-[3px] shrink-0"})," ",t("settings.vault.secret.private")]}),i&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:i}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:n,disabled:a,className:"ui-button ui-button-md",children:t("logins.cancel")}),e.jsxs("button",{type:"submit",disabled:a,className:"ui-button ui-button-md ui-button-primary inline-flex items-center gap-1.5",children:[a&&e.jsx(J,{size:13,className:"animate-spin"}),r]})]})]})}function Hn({secret:s,bots:n,onCancel:a,onSaved:i}){const[r,c]=l.useState(s?.name??""),[o,d]=l.useState(""),[m,u]=l.useState(s?.bots??"all"),[x,p]=l.useState(!1),[g,f]=l.useState(null),y=async b=>{if(b.preventDefault(),!x){p(!0),f(null);try{s?await vo(s.id,{...r.trim()!==s.name?{name:r.trim()}:{},value:o,bots:m}):await jo(r.trim(),o,m),d(""),await i()}catch(h){f(h instanceof Error&&h.message?h.message:t("settings.vault.secret.saveError"))}finally{p(!1)}}};return e.jsxs(Wi,{form:"secret-form",onSubmit:b=>{y(b)},onCancel:a,pending:x,error:g,submitLabel:t(s?"settings.logins.saveChange":"settings.vault.secret.save"),children:[e.jsxs("label",{className:fs,children:[t("settings.vault.secret.name"),e.jsx("input",{name:"secretName",type:"text",autoComplete:"off",spellCheck:!1,required:!0,maxLength:Zm,value:r,autoFocus:!0,placeholder:t("settings.vault.secret.namePlaceholder"),onChange:b=>c(b.target.value),disabled:x,className:hs}),e.jsx("span",{className:"text-[12px] font-normal leading-snug text-ink-tertiary",children:t("settings.vault.secret.nameHint")})]}),e.jsxs("label",{className:fs,children:[t(s?"settings.vault.secret.valueKeep":"settings.vault.secret.value"),e.jsx("input",{name:"secretValue",type:"password",autoComplete:"new-password",spellCheck:!1,required:!s,value:o,placeholder:"••••••••",onChange:b=>d(b.target.value),disabled:x,className:hs})]}),e.jsx(dt,{value:m,onChange:u,bots:n,disabled:x})]})}function ep({bots:s,onCancel:n,onSaved:a}){const[i,r]=l.useState(""),[c,o]=l.useState("all"),[d,m]=l.useState(!1),[u,x]=l.useState(null),[p,g]=l.useState(null),f=async y=>{if(y.preventDefault(),d)return;const b=ko(i);if(!b.length){x(t("settings.vault.env.none"));return}m(!0),x(null),g(null);try{g(await No(b,c)),r("")}catch(h){x(h instanceof Error&&h.message?h.message:t("settings.vault.secret.saveError"))}finally{m(!1),await a().catch(()=>{})}};return e.jsxs(Wi,{form:"env-form",onSubmit:y=>{f(y)},onCancel:n,pending:d,error:u,submitLabel:t("settings.vault.env.submit"),children:[e.jsxs("label",{className:fs,children:[t("settings.vault.env.label"),e.jsx("textarea",{name:"envText",rows:5,autoComplete:"off",spellCheck:!1,autoFocus:!0,value:i,onChange:y=>r(y.target.value),disabled:d,placeholder:"STRIPE_SECRET_KEY=…",dir:"ltr",className:`${hs} font-mono`}),e.jsx("span",{className:"text-[12px] font-normal leading-snug text-ink-tertiary",children:t("settings.vault.env.hint")})]}),e.jsx(dt,{value:c,onChange:o,bots:s,disabled:d}),p!==null&&e.jsx("p",{role:"status",className:"text-[12px] text-ink-secondary",children:t("settings.vault.env.done",{count:String(p)})})]})}const Wn={card:"settings.logins.source.card",settings:"settings.logins.source.settings","1password":"settings.logins.source.1password",linked:"settings.logins.source.1password"},bs="flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-[12px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50",tp=[["login","settings.vault.addLogin"],["secret","settings.vault.addSecret"],["env","settings.vault.importEnv"]];function sp(s,n,a,i){const r=i.trim().toLowerCase();return[...a==="secrets"?[]:s.map(o=>({kind:"login",key:[o.site,o.username,...o.hosts].join(" "),login:o})),...a==="logins"?[]:n.map(o=>({kind:"secret",key:o.name,secret:o}))].filter(o=>!r||o.key.toLowerCase().includes(r)).sort((o,d)=>o.key.localeCompare(d.key))}function Gi(){const{state:s,dispatch:n}=G(),a=Ot(),i=s.bots.map(C=>({id:C.id,name:C.name})),[r,c]=l.useState(null),[o,d]=l.useState([]),[m,u]=l.useState({connected:!1}),[x,p]=l.useState(null),[g,f]=l.useState(""),[y,b]=l.useState("all"),[h,k]=l.useState(!1),[S,E]=l.useState(null),[N,P]=l.useState(""),[j,B]=l.useState("all"),[v,A]=l.useState(!1),[T,$]=l.useState(null),[U,Z]=l.useState("all"),[H,ne]=l.useState(!1),[ae,oe]=l.useState(!1),[F,L]=l.useState(null),[X,se]=l.useState(!1),[he,pe]=l.useState([]),ce=async()=>{try{const C=await Co();c(C.logins??[]),d(C.secrets??[]),u(C.onePassword??{connected:!1}),p(null)}catch(C){p(C instanceof Error&&C.message?C.message:t("settings.vault.loadError"))}};if(l.useEffect(()=>{a&&ce()},[a]),a===!1)return e.jsx(Y,{title:t("settings.vault.title"),subtitle:t("settings.vault.adminOnly")});const ue=C=>{if(C==="all")return t("settings.logins.allBots");const W=C.flatMap(xe=>i.find(V=>V.id===xe)?.name??[]);return W.length?W.join(", "):t("settings.logins.noBots")},w=C=>C?t("settings.logins.used",{when:ai(C)}):t("settings.logins.neverUsed"),re=(C,W)=>{E(null),L(null),oe(!1),W&&(Z(W.bots),ne(W.exactHost)),$(C)},te=C=>{k(!1),$(null),L(null),E(C)},ee=async(C,W)=>{if(F!==C){L(C);return}se(!0),pe([]);try{W==="login"?await Po(C):pe(await To(C)),L(null),await ce()}catch(xe){p(xe instanceof Error&&xe.message?xe.message:t("settings.logins.deleteError"))}finally{se(!1)}},K=(C,W,xe,V)=>e.jsxs("div",{className:"flex shrink-0 gap-1",children:[e.jsx("button",{type:"button",className:bs,disabled:X,onClick:V,"aria-label":W==="login"?t("settings.logins.changeFor",{site:xe}):t("settings.vault.secret.changeFor",{name:xe}),children:t("settings.logins.change")}),e.jsxs("button",{type:"button",className:bs,disabled:X,onClick:()=>{ee(C,W)},"aria-label":F===C?t("settings.logins.deleteConfirm"):W==="login"?t("settings.logins.deleteFor",{site:xe}):t("settings.vault.secret.deleteFor",{name:xe}),children:[e.jsx(Se,{size:13}),F===C?t("settings.logins.deleteConfirm"):t("settings.logins.delete")]})]}),le=sp(r??[],o,y,g),_=r!==null&&r.length===0&&o.length===0,ie=C=>e.jsxs("li",{className:"flex flex-col gap-2 py-2.5","data-login-row":C.site,children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx(Dt,{size:14,"aria-hidden":"true",className:"mt-[3px] shrink-0 text-ink-tertiary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5",children:[e.jsx("span",{dir:"ltr",className:"truncate text-[13px] font-medium text-ink",title:C.site,children:C.site}),C.hasTotp&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-full bg-ink/[0.07] px-1.5 text-[11px] text-ink-secondary",children:[e.jsx(Eo,{size:11,"aria-hidden":"true"}),t("settings.logins.twoFactor")]})]}),e.jsx("div",{dir:"auto",className:"truncate text-[12px] text-ink-secondary",children:C.username||t("settings.logins.noUsername")}),Gn(C)&&e.jsx("div",{dir:"ltr",className:"truncate text-[12px] text-ink-tertiary","data-login-hosts":!0,children:Gn(C)}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-snug text-ink-tertiary",children:[t(Wn[C.source]),ue(C.bots),w(C.lastUsedAt)].join(" · ")}),pn(C,s.bots).length>0&&e.jsx("div",{className:"mt-0.5 text-[12px] leading-snug text-warning","data-login-held-back":!0,children:t("settings.logins.sharedBrowser",{bots:ue(pn(C,s.bots))})})]}),C.source!=="1password"&&K(C.id,"login",C.site,()=>re(C.id,C))]}),T===C.id&&e.jsx("div",{className:"ms-6 rounded-lg bg-inset/60 p-3",children:e.jsxs(mn,{username:!1,replacing:!0,submitLabel:t("settings.logins.saveChange"),autoFocus:!0,onCancel:()=>$(null),onSubmit:async W=>{await Ao(C.id,{password:W.password,totp:W.totp,removeTotp:ae,bots:U,...H===C.exactHost?{}:{exactHost:H}}),$(null),await ce()},children:[C.hasTotp&&e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-ink",children:[e.jsx("input",{type:"checkbox",checked:ae,onChange:W=>oe(W.target.checked)}),t("settings.logins.removeTotp")]}),e.jsx(qn,{checked:H,onChange:ne,label:t("settings.logins.exactHostFor",{hosts:C.hosts.join(", "),site:C.site})}),e.jsx(dt,{value:U,onChange:Z,bots:i})]})})]},C.id),I=C=>e.jsxs("li",{className:"flex flex-col gap-2 py-2.5","data-secret-row":C.name,children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx(Wa,{size:14,"aria-hidden":"true",className:"mt-[3px] shrink-0 text-ink-tertiary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{dir:"auto",className:"truncate text-[13px] font-medium text-ink",title:C.name,children:C.name}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-snug text-ink-tertiary",children:[t(Wn[C.source]),ue(C.bots),w(C.lastUsedAt)].join(" · ")})]}),C.source!=="linked"&&K(C.id,"secret",C.name,()=>re(C.id))]}),T===C.id&&C.source!=="linked"&&e.jsx("div",{className:"ms-6 rounded-lg bg-inset/60 p-3",children:e.jsx(Hn,{secret:C,bots:i,onCancel:()=>$(null),onSaved:async()=>{$(null),await ce()}})})]},C.id);return e.jsx(Y,{title:t("settings.vault.title"),subtitle:t("settings.vault.subtitle"),children:e.jsxs("div",{className:"flex flex-col gap-3","aria-busy":r===null||X,"data-vault":!0,children:[s.config?.cloudHome===!0&&e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary","data-logins-cloud-own":!0,children:t("settings.logins.cloudOwn")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"flex h-8 min-w-[12rem] flex-1 items-center gap-2 rounded-lg bg-ink/[0.05] px-[9px] focus-within:ring-2 focus-within:ring-focus/60",children:[e.jsx(mt,{size:15,"aria-hidden":"true",className:"shrink-0 text-ink-secondary"}),e.jsx("input",{"data-vault-search":!0,type:"text",value:g,onChange:C=>f(C.target.value),autoComplete:"off",spellCheck:!1,placeholder:t("settings.vault.search"),"aria-label":t("settings.vault.search"),className:"w-full min-w-0 bg-transparent text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",className:"ui-button ui-button-md",disabled:r===null,"aria-expanded":h,onClick:()=>k(!h),onKeyDown:C=>{C.key==="Escape"&&k(!1)},children:[e.jsx(we,{size:14}),t("settings.vault.add"),e.jsx(Sa,{size:13,"aria-hidden":"true"})]}),h&&e.jsx("div",{className:"absolute end-0 top-full z-10 mt-1 flex min-w-[11rem] flex-col rounded-lg border border-hairline/60 bg-menu p-1 shadow-lg","data-vault-add":!0,children:tp.map(([C,W])=>e.jsx("button",{type:"button",className:"rounded-md px-2.5 py-1.5 text-start text-[13px] text-ink hover:bg-control",onClick:()=>te(C),children:t(W)},C))})]})]}),e.jsx(wo,{label:t("settings.vault.filter"),attr:"data-vault-filter",value:y,onChange:b,options:[{value:"all",label:t("settings.vault.filter.all")},{value:"logins",label:t("settings.vault.filter.logins")},{value:"secrets",label:t("settings.vault.filter.secrets")}]}),S==="login"&&e.jsx("div",{className:"rounded-lg bg-inset/60 p-3",children:e.jsxs(mn,{site:{value:N,onChange:P},submitLabel:t("settings.logins.save"),autoFocus:!0,onCancel:()=>E(null),onSubmit:async C=>{await So(N,C,j,v),E(null),P(""),B("all"),A(!1),await ce()},children:[e.jsx(qn,{checked:v,onChange:A,label:t("settings.logins.exactHost")}),e.jsx(dt,{value:j,onChange:B,bots:i})]})}),S==="secret"&&e.jsx("div",{className:"rounded-lg bg-inset/60 p-3",children:e.jsx(Hn,{bots:i,onCancel:()=>E(null),onSaved:async()=>{E(null),await ce()}})}),S==="env"&&e.jsx("div",{className:"rounded-lg bg-inset/60 p-3",children:e.jsx(ep,{bots:i,onCancel:()=>E(null),onSaved:ce})}),r===null&&!x&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("settings.vault.loading")}),_&&!S&&e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.vault.empty")}),!_&&r!==null&&le.length===0&&e.jsx("p",{className:"text-[12px] text-ink-secondary","data-vault-none":!0,children:t("settings.vault.noMatch")}),le.length>0&&e.jsx("ul",{className:"divide-y divide-hairline/30","data-logins-list":!0,children:le.map(C=>C.kind==="login"?ie(C.login):I(C.secret))}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-tertiary",children:t("settings.logins.limits")}),he.length>0&&e.jsx("p",{role:"status",className:"text-[12px] leading-relaxed text-warning","data-vault-keys-off":!0,children:t("settings.vault.secret.keyOff",{servers:he.join(", ")})}),x&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:x}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-hairline/30 pt-3","data-vault-keys":!0,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] font-medium text-ink",children:t("settings.vault.keys.title")}),e.jsx("div",{className:"text-[12px] leading-snug text-ink-tertiary",children:t("settings.vault.keys.hint")})]}),e.jsx("button",{type:"button",className:"ui-button ui-button-md shrink-0",onClick:()=>n({type:"toggleAppSettings",open:!0,section:"connections"}),children:t("keys.row.open")})]}),e.jsx(ap,{status:m,disabled:r===null,bots:i,botNames:ue,onChange:async C=>{u(C),await ce()}})]})})}function Gn(s){if(s.exactHost)return t("settings.logins.onlyOn",{hosts:s.hosts.join(", ")});const n=s.hosts.filter(a=>a!==s.site);return n.length?t("settings.logins.signsInOn",{hosts:n.join(", ")}):null}function qn({checked:s,onChange:n,label:a}){return e.jsxs("label",{className:"flex items-start gap-2 text-[13px] leading-snug text-ink",children:[e.jsx("input",{type:"checkbox",name:"exactHost",className:"mt-[2px]",checked:s,onChange:i=>n(i.target.checked)}),a]})}function np({vault:s,bots:n,botNames:a,disabled:i,onChange:r}){const[c,o]=l.useState(!1),[d,m]=l.useState(s.bots),[u,x]=l.useState(!1),[p,g]=l.useState(null),f=async()=>{x(!0),g(null);try{await r(await Ro(s.id,d)),o(!1)}catch(y){g(y instanceof Error&&y.message?y.message:t("settings.logins.onePassword.error"))}finally{x(!1)}};return e.jsxs("li",{className:"flex flex-col gap-2 py-2","data-vault":s.title,children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] font-medium text-ink",children:s.title}),e.jsx("div",{className:"text-[12px] text-ink-tertiary",children:t("settings.logins.onePassword.vaultUse",{count:String(s.items),who:a(s.bots)})})]}),!c&&e.jsx("button",{type:"button",className:bs,disabled:i||u,onClick:()=>{m(s.bots),o(!0)},"aria-label":t("settings.logins.onePassword.changeVault",{vault:s.title}),children:t("settings.logins.change")})]}),c&&e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg bg-inset/60 p-3",children:[e.jsx(dt,{value:d,onChange:m,bots:n,disabled:u}),p&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:p}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx("button",{type:"button",className:"ui-button ui-button-md",disabled:u,onClick:()=>o(!1),children:t("logins.cancel")}),e.jsx("button",{type:"button",className:"ui-button ui-button-md ui-button-primary",disabled:u,onClick:()=>{f()},children:t("settings.logins.saveChange")})]})]})]})}function ap({status:s,disabled:n,bots:a,botNames:i,onChange:r}){const[c,o]=l.useState(""),[d,m]=l.useState(null),[u,x]=l.useState(null),p=async(f,y)=>{if(!d){m(f),x(null);try{await r(await y()),f==="connect"&&o("")}catch(b){x(b instanceof Error&&b.message?b.message:t("settings.logins.onePassword.error"))}finally{m(null)}}},g=f=>{f.preventDefault(),c.trim()&&p("connect",()=>Io(c.trim()))};return e.jsxs("section",{className:"mt-1 flex flex-col gap-2 border-t border-hairline/30 pt-3","aria-label":t("settings.vault.manager"),"data-onepassword":!0,children:[e.jsx("div",{className:"text-[13px] font-medium text-ink",children:t("settings.vault.manager")}),e.jsx("div",{className:"text-[12px] font-medium text-ink-secondary",children:t("settings.logins.onePassword.title")}),s.connected?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-snug text-ink-secondary",children:t("settings.logins.onePassword.connected",{vaults:(s.vaults??[]).map(f=>f.title).join(", ")||"—",count:String(s.items??0)})}),s.error&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:s.error}),!!s.vaults?.length&&e.jsx("ul",{className:"divide-y divide-hairline/30","aria-label":t("settings.logins.onePassword.vaults"),children:s.vaults.map(f=>e.jsx(np,{vault:f,bots:a,botNames:i,disabled:n,onChange:r},f.id))}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{type:"button",className:"ui-button ui-button-md",disabled:n||d!==null,onClick:()=>{p("refresh",Lo)},children:[d==="refresh"?e.jsx(J,{size:13,className:"animate-spin"}):e.jsx(Ae,{size:13}),t("settings.logins.onePassword.refresh")]}),e.jsx("button",{type:"button",className:"ui-button ui-button-md",disabled:n||d!==null,onClick:()=>{p("disconnect",Bo)},children:t("settings.logins.onePassword.disconnect")})]})]}):e.jsxs("form",{className:"flex flex-col gap-2",onSubmit:g,children:[e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.logins.onePassword.guide")}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{name:"onePasswordToken",type:"password",autoComplete:"off",spellCheck:!1,maxLength:8192,value:c,onChange:f=>o(f.target.value),disabled:n||d!==null,"aria-label":t("settings.logins.onePassword.token"),placeholder:t("settings.logins.onePassword.token"),className:"min-w-0 flex-1 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5 text-[13px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent disabled:opacity-60"}),e.jsxs("button",{type:"submit",className:"ui-button ui-button-md ui-button-primary",disabled:n||d!==null||!c.trim(),children:[d==="connect"&&e.jsx(J,{size:13,className:"animate-spin"}),t("settings.logins.onePassword.connect")]})]})]}),e.jsxs("p",{className:"flex items-start gap-1 text-[12px] leading-snug text-ink-tertiary",children:[e.jsx(Dt,{size:11,"aria-hidden":"true",className:"mt-[3px] shrink-0"})," ",t("settings.logins.onePassword.note")]}),u&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:u})]})}const is="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink placeholder:text-ink-secondary focus:outline-none";function Vn(s){return String(s?.message??s).replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/,"")}function ip(s){const n=s.trim();if(!/^https?:\/\//i.test(n))return!1;const a=Dr(n);return a.ok&&(a.code!==null||a.credential!==null)}function rp({hideWhenUnavailable:s=!1,legacyOnly:n=!1}){const a=window.ogb?.remoteClient,i=window.ogb?.environments,[r,c]=l.useState({active:a?.active===!0}),[o,d]=l.useState(i?"server":"companion"),[m,u]=l.useState(""),[x,p]=l.useState(""),[g,f]=l.useState(""),[y,b]=l.useState(!1),[h,k]=l.useState(""),S=l.useRef(!1),E=!!i&&o==="server",N=l.useRef(!0),P=l.useCallback(()=>{a?.state().then(v=>{N.current&&c(v)}).catch(()=>{})},[a]);l.useEffect(()=>(N.current=!0,P(),()=>{N.current=!1}),[P]);const j=async()=>{if(!(S.current||!a&&!i)){S.current=!0,b(!0),k("");try{if(E&&i){if(!ip(m))throw new Error(t("remote.client.server.invalidLink"));await i.addFromLink(m.trim()),P()}else a&&(await a.pair(x,g),P())}catch(v){k(Vn(v))}finally{S.current=!1,b(!1)}}},B=async()=>{if(!(!a||S.current)){S.current=!0,b(!0),k("");try{await a.disconnect(),P()}catch(v){k(Vn(v))}finally{S.current=!1,b(!1)}}};return!a&&!i&&s||n&&!r.active?null:e.jsxs(Y,{title:r.active?t("remote.client.active"):t("remote.client.idle"),subtitle:t("remote.client.subtitle"),children:[!a&&!i?e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("remote.client.desktopOnly")}):r.active?e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-success/25 bg-success/10 px-3 py-3",children:[e.jsx(St,{size:18,className:"mt-0.5 shrink-0 text-success"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-medium text-ink",children:t("remote.client.connected",{name:r.serverName||t("remote.client.fallbackName")})}),e.jsx("div",{className:"mt-1 break-all text-[12px] text-ink-secondary",children:r.endpoint})]})]}),e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("remote.client.mode")}),e.jsx("p",{role:"status",className:"rounded-lg bg-inset px-3 py-2 text-[13px] leading-relaxed text-ink","data-legacy-client-notice":"",children:t("remote.client.endsDec7")}),e.jsxs("button",{type:"button",disabled:y,onClick:()=>{B()},className:"flex w-fit items-center gap-2 rounded-lg border border-danger/30 px-3 py-2 text-[13px] text-danger hover:bg-danger/10 disabled:opacity-50",children:[y?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(qd,{size:14}),t("remote.client.disconnect")]})]}):e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:v=>{v.preventDefault(),j()},children:[i&&a?e.jsxs("label",{className:"flex flex-col gap-1.5 text-[12px] text-ink-secondary",children:[t("remote.client.connectionType"),e.jsxs(ge,{value:o,disabled:y,onChange:v=>{d(v.target.value),k("")},className:"w-full",children:[e.jsx("option",{value:"server",children:t("remote.client.server.option")}),e.jsx("option",{value:"companion",children:t("remote.client.companion.option")})]})]}):null,E?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("remote.client.server.hint")}),e.jsxs("div",{"data-pair-access":"full",className:"flex flex-col gap-1",children:[e.jsx("p",{className:"text-[12px] font-medium text-ink",children:t("remote.client.server.fullTitle")}),e.jsx("code",{className:"select-all rounded-lg bg-inset px-3 py-2 text-[12px] text-ink",children:"npx limixbot pair"})]}),e.jsxs("div",{"data-pair-access":"client",className:"flex flex-col gap-1",children:[e.jsx("p",{className:"text-[12px] font-medium text-ink",children:t("remote.client.server.clientTitle")}),e.jsx("code",{className:"select-all rounded-lg bg-inset px-3 py-2 text-[12px] text-ink",children:"npx limixbot pair --client"}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("remote.client.server.clientNote")})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-[12px] text-ink-secondary",children:[t("remote.client.server.pairingLink"),e.jsx("input",{value:m,onChange:v=>u(v.target.value),placeholder:"https://bots.example.com/pair#code=XXXX-XXXX-XXXX",disabled:y,autoCapitalize:"none",autoCorrect:"off",autoComplete:"off",spellCheck:!1,className:is})]}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("remote.client.server.domainHint")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("remote.client.companion.hint")}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-[12px] text-ink-secondary",children:[t("remote.client.companion.address"),e.jsx("input",{value:x,onChange:v=>p(v.target.value),placeholder:"computer.tailnet.ts.net",disabled:y,autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,className:is})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-[12px] text-ink-secondary",children:[t("remote.client.companion.code"),e.jsx("input",{value:g,onChange:v=>f(v.target.value.replace(/\D/g,"").slice(0,6)),placeholder:"000000",disabled:y,inputMode:"numeric",autoComplete:"one-time-code",className:`${is} max-w-40 font-mono tracking-[0.2em]`})]})]}),h?e.jsx("p",{role:"alert",className:"text-[13px] text-danger",children:h}):null,e.jsxs("button",{type:"submit",disabled:y||(E?!m.trim():x.trim()===""||g.length!==6),className:"flex w-fit items-center gap-2 rounded-lg bg-accent px-3 py-2 text-[13px] font-medium text-white hover:brightness-110 disabled:opacity-50",children:[y?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(St,{size:14}),E?t("remote.client.server.connect"):t("remote.client.pair")]}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:E?t("remote.client.server.switchNote"):t("remote.client.restartNote")})]}),r.active&&h?e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:h}):null]})}const lp={list_files:"lending.action.listFiles",read_file:"lending.action.readFile",write_file:"lending.action.writeFile",edit_file:"lending.action.writeFile",append_file:"lending.action.writeFile",delete_file:"lending.action.deleteFile",run_command:"lending.action.runCommand",computer_tools:"lending.action.screenTools",computer_call:"lending.action.screen",invalid:"lending.action.invalid",internet:"lending.action.website",chrome:"lending.action.chrome"};function op({entries:s}){return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:"font-medium text-ink",children:t("lending.activity.title")}),s&&s.length===0&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("lending.activity.empty")}),s&&s.length>0&&e.jsx("ul",{"aria-label":t("lending.activity.title"),className:"flex max-h-56 flex-col gap-1 overflow-y-auto text-[12px]",children:s.map((n,a)=>e.jsxs("li",{className:"flex flex-wrap gap-x-2 text-ink-secondary",children:[e.jsx("time",{dateTime:new Date(n.at).toISOString(),className:"shrink-0 tabular-nums",children:new Date(n.at).toLocaleString(ws())}),e.jsxs("span",{className:n.ok?"text-ink":"text-danger",children:[t(lp[n.action]??"lending.action.other"),n.ok?"":` · ${t("lending.activity.refused")}`]}),n.detail&&e.jsx("span",{dir:"auto",className:"min-w-0 break-all",children:n.detail})]},`${n.at}-${a}`))})]})}function cp({workspace:s,own:n=!1,onClose:a}){const{state:i}=G(),c=n||Ga(i.config)?window.ogb?.computerSharing:void 0,[o,d]=l.useState(null),[m,u]=l.useState([]),[x,p]=l.useState(!1),[g,f]=l.useState(!1),[y,b]=l.useState(!1),[h,k]=l.useState(""),[S,E]=l.useState(null),N=l.useRef(!1),P=l.useRef(!1),j=l.useRef(null),B=A=>{d(A),u(A.folders),p(A.terminal),f(A.computer)};l.useEffect(()=>{N.current=!0,j.current?.scrollIntoView({block:"start"}),c?.state(s.id).then($=>{N.current&&B($)}).catch(()=>{N.current&&k(t("computerSharing.loadFailed"))});const A=()=>{c?.state(s.id).then($=>{N.current&&d($)}).catch(()=>{}),c?.activity?.(s.id).then($=>{N.current&&E($)}).catch(()=>{})};A();const T=setInterval(A,3e3);return()=>{N.current=!1,clearInterval(T)}},[c,s.id]);const v=async A=>{if(!P.current){P.current=!0,b(!0),k("");try{await A()}catch(T){N.current&&k(String(T?.message??T).replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/,""))}finally{P.current=!1,N.current&&b(!1)}}};return c?e.jsx("div",{ref:j,children:e.jsx(Y,{title:t("computerSharing.title",{name:s.name}),subtitle:s.origin,children:e.jsxs("div",{className:"flex flex-col gap-4 text-[13px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{role:"status",className:"text-ink-secondary",children:o?o.enabled?o.connected?t("computerSharing.sharing"):"Waiting for the workspace to connect":t("computerSharing.notShared"):t("computerSharing.loading")}),e.jsx("button",{type:"button","aria-label":t("computerSharing.close"),onClick:a,className:"rounded p-1 text-ink-secondary hover:bg-control",children:e.jsx($e,{size:16})})]}),e.jsx("p",{className:"text-ink-secondary",children:n?t("computerSharing.ownIntro",{name:s.name}):"Choose what this workspace’s bots can use. Shared files and screen content may be sent to its AI provider. Access stays on when you switch workspaces, until you stop sharing or close the desktop app."}),n&&o?.enabled&&e.jsxs("div",{"data-sharing-pause":!0,className:"flex items-center gap-3 rounded-lg bg-inset px-3 py-2",children:[e.jsx("p",{className:"min-w-0 flex-1 text-[12px] text-ink-secondary",children:t(o.paused?"computerSharing.paused":"computerSharing.pauseHint")}),e.jsx("button",{type:"button",disabled:y,onClick:()=>{v(async()=>{await(o.paused?c.resume?.():c.pause?.());const A=await c.state(s.id);N.current&&d(A)})},className:"shrink-0 rounded-lg border border-hairline/40 px-3 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50",children:t(o.paused?"computerSharing.resume":"computerSharing.pause")})]}),e.jsxs("fieldset",{disabled:y||!o,className:"flex flex-col gap-3 disabled:opacity-50",children:[e.jsx("legend",{className:"mb-2 font-medium text-ink",children:t("computerSharing.folders")}),m.length===0&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("computerSharing.noFolders")}),m.map(A=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border border-hairline/40 p-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-ink",children:A.name}),e.jsx("p",{className:"break-all text-[12px] text-ink-secondary",children:A.path})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-ink-secondary",children:[e.jsx("input",{type:"checkbox",checked:A.write,onChange:T=>u($=>$.map(U=>U.id===A.id?{...U,write:T.target.checked}:U))}),t("computerSharing.allowEdits")]}),e.jsx("button",{type:"button","aria-label":t("lending.removeFolder",{name:A.name}),onClick:()=>u(T=>T.filter($=>$.id!==A.id)),className:"rounded p-1 text-ink-secondary hover:bg-control",children:e.jsx($e,{size:14})})]},A.id)),e.jsxs("button",{type:"button",disabled:m.length>=20,onClick:()=>{v(async()=>{const A=await c.chooseFolder();N.current&&A&&u(T=>T.some($=>$.path===A.path)?T:[...T,A])})},className:"flex w-fit items-center gap-2 rounded-lg border border-hairline/40 px-3 py-2 text-ink hover:bg-control",children:[e.jsx(Oo,{size:14}),t("computerSharing.chooseFolder")]}),e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("computerSharing.smallFiles")})]}),e.jsxs("fieldset",{disabled:y||!o,className:"flex flex-col gap-3 border-t border-hairline/40 pt-3 disabled:opacity-50",children:[e.jsx("legend",{className:"font-medium text-ink",children:t("computerSharing.broader")}),e.jsxs("label",{className:"flex items-start gap-2",children:[e.jsx("input",{className:"mt-1",type:"checkbox",checked:x,onChange:A=>p(A.target.checked)}),e.jsxs("span",{className:"text-ink",children:[t("computerSharing.terminal"),e.jsx("span",{className:"mt-1 block text-[12px] text-ink-secondary",children:t("computerSharing.terminalHint")})]})]}),e.jsxs("label",{className:"flex items-start gap-2",children:[e.jsx("input",{className:"mt-1",type:"checkbox",checked:g,onChange:A=>f(A.target.checked)}),e.jsxs("span",{className:"text-ink",children:[t("computerSharing.control"),e.jsx("span",{className:"mt-1 block text-[12px] text-ink-secondary",children:t("computerSharing.controlHint")})]})]})]}),(h||o?.error)&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:h||o?.error}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:y||!o||!m.length&&!x&&!g,onClick:()=>{v(async()=>{const A=await c.save(s.id,{folders:m,terminal:x,computer:g});N.current&&A&&B(A)})},className:"rounded-lg bg-accent px-3 py-2 font-medium text-accent-ink disabled:opacity-50",children:t(o?.enabled?"computerSharing.save":"computerSharing.share")}),o?.enabled&&e.jsx("button",{type:"button",disabled:y,onClick:()=>{v(async()=>{const A=await c.revoke(s.id);N.current&&B(A)})},className:"rounded-lg border border-hairline/40 px-3 py-2 text-danger disabled:opacity-50",children:t("computerSharing.stop")})]}),o?.enabled&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("computerSharing.stopHint")}),e.jsx("div",{className:"border-t border-hairline/40 pt-3",children:e.jsx(op,{entries:S})})]})})}):null}const dp={https:"servers.transport.https",tailscale:"servers.transport.tailscale","private-http":"servers.transport.privateHttp",loopback:"servers.transport.loopback"},vt=s=>s.kind!=="local"&&!!s.origin&&!s.home&&!s.cloud&&!("team"in s&&s.team),up=s=>new Date(s).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});function mp(s,n){return s==="docker"?"git pull && ./update.sh":s==="global"?`npm install -g limixbot@${n}`:s==="source"?"git pull && pnpm install":`npx limixbot@${n} serve`}function pp({name:s,status:n,appVersion:a,onHide:i}){const{state:r,copy:c}=Ss(mp(n.install,a));return e.jsxs("div",{"data-server-behind":!0,className:"mt-2 flex items-center gap-2 rounded-lg bg-inset px-3 py-2 text-[12px] text-ink",children:[e.jsx("span",{className:"min-w-0 flex-1",children:t("servers.behind",{name:s,server:n.version??"",app:a})}),e.jsx("button",{type:"button",onClick:c,className:"shrink-0 font-medium text-accent-text hover:underline",children:t(r==="copied"?"servers.copied":"servers.behind.copy")}),e.jsx("button",{type:"button",onClick:i,"aria-label":t("servers.behind.hide"),className:"shrink-0 text-ink-secondary hover:text-ink",children:e.jsx($e,{size:13})})]})}function xp({origin:s,name:n}){const{state:a,copy:i}=Ss(s);return e.jsx("button",{type:"button",onClick:i,"aria-label":t("servers.copyAddressFor",{name:n}),title:t(a==="copied"?"servers.copied":"servers.copyAddress"),className:"rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-ink",children:a==="copied"?e.jsx(be,{size:14}):e.jsx(Ea,{size:14})})}function gp({status:s,onTryNow:n,onPairAgain:a,onEdit:i}){if(!s||s.state==="connected")return null;const r=(d,m)=>e.jsx("button",{type:"button",onClick:m,className:"ml-2 font-medium text-accent-text hover:underline",children:d}),c=s.state==="checking"?t("servers.state.checking"):s.state==="reconnecting"?t("servers.state.reconnecting"):s.state==="cantReach"?t("servers.state.cantReach",{time:up(s.since)}):s.state==="signedOut"?t("servers.state.signedOut"):t("servers.state.insecure"),o=s.state==="signedOut"||s.state==="insecure";return e.jsxs("div",{"data-server-state":s.state,className:o||s.state==="cantReach"?"text-[12px] text-danger":"text-[12px] text-ink-secondary",children:[c,s.state==="cantReach"&&r(t("servers.tryNow"),n),s.state==="signedOut"&&r(t("servers.pairAgain"),a),s.state==="insecure"&&r(t("servers.editAddress"),i)]})}function hp({name:s,share:n,busy:a,onShare:i,onOpen:r}){const c=n.enabled?n.paused?"servers.share.paused":"servers.share.on":"servers.share.off";return e.jsxs("div",{"data-server-share":n.id,className:"mt-2 flex items-center gap-3 rounded-lg bg-inset px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12px] font-medium text-ink",children:t("servers.share.title")}),e.jsx("div",{className:"text-[12px] text-ink-secondary",children:t(c,{name:s})})]}),n.enabled&&e.jsx("button",{type:"button",disabled:a,onClick:r,className:"shrink-0 text-[12px] font-medium text-accent-text hover:underline disabled:opacity-50",children:t("servers.share.choose")}),e.jsx(me,{checked:n.enabled,disabled:a,"aria-label":t("servers.share.for",{name:s}),onClick:()=>i(!n.enabled)})]})}function fp({saved:s,busy:n,sharingOffered:a,ownServers:i=[],appVersion:r,onSwitch:c,onForget:o,onComputerAccess:d,onShare:m=()=>{}}){const u=window.ogb?.environments,[x,p]=l.useState([]),[g,f]=l.useState([]),[y,b]=l.useState(null);l.useEffect(()=>{if(!u?.status)return;let N=!0;const P=()=>{u.status().then(B=>{N&&p(B)}).catch(()=>{})};P();const j=u.onStatus?.(P);return()=>{N=!1,j?.()}},[u,s]);const h=N=>x.find(P=>P.id===N),k=N=>b({address:N.origin,locked:!0,title:t("servers.pairAgainTitle",{name:N.name})}),S=N=>b({address:N.origin.replace(/^http:/,"https:"),locked:!1,title:t("connect.title")}),E=[{id:"local",name:t("place.local"),kind:"local"},...s.environments.filter(N=>N.kind!=="local")];return e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"divide-y divide-hairline/40",children:E.map(N=>{const P=N.id===s.activeId,j=vt(N)?h(N.id):void 0,B=N.id==="local"?St:Rt,v=N.id==="local"?t("servers.localHint"):vt(N)?`${new URL(N.origin).host} · ${t(dp[_r(N.origin)])}`:N.home?t("servers.managed"):new URL(N.origin).host,A=i.find($=>$.id===N.id),T=j?.behind===!0&&r!==null&&!g.includes(`${N.id}:${j.version}`);return e.jsxs("li",{"data-server-row":N.id,className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[$r(N.color)?e.jsx(Kr,{color:N.color,size:20}):e.jsx(B,{size:18,className:"shrink-0 text-ink-secondary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] font-medium text-ink",children:N.name}),e.jsx("div",{"data-server-where":!0,className:"break-all text-[12px] text-ink-secondary",children:v}),e.jsx(gp,{status:j,onTryNow:()=>{u?.retry?.(N.id)},onPairAgain:()=>k(N),onEdit:()=>S(N)})]}),P?e.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[12px] text-ink-secondary",children:[e.jsx(be,{size:13}),t("servers.current")]}):e.jsx("button",{type:"button",disabled:n,"aria-label":t("servers.switchTo",{name:N.name}),onClick:()=>c(N.id),className:"rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50",children:t("servers.switch")}),vt(N)&&j?.state!=="signedOut"&&e.jsx("button",{type:"button",disabled:n,onClick:()=>k(N),className:"rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50",children:t("servers.pairAgain")}),N.id!=="local"&&!N.home&&!N.cloud&&!A&&a&&e.jsx("button",{type:"button",disabled:n,"aria-label":t("servers.computerAccessFor",{name:N.name}),onClick:()=>d(N.id),className:"rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control",children:t("servers.computerAccess")}),vt(N)&&e.jsx(xp,{origin:N.origin,name:N.name}),N.id!=="local"&&!N.home&&e.jsx("button",{type:"button",disabled:n,"aria-label":t("servers.removeName",{name:N.name}),title:t("servers.removeName",{name:N.name}),onClick:()=>o(N.id),className:"rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-danger disabled:opacity-50",children:e.jsx(Se,{size:14})})]}),A&&e.jsx(hp,{name:N.name,share:A,busy:n,onShare:$=>m(N.id,$),onOpen:()=>d(N.id)}),T&&e.jsx(pp,{name:N.name,status:j,appVersion:r,onHide:()=>f($=>[...$,`${N.id}:${j.version}`])})]},N.id)})}),e.jsxs("button",{type:"button","data-server-connect":!0,disabled:n,onClick:()=>b({address:"",locked:!1,title:t("connect.title")}),className:"mt-3 flex w-fit items-center gap-2 rounded-lg bg-accent px-3 py-2 text-[13px] font-medium text-accent-ink disabled:opacity-50",children:[e.jsx(we,{size:14}),t("connect.title")]}),y&&e.jsx(xl,{focusKey:y.locked?"pair-again":"connect",onClose:()=>b(null),children:e.jsx(gl,{onBack:null,onConnected:()=>b(null),start:y})})]})}function Jn(){const s=window.ogb?.environments,{state:n}=G(),a=Ga(n.config)&&!!window.ogb?.computerSharing,i=window.ogb?.computerSharing,[r,c]=l.useState([]),[o,d]=l.useState(null),[m,u]=l.useState(!1),[x,p]=l.useState(""),[g,f]=l.useState(()=>new URLSearchParams(window.location?.search??"").get("share-computer")),[y,b]=l.useState(""),[h,k]=l.useState(""),[S,E]=l.useState(null),[N,P]=l.useState(!1),[j,B]=l.useState(""),v=l.useRef(!1),A=l.useRef(0);l.useEffect(()=>{const F=++A.current;return s?.state().then(L=>{A.current===F&&d(L)}).catch(()=>{A.current===F&&p(t("servers.loadFailed"))}),()=>{A.current++}},[s]),l.useEffect(()=>{if(!i?.servers||!o)return;let F=!0;const L=()=>{i.servers().then(se=>{F&&c(se)}).catch(()=>{})};L();const X=setInterval(L,5e3);return()=>{F=!1,clearInterval(X)}},[i,o]);const T=(F,L)=>{$(async()=>{L?await i?.allow?.(F)&&f(F):await i?.revoke(F),i?.servers&&c(await i.servers())})};l.useEffect(()=>{const F=L=>{L&&f(L);const X=new URL(window.location.href);X.searchParams.delete("share-computer"),window.history.replaceState(null,"",`${X.pathname}${X.search}${X.hash}`)};return F(),s?.onOpenSettings?.(F)},[s]);const $=async(F,L=p)=>{if(v.current||!s)return;v.current=!0,u(!0),p(""),B("");const X=A.current;try{if(await F()===!0)return;const se=await s.state();A.current===X&&d(se)}catch(se){A.current===X&&L(String(se?.message??se).replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/,""))}finally{v.current=!1,A.current===X&&u(!1)}};if(!s)return e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("servers.desktopOnly")});const U=F=>window.ogb?.confirm?window.ogb.confirm(F):window.confirm(F),Z=o?.environments.find(F=>F.id===g),H=Z?.origin&&!Z.home?{id:Z.id,name:Z.name,origin:Z.origin}:void 0,ne=!!(H&&r.some(F=>F.id===H.id)),ae=o?.environments.filter(F=>F.kind==="local")??[],oe=ae.find(F=>F.id===S);return e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("servers.intro")}),o?.packaged&&e.jsxs(Y,{title:t("connectedWorkspaces.localTitle"),subtitle:t("connectedWorkspaces.localSubtitle"),children:[j&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:j}),ae.length>0&&e.jsx("ul",{className:"divide-y divide-hairline/40",children:ae.map(F=>{const L=F.id===o.activeId;return e.jsxs("li",{className:"flex items-center gap-3 py-3",children:[e.jsx(St,{size:18,className:"shrink-0 text-ink-secondary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] font-medium text-ink",children:F.name}),e.jsxs("div",{className:"break-all text-[12px] text-ink-secondary",children:[F.dataDir,F.missing&&e.jsx("span",{className:"ml-2 rounded-md bg-inset px-1.5 py-0.5 text-[11px]",children:t("connectedWorkspaces.missing")})]})]}),L?e.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[12px] text-ink-secondary",children:[e.jsx(be,{size:13}),t("connectedWorkspaces.current")]}):e.jsx("button",{type:"button",disabled:m,"aria-label":t("connectedWorkspaces.switchTo",{name:F.name}),onClick:()=>{$(async()=>{if(!await U(t("connectedWorkspaces.switchConfirm",{name:F.name})))return;const X=await s.switch(F.id);if(X&&X.ok===!1)throw new Error(t("connectedWorkspaces.switchError"));return!0},B)},className:"rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50",children:t("connectedWorkspaces.switch")}),!L&&e.jsx("button",{type:"button",disabled:m,"aria-label":t("connectedWorkspaces.forgetName",{name:F.name}),title:t("connectedWorkspaces.forgetName",{name:F.name}),onClick:()=>{E(F.id),P(!1)},className:"rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-danger disabled:opacity-50",children:e.jsx(Se,{size:14})})]},F.id)})}),oe&&e.jsxs("div",{className:"mt-3 rounded-lg border border-hairline/40 p-3",children:[e.jsxs("label",{className:"flex items-start gap-2 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx("input",{type:"checkbox",checked:N,disabled:m,className:"mt-0.5",onChange:F=>P(F.target.checked)}),t("connectedWorkspaces.forgetPurge",{path:oe.dataDir??""})]}),e.jsxs("div",{className:"mt-2 flex gap-2",children:[e.jsx("button",{type:"button",disabled:m,onClick:()=>{$(async()=>{const F=N?await s.forget(oe.id,!0):await s.forget(oe.id);if(F&&F.ok===!1)throw new Error(t("connectedWorkspaces.forgetError"));E(null)},B)},className:"rounded-lg px-3 py-1.5 text-[12px] font-medium text-danger hover:bg-control disabled:opacity-50",children:t("connectedWorkspaces.forget")}),e.jsx("button",{type:"button",onClick:()=>E(null),className:"rounded-lg px-3 py-1.5 text-[12px] text-ink hover:bg-control",children:t("connectedWorkspaces.cancel")})]})]}),e.jsx("p",{className:"mt-4 text-[13px] font-medium text-ink",children:t("connectedWorkspaces.newEnvironment")}),e.jsxs("form",{className:"flex flex-col gap-3 pt-2",onSubmit:F=>{F.preventDefault(),y.trim()&&$(async()=>{if(!(await s.create(y.trim(),h.trim()||void 0))?.ok)throw new Error(t("connectedWorkspaces.createError"));b(""),k("")},B)},children:[e.jsxs("label",{className:"flex flex-col gap-1.5 text-[12px] text-ink-secondary",children:[t("connectedWorkspaces.name"),e.jsx("input",{required:!0,value:y,disabled:m,maxLength:60,onChange:F=>b(F.target.value),placeholder:t("connectedWorkspaces.environmentPlaceholder"),className:"w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink outline-none focus:border-accent/50"})]}),e.jsxs("label",{className:"flex flex-col gap-1.5 text-[12px] text-ink-secondary",children:[t("connectedWorkspaces.dataFolder"),e.jsxs("span",{className:"flex gap-2",children:[e.jsx("input",{value:h,disabled:m,onChange:F=>k(F.target.value),placeholder:t("connectedWorkspaces.defaultFolder"),className:"w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink outline-none focus:border-accent/50"}),e.jsx("button",{type:"button",disabled:m,onClick:()=>{$(async()=>{const F=await s.pickDir();F?.ok&&F.path&&k(F.path)},B)},className:"shrink-0 rounded-lg border border-hairline/40 px-3 text-[12px] text-ink hover:bg-control disabled:opacity-50",children:t("connectedWorkspaces.choose")})]})]}),e.jsxs("button",{type:"submit",disabled:m||!y.trim(),className:"flex w-fit items-center gap-2 rounded-lg bg-accent px-3 py-2 text-[13px] font-medium text-accent-ink disabled:opacity-50",children:[m&&e.jsx(J,{size:14,className:"animate-spin"}),t("connectedWorkspaces.create")]})]})]}),e.jsxs(Y,{title:t("servers.yours.title"),subtitle:t("servers.yours.subtitle"),children:[o?e.jsx(fp,{saved:o,busy:m,sharingOffered:a,ownServers:r,appVersion:window.ogb?.app?.version??null,onShare:T,onSwitch:F=>{$(async()=>(await s.switch(F),!0))},onForget:F=>{$(()=>s.forget(F))},onComputerAccess:f}):e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t(x?"servers.yours.loadFailed":"servers.yours.loading")}),o&&x&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:x})]}),(a||ne)&&H&&e.jsx(cp,{workspace:H,own:ne,onClose:()=>f(null)},H.id)]})}const bp={format:"placeLook.imageFormat",read:"placeLook.imageRead",size:"placeLook.imageSize",animated:"placeLook.imageMoving",failed:"placeLook.imageFailed"};function yp({banner:s,canChange:n,subtitle:a}){const i=l.useRef(null),[r,c]=l.useState(!1),[o,d]=l.useState(null),m=Mo(s),u=async g=>{c(!0),d(null);const f=await Promise.resolve().then(g).catch(()=>({ok:!1,problem:"failed"}));c(!1),f.ok||d(bp[f.problem])},x=g=>{i.current&&(i.current.value=""),!(!g||!n)&&u(async()=>{const f=await Uo(g);return f.ok?Fo(f.blob):f})},p=o?e.jsx("p",{role:"alert",className:"text-danger",children:t(o)}):n?null:e.jsx("p",{className:"text-ink-secondary",children:t("placeLook.imageAdmins")});return e.jsx("div",{"data-place-picture":m?"set":"none",children:e.jsx(de,{title:t("placeLook.sidebarPicture"),subtitle:a,message:p,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[m&&e.jsx("img",{src:m,alt:t("placeLook.currentImage"),className:"h-8 w-14 rounded-md border border-ink/10 object-cover"}),e.jsx("button",{type:"button",className:"ui-button",disabled:!n||r,onClick:()=>i.current?.click(),children:r?t("placeLook.imageSaving"):t(m?"placeLook.changeImage":"placeLook.useImage")}),m&&e.jsx("button",{type:"button",className:"ui-button",disabled:!n||r,onClick:()=>{u(Do)},children:t("placeLook.removeImage")}),e.jsx("input",{ref:i,type:"file",accept:zo,hidden:!0,"data-place-picture-input":!0,onChange:g=>x(g.target.files?.[0])})]})})})}function qi(){const s=_o(),{state:n}=G(),a=Ot()===!0,i=window.ogb?.app?.ownPage===!0,[r,c]=l.useState(null),[o,d]=l.useState(null),m=s?.change===null,u=p=>{!s||m||r||p===s.swatch||(c(p),d(null),$o(p).then(g=>{c(null),d(g)}))},x=s?.reason==="member"||o==="refused"?t("placeLook.member"):s?.reason==="signed-out"?t("placeLook.signedOut"):o==="unsupported"?t("placeLook.unsupported"):null;return e.jsxs(e.Fragment,{children:[s&&e.jsx("div",{"data-place-look":s.change??"locked",children:e.jsx(de,{title:t("placeLook.sidebarColor"),subtitle:i?t("placeLook.sidebarColorSub"):t("placeLook.sub",{name:s.name}),message:o==="failed"?e.jsx("p",{role:"alert",className:"text-danger",children:t("placeLook.failed")}):x&&e.jsx("p",{className:"text-ink-secondary",children:x}),children:e.jsx(hl,{value:r??s.swatch,onChange:u,label:i?t("placeLook.sidebarColor"):t("placeLook.aria",{name:s.name}),disabled:m,offset:"menu",none:!0})})}),e.jsx(yp,{banner:n.config?.workspaceBanner??null,canChange:a,subtitle:t(i?"placeLook.sidebarPictureSub":"placeLook.sharedPictureSub")})]})}function vp(){return e.jsx("div",{"data-sidebar-look":!0,"data-settings-look":"simple",className:qa,children:e.jsx(ve,{children:e.jsx(qi,{})})})}function Vi(){const{capabilities:s}=Aa(),n=typeof window>"u"?void 0:window.ogb?.windowFrame,[a,i]=l.useState(null);l.useEffect(()=>{if(!n)return;let d=!0;return n.state().then(m=>{d&&i(m)}).catch(()=>{}),()=>{d=!1}},[n]);const r=s.host?.platform;if(!n||!a||r!=="darwin"&&r!=="win32")return null;const c=window.ogb?.relaunch,o=()=>{n.set(!a.on).then(i).catch(()=>{})};return e.jsxs("div",{"data-window-frame-switch":!0,children:[e.jsx(de,{title:t("settings.windowFrame.title"),subtitle:t("settings.windowFrame.subtitle"),children:e.jsx(me,{checked:a.on,"aria-label":t("settings.windowFrame.title"),onClick:o})}),a.restart&&e.jsxs("div",{role:"status","data-window-frame-restart":!0,className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-4 pb-3 text-[13px] text-ink-secondary",children:[e.jsx("span",{children:t("settings.windowFrame.restart",{app:Ns()})}),c&&e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{c().catch(()=>{})},children:t("settings.windowFrame.restartNow")})]})]})}function Ji(s){return s.readOnly===!0&&s.managed!==void 0&&s.instanceId.startsWith("company.")}function jp(s,n){return s.find(a=>Ji(a)&&a.instanceId.endsWith(`.${n}`))}function Ks(s){return!!(s&&!s.policy&&s.snapshot.state==="available"&&(s.access==="custom"||s.snapshot.authenticated!==!1))}function Xn(s,n){const a=n.find(i=>i.instanceId===s.instanceId);return Ks(a)?!0:!!(a&&!a.policy&&a.snapshot.state==="available"&&a.models.options.some(i=>i.id===s.model&&i.custom))}function kp(s,n){const a=n.filter(o=>Ji(o)&&Ks(o)),i=a.find(o=>o.driverKind==="claudeAgent")??a[0];if(!i)return{bots:[],needsAsk:[]};const r={target:i,bots:[],needsAsk:[]},c=o=>n.find(d=>d.instanceId===o)?.driverKind;for(const o of s){if(o.hidden)continue;const d=Ko(o);if(Xn(o.modelSelection,n)||Xn(d.modelSelection,n))continue;([o,d].some(u=>Ho(Wo(u),c(u.modelSelection.instanceId),i.driverKind))?r.needsAsk:r.bots).push(o)}return r}const Np={anthropic:"Anthropic",openai:"OpenAI",openrouter:"OpenRouter"};function wp({providers:s}){const{state:n,dispatch:a,flushBotPatches:i}=G(),[r,c]=l.useState(!1),[o,d]=l.useState(null),m=kp(n.bots,n.instances),u=m.target,x=g=>g.map(f=>f.name).join(", "),p=async()=>{if(!u||!m.bots.length||r)return;const g=m.bots,f={instanceId:u.instanceId,model:u.models.default};c(!0),d(null);for(const y of g)a({type:"setModel",botId:y.id,selection:f});try{const y=await Promise.all(g.map(h=>i(h.id).catch(()=>null))),b=g.filter((h,k)=>y[k]?.modelSelection.instanceId===f.instanceId);b.length&&d({name:u.displayName,bots:b.map(h=>h.name)})}finally{c(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"divide-y divide-hairline/40",children:s.map(g=>e.jsxs("li",{className:"py-2 text-[13px]",children:[e.jsxs("div",{className:"flex flex-wrap justify-between gap-2",children:[e.jsx("span",{className:"text-ink",children:Np[g.id]??g.id}),e.jsx("span",{className:"text-ink-secondary",children:g.configured?t("organization.modelCount",{count:g.models.length}):t("organization.notConfigured")})]}),g.configured&&g.models.length>0&&e.jsx(Sp,{instance:jp(n.instances,g.id),instances:n.instances})]},g.id))}),o&&e.jsx("p",{role:"status",className:"break-words text-[12px] text-ink-secondary",children:t("organization.useCompanyDone",{name:o.name,names:o.bots.join(", ")})}),u&&m.bots.length>0&&e.jsxs("div",{"data-company-switch":!0,className:"flex flex-col items-start gap-2 rounded-lg border border-hairline/40 p-3",children:[e.jsx("p",{className:"break-words text-[13px] text-ink",children:t("organization.useCompanyBots",{names:x(m.bots)})}),e.jsx("button",{type:"button",className:"ui-button",disabled:r,onClick:()=>{p()},children:m.bots.length===1?t("organization.useCompanyOne",{name:u.displayName}):t("organization.useCompanyMany",{name:u.displayName,count:m.bots.length})}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("organization.useCompanyNote")})]}),u&&m.needsAsk.length>0&&e.jsx("p",{className:"break-words text-[12px] text-ink-secondary",children:t("organization.useCompanyElevated",{names:x(m.needsAsk)})})]})}function Sp({instance:s,instances:n}){if(!s)return null;if(s.policy)return e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:s.policy.reason});if(Ks(s))return e.jsxs("p",{className:"mt-1 flex items-center gap-1 text-[12px] text-ink-secondary",children:[e.jsx(be,{size:12,className:"text-success","aria-hidden":"true"}),t("organization.engineReady")]});const a=s.driverKind==="claudeAgent"||s.driverKind==="codex"?n.find(i=>i.driverKind===s.driverKind&&!i.readOnly&&i.install):void 0;return a&&Go(a)?e.jsx(Mt,{instance:a,intent:"inject",className:"mt-2",description:t("organization.engineInstallHelp",{engine:a.displayName})}):e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:s.snapshot.reason??t("organization.engineUnavailable")})}const Cp={anthropic:"Anthropic",openai:"OpenAI",openrouter:"OpenRouter"},Yn="https://admin.limixbot.com",Qn={clearFailed:"organization.status.clearFailed",disconnected:"organization.status.disconnected",runtimeRunning:"organization.status.runtimeRunning",portalUnreachable:"organization.status.portalUnreachable",confirmStopped:"organization.status.confirmStopped",expired:"organization.status.expired",accessEnded:"organization.status.accessEnded",retrying:"organization.status.retrying",codeExpired:"organization.status.codeExpired",denied:"organization.status.denied",completeFailed:"organization.status.completeFailed",removed:"organization.status.removed",restoreFailed:"organization.status.restoreFailed",startFailed:"organization.status.startFailed"};function Ep(s){const n=s.messageCodes;return!n?.length||!n.every(a=>Object.hasOwn(Qn,a))?s.message:n.map(a=>t(Qn[a])).join(" ")}function Xi(){const s=window.ogb?.remoteClient?.active?void 0:window.ogb?.organization,[n,a]=l.useState(null),[i,r]=l.useState(""),[c,o]=l.useState(!1),[d,m]=l.useState(""),[u,x]=l.useState(!1),p=l.useRef(!1),g=l.useRef(0),f=l.useRef(0),y=l.useRef(void 0),b=j=>{const B=y.current!==j.status;y.current=j.status,a(j),B&&m(""),j.status!=="connected"&&j.status!=="reauth-required"&&x(!1)};l.useEffect(()=>{s?.settingsOpened?.().catch(()=>{});const j=++g.current,B=f.current,v=T=>{g.current===j&&(f.current++,b(T))},A=s?.onState(v);return s?.state().then(T=>{f.current===B&&v(T)}).catch(()=>{g.current===j&&f.current===B&&m(t("organization.loadFailed"))}),()=>{g.current++,A?.()}},[s]);const h=async j=>{if(!s||p.current)return;p.current=!0,o(!0),m("");const B=g.current,v=f.current;try{const A=await j();g.current===B&&f.current===v&&b(A)}catch{g.current===B&&f.current===v&&m(t("organization.actionFailed"))}finally{p.current=!1,g.current===B&&o(!1)}};if(!s)return e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("organization.desktopOnly")});const k=n?.status==="connected"||n?.status==="reauth-required"||n?.status==="unavailable"||n?.status==="license-expired",S=n?.status==="license-expired"||n?.notice==="license-expired",E=n?.enrollment?.expiresAt??n?.expiresAt,N=typeof E=="number"&&Number.isFinite(E)?new Date(E):null,P=N&&Number.isFinite(N.getTime())?new Intl.DateTimeFormat(Me(),{dateStyle:"medium",timeStyle:"short"}).format(N):null;return e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("organization.additive")}),e.jsxs(Y,{title:t("settings.section.organization"),subtitle:t("organization.privacy"),children:[!n&&e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:d||t("organization.loading")}),n?.message&&e.jsx("p",{role:"status",className:"mb-3 text-[13px] text-ink-secondary",children:Ep(n)}),S&&e.jsx("p",{role:"alert",className:"mb-3 text-[13px] text-ink",children:t("organization.licenseExpired")}),n?.status==="signed-out"&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("organization.signInHelp")}),e.jsx("button",{type:"button",disabled:c,onClick:()=>{h(()=>s.begin({portalOrigin:Yn}))},className:"w-fit rounded-lg bg-accent px-4 py-2 text-[13px] font-medium text-white hover:brightness-110 disabled:opacity-50",children:c?t("organization.working"):t("organization.signIn")}),e.jsxs("details",{className:"text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"w-fit cursor-pointer hover:text-ink",children:t("organization.advanced")}),e.jsxs("form",{className:"mt-2 flex flex-col gap-2",onSubmit:j=>{j.preventDefault(),i.trim()&&h(()=>s.begin({portalOrigin:i.trim()}))},children:[e.jsx("p",{children:t("organization.advancedHelp")}),e.jsxs("label",{className:"flex flex-col gap-1.5",children:[t("organization.address"),e.jsx("input",{type:"url",required:!0,value:i,disabled:c,onChange:j=>r(j.target.value),placeholder:Yn,autoCapitalize:"none",autoCorrect:"off",autoComplete:"off",spellCheck:!1,maxLength:2048,className:"w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink outline-none focus:border-accent/50"})]}),e.jsx("button",{type:"submit",disabled:c||!i.trim(),className:"ui-button w-fit",children:t("organization.customSignIn")})]})]})]}),n?.status==="connecting"&&e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("organization.browserConsent")}),n.enrollment&&e.jsxs("details",{className:"w-full text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"w-fit cursor-pointer hover:text-ink",children:t("organization.securityDetails")}),e.jsx("p",{className:"mt-2",children:t("organization.securityDetailsHelp")}),e.jsx("div",{className:"mt-3",children:t("organization.code")}),e.jsx("code",{dir:"ltr",className:"mt-1 block w-fit select-all rounded-lg bg-inset px-3 py-2 text-base tracking-widest text-ink",children:n.enrollment.userCode})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.enrollment&&s.reopen&&e.jsx("button",{type:"button",disabled:c,className:"ui-button",onClick:()=>{h(()=>s.reopen())},children:t("organization.reopen")}),e.jsx("button",{type:"button",disabled:c,className:"ui-button",onClick:()=>{h(()=>s.cancelEnrollment())},children:t("organization.cancel")})]})]}),k&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{children:[n.branding?.logo&&e.jsx("img",{src:n.branding.logo,alt:t("organization.logo"),className:"mb-2 size-12 rounded-lg object-contain"}),e.jsx("div",{className:"break-words text-[15px] font-medium text-ink",children:n.organization?.name}),e.jsx("div",{className:"break-all text-[13px] text-ink-secondary",children:n.email})]}),n.status==="reauth-required"?e.jsx("p",{role:"alert",className:"text-[13px] text-ink-secondary",children:t("organization.reauth")}):n.status==="license-expired"?e.jsx(e.Fragment,{children:n.providers?.some(j=>j.configured&&j.models.length>0)&&e.jsx("ul",{className:"divide-y divide-hairline/40",children:n.providers.filter(j=>j.configured&&j.models.length>0).map(j=>e.jsxs("li",{className:"flex flex-wrap justify-between gap-2 py-2 text-[13px]",children:[e.jsx("span",{className:"text-ink",children:Cp[j.id]??j.id}),e.jsx("span",{className:"text-ink-secondary",children:t("organization.companyModelsUnavailable")})]},j.id))})}):n.status==="connected"?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("organization.modelHelp")}),n.providers?.some(j=>j.configured&&j.models.length>0)?e.jsx(wp,{providers:n.providers}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("organization.noModels")})]}):null,u?e.jsxs("div",{role:"group","aria-label":t("organization.disconnectTitle"),className:"rounded-lg border border-hairline/40 p-3",children:[e.jsx("p",{className:"text-[13px] text-ink",children:t("organization.disconnectWarning")}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",autoFocus:!0,disabled:c,className:"ui-button",onClick:()=>x(!1),children:t("organization.keepConnection")}),e.jsx("button",{type:"button",disabled:c,className:"ui-button text-danger",onClick:()=>{h(()=>s.disconnect())},children:t("organization.disconnectConfirm")})]})]}):e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.status!=="reauth-required"&&e.jsx("button",{type:"button",disabled:c,className:"ui-button",onClick:()=>{h(()=>s.refresh())},children:t("organization.refresh")}),e.jsx("button",{type:"button",disabled:c,className:"ui-button",onClick:()=>x(!0),children:t("organization.disconnect")})]})]}),n?.status==="unavailable"&&e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("organization.unavailable")}),P&&e.jsx("p",{className:"mt-3 text-[12px] text-ink-secondary",children:t("organization.expires",{date:P})}),d&&n&&e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:d}),!n&&e.jsx("button",{type:"button",disabled:c,className:"ui-button mt-3",onClick:()=>{h(()=>s.refresh())},children:t("organization.refresh")})]})]})}const Ap="https://cal.com/milind-soni-002qed/30min",Ip=["feature","price","setup","broken","later","other"],Pp={feature:"cloudCancel.answer.feature",price:"cloudCancel.answer.price",setup:"cloudCancel.answer.setup",broken:"cloudCancel.answer.broken",later:"cloudCancel.answer.later",other:"cloudCancel.answer.other"},Zn=2e3,ys=s=>new Intl.DateTimeFormat(Me(),{dateStyle:"medium"}).format(new Date(s)),Tp=s=>s.endsAt??s.renewsAt;function Yi(s){const n=Tp(s);return s.trial?n?t("cloudCancel.endedTrial",{date:ys(n)}):t("cloudCancel.endedTrialNoDate"):n?t("cloudCancel.endedPlan",{date:ys(n)}):t("cloudCancel.endedPlanNoDate")}function Rp(s){const n=s.team?t("cloudCancel.teamStops",{team:s.team}):t("cloudCancel.stops"),a=s.keptDays;if(a===null)return n;const i=a<=0?t("cloudCancel.keptNone"):Number.isInteger(a)?a===1?t("cloudCancel.keptDay"):t("cloudCancel.keptDays",{days:a}):t("cloudCancel.keptHours",{hours:Math.max(1,Math.round(a*24))});return`${n} ${i}`}function Lp(s){return[s.renewsAt?t(s.trial?"cloudCancel.runsTrial":"cloudCancel.runsPlan",{date:ys(s.renewsAt)}):null,t(s.trial?"cloudCancel.nothingCharged":"cloudCancel.noMoreCharges"),s.team?t("cloudCancel.teamStops",{team:s.team}):null].filter(Boolean).join(" ")}function Qi({renewal:s,actions:n,onChanged:a}){const[i,r]=l.useState(null),[c,o]=l.useState(!1),[d,m]=l.useState(null);if(!s||!n)return null;const u=()=>{o(!0),m(null),n.keep().then(x=>{x.outcome==="kept"?a?.():m(x.outcome==="browser"?"browser":"failed")},()=>m("failed")).finally(()=>o(!1))};return e.jsxs(e.Fragment,{children:[s.cancelled?e.jsxs("div",{"data-cloud-cancel":"cancelled",className:"flex flex-col items-start gap-2 self-start",children:[e.jsx("p",{role:"status",className:"text-[13px] text-ink",children:Yi(s)}),e.jsx("button",{type:"button",className:"ui-button",disabled:c,onClick:u,children:t(c?"cloudCancel.keeping":"cloudCancel.keep")}),d&&e.jsx("p",{role:d==="failed"?"alert":"status",className:z("text-[13px]",d==="failed"?"text-danger":"text-ink-secondary"),children:t(d==="failed"?"cloudCancel.failed":"cloudCancel.browser")})]}):e.jsx("button",{type:"button","data-cloud-cancel":"renewing",className:"ui-button self-start",onClick:()=>{m(null),r(s)},children:t(s.trial?"cloudCancel.cancelTrial":"cloudCancel.cancelPlan")}),i&&e.jsx(Bp,{renewal:i,actions:n,onClose:x=>{r(null),x&&a?.()}})]})}function Bp({renewal:s,actions:n,onClose:a}){const[i,r]=l.useState(null),[c,o]=l.useState(""),[d,m]=l.useState(""),[u,x]=l.useState({step:"ask"}),[p,g]=l.useState(!1),[f,y]=l.useState(!1),b=l.useRef(!1),h=l.useRef(null),k=()=>{p||a(b.current)};l.useEffect(()=>{const v=document.activeElement instanceof HTMLElement?document.activeElement:null;return h.current?.querySelector("button[aria-pressed]")?.focus(),()=>{v?.isConnected&&v.focus()}},[]);const S=v=>{g(!0),y(!1),v().catch(()=>y(!0)).finally(()=>g(!1))},E=()=>S(async()=>{const v=i!==null||c.trim()!==""||d.trim()!=="",A=await n.cancel(v?{answer:i,...c.trim()?{expected:c}:{},...d.trim()?{improve:d}:{}}:null);A.outcome==="cancelled"?(b.current=!0,x({step:"done",renewal:A.renewal??{...s,cancelled:!0,endsAt:s.renewsAt,renewsAt:null},surveyed:A.surveyed})):A.outcome==="browser"?x({step:"browser"}):y(!0)}),N=()=>S(async()=>{const v=await n.keep();v.outcome==="kept"?(b.current=!0,a(!0)):v.outcome==="browser"?x({step:"browser"}):y(!0)}),P=t(s.trial?"cloudCancel.titleTrial":"cloudCancel.titlePlan"),j="mt-1.5 w-full rounded-lg border border-hairline/50 bg-inset px-3 py-2 text-[14px] text-ink disabled:opacity-60",B=f&&e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:t("cloudCancel.failed")});return fl.createPortal(e.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/55 p-4",onMouseDown:v=>v.stopPropagation(),children:e.jsxs("div",{ref:h,role:"dialog","aria-modal":"true","aria-labelledby":"cloud-cancel-title","aria-busy":p,tabIndex:-1,"data-cloud-cancel-sheet":u.step,className:"flex max-h-[90vh] w-full max-w-[480px] flex-col overflow-hidden rounded-2xl border border-hairline/50 bg-panel text-ink shadow-2xl outline-none",onKeyDown:v=>{if(v.key==="Escape"&&(v.stopPropagation(),k()),v.key==="Tab"){const A=h.current?.querySelectorAll("a[href], textarea:enabled, button:enabled");if(!A?.length)return;const T=A[0],$=A[A.length-1];v.shiftKey&&document.activeElement===T?(v.preventDefault(),$.focus()):!v.shiftKey&&document.activeElement===$&&(v.preventDefault(),T.focus())}},children:[e.jsxs("header",{className:"flex items-start justify-between gap-3 px-6 pb-1 pt-5",children:[e.jsx("h2",{id:"cloud-cancel-title",className:"text-[17px] font-semibold",children:P}),e.jsx("button",{type:"button","aria-label":t("cloudCancel.close"),disabled:p,onClick:k,className:"rounded-lg p-1.5 text-ink-secondary hover:bg-raised",children:e.jsx($e,{size:18})})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 pb-5 pt-1",children:[u.step==="ask"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:Lp(s)}),e.jsxs("fieldset",{className:"mt-4",disabled:p,children:[e.jsx("legend",{className:"text-[14px] font-medium text-ink",children:t("cloudCancel.question")}),e.jsx("div",{className:"mt-2.5 flex flex-wrap gap-2",children:Ip.map(v=>e.jsx("button",{type:"button","aria-pressed":i===v,onClick:()=>r(A=>A===v?null:v),className:z("ui-button ui-button-pill",i===v&&"border-accent bg-accent/10 font-medium"),children:t(Pp[v])},v))})]}),e.jsxs("label",{className:"mt-4 block text-[13px] text-ink",children:[t("cloudCancel.expected")," ",e.jsx("span",{className:"text-ink-secondary",children:t("cloudCancel.optional")}),e.jsx("textarea",{rows:2,maxLength:Zn,value:c,disabled:p,onChange:v=>o(v.target.value),className:j})]}),e.jsxs("label",{className:"mt-3 block text-[13px] text-ink",children:[t("cloudCancel.improve")," ",e.jsx("span",{className:"text-ink-secondary",children:t("cloudCancel.optional")}),e.jsx("textarea",{rows:2,maxLength:Zn,value:d,disabled:p,onChange:v=>m(v.target.value),className:j})]}),e.jsxs("p",{className:"mt-3 text-[12px] text-ink-secondary",children:[t("cloudCancel.talk")," ",e.jsx("a",{href:Ap,target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 hover:text-ink",children:t("cloudCancel.book")})]}),B,e.jsxs("div",{className:"mt-5 flex flex-wrap justify-end gap-2",children:[e.jsx("button",{type:"button",className:"ui-button",disabled:p,onClick:k,children:t("cloudCancel.keep")}),e.jsx("button",{type:"button","data-cloud-cancel-confirm":!0,className:"ui-button border-transparent bg-danger text-white hover:brightness-110",disabled:p,onClick:E,children:t(p?"cloudCancel.cancelling":s.trial?"cloudCancel.confirmTrial":"cloudCancel.confirmPlan")})]})]}),u.step==="done"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{role:"status",className:"text-[14px] font-medium text-ink",children:Yi(u.renewal)}),e.jsx("p",{className:"mt-2 text-[13px] leading-relaxed text-ink-secondary",children:Rp(u.renewal)}),u.surveyed&&e.jsx("p",{className:"mt-2 text-[13px] leading-relaxed text-ink-secondary",children:t("cloudCancel.thanks")}),B,e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[13px] text-ink-secondary",children:t("cloudCancel.changedMind")}),e.jsx("button",{type:"button",className:"ui-button",disabled:p,onClick:N,children:t(p?"cloudCancel.keeping":"cloudCancel.keep")}),e.jsx("button",{type:"button",className:"ui-button ui-button-primary ms-auto",disabled:p,onClick:k,children:t("cloudCancel.done")})]})]}),u.step==="browser"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{role:"status",className:"text-[13px] leading-relaxed text-ink",children:t("cloudCancel.browser")}),e.jsx("div",{className:"mt-5 flex justify-end",children:e.jsx("button",{type:"button",className:"ui-button ui-button-primary",onClick:k,children:t("cloudCancel.done")})})]})]})]})}),document.body)}function Op(s){switch(s){case"offline":return R("Đang chờ My Cloud sẵn sàng. Kiểm tra đăng nhập và kết nối Cloud.","Waiting for My Cloud. Check your sign-in and connection.");case"account":return R("Phiên hiện tại chưa kết nối với My Cloud đã nhận các bot của máy này.","The current session is not connected to the My Cloud that received these bots.");case"local":return R("Chưa mở được thư mục dữ liệu gốc. Kiểm tra thư mục và thử lại.","The original local workspace could not be opened. Check the folder and retry.");case"manifest":return R("Chưa đọc được danh sách tác vụ tự động trên My Cloud. Bạn có thể thử lại.","Could not read automations from My Cloud. You can retry.");case"merge":return R("Chưa hoàn tất bước đưa bot và hội thoại về máy. Bạn có thể tiếp tục thử lại.","Could not finish returning bots and conversations. You can retry.");case"transfer":return R("Lượt đưa bot về bị gián đoạn. Bấm tiếp tục để thử lại.","Returning bots was interrupted. Select Resume to try again.")}}function ea({bridge:s}){const n=s?.keepHere,a=s?.setKeepHere;return s&&n&&a?e.jsx(Mp,{bridge:s,read:n,write:a}):null}function Mp({bridge:s,read:n,write:a}){const[i,r]=l.useState(null),[c,o]=l.useState(!1),[d,m]=l.useState(!1),[u,x]=l.useState(null);if(l.useEffect(()=>{let f=!0;const y=()=>{n().then(h=>{f&&r(h)}).catch(()=>{})};y();const b=s.onNotice(y);return()=>{f=!1,b()}},[s,n]),!i?.shown)return null;const p=f=>{o(!1),m(!0),x(null),a(f).then(y=>r(y),y=>x(Hr(y)??t("cloudAccount.keepHere.failed"))).finally(()=>m(!1))},g=()=>{i.on?p(!1):i.moved?o(!0):p(!0)};return e.jsxs("div",{"data-cloud-keep":i.coming?"coming":i.on?"on":"off",className:"rounded-xl bg-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[14px] font-medium text-ink",children:t("cloudAccount.keepHere.title")}),e.jsx("p",{className:"mt-1 text-[12px] leading-relaxed text-ink-secondary",children:t("cloudAccount.keepHere.line")})]}),e.jsx(me,{checked:i.on||i.coming,disabled:d||i.coming,"aria-label":t("cloudAccount.keepHere.title"),onClick:g})]}),d&&i.returnPending?e.jsx("p",{role:"status",className:"mt-3 text-[13px] text-ink-secondary",children:R("Đang thử lại lượt đưa bot về máy…","Retrying the return to this computer…")}):i.returnError?e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:Op(i.returnError)}):i.coming&&e.jsx("p",{role:"status",className:"mt-3 text-[13px] text-ink-secondary",children:t("cloudAccount.keepHere.coming")}),!c&&(i.moved||i.returnPending)&&e.jsx("button",{type:"button",className:"ui-button mt-3",disabled:d,onClick:()=>i.returnPending?p(!0):o(!0),children:i.returnPending?R("Tiếp tục đưa bot về máy này","Resume bringing bots back"):R("Đưa tất cả bot về máy này","Bring all bots back to this computer")}),c&&e.jsxs("div",{role:"group","aria-label":t("cloudAccount.keepHere.confirmTitle"),className:"mt-3 rounded-lg border border-hairline/40 p-3",children:[e.jsx("p",{className:"text-[13px] font-medium text-ink",children:t("cloudAccount.keepHere.confirmTitle")}),e.jsx("p",{className:"mt-1 text-[13px] leading-relaxed text-ink-secondary",children:t("cloudAccount.keepHere.confirm")}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",autoFocus:!0,className:"ui-button",onClick:()=>o(!1),children:t("common.cancel")}),e.jsx("button",{type:"button",className:"ui-button ui-button-primary",onClick:()=>p(!0),children:t("cloudAccount.keepHere.bringBack")})]})]}),u&&e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:u})]})}function zp({label:s,suggest:n,className:a="ui-button"}){const{dispatch:i}=G();return e.jsx("button",{type:"button",className:a,onClick:()=>i({type:"showFiles",...n?{suggest:n}:{}}),children:s})}function Up({trial:s,busy:n,onAsk:a}){return s==="pending"?e.jsx("p",{role:"status","data-limix-trial":"pending",className:"text-[13px] text-ink-secondary",children:R("Đã gửi yêu cầu dùng thử. Khi được duyệt, máy Cloud của bạn tự được dựng; mục này sẽ báo khi xong.","Trial requested. Once it is approved the Cloud is set up by itself; this page says when it's ready.")}):e.jsxs("div",{"data-limix-trial":s??"none",className:"flex flex-col items-start gap-2",children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:s==="declined"?R("Yêu cầu trước chưa được duyệt. Bạn có thể gửi lại.","Your earlier request wasn't approved. You can ask again."):R("Bot chạy 24/7 trên máy chủ Limix, kể cả khi máy tính này tắt.","Bots run 24/7 on a Limix server, even while this computer is off.")}),e.jsx("button",{type:"button",disabled:n,className:"ui-button ui-button-primary",onClick:a,children:R("Đăng ký dùng thử","Request a trial")})]})}const Fp={provisioning:"cloudHome.provisioning",ready:"cloudHome.ready",stopped:"cloudHome.stopped","payment-problem":"cloudHome.paymentProblem",failed:"cloudHome.failed"},Zi=s=>new Intl.DateTimeFormat(Me(),{timeStyle:"short"}).format(new Date(s)),Dp=s=>new Intl.DateTimeFormat(Me(),{dateStyle:"medium"}).format(new Date(s));function er(s,n){if(!s&&!n)return null;const a=s?Ia(s):null;return e.jsxs("div",{"data-cloud-trial":s?.state??"none",className:"flex flex-col gap-1",children:[a&&e.jsx("p",{className:"text-[13px] font-medium text-ink",children:a.title}),a&&e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:a.body}),n&&e.jsx("p",{"data-cloud-credit":n.state,className:"text-[13px] leading-relaxed text-ink-secondary",children:Sl(n)})]})}function ta({machine:s,busy:n,failed:a,onConnect:i,trial:r=!1,waking:c=!1,moving:o=null,team:d=null}){const m=s.status==="ready"?s.unreachable:void 0,u=s.status==="ready"&&!m,x=m?t(m.cause==="host"?"cloudHome.unreachableHost":"cloudHome.unreachable"):o??(c&&u?t("cloudHome.waking"):d?.name&&s.status==="ready"?t("cloudHome.team.ready",{name:d.name}):s.status==="ready"&&s.power?.sleeps?t("cloudHome.readySleeps"):r&&(s.status==="stopped"||s.status==="payment-problem")?t("cloudHome.stoppedTrial"):s.status==="failed"&&s.retryAt?t("cloudHome.failedRetry",{time:Zi(s.retryAt)}):s.status==="provisioning"&&s.setup?.slow?t("cloudHome.slow"):d&&s.status==="provisioning"?t("cloudHome.team.provisioning"):t(Fp[s.status]));return e.jsx(Y,{title:d?d.name??t("cloudHome.team.title"):t("cloudHome.title"),children:e.jsxs("div",{"data-cloud-home":s.status,"data-cloud-team":d?!0:void 0,"data-cloud-unreachable":m?.cause,"data-cloud-waking":c&&u?!0:void 0,"data-cloud-moving":o&&!m?!0:void 0,className:"flex flex-col items-start gap-3",children:[e.jsx("p",{role:"status",className:u?"text-[14px] text-ink":"text-[13px] text-ink-secondary",children:x}),s.status==="provisioning"&&s.setup&&e.jsx(hd,{step:s.setup.step}),u&&e.jsxs(e.Fragment,{children:[!o&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:n,className:"ui-button",onClick:i,children:d?.name?t("cloudBuy.setup.open",{name:d.name}):t("cloudHome.connect")}),e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("cloudHome.connectHelp")})]}),!d&&Yo()&&e.jsx(zp,{label:t("cloudHome.filesLink"),className:"text-[13px] font-medium text-accent-text underline underline-offset-2 hover:text-ink"})]}),a&&!m&&e.jsx("p",{role:"alert",className:"text-[13px] text-danger",children:t("cloudHome.connectFailed")})]})})}function _p({ready:s,busy:n,failed:a,onUse:i}){return e.jsx(Y,{title:t("cloudPhone.title"),subtitle:t("cloudPhone.subtitle"),children:e.jsxs("div",{"data-cloud-phone":s?"open":"steps",className:"flex flex-col items-start gap-3",children:[s&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:n,className:"ui-button",onClick:i,children:t("cloudPhone.action")}),e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("cloudPhone.help")})]}),a&&e.jsx("p",{role:"alert",className:"text-[13px] text-danger",children:t("cloudPhone.failed")}),(!s||a)&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t(s?"cloudPhone.stepsIntro":"cloudPhone.notReady")}),s&&e.jsxs("ol",{className:"list-decimal ps-5 text-[13px] leading-relaxed text-ink-secondary",children:[e.jsx("li",{children:t("cloudPhone.step1")}),e.jsx("li",{children:t("cloudPhone.step2")})]})]})]})})}function $p(s,n){return n.arrived&&s.status==="signed-out"&&s.message!=="restoring"?"sign-in":!n.connected&&s.status==="connected"&&s.machine?.status==="ready"&&!s.machine.unreachable?"connect":null}const Kp={darwin:"cloudAccount.restoreRetryKeychain",linux:"cloudAccount.restoreRetryKeyring"};function Hp(s,n,a){return s?s.message==="signout-local-only"?t("cloudAccount.signoutLocalOnly"):s.message==="signout-storage-failed"?t("cloudAccount.storageFailed"):s.message==="restore-failed"?t(Kp[a]??"cloudAccount.restoreRetry"):n.kind==="reauth"?t(n.reason==="expired"?"cloudAccount.reauthExpired":"cloudAccount.reauthEnded"):n.kind==="unverified"?t("cloudAccount.unavailable"):n.kind==="purchase"?n.paidAt?t("cloudAccount.purchaseNote",{date:Dp(n.paidAt)}):t("cloudAccount.purchaseNoteNoDate"):n.kind==="attention"&&!s.machine&&!s.trial?t("cloudAccount.attention"):s.status==="signed-out"&&s.message==="enrollment-expired"?t("cloudAccount.codeExpired"):s.status==="signed-out"&&s.message==="restore-removed"?t("cloudAccount.restoreRemoved"):s.status==="signed-out"&&s.message&&s.message!=="restoring"?t("cloudAccount.signinFailed"):null:null}function Wp({bridge:s,onConnectPhone:n}){const[a,i]=l.useState(null),[r,c]=l.useState(!1),[o,d]=l.useState(!1),[m,u]=l.useState(0);l.useEffect(()=>{let b=!0;return s.state().then(h=>{b&&i(h)}).catch(()=>{b&&d(!0)}),()=>{b=!1}},[s,m]);const x=s.cancel&&s.keep?{cancel:b=>s.cancel(b),keep:()=>s.keep()}:null;if(o)return e.jsx(Y,{title:t("settings.section.cloudAccount"),children:e.jsx("p",{"data-cloud-plan":"elsewhere",className:"text-[13px] text-ink-secondary",children:t("cloudAccount.onCloudNone")})});const p=Nl(a?.tier),g=a?.home===!0,f=a?.status==="paid"?t(wl(a.trial)?"cloudAccount.trialPlan":"cloudAccount.pro",{plan:p}):a?.status==="attention"?t("cloudAccount.inactive",{plan:a.tier?p:"Limix Bot Cloud"}):a?.status==="checking"?t("cloudAccount.lastPlan",{plan:p}):a?.status==="signin"?a.tier?t("cloudAccount.planName",{plan:p}):null:a?t(g?"cloudAccount.onCloudNoneHome":"cloudAccount.onCloudNone"):null,y=b=>{c(!1),b().catch(()=>c(!0))};return e.jsx(Y,{title:t("settings.section.cloudAccount"),subtitle:t(g?"cloudAccount.onCloudHome":"cloudAccount.onCloud"),children:e.jsxs("div",{"data-cloud-plan":a?.status??"loading",className:"flex flex-col items-start gap-3",children:[f?e.jsx("p",{role:"status",className:"text-[15px] font-medium text-ink",children:f}):!a&&e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("cloudAccount.loading")}),a?.status==="signin"&&e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("cloudAccount.onCloudSignIn")}),er(a?.trial,a?.credit),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a?.status==="signin"&&s.signIn&&e.jsx("button",{type:"button",className:"ui-button ui-button-primary",onClick:()=>y(()=>s.signIn()),children:t("cloudAccount.signInAgain")}),e.jsx("button",{type:"button",className:"ui-button",onClick:()=>y(()=>s.manage()),children:a?.trial&&!a.renewal?.cancelled&&Ia(a.trial).action?.label||t("cloudAccount.manageInBrowser")}),a&&n&&e.jsx("button",{type:"button",className:"ui-button",onClick:n,children:t("cloudPhone.action")}),e.jsx(Xo,{})]}),a?.renewal&&e.jsx(Qi,{renewal:a.renewal,actions:x,onChanged:()=>u(b=>b+1)}),r&&e.jsx("p",{role:"alert",className:"text-[13px] text-danger",children:t("cloudAccount.actionFailed")})]})})}function Gp({team:s}){return e.jsx(Y,{title:t("cloudAccount.teamPeopleTitle"),children:e.jsxs("div",{"data-cloud-plan":"team",className:"flex flex-col items-start gap-3",children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("cloudAccount.teamPeopleBody",{team:s.name})}),s.cloudPage&&e.jsx("a",{className:"ui-button",href:s.cloudPage,target:"_blank",rel:"noreferrer",children:t("cloudAccount.teamPeopleOpen")})]})})}function qp({bridge:s}){const[n,a]=l.useState(null),[i,r]=l.useState(!1),[c,o]=l.useState(!1);if(l.useEffect(()=>{let m=!0;return s.botSync?.().then(u=>{m&&a(u)}).catch(()=>{}),()=>{m=!1}},[s]),!n||!s.setBotSync)return null;const d=async()=>{r(!0),o(!1);try{a(await s.setBotSync(!n.enabled))}catch{o(!0)}finally{r(!1)}};return e.jsxs(Y,{title:t("cloudHome.syncLocalBots"),subtitle:t("cloudHome.syncLocalBotsHint"),children:[e.jsx(me,{"aria-label":t("cloudHome.syncLocalBots"),checked:n.enabled,disabled:i,onClick:()=>{d()}}),c&&e.jsx("p",{role:"alert",className:"mt-2 text-[13px] text-danger",children:t("cloudAccount.actionFailed")})]})}function Vp({linkRequest:s=0,cloudHome:n=!1,teamHome:a,onConnectPhone:i,onAddCloud:r,onSignIn:c}={}){const o=window.ogb?.remoteClient?.active?void 0:window.ogb?.cloudAccount,{platform:d}=Aa().capabilities.host,[m,u]=l.useState(null),[x,p]=l.useState(!1),[g,f]=l.useState(!1),[y,b]=l.useState(!1),[h,k]=l.useState(!1),[S,E]=l.useState(!1),[N,P]=l.useState(!1),j=l.useRef(0),B=l.useRef(0),v=l.useRef(!1),A=l.useRef({request:0,arrived:!1,connected:!1});l.useEffect(()=>{const ee=++j.current,K=B.current,le=ie=>{j.current===ee&&(B.current++,u(ie),f(!1),ie.status==="signed-out"&&b(!1))},_=o?.onState(le);return o?.state().then(ie=>{B.current===K&&le(ie)}).catch(()=>{j.current===ee&&B.current===K&&f(!0)}),()=>{j.current++,_?.()}},[o]);const T=async ee=>{if(!o||v.current)return;v.current=!0,p(!0),f(!1);const K=j.current,le=B.current;try{const _=await ee();j.current===K&&B.current===le&&u(_)}catch{j.current===K&&B.current===le&&f(!0)}finally{v.current=!1,j.current===K&&p(!1)}},$=()=>{o&&(E(!1),T(async()=>{try{return await o.connectHome()}catch{return E(!0),o.state()}}))},U=ee=>{o?.openTeam&&(E(!1),T(async()=>{try{await o.openTeam(ee)}catch{E(!0)}return o.state()}))},Z=()=>{o&&(P(!1),T(async()=>{try{return await o.connectHomeForPhone()}catch{return P(!0),o.state()}}))};l.useEffect(()=>{if(s||(A.current.request=0),!o||!s||!m||v.current||(A.current.request!==s&&(A.current={request:s,arrived:!0,connected:!1}),m.status==="signed-out"&&m.message==="restoring"))return;const ee=$p(m,A.current);A.current.arrived=!1,ee==="sign-in"&&T(()=>o.begin()),ee==="connect"&&(A.current.connected=!0,$())},[o,s,m,x]);const[H]=qo(o?window.ogb?.cloudSendPage:void 0),ne=H?.move?Wr(H.move,"local"):null,ae=ne&&ne.kind!=="done"?ne.text:null,oe=Bd(!!m&&rn(ln(m)),m?.offer),F=o?.cancelPlan&&o.keepPlan?{cancel:ee=>o.cancelPlan(ee),keep:()=>o.keepPlan()}:null;if(!o){const ee=window.ogb?.remoteClient?.active||!n?void 0:window.ogb?.cloudPlan;return e.jsxs(e.Fragment,{children:[n&&a?e.jsx(Gp,{team:a}):ee?e.jsx(Wp,{bridge:ee,onConnectPhone:i}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("cloudAccount.desktopOnly")}),ee&&!a&&e.jsx(ea,{bridge:window.ogb?.cloudSendPage})]})}const L=ln(m),X=m&&["connected","unavailable","reauth-required"].includes(m.status),se=Hp(m,L,d),he=bl(L),pe=yl(m),ce=vl(m),ue=L.kind==="paid"?{status:"provisioning"}:void 0,w=pe?ce?.machine??ue:m?.status==="connected"?m.machine??ue:void 0,re=m?.status==="connecting"?m.enrollment:void 0;jl(oe);const te=r&&rn();return e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("cloudAccount.optional")}),e.jsxs(Y,{title:t("settings.section.cloudAccount"),subtitle:t("cloudAccount.separate"),children:[m?.staging&&e.jsx(Gr,{className:"mb-3"}),(!m||L.kind==="unknown")&&e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("cloudAccount.loading")}),se&&e.jsx("p",{role:"status",className:"mb-3 text-[13px] text-ink-secondary",children:se}),(L.kind==="signed-out"||L.kind==="removed")&&e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[te,e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{T(()=>o.begin())},children:t("cloudAccount.signIn")})]}),m?.status==="connecting"&&e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("cloudAccount.browser")}),re&&e.jsxs("div",{"data-cloud-code":!0,className:"flex flex-col gap-1",children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("cloudAccount.codeCheck")}),e.jsx("code",{dir:"ltr",className:"select-all text-[18px] font-semibold tracking-widest text-ink",children:re.userCode}),e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("cloudAccount.codeUntil",{time:Zi(re.expiresAt)})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{T(()=>o.reopen())},children:t("organization.reopen")}),e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{T(()=>o.cancel())},children:t("organization.cancel")})]})]}),X&&e.jsxs("div",{className:"flex flex-col gap-3",children:[m.account?.id==="limix:leox"&&e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{T(()=>o.openDashboard())},children:R("Quản trị Limix Cloud","Manage Limix Cloud")}),m.account&&e.jsx("p",{className:"break-all text-[14px] text-ink",children:m.account.email}),he&&e.jsxs("p",{role:"status","data-cloud-plan":L.kind,className:"text-[15px] font-medium text-ink",children:[he,L.kind==="paid"&&L.checking&&e.jsx("span",{className:"ms-2 text-[12px] font-normal text-ink-secondary",children:t("cloudAccount.checking")})]}),m.status==="connected"&&er(m.trial,m.credit),L.kind==="free"&&te,L.kind==="free"&&!Wt&&m.status==="connected"&&o.requestTrial&&e.jsx(Up,{trial:m.limixTrial,busy:x,onAsk:()=>{T(async()=>(await o.requestTrial()).state)}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[L.kind==="reauth"?e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{T(()=>o.signInAgain())},children:t("cloudAccount.signInAgain")}):e.jsxs(e.Fragment,{children:[Wt,e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{T(()=>o.refresh())},children:t("organization.refresh")})]}),!y&&e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>b(!0),children:t("cloudAccount.signOut")})]}),m.status==="connected"&&m.renewal&&e.jsx(Qi,{renewal:m.renewal,actions:F}),Wt,h&&e.jsx(kl,{adding:"",onClose:()=>k(!1)}),y&&e.jsxs("div",{role:"group","aria-label":t("cloudAccount.signoutTitle"),className:"rounded-lg border border-hairline/40 p-3",children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("cloudAccount.signoutHelp")}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",autoFocus:!0,disabled:x,className:"ui-button",onClick:()=>b(!1),children:t("cloudAccount.keep")}),e.jsx("button",{type:"button",disabled:x,className:"ui-button text-danger",onClick:()=>{T(()=>o.signOut())},children:t("cloudAccount.signOut")})]})]})]}),g&&e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:t("cloudAccount.actionFailed")}),!m&&e.jsx("button",{type:"button",disabled:x,className:"ui-button mt-3",onClick:()=>{T(()=>o.state())},children:t("organization.refresh")})]}),w&&ta(pe?{machine:w,busy:x,failed:S,onConnect:()=>{ce&&U(ce.id)},team:{name:ce?.name??null}}:{machine:w,busy:x,failed:S,onConnect:$,trial:!!m?.trial,waking:m?.waking===!0,moving:ae}),!pe&&w?.accountLink&&e.jsx(Y,{title:t("cloudHome.accountLink"),children:e.jsx("a",{className:"break-all text-[13px] text-accent hover:underline",href:w.accountLink,target:"_blank",rel:"noopener noreferrer",children:w.accountLink})}),X&&!pe&&m?.account?.id&&w?.status==="ready"&&w.origin&&!w.unreachable&&!w.hold&&window.ogb?.cloudSendPage&&e.jsx(Vo,{bridge:window.ogb.cloudSendPage},`agents-${m.account.id}`),X&&!pe&&m?.account?.id&&window.ogb?.cloudSendPage?.botSync&&e.jsx(qp,{bridge:window.ogb.cloudSendPage},m.account.id),X&&L.kind==="paid"&&!pe&&_p({ready:w?.status==="ready"&&!w.unreachable,busy:x,failed:N,onUse:Z}),e.jsx(ea,{bridge:window.ogb?.cloudSendPage}),X&&!pe&&e.jsx(Jo,{})]})}function Jp({account:s}){const n=s?.status==="connected"&&!s.checking,a=n&&s.limixTrial==="approved"&&s.entitlement?.status==="active",i=n&&s.entitlement?.plan==="free",r=R("Gói hiện tại","Current plan");return e.jsxs("section",{"aria-labelledby":"limix-billing-plans",className:"space-y-3",children:[e.jsx("h3",{id:"limix-billing-plans",className:"text-[15px] font-semibold text-ink",children:R("Thanh toán","Billing")}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-xl border border-hairline/50 bg-card p-4",children:[e.jsxs("h4",{className:"font-semibold text-ink",children:["Free",i&&e.jsx("span",{className:"ml-2 text-xs text-accent",children:r})]}),e.jsx("p",{className:"mt-2 text-[13px] text-ink-secondary",children:R("Miễn phí cho mọi tài khoản. Bạn có thể dùng bot trên máy tính. Gói này không bao gồm Limix Cloud.","Free for every account. Run bots on your computer. Limix Cloud is excluded.")})]}),e.jsxs("div",{className:"rounded-xl border border-hairline/50 bg-card p-4",children:[e.jsxs("h4",{className:"font-semibold text-ink",children:["Limix Cloud Beta",a&&e.jsx("span",{className:"ml-2 text-xs text-accent",children:r})]}),e.jsx("p",{className:"mt-2 text-[13px] text-ink-secondary",children:R("Chạy bot trên Limix Cloud. Trong giai đoạn thử nghiệm, chỉ quản trị viên Limix mới có thể cấp quyền cho tài khoản.","Run bots on Limix Cloud. During the beta, access is granted internally by a Limix administrator.")})]})]}),e.jsx("p",{className:"text-xs text-ink-secondary",children:R("Chi phí mô hình trong báo cáo mức dùng là số liệu ước tính, không phải hóa đơn của Limix.","Model costs in the usage report are estimates, not a Limix invoice.")})]})}function tr(){return e.jsx(Jp,{account:fi()?.account})}function sa(s,n,a){const i=s/10**a;try{return new Intl.NumberFormat(Me(),{style:"currency",currency:n,minimumFractionDigits:a,maximumFractionDigits:a}).format(i)}catch{return`${i.toFixed(Math.min(a,100))} ${n}`}}function sr(s){return t("planUsage.spendAmounts",{used:sa(s.usedMinor,s.currency,s.exponent),limit:sa(s.limitMinor,s.currency,s.exponent)})}function nr(s,n){if(!s)return null;const a=Date.parse(s);if(!Number.isFinite(a)||a<=n)return null;const i=Math.floor((a-n)/6e4);if(i<1)return"less than a minute";const r=Math.floor(i/1440),c=Math.floor(i%1440/60),o=i%60;return r>0?c>0?`${r}d ${c}h`:`${r}d`:c>0?o>0?`${c}h ${o}m`:`${c}h`:`${o}m`}function Xp(s,n,a){const i=[];for(const r of s.providers){if(!r.ok)continue;const c=[r.fiveHour.available?r.fiveHour.resetsAt:null,r.weekly.available?r.weekly.resetsAt:null,...r.extra.map(o=>o.resetsAt),...(r.models??[]).flatMap(o=>o.windows.map(d=>d.resetsAt))];for(const o of c){if(!o||a.has(o)||i.includes(o))continue;const d=Date.parse(o);Number.isFinite(d)&&d<=n&&i.push(o)}}return i}function Yp(s){return s>=90?"bg-danger":s>=70?"bg-warning":"bg-success"}function na(s){return s==="5-hour"?t("planUsage.fiveHour"):s==="Weekly"?t("planUsage.weekly"):s==="Monthly spend"?t("planUsage.monthlySpend"):s}function It(s){const n=s.name.trim().toLowerCase();return n==="chatgpt plan"?t("planUsage.provider.chatgptPlan"):n==="claude (api key)"?t("planUsage.provider.claudeApiKey"):s.name}function Qp(s){const n=s.error?.trim();if(!n)return null;const a=/^Sign in again in (.+)$/i.exec(n);return a?t("planUsage.signInAgain",{provider:It({name:a[1]})}):n}function jt({label:s,window:n,now:a,usedHeadline:i=!1,detail:r}){const c=n.available?nr(n.resetsAt,a):null,o=n.usedPercent??0,d=i?n.usedPercent==null?null:t("planUsage.used",{used:Math.round(n.usedPercent)}):n.remainingPercent==null?null:t("planUsage.left",{remaining:Math.round(n.remainingPercent)});return e.jsxs("div",{className:"grid grid-cols-[4.5rem_minmax(0,1fr)] items-center gap-x-3 gap-y-1",children:[e.jsx("div",{className:"text-[12px] text-ink-secondary",children:s}),n.available&&d?e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 text-[13px] text-ink",children:[e.jsx("span",{className:"tabular-nums",children:d}),r&&e.jsx("span",{"data-plan-spend":!0,className:"text-[12px] tabular-nums text-ink-secondary",children:r}),c&&e.jsx("span",{className:"text-[12px] text-ink-secondary",children:t("planUsage.resetsIn",{when:c})})]}),e.jsx("div",{className:"mt-1 h-1.5 overflow-hidden rounded-full bg-inset",role:"meter","aria-label":s,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(Math.min(100,Math.max(0,o))),children:e.jsx("div",{className:z("h-full rounded-full",Yp(o)),style:{width:`${Math.min(100,Math.max(0,o))}%`}})})]}):e.jsx("div",{className:"text-[12px] text-ink-secondary",children:t("planUsage.notReported")})]})}function ar(){const[s,n]=l.useState(null),[a,i]=l.useState(!0),[r,c]=l.useState(""),[o,d]=l.useState(()=>Date.now()),m=l.useRef(new Set),u=l.useCallback(async(x=!1)=>{i(!0),c("");try{const p=await M(x?"/api/plan-usage?refresh=1":"/api/plan-usage");n(p),d(Date.now())}catch(p){c(p instanceof Error&&p.message?p.message:t("planUsage.fetchError"))}finally{i(!1)}},[]);return l.useEffect(()=>{u(!1)},[u]),l.useEffect(()=>{const x=window.setInterval(()=>d(Date.now()),3e4);return()=>window.clearInterval(x)},[]),l.useEffect(()=>{if(!s)return;const x=Xp(s,o,m.current);if(x.length!==0){for(const p of x)m.current.add(p);u(!0)}},[s,o,u]),{report:s,loading:a,error:r,now:o,load:u}}function Zp(s){for(const n of s?.providers??[]){const a=n.ok&&!n.weekly.available?n.extra.find(i=>i.label==="Monthly spend"):void 0;if(a)return{provider:n,budget:a}}return null}function ex(s){let n=null;for(const a of s?.providers??[]){const i=a.ok&&a.weekly.available?a.weekly.usedPercent:null;i!==null&&(!n||i>n.used)&&(n={provider:a,used:i})}return n}function tx(){const{report:s,now:n}=ar();if(!s)return null;const a=ex(s),i=a?null:Zp(s);if(i){const d=It(i.provider),m=Math.round(Math.min(100,Math.max(0,i.budget.usedPercent)));return e.jsx(xn,{kind:"plan",title:t("settings.simple.billing.monthlySpend",{provider:d}),percent:m,label:`${d}: ${t("planUsage.used",{used:m})}`,note:i.budget.spend?sr(i.budget.spend):null})}if(!a)return e.jsx("section",{"data-usage-summary":"own-ai",className:z(Qo,"px-4 py-3.5 text-[14px] leading-5 text-ink-secondary"),children:t("settings.simple.billing.ownAi")});const r=Math.round(Math.min(100,Math.max(0,a.used))),c=nr(a.provider.weekly.resetsAt,n),o=It(a.provider);return e.jsx(xn,{kind:"plan",title:t("settings.simple.billing.weekly",{provider:o}),percent:r,label:`${o}: ${t("planUsage.used",{used:r})}`,note:c?t("planUsage.resetsIn",{when:c}):null})}function sx(){const{report:s,loading:n,error:a,now:i,load:r}=ar();return e.jsxs(Y,{title:t("planUsage.title"),subtitle:t("planUsage.subtitle"),children:[e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>{r(!0)},disabled:n,"aria-label":t("planUsage.refresh"),title:t("planUsage.refresh"),className:"rounded-md p-2 text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50",children:n?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(Ae,{size:14})})}),n&&!s&&e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("planUsage.loading")}),a&&e.jsx("p",{role:"alert",className:"mb-3 text-[13px] text-danger",children:a}),s&&s.providers.length===0&&e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("planUsage.empty")}),s&&s.providers.length>0&&e.jsx("div",{className:"flex flex-col gap-4",children:s.providers.map(c=>e.jsxs("div",{className:"border-t border-hairline/30 pt-3 first:border-t-0 first:pt-0",children:[e.jsxs("div",{className:"mb-2 flex min-w-0 items-baseline gap-2",children:[e.jsx("span",{className:"truncate text-[14px] font-medium text-ink",children:It(c)}),c.plan&&e.jsx("span",{className:"truncate text-[12px] text-ink-secondary",children:c.plan})]}),c.ok?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(jt,{label:t("planUsage.fiveHour"),window:c.fiveHour,now:i}),e.jsx(jt,{label:t("planUsage.weekly"),window:c.weekly,now:i}),c.extra.map((o,d)=>e.jsx(jt,{label:na(o.label),now:i,usedHeadline:!!o.spend,detail:o.spend?sr(o.spend):void 0,window:{available:!0,remainingPercent:o.remainingPercent,usedPercent:o.usedPercent,resetsAt:o.resetsAt}},`${o.label}-${d}`)),(c.models??[]).length>0&&e.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[e.jsx("div",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-ink-secondary",children:t("planUsage.byModel")}),(c.models??[]).map(o=>e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"truncate text-[13px] font-medium text-ink",children:o.name}),o.windows.map((d,m)=>e.jsx(jt,{label:na(d.label),now:i,usedHeadline:!0,window:{available:!0,remainingPercent:d.remainingPercent,usedPercent:d.usedPercent,resetsAt:d.resetsAt}},`${o.name}-${d.label}-${m}`))]},o.name))]})]}):e.jsx("p",{className:"text-[13px] text-danger",children:Qp(c)})]},c.id))})]})}function aa(s,n){return s?.edition?.features?.includes(n)===!0}function nx(s){return s?s.exceeded?"danger":s.warn?"warning":"quiet":"quiet"}function ax({budget:s}){const{state:n,dispatch:a}=G(),i=n.config?.budgets??{},[r,c]=l.useState(i.monthlyUsd===void 0?"":String(i.monthlyUsd)),[o,d]=l.useState(i.warnAtPercent===void 0?"80":String(i.warnAtPercent)),[m,u]=l.useState(!1),[x,p]=l.useState(null);l.useEffect(()=>{c(i.monthlyUsd===void 0?"":String(i.monthlyUsd)),d(i.warnAtPercent===void 0?"80":String(i.warnAtPercent))},[i.monthlyUsd,i.warnAtPercent]);const g=async()=>{if(m)return;const y=r.trim()===""?0:Number(r),b=Number(o);if(!Number.isFinite(y)||y<0||!Number.isInteger(b)||b<1||b>100){p(t("usage.budget.invalid"));return}u(!0),p(null);try{const h=await M("/api/config",{method:"PUT",body:JSON.stringify({budgets:{monthlyUsd:y,warnAtPercent:b}})});a({type:"configStatus",config:h})}catch(h){p(h instanceof Error?h.message:String(h))}finally{u(!1)}},f=nx(s);return e.jsxs(Y,{title:t("usage.budget.title"),subtitle:t("usage.budget.subtitle"),children:[s?e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-1 flex items-baseline justify-between text-[13px]",children:[e.jsx("span",{className:z(f==="danger"?"text-danger":f==="warning"?"text-warning":"text-ink"),children:s.exceeded?t("usage.budget.reached"):s.warn?t("usage.budget.nearing"):t("usage.budget.within")}),e.jsx("span",{className:"tabular-nums text-ink-secondary",children:t("usage.budget.spent",{spent:ct(s.spentUsd),cap:ct(s.monthlyUsd),percent:String(s.percent)})})]}),e.jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-inset",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.min(100,s.percent),children:e.jsx("div",{className:z("h-full rounded-full",f==="danger"?"bg-danger":f==="warning"?"bg-warning":"bg-accent"),style:{width:`${Math.min(100,s.percent)}%`}})})]}):e.jsx("p",{className:"mb-4 text-[13px] text-ink-secondary",children:t("usage.budget.none")}),e.jsxs("form",{className:"flex flex-wrap items-end gap-3",onSubmit:y=>{y.preventDefault(),g()},children:[e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("usage.budget.monthly"),e.jsx("input",{value:r,onChange:y=>c(y.target.value),inputMode:"decimal",placeholder:"0","aria-label":t("usage.budget.monthly"),disabled:m,className:"w-32 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] tabular-nums text-ink focus:outline-none disabled:opacity-50"})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("usage.budget.warnAt"),e.jsx("input",{value:o,onChange:y=>d(y.target.value),inputMode:"numeric","aria-label":t("usage.budget.warnAt"),disabled:m,className:"w-20 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] tabular-nums text-ink focus:outline-none disabled:opacity-50"})]}),e.jsxs("button",{type:"submit",disabled:m,className:"flex items-center gap-1.5 rounded-lg bg-raised px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",children:[m&&e.jsx(J,{size:13,className:"animate-spin"}),t("common.save")]})]}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("usage.budget.hint")}),x&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:x})]})}function ia(s){const n=Object.entries(s??{}).map(([a,i])=>({key:a,input:String(i.inputPerMillion),output:String(i.outputPerMillion),cached:i.cachedInputPerMillion===void 0?"":String(i.cachedInputPerMillion)}));return n.length?n:[{key:"default",input:"",output:"",cached:""}]}function ix(){const{state:s,dispatch:n}=G(),a=s.config?.billing,[i,r]=l.useState(a?.currency??"USD"),[c,o]=l.useState(ia(a?.prices)),[d,m]=l.useState(!1),[u,x]=l.useState(null);l.useEffect(()=>{r(a?.currency??"USD"),o(ia(a?.prices))},[a]);const p=(y,b)=>o(h=>h.map((k,S)=>S===y?{...k,...b}:k)),g=async()=>{if(d)return;const y={};for(const b of c){const h=b.key.trim();if(!h)continue;const k=Number(b.input),S=Number(b.output),E=b.cached.trim()===""?void 0:Number(b.cached);if(!Number.isFinite(k)||!Number.isFinite(S)||k<0||S<0||E!==void 0&&(!Number.isFinite(E)||E<0)){x(t("usage.prices.invalid",{model:h}));return}y[h]={inputPerMillion:k,outputPerMillion:S,...E===void 0?{}:{cachedInputPerMillion:E}}}if(!/^[A-Z]{3}$/.test(i.trim().toUpperCase())){x(t("usage.prices.currencyInvalid"));return}m(!0),x(null);try{const b=await M("/api/config",{method:"PUT",body:JSON.stringify({billing:{currency:i.trim().toUpperCase(),prices:y}})});n({type:"configStatus",config:b})}catch(b){x(b instanceof Error?b.message:String(b))}finally{m(!1)}},f="w-full rounded-lg border border-hairline/40 bg-inset px-2 py-1.5 text-[13px] tabular-nums text-ink focus:outline-none disabled:opacity-50";return e.jsxs(Y,{title:t("usage.prices.title"),subtitle:t("usage.prices.subtitle"),children:[e.jsx("div",{className:"mb-3 flex items-center gap-2 text-[12px] text-ink-secondary",children:e.jsxs("label",{className:"flex items-center gap-2",children:[t("usage.prices.currency"),e.jsx("input",{value:i,onChange:y=>r(y.target.value),maxLength:3,"aria-label":t("usage.prices.currency"),disabled:d,className:"w-16 rounded-lg border border-hairline/40 bg-inset px-2 py-1.5 text-[13px] uppercase text-ink focus:outline-none disabled:opacity-50"})]})}),e.jsxs("div",{className:"grid grid-cols-[1fr_5rem_5rem_5rem_auto] items-center gap-x-2 gap-y-1.5 text-[12px] font-medium uppercase tracking-wide text-ink-secondary",children:[e.jsx("span",{children:t("usage.prices.colModel")}),e.jsx("span",{children:t("usage.prices.colInput")}),e.jsx("span",{children:t("usage.prices.colOutput")}),e.jsx("span",{children:t("usage.prices.colCached")}),e.jsx("span",{}),c.map((y,b)=>e.jsxs("div",{className:"contents",children:[e.jsx("input",{value:y.key,onChange:h=>p(b,{key:h.target.value}),placeholder:t("usage.prices.modelPlaceholder"),"aria-label":t("usage.prices.colModel"),disabled:d,className:z(f,"font-mono normal-case tracking-normal")}),e.jsx("input",{value:y.input,onChange:h=>p(b,{input:h.target.value}),inputMode:"decimal","aria-label":t("usage.prices.colInput"),disabled:d,className:f}),e.jsx("input",{value:y.output,onChange:h=>p(b,{output:h.target.value}),inputMode:"decimal","aria-label":t("usage.prices.colOutput"),disabled:d,className:f}),e.jsx("input",{value:y.cached,onChange:h=>p(b,{cached:h.target.value}),inputMode:"decimal",placeholder:"—","aria-label":t("usage.prices.colCached"),disabled:d,className:f}),e.jsx("button",{type:"button",onClick:()=>o(h=>h.filter((k,S)=>S!==b)),"aria-label":t("usage.prices.remove"),disabled:d,className:"rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-danger disabled:opacity-50",children:e.jsx(Se,{size:13})})]},b))]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>o(y=>[...y,{key:"",input:"",output:"",cached:""}]),disabled:d,className:"flex items-center gap-1.5 rounded-lg border border-hairline/40 px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:opacity-50",children:[e.jsx(we,{size:13}),t("usage.prices.add")]}),e.jsxs("button",{type:"button",onClick:()=>{g()},disabled:d,className:"ml-auto flex items-center gap-1.5 rounded-lg bg-raised px-3 py-1.5 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",children:[d&&e.jsx(J,{size:13,className:"animate-spin"}),t("common.save")]})]}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("usage.prices.hint")}),u&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:u})]})}function rx({budget:s}){const{state:n}=G(),a=aa(n.config,"budgets"),i=aa(n.config,"billing");return!a&&!i?null:e.jsxs(e.Fragment,{children:[a&&e.jsx(ax,{budget:s}),i&&e.jsx(ix,{})]})}const lx=["model","user","department","day","engine","routine"],ra={bot:"usage.history.byBot",model:"usage.history.byModel",user:"usage.history.byUser",day:"usage.history.byDay",engine:"usage.history.byEngine",routine:"usage.history.byRoutine",department:"usage.history.byDepartment"},ox={today:"usage.page.today",week:"usage.page.week",month:"usage.history.thisMonth",lastMonth:"usage.history.lastMonth",days30:"usage.history.last30Days"},cx=2e3;function dx(s,n){return n.key==="routine:private"?t("usage.history.privateRoutine"):n.key==="bot:private"?t("usage.history.privateBot"):s==="routine"?n.key==="manual"?t("usage.history.notRoutine"):n.label:s==="department"?n.label||t("usage.history.noDepartment"):s!=="user"?n.label:n.key==="owner"?t("usage.history.owner"):n.key==="bot"?t("usage.history.botToBot"):n.key.startsWith("routine:")?t("usage.history.routine",{name:n.label.replace(/^Routine: /,"")}):n.label}function la(s,n,a){const[i,r]=l.useState(null);return l.useEffect(()=>{let c=!0;return M(`/api/usage?from=${encodeURIComponent(s.from)}&to=${encodeURIComponent(s.to)}&groupBy=${n}`).then(o=>{c&&r(o)}).catch(()=>{c&&r(null)}),()=>{c=!1}},[s.from,s.to,n,a]),i}function oa({groupBy:s,groups:n}){const{state:a}=G(),i=[...n].sort((c,o)=>nt(o)-nt(c)).slice(0,6),r=Math.max(...i.map(nt),0);return!i.length||r<=0?e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("usage.page.whereEmpty")}):e.jsx("ul",{className:"flex flex-col gap-2.5",children:i.map(c=>{const o=s==="bot"?a.bots.find(d=>`bot:${d.id}`===c.key):void 0;return e.jsxs("li",{className:"grid grid-cols-[minmax(0,9rem)_1fr_auto] items-center gap-3 text-[13px]",title:t("usage.page.turns",{count:String(c.turns)}),children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2 text-ink",children:[o&&e.jsx(Bt,{bot:o,state:"idle",size:18,animated:!1}),e.jsx("span",{className:"truncate",children:s==="model"?cc(c.label,a.instances):dx(s,c)})]}),e.jsx("span",{className:"h-2 overflow-hidden rounded-full bg-raised",children:e.jsx("span",{className:"block h-full rounded-full bg-accent/70",style:{width:`${Math.max(2,nt(c)/r*100)}%`}})}),e.jsxs("span",{className:"min-w-[4.5rem] text-right tabular-nums text-ink-secondary",children:[dc(nt(c)),ot(c.costUsd)&&c.costUsd>0&&` · ${Va(c.costUsd)}`]})]},c.key)})})}function ux({range:s,version:n,onBudget:a}){const[i,r]=l.useState("model"),c=la(s,"bot",n),o=la(s,i,n);return l.useEffect(()=>{a(c?.budget??null)},[c,a]),e.jsxs("section",{className:"rounded-2xl border border-hairline/50 bg-card p-5","aria-label":t("usage.page.where"),children:[e.jsx("h3",{className:"text-[15px] font-medium text-ink",children:t("usage.page.where")}),e.jsxs("div",{className:"mt-4 grid gap-6 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-3 text-[11px] font-medium uppercase tracking-[0.08em] text-ink-secondary",children:t(ra.bot)}),c?e.jsx(oa,{groupBy:"bot",groups:c.groups}):e.jsx(J,{size:14,className:"animate-spin text-ink-secondary"})]}),e.jsxs("div",{children:[e.jsx("div",{role:"tablist","aria-label":t("usage.history.groupBy"),className:"-mt-1 mb-2 flex flex-wrap gap-1",children:lx.map(d=>e.jsx("button",{type:"button",role:"tab","aria-selected":i===d,onClick:()=>r(d),className:z("rounded-md px-2 py-0.5 text-[11px] font-medium uppercase tracking-[0.06em]",i===d?"bg-accent/12 text-accent":"text-ink-secondary hover:bg-raised/60 hover:text-ink"),children:t(ra[d])},d))}),o?.groupBy===i?e.jsx(oa,{groupBy:i,groups:o.groups}):e.jsx(J,{size:14,className:"animate-spin text-ink-secondary"})]})]})]})}function mx(s){return new Date(s).toLocaleString(qr(Me()),{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function px({root:s,onOpen:n}){const{state:a}=G(),i=s.title||t(`trace.source.${s.source}`,{bot:s.bots[0]?.name??""});return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:n,className:"grid w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-3 rounded-xl px-3 py-2.5 text-left hover:bg-raised/50","data-testid":"usage-run",children:[e.jsx("span",{className:"flex w-[38px] shrink-0 -space-x-1.5 sm:w-[74px]",children:s.bots.slice(0,4).map((r,c)=>{const o=a.bots.find(d=>d.id===r.id);return o?e.jsx("span",{className:z("rounded-full ring-2 ring-card",c>1&&"hidden sm:block"),children:e.jsx(Bt,{bot:o,state:"idle",size:22,animated:!1})},r.id):e.jsx("span",{className:z("flex size-[22px] items-center justify-center rounded-full bg-raised text-[10px] font-semibold text-ink-secondary ring-2 ring-card",c>1&&"hidden sm:flex"),children:r.name.slice(0,1).toUpperCase()},r.id)})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-[14px] text-ink",children:i}),e.jsxs("span",{className:"block truncate text-[12px] text-ink-tertiary",children:[mx(s.startedAt)," · ",s.bots.map(r=>r.name).join(", ")]})]}),e.jsxs("span",{className:"flex items-center gap-3 text-[13px] tabular-nums text-ink-secondary",children:[s.running&&e.jsx(lc,{}),s.errors>0&&e.jsx("span",{className:"rounded-md bg-danger/12 px-1.5 py-0.5 text-[12px] font-medium text-danger",children:t("trace.groupErrors",{count:String(s.errors)})}),s.timed?e.jsx("span",{className:"hidden min-w-[3.5rem] text-right sm:inline",children:oc(s.durationMs)}):e.jsx("span",{className:"hidden rounded bg-raised px-1.5 text-[11px] sm:inline",children:t("trace.notTimed")}),e.jsx("span",{className:"min-w-[3.5rem] text-right text-ink",children:Va(s.costUsd)}),e.jsx(Ps,{size:14,className:"text-ink-tertiary"})]})]})})}function ir(){const[s,n]=l.useState("month"),a=l.useMemo(()=>Zo(s),[s]),[i,r]=l.useState(null),[c,o]=l.useState(null),[d,m]=l.useState(0),[u,x]=l.useState(null),[p,g]=l.useState(null),f=l.useRef(null);l.useEffect(()=>{let h=!0;return gn(a).then(k=>{h&&(r(k),o(null))}).catch(k=>{h&&o(k instanceof Error?k.message:String(k))}),()=>{h=!1}},[a,d]),l.useEffect(()=>ec({onFrame:h=>{if(h.kind!=="runtime"||f.current)return;const k=h.event?.type;k!=="turn.started"&&k!=="turn.completed"||(f.current=setTimeout(()=>{f.current=null,m(S=>S+1)},cx))},onMissedFrames:()=>m(h=>h+1)}),[]),l.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const y=()=>{i?.next&&gn(a,i.next).then(h=>r(k=>k?{...h,roots:[...k.roots,...h.roots]}:h))},b=i?.roots.some(h=>!h.timed);return e.jsxs("div",{className:"flex flex-col gap-4","data-testid":"usage-page",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4",children:[e.jsx("p",{className:"min-w-0 flex-1 text-[13px] leading-relaxed text-ink-secondary",children:t("usage.page.subtitle")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{size:"sm",value:s,onChange:h=>{n(h.target.value),g(null)},"aria-label":t("usage.history.period"),children:tc.map(h=>e.jsx("option",{value:h,children:t(ox[h])},h))}),e.jsxs("a",{href:sc(a),download:!0,className:"flex items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink",children:[e.jsx(Ye,{size:13}),t("usage.history.export")]})]})]}),c&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:c}),p?e.jsx(nc,{id:p.id,at:p.at,actions:e.jsxs("button",{type:"button",onClick:()=>g(null),className:"flex shrink-0 items-center gap-1 rounded-lg px-2 py-1 text-[13px] text-ink-secondary hover:bg-raised hover:text-ink",children:[e.jsx(ac,{size:13}),t("trace.back")]})}):e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"overflow-hidden rounded-2xl border border-hairline/50 bg-card","data-testid":"usage-totals",children:i?e.jsx(ic,{items:rc(i.totals,t("trace.stat.time"))}):e.jsxs("div",{className:"flex items-center gap-2 p-5 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:14,className:"animate-spin"}),t("common.checking")]})}),e.jsx(ux,{range:a,version:d,onBudget:x}),e.jsxs("section",{className:"rounded-2xl border border-hairline/50 bg-card p-2","aria-label":t("usage.page.runs"),children:[e.jsxs("div",{className:"px-3 pb-1 pt-3",children:[e.jsx("h3",{className:"text-[15px] font-medium text-ink",children:t("usage.page.runs")}),e.jsx("p",{className:"mt-0.5 text-[13px] text-ink-secondary",children:t("usage.page.runsHint")})]}),i&&!i.roots.length&&e.jsx("p",{className:"px-3 py-3 text-[13px] text-ink-secondary",children:t("usage.page.runsEmpty")}),e.jsx("ul",{className:"mt-1 flex flex-col",children:i?.roots.map(h=>e.jsx(px,{root:h,onOpen:()=>g({id:h.id,at:h.startedAt})},h.id))}),i?.next!==void 0&&e.jsx("button",{type:"button",onClick:y,className:"m-2 rounded-lg px-3 py-1.5 text-[13px] text-accent hover:bg-raised/50",children:t("usage.page.more")}),b&&e.jsx("p",{className:"px-3 pb-3 pt-1 text-[12px] text-ink-tertiary",children:t("usage.page.untimedNote")})]})]}),e.jsx(sx,{}),e.jsx(rx,{budget:u})]})}const Je=["catalog","bundled","local","tools"];function xx({catalog:s,bundled:n,tools:a,children:i}){const[r,c]=l.useState("catalog"),o=l.useId(),d={catalog:R("Kho kỹ năng","Skill catalog"),bundled:R("Có sẵn","Built-in"),local:t("skills.library.title"),tools:R("Công cụ","Tools")},m={catalog:s,bundled:n,local:i,tools:a};return e.jsxs(e.Fragment,{children:[e.jsx("div",{role:"tablist","aria-label":t("settings.section.skills"),className:"sticky top-0 z-10 flex flex-wrap gap-1 self-start rounded-xl border border-hairline/40 bg-card p-1",children:Je.map((u,x)=>e.jsx("button",{type:"button",role:"tab",id:o+u,"aria-controls":o+u+"-panel","aria-selected":r===u,tabIndex:r===u?0:-1,className:`rounded-lg px-3 py-1.5 text-[13px] font-medium ${r===u?"bg-control text-ink":"text-ink-secondary hover:text-ink"}`,onClick:()=>c(u),onKeyDown:p=>{const f={ArrowRight:1,ArrowLeft:-1,Home:-x,End:Je.length-1-x}[p.key];if(typeof f!="number")return;p.preventDefault();const y=Je[(x+f+Je.length)%Je.length];c(y),document.getElementById(o+y)?.focus()},children:d[u]},u))}),Je.map(u=>e.jsx("section",{role:"tabpanel",id:o+u+"-panel","aria-labelledby":o+u,hidden:r!==u,children:e.jsx("div",{className:"flex flex-col gap-4",children:m[u]})},u))]})}function gx(){const[s,n]=l.useState(null);return l.useEffect(()=>{fetch("/api/limix/bundled-skills").then(a=>a.ok?a.json():{skills:[]}).then(a=>n(a.skills??[])).catch(()=>n([]))},[]),e.jsx(Y,{title:R("Kỹ năng có sẵn của Limix Bot","Skills built into Limix Bot"),subtitle:R("Mọi bot đều có sẵn các kỹ năng cơ bản. Để thêm kỹ năng khác, mở mục Kỹ năng trong cài đặt của từng bot.","Shipped with the app. Core skills are always on for every bot; the others wait in the store, and you add them to one bot at a time under the bot's Skills page."),children:e.jsx("div",{className:"flex flex-col gap-3",children:s===null?null:s.length===0?e.jsx("p",{className:"text-[13px] text-ink-secondary",children:R("Chưa thấy kỹ năng có sẵn nào trong bản cài này.","No built-in skills were found in this install.")}):e.jsx("ul",{className:"flex flex-col divide-y divide-hairline/40 rounded-xl border border-hairline/40",children:s.map(a=>e.jsxs("li",{className:"px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-[13px] text-ink",children:a.id}),e.jsx("span",{className:"text-[12px] text-ink-tertiary",children:a.core?R("Kỹ năng gốc · mọi bot","Core skill · every bot"):R("Trong kho · thêm cho từng bot","In the store · add per bot")})]}),e.jsx("p",{className:"mt-0.5 text-[12px] leading-relaxed text-ink-secondary",children:a.description}),a.triggerTerms.length>0&&e.jsxs("p",{className:"mt-1 text-[12px] text-ink-tertiary",children:[R("Từ khóa","Keywords"),": ",a.triggerTerms.slice(0,6).join(", "),a.triggerTerms.length>6?"…":""]})]},a.id))})})})}function hx(){const[s,n]=l.useState(!1);return e.jsxs(Y,{title:R("Công cụ cho kỹ năng","Tools for skills"),subtitle:R("Chương trình mà các kỹ năng cần để chạy: Docker, Node.js, ffmpeg, Java, JADX, Ghidra, Agent-Reach… Thiếu gì thì bấm cài.","Programs the skills need to run: Docker, Node.js, ffmpeg, Java, JADX, Ghidra, Agent-Reach… Install whatever is missing."),children:[Ja()?e.jsxs("button",{type:"button",onClick:()=>n(!0),className:"inline-flex w-fit items-center gap-1.5 rounded-lg border border-hairline/60 bg-raised px-3 py-1.5 text-[13px] text-ink hover:bg-raised-hover",children:[e.jsx(uc,{size:14}),R("Xem và cài công cụ còn thiếu","See and install missing tools")]}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:R("Mở mục này trong ứng dụng Limix Bot trên máy tính.","Open this in the Limix Bot desktop app.")}),s&&e.jsx(Xa,{onClose:()=>n(!1)})]})}const it=12,fx=[["discover",()=>R("Khám phá","Discover")],["recommended",()=>R("Khuyên dùng","Recommended")],["installed",()=>R("Đã cài","Installed")],["updates",()=>R("Cập nhật","Updates")],["security",()=>R("Bảo mật","Security")],["settings",()=>R("Cài đặt","Settings")]],Ue=s=>{const n=new Date(s);return Number.isNaN(n.getTime())?s:n.toLocaleDateString(R("vi-VN","en-US"))},bx=s=>({excellent:R("Xuất sắc","Excellent"),recommended:R("Khuyên dùng","Recommended"),review:R("Cần xem xét","Needs review"),rejected:R("Từ chối","Rejected")})[s],yx=s=>({"instructions-only":R("Chỉ hướng dẫn","Instructions only"),"skill-with-tools":R("Kèm tool/script","With tools/scripts"),"mcp-bundle":R("Kèm MCP","With MCP")})[s],vx=s=>({clean:R("Sạch","Clean"),warning:R("Có cảnh báo","Warnings"),quarantined:R("Cách ly","Quarantined")})[s],Ee="inline-flex items-center gap-1.5 rounded-lg border border-hairline/60 bg-raised px-3 py-1.5 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50";async function Re(s,n){const a=await fetch(s,n===void 0?void 0:{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),i=await a.json().catch(()=>({}));if(!a.ok)throw new Error(i.error??R(`Lỗi ${a.status}`,`Error ${a.status}`));return i}function jx(){const[s,n]=l.useState(null),[a,i]=l.useState("recommended"),[r,c]=l.useState(null),[o,d]=l.useState(null),[m,u]=l.useState(""),[x,p]=l.useState(""),[g,f]=l.useState("catalog"),[y,b]=l.useState(""),[h,k]=l.useState(""),[S,E]=l.useState(""),[N,P]=l.useState(),[j,B]=l.useState(!1),[v,A]=l.useState(null),[T,$]=l.useState(null),[U,Z]=l.useState(it);l.useEffect(()=>Z(it),[a,m,x,g,y,h,S]);const H=l.useCallback(async()=>{try{n(await Re("/api/limix/hub"))}catch(w){d(w instanceof Error?w.message:String(w))}},[]);l.useEffect(()=>{H()},[H]);const ne=async(w,re)=>{c(w),d(null);try{await re()}catch(te){d(te instanceof Error?te.message:String(te))}finally{await H(),c(null)}},ae=s?.skills??[],oe=l.useMemo(()=>[...new Set(ae.map(w=>w.category))].sort(),[ae]),F=l.useMemo(()=>{const w=m.trim().toLowerCase(),re=h?new Date(h+"T00:00:00").getTime():-1/0,te=S?new Date(S+"T00:00:00"):null;te&&te.setDate(te.getDate()+1);const ee=ae.filter(K=>{if(y&&(K.stars==null||K.stars<Number(y)))return!1;if(h||S){const le=Date.parse(K.added_at??"");if(!Number.isFinite(le)||le<re||te&&le>=te.getTime())return!1}if(x&&K.category!==x||w&&!`${K.name} ${K.description} ${K.description_vi??""} ${K.tags.join(" ")}`.toLowerCase().includes(w))return!1;switch(a){case"discover":return!0;case"recommended":return!K.blocked&&!K.risky&&(K.grade==="excellent"||K.grade==="recommended");case"installed":return K.installed;case"updates":return K.updateAvailable;case"security":return K.security_status!=="clean"||!!K.risky;default:return!1}});return g==="stars"&&ee.sort((K,le)=>(le.stars??-1)-(K.stars??-1)),g==="newest"&&ee.sort((K,le)=>(Date.parse(le.added_at??"")||0)-(Date.parse(K.added_at??"")||0)),ee},[ae,a,m,x,g,y,h,S]),L=()=>ne("sync",()=>Re("/api/limix/hub/sync",{})),X={excellent:"bg-emerald-500/15 text-emerald-500",recommended:"bg-sky-500/15 text-sky-500",review:"bg-amber-500/15 text-amber-500",rejected:"bg-danger/15 text-danger"},se="rounded-md bg-ink/[0.06] px-1.5 py-0.5 text-[11px] text-ink-secondary",he=w=>ne(w.id,async()=>{const re=await Re("/api/limix/hub/install",{id:w.id,allowTools:!0}),te=[];w.permissions.mcp&&!re.bundle.mcp.length&&te.push(R("Nguồn khai báo MCP nhưng gói tải về thiếu tệp cấu hình máy chủ. Xem phần thiết lập MCP của kỹ năng.","The source declares MCP but the download contains no server configuration. Check the skill’s MCP setup instructions."));for(const K of re.bundle.mcp)try{await Re("/api/mcp/servers/import",{json:K})}catch(le){te.push(le instanceof Error?le.message:String(le))}const ee=Ja();if(ee?.scan&&ee.installRequirements){const K=await ee.scan();if(K.skillScan?.error)throw new Error(K.skillScan.error);const _=(K.skillScan?.requirements?.filter(I=>I.directory===re.bundle.directory)??[]).flatMap(I=>I.status==="missing"&&I.installable&&I.id?[I.id]:[]),ie=w.compatibility.runtimes.flatMap(I=>K.items.some(C=>C.id===I.installerId&&!C.installed&&C.installable)?[I.installerId]:[]);ie.length&&await ee.install(ie),K.supported&&_.length&&await ee.installRequirements(_,"limix:skill-bundle"),P(re.bundle.directory),B(!0)}else te.push(R("Đã tải tệp kỹ năng. Mở Limix Bot Desktop để cài các công cụ trên máy.","Skill files downloaded. Open Limix Bot Desktop to install host tools."));if(te.length)throw new Error(te.join(`
11
+ `))}),pe=w=>{window.confirm(R(`CẢNH BÁO: "${w.name}" bị cách ly vì ${w.risky??"có dấu hiệu nguy hiểm"}
12
+
13
+ Không khuyến khích cài. Kỹ năng này có thể chứa mã độc hoặc lệnh nguy hiểm. Chỉ cài nếu bạn hiểu rõ và tin tưởng nguồn ${w.source.repository??"này"}.
14
+
15
+ Vẫn cài đặt (kỹ năng sẽ ở trạng thái tắt)?`,`WARNING: "${w.name}" is quarantined because ${w.risky??"it looks dangerous"}
16
+
17
+ Installing is not recommended. This skill may contain malware or dangerous commands. Only install it if you understand the risk and trust ${w.source.repository??"the source"}.
18
+
19
+ Install anyway (the skill will stay switched off)?`))&&ne(w.id,()=>Re("/api/limix/hub/install",{id:w.id,allowRisky:!0}))},ce=w=>{!w.enabled&&w.risky&&!window.confirm(R(`"${w.name}" bị cách ly (${w.risky}). Vẫn bật cho bot dùng?`,`"${w.name}" is quarantined (${w.risky}). Switch it on for bots anyway?`))||ne(w.id,()=>Re("/api/limix/hub/enable",{id:w.id,enabled:!w.enabled}))},ue=w=>{const re=w.description_vi||w.description,te=T===w.id,ee=(w.permissions.runs_code||w.permissions.mcp)&&!w.blocked;return e.jsx("li",{className:"px-4 py-4",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"font-mono text-[14px] font-semibold text-ink",children:w.name}),e.jsxs("span",{className:`rounded-md px-1.5 py-0.5 text-[11px] font-medium ${X[w.grade]??"bg-ink/10 text-ink-secondary"}`,children:[w.quality_score,"/100 · ",bx(w.grade)??w.grade]}),typeof w.stars=="number"&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[12px] text-ink-secondary",children:[e.jsx(mc,{size:12}),w.stars.toLocaleString(R("vi-VN","en-US"))]})]}),e.jsx("p",{className:`mt-1 text-[12.5px] leading-relaxed text-ink-secondary ${te?"":"line-clamp-3"}`,children:re}),re.length>220&&e.jsx("button",{type:"button",className:"mt-0.5 text-[12px] text-ink underline-offset-2 hover:underline",onClick:()=>$(te?null:w.id),children:te?R("Thu gọn","Show less"):R("Xem thêm","Show more")}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:se,children:yx(w.kind)??w.kind}),e.jsxs("span",{className:`${se} ${w.security_status==="clean"?"":w.security_status==="quarantined"?"!bg-danger/15 !text-danger":"!bg-amber-500/15 !text-amber-500"}`,children:[R("Bảo mật","Security"),": ",vx(w.security_status)??w.security_status]}),e.jsx("span",{className:se,children:w.license??R("Chưa có giấy phép","No license")}),w.dependencies.length>0&&e.jsxs("span",{className:se,children:[R("Cần","Needs"),": ",w.dependencies.join(", ")]})]}),e.jsxs("p",{className:"mt-1.5 text-[11px] leading-relaxed text-ink-tertiary",children:[w.source.repository??R("Không rõ nguồn","Unknown source"),w.added_at&&R(` · Thêm vào kho ${Ue(w.added_at)}`,` · Added to catalog ${Ue(w.added_at)}`),w.created_at&&R(` · Tạo ${Ue(w.created_at)}`,` · Created ${Ue(w.created_at)}`),w.pushed_at&&R(` · Cập nhật ${Ue(w.pushed_at)}`,` · Updated ${Ue(w.pushed_at)}`),w.stats_checked&&R(` · số sao đo ngày ${Ue(w.stats_checked)}`,` · stars measured ${Ue(w.stats_checked)}`)]}),w.risky&&e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 rounded-lg bg-danger/10 p-2 text-[12px] leading-relaxed text-danger",children:[e.jsx(hn,{size:14,className:"mt-0.5 shrink-0"}),e.jsxs("span",{children:[w.risky," ",R("Không khuyến khích cài.","Installing is not recommended.")]})]}),w.blocked&&e.jsxs("p",{className:"mt-1 flex items-center gap-1 text-[12px] text-danger",children:[e.jsx(hn,{size:13}),w.blocked]}),ee&&e.jsxs("div",{className:"mt-2 rounded-lg border border-hairline/40 bg-raised/50 p-2.5 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx("button",{type:"button",className:"text-ink underline-offset-2 hover:underline",onClick:()=>A(v===w.id?null:w.id),children:v===w.id?R("Ẩn hướng dẫn cài đặt","Hide install guide"):R("Kỹ năng này có tool: xem hướng dẫn cài đặt","This skill has tools: see the install guide")}),v===w.id&&e.jsxs("ol",{className:"mt-2 list-decimal space-y-1.5 pl-4",children:[e.jsx("li",{children:R("Cài trọn bộ tải các tệp đã xác minh, nhập cấu hình MCP và cài công cụ theo kỹ năng. Kiểm tra các mục cần tài khoản hoặc thiết lập riêng trong cửa sổ công cụ.","Install bundle downloads verified files, imports MCP configurations and installs skill dependencies. Review any account or manual setup in the tools window.")}),e.jsx("li",{children:R(e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"Bật:"}),' sau khi cài, gạt công tắc "Đang tắt" sang bật, rồi mở cài đặt của bot → Kỹ năng để thêm.']}),e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"Switch on:"}),' after installing, flip the "Off" switch to on, then add it in the bot’s Settings → Skills.']}))})]})]}),a==="security"&&w.security_findings?.slice(0,5).map((K,le)=>e.jsxs("p",{className:"text-[11px] text-ink-tertiary",children:[K.severity," · ",K.rule," · ",K.file,K.line?`:${K.line}`:""]},le)),w.notes.map(K=>e.jsx("p",{className:"mt-0.5 text-[11px] text-ink-tertiary",children:K},K))]}),e.jsx("div",{className:"flex shrink-0 flex-row flex-wrap items-center gap-2 sm:w-[168px] sm:flex-col sm:items-stretch",children:r===w.id?e.jsx(J,{size:15,className:"animate-spin text-ink-secondary sm:self-end"}):w.installed?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-center justify-between gap-2 text-[12px] text-ink-secondary",children:[w.enabled?R("Đang bật","On"):R("Đang tắt","Off"),e.jsx(me,{checked:w.enabled,disabled:r!==null,onClick:()=>ce(w)})]}),!w.risky&&!w.blocked&&e.jsxs("button",{type:"button",className:Ee,disabled:r!==null,onClick:()=>{he(w)},children:[e.jsx(Ye,{size:14}),w.updateAvailable?R("Cập nhật trọn bộ","Update bundle"):R("Cài bổ sung trọn bộ","Complete bundle setup")]}),e.jsxs("button",{type:"button",className:`${Ee} justify-center`,disabled:r!==null,onClick:()=>{ne(w.id,()=>Re("/api/limix/hub/remove",{id:w.id}))},children:[e.jsx(Se,{size:14}),R("Gỡ","Remove")]})]}):e.jsx(e.Fragment,{children:w.risky?e.jsxs("button",{type:"button",className:`${Ee} justify-center !border-danger/40 !text-danger`,disabled:!!w.blocked||r!==null,onClick:()=>pe(w),children:[e.jsx(Ye,{size:14}),R("Cài đặt (không khuyến khích)","Install (not recommended)")]}):e.jsxs("button",{type:"button",className:`${Ee} justify-center`,disabled:!!w.blocked||r!==null,onClick:()=>{he(w)},children:[e.jsx(Ye,{size:14}),R("Cài trọn bộ","Install bundle")]})})})]})},w.id)};return e.jsxs(Y,{title:R("Kho kỹ năng Limix","Limix Skill Catalog"),subtitle:R("Các kỹ năng trong kho đã được quét bảo mật và chấm điểm. Sau khi cài, mở cài đặt của bot → Kỹ năng → Kho kỹ năng để thêm kỹ năng cho bot đó.","Skills that are security-scanned and scored. Once installed, a skill waits in the store and no bot uses it yet: open a bot → Skills → Skills Store to add it to one bot."),children:[e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:fx.map(([w,re])=>{const te=w==="installed"?ae.filter(ee=>ee.installed).length:w==="updates"?ae.filter(ee=>ee.updateAvailable).length:w==="discover"?ae.length:null;return e.jsxs("button",{type:"button",onClick:()=>i(w),className:`rounded-lg px-2.5 py-1 text-[13px] ${a===w?"bg-raised text-ink":"text-ink-secondary hover:bg-raised-hover"}`,children:[re(),te?e.jsx("span",{className:"ml-1 text-[11px] text-ink-tertiary",children:te}):null]},w)})}),o&&e.jsx("p",{className:"text-[12px] text-danger",children:o}),s?a==="settings"?e.jsxs("div",{className:"flex flex-col gap-3 text-[13px] text-ink",children:[e.jsxs("label",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{children:[R("Tự đồng bộ danh mục","Sync the catalog automatically"),e.jsx("span",{className:"block text-[12px] text-ink-secondary",children:R("Chỉ cập nhật danh sách, không cài gì.","Only refreshes the list, installs nothing.")})]}),e.jsx(me,{checked:s.settings.autoSync,onClick:()=>{ne("settings",()=>Re("/api/limix/hub/settings",{autoSync:!s.settings.autoSync}))}})]}),e.jsxs("label",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{children:[R("Tự cài kỹ năng mới","Install new skills automatically"),e.jsx("span",{className:"block text-[12px] text-ink-secondary",children:R("Mặc định tắt. Nếu bật: chỉ cài loại chỉ có hướng dẫn, đã duyệt, điểm từ 80; vẫn ở trạng thái tắt.","Off by default. When on: only instruction-only skills that are approved and score 80 or more are installed, and they stay switched off.")})]}),e.jsx(me,{checked:s.settings.autoInstall,onClick:()=>{ne("settings",()=>Re("/api/limix/hub/settings",{autoInstall:!s.settings.autoInstall}))}})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{value:m,onChange:w=>u(w.target.value),placeholder:R("Tìm kỹ năng…","Search skills…"),className:"min-w-[160px] flex-1 rounded-lg border border-hairline/60 bg-card px-3 py-1.5 text-[13px] text-ink"}),e.jsxs("select",{"aria-label":R("Chủ đề","Topic"),value:x,onChange:w=>p(w.target.value),className:"rounded-lg border border-hairline/60 bg-card px-2 py-1.5 text-[13px] text-ink",children:[e.jsx("option",{value:"",children:R("Mọi chủ đề","All topics")}),oe.map(w=>e.jsx("option",{value:w,children:w},w))]}),e.jsxs("select",{"aria-label":R("Sắp xếp","Sort by"),value:g,onChange:w=>f(w.target.value),className:Ee,children:[e.jsx("option",{value:"catalog",children:R("Thứ tự trong kho","Catalog order")}),e.jsx("option",{value:"stars",children:R("Nhiều sao nhất","Most stars")}),e.jsx("option",{value:"newest",children:R("Mới thêm nhất","Recently added")})]}),a==="discover"&&e.jsxs("button",{type:"button",className:`${Ee} shrink-0`,disabled:r!==null,onClick:()=>{L()},children:[r==="sync"?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(Ae,{size:14}),R("Đồng bộ ngay","Sync now")]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 text-[12px] text-ink-secondary",children:[e.jsxs("label",{className:"grid gap-1",children:[R("Số sao tối thiểu","Minimum stars"),e.jsx("input",{type:"number",min:"0",step:"1",placeholder:"0",value:y,onChange:w=>b(w.target.validity.valid?w.target.value:""),className:`${Ee} w-28`})]}),e.jsxs("label",{className:"grid gap-1",children:[R("Thêm vào kho từ ngày","Added from"),e.jsx("input",{type:"date",value:h,max:S||void 0,onChange:w=>k(w.target.value),className:Ee})]}),e.jsxs("label",{className:"grid gap-1",children:[R("Đến ngày","Added through"),e.jsx("input",{type:"date",value:S,min:h||void 0,onChange:w=>E(w.target.value),className:Ee})]}),(m||x||y||h||S)&&e.jsx("button",{type:"button",className:Ee,onClick:()=>{u(""),p(""),b(""),k(""),E("")},children:R("Xóa bộ lọc","Clear filters")})]}),a==="discover"&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[12px] text-ink-tertiary",role:"status",children:[R("Đồng bộ gần nhất","Last sync"),": ",s.settings.lastSync?new Date(s.settings.lastSync).toLocaleString(R("vi-VN","en-US")):R("chưa lần nào","never")]}),s.settings.lastError&&e.jsxs("p",{className:"text-[12px] text-danger",children:[R("Lỗi đồng bộ gần nhất","Last sync error"),": ",s.settings.lastError]})]}),F.length===0?e.jsx("p",{className:"text-[13px] text-ink-secondary",children:ae.length===0?R("Chưa có danh mục. Mở Khám phá và bấm Đồng bộ ngay.","No catalog yet. Open Discover and press Sync now."):R("Không có kỹ năng nào ở mục này.","No skills in this tab.")}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[12px] text-ink-tertiary",children:[F.length," ",R("kỹ năng","skills")]}),e.jsx("ul",{className:"flex flex-col divide-y divide-hairline/40 rounded-xl border border-hairline/40 bg-card",children:F.slice(0,U).map(ue)}),F.length>U&&e.jsx("button",{type:"button",className:`${Ee} w-fit self-center`,onClick:()=>Z(w=>w+it),children:R(`Xem thêm ${Math.min(it,F.length-U)} kỹ năng`,`Show ${Math.min(it,F.length-U)} more`)})]}),a==="installed"&&F.length>0&&e.jsxs("p",{className:"flex items-center gap-1 text-[12px] text-ink-tertiary",children:[e.jsx(be,{size:13}),R("Kỹ năng đã bật nằm trong thư viện bên dưới. Mở cài đặt của từng bot → Kỹ năng để thêm.","Enabled skills are in the library below. Add them from each bot’s Settings → Skills.")]})]}):e.jsx(J,{size:15,className:"animate-spin text-ink-secondary"})]}),j&&e.jsx(Xa,{directory:N,bundleIssue:N?o:null,onClose:()=>{B(!1),P(void 0)}})]})}function kx(s,n,a){const i=n.trim().toLowerCase();return s.filter(r=>a&&!r.tags.includes(a)?!1:i?[r.name,r.description,r.source].some(c=>c.toLowerCase().includes(i)):!0)}function rr({skill:s}){return e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-ink-secondary",children:[e.jsx("span",{className:"truncate",title:s.source,children:t("skills.source",{source:s.source})}),e.jsx("span",{children:s.version?t("skills.library.version",{version:s.version}):t("skills.library.noVersion")}),e.jsx("span",{children:t("skills.library.importedAt",{date:new Date(s.importedAt).toLocaleDateString(ws())})}),s.tags.map(n=>e.jsx("span",{className:"rounded bg-control px-1.5 py-0.5 font-mono",children:n},n))]})}function Nx(){const[s,n]=l.useState([]),[a,i]=l.useState(!0),[r,c]=l.useState(""),[o,d]=l.useState(""),[m,u]=l.useState(null),[x,p]=l.useState(null),[g,f]=l.useState(""),[y,b]=l.useState(""),[h,k]=l.useState(!1),[S,E]=l.useState(""),N=l.useRef(!1),P=l.useMemo(()=>[...new Set(s.flatMap(U=>U.tags))].sort((U,Z)=>U.localeCompare(Z)),[s]),j=kx(s,o,m),B=async U=>{try{const Z=await fetch("/api/skills-library"),H=await Z.json();if(!Z.ok)throw new Error(H.error??t("skills.library.loadError"));if(U?.())return;n(H.skills??[]),c("")}catch(Z){U?.()||c(Z instanceof Error?Z.message:t("skills.library.loadError"))}finally{U?.()||i(!1)}};l.useEffect(()=>{let U=!1;return i(!0),B(()=>U),()=>{U=!0}},[]);const v=async(U,Z=!1)=>{if(!N.current){if(!U.enabled&&!Z)return A(U,!0);N.current=!0,f(U.name),c("");try{const H=await fetch(`/api/skills-library/${encodeURIComponent(U.name)}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:!U.enabled})}),ne=await H.json();if(!H.ok)throw new Error(ne.error??t("skills.error.update"));Z&&p(null),await B()}catch(H){c(H instanceof Error?H.message:t("skills.error.update"))}finally{N.current=!1,f("")}}},A=async(U,Z=!1)=>{c("");try{const H=await fetch(`/api/skills-library/${encodeURIComponent(U.name)}`),ne=await H.json();if(!H.ok)throw new Error(ne.error??t("skills.error.load"));if(!ne.text)throw new Error(t("skills.error.contentsImport"));p({skill:U,text:ne.text,review:Z})}catch(H){c(H instanceof Error?H.message:t("skills.error.load"))}},T=async()=>{const U=y.trim();if(U){k(!0),c(""),E("");try{const Z=await fetch("/api/skills-library",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:U})}),H=await Z.json();if(!Z.ok)throw new Error(H.error??t("skills.error.import"));E(t("skills.library.imported",{name:H.skill?.name??""})),b(""),await B()}catch(Z){c(Z instanceof Error?Z.message:t("skills.error.import"))}finally{k(!1)}}},$="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink placeholder:text-ink-secondary focus:outline-none";return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs(xx,{catalog:e.jsx(jx,{}),bundled:e.jsx(gx,{}),tools:e.jsx(hx,{}),children:[e.jsx(Y,{title:t("skills.library.title"),subtitle:t("skills.library.subtitle"),children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mt,{size:15,className:"shrink-0 text-ink-secondary"}),e.jsx("input",{className:$,placeholder:t("skills.library.searchPlaceholder"),"aria-label":t("skills.library.searchPlaceholder"),value:o,onChange:U=>d(U.target.value)})]}),P.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>u(null),className:m===null?"rounded-full bg-control px-2.5 py-1 text-[12px] font-medium text-ink":"rounded-full px-2.5 py-1 text-[12px] text-ink-secondary hover:bg-control/50 hover:text-ink",children:t("skills.library.allTags")}),P.map(U=>e.jsx("button",{type:"button",onClick:()=>u(m===U?null:U),className:m===U?"rounded-full bg-control px-2.5 py-1 font-mono text-[12px] font-medium text-ink":"rounded-full px-2.5 py-1 font-mono text-[12px] text-ink-secondary hover:bg-control/50 hover:text-ink",children:U},U))]}),a?e.jsx("div",{className:"text-[12px] text-ink-secondary",children:t("skills.library.loading")}):j.length===0?e.jsx("div",{className:"rounded-lg bg-inset px-3 py-2 text-[12px] text-ink-secondary",children:s.length===0?t("skills.library.empty"):t("skills.library.noMatches")}):e.jsx("div",{className:"divide-y divide-hairline/40 overflow-hidden rounded-lg border border-hairline/40",children:j.map(U=>e.jsxs("div",{className:"px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{A(U)},className:"min-w-0 flex-1 text-left","aria-label":t("skills.library.view",{skill:U.name}),children:[e.jsx("div",{className:"truncate font-mono text-[13px] text-ink",children:U.name}),e.jsx("div",{className:"mt-0.5 line-clamp-2 text-[12px] text-ink-secondary",children:U.description})]}),e.jsx(me,{checked:U.enabled,"aria-label":U.enabled?t("skills.library.disable",{skill:U.name}):t("skills.library.enable",{skill:U.name}),disabled:!!(g||h),onClick:()=>{v(U)}})]}),e.jsx(rr,{skill:U}),U.warnings.length>0&&e.jsx("div",{className:"mt-1 text-[11px] text-warning",children:U.warnings.join(" · ")})]},U.name))}),r&&e.jsx("div",{role:"alert",className:"mt-2 text-[12px] text-danger",children:r})]})}),e.jsx(Y,{title:t("skills.library.importTitle"),subtitle:t("skills.library.importHint"),children:e.jsxs("form",{className:"flex flex-col gap-2",onSubmit:U=>{U.preventDefault(),T()},children:[e.jsx("textarea",{className:`${$} min-h-32 font-mono text-[12px]`,placeholder:t("skills.library.importPlaceholder"),"aria-label":t("skills.library.importTitle"),value:y,onChange:U=>b(U.target.value)}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[S?e.jsx("div",{className:"text-[12px] text-ink-secondary",children:S}):e.jsx("span",{}),e.jsx("button",{type:"submit",disabled:h||!!g||!y.trim(),className:"shrink-0 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",children:h?t("skills.library.importing"):t("skills.library.importButton")})]})]})})]}),x&&e.jsx(Pa,{modal:!0,children:e.jsx(wx,{viewing:x,error:r,working:!!g,onClose:()=>{g||p(null)},onEnable:()=>{v(x.skill,!0)}})})]})}function wx({viewing:s,error:n,working:a,onClose:i,onEnable:r}){const c=l.useRef(null);return Cl(c,i),e.jsx("div",{ref:c,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"skills-library-view-title",className:"fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-6",children:e.jsxs("div",{className:"flex max-h-[min(760px,90vh)] w-full max-w-2xl flex-col rounded-2xl bg-card p-5 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{id:"skills-library-view-title",className:"text-[16px] font-semibold text-ink",children:s.review?t("skills.reviewTitle",{name:s.skill.name}):s.skill.name}),e.jsx("button",{type:"button",disabled:a,onClick:i,className:"rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink",children:t("skills.library.close")})]}),s.review&&e.jsx(rr,{skill:s.skill}),s.skill.warnings.length>0&&e.jsx("div",{className:"mt-2 text-[12px] text-warning",children:s.skill.warnings.join(" · ")}),e.jsx("pre",{tabIndex:0,"aria-label":`${t("skills.library.view",{skill:s.skill.name})}`,className:"mt-3 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-inset p-3 font-mono text-[12px] leading-relaxed text-ink",children:s.text}),n&&e.jsx("div",{role:"alert",className:"mt-2 text-[12px] text-danger",children:n}),s.review&&e.jsx("button",{type:"button",disabled:a,onClick:r,className:"mt-4 self-end rounded-lg bg-accent px-4 py-2 text-[13px] font-semibold text-white disabled:opacity-40",children:t("skills.enableReviewed")})]})})}function Sx(s){const n=s?.edition?.license;return!n||typeof n.expiresAt!="string"||!Number.isFinite(n.expiresInDays)?null:n.graceEndsAt?{tone:"danger",text:t("settings.license.grace",{date:n.expiresAt,graceEnd:n.graceEndsAt})}:{tone:"warning",text:t("settings.license.expiring",{date:n.expiresAt,days:String(Math.max(0,n.expiresInDays))})}}function ca({config:s}){const n=Sx(s);return n?e.jsxs("div",{role:"status",className:z("flex items-start gap-2 rounded-xl border px-3 py-2.5 text-[13px] leading-relaxed",n.tone==="danger"?"border-danger/40 bg-danger/10 text-danger":"border-warning/40 bg-warning/10 text-warning"),children:[e.jsx(Oe,{size:14,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:n.text})]}):null}function lr(s){return s?.edition?.features?.includes("admin")===!0&&s?.fleet?.available===!0}const Cx=()=>M("/api/fleet");function Ex({fleet:s,onAct:n,busy:a}){return s.workspaces.length===0?e.jsx("div",{className:"text-[13px] text-ink-secondary",children:t("workspaces.empty",{domain:s.domain})}):e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-x-5 border-b border-hairline/40 pb-2 text-[12px] font-medium uppercase tracking-wide text-ink-secondary",children:[e.jsx("span",{children:t("workspaces.colWorkspace")}),e.jsx("span",{className:"text-right",children:t("workspaces.colState")}),e.jsx("span",{className:"text-right",children:t("workspaces.colMonth")}),e.jsx("span",{})]}),s.workspaces.map(i=>{const r=i.status==="suspended",c=i.status==="running"||r,o=i.status==="provisioning"?t("workspaces.provisioning"):i.status==="error"?t("workspaces.error"):i.status==="retained"?t("workspaces.retained"):r?t("workspaces.suspended"):i.live==="active"?t("workspaces.running"):i.live;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] items-center gap-x-5 border-b border-hairline/20 py-2 text-[13px]",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-ink",children:i.slug}),e.jsx("a",{href:`https://${i.host}`,target:"_blank",rel:"noreferrer",className:"block truncate text-[12px] text-accent hover:underline",children:i.host}),!c&&e.jsx("span",{className:"block text-[12px] text-ink-secondary",children:t("workspaces.recoveryHint")})]}),e.jsx("span",{className:z("text-right",r||i.status==="provisioning"?"text-warning":i.status==="running"&&i.live==="active"?"text-success":"text-danger"),children:o}),e.jsxs("span",{className:"text-right tabular-nums text-ink",title:i.usage.turns===null?void 0:t("workspaces.turns",{turns:String(i.usage.turns)}),children:[ot(i.usage.costUsd)?ct(i.usage.costUsd):"—",ot(i.usage.billableUsd)&&e.jsxs("span",{className:"text-ink-secondary",children:[" · ",ct(i.usage.billableUsd)]})]}),e.jsx("span",{className:"flex items-center justify-end gap-2 text-[12px]",children:c&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:a!==null,onClick:()=>n(i.slug,"users"),className:"text-ink-secondary hover:text-ink disabled:opacity-50",children:t("workspaces.users")}),e.jsx("button",{type:"button",disabled:a!==null,onClick:()=>n(i.slug,r?"resume":"suspend"),className:"text-ink-secondary hover:text-ink disabled:opacity-50",children:r?t("workspaces.resume"):t("workspaces.suspend")}),e.jsx("button",{type:"button",disabled:a!==null,onClick:()=>n(i.slug,"delete"),className:"text-danger hover:underline disabled:opacity-50",children:t("workspaces.delete")})]})})]},i.slug)})]})}function Ax({domain:s,onCreated:n,disabled:a}){const[i,r]=l.useState(""),[c,o]=l.useState(""),[d,m]=l.useState(""),[u,x]=l.useState(""),[p,g]=l.useState(""),[f,y]=l.useState(!1),[b,h]=l.useState(null),k=async()=>{if(!f){y(!0),h(null);try{const E={slug:i.trim().toLowerCase(),admins:[c.trim()],members:d.split(/[,\s]+/).map(P=>P.trim()).filter(Boolean),...u.trim()?{cap:Number(u)}:{},...p.trim()?{anthropicKey:p.trim()}:{}},N=await M("/api/fleet/workspaces",{method:"POST",body:JSON.stringify(E)});r(""),o(""),m(""),x(""),g(""),n(N.log??[],{slug:E.slug,admin:E.admins[0]})}catch(E){h(E instanceof Error?E.message:String(E))}finally{y(!1)}}},S="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none disabled:opacity-50";return e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:E=>{E.preventDefault(),k()},children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("workspaces.name"),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{value:i,onChange:E=>r(E.target.value),placeholder:"acme",pattern:"[a-z][a-z0-9-]{1,30}",required:!0,disabled:a||f,"aria-label":t("workspaces.name"),className:S}),e.jsxs("span",{className:"whitespace-nowrap text-[12px] text-ink-secondary",children:[".",s]})]})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("workspaces.adminEmail"),e.jsx("input",{value:c,onChange:E=>o(E.target.value),type:"email",required:!0,disabled:a||f,"aria-label":t("workspaces.adminEmail"),className:S})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("workspaces.members"),e.jsx("input",{value:d,onChange:E=>m(E.target.value),placeholder:"bob@acme.test, @acme.test",disabled:a||f,"aria-label":t("workspaces.members"),className:S})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("workspaces.cap"),e.jsx("input",{value:u,onChange:E=>x(E.target.value),inputMode:"decimal",placeholder:"50",disabled:a||f,"aria-label":t("workspaces.cap"),className:S})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary sm:col-span-2",children:[t("workspaces.anthropicKey"),e.jsx("input",{value:p,onChange:E=>g(E.target.value),type:"password",autoComplete:"off",placeholder:"sk-ant-…",disabled:a||f,"aria-label":t("workspaces.anthropicKey"),className:S})]})]}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("workspaces.createHint")}),b&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:b}),e.jsx("div",{className:"flex justify-end",children:e.jsxs("button",{type:"submit",disabled:a||f,className:"ui-button ui-button-primary",children:[f?e.jsx(J,{size:13,className:"animate-spin"}):e.jsx(we,{size:13}),f?t("workspaces.creating"):t("workspaces.create")]})})]})}function Ix({slug:s,onDone:n}){const[a,i]=l.useState(""),[r,c]=l.useState(!1),[o,d]=l.useState(null),[m,u]=l.useState(null),x=async p=>{if(!o){d(p),u(null);try{const g=await M(`/api/fleet/workspaces/${encodeURIComponent(s)}/users`,{method:"POST",body:JSON.stringify({action:p,email:a.trim(),chatOnly:r})});i(""),n(g.log??[])}catch(g){u(g instanceof Error?g.message:String(g))}finally{d(null)}}};return e.jsxs("div",{className:"mt-2 rounded-lg border border-hairline/40 p-3",children:[e.jsx("div",{className:"mb-2 text-[13px] font-medium text-ink",children:t("workspaces.usersTitle",{slug:s})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{value:a,onChange:p=>i(p.target.value),type:"text",placeholder:"person@example.com or @example.com","aria-label":t("workspaces.email"),disabled:o!==null,className:"min-w-[16rem] flex-1 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none disabled:opacity-50"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[12px] text-ink-secondary",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:p=>c(p.target.checked),disabled:o!==null}),t("workspaces.chatOnly")]}),e.jsx("button",{type:"button",disabled:o!==null||!a.trim(),onClick:()=>{x("add")},className:"rounded-lg bg-raised px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-50",children:o==="add"?t("workspaces.working"):t("workspaces.addUser")}),e.jsx("button",{type:"button",disabled:o!==null||!a.trim(),onClick:()=>{x("remove")},className:"rounded-lg px-3 py-1.5 text-[12px] text-danger hover:underline disabled:opacity-50",children:o==="remove"?t("workspaces.working"):t("workspaces.removeUser")})]}),m&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:m})]})}function Px({load:s=Cx}){const{state:n}=G(),[a,i]=l.useState(null),[r,c]=l.useState(null),[o,d]=l.useState(!1),[m,u]=l.useState(null),[x,p]=l.useState([]),[g,f]=l.useState(null),[y,b]=l.useState(null),[h,k]=l.useState(!1),[S,E]=l.useState(null),N=l.useCallback(async()=>{d(!0),c(null);try{i(await s())}catch(v){c(v instanceof Error?v.message:String(v))}finally{d(!1)}},[s]);l.useEffect(()=>{N()},[N]);const P=async(v,A)=>{if(A==="users"){f(T=>T===v?null:v);return}if(A==="delete"){b({slug:v,keepData:!1});return}u(v),c(null);try{const T=await M(`/api/fleet/workspaces/${encodeURIComponent(v)}/${A}`,{method:"POST"});p(T.log??[]),await N()}catch(T){c(T instanceof Error?T.message:String(T))}finally{u(null)}},j=async()=>{if(!y)return;const{slug:v,keepData:A}=y;b(null),u(v),c(null);try{const T=await M(`/api/fleet/workspaces/${encodeURIComponent(v)}`,{method:"DELETE",body:JSON.stringify({keepData:A})});p(T.log??[]),await N()}catch(T){c(T instanceof Error?T.message:String(T))}finally{u(null)}},B=async()=>{u("*"),c(null);try{const v=await M("/api/fleet/upgrade",{method:"POST"});p(v.log??[t("workspaces.upgraded")]),await N()}catch(v){c(v instanceof Error?v.message:String(v))}finally{u(null)}};return lr(n.config)?e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsxs(Y,{title:t("workspaces.title"),subtitle:t("workspaces.subtitle"),children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>{N()},disabled:o||m!==null,className:"flex items-center gap-1 text-[12px] text-ink-secondary hover:text-ink disabled:opacity-50",children:[e.jsx(Ae,{size:12,className:z(o&&"animate-spin")}),t("workspaces.refresh")]}),e.jsxs("button",{type:"button",onClick:()=>k(v=>!v),disabled:m!==null,className:"ml-auto flex items-center gap-1.5 rounded-lg border border-hairline/40 px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:opacity-50",children:[e.jsx(we,{size:13}),t("workspaces.new")]}),e.jsx("button",{type:"button",onClick:()=>{B()},disabled:m!==null||!a?.workspaces.length,className:"rounded-lg border border-hairline/40 px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink disabled:opacity-50",children:m==="*"?t("workspaces.working"):t("workspaces.upgradeAll")})]}),h&&a&&e.jsx("div",{className:"mb-4 rounded-xl border border-hairline/40 p-3",children:e.jsx(Ax,{domain:a.domain,disabled:m!==null,onCreated:(v,A)=>{k(!1),p(v),E(`https://${A.slug}.${a.domain}/pair?email=${encodeURIComponent(A.admin)}`),N()}})}),S&&e.jsx("div",{className:"mb-4",children:e.jsx(Di,{link:S})}),r&&e.jsx("p",{role:"alert",className:"mb-2 text-[12px] text-danger",children:r}),a?e.jsx(Ex,{fleet:a,onAct:(v,A)=>{P(v,A)},busy:m}):o?e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:14,className:"animate-spin"}),t("common.checking")]}):null,g&&e.jsx(Ix,{slug:g,onDone:v=>{p(v),N()}}),x.length>0&&e.jsx("pre",{className:"mt-3 max-h-40 overflow-auto rounded-lg bg-inset p-2 text-[12px] text-ink-secondary",children:x.join(`
20
+ `)})]}),e.jsx(Qe,{open:y!==null,title:t("workspaces.deleteTitle",{slug:y?.slug??""}),body:t(y?.keepData?"workspaces.deleteKeepHint":"workspaces.deleteHint"),confirmLabel:t("workspaces.delete"),onCancel:()=>b(null),onConfirm:()=>{j()}}),y&&e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-ink-secondary",children:[e.jsx("input",{type:"checkbox",checked:y.keepData,onChange:v=>b({...y,keepData:v.target.checked})}),t("workspaces.keepData")]})]}):null}const or=s=>({method:"PUT",body:JSON.stringify(s)}),Pt=s=>s instanceof Error?s.message:String(s);function Tx(){return l.useSyncExternalStore(ii,()=>yd()?.id??null,()=>null)}function Rx(s,n){const a=URL.createObjectURL(new Blob([JSON.stringify(n,null,2)],{type:"application/json"}));Object.assign(document.createElement("a"),{href:a,download:s}).click(),setTimeout(()=>URL.revokeObjectURL(a),1e3)}function Lx({id:s,act:n,onClose:a,onDelete:i}){const[r,c]=l.useState(null),[o,d]=l.useState(null),[m,u]=l.useState(!1);if(l.useEffect(()=>{M(`/api/themes/${s}`).then(g=>c(g.theme),g=>d(Pt(g)))},[s]),!r)return e.jsx(ds,{children:o??t("settings.customThemes.loading")});const x=r.css?vd(r.css):null,p=async()=>{u(!0);try{await M(`/api/themes/${s}`,or({theme:{...r,name:r.name.trim(),css:r.css||void 0}})),d(t("settings.customThemes.saved")),await Ts()}catch(g){d(Pt(g))}finally{u(!1)}};return e.jsxs("div",{"data-settings-block":"theme-editor",className:"flex flex-col gap-3 px-4 py-3",children:[e.jsx(fn,{label:t("settings.customThemes.name"),children:e.jsx("input",{className:bn,value:r.name,maxLength:60,onChange:g=>c({...r,name:g.target.value})})}),e.jsx("div",{className:"flex flex-wrap gap-4",children:["canvas","accent"].map(g=>e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-ink",children:[e.jsx("input",{type:"color",className:"size-7 cursor-pointer rounded-md bg-transparent",value:r[g]??(g==="canvas"?"#121212":"#1084fe"),onChange:f=>c({...r,[g]:f.target.value})}),t(g==="canvas"?"settings.customThemes.canvas":"settings.customThemes.accent"),r[g]&&e.jsx("button",{type:"button",className:"text-[12px] text-accent-text hover:underline",onClick:()=>c({...r,[g]:void 0}),children:t("settings.customThemes.clear")})]},g))}),e.jsx(fn,{label:t("settings.customThemes.css"),hint:x??t("settings.customThemes.cssHint"),children:e.jsx("textarea",{className:`${bn} h-64 resize-y py-2 font-mono text-[12px]`,spellCheck:!1,maxLength:jd.cssChars,"aria-label":t("settings.customThemes.css"),value:r.css??"",onChange:g=>c({...r,css:g.target.value})})}),e.jsxs(xc,{status:o,children:[e.jsxs("div",{className:"mr-auto flex flex-wrap gap-1.5",children:[e.jsx("button",{type:"button",className:"ui-button ui-button-sm",onClick:()=>{n(()=>M(`/api/themes/${s}/duplicate`,{method:"POST",body:JSON.stringify({name:t("settings.customThemes.copyName",{name:r.name}).slice(0,60)})}))},children:t("settings.customThemes.duplicate")}),e.jsx("button",{type:"button",className:"ui-button ui-button-sm",onClick:()=>{n(async()=>Rx(`${s}.limixbot-theme.json`,await M(`/api/themes/${s}/export`)))},children:t("settings.customThemes.export")}),e.jsx("button",{type:"button",className:"ui-button ui-button-sm","data-danger":"",onClick:i,children:t("common.delete")})]}),e.jsx("button",{type:"button",className:"ui-button",onClick:a,children:t("common.cancel")}),e.jsx("button",{type:"button",className:"ui-button ui-button-primary",disabled:m||!!x||!r.name.trim(),onClick:()=>{p()},children:t("common.save")})]})]})}const Bx=6;function Ox(s){const n=s.name??"";switch(s.kind){case"made":return t("settings.customThemes.historyMade",{name:n});case"edited":return t("settings.customThemes.historyEdited",{name:n});case"deleted":return t("settings.customThemes.historyDeleted",{name:n});case"wore":return t("settings.customThemes.historyWore",{name:n});case"skin":return t("settings.customThemes.historySkin",{name:Lt.find(a=>a.id===n)?.name??n});case"default":return t("settings.customThemes.historyDefault");case"undid":return t("settings.customThemes.historyUndid")}}function Mx({items:s,act:n}){return s.length<2?null:e.jsx(ye,{label:t("settings.customThemes.history"),block:"theme-history",description:t("settings.customThemes.historyHint"),children:e.jsx(ve,{children:s.slice(0,Bx).map(a=>e.jsx(de,{title:Ox(a),subtitle:ai(Date.parse(a.at)),children:a.index===1?e.jsx("span",{className:"text-[12px] text-ink-tertiary",children:t("settings.customThemes.historyNow")}):e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{n(async()=>{await M("/api/themes/history",{method:"POST",body:JSON.stringify({index:a.index})}),await Ts()})},children:t("settings.customThemes.restore")})},a.index))})})}function cr(){const[s,n]=l.useState(null),[a,i]=l.useState(null),[r,c]=l.useState(null),o=l.useRef(null),d=Tx(),[m,u]=l.useState([]),x=l.useCallback(()=>Promise.all([M("/api/themes").then(n,h=>c(Pt(h))),M("/api/themes/history").then(h=>u(h.items),()=>u([]))]),[]);l.useEffect(()=>(x(),ii(()=>{x()})),[x]);const p=async h=>{c(null);try{await h()}catch(k){c(Pt(k))}await x()},g=()=>p(async()=>{const h=`theme-${Date.now().toString(36)}`;await M(`/api/themes/${h}`,or({theme:{name:t("settings.customThemes.newName")}})),i(h)}),f=h=>h&&p(async()=>{let k;try{k=JSON.parse(await h.text())}catch{throw new Error(t("settings.customThemes.importFailed"))}await M("/api/themes/import",{method:"POST",body:JSON.stringify(k)})}),y=(h,k)=>p(async()=>{const S=await M(`/api/themes/${h}/export`);await M(`/api/themes/${h}`,{method:"DELETE"}),i(null),await Ts(),c(e.jsxs(e.Fragment,{children:[t("settings.customThemes.deleted",{name:k})," ",e.jsx("button",{type:"button",className:"text-accent-text hover:underline",onClick:()=>{p(()=>M("/api/themes/import",{method:"POST",body:JSON.stringify(S)}))},children:t("common.undo")})]}))}),b=pc()?"⌘⌥⇧R":"Ctrl+Alt+Shift+R";return e.jsxs(e.Fragment,{children:[e.jsx(ye,{label:t("settings.customThemes.title"),block:"custom-themes",description:t("settings.customThemes.description"),actions:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"ui-button",onClick:()=>o.current?.click(),children:t("settings.customThemes.import")}),e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{g()},children:t("settings.customThemes.new")}),e.jsx("input",{ref:o,type:"file",accept:"application/json,.json",hidden:!0,onChange:h=>{f(h.target.files?.[0]),h.target.value=""}})]}),footnote:r,children:e.jsxs(ve,{children:[fd()&&e.jsx(ds,{children:t("settings.customThemes.safe")}),s&&!s.themes.length&&e.jsx(ds,{children:t("settings.customThemes.empty")}),s?.themes.map(h=>a===h.id?e.jsx(Lx,{id:h.id,act:p,onClose:()=>{i(null),x()},onDelete:()=>{y(h.id,h.name)}},h.id):e.jsx(de,{title:h.name,subtitle:d===h.id?t("settings.customThemes.inUse"):h.assets.length?t("settings.customThemes.files",{count:h.assets.length}):void 0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",className:"ui-button",onClick:()=>i(h.id),children:t("settings.customThemes.edit")}),d===h.id?e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{p(()=>En(null))},children:t("settings.customThemes.takeOff")}):e.jsx("button",{type:"button",className:"ui-button ui-button-primary",onClick:()=>{p(()=>En(h.id))},children:t("settings.customThemes.use")})]})},h.id)),e.jsx(de,{title:t("settings.customThemes.reset"),subtitle:t("settings.customThemes.resetHint",{keys:b}),children:e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{bd(),x()},children:t("settings.customThemes.reset")})})]})}),e.jsx(Mx,{items:m,act:p})]})}const da=[{choice:"system",label:"settings.theme.system"},{choice:Zs.light,label:"settings.theme.light"},{choice:Zs.dark,label:"settings.theme.dark"}];function Hs(){return l.useSyncExternalStore(Jr,en,en)}function dr({simple:s=!1}){const n=Hs(),a=da.some(i=>i.choice===n)?void 0:Lt.find(i=>i.id===n)?.name;return e.jsx(de,{title:t(s?"settings.theme.lightOrDark":"settings.theme.title"),subtitle:a?t("settings.theme.look",{name:a}):s?void 0:t("settings.theme.subtitle"),children:e.jsx("div",{role:"radiogroup","aria-label":t(s?"settings.theme.lightOrDark":"settings.theme.title"),className:s?"inline-flex h-7 rounded-full bg-ink/[0.06] p-0.5":"inline-flex rounded-full bg-inset p-0.5",children:da.map(i=>e.jsx("button",{type:"button",role:"radio","aria-checked":n===i.choice,onClick:()=>Vr(i.choice),className:s?z("h-6 rounded-full px-2.5 text-[13px] transition-colors",n===i.choice?"bg-ink/[0.12] text-ink":"text-ink-secondary hover:text-ink"):z("rounded-full px-3 py-1 text-[13px] font-medium transition-colors",n===i.choice?"bg-raised text-ink shadow-sm":"text-ink-secondary hover:text-ink"),children:t(s&&i.choice==="system"?"settings.simple.theme.system":i.label)},i.choice))})})}function zx({skin:s}){return e.jsxs("div",{"data-skin":s,"data-skin-preview":"","aria-hidden":"true",className:"flex h-[78px] w-full overflow-hidden rounded-lg bg-app ring-1 ring-hairline/60",children:[e.jsxs("div",{className:"flex w-[11px] shrink-0 flex-col items-center gap-[3px] bg-panel pt-[5px]",children:[e.jsx("span",{className:"size-[5px] rounded-full bg-accent"}),e.jsx("span",{className:"size-[5px] rounded-full bg-ink-secondary/40"}),e.jsx("span",{className:"size-[5px] rounded-full bg-ink-secondary/40"})]}),e.jsxs("div",{className:"flex w-[30px] shrink-0 flex-col gap-[3px] border-r border-hairline bg-panel p-[4px]",children:[e.jsxs("span",{className:"flex h-[9px] w-full items-center gap-[2px] rounded-sm bg-raised px-[2px]",children:[e.jsx("span",{className:"size-[4px] shrink-0 rounded-full bg-accent"}),e.jsx("span",{className:"h-[2px] flex-1 rounded-full bg-ink/50"})]}),e.jsx("span",{className:"h-[3px] w-[80%] rounded-full bg-ink-secondary/30"}),e.jsx("span",{className:"h-[3px] w-[62%] rounded-full bg-ink-secondary/30"}),e.jsx("span",{className:"h-[3px] w-[74%] rounded-full bg-ink-secondary/30"})]}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-[4px] p-[6px]",children:[e.jsx("span",{className:"h-[13px] w-[62%] self-end rounded-md bg-bubble-user"}),e.jsxs("div",{className:"flex w-[88%] flex-col gap-[3px] rounded-md bg-card p-[4px]",children:[e.jsx("span",{className:"h-[2px] w-full rounded-full bg-ink/45"}),e.jsx("span",{className:"h-[2px] w-[85%] rounded-full bg-ink/45"}),e.jsx("span",{className:"h-[2px] w-[60%] rounded-full bg-ink-secondary/40"})]}),e.jsxs("div",{className:"mt-auto flex items-center gap-[4px]",children:[e.jsx("span",{className:"h-[11px] flex-1 rounded-full bg-inset ring-1 ring-hairline"}),e.jsx("span",{className:"flex size-[11px] items-center justify-center rounded-full bg-accent",children:e.jsx("span",{className:"h-[1.5px] w-[5px] rounded-full",style:{background:"var(--color-accent-ink)"}})})]})]})]})}const Ux={halloween:["orange","purple","teal","red"],diwali:["red","orange","pink","coral"]};function Fx({festival:s}){const n=Al(),a=t("settings.skin.dressUp.title");return e.jsxs("div",{"data-dress-up":!0,className:"mt-4 flex items-center gap-4 rounded-xl border border-accent-border/40 bg-accent/[0.06] p-3",children:[e.jsx("div",{className:"flex shrink-0 -space-x-1.5","aria-hidden":"true",children:Ux[s].map(i=>e.jsx(Il,{color:i,bodyId:Pl[s].costumes[i],size:30,animated:!1,trackPointer:!1},i))}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[14px] font-medium text-ink",children:a}),e.jsx("div",{className:"mt-1 text-[12px] leading-relaxed text-ink-secondary",children:t("settings.skin.dressUp.subtitle")})]}),e.jsx(me,{checked:n,"aria-label":a,onClick:()=>Tl(!n)})]})}function ur(){const s=Ca(Hs());return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:Lt.map(n=>{const a=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>{Yr(n.id),kd()},"aria-pressed":a,className:z("cursor-pointer flex flex-col gap-2 rounded-xl border p-2 text-left transition-colors",a?"border-accent-border bg-control":"border-hairline/60 hover:border-hairline hover:bg-control/50"),children:[e.jsx(zx,{skin:n.id}),e.jsxs("div",{className:"flex items-start gap-1.5 px-0.5 pb-0.5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] font-medium text-ink",children:n.name}),e.jsx("div",{className:"mt-0.5 text-[11px] leading-snug text-ink-secondary",children:Xr(`skins.tagline.${n.id}`,n.tagline)})]}),a&&e.jsx(be,{size:13,className:"mt-0.5 shrink-0 text-accent-text"})]})]},n.id)})}),El(s)&&e.jsx(Fx,{festival:s})]})}function Dx(){const[s,n]=l.useState(Qr);return e.jsx(de,{title:t("settings.font.title"),subtitle:t("settings.font.subtitle"),children:e.jsx(ge,{size:"sm",className:"w-full max-w-[240px]",value:s,"aria-label":t("settings.font.aria"),onChange:a=>{const i=a.target.value;el(i),n(i)},children:Zr.map(a=>e.jsx("option",{value:a,children:t(`settings.font.${a}`)},a))})})}function _x(){const[s,n]=l.useState(tl);return e.jsx(de,{title:t("settings.chatWidth.title"),subtitle:t("settings.chatWidth.subtitle"),children:e.jsx(ge,{size:"sm",className:"w-full max-w-[240px]",value:s,"aria-label":t("settings.chatWidth.aria"),onChange:a=>{const i=tn.find(r=>r===a.target.value);i&&(sl(i),n(i))},children:tn.map(a=>e.jsx("option",{value:a,children:t(`settings.chatWidth.${a}`)},a))})})}function $x(){const s=gc();return e.jsx(de,{title:t("sidebar.toolsLayout.title"),subtitle:t("sidebar.toolsLayout.subtitle"),children:e.jsx(ge,{size:"sm",className:"w-full max-w-[240px]",value:s,"aria-label":t("sidebar.toolsLayout.chooseAria"),onChange:n=>fc(bc(n.target.value)),children:hc.map(n=>e.jsx("option",{value:n,children:t(`sidebar.toolsLayout.${n}`)},n))})})}function mr(){const{state:s,dispatch:n}=G(),a=s.config?.rooms.turnTimeoutMinutes??5,[i,r]=l.useState(String(a)),[c,o]=l.useState(!1),[d,m]=l.useState(""),[u,x]=l.useState(!1),p=l.useRef(!1);l.useEffect(()=>{c||r(String(a))},[a,c]);const g=async()=>{if(!c||p.current)return;const f=jc(i);if(!f.ok){m(t("settings.roomTurns.range"));return}p.current=!0,x(!0);try{const y=await M("/api/config",{method:"PUT",body:JSON.stringify({rooms:{turnTimeoutMinutes:f.minutes}})});n({type:"configStatus",config:y}),r(String(y.rooms.turnTimeoutMinutes)),o(!1),m("")}catch(y){m(y instanceof Error?y.message:t("settings.roomTurns.error"))}finally{p.current=!1,x(!1)}};return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{htmlFor:"room-turn-timeout",className:"text-[13px] font-medium text-ink",children:t("settings.roomTurns.label")}),e.jsxs("div",{className:`flex max-w-[220px] items-center rounded-lg border bg-inset ${d?"border-danger/60":"border-hairline/40 focus-within:border-focus"}`,children:[e.jsx("input",{id:"room-turn-timeout",type:"number",min:vc,max:yc,step:1,inputMode:"numeric",value:i,disabled:u,"aria-invalid":!!d,"aria-describedby":d?"room-turn-timeout-error room-turn-timeout-help":"room-turn-timeout-help",onChange:f=>{r(f.target.value),o(!0),m("")},onBlur:()=>{g()},onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()},className:"min-w-0 flex-1 bg-transparent px-3 py-2 text-[14px] tabular-nums text-ink focus:outline-none"}),e.jsx("span",{className:"pr-3 text-[13px] text-ink-secondary",children:t("settings.roomTurns.minutes")})]}),e.jsx("p",{id:"room-turn-timeout-help",className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.roomTurns.help")}),d?e.jsx("p",{id:"room-turn-timeout-error",role:"alert",className:"text-[12px] text-danger",children:d}):null]})}const Kx=10,pr=1,xr=60,ua="Enter a whole number from 1 to 60.";function Hx(s){const n=s.trim();if(!/^\d+$/.test(n))return{ok:!1,error:ua};const a=Number(n);return a<pr||a>xr?{ok:!1,error:ua}:{ok:!0,minutes:a}}function ma(s){return s?.mcp?.callTimeoutMinutes??Kx}function gr(){const{state:s,dispatch:n}=G(),a=ma(s.config),[i,r]=l.useState(String(a)),[c,o]=l.useState(!1),[d,m]=l.useState(""),[u,x]=l.useState(!1),p=l.useRef(!1);l.useEffect(()=>{c||r(String(a))},[a,c]);const g=async()=>{if(!c||p.current)return;const f=Hx(i);if(!f.ok){m(t("settings.mcpCalls.range"));return}p.current=!0,x(!0);try{const y=await M("/api/config",{method:"PUT",body:JSON.stringify({mcp:{callTimeoutMinutes:f.minutes}})});n({type:"configStatus",config:y}),r(String(ma(y))),o(!1),m("")}catch(y){m(y instanceof Error?y.message:t("settings.mcpCalls.error"))}finally{p.current=!1,x(!1)}};return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{htmlFor:"mcp-call-timeout",className:"text-[13px] font-medium text-ink",children:t("settings.mcpCalls.label")}),e.jsxs("div",{className:`flex max-w-[220px] items-center rounded-lg border bg-inset ${d?"border-danger/60":"border-hairline/40 focus-within:border-focus"}`,children:[e.jsx("input",{id:"mcp-call-timeout",type:"number",min:pr,max:xr,step:1,inputMode:"numeric",value:i,disabled:u,"aria-invalid":!!d,"aria-describedby":d?"mcp-call-timeout-error mcp-call-timeout-help":"mcp-call-timeout-help",onChange:f=>{r(f.target.value),o(!0),m("")},onBlur:()=>{g()},onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()},className:"min-w-0 flex-1 bg-transparent px-3 py-2 text-[14px] tabular-nums text-ink focus:outline-none"}),e.jsx("span",{className:"pr-3 text-[13px] text-ink-secondary",children:t("settings.mcpCalls.minutes")})]}),e.jsx("p",{id:"mcp-call-timeout-help",className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.mcpCalls.help")}),d?e.jsx("p",{id:"mcp-call-timeout-error",role:"alert",className:"text-[12px] text-danger",children:d}):null]})}function hr(s,n){let a={value:s,status:"idle"},i=!1,r,c;const o=new Set,d=(u,x)=>{a={value:u,status:x};for(const p of o)p()},m=()=>(clearTimeout(c),r||(i?(d(a.value,"saving"),r=(async()=>{try{for(;i;){const u=a.value;await n(u),i=a.value!==u}d(a.value,"saved")}catch{d(a.value,"error")}})().finally(()=>{r=void 0}),r):Promise.resolve()));return{getSnapshot:()=>a,subscribe(u){return o.add(u),()=>{o.delete(u)}},confirm(u){!i&&!r&&u!==a.value&&d(u,"idle")},edit(u){i=!0,d(u,"idle"),clearTimeout(c),c=setTimeout(()=>{m()},600)},flush:m}}const pa=new WeakMap;function Wx(){const{state:s,dispatch:n}=G(),a=s.config?.profile?.aboutMe??"",i=!!s.config?.team;let r=pa.get(n);if(!r){const u={current:i};r={team:u,controller:hr(a,async x=>{const p=u.current?await As({aboutMe:x}):(await M("/api/config",{method:"PUT",body:JSON.stringify({profile:{aboutMe:x}}),timeoutMs:1e4})).profile;n({type:"profileSaved",profile:{aboutMe:p?.aboutMe??x}})})},pa.set(n,r)}r.team.current=i;const c=r.controller,{value:o,status:d}=l.useSyncExternalStore(c.subscribe,c.getSnapshot,c.getSnapshot),{flush:m}=c;return l.useEffect(()=>{c.confirm(a)},[c,a]),l.useEffect(()=>()=>{m()},[m]),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{htmlFor:"profile-about-me",className:"text-[14px] text-ink",children:t("settings.profile.aboutMe")}),e.jsxs("details",{className:"group relative",children:[e.jsx("summary",{title:t("settings.profile.aboutMeHelp"),"aria-label":t("settings.profile.aboutMeHelp"),className:"flex size-6 cursor-pointer list-none items-center justify-center rounded-md text-ink-secondary hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/70 [&::-webkit-details-marker]:hidden",children:e.jsx(kc,{size:14,"aria-hidden":"true"})}),e.jsx("p",{className:"absolute left-0 z-30 mt-1 w-56 rounded-xl border border-hairline bg-panel p-3 text-[12px] text-ink-secondary shadow-xl",children:t("settings.profile.aboutMeHelp")})]})]}),e.jsx("textarea",{id:"profile-about-me",value:o,rows:5,maxLength:i?4e3:24e3,onChange:u=>c.edit(u.target.value),onBlur:()=>{m()},className:"min-h-[120px] w-full resize-y rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink focus:outline-none"}),e.jsx(Gx,{onChanged:u=>{c.confirm(u),n({type:"profileSaved",profile:{aboutMe:u}})}}),e.jsxs("div",{className:"min-h-4 text-[12px]",role:"status",children:[d==="saving"&&e.jsx("span",{className:"text-ink-secondary",children:t("settings.profile.saving")}),d==="saved"&&e.jsx("span",{className:"text-success",children:t("settings.profile.saved")}),d==="error"&&e.jsxs("span",{className:"text-danger",children:[t("settings.profile.saveError")," "," ",e.jsx("button",{type:"button",onClick:()=>{m()},className:"underline",children:t("settings.profile.retry")})]})]})]})}function Gx({onChanged:s}){const[n,a]=l.useState([]),[i,r]=l.useState(null),[c,o]=l.useState(!1);l.useEffect(()=>{let m=!1;return M("/api/profile/learned").then(u=>{m||a(u.learned)}).catch(()=>{}),()=>{m=!0}},[]);const d=async m=>{r(m),o(!1);try{const u=await M(`/api/profile/learned/${encodeURIComponent(m)}/remove`,{method:"POST"});a(u.learned),s(u.aboutMe)}catch{o(!0)}finally{r(null)}};return n.length?e.jsxs("div",{className:"mt-1 rounded-lg border border-hairline/40 bg-inset p-3",children:[e.jsx("div",{className:"text-[13px] font-medium text-ink",children:t("settings.profile.learned.title")}),e.jsx("p",{className:"mt-0.5 text-[12px] text-ink-secondary",children:t("settings.profile.learned.hint")}),e.jsx("ul",{className:"mt-2 flex flex-col gap-2",children:n.map(m=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 text-[13px] text-ink",children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[m.text," ",e.jsx("span",{className:"text-[12px] text-ink-secondary",children:t("settings.profile.learned.from",{name:m.botName})})]}),e.jsx("button",{type:"button",disabled:i===m.id,onClick:()=>{d(m.id)},className:"rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50",children:t("settings.profile.learned.remove")})]},m.id))}),c&&e.jsx("div",{className:"mt-2 text-[12px] text-danger",children:t("settings.profile.learned.error")})]}):null}const xa=new WeakMap;function qx(){const{state:s,dispatch:n}=G(),a=s.config?.everyBotRules;let i=xa.get(n);i||(i=hr(a??"",async u=>{const x=await M("/api/config",{method:"PUT",body:JSON.stringify({everyBotRules:u}),timeoutMs:1e4});n({type:"configStatus",config:x})}),xa.set(n,i));const{value:r,status:c}=l.useSyncExternalStore(i.subscribe,i.getSnapshot,i.getSnapshot),{confirm:o,edit:d,flush:m}=i;return l.useEffect(()=>{o(a??"")},[o,a]),l.useEffect(()=>()=>{m()},[m]),a===void 0?null:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{htmlFor:"profile-every-bot-rules",className:"text-[14px] text-ink",children:t("settings.profile.everyBotRules")}),e.jsx("textarea",{id:"profile-every-bot-rules",value:r,rows:4,maxLength:24e3,placeholder:t("settings.profile.everyBotRulesPlaceholder"),onChange:u=>d(u.target.value),onBlur:()=>{m()},className:"min-h-[96px] w-full resize-y rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink placeholder:text-ink-secondary focus:outline-none"}),e.jsxs("div",{className:"min-h-4 text-[12px]",role:"status",children:[c==="saving"&&e.jsx("span",{className:"text-ink-secondary",children:t("settings.profile.saving")}),c==="saved"&&e.jsx("span",{className:"text-success",children:t("settings.profile.saved")}),c==="error"&&e.jsxs("span",{className:"text-danger",children:[t("settings.profile.saveError")," "," ",e.jsx("button",{type:"button",onClick:()=>{m()},className:"underline",children:t("settings.profile.retry")})]})]})]})}const ga=64,ha=8192,kt=512;function Vx(s){return Sc(s)?s.size>Cc?"settings.profile.avatar.tooLarge":null:"settings.profile.avatar.invalidType"}function Jx(s,n){return s<ga||n<ga?"settings.profile.avatar.tooSmall":s>ha||n>ha?"settings.profile.avatar.tooLargeDimensions":null}async function fr(s,n){const a=URL.createObjectURL(s);try{const i=await new Promise((r,c)=>{const o=new Image;o.onload=()=>r(o),o.onerror=()=>c(new Error("invalid-image")),o.src=a});if(i.naturalWidth<=0||i.naturalHeight<=0)throw new Error("invalid-image");return await n(i)}finally{URL.revokeObjectURL(a)}}function Xx(s,n){return fr(s,async a=>{const i=Math.min(a.naturalWidth,a.naturalHeight)/Math.max(1,n),r=document.createElement("canvas");r.width=kt,r.height=kt;const c=r.getContext("2d");if(!c)throw new Error("canvas-unavailable");c.drawImage(a,(a.naturalWidth-i)/2,(a.naturalHeight-i)/2,i,i,0,0,kt,kt);const o=await new Promise((d,m)=>r.toBlob(u=>u?d(u):m(new Error("image-encode-failed")),"image/webp",.9));return new File([o],"profile-photo.webp",{type:"image/webp"})})}function Yx(){const{state:s,dispatch:n}=G(),a=s.config?.profile?.avatarUrl??"",[i,r]=l.useState(!1),[c,o]=l.useState(null),[d,m]=l.useState(null),u=l.useRef(null),x=h=>{const k=u.current;k&&k.previewUrl!==h?.previewUrl&&URL.revokeObjectURL(k.previewUrl),u.current=h,m(h)};l.useEffect(()=>()=>{u.current&&URL.revokeObjectURL(u.current.previewUrl)},[]);const p=!!s.config?.team,g=async h=>{const k=p?await As({avatarUrl:h}):(await M("/api/config",{method:"PUT",body:JSON.stringify({profile:{avatarUrl:h}})})).profile;n({type:"profileSaved",profile:{avatarUrl:k?.avatarUrl}})},f=h=>{if(!h)return;o(null);const k=Vx(h);if(k)return o(t(k));fr(h,S=>({width:S.naturalWidth,height:S.naturalHeight})).then(({width:S,height:E})=>{const N=Jx(S,E);if(N)return o(t(N));x({file:h,previewUrl:URL.createObjectURL(h),width:S,height:E,zoom:1})},()=>o(t("settings.profile.avatar.invalidType")))},y=h=>{r(!0),o(null),Xx(h.file,h.zoom).then(k=>wc(k)).then(k=>{const S=k?Rl(k.path):null;if(!S)throw new Error("avatar");return g(S)}).then(()=>x(null),()=>o(t("settings.profile.avatar.saveError"))).finally(()=>r(!1))},b=()=>{o(null),g("").catch(()=>o(t("settings.profile.avatar.saveError")))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[d?e.jsx("div",{className:"flex w-full flex-col gap-2 rounded-lg border border-hairline/40 bg-inset p-2",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"size-16 shrink-0 overflow-hidden rounded-full bg-raised",children:e.jsx("img",{src:d.previewUrl,alt:"",className:"size-full object-cover",style:{transform:`scale(${d.zoom})`}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12px] font-medium text-ink",children:t("settings.profile.avatar.cropTitle")}),e.jsxs("div",{className:"text-[11px] text-ink-secondary",children:[d.width," × ",d.height,"px"]}),e.jsxs("label",{className:"mt-1 block text-[11px] text-ink-secondary",children:[t("settings.profile.avatar.zoom"),e.jsx("input",{"aria-label":t("settings.profile.avatar.zoom"),type:"range",min:"1",max:"2.5",step:"0.05",value:d.zoom,onChange:h=>x({...d,zoom:Number(h.target.value)}),className:"ml-2 w-28 align-middle accent-accent"})]})]}),e.jsx("button",{type:"button",className:"rounded-md px-2 py-1 text-[12px] text-ink-secondary hover:bg-control",onClick:()=>x(null),children:t("settings.profile.avatar.cancel")}),e.jsx("button",{type:"button",className:"rounded-md bg-control px-2 py-1 text-[12px] text-ink hover:bg-raised-hover",disabled:i,onClick:()=>y(d),children:t("settings.profile.avatar.save")})]})}):a?e.jsx("img",{...ls("person","picture"),src:a,alt:"",className:"size-12 rounded-full object-cover"}):e.jsx("div",{...ls("person","initials"),className:"size-12 rounded-full bg-raised"}),e.jsxs("label",{className:"cursor-pointer rounded-lg bg-control px-3 py-2 text-[12px] text-ink hover:bg-raised-hover",children:[i?t("settings.profile.avatar.uploading"):t("settings.profile.avatar.choose"),e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"sr-only",disabled:i,onChange:h=>{const k=h.target.files?.[0];h.currentTarget.value="",f(k)}})]}),a&&!d&&e.jsx("button",{type:"button",className:"text-[12px] text-ink-secondary underline",onClick:b,children:t("settings.profile.avatar.remove")})]}),c&&e.jsx("div",{role:"alert",className:"text-[12px] text-danger",children:c})]})}function br(){const{state:s,dispatch:n}=G(),[a,i]=l.useState(s.config?.profile?.name??""),[r,c]=l.useState(s.config?.profile?.email??"");l.useEffect(()=>{i(s.config?.profile?.name??""),c(s.config?.profile?.email??"")},[s.config?.profile?.name,s.config?.profile?.email]);const o=!!s.config?.team,d=()=>{if(o){As({name:a.trim()}).then(u=>n({type:"profileSaved",profile:{name:u.name,email:u.email}})).catch(()=>{});return}fetch("/api/config",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({profile:{name:a.trim(),email:r.trim().toLowerCase()}})}).then(u=>{if(!u.ok)throw new Error("Profile save failed");return u.json()}).then(u=>{u.profile&&n({type:"profileSaved",profile:{name:u.profile.name,email:u.profile.email}})}).catch(()=>{})},m="w-full rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[14px] text-ink placeholder:text-ink-secondary focus:outline-none";return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Yx,{}),e.jsx("input",{"aria-label":t("settings.profile.name"),value:a,onChange:u=>i(u.target.value),onBlur:d,placeholder:t("settings.profile.name"),className:m}),e.jsx("input",{type:"email","aria-label":t("phone.signIn.email"),value:r,onChange:u=>c(u.target.value),onBlur:o?void 0:d,readOnly:o,placeholder:t("common.emailPlaceholder"),className:m}),e.jsx(Wx,{}),e.jsx(qx,{})]})}function Qx({profile:s}){const[n,a]=l.useState(null),i=Nc(s),r=s?.avatarUrl&&n!==s.avatarUrl?s.avatarUrl:null;return e.jsx("span",{...ls("person",r?"picture":"initials"),className:"flex size-11 shrink-0 items-center justify-center overflow-hidden rounded-full bg-ink/[0.06] text-[15px] font-medium text-ink-secondary",children:r?e.jsx("img",{src:r,alt:"",onError:()=>a(r),className:"size-full object-cover"}):i!=="?"?i:e.jsx(Ya,{size:20,"aria-hidden":"true"})})}function Zx(){const{state:s}=G(),[n,a]=l.useState(!1),i=s.config?.profile,r=i?.name?.trim()??"",c=i?.email?.trim()??"",o=l.useId(),d=l.useRef(null);return l.useEffect(()=>{n&&d.current?.querySelector("input:not([type=file])")?.focus()},[n]),e.jsxs("div",{"data-profile-summary":"",className:"px-4 py-[13px]",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(Qx,{profile:i}),e.jsx("div",{className:"min-w-0 flex-1",children:r||c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"truncate text-[14px] leading-5 text-ink",children:r||c}),r&&c&&e.jsx("div",{className:"truncate text-[13px] leading-[18px] text-ink-secondary",children:c})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"truncate text-[14px] leading-5 text-ink",children:t("settings.simple.account.yourName")}),e.jsx("div",{className:"truncate text-[13px] leading-[18px] text-ink-secondary",children:t("settings.simple.account.noNameHint")})]})}),e.jsx("button",{type:"button","aria-expanded":n,"aria-controls":o,className:"ui-button shrink-0",onClick:()=>a(!n),children:n?t("common.done"):t(r||c?"settings.simple.account.edit":"settings.simple.account.add")})]}),e.jsx("div",{id:o,ref:d,hidden:!n,className:"mt-4",children:n&&e.jsx(br,{})})]})}function yr({row:s=!1}){const n=!!G().state.config?.team,[a,i]=l.useState(null),[r,c]=l.useState(!1),o=l.useId();l.useEffect(()=>{if(!n)return;let m=!0;return M("/api/me/away-emails",{timeoutMs:1e4}).then(u=>{m&&i(u.on)},()=>{}),()=>{m=!1}},[n]);const d=m=>{const u=a;i(m),c(!1),M("/api/me/away-emails",{method:"PUT",body:JSON.stringify({on:m}),timeoutMs:1e4}).then(x=>i(x.on),()=>{i(u),c(!0)})};return!n||a===null?null:e.jsxs("div",{className:s?"flex flex-col gap-1 px-4 py-[13px]":"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{id:o,className:"text-[14px] text-ink",children:t("settings.profile.awayEmails")}),e.jsx(me,{"aria-labelledby":o,checked:a,onClick:()=>d(!a)})]}),e.jsx("div",{className:"text-[12px] text-ink-secondary",children:t("settings.profile.awayEmailsHelp")}),r&&e.jsx("div",{role:"alert",className:"text-[12px] text-danger",children:t("settings.profile.awayEmailsError")})]})}function vr(){const{state:s,dispatch:n}=G(),a=s.config?.threads?.maxConcurrentPerBot??3,i=s.config?.cloudStarter===!0,[r,c]=l.useState(null),[o,d]=l.useState(""),m=l.useRef(!1),u=async x=>{if(!(m.current||x===a)){m.current=!0,c(x),d("");try{const p=await M("/api/config",{method:"PATCH",body:JSON.stringify({threads:{maxConcurrentPerBot:x}})});n({type:"configStatus",config:p})}catch(p){d(p instanceof Error?p.message:t("settings.threads.error"))}finally{m.current=!1,c(null)}}};return e.jsxs(Y,{title:t("settings.threads.title"),subtitle:t("settings.threads.subtitle"),children:[e.jsx("label",{htmlFor:"thread-concurrency",className:"block text-[13px] font-medium text-ink",children:t("settings.threads.label")}),e.jsx(ge,{className:"mt-2",id:"thread-concurrency",value:r??a,disabled:r!==null||i,"aria-describedby":"thread-concurrency-help",onChange:x=>{u(Number(x.target.value))},children:Array.from({length:16},(x,p)=>p+1).map(x=>e.jsx("option",{value:x,children:x},x))}),e.jsx("p",{id:"thread-concurrency-help",className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:i?t("settings.threads.starter"):t("settings.threads.helpHanded")}),r!==null&&e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t("settings.threads.saving")}),o&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:o})]})}function jr(){const{state:s,dispatch:n}=G(),[a,i]=l.useState(null),[r,c]=l.useState(!1),[o,d]=l.useState(""),m=l.useRef(!1),u=a??s.config?.automaticRecovery??{enabled:!1},x=s.instances.filter(h=>h.snapshot.state==="available"&&!h.policy),p=x.find(h=>h.instanceId===u.backup?.instanceId),g=p?.models.options.filter(h=>!h.orgBlocked&&!h.needsCliUpdate&&(p.snapshot.authenticated!==!1||h.custom))??[],f=g.some(h=>h.id===u.backup?.model),y=h=>{i(h),d("")},b=async()=>{if(!(!a||m.current||u.enabled&&!f)){m.current=!0,c(!0),d("");try{const h=await M("/api/config",{method:"PUT",body:JSON.stringify({automaticRecovery:{enabled:a.enabled,...a.backup?.model?{backup:a.backup}:{}}})});n({type:"configStatus",config:h}),i(null)}catch(h){d(h instanceof Error?h.message:t("settings.recovery.error"))}finally{m.current=!1,c(!1)}}};return e.jsxs(Y,{title:t("settings.recovery.title"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("label",{htmlFor:"automatic-recovery-enabled",className:"text-[13px] font-medium text-ink",children:t("settings.recovery.enable")}),e.jsx(me,{id:"automatic-recovery-enabled",checked:u.enabled,disabled:r||!s.config,"aria-describedby":"automatic-recovery-help automatic-recovery-scope automatic-recovery-own",onClick:()=>y({...u,enabled:!u.enabled})})]}),e.jsx("p",{id:"automatic-recovery-help",className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("settings.recovery.help")}),e.jsx("p",{id:"automatic-recovery-scope",className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("settings.recovery.scopeHanded")}),e.jsx("p",{id:"automatic-recovery-own",className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("settings.recovery.ownBackups")}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:"automatic-recovery-engine",className:"block text-[13px] font-medium text-ink",children:t("settings.recovery.engine")}),e.jsxs(ge,{className:"mt-2 w-full",id:"automatic-recovery-engine",value:u.backup?.instanceId??"",disabled:r||!u.enabled,onChange:h=>y({enabled:u.enabled,...h.target.value?{backup:{instanceId:h.target.value,model:""}}:{}}),children:[e.jsx("option",{value:"",children:t("settings.recovery.chooseEngine")}),u.backup&&!p&&e.jsx("option",{value:u.backup.instanceId,disabled:!0,children:t("settings.recovery.unavailable",{name:u.backup.instanceId})}),x.map(h=>e.jsx("option",{value:h.instanceId,disabled:!h.models.options.some(k=>h.snapshot.authenticated!==!1||k.custom),children:h.displayName},h.instanceId))]})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("label",{htmlFor:"automatic-recovery-model",className:"block text-[13px] font-medium text-ink",children:t("settings.recovery.model")}),e.jsxs(ge,{className:"mt-2 w-full",id:"automatic-recovery-model",value:u.backup?.model??"",disabled:r||!u.enabled||!p,onChange:h=>y({enabled:u.enabled,backup:{instanceId:p.instanceId,model:h.target.value}}),children:[e.jsx("option",{value:"",children:t("settings.recovery.chooseModel")}),u.backup?.model&&!f&&e.jsx("option",{value:u.backup.model,disabled:!0,children:t("settings.recovery.unavailable",{name:u.backup.model})}),g.map(h=>e.jsx("option",{value:h.id,children:h.label},h.id))]})]})]}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("settings.recovery.charges")}),u.enabled&&!f&&e.jsx("p",{className:"mt-2 text-[12px] text-ink-secondary",children:t("settings.recovery.required")}),e.jsx("button",{type:"button",disabled:!a||r||u.enabled&&!f,onClick:()=>{b()},className:"mt-3 cursor-pointer rounded-lg bg-accent px-3 py-2 text-[13px] font-medium text-white disabled:opacity-50",children:r?t("settings.threads.saving"):t("common.save")}),r&&e.jsx("span",{role:"status",className:"sr-only",children:t("settings.threads.saving")}),o&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:o})]})}const kr=1,Nr=3650,eg=30,Tt=1024*1024,vs=256*1024,wr=4*1024*1024*1024,tg=50;function fa(s){const n=Number(s);return Number.isInteger(n)&&n>=kr&&n<=Nr?n:null}function ba(s){const n=Number(s);if(!Number.isFinite(n))return null;const a=Math.round(n*Tt);return a>=vs&&a<=wr&&a%vs===0?a:null}function ya(s){const n=s/Tt;return String(Number.isInteger(n)?n:Number(n.toFixed(2)))}function Sr(){const{state:s,dispatch:n}=G(),a=s.config?.threads?.eventLogRetentionDays??null,i=s.config?.threads?.eventLogMaxBytes??null,[r,c]=l.useState(null),[o,d]=l.useState(null),[m,u]=l.useState(null),[x,p]=l.useState(""),[g,f]=l.useState(null),y=l.useRef(!1),b=r??String(a===null?eg:a),h=o??(i===null?String(tg):ya(i));l.useEffect(()=>{r!==null&&a!==null&&String(a)===r&&c(null)},[a,r]),l.useEffect(()=>{o!==null&&i!==null&&ya(i)===o&&d(null)},[i,o]);const k=async(j,B)=>{if(!y.current){y.current=!0,u(B),p(""),f(null);try{const v=await M("/api/config",{method:"PATCH",body:JSON.stringify({threads:j})});n({type:"configStatus",config:v})}catch(v){p(v instanceof Error?v.message:t("settings.threadCleanup.error"))}finally{y.current=!1,u(null)}}},S=j=>{if(!j){c(null),p(""),f(null),k({eventLogRetentionDays:null},"retention");return}const B=fa(b);if(B===null){p(t("settings.threadCleanup.invalidRetention")),f("retention");return}k({eventLogRetentionDays:B},"retention")},E=j=>{if(!j){d(null),p(""),f(null),k({eventLogMaxBytes:null},"cap");return}const B=ba(h);if(B===null){p(t("settings.threadCleanup.invalidCap")),f("cap");return}k({eventLogMaxBytes:B},"cap")},N=()=>{if(a===null)return;const j=fa(b);if(j===null){p(t("settings.threadCleanup.invalidRetention")),f("retention");return}if(j===a){c(null),p("");return}k({eventLogRetentionDays:j},"retention")},P=()=>{if(i===null)return;const j=ba(h);if(j===null){p(t("settings.threadCleanup.invalidCap")),f("cap");return}if(j===i){d(null),p("");return}k({eventLogMaxBytes:j},"cap")};return e.jsxs(Y,{title:t("settings.threadCleanup.title"),subtitle:t("settings.threadCleanup.subtitle"),children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{id:"thread-log-retention-enabled",type:"checkbox",checked:a!==null,disabled:m!==null,onChange:j=>S(j.target.checked),className:"size-4 accent-accent"}),e.jsx("label",{htmlFor:"thread-log-retention-enabled",className:"text-[13px] font-medium text-ink",children:t("settings.threadCleanup.retention.enable")}),e.jsxs("div",{className:`flex max-w-[160px] items-center rounded-lg border bg-inset ${g==="retention"?"border-danger/60":"border-hairline/40 focus-within:border-focus"}`,children:[e.jsx("input",{id:"thread-log-retention-days",type:"number",min:kr,max:Nr,step:1,inputMode:"numeric",value:b,disabled:a===null||m!==null,"aria-invalid":g==="retention","aria-describedby":"thread-log-retention-help",onChange:j=>{c(j.target.value),p(""),f(null)},onBlur:N,onKeyDown:j=>{j.key==="Enter"&&j.currentTarget.blur()},className:"min-w-0 flex-1 bg-transparent px-3 py-2 text-[14px] tabular-nums text-ink focus:outline-none"}),e.jsx("span",{className:"pr-3 text-[13px] text-ink-secondary",children:t("settings.threadCleanup.retention.unit")})]})]}),e.jsx("p",{id:"thread-log-retention-help",className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.threadCleanup.retention.help")})]}),e.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{id:"thread-log-cap-enabled",type:"checkbox",checked:i!==null,disabled:m!==null,onChange:j=>E(j.target.checked),className:"size-4 accent-accent"}),e.jsx("label",{htmlFor:"thread-log-cap-enabled",className:"text-[13px] font-medium text-ink",children:t("settings.threadCleanup.cap.enable")}),e.jsxs("div",{className:`flex max-w-[160px] items-center rounded-lg border bg-inset ${g==="cap"?"border-danger/60":"border-hairline/40 focus-within:border-focus"}`,children:[e.jsx("input",{id:"thread-log-cap-mib",type:"number",min:vs/Tt,max:wr/Tt,step:.25,inputMode:"decimal",value:h,disabled:i===null||m!==null,"aria-invalid":g==="cap","aria-describedby":"thread-log-cap-help",onChange:j=>{d(j.target.value),p(""),f(null)},onBlur:P,onKeyDown:j=>{j.key==="Enter"&&j.currentTarget.blur()},className:"min-w-0 flex-1 bg-transparent px-3 py-2 text-[14px] tabular-nums text-ink focus:outline-none"}),e.jsx("span",{className:"pr-3 text-[13px] text-ink-secondary",children:t("settings.threadCleanup.cap.unit")})]})]}),e.jsx("p",{id:"thread-log-cap-help",className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.threadCleanup.cap.help")})]}),m!==null&&e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t("settings.threadCleanup.saving")}),x&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:x})]})}const va="min-w-0 rounded-lg border bg-inset px-3 py-2 text-[14px] text-ink focus:outline-none";function sg(){const s=nl(),[n,a]=l.useState(""),[i,r]=l.useState(""),[c,o]=l.useState(""),d=s.length>=sn,m=()=>{const u=al({name:n,url:i},window.location.origin);if(!u.ok){o(u.error);return}nn([...s,{id:il(s),name:u.name,url:u.url}]),a(""),r(""),o("")};return e.jsx(Y,{title:t("webPanels.settings.title"),subtitle:t("webPanels.settings.subtitle"),children:e.jsxs("div",{className:"flex flex-col gap-3",children:[s.length>0&&e.jsx("ul",{className:"flex flex-col divide-y divide-hairline/40 rounded-lg border border-hairline/40",children:s.map(u=>e.jsxs("li",{className:"flex items-center gap-3 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-[14px] font-medium text-ink",children:u.name}),e.jsx("p",{className:"truncate text-[12px] text-ink-secondary",title:u.url,children:u.url??t("webPanels.settings.chatPage")})]}),e.jsx("button",{type:"button",className:"ui-button text-danger",onClick:()=>nn(s.filter(x=>x.id!==u.id)),children:t("webPanels.settings.remove")})]},u.id))}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsx("input",{"aria-label":t("webPanels.settings.name"),placeholder:t("webPanels.settings.name"),value:n,maxLength:an,disabled:d,"aria-invalid":c==="name",onChange:u=>{a(u.target.value),o("")},className:`${va} sm:w-40 ${c==="name"?"border-danger/60":"border-hairline/40 focus:border-focus"}`}),e.jsx("input",{"aria-label":t("webPanels.settings.url"),placeholder:"https://",type:"url",inputMode:"url",value:i,disabled:d,"aria-invalid":c==="url"||c==="self",onChange:u=>{r(u.target.value),o("")},onKeyDown:u=>{u.key==="Enter"&&m()},className:`${va} flex-1 ${c==="url"||c==="self"?"border-danger/60":"border-hairline/40 focus:border-focus"}`}),e.jsx("button",{type:"button",className:"ui-button",disabled:d,onClick:m,children:t("webPanels.settings.add")})]}),c&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:t(c==="name"?"webPanels.settings.nameInvalid":c==="self"?"webPanels.settings.urlSelf":"webPanels.settings.urlInvalid",{max:an})}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:d?t("webPanels.settings.full",{max:sn}):t("webPanels.settings.help")})]})})}const rs="mt-1 w-full rounded-lg border border-hairline/50 bg-inset px-3 py-2 text-[14px] text-ink disabled:opacity-50",Xe=s=>{const n=s>=1073741824?3:s>=1048576?2:1;return`${new Intl.NumberFormat(Me(),{maximumFractionDigits:2}).format(s/1024**n)} ${["","KiB","MiB","GiB"][n]}`},ja=s=>{const n=new Date(s.completedAt??s.createdAt??NaN);return Number.isFinite(n.getTime())?new Intl.DateTimeFormat(Me(),{dateStyle:"medium",timeStyle:"short"}).format(n):t("companyBackup.unknownDate")};function ng(){const s=window.ogb?.remoteClient?.active?void 0:window.ogb?.organization,n=s?window.ogb?.companyBackups:void 0,[a,i]=l.useState(null),r=l.useRef(0),c=l.useRef(0);return l.useEffect(()=>{const o=++r.current,d=c.current;i(null);const m=x=>{r.current===o&&(c.current++,i(x))},u=s?.onState(m);return s?.state().then(x=>{c.current===d&&m(x)}).catch(()=>{}),()=>{r.current++,u?.()}},[s]),!n||!a?null:a.status!=="connected"||a.cloudBackups!==!0||!a.organization?.id||!a.organization.name?.trim()||!a.email?e.jsx(ag,{bridge:n}):e.jsx(ig,{connection:a,bridge:n},`${a.organization.id}:${a.email}:${a.deviceId??""}`)}function ag({bridge:s}){const[n,a]=l.useState(null),[i,r]=l.useState(!1),[c,o]=l.useState(""),d=l.useRef(0);if(l.useEffect(()=>{const u=++d.current,x=s.onState(p=>{u===d.current&&a(p.schedule??null)});return s.state().then(p=>{u===d.current&&a(p.schedule??null)}).catch(()=>{}),()=>{d.current++,x()}},[s]),!s.configureSchedule||!n?.enabled)return null;const m=async()=>{if(i||!s.configureSchedule)return;const u=d.current;r(!0),o("");try{const x=await s.configureSchedule({enabled:!1});u===d.current&&a(x.schedule??null)}catch{u===d.current&&o(t("companyBackup.scheduleFailed"))}finally{u===d.current&&r(!1)}};return e.jsx(Y,{title:t("companyBackup.title"),subtitle:t("companyBackup.savedSchedule"),children:e.jsxs("div",{className:"rounded-lg border border-hairline/40 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"text-[14px] font-medium",children:t("companyBackup.daily")}),e.jsx(me,{"aria-label":t("companyBackup.daily"),checked:!0,disabled:i,onClick:()=>{m()}})]}),e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t(`companyBackup.scheduleStatus.${n.status}`)}),c&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:c})]})})}function ig({connection:s,bridge:n}){const[a,i]=l.useState(null),[r,c]=l.useState(null),[o,d]=l.useState(!1),[m,u]=l.useState(null),[x,p]=l.useState(""),[g,f]=l.useState(null),[y,b]=l.useState(""),[h,k]=l.useState(""),[S,E]=l.useState(null),[N,P]=l.useState(!1),j=l.useRef(0),B=l.useRef(0),v=l.useRef(0),A=l.useRef(void 0),T=l.useRef(!1),$=l.useRef(null),U=async()=>{const _=j.current,ie=++v.current,I=B.current;d(!0);try{await Promise.all([n.state().then(C=>{_===j.current&&ie===v.current&&B.current===I&&i(C)}),n.list().then(C=>{_===j.current&&ie===v.current&&c(C)})]),_===j.current&&ie===v.current&&p("")}catch{_===j.current&&ie===v.current&&p(t("companyBackup.loadFailed"))}finally{_===j.current&&ie===v.current&&d(!1)}};l.useEffect(()=>{const _=++j.current,ie=C=>{if(_!==j.current)return;B.current++,i(C);const W=C.lastBackupAt??C.schedule?.lastBackupAt;!C.busy&&!C.pendingRestore&&W&&W!==A.current&&(A.current=W,U())},I=n.onState(ie);return U(),()=>{j.current++,v.current++,I()}},[n]),l.useEffect(()=>{const _=$.current;if(!(!g||!_))return _.showModal(),()=>{_.close()}},[g]);const Z=N||a?.pendingRestore===!0,H=m!==null||!a||a.busy||Z,ne=()=>{f(null),b(""),k(""),E(null)},ae=_=>{H||T.current||(p(""),b(""),k(""),E(null),f(_))},oe=async(_,ie)=>{if(H||T.current)return;T.current=!0,u(_),p("");const I=j.current;try{await ie(()=>I===j.current)}catch{I===j.current&&p(t(_==="restore"?"companyBackup.restoreFailed":"companyBackup.actionFailed"))}finally{T.current=!1,I===j.current&&u(null)}},F=()=>{g?.kind==="create"&&oe("create",async _=>{await n.create({clientState:Ac()}),_()&&(ne(),await U())})},L=async _=>{if(!n.configureSchedule||T.current||!a||_&&(H||g?.kind!=="schedule"||h!=="BACK UP THIS WORKSPACE DAILY"))return;T.current=!0,u("schedule"),p("");const ie=j.current,I=B.current;k("");try{const C=await n.configureSchedule(_?{enabled:!0,confirmation:"BACK UP THIS WORKSPACE DAILY"}:{enabled:!1});ie===j.current&&(B.current===I&&i(C),ne())}catch{ie===j.current&&p(t("companyBackup.scheduleFailed"))}finally{T.current=!1,ie===j.current&&u(null)}},X=()=>{g?.kind!=="restore"||g.entry.passwordRequired!==!1&&(y.length<12||y.length>1024)||oe("prepare",async _=>{const ie=y;b(""),E(null),k("");const I=await n.prepareRestore({id:g.entry.id,...g.entry.passwordRequired!==!1?{password:ie}:{}});_()&&E(I)})},se=()=>{g?.kind!=="restore"||!S||h!=="REPLACE"||oe("restore",async _=>{const ie=localStorage.getItem(vn);if(ie&&ie!==S.id)throw new Error(t("companyBackup.restorePending"));localStorage.setItem(vn,S.id),await n.restore({id:S.id,confirmation:"REPLACE"}),_()&&(P(!0),ne())})},he=()=>{g?.kind!=="delete"||h!=="DELETE"||oe("delete",async _=>{await n.delete({id:g.entry.id,confirmation:"DELETE"}),_()&&(ne(),await U())})},pe=async()=>{const _=j.current;try{await n.cancel()}catch{_===j.current&&p(t("companyBackup.actionFailed"))}},ce=r?.backups.filter(_=>_.status==="ready")??[],ue=r?r.backups.length-ce.length:0,w=a?.progress,re=x||a?.message,te=(a?.busy||m)&&e.jsxs("div",{role:"status",className:"flex flex-col items-start gap-2 text-[13px] text-ink-secondary",children:[e.jsx("span",{children:m==="restore"?t("backup.restoring"):w?t(`companyBackup.phase.${w.phase}`):t("companyBackup.working")}),w&&w.totalBytes>0&&e.jsxs(e.Fragment,{children:[e.jsx("progress",{className:"w-full accent-accent",max:w.totalBytes,value:Math.min(w.bytesTransferred,w.totalBytes),"aria-label":t("companyBackup.progress")}),e.jsx("span",{children:t("companyBackup.transferred",{done:Xe(w.bytesTransferred),total:Xe(w.totalBytes)})})]}),a?.busy&&m!=="restore"&&e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{pe()},children:t("companyBackup.cancelTransfer")})]}),ee=g?.kind==="restore"?t("companyBackup.restore"):g?.kind==="delete"?t("companyBackup.delete"):g?.kind==="schedule"?t("companyBackup.enableSchedule"):t("companyBackup.create"),K=a?.schedule,le=_=>new Intl.DateTimeFormat(Me(),{dateStyle:"medium",timeStyle:"short"}).format(new Date(_));return e.jsxs(Y,{title:t("companyBackup.title"),subtitle:t("companyBackup.account",{organization:s.organization?.name??"",email:s.email??""}),children:[e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("companyBackup.managedScope")}),n.configureSchedule&&K&&e.jsxs("div",{className:"rounded-lg border border-hairline/40 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[14px] font-medium",children:t("companyBackup.daily")}),e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:t("companyBackup.scheduleHelp")})]}),e.jsx(me,{"aria-label":t("companyBackup.daily"),checked:K.enabled,disabled:m!==null||!a||!K.enabled&&H,onClick:()=>K.enabled?void L(!1):ae({kind:"schedule"})})]}),e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t(`companyBackup.scheduleStatus.${K.status}`)}),K.enabled&&K.nextBackupAt&&Number.isFinite(K.nextBackupAt)&&e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:t("companyBackup.nextBackup",{date:le(K.nextBackupAt)})}),K.lastBackupAt&&Number.isFinite(K.lastBackupAt)&&e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:t("companyBackup.lastScheduledBackup",{date:le(K.lastBackupAt)})}),K.message&&e.jsx("p",{role:"status",className:"mt-1 break-words text-[12px] text-ink-secondary",children:K.message})]}),Z?e.jsx("div",{className:"rounded-lg border border-warning/40 bg-warning/10 p-3 text-ink",children:e.jsx(yn,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"ui-button",disabled:H,onClick:()=>ae({kind:"create"}),children:t("companyBackup.create")}),e.jsx("button",{type:"button",className:"ui-button",disabled:m!==null||a?.busy||Z||o,onClick:()=>{U()},children:t("companyBackup.refresh")})]}),o&&e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("companyBackup.loading")}),r&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("companyBackup.quota",{used:Xe(r.usedBytes),total:Xe(r.limits.ownerQuotaBytes),count:r.limits.retainedSnapshots})}),ue>0&&e.jsx("p",{role:"status",className:"text-[12px] text-ink-secondary",children:t("companyBackup.pending",{count:ue})}),r&&ce.length===0&&e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("companyBackup.empty")}),e.jsx("ul",{className:"divide-y divide-hairline/40",children:ce.map(_=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-3 py-3",children:[e.jsxs("div",{className:"min-w-0 text-[13px]",children:[e.jsx("div",{className:"text-ink",children:ja(_)}),e.jsxs("div",{className:"text-[12px] text-ink-secondary",children:[Xe(_.sizeBytes),_.appVersion?` · ${_.appVersion}`:""]}),e.jsx("code",{className:"break-all text-[11px] text-ink-secondary",children:_.id})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"ui-button",disabled:H,onClick:()=>ae({kind:"restore",entry:_}),children:t("companyBackup.restore")}),e.jsx("button",{type:"button",className:"ui-button text-danger",disabled:H,onClick:()=>ae({kind:"delete",entry:_}),children:t("companyBackup.delete")})]})]},_.id))})]}),!g&&te,!g&&re&&e.jsx("p",{role:"alert",className:"break-words text-[13px] text-danger",children:re})]}),g&&e.jsx("dialog",{ref:$,"aria-labelledby":"company-backup-dialog-title",onKeyDown:_=>{(_.key==="Escape"||_.key==="Tab")&&_.stopPropagation()},onCancel:_=>{_.preventDefault(),m||ne()},className:"fixed inset-0 m-auto max-h-[85dvh] w-[min(34rem,calc(100vw-2rem))] overflow-y-auto rounded-xl border border-hairline/50 bg-app p-5 text-ink shadow-xl backdrop:bg-black/45",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("h3",{id:"company-backup-dialog-title",className:"text-[16px] font-semibold",children:ee}),Z&&e.jsx(yn,{}),(g.kind==="restore"||g.kind==="delete")&&e.jsxs("div",{className:"text-[13px] text-ink-secondary",children:[e.jsxs("p",{children:[ja(g.entry)," · ",Xe(g.entry.sizeBytes)]}),e.jsx("code",{className:"break-all text-[11px]",children:g.entry.id})]}),(g.kind==="create"||g.kind==="schedule")&&e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:_=>{_.preventDefault(),g.kind==="schedule"?L(!0):F()},children:[e.jsx("p",{className:"text-[13px] text-ink",children:t(g.kind==="schedule"?"companyBackup.scheduleWarning":"companyBackup.managedUploadWarning",{organization:s.organization?.name??"",email:s.email??""})}),g.kind==="schedule"?e.jsxs("details",{className:"text-[13px] text-ink-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-ink",children:t("companyBackup.included")}),e.jsx("p",{className:"mt-2",children:t("backup.excluded")}),e.jsx("p",{className:"mt-2",children:t("companyBackup.managedPrivacy")})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("backup.excluded")}),e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("companyBackup.managedPrivacy")})]}),e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("companyBackup.managedEncryption")}),g.kind==="schedule"&&e.jsxs("label",{className:"flex items-start gap-2 text-[13px]",children:[e.jsx("input",{className:"mt-1 accent-accent",type:"checkbox",required:!0,disabled:H,checked:h==="BACK UP THIS WORKSPACE DAILY",onChange:_=>k(_.target.checked?"BACK UP THIS WORKSPACE DAILY":"")}),e.jsx("span",{children:t("companyBackup.scheduleConsent")})]}),e.jsx("button",{type:"submit",className:"ui-button",disabled:H||g.kind==="schedule"&&h!=="BACK UP THIS WORKSPACE DAILY",children:t(g.kind==="schedule"?"companyBackup.enableSchedule":"companyBackup.create")})]}),g.kind==="restore"&&(S?e.jsxs(e.Fragment,{children:[e.jsx(Ec,{summary:S.summary}),e.jsx("p",{className:"text-[13px] text-danger",children:t("backup.replaceWarning")}),e.jsx("p",{className:"text-[13px] text-danger",children:t("backup.trustWarning")}),e.jsxs("label",{className:"text-[13px]",children:[t("backup.confirmReplace"),e.jsx("input",{autoComplete:"off",spellCheck:!1,maxLength:7,disabled:H,value:h,onChange:_=>k(_.target.value),className:rs})]}),e.jsx("button",{type:"button",className:"ui-button text-danger",disabled:H||h!=="REPLACE",onClick:se,children:t("backup.replace")})]}):e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:_=>{_.preventDefault(),X()},children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("companyBackup.previewHelp")}),g.entry.passwordRequired!==!1&&e.jsxs("label",{className:"text-[13px]",children:[t("backup.importPassword"),e.jsx("input",{type:"password",autoComplete:"off",required:!0,minLength:12,maxLength:1024,disabled:H,value:y,onChange:_=>b(_.target.value),className:rs})]}),e.jsx("button",{type:"submit",className:"ui-button",disabled:H||g.entry.passwordRequired!==!1&&(y.length<12||y.length>1024),children:t("backup.validate")})]})),g.kind==="delete"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] text-danger",children:t("companyBackup.deleteWarning")}),e.jsxs("label",{className:"text-[13px]",children:[t("companyBackup.confirmDelete"),e.jsx("input",{autoComplete:"off",spellCheck:!1,maxLength:6,disabled:H,value:h,onChange:_=>k(_.target.value),className:rs})]}),e.jsx("button",{type:"button",className:"ui-button text-danger",disabled:H||h!=="DELETE",onClick:he,children:t("companyBackup.delete")})]}),te,re&&e.jsx("p",{role:"alert",className:"break-words text-[13px] text-danger",children:re}),e.jsx("button",{type:"button",autoFocus:!0,className:"ui-button w-fit",disabled:m!==null,onClick:ne,children:t("companyBackup.cancel")})]})})]})}function rg({sources:s}){const n=[...new Set(s.map(a=>a==="claudeDesktop"?"claudeCode":a))];return e.jsx("span",{className:"mr-1.5 inline-flex items-center gap-1 align-[-1px]","aria-hidden":"true",children:n.map(a=>{switch(a){case"codex":return e.jsx(_c,{size:12},a);case"cursor":return e.jsx(Dc,{size:12},a);case"gemini":return e.jsx(Ua,{preset:"google",size:12},a);default:return e.jsx(Fc,{size:12},a)}})})}function ka({icon:s,label:n,summary:a,hint:i,sources:r,checked:c,disabled:o,onChange:d}){return e.jsxs("label",{className:z("flex items-start gap-3 px-3.5 py-3 transition-colors",o?"cursor-default":"cursor-pointer hover:bg-raised/40"),children:[e.jsx("input",{type:"checkbox",checked:c,disabled:o,onChange:m=>d(m.target.checked),className:"mt-0.5 size-4 shrink-0 cursor-[inherit] accent-[var(--color-accent)]"}),e.jsx("span",{className:"mt-0.5 flex size-4 shrink-0 items-center justify-center text-ink-secondary",children:s}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("span",{className:"text-[13px] leading-5 text-ink-secondary",children:[e.jsx("span",{className:"mr-2 text-[14px] font-medium text-ink",children:n}),e.jsx(rg,{sources:r}),a]}),e.jsx("span",{className:"mt-0.5 text-[12px] leading-relaxed text-ink-secondary",children:i})]})]})}const Cr="inline-flex items-center justify-center gap-2 rounded-lg bg-accent px-3 py-2 text-[13px] font-medium text-accent-ink disabled:opacity-40";function lg({local:s,detection:n,chosen:a,status:i,result:r,onChoose:c,onBring:o}){const d=i==="working";let m;if(!s)m=e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("settings.import.appsLocalOnly")});else if(n===void 0)m=e.jsxs("p",{className:"flex items-center gap-2 text-[13px] text-ink-secondary",children:[e.jsx(J,{size:14,className:"animate-spin"}),t("settings.import.appsLooking")]});else if(r){const{line:u,notes:x,done:p}=Lc(r);m=e.jsxs("div",{role:"status",className:"flex items-start gap-3",children:[e.jsx("span",{className:z("mt-px flex size-5 shrink-0 items-center justify-center rounded-full",p?"bg-success/15 text-success":"bg-control text-ink-secondary"),children:p?e.jsx(be,{size:12,strokeWidth:3}):e.jsx(Bc,{size:12,strokeWidth:2.5})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[14px] font-medium text-ink",children:u}),x.map(g=>e.jsx("p",{className:"mt-1 text-[12px] leading-relaxed text-ink-secondary",children:g},g))]})]})}else!n||Oc(n)===0?m=e.jsx("p",{className:"text-[13px] text-ink-secondary",children:n===null?t("onboarding.import.error"):t("settings.import.appsNothing")}):m=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"divide-y divide-hairline/40 overflow-hidden rounded-xl border border-hairline/40",children:[n.skills.length>0&&e.jsx(ka,{icon:e.jsx(Is,{size:15}),label:t("onboarding.import.skills"),summary:Mc(n),hint:t("onboarding.import.skillsHint"),sources:jn(n.skills),checked:a.skills,disabled:d,onChange:u=>c({...a,skills:u})}),n.tools.length>0&&e.jsx(ka,{icon:e.jsx(Uc,{size:15}),label:t("onboarding.import.tools"),summary:zc(n),hint:t("onboarding.import.toolsHint"),sources:jn(n.tools),checked:a.tools,disabled:d,onChange:u=>c({...a,tools:u})})]}),i==="failed"&&e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:t("onboarding.import.error")}),e.jsxs("button",{onClick:o,disabled:d||!(a.skills||a.tools),className:z(Cr,"mt-3"),children:[d&&e.jsx(J,{size:14,className:"animate-spin"}),d?t("onboarding.import.bringing"):t("onboarding.import.bring")]})]});return e.jsxs("section",{"data-import-section":"apps",className:"rounded-xl bg-card p-4",children:[e.jsx("div",{className:"text-[15px] font-medium text-ink",children:t("settings.import.appsTitle")}),e.jsx("div",{className:"mt-0.5 text-[13px] leading-relaxed text-ink-secondary",children:t("settings.import.appsSubtitle")}),e.jsx("div",{className:"mt-4",children:m})]})}function og({client:s,local:n}){const[a,i]=l.useState(void 0),[r,c]=l.useState({skills:!0,tools:!0}),[o,d]=l.useState("idle"),[m,u]=l.useState(null);l.useEffect(()=>{if(!n)return;const p=new AbortController;return s.detect(p.signal).then(i,()=>i(null)),()=>p.abort()},[s,n]);const x=async()=>{if(!a||o==="working")return;const p={...r.skills&&a.skills.length?{skills:!0}:{},...r.tools&&a.tools.length?{tools:!0}:{}};if(!(!p.skills&&!p.tools)){d("working");try{const g=await s.apply(p);Ll("setup_import_applied",{skills:g.skills?.added.length??0,tools:g.tools?.added.length??0}),u(g),d("idle")}catch{d("failed")}}};return e.jsx(lg,{local:n,detection:a,chosen:r,status:o,result:m,onChoose:c,onBring:()=>{x()}})}function cg(){const[s,n]=l.useState(!1),[a,i]=l.useState(!1);return e.jsxs("section",{"data-import-section":"grok",className:"rounded-xl bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[15px] font-medium text-ink",children:[e.jsx(Tc,{size:16}),t("settings.import.grokTitle")]}),e.jsx("div",{className:"mt-0.5 text-[13px] leading-relaxed text-ink-secondary",children:t("settings.import.grokSubtitle")}),e.jsxs("button",{type:"button","data-grok-move-open":!0,"aria-expanded":a,onClick:()=>{n(!0),i(!a)},className:z(Cr,"mt-3"),children:[t("settings.import.grokTitle"),e.jsx(Sa,{size:14,"aria-hidden":"true",className:z("transition-transform",a&&"rotate-180")})]}),s&&e.jsx("div",{className:a?void 0:"hidden",children:e.jsx(Rc,{inline:!0,onClose:()=>{n(!1),i(!1)}})})]})}function Er({client:s=Ic}){const{state:n}=G();return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(og,{client:s,local:Pc(n.config?.cloudHome===!0)}),e.jsx(cg,{})]})}function Ar({simple:s=!1}){return e.jsxs(e.Fragment,{children:[e.jsx(dg,{simple:s}),e.jsx(ug,{simple:s}),e.jsx(mg,{simple:s})]})}const Na=()=>typeof Notification<"u"?Notification.permission:"default";function dg({simple:s=!1}){const[n,a]=l.useState(Na),i=$c();if(l.useEffect(()=>{const o=()=>{document.visibilityState==="visible"&&a(Na())};return window.addEventListener("focus",o),document.addEventListener("visibilitychange",o),()=>{window.removeEventListener("focus",o),document.removeEventListener("visibilitychange",o)}},[]),typeof Notification>"u")return null;const r=n==="denied",c=async()=>{if(n==="granted")return kn(!i);const o=await qc();o&&(a(o),o==="granted"&&kn(!0))};return e.jsx(de,{title:t("settings.deviceNotifications.title"),subtitle:t(r?"settings.deviceNotifications.blocked":s?"settings.simple.deviceNotifications":"settings.deviceNotifications.subtitle"),children:e.jsx(me,{checked:n==="granted"&&i,disabled:r,"aria-label":t("settings.deviceNotifications.show"),onClick:()=>{c()}})})}function ug({simple:s=!1}){const n=Kc();return e.jsx(de,{title:t("settings.notificationSounds.title"),subtitle:t(s?"settings.simple.notificationSounds":"settings.notificationSounds.subtitle"),children:e.jsx(me,{checked:n,"aria-label":t("settings.notificationSounds.play"),onClick:()=>Hc(!n)})})}function mg({simple:s=!1}){const n=Wc();return e.jsx(de,{title:t("settings.notificationFeed.title"),subtitle:t(s?"settings.simple.notificationFeed":"settings.notificationFeed.subtitle"),children:e.jsx(me,{checked:n,"aria-label":t("settings.notificationFeed.show"),onClick:()=>Gc(!n)})})}function Ir(){const{state:s,dispatch:n}=G(),a=Vc(s.config),[i,r]=l.useState(!1),[c,o]=l.useState("");if(!Jc(s.config))return null;const d=async()=>{if(!i){r(!0),o("");try{const m=await M("/api/config",{method:"PATCH",body:JSON.stringify({features:{savedSteps:!a}})});n({type:"configStatus",config:m})}catch(m){o(m instanceof Error?m.message:t("settings.savedSteps.error"))}finally{r(!1)}}};return e.jsx(de,{title:t("settings.savedSteps.title"),subtitle:t("settings.savedSteps.subtitle"),children:e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx(me,{checked:a,disabled:i,"aria-label":t("settings.savedSteps.aria"),onClick:d}),c&&e.jsx("span",{role:"alert",className:"text-[12px] text-danger",children:c})]})})}const pg=["settings.font.title","settings.chatWidth.title","settings.pinnedCircles.title","settings.universalPins.title","settings.runCard.title"],xg=["settings.roomTurns.title","settings.mcpCalls.title","settings.threads.title","settings.recovery.title","settings.threadCleanup.title","settings.keepWarm.title","settings.savedSteps.title"];function gg({has:s,peopleOpen:n,onLooks:a,onMore:i}){return e.jsxs(e.Fragment,{children:[(s("general")||s("people"))&&e.jsx(ye,{label:t("settings.group.account"),block:"general",children:e.jsxs(ve,{children:[s("general")&&e.jsx(Zx,{}),s("general")&&e.jsx(yr,{row:!0}),s("general")&&e.jsx(bi,{place:"account"}),s("people")&&e.jsx("div",{"data-settings-block":"people",className:"scroll-mt-4",children:e.jsx(_i,{simple:!0,startOpen:n})})]})}),s("appearance")&&e.jsx(ye,{label:t("settings.section.appearance"),block:"appearance",children:e.jsxs(ve,{children:[e.jsx(dr,{simple:!0}),e.jsx(hg,{onLooks:a}),e.jsx(qi,{}),e.jsx(ei,{}),e.jsx(Vi,{}),e.jsx(pi,{simple:!0})]})}),s("appearance")&&e.jsx(ye,{label:t("settings.simple.group.typing"),children:e.jsxs(ve,{children:[e.jsx(us,{simple:!0}),e.jsx(xi,{}),e.jsx(gi,{simple:!0}),e.jsx(hi,{simple:!0})]})}),s("appearance")&&e.jsx(ye,{label:t("notifications.title"),children:e.jsx(ve,{children:e.jsx(Ar,{simple:!0})})}),s("general")&&e.jsx(ye,{label:t("settings.simple.group.system"),children:e.jsxs(ve,{children:[e.jsx(Si,{simple:!0}),e.jsx(ti,{simple:!0}),e.jsx(Ci,{}),e.jsx(Ei,{}),e.jsx(wi,{simple:!0})]})}),s("import")&&e.jsx(ye,{label:t("settings.section.import"),block:"import",children:e.jsx(je,{children:e.jsx(Er,{})})}),s("organization")&&e.jsx(ye,{label:t("settings.section.organization"),block:"organization",children:e.jsx(Xi,{})}),s("activity")&&e.jsx(ye,{label:t("settings.section.activity"),block:"activity",children:e.jsx($i,{})}),i&&e.jsx("div",{"data-settings-block":"more",className:"scroll-mt-4",children:e.jsx(ve,{children:e.jsx(de,{title:t("settings.simple.more.title"),subtitle:t("settings.simple.more.subtitle"),children:e.jsx("button",{type:"button",className:"ui-button","data-settings-more":"",onClick:i,children:t("settings.simple.more.open")})})})}),e.jsx("div",{"data-settings-block":"advanced-mode",className:"scroll-mt-4",children:e.jsx(ve,{children:e.jsx(ms,{simple:!0})})})]})}function hg({onLooks:s}){const n=Hs(),a=Lt.find(r=>r.id===Ca(n))?.name,i=n==="system"?t("settings.simple.themes.followHint"):a;return e.jsx(de,{title:t("settings.theme.title"),subtitle:i,children:e.jsx("button",{type:"button",className:"ui-button",onClick:s,children:t("settings.simple.themes.browse")})})}function fg({onBack:s,toolCalls:n=!0}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{children:e.jsx("button",{type:"button",className:"ui-button",onClick:s,children:t("settings.simple.looks.back")})}),e.jsx("div",{"data-settings-block":"looks",children:e.jsx(ur,{})}),e.jsx(cr,{}),n&&e.jsx(ve,{children:e.jsx(mi,{})})]})}function bg({sections:s,onOpen:n,onBack:a}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{children:e.jsx("button",{type:"button",className:"ui-button",onClick:a,children:t("settings.simple.looks.back")})}),s.length>0&&e.jsx(ye,{block:"more-sections",children:e.jsx(ve,{children:s.map(({id:i,labelKey:r})=>e.jsx(de,{title:t(r),children:e.jsx("button",{type:"button",className:"ui-button","data-settings-more-section":i,onClick:()=>n(i),children:t("settings.simple.more.open")})},i))})}),e.jsx(ye,{label:t("settings.simple.more.limits"),block:"limits",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Y,{title:t("settings.roomTurns.title"),subtitle:t("settings.roomTurns.subtitle"),children:e.jsx(mr,{})}),e.jsx(Y,{title:t("settings.mcpCalls.title"),subtitle:t("settings.mcpCalls.subtitle"),children:e.jsx(gr,{})}),e.jsx(vr,{}),e.jsx(jr,{}),e.jsx(Sr,{}),e.jsx(Ri,{}),e.jsx(ve,{children:e.jsx(Ir,{})})]})})]})}function yg({has:s,disclose:n,connections:a}){return e.jsxs(e.Fragment,{children:[s("engines")&&e.jsx("div",{"data-settings-block":"engines",className:"flex scroll-mt-4 flex-col gap-7",children:e.jsxs(je,{children:[e.jsx(Bi,{simple:!0,more:n("ai-more")}),e.jsx(ve,{children:e.jsx(ui,{simple:!0})})]})}),s("connections")&&e.jsx(je,{children:e.jsx(zt,{title:t("settings.section.connections"),block:"connections",...n("ai-keys"),children:a})})]})}function vg({has:s,remoteAccess:n,servers:a,disclose:i}){return e.jsxs(e.Fragment,{children:[s("computer")&&e.jsx(ye,{label:t("settings.simple.computer.bots"),block:"computer",children:e.jsx(je,{children:e.jsx(Ui,{})})}),s("companion")&&e.jsxs(ye,{label:t(Za()?"settings.section.phoneDevices":"settings.section.thisServer"),block:"companion",children:[n.companion,n.pairing,n.domain]}),s("computer")&&e.jsxs(ye,{label:t("settings.experimental.browser"),block:"browser",children:[e.jsxs(ve,{children:[e.jsx(oi,{}),e.jsx(ci,{})]}),e.jsx(di,{})]}),s("logins")&&e.jsx("div",{"data-settings-block":"logins",className:"scroll-mt-4",children:e.jsx(Gi,{})}),(s("companion")||s("desktopWorkspaces"))&&e.jsxs(zt,{title:t("settings.simple.computer.elsewhere"),block:"elsewhere",...i("computer-elsewhere"),children:[s("desktopWorkspaces")&&e.jsx("div",{"data-settings-block":"desktopWorkspaces",className:"flex scroll-mt-4 flex-col gap-4",children:a}),s("companion")&&e.jsx("div",{"data-settings-block":"remote",className:"flex scroll-mt-4 flex-col gap-4 empty:hidden",children:n.client})]})]})}function jg({has:s,disclose:n,cloudAccount:a}){const{usage:i,upgrade:r,dialog:c}=Xc(),o=fi(),d=o?.view.kind==="signed-out"||o?.view.kind==="removed";return e.jsxs(e.Fragment,{children:[e.jsx(tr,{}),e.jsx("div",{"data-settings-block":"usage",className:"scroll-mt-4",children:i?e.jsx(Yc,{usage:i,upgrade:r,children:c}):e.jsx(je,{note:"settings.adminOnly.usage",children:e.jsx(tx,{})})}),(i||s("usage"))&&e.jsxs(zt,{title:t("settings.simple.billing.limits"),...n("billing-limits"),children:[i&&e.jsx(Qc,{usage:i,upgrade:r}),s("usage")&&e.jsx(je,{note:"settings.adminOnly.usage",children:e.jsx(ir,{})})]}),s("cloudAccount")&&e.jsxs(ye,{label:t("settings.simple.billing.plan"),block:"cloudAccount",footnote:e.jsx(Od,{}),children:[e.jsx(ve,{children:e.jsx(bi,{place:"plan",usage:i,upgrade:r})}),d?null:e.jsx("div",{className:"flex flex-col gap-4",children:a})]})]})}const Pr=()=>`${Ns()} ${Zc()}`;function kg(){const s=ed(!0);if(!s)return null;const n=s.phase==="idle"?void 0:[s.label,s.item.subtitle].filter(Boolean).join(" "),a=s.phase==="available"?t("settings.simple.updates.seeRelease"):s.phase==="reload"?t("settings.simple.updates.reload"):s.phase==="checking"?t("common.checking"):t("settings.updates.check");return e.jsx(de,{title:Pr(),subtitle:n,children:e.jsx("button",{type:"button",className:"ui-button",disabled:s.item.disabled,onClick:s.item.onSelect,children:a})})}function Ng({remoteActive:s}){return e.jsx(ye,{block:"updates",children:e.jsxs(ve,{children:[window.ogb?.updater?e.jsx(ri,{title:Pr()}):e.jsx(kg,{}),e.jsx(Qa,{}),!s&&e.jsx(li,{}),e.jsx(Ai,{simple:!0})]})})}const wa=[{id:"you",labelKey:"settings.group.you"},{id:"ai",labelKey:"settings.group.ai"},{id:"computers",labelKey:"settings.group.computers"},{id:"account",labelKey:"settings.group.account"}],Ws=[{id:"general",group:"you",labelKey:"settings.section.general",icon:Ya,keywords:["profile","pinned panels","web panel","dashboard","pin a page","name","email","about me","about","suggestions","suggested","memory","analytics","updates","product updates","newsletter","email updates","effort","new bots","reasoning","threads","parallel","concurrency","cleanup","retention","attachments","clear attachments","event log","event-log","log size","automatic recovery","backup model","fallback","routines","conversation","schedule","usage","limit","plan","upgrade","cloud desktop hours","storage","saved steps","repeat","replay","computer tasks","without ai","forget",...Cu()]},{id:"appearance",group:"you",labelKey:"settings.section.appearance",icon:_d,keywords:["skin","theme","appearance","font","typeface","chat width","width","wide","full width","bubble","bubbles","tools","tool calls","threads","show threads","hide threads","sidebar","display","run","this run","run card","commands","notifications","sound","sounds","mute","silent","chime","pinned","circles","universal","groups","top","send","enter","return","shift+enter","ctrl+enter","cmd+enter","⌘+enter","new line","keyboard","ime","japanese","message color","my messages","toolbar","tools layout","footer","routines","triggers","team map","color","colour","cloud color","server color","tint","sidebar color","sidebar picture","picture","image","banner","background","computers","your computers","rail","strip","frame","window frame","title bar"]},{id:"companion",group:"you",labelKey:"settings.section.companion",icon:td,keywords:["companion","device","phone","desktop","client","host","pair","pairing","mobile","https","secure","tailscale","wifi","remote","advanced","domain","dns","self-hosted","server","caddy"]},{id:"engines",group:"ai",labelKey:"settings.section.engines",icon:Wd,keywords:["models","model providers","engines","claude","codex","grok","providers","cli","sign in","subscription"]},{id:"connections",group:"ai",labelKey:"settings.section.connections",icon:Wa,keywords:["keys","api","api key","api keys","connections","composio","box","xai","mistral","cerebras","meta","muse","vps","router","openrouter","base url","openai","anthropic","groq","greenference","modelgo","opencode","deepseek","provider","ollama","lm studio","lmstudio","llm studio","llmstudio","bionic"]},{id:"decisionModel",group:"ai",labelKey:"settings.section.decisionModel",icon:sd,keywords:["decision","extraction","jev","typesafe","cloudflare","workers ai","clef","clairic","email","routing","auto","rooms","who answers"]},{id:"imageGeneration",group:"ai",labelKey:"settings.section.imageGeneration",icon:nd,keywords:["image","images","picture","generate","avatar","gpt image","grok imagine","gemini","nano banana","openrouter","flux","backup"]},{id:"skills",group:"ai",labelKey:"settings.section.skills",icon:Is,keywords:["skills","library","assign","agent skills","skill md"]},{id:"desktopWorkspaces",group:"computers",labelKey:"settings.section.desktopWorkspaces",icon:Gt,keywords:["workspace","cloud","hosted","vps","server","servers","connect","pair","switch","local"]},{id:"computer",group:"computers",labelKey:"settings.section.computer",icon:yi,keywords:["vm","virtual","desktop","browser","built-in browser","profiles","browser profiles"]},{id:"logins",group:"computers",labelKey:"settings.section.vault",icon:Dt,keywords:["vault","logins","login","passwords","password","sign in","2fa","one-time code","totp","fill_login","1password","password manager","secrets","secret","token",".env","env"]},{id:"cloudAccount",group:"account",labelKey:"settings.section.cloudAccount",icon:Rt,keywords:["cloud","my cloud","account","personal","sign in","pro","subscription","billing","sync","send","this computer","bots","logins","1password"]},{id:"organization",group:"account",labelKey:"settings.section.organization",icon:Gt,keywords:["company","organization","organisation","sign in","enroll","managed","models","disconnect"]},{id:"usage",group:"account",labelKey:"settings.section.usage",icon:zd,keywords:["tokens","cost","billing","plan","quota","remaining","weekly","5-hour","model","used"]},{id:"backups",group:"account",labelKey:"settings.section.backups",icon:si,keywords:["export","import","restore","full backup","password","recovery"]},{id:"import",group:"account",labelKey:"settings.section.import",icon:Ye,keywords:["import","grok","grok bot","move","cursor","claude code","codex","gemini","skills","mcp","tools","bring"]},{id:"people",group:"account",labelKey:"settings.section.people",icon:Ct,keywords:["people","users","invite","sign in","members","admins","access"]},{id:"botAccess",group:"account",labelKey:"settings.section.botAccess",icon:Ct,keywords:["access","share","sharing","who can","view","chat","edit","permissions","team","members","bots"]},{id:"activity",group:"account",labelKey:"settings.section.activity",icon:Kd,keywords:["activity","audit","log","history","who changed","approvals","decisions","admin"]},{id:"workspaces",group:"account",labelKey:"settings.section.workspaces",icon:Gt,keywords:["clients","tenants","fleet","workspaces","installation","installations"]},{id:"experimental",group:"account",labelKey:"settings.section.experimental",icon:ad,keywords:["early","preview","learn","skill","authoring"]}],wg=[{id:"general",labelKey:"settings.section.general",icon:rd,sections:["general","appearance","people","import","organization","activity"],keywords:["account","theme","looks","open at login","startup","analytics","advanced mode","more settings","limits","timeout"]},{id:"botAccess",labelKey:"settings.section.botAccess",icon:Ct,sections:["botAccess"]},{id:"ai",labelKey:"settings.group.ai",icon:ld,sections:["engines","connections","imageGeneration"],keywords:["new bots","defaults","effort"]},{id:"skills",labelKey:"settings.section.skills",icon:Is,sections:["skills"],keywords:["skills","skill hub","library","kỹ năng","thư viện"]},{id:"computer",labelKey:"settings.simple.page.computer",icon:yi,sections:["companion","desktopWorkspaces","computer","logins"]},{id:"billing",labelKey:"settings.simple.page.billing",icon:od,sections:["usage"],keywords:["billing","included","allowance","cloud hours","voice"]},{id:"backups",labelKey:"settings.section.backups",icon:si,sections:["backups"],keywords:["chuyển máy offline","transfer","export","import","restore","sao lưu"]},{id:"cloudAccount",labelKey:"settings.section.cloudAccount",icon:Rt,sections:["cloudAccount"],keywords:["cloud","limix cloud","đám mây","máy chủ","server"]},{id:"updates",labelKey:"settings.simple.page.updates",icon:Fd,sections:["updates"],keywords:["update","version","release","product updates","newsletter","email updates","welcome","tour","diagnostics","logs","support"]}],js=["experimental","workspaces","decisionModel"],Sg={connections:"ai-keys",remote:"computer-elsewhere",desktopWorkspaces:"computer-elsewhere"};function Cg(s,n){const a=wg.map(r=>({...r,sections:r.sections.filter(c=>s.has(c))})).filter(r=>r.sections.length>0),i=js.includes(n)&&s.has(n)?Ws.find(r=>r.id===n):void 0;return i&&a.push({id:i.id,labelKey:i.labelKey,icon:i.icon,sections:[i.id]}),a}function Eg(s,n,a){if(a<=0){s.scrollTop=0;return}const i=s.querySelector(`[data-settings-block="${n}"]`);i&&Ls(s,i)}function Ag(s,n){return!n||[t(s.labelKey),...s.keywords??[]].some(a=>a.toLowerCase().includes(n))?!0:s.sections.some(a=>{const i=Ws.find(r=>r.id===a);return i?ks(i,n):!1})}function ks(s,n){return!n||s.id==="connections"&&lt.some(a=>Cs(a,n))?!0:[t(s.labelKey),...s.keywords].some(a=>a.toLowerCase().includes(n))}function Ig(s){return s?lt.filter(n=>Cs(n,s)).slice(0,8):[]}const Pg=s=>s.uses?cs(s.uses,s.id):cs(s.id);function eh(){return e.jsx(Pa,{modal:!0,children:e.jsx(Tg,{})})}function Tg(){const s=Bl(),{state:n,dispatch:a}=G(),i=rl(),r=window.ogb?.remoteClient?.active===!0,c=n.appSettingsSection,o=i&&c==="remote"&&window.ogb?.environments?"desktopWorkspaces":r&&!["appearance","desktopWorkspaces"].includes(c)||c==="remote"?"companion":i&&c==="updates"?"general":c,d=l.useRef(null),m=l.useRef(null),u=l.useRef(i),[x,p]=l.useState("");l.useEffect(()=>window.ogb?.environments?.onOpenSettings?.(()=>p("")),[]),l.useEffect(()=>window.ogb?.onOpenAppSettings?.(()=>p("")),[]);const g=x.trim().toLowerCase(),f=Ot(),y=Za(),b=Ws.map(I=>I.id==="companion"?{...I,labelKey:y?"settings.section.phoneDevices":"settings.section.thisServer"}:I),k=b.filter(I=>!r||I.id==="companion"||I.id==="appearance"||I.id==="desktopWorkspaces").filter(I=>I.id!=="desktopWorkspaces"||!!window.ogb?.environments).filter(I=>I.id!=="organization"||!!window.ogb?.organization).filter(I=>I.id!=="cloudAccount"||!!(window.ogb?.cloudAccount||window.ogb?.cloudPlan&&n.config?.cloudHome===!0)).filter(I=>I.id!=="workspaces"||lr(n.config)).filter(I=>I.id!=="people"||!window.ogb&&n.config?.cloudHome!==!0).filter(I=>I.id!=="activity"||!window.ogb&&f===!0).filter(I=>I.id!=="botAccess"||!!n.config?.team&&f===!0).filter(I=>(I.id!=="skills"||Nn(n.config))&&(I.id!=="cloudAccount"||Ol)),S=k.filter(I=>ks(I,g)),E=new Set([...k.map(I=>I.id),...r?[]:["updates"]]),N=i?[]:Cg(E,o),P=N.filter(I=>Ag(I,g)),j=N.find(I=>I.sections.includes(o)),B=i?b.find(I=>I.id===o)?.labelKey:j?.labelKey,v=i?S.some(I=>I.id===o)?void 0:S[0]?.id:j&&P.includes(j)?void 0:P[0]&&(P[0].sections.find(I=>S.some(C=>C.id===I))??P[0].sections[0]);l.useEffect(()=>{v&&a({type:"toggleAppSettings",open:!0,section:v})},[a,v]);const[A,T]=l.useState({}),$=Ra();l.useEffect(()=>{$&&T(I=>I["ai-keys"]?I:{...I,"ai-keys":!0})},[$]);const U=I=>{const C=g!==""||(A[I]??Sg[c]===I);return{id:I,open:C,onToggle:()=>T(W=>({...W,[I]:!C}))}},[Z,H]=l.useState(null),ne=Z?.for===c?Z.view:null,ae=(I,C=c)=>H(I&&{view:I,for:C});l.useEffect(()=>{H(I=>I?.for===c?I:null)},[c]);const[oe,F]=l.useState(null),L=i||ll||!g?[]:pg.filter(I=>t(I).toLowerCase().includes(g)),X=k.filter(I=>js.includes(I.id)),se=r||!k.some(I=>I.id==="connections")?[]:Ig(g),he=I=>se.map(C=>e.jsx("button",{type:"button","data-settings-key-result":C.id,className:I,onClick:()=>{p(""),ae(null),a(Pg(C))},children:e.jsxs("span",{children:[t(C.labelKey)," ",e.jsxs("span",{className:"text-ink-secondary",children:["· ",t(cd(C).titleKey)]})]})},C.id)),pe=j?.sections.indexOf(o)??0,ce=!i&&c==="remote"?"remote":o;l.useEffect(()=>{m.current&&Eg(m.current,ce,i?0:ce===o?pe:1)},[i,ce,o,pe]),l.useEffect(()=>{if(!oe)return;const I=m.current?.querySelector(`[data-settings-block="${oe}"]`);m.current&&I&&Ls(m.current,I),F(null)},[oe]),l.useEffect(()=>{const I=document.activeElement instanceof HTMLElement?document.activeElement:null,C=d.current,W=C?.querySelector("[data-settings-search]");u.current&&W?.checkVisibility()?W.focus():C?.focus();const xe=V=>{if(!s())return;if(!u.current&&C&&document.activeElement===C&&V.key.length===1&&!V.metaKey&&!V.ctrlKey&&!V.altKey&&W?.checkVisibility()){V.preventDefault(),W.focus(),p(ze=>ze+V.key);return}if(V.defaultPrevented||C&&[...C.querySelectorAll('[role="dialog"], [role="alertdialog"]')].some(ze=>ze.getClientRects().length))return;if(V.key==="Escape"){V.preventDefault(),a({type:"toggleAppSettings",open:!1});return}if(V.key!=="Tab"||!C)return;const ke=Array.from(C.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex="-1"])')).filter(ze=>ze.checkVisibility());if(ke.length===0){V.preventDefault(),C.focus();return}const Ie=ke[0],et=ke[ke.length-1],tt=document.activeElement;V.shiftKey&&(tt===Ie||!C.contains(tt))?(V.preventDefault(),et.focus()):!V.shiftKey&&tt===et&&(V.preventDefault(),Ie.focus())};return window.addEventListener("keydown",xe),()=>{window.removeEventListener("keydown",xe),I?.focus()}},[a,s]);const ue=I=>a({type:"toggleAppSettings",open:!0,section:I}),w=n.appSettingsPhonePairing,re=Nd(n.config?.cloudHome===!0)==="computer",te={client:e.jsx(rp,{hideWhenUnavailable:!0,legacyOnly:!0}),domain:r||y?null:e.jsx(Qm,{}),pairing:y?null:e.jsx(id,{cloudHome:n.config?.cloudHome===!0,focusRequest:re?0:w,team:n.config?.team?.name,teamPhoneBlocked:n.config?.managedPolicy?.remoteAccess===!1?t("policy.teamRemoteBlocked",{organization:n.config.managedPolicy.organizationName}):null,simple:!i}),companion:y?e.jsx(Lm,{profileEmail:n.config?.profile?.email,focusRequest:w,simple:!i}):null},ee=I=>{switch(I){case"desktopWorkspaces":return e.jsxs(e.Fragment,{children:[e.jsx(Jn,{}),te.client]});case"organization":return window.ogb?.organization&&!r?e.jsx(Xi,{}):null;case"cloudAccount":return(window.ogb?.cloudAccount||window.ogb?.cloudPlan&&n.config?.cloudHome===!0)&&!r?e.jsx(Vp,{linkRequest:n.appSettingsCloudLink,cloudHome:n.config?.cloudHome===!0,teamHome:n.config?.team,onConnectPhone:()=>{a({type:"toggleAppSettings",open:!1}),window.dispatchEvent(new Event("limix:phone"))},onAddCloud:i?()=>a({type:"openCloudAdd",source:"app_settings"}):void 0,onSignIn:()=>a({type:"openCloudAdd",source:"app_settings",signIn:!0})}):null;case"general":return e.jsxs(e.Fragment,{children:[e.jsx(ms,{}),e.jsx(ti,{}),e.jsx(Ci,{}),e.jsx(Md,{}),e.jsx(ud,{}),e.jsxs(Y,{title:t("settings.profile.title"),subtitle:t("settings.profile.sharedSubtitle"),children:[e.jsx(br,{}),e.jsx(yr,{})]}),e.jsx(us,{}),e.jsx(Si,{}),e.jsx(Ld,{}),e.jsx(Ir,{}),e.jsx(wi,{}),e.jsx(Qa,{}),e.jsx(ui,{}),e.jsx(Y,{title:t("settings.roomTurns.title"),subtitle:t("settings.roomTurns.subtitle"),children:e.jsx(mr,{})}),e.jsx(Y,{title:t("settings.mcpCalls.title"),subtitle:t("settings.mcpCalls.subtitle"),children:e.jsx(gr,{})}),e.jsx(vr,{}),e.jsx(jr,{}),e.jsx(Sr,{}),e.jsx(Ei,{}),e.jsx(sg,{}),!r&&e.jsx(li,{}),e.jsx(ri,{}),e.jsx(Ai,{})]});case"appearance":return e.jsxs(e.Fragment,{children:[e.jsx(dr,{}),e.jsx(Y,{title:t("settings.skin.title"),subtitle:t("settings.skin.subtitle"),children:e.jsx(ur,{})}),e.jsx(cr,{}),e.jsx(vp,{}),r&&e.jsx(ms,{}),r&&e.jsx(us,{}),e.jsx(Dx,{}),e.jsx(_x,{}),e.jsx(pi,{}),e.jsx(xi,{}),e.jsx(gi,{}),e.jsx(hi,{}),e.jsx($x,{}),e.jsx(ei,{}),e.jsx(Vi,{}),e.jsx(Id,{}),e.jsx(Pd,{}),e.jsx(Td,{}),e.jsx(Ar,{}),!r&&e.jsx(mi,{}),e.jsx(Rd,{})]});case"experimental":return e.jsx(Ad,{});case"connections":return e.jsx(je,{children:e.jsx(Su,{})});case"decisionModel":return e.jsx(je,{children:e.jsx(Mu,{})});case"imageGeneration":return e.jsx(je,{children:e.jsx(Wu,{})});case"engines":return e.jsx(je,{children:e.jsx(Bi,{})});case"backups":return e.jsxs(je,{children:[e.jsx(dd,{}),e.jsx(ng,{})]});case"import":return e.jsx(je,{children:e.jsx(Er,{})});case"companion":return e.jsxs(e.Fragment,{children:[te.companion,te.pairing,te.domain,window.ogb?.environments?null:te.client]});case"computer":return e.jsxs(e.Fragment,{children:[e.jsx(oi,{}),e.jsx(ci,{}),e.jsx(di,{}),e.jsx(je,{children:e.jsx(Ui,{})})]});case"logins":return e.jsx(Gi,{});case"usage":return e.jsxs(e.Fragment,{children:[e.jsx(tr,{}),e.jsx(je,{note:"settings.adminOnly.usage",children:e.jsx(ir,{})})]});case"skills":return Nn(n.config)?e.jsx(Nx,{}):null;case"people":return e.jsx(_i,{});case"activity":return e.jsx($i,{});case"botAccess":return e.jsx($m,{});case"workspaces":return e.jsx(Px,{});default:return null}},K=()=>{ue("general"),ae("more","general")},le=I=>{const C=W=>I.sections.includes(W);switch(I.id){case"general":return ne==="looks"?e.jsx(fg,{toolCalls:!r,onBack:()=>{ae(null),F("appearance")}}):ne==="more"?e.jsx(bg,{sections:X,onOpen:W=>{ae(null),ue(W)},onBack:()=>{ae(null),F("more")}}):e.jsx(gg,{has:C,peopleOpen:o==="people",onLooks:()=>ae("looks"),onMore:C("general")?()=>ae("more"):void 0});case"ai":return e.jsx(yg,{has:C,disclose:U,connections:ee("connections")});case"computer":return e.jsx(vg,{has:C,remoteAccess:te,servers:e.jsx(Jn,{}),disclose:U});case"billing":return e.jsx(jg,{has:C,disclose:U,cloudAccount:ee("cloudAccount")});case"updates":return e.jsx(Ng,{remoteActive:r});default:return e.jsxs(e.Fragment,{children:[js.includes(I.sections[0])&&E.has("general")&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ui-button",onClick:K,children:t("settings.simple.looks.back")})}),I.sections.map(W=>e.jsx("section",{"data-settings-block":W,className:"flex scroll-mt-4 flex-col gap-4",children:ee(W)},W))]})}},_=()=>a({type:"toggleAppSettings",open:!1}),ie=(I,C)=>e.jsxs("div",{className:I,children:[e.jsx(mt,{size:15,"aria-hidden":"true",className:"shrink-0 text-ink-secondary"}),e.jsx("input",{"data-settings-search":!0,value:x,onChange:W=>p(W.target.value),onKeyDown:W=>{W.key==="Escape"&&(W.stopPropagation(),x?p(""):_())},placeholder:t("settings.search"),"aria-label":t("settings.searchAria"),className:C})]});if(!i){const I=j?.id==="general"?ne:null,C="flex min-h-8 shrink-0 cursor-pointer items-center rounded-lg px-[9px] py-1.5 text-left text-[13px] leading-[18px] text-ink transition-colors hover:bg-ink/[0.06] motion-reduce:transition-none",W=V=>{ae(null),ue(V)},xe=g?[...X.filter(V=>ks(V,g)).map(V=>({key:V.id,labelKey:V.labelKey,open:()=>W(V.id)})),...(E.has("general")?xg:[]).filter(V=>t(V).toLowerCase().includes(g)).map(V=>({key:V,labelKey:V,open:()=>{K(),F("limits")}}))]:[];return e.jsxs("div",{className:"glass-popup-frame","data-settings-sheet":!0,"data-settings-look":"simple",style:Sn(),onMouseDown:V=>V.stopPropagation(),children:[e.jsx("div",{"aria-hidden":"true",className:"glass-scrim pointer-events-none absolute inset-0"}),e.jsxs("div",{ref:d,role:"dialog","data-look":"settings","aria-modal":"true","aria-labelledby":"app-settings-title",tabIndex:-1,style:{outline:"none"},className:"glass-surface glass-popup animate-pop-in relative flex overflow-hidden rounded-2xl text-ink",children:[e.jsx("span",{id:"app-settings-title",className:"sr-only",children:t("settings.title")}),e.jsx(ol,{}),e.jsxs("nav",{"aria-label":t("settings.title"),className:"glass-rail hidden min-h-0 w-[198px] md:w-[220px] shrink-0 flex-col gap-0.5 overflow-y-auto px-3 py-4 sm:flex",children:[ie("mb-2 flex h-8 shrink-0 items-center gap-2 rounded-lg bg-ink/[0.05] px-[9px] text-[13px] focus-within:ring-2 focus-within:ring-focus/60","w-full min-w-0 bg-transparent text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none"),P.length===0&&L.length===0&&xe.length===0&&se.length===0&&e.jsx("div",{className:"px-[9px] py-3 text-[13px] leading-[18px] text-ink-secondary",children:t("settings.noMatch",{query:x.trim()})}),P.map(V=>{const ke=V.icon,Ie=V===j;return e.jsxs("button",{type:"button","data-settings-page":V.id,onClick:()=>W(V.sections[0]),"aria-current":Ie?"page":void 0,className:z("flex min-h-8 shrink-0 cursor-pointer items-center gap-[9px] rounded-lg px-[9px] py-1 leading-[18px] text-left text-[13px] text-ink transition-colors motion-reduce:transition-none",Ie?"bg-ink/[0.08]":"hover:bg-ink/[0.06]"),children:[e.jsx(ke,{size:15,"aria-hidden":"true",className:"shrink-0"}),e.jsx("span",{className:"min-w-0 whitespace-normal [overflow-wrap:anywhere]",children:t(V.labelKey)})]},V.id)}),L.map(V=>e.jsx("button",{type:"button","data-settings-advanced-only":V,onClick:()=>{p(""),W("general"),F("advanced-mode")},className:C,children:e.jsxs("span",{children:[t(V)," ",e.jsxs("span",{className:"text-ink-secondary",children:["· ",t("settings.simple.advanced")]})]})},V)),xe.map(V=>e.jsx("button",{type:"button","data-settings-more-result":V.key,onClick:()=>{p(""),V.open()},className:C,children:e.jsxs("span",{children:[t(V.labelKey)," ",e.jsxs("span",{className:"text-ink-secondary",children:["· ",t("settings.simple.more.title")]})]})},V.key)),he(C)]}),e.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:[e.jsxs("header",{className:"flex shrink-0 items-center gap-3 py-3 pl-4 pr-14 sm:pb-1.5 sm:pl-12 sm:pt-8",children:[e.jsx(ge,{className:"min-w-0 sm:hidden","aria-label":t("settings.title"),value:j?.id??"",onChange:V=>{p("");const ke=N.find(Ie=>Ie.id===V.target.value);ke&&W(ke.sections[0])},children:N.map(V=>e.jsx("option",{value:V.id,children:t(V.labelKey)},V.id))}),e.jsx("h2",{className:"hidden truncate text-[17px] font-medium leading-6 tracking-[-0.008em] text-ink sm:block",children:I==="looks"?t("settings.simple.page.looks"):I==="more"?t("settings.simple.more.title"):j?t(j.labelKey):null})]}),e.jsx("button",{type:"button",onClick:_,"aria-label":t("settings.close"),title:`${t("settings.close")} (${wn("close-panel")})`,className:"absolute right-5 top-[18px] flex size-8 cursor-pointer items-center justify-center rounded-full text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink motion-reduce:transition-none",children:e.jsx($e,{size:16,"aria-hidden":"true"})}),e.jsxs("div",{ref:m,"data-settings-scroll":!0,className:z("settings-scroll flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-4 pb-10 pt-4 sm:px-8 sm:pb-12 sm:pt-[22px]",qa,"[&_.uppercase]:normal-case [&_.uppercase]:tracking-normal"),children:[e.jsx(ca,{config:n.config}),j?le(j):null]})]})]})]})}return e.jsxs("div",{className:"glass-popup-frame","data-settings-sheet":!0,"data-settings-look":"advanced",style:Sn(),onMouseDown:I=>I.stopPropagation(),children:[e.jsx("div",{"aria-hidden":"true",className:"glass-scrim pointer-events-none absolute inset-0"}),e.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"app-settings-title",tabIndex:-1,className:"glass-surface glass-popup animate-pop-in relative flex overflow-hidden rounded-2xl outline-none",children:[e.jsx("span",{id:"app-settings-title",className:"sr-only",children:t("settings.title")}),e.jsxs("nav",{className:"glass-rail hidden min-h-0 w-[200px] md:w-[220px] shrink-0 flex-col gap-1 overflow-y-auto border-r border-hairline/30 p-3 sm:flex",children:[e.jsx("div",{className:"shrink-0 px-2 py-3 text-[15px] font-semibold text-ink",children:t("settings.title")}),ie("mb-2 mt-1 flex h-8 shrink-0 items-center gap-2 rounded-lg bg-ink/[0.05] px-[9px] text-[13px] focus-within:ring-2 focus-within:ring-focus/60","w-full min-w-0 bg-transparent text-[13px] text-ink placeholder:text-ink-tertiary focus:outline-none"),S.length===0&&e.jsx("div",{className:"px-2.5 py-4 text-[13px] leading-relaxed text-ink-secondary",children:t("settings.noMatch",{query:x.trim()})}),wa.map(I=>{const C=S.filter(W=>W.group===I.id);return C.length===0?null:e.jsxs("div",{role:"group","aria-labelledby":`settings-group-${I.id}`,"data-settings-group":I.id,className:"flex flex-col gap-0.5 pb-2",children:[e.jsx("div",{id:`settings-group-${I.id}`,className:"px-[9px] pb-1 pt-2 text-[12px] font-medium leading-4 text-ink-tertiary",children:t(I.labelKey)}),C.map(({id:W,labelKey:xe,icon:V})=>e.jsxs("button",{"data-settings-section":W,onClick:()=>ue(W),"aria-current":o===W?"page":void 0,className:z("flex min-h-8 shrink-0 cursor-pointer items-center gap-[9px] rounded-lg px-[9px] py-1 leading-[18px] text-left text-[13px] text-ink transition-colors motion-reduce:transition-none",o===W?"bg-ink/[0.08]":"hover:bg-ink/[0.06]"),children:[e.jsx(V,{size:15,className:"shrink-0"}),e.jsx("span",{className:"min-w-0 whitespace-normal [overflow-wrap:anywhere]",children:t(xe)})]},W))]},I.id)}),he("cursor-pointer flex min-h-9 items-center rounded-lg px-2.5 py-2 text-left text-[13px] text-ink transition-colors hover:bg-control/50 motion-reduce:transition-none")]}),e.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-hairline/30 px-3 py-3 sm:pl-9",children:[e.jsx(ge,{className:"min-w-0 sm:hidden","aria-label":t("settings.title"),value:o,onChange:I=>{p(""),ue(I.target.value)},children:wa.map(I=>{const C=k.filter(W=>W.group===I.id);return C.length===0?null:e.jsx("optgroup",{label:t(I.labelKey),children:C.map(({id:W,labelKey:xe})=>e.jsx("option",{value:W,children:t(xe)},W))},I.id)})}),e.jsx("span",{className:"hidden text-[15px] font-semibold text-ink sm:block",children:B?t(B):null}),e.jsx("button",{onClick:_,"aria-label":t("settings.close"),title:`${t("settings.close")} (${wn("close-panel")})`,className:"ui-icon-button cursor-pointer shrink-0 max-md:size-9 max-md:rounded-full max-md:border max-md:border-hairline max-md:bg-card",children:e.jsx($e,{size:18})})]}),e.jsxs("div",{ref:m,className:"flex flex-1 flex-col gap-4 overflow-y-auto px-3 py-4 sm:px-5 sm:pb-5",children:[e.jsx(ca,{config:n.config}),ee(o)]})]})]})]})}export{Ws as SECTIONS,wa as SETTINGS_GROUPS,Sg as SIMPLE_FOLDED,js as SIMPLE_HIDDEN_SECTIONS,wg as SIMPLE_PAGES,eh as SettingsModal,Ig as keySearchResults,Pg as openKeyResult,Eg as revealSettingsBlock,ks as sectionMatches,Cg as simpleSettingsPages};