limixbot 0.3.114 → 0.3.115
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{ActivityPanel-DiLMgzph.js → ActivityPanel-BKVVoPVs.js} +1 -1
- package/dist/assets/{App-Ddh_DeKL.js → App-Bs3xsnrc.js} +8 -8
- package/dist/assets/{AppEventEditor-DxveH-cr.js → AppEventEditor-OAf9a0tt.js} +1 -1
- package/dist/assets/{BotSettingsDialog-DMl_BpJ5.js → BotSettingsDialog-BjXot86a.js} +1 -1
- package/dist/assets/{BrowserPanel-epB3EK-g.js → BrowserPanel-hL-eDB2c.js} +1 -1
- package/dist/assets/{BrowserProfilesManager-BCHI-qVi.js → BrowserProfilesManager-C6T0zWzY.js} +1 -1
- package/dist/assets/{CloudAddDialog-C6MFVLlA.js → CloudAddDialog-DRM9yXbC.js} +1 -1
- package/dist/assets/{ComputerFilesPane--Bw2H6YF.js → ComputerFilesPane-BNu7R0f8.js} +1 -1
- package/dist/assets/{ComputerPanel-C4Q3wifa.js → ComputerPanel-DxKmRVYu.js} +2 -2
- package/dist/assets/{DataPanel-D6IvdVhd.js → DataPanel-DfN9iz0h.js} +1 -1
- package/dist/assets/{GrokMoveDialog-0QYeBKvp.js → GrokMoveDialog-BjiqGVnQ.js} +1 -1
- package/dist/assets/{InspectorPanel-DUqPg7KZ.js → InspectorPanel-DwuollBI.js} +1 -1
- package/dist/assets/{KeyboardShortcutsModal-BaPZ9Yfj.js → KeyboardShortcutsModal-Cqyls2vU.js} +1 -1
- package/dist/assets/{LimixResizeHandles-Cgoym0Xl.js → LimixResizeHandles-Cdd3ZWsF.js} +1 -1
- package/dist/assets/{LiveDesktop-BGy8nqFB.js → LiveDesktop-BqYFy0dM.js} +1 -1
- package/dist/assets/{LocalVmWorkspace-BUhMJYrY.js → LocalVmWorkspace-fc7eYhrx.js} +1 -1
- package/dist/assets/{MacLocalControl-DDgUk1AE.js → MacLocalControl-DZ-mA_P5.js} +1 -1
- package/dist/assets/{MarkdownFilePreview-0simEJp-.js → MarkdownFilePreview-Db67LyUo.js} +1 -1
- package/dist/assets/{NewBotDialog-DHQujvPN.js → NewBotDialog-1eCNcdXB.js} +1 -1
- package/dist/assets/{PhoneAppDialog-Cq-1ZBsB.js → PhoneAppDialog-FAjmm1JH.js} +1 -1
- package/dist/assets/{PluginsPanel-D0mOM94r.js → PluginsPanel-Ch6zuNsG.js} +1 -1
- package/dist/assets/{ProIntroduction-CutUiKNu.js → ProIntroduction-B2GdPHit.js} +1 -1
- package/dist/assets/{RemoteAgentSettingsPanel-DZzqIhvL.js → RemoteAgentSettingsPanel-LNFAibT2.js} +1 -1
- package/dist/assets/{RoomPanel-DVkmk2hl.js → RoomPanel-Cx3DTlAR.js} +1 -1
- package/dist/assets/{RoutinesPage-C3w9qdbF.js → RoutinesPage-Cxwi6eIR.js} +1 -1
- package/dist/assets/SettingsModal-Dyw-u2wY.js +19 -0
- package/dist/assets/{ShareTeamDialog-CIvnf9Ql.js → ShareTeamDialog-DCdKihAm.js} +1 -1
- package/dist/assets/{SignedInSites-BE6eaSJq.js → SignedInSites-DH7N9tUA.js} +1 -1
- package/dist/assets/{TeamLibraryPanel-BIcy8Iyf.js → TeamLibraryPanel-CbQaWAWx.js} +1 -1
- package/dist/assets/{TeamMapPage-DnXg1zmn.js → TeamMapPage-DoYg4ueL.js} +1 -1
- package/dist/assets/{TriggersPage-D9sr9f5M.js → TriggersPage-CtDhsC18.js} +1 -1
- package/dist/assets/{VisibilitySection-j0PdMnH3.js → VisibilitySection-DmAqf_a9.js} +1 -1
- package/dist/assets/{WebhookTrigger-ByvIgnn0.js → WebhookTrigger-DIkM9UMJ.js} +1 -1
- package/dist/assets/{WorksOnGrid-D__HSyhm.js → WorksOnGrid-BXPjyVfb.js} +1 -1
- package/dist/assets/{core-DnKXzdi1.js → core-CLmWJmRN.js} +1 -1
- package/dist/assets/{import-name-DEPg2ht3.js → import-name-CuQ-o1MN.js} +1 -1
- package/dist/assets/{index-B48L2b4D.js → index-B4GUPRYB.js} +1 -1
- package/dist/assets/{index-BIFgmFd6.js → index-CLQ_hYWY.js} +2 -2
- package/dist/assets/{mcp-servers-CIoA0Z8X.js → mcp-servers-CE2IPhL7.js} +1 -1
- package/dist/assets/{new-bot-DB8EcyfW.js → new-bot-biSOJm6z.js} +1 -1
- package/dist/assets/{org-library-C-mDWISC.js → org-library-4LsB5uzZ.js} +1 -1
- package/dist/assets/{package-format-CYXsEP2B.js → package-format-CBEJWXeV.js} +1 -1
- package/dist/assets/{remote-desktop-panel-BTKO8ICQ.js → remote-desktop-panel-BUZzS8Qz.js} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/index.js +26 -25
- package/dist-server/package.json +1 -1
- package/dist-server/server/bot-channels/zalo-media.js +4 -4
- package/dist-server/server/limix-skill-hub.js +27 -3
- package/package.json +1 -1
- package/dist/assets/SettingsModal-Dokjrp1d.js +0 -19
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{c as mt,j as e,t,r as l,a as z,S as pt,d as fe,p as Cs,k as Lt,ad as Wr,X as $e,i as Es,C as Gr,ae as Ia,L as Ct,aO as Vr,aZ as qr,a8 as Jr,R as Xr,l as Me,a_ as Yr,a$ as Qr,ab as Zr,b0 as el,b1 as Bt,ax as sn,y as tl,au as sl,z as nn,ay as Pa,b as nl,b2 as al,B as il,b3 as rl,A as ll,aD as ol,b4 as an,aC as cl,b5 as dl,b6 as rn,b7 as ln,b8 as on,b9 as ul,ba as ml,ah as pl,bb as xl}from"./styles-DaC7RuGF.js";import{L as hl}from"./LimixResizeHandles-Cdd3ZWsF.js";import{L as Y,P as Ce,v as xt,E as gl,ah as fl,ai as bl,$ as yl,W as vl,K as jl,l as As,C as Ta,B as Ot,aj as kl,ak as Nl,al as wl,d as Ra,r as Sl,h as cn,g as dn,i as Cl,am as El,an as Al,ao as Il,ap as Gt,A as Pl,p as Tl,aq as Rl,ar as La,as as Ll,R as Ba,c as Bl,at as Ol,au as Ml,M as zl,ab as Ul,av as Fl,aw as cs,b as Dl,t as _l,U as $l,N as Vt,f as Kl}from"./PlacesRail-3RYT-fm8.js";import{bY as Mt,u as G,S as me,j as O,h6 as Be,T as Ee,dA as Qe,w as pe,cT as Hl,cP as Oa,eR as Ze,h7 as Wl,Y as Oe,eP as Gl,eQ as Vl,h8 as ds,h9 as lt,ha as Ma,hb as Is,hc as Ps,hd as ql,e8 as un,he as za,hf as Ua,hg as Jl,hh as Xl,hi as Yl,a2 as ue,c7 as Z,eg as us,eO as Ql,hj as Fa,hk as wt,hl as zt,hm as Da,hn as _a,ho as Le,hp as _e,hq as Zl,hr as eo,hs as to,ht as so,hu as no,hv as $a,hw as ao,hx as io,hy as Ka,hz as Ha,hA as be,hB as ye,dw as mn,hC as Ut,hD as ro,hE as lo,hF as oo,hG as co,hH as uo,g$ as Wa,bu as mo,x as L,hI as rt,R as po,dP as xo,Q as Ga,hJ as Va,hK as ho,aQ as Et,fA as ct,fB as dt,hL as go,K as Ye,r as fo,cs as bo,gQ as yo,hM as Ft,hN as qa,hO as vo,hP as jo,hQ as pn,hR as Ja,hS as Dt,hT as Xa,hU as ko,hV as No,hW as wo,hX as So,G as Co,hY as Eo,hZ as ut,en as _t,h_ as Ao,h$ as Io,i0 as Po,i1 as To,fI as Ro,i2 as xn,i3 as Lo,i4 as Bo,E as Oo,i5 as hn,i6 as Mo,el as Ya,i7 as zo,i8 as Uo,i9 as Fo,ia as Do,ib as _o,ic as $o,id as Qa,ie as Ko,ig as Ho,ih as Wo,ii as Go,ij as Vo,ik as qo,il as Za,im as Jo,io as Xo,dV as Yo,ip as Qo,eh as Zo,iq as ec,ir as tc,is as sc,it as nc,iu as gn,iv as ac,iw as fn,l as ic,ix as rc,iy as lc,iz as oc,bR as cc,iA as dc,iB as uc,iC as mc,iD as pc,iE as ei,fy as nt,iF as xc,fx as hc,iG as ti,iH as gc,iI as si,iJ as fc,iK as bn,i as bc,iL as ms,iM as yn,iN as vn,iO as yc,iP as vc,iQ as jc,iR as kc,iS as Nc,iT as wc,iU as Sc,iV as Cc,iW as Ec,iX as Ts,iY as Ac,fo as ni,h as Ic,iZ as Pc,i_ as Tc,i$ as jn,j0 as Rc,j1 as Lc,j2 as kn,j3 as Bc,b9 as Oc,j4 as Mc,j5 as zc,j6 as Uc,bJ as Fc,j7 as Dc,j8 as Nn,j9 as _c,bE as Rs,ja as $c,bF as Kc,jb as Hc,jc as Wc,jd as Gc,je as Vc,jf as qc,jg as Jc,jh as Xc,ji as Yc,jj as wn,gC as Qc,jk as Zc,jl as ed,jm as ai,jn as td,jo as sd,jp as nd,jq as ii,jr as ri,js as li,jt as ad,ju as id,jv as rd,dc as ld,I as od,jw as oi,eJ as cd,c5 as Sn,jx as Cn,f6 as En,e7 as dd,_ as ud,az as md,jy as pd,jz as xd,jA as hd}from"./App-Bs3xsnrc.js";import{C as Ls,a as gd,R as Se}from"./MenuMotion-READmdk4.js";import{l as ci,M as fd,w as An}from"./MacLocalControl-DZ-mA_P5.js";import{Q as di}from"./VisibilitySection-DmAqf_a9.js";import{r as ui,a as mi,b as bd,i as yd,C as vd,s as pi,c as jd,d as kd,w as Nd,t as wd,T as Sd,l as Bs,e as In,f as Cd,g as Ed}from"./index-CLQ_hYWY.js";import{c as Ad,A as Id,w as Pd,d as Td,e as Pn}from"./activity-Cy9rKER-.js";import{U as xi,R as hi,B as gi,S as fi,a as bi,D as yi,T as vi,C as ji,L as ps,b as ki,F as Ni,A as xs,E as Rd,c as Ld,P as Bd,d as Od,e as Md,N as zd}from"./NewBotDialog-1eCNcdXB.js";import{a as Ud,u as Fd,C as wi,b as Dd,P as _d}from"./ProIntroduction-B2GdPHit.js";import{M as Si}from"./monitor-Ehduuiym.js";import{C as $d}from"./coins-DTHSSVDb.js";import"./org-library-4LsB5uzZ.js";import"./package-format-CBEJWXeV.js";import"./mcp-servers-CE2IPhL7.js";import"./WorksOnGrid-BXPjyVfb.js";import"./new-bot-biSOJm6z.js";import"./RoutinesPage-Cxwi6eIR.js";import"./remote-desktop-DDRRx8uY.js";import"./team-share-Coietrtx.js";import"./BrowserProfilesManager-C6T0zWzY.js";import"./SignedInSites-DH7N9tUA.js";const Kd=[["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"}]],Hd=mt("cloud-download",Kd);const Wd=[["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"}]],Gd=mt("palette",Wd);const Vd=[["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"}]],qd=mt("scroll-text",Vd);const Jd=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Xd=mt("terminal",Jd);const Yd=[["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=mt("unplug",Yd);function Os(s){return s.filter(n=>n.driverKind==="openai-compat"&&n.instanceId.startsWith("openai-compat-"))}function je({children:s,note:n="settings.adminOnly.change"}){return Mt()===!1?e.jsx("p",{"data-admin-only":!0,className:"text-[13px] text-ink-secondary",children:t(n)}):s}function Ms(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 Zd(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 eu(){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),O("/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 tu="https://api.xingchiapi.com/v1",su={claude:{url:"https://api.anthropic.com",model:"deepseek-chat"},codex:{url:"https://api.openai.com/v1",model:""}},bt=z(Be,"font-sans"),Tn={name:"",url:"",token:"",model:""},nu=s=>({name:s.displayName,url:(s.claudeEndpoint??s.codexEndpoint)?.baseUrl??"",token:"",model:(s.claudeEndpoint??s.codexEndpoint)?.model??""});function zs({instance:s,engine:n,onDone:a,xingchi:i=!1}){const{dispatch:r}=G(),c=su[n],[o,d]=l.useState(s?nu(s):i?{...Tn,name:"Xingchi (Codex Responses)",url:tu}:Tn),[m,u]=l.useState(!1),[x,p]=l.useState(null),h=b=>({value:o[b],onChange:g=>d(k=>({...k,[b]:g.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 g=s?await O(`/api/instances/${encodeURIComponent(s.instanceId)}/${n}-endpoint`,{method:"PATCH",body:JSON.stringify(b)}):await O(`/api/instances/${n}-endpoint`,{method:"POST",body:JSON.stringify(b)});Array.isArray(g.instances)&&r({type:"instances",instances:g.instances}),a()}catch(g){const k=g instanceof Error?g.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",{...h("name"),maxLength:80,autoFocus:!0,"aria-label":t("claudeEndpoints.name"),className:bt})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeEndpoints.baseUrl"),e.jsx("input",{...h("url"),readOnly:i||s?.codexEndpoint?.profile==="xingchi",type:"url",maxLength:2048,placeholder:c.url,"aria-label":t("claudeEndpoints.baseUrl"),className:z(bt,"font-mono")})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t("claudeEndpoints.token"),e.jsx("input",{...h("token"),type:"password",maxLength:4096,autoComplete:"off","aria-label":t("claudeEndpoints.token"),className:z(bt,"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",{...h("model"),maxLength:160,placeholder:c.model,"aria-label":t("claudeEndpoints.model"),className:z(bt,"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(Y,{size:13,className:"animate-spin"}),t("common.save")]})]})]})}function Ci({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),h=a.bots.filter(b=>b.modelSelection.instanceId===s.instanceId||b.fallback?.some(g=>g.instanceId===s.instanceId)||b.tasks?.some(g=>g.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 O(`/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(zs,{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||h>0,onClick:()=>d(!0),title:h>0?t("accounts.inUse",{count:String(h)}):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(Y,{size:14,className:"animate-spin"}):e.jsx(Ee,{size:14}),t("common.delete")]})]}),h>0&&e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:t("accounts.inUse",{count:String(h)})}),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 Ei({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(Ci,{instance:c,showName:!0})},c.instanceId))}),i?e.jsx(zs,{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(Ce,{size:14}),t("claudeEndpoints.add")]})]})}function qt(){return e.jsx(Ei,{engine:"claude"})}function St(){return e.jsx(Ei,{engine:"codex"})}function Jt(s){return[...new Set(s.split(/[,,、\s]+/).map(n=>n.trim()).filter(Boolean))]}const De=z(Be,"font-sans"),au=[5,10,20,30,60],Xt="ui-icon-button shrink-0 hover:text-ink",Yt={name:"Google Gemini",url:"https://generativelanguage.googleapis.com/v1beta/openai"},hs={count:64,length:200},iu=s=>s.length<=hs.count&&s.every(n=>n.length<=hs.length),gs=(s,n)=>O(`/api/instances/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(n)});function Ai({server:s,disabled:n,onPick:a}){return e.jsxs(pe,{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([...au,...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 ru(){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),gs(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(Ai,{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 lu(){const{state:s}=G();return e.jsxs(e.Fragment,{children:[e.jsx(ou,{servers:Os(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(St,{})]})]})}function ou({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,h]=l.useState(null),[f,y]=l.useState(null),[b,g]=l.useState(null),[k,C]=l.useState(""),N=!!(i.trim()&&c.trim()&&d.trim()),w=(v,B,j,A)=>{p||(h(v),y(null),B().then(async({instances:I})=>{Array.isArray(I)?n({type:"instances",instances:I}):await a({reportErrors:!0}),j?.()}).catch(I=>y({text:I.message||t("apiInstances.failed"),at:A})).finally(()=>h(null)))},P=()=>N&&w("add",()=>O("/api/instances/openai-compat",{method:"POST",body:JSON.stringify({displayName:i.trim(),url:c.trim(),key:d.trim(),...Jt(u).length?{models:Jt(u)}:{}})}).then(v=>(Ze("custom_endpoint","settings","unverified"),v),v=>{throw Ze("custom_endpoint","settings","error"),v}),()=>{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(v=>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:v.displayName}),v.url&&e.jsx("div",{className:"truncate font-mono text-[11px] text-ink-secondary",children:v.url})]}),e.jsx(Ai,{server:v,disabled:p!==null,onPick:B=>w("other",()=>gs(v.instanceId,{replyWaitMinutes:B}))}),e.jsx("button",{type:"button",onClick:()=>{C((v.managedModels??[]).join(", ")),g(b===v.instanceId?null:v.instanceId),y(null)},disabled:p!==null,"aria-label":t("apiInstances.editModels",{name:v.displayName}),"aria-expanded":b===v.instanceId,title:t("apiInstances.editModels",{name:v.displayName}),className:Xt,children:e.jsx(Hl,{size:13,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>w("other",()=>O(`/api/instances/${encodeURIComponent(v.instanceId)}/refresh-models`,{method:"POST"})),disabled:p!==null,"aria-label":t("apiInstances.refreshModels",{name:v.displayName}),title:t("apiInstances.refreshModels",{name:v.displayName}),className:Xt,children:e.jsx(Oa,{size:13,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>w("other",()=>O(`/api/instances/${encodeURIComponent(v.instanceId)}`,{method:"DELETE"})),disabled:p!==null,"aria-label":t("apiInstances.remove",{name:v.displayName}),title:t("apiInstances.remove",{name:v.displayName}),className:`${Xt} hover:bg-danger/10 hover:text-danger`,children:e.jsx(Ee,{size:13,"aria-hidden":"true"})})]}),b===v.instanceId&&e.jsxs("div",{className:"mt-1.5 flex flex-col gap-1.5",children:[e.jsx("input",{value:k,onChange:B=>C(B.target.value),placeholder:t("apiInstances.models"),"aria-label":t("apiInstances.modelsFor",{name:v.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=Jt(k);if(!iu(B)){y({text:t("apiInstances.modelsLimit",hs),at:v.instanceId});return}w("other",()=>gs(v.instanceId,{models:B}),()=>g(null),v.instanceId)},disabled:p!==null,className:"ui-button",children:t("common.save")}),e.jsx("button",{type:"button",onClick:()=>g(null),disabled:p!==null,className:"ui-button",children:t("common.cancel")})]}),f?.at===v.instanceId&&e.jsx("div",{role:"alert",className:"text-[12px] leading-4 text-danger",children:f.text})]})]},v.instanceId)),e.jsxs("div",{className:"mt-2 flex flex-col gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>{r(Yt.name),o(Yt.url)},disabled:p!==null,className:"ui-button self-start",children:t("apiInstances.geminiPreset")}),c.trim()===Yt.url&&e.jsx("p",{className:"text-[12px] leading-4 text-ink-secondary",children:t("apiInstances.geminiKeyHint")}),e.jsx("input",{value:i,onChange:v=>r(v.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:v=>o(v.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:v=>m(v.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:v=>x(v.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||!N,className:"ui-button self-start",children:[p==="add"?e.jsx(Y,{size:12,"aria-hidden":"true",className:"animate-spin"}):e.jsx(Ce,{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 cu="lm-studio";function du(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 uu({heading:s=!0}={}){const{state:n,dispatch:a,refreshInstances:i}=G(),r=Os(n.instances),[c,o]=l.useState("1234"),[d,m]=l.useState(""),[u,x]=l.useState(!1),[p,h]=l.useState(null),f=du(c),y=!!(f&&r.some(g=>g.url===f)),b=()=>{u||!f||y||(x(!0),h(null),O("/api/instances/openai-compat",{method:"POST",body:JSON.stringify({displayName:"LM Studio",url:f,key:d.trim()||cu,catalog:"lmstudio"})}).then(async g=>{Ze("custom_endpoint","settings","unverified"),Array.isArray(g.instances)?a({type:"instances",instances:g.instances}):await i({reportErrors:!0}),m("")},g=>{Ze("custom_endpoint","settings","error"),h(g instanceof Error&&g.message?g.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:g=>o(g.target.value),"aria-label":t("lmStudio.port"),spellCheck:!1,disabled:u,className:z(De,"font-mono")})]}),e.jsx("input",{type:"password",value:d,onChange:g=>m(g.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(Y,{size:12,"aria-hidden":"true",className:"animate-spin"}):e.jsx(Ce,{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 mu="ollama",pu="https://ollama.com/download",xu=s=>`${s.replace(/\/+$/,"")}/v1`,hu=(s,n)=>s?.trim().replace(/\/+$/,"")===n;function gu({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),[h,f]=l.useState(null),y=l.useRef(0),b=l.useRef(!1),g=l.useCallback(P=>{const v=++y.current;u(!0),f(null),O(`/api/instances/ollama${P?`?url=${encodeURIComponent(P)}`:""}`).then(B=>{v===y.current&&d(B.status)}).catch(B=>{v===y.current&&(d(null),f(B.message||t("apiInstances.failed")))}).finally(()=>{v===y.current&&u(!1)})},[]);l.useEffect(()=>{!s||b.current||(b.current=!0,g(""))},[s,g]);const k=o?xu(o.url):null,C=!!(k&&(Os(n.instances).some(P=>P.url===k)||hu(n.config?.openaiCompat?.url,k))),N=!!(k&&!C&&!x&&!m&&(o?.state==="ready"||o?.state==="no-models")),w=()=>{!N||!k||(p(!0),f(null),O("/api/instances/openai-compat",{method:"POST",body:JSON.stringify({displayName:"Ollama",url:k,key:mu,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(Y,{size:12,className:"animate-spin","aria-hidden":"true"}),t("ollama.checking")]}):o&&e.jsx(Wl,{status:o})}),!m&&o?.state==="not-running"&&e.jsx("a",{href:pu,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"&&g(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:w,disabled:!N,className:"ui-button",children:[x?e.jsx(Y,{size:12,"aria-hidden":"true",className:"animate-spin"}):e.jsx(Ce,{size:12,"aria-hidden":"true"}),x?t("ollama.adding"):t("ollama.add")]}),e.jsxs("button",{type:"button",onClick:()=>g(r.trim()),disabled:m||x,className:"ui-button",children:[e.jsx(Oa,{size:12,"aria-hidden":"true"}),t("common.checkAgain")]})]}),C&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("ollama.added")})]}),h&&e.jsx("div",{role:"alert",className:"mt-1 text-[12px] text-danger",children:h})]})}function fu(){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,h]=l.useState(null),f=d||u!==null,y=(k,C)=>O("/api/config",{method:"PUT",body:JSON.stringify({opencodeGo:{providerKeys:{[k]:C}}})}).then(N=>n({type:"configStatus",config:N})),b=()=>{const k=i.trim().toUpperCase(),C=Gl(c);if(!(f||!k||!C)){if(!Vl(C)){h(t("keys.notAKey"));return}m(!0),h(null),y(k,C).then(()=>{r(""),o("")}).catch(N=>h(N.message)).finally(()=>m(!1))}},g=k=>{f||(x(k),h(null),y(k,"").catch(C=>h(C.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,C)=>C===0?[k]:[e.jsx("code",{className:"font-mono",children:"opencode auth login"},C),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:()=>g(k),disabled:f,"aria-label":t("keys.opencode.otherProviders.removeAria",{name:k}),className:"ui-button shrink-0",children:u===k?e.jsx(Y,{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=>{h(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=>{h(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(Y,{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 bu(){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),O("/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 yu(){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),O("/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(Y,{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 vu(){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),O("/api/config",{method:"PUT",body:JSON.stringify({openaiCompat:{url:i.trim()}})}).then(h=>n({type:"configStatus",config:h})).catch(h=>m(h.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:h=>r(h.target.value),onBlur:p,onKeyDown:h=>h.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(Y,{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 ju="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",ku=1600,Nu={opencodeProviders:()=>e.jsx(fu,{}),ollama:s=>e.jsx(gu,{visible:s}),lmStudio:()=>e.jsx(uu,{heading:!1}),vps:()=>e.jsx(yu,{})},wu={anthropic:()=>e.jsx(bu,{}),openaiCompat:()=>e.jsxs(e.Fragment,{children:[e.jsx(vu,{}),e.jsx(ru,{}),e.jsx(lu,{})]}),box:()=>e.jsx(Yl,{}),liveKey:()=>e.jsx(Xl,{})};function Ii(s,n){if(s.kind==="uses")return!1;const a=Ps(s,n);return a.configured||a.included===!0}function Su({entry:s,visible:n}){const{state:a}=G(),i=l.useId(),c=Ps(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:za,children:[e.jsx(Ua,{entry:s,status:c,titleId:i}),e.jsx("div",{className:"flex flex-col gap-2 pl-8",children:Nu[s.id]?.(n)})]})}function Cu({entry:s}){const{state:n,dispatch:a}=G(),i=l.useId(),r=s.opens,c=Ps(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:za,children:[e.jsx(Ua,{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(Jl,{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 Eu({entry:s,visible:n}){return s.kind==="uses"&&s.uses?e.jsx(un,{id:s.uses,row:s.id}):s.kind==="panel"?e.jsx(Su,{entry:s,visible:n}):s.kind==="elsewhere"?e.jsx(Cu,{entry:s}):e.jsx(un,{id:s.id,children:wu[s.id]?.()})}function Au({id:s,rows:n,open:a,onToggle:i}){const{state:r}=G(),c=ds.find(u=>u.id===s),o=l.useId(),d=l.useId(),m=n.filter(u=>Ii(u,r.config)).length;return e.jsxs("section",{"data-keys-section":s,"aria-labelledby":o,className:ju,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(Ls,{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(Eu,{entry:u,visible:a},u.id)),s==="voice"&&e.jsx(eu,{})]})]})}function Iu(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=Zd(i);return r&&Ms(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"),ku)),!0}function Pu(){const{state:s}=G(),[n,a]=l.useState(""),[i,r]=l.useState(()=>new Set(ds.filter(p=>p.id==="ai"||lt.some(h=>h.section===p.id&&Ii(h,s.config))).map(p=>p.id))),c=l.useRef(null),o=Ma(),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 h=0,f=0;const y=()=>{Iu(c.current,o,p)||++f>60?ql(o):h=window.requestAnimationFrame(y)};return h=window.requestAnimationFrame(y),()=>window.cancelAnimationFrame(h)},[o]);const m=s.config?.live?.provider==="azure",u=lt.filter(p=>Is(p,d)&&!(m&&p.id==="liveCalls")),x=ds.flatMap(p=>{const h=u.filter(f=>f.section===p.id);return h.length>0?[{id:p.id,rows:h}]:[]});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(pt,{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:h})=>e.jsx(Au,{id:p,rows:h,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 Pi({simple:s=!1}){return null}function Ti({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(ue,{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 Tu(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 Ri(){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(h=>{p&&a(h)}).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(pe,{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(ue,{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 Qt=s=>s===0||s>=1024*1024?`${Math.round(s/(1024*1024))} MB`:`${Math.ceil(s/1024)} KB`;function Li(){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 O("/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 O("/api/attachment-storage",{method:"POST"});n(u);const x=t("settings.attachments.cleared",{count:u.removed,freed:Qt(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(ue,{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:Qt(s.usedBytes),max:Qt(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 Bi({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(ue,{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 Ru="https://dash.cloudflare.com/profile/api-tokens",Lu=/^[0-9a-f]{32}$/i,Rn="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 Bu({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),[h,f]=l.useState(!1),[y,b]=l.useState(null),[g,k]=l.useState(null),C=(o??c).trim(),N=m.trim(),w=!N&&r&&o===null,P=o!==null&&C!==c,v=A=>a({type:"configStatus",config:A}),B=async()=>{if(!(x||!N&&!r&&!P)){if(N&&!Lu.test(C))return b(t("decider.workersAi.needsAccount"));p(!0),b(null),k(null);try{(P||N&&!c)&&v(await O("/api/config",{method:"PUT",body:JSON.stringify({decider:{workersAiAccountId:C}})})),(N||w)&&v(window.ogb?.setCredential?await window.ogb.setCredential("workersAiToken",N):await O("/api/config",{method:"PUT",body:JSON.stringify({decider:{workersAiToken:N}})})),u(""),d(null)}catch(A){b(A instanceof Error?A.message:String(A))}finally{p(!1)}}},j=async()=>{if(!(h||x||!N&&!r)){f(!0),k(null),b(null);try{const A=await O("/api/decider/test",{method:"POST",body:JSON.stringify({provider:"workersai",...N?{key:N,accountId:C}:{}})}),I=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)}),...I].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(Z,{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:Rn}),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:Rn}),e.jsx("button",{type:"button","data-testid":"workers-ai-save",onClick:()=>{B()},disabled:x||!N&&!r&&!P,title:w?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",w?"text-danger":"text-ink"),children:x?e.jsx(Y,{size:13,className:"animate-spin"}):w?t("keys.clear"):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:13}),t("common.save")]})}),e.jsx("button",{type:"button","data-testid":"workers-ai-test",onClick:()=>{j()},disabled:h||x||!N&&!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:h?t("keys.testing"):t("keys.test")})]})]}),y&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:y}),g&&e.jsx("p",{role:"status",className:z("mt-1 text-[12px]",g.ok?"text-success":"text-danger"),children:g.text}),e.jsxs("a",{href:Ru,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(xt,{size:11,"aria-hidden":"true"})]})]})}const Ou={jev:"https://typesafe.ai",openrouter:"https://openrouter.ai/keys"},Mu=1500,Us={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"},Ln={rejected:"decider.included.error.rejected",rate_limited:"decider.included.error.limited"},zu={...Us,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"},Uu={...Us,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"},Zt={jev:"decider.status.byJev",workersai:"decider.status.byWorkersAi",openrouter:"decider.status.byOpenRouter"};function Fu(s){const n=s?.decider,a=s?.helpers?.extraction,i=n?.configured?n.included?t("decider.status.byCloud"):t(Zt[n.provider]??Zt.jev):t("decider.status.notSetUp"),r=a?.provider?a.included?t("decider.status.byCloud"):t(Zt[a.provider]):t("decider.status.notSetUp");return t("decider.status.line",{decisions:i,extraction:r})}function Bn(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=Uu[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=zu[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&&Ln[s.reason])return t(Ln[s.reason]);if(s.reason==="http_error")return t("decider.error.http",{status:String(s.status??"?")});const i=Us[s.reason];return i?t(i):t("decider.error.other")}const Du=["decider.jobs.browserClicks","decider.jobs.toolSelection","decider.jobs.placement"];function _u(){const{state:s,dispatch:n}=G(),a=s.config?.decider,i=a?.provider==="openrouter"?"openrouter":"jev",r=i==="openrouter",c=a?.configured??!1,o=c&&a?.included===!0,d=r&&c&&a?.keySource==="shared",m=r&&a?.sharedKey===!0,u=c&&!o&&!d,x=a?.enabled??!1,p=a?.jobs.roomRouting??!0,[h,f]=l.useState(""),[y,b]=l.useState(!1),[g,k]=l.useState(!1),[C,N]=l.useState(!1),[w,P]=l.useState(null),[v,B]=l.useState(null),[j,A]=l.useState(null),I=h.trim(),H=!I&&u,D=!r||o?null:d?"decider.openrouter.status.sharedHint":c?m?"decider.openrouter.status.ownFallbackHint":null:"decider.openrouter.status.notConnectedHint",V=T=>n({type:"configStatus",config:T}),$=async T=>{if(!g){k(!0),P(null);try{V(await O("/api/config",{method:"PUT",body:JSON.stringify({decider:T})}))}catch(U){P(U instanceof Error?U.message:String(U))}finally{k(!1)}}};l.useEffect(()=>{if(!r||j)return;let T=!1;return O("/api/decider/models").then(U=>{T||A(U)},()=>{}),()=>{T=!0}},[r,j]);const se=T=>{f(""),B(null),$(T)},ne=async()=>{if(!(y||!I&&!u)){b(!0),P(null),B(null);try{const T=window.ogb?.setCredential?await window.ogb.setCredential(r?"openrouterDeciderKey":"jevApiKey",I):await O("/api/config",{method:"PUT",body:JSON.stringify({decider:{[r?"openrouterKey":"key"]:I}})});V(T),f("")}catch(T){P(T instanceof Error?T.message:String(T))}finally{b(!1)}}},ce=async()=>{if(C||y||!I&&!c)return;N(!0),B(null),P(null);const T=!I&&o,U=!I&&d;try{const Q=await O("/api/decider/test",{method:"POST",body:JSON.stringify(I?{key:I}:{})});B(Q.ok?{ok:!0,text:r?[t(U?"decider.openrouter.test.okShared":"decider.openrouter.test.ok",{ms:String(Q.latencyMs)}),...Q.latencyMs>Mu?[t("decider.test.slow")]:[]].join(" "):t("decider.test.ok",{ms:String(Q.latencyMs)})}:{ok:!1,text:Bn(Q,T,i)})}catch(Q){B({ok:!1,text:Q instanceof Error?Q.message:String(Q)})}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:Fu(s.config)})]}),e.jsx(Bu,{failureText:T=>Bn(T,!1,"workersai")}),e.jsx(ue,{title:t("decider.provider.label"),children:e.jsxs(pe,{className:"w-48","data-testid":"decider-provider",value:i,onChange:T=>se({provider:T.target.value==="openrouter"?"openrouter":"jev"}),disabled:g||!s.config,"aria-label":t("decider.provider.label"),children:[e.jsx("option",{value:"jev",children:t("decider.provider.jev")}),e.jsx("option",{value:"openrouter",children:t("decider.provider.openrouter")})]})}),r&&e.jsx(ue,{title:t("decider.model.label"),subtitle:j?.source==="builtin"?t("decider.model.builtinNote"):void 0,children:e.jsxs(pe,{className:"w-64 max-w-full","data-testid":"decider-model",value:a?.model??"",onChange:T=>se({openrouterModel:T.target.value,openrouterApi:j?.models.find(U=>U.id===T.target.value)?.api??"chat"}),disabled:g,"aria-label":t("decider.model.label"),children:[a?.model&&!j?.models.some(T=>T.id===a.model)&&e.jsx("option",{value:a.model,children:a.model}),["recommended","more"].map(T=>{const U=j?.models.filter(Q=>Q.group===T)??[];return U.length>0&&e.jsx("optgroup",{label:t(T==="recommended"?"decider.model.recommended":"decider.model.more"),children:U.map(Q=>e.jsx("option",{value:Q.id,children:Q.name},Q.id))},T)})]})}),e.jsx(ue,{title:t(r?"decider.openrouter.master":"decider.master"),subtitle:c?void 0:t(r?"decider.masterNeedsKey.openrouter":"decider.masterNeedsKey"),children:e.jsx(me,{"data-testid":"decider-master","aria-label":t(r?"decider.openrouter.master":"decider.master"),checked:x,disabled:!c||g||!s.config,onClick:()=>{$({enabled:!x})},className:"cursor-pointer"})}),e.jsxs(Z,{title:t(r?"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",c?"bg-success":"bg-raised-hover")}),e.jsx("span",{className:c?"text-success":void 0,children:o?t("keys.includedWithCloudPro"):d?t("decider.openrouter.status.shared"):c?t(m?"decider.openrouter.status.own":"decider.status.connected"):t("decider.status.notConnected")})]}),D&&e.jsxs("p",{className:"mb-2 text-[12px] leading-relaxed text-ink-secondary",children:[t(D),!u&&e.jsxs(e.Fragment,{children:[" ",e.jsx("button",{type:"button","data-testid":"decider-manage-keys",onClick:()=>n(us("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:h,onChange:T=>{B(null),P(null),f(T.target.value)},onKeyDown:T=>T.key==="Enter"&&void ne(),disabled:y,placeholder:u?t("keys.replace"):t(d?"decider.openrouter.key.overridePlaceholder":r?"decider.openrouter.key.placeholder":"decider.key.placeholder"),"aria-label":t(r?"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:()=>{ne()},disabled:y||!I&&!u,title:H?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",H?"text-danger":"text-ink"),children:y?e.jsx(Y,{size:13,className:"animate-spin"}):H?t("keys.clear"):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:13}),t("common.save")]})}),e.jsx("button",{type:"button","data-testid":"decider-test",onClick:()=>{ce()},disabled:C||y||!I&&!c,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:C?t("keys.testing"):t("keys.test")})]}),w&&e.jsx("p",{role:"alert",className:"mt-1 text-[12px] text-danger",children:w}),v&&e.jsx("p",{role:"status",className:z("mt-1 text-[12px]",v.ok?"text-success":"text-danger"),children:v.text}),!d&&e.jsxs("a",{href:Ou[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(r?"decider.openrouter.key.getKey":"decider.key.getKey"),e.jsx(xt,{size:11,"aria-hidden":"true"})]})]}),e.jsx(Z,{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:x&&p,disabled:!x||g,onClick:()=>{$({jobs:{roomRouting:!p}})},className:"cursor-pointer"})]}),Du.map(T=>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(T)}),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")})]},T))]})})]})}const $u=["openai","xai","gemini","openrouter","custom"],Ku=4,Oi={openai:"gpt-image-2",xai:"grok-imagine-image-2.0",gemini:"gemini-2.5-flash-image",openrouter:"google/gemini-2.5-flash-image",custom:""},Hu={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 Wu(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 At={openai:"OpenAI",xai:"Grok (xAI)",gemini:"Gemini",openrouter:"OpenRouter",custom:"Custom"},Gu={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"}},Vu={xai:{label:"imageGen.key.xai",note:"imageGen.key.sharedXai"},openrouter:{label:"imageGen.key.openrouter",note:"imageGen.key.sharedOpenrouter"}},On={openai:"https://platform.openai.com/api-keys",gemini:"https://aistudio.google.com/apikey",xai:"https://console.x.ai",openrouter:"https://openrouter.ai/keys"},fs="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",It="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",es="\0other";function qu(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 Ju(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 Xu(){const{state:s,dispatch:n}=G(),a=s.config?.imageGen,i=a?.primary??{provider:a?.provider??"openai",model:a?.model??Oi.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 O("/api/images/openrouter-models").then(g=>{b||x(Array.isArray(g?.models)?g:{source:"builtin",models:[]})},()=>{b||x({source:"builtin",models:[]})}),()=>{b=!0}},[p,u]);const h=async b=>{o(!0),m(null);try{const g=await O("/api/config",{method:"PUT",body:JSON.stringify(b)});n({type:"configStatus",config:g})}catch(g){m(g instanceof Error?g.message:String(g))}finally{o(!1)}},f=(b,g)=>{if(b==="fallback"&&g==="")return void h({imageGen:{fallback:null}});const k=g,C=b==="primary"&&r?.provider===k;h({imageGen:{[b]:{provider:k},...C?{fallback:null}:{}}})},y=[i.provider,...r?[r.provider]:[]].filter((b,g,k)=>k.indexOf(b)===g);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:At[i.provider]}):t("imageGen.status.backupOnly",{provider:At[r.provider]}):t("imageGen.status.notReady")]})]}),e.jsx(Yu,{disabled:c}),e.jsx(Mn,{slot:"primary",provider:i.provider,model:i.model,configured:i.configured,openrouterModels:u,disabled:c||!s.config,onProvider:f,onModel:b=>{h({imageGen:{primary:{provider:i.provider,model:b}}})}}),e.jsx(Mn,{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 h({imageGen:{fallback:{provider:r.provider,model:b}}})}),e.jsx(ue,{title:t("imageGen.maxPerTurn.label"),subtitle:t("imageGen.maxPerTurn.help"),children:e.jsx(pe,{className:"w-20","data-testid":"image-gen-max",value:String(a?.maxPerTurn??Ku),onChange:b=>{h({imageGen:{maxPerTurn:Number(b.target.value)}})},disabled:c||!s.config,"aria-label":t("imageGen.maxPerTurn.label"),children:Array.from({length:10},(b,g)=>g+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(Zu,{provider:b,status:a},b))]})}function Yu({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 h=await O("/api/images/connections",{method:"POST",body:JSON.stringify({id:r})});n({type:"configStatus",config:h}),i(null),c("")}else{const h=await O("/api/images/connections");i(h.connections),c(h.connections[0]?.id??"")}}catch(h){u(h instanceof Error?h.message:String(h))}finally{d(!1)}};return e.jsxs(Z,{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:It,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(pe,{"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:It,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 Mn({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(ue,{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(pe,{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")}),$u.filter(x=>x!==r).map(x=>e.jsx("option",{value:x,children:At[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",h=(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"}]:Hu[a]).map(g=>({...g,group:"recommended"})),f=d!==null||h.length===0,y=()=>{d!==null&&(m(null),d.trim()&&d.trim()!==i&&o(d.trim()))},b=g=>{if(g===es)return m(i);m(null),o(g)};return e.jsx(ue,{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:[h.length>0&&e.jsxs(pe,{className:"w-64 max-w-full","data-testid":`image-gen-${s}-model`,value:f?es:i,onChange:g=>b(g.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&&!h.some(g=>g.id===i)&&e.jsx("option",{value:i,children:i}),["recommended","more"].map(g=>{const k=h.filter(C=>C.group===g);return k.length>0&&e.jsx("optgroup",{label:t(g==="recommended"?"decider.model.recommended":"decider.model.more"),children:k.map(C=>e.jsx("option",{value:C.id,children:C.name},C.id))},g)}),e.jsx("option",{value:es,children:t("imageGen.model.other")})]}),f&&e.jsx("input",{value:d??i,onChange:g=>m(g.target.value),onBlur:y,onKeyDown:g=>g.key==="Enter"&&y(),disabled:c,placeholder:Oi[a]||t("imageGen.model.placeholder"),"aria-label":t("imageGen.model.idLabel",{slot:n}),autoComplete:"off",spellCheck:!1,className:z(fs,"w-64 max-w-full")})]})})}function Zu({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,h]=l.useState(!1),[f,y]=l.useState(null),b=s==="openrouter"?[n?.primary,n?.fallback].filter(I=>I?.provider===s).map(I=>I?.model).join(" "):"",g=f?.models===b?f:null,k=I=>y(I&&{...I,models:b}),C=Ju(n,s),N=s==="openai"||s==="gemini"||s==="custom"?Gu[s]:null,w=s==="xai"||s==="openrouter"?Vu[s]:null,P=c??n?.customUrl??"",v=async I=>{m(!0),x(null),k(null);try{a({type:"configStatus",config:await I()}),r(""),o(null)}catch(H){x(H instanceof Error?H.message:String(H))}finally{m(!1)}},B=I=>v(async()=>s==="xai"||s==="openrouter"?Ql(s,I,!1):window.ogb?.setCredential&&N?window.ogb.setCredential(N.credential,I):O("/api/config",{method:"PUT",body:JSON.stringify(N.patch(I))})),j=()=>v(async()=>{const I=P.trim()?Wu(P.trim()):"";return O("/api/config",{method:"PUT",body:JSON.stringify({imageGen:{customUrl:I}})})}),A=async()=>{h(!0),k(null);try{k(qu(s,await O("/api/images/test",{method:"POST",body:JSON.stringify({provider:s})})))}catch(I){k({ok:!1,text:I instanceof Error?I.message:String(I)})}finally{h(!1)}};return e.jsxs(Z,{title:At[s],children:[e.jsx(em,{configured:C,optional:s==="custom"}),w&&e.jsxs("p",{className:"mb-2 text-[12px] leading-relaxed text-ink-secondary",children:[t(w.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(pe,{"aria-label":t("imageGen.custom.api"),value:n?.customApi??"images",disabled:d,onChange:I=>{v(()=>O("/api/config",{method:"PUT",body:JSON.stringify({imageGen:{customApi:I.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:I=>{v(()=>O("/api/config",{method:"PUT",body:JSON.stringify({imageGen:{customLocalImageExtension:I.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:I=>o(I.target.value),onKeyDown:I=>I.key==="Enter"&&void j(),disabled:d,placeholder:"http://127.0.0.1:4000/v1","aria-label":t("imageGen.custom.url"),autoComplete:"off",className:fs}),e.jsxs("button",{type:"button",onClick:()=>{j()},disabled:d||c===null,className:It,children:[d?e.jsx(Y,{size:13,className:"animate-spin"}):e.jsx(fe,{size:13}),t("common.save")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"password",value:i,onChange:I=>r(I.target.value),onKeyDown:I=>I.key==="Enter"&&i.trim()&&void B(i.trim()),disabled:d,placeholder:C?t("keys.replace"):t("imageGen.key.paste"),"aria-label":t((N??w).label),autoComplete:"off",spellCheck:!1,className:fs}),e.jsxs("button",{type:"button",onClick:()=>{B(i.trim())},disabled:d||!i.trim(),className:It,children:[d?e.jsx(Y,{size:13,className:"animate-spin"}):e.jsx(fe,{size:13}),t("common.save")]}),C&&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")})]}),g&&e.jsx("p",{role:"status",className:z("mt-1 text-[12px]",g.ok?"text-success":"text-danger"),children:g.text}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 text-[12px] text-ink-secondary",children:[On[s]?e.jsx("a",{href:On[s],target:"_blank",rel:"noreferrer",className:"text-accent hover:underline",children:t("imageGen.key.get")}):e.jsx("span",{children:t("imageGen.custom.help",{app:Cs()})}),C&&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 em({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 ts(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")&&Fa(s.driverKind)==="codex"?"chatgpt":null}function Fs(s){return s.snapshot.state!=="available"?"unavailable":s.snapshot.authenticated===!0?"signedIn":s.snapshot.authenticated===!1?"signedOut":"unknown"}const Ds={claude:{title:"accounts.claude",add:"accounts.addClaude",removeBody:"accounts.removeBodyClaude"},chatgpt:{title:"accounts.chatgpt",add:"accounts.addChatgpt",removeBody:"accounts.removeBodyChatgpt"}};function tm(s,n){return{signOut:Fs(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 Mi(s){return s.some(Le)}function sm(s,n){const a=n.filter(o=>Fs(o)==="signedIn"),i=Mi(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??no(n[0]);return{title:t(Ds[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 nm({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),[h,f]=l.useState(null),y=l.useRef(null),{signOut:b,remove:g}=tm(s,n),k=i.bots.filter(w=>w.modelSelection.instanceId===n.instanceId).length;l.useEffect(()=>{if(!o)return;const w=v=>{v.key==="Escape"&&(v.stopPropagation(),d(!1))},P=v=>{v.target instanceof Node&&!y.current?.contains(v.target)&&d(!1)};return window.addEventListener("keydown",w,!0),window.addEventListener("pointerdown",P),()=>{window.removeEventListener("keydown",w,!0),window.removeEventListener("pointerdown",P)}},[o]);const C=async w=>{u(null),p(!0),f(null);try{const P=`/api/instances/${encodeURIComponent(n.instanceId)}${w==="signOut"?"/auth/sign-out":""}`,{instances:v}=await O(P,w==="signOut"?{method:"POST"}:{method:"DELETE"});Array.isArray(v)?r({type:"instances",instances:v}):await c().catch(()=>{})}catch(P){f(P instanceof Error?P.message:String(P))}finally{p(!1)}},N="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:[g&&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(w=>!w),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(Y,{size:14,className:"animate-spin"}):e.jsx(gl,{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]",fl),children:[e.jsx("button",{type:"button",role:"menuitem",className:z(N,"text-ink"),onClick:()=>{d(!1),a()},children:t("accounts.rename")}),b&&e.jsx("button",{type:"button",role:"menuitem",className:z(N,"text-ink"),onClick:()=>{d(!1),u("signOut")},children:t("accounts.signOut")}),g&&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)})})]}),h&&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:h}),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:()=>{C("signOut")}}),e.jsx(Qe,{open:m==="remove",title:t("accounts.removeTitle",{name:_e(n)}),body:t(Ds[s].removeBody),confirmLabel:t("accounts.remove"),tone:"neutral",onCancel:()=>u(null),onConfirm:()=>{C("remove")}})]})}function am({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 O(`/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(Y,{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 im({group:s,instance:n,signingIn:a,onSignIn:i,onSignInDone:r}){const[c,o]=l.useState(!1),d=Fs(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(fe,{size:13}):e.jsx("span",{className:z("size-1.5 rounded-full",d==="signedOut"?"bg-warning":"bg-ink-tertiary")})}),c?e.jsx(am,{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(nm,{group:s,instance:n,onRename:()=>o(!0)})]})]}),a&&e.jsx("div",{className:"pl-9",children:s==="claude"?e.jsxs(e.Fragment,{children:[e.jsx(Zl,{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(eo,{command:n.claudeAccount.signInCommand,actionLabel:t("engineSetup.openSignIn"),compact:!0})]})]}):e.jsx(to,{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(so,{instanceId:n.instanceId,welcome:!1})})]})}function zi({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,h]=l.useState(""),[f,y]=l.useState(!1),[b,g]=l.useState(null),k=async()=>{if(!(f||!u.trim())){y(!0),g(null);try{const C={displayName:u.trim(),...a,...i&&p.trim()?{configDir:p.trim()}:{}},N=await O(n,{method:"POST",body:JSON.stringify(C)});Array.isArray(N.instances)&&o({type:"instances",instances:N.instances}),m(!1),x(""),h(""),typeof N.instanceId=="string"&&c(N.instanceId)}catch(C){g(C instanceof Error?C.message:String(C))}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:C=>{C.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:C=>x(C.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:C=>h(C.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),g(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(Y,{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(Ce,{size:14}),s]})}function rm({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(wt,{instance:o,summary:sm(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(im,{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(zi,{label:t(Ds[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(zt,{instance:o,unframed:!0}),o.snapshot.update&&e.jsx(Da,{update:o.snapshot.update,instance:o,className:"mt-3",quiet:!0}),o.snapshot.warning&&e.jsx(_a,{warning:o.snapshot.warning,className:"mt-3"}),a]})}const at=z(Be,"font-sans"),lm={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"},zn=["opusModel","sonnetModel","haikuModel","smallFastModel"],om={name:"Claude on Bedrock",awsProfile:"default",awsRegion:"",model:"",opusModel:"",sonnetModel:"",haikuModel:"",smallFastModel:""},cm=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??""}},Un={opusModel:"claudeBedrock.opus",sonnetModel:"claudeBedrock.sonnet",haikuModel:"claudeBedrock.haiku",smallFastModel:"claudeBedrock.smallFast"};function Fn({instance:s,onDone:n}){const{dispatch:a}=G(),[i,r]=l.useState(s?cm(s):om),[c,o]=l.useState(!1),[d,m]=l.useState(null),u=h=>({value:i[h],onChange:f=>r(y=>({...y,[h]: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 h={displayName:i.name.trim(),awsProfile:i.awsProfile.trim(),awsRegion:i.awsRegion.trim(),model:i.model.trim(),...Object.fromEntries(zn.map(f=>[f,i[f].trim()]))};try{const f=s?await O(`/api/instances/${encodeURIComponent(s.instanceId)}/claude-bedrock`,{method:"PATCH",body:JSON.stringify(h)}):await O("/api/instances/claude-bedrock",{method:"POST",body:JSON.stringify(h)});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:h=>{h.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:zn.map(h=>e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] font-medium text-ink",children:[t(Un[h]),e.jsx("input",{...u(h),maxLength:160,placeholder:lm[h],"aria-label":t(Un[h]),className:z(at,"font-mono")})]},h))})]}),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(Y,{size:13,className:"animate-spin"}),t("common.save")]})]})]})}function dm({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,h=async()=>{c(!1),d(!0),u(null);try{const f=await O(`/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($a,{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(Y,{size:14,className:"animate-spin"}):e.jsx(Ee,{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:()=>{h()}})]})}function ss(){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(Fn,{instance:r,onDone:()=>i(null)})},r.instanceId):e.jsx(dm,{instance:r,onEdit:()=>i(r.instanceId)},r.instanceId))}),a==="new"?e.jsx(Fn,{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(Ce,{size:14}),t("claudeBedrock.add")]})]})}function Dn(s){const n=s/1048576;return n<1?t("engines.freeSpace.underOneMb"):n<1024?`${Math.round(n)} MB`:`${(n/1024).toFixed(1)} GB`}function um({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 O(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 O(`${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(bl,{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(Y,{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:Dn(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:Dn(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 ns=[60,120,180,360,720];function Ui(){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 O("/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=ns.includes(d.windowMinutes)?[...ns]:[...ns,d.windowMinutes].sort((x,p)=>x-p);return e.jsxs(Z,{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(pe,{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 mm({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),[h,f]=l.useState(null),[y,b]=l.useState(!1),[g,k]=l.useState(null),C=l.useRef(!1);l.useEffect(()=>{C.current||(C.current=!0,O(`/api/cli-candidates?name=${encodeURIComponent(n??"")}`).then(({candidates:j})=>{c(j),s.cli&&(j.includes(s.cli)?d(s.cli):u(s.cli))}).catch(()=>c(j=>j??[])))},[n,s.cli]);const N=m.trim()||o,w=N!==(s.cli??""),P=x||y;l.useEffect(()=>{f(null)},[N]);const v=()=>{if(P||!N||!w)return;b(!0),k(null);const j=N;O(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"PATCH",body:JSON.stringify({cli:j})}).then(()=>Promise.resolve(i()).catch(()=>{})).then(a).catch(A=>k(A.message)).finally(()=>b(!1))},B=()=>{P||!N||!w||(p(!0),k(null),O("/api/cli-test",{method:"POST",body:JSON.stringify({cli:N,driver:s.driverKind})}).then(j=>{f(j),j.ok&&v()}).catch(j=>k(j.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(pe,{className:"w-full font-mono",value:m.trim()?"":o,onChange:j=>{d(j.target.value),u("")},"aria-label":t("engines.detectedAria",{name:s.displayName}),disabled:P,children:[e.jsx("option",{value:"",children:t("engines.selectBinary")}),r.map(j=>e.jsx("option",{value:j,children:j},j))]}),e.jsx("input",{type:"text",value:m,onChange:j=>u(j.target.value),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),!(!N||!w)&&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"}),h&&!h.ok&&h.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:h.message})})]}),h?.ok&&h.version&&e.jsx("div",{className:"text-[12px] text-success",children:t("engines.testPassed",{version:h.version})}),g&&e.jsx("div",{role:"alert",className:"text-[12px] text-danger",children:g}),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")}),h&&!h.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:()=>v(),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(Y,{size:13,className:"animate-spin"}):t("engines.saveAnyway")})]}):e.jsx("button",{onClick:B,disabled:P||!N||!w,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(Y,{size:13,className:"animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:13}),t("common.save")]})})]})]})}function Fi({instance:s}){const{refreshInstances:n}=G(),[a,i]=l.useState(!1),r=gd(a),[c,o]=l.useState(!1),[d,m]=l.useState(!1),[u,x]=l.useState(null),[p,h]=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),h(null),O(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"PATCH",body:JSON.stringify({cli:""})}).then(()=>Promise.resolve(n()).catch(()=>{})).catch(k=>h(k.message)).finally(()=>o(!1)))},b=()=>{c||d||(o(!0),h(null),O(`/api/instances/${encodeURIComponent(s.instanceId)}`,{method:"PATCH",body:JSON.stringify({hidden:!0})}).then(()=>Promise.resolve(n()).catch(()=>{})).catch(k=>h(k.message)).finally(()=>o(!1)))},g=()=>{c||d||(m(!0),x(null),h(null),O(`/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=>h(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:g,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(Y,{size:12,className:"animate-spin"}):e.jsx(Se,{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(mm,{instance:s,cliDefault:s.cliDefault,onClose:()=>i(!1),onSaved:n})})]})}function _n({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",h=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:g}=await O(b,{method:p?"DELETE":"POST"});Array.isArray(g)?i({type:"instances",instances:g}):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||h>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(Y,{size:13,className:"animate-spin"}):f}),h>0&&e.jsx("p",{className:"text-[11px] text-ink-secondary",children:t("accounts.inUse",{count:String(h)})})]}),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 pm({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(zi,{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(zt,{instance:r,unframed:!0})})]})}function xm({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(wt,{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(wt,{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(wt,{instance:s,bare:n,children:[a,(s.codexEndpoint||s.claudeEndpoint)&&e.jsx(Ci,{instance:s},s.instanceId),!Le(s)&&e.jsx(zt,{instance:s,intent:s.access==="custom"?"inject":"cloud",description:s.codexEndpoint?t("agentEndpoints.codexHint"):void 0,unframed:!0}),Le(s)&&e.jsx(lo,{instance:s,className:"mt-3"}),Le(s)&&s.serverKind==="ollama"&&e.jsx(oo,{instance:s,className:"mt-3"}),Le(s)&&e.jsx(co,{instance:s,className:"mt-3"}),s.snapshot.update&&e.jsx(Da,{update:s.snapshot.update,instance:s,className:"mt-3",quiet:!0}),s.snapshot.warning&&e.jsx(_a,{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(fe,{size:13}),t(uo[Fa(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(fe,{size:13}),t("engineSetup.claude.connectedAccount")]})),s.freeUpSpace&&e.jsx(um,{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(pm,{source:s}),s.snapshot.authenticated===!0&&s.authentication?.signOut===!0&&e.jsx(_n,{instance:s,action:"signOut"}),s.instanceId.startsWith("antigravity-")&&e.jsx(_n,{instance:s,action:"remove"})]}),e.jsx(Fi,{instance:s})]})}function hm(s,n){return n?s.snapshot.authenticated===!0&&s.snapshot.account?.email?s.snapshot.account.email:t("onboarding.engines.ready"):s.snapshot.ollama?ro(s.snapshot.ollama):s.snapshot.state==="available"&&s.snapshot.authenticated===!1?t("model.signInRequired"):t("onboarding.engines.needsSetup")}function gm({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(be,{label:t("settings.simple.ai.yours"),actions:e.jsx(Ka,{}),children:e.jsx(ye,{children:o.map(p=>{const h=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(mn,{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:hm(p,h)})]})]}),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":h||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(Ut,{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(mn,{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(zs,{engine:"codex",xingchi:!0,onDone:()=>m(!1)})]}),e.jsx(Ha,{instances:x,isReady:n,renderEngine:p=>a(p)})]})]})}function fm(){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 O("/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),O(`/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 Di({simple:s=!1,more:n}){const{state:a}=G();l.useEffect(()=>ao,[]);const i=a.instances.filter(h=>h.readOnly||h.cli!==void 0||h.cliDefault!==void 0||h.snapshot.state==="unavailable"||io(h)||h.claudeEndpoint!==void 0||h.claudeBedrock!==void 0||h.codexEndpoint!==void 0),r=new Map;for(const h of i){const f=ts(h);f&&r.set(f,[...r.get(f)??[],h])}const c=h=>{const f=ts(h);return f&&r.get(f)?.[0]===h?f:null},o=i.filter(h=>!ts(h)||c(h)),d=o.length>0&&o.every(h=>h.readOnly),m=!r.has("chatgpt")&&!d,u=!r.has("claude")&&!d,x=h=>{const f=c(h);return f?Mi(r.get(f)):Le(h)},p=(h,f=!1)=>{const y=c(h);return y?e.jsx(rm,{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(ss,{})]}):e.jsx(St,{}),e.jsx(Fi,{instance:h})]})}):e.jsx(xm,{instance:h,bare:f})};return s&&n?e.jsxs(e.Fragment,{children:[e.jsx(gm,{rows:o,isReady:x,renderEngine:p,more:n}),u&&e.jsxs("div",{className:"px-4",children:[e.jsx(qt,{}),e.jsx(ss,{})]}),m&&e.jsx("div",{className:"px-4",children:e.jsx(St,{})})]}):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(Ka,{})]}),e.jsx(Ha,{instances:o,isReady:x,renderEngine:p}),u&&e.jsxs("div",{className:"px-4",children:[e.jsx(qt,{}),e.jsx(ss,{})]}),m&&e.jsx("div",{className:"px-4",children:e.jsx(St,{})}),e.jsx(fm,{}),e.jsx(Ui,{})]})}const bm={status:"/api/local-computer","local-vms":"/api/local-computer/instances",cloud:"/api/computers/boxes",vps:"/api/computers/vps"};function yt(s,n){return[bm[s],{signal:n}]}function _s(s,n){return[s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}]}function ym({instances:s,configured:n,aliases:a,loading:i,removingName:r,error:c,unavailableReason:o,onRefresh:d,onRemove:m}){return e.jsxs(Z,{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(Wa,{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(Se,{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(Y,{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(yl,{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=Im(u),h=$s(p),f=r===u.name,y=Ks(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:h}),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(Y,{size:12,className:"animate-spin"}):e.jsx(Ee,{size:12}),t("vm.vps.remove")]})]},`${u.vpsAlias??""}:${u.name}`)})]})]})}const vm=[1e3,2e3,4e3];function jm(s){return new Promise(n=>window.setTimeout(n,s))}const km={auto:"vm.dest.auto",cloud:"place.cloud",vm:"vm.dest.vm",local:"vm.dest.local",browser:"vm.dest.browser",off:"vm.dest.off"},Nm={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 $s(s){return t(Nm[s])}function wm(s){return s.managed?s.inUse?"in-use":s.container==="stopped"?"stopped":s.ready?"running":"attention":"unmanaged"}function Sm(s){return $s(wm(s))}function Cm(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 _i(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 Em(s,n,a){return s.configured!==!0||s.available!==!0?{instances:n,overrides:{...a}}:_i(Array.isArray(s.instances)?s.instances:[],n,a)}function Am(s){return["idle","ready","running"].includes(s.state)}function Im(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 Ks(s){const n=/-([a-f0-9]{12})$/i.exec(s)?.[1];return n?n.slice(-8).toLowerCase():"unknown"}function Pm(s){return{confirmation:t("vm.confirm.deleteBotVm",{name:s.name}),request:_s(`/api/bots/${s.botId}/local-computer/remove`,{})}}function Tm(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:_s(`/api/computers/boxes/${encodeURIComponent(n.boxId)}/${s}`,s==="delete"?{confirmName:n.name}:{})}}function Rm(s){const n=Ks(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:_s(`/api/computers/vps/${encodeURIComponent(s.name)}/remove`,{confirmName:s.name,alias:s.vpsAlias})}}function as(s,n){return s.confirmation!==null&&!n(s.confirmation)?null:s.request}function Lm({instances:s,configured:n,loading:a,pending:i,error:r,unavailableReason:c,onRefresh:o,onSleep:d,onDelete:m}){return e.jsxs(Z,{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(Wa,{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(Se,{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(Y,{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(Lt,{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=Cm(u),h=$s(p),f=i?.boxId===u.boxId,y=Am(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:h})]}),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:h.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(Y,{size:12,className:"animate-spin"}):e.jsx(vl,{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(Y,{size:12,className:"animate-spin"}):e.jsx(Ee,{size:12}),t("common.delete")]})]})]},u.boxId)})})]})}function Bm({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(Z,{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}):L(`Đã 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"):L("Ứ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(Se,{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(Y,{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,h)=>{const f=Sm(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",h>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(km[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:ci(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(Y,{size:12,className:"animate-spin"}),p.container==="running"?L("Dừng","Stop"):L("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(Y,{size:12,className:"animate-spin"}):e.jsx(Ee,{size:12}),t("common.delete")]})]})]},p.botId)})})]})}function vt({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(fe,{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 qe({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(Y,{size:13,className:"animate-spin"}),a]})}const $i=5,Ki=1440,Om=480;function Mm(s){const n=s.trim();if(!/^\d+$/.test(n))return null;const a=Number(n);return a>=$i&&a<=Ki?a:null}function zm({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 h=Mm(i);if(h===null){m(t("vm.idle.range"));return}x(!0);try{await a(h),r(String(h)),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:$i,max:Ki,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:h=>{r(h.target.value),o(!0),m("")},onBlur:()=>{p()},onKeyDown:h=>{h.key==="Enter"&&h.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 Hi(){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),[h,f]=l.useState(0),[y,b]=l.useState([]),[g,k]=l.useState(2),[C,N]=l.useState(!1),[w,P]=l.useState(null),[v,B]=l.useState(null),[j,A]=l.useState(null),[I,H]=l.useState(null),[D,V]=l.useState(0),[$,se]=l.useState([]),[ne,ce]=l.useState(null),[T,U]=l.useState(!0),[Q,le]=l.useState(null),[he,S]=l.useState(null),[ae,F]=l.useState(null),[te,q]=l.useState(0),ie=l.useRef([]),re=l.useRef({}),[de,ve]=l.useState([]),[K,oe]=l.useState(null),[R,E]=l.useState([]),[W,xe]=l.useState(!0),[X,ke]=l.useState(null),[Pe,et]=l.useState(null),[tt,ze]=l.useState(null),[zr,Ur]=l.useState(0),[Fr,Fe]=l.useState(""),Ke=l.useCallback(async M=>{const _=await fetch(...yt("status",M)),ee=await _.json().catch(()=>({}));if(!M?.aborted){if(!_.ok)throw new Error(ee.error??t("vm.err.status",{code:_.status}));return a(ee),u(null),ee}},[]),ht=l.useCallback(async M=>{const _=await fetch(...yt("local-vms",M)),ee=await _.json().catch(()=>({}));if(!_.ok)throw new Error(ee.error??t("vm.err.inventory",{code:_.status}));const J=ee;b(J.instances),k(J.maxInstances),B(J.available?null:ci(J.problem)??t("vm.err.runtimeUnavailable")),P(null)},[]),st=l.useCallback(async M=>{const _=await fetch(...yt("cloud",M)),ee=await _.json().catch(()=>({}));if(!_.ok)throw new Error(ee.error??t("vm.err.cloudInventory",{code:_.status}));const J=ee,ge=Em(J,ie.current,re.current);re.current=ge.overrides,ie.current=ge.instances,se(ge.instances),ce(J.configured===!0),S(J.available||!J.configured?null:J.problem??t("vm.err.cloudUnavailable")),le(null)},[]),$t=l.useCallback(async M=>{const _=await fetch(...yt("vps",M)),ee=await _.json().catch(()=>({}));if(!_.ok)throw new Error(ee.error??t("vm.err.vpsInventory",{code:_.status}));const J=ee;ve(Array.isArray(J.instances)?J.instances:[]),oe(J.configured===!0),E(Array.isArray(J.vpsAliases)?J.vpsAliases:[]),et(J.available||!J.configured?null:J.problem??t("vm.err.vpsUnavailable")),ke(null)},[]);l.useEffect(()=>{if(s)return;let M=!0,_,ee;const J=async()=>{ee=new AbortController;try{await Ke(ee.signal)}catch(ge){M&&!(ge instanceof DOMException&&ge.name==="AbortError")&&(a(null),u(ge instanceof Error?ge.message:String(ge)))}finally{M&&(r(!1),_=window.setTimeout(()=>{J()},5e3))}};return J(),()=>{M=!1,ee?.abort(),_!==void 0&&window.clearTimeout(_)}},[s,Ke,h]),l.useEffect(()=>{if(n?.mode!=="per-bot"){b([]),N(!1),P(null),B(null);return}const M=new AbortController;return N(!0),ht(M.signal).catch(_=>{_ instanceof DOMException&&_.name==="AbortError"||P(_ instanceof Error?_.message:String(_))}).finally(()=>{M.signal.aborted||N(!1)}),()=>M.abort()},[D,ht,n?.mode]),l.useEffect(()=>{const M=new AbortController;return U(!0),st(M.signal).catch(_=>{_ instanceof DOMException&&_.name==="AbortError"||S(_ instanceof Error?_.message:String(_))}).finally(()=>{M.signal.aborted||U(!1)}),()=>M.abort()},[te,st]),l.useEffect(()=>{const M=new AbortController;return xe(!0),$t(M.signal).catch(_=>{_ instanceof DOMException&&_.name==="AbortError"||et(_ instanceof Error?_.message:String(_))}).finally(()=>{M.signal.aborted||xe(!1)}),()=>M.abort()},[$t,zr]);const Kt=async(M,_)=>{const ee=await fetch(`/api/local-computer/${M}`,{method:"POST",headers:{"content-type":"application/json"},body:"{}",signal:_}),J=await ee.json().catch(()=>({})),ge={pull:"vm.err.prepare",run:"vm.err.create",start:"vm.err.start",stop:"vm.err.stop",remove:"vm.deleteError"};if(!ee.ok)throw new Error(J.error??t(ge[M]));return _.throwIfAborted(),a(J),J},Js=M=>window.ogb?.confirm?window.ogb.confirm(M):window.confirm(M),He=async M=>{if(c!==null||d.current)return;const _=new AbortController;d.current=_,o(M),u(null);try{if(M==="remove"&&!await Js(t("vm.confirm.deleteShared"))||M==="recreate"&&!await Js(t("vm.confirm.recreate")))return;let ee;if(M==="recreate"?(await Kt("remove",_.signal),ee=await Kt("run",_.signal)):ee=await Kt(M,_.signal),(M==="run"||M==="start"||M==="recreate")&&(ee=await An(ee,async()=>await Ke(_.signal)??ee,_.signal),!ee.ready&&!ee.capacity_limited))throw new Error(ee.problem??t("vm.err.start"));await Ke(),Fe(M==="remove"?t("vm.announce.deleted"):M==="stop"?t("vm.announce.stopped"):t("vm.announce.updated"))}catch(ee){if(_.signal.aborted)return;u(ee instanceof Error?ee.message:String(ee))}finally{d.current=null,_.signal.aborted||o(null)}},Dr=async(M,_)=>{if(I||j)return;H({botId:M.botId,action:_}),P(null);const ee=new AbortController;try{const J=`/api/bots/${encodeURIComponent(M.botId)}/local-computer`,ge=await fetch(`${J}/${_}`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"});let Re=await ge.json();if(!ge.ok)throw new Error(Re.error??t("vm.err.start"));if(_==="start"&&(Re=await An(Re,async()=>{const We=await fetch(J);if(!We.ok)throw new Error(t("vm.err.start"));return We.json()},ee.signal)),_==="start"&&!Re.ready)throw new Error(Re.problem??t("vm.err.start"));await Promise.all([ht(),Ke()])}catch(J){P(J instanceof Error?J.message:String(J))}finally{H(null)}},Xs=async M=>{p(!0),u(null);try{const _=await fetch("/api/config",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({localVm:{mode:M,automaticCapacity:!0}})}),ee=await _.json().catch(()=>({}));if(!_.ok)throw new Error(ee.error??t("vm.policyError"));a(J=>J&&{...J,mode:M}),await Ke()}catch(_){u(_ instanceof Error?_.message:String(_))}finally{p(!1)}},_r=async M=>{const _=await fetch("/api/config",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({localVm:{idleTimeoutMinutes:M}})}),ee=await _.json().catch(()=>({}));if(!_.ok)throw new Error(ee.error??t("vm.idle.error"));a(J=>J&&{...J,idle_timeout_ms:M*6e4})},$r=async M=>{if(!M.managed){P(t("vm.unmanagedError"));return}const _=as(Pm(M),ee=>window.confirm(ee));if(_){A(M.botId),P(null);try{const ee=await fetch(..._),J=await ee.json().catch(()=>({}));if(!ee.ok)throw new Error(J.error??t("vm.deleteError"));await ht(),Fe(t("vm.announce.deletedBot",{name:M.name}))}catch(ee){P(ee instanceof Error?ee.message:String(ee))}finally{A(null)}}},Ys=async(M,_)=>{const ee=as(Tm(M,_),J=>window.confirm(J));if(ee){F({boxId:_.boxId,action:M}),le(null),Fe("");try{const J=await fetch(...ee),ge=await J.json().catch(()=>({}));if(!J.ok)throw new Error(ge.error??t(M==="delete"?"vm.cloud.deleteError":"vm.cloud.sleepError"));const Re=M==="delete"&&ge?.pending===!0;re.current={...re.current,[_.boxId]:M==="delete"?Re?"deleting":"deleted":"sleeping"};const We=_i(ie.current,ie.current,re.current);re.current=We.overrides,ie.current=We.instances,se(We.instances);const Ge=_.orphaned?t("vm.announce.orphanCloud"):t("vm.confirm.ownedCloud",{name:_.ownerName??""});if(Fe(Re?`${Ge}: ${t("vm.state.removing")}.`:t(M==="delete"?"vm.announce.cloudDeleted":"vm.announce.cloudSleeping",{subject:Ge})),Re){for(const Ae of vm){await jm(Ae);try{await st()}catch{}if(re.current[_.boxId]!=="deleting"){Fe(t("vm.announce.cloudDeleted",{subject:Ge}));return}}const Ve={...re.current};delete Ve[_.boxId],re.current=Ve;const ft=ie.current.map(Ae=>Ae.boxId===_.boxId?{...Ae,state:_.state}:Ae);ie.current=ft,se(ft);try{await st(),ie.current.some(Ae=>Ae.boxId===_.boxId)||Fe(t("vm.announce.cloudDeleted",{subject:Ge}))}catch(Ae){const Hr=Ae instanceof Error?Ae.message:String(Ae);le(`${Ge}: ${t("vm.state.removing")}. ${Hr}`)}return}try{await st()}catch(Ve){const ft=Ve instanceof Error?Ve.message:String(Ve);le(t(M==="delete"?"vm.cloud.deletedRefreshError":"vm.cloud.sleepRefreshError",{subject:Ge,detail:ft}))}}catch(J){le(J instanceof Error?J.message:String(J))}finally{F(null)}}},Kr=async M=>{const _=Ks(M.name),ee=as(Rm(M),J=>window.confirm(J));if(ee){ze(M.name),ke(null);try{const J=await fetch(...ee),ge=await J.json().catch(()=>({}));if(!J.ok)throw new Error(ge.error??t("vm.vpsRemoveError"));await $t(),Fe(t("vm.announce.vpsRemoved",{subject:M.orphaned?t("vm.announce.orphanVps",{id:_}):t("vm.confirm.ownedVps",{name:M.ownerName??""})}))}catch(J){ke(J instanceof Error?J.message:String(J))}finally{ze(null)}}},Te=n?.commands,gt=n?.ready===!0,Qs=n?.container!=="missing",Zs=!!(Qs&&(!n?.imageMatches||!n?.managed||n?.network==="unsafe"||n?.security==="unsafe"||n?.persistence==="unsafe")),en=!i&&!n,tn=n?.platform==="darwin"?t("vm.host.mac"):t("vm.host.computer"),Ne=n?.mode==="per-bot",Ht=Ne&&n?.runtime==="container",Wt=Ne?!!(n?.daemonUp&&n?.image&&!Ht):gt;return e.jsxs(e.Fragment,{children:[e.jsx("p",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:Fr}),e.jsx(Lm,{instances:$,configured:ne,loading:T,pending:ae,error:Q,unavailableReason:he,onRefresh:()=>q(M=>M+1),onSleep:M=>{Ys("sleep",M)},onDelete:M=>{Ys("delete",M)}}),e.jsx(ym,{instances:de,configured:K,aliases:R,loading:W,removingName:tt,error:X,unavailableReason:Pe,onRefresh:()=>Ur(M=>M+1),onRemove:M=>{Kr(M)}}),e.jsx(fd,{}),!s&&e.jsxs(e.Fragment,{children:[e.jsxs(Z,{title:t("vm.main.title"),subtitle:Ne?t("vm.main.perBotSubtitle",{host:tn}):t("vm.main.sharedSubtitle",{host:tn}),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]",Wt?"bg-success/15 text-success":"bg-control text-ink-secondary"),children:[i?e.jsx(Y,{size:12,className:"animate-spin"}):Wt?e.jsx(fe,{size:12}):e.jsx(mo,{size:9}),i?t("common.checking"):en?t("vm.main.statusUnavailable"):Ne&&Wt?t("vm.main.readyPerBot"):Ht?t("vm.main.perBotUnsupported"):gt?t("vm.main.ready"):n?.problem??t("vm.main.notReady")]}),e.jsxs("button",{onClick:()=>{r(!0),f(M=>M+1),V(M=>M+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(Se,{size:12})," ",t("vm.main.recheck")]}),gt&&!Ne&&e.jsxs("a",{href:n?.viewer_url??Te?.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(xt,{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(Z,{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((M,_)=>e.jsx("button",{type:"button",disabled:!n||x,onClick:()=>{Xs(M)},className:z("flex-1 px-3 py-2 text-[13px] disabled:opacity-50",_>0&&"border-l border-hairline/40",n?.mode===M?"bg-control text-ink":"text-ink-secondary hover:text-ink"),children:M==="shared"?t("vm.isolation.shared"):t("vm.isolation.perBot")},M))}),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:L("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:L("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"?L("Ướ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`,` · ${L("Mỗi máy","Each desktop")}: ${n.capacity.perVmMemoryGb} GB / ${n.capacity.perVmCpus} CPU`,` · ${L("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:()=>{Xs(n.mode)},className:"mt-1 text-[12px] text-accent hover:underline",children:L("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:L("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?L("Thủ công","Manual"):L("Tự động","Automatic")}),e.jsx("div",{className:"font-semibold tabular-nums",children:n?.max_instances??"…"})]})]}),e.jsx(zm,{minutes:n?Math.round(n.idle_timeout_ms/6e4):Om,disabled:!n||x,onSave:_r}),x&&e.jsxs("div",{className:"mt-2 flex items-center gap-1.5 text-[12px] text-ink-secondary",children:[e.jsx(Y,{size:12,className:"animate-spin"})," ",t("vm.saving")]})]}),e.jsx(Z,{title:t("vm.setup.title"),subtitle:t("vm.setup.subtitle"),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs(vt,{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")}),Te?.install?e.jsx(rt,{command:Te.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(vt,{n:2,title:n?.runtime&&!n.daemonUp?t("vm.setup.step2Open",{runtime:n.runtime}):t("vm.setup.step2"),done:!!n?.daemonUp,children:n?.runtime?Te?.runtimeStart?e.jsx(rt,{command:Te.runtimeStart}):e.jsx("div",{className:"text-[13px] text-ink-secondary",children:t("vm.setup.step2Detail")}):null}),e.jsxs(vt,{n:3,title:t("vm.setup.step3"),done:!!n?.image,children:[n?.daemonUp&&e.jsx(qe,{action:"pull",pending:c,onClick:()=>{He("pull")},children:t("vm.setup.prepare")}),Te?.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:Te.pull})})]})]}),e.jsxs(vt,{n:4,title:Ne?t("vm.setup.step4PerBot"):Zs?t("vm.setup.step4Recreate"):t("vm.setup.step4"),done:Ne?y.some(M=>M.managed):gt,children:[Ne?e.jsx("div",{className:"text-[13px] leading-relaxed text-ink-secondary",children:Ht?t("vm.setup.applePort"):t("vm.setup.perBotHint")}):Zs?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(qe,{action:"recreate",pending:c,onClick:()=>{He("recreate")},danger:!0,children:[e.jsx(po,{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(qe,{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(Y,{size:13,className:"animate-spin"})," ",t("vm.setup.waiting")]}):n?.image?e.jsxs(e.Fragment,{children:[e.jsx(qe,{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,Te?.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:Te.run})})]})]})]})}),Ne&&e.jsx(Bm,{instances:y,maxInstances:n?.max_instances??g,runningInstances:n?.running_instances,powerPending:I,onPower:(M,_)=>{Dr(M,_)},loading:C,deletingBotId:j,error:w,unavailableReason:v,onRefresh:()=>V(M=>M+1),onDelete:M=>{$r(M)}}),en&&e.jsx(Z,{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(Z,{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:[Qs&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n?.container==="running"&&e.jsxs(qe,{action:"stop",pending:c,onClick:()=>{He("stop")},children:[e.jsx(xo,{size:12})," ",t("vm.safety.stop")]}),e.jsxs(qe,{action:"remove",pending:c,onClick:()=>{He("remove")},danger:!0,children:[e.jsx(Ee,{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 Wi(s){return t("pairing.worksOnceUntil",{time:Wr(s)})}function bs(s,n=Date.now()){const a=Math.max(0,Math.floor((n-s)/6e4));return a<1?t("remote.serverPairing.justNow"):a<60?t("remote.serverPairing.minutesAgo",{minutes:a}):a<1440?t("remote.serverPairing.hoursAgo",{hours:Math.round(a/60)}):t("remote.serverPairing.daysAgo",{days:Math.round(a/1440)})}const Um="/api/team/phone-pairing",$n="/api/team/phones",Fm=4e3;function Dm(s){return`${s.label} · ${s.email}`}function _m({team:s,blocked:n}){const[a,i]=l.useState(null),[r,c]=l.useState(null),[o,d]=l.useState(null),[m,u]=l.useState(!1),[x,p]=l.useState(null),[h,f]=l.useState(()=>Date.now()),y=N=>p(t("remote.serverPairing.error",{error:N instanceof Error?N.message:String(N)}));async function b(){try{const N=await O($n);c(Array.isArray(N?.phones)?N.phones:[]),d(typeof N?.current=="string"?N.current:null)}catch(N){y(N)}}l.useEffect(()=>{b()},[]);const g=a?a.expiresAt<=h:!1;l.useEffect(()=>{if(!a)return;const N=setInterval(()=>f(Date.now()),15e3);return()=>clearInterval(N)},[a]),l.useEffect(()=>{if(!a||g)return;const N=setInterval(()=>{b()},Fm);return()=>clearInterval(N)},[a,g]);async function k(){u(!0),p(null);try{i(await O(Um,{method:"POST",body:"{}"})),f(Date.now())}catch(N){y(N)}finally{u(!1)}}async function C(N){p(null);try{await O(`${$n}/${encodeURIComponent(N)}`,{method:"DELETE"})}catch(w){y(w)}await b()}return e.jsxs(Z,{title:t("teamPhone.title"),subtitle:t("teamPhone.subtitle",{team:s}),children:[e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:e.jsx("button",{type:"button","data-phone-pairing-action":!0,onClick:()=>{k()},disabled:m||!!n,title:n??void 0,className:"ui-button ui-button-primary",children:m?t("remote.serverPairing.creating"):t("remote.serverPairing.create")})}),n?e.jsx("p",{role:"status","data-team-phone-blocked":!0,className:"mt-3 text-[13px] text-ink-secondary",children:n}):null,a?e.jsx("div",{"data-team-phone-code":!0,className:"mt-4 rounded-lg border border-hairline/40 bg-inset p-4",children:g?e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("remote.serverPairing.expired")}):e.jsxs("div",{className:"flex flex-wrap items-start gap-5",children:[a.url?e.jsx("div",{className:"rounded-md bg-white p-2",children:e.jsx(Ga,{value:a.url,size:160,level:"M",bgColor:"#ffffff",fgColor:"#111111"})}):null,e.jsxs("div",{className:"min-w-[200px] flex-1",children:[e.jsx("div",{className:"font-mono text-[18px] tracking-[0.14em] text-ink",children:a.code}),e.jsx("div",{className:"mt-1 text-[13px] text-ink-secondary",children:Wi(a.expiresAt)}),a.url?null:e.jsx("p",{className:"mt-3 text-[13px] text-ink-secondary",children:a.hint??t("remote.serverPairing.noLink")})]})]})}):null,e.jsx("p",{className:"mt-3 text-[13px] text-ink-secondary",children:t("teamPhone.stays",{team:s})}),r?e.jsxs("div",{"data-team-phones":!0,children:[e.jsx("div",{className:"mt-5 text-[13px] font-medium text-ink",children:t("remote.serverPairing.devices")}),r.length===0?e.jsx("p",{className:"mt-1 text-[13px] text-ink-secondary",children:t("remote.serverPairing.noDevices")}):e.jsx("ul",{className:"mt-1 divide-y divide-hairline/40",children:r.map(N=>e.jsxs("li",{"data-team-phone":N.id,className:"flex flex-wrap items-center justify-between gap-2 py-2 text-[13px]",children:[e.jsxs("span",{className:"text-ink",children:[Dm(N),e.jsxs("span",{className:"text-ink-secondary",children:[" · ",t("remote.serverPairing.seen",{when:bs(N.lastSeenAt,h)}),N.id===o?` · ${t("remote.serverPairing.thisBrowser")}`:""]})]}),N.id===o?null:e.jsx("button",{type:"button","data-team-phone-remove":!0,onClick:()=>{C(N.id)},className:"ui-button",children:t("teamPhone.remove")})]},N.id))})]}):null,x?e.jsx("p",{className:"mt-3 text-[13px] text-danger",children:x}):null]})}function $m({saved:s,onSaved:n,className:a}){const[i,r]=l.useState(s),[c,o]=l.useState(!1),[d,m]=l.useState(null);l.useEffect(()=>r(s),[s]);async function u(){const x=i.trim();if(!(c||x===s)){o(!0),m(null);try{const p=await O("/api/config",{method:"PATCH",body:JSON.stringify({computerName:x})});n(p.computerName??x)}catch(p){m(t("remote.computerName.error",{error:p instanceof Error?p.message:String(p)}))}finally{o(!1)}}}return e.jsxs("div",{"data-computer-name":!0,className:z("flex flex-col gap-1",a),children:[e.jsx("label",{htmlFor:"computer-name",className:"text-[13px] font-medium text-ink",children:t("remote.computerName.title")}),e.jsx("input",{id:"computer-name",value:i,disabled:c,placeholder:t("remote.computerName.placeholder"),"aria-describedby":"computer-name-help",onChange:x=>r(x.target.value),onBlur:()=>{u()},onKeyDown:x=>{x.key==="Enter"&&x.currentTarget.blur()},className:"w-full max-w-xs 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("p",{id:"computer-name-help",className:"text-[12px] leading-4 text-ink-secondary",children:t("remote.computerName.help")}),d?e.jsx("p",{role:"alert",className:"text-[12px] leading-4 text-danger",children:d}):null]})}function ot(s){return yd(s)}function Km(s){return s?.kind==="session"&&!s.scopes.includes("admin")?"chat-only":null}function Hm(s,n){return n?s.filter(a=>a.scopes.includes("admin")):s}const Wm="ui-button ui-button-primary",Kn="ui-button";function Gm({initialSession:s=null,initialPairingCodes:n=!0,cloudHome:a=!1,focusRequest:i=0,team:r,teamPhoneBlocked:c=null,simple:o=!1,reveal:d=!0}){const[m,u]=l.useState(s),[x,p]=l.useState(n),[h,f]=l.useState(null),[y,b]=l.useState("admin"),[g,k]=l.useState(null),[C,N]=l.useState([]),[w,P]=l.useState(null),[v,B]=l.useState(!1),[j,A]=l.useState("idle"),[I,H]=l.useState(null),[D,V]=l.useState(()=>Date.now()),$=l.useRef(null),se=l.useRef(0);async function ne(){try{const F=await O("/api/auth/sessions");N(Array.isArray(F?.sessions)?F.sessions:[]),P(typeof F?.current=="string"?F.current:null)}catch(F){H(t("remote.serverPairing.error",{error:F instanceof Error?F.message:String(F)}))}}if(l.useEffect(()=>{ui().then(F=>{u(F),ot(F)&&ne(),(F.kind==="loopback"||F.kind==="session")&&O("/api/config").then(te=>{p(mi(te).pairingCodes),ot(F)&&f(typeof te?.computerName=="string"?te.computerName:"")}).catch(()=>{})})},[]),l.useEffect(()=>{i?se.current!==i&&bd($.current)&&(se.current=i):se.current=0},[i,m]),l.useEffect(()=>{if(!g)return;const F=setInterval(()=>V(Date.now()),15e3);return()=>clearInterval(F)},[g]),r&&m?.kind==="session"&&m.team)return e.jsx("div",{ref:$,tabIndex:-1,"data-phone-pairing":"server",className:"scroll-mt-4 rounded-xl focus:outline-none",children:e.jsx(_m,{team:r,blocked:c})});if(!ot(m))return Km(m)!=="chat-only"?null:e.jsx("div",{ref:$,tabIndex:-1,"data-phone-pairing":"server",className:"scroll-mt-4 rounded-xl focus:outline-none",children:e.jsx(Z,{title:t("remote.serverPairing.title"),subtitle:t(x?"remote.serverPairing.subtitle":"remote.serverPairing.portalSubtitle"),children:e.jsx("p",{"data-server-pairing-chat-only":!0,className:"mt-3 text-[13px] text-ink-secondary",children:t(x?"remote.serverPairing.chatOnly":"remote.serverPairing.portalChatOnly")})})});const ce=g?g.expiresAt<=D:!1,T=Hm(C,a);async function U(){B(!0),H(null),A("idle");try{const F=await O("/api/auth/pairing",{method:"POST",body:JSON.stringify({scopes:y==="admin"||a?["admin","client"]:["client"]})});k(F),V(Date.now())}catch(F){H(t("remote.serverPairing.error",{error:F instanceof Error?F.message:String(F)}))}finally{B(!1)}}async function Q(F){H(null);try{await O(`/api/auth/sessions/${encodeURIComponent(F)}`,{method:"DELETE"}),await ne()}catch(te){H(t("remote.serverPairing.error",{error:te instanceof Error?te.message:String(te)}))}}async function le(){if(!g?.url)return;const F=await jl(g.url);F!=="empty"&&A(F)}const he=x&&g?e.jsx("div",{className:"mt-4 rounded-lg border border-hairline/40 bg-inset p-4",children:ce?e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("remote.serverPairing.expired")}):e.jsxs("div",{className:"flex flex-wrap items-start gap-5",children:[g.url?e.jsx("div",{className:"rounded-md bg-white p-2",children:e.jsx(Ga,{value:g.url,size:160,level:"M",bgColor:"#ffffff",fgColor:"#111111"})}):null,e.jsxs("div",{className:"min-w-[200px] flex-1",children:[e.jsx("div",{className:"font-mono text-[18px] tracking-[0.14em] text-ink",children:g.code}),e.jsx("div",{className:"mt-1 text-[13px] text-ink-secondary",children:Wi(g.expiresAt)}),g.url?e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsx("code",{className:"break-all text-[12px] text-ink-secondary",children:g.url}),e.jsx("button",{type:"button",onClick:()=>{le()},className:Kn,children:t(j==="copied"?"remote.serverPairing.copied":j==="failed"?"common.copyFailed":"remote.serverPairing.copyLink")})]}):e.jsx("p",{className:"mt-3 text-[13px] text-ink-secondary",children:g.hint??t("remote.serverPairing.noLink")})]})]})}):null,S=F=>x&&!a&&h!==null?e.jsx($m,{saved:h,onSaved:f,className:F}):null,ae=F=>t(F.scopes.includes("admin")?"remote.serverPairing.scope.admin":"remote.serverPairing.scope.client");return o?e.jsxs("div",{ref:$,tabIndex:-1,"data-phone-pairing":"server",className:"flex scroll-mt-4 flex-col gap-1.5 focus:outline-none",children:[e.jsxs("div",{"data-settings-rows":"",className:z(Va,"flex flex-col"),children:[S("px-4 py-2.5"),e.jsx(ue,{title:t("settings.simple.computer.pair"),subtitle:x?a?t("remote.serverPairing.cloudPersonal"):void 0:t("remote.serverPairing.portal"),children:x?e.jsxs("div",{className:"flex items-center gap-2",children:[a?null:e.jsxs(pe,{variant:"ghost",value:y,"aria-label":t("remote.serverPairing.title"),onChange:F=>b(F.target.value==="client"?"client":"admin"),children:[e.jsx("option",{value:"admin",children:t("remote.serverPairing.scope.admin")}),e.jsx("option",{value:"client",children:t("remote.serverPairing.scope.client")})]}),e.jsx("button",{type:"button","data-phone-pairing-action":d?"":void 0,onClick:()=>{U()},disabled:v,className:"ui-button",children:v?t("remote.serverPairing.creating"):t("settings.simple.computer.createCode")})]}):null}),he?e.jsx("div",{className:"px-4 pb-2.5 [&>div]:mt-0",children:he}):null,T.length===0?e.jsx("p",{className:"px-4 py-2.5 text-[13px] leading-[18px] text-ink-secondary",children:t("remote.serverPairing.noDevices")}):T.map(F=>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:"min-w-[min(100%,15rem)] flex-1 text-[14px] leading-5 text-ink",children:[F.label,e.jsxs("span",{className:"text-ink-secondary",children:[" · ",ae(F)," · ",t("remote.serverPairing.seen",{when:bs(F.lastSeenAt,D)}),F.id===w?` · ${t("remote.serverPairing.thisBrowser")}`:""]})]}),F.id===w?null:e.jsx("button",{type:"button",onClick:()=>{Q(F.id)},className:"ui-button ml-auto shrink-0",children:t("remote.serverPairing.signOut")})]},F.id))]}),I?e.jsx("p",{className:"pl-4 text-[12px] leading-4 text-danger",children:I}):null]}):e.jsx("div",{ref:$,tabIndex:-1,"data-phone-pairing":"server",className:"scroll-mt-4 rounded-xl focus:outline-none",children:e.jsxs(Z,{title:t("remote.serverPairing.title"),subtitle:t(x?"remote.serverPairing.subtitle":"remote.serverPairing.portalSubtitle"),children:[x&&a?e.jsx("p",{"data-server-pairing-personal":!0,className:"mt-3 text-[13px] text-ink-secondary",children:t("remote.serverPairing.cloudPersonal")}):null,S("mt-3"),x?e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[a?null:e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-[13px] text-ink",children:[e.jsx("input",{type:"radio",name:"server-pairing-scope",checked:y==="admin",onChange:()=>b("admin")}),t("remote.serverPairing.scope.admin")]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[13px] text-ink",children:[e.jsx("input",{type:"radio",name:"server-pairing-scope",checked:y==="client",onChange:()=>b("client")}),t("remote.serverPairing.scope.client")]})]}),e.jsx("button",{type:"button","data-phone-pairing-action":d?"":void 0,onClick:()=>{U()},disabled:v,className:Wm,children:v?t("remote.serverPairing.creating"):t("remote.serverPairing.create")})]}):e.jsx("p",{"data-server-pairing-portal":!0,className:"mt-3 text-[13px] text-ink-secondary",children:t("remote.serverPairing.portal")}),he,e.jsx("div",{className:"mt-5 text-[13px] font-medium text-ink",children:t(x?"remote.serverPairing.devices":"remote.serverPairing.portalDevices")}),T.length===0?e.jsx("p",{className:"mt-1 text-[13px] text-ink-secondary",children:t("remote.serverPairing.noDevices")}):e.jsx("ul",{className:"mt-1 divide-y divide-hairline/40",children:T.map(F=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2 py-2 text-[13px]",children:[e.jsxs("span",{className:"text-ink",children:[F.label,F.email?e.jsxs("span",{className:"text-ink-secondary",children:[" · ",F.email]}):null,e.jsxs("span",{className:"text-ink-secondary",children:[" · ",F.scopes.includes("admin")?t("remote.serverPairing.scope.admin"):t("remote.serverPairing.scope.client")," · ",t("remote.serverPairing.seen",{when:bs(F.lastSeenAt,D)}),F.id===w?` · ${t("remote.serverPairing.thisBrowser")}`:""]})]}),F.id===w?null:e.jsx("button",{type:"button",onClick:()=>{Q(F.id)},className:Kn,children:t("remote.serverPairing.signOut")})]},F.id))}),I?e.jsx("p",{className:"mt-3 text-[13px] text-danger",children:I}):null]})})}function Vm({profileEmail:s="",focusRequest:n=0,simple:a=!1}){return e.jsx(ho,{})}function qm(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 Hn(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 Jm(s,n){return{admins:s.admins.filter(a=>a!==n),members:s.members.filter(a=>a!==n)}}function Wn(s,n){const a=s.replace(/\/+$/,"");return n.startsWith("@")?`${a}/pair`:`${a}/pair?email=${encodeURIComponent(n)}`}function Xm(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,...ct(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 Ym(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 Qm(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 Gi({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?"—":Qm(d.lastSeenAt)}),e.jsx("span",{className:"text-right tabular-nums text-ink",title:t("people.turns",{turns:String(d.turns)}),children:ct(d.costUsd)?`${d.estimated?"~":""}${dt(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(go,{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 Vi({link:s}){const{state:n,copy:a}=As(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(fe,{size:13,className:"text-success"}):n==="failed"?e.jsx($e,{size:13,className:"text-danger"}):e.jsx(Ta,{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 Zm({peopleUrl:s,people:n}){const a=()=>{};return e.jsxs(Z,{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(xt,{size:14,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Gi,{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 qi({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),[h,f]=l.useState([]),[y,b]=l.useState(typeof window<"u"?window.location.origin:""),[g,k]=l.useState(null),[C,N]=l.useState(""),[w,P]=l.useState("member"),[v,B]=l.useState(null),[j,A]=l.useState(!1),[I,H]=l.useState(!1),[D,V]=l.useState(null),$=l.useCallback(async()=>{H(!0),V(null);try{const[U,Q,le,he,S]=await Promise.all([O("/api/config"),O("/api/auth/sessions").catch(()=>({sessions:[]})),O("/api/usage?groupBy=user").catch(()=>({groups:[]})),O("/api/settings/custom-domain").catch(()=>null),fetch("/.well-known/openmausbot/environment").then(ie=>ie.ok?ie.json():null).catch(()=>null)]),ae={admins:Array.isArray(U?.signIn?.admins)?U.signIn.admins:[],members:Array.isArray(U?.signIn?.members)?U.signIn.members:[]},F=mi(U);u(F),p(ae);const te=Array.isArray(Q?.sessions)?Q.sessions:[],q=Array.isArray(le?.groups)?le.groups:[];f(F.authority==="portal"?Ym(te,q):Xm(ae,te,q)),typeof he?.publicUrl=="string"&&he.publicUrl&&b(he.publicUrl),k(S?.capabilities?.emailSignIn===!0?!0:S?!1:null)}catch(U){V(U instanceof Error?U.message:String(U))}finally{H(!1)}},[]);l.useEffect(()=>{ui().then(U=>{d(U),ot(U)&&$()})},[$]);const se=async U=>{A(!0),V(null);try{await O("/api/config",{method:"PUT",body:JSON.stringify({signIn:U})}),await $()}catch(Q){V(Q instanceof Error?Q.message:String(Q))}finally{A(!1)}},ne=async()=>{if(c(!0),!x||j)return;const U=qm(C);if(!U){V(t("remote.signInAccess.invalid"));return}await se(Hn(x,U,w)),N(""),B(Wn(y,U))};if(!ot(o))return null;const ce=m?.authority==="portal"?e.jsx(Zm,{peopleUrl:m.peopleUrl,people:h}):null,T=e.jsxs(e.Fragment,{children:[g===!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:U=>{U.preventDefault(),ne()},children:[e.jsx("input",{value:C,onChange:U=>N(U.target.value),placeholder:t("remote.signInAccess.placeholder"),"aria-label":t("people.inviteEmail"),disabled:j,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(pe,{value:w,onChange:U=>P(U.target.value),"aria-label":t("people.colRole"),disabled:j,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:j||!C.trim(),className:"ui-button ui-button-primary",children:[j?e.jsx(Y,{size:13,className:"animate-spin"}):e.jsx(Ce,{size:13}),t("people.invite")]}),e.jsx("button",{type:"button",onClick:()=>{$()},disabled:I||j,"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(Se,{size:13,className:z(I&&"animate-spin")})})]}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-ink-secondary",children:t("people.inviteHint")}),v&&e.jsx(Vi,{link:v}),D&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:D}),e.jsx("div",{className:"mt-4",children:e.jsx(Gi,{people:h,busy:j,onRole:(U,Q)=>{x&&se(Hn(x,U.entry,Q))},onRemove:U=>{x&&se(Jm(x,U.entry))},onLink:U=>B(Wn(y,U.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(Et,{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:ce??T})]}):ce??e.jsx(Z,{title:t("people.title"),subtitle:t("people.subtitle"),children:T})}const is="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 ep({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(Es())}),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:Pd(s.who)}),e.jsx("span",{className:"min-w-0 break-words text-ink",children:Td(s)})]}),s.type==="approval"&&s.summary&&e.jsx("div",{className:"mt-0.5 truncate text-[12px] text-ink-secondary",children:fo(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(Ls,{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:Pn(s.before?.[r])}),e.jsx("dd",{className:"min-w-0 break-all font-mono text-ink",children:Pn(s.after?.[r])})]},r))]})]})]})})}function Ji(){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),h=Ad(s),f=l.useCallback(async()=>{u(!0),p(null);try{const b=await O(`/api/admin-activity${h}`);i(b.entries),c(b.total),d(b.retentionDays)}catch(b){p(b instanceof Error?b.message:String(b))}finally{u(!1)}},[h]);l.useEffect(()=>{const b=window.setTimeout(()=>{f()},250);return()=>window.clearTimeout(b)},[f]);const y=b=>n(g=>({...g,...b}));return e.jsxs(Z,{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(is,"w-44")})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("activity.what"),e.jsx(pe,{value:s.what,onChange:b=>y({what:b.target.value}),children:Id.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:is})]}),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:is})]}),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(Y,{size:14,className:"animate-spin"}):e.jsx(Se,{size:14})}),e.jsxs("a",{href:`/api/admin-activity.csv${h}`,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,g)=>e.jsx(ep,{entry:b},`${b.at}-${g}`))}),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 Gn=4,Hs="flex w-full min-w-0 items-center gap-3 px-3 py-2 text-start",Ws="flex flex-col divide-y divide-hairline/30 overflow-hidden rounded-xl border border-hairline/40 bg-card",tp=s=>s.filter(n=>!n.hidden&&!n.defaultBot?.person).sort((n,a)=>n.name.localeCompare(a.name)),Xi=(s,n)=>Ft(s)===n||Xa(Dt(s),n)!=="none",Yi=(s,n)=>{const a=qa(s,n);return a?t("lookedAfter.line",{name:a.name}):t("lookedAfter.nobody")},Vn=(s,...n)=>n.some(a=>a?.toLowerCase().includes(s));function sp(){const{state:s}=G(),n=bo(),a=yo(),i=l.useRef(null),[r,c]=l.useState("bot"),[o,d]=l.useState(""),[m,u]=l.useState(null),[x,p]=l.useState(null),h=l.useRef(null),[f,y]=l.useState(null),[b,g]=l.useState(""),k=l.useCallback(()=>y(null),[]);if(l.useEffect(()=>{x||!h.current||([...i.current?.querySelectorAll("[data-access-person]")??[]].find(j=>j.dataset.accessPerson===h.current)?.focus(),h.current=null)},[x]),!n||!a)return null;const C=n.people.filter(j=>j.role==="member").sort((j,A)=>j.name.localeCompare(A.name)),N=tp(s.bots),w=m?N.find(j=>j.id===m):void 0,P=x?C.find(j=>j.email===x):void 0,v=o.trim().toLowerCase(),B=async(j,A,I)=>{g("");const H=Dt(j);try{await pn(j.id,A),y({botId:j.id,before:H,after:A,text:I})}catch(D){g(D instanceof Error?D.message:String(D))}};return e.jsxs("div",{ref:i,className:"flex min-w-0 flex-col gap-3","data-access-overview":!0,children:[P?e.jsx(rp,{person:P,bots:N.filter(j=>Xi(j,P.email)),team:n,teamName:a,apply:B,onBack:()=>{h.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(pt,{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:j=>d(j.target.value),onKeyDown:j=>{j.key==="Escape"&&o&&(j.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(j=>e.jsx("button",{type:"button","aria-pressed":r===j,"data-access-listing":j,onClick:()=>{c(j),d("")},className:z("rounded-full px-3 py-1 text-[13px] leading-[18px]",r===j?"bg-menu font-medium text-ink shadow-sm":"text-ink-secondary hover:text-ink"),children:t(j==="bot"?"botAccess.overview.byBot":"botAccess.overview.byPerson")},j))})]}),r==="bot"?e.jsx(np,{bots:N.filter(j=>!v||Vn(v,j.name,qa(j,n)?.name,Ft(j)??void 0)),anyBots:N.length>0,team:n,onOpen:u}):e.jsx(ip,{people:C.filter(j=>!v||Vn(v,j.name,j.email)),anyPeople:C.length>0,bots:N,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}),w&&e.jsx(vo,{bot:w,teamName:a,onClose:()=>u(null),onChanged:j=>y({botId:w.id,...j})}),f&&e.jsx(jo,{text:f.text,onUndo:()=>pn(f.botId,f.before),onDone:k},`${f.botId}:${f.text}:${JSON.stringify(f.after)}`)]})}function np({bots:s,anyBots:n,team:a,onOpen:i}){return n?s.length?e.jsx("ul",{className:Ws,children:s.map(r=>{const c=Dt(r),o=Ft(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(Hs,"hover:bg-ink/[0.06] focus-visible:bg-ink/[0.06] focus-visible:outline-none"),children:[e.jsx(Ot,{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:Yi(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(ap,{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 ap({entries:s,team:n}){if(!s.length)return null;const a=s.map(r=>No(r,n)).join(", "),i=s.length-Gn;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,Gn).map(r=>e.jsx("span",{className:"flex rounded-full ring-2 ring-card",children:e.jsx(wo,{person:So(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 ip({people:s,anyPeople:n,bots:a,onOpen:i}){return n?s.length?e.jsx("ul",{className:Ws,children:s.map(r=>{const c=a.filter(o=>Xi(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(Hs,"hover:bg-ink/[0.06] focus-visible:bg-ink/[0.06] focus-visible:outline-none"),children:[e.jsx(Ja,{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 rp({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(Gr,{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(Ja,{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:Ws,children:n.map(o=>e.jsx(lp,{bot:o,person:s,team:a,teamName:i,apply:r},o.id))})]})}function lp({bot:s,person:n,team:a,teamName:i,apply:r}){const c=Dt(s),o=Ft(s)===n.email,d=c.people[n.email],m=Xa(c,n.email);return e.jsxs("li",{className:Hs,"data-access-person-bot":s.id,children:[e.jsx(Ot,{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}):Yi(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,ko(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 op(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 cp({domain:s,serverIpv4:n}){const a=op(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 dp(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 up({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:dp(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(xt,{size:12})]})]})}function mp(){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 O("/api/settings/custom-domain",{signal:p.signal}).then(h=>{p.signal.aborted||(n(h),i(h.customDomain??""))}).catch(h=>{p.signal.aborted||d(h instanceof Error?h.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 h=await O("/api/settings/custom-domain",{method:p?"DELETE":"POST",...p?{}:{body:JSON.stringify({domain:a.trim()})}});n(h),i(h.customDomain??""),u(p?t("settings.domain.removed"):t("settings.domain.saved"))}catch(h){d(h instanceof Error?h.message:t("settings.domain.failed"))}finally{c(null)}};return e.jsx(Z,{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(Y,{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(cp,{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(Y,{size:14,className:"animate-spin"}):e.jsx(Co,{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(up,{status:s})]}),m&&e.jsxs("p",{role:"status",className:"flex items-start gap-1.5 text-[12px] leading-relaxed text-success",children:[e.jsx(fe,{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 pp=Eo,ys="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",vs="flex flex-col gap-1 text-[12px] font-medium text-ink-secondary";function Qi({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(_t,{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(Y,{size:13,className:"animate-spin"}),r]})]})]})}function qn({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),[h,f]=l.useState(null),y=async b=>{if(b.preventDefault(),!x){p(!0),f(null);try{s?await Ao(s.id,{...r.trim()!==s.name?{name:r.trim()}:{},value:o,bots:m}):await Io(r.trim(),o,m),d(""),await i()}catch(g){f(g instanceof Error&&g.message?g.message:t("settings.vault.secret.saveError"))}finally{p(!1)}}};return e.jsxs(Qi,{form:"secret-form",onSubmit:b=>{y(b)},onCancel:a,pending:x,error:h,submitLabel:t(s?"settings.logins.saveChange":"settings.vault.secret.save"),children:[e.jsxs("label",{className:vs,children:[t("settings.vault.secret.name"),e.jsx("input",{name:"secretName",type:"text",autoComplete:"off",spellCheck:!1,required:!0,maxLength:pp,value:r,autoFocus:!0,placeholder:t("settings.vault.secret.namePlaceholder"),onChange:b=>c(b.target.value),disabled:x,className:ys}),e.jsx("span",{className:"text-[12px] font-normal leading-snug text-ink-tertiary",children:t("settings.vault.secret.nameHint")})]}),e.jsxs("label",{className:vs,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:ys})]}),e.jsx(ut,{value:m,onChange:u,bots:n,disabled:x})]})}function xp({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,h]=l.useState(null),f=async y=>{if(y.preventDefault(),d)return;const b=Po(i);if(!b.length){x(t("settings.vault.env.none"));return}m(!0),x(null),h(null);try{h(await To(b,c)),r("")}catch(g){x(g instanceof Error&&g.message?g.message:t("settings.vault.secret.saveError"))}finally{m(!1),await a().catch(()=>{})}};return e.jsxs(Qi,{form:"env-form",onSubmit:y=>{f(y)},onCancel:n,pending:d,error:u,submitLabel:t("settings.vault.env.submit"),children:[e.jsxs("label",{className:vs,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:`${ys} font-mono`}),e.jsx("span",{className:"text-[12px] font-normal leading-snug text-ink-tertiary",children:t("settings.vault.env.hint")})]}),e.jsx(ut,{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 Jn={card:"settings.logins.source.card",settings:"settings.logins.source.settings","1password":"settings.logins.source.1password",linked:"settings.logins.source.1password"},js="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",hp=[["login","settings.vault.addLogin"],["secret","settings.vault.addSecret"],["env","settings.vault.importEnv"]];function gp(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 Zi(){const{state:s,dispatch:n}=G(),a=Mt(),i=s.bots.map(E=>({id:E.id,name:E.name})),[r,c]=l.useState(null),[o,d]=l.useState([]),[m,u]=l.useState({connected:!1}),[x,p]=l.useState(null),[h,f]=l.useState(""),[y,b]=l.useState("all"),[g,k]=l.useState(!1),[C,N]=l.useState(null),[w,P]=l.useState(""),[v,B]=l.useState("all"),[j,A]=l.useState(!1),[I,H]=l.useState(null),[D,V]=l.useState("all"),[$,se]=l.useState(!1),[ne,ce]=l.useState(!1),[T,U]=l.useState(null),[Q,le]=l.useState(!1),[he,S]=l.useState([]),ae=async()=>{try{const E=await Bo();c(E.logins??[]),d(E.secrets??[]),u(E.onePassword??{connected:!1}),p(null)}catch(E){p(E instanceof Error&&E.message?E.message:t("settings.vault.loadError"))}};if(l.useEffect(()=>{a&&ae()},[a]),a===!1)return e.jsx(Z,{title:t("settings.vault.title"),subtitle:t("settings.vault.adminOnly")});const F=E=>{if(E==="all")return t("settings.logins.allBots");const W=E.flatMap(xe=>i.find(X=>X.id===xe)?.name??[]);return W.length?W.join(", "):t("settings.logins.noBots")},te=E=>E?t("settings.logins.used",{when:di(E)}):t("settings.logins.neverUsed"),q=(E,W)=>{N(null),U(null),ce(!1),W&&(V(W.bots),se(W.exactHost)),H(E)},ie=E=>{k(!1),H(null),U(null),N(E)},re=async(E,W)=>{if(T!==E){U(E);return}le(!0),S([]);try{W==="login"?await Uo(E):S(await Fo(E)),U(null),await ae()}catch(xe){p(xe instanceof Error&&xe.message?xe.message:t("settings.logins.deleteError"))}finally{le(!1)}},de=(E,W,xe,X)=>e.jsxs("div",{className:"flex shrink-0 gap-1",children:[e.jsx("button",{type:"button",className:js,disabled:Q,onClick:X,"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:js,disabled:Q,onClick:()=>{re(E,W)},"aria-label":T===E?t("settings.logins.deleteConfirm"):W==="login"?t("settings.logins.deleteFor",{site:xe}):t("settings.vault.secret.deleteFor",{name:xe}),children:[e.jsx(Ee,{size:13}),T===E?t("settings.logins.deleteConfirm"):t("settings.logins.delete")]})]}),ve=gp(r??[],o,y,h),K=r!==null&&r.length===0&&o.length===0,oe=E=>e.jsxs("li",{className:"flex flex-col gap-2 py-2.5","data-login-row":E.site,children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx(_t,{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:E.site,children:E.site}),E.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(Oo,{size:11,"aria-hidden":"true"}),t("settings.logins.twoFactor")]})]}),e.jsx("div",{dir:"auto",className:"truncate text-[12px] text-ink-secondary",children:E.username||t("settings.logins.noUsername")}),Xn(E)&&e.jsx("div",{dir:"ltr",className:"truncate text-[12px] text-ink-tertiary","data-login-hosts":!0,children:Xn(E)}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-snug text-ink-tertiary",children:[t(Jn[E.source]),F(E.bots),te(E.lastUsedAt)].join(" · ")}),hn(E,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:F(hn(E,s.bots))})})]}),E.source!=="1password"&&de(E.id,"login",E.site,()=>q(E.id,E))]}),I===E.id&&e.jsx("div",{className:"ms-6 rounded-lg bg-inset/60 p-3",children:e.jsxs(xn,{username:!1,replacing:!0,submitLabel:t("settings.logins.saveChange"),autoFocus:!0,onCancel:()=>H(null),onSubmit:async W=>{await Mo(E.id,{password:W.password,totp:W.totp,removeTotp:ne,bots:D,...$===E.exactHost?{}:{exactHost:$}}),H(null),await ae()},children:[E.hasTotp&&e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-ink",children:[e.jsx("input",{type:"checkbox",checked:ne,onChange:W=>ce(W.target.checked)}),t("settings.logins.removeTotp")]}),e.jsx(Yn,{checked:$,onChange:se,label:t("settings.logins.exactHostFor",{hosts:E.hosts.join(", "),site:E.site})}),e.jsx(ut,{value:D,onChange:V,bots:i})]})})]},E.id),R=E=>e.jsxs("li",{className:"flex flex-col gap-2 py-2.5","data-secret-row":E.name,children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[e.jsx(Ya,{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:E.name,children:E.name}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-snug text-ink-tertiary",children:[t(Jn[E.source]),F(E.bots),te(E.lastUsedAt)].join(" · ")})]}),E.source!=="linked"&&de(E.id,"secret",E.name,()=>q(E.id))]}),I===E.id&&E.source!=="linked"&&e.jsx("div",{className:"ms-6 rounded-lg bg-inset/60 p-3",children:e.jsx(qn,{secret:E,bots:i,onCancel:()=>H(null),onSaved:async()=>{H(null),await ae()}})})]},E.id);return e.jsx(Z,{title:t("settings.vault.title"),subtitle:t("settings.vault.subtitle"),children:e.jsxs("div",{className:"flex flex-col gap-3","aria-busy":r===null||Q,"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(pt,{size:15,"aria-hidden":"true",className:"shrink-0 text-ink-secondary"}),e.jsx("input",{"data-vault-search":!0,type:"text",value:h,onChange:E=>f(E.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":g,onClick:()=>k(!g),onKeyDown:E=>{E.key==="Escape"&&k(!1)},children:[e.jsx(Ce,{size:14}),t("settings.vault.add"),e.jsx(Ia,{size:13,"aria-hidden":"true"})]}),g&&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:hp.map(([E,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:()=>ie(E),children:t(W)},E))})]})]}),e.jsx(Ro,{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")}]}),C==="login"&&e.jsx("div",{className:"rounded-lg bg-inset/60 p-3",children:e.jsxs(xn,{site:{value:w,onChange:P},submitLabel:t("settings.logins.save"),autoFocus:!0,onCancel:()=>N(null),onSubmit:async E=>{await Lo(w,E,v,j),N(null),P(""),B("all"),A(!1),await ae()},children:[e.jsx(Yn,{checked:j,onChange:A,label:t("settings.logins.exactHost")}),e.jsx(ut,{value:v,onChange:B,bots:i})]})}),C==="secret"&&e.jsx("div",{className:"rounded-lg bg-inset/60 p-3",children:e.jsx(qn,{bots:i,onCancel:()=>N(null),onSaved:async()=>{N(null),await ae()}})}),C==="env"&&e.jsx("div",{className:"rounded-lg bg-inset/60 p-3",children:e.jsx(xp,{bots:i,onCancel:()=>N(null),onSaved:ae})}),r===null&&!x&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("settings.vault.loading")}),K&&!C&&e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:t("settings.vault.empty")}),!K&&r!==null&&ve.length===0&&e.jsx("p",{className:"text-[12px] text-ink-secondary","data-vault-none":!0,children:t("settings.vault.noMatch")}),ve.length>0&&e.jsx("ul",{className:"divide-y divide-hairline/30","data-logins-list":!0,children:ve.map(E=>E.kind==="login"?oe(E.login):R(E.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(bp,{status:m,disabled:r===null,bots:i,botNames:F,onChange:async E=>{u(E),await ae()}})]})})}function Xn(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 Yn({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 fp({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,h]=l.useState(null),f=async()=>{x(!0),h(null);try{await r(await Do(s.id,d)),o(!1)}catch(y){h(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:js,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(ut,{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 bp({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)}}},h=f=>{f.preventDefault(),c.trim()&&p("connect",()=>zo(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(fp,{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",_o)},children:[d==="refresh"?e.jsx(Y,{size:13,className:"animate-spin"}):e.jsx(Se,{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",$o)},children:t("settings.logins.onePassword.disconnect")})]})]}):e.jsxs("form",{className:"flex flex-col gap-2",onSubmit:h,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(Y,{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(_t,{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 rs="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 Qn(s){return String(s?.message??s).replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/,"")}function yp(s){const n=s.trim();if(!/^https?:\/\//i.test(n))return!1;const a=Vr(n);return a.ok&&(a.code!==null||a.credential!==null)}function vp({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(""),[h,f]=l.useState(""),[y,b]=l.useState(!1),[g,k]=l.useState(""),C=l.useRef(!1),N=!!i&&o==="server",w=l.useRef(!0),P=l.useCallback(()=>{a?.state().then(j=>{w.current&&c(j)}).catch(()=>{})},[a]);l.useEffect(()=>(w.current=!0,P(),()=>{w.current=!1}),[P]);const v=async()=>{if(!(C.current||!a&&!i)){C.current=!0,b(!0),k("");try{if(N&&i){if(!yp(m))throw new Error(t("remote.client.server.invalidLink"));await i.addFromLink(m.trim()),P()}else a&&(await a.pair(x,h),P())}catch(j){k(Qn(j))}finally{C.current=!1,b(!1)}}},B=async()=>{if(!(!a||C.current)){C.current=!0,b(!0),k("");try{await a.disconnect(),P()}catch(j){k(Qn(j))}finally{C.current=!1,b(!1)}}};return!a&&!i&&s||n&&!r.active?null:e.jsxs(Z,{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(Ct,{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(Y,{size:14,className:"animate-spin"}):e.jsx(Qd,{size:14}),t("remote.client.disconnect")]})]}):e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:j=>{j.preventDefault(),v()},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(pe,{value:o,disabled:y,onChange:j=>{d(j.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,N?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:j=>u(j.target.value),placeholder:"https://bots.example.com/pair#code=XXXX-XXXX-XXXX",disabled:y,autoCapitalize:"none",autoCorrect:"off",autoComplete:"off",spellCheck:!1,className:rs})]}),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:j=>p(j.target.value),placeholder:"https://…openmausbot.com or computer.tailnet.ts.net",disabled:y,autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,className:rs})]}),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:h,onChange:j=>f(j.target.value.replace(/\D/g,"").slice(0,6)),placeholder:"000000",disabled:y,inputMode:"numeric",autoComplete:"one-time-code",className:`${rs} max-w-40 font-mono tracking-[0.2em]`})]})]}),g?e.jsx("p",{role:"alert",className:"text-[13px] text-danger",children:g}):null,e.jsxs("button",{type:"submit",disabled:y||(N?!m.trim():x.trim()===""||h.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(Y,{size:14,className:"animate-spin"}):e.jsx(Ct,{size:14}),N?t("remote.client.server.connect"):t("remote.client.pair")]}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:N?t("remote.client.server.switchNote"):t("remote.client.restartNote")})]}),r.active&&g?e.jsx("p",{role:"alert",className:"mt-3 text-[13px] text-danger",children:g}):null]})}const jp={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 kp({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(Es())}),e.jsxs("span",{className:n.ok?"text-ink":"text-danger",children:[t(jp[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 Np({workspace:s,own:n=!1,onClose:a}){const{state:i}=G(),c=n||Qa(i.config)?window.ogb?.computerSharing:void 0,[o,d]=l.useState(null),[m,u]=l.useState([]),[x,p]=l.useState(!1),[h,f]=l.useState(!1),[y,b]=l.useState(!1),[g,k]=l.useState(""),[C,N]=l.useState(null),w=l.useRef(!1),P=l.useRef(!1),v=l.useRef(null),B=A=>{d(A),u(A.folders),p(A.terminal),f(A.computer)};l.useEffect(()=>{w.current=!0,v.current?.scrollIntoView({block:"start"}),c?.state(s.id).then(H=>{w.current&&B(H)}).catch(()=>{w.current&&k(t("computerSharing.loadFailed"))});const A=()=>{c?.state(s.id).then(H=>{w.current&&d(H)}).catch(()=>{}),c?.activity?.(s.id).then(H=>{w.current&&N(H)}).catch(()=>{})};A();const I=setInterval(A,3e3);return()=>{w.current=!1,clearInterval(I)}},[c,s.id]);const j=async A=>{if(!P.current){P.current=!0,b(!0),k("");try{await A()}catch(I){w.current&&k(String(I?.message??I).replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/,""))}finally{P.current=!1,w.current&&b(!1)}}};return c?e.jsx("div",{ref:v,children:e.jsx(Z,{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:()=>{j(async()=>{await(o.paused?c.resume?.():c.pause?.());const A=await c.state(s.id);w.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:I=>u(H=>H.map(D=>D.id===A.id?{...D,write:I.target.checked}:D))}),t("computerSharing.allowEdits")]}),e.jsx("button",{type:"button","aria-label":t("lending.removeFolder",{name:A.name}),onClick:()=>u(I=>I.filter(H=>H.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:()=>{j(async()=>{const A=await c.chooseFolder();w.current&&A&&u(I=>I.some(H=>H.path===A.path)?I:[...I,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(Ko,{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:h,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")})]})]})]}),(g||o?.error)&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:g||o?.error}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:y||!o||!m.length&&!x&&!h,onClick:()=>{j(async()=>{const A=await c.save(s.id,{folders:m,terminal:x,computer:h});w.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:()=>{j(async()=>{const A=await c.revoke(s.id);w.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(kp,{entries:C})})]})})}):null}const wp={https:"servers.transport.https",tailscale:"servers.transport.tailscale","private-http":"servers.transport.privateHttp",loopback:"servers.transport.loopback"},jt=s=>s.kind!=="local"&&!!s.origin&&!s.home&&!s.cloud&&!("team"in s&&s.team),Sp=s=>new Date(s).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});function Cp(s,n){return s==="docker"?"git pull && ./update.sh":s==="global"?`npm install -g openmausbot@${n}`:s==="source"?"git pull && pnpm install":`npx openmausbot@${n} serve`}function Ep({name:s,status:n,appVersion:a,onHide:i}){const{state:r,copy:c}=As(Cp(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 Ap({origin:s,name:n}){const{state:a,copy:i}=As(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(fe,{size:14}):e.jsx(Ta,{size:14})})}function Ip({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:Sp(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 Pp({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 Tp({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([]),[h,f]=l.useState([]),[y,b]=l.useState(null);l.useEffect(()=>{if(!u?.status)return;let w=!0;const P=()=>{u.status().then(B=>{w&&p(B)}).catch(()=>{})};P();const v=u.onStatus?.(P);return()=>{w=!1,v?.()}},[u,s]);const g=w=>x.find(P=>P.id===w),k=w=>b({address:w.origin,locked:!0,title:t("servers.pairAgainTitle",{name:w.name})}),C=w=>b({address:w.origin.replace(/^http:/,"https:"),locked:!1,title:t("connect.title")}),N=[{id:"local",name:t("place.local"),kind:"local"},...s.environments.filter(w=>w.kind!=="local")];return e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"divide-y divide-hairline/40",children:N.map(w=>{const P=w.id===s.activeId,v=jt(w)?g(w.id):void 0,B=w.id==="local"?Ct:Lt,j=w.id==="local"?t("servers.localHint"):jt(w)?`${new URL(w.origin).host} · ${t(wp[qr(w.origin)])}`:w.home?t("servers.managed"):new URL(w.origin).host,A=i.find(H=>H.id===w.id),I=v?.behind===!0&&r!==null&&!h.includes(`${w.id}:${v.version}`);return e.jsxs("li",{"data-server-row":w.id,className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[Jr(w.color)?e.jsx(Xr,{color:w.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:w.name}),e.jsx("div",{"data-server-where":!0,className:"break-all text-[12px] text-ink-secondary",children:j}),e.jsx(Ip,{status:v,onTryNow:()=>{u?.retry?.(w.id)},onPairAgain:()=>k(w),onEdit:()=>C(w)})]}),P?e.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[12px] text-ink-secondary",children:[e.jsx(fe,{size:13}),t("servers.current")]}):e.jsx("button",{type:"button",disabled:n,"aria-label":t("servers.switchTo",{name:w.name}),onClick:()=>c(w.id),className:"rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50",children:t("servers.switch")}),jt(w)&&v?.state!=="signedOut"&&e.jsx("button",{type:"button",disabled:n,onClick:()=>k(w),className:"rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control disabled:opacity-50",children:t("servers.pairAgain")}),w.id!=="local"&&!w.home&&!w.cloud&&!A&&a&&e.jsx("button",{type:"button",disabled:n,"aria-label":t("servers.computerAccessFor",{name:w.name}),onClick:()=>d(w.id),className:"rounded-md px-2 py-1.5 text-[12px] text-ink hover:bg-control",children:t("servers.computerAccess")}),jt(w)&&e.jsx(Ap,{origin:w.origin,name:w.name}),w.id!=="local"&&!w.home&&e.jsx("button",{type:"button",disabled:n,"aria-label":t("servers.removeName",{name:w.name}),title:t("servers.removeName",{name:w.name}),onClick:()=>o(w.id),className:"rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-danger disabled:opacity-50",children:e.jsx(Ee,{size:14})})]}),A&&e.jsx(Pp,{name:w.name,share:A,busy:n,onShare:H=>m(w.id,H),onOpen:()=>d(w.id)}),I&&e.jsx(Ep,{name:w.name,status:v,appVersion:r,onHide:()=>f(H=>[...H,`${w.id}:${v.version}`])})]},w.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(Ce,{size:14}),t("connect.title")]}),y&&e.jsx(kl,{focusKey:y.locked?"pair-again":"connect",onClose:()=>b(null),children:e.jsx(Nl,{onBack:null,onConnected:()=>b(null),start:y})})]})}function Zn(){const s=window.ogb?.environments,{state:n}=G(),a=Qa(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(""),[h,f]=l.useState(()=>new URLSearchParams(window.location?.search??"").get("share-computer")),[y,b]=l.useState(""),[g,k]=l.useState(""),[C,N]=l.useState(null),[w,P]=l.useState(!1),[v,B]=l.useState(""),j=l.useRef(!1),A=l.useRef(0);l.useEffect(()=>{const T=++A.current;return s?.state().then(U=>{A.current===T&&d(U)}).catch(()=>{A.current===T&&p(t("servers.loadFailed"))}),()=>{A.current++}},[s]),l.useEffect(()=>{if(!i?.servers||!o)return;let T=!0;const U=()=>{i.servers().then(le=>{T&&c(le)}).catch(()=>{})};U();const Q=setInterval(U,5e3);return()=>{T=!1,clearInterval(Q)}},[i,o]);const I=(T,U)=>{H(async()=>{U?await i?.allow?.(T)&&f(T):await i?.revoke(T),i?.servers&&c(await i.servers())})};l.useEffect(()=>{const T=U=>{U&&f(U);const Q=new URL(window.location.href);Q.searchParams.delete("share-computer"),window.history.replaceState(null,"",`${Q.pathname}${Q.search}${Q.hash}`)};return T(),s?.onOpenSettings?.(T)},[s]);const H=async(T,U=p)=>{if(j.current||!s)return;j.current=!0,u(!0),p(""),B("");const Q=A.current;try{if(await T()===!0)return;const le=await s.state();A.current===Q&&d(le)}catch(le){A.current===Q&&U(String(le?.message??le).replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/,""))}finally{j.current=!1,A.current===Q&&u(!1)}};if(!s)return e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("servers.desktopOnly")});const D=T=>window.ogb?.confirm?window.ogb.confirm(T):window.confirm(T),V=o?.environments.find(T=>T.id===h),$=V?.origin&&!V.home?{id:V.id,name:V.name,origin:V.origin}:void 0,se=!!($&&r.some(T=>T.id===$.id)),ne=o?.environments.filter(T=>T.kind==="local")??[],ce=ne.find(T=>T.id===C);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(Z,{title:t("connectedWorkspaces.localTitle"),subtitle:t("connectedWorkspaces.localSubtitle"),children:[v&&e.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:v}),ne.length>0&&e.jsx("ul",{className:"divide-y divide-hairline/40",children:ne.map(T=>{const U=T.id===o.activeId;return e.jsxs("li",{className:"flex items-center gap-3 py-3",children:[e.jsx(Ct,{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:T.name}),e.jsxs("div",{className:"break-all text-[12px] text-ink-secondary",children:[T.dataDir,T.missing&&e.jsx("span",{className:"ml-2 rounded-md bg-inset px-1.5 py-0.5 text-[11px]",children:t("connectedWorkspaces.missing")})]})]}),U?e.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[12px] text-ink-secondary",children:[e.jsx(fe,{size:13}),t("connectedWorkspaces.current")]}):e.jsx("button",{type:"button",disabled:m,"aria-label":t("connectedWorkspaces.switchTo",{name:T.name}),onClick:()=>{H(async()=>{if(!await D(t("connectedWorkspaces.switchConfirm",{name:T.name})))return;const Q=await s.switch(T.id);if(Q&&Q.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")}),!U&&e.jsx("button",{type:"button",disabled:m,"aria-label":t("connectedWorkspaces.forgetName",{name:T.name}),title:t("connectedWorkspaces.forgetName",{name:T.name}),onClick:()=>{N(T.id),P(!1)},className:"rounded-md p-1.5 text-ink-secondary hover:bg-control hover:text-danger disabled:opacity-50",children:e.jsx(Ee,{size:14})})]},T.id)})}),ce&&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:w,disabled:m,className:"mt-0.5",onChange:T=>P(T.target.checked)}),t("connectedWorkspaces.forgetPurge",{path:ce.dataDir??""})]}),e.jsxs("div",{className:"mt-2 flex gap-2",children:[e.jsx("button",{type:"button",disabled:m,onClick:()=>{H(async()=>{const T=w?await s.forget(ce.id,!0):await s.forget(ce.id);if(T&&T.ok===!1)throw new Error(t("connectedWorkspaces.forgetError"));N(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:()=>N(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:T=>{T.preventDefault(),y.trim()&&H(async()=>{if(!(await s.create(y.trim(),g.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:T=>b(T.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:g,disabled:m,onChange:T=>k(T.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:()=>{H(async()=>{const T=await s.pickDir();T?.ok&&T.path&&k(T.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(Y,{size:14,className:"animate-spin"}),t("connectedWorkspaces.create")]})]})]}),e.jsxs(Z,{title:t("servers.yours.title"),subtitle:t("servers.yours.subtitle"),children:[o?e.jsx(Tp,{saved:o,busy:m,sharingOffered:a,ownServers:r,appVersion:window.ogb?.app?.version??null,onShare:I,onSwitch:T=>{H(async()=>(await s.switch(T),!0))},onForget:T=>{H(()=>s.forget(T))},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||se)&&$&&e.jsx(Np,{workspace:$,own:se,onClose:()=>f(null)},$.id)]})}const Rp={format:"placeLook.imageFormat",read:"placeLook.imageRead",size:"placeLook.imageSize",animated:"placeLook.imageMoving",failed:"placeLook.imageFailed"};function Lp({banner:s,canChange:n,subtitle:a}){const i=l.useRef(null),[r,c]=l.useState(!1),[o,d]=l.useState(null),m=Ho(s),u=async h=>{c(!0),d(null);const f=await Promise.resolve().then(h).catch(()=>({ok:!1,problem:"failed"}));c(!1),f.ok||d(Rp[f.problem])},x=h=>{i.current&&(i.current.value=""),!(!h||!n)&&u(async()=>{const f=await Go(h);return f.ok?Vo(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(ue,{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(qo)},children:t("placeLook.removeImage")}),e.jsx("input",{ref:i,type:"file",accept:Wo,hidden:!0,"data-place-picture-input":!0,onChange:h=>x(h.target.files?.[0])})]})})})}function er(){const s=Jo(),{state:n}=G(),a=Mt()===!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),Xo(p).then(h=>{c(null),d(h)}))},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(ue,{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(wl,{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(Lp,{banner:n.config?.workspaceBanner??null,canChange:a,subtitle:t(i?"placeLook.sidebarPictureSub":"placeLook.sharedPictureSub")})]})}function Bp(){return e.jsx("div",{"data-sidebar-look":!0,"data-settings-look":"simple",className:Za,children:e.jsx(ye,{children:e.jsx(er,{})})})}function tr(){const{capabilities:s}=Ra(),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(ue,{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:Cs()})}),c&&e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{c().catch(()=>{})},children:t("settings.windowFrame.restartNow")})]})]})}function sr(s){return s.readOnly===!0&&s.managed!==void 0&&s.instanceId.startsWith("company.")}function Op(s,n){return s.find(a=>sr(a)&&a.instanceId.endsWith(`.${n}`))}function Gs(s){return!!(s&&!s.policy&&s.snapshot.state==="available"&&(s.access==="custom"||s.snapshot.authenticated!==!1))}function ea(s,n){const a=n.find(i=>i.instanceId===s.instanceId);return Gs(a)?!0:!!(a&&!a.policy&&a.snapshot.state==="available"&&a.models.options.some(i=>i.id===s.model&&i.custom))}function Mp(s,n){const a=n.filter(o=>sr(o)&&Gs(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=Yo(o);if(ea(o.modelSelection,n)||ea(d.modelSelection,n))continue;([o,d].some(u=>Qo(Zo(u),c(u.modelSelection.instanceId),i.driverKind))?r.needsAsk:r.bots).push(o)}return r}const zp={anthropic:"Anthropic",openai:"OpenAI",openrouter:"OpenRouter"};function Up({providers:s}){const{state:n,dispatch:a,flushBotPatches:i}=G(),[r,c]=l.useState(!1),[o,d]=l.useState(null),m=Mp(n.bots,n.instances),u=m.target,x=h=>h.map(f=>f.name).join(", "),p=async()=>{if(!u||!m.bots.length||r)return;const h=m.bots,f={instanceId:u.instanceId,model:u.models.default};c(!0),d(null);for(const y of h)a({type:"setModel",botId:y.id,selection:f});try{const y=await Promise.all(h.map(g=>i(g.id).catch(()=>null))),b=h.filter((g,k)=>y[k]?.modelSelection.instanceId===f.instanceId);b.length&&d({name:u.displayName,bots:b.map(g=>g.name)})}finally{c(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"divide-y divide-hairline/40",children:s.map(h=>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:zp[h.id]??h.id}),e.jsx("span",{className:"text-ink-secondary",children:h.configured?t("organization.modelCount",{count:h.models.length}):t("organization.notConfigured")})]}),h.configured&&h.models.length>0&&e.jsx(Fp,{instance:Op(n.instances,h.id),instances:n.instances})]},h.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 Fp({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(Gs(s))return e.jsxs("p",{className:"mt-1 flex items-center gap-1 text-[12px] text-ink-secondary",children:[e.jsx(fe,{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&&ec(a)?e.jsx(zt,{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 Dp={anthropic:"Anthropic",openai:"OpenAI",openrouter:"OpenRouter"},ta="https://admin.limixbot.com",sa={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 _p(s){const n=s.messageCodes;return!n?.length||!n.every(a=>Object.hasOwn(sa,a))?s.message:n.map(a=>t(sa[a])).join(" ")}function nr(){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),h=l.useRef(0),f=l.useRef(0),y=l.useRef(void 0),b=v=>{const B=y.current!==v.status;y.current=v.status,a(v),B&&m(""),v.status!=="connected"&&v.status!=="reauth-required"&&x(!1)};l.useEffect(()=>{s?.settingsOpened?.().catch(()=>{});const v=++h.current,B=f.current,j=I=>{h.current===v&&(f.current++,b(I))},A=s?.onState(j);return s?.state().then(I=>{f.current===B&&j(I)}).catch(()=>{h.current===v&&f.current===B&&m(t("organization.loadFailed"))}),()=>{h.current++,A?.()}},[s]);const g=async v=>{if(!s||p.current)return;p.current=!0,o(!0),m("");const B=h.current,j=f.current;try{const A=await v();h.current===B&&f.current===j&&b(A)}catch{h.current===B&&f.current===j&&m(t("organization.actionFailed"))}finally{p.current=!1,h.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",C=n?.status==="license-expired"||n?.notice==="license-expired",N=n?.enrollment?.expiresAt??n?.expiresAt,w=typeof N=="number"&&Number.isFinite(N)?new Date(N):null,P=w&&Number.isFinite(w.getTime())?new Intl.DateTimeFormat(Me(),{dateStyle:"medium",timeStyle:"short"}).format(w):null;return e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("organization.additive")}),e.jsxs(Z,{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:_p(n)}),C&&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:()=>{g(()=>s.begin({portalOrigin:ta}))},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:v=>{v.preventDefault(),i.trim()&&g(()=>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:v=>r(v.target.value),placeholder:ta,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:()=>{g(()=>s.reopen())},children:t("organization.reopen")}),e.jsx("button",{type:"button",disabled:c,className:"ui-button",onClick:()=>{g(()=>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(v=>v.configured&&v.models.length>0)&&e.jsx("ul",{className:"divide-y divide-hairline/40",children:n.providers.filter(v=>v.configured&&v.models.length>0).map(v=>e.jsxs("li",{className:"flex flex-wrap justify-between gap-2 py-2 text-[13px]",children:[e.jsx("span",{className:"text-ink",children:Dp[v.id]??v.id}),e.jsx("span",{className:"text-ink-secondary",children:t("organization.companyModelsUnavailable")})]},v.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(v=>v.configured&&v.models.length>0)?e.jsx(Up,{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:()=>{g(()=>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:()=>{g(()=>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:()=>{g(()=>s.refresh())},children:t("organization.refresh")})]})]})}const $p="https://cal.com/milind-soni-002qed/30min",Kp=["feature","price","setup","broken","later","other"],Hp={feature:"cloudCancel.answer.feature",price:"cloudCancel.answer.price",setup:"cloudCancel.answer.setup",broken:"cloudCancel.answer.broken",later:"cloudCancel.answer.later",other:"cloudCancel.answer.other"},na=2e3,ks=s=>new Intl.DateTimeFormat(Me(),{dateStyle:"medium"}).format(new Date(s)),Wp=s=>s.endsAt??s.renewsAt;function ar(s){const n=Wp(s);return s.trial?n?t("cloudCancel.endedTrial",{date:ks(n)}):t("cloudCancel.endedTrialNoDate"):n?t("cloudCancel.endedPlan",{date:ks(n)}):t("cloudCancel.endedPlanNoDate")}function Gp(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 Vp(s){return[s.renewsAt?t(s.trial?"cloudCancel.runsTrial":"cloudCancel.runsPlan",{date:ks(s.renewsAt)}):null,t(s.trial?"cloudCancel.nothingCharged":"cloudCancel.noMoreCharges"),s.team?t("cloudCancel.teamStops",{team:s.team}):null].filter(Boolean).join(" ")}function ir({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:ar(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(qp,{renewal:i,actions:n,onClose:x=>{r(null),x&&a?.()}})]})}function qp({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,h]=l.useState(!1),[f,y]=l.useState(!1),b=l.useRef(!1),g=l.useRef(null),k=()=>{p||a(b.current)};l.useEffect(()=>{const j=document.activeElement instanceof HTMLElement?document.activeElement:null;return g.current?.querySelector("button[aria-pressed]")?.focus(),()=>{j?.isConnected&&j.focus()}},[]);const C=j=>{h(!0),y(!1),j().catch(()=>y(!0)).finally(()=>h(!1))},N=()=>C(async()=>{const j=i!==null||c.trim()!==""||d.trim()!=="",A=await n.cancel(j?{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)}),w=()=>C(async()=>{const j=await n.keep();j.outcome==="kept"?(b.current=!0,a(!0)):j.outcome==="browser"?x({step:"browser"}):y(!0)}),P=t(s.trial?"cloudCancel.titleTrial":"cloudCancel.titlePlan"),v="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 Sl.createPortal(e.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/55 p-4",onMouseDown:j=>j.stopPropagation(),children:e.jsxs("div",{ref:g,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:j=>{if(j.key==="Escape"&&(j.stopPropagation(),k()),j.key==="Tab"){const A=g.current?.querySelectorAll("a[href], textarea:enabled, button:enabled");if(!A?.length)return;const I=A[0],H=A[A.length-1];j.shiftKey&&document.activeElement===I?(j.preventDefault(),H.focus()):!j.shiftKey&&document.activeElement===H&&(j.preventDefault(),I.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:Vp(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:Kp.map(j=>e.jsx("button",{type:"button","aria-pressed":i===j,onClick:()=>r(A=>A===j?null:j),className:z("ui-button ui-button-pill",i===j&&"border-accent bg-accent/10 font-medium"),children:t(Hp[j])},j))})]}),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:na,value:c,disabled:p,onChange:j=>o(j.target.value),className:v})]}),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:na,value:d,disabled:p,onChange:j=>m(j.target.value),className:v})]}),e.jsxs("p",{className:"mt-3 text-[12px] text-ink-secondary",children:[t("cloudCancel.talk")," ",e.jsx("a",{href:$p,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:N,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:ar(u.renewal)}),e.jsx("p",{className:"mt-2 text-[13px] leading-relaxed text-ink-secondary",children:Gp(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:w,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 aa({bridge:s}){const n=s?.keepHere,a=s?.setKeepHere;return s&&n&&a?e.jsx(Jp,{bridge:s,read:n,write:a}):null}function Jp({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(g=>{f&&r(g)}).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(Yr(y)??t("cloudAccount.keepHere.failed"))).finally(()=>m(!1))},h=()=>{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:h})]}),i.coming&&e.jsx("p",{role:"status",className:"mt-3 text-[13px] text-ink-secondary",children:t("cloudAccount.keepHere.coming")}),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 Xp({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 Yp({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:L("Đã 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"?L("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."):L("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:L("Đăng ký dùng thử","Request a trial")})]})}const Qp={provisioning:"cloudHome.provisioning",ready:"cloudHome.ready",stopped:"cloudHome.stopped","payment-problem":"cloudHome.paymentProblem",failed:"cloudHome.failed"},rr=s=>new Intl.DateTimeFormat(Me(),{timeStyle:"short"}).format(new Date(s)),Zp=s=>new Intl.DateTimeFormat(Me(),{dateStyle:"medium"}).format(new Date(s));function lr(s,n){if(!s&&!n)return null;const a=s?La(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:Ll(n)})]})}function ia({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:rr(s.retryAt)}):s.status==="provisioning"&&s.setup?.slow?t("cloudHome.slow"):d&&s.status==="provisioning"?t("cloudHome.team.provisioning"):t(Qp[s.status]));return e.jsx(Z,{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(vd,{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&&nc()&&e.jsx(Xp,{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 ex({ready:s,busy:n,failed:a,onUse:i}){return e.jsx(Z,{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 tx(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 sx={darwin:"cloudAccount.restoreRetryKeychain",linux:"cloudAccount.restoreRetryKeyring"};function nx(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(sx[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:Zp(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 ax({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(g=>{b&&i(g)}).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(Z,{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=Tl(a?.tier),h=a?.home===!0,f=a?.status==="paid"?t(Rl(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(h?"cloudAccount.onCloudNoneHome":"cloudAccount.onCloudNone"):null,y=b=>{c(!1),b().catch(()=>c(!0))};return e.jsx(Z,{title:t("settings.section.cloudAccount"),subtitle:t(h?"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")}),lr(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&&La(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(sc,{})]}),a?.renewal&&e.jsx(ir,{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 ix({team:s}){return e.jsx(Z,{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 rx({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(Z,{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 lx({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}=Ra().capabilities.host,[m,u]=l.useState(null),[x,p]=l.useState(!1),[h,f]=l.useState(!1),[y,b]=l.useState(!1),[g,k]=l.useState(!1),[C,N]=l.useState(!1),[w,P]=l.useState(!1),v=l.useRef(0),B=l.useRef(0),j=l.useRef(!1),A=l.useRef({request:0,arrived:!1,connected:!1});l.useEffect(()=>{const re=++v.current,de=B.current,ve=oe=>{v.current===re&&(B.current++,u(oe),f(!1),oe.status==="signed-out"&&b(!1))},K=o?.onState(ve);return o?.state().then(oe=>{B.current===de&&ve(oe)}).catch(()=>{v.current===re&&B.current===de&&f(!0)}),()=>{v.current++,K?.()}},[o]);const I=async re=>{if(!o||j.current)return;j.current=!0,p(!0),f(!1);const de=v.current,ve=B.current;try{const K=await re();v.current===de&&B.current===ve&&u(K)}catch{v.current===de&&B.current===ve&&f(!0)}finally{j.current=!1,v.current===de&&p(!1)}},H=()=>{o&&(N(!1),I(async()=>{try{return await o.connectHome()}catch{return N(!0),o.state()}}))},D=re=>{o?.openTeam&&(N(!1),I(async()=>{try{await o.openTeam(re)}catch{N(!0)}return o.state()}))},V=()=>{o&&(P(!1),I(async()=>{try{return await o.connectHomeForPhone()}catch{return P(!0),o.state()}}))};l.useEffect(()=>{if(s||(A.current.request=0),!o||!s||!m||j.current||(A.current.request!==s&&(A.current={request:s,arrived:!0,connected:!1}),m.status==="signed-out"&&m.message==="restoring"))return;const re=tx(m,A.current);A.current.arrived=!1,re==="sign-in"&&I(()=>o.begin()),re==="connect"&&(A.current.connected=!0,H())},[o,s,m,x]);const[$]=tc(o?window.ogb?.cloudSendPage:void 0),se=$?.move?Qr($.move,"local"):null,ne=se&&se.kind!=="done"?se.text:null,ce=Ud(!!m&&cn(dn(m)),m?.offer),T=o?.cancelPlan&&o.keepPlan?{cancel:re=>o.cancelPlan(re),keep:()=>o.keepPlan()}:null;if(!o){const re=window.ogb?.remoteClient?.active||!n?void 0:window.ogb?.cloudPlan;return e.jsxs(e.Fragment,{children:[n&&a?e.jsx(ix,{team:a}):re?e.jsx(ax,{bridge:re,onConnectPhone:i}):e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("cloudAccount.desktopOnly")}),re&&!a&&e.jsx(aa,{bridge:window.ogb?.cloudSendPage})]})}const U=dn(m),Q=m&&["connected","unavailable","reauth-required"].includes(m.status),le=nx(m,U,d),he=Cl(U),S=El(m),ae=Al(m),F=U.kind==="paid"?{status:"provisioning"}:void 0,te=S?ae?.machine??F:m?.status==="connected"?m.machine??F:void 0,q=m?.status==="connecting"?m.enrollment:void 0;Il(ce);const ie=r&&cn();return e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:t("cloudAccount.optional")}),e.jsxs(Z,{title:t("settings.section.cloudAccount"),subtitle:t("cloudAccount.separate"),children:[m?.staging&&e.jsx(Zr,{className:"mb-3"}),(!m||U.kind==="unknown")&&e.jsx("p",{role:"status",className:"text-[13px] text-ink-secondary",children:t("cloudAccount.loading")}),le&&e.jsx("p",{role:"status",className:"mb-3 text-[13px] text-ink-secondary",children:le}),(U.kind==="signed-out"||U.kind==="removed")&&e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[ie,e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{I(()=>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")}),q&&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:q.userCode}),e.jsx("p",{className:"text-[12px] text-ink-secondary",children:t("cloudAccount.codeUntil",{time:rr(q.expiresAt)})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{I(()=>o.reopen())},children:t("organization.reopen")}),e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{I(()=>o.cancel())},children:t("organization.cancel")})]})]}),Q&&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:()=>{I(()=>o.openDashboard())},children:L("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":U.kind,className:"text-[15px] font-medium text-ink",children:[he,U.kind==="paid"&&U.checking&&e.jsx("span",{className:"ms-2 text-[12px] font-normal text-ink-secondary",children:t("cloudAccount.checking")})]}),m.status==="connected"&&lr(m.trial,m.credit),U.kind==="free"&&ie,U.kind==="free"&&!Gt&&m.status==="connected"&&o.requestTrial&&e.jsx(Yp,{trial:m.limixTrial,busy:x,onAsk:()=>{I(async()=>(await o.requestTrial()).state)}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[U.kind==="reauth"?e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{I(()=>o.signInAgain())},children:t("cloudAccount.signInAgain")}):e.jsxs(e.Fragment,{children:[Gt,e.jsx("button",{type:"button",disabled:x,className:"ui-button",onClick:()=>{I(()=>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(ir,{renewal:m.renewal,actions:T}),Gt,g&&e.jsx(Pl,{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:()=>{I(()=>o.signOut())},children:t("cloudAccount.signOut")})]})]})]}),h&&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:()=>{I(()=>o.state())},children:t("organization.refresh")})]}),te&&ia(S?{machine:te,busy:x,failed:C,onConnect:()=>{ae&&D(ae.id)},team:{name:ae?.name??null}}:{machine:te,busy:x,failed:C,onConnect:H,trial:!!m?.trial,waking:m?.waking===!0,moving:ne}),!S&&te?.accountLink&&e.jsx(Z,{title:t("cloudHome.accountLink"),children:e.jsx("a",{className:"break-all text-[13px] text-accent hover:underline",href:te.accountLink,target:"_blank",rel:"noopener noreferrer",children:te.accountLink})}),Q&&!S&&m?.account?.id&&window.ogb?.cloudSendPage?.botSync&&e.jsx(rx,{bridge:window.ogb.cloudSendPage},m.account.id),Q&&U.kind==="paid"&&!S&&ex({ready:te?.status==="ready"&&!te.unreachable,busy:x,failed:w,onUse:V}),e.jsx(aa,{bridge:window.ogb?.cloudSendPage})]})}function ra(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 or(s){return t("planUsage.spendAmounts",{used:ra(s.usedMinor,s.currency,s.exponent),limit:ra(s.limitMinor,s.currency,s.exponent)})}function cr(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 ox(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 cx(s){return s>=90?"bg-danger":s>=70?"bg-warning":"bg-success"}function la(s){return s==="5-hour"?t("planUsage.fiveHour"):s==="Weekly"?t("planUsage.weekly"):s==="Monthly spend"?t("planUsage.monthlySpend"):s}function Pt(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 dx(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:Pt({name:a[1]})}):n}function kt({label:s,window:n,now:a,usedHeadline:i=!1,detail:r}){const c=n.available?cr(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",cx(o)),style:{width:`${Math.min(100,Math.max(0,o))}%`}})})]}):e.jsx("div",{className:"text-[12px] text-ink-secondary",children:t("planUsage.notReported")})]})}function dr(){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 O(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=ox(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 ux(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 mx(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 px(){const{report:s,now:n}=dr();if(!s)return null;const a=mx(s),i=a?null:ux(s);if(i){const d=Pt(i.provider),m=Math.round(Math.min(100,Math.max(0,i.budget.usedPercent)));return e.jsx(gn,{kind:"plan",title:t("settings.simple.billing.monthlySpend",{provider:d}),percent:m,label:`${d}: ${t("planUsage.used",{used:m})}`,note:i.budget.spend?or(i.budget.spend):null})}if(!a)return e.jsx("section",{"data-usage-summary":"own-ai",className:z(Va,"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=cr(a.provider.weekly.resetsAt,n),o=Pt(a.provider);return e.jsx(gn,{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 xx(){const{report:s,loading:n,error:a,now:i,load:r}=dr();return e.jsxs(Z,{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(Y,{size:14,className:"animate-spin"}):e.jsx(Se,{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:Pt(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(kt,{label:t("planUsage.fiveHour"),window:c.fiveHour,now:i}),e.jsx(kt,{label:t("planUsage.weekly"),window:c.weekly,now:i}),c.extra.map((o,d)=>e.jsx(kt,{label:la(o.label),now:i,usedHeadline:!!o.spend,detail:o.spend?or(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(kt,{label:la(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:dx(c)})]},c.id))})]})}function oa(s,n){return s?.edition?.features?.includes(n)===!0}function hx(s){return s?s.exceeded?"danger":s.warn?"warning":"quiet":"quiet"}function gx({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 h=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 g=await O("/api/config",{method:"PUT",body:JSON.stringify({budgets:{monthlyUsd:y,warnAtPercent:b}})});a({type:"configStatus",config:g})}catch(g){p(g instanceof Error?g.message:String(g))}finally{u(!1)}},f=hx(s);return e.jsxs(Z,{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:dt(s.spentUsd),cap:dt(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(),h()},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(Y,{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 ca(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 fx(){const{state:s,dispatch:n}=G(),a=s.config?.billing,[i,r]=l.useState(a?.currency??"USD"),[c,o]=l.useState(ca(a?.prices)),[d,m]=l.useState(!1),[u,x]=l.useState(null);l.useEffect(()=>{r(a?.currency??"USD"),o(ca(a?.prices))},[a]);const p=(y,b)=>o(g=>g.map((k,C)=>C===y?{...k,...b}:k)),h=async()=>{if(d)return;const y={};for(const b of c){const g=b.key.trim();if(!g)continue;const k=Number(b.input),C=Number(b.output),N=b.cached.trim()===""?void 0:Number(b.cached);if(!Number.isFinite(k)||!Number.isFinite(C)||k<0||C<0||N!==void 0&&(!Number.isFinite(N)||N<0)){x(t("usage.prices.invalid",{model:g}));return}y[g]={inputPerMillion:k,outputPerMillion:C,...N===void 0?{}:{cachedInputPerMillion:N}}}if(!/^[A-Z]{3}$/.test(i.trim().toUpperCase())){x(t("usage.prices.currencyInvalid"));return}m(!0),x(null);try{const b=await O("/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(Z,{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:g=>p(b,{key:g.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:g=>p(b,{input:g.target.value}),inputMode:"decimal","aria-label":t("usage.prices.colInput"),disabled:d,className:f}),e.jsx("input",{value:y.output,onChange:g=>p(b,{output:g.target.value}),inputMode:"decimal","aria-label":t("usage.prices.colOutput"),disabled:d,className:f}),e.jsx("input",{value:y.cached,onChange:g=>p(b,{cached:g.target.value}),inputMode:"decimal",placeholder:"—","aria-label":t("usage.prices.colCached"),disabled:d,className:f}),e.jsx("button",{type:"button",onClick:()=>o(g=>g.filter((k,C)=>C!==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(Ee,{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(Ce,{size:13}),t("usage.prices.add")]}),e.jsxs("button",{type:"button",onClick:()=>{h()},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(Y,{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 bx({budget:s}){const{state:n}=G(),a=oa(n.config,"budgets"),i=oa(n.config,"billing");return!a&&!i?null:e.jsxs(e.Fragment,{children:[a&&e.jsx(gx,{budget:s}),i&&e.jsx(fx,{})]})}const yx=["model","user","department","day","engine","routine"],da={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"},vx={today:"usage.page.today",week:"usage.page.week",month:"usage.history.thisMonth",lastMonth:"usage.history.lastMonth",days30:"usage.history.last30Days"},jx=2e3;function kx(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 ua(s,n,a){const[i,r]=l.useState(null);return l.useEffect(()=>{let c=!0;return O(`/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 ma({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(Ot,{bot:o,state:"idle",size:18,animated:!1}),e.jsx("span",{className:"truncate",children:s==="model"?xc(c.label,a.instances):kx(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:[hc(nt(c)),ct(c.costUsd)&&c.costUsd>0&&` · ${ei(c.costUsd)}`]})]},c.key)})})}function Nx({range:s,version:n,onBudget:a}){const[i,r]=l.useState("model"),c=ua(s,"bot",n),o=ua(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(da.bot)}),c?e.jsx(ma,{groupBy:"bot",groups:c.groups}):e.jsx(Y,{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:yx.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(da[d])},d))}),o?.groupBy===i?e.jsx(ma,{groupBy:i,groups:o.groups}):e.jsx(Y,{size:14,className:"animate-spin text-ink-secondary"})]})]})]})}function wx(s){return new Date(s).toLocaleString(el(Me()),{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Sx({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(Ot,{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:[wx(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(mc,{}),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:pc(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:ei(s.costUsd)}),e.jsx(Ls,{size:14,className:"text-ink-tertiary"})]})]})})}function ur(){const[s,n]=l.useState("month"),a=l.useMemo(()=>ac(s),[s]),[i,r]=l.useState(null),[c,o]=l.useState(null),[d,m]=l.useState(0),[u,x]=l.useState(null),[p,h]=l.useState(null),f=l.useRef(null);l.useEffect(()=>{let g=!0;return fn(a).then(k=>{g&&(r(k),o(null))}).catch(k=>{g&&o(k instanceof Error?k.message:String(k))}),()=>{g=!1}},[a,d]),l.useEffect(()=>ic({onFrame:g=>{if(g.kind!=="runtime"||f.current)return;const k=g.event?.type;k!=="turn.started"&&k!=="turn.completed"||(f.current=setTimeout(()=>{f.current=null,m(C=>C+1)},jx))},onMissedFrames:()=>m(g=>g+1)}),[]),l.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const y=()=>{i?.next&&fn(a,i.next).then(g=>r(k=>k?{...g,roots:[...k.roots,...g.roots]}:g))},b=i?.roots.some(g=>!g.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(pe,{size:"sm",value:s,onChange:g=>{n(g.target.value),h(null)},"aria-label":t("usage.history.period"),children:rc.map(g=>e.jsx("option",{value:g,children:t(vx[g])},g))}),e.jsxs("a",{href:lc(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(oc,{id:p.id,at:p.at,actions:e.jsxs("button",{type:"button",onClick:()=>h(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(cc,{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(dc,{items:uc(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(Y,{size:14,className:"animate-spin"}),t("common.checking")]})}),e.jsx(Nx,{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(g=>e.jsx(Sx,{root:g,onOpen:()=>h({id:g.id,at:g.startedAt})},g.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(xx,{}),e.jsx(bx,{budget:u})]})}const Je=["catalog","bundled","local","tools"];function Cx({catalog:s,bundled:n,tools:a,children:i}){const[r,c]=l.useState("catalog"),o=l.useId(),d={catalog:L("Kho kỹ năng","Skill catalog"),bundled:L("Có sẵn","Built-in"),local:t("skills.library.title"),tools:L("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 Ex(){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(Z,{title:L("Kĩ năng có sẵn của Limix Bot","Skills built into Limix Bot"),subtitle:L("Đi kèm ứng dụng. Kĩ năng gốc luôn bật cho mọi bot; các kĩ năng khác nằm trong kho, thêm cho từng bot ở mục Kĩ Năng (Skills) của 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:L("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?L("Kĩ năng gốc · mọi bot","Core skill · every bot"):L("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:[L("Từ khóa","Keywords"),": ",a.triggerTerms.slice(0,6).join(", "),a.triggerTerms.length>6?"…":""]})]},a.id))})})})}function Ax(){const[s,n]=l.useState(!1);return e.jsxs(Z,{title:L("Công cụ cho kỹ năng","Tools for skills"),subtitle:L("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:[ti()?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(gc,{size:14}),L("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:L("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(si,{onClose:()=>n(!1)})]})}const it=12,Ix=[["discover",()=>L("Khám phá","Discover")],["recommended",()=>L("Khuyên dùng","Recommended")],["installed",()=>L("Đã cài","Installed")],["updates",()=>L("Cập nhật","Updates")],["security",()=>L("Bảo mật","Security")],["settings",()=>L("Cài đặt","Settings")]],Ue=s=>{const n=new Date(s);return Number.isNaN(n.getTime())?s:n.toLocaleDateString(L("vi-VN","en-US"))},Px=s=>({excellent:L("Xuất sắc","Excellent"),recommended:L("Khuyên dùng","Recommended"),review:L("Cần xem xét","Needs review"),rejected:L("Từ chối","Rejected")})[s],Tx=s=>({"instructions-only":L("Chỉ hướng dẫn","Instructions only"),"skill-with-tools":L("Kèm tool/script","With tools/scripts"),"mcp-bundle":L("Kèm MCP","With MCP")})[s],ls=s=>({clean:L("Sạch","Clean"),warning:L("Có cảnh báo","Warnings"),quarantined:L("Cách ly","Quarantined")})[s],we="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 Ie(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??L(`Lỗi ${a.status}`,`Error ${a.status}`));return i}function Rx(){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(""),[h,f]=l.useState("catalog"),[y,b]=l.useState(""),[g,k]=l.useState(""),[C,N]=l.useState(""),[w,P]=l.useState(!1),[v,B]=l.useState(null),[j,A]=l.useState(null),[I,H]=l.useState(it);l.useEffect(()=>H(it),[a,m,x,h,y,g,C]);const D=l.useCallback(async()=>{try{n(await Ie("/api/limix/hub"))}catch(S){d(S instanceof Error?S.message:String(S))}},[]);l.useEffect(()=>{D()},[D]);const V=async(S,ae)=>{c(S),d(null);try{await ae()}catch(F){d(F instanceof Error?F.message:String(F))}finally{await D(),c(null)}},$=s?.skills??[],se=l.useMemo(()=>[...new Set($.map(S=>S.category))].sort(),[$]),ne=l.useMemo(()=>{const S=m.trim().toLowerCase(),ae=g?new Date(g+"T00:00:00").getTime():-1/0,F=C?new Date(C+"T00:00:00"):null;F&&F.setDate(F.getDate()+1);const te=$.filter(q=>{if(y&&(q.stars==null||q.stars<Number(y)))return!1;if(g||C){const ie=Date.parse(q.added_at??"");if(!Number.isFinite(ie)||ie<ae||F&&ie>=F.getTime())return!1}if(x&&q.category!==x||S&&!`${q.name} ${q.description} ${q.description_vi??""} ${q.tags.join(" ")}`.toLowerCase().includes(S))return!1;switch(a){case"discover":return!0;case"recommended":return!q.blocked&&!q.risky&&(q.grade==="excellent"||q.grade==="recommended");case"installed":return q.installed;case"updates":return q.updateAvailable;case"security":return q.security_status!=="clean"||!!q.risky;default:return!1}});return h==="stars"&&te.sort((q,ie)=>(ie.stars??-1)-(q.stars??-1)),h==="newest"&&te.sort((q,ie)=>(Date.parse(ie.added_at??"")||0)-(Date.parse(q.added_at??"")||0)),te},[$,a,m,x,h,y,g,C]),ce=()=>V("sync",()=>Ie("/api/limix/hub/sync",{})),T={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"},U="rounded-md bg-ink/[0.06] px-1.5 py-0.5 text-[11px] text-ink-secondary",Q=S=>{window.confirm(L(`CẢNH BÁO: "${S.name}" bị cách ly vì ${S.risky??"có dấu hiệu nguy hiểm"}
|
|
11
|
+
|
|
12
|
+
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 ${S.source.repository??"này"}.
|
|
13
|
+
|
|
14
|
+
Vẫn cài đặt (kỹ năng sẽ ở trạng thái tắt)?`,`WARNING: "${S.name}" is quarantined because ${S.risky??"it looks dangerous"}
|
|
15
|
+
|
|
16
|
+
Installing is not recommended. This skill may contain malware or dangerous commands. Only install it if you understand the risk and trust ${S.source.repository??"the source"}.
|
|
17
|
+
|
|
18
|
+
Install anyway (the skill will stay switched off)?`))&&V(S.id,()=>Ie("/api/limix/hub/install",{id:S.id,allowRisky:!0}))},le=S=>{!S.enabled&&S.risky&&!window.confirm(L(`"${S.name}" bị cách ly (${S.risky}). Vẫn bật cho bot dùng?`,`"${S.name}" is quarantined (${S.risky}). Switch it on for bots anyway?`))||V(S.id,()=>Ie("/api/limix/hub/enable",{id:S.id,enabled:!S.enabled}))},he=S=>{const ae=S.description_vi||S.description,F=j===S.id,te=(S.permissions.runs_code||S.permissions.mcp)&&!S.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:S.name}),e.jsxs("span",{className:`rounded-md px-1.5 py-0.5 text-[11px] font-medium ${T[S.grade]??"bg-ink/10 text-ink-secondary"}`,children:[S.quality_score,"/100 · ",Px(S.grade)??S.grade]}),typeof S.stars=="number"&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[12px] text-ink-secondary",children:[e.jsx(fc,{size:12}),S.stars.toLocaleString(L("vi-VN","en-US"))]})]}),e.jsx("p",{className:`mt-1 text-[12.5px] leading-relaxed text-ink-secondary ${F?"":"line-clamp-3"}`,children:ae}),ae.length>220&&e.jsx("button",{type:"button",className:"mt-0.5 text-[12px] text-ink underline-offset-2 hover:underline",onClick:()=>A(F?null:S.id),children:F?L("Thu gọn","Show less"):L("Xem thêm","Show more")}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:U,children:Tx(S.kind)??S.kind}),e.jsxs("span",{className:`${U} ${S.security_status==="clean"?"":S.security_status==="quarantined"?"!bg-danger/15 !text-danger":"!bg-amber-500/15 !text-amber-500"}`,children:[L("Bảo mật","Security"),": ",ls(S.security_status)??S.security_status]}),e.jsx("span",{className:U,children:S.license??L("Chưa có giấy phép","No license")}),S.dependencies.length>0&&e.jsxs("span",{className:U,children:[L("Cần","Needs"),": ",S.dependencies.join(", ")]})]}),e.jsxs("p",{className:"mt-1.5 text-[11px] leading-relaxed text-ink-tertiary",children:[S.source.repository??L("Không rõ nguồn","Unknown source"),S.added_at&&L(` · Thêm vào kho ${Ue(S.added_at)}`,` · Added to catalog ${Ue(S.added_at)}`),S.created_at&&L(` · Tạo ${Ue(S.created_at)}`,` · Created ${Ue(S.created_at)}`),S.pushed_at&&L(` · Cập nhật ${Ue(S.pushed_at)}`,` · Updated ${Ue(S.pushed_at)}`),S.stats_checked&&L(` · số sao đo ngày ${Ue(S.stats_checked)}`,` · stars measured ${Ue(S.stats_checked)}`)]}),S.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(bn,{size:14,className:"mt-0.5 shrink-0"}),e.jsxs("span",{children:[S.risky," ",L("Không khuyến khích cài.","Installing is not recommended.")]})]}),S.blocked&&e.jsxs("p",{className:"mt-1 flex items-center gap-1 text-[12px] text-danger",children:[e.jsx(bn,{size:13}),S.blocked]}),te&&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:()=>B(v===S.id?null:S.id),children:v===S.id?L("Ẩn hướng dẫn cài đặt","Hide install guide"):L("Kỹ năng này có tool: xem hướng dẫn cài đặt","This skill has tools: see the install guide")}),v===S.id&&e.jsxs("ol",{className:"mt-2 list-decimal space-y-1.5 pl-4",children:[e.jsx("li",{children:L(e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"Cài kỹ năng:"}),' bấm "Cài đặt". Mặc định chỉ lấy phần hướng dẫn (SKILL.md). Kỹ năng được tải từ GitHub và kiểm tra SHA-256 từng file.']}),e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"Install the skill:"}),' press "Install". By default only the instructions (SKILL.md) are taken. The skill is downloaded from GitHub and every file is checked with SHA-256.']}))}),S.compatibility.runtimes.length>0&&e.jsxs("li",{children:[e.jsxs("b",{className:"text-ink",children:[L("Chuẩn bị máy","Prepare this computer"),":"]})," ",L("kỹ năng cần","the skill needs")," ",S.compatibility.runtimes.map(q=>q.name).join(", "),".",S.compatibility.runtimes.filter(q=>q.installerId).length>0&&e.jsxs(e.Fragment,{children:[" ",L("Limix Bot cài được","Limix Bot can install"),": ",S.compatibility.runtimes.filter(q=>q.installerId).map(q=>q.name).join(", "),". "]}),S.compatibility.runtimes.some(q=>!q.installerId)&&e.jsxs(e.Fragment,{children:[" ",L("Phải cài tay","Install by hand"),": ",S.compatibility.runtimes.filter(q=>!q.installerId).map(q=>q.name).join(", ")," (",L('Python: tải từ python.org, tick "Add python.exe to PATH"','Python: download from python.org, tick "Add python.exe to PATH"'),"). "]}),ti()&&e.jsx("button",{type:"button",className:"ml-1 text-ink underline",onClick:()=>P(!0),children:L('Mở "Công cụ cho kỹ năng"','Open "Tools for skills"')})]}),S.permissions.runs_code&&e.jsx("li",{children:L(e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"Cài phần script:"}),' bấm "Cài đặt kèm tool". Các file script nằm trong thư mục kỹ năng và bot có thể chạy chúng. Chỉ làm khi bạn tin nguồn ',S.source.repository??"này"," (đã quét: ",ls(S.security_status)??S.security_status,")."]}),e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"Install the scripts:"}),' press "Install with tools". The script files go in the skill folder and the bot can run them. Only do this if you trust ',S.source.repository??"the source"," (scanned: ",ls(S.security_status)??S.security_status,")."]}))}),S.permissions.mcp&&e.jsx("li",{children:L(e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"MCP:"})," file cấu hình MCP chỉ được chép vào thư mục kỹ năng, không tự bật. Muốn dùng, thêm máy chủ MCP ở Cài đặt rồi bật."]}),e.jsxs(e.Fragment,{children:[e.jsx("b",{className:"text-ink",children:"MCP:"})," the MCP config file is only copied into the skill folder and is not switched on. To use it, add the MCP server in Settings and turn it on."]}))}),e.jsx("li",{children:L(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 (Skills) để 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"&&S.security_findings?.slice(0,5).map((q,ie)=>e.jsxs("p",{className:"text-[11px] text-ink-tertiary",children:[q.severity," · ",q.rule," · ",q.file,q.line?`:${q.line}`:""]},ie)),S.notes.map(q=>e.jsx("p",{className:"mt-0.5 text-[11px] text-ink-tertiary",children:q},q))]}),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===S.id?e.jsx(Y,{size:15,className:"animate-spin text-ink-secondary sm:self-end"}):S.installed?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-center justify-between gap-2 text-[12px] text-ink-secondary",children:[S.enabled?L("Đang bật","On"):L("Đang tắt","Off"),e.jsx(me,{checked:S.enabled,disabled:r!==null,onClick:()=>le(S)})]}),S.updateAvailable&&e.jsxs("button",{type:"button",className:`${we} justify-center`,disabled:r!==null,onClick:()=>{V(S.id,()=>Ie("/api/limix/hub/update",{id:S.id,allowRisky:!!S.risky}))},children:[e.jsx(Se,{size:14}),L("Cập nhật","Update")]}),e.jsxs("button",{type:"button",className:`${we} justify-center`,disabled:r!==null,onClick:()=>{V(S.id,()=>Ie("/api/limix/hub/remove",{id:S.id}))},children:[e.jsx(Ee,{size:14}),L("Gỡ","Remove")]})]}):e.jsxs(e.Fragment,{children:[S.risky?e.jsxs("button",{type:"button",className:`${we} justify-center !border-danger/40 !text-danger`,disabled:!!S.blocked||r!==null,onClick:()=>Q(S),children:[e.jsx(Ye,{size:14}),L("Cài đặt (không khuyến khích)","Install (not recommended)")]}):e.jsxs("button",{type:"button",className:`${we} justify-center`,disabled:!!S.blocked||r!==null,onClick:()=>{V(S.id,()=>Ie("/api/limix/hub/install",{id:S.id}))},children:[e.jsx(Ye,{size:14}),L("Cài đặt","Install")]}),S.permissions.runs_code&&!S.blocked&&!S.risky&&e.jsxs("button",{type:"button",className:`${we} justify-center`,disabled:r!==null,onClick:()=>{window.confirm(L(`Cài cả script của "${S.name}"? Bot có thể chạy các script này. Chỉ làm khi bạn tin nguồn.`,`Install the scripts of "${S.name}" too? Bots can run these scripts. Only do this if you trust the source.`))&&V(S.id,()=>Ie("/api/limix/hub/install",{id:S.id,allowTools:!0}))},children:[e.jsx(Ye,{size:14}),L("Cài đặt kèm tool","Install with tools")]})]})})]})},S.id)};return e.jsxs(Z,{title:L("Kho kỹ năng Limix","Limix Skill Catalog"),subtitle:L("Kĩ năng đã quét bảo mật và chấm điểm. Cài xong, kĩ năng nằm sẵn trong kho nhưng chưa bot nào dùng: mở bot → Kĩ Năng (Skills) → Kho Kĩ Năng (Skills) để thêm cho từng 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:Ix.map(([S,ae])=>{const F=S==="installed"?$.filter(te=>te.installed).length:S==="updates"?$.filter(te=>te.updateAvailable).length:S==="discover"?$.length:null;return e.jsxs("button",{type:"button",onClick:()=>i(S),className:`rounded-lg px-2.5 py-1 text-[13px] ${a===S?"bg-raised text-ink":"text-ink-secondary hover:bg-raised-hover"}`,children:[ae(),F?e.jsx("span",{className:"ml-1 text-[11px] text-ink-tertiary",children:F}):null]},S)})}),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:[L("Tự đồng bộ danh mục","Sync the catalog automatically"),e.jsx("span",{className:"block text-[12px] text-ink-secondary",children:L("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:()=>{V("settings",()=>Ie("/api/limix/hub/settings",{autoSync:!s.settings.autoSync}))}})]}),e.jsxs("label",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{children:[L("Tự cài kỹ năng mới","Install new skills automatically"),e.jsx("span",{className:"block text-[12px] text-ink-secondary",children:L("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:()=>{V("settings",()=>Ie("/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:S=>u(S.target.value),placeholder:L("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":L("Chủ đề","Topic"),value:x,onChange:S=>p(S.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:L("Mọi chủ đề","All topics")}),se.map(S=>e.jsx("option",{value:S,children:S},S))]}),e.jsxs("select",{"aria-label":L("Sắp xếp","Sort by"),value:h,onChange:S=>f(S.target.value),className:we,children:[e.jsx("option",{value:"catalog",children:L("Thứ tự trong kho","Catalog order")}),e.jsx("option",{value:"stars",children:L("Nhiều sao nhất","Most stars")}),e.jsx("option",{value:"newest",children:L("Mới thêm nhất","Recently added")})]}),a==="discover"&&e.jsxs("button",{type:"button",className:`${we} shrink-0`,disabled:r!==null,onClick:()=>{ce()},children:[r==="sync"?e.jsx(Y,{size:14,className:"animate-spin"}):e.jsx(Se,{size:14}),L("Đồ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:[L("Số sao tối thiểu","Minimum stars"),e.jsx("input",{type:"number",min:"0",step:"1",placeholder:"0",value:y,onChange:S=>b(S.target.validity.valid?S.target.value:""),className:`${we} w-28`})]}),e.jsxs("label",{className:"grid gap-1",children:[L("Thêm vào kho từ ngày","Added from"),e.jsx("input",{type:"date",value:g,max:C||void 0,onChange:S=>k(S.target.value),className:we})]}),e.jsxs("label",{className:"grid gap-1",children:[L("Đến ngày","Added through"),e.jsx("input",{type:"date",value:C,min:g||void 0,onChange:S=>N(S.target.value),className:we})]}),(m||x||y||g||C)&&e.jsx("button",{type:"button",className:we,onClick:()=>{u(""),p(""),b(""),k(""),N("")},children:L("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:[L("Đồng bộ gần nhất","Last sync"),": ",s.settings.lastSync?new Date(s.settings.lastSync).toLocaleString(L("vi-VN","en-US")):L("chưa lần nào","never")]}),s.settings.lastError&&e.jsxs("p",{className:"text-[12px] text-danger",children:[L("Lỗi đồng bộ gần nhất","Last sync error"),": ",s.settings.lastError]})]}),ne.length===0?e.jsx("p",{className:"text-[13px] text-ink-secondary",children:$.length===0?L("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."):L("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:[ne.length," ",L("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:ne.slice(0,I).map(he)}),ne.length>I&&e.jsx("button",{type:"button",className:`${we} w-fit self-center`,onClick:()=>H(S=>S+it),children:L(`Xem thêm ${Math.min(it,ne.length-I)} kỹ năng`,`Show ${Math.min(it,ne.length-I)} more`)})]}),a==="installed"&&ne.length>0&&e.jsxs("p",{className:"flex items-center gap-1 text-[12px] text-ink-tertiary",children:[e.jsx(fe,{size:13}),L("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 (Skills) để thêm.","Enabled skills are in the library below. Add them from each bot’s Settings → Skills.")]})]}):e.jsx(Y,{size:15,className:"animate-spin text-ink-secondary"})]}),w&&e.jsx(si,{onClose:()=>P(!1)})]})}function Lx(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 mr({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(Es())})}),s.tags.map(n=>e.jsx("span",{className:"rounded bg-control px-1.5 py-0.5 font-mono",children:n},n))]})}function Bx(){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),[h,f]=l.useState(""),[y,b]=l.useState(""),[g,k]=l.useState(!1),[C,N]=l.useState(""),w=l.useRef(!1),P=l.useMemo(()=>[...new Set(s.flatMap(D=>D.tags))].sort((D,V)=>D.localeCompare(V)),[s]),v=Lx(s,o,m),B=async D=>{try{const V=await fetch("/api/skills-library"),$=await V.json();if(!V.ok)throw new Error($.error??t("skills.library.loadError"));if(D?.())return;n($.skills??[]),c("")}catch(V){D?.()||c(V instanceof Error?V.message:t("skills.library.loadError"))}finally{D?.()||i(!1)}};l.useEffect(()=>{let D=!1;return i(!0),B(()=>D),()=>{D=!0}},[]);const j=async(D,V=!1)=>{if(!w.current){if(!D.enabled&&!V)return A(D,!0);w.current=!0,f(D.name),c("");try{const $=await fetch(`/api/skills-library/${encodeURIComponent(D.name)}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:!D.enabled})}),se=await $.json();if(!$.ok)throw new Error(se.error??t("skills.error.update"));V&&p(null),await B()}catch($){c($ instanceof Error?$.message:t("skills.error.update"))}finally{w.current=!1,f("")}}},A=async(D,V=!1)=>{c("");try{const $=await fetch(`/api/skills-library/${encodeURIComponent(D.name)}`),se=await $.json();if(!$.ok)throw new Error(se.error??t("skills.error.load"));if(!se.text)throw new Error(t("skills.error.contentsImport"));p({skill:D,text:se.text,review:V})}catch($){c($ instanceof Error?$.message:t("skills.error.load"))}},I=async()=>{const D=y.trim();if(D){k(!0),c(""),N("");try{const V=await fetch("/api/skills-library",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:D})}),$=await V.json();if(!V.ok)throw new Error($.error??t("skills.error.import"));N(t("skills.library.imported",{name:$.skill?.name??""})),b(""),await B()}catch(V){c(V instanceof Error?V.message:t("skills.error.import"))}finally{k(!1)}}},H="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(Cx,{catalog:e.jsx(Rx,{}),bundled:e.jsx(Ex,{}),tools:e.jsx(Ax,{}),children:[e.jsx(Z,{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(pt,{size:15,className:"shrink-0 text-ink-secondary"}),e.jsx("input",{className:H,placeholder:t("skills.library.searchPlaceholder"),"aria-label":t("skills.library.searchPlaceholder"),value:o,onChange:D=>d(D.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(D=>e.jsx("button",{type:"button",onClick:()=>u(m===D?null:D),className:m===D?"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:D},D))]}),a?e.jsx("div",{className:"text-[12px] text-ink-secondary",children:t("skills.library.loading")}):v.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:v.map(D=>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(D)},className:"min-w-0 flex-1 text-left","aria-label":t("skills.library.view",{skill:D.name}),children:[e.jsx("div",{className:"truncate font-mono text-[13px] text-ink",children:D.name}),e.jsx("div",{className:"mt-0.5 line-clamp-2 text-[12px] text-ink-secondary",children:D.description})]}),e.jsx(me,{checked:D.enabled,"aria-label":D.enabled?t("skills.library.disable",{skill:D.name}):t("skills.library.enable",{skill:D.name}),disabled:!!(h||g),onClick:()=>{j(D)}})]}),e.jsx(mr,{skill:D}),D.warnings.length>0&&e.jsx("div",{className:"mt-1 text-[11px] text-warning",children:D.warnings.join(" · ")})]},D.name))}),r&&e.jsx("div",{role:"alert",className:"mt-2 text-[12px] text-danger",children:r})]})}),e.jsx(Z,{title:t("skills.library.importTitle"),subtitle:t("skills.library.importHint"),children:e.jsxs("form",{className:"flex flex-col gap-2",onSubmit:D=>{D.preventDefault(),I()},children:[e.jsx("textarea",{className:`${H} min-h-32 font-mono text-[12px]`,placeholder:t("skills.library.importPlaceholder"),"aria-label":t("skills.library.importTitle"),value:y,onChange:D=>b(D.target.value)}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[C?e.jsx("div",{className:"text-[12px] text-ink-secondary",children:C}):e.jsx("span",{}),e.jsx("button",{type:"submit",disabled:g||!!h||!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:g?t("skills.library.importing"):t("skills.library.importButton")})]})]})})]}),x&&e.jsx(Ba,{modal:!0,children:e.jsx(Ox,{viewing:x,error:r,working:!!h,onClose:()=>{h||p(null)},onEnable:()=>{j(x.skill,!0)}})})]})}function Ox({viewing:s,error:n,working:a,onClose:i,onEnable:r}){const c=l.useRef(null);return Bl(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(mr,{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 Mx(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 pa({config:s}){const n=Mx(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 pr(s){return s?.edition?.features?.includes("admin")===!0&&s?.fleet?.available===!0}const zx=()=>O("/api/fleet");function Ux({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:[ct(i.usage.costUsd)?dt(i.usage.costUsd):"—",ct(i.usage.billableUsd)&&e.jsxs("span",{className:"text-ink-secondary",children:[" · ",dt(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 Fx({domain:s,onCreated:n,disabled:a}){const[i,r]=l.useState(""),[c,o]=l.useState(""),[d,m]=l.useState(""),[u,x]=l.useState(""),[p,h]=l.useState(""),[f,y]=l.useState(!1),[b,g]=l.useState(null),k=async()=>{if(!f){y(!0),g(null);try{const N={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()}:{}},w=await O("/api/fleet/workspaces",{method:"POST",body:JSON.stringify(N)});r(""),o(""),m(""),x(""),h(""),n(w.log??[],{slug:N.slug,admin:N.admins[0]})}catch(N){g(N instanceof Error?N.message:String(N))}finally{y(!1)}}},C="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:N=>{N.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:N=>r(N.target.value),placeholder:"acme",pattern:"[a-z][a-z0-9-]{1,30}",required:!0,disabled:a||f,"aria-label":t("workspaces.name"),className:C}),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:N=>o(N.target.value),type:"email",required:!0,disabled:a||f,"aria-label":t("workspaces.adminEmail"),className:C})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("workspaces.members"),e.jsx("input",{value:d,onChange:N=>m(N.target.value),placeholder:"bob@acme.test, @acme.test",disabled:a||f,"aria-label":t("workspaces.members"),className:C})]}),e.jsxs("label",{className:"flex flex-col gap-1 text-[12px] text-ink-secondary",children:[t("workspaces.cap"),e.jsx("input",{value:u,onChange:N=>x(N.target.value),inputMode:"decimal",placeholder:"50",disabled:a||f,"aria-label":t("workspaces.cap"),className:C})]}),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:N=>h(N.target.value),type:"password",autoComplete:"off",placeholder:"sk-ant-…",disabled:a||f,"aria-label":t("workspaces.anthropicKey"),className:C})]})]}),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(Y,{size:13,className:"animate-spin"}):e.jsx(Ce,{size:13}),f?t("workspaces.creating"):t("workspaces.create")]})})]})}function Dx({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 h=await O(`/api/fleet/workspaces/${encodeURIComponent(s)}/users`,{method:"POST",body:JSON.stringify({action:p,email:a.trim(),chatOnly:r})});i(""),n(h.log??[])}catch(h){u(h instanceof Error?h.message:String(h))}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 _x({load:s=zx}){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([]),[h,f]=l.useState(null),[y,b]=l.useState(null),[g,k]=l.useState(!1),[C,N]=l.useState(null),w=l.useCallback(async()=>{d(!0),c(null);try{i(await s())}catch(j){c(j instanceof Error?j.message:String(j))}finally{d(!1)}},[s]);l.useEffect(()=>{w()},[w]);const P=async(j,A)=>{if(A==="users"){f(I=>I===j?null:j);return}if(A==="delete"){b({slug:j,keepData:!1});return}u(j),c(null);try{const I=await O(`/api/fleet/workspaces/${encodeURIComponent(j)}/${A}`,{method:"POST"});p(I.log??[]),await w()}catch(I){c(I instanceof Error?I.message:String(I))}finally{u(null)}},v=async()=>{if(!y)return;const{slug:j,keepData:A}=y;b(null),u(j),c(null);try{const I=await O(`/api/fleet/workspaces/${encodeURIComponent(j)}`,{method:"DELETE",body:JSON.stringify({keepData:A})});p(I.log??[]),await w()}catch(I){c(I instanceof Error?I.message:String(I))}finally{u(null)}},B=async()=>{u("*"),c(null);try{const j=await O("/api/fleet/upgrade",{method:"POST"});p(j.log??[t("workspaces.upgraded")]),await w()}catch(j){c(j instanceof Error?j.message:String(j))}finally{u(null)}};return pr(n.config)?e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsxs(Z,{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:()=>{w()},disabled:o||m!==null,className:"flex items-center gap-1 text-[12px] text-ink-secondary hover:text-ink disabled:opacity-50",children:[e.jsx(Se,{size:12,className:z(o&&"animate-spin")}),t("workspaces.refresh")]}),e.jsxs("button",{type:"button",onClick:()=>k(j=>!j),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(Ce,{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")})]}),g&&a&&e.jsx("div",{className:"mb-4 rounded-xl border border-hairline/40 p-3",children:e.jsx(Fx,{domain:a.domain,disabled:m!==null,onCreated:(j,A)=>{k(!1),p(j),N(`https://${A.slug}.${a.domain}/pair?email=${encodeURIComponent(A.admin)}`),w()}})}),C&&e.jsx("div",{className:"mb-4",children:e.jsx(Vi,{link:C})}),r&&e.jsx("p",{role:"alert",className:"mb-2 text-[12px] text-danger",children:r}),a?e.jsx(Ux,{fleet:a,onAct:(j,A)=>{P(j,A)},busy:m}):o?e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-ink-secondary",children:[e.jsx(Y,{size:14,className:"animate-spin"}),t("common.checking")]}):null,h&&e.jsx(Dx,{slug:h,onDone:j=>{p(j),w()}}),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(`
|
|
19
|
+
`)})]}),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:()=>{v()}}),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:j=>b({...y,keepData:j.target.checked})}),t("workspaces.keepData")]})]}):null}const xr=s=>({method:"PUT",body:JSON.stringify(s)}),Tt=s=>s instanceof Error?s.message:String(s);function $x(){return l.useSyncExternalStore(pi,()=>Nd()?.id??null,()=>null)}function Kx(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 Hx({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(()=>{O(`/api/themes/${s}`).then(h=>c(h.theme),h=>d(Tt(h)))},[s]),!r)return e.jsx(ms,{children:o??t("settings.customThemes.loading")});const x=r.css?wd(r.css):null,p=async()=>{u(!0);try{await O(`/api/themes/${s}`,xr({theme:{...r,name:r.name.trim(),css:r.css||void 0}})),d(t("settings.customThemes.saved")),await Bs()}catch(h){d(Tt(h))}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(yn,{label:t("settings.customThemes.name"),children:e.jsx("input",{className:vn,value:r.name,maxLength:60,onChange:h=>c({...r,name:h.target.value})})}),e.jsx("div",{className:"flex flex-wrap gap-4",children:["canvas","accent"].map(h=>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[h]??(h==="canvas"?"#121212":"#1084fe"),onChange:f=>c({...r,[h]:f.target.value})}),t(h==="canvas"?"settings.customThemes.canvas":"settings.customThemes.accent"),r[h]&&e.jsx("button",{type:"button",className:"text-[12px] text-accent-text hover:underline",onClick:()=>c({...r,[h]:void 0}),children:t("settings.customThemes.clear")})]},h))}),e.jsx(yn,{label:t("settings.customThemes.css"),hint:x??t("settings.customThemes.cssHint"),children:e.jsx("textarea",{className:`${vn} h-64 resize-y py-2 font-mono text-[12px]`,spellCheck:!1,maxLength:Sd.cssChars,"aria-label":t("settings.customThemes.css"),value:r.css??"",onChange:h=>c({...r,css:h.target.value})})}),e.jsxs(yc,{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(()=>O(`/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()=>Kx(`${s}.mausbot-theme.json`,await O(`/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 Wx=6;function Gx(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:Bt.find(a=>a.id===n)?.name??n});case"default":return t("settings.customThemes.historyDefault");case"undid":return t("settings.customThemes.historyUndid")}}function Vx({items:s,act:n}){return s.length<2?null:e.jsx(be,{label:t("settings.customThemes.history"),block:"theme-history",description:t("settings.customThemes.historyHint"),children:e.jsx(ye,{children:s.slice(0,Wx).map(a=>e.jsx(ue,{title:Gx(a),subtitle:di(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 O("/api/themes/history",{method:"POST",body:JSON.stringify({index:a.index})}),await Bs()})},children:t("settings.customThemes.restore")})},a.index))})})}function hr(){const[s,n]=l.useState(null),[a,i]=l.useState(null),[r,c]=l.useState(null),o=l.useRef(null),d=$x(),[m,u]=l.useState([]),x=l.useCallback(()=>Promise.all([O("/api/themes").then(n,g=>c(Tt(g))),O("/api/themes/history").then(g=>u(g.items),()=>u([]))]),[]);l.useEffect(()=>(x(),pi(()=>{x()})),[x]);const p=async g=>{c(null);try{await g()}catch(k){c(Tt(k))}await x()},h=()=>p(async()=>{const g=`theme-${Date.now().toString(36)}`;await O(`/api/themes/${g}`,xr({theme:{name:t("settings.customThemes.newName")}})),i(g)}),f=g=>g&&p(async()=>{let k;try{k=JSON.parse(await g.text())}catch{throw new Error(t("settings.customThemes.importFailed"))}await O("/api/themes/import",{method:"POST",body:JSON.stringify(k)})}),y=(g,k)=>p(async()=>{const C=await O(`/api/themes/${g}/export`);await O(`/api/themes/${g}`,{method:"DELETE"}),i(null),await Bs(),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(()=>O("/api/themes/import",{method:"POST",body:JSON.stringify(C)}))},children:t("common.undo")})]}))}),b=bc()?"⌘⌥⇧R":"Ctrl+Alt+Shift+R";return e.jsxs(e.Fragment,{children:[e.jsx(be,{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:()=>{h()},children:t("settings.customThemes.new")}),e.jsx("input",{ref:o,type:"file",accept:"application/json,.json",hidden:!0,onChange:g=>{f(g.target.files?.[0]),g.target.value=""}})]}),footnote:r,children:e.jsxs(ye,{children:[jd()&&e.jsx(ms,{children:t("settings.customThemes.safe")}),s&&!s.themes.length&&e.jsx(ms,{children:t("settings.customThemes.empty")}),s?.themes.map(g=>a===g.id?e.jsx(Hx,{id:g.id,act:p,onClose:()=>{i(null),x()},onDelete:()=>{y(g.id,g.name)}},g.id):e.jsx(ue,{title:g.name,subtitle:d===g.id?t("settings.customThemes.inUse"):g.assets.length?t("settings.customThemes.files",{count:g.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(g.id),children:t("settings.customThemes.edit")}),d===g.id?e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{p(()=>In(null))},children:t("settings.customThemes.takeOff")}):e.jsx("button",{type:"button",className:"ui-button ui-button-primary",onClick:()=>{p(()=>In(g.id))},children:t("settings.customThemes.use")})]})},g.id)),e.jsx(ue,{title:t("settings.customThemes.reset"),subtitle:t("settings.customThemes.resetHint",{keys:b}),children:e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{kd(),x()},children:t("settings.customThemes.reset")})})]})}),e.jsx(Vx,{items:m,act:p})]})}const xa=[{choice:"system",label:"settings.theme.system"},{choice:sn.light,label:"settings.theme.light"},{choice:sn.dark,label:"settings.theme.dark"}];function Vs(){return l.useSyncExternalStore(sl,nn,nn)}function gr({simple:s=!1}){const n=Vs(),a=xa.some(i=>i.choice===n)?void 0:Bt.find(i=>i.id===n)?.name;return e.jsx(ue,{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:xa.map(i=>e.jsx("button",{type:"button",role:"radio","aria-checked":n===i.choice,onClick:()=>tl(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 qx({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 Jx={halloween:["orange","purple","teal","red"],diwali:["red","orange","pink","coral"]};function Xx({festival:s}){const n=Ml(),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:Jx[s].map(i=>e.jsx(zl,{color:i,bodyId:Ul[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:()=>Fl(!n)})]})}function fr(){const s=Pa(Vs());return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:Bt.map(n=>{const a=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>{al(n.id),Cd()},"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(qx,{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:nl(`skins.tagline.${n.id}`,n.tagline)})]}),a&&e.jsx(fe,{size:13,className:"mt-0.5 shrink-0 text-accent-text"})]})]},n.id)})}),Ol(s)&&e.jsx(Xx,{festival:s})]})}function Yx(){const[s,n]=l.useState(il);return e.jsx(ue,{title:t("settings.font.title"),subtitle:t("settings.font.subtitle"),children:e.jsx(pe,{size:"sm",className:"w-full max-w-[240px]",value:s,"aria-label":t("settings.font.aria"),onChange:a=>{const i=a.target.value;ll(i),n(i)},children:rl.map(a=>e.jsx("option",{value:a,children:t(`settings.font.${a}`)},a))})})}function Qx(){const[s,n]=l.useState(ol);return e.jsx(ue,{title:t("settings.chatWidth.title"),subtitle:t("settings.chatWidth.subtitle"),children:e.jsx(pe,{size:"sm",className:"w-full max-w-[240px]",value:s,"aria-label":t("settings.chatWidth.aria"),onChange:a=>{const i=an.find(r=>r===a.target.value);i&&(cl(i),n(i))},children:an.map(a=>e.jsx("option",{value:a,children:t(`settings.chatWidth.${a}`)},a))})})}function Zx(){const s=vc();return e.jsx(ue,{title:t("sidebar.toolsLayout.title"),subtitle:t("sidebar.toolsLayout.subtitle"),children:e.jsx(pe,{size:"sm",className:"w-full max-w-[240px]",value:s,"aria-label":t("sidebar.toolsLayout.chooseAria"),onChange:n=>kc(Nc(n.target.value)),children:jc.map(n=>e.jsx("option",{value:n,children:t(`sidebar.toolsLayout.${n}`)},n))})})}function br(){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 h=async()=>{if(!c||p.current)return;const f=Cc(i);if(!f.ok){m(t("settings.roomTurns.range"));return}p.current=!0,x(!0);try{const y=await O("/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:Sc,max:wc,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:()=>{h()},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 eh=10,yr=1,vr=60,ha="Enter a whole number from 1 to 60.";function th(s){const n=s.trim();if(!/^\d+$/.test(n))return{ok:!1,error:ha};const a=Number(n);return a<yr||a>vr?{ok:!1,error:ha}:{ok:!0,minutes:a}}function ga(s){return s?.mcp?.callTimeoutMinutes??eh}function jr(){const{state:s,dispatch:n}=G(),a=ga(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 h=async()=>{if(!c||p.current)return;const f=th(i);if(!f.ok){m(t("settings.mcpCalls.range"));return}p.current=!0,x(!0);try{const y=await O("/api/config",{method:"PUT",body:JSON.stringify({mcp:{callTimeoutMinutes:f.minutes}})});n({type:"configStatus",config:y}),r(String(ga(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:yr,max:vr,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:()=>{h()},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 kr(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 fa=new WeakMap;function sh(){const{state:s,dispatch:n}=G(),a=s.config?.profile?.aboutMe??"",i=!!s.config?.team;let r=fa.get(n);if(!r){const u={current:i};r={team:u,controller:kr(a,async x=>{const p=u.current?await Ts({aboutMe:x}):(await O("/api/config",{method:"PUT",body:JSON.stringify({profile:{aboutMe:x}}),timeoutMs:1e4})).profile;n({type:"profileSaved",profile:{aboutMe:p?.aboutMe??x}})})},fa.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(Ec,{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(nh,{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 nh({onChanged:s}){const[n,a]=l.useState([]),[i,r]=l.useState(null),[c,o]=l.useState(!1);l.useEffect(()=>{let m=!1;return O("/api/profile/learned").then(u=>{m||a(u.learned)}).catch(()=>{}),()=>{m=!0}},[]);const d=async m=>{r(m),o(!1);try{const u=await O(`/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 ba=new WeakMap;function ah(){const{state:s,dispatch:n}=G(),a=s.config?.everyBotRules;let i=ba.get(n);i||(i=kr(a??"",async u=>{const x=await O("/api/config",{method:"PUT",body:JSON.stringify({everyBotRules:u}),timeoutMs:1e4});n({type:"configStatus",config:x})}),ba.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 ya=64,va=8192,Nt=512;function ih(s){return Pc(s)?s.size>Tc?"settings.profile.avatar.tooLarge":null:"settings.profile.avatar.invalidType"}function rh(s,n){return s<ya||n<ya?"settings.profile.avatar.tooSmall":s>va||n>va?"settings.profile.avatar.tooLargeDimensions":null}async function Nr(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 lh(s,n){return Nr(s,async a=>{const i=Math.min(a.naturalWidth,a.naturalHeight)/Math.max(1,n),r=document.createElement("canvas");r.width=Nt,r.height=Nt;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,Nt,Nt);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 oh(){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=g=>{const k=u.current;k&&k.previewUrl!==g?.previewUrl&&URL.revokeObjectURL(k.previewUrl),u.current=g,m(g)};l.useEffect(()=>()=>{u.current&&URL.revokeObjectURL(u.current.previewUrl)},[]);const p=!!s.config?.team,h=async g=>{const k=p?await Ts({avatarUrl:g}):(await O("/api/config",{method:"PUT",body:JSON.stringify({profile:{avatarUrl:g}})})).profile;n({type:"profileSaved",profile:{avatarUrl:k?.avatarUrl}})},f=g=>{if(!g)return;o(null);const k=ih(g);if(k)return o(t(k));Nr(g,C=>({width:C.naturalWidth,height:C.naturalHeight})).then(({width:C,height:N})=>{const w=rh(C,N);if(w)return o(t(w));x({file:g,previewUrl:URL.createObjectURL(g),width:C,height:N,zoom:1})},()=>o(t("settings.profile.avatar.invalidType")))},y=g=>{r(!0),o(null),lh(g.file,g.zoom).then(k=>Ic(k)).then(k=>{const C=k?Dl(k.path):null;if(!C)throw new Error("avatar");return h(C)}).then(()=>x(null),()=>o(t("settings.profile.avatar.saveError"))).finally(()=>r(!1))},b=()=>{o(null),h("").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:g=>x({...d,zoom:Number(g.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",{...cs("person","picture"),src:a,alt:"",className:"size-12 rounded-full object-cover"}):e.jsx("div",{...cs("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:g=>{const k=g.target.files?.[0];g.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 wr(){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){Ts({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(oh,{}),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(sh,{}),e.jsx(ah,{})]})}function ch({profile:s}){const[n,a]=l.useState(null),i=Ac(s),r=s?.avatarUrl&&n!==s.avatarUrl?s.avatarUrl:null;return e.jsx("span",{...cs("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(ni,{size:20,"aria-hidden":"true"})})}function dh(){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(ch,{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(wr,{})})]})}function Sr({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 O("/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),O("/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 Cr(){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 O("/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(Z,{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(pe,{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 Er(){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(g=>g.snapshot.state==="available"&&!g.policy),p=x.find(g=>g.instanceId===u.backup?.instanceId),h=p?.models.options.filter(g=>!g.orgBlocked&&!g.needsCliUpdate&&(p.snapshot.authenticated!==!1||g.custom))??[],f=h.some(g=>g.id===u.backup?.model),y=g=>{i(g),d("")},b=async()=>{if(!(!a||m.current||u.enabled&&!f)){m.current=!0,c(!0),d("");try{const g=await O("/api/config",{method:"PUT",body:JSON.stringify({automaticRecovery:{enabled:a.enabled,...a.backup?.model?{backup:a.backup}:{}}})});n({type:"configStatus",config:g}),i(null)}catch(g){d(g instanceof Error?g.message:t("settings.recovery.error"))}finally{m.current=!1,c(!1)}}};return e.jsxs(Z,{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(pe,{className:"mt-2 w-full",id:"automatic-recovery-engine",value:u.backup?.instanceId??"",disabled:r||!u.enabled,onChange:g=>y({enabled:u.enabled,...g.target.value?{backup:{instanceId:g.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(g=>e.jsx("option",{value:g.instanceId,disabled:!g.models.options.some(k=>g.snapshot.authenticated!==!1||k.custom),children:g.displayName},g.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(pe,{className:"mt-2 w-full",id:"automatic-recovery-model",value:u.backup?.model??"",disabled:r||!u.enabled||!p,onChange:g=>y({enabled:u.enabled,backup:{instanceId:p.instanceId,model:g.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})}),h.map(g=>e.jsx("option",{value:g.id,children:g.label},g.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 Ar=1,Ir=3650,uh=30,Rt=1024*1024,Ns=256*1024,Pr=4*1024*1024*1024,mh=50;function ja(s){const n=Number(s);return Number.isInteger(n)&&n>=Ar&&n<=Ir?n:null}function ka(s){const n=Number(s);if(!Number.isFinite(n))return null;const a=Math.round(n*Rt);return a>=Ns&&a<=Pr&&a%Ns===0?a:null}function Na(s){const n=s/Rt;return String(Number.isInteger(n)?n:Number(n.toFixed(2)))}function Tr(){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(""),[h,f]=l.useState(null),y=l.useRef(!1),b=r??String(a===null?uh:a),g=o??(i===null?String(mh):Na(i));l.useEffect(()=>{r!==null&&a!==null&&String(a)===r&&c(null)},[a,r]),l.useEffect(()=>{o!==null&&i!==null&&Na(i)===o&&d(null)},[i,o]);const k=async(v,B)=>{if(!y.current){y.current=!0,u(B),p(""),f(null);try{const j=await O("/api/config",{method:"PATCH",body:JSON.stringify({threads:v})});n({type:"configStatus",config:j})}catch(j){p(j instanceof Error?j.message:t("settings.threadCleanup.error"))}finally{y.current=!1,u(null)}}},C=v=>{if(!v){c(null),p(""),f(null),k({eventLogRetentionDays:null},"retention");return}const B=ja(b);if(B===null){p(t("settings.threadCleanup.invalidRetention")),f("retention");return}k({eventLogRetentionDays:B},"retention")},N=v=>{if(!v){d(null),p(""),f(null),k({eventLogMaxBytes:null},"cap");return}const B=ka(g);if(B===null){p(t("settings.threadCleanup.invalidCap")),f("cap");return}k({eventLogMaxBytes:B},"cap")},w=()=>{if(a===null)return;const v=ja(b);if(v===null){p(t("settings.threadCleanup.invalidRetention")),f("retention");return}if(v===a){c(null),p("");return}k({eventLogRetentionDays:v},"retention")},P=()=>{if(i===null)return;const v=ka(g);if(v===null){p(t("settings.threadCleanup.invalidCap")),f("cap");return}if(v===i){d(null),p("");return}k({eventLogMaxBytes:v},"cap")};return e.jsxs(Z,{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:v=>C(v.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 ${h==="retention"?"border-danger/60":"border-hairline/40 focus-within:border-focus"}`,children:[e.jsx("input",{id:"thread-log-retention-days",type:"number",min:Ar,max:Ir,step:1,inputMode:"numeric",value:b,disabled:a===null||m!==null,"aria-invalid":h==="retention","aria-describedby":"thread-log-retention-help",onChange:v=>{c(v.target.value),p(""),f(null)},onBlur:w,onKeyDown:v=>{v.key==="Enter"&&v.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:v=>N(v.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 ${h==="cap"?"border-danger/60":"border-hairline/40 focus-within:border-focus"}`,children:[e.jsx("input",{id:"thread-log-cap-mib",type:"number",min:Ns/Rt,max:Pr/Rt,step:.25,inputMode:"decimal",value:g,disabled:i===null||m!==null,"aria-invalid":h==="cap","aria-describedby":"thread-log-cap-help",onChange:v=>{d(v.target.value),p(""),f(null)},onBlur:P,onKeyDown:v=>{v.key==="Enter"&&v.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 wa="min-w-0 rounded-lg border bg-inset px-3 py-2 text-[14px] text-ink focus:outline-none";function ph(){const s=dl(),[n,a]=l.useState(""),[i,r]=l.useState(""),[c,o]=l.useState(""),d=s.length>=rn,m=()=>{const u=ul({name:n,url:i},window.location.origin);if(!u.ok){o(u.error);return}ln([...s,{id:ml(s),name:u.name,url:u.url}]),a(""),r(""),o("")};return e.jsx(Z,{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:()=>ln(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:on,disabled:d,"aria-invalid":c==="name",onChange:u=>{a(u.target.value),o("")},className:`${wa} 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:`${wa} 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:on})}),e.jsx("p",{className:"text-[12px] leading-relaxed text-ink-secondary",children:d?t("webPanels.settings.full",{max:rn}):t("webPanels.settings.help")})]})})}const os="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]}`},Sa=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 xh(){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(hh,{bridge:n}):e.jsx(gh,{connection:a,bridge:n},`${a.organization.id}:${a.email}:${a.deviceId??""}`)}function hh({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(Z,{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 gh({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(""),[h,f]=l.useState(null),[y,b]=l.useState(""),[g,k]=l.useState(""),[C,N]=l.useState(null),[w,P]=l.useState(!1),v=l.useRef(0),B=l.useRef(0),j=l.useRef(0),A=l.useRef(void 0),I=l.useRef(!1),H=l.useRef(null),D=async()=>{const K=v.current,oe=++j.current,R=B.current;d(!0);try{await Promise.all([n.state().then(E=>{K===v.current&&oe===j.current&&B.current===R&&i(E)}),n.list().then(E=>{K===v.current&&oe===j.current&&c(E)})]),K===v.current&&oe===j.current&&p("")}catch{K===v.current&&oe===j.current&&p(t("companyBackup.loadFailed"))}finally{K===v.current&&oe===j.current&&d(!1)}};l.useEffect(()=>{const K=++v.current,oe=E=>{if(K!==v.current)return;B.current++,i(E);const W=E.lastBackupAt??E.schedule?.lastBackupAt;!E.busy&&!E.pendingRestore&&W&&W!==A.current&&(A.current=W,D())},R=n.onState(oe);return D(),()=>{v.current++,j.current++,R()}},[n]),l.useEffect(()=>{const K=H.current;if(!(!h||!K))return K.showModal(),()=>{K.close()}},[h]);const V=w||a?.pendingRestore===!0,$=m!==null||!a||a.busy||V,se=()=>{f(null),b(""),k(""),N(null)},ne=K=>{$||I.current||(p(""),b(""),k(""),N(null),f(K))},ce=async(K,oe)=>{if($||I.current)return;I.current=!0,u(K),p("");const R=v.current;try{await oe(()=>R===v.current)}catch{R===v.current&&p(t(K==="restore"?"companyBackup.restoreFailed":"companyBackup.actionFailed"))}finally{I.current=!1,R===v.current&&u(null)}},T=()=>{h?.kind==="create"&&ce("create",async K=>{await n.create({clientState:Lc()}),K()&&(se(),await D())})},U=async K=>{if(!n.configureSchedule||I.current||!a||K&&($||h?.kind!=="schedule"||g!=="BACK UP THIS WORKSPACE DAILY"))return;I.current=!0,u("schedule"),p("");const oe=v.current,R=B.current;k("");try{const E=await n.configureSchedule(K?{enabled:!0,confirmation:"BACK UP THIS WORKSPACE DAILY"}:{enabled:!1});oe===v.current&&(B.current===R&&i(E),se())}catch{oe===v.current&&p(t("companyBackup.scheduleFailed"))}finally{I.current=!1,oe===v.current&&u(null)}},Q=()=>{h?.kind!=="restore"||h.entry.passwordRequired!==!1&&(y.length<12||y.length>1024)||ce("prepare",async K=>{const oe=y;b(""),N(null),k("");const R=await n.prepareRestore({id:h.entry.id,...h.entry.passwordRequired!==!1?{password:oe}:{}});K()&&N(R)})},le=()=>{h?.kind!=="restore"||!C||g!=="REPLACE"||ce("restore",async K=>{const oe=localStorage.getItem(kn);if(oe&&oe!==C.id)throw new Error(t("companyBackup.restorePending"));localStorage.setItem(kn,C.id),await n.restore({id:C.id,confirmation:"REPLACE"}),K()&&(P(!0),se())})},he=()=>{h?.kind!=="delete"||g!=="DELETE"||ce("delete",async K=>{await n.delete({id:h.entry.id,confirmation:"DELETE"}),K()&&(se(),await D())})},S=async()=>{const K=v.current;try{await n.cancel()}catch{K===v.current&&p(t("companyBackup.actionFailed"))}},ae=r?.backups.filter(K=>K.status==="ready")??[],F=r?r.backups.length-ae.length:0,te=a?.progress,q=x||a?.message,ie=(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"):te?t(`companyBackup.phase.${te.phase}`):t("companyBackup.working")}),te&&te.totalBytes>0&&e.jsxs(e.Fragment,{children:[e.jsx("progress",{className:"w-full accent-accent",max:te.totalBytes,value:Math.min(te.bytesTransferred,te.totalBytes),"aria-label":t("companyBackup.progress")}),e.jsx("span",{children:t("companyBackup.transferred",{done:Xe(te.bytesTransferred),total:Xe(te.totalBytes)})})]}),a?.busy&&m!=="restore"&&e.jsx("button",{type:"button",className:"ui-button",onClick:()=>{S()},children:t("companyBackup.cancelTransfer")})]}),re=h?.kind==="restore"?t("companyBackup.restore"):h?.kind==="delete"?t("companyBackup.delete"):h?.kind==="schedule"?t("companyBackup.enableSchedule"):t("companyBackup.create"),de=a?.schedule,ve=K=>new Intl.DateTimeFormat(Me(),{dateStyle:"medium",timeStyle:"short"}).format(new Date(K));return e.jsxs(Z,{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&&de&&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:de.enabled,disabled:m!==null||!a||!de.enabled&&$,onClick:()=>de.enabled?void U(!1):ne({kind:"schedule"})})]}),e.jsx("p",{role:"status",className:"mt-2 text-[12px] text-ink-secondary",children:t(`companyBackup.scheduleStatus.${de.status}`)}),de.enabled&&de.nextBackupAt&&Number.isFinite(de.nextBackupAt)&&e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:t("companyBackup.nextBackup",{date:ve(de.nextBackupAt)})}),de.lastBackupAt&&Number.isFinite(de.lastBackupAt)&&e.jsx("p",{className:"mt-1 text-[12px] text-ink-secondary",children:t("companyBackup.lastScheduledBackup",{date:ve(de.lastBackupAt)})}),de.message&&e.jsx("p",{role:"status",className:"mt-1 break-words text-[12px] text-ink-secondary",children:de.message})]}),V?e.jsx("div",{className:"rounded-lg border border-warning/40 bg-warning/10 p-3 text-ink",children:e.jsx(jn,{})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"ui-button",disabled:$,onClick:()=>ne({kind:"create"}),children:t("companyBackup.create")}),e.jsx("button",{type:"button",className:"ui-button",disabled:m!==null||a?.busy||V||o,onClick:()=>{D()},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})}),F>0&&e.jsx("p",{role:"status",className:"text-[12px] text-ink-secondary",children:t("companyBackup.pending",{count:F})}),r&&ae.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:ae.map(K=>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:Sa(K)}),e.jsxs("div",{className:"text-[12px] text-ink-secondary",children:[Xe(K.sizeBytes),K.appVersion?` · ${K.appVersion}`:""]}),e.jsx("code",{className:"break-all text-[11px] text-ink-secondary",children:K.id})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"ui-button",disabled:$,onClick:()=>ne({kind:"restore",entry:K}),children:t("companyBackup.restore")}),e.jsx("button",{type:"button",className:"ui-button text-danger",disabled:$,onClick:()=>ne({kind:"delete",entry:K}),children:t("companyBackup.delete")})]})]},K.id))})]}),!h&&ie,!h&&q&&e.jsx("p",{role:"alert",className:"break-words text-[13px] text-danger",children:q})]}),h&&e.jsx("dialog",{ref:H,"aria-labelledby":"company-backup-dialog-title",onKeyDown:K=>{(K.key==="Escape"||K.key==="Tab")&&K.stopPropagation()},onCancel:K=>{K.preventDefault(),m||se()},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:re}),V&&e.jsx(jn,{}),(h.kind==="restore"||h.kind==="delete")&&e.jsxs("div",{className:"text-[13px] text-ink-secondary",children:[e.jsxs("p",{children:[Sa(h.entry)," · ",Xe(h.entry.sizeBytes)]}),e.jsx("code",{className:"break-all text-[11px]",children:h.entry.id})]}),(h.kind==="create"||h.kind==="schedule")&&e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:K=>{K.preventDefault(),h.kind==="schedule"?U(!0):T()},children:[e.jsx("p",{className:"text-[13px] text-ink",children:t(h.kind==="schedule"?"companyBackup.scheduleWarning":"companyBackup.managedUploadWarning",{organization:s.organization?.name??"",email:s.email??""})}),h.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")}),h.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:$,checked:g==="BACK UP THIS WORKSPACE DAILY",onChange:K=>k(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.kind==="schedule"&&g!=="BACK UP THIS WORKSPACE DAILY",children:t(h.kind==="schedule"?"companyBackup.enableSchedule":"companyBackup.create")})]}),h.kind==="restore"&&(C?e.jsxs(e.Fragment,{children:[e.jsx(Rc,{summary:C.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:$,value:g,onChange:K=>k(K.target.value),className:os})]}),e.jsx("button",{type:"button",className:"ui-button text-danger",disabled:$||g!=="REPLACE",onClick:le,children:t("backup.replace")})]}):e.jsxs("form",{className:"flex flex-col gap-3",onSubmit:K=>{K.preventDefault(),Q()},children:[e.jsx("p",{className:"text-[13px] text-ink-secondary",children:t("companyBackup.previewHelp")}),h.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:$,value:y,onChange:K=>b(K.target.value),className:os})]}),e.jsx("button",{type:"submit",className:"ui-button",disabled:$||h.entry.passwordRequired!==!1&&(y.length<12||y.length>1024),children:t("backup.validate")})]})),h.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:$,value:g,onChange:K=>k(K.target.value),className:os})]}),e.jsx("button",{type:"button",className:"ui-button text-danger",disabled:$||g!=="DELETE",onClick:he,children:t("companyBackup.delete")})]}),ie,q&&e.jsx("p",{role:"alert",className:"break-words text-[13px] text-danger",children:q}),e.jsx("button",{type:"button",autoFocus:!0,className:"ui-button w-fit",disabled:m!==null,onClick:se,children:t("companyBackup.cancel")})]})})]})}function fh({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(Gc,{size:12},a);case"cursor":return e.jsx(Wc,{size:12},a);case"gemini":return e.jsx($a,{preset:"google",size:12},a);default:return e.jsx(Hc,{size:12},a)}})})}function Ca({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(fh,{sources:r}),a]}),e.jsx("span",{className:"mt-0.5 text-[12px] leading-relaxed text-ink-secondary",children:i})]})]})}const Rr="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 bh({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(Y,{size:14,className:"animate-spin"}),t("settings.import.appsLooking")]});else if(r){const{line:u,notes:x,done:p}=Uc(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(fe,{size:12,strokeWidth:3}):e.jsx(Fc,{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(h=>e.jsx("p",{className:"mt-1 text-[12px] leading-relaxed text-ink-secondary",children:h},h))]})]})}else!n||Dc(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(Ca,{icon:e.jsx(Rs,{size:15}),label:t("onboarding.import.skills"),summary:_c(n),hint:t("onboarding.import.skillsHint"),sources:Nn(n.skills),checked:a.skills,disabled:d,onChange:u=>c({...a,skills:u})}),n.tools.length>0&&e.jsx(Ca,{icon:e.jsx(Kc,{size:15}),label:t("onboarding.import.tools"),summary:$c(n),hint:t("onboarding.import.toolsHint"),sources:Nn(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(Rr,"mt-3"),children:[d&&e.jsx(Y,{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 yh({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 h=await s.apply(p);_l("setup_import_applied",{skills:h.skills?.added.length??0,tools:h.tools?.added.length??0}),u(h),d("idle")}catch{d("failed")}}};return e.jsx(bh,{local:n,detection:a,chosen:r,status:o,result:m,onChoose:c,onBring:()=>{x()}})}function vh(){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(Mc,{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(Rr,"mt-3"),children:[t("settings.import.grokTitle"),e.jsx(Ia,{size:14,"aria-hidden":"true",className:z("transition-transform",a&&"rotate-180")})]}),s&&e.jsx("div",{className:a?void 0:"hidden",children:e.jsx(zc,{inline:!0,onClose:()=>{n(!1),i(!1)}})})]})}function Lr({client:s=Bc}){const{state:n}=G();return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(yh,{client:s,local:Oc(n.config?.cloudHome===!0)}),e.jsx(vh,{})]})}function Br({simple:s=!1}){return e.jsxs(e.Fragment,{children:[e.jsx(jh,{simple:s}),e.jsx(kh,{simple:s}),e.jsx(Nh,{simple:s})]})}const Ea=()=>typeof Notification<"u"?Notification.permission:"default";function jh({simple:s=!1}){const[n,a]=l.useState(Ea),i=Vc();if(l.useEffect(()=>{const o=()=>{document.visibilityState==="visible"&&a(Ea())};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 wn(!i);const o=await Qc();o&&(a(o),o==="granted"&&wn(!0))};return e.jsx(ue,{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 kh({simple:s=!1}){const n=qc();return e.jsx(ue,{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:()=>Jc(!n)})})}function Nh({simple:s=!1}){const n=Xc();return e.jsx(ue,{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:()=>Yc(!n)})})}function Or(){const{state:s,dispatch:n}=G(),a=Zc(s.config),[i,r]=l.useState(!1),[c,o]=l.useState("");if(!ed(s.config))return null;const d=async()=>{if(!i){r(!0),o("");try{const m=await O("/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(ue,{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 wh=["settings.font.title","settings.chatWidth.title","settings.pinnedCircles.title","settings.universalPins.title","settings.runCard.title"],Sh=["settings.roomTurns.title","settings.mcpCalls.title","settings.threads.title","settings.recovery.title","settings.threadCleanup.title","settings.keepWarm.title","settings.savedSteps.title"];function Ch({has:s,peopleOpen:n,onLooks:a,onMore:i}){return e.jsxs(e.Fragment,{children:[(s("general")||s("people"))&&e.jsx(be,{label:t("settings.group.account"),block:"general",children:e.jsxs(ye,{children:[s("general")&&e.jsx(dh,{}),s("general")&&e.jsx(Sr,{row:!0}),s("general")&&e.jsx(wi,{place:"account"}),s("people")&&e.jsx("div",{"data-settings-block":"people",className:"scroll-mt-4",children:e.jsx(qi,{simple:!0,startOpen:n})})]})}),s("appearance")&&e.jsx(be,{label:t("settings.section.appearance"),block:"appearance",children:e.jsxs(ye,{children:[e.jsx(gr,{simple:!0}),e.jsx(Eh,{onLooks:a}),e.jsx(er,{}),e.jsx(ri,{}),e.jsx(tr,{}),e.jsx(ji,{simple:!0})]})}),s("appearance")&&e.jsx(be,{label:t("settings.simple.group.typing"),children:e.jsxs(ye,{children:[e.jsx(ps,{simple:!0}),e.jsx(ki,{simple:!0}),e.jsx(Ni,{simple:!0})]})}),s("appearance")&&e.jsx(be,{label:t("notifications.title"),children:e.jsx(ye,{children:e.jsx(Br,{simple:!0})})}),s("general")&&e.jsx(be,{label:t("settings.simple.group.system"),children:e.jsxs(ye,{children:[e.jsx(Ti,{simple:!0}),e.jsx(li,{simple:!0}),e.jsx(Ri,{}),e.jsx(Li,{}),e.jsx(Pi,{simple:!0})]})}),s("import")&&e.jsx(be,{label:t("settings.section.import"),block:"import",children:e.jsx(je,{children:e.jsx(Lr,{})})}),s("organization")&&e.jsx(be,{label:t("settings.section.organization"),block:"organization",children:e.jsx(nr,{})}),s("activity")&&e.jsx(be,{label:t("settings.section.activity"),block:"activity",children:e.jsx(Ji,{})}),i&&e.jsx("div",{"data-settings-block":"more",className:"scroll-mt-4",children:e.jsx(ye,{children:e.jsx(ue,{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(ye,{children:e.jsx(xs,{simple:!0})})})]})}function Eh({onLooks:s}){const n=Vs(),a=Bt.find(r=>r.id===Pa(n))?.name,i=n==="system"?t("settings.simple.themes.followHint"):a;return e.jsx(ue,{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 Ah({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(fr,{})}),e.jsx(hr,{}),n&&e.jsx(ye,{children:e.jsx(vi,{})})]})}function Ih({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(be,{block:"more-sections",children:e.jsx(ye,{children:s.map(({id:i,labelKey:r})=>e.jsx(ue,{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(be,{label:t("settings.simple.more.limits"),block:"limits",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(Z,{title:t("settings.roomTurns.title"),subtitle:t("settings.roomTurns.subtitle"),children:e.jsx(br,{})}),e.jsx(Z,{title:t("settings.mcpCalls.title"),subtitle:t("settings.mcpCalls.subtitle"),children:e.jsx(jr,{})}),e.jsx(Cr,{}),e.jsx(Er,{}),e.jsx(Tr,{}),e.jsx(Ui,{}),e.jsx(ye,{children:e.jsx(Or,{})})]})})]})}function Ph({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(Di,{simple:!0,more:n("ai-more")}),e.jsx(ye,{children:e.jsx(yi,{simple:!0})})]})}),s("connections")&&e.jsx(je,{children:e.jsx(Ut,{title:t("settings.section.connections"),block:"connections",...n("ai-keys"),children:a})})]})}function Th({has:s,remoteAccess:n,servers:a,disclose:i}){return e.jsxs(e.Fragment,{children:[s("computer")&&e.jsx(be,{label:t("settings.simple.computer.bots"),block:"computer",children:e.jsx(je,{children:e.jsx(Hi,{})})}),s("companion")&&e.jsxs(be,{label:t(ii()?"settings.section.phoneDevices":"settings.section.thisServer"),block:"companion",children:[n.companion,n.pairing,n.domain]}),s("computer")&&e.jsxs(be,{label:t("settings.experimental.browser"),block:"browser",children:[e.jsxs(ye,{children:[e.jsx(gi,{}),e.jsx(fi,{})]}),e.jsx(bi,{})]}),s("logins")&&e.jsx("div",{"data-settings-block":"logins",className:"scroll-mt-4",children:e.jsx(Zi,{})}),(s("companion")||s("desktopWorkspaces"))&&e.jsxs(Ut,{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 Rh({has:s,disclose:n,cloudAccount:a}){const{usage:i,upgrade:r,dialog:c}=td(),o=Fd(),d=o?.view.kind==="signed-out"||o?.view.kind==="removed";return e.jsxs(e.Fragment,{children:[e.jsx("div",{"data-settings-block":"usage",className:"scroll-mt-4",children:i?e.jsx(sd,{usage:i,upgrade:r,children:c}):e.jsx(je,{note:"settings.adminOnly.usage",children:e.jsx(px,{})})}),(i||s("usage"))&&e.jsxs(Ut,{title:t("settings.simple.billing.limits"),...n("billing-limits"),children:[i&&e.jsx(nd,{usage:i,upgrade:r}),s("usage")&&e.jsx(je,{note:"settings.adminOnly.usage",children:e.jsx(ur,{})})]}),s("cloudAccount")&&e.jsxs(be,{label:t("settings.simple.billing.plan"),block:"cloudAccount",footnote:e.jsx(Dd,{}),children:[e.jsx(ye,{children:e.jsx(wi,{place:"plan",usage:i,upgrade:r})}),d?null:e.jsx("div",{className:"flex flex-col gap-4",children:a})]})]})}const Mr=()=>`${Cs()} ${ad()}`;function Lh(){const s=id(!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(ue,{title:Mr(),subtitle:n,children:e.jsx("button",{type:"button",className:"ui-button",disabled:s.item.disabled,onClick:s.item.onSelect,children:a})})}function Bh({remoteActive:s}){return e.jsx(be,{block:"updates",children:e.jsxs(ye,{children:[window.ogb?.updater?e.jsx(xi,{title:Mr()}):e.jsx(Lh,{}),e.jsx(ai,{}),!s&&e.jsx(hi,{}),e.jsx(Bi,{simple:!0})]})})}const Aa=[{id:"you",labelKey:"settings.group.you"},{id:"ai",labelKey:"settings.group.ai"},{id:"computers",labelKey:"settings.group.computers"},{id:"account",labelKey:"settings.group.account"}],qs=[{id:"general",group:"you",labelKey:"settings.section.general",icon:ni,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",...Tu()]},{id:"appearance",group:"you",labelKey:"settings.section.appearance",icon:Gd,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:rd,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:Xd,keywords:["models","model providers","engines","claude","codex","grok","providers","cli","sign in","subscription"]},{id:"connections",group:"ai",labelKey:"settings.section.connections",icon:Ya,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:ld,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:od,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:Rs,keywords:["skills","library","assign","agent skills","skill md"]},{id:"desktopWorkspaces",group:"computers",labelKey:"settings.section.desktopWorkspaces",icon:Vt,keywords:["workspace","cloud","hosted","vps","server","servers","connect","pair","switch","local"]},{id:"computer",group:"computers",labelKey:"settings.section.computer",icon:Si,keywords:["vm","virtual","desktop","browser","built-in browser","profiles","browser profiles"]},{id:"logins",group:"computers",labelKey:"settings.section.vault",icon:_t,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:Lt,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:Vt,keywords:["company","organization","organisation","sign in","enroll","managed","models","disconnect"]},{id:"usage",group:"account",labelKey:"settings.section.usage",icon:$d,keywords:["tokens","cost","billing","plan","quota","remaining","weekly","5-hour","model","used"]},{id:"backups",group:"account",labelKey:"settings.section.backups",icon:oi,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:Et,keywords:["people","users","invite","sign in","members","admins","access"]},{id:"botAccess",group:"account",labelKey:"settings.section.botAccess",icon:Et,keywords:["access","share","sharing","who can","view","chat","edit","permissions","team","members","bots"]},{id:"activity",group:"account",labelKey:"settings.section.activity",icon:qd,keywords:["activity","audit","log","history","who changed","approvals","decisions","admin"]},{id:"workspaces",group:"account",labelKey:"settings.section.workspaces",icon:Vt,keywords:["clients","tenants","fleet","workspaces","installation","installations"]},{id:"experimental",group:"account",labelKey:"settings.section.experimental",icon:cd,keywords:["early","preview","learn","skill","authoring"]}],Oh=[{id:"general",labelKey:"settings.section.general",icon:dd,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:Et,sections:["botAccess"]},{id:"ai",labelKey:"settings.group.ai",icon:ud,sections:["engines","connections","imageGeneration"],keywords:["new bots","defaults","effort"]},{id:"skills",labelKey:"settings.section.skills",icon:Rs,sections:["skills"],keywords:["skills","skill hub","library","kỹ năng","thư viện"]},{id:"computer",labelKey:"settings.simple.page.computer",icon:Si,sections:["companion","desktopWorkspaces","computer","logins"]},{id:"billing",labelKey:"settings.simple.page.billing",icon:md,sections:["usage"],keywords:["billing","included","allowance","cloud hours","voice"]},{id:"backups",labelKey:"settings.section.backups",icon:oi,sections:["backups"],keywords:["chuyển máy offline","transfer","export","import","restore","sao lưu"]},{id:"cloudAccount",labelKey:"settings.section.cloudAccount",icon:Lt,sections:["cloudAccount"],keywords:["cloud","limix cloud","đám mây","máy chủ","server"]},{id:"updates",labelKey:"settings.simple.page.updates",icon:Hd,sections:["updates"],keywords:["update","version","release","product updates","newsletter","email updates","welcome","tour","diagnostics","logs","support"]}],ws=["experimental","workspaces","decisionModel"],Mh={connections:"ai-keys",remote:"computer-elsewhere",desktopWorkspaces:"computer-elsewhere"};function zh(s,n){const a=Oh.map(r=>({...r,sections:r.sections.filter(c=>s.has(c))})).filter(r=>r.sections.length>0),i=ws.includes(n)&&s.has(n)?qs.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 Uh(s,n,a){if(a<=0){s.scrollTop=0;return}const i=s.querySelector(`[data-settings-block="${n}"]`);i&&Ms(s,i)}function Fh(s,n){return!n||[t(s.labelKey),...s.keywords??[]].some(a=>a.toLowerCase().includes(n))?!0:s.sections.some(a=>{const i=qs.find(r=>r.id===a);return i?Ss(i,n):!1})}function Ss(s,n){return!n||s.id==="connections"&<.some(a=>Is(a,n))?!0:[t(s.labelKey),...s.keywords].some(a=>a.toLowerCase().includes(n))}function Dh(s){return s?lt.filter(n=>Is(n,s)).slice(0,8):[]}const _h=s=>s.uses?us(s.uses,s.id):us(s.id);function mg(){return e.jsx(Ba,{modal:!0,children:e.jsx($h,{})})}function $h(){const s=$l(),{state:n,dispatch:a}=G(),i=pl(),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 h=x.trim().toLowerCase(),f=Mt(),y=ii(),b=qs.map(R=>R.id==="companion"?{...R,labelKey:y?"settings.section.phoneDevices":"settings.section.thisServer"}:R),k=b.filter(R=>!r||R.id==="companion"||R.id==="appearance"||R.id==="desktopWorkspaces").filter(R=>R.id!=="desktopWorkspaces"||!!window.ogb?.environments).filter(R=>R.id!=="organization"||!!window.ogb?.organization).filter(R=>R.id!=="cloudAccount"||!!(window.ogb?.cloudAccount||window.ogb?.cloudPlan&&n.config?.cloudHome===!0)).filter(R=>R.id!=="workspaces"||pr(n.config)).filter(R=>R.id!=="people"||!window.ogb&&n.config?.cloudHome!==!0).filter(R=>R.id!=="activity"||!window.ogb&&f===!0).filter(R=>R.id!=="botAccess"||!!n.config?.team&&f===!0).filter(R=>(R.id!=="skills"||Sn(n.config))&&(R.id!=="cloudAccount"||Kl)),C=k.filter(R=>Ss(R,h)),N=new Set([...k.map(R=>R.id),...r?[]:["updates"]]),w=i?[]:zh(N,o),P=w.filter(R=>Fh(R,h)),v=w.find(R=>R.sections.includes(o)),B=i?b.find(R=>R.id===o)?.labelKey:v?.labelKey,j=i?C.some(R=>R.id===o)?void 0:C[0]?.id:v&&P.includes(v)?void 0:P[0]&&(P[0].sections.find(R=>C.some(E=>E.id===R))??P[0].sections[0]);l.useEffect(()=>{j&&a({type:"toggleAppSettings",open:!0,section:j})},[a,j]);const[A,I]=l.useState({}),H=Ma();l.useEffect(()=>{H&&I(R=>R["ai-keys"]?R:{...R,"ai-keys":!0})},[H]);const D=R=>{const E=h!==""||(A[R]??Mh[c]===R);return{id:R,open:E,onToggle:()=>I(W=>({...W,[R]:!E}))}},[V,$]=l.useState(null),se=V?.for===c?V.view:null,ne=(R,E=c)=>$(R&&{view:R,for:E});l.useEffect(()=>{$(R=>R?.for===c?R:null)},[c]);const[ce,T]=l.useState(null),U=i||xl||!h?[]:wh.filter(R=>t(R).toLowerCase().includes(h)),Q=k.filter(R=>ws.includes(R.id)),le=r||!k.some(R=>R.id==="connections")?[]:Dh(h),he=R=>le.map(E=>e.jsx("button",{type:"button","data-settings-key-result":E.id,className:R,onClick:()=>{p(""),ne(null),a(_h(E))},children:e.jsxs("span",{children:[t(E.labelKey)," ",e.jsxs("span",{className:"text-ink-secondary",children:["· ",t(pd(E).titleKey)]})]})},E.id)),S=v?.sections.indexOf(o)??0,ae=!i&&c==="remote"?"remote":o;l.useEffect(()=>{m.current&&Uh(m.current,ae,i?0:ae===o?S:1)},[i,ae,o,S]),l.useEffect(()=>{if(!ce)return;const R=m.current?.querySelector(`[data-settings-block="${ce}"]`);m.current&&R&&Ms(m.current,R),T(null)},[ce]),l.useEffect(()=>{const R=document.activeElement instanceof HTMLElement?document.activeElement:null,E=d.current,W=E?.querySelector("[data-settings-search]");u.current&&W?.checkVisibility()?W.focus():E?.focus();const xe=X=>{if(!s())return;if(!u.current&&E&&document.activeElement===E&&X.key.length===1&&!X.metaKey&&!X.ctrlKey&&!X.altKey&&W?.checkVisibility()){X.preventDefault(),W.focus(),p(ze=>ze+X.key);return}if(X.defaultPrevented||E&&[...E.querySelectorAll('[role="dialog"], [role="alertdialog"]')].some(ze=>ze.getClientRects().length))return;if(X.key==="Escape"){X.preventDefault(),a({type:"toggleAppSettings",open:!1});return}if(X.key!=="Tab"||!E)return;const ke=Array.from(E.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){X.preventDefault(),E.focus();return}const Pe=ke[0],et=ke[ke.length-1],tt=document.activeElement;X.shiftKey&&(tt===Pe||!E.contains(tt))?(X.preventDefault(),et.focus()):!X.shiftKey&&tt===et&&(X.preventDefault(),Pe.focus())};return window.addEventListener("keydown",xe),()=>{window.removeEventListener("keydown",xe),R?.focus()}},[a,s]);const F=R=>a({type:"toggleAppSettings",open:!0,section:R}),te=n.appSettingsPhonePairing,q=Ed(n.config?.cloudHome===!0)==="computer",ie={client:e.jsx(vp,{hideWhenUnavailable:!0,legacyOnly:!0}),domain:r||y?null:e.jsx(mp,{}),pairing:y?null:e.jsx(Gm,{cloudHome:n.config?.cloudHome===!0,focusRequest:q?0:te,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(Vm,{profileEmail:n.config?.profile?.email,focusRequest:te,simple:!i}):null},re=R=>{switch(R){case"desktopWorkspaces":return e.jsxs(e.Fragment,{children:[e.jsx(Zn,{}),ie.client]});case"organization":return window.ogb?.organization&&!r?e.jsx(nr,{}):null;case"cloudAccount":return(window.ogb?.cloudAccount||window.ogb?.cloudPlan&&n.config?.cloudHome===!0)&&!r?e.jsx(lx,{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(xs,{}),e.jsx(li,{}),e.jsx(Ri,{}),e.jsx(_d,{}),e.jsx(hd,{}),e.jsxs(Z,{title:t("settings.profile.title"),subtitle:t("settings.profile.sharedSubtitle"),children:[e.jsx(wr,{}),e.jsx(Sr,{})]}),e.jsx(ps,{}),e.jsx(Ti,{}),e.jsx(zd,{}),e.jsx(Or,{}),e.jsx(Pi,{}),e.jsx(ai,{}),e.jsx(yi,{}),e.jsx(Z,{title:t("settings.roomTurns.title"),subtitle:t("settings.roomTurns.subtitle"),children:e.jsx(br,{})}),e.jsx(Z,{title:t("settings.mcpCalls.title"),subtitle:t("settings.mcpCalls.subtitle"),children:e.jsx(jr,{})}),e.jsx(Cr,{}),e.jsx(Er,{}),e.jsx(Tr,{}),e.jsx(Li,{}),e.jsx(ph,{}),!r&&e.jsx(hi,{}),e.jsx(xi,{}),e.jsx(Bi,{})]});case"appearance":return e.jsxs(e.Fragment,{children:[e.jsx(gr,{}),e.jsx(Z,{title:t("settings.skin.title"),subtitle:t("settings.skin.subtitle"),children:e.jsx(fr,{})}),e.jsx(hr,{}),e.jsx(Bp,{}),r&&e.jsx(xs,{}),r&&e.jsx(ps,{}),e.jsx(Yx,{}),e.jsx(Qx,{}),e.jsx(ji,{}),e.jsx(ki,{}),e.jsx(Ni,{}),e.jsx(Zx,{}),e.jsx(ri,{}),e.jsx(tr,{}),e.jsx(Ld,{}),e.jsx(Bd,{}),e.jsx(Od,{}),e.jsx(Br,{}),!r&&e.jsx(vi,{}),e.jsx(Md,{})]});case"experimental":return e.jsx(Rd,{});case"connections":return e.jsx(je,{children:e.jsx(Pu,{})});case"decisionModel":return e.jsx(je,{children:e.jsx(_u,{})});case"imageGeneration":return e.jsx(je,{children:e.jsx(Xu,{})});case"engines":return e.jsx(je,{children:e.jsx(Di,{})});case"backups":return e.jsxs(je,{children:[e.jsx(xd,{}),e.jsx(xh,{})]});case"import":return e.jsx(je,{children:e.jsx(Lr,{})});case"companion":return e.jsxs(e.Fragment,{children:[ie.companion,ie.pairing,ie.domain,window.ogb?.environments?null:ie.client]});case"computer":return e.jsxs(e.Fragment,{children:[e.jsx(gi,{}),e.jsx(fi,{}),e.jsx(bi,{}),e.jsx(je,{children:e.jsx(Hi,{})})]});case"logins":return e.jsx(Zi,{});case"usage":return e.jsx(je,{note:"settings.adminOnly.usage",children:e.jsx(ur,{})});case"skills":return Sn(n.config)?e.jsx(Bx,{}):null;case"people":return e.jsx(qi,{});case"activity":return e.jsx(Ji,{});case"botAccess":return e.jsx(sp,{});case"workspaces":return e.jsx(_x,{});default:return null}},de=()=>{F("general"),ne("more","general")},ve=R=>{const E=W=>R.sections.includes(W);switch(R.id){case"general":return se==="looks"?e.jsx(Ah,{toolCalls:!r,onBack:()=>{ne(null),T("appearance")}}):se==="more"?e.jsx(Ih,{sections:Q,onOpen:W=>{ne(null),F(W)},onBack:()=>{ne(null),T("more")}}):e.jsx(Ch,{has:E,peopleOpen:o==="people",onLooks:()=>ne("looks"),onMore:E("general")?()=>ne("more"):void 0});case"ai":return e.jsx(Ph,{has:E,disclose:D,connections:re("connections")});case"computer":return e.jsx(Th,{has:E,remoteAccess:ie,servers:e.jsx(Zn,{}),disclose:D});case"billing":return e.jsx(Rh,{has:E,disclose:D,cloudAccount:re("cloudAccount")});case"updates":return e.jsx(Bh,{remoteActive:r});default:return e.jsxs(e.Fragment,{children:[ws.includes(R.sections[0])&&N.has("general")&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ui-button",onClick:de,children:t("settings.simple.looks.back")})}),R.sections.map(W=>e.jsx("section",{"data-settings-block":W,className:"flex scroll-mt-4 flex-col gap-4",children:re(W)},W))]})}},K=()=>a({type:"toggleAppSettings",open:!1}),oe=(R,E)=>e.jsxs("div",{className:R,children:[e.jsx(pt,{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(""):K())},placeholder:t("settings.search"),"aria-label":t("settings.searchAria"),className:E})]});if(!i){const R=v?.id==="general"?se:null,E="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=X=>{ne(null),F(X)},xe=h?[...Q.filter(X=>Ss(X,h)).map(X=>({key:X.id,labelKey:X.labelKey,open:()=>W(X.id)})),...(N.has("general")?Sh:[]).filter(X=>t(X).toLowerCase().includes(h)).map(X=>({key:X,labelKey:X,open:()=>{de(),T("limits")}}))]:[];return e.jsxs("div",{className:"glass-popup-frame","data-settings-sheet":!0,"data-settings-look":"simple",style:En(),onMouseDown:X=>X.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(hl,{}),e.jsxs("nav",{"aria-label":t("settings.title"),className:"glass-rail hidden min-h-0 w-[198px] shrink-0 flex-col gap-0.5 overflow-y-auto px-3 py-4 sm:flex",children:[oe("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&&U.length===0&&xe.length===0&&le.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(X=>{const ke=X.icon,Pe=X===v;return e.jsxs("button",{type:"button","data-settings-page":X.id,onClick:()=>W(X.sections[0]),"aria-current":Pe?"page":void 0,className:z("flex h-8 shrink-0 cursor-pointer items-center gap-[9px] rounded-lg px-[9px] text-left text-[13px] text-ink transition-colors motion-reduce:transition-none",Pe?"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:"truncate",children:t(X.labelKey)})]},X.id)}),U.map(X=>e.jsx("button",{type:"button","data-settings-advanced-only":X,onClick:()=>{p(""),W("general"),T("advanced-mode")},className:E,children:e.jsxs("span",{children:[t(X)," ",e.jsxs("span",{className:"text-ink-secondary",children:["· ",t("settings.simple.advanced")]})]})},X)),xe.map(X=>e.jsx("button",{type:"button","data-settings-more-result":X.key,onClick:()=>{p(""),X.open()},className:E,children:e.jsxs("span",{children:[t(X.labelKey)," ",e.jsxs("span",{className:"text-ink-secondary",children:["· ",t("settings.simple.more.title")]})]})},X.key)),he(E)]}),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(pe,{className:"min-w-0 sm:hidden","aria-label":t("settings.title"),value:v?.id??"",onChange:X=>{p("");const ke=w.find(Pe=>Pe.id===X.target.value);ke&&W(ke.sections[0])},children:w.map(X=>e.jsx("option",{value:X.id,children:t(X.labelKey)},X.id))}),e.jsx("h2",{className:"hidden truncate text-[17px] font-medium leading-6 tracking-[-0.008em] text-ink sm:block",children:R==="looks"?t("settings.simple.page.looks"):R==="more"?t("settings.simple.more.title"):v?t(v.labelKey):null})]}),e.jsx("button",{type:"button",onClick:K,"aria-label":t("settings.close"),title:`${t("settings.close")} (${Cn("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]",Za,"[&_.uppercase]:normal-case [&_.uppercase]:tracking-normal"),children:[e.jsx(pa,{config:n.config}),v?ve(v):null]})]})]})]})}return e.jsxs("div",{className:"glass-popup-frame","data-settings-sheet":!0,"data-settings-look":"advanced",style:En(),onMouseDown:R=>R.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] 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")}),oe("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"),C.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()})}),Aa.map(R=>{const E=C.filter(W=>W.group===R.id);return E.length===0?null:e.jsxs("div",{role:"group","aria-labelledby":`settings-group-${R.id}`,"data-settings-group":R.id,className:"flex flex-col gap-0.5 pb-2",children:[e.jsx("div",{id:`settings-group-${R.id}`,className:"px-[9px] pb-1 pt-2 text-[12px] font-medium leading-4 text-ink-tertiary",children:t(R.labelKey)}),E.map(({id:W,labelKey:xe,icon:X})=>e.jsxs("button",{"data-settings-section":W,onClick:()=>F(W),"aria-current":o===W?"page":void 0,className:z("flex h-8 shrink-0 cursor-pointer items-center gap-[9px] rounded-lg px-[9px] 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(X,{size:15,className:"shrink-0"}),t(xe)]},W))]},R.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(pe,{className:"min-w-0 sm:hidden","aria-label":t("settings.title"),value:o,onChange:R=>{p(""),F(R.target.value)},children:Aa.map(R=>{const E=k.filter(W=>W.group===R.id);return E.length===0?null:e.jsx("optgroup",{label:t(R.labelKey),children:E.map(({id:W,labelKey:xe})=>e.jsx("option",{value:W,children:t(xe)},W))},R.id)})}),e.jsx("span",{className:"hidden text-[15px] font-semibold text-ink sm:block",children:B?t(B):null}),e.jsx("button",{onClick:K,"aria-label":t("settings.close"),title:`${t("settings.close")} (${Cn("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(pa,{config:n.config}),re(o)]})]})]})]})}export{qs as SECTIONS,Aa as SETTINGS_GROUPS,Mh as SIMPLE_FOLDED,ws as SIMPLE_HIDDEN_SECTIONS,Oh as SIMPLE_PAGES,mg as SettingsModal,Dh as keySearchResults,_h as openKeyResult,Uh as revealSettingsBlock,Ss as sectionMatches,zh as simpleSettingsPages};
|