@markus-global/cli 0.11.3 → 0.12.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.js +5 -1
- package/dist/backend.js.map +1 -1
- package/dist/commands/approval-card.d.ts +53 -0
- package/dist/commands/approval-card.d.ts.map +1 -0
- package/dist/commands/approval-card.js +43 -0
- package/dist/commands/approval-card.js.map +1 -0
- package/dist/commands/auth.d.ts.map +1 -1
- package/dist/commands/auth.js +11 -5
- package/dist/commands/auth.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +7 -5
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/model.d.ts.map +1 -1
- package/dist/commands/model.js +6 -4
- package/dist/commands/model.js.map +1 -1
- package/dist/commands/outbound.d.ts +76 -0
- package/dist/commands/outbound.d.ts.map +1 -0
- package/dist/commands/outbound.js +80 -0
- package/dist/commands/outbound.js.map +1 -0
- package/dist/commands/start.d.ts +124 -2
- package/dist/commands/start.d.ts.map +1 -1
- package/dist/commands/start.js +718 -82
- package/dist/commands/start.js.map +1 -1
- package/dist/index.js +5 -20
- package/dist/index.js.map +1 -1
- package/dist/markus.mjs +112615 -103125
- package/dist/web-ui/assets/AsyncState-BebkDWbq.js +1 -0
- package/dist/web-ui/assets/{CommentInput-DN3Cichs.js → CommentInput-BRZWIC3U.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-CjHOyYgJ.js → ContentRenderer-PGP8H_Zz.js} +2 -2
- package/dist/web-ui/assets/DeliverableShareModal-CcigVYGz.js +1 -0
- package/dist/web-ui/assets/Deliverables-CQwXaCA4.js +3 -0
- package/dist/web-ui/assets/{Notifications-CCsdBfdg.js → Notifications-BvHJCIRG.js} +1 -1
- package/dist/web-ui/assets/Search-BA-aXh7i.js +1 -0
- package/dist/web-ui/assets/SendToChat-CAfyKhpq.js +1 -0
- package/dist/web-ui/assets/Settings-icFp6tNI.js +8 -0
- package/dist/web-ui/assets/{Store-BWi97VP9.js → Store-DKwOcmMu.js} +1 -1
- package/dist/web-ui/assets/Switch-C7lFnHA7.js +1 -0
- package/dist/web-ui/assets/Team-DyqXLZ-X.js +84 -0
- package/dist/web-ui/assets/Work-BXGrda4S.js +12 -0
- package/dist/web-ui/assets/{arc-Cg0-C295.js → arc-Dnk6N-Zc.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BctEHNLp.js → architectureDiagram-3BPJPVTR-CV8JIXXD.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-hxr2ZwOV.js → blockDiagram-GPEHLZMM-D9pKmrXH.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-CfIRo1GE.js → c4Diagram-AAUBKEIU-Q26HvIpY.js} +1 -1
- package/dist/web-ui/assets/channel-BZs6ereM.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-T0bENsqX.js → chunk-2J33WTMH-BSjFVwnx.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-ChLLkyYx.js → chunk-4BX2VUAB-BZXv4MQp.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-BD3ENYp9.js → chunk-55IACEB6-CeKd3oeJ.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-BAes4atE.js → chunk-727SXJPM-DP1tSQo5.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-FymM7gfT.js → chunk-AQP2D5EJ-DqEncn7j.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-N5sRT0m9.js → chunk-FMBD7UC4-tuDUJ9Xx.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-BSjS3JyS.js → chunk-ND2GUHAM-DoC8aLWB.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-Dkwitdbr.js → chunk-QZHKN3VN-74zpvcgs.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C9JIxJeJ.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C9JIxJeJ.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-BLuYATCK.js → cose-bilkent-S5V4N54A-DjYUalC1.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-DGLiqiH2.js → dagre-BM42HDAG-oSewacE8.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-Cq_GnNKs.js → diagram-2AECGRRQ-C1fiWe46.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-CHNz-2dA.js → diagram-5GNKFQAL-9G_q6hCa.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-D8eKa7jh.js → diagram-KO2AKTUF-CSm-lJp-.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-RkDgQcLr.js → diagram-LMA3HP47-BTAORcHx.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-LqxQrIwa.js → diagram-OG6HWLK6-DbcCkDfo.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-Be-Qo_ag.js → docx-preview-DjqdA44x.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-BX0zZgYQ.js → erDiagram-TEJ5UH35-DFa-B8-u.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-DKnfIFA4.js → flowDiagram-I6XJVG4X-WCTnaK9M.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-DjBURmY-.js → ganttDiagram-6RSMTGT7-DbW1CoJJ.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BvSi7SvS.js → gitGraphDiagram-PVQCEYII-1faDfO29.js} +1 -1
- package/dist/web-ui/assets/index-B8h1PPzP.js +883 -0
- package/dist/web-ui/assets/index-DD3NMntN.css +1 -0
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CwtIgim2.js → infoDiagram-5YYISTIA-DfXKP4tQ.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-CWhXJfSa.js → ishikawaDiagram-YF4QCWOH-D6FOsFQ5.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-DN9rorlL.js → journeyDiagram-JHISSGLW-DXpxntIF.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-Burf5FE8.js → kanban-definition-UN3LZRKU-Dt7FBCF3.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-Dx4rzlyC.js → mermaid.core-sTcSUoRD.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DqZ21Siw.js → mindmap-definition-RKZ34NQL-CvOU23ga.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-C_4ksu-T.js → pieDiagram-4H26LBE5-DUedtXVj.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-Dl6Rjg1X.js → quadrantDiagram-W4KKPZXB-CqpHHRca.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-CzmWi02d.js → requirementDiagram-4Y6WPE33-CKZYvVDJ.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-D8K7e8we.js → sankeyDiagram-5OEKKPKP-gZ0nzDfs.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-1z9rqtVx.js → sequenceDiagram-3UESZ5HK-DN3XdBkW.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-nneYkkHa.js → stateDiagram-AJRCARHV-BvtafGxO.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-B2nWDV5R.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-D6GmLlRi.js → timeline-definition-PNZ67QCA-BrR919lp.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-TVefhiCa.js → vennDiagram-CIIHVFJN-B7CTm4yM.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-BgUuAeiM.js → wardley-L42UT6IY-CyqFngx_.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CyJ_l94o.js → wardleyDiagram-YWT4CUSO-BCqEPBJ5.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-kajbbx7a.js → xychartDiagram-2RQKCTM6-BmT6Cmz-.js} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/docs/README.md +1 -0
- package/docs/architecture/architecture.md +1 -1
- package/docs/architecture/configuration-model.md +156 -0
- package/docs/architecture/messaging-gateway.md +1043 -0
- package/docs/architecture/notification-delivery.md +273 -0
- package/docs/design/remote-access-contract.md +445 -0
- package/docs/guides/development.md +1 -1
- package/docs/guides/guide.md +4 -2
- package/docs/guides/remote-access.md +147 -214
- package/docs/handoff/approval-tri-state-handoff.md +69 -0
- package/docs/handoff/remote-access-handoff.md +160 -0
- package/docs/records/agent-platform-friction-2026-10.md +102 -2
- package/package.json +1 -1
- package/dist/web-ui/assets/DeliverableShareModal-CBSvxB-X.js +0 -1
- package/dist/web-ui/assets/Deliverables-BaAF4-w0.js +0 -3
- package/dist/web-ui/assets/Search-BiBdevAU.js +0 -1
- package/dist/web-ui/assets/Settings-CawBnWuy.js +0 -8
- package/dist/web-ui/assets/Team-CfUDkdc3.js +0 -84
- package/dist/web-ui/assets/Work-DrIXOW-P.js +0 -12
- package/dist/web-ui/assets/channel-DAQ2Rbxq.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BZyCVtJb.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BZyCVtJb.js +0 -1
- package/dist/web-ui/assets/index-D8vskks7.js +0 -882
- package/dist/web-ui/assets/index-DEN_qReg.css +0 -1
- package/dist/web-ui/assets/modelCapabilities-DDtCBZ6o.js +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C-hpzcms.js +0 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{u as xe,r as o,j as e,J as fs,l as F,k as ti,y as si,a0 as ri,a1 as ni,h as Ot,a2 as oa,a3 as ai,a4 as ii,w as oi,a5 as li,v as la,a6 as di,a7 as ci,a8 as ui,a9 as dn,aa as mi,n as ms,P as br,_ as xi,ab as gi,a as fi,b as pi,c as hi,ac as cn,ad as bi,ae as un,i as yi,o as Us}from"./index-B8h1PPzP.js";import{L as vi}from"./AsyncState-BebkDWbq.js";import{i as ji,S as bs}from"./Switch-C7lFnHA7.js";function Ni(t,r){for(var i=0;i<r.length;i++){const a=r[i];if(typeof a!="string"&&!Array.isArray(a)){for(const n in a)if(n!=="default"&&!(n in t)){const s=Object.getOwnPropertyDescriptor(a,n);s&&Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>a[n]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}function wi(t){return t>=1e6?`${(t/1e6).toFixed(t%1e6===0?0:1)}M`:t>=1e3?`${(t/1e3).toFixed((t%1e3===0,0))}K`:String(t)}function ki(t){return t.maxInputTokens>0||t.inputCostPer1MTokens>0||t.outputCostPer1MTokens>0}function Ks(t){if(t.tier)return t.tier;const r=t.id.toLowerCase(),i=/opus|5\.4|o3-(?!mini)|o1-(?!mini)|gemini.*ultra|sonnet-4-20/,a=/haiku|flash|nano|lite|small|fast|free|8b|7b|1b|3b/;return/o4-mini|o3-mini|o1-mini|gpt-4o-mini/.test(r)?"pro":i.test(r)?"max":a.test(r)?"base":"pro"}const mn={max:"bg-purple-500/20 text-purple-400 border-purple-500/30",pro:"bg-blue-500/20 text-blue-400 border-blue-500/30",base:"bg-gray-500/20 text-gray-400 border-gray-500/30"};function da({models:t,selectedModel:r,onSelect:i,loading:a,compact:n,maxVisible:s,showTiers:c}){const{t:d}=xe("settings"),[u,p]=o.useState(""),[x,k]=o.useState(!1),[y,j]=o.useState(""),w=o.useMemo(()=>{let m=t;if(u){const v=u.toLowerCase();m=m.filter($=>$.id.toLowerCase().includes(v))}return y&&(m=m.filter(v=>Ks(v)===y)),m},[t,u,y]),b=o.useMemo(()=>{const m={max:0,pro:0,base:0};for(const v of t)m[Ks(v)]++;return m},[t]),S=s??(n?5:10),h=x?w:w.slice(0,S),P=w.length>S;return a?e.jsxs("div",{className:"flex items-center gap-2 py-4 text-sm text-fg-tertiary",children:[e.jsx("div",{className:"w-4 h-4 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),d("modelPicker.loading")]}):t.length===0?e.jsx("div",{className:"py-3 text-sm text-fg-tertiary",children:d("modelPicker.empty")}):e.jsxs("div",{className:"space-y-2",children:[c&&t.length>3&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>j(""),className:`px-2 py-0.5 rounded text-[10px] transition-colors ${y?"bg-surface-overlay text-fg-tertiary hover:text-fg-secondary":"bg-brand-500/20 text-brand-500"}`,children:d("modelPicker.allCount",{count:t.length})}),["max","pro","base"].filter(m=>b[m]>0).map(m=>e.jsx("button",{onClick:()=>j(y===m?"":m),className:`px-2 py-0.5 rounded text-[10px] font-medium uppercase transition-colors border ${y===m?mn[m]:"border-transparent bg-surface-overlay text-fg-tertiary hover:text-fg-secondary"}`,children:d("modelPicker.tierCount",{tier:d(`modelRouting.tier.${m}`),count:b[m]})},m))]}),t.length>5&&e.jsx("input",{type:"text",value:u,onChange:m=>{p(m.target.value),k(!1)},placeholder:d("modelPicker.filterPlaceholder"),className:"w-full px-3 py-1.5 bg-surface-overlay border border-border-default rounded-lg text-xs text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:border-brand-500"}),e.jsx("div",{className:`space-y-1 ${n?"max-h-[280px] overflow-y-auto":""}`,children:h.map(m=>{const v=m.id===r,$=Ks(m);return e.jsxs("button",{type:"button",onClick:()=>i(m.id),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${v?"bg-brand-500/10 border border-brand-500/30":"hover:bg-surface-overlay border border-transparent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-3 h-3 rounded-full border-2 flex items-center justify-center ${v?"border-brand-500":"border-border-default"}`,children:v&&e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),e.jsx("span",{className:`text-xs font-medium ${v?"text-brand-500":"text-fg-primary"}`,children:m.id}),c&&e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-semibold uppercase border ${mn[$]}`,children:d(`modelRouting.tier.${$}`)})]}),e.jsx("div",{className:"flex items-center gap-2",children:v&&e.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:d("modelPicker.active")})})]}),ki(m)&&m.maxInputTokens>0&&e.jsx("div",{className:"ml-5 mt-0.5 flex items-center gap-2 text-[10px] text-fg-tertiary flex-wrap",children:e.jsxs("span",{children:[wi(m.maxInputTokens)," ",d("modelPicker.ctx")]})}),!n&&e.jsxs("div",{className:"ml-5 mt-1 flex items-center gap-1.5 flex-wrap",children:[m.capabilities.functionCalling&&e.jsx(Et,{label:d("modelPicker.capabilities.tools")}),m.capabilities.vision&&e.jsx(Et,{label:d("modelPicker.capabilities.vision")}),m.capabilities.reasoning&&e.jsx(Et,{label:d("modelPicker.capabilities.reasoning")}),m.capabilities.promptCaching&&e.jsx(Et,{label:d("modelPicker.capabilities.caching")}),m.capabilities.webSearch&&e.jsx(Et,{label:d("modelPicker.capabilities.search")})]})]},m.id)})}),P&&!x&&e.jsx("button",{type:"button",onClick:()=>k(!0),className:"text-xs text-brand-500 hover:text-brand-400 px-3",children:d("modelPicker.showAll",{count:w.length})}),x&&P&&e.jsx("button",{type:"button",onClick:()=>k(!1),className:"text-xs text-fg-tertiary hover:text-fg-secondary px-3",children:d("modelPicker.showLess")})]})}function Et({label:t}){return e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] bg-surface-overlay text-fg-tertiary border border-border-default",children:t})}function Vt({value:t,options:r,placeholder:i,onChange:a}){const{t:n}=xe("settings"),[s,c]=o.useState(!1),[d,u]=o.useState(""),p=o.useRef(null),x=o.useRef(null),k=o.useRef(null),[y,j]=o.useState(-1);o.useEffect(()=>{function m(v){p.current&&!p.current.contains(v.target)&&c(!1)}return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]),o.useEffect(()=>{s&&x.current&&x.current.focus()},[s]);const w=o.useMemo(()=>{if(!d.trim())return r;const m=d.toLowerCase();return r.filter(v=>v.modelId.toLowerCase().includes(m)||v.modelName.toLowerCase().includes(m)||v.provider.toLowerCase().includes(m)||v.providerLabel.toLowerCase().includes(m)||v.tier&&v.tier.toLowerCase().includes(m))},[r,d]),b=o.useMemo(()=>{const m=new Map;for(const $ of w){const I=$.providerLabel;m.has(I)||m.set(I,[]),m.get(I).push($)}const v={max:0,pro:1,base:2};for(const $ of m.values())$.sort((I,R)=>(v[I.tier??"base"]??9)-(v[R.tier??"base"]??9));return m},[w]),S=o.useMemo(()=>{const m=[];for(const v of b.values())m.push(...v);return m},[b]),h=o.useMemo(()=>{if(!t)return i??n("modelRouting.auto");const m=r.find(v=>`${v.provider}/${v.modelId}`===t);return m?`${m.providerLabel}/${m.modelName}`:t},[t,r,i,n]);function P(m){if(!s){(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),c(!0));return}switch(m.key){case"ArrowDown":m.preventDefault(),j(v=>Math.min(v+1,S.length-1));break;case"ArrowUp":m.preventDefault(),j(v=>Math.max(v-1,-1));break;case"Enter":m.preventDefault(),y===-1?a(""):S[y]&&a(`${S[y].provider}/${S[y].modelId}`),c(!1),u("");break;case"Escape":c(!1),u("");break}}return o.useEffect(()=>{k.current&&y>=0&&k.current.querySelector(`[data-focus-index="${y}"]`)?.scrollIntoView({block:"nearest"})},[y]),e.jsxs("div",{ref:p,className:"relative min-w-0",onKeyDown:P,children:[e.jsx("button",{type:"button",onClick:()=>{c(!s),u(""),j(-1)},className:"w-full px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary text-left truncate focus:outline-none focus:border-brand-500",children:h}),s&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full min-w-[240px] max-h-[280px] bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden flex flex-col",children:[e.jsx("div",{className:"p-1.5 border-b border-border-default",children:e.jsx("input",{ref:x,type:"text",value:d,onChange:m=>{u(m.target.value),j(-1)},placeholder:n("modelPicker.searchPlaceholder")||"Search models...",className:"w-full px-2 py-1 bg-surface-overlay border border-border-default rounded text-xs text-fg-primary focus:outline-none focus:border-brand-500"})}),e.jsxs("div",{ref:k,className:"overflow-y-auto flex-1",children:[e.jsx("div",{className:`px-3 py-1.5 text-xs cursor-pointer ${y===-1?"bg-brand-500/20 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,onClick:()=>{a(""),c(!1),u("")},children:i??n("modelRouting.auto")}),[...b.entries()].map(([m,v])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 py-1 text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider bg-surface-overlay/50 sticky top-0",children:m}),v.map($=>{const I=S.indexOf($),R=`${$.provider}/${$.modelId}`===t;return e.jsxs("div",{"data-focus-index":I,className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${I===y?"bg-brand-500/20":R?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,onClick:()=>{a(`${$.provider}/${$.modelId}`),c(!1),u("")},children:[e.jsx("span",{className:"flex-1 truncate text-fg-primary",children:$.modelName}),$.tier&&e.jsx(Ci,{tier:$.tier}),$.costTier&&e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:$.costTier})]},`${$.provider}/${$.modelId}`)})]},m)),S.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:n("modelPicker.empty")})]})]})]})}function Ci({tier:t}){const r={max:"bg-purple-500/20 text-purple-400",pro:"bg-blue-500/20 text-blue-400",base:"bg-gray-500/20 text-gray-400"};return e.jsx("span",{className:`px-1 py-0.5 rounded text-[8px] font-bold uppercase ${r[t]??r.base}`,children:t})}const Si=500,xn=[{groupKey:"image",capabilities:["image_recognition","image_generation"]},{groupKey:"audio",capabilities:["audio_tts","audio_stt"]},{groupKey:"video",capabilities:["video_generation"]}];function Ai({onSave:t,configuredProviders:r}){const{t:i}=xe(["settings","common"]),[a,n]=o.useState({}),[s,c]=o.useState(null),[d,u]=o.useState(!1),[p,x]=o.useState(null),[k,y]=o.useState(!0),[j,w]=o.useState("idle"),[b,S]=o.useState(null),[h,P]=o.useState({}),[m,v]=o.useState(!1),[$,I]=o.useState("idle"),[R,V]=o.useState(null),[C,M]=o.useState(!1),B=o.useRef(null),L=o.useRef(null),U=o.useMemo(()=>r.map(g=>g.name).sort().join(","),[r]);o.useEffect(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(g=>{if(!g.ok)throw new Error(`HTTP ${g.status}`);return g.json()}).then(g=>{n(g.capabilityRouting?.assignments??{}),c(g.routingDefaultModel??null),u(!0)}).catch(g=>{x(String(g)),u(!0)})},[U]),o.useEffect(()=>{let g=!1;return y(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(T=>{if(!T.ok)throw new Error(`HTTP ${T.status}`);return T.json()}).then(T=>{if(g)return;const f=[];for(const K of T.providers)for(const z of K.models)f.push({provider:K.provider,providerLabel:K.displayName,modelId:z.id,modelName:z.name,mode:z.mode,tier:z.tier,costTier:z.costTier,capabilities:z.capabilities});S(f)}).catch(()=>{g||S(null)}).finally(()=>{g||y(!1)}),()=>{g=!0}},[U]),o.useEffect(()=>{fetch("/api/models/suggested-assignments",{credentials:"include"}).then(g=>{if(!g.ok)throw new Error(`HTTP ${g.status}`);return g.json()}).then(g=>{P(g.suggestions),v(!0)}).catch(()=>v(!0))},[U]);const H=o.useCallback(g=>{w("saving"),t(g).then(()=>{w("saved"),setTimeout(()=>w(T=>T==="saved"?"idle":T),2e3)}).catch(()=>{w("error"),setTimeout(()=>w(T=>T==="error"?"idle":T),3e3)})},[t]),W=o.useCallback((g,T)=>{L.current={capabilityRouting:g!==void 0?{assignments:g}:L.current?.capabilityRouting,routingDefaultModel:T!==void 0?T:L.current?.routingDefaultModel},B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{const f=L.current;L.current=null,f&&H(f)},Si)},[H]),O=o.useMemo(()=>r.flatMap(g=>(g.models??[{id:g.model,name:g.model}]).map(T=>({provider:g.name,providerLabel:g.displayName??g.name,modelId:T.id,modelName:T.name}))),[r]),_=b??O,X=o.useMemo(()=>Object.entries(a).map(([g,T])=>`${g}:${T?.provider??""}/${T?.model??""}`).sort().join("|"),[a]);o.useEffect(()=>{!d||!b||b.length===0||b.some(g=>!!g.modelId)&&(n(g=>{let T=!1;const f={...g};for(const K of xn)for(const z of K.capabilities){const se=f[z];if(!se?.model)continue;const ae=ca(b,z);if(ae.length===0)continue;ae.some(te=>te.provider===se.provider&&te.modelId===se.model)||(delete f[z],T=!0)}return T?(W(f),f):g}),c(g=>{if(!g?.model||b.some(z=>z.provider===g.provider&&z.modelId===g.model))return g;const f=b.find(z=>z.provider==="markus"),K=f?{provider:f.provider,model:f.modelId}:{provider:b[0].provider,model:b[0].modelId};return t({routingDefaultModel:K}),K}))},[d,b,U,W,X]);const ce=o.useCallback(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(g=>{if(!g.ok)throw new Error(`HTTP ${g.status}`);return g.json()}).then(g=>{n(g.capabilityRouting?.assignments??{}),c(g.routingDefaultModel??null)}).catch(()=>{}),y(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(g=>{if(!g.ok)throw new Error(`HTTP ${g.status}`);return g.json()}).then(g=>{const T=[];for(const f of g.providers)for(const K of f.models)T.push({provider:f.provider,providerLabel:f.displayName,modelId:K.id,modelName:K.name,mode:K.mode,tier:K.tier,costTier:K.costTier,capabilities:K.capabilities});S(T)}).catch(()=>{}).finally(()=>y(!1))},[]),oe=o.useCallback(async()=>{if($!=="working"){I("working"),V(null);try{const g=await fetch("/api/settings/llm/restore-recommended",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}}),T=await g.json().catch(()=>({}));if(!g.ok||!T.ok)throw new Error(T.error??`HTTP ${g.status}`);T.capabilityRouting&&n(T.capabilityRouting.assignments??{}),T.routingDefaultModel!==void 0&&c(T.routingDefaultModel),ce(),I("idle"),w("saved"),setTimeout(()=>w(f=>f==="saved"?"idle":f),2e3)}catch(g){I("error"),V(g instanceof Error?g.message:String(g)),setTimeout(()=>I("idle"),4e3)}}},[$,ce]),ee=_.length>0;return d?p?e.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-xs text-red-400",children:i("modelRouting.loadError",{error:p})}):k&&!ee?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-secondary",children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin text-brand-500",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),e.jsx("span",{children:i("modelRouting.loadingModels")})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Ti,{status:j,t:i}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("button",{type:"button",onClick:()=>M(!0),disabled:$==="working",className:"text-xs px-3 py-1.5 rounded-lg border border-border-default text-fg-secondary hover:text-fg-primary hover:border-brand-500/40 disabled:opacity-50 transition-colors",children:i($==="working"?"modelRouting.restoreWorking":"modelRouting.restoreRecommended")}),R&&e.jsx("span",{className:"text-[10px] text-red-400 max-w-xs text-right",children:R})]})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:i("modelRouting.defaultModelTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:i("modelRouting.defaultModelDesc")})]}),e.jsx("div",{className:"max-w-md",children:e.jsx(Vt,{value:s?`${s.provider}/${s.model}`:"",options:_,placeholder:i("modelRouting.defaultModelPlaceholder"),onChange:g=>{if(!g)c(null),W(void 0,null);else{const[T,...f]=g.split("/"),K={provider:T,model:f.join("/")};if(c(K),a.text){const z={...a};delete z.text,n(z),W(z,K)}else W(void 0,K)}}})})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary",children:i("modelRouting.capabilityAssignTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:i("modelRouting.capabilityAssignDesc")})]}),r.length===0&&e.jsx("div",{className:"p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg text-xs text-yellow-400",children:i("modelRouting.noProvidersHint")}),r.length>0&&e.jsx("div",{className:"space-y-4",children:xn.map(g=>e.jsx(Pi,{groupKey:g.groupKey,capabilities:g.capabilities,assignments:a,suggestions:h,allModels:_,configuredProviderNames:new Set(r.map(T=>T.name)),t:i,onAssign:(T,f)=>{const K={...a};f?K[T]=f:delete K[T],n(K),W(K)}},g.groupKey))})]}),C&&e.jsx(fs,{variant:"primary",title:i("modelRouting.restoreRecommended"),message:i("modelRouting.restoreConfirm"),confirmLabel:i("common:confirm"),onConfirm:()=>{M(!1),oe()},onCancel:()=>M(!1)})]}):e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 animate-pulse",children:[e.jsx("div",{className:"h-4 bg-surface-overlay rounded w-1/3 mb-3"}),e.jsx("div",{className:"h-3 bg-surface-overlay rounded w-2/3 mb-4"}),e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(g=>e.jsx("div",{className:"h-10 bg-surface-overlay rounded-lg"},g))})]})})}function Pi({groupKey:t,capabilities:r,assignments:i,suggestions:a,allModels:n,configuredProviderNames:s,t:c,onAssign:d}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-2 px-1",children:c(`modelRouting.capabilityGroups.${t}`)}),e.jsx("div",{className:"space-y-1",children:r.map(u=>{const p=i[u],x=a[u],k=p?`${p.provider}/${p.model}`:"",y=ca(n,u),j=x?y.find(P=>P.provider===x.provider&&P.modelId===x.model)?.modelName??x.model:void 0,w=y.length>0,b=p?Mi(n,p.provider,p.model):void 0,S=p&&!s.has(p.provider),h=!!(p&&w&&u!=="text"&&!y.some(P=>P.provider===p.provider&&P.modelId===p.model));return e.jsxs("div",{className:`flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg md:flex-nowrap md:gap-3 ${h?"bg-red-500/10 border border-red-500/30":S?"bg-yellow-500/10 border border-yellow-500/30":!w&&!p?"bg-amber-500/5 border border-amber-500/20":"bg-surface-overlay/40"}`,children:[e.jsx("div",{className:"w-full shrink-0 md:w-28",children:e.jsx("span",{className:"text-xs text-fg-primary",children:c(`modelRouting.capabilities.${u}`)})}),e.jsx("div",{className:"flex-1 min-w-0",children:h?e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"text-xs text-red-400",children:["⚠ ",p.model]}),e.jsx("span",{className:"text-[10px] text-red-400/70",children:c("modelRouting.mismatchHint")})]}),e.jsx(Vt,{value:"",options:y,placeholder:c("modelRouting.selectModel"),onChange:P=>{if(!P)d(u,null);else{const[m,...v]=P.split("/");d(u,{provider:m,model:v.join("/")})}}})]}):w?e.jsx(Vt,{value:k,options:y,placeholder:j?`${j} (${c("modelRouting.suggested")})`:c("modelRouting.selectModel"),onChange:P=>{if(!P)d(u,null);else{const[m,...v]=P.split("/");d(u,{provider:m,model:v.join("/")})}}}):e.jsxs("span",{className:"text-xs text-amber-400",children:[c("modelRouting.noModelAvailable"),e.jsxs("span",{className:"text-fg-tertiary ml-1",children:["— ",c("modelRouting.addProviderHint")]})]})}),e.jsxs("div",{className:"w-14 shrink-0 flex justify-end",children:[h&&e.jsx("span",{className:"text-[10px] text-red-400 font-medium",title:c("modelRouting.mismatchHint"),children:"⚠"}),!h&&S&&e.jsx("span",{className:"text-[10px] text-yellow-400 font-medium",title:c("modelRouting.staleProvider"),children:"⚠"}),!h&&!S&&b&&e.jsx(gn,{tier:b}),!h&&!S&&!b&&p&&e.jsx(gn,{tier:"unknown"})]}),e.jsx("div",{className:"w-8 shrink-0 flex justify-end",children:p&&e.jsx("button",{onClick:()=>d(u,null),className:"text-fg-tertiary hover:text-red-400 transition-colors",title:c("modelRouting.clear"),children:e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})})]},u)})})]})}function Mi(t,r,i){return t.find(n=>n.provider===r&&n.modelId===i)?.tier}function Ti({status:t,t:r}){if(t==="idle")return null;const i={idle:"",saving:"text-fg-tertiary",saved:"text-green-400",error:"text-red-400"},a={idle:"",saving:r("modelRouting.saving"),saved:r("modelRouting.saved"),error:r("modelRouting.saveError")};return e.jsx("div",{className:`text-xs font-medium transition-opacity ${i[t]}`,children:a[t]})}function gn({tier:t}){const r={max:"bg-purple-500/20 text-purple-400 border-purple-500/30",pro:"bg-blue-500/20 text-blue-400 border-blue-500/30",base:"bg-gray-500/20 text-gray-400 border-gray-500/30",unknown:"bg-gray-500/10 text-fg-tertiary border-border-default"};return e.jsx("span",{className:`px-1.5 py-0.5 text-[9px] rounded font-semibold uppercase border ${r[t]??r.unknown}`,children:t==="unknown"?"—":t})}function ca(t,r){if(r==="text")return t.filter(c=>ji(c));const i={image_generation:["image_generation"],audio_tts:["audio_speech"],audio_stt:["audio_transcription"],video_generation:["video_generation"]},a={image_recognition:["vision"],image_generation:["imageGeneration"],audio_tts:["tts"],audio_stt:["stt"],video_generation:["videoGeneration"]},n=i[r],s=a[r];return t.filter(c=>!!(c.capabilities&&c.capabilities.length>0&&s&&s.some(d=>c.capabilities.includes(d))||n&&c.mode&&n.includes(c.mode)))}function Ei({configuredProviders:t}){const{t:r}=xe("settings"),[i,a]=o.useState(null),[n,s]=o.useState([]),[c,d]=o.useState(null),[u,p]=o.useState(null),x=o.useMemo(()=>t.map(b=>`${b.name}:${b.models?.length??0}`).sort().join(","),[t]),k=o.useCallback(async()=>{d(null);try{const[{agents:b},S]=await Promise.all([F.agents.list({lean:!0}),F.teams.list()]),h=S.teams.map(m=>({id:m.id,name:m.name}));s(h);const P=await Promise.all(b.map(async m=>{try{const $=(await F.agents.get(m.id)).config?.llmConfig;return{id:m.id,name:m.name||m.id,teamId:m.teamId,override:$?.modelMode==="custom"&&$.primary&&$.defaultModel?`${$.primary}/${$.defaultModel}`:null,llmConfig:{modelMode:$?.modelMode,primary:$?.primary??"",defaultModel:$?.defaultModel}}}catch{return{id:m.id,name:m.name||m.id,teamId:m.teamId,override:null,llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}}}));a(b.length?P:null)}catch(b){d(String(b))}},[x]);o.useEffect(()=>{k()},[k,x]);const y=o.useMemo(()=>{const b=[];for(const S of t)for(const h of S.models??[])b.push({provider:S.name,providerLabel:S.displayName??S.name,modelId:h.id,modelName:h.name??h.id});return b},[t]),j=async(b,S)=>{p(b),d(null);try{if(S){const[h,P]=[S.slice(0,S.lastIndexOf("/")),S.slice(S.lastIndexOf("/")+1)];await F.agents.updateConfig(b,{llmConfig:{modelMode:"custom",primary:h,defaultModel:P}})}else await F.agents.updateConfig(b,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}});a(h=>h?.map(P=>P.id===b?{...P,override:S}:P)??h)}catch(h){d(String(h))}finally{p(null)}},w=o.useMemo(()=>{if(!i)return[];const b=new Map,S=[];for(const P of i)if(P.teamId){const m=b.get(P.teamId)??[];m.push(P),b.set(P.teamId,m)}else S.push(P);const h=[];S.length&&h.push({key:"ungrouped",label:r("perAgentModel.ungrouped",{defaultValue:"Ungrouped"}),rows:S});for(const P of n){const m=b.get(P.id);m?.length&&h.push({key:`team:${P.id}`,label:P.name,rows:m})}for(const[P,m]of b)n.some(v=>v.id===P)||h.push({key:`team:${P}`,label:P,rows:m});return h},[i,n,r]);return i===null&&!c?e.jsx("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 text-sm text-fg-tertiary",children:r("common:loading",{defaultValue:"Loading…"})}):e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:r("perAgentModel.title",{defaultValue:"Per-agent default model"})}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:r("perAgentModel.desc",{defaultValue:'Bind a specific provider+model to an agent, or leave it following the global default. This is what the composer "Apply to current agent" writes.'})})]})}),c&&e.jsx("div",{className:"text-xs text-red-500",children:c}),(!i||i.length===0)&&!c&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:r("perAgentModel.noAgents",{defaultValue:"No agents available."})}),i&&i.length>0&&e.jsx("div",{className:"space-y-5",children:w.map(b=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-fg-tertiary truncate",children:b.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary/70 tabular-nums shrink-0",children:b.rows.length})]}),e.jsx("div",{className:"space-y-2",children:b.rows.map(S=>e.jsxs("div",{className:"flex flex-col gap-2 text-sm md:flex-row md:items-center md:justify-between md:gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1 truncate",children:[e.jsx("span",{className:"font-medium",children:S.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-2 truncate",children:S.id})]}),e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 md:w-[320px]",children:[S.override?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{value:S.override,options:y,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:h=>{j(S.id,h||null)}}),e.jsx("button",{type:"button",disabled:u===S.id,onClick:()=>{j(S.id,null)},className:"shrink-0 px-2.5 py-1.5 text-xs border border-border-default rounded-lg hover:bg-surface-base disabled:opacity-40 transition-colors",children:r("perAgentModel.reset",{defaultValue:"Reset"})})]}):e.jsx(Vt,{value:"",options:y,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:h=>{j(S.id,h||null)}}),u===S.id&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary",children:r("common:loading",{defaultValue:"…"})})]})]},S.id))})]},b.key))})]})}let xs=[],ls=null;async function Li(){return ls||(ls=(async()=>{try{xs=(await F.modelCatalog.providerCatalog()).providers??[]}catch{xs=[]}return xs})(),ls)}function Ri(){const[t,r]=o.useState(xs);return o.useEffect(()=>{let i=!0;return Li().then(a=>{i&&r(a)}),()=>{i=!1}},[]),t}const Ii="integrations.platforms",kr=(t,r)=>`settings:${Ii}.${t}.${r}`,Bi={feishu:"https://open.feishu.cn/app",telegram:"https://t.me/BotFather",slack:"https://api.slack.com/apps",whatsapp:"https://developers.facebook.com/apps",discord:"https://discord.com/developers/applications"};function Di(t){return Bi[t]}function Oi(t,r){return t(kr(r.id,"label"),{defaultValue:r.label})}function ua(t,r,i){const a=kr(r,`fields.${i.key}`);return{label:t(`${a}.label`,{defaultValue:i.label}),help:i.help?t(`${a}.help`,{defaultValue:i.help}):void 0,placeholder:i.placeholder?t(`${a}.placeholder`,{defaultValue:i.placeholder}):void 0,options:i.options?.map(n=>({value:n.value,label:t(`${a}.options.${n.value}`,{defaultValue:n.label})}))}}function $i(t,r,i){const a=[],n=kr(i,"guide");for(let s=1;s<=20;s+=1){const c=`${n}.step${s}.title`;if(!t.exists(c))break;const d=`${n}.step${s}.desc`,u=t.exists(d)?r(d):void 0;a.push({title:r(c),...u?{desc:u}:{}})}return a}function Vi(t){return t("settings:integrations.guide.heading",{defaultValue:"Setup guide"})}function _i(t){return t.type==="boolean"?t.default===!0:t.multiple?Array.isArray(t.default)?[...t.default]:[]:t.default!==void 0?t.default:""}function ps(t,r){return r==null?!0:t.type==="boolean"?!1:t.multiple?!Array.isArray(r)||r.length===0:typeof r=="string"?r.trim()==="":!1}function fn(t){const r={};for(const i of t.fields){if(i.secret){r[i.key]="";continue}const a=t.values[i.key];r[i.key]=a??_i(i)}return r}function pn(t,r,i={}){const a=[];for(const n of t)if(n.required){if(n.secret){if(!ps(n,r[n.key]))continue;i[n.key]?.hasValue||a.push(n.key);continue}ps(n,r[n.key])&&a.push(n.key)}return a}function Fi(t,r,i){const a={enabled:i};for(const n of t.fields){const s=r[n.key];if(n.secret){if(ps(n,s))continue;a[n.key]=s;continue}s!==void 0&&(a[n.key]=s)}return a}function Ui(t){return t.filter(r=>r.required||r.type==="agent")}function Ki(t){return t.filter(r=>!(r.required||r.type==="agent"))}function yr(t){return Array.isArray(t)?`[${t.map(yr).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,i])=>i!==void 0).sort(([i],[a])=>i<a?-1:i>a?1:0).map(([i,a])=>`${JSON.stringify(i)}:${yr(a)}`).join(",")}}`:JSON.stringify(t)??"null"}function Hi(t){return yr({id:t.id,enabled:t.enabled,fields:t.fields.map(r=>({key:r.key,type:r.type,required:r.required,secret:r.secret===!0,multiple:r.multiple===!0,default:r.default??null,value:r.secret?!1:t.values[r.key]??null,hasValue:r.secret?t.secrets[r.key]?.hasValue===!0:!1}))})}function zi(t){const r=t.ok===!0||t.success===!0;return{ok:r,text:t.message??t.error??(r?"OK":"Failed"),code:t.code}}function qi(t){return t?.status==="awaiting_reply"||t?.status==="awaiting_inbound"}function Wi(t,r=!1){return t.hasConfig?t.enabled?t.lastVerifiedAt||r?"verified":"unverified":"off":"unconfigured"}function Gi(t){return{id:"",platform:t.id,label:"",enabled:!0,connected:!1,hasConfig:!1,capabilities:t.capabilities,fields:t.fields,values:{},secrets:Ji(t.fields),agentId:null,notifyAgentId:null,channels:[],lastError:null,canListChannels:!1,lastVerifiedAt:null}}function Ji(t){const r={};for(const i of t)i.secret&&(r[i.key]={hasValue:!1});return r}function Yi(t){return t.id===""}function hn(t){return{id:t.platform,label:t.label,capabilities:t.capabilities,fields:t.fields,defaultEnabled:!1,enabled:t.enabled,connected:t.connected,hasConfig:t.hasConfig,values:{...t.values,agentId:t.agentId??""},secrets:t.secrets}}function Hs(t,r){return t.find(i=>i.nativeId===r)}function bn(t,r,i,a){const n=t.filter(s=>s.nativeId!==r);return n.push({nativeId:r,kind:a??null,agentId:i}),n.sort((s,c)=>s.nativeId.localeCompare(c.nativeId))}function yn(t,r){return t.filter(i=>i.nativeId!==r)}function Qi(t,r){const i=new Set(r.map(a=>a.id));return t.filter(a=>!i.has(a.nativeId))}function Zi(t,r){const i=r.trim().toLowerCase();return i?t.filter(a=>a.name.toLowerCase().includes(i)||a.id.toLowerCase().includes(i)):t}function Xi(t){const r=new Map;for(const i of t){const a=r.get(i.platform);a?a.push(i):r.set(i.platform,[i])}return[...r.entries()].map(([i,a])=>({platform:i,instances:a}))}function eo(t,r,i={}){const a=i.devMode??!1,n=new Set(t.filter(d=>d.devOnly&&!a).map(d=>d.id)),s=[],c=new Set;for(const d of t)n.has(d.id)||c.has(d.id)||(c.add(d.id),s.push(d.id));for(const d of r)n.has(d.platform)||c.has(d.platform)||(c.add(d.platform),s.push(d.platform));return s}function to(t,r,i){const[a,n]=o.useState([]),[s,c]=o.useState(null),[d,u]=o.useState(!1),p=o.useRef(t);p.current=t;const x=o.useRef(0),k=o.useCallback(()=>{if(!i||!r)return;const y=++x.current;u(!0),p.current(r).then(j=>{y===x.current&&(n(j.channels??[]),c(j.error??null))}).catch(j=>{y===x.current&&(n([]),c(j instanceof Error?j.message:String(j)))}).finally(()=>{y===x.current&&u(!1)})},[i,r]);return o.useEffect(()=>(k(),()=>{x.current+=1}),[k]),{channels:a,error:s,loading:d,reloadChannels:k}}const ma=/^notify[A-Z]/,xa="notifyEnabled";function so(t){return t.find(r=>r.key===xa)}function ro(t){return t.notifyTarget==="chat"||t.notifyTarget==="user"||ma.test(t.key)}function _t(t){return t.filter(r=>r.notifyTarget==="chat"||r.notifyTarget==="user")}function no(t){return t.filter(r=>!r.notifyTarget&&!r.secret&&r.key!==xa&&ma.test(r.key))}function ao(t){return t.filter(ro)}function ga(t){return _t(t).find(r=>r.notifyTarget==="chat")}function io(t,r){const i=_t(t);return i.length===0?"unsupported":i.some(a=>!ps(a,r[a.key]))?"configured":"not-configured"}function vn(t){return typeof t=="string"?{value:t,label:t}:{value:t.value,label:t.label??t.value,hint:t.hint}}function jn(t,r,i){const a=t.label.toLowerCase(),n=t.value.toLowerCase(),s=`${a} ${n} ${(t.hint??"").toLowerCase()}`;for(const d of r)if(!s.includes(d))return null;if(a.startsWith(i)||n.startsWith(i))return 0;const c=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[\\s./:_-])${c}`).test(a)?1:2}function fa({value:t,options:r,onChange:i,placeholder:a,filterPlaceholder:n,emptyText:s,customHint:c,disabled:d,ariaLabel:u,className:p}){const[x,k]=o.useState(!1),[y,j]=o.useState(""),[w,b]=o.useState(!1),[S,h]=o.useState(-1),P=o.useRef(null),m=o.useRef(null),v=o.useRef(null),$=o.useRef(null),I=o.useId(),[R,V]=o.useState({}),C=o.useMemo(()=>t?r.map(vn).find(O=>O.value===t)?.label??t:a??"",[t,r,a]);o.useEffect(()=>{x||(j(C),b(!1))},[C,x]),o.useEffect(()=>{function O(_){const X=_.target;$.current?.contains(X)||P.current&&!P.current.contains(X)&&k(!1)}return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);function M(){const O=m.current;if(!O)return;const _=O.getBoundingClientRect(),X=Math.max(_.width,240),ce=window.innerHeight-_.bottom-8,oe=ce<180&&_.top>ce;V({position:"fixed",left:_.left,width:X,maxHeight:Math.min(260,oe?Math.max(_.top-12,120):ce),...oe?{bottom:window.innerHeight-_.top+4}:{top:_.bottom+4}})}o.useLayoutEffect(()=>{if(!x)return;M();const O=()=>M();return window.addEventListener("scroll",O,!0),window.addEventListener("resize",O),()=>{window.removeEventListener("scroll",O,!0),window.removeEventListener("resize",O)}},[x]);const B=o.useMemo(()=>{const O=r.map(vn),_=y.trim(),X=w?_.toLowerCase().split(/\s+/).filter(Boolean):[],ce=[];O.forEach((g,T)=>{const f=X.length?jn(g,X,_.toLowerCase()):0;f!==null&&ce.push({row:g,score:f,idx:T})}),ce.sort((g,T)=>g.score-T.score||g.idx-T.idx);const oe=[];if(a!==void 0){const g={value:"",label:a};(X.length?jn(g,X,_.toLowerCase()):0)!==null&&oe.push(g)}oe.push(...ce.map(g=>g.row));const ee=_&&!O.some(g=>g.value.toLowerCase()===_.toLowerCase());return c&&w&&ee&&oe.push({value:_,label:_,custom:!0}),oe},[r,y,w,a,c]);o.useEffect(()=>{if(!x||S<0||!v.current)return;v.current.querySelector(`[data-index="${S}"]`)?.scrollIntoView({block:"nearest"})},[S,x,B.length]);function L(){d||(j(C),b(!1),h(B.findIndex(O=>O.value===t)),k(!0),requestAnimationFrame(()=>m.current?.select()))}function U(){k(!1),j(C),b(!1),h(-1)}function H(O){i(O.value),k(!1),j(O.value?O.label:a??""),b(!1),h(-1),m.current?.focus()}function W(O){if(O.key==="ArrowDown"||O.key==="ArrowUp"){if(O.preventDefault(),!x){L();return}h(_=>{const X=O.key==="ArrowDown"?_+1:_-1;return Math.max(-1,Math.min(X,B.length-1))});return}if(O.key==="Enter"){if(!x){O.preventDefault(),L();return}const _=B[S];_?(O.preventDefault(),H(_)):U();return}if(O.key==="Escape"&&x){O.preventDefault(),O.stopPropagation(),U();return}O.key==="Tab"&&x&&U()}return e.jsxs("div",{ref:P,className:`relative ${p??""}`,children:[e.jsx("input",{ref:m,type:"text",role:"combobox","aria-expanded":x,"aria-controls":x?I:void 0,"aria-autocomplete":"list","aria-label":u,"aria-activedescendant":x&&S>=0?`${I}-opt-${S}`:void 0,disabled:d,value:x?y:C,placeholder:n,onMouseDown:()=>{x?k(!1):L()},onChange:O=>{x||k(!0),j(O.target.value),b(!0),h(0)},onKeyDown:W,onBlur:()=>{x&&U()},className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none truncate"}),x&&ti.createPortal(e.jsxs("div",{id:I,role:"listbox",ref:O=>{v.current=O,$.current=O},style:R,onMouseDown:O=>O.preventDefault(),"data-keep-edit-focus":!0,className:"z-50 overflow-y-auto bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1",children:[B.map((O,_)=>e.jsxs("div",{id:`${I}-opt-${_}`,"data-index":_,role:"option","aria-selected":O.value===t,onMouseDown:X=>{X.preventDefault(),H(O)},className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${_===S?"bg-brand-500/20":O.value===t?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,children:[e.jsx("span",{className:`flex-1 truncate ${O.custom?"text-brand-500":"text-fg-primary"}`,children:O.label}),O.hint&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:O.hint}),O.custom&&c&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:typeof c=="function"?c(O.value):c})]},`${O.custom?"custom:":""}${O.value}`)),B.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:s})]}),document.body)]})}async function oo(){const{agents:t}=await F.agents.list({lean:!0});return t.map(r=>({id:r.id,name:r.name,role:r.role}))}let ds=null;function pa(){return ds||(ds=oo().catch(t=>{throw ds=null,t})),ds}function lo(t=pa,r=!0){const[i,a]=o.useState([]);return o.useEffect(()=>{if(!r)return;let n=!0;return t().then(s=>{n&&a(s)}).catch(()=>{n&&a([])}),()=>{n=!1}},[t,r]),i}function hs({value:t,options:r,onChange:i,fieldKey:a,ariaLabel:n,disabled:s}){const{t:c}=xe(["settings"]);return e.jsx(fa,{value:typeof t=="string"?t:"",options:r.map(d=>({value:d.id,label:d.name,hint:d.role})),onChange:d=>i(a,d),disabled:s,placeholder:c("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),filterPlaceholder:c("settings:integrations.agentSelect.search",{defaultValue:"Search agents…"}),emptyText:c("settings:integrations.agentSelect.empty",{defaultValue:"No matching agent"}),ariaLabel:n??c("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),className:"w-full"})}function ha({loading:t,error:r,onReload:i,buttonTestId:a,errorTestId:n,empty:s=!1}){const{t:c}=xe(["settings","common"]);return e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-h-[1.25rem]",children:[e.jsxs("button",{type:"button",onClick:i,disabled:t,"aria-busy":t,"data-testid":a,className:"inline-flex items-center gap-1 text-[11px] font-medium text-fg-tertiary hover:text-fg-secondary disabled:opacity-60 transition-colors",children:[e.jsx("svg",{className:`w-3.5 h-3.5 ${t?"animate-spin":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),t?c("settings:instances.channels.refreshing",{defaultValue:"Refreshing…"}):s?c("settings:integrations.loadGroups",{defaultValue:"Load groups"}):c("settings:instances.channels.refresh",{defaultValue:"Refresh"})]}),r&&e.jsx("span",{"data-testid":n,className:"text-[11px] text-red-600",children:r})]})}const gs="rounded-xl border border-border-default bg-surface-secondary p-4",Dt="text-sm font-semibold text-fg-primary",ba="flex flex-wrap items-center justify-between gap-x-4 gap-y-2",co="flex flex-wrap items-start justify-between gap-x-4 gap-y-2",vr="shrink-0 text-sm text-fg-secondary",ya="flex-1 min-w-[10rem] flex justify-end",bt="text-xs text-fg-tertiary",jr="w-full px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500 transition-colors";function Nr(t){return"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs rounded-lg border transition-colors "+(t?"bg-selected-bg border-selected-border text-selected-fg":"bg-surface-primary border-border-default text-fg-secondary hover:border-fg-tertiary")}const uo={verified:"bg-green-500/10 text-green-600 border-green-500/30",unverified:"bg-amber-500/10 text-amber-600 border-amber-500/30",off:"bg-gray-500/10 text-fg-tertiary border-border-default",unconfigured:"bg-gray-500/10 text-fg-tertiary border-border-default"},mo={verified:"bg-green-500",unverified:"bg-amber-400",off:"bg-gray-400",unconfigured:"bg-gray-400"},xo={verified:"settings:integrations.status.verified",unverified:"settings:integrations.status.unverified",off:"settings:integrations.status.off",unconfigured:"settings:integrations.status.unconfigured"},go={verified:"Connected",unverified:"Not verified",off:"Off",unconfigured:"Not configured"};function fo({state:t}){const{t:r}=xe(["settings"]);return e.jsxs("span",{"data-testid":"integration-status","data-state":t,"data-connected":t==="verified"?"true":"false",className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${uo[t]}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${mo[t]}`}),r(xo[t],{defaultValue:go[t]})]})}function $t({type:t,text:r}){return e.jsx("div",{"data-testid":t==="ok"?"integration-msg-ok":"integration-msg-err",className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs ${t==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-600 border border-red-500/30"}`,children:r})}function Lt({label:t,control:r,help:i,htmlFor:a,start:n=!1}){return e.jsxs("div",{children:[e.jsxs("div",{className:n?co:ba,children:[a?e.jsx("label",{htmlFor:a,className:vr,children:t}):e.jsx("span",{className:vr,children:t}),e.jsx("div",{className:ya,children:r})]}),i?e.jsx("p",{className:`${bt} mt-1.5`,children:i}):null]})}function po({field:t,value:r,hasStored:i,onChange:a,platformId:n="",agentOptions:s=[]}){const{t:c}=xe(["settings"]),d=`integration-field-${t.key}`,[u,p]=o.useState(!1),x=o.useMemo(()=>n?ua(c,n,t):{label:t.label,help:t.help,placeholder:t.placeholder,options:t.options},[c,n,t]),k=x.label,y=x.help,j=x.placeholder,w=x.options??t.options??[],b=e.jsxs(e.Fragment,{children:[k,t.required&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),S=t.secret&&i?c("settings:integrations.secretStored"):y||void 0;if(t.type==="boolean"){const m=r===!0;return e.jsx(Lt,{label:k,help:y,control:e.jsx(bs,{checked:m,onChange:v=>a(t.key,v),label:k,size:"md",testId:`integration-field-${t.key}`})})}if(t.type==="agent")return e.jsx(Lt,{label:b,help:S,control:e.jsx("div",{className:"w-full","data-testid":`integration-field-${t.key}`,children:e.jsx(hs,{value:r,options:s,onChange:a,fieldKey:t.key,ariaLabel:k})})});if(t.type==="select"&&t.multiple){const m=Array.isArray(r)?r.map(String):[];return e.jsx(Lt,{start:!0,label:b,help:S,control:e.jsx("div",{className:"flex flex-wrap justify-end gap-1.5","data-testid":`integration-field-${t.key}`,children:w.map(v=>{const $=m.includes(v.value);return e.jsx("button",{type:"button","aria-pressed":$,"data-option":v.value,onClick:()=>a(t.key,$?m.filter(I=>I!==v.value):[...m,v.value]),className:Nr($),children:v.label},v.value)})})})}if(t.type==="select")return e.jsx(Lt,{label:b,help:S,htmlFor:d,control:e.jsx("select",{id:d,"data-testid":`integration-field-${t.key}`,value:typeof r=="string"?r:"",onChange:m=>a(t.key,m.target.value),className:jr,children:(t.options??[]).map(m=>{const v=w.find($=>$.value===m.value)?.label??m.label;return e.jsx("option",{value:m.value,children:v},m.value)})})});const h=t.type==="password",P=t.type==="number";return e.jsx(Lt,{label:b,help:S,htmlFor:d,control:e.jsxs("div",{className:"relative w-full",children:[e.jsx("input",{id:d,"data-testid":`integration-field-${t.key}`,type:P?"number":h&&!u?"password":"text",value:r==null?"":String(r),placeholder:h&&i?c("settings:integrations.secretStoredPlaceholder"):j,onChange:m=>a(t.key,m.target.value),className:`${jr}${h?" font-mono pr-10":""}`}),h&&e.jsx("button",{type:"button","aria-label":u?c("settings:integrations.hide",{defaultValue:"Hide"}):c("settings:integrations.show",{defaultValue:"Show"}),onClick:()=>p(m=>!m),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-fg-tertiary hover:text-fg-secondary transition-colors",children:u?"🙈":"👁"})]})})}function yt({status:t,draft:r,fields:i=t.fields,onChange:a,agentOptions:n=[]}){return e.jsx(e.Fragment,{children:i.map(s=>e.jsx(po,{field:s,platformId:t.id,value:r[s.key],hasStored:t.secrets[s.key]?.hasValue===!0,agentOptions:n,onChange:a},s.key))})}const Nn={pending:"bg-amber-400 animate-pulse",ok:"bg-emerald-500",failed:"bg-red-500"};function wn({label:t,hint:r,leg:i}){const{t:a}=xe("settings");return e.jsxs("div",{className:"flex items-start gap-2.5","data-testid":"connection-test-leg",children:[e.jsx("span",{className:`mt-1.5 w-2 h-2 rounded-full shrink-0 ${Nn[i.state]??Nn.pending}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm text-fg-primary",children:t}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 break-words",children:i.state==="ok"?i.detail??a("integrations.connectionTest.legOk",{defaultValue:"Verified"}):i.state==="failed"?i.detail??a("integrations.connectionTest.legFailed",{defaultValue:"Failed"}):r})]})]})}function ho(t,r){const i=new Date(t);return Number.isNaN(i.getTime())?t:i.toLocaleString(r,{dateStyle:"medium",timeStyle:"short"})}function bo({test:t,starting:r,onStart:i,lastVerifiedAt:a=null}){const{t:n,i18n:s}=xe("settings"),c=(()=>{if(!t)return null;switch(t.status){case"awaiting_reply":return n("integrations.connectionTest.awaitingReply",{defaultValue:"A test message was sent to {{target}}. Reply to it in {{platform}} to finish — include {{code}} if you can.",target:t.targetChannelName??t.targetChannelId??"",platform:t.platform,code:t.code??""});case"awaiting_inbound":return n("integrations.connectionTest.awaitingInbound",{defaultValue:"Send any message to this bot in {{platform}} — we will answer it to confirm both directions.",platform:t.platform});case"verified":return n("integrations.connectionTest.verified",{defaultValue:"Both directions work — Markus can send to and receive from this bot."});case"expired":return n("integrations.connectionTest.expired",{defaultValue:"No reply arrived in time. Check the bot is in the conversation, then try again."});default:return null}})();return e.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:n("integrations.connectionTest.title",{defaultValue:"Connection verification"})}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:n("integrations.connectionTest.subtitle",{defaultValue:"Sends a real message and waits for your reply — proves both directions."})})]}),t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(wn,{label:n("integrations.connectionTest.outbound",{defaultValue:"Outbound (bot → IM)"}),hint:n("integrations.connectionTest.outboundPending",{defaultValue:"Not sent yet"}),leg:t.outbound}),e.jsx(wn,{label:n("integrations.connectionTest.inbound",{defaultValue:"Inbound (IM → bot)"}),hint:n("integrations.connectionTest.inboundPending",{defaultValue:"Waiting for your reply"}),leg:t.inbound})]}),c&&(t.status==="verified"||t.status==="expired"?e.jsx($t,{type:t.status==="verified"?"ok":"err",text:c}):e.jsx("div",{className:"px-3 py-2 rounded-lg text-xs bg-surface-tertiary text-fg-secondary",children:c}))]}):a?e.jsx($t,{type:"ok",text:n("integrations.connectionTest.lastVerified",{defaultValue:"Verified {{when}}.",when:ho(a,s.language)})}):e.jsx("div",{className:"text-xs text-fg-tertiary",children:n("integrations.connectionTest.idle",{defaultValue:"Not verified yet. Verify to send a real message to the bot and confirm the round trip."})}),e.jsxs("button",{type:"button",onClick:i,disabled:r,"data-testid":"connection-test-start",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-fg-primary border border-border-default rounded-lg hover:bg-surface-tertiary disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[r?e.jsx("div",{className:"w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin"}):null,t?n("integrations.connectionTest.retry",{defaultValue:"Verify again"}):n("integrations.connectionTest.start",{defaultValue:"Verify connection"})," "]})]})}function yo({status:t,values:r,setValue:i,channels:a=[],canListChannels:n=!1,channelsLoading:s=!1,channelsError:c=null,onReloadChannels:d=()=>{},channelsGuidance:u=null,testSlot:p}){const{t:x}=xe(["settings","common"]),[k,y]=o.useState(!1),j=_t(t.fields),w=no(t.fields),b=so(t.fields),S=io(t.fields,r),h=ga(t.fields),P=b?r[b.key]!==!1:!0,m=n&&h?h.key:null,v=m!==null?String(r[m]??""):"",$={configured:x("settings:instances.notify.reachConfigured",{defaultValue:"Configured"}),"not-configured":x("settings:instances.notify.reachNotConfigured",{defaultValue:"Not set"}),unsupported:x("settings:instances.notify.reachUnsupported",{defaultValue:"Not supported"})},I={configured:"text-green-600","not-configured":"text-amber-600",unsupported:"text-fg-tertiary"},R={configured:"bg-green-500","not-configured":"bg-amber-400",unsupported:"bg-gray-400"},V=x("settings:instances.notify.guidanceFallback",{defaultValue:"This platform can’t list its conversations — enter the destination ID manually."}),C=u?x(u,{defaultValue:V}):V,M=m!==null&&!s&&v!==""&&!a.some(L=>L.id===v),B="text-xs font-medium text-fg-secondary mb-2";return e.jsxs("section",{"data-testid":"notification-panel","data-reachability":S,className:gs,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsx("h3",{className:Dt,children:x("settings:instances.notify.title",{defaultValue:"Notifications"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 text-xs ${I[S]}`,"data-testid":"notification-reachability","data-state":S,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${R[S]}`}),$[S]]}),b&&e.jsx(bs,{checked:P,onChange:L=>i(b.key,L),label:x("settings:instances.notify.masterLabel",{defaultValue:"Enable notifications"}),size:"md",testId:`integration-field-${b.key}`})]})]}),e.jsxs("div",{className:`space-y-4${P?"":" opacity-60"}`,children:[j.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:B,children:x("settings:instances.notify.destination",{defaultValue:"Destination"})}),m!==null&&e.jsxs("div",{"data-testid":"notification-chat-list",className:"space-y-1.5",children:[e.jsx(ha,{loading:s,error:c,onReload:d,empty:a.length===0,buttonTestId:"notification-chat-refresh",errorTestId:"notification-chat-error"}),a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(L=>e.jsx("button",{type:"button","aria-pressed":v===L.id,"data-testid":`notification-chat-pick-${L.id}`,onClick:()=>i(m,L.id),className:Nr(v===L.id),children:L.name},L.id))}),a.length===0&&!s&&!c&&e.jsx("p",{"data-testid":"notification-chat-empty",className:bt,children:x("settings:instances.notify.pickEmpty",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}),M&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:e.jsx("button",{type:"button","aria-pressed":"true","data-testid":"notification-chat-pick-current",onClick:()=>i(m,v),className:Nr(!0),children:v})})]}),m===null&&e.jsx("p",{"data-testid":"notification-chat-guidance",className:bt,children:C}),m!==null?e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button","aria-expanded":k,"data-testid":"notification-manual-toggle",onClick:()=>y(L=>!L),className:"inline-flex items-center gap-1 text-xs font-medium text-fg-tertiary hover:text-fg-secondary transition-colors",children:[e.jsx("svg",{className:`w-3 h-3 transition-transform ${k?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),x("settings:instances.notify.manualInput",{defaultValue:"Enter an ID manually"})]}),k&&e.jsx("div",{className:"space-y-4 mt-3","data-testid":"notification-manual-fields",children:e.jsx(yt,{status:t,draft:r,fields:j,onChange:i})})]}):e.jsx("div",{className:"mt-2",children:e.jsx(yt,{status:t,draft:r,fields:j,onChange:i})})]}),w.length>0&&e.jsxs("div",{"data-testid":"notification-preferences",className:"space-y-3",children:[e.jsx("div",{className:B,children:x("settings:instances.notify.content",{defaultValue:"What to send"})}),e.jsx(yt,{status:t,draft:r,fields:w,onChange:i})]}),p]})]})}const ht={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"},vo={color:"#64748b",glyph:e.jsx("g",{...ht,children:e.jsx("path",{d:"M21 12a8 8 0 0 1-11.6 7.1L4 21l1.9-5.4A8 8 0 1 1 21 12z"})})},jo={feishu:{color:"#3370ff",glyph:e.jsx("g",{...ht,children:e.jsx("path",{d:"M21 5 3 11l5.5 2.2L19 7l-7.5 8.3L12 21l3-4.5L21 5z"})})},telegram:{color:"#229ed9",glyph:e.jsx("g",{...ht,children:e.jsx("path",{d:"M22 3 2.5 10.5l5.5 2L21 6l-9 10v5l3.5-4.5L20 19 22 3z"})})},slack:{color:"#611f69",glyph:e.jsx("g",{...ht,children:e.jsx("path",{d:"M9.5 3 7.5 20M16.5 4 14.5 21M3.5 9h17M2.5 15h17"})})},whatsapp:{color:"#1faa59",glyph:e.jsxs("g",{...ht,children:[e.jsx("path",{d:"M21 11.5a8.5 8.5 0 0 1-12.6 7.4L3 20.5l1.6-5.3A8.5 8.5 0 1 1 21 11.5z"}),e.jsx("path",{d:"M9 8.8c.3 2.6 2.6 4.9 5.2 5.2l1-1.3 1.9.8"})]})},discord:{color:"#5865f2",glyph:e.jsxs("g",{...ht,children:[e.jsx("rect",{x:"3",y:"7",width:"18",height:"10",rx:"4.5"}),e.jsx("path",{d:"M7.5 11.5h3M9 10v3"}),e.jsx("circle",{cx:"15",cy:"10.7",r:"0.9"}),e.jsx("circle",{cx:"17.3",cy:"13",r:"0.9"})]})}};function No(t){return jo[t]??vo}function va({id:t,size:r=36}){const i=No(t);return e.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded-lg",style:{width:r,height:r,backgroundColor:`${i.color}1a`,color:i.color},"aria-hidden":"true","data-testid":`platform-icon-${t}`,children:e.jsx("svg",{width:Math.round(r*.58),height:Math.round(r*.58),viewBox:"0 0 24 24",children:i.glyph})})}function wo({status:t,configured:r,canListChannels:i=!1,channelsGuidance:a=null}){const{t:n,i18n:s}=xe(["settings","common"]),[c,d]=o.useState(!r),u=o.useMemo(()=>{const k=$i(s,n,t.id);if(_t(t.fields).length===0)return k;const y=n("settings:integrations.guide.destinationStep.desc",{defaultValue:"Pick the chat or user that should receive approvals and notifications — without it they have nowhere to go."}),j=i?{title:n("settings:integrations.guide.selectChatStep.title",{defaultValue:"Pick the notification group"}),desc:n("settings:integrations.guide.selectChatStep.desc",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}:{title:n("settings:integrations.guide.destinationStep.title",{defaultValue:"Set a notification destination"}),desc:a?n(a,{defaultValue:y}):y};return[...k,j]},[s,n,t.id,t.fields,i,a]),p=Di(t.id),x=n(`settings:integrations.platforms.${t.id}.description`,{defaultValue:""});return e.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl overflow-hidden","data-testid":"integration-guide","data-open":c?"true":"false",children:[e.jsxs("button",{type:"button",onClick:()=>d(k=>!k),"aria-expanded":c,"data-testid":"integration-guide-toggle",className:"w-full flex items-center gap-2.5 px-4 py-3 text-left hover:bg-white/[0.02] transition-colors",children:[e.jsx("span",{className:"text-base leading-none","aria-hidden":"true",children:"🧭"}),e.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary",children:Vi(n)}),e.jsx("svg",{className:`w-4 h-4 text-fg-tertiary transition-transform ${c?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),c&&e.jsxs("div",{className:"px-4 pb-4 pt-1 space-y-3 border-t border-border-default",children:[x&&e.jsx("p",{className:"text-xs text-fg-tertiary",children:x}),u.length>0?e.jsx("ol",{className:"space-y-2.5","data-testid":"integration-guide-steps",children:u.map((k,y)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"shrink-0 w-5 h-5 mt-0.5 rounded-full bg-brand-500/15 text-brand-600 text-[11px] font-semibold flex items-center justify-center",children:y+1}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-xs font-medium text-fg-primary",children:k.title}),k.desc&&e.jsx("span",{className:"block text-[11px] text-fg-tertiary mt-0.5",children:k.desc})]})]},k.title))}):e.jsx("p",{className:"text-xs text-fg-tertiary",children:n("settings:integrations.guide.fallback",{defaultValue:"Fill in the credentials from the platform’s developer console below."})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 pt-1",children:[p&&e.jsxs("a",{href:p,target:"_blank",rel:"noreferrer","data-testid":"integration-guide-console",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors",children:[n("settings:integrations.guide.openConsole",{defaultValue:"Open developer console"}),e.jsx("span",{"aria-hidden":"true",children:"↗"})]}),t.docsUrl&&e.jsx("a",{href:t.docsUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-brand-600 hover:text-brand-700",children:n("settings:integrations.docs",{defaultValue:"Setup docs"})})]})]})]})}const ja={create:(t,r)=>F.settings.createInstance(t,r).then(i=>i.instance),save:(t,r)=>F.settings.saveInstance(t,r).then(()=>{}),test:(t,r)=>F.settings.testInstance(t,r),remove:t=>F.settings.deleteInstance(t).then(()=>{}),listChannels:t=>F.settings.listInstanceChannels(t),saveChannels:(t,r)=>F.settings.saveInstanceChannels(t,r).then(()=>{}),startConnectionTest:(t,r)=>F.settings.startConnectionTest(t,r).then(i=>i.test),getConnectionTest:t=>F.settings.getConnectionTest(t).then(r=>r.test)},ko=700;function kn({instance:t,client:r=ja,extras:i={},onChanged:a,onCreated:n,loadAgents:s,defaultExpanded:c}){const{t:d}=xe(["settings","common"]),u=Yi(t),[p,x]=o.useState(c??u),[k,y]=o.useState(!1),j=o.useMemo(()=>hn(t),[t]),[w,b]=o.useState(t.label),[S,h]=o.useState(()=>fn(j)),[P,m]=o.useState(t.enabled),[v,$]=o.useState(t.channels),[I,R]=o.useState(typeof t.notifyAgentId=="string"?t.notifyAgentId:""),[V,C]=o.useState({kind:"idle"}),M=!!i[t.platform]?.guidedSetup,[B,L]=o.useState(M&&!t.hasConfig?"guided":"manual"),U=M&&B==="guided",{channels:H,error:W,loading:O,reloadChannels:_}=to(r.listChannels,t.id,p&&t.canListChannels),[X,ce]=o.useState(""),[oe,ee]=o.useState(null),[g,T]=o.useState(!1),[f,K]=o.useState(null),z=qi(oe),[se,ae]=o.useState(!1),ge=t.fields.some(E=>E.type==="agent"),te=lo(o.useMemo(()=>s??pa,[s]),ge),Je=o.useCallback(E=>E?te.find(re=>re.id===E)?.name??E:"",[te]),Ae=Hi(j),Se=o.useRef(t);Se.current=t;const Be=o.useRef(!1),ot=o.useRef(!1);o.useEffect(()=>{if(Be.current)return;const E=Se.current;b(E.label),h(fn(hn(E))),m(E.enabled),$(E.channels),R(typeof E.notifyAgentId=="string"?E.notifyAgentId:"")},[Ae]),o.useEffect(()=>{C({kind:"idle"}),ee(null),K(null),et(!1)},[t.id]),o.useEffect(()=>{L(M&&!t.hasConfig?"guided":"manual")},[t.id,t.hasConfig,M]);const we=o.useCallback(()=>{Be.current=!0,C({kind:"idle"})},[]),fe=o.useCallback((E,re)=>{we(),h(le=>({...le,[E]:re}))},[we]),Ft=o.useCallback(E=>{we(),b(E)},[we]),Ye=o.useCallback(E=>{we(),m(E)},[we]),vt=o.useRef(()=>Promise.resolve()),De=o.useCallback(async()=>{if(!ot.current){ot.current=!0,C({kind:"saving"});try{let E=Se.current.id;E||(E=(await r.create(Se.current.platform,w.trim())).id),await r.save(E,{...Fi(j,S,P),notifyAgentId:I}),Se.current.canListChannels&&await r.saveChannels(E,v);let re=null;try{const{ok:le,text:Ke,code:At}=zi(await r.test(E,{}));!le&&!/not supported/i.test(Ke)&&(re=At==="network_unreachable"?d("settings:integrations.savedNotVerifiedNetwork"):d("settings:integrations.savedNotVerified",{reason:Ke}))}catch(le){re=d("settings:integrations.savedNotVerified",{reason:String(le)})}Be.current=!1,C(re?{kind:"error",text:re}:{kind:"saved"}),await a?.(),Se.current.id===""&&n?.(E)}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}finally{ot.current=!1}}},[r,j,S,P,I,v,w,d,a,n]);vt.current=De;const lt=pn(j.fields,S,t.secrets),Ut=u&&w.trim()==="",Kt=v.every(E=>E.agentId),Qe=!U&&!Ut&<.length===0&&Kt,Ee=o.useMemo(()=>JSON.stringify([w,P,I,v,S]),[w,P,I,v,S]);o.useEffect(()=>{if(!Be.current||!Qe)return;const E=setTimeout(()=>{vt.current()},ko);return()=>clearTimeout(E)},[Ee,Qe]),o.useEffect(()=>{if(!p||u)return;let E=!0;return r.getConnectionTest(t.id).then(re=>{E&&re&&ee(re)}).catch(()=>{}),()=>{E=!1}},[p,u,r,t.id]),o.useEffect(()=>{if(!p||!z)return;let E=!0;const re=setInterval(()=>{r.getConnectionTest(t.id).then(le=>{E&&le&&ee(le)}).catch(()=>{})},2500);return()=>{E=!1,clearInterval(re)}},[p,z,r,t.id]);const jt=o.useRef(null);o.useEffect(()=>{oe?.status==="verified"&&jt.current!==t.id&&(jt.current=t.id,a?.())},[oe?.status,t.id,a]);const Ht=o.useCallback(async()=>{T(!0),K(null);try{ee(await r.startConnectionTest(t.id))}catch(E){K(E instanceof Error?E.message:String(E))}finally{T(!1)}},[r,t.id]),ye=i[t.platform],_e=o.useMemo(()=>({platformId:t.platform,instanceId:t.id||void 0,status:j,values:S,setValue:fe,reload:()=>{a?.()},agents:te,onCreated:n,setupMethod:M?B:void 0,setSetupMethod:M?L:void 0}),[t.platform,t.id,j,S,fe,a,te,n,M,B]),Ne=o.useMemo(()=>new Set(ye?.ownedFields??[]),[ye]),Nt=_t(j.fields).length>0,wt=o.useMemo(()=>new Set(Nt?ao(j.fields).map(E=>E.key):[]),[j.fields,Nt]),Ze=o.useMemo(()=>j.fields.filter(E=>!Ne.has(E.key)&&!wt.has(E.key)),[j.fields,Ne,wt]),Fe=o.useMemo(()=>Ui(Ze),[Ze]),Xe=o.useMemo(()=>Ki(Ze),[Ze]),kt=o.useMemo(()=>Fe.filter(E=>E.type==="agent"),[Fe]),Ct=o.useMemo(()=>Fe.filter(E=>E.type!=="agent"),[Fe]),[zt,et]=o.useState(!1),tt=o.useMemo(()=>pn(t.fields,t.values,t.secrets),[t.fields,t.values,t.secrets]),Oe=t.hasConfig&&!tt.some(E=>Ct.some(re=>re.key===E)),St=o.useMemo(()=>Zi(H,X),[H,X]),je=o.useMemo(()=>Qi(v,H),[v,H]),st=v.filter(E=>!E.agentId).length,qt=o.useCallback((E,re)=>{we(),$(le=>re?bn(le,E.id,Hs(le,E.id)?.agentId??t.agentId??"",E.kind??null):yn(le,E.id))},[we,t.agentId]),Wt=o.useCallback((E,re)=>{we(),$(le=>bn(le,E,re,Hs(le,E)?.kind??null))},[we]),rt=o.useCallback(async()=>{ae(!1);try{await r.remove(t.id),await a?.()}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}},[r,t.id,a]),Ue=Wi(t,oe?.status==="verified"),ne=t.id||`new-${t.platform}`,pe=`instance-name-${ne}`,Gt=lt.map(E=>{const re=j.fields.find(le=>le.key===E);return re?ua(d,t.platform,re).label:E}).join(", ");return e.jsxs("div",{className:"bg-surface-elevated rounded-xl overflow-hidden border border-border-default","data-testid":`instance-card-${ne}`,"data-instance":t.id,"data-platform":t.platform,"data-draft":u?"true":"false","data-expanded":p?"true":"false","data-connection":Ue,children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsxs("button",{type:"button",onClick:()=>x(E=>!E),"aria-expanded":p,"data-testid":`instance-toggle-${ne}`,className:"flex-1 min-w-0 flex items-center gap-3 text-left",children:[e.jsx(va,{id:t.platform}),e.jsxs("span",{className:"flex-1 min-w-0 flex items-center gap-2.5",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary truncate","data-testid":`instance-label-${ne}`,children:w.trim()===""?d("settings:instances.newBot",{defaultValue:"New bot"}):w}),!u&&e.jsx("span",{className:"hidden sm:inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[10px] font-medium bg-surface-secondary border border-border-default text-fg-tertiary","data-testid":`instance-platform-${ne}`,children:t.platform}),!u&&t.agentId&&e.jsxs("span",{className:"hidden sm:inline-flex items-center gap-1.5 text-xs text-fg-tertiary truncate","data-testid":`instance-agent-${ne}`,title:d("settings:instances.boundAgent",{defaultValue:"Bound agent"}),children:[e.jsx("span",{className:"text-fg-quaternary",children:"→"}),Je(t.agentId)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5 shrink-0",children:[e.jsx(fo,{state:Ue}),!u&&e.jsx(bs,{checked:P,onChange:Ye,size:"md",testId:`instance-enabled-${ne}`,label:d("settings:instances.toggleLabel",{defaultValue:"Turn this bot on or off"})}),e.jsx("button",{type:"button",onClick:()=>x(E=>!E),"aria-expanded":p,"data-testid":`instance-chevron-${ne}`,className:"p-1 text-fg-tertiary hover:text-fg-secondary transition-colors",children:e.jsx("svg",{className:`w-4 h-4 transition-transform ${p?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})})]})]}),p&&e.jsxs("div",{className:"px-6 pb-6 pt-5 border-t border-border-default space-y-6",children:[!t.hasConfig&&!U&&e.jsx(wo,{status:j,configured:t.hasConfig,canListChannels:t.canListChannels,channelsGuidance:t.channelsGuidance??null}),!M&&ye?.placement==="before"&&ye.render(_e),e.jsxs("section",{"data-testid":`instance-credentials-${ne}`,className:gs,children:[e.jsx("h3",{className:`${Dt} mb-3`,children:t.hasConfig?d("settings:instances.setup.configuredTitle",{defaultValue:"Bot setup"}):M?d("settings:instances.setup.title",{defaultValue:"Connection"}):d("settings:instances.credentials",{defaultValue:"Credentials"})}),M&&!t.hasConfig&&e.jsx("div",{role:"tablist",className:"inline-flex rounded-lg border border-border-default bg-surface-secondary p-0.5 mb-4",children:["guided","manual"].map(E=>e.jsx("button",{type:"button",role:"tab","aria-selected":B===E,onClick:()=>L(E),"data-testid":`setup-method-${E}-${ne}`,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${B===E?"bg-surface-elevated text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:E==="guided"?d("settings:instances.setup.guided",{defaultValue:"Scan to create (recommended)"}):d("settings:instances.setup.manual",{defaultValue:"Enter credentials manually"})},E))}),U?e.jsx("div",{className:"space-y-4",children:ye.render(_e)}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:ba,children:[e.jsxs("label",{htmlFor:pe,className:vr,children:[d("settings:instances.addBot.name",{defaultValue:"Bot name"}),e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),e.jsx("div",{className:ya,children:e.jsx("input",{id:pe,"data-testid":`new-bot-name-${t.platform}`,value:w,onChange:E=>Ft(E.target.value),placeholder:d("settings:instances.addBot.namePlaceholder",{defaultValue:"e.g. Sales"}),className:jr})})]}),kt.length>0&&e.jsx(yt,{status:j,draft:S,fields:kt,onChange:fe,agentOptions:te}),Ct.length>0&&(Oe&&!zt?e.jsx("div",{"data-testid":`instance-credentials-configured-${ne}`,className:"space-y-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-green-600",children:[e.jsx("span",{"aria-hidden":"true",children:"✓"}),d("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>et(!0),"data-testid":`instance-credentials-edit-${ne}`,className:"text-xs text-brand-600 hover:text-brand-700",children:d("settings:instances.credentialsEdit",{defaultValue:"Change"})})]})}):e.jsxs("div",{className:"space-y-3",children:[Oe&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-green-600",children:[e.jsx("span",{"aria-hidden":"true",children:"✓"}),d("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>et(!1),"data-testid":`instance-credentials-hide-${ne}`,className:"text-xs text-brand-600 hover:text-brand-700",children:d("settings:instances.credentialsHide",{defaultValue:"Hide"})})]}),e.jsx(yt,{status:j,draft:S,fields:Ct,onChange:fe,agentOptions:te})]}))]}),e.jsx("div",{className:"mt-3 min-h-[1.25rem]","data-testid":`instance-save-state-${ne}`,children:e.jsxs("span",{"data-state":V.kind,className:"inline-flex items-center gap-2 text-xs text-fg-tertiary",children:[V.kind==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),d("settings:instances.autosave.saving",{defaultValue:"Saving…"})]}),V.kind==="saved"&&e.jsxs("span",{className:"text-green-600",children:["✓ ",d("settings:instances.autosave.saved",{defaultValue:"Saved"})]}),!Qe&&!U&&e.jsx("span",{"data-testid":`instance-missing-${ne}`,children:lt.length>0?d("settings:integrations.missingRequired",{defaultValue:"Required: {{fields}}",fields:Gt}):d("settings:instances.addBot.labelRequired",{defaultValue:"Give the bot a name."})})]})}),V.kind==="error"&&e.jsx("div",{className:"mt-2",children:e.jsx($t,{type:"err",text:V.text})})]}),!u&&e.jsxs("section",{children:[e.jsx(bo,{test:oe,starting:g,lastVerifiedAt:t.lastVerifiedAt,onStart:()=>{Ht()}}),f&&e.jsx("div",{className:"mt-3",children:e.jsx($t,{type:"err",text:f})})]}),!u&&Nt&&e.jsx(yo,{status:j,values:S,setValue:fe,channels:H,canListChannels:t.canListChannels,channelsLoading:O,channelsError:W,onReloadChannels:_,channelsGuidance:t.channelsGuidance??null,testSlot:ye?.sendTest?.(_e)}),e.jsxs("section",{"data-testid":`instance-more-${ne}`,children:[e.jsxs("button",{type:"button",onClick:()=>y(E=>!E),"aria-expanded":k,"data-testid":`instance-more-toggle-${ne}`,className:"w-full flex items-center gap-2 text-left group px-1",children:[e.jsx("span",{className:Dt,children:d("settings:instances.moreSettings",{defaultValue:"Advanced"})}),e.jsx("span",{className:`${bt} truncate hidden sm:inline`,children:d("settings:instances.moreSettingsHint",{defaultValue:"Chat routing and platform options"})}),e.jsx("svg",{className:`ml-auto w-3.5 h-3.5 text-fg-tertiary transition-transform ${k?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),k&&e.jsxs("div",{className:"mt-3 space-y-4",children:[Xe.length>0&&e.jsxs("div",{className:gs,children:[e.jsx("h4",{className:`${Dt} mb-1`,children:d("settings:instances.advancedTitle",{defaultValue:"Platform options"})}),!u&&e.jsx("p",{className:`${bt} mb-3`,children:d("settings:instances.advancedHint",{defaultValue:"These default to the right value for almost every setup — leave them alone unless you know you need them."})}),e.jsx(yt,{status:j,draft:S,fields:Xe,onChange:fe,agentOptions:te})]}),!u&&e.jsxs("div",{className:gs,children:[e.jsx("h4",{className:`${Dt} mb-1`,children:d("settings:instances.routing.chats",{defaultValue:"Chat routing"})}),e.jsx("p",{className:`${bt} mb-3`,children:d("settings:instances.routing.chatsHint",{defaultValue:"The agent bound above answers every chat by default. Route a specific chat to a different agent here."})}),!t.canListChannels&&e.jsx("p",{className:"text-[11px] text-fg-tertiary","data-testid":`instance-chats-unsupported-${ne}`,children:t.channelsGuidance?d(t.channelsGuidance,{defaultValue:d("settings:instances.routing.unsupported",{defaultValue:"This platform does not let us list its chats."})}):d("settings:instances.routing.unsupported",{defaultValue:"This platform does not let us list its chats."})}),t.canListChannels&&e.jsx("div",{className:"mb-2",children:e.jsx(ha,{loading:O,error:W,onReload:_,empty:H.length===0,buttonTestId:`instance-chats-refresh-${ne}`,errorTestId:`instance-chats-error-${ne}`})}),t.canListChannels&&H.length>0&&e.jsx("input",{type:"text",value:X,onChange:E=>ce(E.target.value),placeholder:d("settings:instances.routing.searchChats",{defaultValue:"Search chats…"}),"data-testid":`instance-chat-search-${ne}`,className:"w-full mb-2 px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500"}),e.jsxs("div",{className:"space-y-2","data-testid":`instance-chats-${ne}`,children:[St.map(E=>{const re=Hs(v,E.id);return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-fg-primary min-w-0 flex-1",children:[e.jsx("input",{type:"checkbox",checked:!!re,"data-testid":`instance-chat-toggle-${ne}-${E.id}`,onChange:le=>qt(E,le.target.checked),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate",title:E.id,children:E.name})]}),re&&e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${ne}-${E.id}`,children:e.jsx(hs,{value:re.agentId,options:te,onChange:(le,Ke)=>Wt(E.id,typeof Ke=="string"?Ke:""),fieldKey:"agentId",ariaLabel:d("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.id)}),je.map(E=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm text-fg-primary min-w-0 flex-1",children:[e.jsx("input",{type:"checkbox",checked:!0,"data-testid":`instance-chat-toggle-${ne}-${E.nativeId}`,onChange:()=>$(re=>yn(re,E.nativeId)),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate font-mono text-xs",title:E.nativeId,children:E.nativeId})]}),e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${ne}-${E.nativeId}`,children:e.jsx(hs,{value:E.agentId,options:te,onChange:(re,le)=>Wt(E.nativeId,typeof le=="string"?le:""),fieldKey:"agentId",ariaLabel:d("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.nativeId))]}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-2",children:d("settings:instances.routing.autoSaved",{defaultValue:"Changes are saved automatically."})}),st>0&&e.jsx("div",{className:"mt-3",children:e.jsx($t,{type:"err",text:d("settings:instances.routing.agentRequired",{defaultValue:"Pick an agent for every selected chat ({{count}} still unassigned).",count:st})})})]})]})]}),!M&&ye&&ye.placement!=="before"&&ye.render(_e),!u&&e.jsx("div",{className:"pt-1",children:e.jsx("button",{type:"button",onClick:()=>ae(!0),"data-testid":`instance-disconnect-${ne}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-red-600 border border-red-500/30 rounded-lg hover:bg-red-500/10 transition-colors",children:d("settings:integrations.disconnect",{defaultValue:"Disconnect"})})})]}),se&&e.jsx(fs,{title:d("settings:integrations.disconnectConfirmTitle",{defaultValue:"Disconnect this bot?"}),message:d("settings:integrations.disconnectConfirmMessage",{defaultValue:"Its stored credentials are removed and it stops sending and receiving messages. This cannot be undone."}),confirmLabel:d("settings:integrations.disconnect",{defaultValue:"Disconnect"}),variant:"danger",onConfirm:()=>{rt()},onCancel:()=>ae(!1)})]})}var ft={},zs,Cn;function Co(){return Cn||(Cn=1,zs=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),zs}var qs={},Ge={},Sn;function at(){if(Sn)return Ge;Sn=1;let t;const r=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ge.getSymbolSize=function(a){if(!a)throw new Error('"version" cannot be null or undefined');if(a<1||a>40)throw new Error('"version" should be in range from 1 to 40');return a*4+17},Ge.getSymbolTotalCodewords=function(a){return r[a]},Ge.getBCHDigit=function(i){let a=0;for(;i!==0;)a++,i>>>=1;return a},Ge.setToSJISFunction=function(a){if(typeof a!="function")throw new Error('"toSJISFunc" is not a valid function.');t=a},Ge.isKanjiModeEnabled=function(){return typeof t<"u"},Ge.toSJIS=function(a){return t(a)},Ge}var Ws={},An;function Cr(){return An||(An=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function r(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+i)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,n){if(t.isValid(a))return a;try{return r(a)}catch{return n}}})(Ws)),Ws}var Gs,Pn;function So(){if(Pn)return Gs;Pn=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(r){const i=Math.floor(r/8);return(this.buffer[i]>>>7-r%8&1)===1},put:function(r,i){for(let a=0;a<i;a++)this.putBit((r>>>i-a-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){const i=Math.floor(this.length/8);this.buffer.length<=i&&this.buffer.push(0),r&&(this.buffer[i]|=128>>>this.length%8),this.length++}},Gs=t,Gs}var Js,Mn;function Ao(){if(Mn)return Js;Mn=1;function t(r){if(!r||r<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=r,this.data=new Uint8Array(r*r),this.reservedBit=new Uint8Array(r*r)}return t.prototype.set=function(r,i,a,n){const s=r*this.size+i;this.data[s]=a,n&&(this.reservedBit[s]=!0)},t.prototype.get=function(r,i){return this.data[r*this.size+i]},t.prototype.xor=function(r,i,a){this.data[r*this.size+i]^=a},t.prototype.isReserved=function(r,i){return this.reservedBit[r*this.size+i]},Js=t,Js}var Ys={},Tn;function Po(){return Tn||(Tn=1,(function(t){const r=at().getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,s=r(a),c=s===145?26:Math.ceil((s-13)/(2*n-2))*2,d=[s-7];for(let u=1;u<n-1;u++)d[u]=d[u-1]-c;return d.push(6),d.reverse()},t.getPositions=function(a){const n=[],s=t.getRowColCoords(a),c=s.length;for(let d=0;d<c;d++)for(let u=0;u<c;u++)d===0&&u===0||d===0&&u===c-1||d===c-1&&u===0||n.push([s[d],s[u]]);return n}})(Ys)),Ys}var Qs={},En;function Mo(){if(En)return Qs;En=1;const t=at().getSymbolSize,r=7;return Qs.getPositions=function(a){const n=t(a);return[[0,0],[n-r,0],[0,n-r]]},Qs}var Zs={},Ln;function To(){return Ln||(Ln=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const r={N1:3,N2:3,N3:40,N4:10};t.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},t.from=function(n){return t.isValid(n)?parseInt(n,10):void 0},t.getPenaltyN1=function(n){const s=n.size;let c=0,d=0,u=0,p=null,x=null;for(let k=0;k<s;k++){d=u=0,p=x=null;for(let y=0;y<s;y++){let j=n.get(k,y);j===p?d++:(d>=5&&(c+=r.N1+(d-5)),p=j,d=1),j=n.get(y,k),j===x?u++:(u>=5&&(c+=r.N1+(u-5)),x=j,u=1)}d>=5&&(c+=r.N1+(d-5)),u>=5&&(c+=r.N1+(u-5))}return c},t.getPenaltyN2=function(n){const s=n.size;let c=0;for(let d=0;d<s-1;d++)for(let u=0;u<s-1;u++){const p=n.get(d,u)+n.get(d,u+1)+n.get(d+1,u)+n.get(d+1,u+1);(p===4||p===0)&&c++}return c*r.N2},t.getPenaltyN3=function(n){const s=n.size;let c=0,d=0,u=0;for(let p=0;p<s;p++){d=u=0;for(let x=0;x<s;x++)d=d<<1&2047|n.get(p,x),x>=10&&(d===1488||d===93)&&c++,u=u<<1&2047|n.get(x,p),x>=10&&(u===1488||u===93)&&c++}return c*r.N3},t.getPenaltyN4=function(n){let s=0;const c=n.data.length;for(let u=0;u<c;u++)s+=n.data[u];return Math.abs(Math.ceil(s*100/c/5)-10)*r.N4};function i(a,n,s){switch(a){case t.Patterns.PATTERN000:return(n+s)%2===0;case t.Patterns.PATTERN001:return n%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(n+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return n*s%2+n*s%3===0;case t.Patterns.PATTERN110:return(n*s%2+n*s%3)%2===0;case t.Patterns.PATTERN111:return(n*s%3+(n+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(n,s){const c=s.size;for(let d=0;d<c;d++)for(let u=0;u<c;u++)s.isReserved(u,d)||s.xor(u,d,i(n,u,d))},t.getBestMask=function(n,s){const c=Object.keys(t.Patterns).length;let d=0,u=1/0;for(let p=0;p<c;p++){s(p),t.applyMask(p,n);const x=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(p,n),x<u&&(u=x,d=p)}return d}})(Zs)),Zs}var cs={},Rn;function Na(){if(Rn)return cs;Rn=1;const t=Cr(),r=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],i=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return cs.getBlocksCount=function(n,s){switch(s){case t.L:return r[(n-1)*4+0];case t.M:return r[(n-1)*4+1];case t.Q:return r[(n-1)*4+2];case t.H:return r[(n-1)*4+3];default:return}},cs.getTotalCodewordsCount=function(n,s){switch(s){case t.L:return i[(n-1)*4+0];case t.M:return i[(n-1)*4+1];case t.Q:return i[(n-1)*4+2];case t.H:return i[(n-1)*4+3];default:return}},cs}var Xs={},Rt={},In;function Eo(){if(In)return Rt;In=1;const t=new Uint8Array(512),r=new Uint8Array(256);return(function(){let a=1;for(let n=0;n<255;n++)t[n]=a,r[a]=n,a<<=1,a&256&&(a^=285);for(let n=255;n<512;n++)t[n]=t[n-255]})(),Rt.log=function(a){if(a<1)throw new Error("log("+a+")");return r[a]},Rt.exp=function(a){return t[a]},Rt.mul=function(a,n){return a===0||n===0?0:t[r[a]+r[n]]},Rt}var Bn;function Lo(){return Bn||(Bn=1,(function(t){const r=Eo();t.mul=function(a,n){const s=new Uint8Array(a.length+n.length-1);for(let c=0;c<a.length;c++)for(let d=0;d<n.length;d++)s[c+d]^=r.mul(a[c],n[d]);return s},t.mod=function(a,n){let s=new Uint8Array(a);for(;s.length-n.length>=0;){const c=s[0];for(let u=0;u<n.length;u++)s[u]^=r.mul(n[u],c);let d=0;for(;d<s.length&&s[d]===0;)d++;s=s.slice(d)}return s},t.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let s=0;s<a;s++)n=t.mul(n,new Uint8Array([1,r.exp(s)]));return n}})(Xs)),Xs}var er,Dn;function Ro(){if(Dn)return er;Dn=1;const t=Lo();function r(i){this.genPoly=void 0,this.degree=i,this.degree&&this.initialize(this.degree)}return r.prototype.initialize=function(a){this.degree=a,this.genPoly=t.generateECPolynomial(this.degree)},r.prototype.encode=function(a){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(a.length+this.degree);n.set(a);const s=t.mod(n,this.genPoly),c=this.degree-s.length;if(c>0){const d=new Uint8Array(this.degree);return d.set(s,c),d}return s},er=r,er}var tr={},sr={},rr={},On;function wa(){return On||(On=1,rr.isValid=function(r){return!isNaN(r)&&r>=1&&r<=40}),rr}var Re={},$n;function ka(){if($n)return Re;$n=1;const t="[0-9]+",r="[A-Z $%*+\\-./:]+";let i="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";i=i.replace(/u/g,"\\u");const a="(?:(?![A-Z0-9 $%*+\\-./:]|"+i+`)(?:.|[\r
|
|
2
|
+
]))+`;Re.KANJI=new RegExp(i,"g"),Re.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Re.BYTE=new RegExp(a,"g"),Re.NUMERIC=new RegExp(t,"g"),Re.ALPHANUMERIC=new RegExp(r,"g");const n=new RegExp("^"+i+"$"),s=new RegExp("^"+t+"$"),c=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Re.testKanji=function(u){return n.test(u)},Re.testNumeric=function(u){return s.test(u)},Re.testAlphanumeric=function(u){return c.test(u)},Re}var Vn;function it(){return Vn||(Vn=1,(function(t){const r=wa(),i=ka();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,c){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!r.isValid(c))throw new Error("Invalid version: "+c);return c>=1&&c<10?s.ccBits[0]:c<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return i.testNumeric(s)?t.NUMERIC:i.testAlphanumeric(s)?t.ALPHANUMERIC:i.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+n)}}t.from=function(s,c){if(t.isValid(s))return s;try{return a(s)}catch{return c}}})(sr)),sr}var _n;function Io(){return _n||(_n=1,(function(t){const r=at(),i=Na(),a=Cr(),n=it(),s=wa(),c=7973,d=r.getBCHDigit(c);function u(y,j,w){for(let b=1;b<=40;b++)if(j<=t.getCapacity(b,w,y))return b}function p(y,j){return n.getCharCountIndicator(y,j)+4}function x(y,j){let w=0;return y.forEach(function(b){const S=p(b.mode,j);w+=S+b.getBitsLength()}),w}function k(y,j){for(let w=1;w<=40;w++)if(x(y,w)<=t.getCapacity(w,j,n.MIXED))return w}t.from=function(j,w){return s.isValid(j)?parseInt(j,10):w},t.getCapacity=function(j,w,b){if(!s.isValid(j))throw new Error("Invalid QR Code version");typeof b>"u"&&(b=n.BYTE);const S=r.getSymbolTotalCodewords(j),h=i.getTotalCodewordsCount(j,w),P=(S-h)*8;if(b===n.MIXED)return P;const m=P-p(b,j);switch(b){case n.NUMERIC:return Math.floor(m/10*3);case n.ALPHANUMERIC:return Math.floor(m/11*2);case n.KANJI:return Math.floor(m/13);case n.BYTE:default:return Math.floor(m/8)}},t.getBestVersionForData=function(j,w){let b;const S=a.from(w,a.M);if(Array.isArray(j)){if(j.length>1)return k(j,S);if(j.length===0)return 1;b=j[0]}else b=j;return u(b.mode,b.getLength(),S)},t.getEncodedBits=function(j){if(!s.isValid(j)||j<7)throw new Error("Invalid QR Code version");let w=j<<12;for(;r.getBCHDigit(w)-d>=0;)w^=c<<r.getBCHDigit(w)-d;return j<<12|w}})(tr)),tr}var nr={},Fn;function Bo(){if(Fn)return nr;Fn=1;const t=at(),r=1335,i=21522,a=t.getBCHDigit(r);return nr.getEncodedBits=function(s,c){const d=s.bit<<3|c;let u=d<<10;for(;t.getBCHDigit(u)-a>=0;)u^=r<<t.getBCHDigit(u)-a;return(d<<10|u)^i},nr}var ar={},ir,Un;function Do(){if(Un)return ir;Un=1;const t=it();function r(i){this.mode=t.NUMERIC,this.data=i.toString()}return r.getBitsLength=function(a){return 10*Math.floor(a/3)+(a%3?a%3*3+1:0)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(a){let n,s,c;for(n=0;n+3<=this.data.length;n+=3)s=this.data.substr(n,3),c=parseInt(s,10),a.put(c,10);const d=this.data.length-n;d>0&&(s=this.data.substr(n),c=parseInt(s,10),a.put(c,d*3+1))},ir=r,ir}var or,Kn;function Oo(){if(Kn)return or;Kn=1;const t=it(),r=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function i(a){this.mode=t.ALPHANUMERIC,this.data=a}return i.getBitsLength=function(n){return 11*Math.floor(n/2)+6*(n%2)},i.prototype.getLength=function(){return this.data.length},i.prototype.getBitsLength=function(){return i.getBitsLength(this.data.length)},i.prototype.write=function(n){let s;for(s=0;s+2<=this.data.length;s+=2){let c=r.indexOf(this.data[s])*45;c+=r.indexOf(this.data[s+1]),n.put(c,11)}this.data.length%2&&n.put(r.indexOf(this.data[s]),6)},or=i,or}var lr,Hn;function $o(){if(Hn)return lr;Hn=1;const t=it();function r(i){this.mode=t.BYTE,typeof i=="string"?this.data=new TextEncoder().encode(i):this.data=new Uint8Array(i)}return r.getBitsLength=function(a){return a*8},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){for(let a=0,n=this.data.length;a<n;a++)i.put(this.data[a],8)},lr=r,lr}var dr,zn;function Vo(){if(zn)return dr;zn=1;const t=it(),r=at();function i(a){this.mode=t.KANJI,this.data=a}return i.getBitsLength=function(n){return n*13},i.prototype.getLength=function(){return this.data.length},i.prototype.getBitsLength=function(){return i.getBitsLength(this.data.length)},i.prototype.write=function(a){let n;for(n=0;n<this.data.length;n++){let s=r.toSJIS(this.data[n]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[n]+`
|
|
3
|
+
Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),a.put(s,13)}},dr=i,dr}var cr={exports:{}},qn;function _o(){return qn||(qn=1,(function(t){var r={single_source_shortest_paths:function(i,a,n){var s={},c={};c[a]=0;var d=r.PriorityQueue.make();d.push(a,0);for(var u,p,x,k,y,j,w,b,S;!d.empty();){u=d.pop(),p=u.value,k=u.cost,y=i[p]||{};for(x in y)y.hasOwnProperty(x)&&(j=y[x],w=k+j,b=c[x],S=typeof c[x]>"u",(S||b>w)&&(c[x]=w,d.push(x,w),s[x]=p))}if(typeof n<"u"&&typeof c[n]>"u"){var h=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(h)}return s},extract_shortest_path_from_predecessor_list:function(i,a){for(var n=[],s=a;s;)n.push(s),i[s],s=i[s];return n.reverse(),n},find_path:function(i,a,n){var s=r.single_source_shortest_paths(i,a,n);return r.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(i){var a=r.PriorityQueue,n={},s;i=i||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=i.sorter||a.default_sorter,n},default_sorter:function(i,a){return i.cost-a.cost},push:function(i,a){var n={value:i,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=r})(cr)),cr.exports}var Wn;function Fo(){return Wn||(Wn=1,(function(t){const r=it(),i=Do(),a=Oo(),n=$o(),s=Vo(),c=ka(),d=at(),u=_o();function p(h){return unescape(encodeURIComponent(h)).length}function x(h,P,m){const v=[];let $;for(;($=h.exec(m))!==null;)v.push({data:$[0],index:$.index,mode:P,length:$[0].length});return v}function k(h){const P=x(c.NUMERIC,r.NUMERIC,h),m=x(c.ALPHANUMERIC,r.ALPHANUMERIC,h);let v,$;return d.isKanjiModeEnabled()?(v=x(c.BYTE,r.BYTE,h),$=x(c.KANJI,r.KANJI,h)):(v=x(c.BYTE_KANJI,r.BYTE,h),$=[]),P.concat(m,v,$).sort(function(R,V){return R.index-V.index}).map(function(R){return{data:R.data,mode:R.mode,length:R.length}})}function y(h,P){switch(P){case r.NUMERIC:return i.getBitsLength(h);case r.ALPHANUMERIC:return a.getBitsLength(h);case r.KANJI:return s.getBitsLength(h);case r.BYTE:return n.getBitsLength(h)}}function j(h){return h.reduce(function(P,m){const v=P.length-1>=0?P[P.length-1]:null;return v&&v.mode===m.mode?(P[P.length-1].data+=m.data,P):(P.push(m),P)},[])}function w(h){const P=[];for(let m=0;m<h.length;m++){const v=h[m];switch(v.mode){case r.NUMERIC:P.push([v,{data:v.data,mode:r.ALPHANUMERIC,length:v.length},{data:v.data,mode:r.BYTE,length:v.length}]);break;case r.ALPHANUMERIC:P.push([v,{data:v.data,mode:r.BYTE,length:v.length}]);break;case r.KANJI:P.push([v,{data:v.data,mode:r.BYTE,length:p(v.data)}]);break;case r.BYTE:P.push([{data:v.data,mode:r.BYTE,length:p(v.data)}])}}return P}function b(h,P){const m={},v={start:{}};let $=["start"];for(let I=0;I<h.length;I++){const R=h[I],V=[];for(let C=0;C<R.length;C++){const M=R[C],B=""+I+C;V.push(B),m[B]={node:M,lastCount:0},v[B]={};for(let L=0;L<$.length;L++){const U=$[L];m[U]&&m[U].node.mode===M.mode?(v[U][B]=y(m[U].lastCount+M.length,M.mode)-y(m[U].lastCount,M.mode),m[U].lastCount+=M.length):(m[U]&&(m[U].lastCount=M.length),v[U][B]=y(M.length,M.mode)+4+r.getCharCountIndicator(M.mode,P))}}$=V}for(let I=0;I<$.length;I++)v[$[I]].end=0;return{map:v,table:m}}function S(h,P){let m;const v=r.getBestModeForData(h);if(m=r.from(P,v),m!==r.BYTE&&m.bit<v.bit)throw new Error('"'+h+'" cannot be encoded with mode '+r.toString(m)+`.
|
|
4
|
+
Suggested mode is: `+r.toString(v));switch(m===r.KANJI&&!d.isKanjiModeEnabled()&&(m=r.BYTE),m){case r.NUMERIC:return new i(h);case r.ALPHANUMERIC:return new a(h);case r.KANJI:return new s(h);case r.BYTE:return new n(h)}}t.fromArray=function(P){return P.reduce(function(m,v){return typeof v=="string"?m.push(S(v,null)):v.data&&m.push(S(v.data,v.mode)),m},[])},t.fromString=function(P,m){const v=k(P,d.isKanjiModeEnabled()),$=w(v),I=b($,m),R=u.find_path(I.map,"start","end"),V=[];for(let C=1;C<R.length-1;C++)V.push(I.table[R[C]].node);return t.fromArray(j(V))},t.rawSplit=function(P){return t.fromArray(k(P,d.isKanjiModeEnabled()))}})(ar)),ar}var Gn;function Uo(){if(Gn)return qs;Gn=1;const t=at(),r=Cr(),i=So(),a=Ao(),n=Po(),s=Mo(),c=To(),d=Na(),u=Ro(),p=Io(),x=Bo(),k=it(),y=Fo();function j(I,R){const V=I.size,C=s.getPositions(R);for(let M=0;M<C.length;M++){const B=C[M][0],L=C[M][1];for(let U=-1;U<=7;U++)if(!(B+U<=-1||V<=B+U))for(let H=-1;H<=7;H++)L+H<=-1||V<=L+H||(U>=0&&U<=6&&(H===0||H===6)||H>=0&&H<=6&&(U===0||U===6)||U>=2&&U<=4&&H>=2&&H<=4?I.set(B+U,L+H,!0,!0):I.set(B+U,L+H,!1,!0))}}function w(I){const R=I.size;for(let V=8;V<R-8;V++){const C=V%2===0;I.set(V,6,C,!0),I.set(6,V,C,!0)}}function b(I,R){const V=n.getPositions(R);for(let C=0;C<V.length;C++){const M=V[C][0],B=V[C][1];for(let L=-2;L<=2;L++)for(let U=-2;U<=2;U++)L===-2||L===2||U===-2||U===2||L===0&&U===0?I.set(M+L,B+U,!0,!0):I.set(M+L,B+U,!1,!0)}}function S(I,R){const V=I.size,C=p.getEncodedBits(R);let M,B,L;for(let U=0;U<18;U++)M=Math.floor(U/3),B=U%3+V-8-3,L=(C>>U&1)===1,I.set(M,B,L,!0),I.set(B,M,L,!0)}function h(I,R,V){const C=I.size,M=x.getEncodedBits(R,V);let B,L;for(B=0;B<15;B++)L=(M>>B&1)===1,B<6?I.set(B,8,L,!0):B<8?I.set(B+1,8,L,!0):I.set(C-15+B,8,L,!0),B<8?I.set(8,C-B-1,L,!0):B<9?I.set(8,15-B-1+1,L,!0):I.set(8,15-B-1,L,!0);I.set(C-8,8,1,!0)}function P(I,R){const V=I.size;let C=-1,M=V-1,B=7,L=0;for(let U=V-1;U>0;U-=2)for(U===6&&U--;;){for(let H=0;H<2;H++)if(!I.isReserved(M,U-H)){let W=!1;L<R.length&&(W=(R[L]>>>B&1)===1),I.set(M,U-H,W),B--,B===-1&&(L++,B=7)}if(M+=C,M<0||V<=M){M-=C,C=-C;break}}}function m(I,R,V){const C=new i;V.forEach(function(H){C.put(H.mode.bit,4),C.put(H.getLength(),k.getCharCountIndicator(H.mode,I)),H.write(C)});const M=t.getSymbolTotalCodewords(I),B=d.getTotalCodewordsCount(I,R),L=(M-B)*8;for(C.getLengthInBits()+4<=L&&C.put(0,4);C.getLengthInBits()%8!==0;)C.putBit(0);const U=(L-C.getLengthInBits())/8;for(let H=0;H<U;H++)C.put(H%2?17:236,8);return v(C,I,R)}function v(I,R,V){const C=t.getSymbolTotalCodewords(R),M=d.getTotalCodewordsCount(R,V),B=C-M,L=d.getBlocksCount(R,V),U=C%L,H=L-U,W=Math.floor(C/L),O=Math.floor(B/L),_=O+1,X=W-O,ce=new u(X);let oe=0;const ee=new Array(L),g=new Array(L);let T=0;const f=new Uint8Array(I.buffer);for(let ge=0;ge<L;ge++){const te=ge<H?O:_;ee[ge]=f.slice(oe,oe+te),g[ge]=ce.encode(ee[ge]),oe+=te,T=Math.max(T,te)}const K=new Uint8Array(C);let z=0,se,ae;for(se=0;se<T;se++)for(ae=0;ae<L;ae++)se<ee[ae].length&&(K[z++]=ee[ae][se]);for(se=0;se<X;se++)for(ae=0;ae<L;ae++)K[z++]=g[ae][se];return K}function $(I,R,V,C){let M;if(Array.isArray(I))M=y.fromArray(I);else if(typeof I=="string"){let W=R;if(!W){const O=y.rawSplit(I);W=p.getBestVersionForData(O,V)}M=y.fromString(I,W||40)}else throw new Error("Invalid data");const B=p.getBestVersionForData(M,V);if(!B)throw new Error("The amount of data is too big to be stored in a QR Code");if(!R)R=B;else if(R<B)throw new Error(`
|
|
5
|
+
The chosen QR Code version cannot contain this amount of data.
|
|
6
|
+
Minimum version required to store current data is: `+B+`.
|
|
7
|
+
`);const L=m(R,V,M),U=t.getSymbolSize(R),H=new a(U);return j(H,R),w(H),b(H,R),h(H,V,0),R>=7&&S(H,R),P(H,L),isNaN(C)&&(C=c.getBestMask(H,h.bind(null,H,V))),c.applyMask(C,H),h(H,V,C),{modules:H,version:R,errorCorrectionLevel:V,maskPattern:C,segments:M}}return qs.create=function(R,V){if(typeof R>"u"||R==="")throw new Error("No input text");let C=r.M,M,B;return typeof V<"u"&&(C=r.from(V.errorCorrectionLevel,r.M),M=p.from(V.version),B=c.from(V.maskPattern),V.toSJISFunc&&t.setToSJISFunction(V.toSJISFunc)),$(R,M,C,B)},qs}var ur={},mr={},Jn;function Ca(){return Jn||(Jn=1,(function(t){function r(i){if(typeof i=="number"&&(i=i.toString()),typeof i!="string")throw new Error("Color should be defined as hex string");let a=i.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+i);(a.length===3||a.length===4)&&(a=Array.prototype.concat.apply([],a.map(function(s){return[s,s]}))),a.length===6&&a.push("F","F");const n=parseInt(a.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const n=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,c=a.scale||4;return{width:s,scale:s?4:c,margin:n,color:{dark:r(a.color.dark||"#000000ff"),light:r(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,n){return n.width&&n.width>=a+n.margin*2?n.width/(a+n.margin*2):n.scale},t.getImageWidth=function(a,n){const s=t.getScale(a,n);return Math.floor((a+n.margin*2)*s)},t.qrToImageData=function(a,n,s){const c=n.modules.size,d=n.modules.data,u=t.getScale(c,s),p=Math.floor((c+s.margin*2)*u),x=s.margin*u,k=[s.color.light,s.color.dark];for(let y=0;y<p;y++)for(let j=0;j<p;j++){let w=(y*p+j)*4,b=s.color.light;if(y>=x&&j>=x&&y<p-x&&j<p-x){const S=Math.floor((y-x)/u),h=Math.floor((j-x)/u);b=k[d[S*c+h]?1:0]}a[w++]=b.r,a[w++]=b.g,a[w++]=b.b,a[w]=b.a}}})(mr)),mr}var Yn;function Ko(){return Yn||(Yn=1,(function(t){const r=Ca();function i(n,s,c){n.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=c,s.width=c,s.style.height=c+"px",s.style.width=c+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,c,d){let u=d,p=c;typeof u>"u"&&(!c||!c.getContext)&&(u=c,c=void 0),c||(p=a()),u=r.getOptions(u);const x=r.getImageWidth(s.modules.size,u),k=p.getContext("2d"),y=k.createImageData(x,x);return r.qrToImageData(y.data,s,u),i(k,p,x),k.putImageData(y,0,0),p},t.renderToDataURL=function(s,c,d){let u=d;typeof u>"u"&&(!c||!c.getContext)&&(u=c,c=void 0),u||(u={});const p=t.render(s,c,u),x=u.type||"image/png",k=u.rendererOpts||{};return p.toDataURL(x,k.quality)}})(ur)),ur}var xr={},Qn;function Ho(){if(Qn)return xr;Qn=1;const t=Ca();function r(n,s){const c=n.a/255,d=s+'="'+n.hex+'"';return c<1?d+" "+s+'-opacity="'+c.toFixed(2).slice(1)+'"':d}function i(n,s,c){let d=n+s;return typeof c<"u"&&(d+=" "+c),d}function a(n,s,c){let d="",u=0,p=!1,x=0;for(let k=0;k<n.length;k++){const y=Math.floor(k%s),j=Math.floor(k/s);!y&&!p&&(p=!0),n[k]?(x++,k>0&&y>0&&n[k-1]||(d+=p?i("M",y+c,.5+j+c):i("m",u,0),u=0,p=!1),y+1<s&&n[k+1]||(d+=i("h",x),x=0)):u++}return d}return xr.render=function(s,c,d){const u=t.getOptions(c),p=s.modules.size,x=s.modules.data,k=p+u.margin*2,y=u.color.light.a?"<path "+r(u.color.light,"fill")+' d="M0 0h'+k+"v"+k+'H0z"/>':"",j="<path "+r(u.color.dark,"stroke")+' d="'+a(x,p,u.margin)+'"/>',w='viewBox="0 0 '+k+" "+k+'"',S='<svg xmlns="http://www.w3.org/2000/svg" '+(u.width?'width="'+u.width+'" height="'+u.width+'" ':"")+w+' shape-rendering="crispEdges">'+y+j+`</svg>
|
|
8
|
+
`;return typeof d=="function"&&d(null,S),S},xr}var Zn;function zo(){if(Zn)return ft;Zn=1;const t=Co(),r=Uo(),i=Ko(),a=Ho();function n(s,c,d,u,p){const x=[].slice.call(arguments,1),k=x.length,y=typeof x[k-1]=="function";if(!y&&!t())throw new Error("Callback required as last argument");if(y){if(k<2)throw new Error("Too few arguments provided");k===2?(p=d,d=c,c=u=void 0):k===3&&(c.getContext&&typeof p>"u"?(p=u,u=void 0):(p=u,u=d,d=c,c=void 0))}else{if(k<1)throw new Error("Too few arguments provided");return k===1?(d=c,c=u=void 0):k===2&&!c.getContext&&(u=d,d=c,c=void 0),new Promise(function(j,w){try{const b=r.create(d,u);j(s(b,c,u))}catch(b){w(b)}})}try{const j=r.create(d,u);p(null,s(j,c,u))}catch(j){p(j)}}return ft.create=r.create,ft.toCanvas=n.bind(null,i.render),ft.toDataURL=n.bind(null,i.renderToDataURL),ft.toString=n.bind(null,function(s,c,d){return a.render(s,d)}),ft}var Sa=zo();const Aa=si(Sa),qo=Ni({__proto__:null,default:Aa},[Sa]);function Wo({ctx:t}){const{t:r}=xe(["settings","common"]),{values:i,reload:a,onCreated:n,agents:s=[]}=t,[c,d]=o.useState(null),[u,p]=o.useState("idle"),[x,k]=o.useState(null),[y,j]=o.useState(()=>String(i.agentId??"")),w=o.useRef(null),b=u!=="idle";o.useEffect(()=>()=>{w.current&&clearInterval(w.current)},[]);const S=o.useCallback(()=>{w.current&&(clearInterval(w.current),w.current=null)},[]),h=o.useCallback(async()=>{p("waiting_qr"),k(null),d(null),w.current=setInterval(async()=>{try{const m=await F.settings.getFeishuRegisterStatus();if(m.active&&m.url){p("scanning");try{k(await Aa.toDataURL(m.url,{width:192,margin:2,color:{dark:"#000000",light:"#ffffff"}}))}catch{}}}catch{}},1e3);try{const m=await F.settings.registerFeishuApp({agentId:y||void 0});S(),m.success&&m.appId?(p("done"),d({type:"ok",text:r("settings:feishu.registerSuccess",{defaultValue:"App created successfully! Integration is now active."})}),await a(),m.instanceId&&n?.(m.instanceId)):(p("error"),d({type:"err",text:m.message??r("settings:feishu.registerFailed",{defaultValue:"Registration failed"})}))}catch(m){S(),p("error"),d({type:"err",text:m instanceof Error?m.message:String(m)})}},[a,n,y,r,S]),P=o.useCallback(()=>{S(),p("idle"),k(null),d(null)},[S]);return e.jsxs("div",{className:"space-y-4","data-testid":"feishu-extras",children:[e.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-xl p-5 space-y-4","data-testid":"feishu-register",children:[e.jsxs("div",{className:"max-w-sm",children:[e.jsxs("label",{className:"block text-xs font-medium text-fg-secondary mb-1.5",htmlFor:"feishu-register-agent",children:[r("settings:feishu.bindAgent",{defaultValue:"Agent that answers for this bot"}),e.jsx("span",{className:"text-red-500 ml-0.5","aria-hidden":"true",children:"*"})]}),e.jsx(hs,{value:y,options:s,onChange:(m,v)=>j(typeof v=="string"?v:""),fieldKey:"agentId",disabled:b,ariaLabel:r("settings:feishu.bindAgent",{defaultValue:"Agent that answers for this bot"})}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-1",children:b?r("settings:feishu.bindAgentLocked",{defaultValue:"This agent is baked into the QR — cancel the scan to change it."}):r("settings:feishu.bindAgentHint",{defaultValue:"The Feishu app is created as this agent. Pick it now so the bot is never wired to the wrong one."})})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:h,disabled:!y||u!=="idle","data-testid":"feishu-register-start",className:"inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:r("settings:feishu.scanToCreate",{defaultValue:"Scan QR Code"})}),b&&u!=="done"&&e.jsx("button",{type:"button",onClick:P,"data-testid":"feishu-register-cancel",className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:r("common:cancel",{defaultValue:"Cancel"})})]}),x&&e.jsxs("div",{className:"text-center space-y-2","data-testid":"feishu-qr",children:[e.jsx("div",{className:"inline-block p-3 bg-white rounded-xl shadow-sm border border-gray-200",children:e.jsx("img",{src:x,alt:"Feishu QR Code",className:"w-48 h-48"})}),e.jsx("p",{className:"text-xs text-fg-tertiary",children:r("settings:feishu.scanWithFeishu",{defaultValue:"Scan with the Feishu app to authorize."})})]}),u==="scanning"&&!x&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx("div",{className:"w-5 h-5 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})})]}),c&&e.jsx("div",{"data-testid":c.type==="ok"?"feishu-msg-ok":"feishu-msg-err",className:`px-3 py-2 rounded-lg text-xs ${c.type==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-600 border border-red-500/30"}`,children:c.text})]})}function Go({ctx:t}){const{t:r}=xe(["settings","common"]),[i,a]=o.useState(!1),[n,s]=o.useState(null),c=ga(t.status.fields),d=String(c?t.values[c.key]??"":"").trim(),u=t.instanceId,p=o.useCallback(async()=>{if(!d){s({type:"err",text:r("settings:feishu.chatIdRequired",{defaultValue:"Please select a group chat first"})});return}a(!0),s(null);try{const x=await F.settings.sendFeishuTestMessage({chatId:d,...u?{instanceId:u}:{}});s(x.success?{type:"ok",text:x.message??r("settings:feishu.testMsgSent",{defaultValue:"Test message sent"})}:{type:"err",text:x.message??r("settings:feishu.testMsgFailed",{defaultValue:"Failed to send test message"})})}catch(x){s({type:"err",text:x instanceof Error?x.message:String(x)})}finally{a(!1)}},[d,u,r]);return e.jsxs("div",{className:"space-y-2","data-testid":"feishu-test",children:[e.jsxs("button",{type:"button",onClick:p,disabled:i,"data-testid":"feishu-test-message",className:"inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium bg-surface-primary border border-border-default rounded-lg text-fg-secondary hover:bg-surface-overlay disabled:opacity-50 transition-colors",children:[i?e.jsx("div",{className:"w-3.5 h-3.5 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}):null,r("settings:feishu.sendTestMessage",{defaultValue:"Send test message"})]}),n&&e.jsx("div",{"data-testid":n.type==="ok"?"feishu-msg-ok":"feishu-msg-err",className:`px-3 py-2 rounded-lg text-xs ${n.type==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-600 border border-red-500/30"}`,children:n.text})]})}const Jo={feishu:{placement:"before",guidedSetup:{credentialFields:["appId","appSecret"]},render:t=>e.jsx(Wo,{ctx:t}),sendTest:t=>e.jsx(Go,{ctx:t})}};async function Yo(){return(await F.settings.listInstances()).instances??[]}async function Qo(){return(await F.settings.listIntegrations()).platforms??[]}function Zo({loadPlatforms:t=Qo,loadInstances:r=Yo,client:i=ja,extras:a=Jo,loadAgents:n,devMode:s=!1,defaultExpanded:c=!1}){const{t:d}=xe(["settings","common"]),[u,p]=o.useState([]),[x,k]=o.useState([]),[y,j]=o.useState(!0),[w,b]=o.useState(null),[S,h]=o.useState(null),[P,m]=o.useState(null),v=o.useCallback(async()=>{const[C,M]=await Promise.all([r(),t()]);p(C),k(M),b(null)},[r,t]);o.useEffect(()=>{let C=!1;return(async()=>{j(!0);try{const[M,B]=await Promise.all([r(),t()]);if(C)return;p(M),k(B),b(null)}catch(M){C||b(M instanceof Error?M.message:String(M))}finally{C||j(!1)}})(),()=>{C=!0}},[r,t]);const $=o.useMemo(()=>Xi(u),[u]),I=o.useCallback(C=>{const M=x.find(B=>B.id===C);return M?Oi(d,M):C},[x,d]),R=o.useMemo(()=>eo(x,u,{devMode:s}),[x,u,s]),V=o.useCallback(C=>{h(C)},[]);return y?e.jsxs("div",{"data-testid":"integrations-loading",className:"flex items-center justify-center py-16",children:[e.jsx("div",{className:"w-5 h-5 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),e.jsx("span",{className:"ml-2 text-sm text-fg-tertiary",children:d("common:loading",{defaultValue:"Loading…"})})]}):w?e.jsxs("div",{"data-testid":"integrations-error",className:"bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-sm text-red-600",children:[d("settings:integrations.loadFailed",{defaultValue:"Failed to load integrations"}),": ",w]}):e.jsxs("div",{"data-testid":"instances-section",className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-fg-tertiary",children:d("settings:instances.subtitle",{defaultValue:"Each bot is an instance: its own credentials, its own agent, its own chats. A platform can host several."})}),R.map(C=>{const B=$.find(L=>L.platform===C)?.instances??[];return e.jsxs("div",{"data-testid":`platform-group-${C}`,className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{id:C}),e.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:I(C)}),B.length>0&&e.jsx("span",{className:"text-[11px] text-fg-tertiary","data-testid":`platform-bot-count-${C}`,children:d("settings:instances.botCount",{defaultValue:"{{count}} bot(s)",count:B.length})}),e.jsx("div",{className:"flex-1"}),e.jsxs("button",{type:"button",onClick:()=>V(C),"data-testid":`add-bot-${C}`,className:"inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-brand-600 border border-brand-500/30 rounded-lg hover:bg-brand-500/10 transition-colors",children:["+ ",d("settings:instances.addBot.label",{defaultValue:"Add bot"})]})]}),S===C&&e.jsx(kn,{instance:Gi(x.find(L=>L.id===C)??{id:C,label:I(C),capabilities:{inbound:!1,outbound:!1,threads:!1},fields:[]}),client:i,extras:a,loadAgents:n,onChanged:v,onCreated:L=>{h(null),m(L)},defaultExpanded:!0}),B.map(L=>e.jsx(kn,{instance:L,client:i,extras:a,loadAgents:n,onChanged:v,defaultExpanded:c||L.id===P},L.id)),B.length===0&&S!==C&&e.jsx("p",{className:"text-[11px] text-fg-tertiary pl-7","data-testid":`platform-empty-${C}`,children:d("settings:instances.noBots",{defaultValue:"No bots yet."})})]},C)})]})}const Xo=["macos","linux","windows"];function el(){const{t}=xe(["settings","common"]),[r,i]=o.useReducer(ri,ni),[a,n]=o.useState(null),[s,c]=o.useState("linux"),[d,u]=o.useState(!1),[p,x]=o.useState(null),[k,y]=o.useState(null),[j,w]=o.useState(""),[b,S]=o.useState(!1),[h,P]=o.useState(null),[m,v]=o.useState(""),$=o.useRef(!0),I=Ot.isAuthenticated(),R=oa(),{kind:V,phase:C}=r,M=V?ai(V):null;o.useEffect(()=>{c(ii(typeof navigator>"u"?"":navigator.userAgent))},[]),o.useEffect(()=>($.current=!0,F.settings.getRemoteV2().then(f=>{$.current&&f&&i({type:"status",status:f})}).catch(()=>{}),F.settings.remoteDetect().then(f=>{$.current&&n(f)}).catch(()=>{$.current&&n(null)}),F.settings.remoteSetupTargets().then(f=>{$.current&&(P(f),v(K=>K||f.recommendedId||f.agents[0]?.id||""))}).catch(()=>{$.current&&P(null)}),()=>{$.current=!1}),[]),o.useEffect(()=>oi.on("remote:status",f=>{const K=li(f.payload);K&&i({type:"status",status:K})}),[]);const B=o.useCallback((f,K)=>{navigator.clipboard?.writeText(f),y(K),setTimeout(()=>y(z=>z===K?null:z),2e3)},[]),L=o.useCallback(async()=>{try{const f=await F.settings.getRemoteV2();return f&&i({type:"status",status:f}),f}catch{return null}},[]),U=o.useCallback(async()=>{try{await la()}catch{}},[]),H=f=>{x(null),S(!1),i({type:"selectKind",kind:f})},W=async()=>{x(null),i({type:"choosePath",path:"self"}),i({type:"beginInstall"}),i({type:"installSucceeded"});const f=await L();i(mi(f))},O=async()=>{const f=j.trim();if(f){u(!0),x(null);try{await F.settings.remoteTunnelRegister({kind:V??"custom",publicUrl:f}),i({type:"addressResolved",publicUrl:f}),await L()}catch(K){const z=String(K instanceof Error?K.message:K);x(z),i({type:"userError",message:z})}finally{u(!1)}}},_=()=>{x(null),i({type:"choosePath",path:"agent"})},X=async()=>{if(x(null),!V){x(t("settings:remoteAccess.path.agent.pickFirst"));return}u(!0);try{const f=await F.settings.remoteAgentSetup({kind:V,platform:s,...m?{agentId:m}:{},...R?.username?{username:R.username}:{}});f.ok&&f.agentId&&f.prompt?(i({type:"handedToChat",contract:f.contract??null}),ms.navigate(br.TEAM,{agentId:f.agentId,prefillMessage:f.prompt})):x(f.error??t("settings:remoteAccess.path.agent.unavailable"))}catch(f){const K=String(f instanceof Error?f.message:f);x(K||t("settings:remoteAccess.path.agent.unavailable"))}finally{u(!1)}},ce=async f=>{u(!0),x(null);try{f==="restart"?await F.settings.remoteTunnelRestart():f==="rotate"?await F.settings.remoteTunnelRotate():(await F.settings.remoteTunnelStop().catch(()=>{}),await F.settings.disableRemote().catch(()=>{})),f==="stop"?i({type:"reset"}):await L()}catch(K){x(String(K instanceof Error?K.message:K))}finally{u(!1)}},oe=()=>{ce("stop")},ee=r.entryUrl??di(R?.username??null),g=C==="ready"||C==="reconnecting",T=V?ui(V,s):null;return e.jsx(tl,{title:t("settings:remoteAccess.title"),children:e.jsxs("div",{className:"space-y-5",children:[e.jsx("p",{className:"text-sm text-content-secondary",children:t("settings:remoteAccess.description")}),I?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-content-secondary",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),t("settings:remoteAccess.signedInAs")," ",e.jsx("strong",{children:R?.username??R?.displayName})]}):e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-amber-500/10 border border-amber-500/20",children:[e.jsx(sl,{}),e.jsx("span",{className:"text-sm text-amber-600 dark:text-amber-400",children:t("settings:remoteAccess.loginRequired")}),e.jsx("button",{onClick:()=>{U()},className:"ml-auto px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",children:t("settings:remoteAccess.signIn")})]}),I&&e.jsx(e.Fragment,{children:g&&M?e.jsx(fl,{t,phase:C,meta:M,entryUrl:ee,publicUrl:r.publicUrl,health:r.health,latencyMs:r.latencyMs,message:r.message,busy:d,copied:k,onCopy:B,onRestart:()=>{ce("restart")},onRotate:()=>{ce("rotate")},onClose:oe}):e.jsxs(e.Fragment,{children:[e.jsx(dl,{t,detected:a,selected:V,onSelect:H}),V&&M&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(cl,{t,phase:C}),C==="error"&&e.jsx(gl,{t,message:r.message,verifyFailure:r.verifyFailure,showManual:b,manualUrl:j,busy:d,onToggleManual:()=>S(f=>!f),onManualChange:w,onManualSubmit:()=>{O()},onRetry:()=>{x(null),i({type:"verifyStarted"}),L()},onStartOver:()=>{x(null),S(!1),i({type:"reset"})}}),C==="reconnecting"&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-blue-500/10 border border-blue-500/20 text-sm text-blue-600 dark:text-blue-400",children:[e.jsx(Pa,{}),e.jsx("span",{children:t("settings:remoteAccess.wizard.reconnecting")})]}),e.jsx(ul,{t,setupPath:r.path,busy:d,onSelf:()=>i({type:"choosePath",path:"self"}),onAgent:()=>_()}),r.path==="self"&&T&&e.jsx(ml,{t,platform:s,onPlatform:c,commands:T,meta:M,detected:a,copied:k,onCopy:B,onDone:()=>{W()},busy:d}),r.path==="self"&&C==="resolve"&&e.jsx(xl,{t,value:j,busy:d,onChange:w,onSubmit:()=>{O()}}),r.path==="agent"&&e.jsxs("div",{className:"space-y-3",children:[h&&h.agents.length>0?e.jsxs("label",{className:"block text-sm",children:[e.jsx("span",{className:"text-content-secondary",children:t("settings:remoteAccess.path.agent.pickAgent")}),e.jsx("select",{className:"mt-1 w-full rounded-lg border border-border-default bg-surface-primary px-3 py-2 text-sm",value:m,onChange:f=>{v(f.target.value),i({type:"selectAgent",agentId:f.target.value})},children:h.agents.map(f=>e.jsxs("option",{value:f.id,children:[f.name,f.id===h.recommendedId?` — ${t("settings:remoteAccess.path.agent.recommended")}`:""]},f.id))})]}):e.jsx("div",{className:"p-3 rounded-xl bg-surface-secondary border border-border-default text-sm text-content-secondary",children:t("settings:remoteAccess.path.agent.noTargets")}),e.jsx("div",{className:"p-3 rounded-xl bg-surface-secondary border border-border-default text-sm text-content-secondary",children:r.handedToChat?t("settings:remoteAccess.path.agent.handed"):t("settings:remoteAccess.path.agent.desc")}),r.agentContract&&e.jsxs("div",{className:"p-3 rounded-xl bg-surface-secondary border border-border-default text-xs space-y-2",children:[e.jsx("div",{className:"font-semibold text-content-secondary",children:t("settings:remoteAccess.path.agent.willRun")}),e.jsx("ul",{className:"space-y-1",children:r.agentContract.commands.map(f=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"shrink-0",children:f.sensitive?t("settings:remoteAccess.path.agent.sensitive"):"›"}),e.jsx("code",{className:"break-all text-content-primary",children:f.run})]},f.id))})]}),V&&e.jsx("button",{type:"button",className:"w-full rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-500 disabled:opacity-50",disabled:d||!h||h.agents.length===0,onClick:()=>{X()},children:t("settings:remoteAccess.path.agent.handOff")})]}),p&&e.jsx("div",{className:"p-2 rounded-lg bg-red-500/10 text-red-500 text-sm",children:p})]})]})}),e.jsx(pl,{t})]})})}function tl({title:t,children:r}){return e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-4",children:t}),e.jsx("div",{className:"space-y-4",children:r})]})}function sl(){return e.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Pa(){return e.jsxs("svg",{className:"w-4 h-4 animate-spin text-content-secondary",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}function rl({url:t}){const r=o.useRef(null),[i,a]=o.useState(!1);return o.useEffect(()=>{const n=r.current;n&&(a(!1),xi(()=>Promise.resolve().then(()=>qo),void 0).then(s=>{s.toCanvas(n,t,{width:200,margin:2,color:{dark:"#000000",light:"#ffffff"},errorCorrectionLevel:"M"})}).catch(()=>a(!0)))},[t]),i?e.jsx("a",{href:t,target:"_blank",rel:"noopener",className:"text-sm text-brand-500 underline",children:t}):e.jsx("div",{className:"inline-block p-2 bg-white rounded-lg",children:e.jsx("canvas",{ref:r,className:"block",style:{width:160,height:160}})})}const nl={install:"settings:remoteAccess.stepInstall",start:"settings:remoteAccess.stepStart",resolve:"settings:remoteAccess.stepResolve",register:"settings:remoteAccess.stepRegister",verify:"settings:remoteAccess.stepVerify",ready:"settings:remoteAccess.stepReady"},wr={cloudflare_quick:{name:"settings:remoteAccess.methodCloudflareQuick",desc:"settings:remoteAccess.methodCloudflareQuickDesc"},cloudflare_named:{name:"settings:remoteAccess.methodCloudflareNamed",desc:"settings:remoteAccess.methodCloudflareNamedDesc"},tailscale_funnel:{name:"settings:remoteAccess.methodTailscaleFunnel",desc:"settings:remoteAccess.methodTailscaleFunnelDesc"},tailscale_serve:{name:"settings:remoteAccess.methodTailscaleServe",desc:"settings:remoteAccess.methodTailscaleServeDesc"},custom:{name:"settings:remoteAccess.methodCustom",desc:"settings:remoteAccess.methodCustomDesc"}},al={low:"settings:remoteAccess.barrierLow",medium:"settings:remoteAccess.barrierMedium",high:"settings:remoteAccess.barrierHigh"},il={high:"settings:remoteAccess.stabilityHigh",medium:"settings:remoteAccess.stabilityMedium",low:"settings:remoteAccess.stabilityLow"},ol={macos:"settings:remoteAccess.platformMacos",linux:"settings:remoteAccess.platformLinux",windows:"settings:remoteAccess.platformWindows"},ll={unreachable:"settings:remoteAccess.verifyReasonUnreachable",non_https:"settings:remoteAccess.verifyReasonNonHttps",blocked_target:"settings:remoteAccess.verifyReasonBlockedTarget",too_many_redirects:"settings:remoteAccess.verifyReasonTooManyRedirects",response_too_large:"settings:remoteAccess.verifyReasonResponseTooLarge",token_mismatch:"settings:remoteAccess.verifyReasonTokenMismatch",malformed_response:"settings:remoteAccess.verifyReasonMalformedResponse"};function dl({t,detected:r,selected:i,onSelect:a}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-content-tertiary uppercase tracking-wider mb-2",children:t("settings:remoteAccess.methodTitle")}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:ci.map(n=>{const s=i===n.kind,c=r&&n.binary?r[n.binary]:null;return e.jsxs("button",{type:"button",onClick:()=>a(n.kind),className:`text-left p-3 rounded-xl border transition-colors ${s?"border-brand-500 bg-brand-500/5":"border-border-default bg-surface-secondary hover:border-brand-400/60"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-content-primary",children:t(wr[n.kind].name)}),n.recommended&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] font-medium rounded bg-brand-500/15 text-brand-500",children:["★ ",t("settings:remoteAccess.badgeRecommended")]})]}),e.jsx("p",{className:"text-xs text-content-tertiary mt-1 leading-snug",children:t(wr[n.kind].desc)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[e.jsx(It,{children:t(al[n.barrier])}),e.jsx(It,{children:t(il[n.stability])}),e.jsx(It,{children:n.needsAccount?t("settings:remoteAccess.badgeNeedsAccount"):t("settings:remoteAccess.badgeNoAccount")}),e.jsx(It,{children:n.needsDomain?t("settings:remoteAccess.badgeNeedsDomain"):t("settings:remoteAccess.badgeNoDomain")}),c!==null&&e.jsxs(It,{tone:c?"good":"warn",children:[c?"✓ ":"✕ ",n.binary," ",t(c?"settings:remoteAccess.badgeDetected":"settings:remoteAccess.badgeNotDetected")]})]})]},n.kind)})})]})}function It({children:t,tone:r="default"}){const i=r==="good"?"bg-green-500/10 text-green-600 dark:text-green-400":r==="warn"?"bg-amber-500/10 text-amber-600 dark:text-amber-400":"bg-surface-inset text-content-tertiary";return e.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded ${i}`,children:t})}function cl({t,phase:r}){const i=gi(r),a=r==="error";return e.jsx("div",{className:"flex items-center gap-1",children:dn.map((n,s)=>{const c=i>=0&&s<i,d=i>=0&&s===i,u=a&&s===Math.max(0,i);return e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 min-w-0",children:[e.jsx("span",{className:`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-medium shrink-0 ${u?"bg-red-500 text-white":c?"bg-green-500 text-white":d?"bg-brand-600 text-white":"bg-surface-inset text-content-tertiary"}`,children:c?"✓":u?"!":s+1}),e.jsx("span",{className:`text-[10px] leading-tight text-center truncate ${d||u?"text-content-primary":"text-content-tertiary"}`,children:t(nl[n])})]}),s<dn.length-1&&e.jsx("span",{className:`h-px flex-1 ${c?"bg-green-500/50":"bg-border-default"}`})]},n)})})}function ul({t,setupPath:r,busy:i,onSelf:a,onAgent:n}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-content-tertiary uppercase tracking-wider mb-2",children:t("settings:remoteAccess.pathTitle")}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("button",{type:"button",onClick:a,className:`text-left p-3 rounded-xl border transition-colors ${r==="self"?"border-brand-500 bg-brand-500/5":"border-border-default bg-surface-secondary hover:border-brand-400/60"}`,children:[e.jsx("div",{className:"text-sm font-medium text-content-primary",children:t("settings:remoteAccess.pathSelfTitle")}),e.jsx("p",{className:"text-xs text-content-tertiary mt-1",children:t("settings:remoteAccess.pathSelfDesc")})]}),e.jsxs("button",{type:"button",onClick:n,disabled:i,className:`text-left p-3 rounded-xl border transition-colors disabled:opacity-60 ${r==="agent"?"border-brand-500 bg-brand-500/5":"border-border-default bg-surface-secondary hover:border-brand-400/60"}`,children:[e.jsx("div",{className:"text-sm font-medium text-content-primary",children:t("settings:remoteAccess.pathAgentTitle")}),e.jsx("p",{className:"text-xs text-content-tertiary mt-1",children:t("settings:remoteAccess.pathAgentDesc")})]})]})]})}function ml({t,platform:r,onPlatform:i,commands:a,meta:n,detected:s,copied:c,onCopy:d,onDone:u,busy:p}){const x=!!(n.binary&&s&&!s[n.binary]);return e.jsxs("div",{className:"p-3 rounded-xl bg-surface-secondary border border-border-default space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:Xo.map(k=>e.jsx("button",{type:"button",onClick:()=>i(k),className:`px-2 py-1 text-xs rounded-md transition-colors ${r===k?"bg-brand-600 text-white":"bg-surface-inset text-content-secondary hover:text-content-primary"}`,children:t(ol[k])},k))}),x&&n.binary&&e.jsx("div",{className:"text-xs text-amber-600 dark:text-amber-400",children:t("settings:remoteAccess.commandsMissingBinary",{binary:n.binary})}),["install","run"].map(k=>e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-content-tertiary mb-1",children:t(k==="install"?"settings:remoteAccess.commandsInstall":"settings:remoteAccess.commandsRun")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-2 text-xs bg-surface-inset rounded font-mono whitespace-pre-wrap break-all",children:a[k]}),e.jsx("button",{type:"button",onClick:()=>d(a[k],k),className:`px-2 py-1.5 text-xs border rounded transition-colors shrink-0 ${c===k?"border-green-500 text-green-600 dark:text-green-400":"border-border-default hover:bg-surface-elevated"}`,children:t(c===k?"settings:remoteAccess.commandsCopied":"settings:remoteAccess.commandsCopy")})]})]},k)),e.jsx("button",{type:"button",onClick:u,disabled:p,className:"w-full px-3 py-2 text-sm font-medium bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors disabled:opacity-60",children:t("settings:remoteAccess.commandsDone")})]})}function xl({t,value:r,busy:i,onChange:a,onSubmit:n}){return e.jsxs("div",{className:"p-3 rounded-xl bg-surface-secondary border border-border-default space-y-2",children:[e.jsx("p",{className:"text-xs text-content-secondary",children:t("settings:remoteAccess.addressPrompt")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:r,onChange:s=>a(s.target.value),placeholder:t("settings:remoteAccess.errorManualPlaceholder"),className:"flex-1 px-2 py-1.5 text-xs bg-surface-inset border border-border-default rounded font-mono"}),e.jsx("button",{type:"button",onClick:n,disabled:i||!r.trim(),className:"px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-white rounded-lg disabled:opacity-60",children:t("settings:remoteAccess.errorManualSubmit")})]})]})}function gl({t,message:r,verifyFailure:i,showManual:a,manualUrl:n,busy:s,onToggleManual:c,onManualChange:d,onManualSubmit:u,onRetry:p,onStartOver:x}){return e.jsxs("div",{className:"p-3 rounded-xl bg-red-500/10 border border-red-500/20 space-y-2",children:[e.jsx("div",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:t("settings:remoteAccess.errorTitle")}),e.jsx("p",{className:"text-xs text-content-secondary",children:i?t(ll[i]):r??t("settings:remoteAccess.errorGeneric")}),i==="unreachable"&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:t("settings:remoteAccess.errorBlockedHint")}),a&&e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("input",{type:"text",value:n,onChange:k=>d(k.target.value),placeholder:t("settings:remoteAccess.errorManualPlaceholder"),className:"flex-1 px-2 py-1.5 text-xs bg-surface-inset border border-border-default rounded font-mono"}),e.jsx("button",{type:"button",onClick:u,disabled:s||!n.trim(),className:"px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-white rounded-lg disabled:opacity-60",children:t("settings:remoteAccess.errorManualSubmit")})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("button",{type:"button",onClick:p,className:"px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-white rounded-lg",children:t("settings:remoteAccess.errorRetry")}),e.jsx("button",{type:"button",onClick:c,className:"px-3 py-1.5 text-xs border border-border-default rounded-lg hover:bg-surface-elevated",children:t("settings:remoteAccess.errorManualToggle")}),e.jsx("button",{type:"button",onClick:x,className:"ml-auto px-3 py-1.5 text-xs text-content-secondary hover:text-content-primary",children:t("settings:remoteAccess.errorStartOver")})]})]})}function fl({t,phase:r,meta:i,entryUrl:a,publicUrl:n,health:s,latencyMs:c,message:d,busy:u,copied:p,onCopy:x,onRestart:k,onRotate:y,onClose:j}){const w=r==="reconnecting",b=s==="up"&&!w;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${b?"bg-green-500 animate-pulse":w?"bg-blue-500 animate-pulse":"bg-amber-500"}`}),e.jsx("span",{className:"text-sm font-medium text-content-primary",children:t(b?"settings:remoteAccess.readyOnline":w?"settings:remoteAccess.wizard.reconnecting":"settings:remoteAccess.readyDegraded")}),b&&c!=null&&e.jsx("span",{className:"text-xs text-content-tertiary",children:t("settings:remoteAccess.readyLatency",{ms:c})}),e.jsxs("span",{className:"text-xs text-content-tertiary",children:["· ",t(wr[i.kind].name)]})]}),w&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-blue-600 dark:text-blue-400",children:[e.jsx(Pa,{}),t("settings:remoteAccess.wizard.reconnectingHint")]}),!w&&d&&e.jsx("div",{className:"text-xs text-amber-600 dark:text-amber-400",children:d}),a&&e.jsxs("div",{className:"p-3 rounded-xl bg-surface-elevated border border-border-default space-y-2",children:[e.jsx("div",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:t("settings:remoteAccess.readyEntry")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-1.5 text-sm bg-surface-inset rounded font-mono truncate",children:a}),e.jsx("button",{type:"button",onClick:()=>x(a,"entry"),className:`px-2 py-1.5 text-xs border rounded transition-colors shrink-0 ${p==="entry"?"border-green-500 text-green-600 dark:text-green-400":"border-border-default hover:bg-surface-elevated"}`,children:t(p==="entry"?"settings:remoteAccess.copied":"settings:remoteAccess.copy")})]}),e.jsx("p",{className:"text-xs text-content-secondary",children:t("settings:remoteAccess.readyEntryHint")}),e.jsxs("div",{className:"pt-1",children:[e.jsx(rl,{url:a}),e.jsx("p",{className:"text-xs text-content-tertiary mt-1",children:t("settings:remoteAccess.readyScanQr")})]}),e.jsx("p",{className:"text-xs text-content-tertiary",children:t("settings:remoteAccess.readyAuthGateNote")})]}),n&&e.jsxs("div",{className:"p-3 rounded-xl bg-surface-secondary border border-border-default space-y-1",children:[e.jsx("div",{className:"text-xs text-content-tertiary uppercase tracking-wider",children:t("settings:remoteAccess.readyPublicUrl")}),e.jsx("code",{className:"block text-xs font-mono break-all text-content-secondary",children:n}),e.jsx("p",{className:"text-xs text-content-tertiary",children:t("settings:remoteAccess.readyAddressBarNote")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",onClick:k,disabled:u,className:"px-3 py-1.5 text-xs border border-border-default rounded-lg hover:bg-surface-elevated disabled:opacity-60",children:t("settings:remoteAccess.readyRestart")}),e.jsx("button",{type:"button",onClick:y,disabled:u,className:"px-3 py-1.5 text-xs border border-border-default rounded-lg hover:bg-surface-elevated disabled:opacity-60",children:t("settings:remoteAccess.readyRotate")}),e.jsx("button",{type:"button",onClick:j,disabled:u,className:"ml-auto px-3 py-1.5 text-xs text-red-600 dark:text-red-400 border border-red-500/30 rounded-lg hover:bg-red-500/10 disabled:opacity-60",children:t("settings:remoteAccess.readyClose")})]})]})}function pl({t}){const[r,i]=o.useState(!1),a=[t("settings:remoteAccess.tipAddressBar"),t("settings:remoteAccess.tipRateLimit"),t("settings:remoteAccess.tipRandomDomain"),t("settings:remoteAccess.tipChina"),t("settings:remoteAccess.tipSecurity"),t("settings:remoteAccess.tipSecuritySteps")];return e.jsxs("div",{className:"rounded-xl border border-border-default bg-surface-secondary",children:[e.jsxs("button",{type:"button",onClick:()=>i(n=>!n),className:"flex items-center justify-between w-full px-3 py-2 text-sm text-content-secondary hover:text-content-primary",children:[e.jsx("span",{children:t("settings:remoteAccess.tipsTitle")}),e.jsx("span",{className:`transition-transform ${r?"":"-rotate-90"}`,children:"▾"})]}),r&&e.jsx("ul",{className:"px-4 pb-3 space-y-1.5 list-disc list-inside",children:a.map((n,s)=>e.jsx("li",{className:"text-xs text-content-tertiary leading-snug",children:n},s))})]})}const Bt=[{id:"serper",labelKey:"searchApi.serper",hintKey:"searchApi.serperHint",field:"serperApiKey"},{id:"tavily",labelKey:"searchApi.tavily",hintKey:"searchApi.tavilyHint",field:"tavilyApiKey"},{id:"google",labelKey:"searchApi.google",hintKey:"searchApi.googleHint",field:"googleSearchApiKey",extraField:"googleSearchCx",extraPlaceholderKey:"searchApi.googleCxPlaceholder"},{id:"bing",labelKey:"searchApi.bing",hintKey:"searchApi.bingHint",field:"bingApiKey"},{id:"brave",labelKey:"searchApi.brave",hintKey:"searchApi.braveHint",field:"braveApiKey"},{id:"serpapi",labelKey:"searchApi.serpapi",hintKey:"searchApi.serpapiHint",field:"serpApiKey"},{id:"exa",labelKey:"searchApi.exa",hintKey:"searchApi.exaHint",field:"exaApiKey"},{id:"bocha",labelKey:"searchApi.bocha",hintKey:"searchApi.bochaHint",field:"bochaApiKey"}],hl=800,Xn=[{id:"perplexity/sonar",labelKey:"searchApi.modelSonar"},{id:"perplexity/sonar-pro",labelKey:"searchApi.modelSonarPro"}];function ea({expanded:t}){return e.jsx("svg",{className:`w-4 h-4 text-fg-tertiary transition-transform ${t?"rotate-90":""}`,viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})}function us({className:t="w-3 h-3"}){return e.jsxs("svg",{className:`${t} animate-spin`,viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}function bl(){const{t}=xe(["settings","common"]),[r,i]=o.useState(null),[a,n]=o.useState(!0),[s,c]=o.useState(new Set),[d,u]=o.useState({}),[p,x]=o.useState({}),[k,y]=o.useState(!1),[j,w]=o.useState(!1),[b,S]=o.useState({}),[h,P]=o.useState({}),[m,v]=o.useState({}),[$,I]=o.useState({}),R=o.useRef({}),V=o.useCallback(async()=>{n(!0);try{const g=await F.settings.getSearch();g&&(i(g),Bt.some(f=>!!g[f.id]?.configured)&&w(!0))}catch{}n(!1)},[]);o.useEffect(()=>{V()},[V]),o.useEffect(()=>()=>{Object.values(R.current).forEach(clearTimeout)},[]);const C=g=>{c(T=>{const f=new Set(T);return f.has(g)?f.delete(g):f.add(g),f})},M=(g,T,f)=>{u(K=>({...K,[T]:f})),R.current[g]&&clearTimeout(R.current[g]),R.current[g]=setTimeout(()=>{B(g)},hl)},B=async g=>{const T=Bt.find(z=>z.id===g);if(!T)return;const f=d[T.field]?.trim(),K=T.extraField?d[T.extraField]?.trim():void 0;if(!(!f&&!K)){x(z=>({...z,[g]:!0})),S(z=>{const se={...z};return delete se[g],se});try{const z={};f&&(z[T.field]=f),K&&T.extraField&&(z[T.extraField]=K);const se=await F.settings.updateSearch(z);i(se),u(ae=>{const ge={...ae};return delete ge[T.field],T.extraField&&delete ge[T.extraField],ge}),S(ae=>({...ae,[g]:{type:"ok",text:t("searchApi.saved")}})),setTimeout(()=>S(ae=>{const ge={...ae};return delete ge[g],ge}),3e3)}catch{S(z=>({...z,[g]:{type:"err",text:t("searchApi.failedToSave")}}))}x(z=>({...z,[g]:!1}))}},L=g=>r?.[g],U=g=>L(g)?.configured??!1,H=g=>L(g)?.enabled!==!1,W=async(g,T)=>{I(f=>({...f,[g]:!0}));try{const f={[`${g}Enabled`]:T},K=await F.settings.updateSearch(f);i(K)}catch{}I(f=>({...f,[g]:!1}))},O=async g=>{R.current[g]&&(clearTimeout(R.current[g]),delete R.current[g],await B(g)),P(T=>({...T,[g]:!0})),v(T=>{const f={...T};return delete f[g],f});try{const T=await F.settings.testSearch(g);if(T.ok){const f=[t("searchApi.testOk",{count:T.count??0})];T.latencyMs!=null&&f.push(`${T.latencyMs}ms`),T.sample?.title&&f.push(T.sample.title.slice(0,48)),v(K=>({...K,[g]:{ok:!0,text:f.join(" · ")}}))}else v(f=>({...f,[g]:{ok:!1,text:T.error||t("searchApi.testFailed")}}))}catch{v(T=>({...T,[g]:{ok:!1,text:t("searchApi.testFailed")}}))}P(T=>({...T,[g]:!1}))},_=async g=>{y(!0);try{const T=await F.settings.updateSearch(g);i(T)}catch{}y(!1)},X=({id:g,disabled:T})=>{const f=h[g];return e.jsxs("button",{type:"button",onClick:()=>{O(g)},disabled:f||T,className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium bg-surface-primary border border-border-default text-fg-secondary hover:text-fg-primary hover:border-brand-500 disabled:opacity-50 transition-colors",children:[f?e.jsx(us,{}):e.jsx("svg",{className:"w-3 h-3",viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M8.5 2a6.5 6.5 0 104.096 11.553l3.925 3.925a.75.75 0 101.06-1.06l-3.925-3.925A6.5 6.5 0 008.5 2zM3.5 8.5a5 5 0 1110 0 5 5 0 01-10 0z",clipRule:"evenodd"})}),t(f?"searchApi.testing":"searchApi.test")]})},ce=({id:g})=>{const T=m[g];return T?e.jsxs("div",{className:`text-[11px] flex items-start gap-1.5 ${T.ok?"text-green-500":"text-red-500"}`,children:[e.jsx("span",{className:"shrink-0 mt-px",children:T.ok?"✓":"✕"}),e.jsx("span",{className:"break-all",children:T.text})]}):null},oe=({id:g})=>{const T=H(g),f=$[g];return e.jsxs("label",{className:"inline-flex items-center gap-2 cursor-pointer shrink-0",onClick:K=>K.stopPropagation(),title:t(T?"searchApi.enabled":"searchApi.disabled"),children:[f&&e.jsx(us,{className:"w-3 h-3 text-fg-tertiary"}),e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:T,disabled:f,onChange:K=>{W(g,K.target.checked)}}),e.jsx("span",{className:"relative w-9 h-5 rounded-full bg-gray-500/40 peer-checked:bg-brand-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:w-4 after:h-4 after:rounded-full after:bg-white after:transition-transform peer-checked:after:translate-x-4"})]})},ee=r?.markus;return e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-4",children:t("searchApi.title")}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:t("searchApi.description")}),a?e.jsx("div",{className:"text-sm text-fg-tertiary py-8 text-center",children:t("common:loading")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-border-default px-4 py-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t("searchApi.markus")}),e.jsx("span",{className:"text-[10px] font-medium text-brand-400",children:t("searchApi.markusBadge")})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 truncate",children:t("searchApi.markusHint")})]}),ee?.available&&ee.enabled&&e.jsx(X,{id:"markus"}),ee?.available?e.jsxs("label",{className:"inline-flex items-center gap-2 cursor-pointer shrink-0",children:[k&&e.jsx(us,{className:"w-3 h-3 text-fg-tertiary"}),e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:ee.enabled,disabled:k,onChange:g=>{_({useMarkusHosted:g.target.checked})}}),e.jsx("span",{className:"relative w-9 h-5 rounded-full bg-gray-500/40 peer-checked:bg-brand-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:w-4 after:h-4 after:rounded-full after:bg-white after:transition-transform peer-checked:after:translate-x-4"})]}):e.jsx("span",{className:"text-[11px] text-amber-500 shrink-0",children:t("searchApi.markusUnavailable")})]}),!ee?.available&&e.jsx("div",{className:"text-[11px] text-amber-500/90",children:t("searchApi.markusUnavailableHint")}),ee?.available&&ee.enabled&&e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("label",{className:"text-[11px] text-fg-tertiary shrink-0",htmlFor:"markus-search-model",children:t("searchApi.modelLabel")}),e.jsxs("select",{id:"markus-search-model",value:ee.markusSearchModel||"perplexity/sonar",disabled:k,onChange:g=>{_({markusSearchModel:g.target.value})},className:"flex-1 min-w-0 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary outline-none focus:border-brand-500",children:[Xn.map(g=>e.jsx("option",{value:g.id,children:t(g.labelKey)},g.id)),ee.markusSearchModel&&!Xn.some(g=>g.id===ee.markusSearchModel)&&e.jsx("option",{value:ee.markusSearchModel,children:ee.markusSearchModel})]})]}),e.jsx("div",{className:"text-[11px] text-fg-tertiary",children:t("searchApi.modelHint")}),e.jsx(ce,{id:"markus"})]}),e.jsxs("div",{className:"rounded-xl border border-border-default overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>w(g=>!g),className:"w-full flex items-center gap-3 px-4 py-2.5 hover:bg-white/[0.02] transition-colors text-left",children:[e.jsx(ea,{expanded:j}),e.jsxs("div",{className:"flex-1 min-w-0 flex items-baseline gap-2 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t("searchApi.ownKeysTitle")}),e.jsx("span",{className:"text-xs text-fg-tertiary truncate",children:t("searchApi.ownKeysHint")})]}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary shrink-0 tabular-nums",children:[Bt.filter(g=>U(g.id)).length,"/",Bt.length]})]}),j&&e.jsx("div",{className:"border-t border-border-default px-2 pb-2 space-y-1",children:Bt.map(g=>{const T=U(g.id),f=s.has(g.id),K=b[g.id],z=p[g.id];return e.jsxs("div",{className:"rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsxs("button",{type:"button",onClick:()=>C(g.id),className:`flex-1 min-w-0 flex items-center gap-3 px-3 py-2.5 hover:bg-white/[0.02] transition-colors text-left ${T&&!H(g.id)?"opacity-50":""}`,children:[e.jsx(ea,{expanded:f}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t(g.labelKey)}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-2 hidden sm:inline",children:t(g.hintKey)})]}),e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:T?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-400"}),e.jsx("span",{className:"text-[10px] font-medium text-green-500",children:t("searchApi.configured")})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-500"}),e.jsx("span",{className:"text-[10px] font-medium text-fg-tertiary",children:t("searchApi.notConfigured")})]})})]}),e.jsx("div",{className:"shrink-0 pr-3 pl-2 border-l border-border-default self-stretch flex items-center",children:e.jsx(oe,{id:g.id})})]}),f&&e.jsx("div",{className:"px-3 pb-3",children:e.jsxs("div",{className:"mt-1 space-y-2",children:[e.jsx("input",{type:"password",value:d[g.field]??"",onChange:se=>M(g.id,g.field,se.target.value),placeholder:t(T?"modelProviders.apiKeyPlaceholder":"searchApi.apiKeyPlaceholder"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none font-mono"}),g.extraField&&e.jsx("input",{type:"text",value:d[g.extraField]??"",onChange:se=>M(g.id,g.extraField,se.target.value),placeholder:g.extraPlaceholderKey?t(g.extraPlaceholderKey):"",className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none font-mono"}),e.jsxs("div",{className:"flex items-center gap-2 min-h-[28px] flex-wrap",children:[e.jsx(X,{id:g.id,disabled:!T&&!d[g.field]?.trim()}),z&&e.jsxs("span",{className:"text-[10px] text-fg-tertiary flex items-center gap-1",children:[e.jsx(us,{}),t("common:saving")]}),K&&e.jsx("span",{className:`text-[10px] ${K.type==="ok"?"text-green-500":"text-red-500"}`,children:K.text})]}),e.jsx(ce,{id:g.id})]})})]},g.id)})})]})]})]})]})}const Ma=[{id:"appearance",labelKey:"nav.appearance"},{id:"storage",labelKey:"nav.storage",adminOnly:!0},{id:"providers",labelKey:"nav.providers",adminOnly:!0},{id:"execution",labelKey:"nav.execution",adminOnly:!0},{id:"browser",labelKey:"nav.browser",adminOnly:!0},{id:"search",labelKey:"nav.search",adminOnly:!0},{id:"integrations",labelKey:"nav.integrations",adminOnly:!0},{id:"remote",labelKey:"nav.remote",adminOnly:!0},{id:"account",labelKey:"nav.account"}],gr=[{labelKey:"nav.group.general",tabs:["appearance","storage"]},{labelKey:"nav.group.aiConfig",tabs:["providers","execution"]},{labelKey:"nav.group.tools",tabs:["browser","search"]},{labelKey:"nav.group.connections",tabs:["integrations","remote"]},{labelKey:"nav.group.account",tabs:["account"]}],yl={Database:"database",Agents:"agents",Skills:"skills","LLM Logs":"llmLogs","Builder Artifacts":"builderArtifacts",Teams:"teams",Shared:"shared",Knowledge:"knowledge"},fr={Database:"keep",Agents:"keep",Skills:"caution","LLM Logs":"safe","Builder Artifacts":"caution",Teams:"keep",Shared:"caution",Knowledge:"caution"},ta={appearance:"M21 4H14 M10 4H3 M21 12H12 M8 12H3 M21 20H16 M12 20H3 M14 2v4 M8 10v4 M16 18v4",storage:"M12 8c4.418 0 8-1.343 8-3s-3.582-3-8-3-8 1.343-8 3 3.582 3 8 3Z M4 5v6c0 1.657 3.582 3 8 3s8-1.343 8-3V5 M4 11v6c0 1.657 3.582 3 8 3s8-1.343 8-3v-6",providers:"M9 2v3 M15 2v3 M9 19v3 M15 19v3 M2 9h3 M2 15h3 M19 9h3 M19 15h3 M6 6h12v12H6z M9 9h6v6H9z",execution:"M12 8V4H8 M4 8h16a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2z M2 14h2 M20 14h2 M15 13v2 M9 13v2",browser:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M2 12h20 M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z","coding-tools":"M16 18l6-6-6-6 M8 6l-6 6 6 6",search:"M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z M21 21l-4.3-4.3",integrations:"M9 17H7A5 5 0 0 1 7 7h2 M15 7h2a5 5 0 1 1 0 10h-2 M8 12h8",remote:"M2 8.5a15 15 0 0 1 20 0 M5 12a10 10 0 0 1 14 0 M8.5 15.5a5 5 0 0 1 7 0 M12 19h.01",account:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2 M12 7a4 4 0 1 0 0 8 4 4 0 0 0 0-8Z",_default:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"};function sa({id:t,className:r}){return e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 ${r??""}`,children:e.jsx("path",{d:ta[t]??ta._default})})}const vl={users:"account",organization:"account",license:"account"};function jl(t){const i=(t.startsWith("#")?t.slice(1):t).split("/");if(i[0]==="settings"&&i[1]){const a=i[1],s=vl[a]??a;if(Ma.some(c=>c.id===s))return s}return null}function ra(){return jl(window.location.hash)}function Fl({theme:t,onThemeChange:r,authUser:i,onLogout:a,onUserUpdated:n}={}){const{t:s,i18n:c}=xe(["settings","common"]),d=fi(),u=pi(br.SETTINGS),p=hi(),x=p?.keyboardPane??"content",[k,y]=o.useState(ra),[j,w]=o.useState(!1);o.useEffect(()=>{const l=()=>y(ra());return window.addEventListener("hashchange",l),()=>window.removeEventListener("hashchange",l)},[]);const b=o.useCallback(l=>{y(l),history.pushState(null,"",`#settings/${l}`)},[]),S=o.useCallback(()=>{y(null),history.pushState(null,"","#settings")},[]),h=k??(d?null:"appearance"),[P,m]=o.useState(!1),[v,$]=o.useState(!1);o.useEffect(()=>{!cn()||!window.markusDesktop?.getLoginItemSettings||window.markusDesktop.getLoginItemSettings().then(l=>m(!!l.openAtLogin)).catch(()=>{})},[]);const I=o.useCallback(async()=>{if(!window.markusDesktop?.setLoginItemSettings||v)return;const l=!P;$(!0),m(l);try{const N=await window.markusDesktop.setLoginItemSettings(l);m(!!N.openAtLogin)}catch{m(!l)}finally{$(!1)}},[P,v]),[R,V]=o.useState(null),[C,M]=o.useState(null),[B,L]=o.useState(""),[U,H]=o.useState(!1),[W,O]=o.useState(null),[_,X]=o.useState(null),[ce,oe]=o.useState(null),[ee,g]=o.useState({}),[T,f]=o.useState(null),[K,z]=o.useState(null),[se,ae]=o.useState(null),[ge,te]=o.useState(!1),[Je,Ae]=o.useState(null),[Se,Be]=o.useState({}),[ot,we]=o.useState(!1),[fe,Ft]=o.useState(null),[Ye,vt]=o.useState(!1),[De,lt]=o.useState(""),[Ut,Kt]=o.useState(!1),[Qe,Ee]=o.useState(null),[jt,Ht]=o.useState(""),[ye,_e]=o.useState(!0),[Ne,Nt]=o.useState(null),[wt,Ze]=o.useState(!1),[Fe,Xe]=o.useState(null),[kt,Ct]=o.useState([]),[zt,et]=o.useState([]),[tt,Oe]=o.useState(null),[St,je]=o.useState(null),[st,qt]=o.useState(""),[Wt,rt]=o.useState(null),[Ue,ne]=o.useState(null),pe=o.useRef(null),Gt=o.useRef(!1),E=o.useRef(!1),[re,le]=o.useState(200),[Ke,At]=o.useState(20),[Jt,Yt]=o.useState(!1),[ys,He]=o.useState(null),[dt,vs]=o.useState(!1),[Sr,js]=o.useState(3),[Ar,Ns]=o.useState("auto"),[Pr,Mr]=o.useState(!1),[ws,ct]=o.useState(null),[ut,ks]=o.useState("embedded"),[Qt,Cs]=o.useState("direct"),[Ss,Zt]=o.useState(!1),[Tr,As]=o.useState(0),[Ps,Xt]=o.useState(!0),[Ms,es]=o.useState(!1),[ze,Er]=o.useState(!1),[Bl,Ta]=o.useState(9333),[he,ue]=o.useState(!1),[Ts,Z]=o.useState(null),[$e,Ea]=o.useState(null),[Es,Lr]=o.useState(!1),[ts,La]=o.useState(null),[Dl,Ol]=o.useState(!1),me=()=>({"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("markus_token")??""}`}),Rr=o.useRef(new Set),Ir=o.useCallback(()=>{F.health().then(V).catch(()=>{})},[]),qe=o.useCallback(()=>{fetch("/api/settings/llm").then(l=>l.ok?l.json():Promise.reject(l.status)).then(l=>{l&&typeof l=="object"&&"providers"in l&&(M(l),L(l.defaultProvider))}).catch(()=>{})},[]),Pt=o.useCallback(()=>{fetch("/api/settings/network").then(l=>l.ok?l.json():Promise.reject(l.status)).then(l=>{Ht(l.network?.proxy??""),_e(l.network?.proxyEnabled!==!1),Nt(l.effective)}).catch(()=>{})},[]),Br=o.useCallback(()=>{fetch("/api/settings/oauth/providers").then(l=>l.ok?l.json():Promise.reject(l.status)).then(l=>Ct(l.providers??[])).catch(()=>{})},[]),ss=o.useCallback((l=!1)=>{fetch(`/api/settings/oauth/profiles${l?"?validate=1":""}`,{headers:me()}).then(D=>D.ok?D.json():Promise.reject(D.status)).then(D=>et(D.profiles??[])).catch(()=>{})},[]),Dr=o.useCallback(()=>{F.settings.getAgent().then(l=>{l&&typeof l.maxToolIterations=="number"&&le(l.maxToolIterations),l&&typeof l.maxPendingTasksPerAgent=="number"&&At(l.maxPendingTasksPerAgent),l?.concurrent&&(vs(l.concurrent.enabled??!0),js(l.concurrent.maxWorkers??3),Ns(l.concurrent.conflictPolicy??"auto"))}).catch(()=>{})},[]),Or=o.useCallback(()=>{F.settings.getBrowser().then(l=>{l&&(ks(l.mode??"embedded"),Cs(l.elementSelection??"direct"),Zt(l.bringToFront??!1),As(l.remoteDebuggingPort??0),Xt(l.autoCloseTabs??!0),es(l.autoClickAllowDialog??!1),Er(l.extensionConnected??!1),Ta(l.extensionBridgePort??9333))}).catch(()=>{})},[]),mt=o.useCallback(()=>{Lr(!0),F.system.storage().then(Ea).catch(()=>{}).finally(()=>Lr(!1)),F.system.orphans().then(La).catch(()=>{})},[]);o.useEffect(()=>{Ir()},[Ir]),o.useEffect(()=>{if(h&&!Rr.current.has(h))switch(Rr.current.add(h),h){case"providers":qe(),Pt(),Br(),ss(!0);break;case"execution":Dr();break;case"browser":Or();break;case"storage":mt();break}},[h,qe,Pt,Br,ss,Dr,Or,mt]),o.useEffect(()=>{const l=()=>mt();return window.addEventListener("markus:data-changed",l),()=>window.removeEventListener("markus:data-changed",l)},[mt]),o.useEffect(()=>{!_||ee[_]||(f(_),_==="markus"&&z(null),F.modelCatalog.getLive(_).then(l=>{g(N=>({...N,[_]:l.models})),_==="markus"&&(l.error&&z(String(l.error)),qe())}).catch(l=>{_==="markus"&&z(l instanceof Error?l.message:String(l)),F.modelCatalog.getByProvider(_).then(N=>{g(D=>({...D,[_]:N.models}))}).catch(()=>{})}).finally(()=>f(null)))},[_]);const Ls=o.useCallback(async()=>{te(!0),Ae(null),ae(null),Be({});try{const l=await fetch("/api/settings/env-models",{headers:me()});if(!l.ok){Ae({type:"err",text:s("envConfig.detectionFailedHttp",{status:l.status})});return}const N=await l.json();if(ae(N),N.detected.length===0)Ae({type:"err",text:s("envConfig.noKeysFound")});else{const D={};for(const G of N.detected)D[G.provider]=!0;Be(D)}}catch{Ae({type:"err",text:s("envConfig.failedToDetect")})}finally{te(!1)}},[s]),Mt=o.useCallback(async()=>{vt(!0),Ee(null),Ft(null);try{const l=await fetch("/api/settings/detect-ollama",{headers:me()});if(!l.ok){Ee({type:"err",text:s("ollama.detectFailed")});return}const N=await l.json();Ft(N),N.found&&N.models&&N.models.length>0?lt(N.models[0].name):N.found||Ee({type:"err",text:N.error||s("ollama.notRunning")})}catch{Ee({type:"err",text:s("ollama.detectFailed")})}finally{vt(!1)}},[s]),$r=C?Object.values(C.providers).some(l=>l.configured):!1;o.useEffect(()=>{C&&!$r&&!Gt.current&&(Gt.current=!0,Ls(),Mt())},[C,$r,Ls,Mt]),o.useEffect(()=>{_==="ollama"&&!fe&&!Ye&&!E.current&&(E.current=!0,Mt())},[_,fe,Ye,Mt]);const Ra=async()=>{if(!(!B||B===C?.defaultProvider)){H(!0),O(null);try{const l=await fetch("/api/settings/llm",{method:"POST",headers:me(),body:JSON.stringify({defaultProvider:B})}),N=await l.json();l.ok?(M(N),O({type:"ok",text:s("defaultProvider.updated",{name:N.defaultProvider})})):O({type:"err",text:N.error??s("modelProviders.saveFailed")})}catch{O({type:"err",text:s("common:networkError")})}finally{H(!1)}}},Ia=async(l,N)=>{oe(l);try{const D=await fetch(`/api/settings/llm/providers/${l}/toggle`,{method:"POST",headers:me(),body:JSON.stringify({enabled:N})});if(D.ok){const G=await D.json();M(G)}}catch{}finally{oe(null)}},Ba=async()=>{if(!se)return;const l=se.detected.filter(N=>Se[N.provider]);if(l.length===0){Ae({type:"err",text:s("envConfig.selectAtLeastOne")});return}we(!0),Ae(null);try{const N=await fetch("/api/settings/env-models",{method:"POST",headers:me(),body:JSON.stringify({providers:l.map(G=>({provider:G.provider,model:G.model,baseUrl:G.baseUrl,enabled:!0}))})});if(!N.ok){Ae({type:"err",text:s("envConfig.applyFailed",{status:N.status})});return}const D=await N.json();Ae({type:"ok",text:D.message}),ae(null),Be({}),qe()}catch{Ae({type:"err",text:s("envConfig.failedToApply")})}finally{we(!1)}},Da=async()=>{if(!(!fe?.found||!De)){Kt(!0),Ee(null);try{const l=await fetch("/api/settings/llm/providers",{method:"POST",headers:me(),body:JSON.stringify({name:"ollama",model:De,baseUrl:fe.baseUrl||"http://localhost:11434"})});if(l.ok){const N=await l.json();M(N),Ee({type:"ok",text:s("ollama.configured",{model:De})})}else{const N=await l.json();Ee({type:"err",text:N.error||s("ollama.applyFailed")})}}catch{Ee({type:"err",text:s("ollama.applyFailed")})}finally{Kt(!1)}}},Vr=async l=>{Oe(l),je(null);try{const N=await fetch("/api/settings/oauth/login",{method:"POST",headers:me(),body:JSON.stringify({provider:l})}),D=await N.json();if(!N.ok||D.error){je({type:"err",text:D.error??s("oauth.loginFailed")});return}D.authorizeUrl&&(window.open(D.authorizeUrl,"_blank","noopener"),rt(l),je({type:"ok",text:s("browserOpened")}),pe.current&&clearInterval(pe.current),pe.current=setInterval(async()=>{try{const Y=await(await fetch(`/api/settings/oauth/status?provider=${l}`,{headers:me()})).json();!Y.pending&&Y.profiles.some(J=>J.provider===l&&J.hasOAuth)&&(pe.current&&clearInterval(pe.current),pe.current=null,rt(null),et(Y.profiles),je({type:"ok",text:s("oauthConnected",{provider:l})}),qe())}catch{}},2e3))}catch{je({type:"err",text:s("oauth.networkErrorDuringLogin")})}finally{Oe(null)}},Oa=async l=>{Oe(l),je(null),ne(null);try{const N=await fetch("/api/settings/oauth/device-code",{method:"POST",headers:me(),body:JSON.stringify({provider:l})}),D=await N.json();if(!N.ok||D.error){je({type:"err",text:D.error??s("oauthAuth.deviceCodeFailed")});return}D.userCode&&D.verificationUri&&(ne({userCode:D.userCode,verificationUri:D.verificationUri,provider:l}),rt(l),je({type:"ok",text:s("oauthAuth.deviceInstructions")}),pe.current&&clearInterval(pe.current),pe.current=setInterval(async()=>{try{const Y=await(await fetch(`/api/settings/oauth/status?provider=${l}`,{headers:me()})).json();!Y.pending&&Y.profiles.some(J=>J.provider===l&&J.hasOAuth)&&(pe.current&&clearInterval(pe.current),pe.current=null,rt(null),ne(null),et(Y.profiles),je({type:"ok",text:s("oauthConnected",{provider:l})}),qe())}catch{}},3e3))}catch{je({type:"err",text:s("oauth.networkErrorDuringLogin")})}finally{Oe(null)}},$a=async()=>{if(st.trim()){Oe("manual"),je(null);try{const l=await fetch("/api/settings/oauth/callback",{method:"POST",headers:me(),body:JSON.stringify({callbackUrl:st})}),N=await l.json();if(!l.ok||N.error){je({type:"err",text:N.error??s("oauth.callbackFailed")});return}je({type:"ok",text:s("oauthConnected",{provider:N.profile?.provider??s("common:unknown")})}),qt(""),rt(null),pe.current&&(clearInterval(pe.current),pe.current=null),ss(),qe()}catch{je({type:"err",text:s("common:networkError")})}finally{Oe(null)}}},Va=async l=>{try{(await fetch(`/api/settings/oauth/profiles/${encodeURIComponent(l)}`,{method:"DELETE",headers:me()})).ok&&(ss(),qe(),je({type:"ok",text:s("authProfileDeleted")}))}catch{}};o.useEffect(()=>()=>{pe.current&&clearInterval(pe.current)},[]),o.useEffect(()=>{if(h!=="browser"||ze)return;const l=setInterval(async()=>{try{(await F.settings.getBrowser()).extensionConnected&&(Er(!0),clearInterval(l))}catch{}},5e3);return()=>clearInterval(l)},[h,ze]);const[_a,Rs]=o.useState(!1),[de,We]=o.useState({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),[rs,_r]=o.useState(!1),[Is,Fr]=o.useState(null),[Bs,nt]=o.useState([]),[Fa,Ur]=o.useState(!1),[Ua,Ds]=o.useState(null),[ve,Os]=o.useState({apiKey:"",baseUrl:"",model:"",contextWindow:0,maxOutputTokens:0,costInput:0,costOutput:0}),[Kr,Hr]=o.useState(!1),[zr,qr]=o.useState(null),[$s,Vs]=o.useState(null),[Ve,xt]=o.useState(""),[Wr,Gr]=o.useState(!1),[_s,ke]=o.useState(null),[Jr,ns]=o.useState(null),as=Ri(),[Pe,is]=o.useState({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1}),[Ka,Yr]=o.useState(!1),Qr=async(l,N)=>{if(!l||l==="__custom__")return;Ur(!0),ke(null);const D=as.find(Y=>Y.id===l),G=de.baseUrl||D?.baseUrl;try{if(N){const Y=await F.modelCatalog.validateKey(l,N,G||void 0);!Y.valid&&Y.error&&ke({type:"err",text:Y.error}),nt(Y.models)}else{const Y=await F.modelCatalog.getByProvider(l);nt(Y.models)}}catch{nt([])}finally{Ur(!1)}},Zr=async()=>{if(!(!de.name||!de.model)){_r(!0),Fr(null),ke(null);try{const l=await fetch("/api/settings/llm/providers",{method:"POST",headers:me(),body:JSON.stringify({name:de.name,apiKey:de.apiKey||void 0,baseUrl:de.baseUrl||void 0,model:de.model,contextWindow:de.contextWindow||void 0,maxOutputTokens:de.maxOutputTokens||void 0,cost:de.costInput||de.costOutput?{input:de.costInput,output:de.costOutput}:void 0})}),N=await l.json();l.ok?(M(N),Rs(!1),xt(""),nt([]),We({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),ke({type:"ok",text:s("modelProviders.providerAdded",{name:de.name})})):ke({type:"err",text:N.error??s("modelProviders.failedToAdd")})}catch{ke({type:"err",text:s("common:networkError")})}finally{_r(!1)}}},Ha=async(l,N)=>{if(!Ve.trim())return;Gr(!0),ke(null);const D=as.find(J=>J.id===l),G=D?.baseUrl;let Y=D?.defaultModel??l;try{const J=await F.modelCatalog.getLive(l);J?.recommended&&(Y=J.recommended)}catch{}try{const J=await fetch("/api/settings/llm/providers",{method:"POST",headers:me(),body:JSON.stringify({name:l,apiKey:Ve.trim(),model:Y,baseUrl:G})}),be=await J.json();J.ok?(M(be),xt(""),nt([]),ke({type:"ok",text:s("modelProviders.quickSetupSuccess",{name:D?.label??l})})):ke({type:"err",text:be.error??s("modelProviders.failedToAdd")})}catch{ke({type:"err",text:s("common:networkError")})}finally{Gr(!1)}},za=(l,N)=>{Ds(l),Os({apiKey:"",baseUrl:N.baseUrl??"",model:N.model,contextWindow:N.contextWindow??0,maxOutputTokens:N.maxOutputTokens??0,costInput:N.cost?.input??0,costOutput:N.cost?.output??0})},qa=async l=>{Hr(!0);try{const N={};ve.apiKey&&(N.apiKey=ve.apiKey),ve.baseUrl!==void 0&&(N.baseUrl=ve.baseUrl),ve.model&&(N.model=ve.model),ve.contextWindow&&(N.contextWindow=ve.contextWindow),ve.maxOutputTokens&&(N.maxOutputTokens=ve.maxOutputTokens),(ve.costInput||ve.costOutput)&&(N.cost={input:ve.costInput,output:ve.costOutput});const D=await fetch(`/api/settings/llm/providers/${l}`,{method:"PUT",headers:me(),body:JSON.stringify(N)});if(D.ok){const G=await D.json();M(G),Ds(null)}}catch{}finally{Hr(!1)}},Wa=async l=>{qr(l);try{const N=await fetch(`/api/settings/llm/providers/${l}`,{method:"DELETE",headers:me()});if(N.ok){const D=await N.json();M(D),L(D.defaultProvider)}}catch{}finally{qr(null)}},Ga=async l=>{if(!(!Pe.id||!Pe.name)){Yr(!0);try{const N=await fetch(`/api/settings/llm/providers/${l}/models`,{method:"POST",headers:me(),body:JSON.stringify({id:Pe.id,name:Pe.name,contextWindow:Pe.contextWindow,maxOutputTokens:Pe.maxOutputTokens,cost:{input:Pe.costInput,output:Pe.costOutput},reasoning:Pe.reasoning||void 0,inputTypes:Pe.vision?["text","image"]:["text"]})});if(N.ok){const D=await N.json();M(D),ns(null),is({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})}}catch{}finally{Yr(!1)}}},Ja=async(l,N)=>{try{const D=await fetch(`/api/settings/llm/providers/${l}/models/${encodeURIComponent(N)}`,{method:"DELETE",headers:me()});if(D.ok){const G=await D.json();M(G)}}catch{}},[Xr,en]=o.useState(null),[tn,Ya]=o.useState({}),[ie,os]=o.useState({}),Qa=async l=>{en(l),os(N=>{const D={...N};return delete D[l],D});try{const N=await fetch(`/api/settings/llm/providers/${l}/test`,{method:"POST",headers:me(),body:JSON.stringify({model:tn[l]||void 0})});if(!N.ok){const G=await N.json().catch(()=>({}));os(Y=>({...Y,[l]:{ok:!1,error:G.error??`HTTP ${N.status}`,errorCode:N.status,code:G.code}}));return}const D=await N.json();os(G=>({...G,[l]:D}))}catch{os(N=>({...N,[l]:{ok:!1,error:s("common:networkError")}}))}finally{en(null)}},Za=l=>l.code==="PROVIDER_DISABLED"?s("modelProviders.testDisabled"):l.code==="PROVIDER_NOT_FOUND"?s("modelProviders.testNotFound"):l.error??(l.errorCode?s("modelProviders.testFailedCode",{code:l.errorCode}):s("modelProviders.testFailed")),Xa=l=>{const N=new Set,D=C?.providers?.[l];D?.model&&N.add(D.model);const G=ee[l];if(G)for(const Y of G)Y.id&&N.add(String(Y.id));if(D?.models)for(const Y of D.models)Y.id&&N.add(Y.id);if(l==="ollama"&&fe?.models)for(const Y of fe.models)Y.name&&N.add(Y.name);return[...N]},sn=C?.providers?Object.entries(C.providers).filter(([,l])=>l.configured&&l.enabled).map(([l])=>l):[],rn=i?.role==="owner"||i?.role==="admin",Tt=Ma.filter(l=>!l.adminOnly||rn),nn=o.useMemo(()=>{const l=[];for(const N of gr)for(const D of N.tabs){const G=Tt.find(Y=>Y.id===D);G&&l.push(G)}return l},[Tt]),an=o.useRef(nn);an.current=nn;const on=o.useRef(h);on.current=h;const ln=!d&&u&&x==="l1";return o.useEffect(()=>{if(d||!u)return;const l=N=>{if(p?.keyboardPane==="l0"||N.metaKey||N.ctrlKey||N.altKey||yi(N.target))return;const D=N.key.length===1?N.key.toLowerCase():N.key;if(D==="h"||D==="ArrowLeft")return;const G=D==="j"||D==="ArrowDown"?1:D==="k"||D==="ArrowUp"?-1:0;if(!G)return;N.preventDefault(),N.stopPropagation(),p?.setKeyboardPane("l1");const Y=an.current;if(Y.length===0)return;const J=on.current;let be=J?Y.findIndex(gt=>gt.id===J):-1;be<0&&(be=G>0?-1:0);const A=Math.max(0,Math.min(Y.length-1,be+G)),q=Y[A];b(q.id),requestAnimationFrame(()=>{document.querySelector(`[data-settings-tab-id="${q.id}"]`)?.scrollIntoView({block:"nearest"})})};return document.addEventListener("keydown",l,!0),()=>document.removeEventListener("keydown",l,!0)},[d,u,p,b]),e.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[e.jsxs("aside",{"data-keyboard-pane":"l1",className:`hidden md:flex flex-col w-56 shrink-0 border-r border-border-default bg-surface-secondary overflow-y-auto ${ln?"ring-1 ring-inset ring-brand-500/30":""}`,children:[e.jsx("div",{"data-electron-drag":!0,className:"electron-mac-top-safe px-3 pt-4 pb-2",children:e.jsxs("button",{"data-no-drag":!0,onClick:()=>{ms.leaveSettings()},className:"flex items-center gap-2 px-2 py-1.5 rounded-lg text-sm text-fg-secondary hover:text-fg-primary hover:bg-surface-overlay transition-colors",title:`${s("common:back",{defaultValue:"Back"})} (H)`,children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M19 12H5"}),e.jsx("polyline",{points:"12 19 5 12 12 5"})]}),s("common:back",{defaultValue:"Back"})]})}),e.jsx("div",{className:"px-5 pb-4",children:e.jsx("h2",{className:"text-base font-semibold text-fg-primary",children:s("title")})}),e.jsx("nav",{className:"flex-1 px-3 pb-4 space-y-3",children:gr.map(l=>{const N=l.tabs.map(D=>Tt.find(G=>G.id===D)).filter(D=>!!D);return N.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"px-3 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wider text-fg-tertiary",children:s(`settings:${l.labelKey}`)}),e.jsx("div",{className:"space-y-0.5",children:N.map(D=>e.jsxs("button",{"data-settings-tab-id":D.id,onClick:()=>{b(D.id),p?.setKeyboardPane("l1")},className:`w-full flex items-center gap-2.5 text-left px-3 py-2 rounded-lg text-sm font-medium transition-colors text-fg-primary ${h===D.id?ln?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(sa,{id:D.id,className:h===D.id?"text-fg-secondary":"text-fg-tertiary"}),e.jsx("span",{className:"truncate",children:s(`settings:${D.labelKey}`)})]},D.id))})]},l.labelKey)})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[d&&h===null&&e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border-default bg-surface-secondary",children:[e.jsx("button",{onClick:()=>ms.leaveSettings(),className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors",title:`${s("common:back",{defaultValue:"Back"})} (H)`,children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M19 12H5"}),e.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),e.jsx("h1",{className:"text-base font-semibold text-fg-primary",children:s("title")})]}),e.jsxs("nav",{className:"flex-1 overflow-y-auto py-2 px-3",children:[gr.map((l,N)=>{const D=l.tabs.map(G=>Tt.find(Y=>Y.id===G)).filter(G=>!!G);return D.length===0?null:e.jsxs("div",{children:[N>0&&e.jsx("div",{className:"border-t border-border-default my-2 mx-2"}),e.jsx("div",{className:"px-4 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-wider text-fg-tertiary",children:s(`settings:${l.labelKey}`)}),D.map(G=>e.jsxs("button",{onClick:()=>b(G.id),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg text-sm text-fg-primary hover:bg-surface-overlay transition-colors",children:[e.jsx(sa,{id:G.id,className:"text-fg-tertiary"}),e.jsx("span",{className:"flex-1 text-left",children:s(`settings:${G.labelKey}`)}),e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id))]},l.labelKey)}),a&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default my-2 mx-2"}),e.jsxs("button",{onClick:()=>w(!0),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg text-sm text-red-500 hover:bg-red-500/10 transition-colors",children:[e.jsx("span",{className:"w-4 h-4 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),e.jsx("polyline",{points:"16 17 21 12 16 7"}),e.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})}),e.jsx("span",{className:"flex-1 text-left",children:s("common:signOut")})]})]})]})]}),d&&h!==null&&e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border-default bg-surface-secondary sticky top-0 z-10",children:[e.jsx("button",{onClick:S,className:"p-1.5 rounded-lg hover:bg-surface-overlay transition-colors",children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M19 12H5"}),e.jsx("polyline",{points:"12 19 5 12 12 5"})]})}),e.jsx("h1",{className:"text-base font-semibold text-fg-primary",children:s(`settings:${Tt.find(l=>l.id===h)?.labelKey||"title"}`)})]}),h!==null&&e.jsxs("div",{className:"p-4 md:p-7 space-y-10 max-w-4xl mx-auto w-full",children:[h==="appearance"&&e.jsxs(e.Fragment,{children:[e.jsx(Te,{title:s("systemStatus.title"),children:R?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 md:gap-4",children:[e.jsx(hr,{label:s("systemStatus.status"),value:R.status==="ok"?s("systemStatus.healthy"):R.status,color:"green"}),e.jsx(hr,{label:s("systemStatus.version"),value:R.version,color:"indigo"}),e.jsx(hr,{label:s("systemStatus.activeAgents"),value:String(R.agents),color:"purple"})]}):e.jsx("div",{className:"text-sm text-fg-tertiary",children:s("common:loading")})}),e.jsx(Te,{title:s("appearance.title"),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:s("appearance.theme")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("appearance.themeDesc")})]}),e.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-elevated rounded-lg p-0.5",children:bi.map(({value:l})=>e.jsx("button",{onClick:()=>r?.(l),className:`px-3 py-1.5 text-xs rounded-md transition-colors ${t===l?"bg-brand-600 text-white":"text-fg-secondary hover:text-fg-primary"}`,children:s(`appearance.modes.${l}`)},l))})]}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between mt-5 pt-5 border-t border-border-default/50",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:s("appearance.language")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("appearance.languageDesc")})]}),e.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-elevated rounded-lg p-0.5",children:un.map(({code:l,label:N})=>e.jsx("button",{onClick:()=>{c.changeLanguage(l),F.settings.updateSearch({language:l}).catch(()=>{})},className:`px-3 py-1.5 text-xs rounded-md transition-colors ${c.language===l||l==="en"&&!un.some(D=>D.code===c.language)?"bg-brand-600 text-white":"text-fg-secondary hover:text-fg-primary"}`,children:N},l))})]}),cn()&&e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between mt-5 pt-5 border-t border-border-default/50",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:s("appearance.launchAtLogin")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("appearance.launchAtLoginDesc")})]}),e.jsx(bs,{checked:P,onChange:()=>{I()},label:s("appearance.launchAtLogin"),size:"lg",disabled:v})]})]})})]}),rn&&e.jsxs(e.Fragment,{children:[h==="providers"&&e.jsxs(e.Fragment,{children:[C&&(()=>{const l=[],N=new Set,D=[],G=[];for(const[A,q]of Object.entries(C.providers))q.configured?D.push([A,q]):A!=="markus"&&G.push([A,q]),N.add(A);for(const A of as)!N.has(A.id)&&A.id!=="markus"&&(G.push([A.id,{name:A.id,displayName:A.label,model:A.defaultModel,configured:!1,enabled:!1}]),N.add(A.id));D.sort((A,q)=>(q[1].enabled?1:0)-(A[1].enabled?1:0)),l.push(...D,...G);const Y=D.length>0,be=C.providers.markus?.configured??!1;return e.jsxs(e.Fragment,{children:[!be&&e.jsx(Te,{title:"Markus Cloud AI",children:e.jsxs("div",{className:"bg-surface-secondary border border-brand-500/30 rounded-xl overflow-hidden transition-colors hover:border-brand-500/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-4 md:px-5 cursor-pointer",onClick:()=>{X(_==="markus"?null:"markus"),xt(""),ke(null)},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:"w-2.5 h-2.5 shrink-0 rounded-full bg-brand-500 shadow-[0_0_6px_rgba(99,102,241,0.4)]"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-sm font-medium",children:"Markus Cloud AI"}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("modelProviders.markusHint")})]})]}),e.jsx("svg",{className:`w-4 h-4 shrink-0 text-fg-tertiary transition-transform ${_==="markus"?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),_==="markus"&&e.jsxs("div",{className:"px-4 md:px-5 pb-5 space-y-3 border-t border-border-default/50",children:[e.jsx("p",{className:"text-xs text-fg-tertiary pt-3",children:s("modelProviders.markusSetupLogin")}),e.jsx("button",{onClick:()=>ms.navigate(br.SETTINGS,{tab:"account"}),className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 text-white text-sm rounded-lg transition-colors",children:s("modelProviders.goToAccount")})]})]})}),e.jsxs(Pl,{title:s("modelProviders.title"),defaultCollapsed:Y,configuredProviders:D,t:s,onBadgeClick:A=>{X(A),xt(""),ke(null),setTimeout(()=>{document.querySelector(`[data-provider-id="${A}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},80)},children:[e.jsxs("div",{className:"space-y-3",children:[Y&&e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-1",children:s("modelProviders.groupConfigured",{count:D.length})}),l.map(([A,q],gt)=>{const Fs=!q.configured&&(gt===0||l[gt-1][1].configured);return e.jsxs("div",{"data-provider-id":A,children:[Fs&&Y&&e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-1 mt-4 mb-2",children:s("modelProviders.groupUnconfigured")}),e.jsxs("div",{className:`bg-surface-secondary border rounded-xl overflow-hidden transition-colors ${q.configured?"border-border-default hover:border-gray-600":"border-border-default/50 hover:border-brand-500/30"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-4 md:px-5 cursor-pointer",onClick:()=>{X(_===A?null:A),xt(""),ke(null),nt([]),We(Q=>({...Q,name:"",model:""}))},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-2 h-2 shrink-0 rounded-full ${q.configured&&q.enabled?"bg-green-400":q.configured?"bg-amber-400":"bg-gray-600"}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:q.displayName??A}),A===C.defaultProvider&&e.jsx("span",{className:"text-[10px] bg-brand-500/15 text-brand-500 px-1.5 py-0.5 rounded",children:s("modelProviders.badgeDefault")}),q.configured&&!q.enabled&&e.jsx("span",{className:"text-[10px] bg-amber-500/15 text-amber-600 px-1.5 py-0.5 rounded",children:s("modelProviders.disabled")}),q.oauthConnected&&e.jsx("span",{className:"text-[10px] bg-green-500/15 text-green-600 px-1.5 py-0.5 rounded",children:s("modelProviders.badgeOAuth")}),ie[A]?.ok===!0&&e.jsx("span",{className:"text-[10px] bg-green-500/15 text-green-600 px-1.5 py-0.5 rounded",children:s("modelProviders.testOk",{ms:ie[A].durationMs})}),ie[A]?.ok===!1&&e.jsx("span",{className:"text-[10px] bg-red-500/15 text-red-500 px-1.5 py-0.5 rounded",title:ie[A].error,children:ie[A].errorCode?s("modelProviders.testFailedCode",{code:ie[A].errorCode}):ie[A].code==="PROVIDER_DISABLED"?s("modelProviders.testDisabled"):s("modelProviders.testFailed")})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:q.configured?e.jsxs(e.Fragment,{children:[q.models&&q.models.length>0?s("modelProviders.modelsAvailable",{count:q.models.length}):"",A!=="markus"&&q.apiKeyPreview&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("code",{className:"text-fg-secondary",children:q.apiKeyPreview})]})]}):s("modelProviders.notConfigured")})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-4",children:[q.configured&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),Ia(A,!q.enabled)},disabled:ce===A,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${q.enabled?"bg-green-500":"bg-gray-600"} ${ce===A?"opacity-50":""}`,title:q.enabled?s("modelProviders.clickToDisable"):s("modelProviders.clickToEnable"),children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${q.enabled?"translate-x-4":"translate-x-1"}`})}),e.jsx("span",{className:"text-fg-tertiary text-xs",children:_===A?"▲":"▼"})]})]}),_===A&&e.jsxs("div",{className:"px-4 md:px-5 pb-4 border-t border-border-default pt-4 space-y-4",children:[A==="ollama"&&e.jsxs("div",{className:"bg-surface-elevated/40 rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-fg-secondary uppercase tracking-wider shrink-0",children:s("ollama.title")}),e.jsxs("button",{onClick:()=>{Mt()},disabled:Ye,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:[e.jsx("svg",{className:`w-3.5 h-3.5 ${Ye?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),s(Ye?"common:detecting":"ollama.detect")]})]}),e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("ollama.description")}),fe?.found&&fe.models&&fe.models.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-green-600",children:s("ollama.foundModels",{count:fe.models.length,url:fe.baseUrl})}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1 pr-1",children:fe.models.map(Q=>e.jsx("label",{className:`flex items-center rounded-lg px-3 py-2 cursor-pointer transition-colors ${De===Q.name?"bg-brand-500/15 border border-brand-500/40":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"radio",name:"ollama-model-panel",value:Q.name,checked:De===Q.name,onChange:()=>lt(Q.name),className:"w-4 h-4 text-brand-500 focus:ring-brand-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-fg-primary font-medium",children:Q.name}),e.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[Q.parameterSize&&e.jsx("span",{children:Q.parameterSize}),Q.family&&e.jsx("span",{className:"ml-2",children:Q.family}),Q.quantization&&e.jsx("span",{className:"ml-2",children:Q.quantization}),Q.size&&e.jsx("span",{className:"ml-2",children:pt(Q.size)})]})]})]})},Q.name))}),e.jsx("button",{onClick:()=>{Da()},disabled:Ut||!De,className:`px-4 py-2 text-sm rounded-lg transition-colors disabled:opacity-40 ${q.configured?"border border-brand-500/40 text-brand-500 hover:bg-brand-500/10":"bg-brand-600 hover:bg-brand-500 text-white"}`,children:Ut?s("common:applying"):q.configured?s("ollama.switchModel"):s("ollama.useModel",{model:De})}),Qe&&e.jsx(Ie,{type:Qe.type,text:Qe.text})]}),fe&&!fe.found&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:fe.error||s("ollama.notRunning")})]}),q.configured&&e.jsxs(e.Fragment,{children:[Ua===A?e.jsxs("div",{className:"bg-surface-elevated/40 rounded-lg p-4 space-y-3",children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:s("modelProviders.editProvider")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.apiKey")}),e.jsx("input",{type:"password",value:ve.apiKey,onChange:Q=>Os({...ve,apiKey:Q.target.value}),placeholder:s("modelProviders.apiKeyPlaceholder"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.baseUrl")}),e.jsx("input",{type:"text",value:ve.baseUrl,onChange:Q=>Os({...ve,baseUrl:Q.target.value}),placeholder:s("modelProviders.baseUrlDisplayDefault"),className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{onClick:()=>{qa(A)},disabled:Kr,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors whitespace-nowrap",children:s(Kr?"common:saving":"common:save")}),e.jsx("button",{onClick:()=>Ds(null),className:"px-3 py-1.5 text-xs border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors whitespace-nowrap",children:s("common:cancel")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider shrink-0",children:s("modelProviders.testModel")}),e.jsx(fa,{value:tn[A]??"",options:Xa(A),onChange:Q=>Ya(Le=>({...Le,[A]:Q})),placeholder:s("modelProviders.testDefaultModel"),filterPlaceholder:s("modelPicker.filterPlaceholder"),emptyText:s("modelPicker.empty"),customHint:s("modelPicker.useTyped"),ariaLabel:s("modelProviders.testModel"),className:"w-full min-w-0 md:w-[260px]"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-2",children:[e.jsx("button",{onClick:Q=>{Q.stopPropagation(),Qa(A)},disabled:Xr===A,className:"px-3 py-1.5 text-xs border border-green-500/30 text-green-500 hover:bg-green-500/10 rounded-lg transition-colors disabled:opacity-40 flex items-center gap-1.5 whitespace-nowrap",children:Xr===A?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-3 h-3 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),s("modelProviders.testing")]}):s("modelProviders.test")}),A!=="markus"&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),za(A,q)},className:"px-3 py-1.5 text-xs border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors whitespace-nowrap",children:s("common:edit")}),A!=="markus"&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),Vs({name:A,label:q.displayName??A})},disabled:zr===A,className:"px-3 py-1.5 text-xs border border-red-500/30 text-red-400 hover:bg-red-500/10 rounded-lg transition-colors disabled:opacity-40 whitespace-nowrap",children:s(zr===A?"common:deleting":"common:delete")})]})]}),ie[A]&&e.jsxs("details",{className:`text-xs rounded-lg border ${ie[A].ok?"bg-green-500/10 border-green-500/30":"bg-red-500/10 border-red-500/30"}`,children:[e.jsx("summary",{className:`px-3 py-2 cursor-pointer select-none ${ie[A].ok?"text-green-600":"text-red-500"}`,children:ie[A].ok?s("modelProviders.testSuccess",{ms:ie[A].durationMs,reply:ie[A].reply}):Za(ie[A])}),e.jsxs("div",{className:"px-3 pb-2 pt-1 space-y-1 text-[11px] text-fg-muted border-t border-current/10",children:[A!=="markus"&&ie[A].requestUrl&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.requestUrl"),":"]})," ",e.jsx("code",{className:"font-mono text-fg-primary",children:ie[A].requestUrl})]}),e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.model"),":"]})," ",e.jsx("code",{className:"font-mono text-fg-primary",children:ie[A].model??q.model})]}),!!ie[A].requestBody&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.requestBody"),":"]}),e.jsx("pre",{className:"mt-0.5 p-1.5 rounded bg-surface-primary/50 font-mono overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(ie[A].requestBody,null,2)})]}),ie[A].ok&&ie[A].reply&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.response"),":"]})," ",ie[A].reply]}),ie[A].usage&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.tokens"),":"]})," ",s("modelProviders.testDetail.inputTokens")," ",ie[A].usage.inputTokens??ie[A].usage.prompt_tokens??"-"," / ",s("modelProviders.testDetail.outputTokens")," ",ie[A].usage.outputTokens??ie[A].usage.completion_tokens??"-"]}),ie[A].durationMs!=null&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.duration"),":"]})," ",ie[A].durationMs,"ms"]})]})]})]}),A==="markus"&&q.configured&&e.jsxs("div",{className:"bg-green-500/5 border border-green-500/20 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400 shadow-[0_0_4px_rgba(74,222,128,0.4)]"}),e.jsx("span",{className:"text-sm font-medium text-green-400",children:s("modelProviders.markusConnected")})]}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-2",children:s("modelProviders.markusConnectedHint")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider",children:s("modelProviders.availableModels")}),q.configured&&A!=="markus"&&Jr!==A&&e.jsx("button",{onClick:()=>{ns(A),is({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})},className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:s("modelProviders.addModel")})]}),Jr===A&&e.jsx("div",{className:"bg-surface-elevated/40 rounded-lg p-3 mb-2 space-y-2",children:e.jsx(Al,{providerName:A,addModelForm:Pe,setAddModelForm:is,addModelSaving:Ka,onAdd:()=>{Ga(A)},onCancel:()=>ns(null),t:s})}),A==="markus"&&q.configured&&(!q.models||q.models.length===0)&&(T===A?e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-fg-tertiary",children:[e.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),s("modelProviders.loadingHubCatalog")]}):e.jsx("div",{className:"mt-1 text-xs text-amber-400/90",children:K?s("modelProviders.hubCatalogError",{error:K}):s("modelProviders.hubCatalogEmpty")})),q.models&&q.models.length>0&&e.jsx(Cl,{models:q.models,providerName:A,activeModelId:q.model,t:s,onDeleteCustom:Q=>{Ja(A,Q)}}),q.configured&&T===A&&e.jsxs("div",{className:"flex items-center gap-2 mt-2 text-xs text-fg-tertiary",children:[e.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),s("modelProviders.loadingCatalog")]}),q.configured&&ee[A]&&ee[A].length>0&&(()=>{const Q=new Set(q.models?.map(Ce=>Ce.id)??[]),Le=ee[A].filter(Ce=>!Q.has(String(Ce.id??"")));return Le.length===0?null:e.jsx(Sl,{models:Le,providerName:A,t:s,onAdd:Ce=>{const Me=Le.find(ei=>String(ei.id??"")===Ce);Me&&(ns(A),is({id:String(Me.id??""),name:String(Me.id??""),contextWindow:Me.maxInputTokens??128e3,maxOutputTokens:Me.maxOutputTokens??16384,costInput:Me.inputCostPer1MTokens??1,costOutput:Me.outputCostPer1MTokens??5,reasoning:Me.capabilities?.reasoning??!1,vision:Me.capabilities?.vision??!1}))}})})()]}),!q.configured&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:s("modelProviders.quickSetupHint")}),A==="markus"&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 rounded-lg bg-brand-600/8 border border-brand-500/15 text-xs text-fg-secondary",children:[e.jsx("svg",{className:"w-4 h-4 shrink-0 text-brand-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),e.jsxs("span",{children:[s("modelProviders.markusKeyHint")," ",e.jsx("a",{href:`${Ot.getUrl()}/settings`,target:"_blank",rel:"noopener noreferrer",className:"text-brand-500 hover:text-brand-400 underline underline-offset-2",children:s("modelProviders.markusKeyLink")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.apiKey")}),e.jsx("input",{type:"password",value:_===A?Ve:"",onChange:Q=>xt(Q.target.value),placeholder:s("modelProviders.quickSetupPlaceholder"),className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none",onBlur:()=>{Ve.trim().length>=8&&_===A&&Qr(A,Ve.trim())},onKeyDown:Q=>{Q.key==="Enter"&&Ve.trim().length>=8&&Qr(A,Ve.trim())}}),Fa&&_===A&&e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 text-xs text-fg-tertiary",children:[e.jsx("div",{className:"w-3 h-3 border-2 border-brand-500 border-t-transparent rounded-full animate-spin"}),s("modelProviders.validatingKey")]})]}),_===A&&Bs.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-2",children:s("modelProviders.selectModel")}),e.jsx(da,{provider:A,models:Bs,selectedModel:de.model,showTiers:!0,onSelect:Q=>{const Le=Bs.find(Ce=>Ce.id===Q);We(Ce=>({...Ce,name:A,model:Q,apiKey:Ve.trim(),baseUrl:as.find(Me=>Me.id===A)?.baseUrl??"",contextWindow:Le?.maxInputTokens??Ce.contextWindow,maxOutputTokens:Le?.maxOutputTokens??Ce.maxOutputTokens,costInput:Le?.inputCostPer1MTokens??Ce.costInput,costOutput:Le?.outputCostPer1MTokens??Ce.costOutput}))},compact:!0,maxVisible:8})]}),_===A&&Ve.trim()&&e.jsx("button",{onClick:()=>{de.model&&de.name===A?Zr():Ha(A)},disabled:Wr||rs,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:s(Wr||rs?"modelProviders.quickSetupSaving":"modelProviders.quickSetupSubmit")}),_s&&_===A&&e.jsx(Ie,{type:_s.type,text:_s.text})]})]})]})]},A)})]}),_a?e.jsxs("div",{className:"mt-3 bg-surface-secondary border border-brand-500/30 rounded-xl p-4 space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-fg-primary",children:s("modelProviders.customProvider")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.providerName")}),e.jsx("input",{type:"text",value:de.name==="__custom__"?"":de.name,onChange:A=>We(q=>({...q,name:A.target.value||"__custom__"})),placeholder:"my-provider",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.baseUrl")}),e.jsx("input",{type:"text",value:de.baseUrl,onChange:A=>We({...de,baseUrl:A.target.value}),placeholder:"https://api.example.com/v1",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.apiKey")}),e.jsx("input",{type:"password",value:de.apiKey,onChange:A=>We({...de,apiKey:A.target.value}),placeholder:s("modelProviders.placeholderApiKeySk"),className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.defaultModel")}),e.jsx("input",{type:"text",value:de.model,onChange:A=>We({...de,model:A.target.value}),placeholder:"gpt-4o",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{onClick:()=>{Zr()},disabled:rs||!de.name||de.name==="__custom__"||!de.model,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors whitespace-nowrap",children:s(rs?"modelProviders.adding":"modelProviders.addProviderSubmit")}),e.jsx("button",{onClick:()=>{Rs(!1),Fr(null),nt([]),We({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5})},className:"px-4 py-2 text-sm border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors whitespace-nowrap",children:s("common:cancel")})]}),Is&&e.jsx(Ie,{type:Is.type,text:Is.text})]}):e.jsxs("button",{onClick:()=>Rs(!0),className:"w-full mt-3 px-4 py-2.5 border border-dashed border-border-default hover:border-brand-500/50 hover:bg-brand-500/5 rounded-xl text-xs text-fg-tertiary hover:text-brand-500 transition-colors",children:["+ ",s("modelProviders.customProvider")]})]})]})})(),e.jsx(pr,{title:s("autoDetect.title"),defaultOpen:!1,children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[e.jsx("div",{className:"text-sm text-fg-secondary",children:s("autoDetect.description")}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:s("envConfig.title")}),e.jsxs("button",{onClick:()=>{Ls()},disabled:ge,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:[e.jsx("svg",{className:`w-3.5 h-3.5 ${ge?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),s(ge?"common:detecting":"envConfig.refreshEnv")]})]}),se&&se.detected.length>0&&e.jsxs("div",{className:"space-y-2",children:[se.detected.map(l=>e.jsxs("label",{className:"flex items-center justify-between gap-3 bg-surface-elevated/30 rounded-lg px-4 py-3 cursor-pointer hover:bg-surface-elevated/50 transition-colors",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("input",{type:"checkbox",checked:Se[l.provider]??!1,onChange:N=>Be({...Se,[l.provider]:N.target.checked}),className:"w-4 h-4 rounded bg-surface-overlay border-gray-600 text-brand-500 focus:ring-brand-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-fg-primary font-medium",children:l.displayName}),e.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[s("envConfig.keyLabel")," ",e.jsx("code",{className:"text-fg-secondary",children:l.apiKeyPreview})," / ",s("envConfig.modelLabel")," ",e.jsx("code",{className:"text-fg-secondary",children:l.model}),l.baseUrl&&e.jsxs(e.Fragment,{children:[" / ",s("envConfig.urlLabel")," ",e.jsx("code",{className:"text-fg-secondary",children:l.baseUrl})]})]})]})]}),e.jsx("div",{className:"shrink-0 text-right text-xs text-fg-tertiary",children:Object.keys(l.envVars).map(N=>e.jsx("div",{children:e.jsx("code",{children:N})},N))})]},l.provider)),se.timeoutMs&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("envConfig.llmTimeout",{ms:se.timeoutMs})}),e.jsx("button",{onClick:()=>{Ba()},disabled:ot||Object.values(Se).filter(Boolean).length===0,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-lg transition-colors",children:ot?s("common:applying"):s("envConfig.applyToConfig",{count:Object.values(Se).filter(Boolean).length})})]}),Je&&e.jsx(Ie,{type:Je.type,text:Je.text})]})]})}),e.jsx(pr,{title:s("oauthAuth.title"),defaultOpen:!1,children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("oauthAuth.description")}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[kt.map(l=>e.jsxs("div",{className:"flex",children:[e.jsx("button",{onClick:()=>Vr(l.name),disabled:!!tt,className:"px-3 py-2 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-l-lg transition-colors",children:tt===l.name?s("oauthAuth.connecting"):s("oauthAuth.signInWith",{name:l.displayName})}),e.jsx("button",{onClick:()=>Oa(l.name),disabled:!!tt,title:s("oauthAuth.deviceTitle"),className:"px-2.5 py-2 text-xs bg-surface-secondary text-fg-secondary border border-border-default border-l-0 rounded-r-lg hover:bg-surface-tertiary disabled:opacity-40 transition-colors",children:s("oauthAuth.device")})]},l.name)),kt.length===0&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:s("oauthAuth.noProviders")})]}),Ue&&e.jsxs("div",{className:"p-4 rounded-lg bg-surface-secondary border border-border-default space-y-2",children:[e.jsx("p",{className:"text-xs text-fg-primary font-medium",children:s("oauthAuth.deviceCodeTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("oauthAuth.deviceInstructions")}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("a",{href:Ue.verificationUri,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-brand-500 underline hover:text-brand-400",children:Ue.verificationUri}),e.jsx("code",{className:"px-2.5 py-1 text-sm font-mono font-bold bg-surface-elevated border border-border-default rounded-lg text-fg-primary select-all",children:Ue.userCode})]}),e.jsx("p",{className:"text-[10px] text-fg-muted",children:s("oauthAuth.deviceWaiting")})]}),Wt&&!Ue&&e.jsxs("div",{className:"p-4 rounded-lg bg-surface-secondary border border-border-default space-y-2",children:[e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("oauthAuth.manualCallbackHint")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:st,onChange:l=>qt(l.target.value),placeholder:s("oauthAuth.manualPlaceholder"),className:"flex-1 px-3 py-2 text-xs bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder:text-fg-muted/50 focus:border-brand-500 outline-none"}),e.jsx("button",{onClick:$a,disabled:!st.trim()||tt==="manual",className:"px-3 py-2 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:s("oauthAuth.submit")})]})]}),St&&e.jsx(Ie,{type:St.type,text:St.text}),zt.filter(l=>l.hasOAuth).length>0&&e.jsxs("div",{className:"space-y-2 border-t border-border-default pt-4",children:[e.jsx("span",{className:"text-xs font-medium text-fg-secondary",children:s("oauthAuth.connectedAccounts")}),zt.filter(l=>l.hasOAuth).map(l=>e.jsxs("div",{className:`flex items-center justify-between gap-3 px-4 py-3 rounded-lg border ${l.oauthExpired?"bg-amber-500/5 border-amber-500/20":"bg-surface-secondary border-border-default"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${l.oauthExpired?"bg-amber-400":"bg-green-400"}`}),e.jsx("span",{className:"text-xs text-fg-primary font-medium",children:l.label??l.provider}),l.accountId&&e.jsxs("span",{className:"text-[10px] text-fg-muted",children:["(",l.accountId.slice(0,12),"...)"]}),l.oauthExpired&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-md bg-amber-500/15 text-amber-600 font-medium",children:s("oauthAuth.expired")})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[l.oauthExpired&&e.jsx("button",{onClick:()=>Vr(l.provider),disabled:!!tt,className:"text-[10px] px-2 py-1 rounded-md text-brand-500 hover:text-brand-400 hover:bg-brand-500/10 transition-colors",children:s("oauthAuth.reconnect")}),e.jsx("button",{onClick:()=>Va(l.id),className:"text-[10px] px-2 py-1 rounded-md text-red-400 hover:text-red-300 hover:bg-red-500/10 transition-colors",children:s("oauthAuth.disconnect")})]})]},l.id))]})]})}),e.jsx(Te,{title:s("defaultProvider.title"),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:s("defaultProvider.primaryProvider")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("defaultProvider.primaryProviderDesc")})]}),e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[C?e.jsx("select",{value:B,onChange:l=>{L(l.target.value),O(null)},className:"px-3 py-1.5 bg-surface-elevated border border-border-default rounded-lg text-sm w-full min-w-0 md:w-48 focus:border-brand-500 outline-none",children:sn.length>0?sn.map(l=>e.jsx("option",{value:l,children:C.providers[l]?.displayName??l},l)):e.jsx("option",{value:"",children:s("defaultProvider.noProviders")})}):e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("common:loading")}),B!==C?.defaultProvider&&e.jsx("button",{onClick:()=>{Ra()},disabled:U,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors shrink-0 whitespace-nowrap",children:s(U?"common:saving":"common:save")})]})]}),W&&e.jsx(Ie,{type:W.type,text:W.text}),e.jsxs("div",{className:"flex flex-col gap-3 border-t border-border-default pt-4 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("defaultProvider.autoFallback")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("defaultProvider.autoFallbackDesc")})]}),e.jsx("button",{onClick:async()=>{const l=!(C?.autoFallback??!1);try{const N=await fetch("/api/settings/llm",{method:"POST",headers:me(),body:JSON.stringify({autoFallback:l})});if(N.ok){const D=await N.json();M(D)}}catch{}},className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${C?.autoFallback??!1?"bg-green-500":"bg-gray-600"}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${C?.autoFallback??!1?"translate-x-4":"translate-x-1"}`})})]})]})}),e.jsx(Te,{title:s("modelRouting.title"),children:e.jsx(Ai,{configuredProviders:Object.entries(C?.providers??{}).filter(([,l])=>l.configured&&l.enabled).map(([l,N])=>({name:l,displayName:N.displayName,model:N.model,models:N.models?.map(D=>({id:D.id,name:D.name}))})),onSave:async l=>{const N=await fetch("/api/settings/llm",{method:"POST",headers:me(),body:JSON.stringify(l)});if(!N.ok)throw new Error(`HTTP ${N.status}`)}},C?.defaultProvider??"no-default")}),e.jsx(Te,{title:s("perAgentModel.section",{defaultValue:"Agent Default Models"}),children:e.jsx(Ei,{configuredProviders:(()=>{try{return Object.entries(C?.providers??{}).filter(([,l])=>l.configured&&l.enabled).map(([l,N])=>({name:l,displayName:N.displayName,model:N.model,models:N.models?.map(D=>({id:D.id,name:D.name}))}))}catch{return[]}})()})}),e.jsx(pr,{title:s("networkProxy.title"),defaultOpen:!1,children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("networkProxy.description")})}),e.jsx("button",{onClick:async()=>{const l=!ye;_e(l);try{await fetch("/api/settings/network",{method:"POST",headers:me(),body:JSON.stringify({proxyEnabled:l})}),Pt()}catch{_e(!l)}},className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${ye?"bg-green-500":"bg-gray-600"}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${ye?"translate-x-4":"translate-x-1"}`})})]}),Ne&&e.jsxs("div",{className:`flex items-center gap-2 px-3 py-2.5 rounded-lg bg-surface-secondary border border-border-default transition-opacity ${ye?"":"opacity-50"}`,children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${ye&&Ne.proxy?"bg-green-400":"bg-gray-600"}`}),e.jsx("span",{className:"text-xs text-fg-secondary",children:ye?Ne.proxy?e.jsxs(e.Fragment,{children:[s("networkProxy.active")," ",e.jsx("code",{className:"text-fg-primary font-mono",children:Ne.proxy})]}):s("networkProxy.noProxy"):s("networkProxy.disabled")}),ye&&Ne.source!=="none"&&Ne.source!=="disabled"&&e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-md font-medium ${Ne.source==="config"?"bg-brand-500/15 text-brand-500":Ne.source==="env"?"bg-amber-500/15 text-amber-600":Ne.source==="system"?"bg-blue-500/15 text-blue-500":"bg-gray-500/15 text-fg-muted"}`,children:Ne.source==="config"?s("networkProxy.sourceConfig"):Ne.source==="env"?s("networkProxy.sourceEnv"):Ne.source==="system"?s("networkProxy.sourceSystem"):""}),e.jsxs("button",{onClick:()=>Pt(),className:"ml-auto text-[10px] px-1.5 py-0.5 rounded-md text-fg-muted hover:text-fg-secondary hover:bg-surface-tertiary transition-colors",title:s("networkProxy.refresh"),children:["↻ ",s("networkProxy.refresh")]})]}),e.jsxs("div",{className:`flex gap-2 items-center transition-opacity ${ye?"":"opacity-50 pointer-events-none"}`,children:[e.jsx("input",{type:"text",value:jt,onChange:l=>Ht(l.target.value),placeholder:s("networkProxy.placeholder"),className:"flex-1 px-3 py-2 text-xs bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder:text-fg-muted/50 focus:border-brand-500 outline-none"}),e.jsx("button",{onClick:async()=>{Ze(!0),Xe(null);try{const l=await fetch("/api/settings/network",{method:"POST",headers:me(),body:JSON.stringify({proxy:jt.trim()})});if(l.ok)Xe({type:"ok",text:s("networkProxy.saved")}),Pt();else{const N=await l.json();Xe({type:"err",text:N.error??s("networkProxy.saveFailed")})}}catch{Xe({type:"err",text:s("networkProxy.networkError")})}finally{Ze(!1)}},disabled:wt,className:"px-3 py-2 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded-lg transition-colors",children:s(wt?"networkProxy.saving":"networkProxy.save")})]}),Fe&&e.jsx(Ie,{type:Fe.type,text:Fe.text})]})})]}),h==="execution"&&e.jsxs(e.Fragment,{children:[e.jsx(Te,{title:s("agentExecution.title"),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("agentExecution.maxToolIterations")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("agentExecution.maxToolIterationsDesc")})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("input",{type:"number",min:0,value:re,onChange:l=>{le(Number(l.target.value)),He(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right"}),e.jsx("button",{disabled:Jt,onClick:async()=>{Yt(!0),He(null);try{const l=await F.settings.updateAgent({maxToolIterations:re});le(l.maxToolIterations),He({type:"ok",text:s("agentExecution.saved")})}catch{He({type:"err",text:s("agentExecution.failedToSave")})}Yt(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:s(Jt?"common:saving":"common:save")})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("agentExecution.maxPendingTasksPerAgent")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("agentExecution.maxPendingTasksPerAgentDesc")})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("input",{type:"number",min:1,value:Ke,onChange:l=>{At(Number(l.target.value)),He(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right"}),e.jsx("button",{disabled:Jt,onClick:async()=>{Yt(!0),He(null);try{const l=await F.settings.updateAgent({maxPendingTasksPerAgent:Ke});At(l.maxPendingTasksPerAgent),He({type:"ok",text:s("agentExecution.saved")})}catch{He({type:"err",text:s("agentExecution.failedToSave")})}Yt(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:s(Jt?"common:saving":"common:save")})]})]}),ys&&e.jsx(Ie,{type:ys.type,text:ys.text})]})}),e.jsx(Te,{title:s("concurrent.title"),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("concurrent.description")}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("concurrent.enabled")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("concurrent.enabledDesc")})]}),e.jsx("button",{onClick:()=>{vs(!dt),ct(null)},className:`relative w-10 h-5 shrink-0 rounded-full transition-colors ${dt?"bg-brand-500":"bg-fg-quaternary"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${dt?"translate-x-5":""}`})})]}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("concurrent.maxWorkers")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("concurrent.maxWorkersDesc")})]}),e.jsx("input",{type:"number",min:1,max:10,disabled:!dt,value:Sr,onChange:l=>{js(Number(l.target.value)),ct(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right disabled:opacity-40"})]}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("concurrent.conflictPolicy")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("concurrent.conflictPolicyDesc")})]}),e.jsxs("select",{value:Ar,disabled:!dt,onChange:l=>{Ns(l.target.value),ct(null)},className:"px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary disabled:opacity-40",children:[e.jsx("option",{value:"auto",children:s("concurrent.policyAuto")}),e.jsx("option",{value:"report",children:s("concurrent.policyReport")})]})]}),e.jsx("div",{className:"flex items-center justify-end gap-2",children:e.jsx("button",{disabled:Pr,onClick:async()=>{Mr(!0),ct(null);try{const l=await F.settings.updateAgent({concurrent:{enabled:dt,maxWorkers:Sr,conflictPolicy:Ar}});vs(l.concurrent.enabled),js(l.concurrent.maxWorkers??3),Ns(l.concurrent.conflictPolicy??"auto"),ct({type:"ok",text:s("concurrent.saved")})}catch{ct({type:"err",text:s("concurrent.failedToSave")})}Mr(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:s(Pr?"common:saving":"common:save")})}),ws&&e.jsx(Ie,{type:ws.type,text:ws.text})]})})]}),h==="browser"&&e.jsxs(e.Fragment,{children:[e.jsxs(Te,{title:s("browserAutomation.title"),children:[e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 mb-4",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:s("browserAutomation.backendTitle")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 mb-3",children:s("browserAutomation.backendDesc")}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("button",{onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.updateBrowser({mode:"embedded"});ks(l.mode??"embedded"),Z({type:"ok",text:s("browserAutomation.backendSwitchToEmbedded")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}ue(!1)},disabled:he,className:`text-left p-4 rounded-xl border transition-colors ${ut==="embedded"?"border-brand-500/60 bg-brand-500/10":"border-border-default bg-surface-primary hover:border-brand-500/40"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg-primary",children:s("browserAutomation.backendEmbedded")}),e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-brand-500/15 text-brand-500",children:s("browserAutomation.modeRecommended")})]}),e.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${ut==="embedded"?"bg-brand-400":"bg-gray-500"}`})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-1",children:s("browserAutomation.backendEmbeddedDesc")})]}),e.jsxs("button",{onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.updateBrowser({mode:"system-chrome"});ks(l.mode??"system-chrome"),Z({type:"ok",text:s("browserAutomation.backendSwitchToSystemChrome")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}ue(!1)},disabled:he,className:`text-left p-4 rounded-xl border transition-colors ${ut==="system-chrome"?"border-brand-500/60 bg-brand-500/10":"border-border-default bg-surface-primary hover:border-brand-500/40"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-semibold text-fg-primary",children:s("browserAutomation.backendSystemChrome")}),e.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${ut==="system-chrome"?"bg-brand-400":"bg-gray-500"}`})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-1",children:s("browserAutomation.backendSystemChromeDesc")})]})]})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 mb-4",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:s("browserAutomation.elementSelectionTitle")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 mb-3",children:s("browserAutomation.elementSelectionDesc")}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("button",{onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.updateBrowser({elementSelection:"direct"});Cs(l.elementSelection??"direct"),Z({type:"ok",text:s("browserAutomation.elementSelectionSwitchToDirect")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}ue(!1)},disabled:he,className:`text-left p-4 rounded-xl border transition-colors ${Qt==="direct"?"border-brand-500/60 bg-brand-500/10":"border-border-default bg-surface-primary hover:border-brand-500/40"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg-primary",children:s("browserAutomation.elementSelectionDirect")}),e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-brand-500/15 text-brand-500",children:s("browserAutomation.modeRecommended")})]}),e.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Qt==="direct"?"bg-brand-400":"bg-gray-500"}`})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-1",children:s("browserAutomation.elementSelectionDirectDesc")})]}),e.jsxs("button",{onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.updateBrowser({elementSelection:"jev"});Cs(l.elementSelection??"jev"),Z({type:"ok",text:s("browserAutomation.elementSelectionSwitchToJev")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}ue(!1)},disabled:he,className:`text-left p-4 rounded-xl border transition-colors ${Qt==="jev"?"border-brand-500/60 bg-brand-500/10":"border-border-default bg-surface-primary hover:border-brand-500/40"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-semibold text-fg-primary",children:s("browserAutomation.elementSelectionJev")}),e.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Qt==="jev"?"bg-brand-400":"bg-gray-500"}`})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-1",children:s("browserAutomation.elementSelectionJevDesc")})]})]})]}),ut==="embedded"?e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 mb-4 flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 w-2 h-2 rounded-full bg-green-400 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-semibold text-fg-primary",children:s("browserAutomation.embeddedActiveTitle")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("browserAutomation.embeddedActiveDesc")})]}),e.jsx("button",{onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.testConcurrentBrowserQuick();Z({type:l.connected?"ok":"err",text:l.connected?s("browserAutomation.backendVerifyOk"):s("browserAutomation.backendVerifyFail",{error:l.summary||"backend not reachable"})})}catch(l){Z({type:"err",text:s("browserAutomation.backendVerifyFail",{error:l?.message||l||"unknown"})})}ue(!1)},disabled:he,className:"px-3 py-1.5 text-xs bg-surface-primary border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40 shrink-0",children:s(he?"browserAutomation.backendVerifying":"browserAutomation.backendVerify")})]}):e.jsxs("div",{className:`rounded-xl p-4 md:p-5 mb-4 ${ze?"bg-green-500/5 border border-green-500/20":"bg-surface-elevated border border-border-default"}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.extensionStatus")}),e.jsxs("span",{className:"text-xs text-fg-tertiary",children:["(",s("browserAutomation.backendCurrentTag"),")"]})]}),e.jsxs("span",{className:`inline-flex shrink-0 items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${ze?"bg-green-500/20 text-green-400":"bg-gray-600/20 text-gray-400"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${ze?"bg-green-400":"bg-gray-400"}`}),s(ze?"browserAutomation.extensionConnected":"browserAutomation.extensionDisconnected")]})]}),e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("browserAutomation.extensionStatusDesc")}),ze?e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 text-xs text-green-400",children:[e.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),s("browserAutomation.extensionActiveNote")]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 text-xs text-amber-400",children:[e.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s("browserAutomation.backendInstallUnmet")]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:s("browserAutomation.extensionSetupTitle")}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[e.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"1"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.extensionStep1")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("browserAutomation.extensionStep1Desc")}),e.jsxs("button",{disabled:he,onClick:async()=>{ue(!0),Z(null);try{await F.settings.downloadExtensionZip()}catch{Z({type:"err",text:s("browserAutomation.extensionDownloadError")})}ue(!1)},className:"mt-2 inline-flex max-w-full items-center gap-1.5 px-3 py-1.5 text-xs text-left break-words bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:[e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),s(he?"browserAutomation.extensionStep1Downloading":"browserAutomation.extensionStep1Btn")]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[e.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"2"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.extensionStep2")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("browserAutomation.extensionStep2Desc")}),navigator.platform.toUpperCase().includes("WIN")?e.jsxs("div",{className:"mt-2 text-xs text-fg-secondary",children:[s("browserAutomation.extensionStep2Desc"),":",e.jsx("code",{className:"ml-1.5 px-1.5 py-0.5 bg-surface-elevated rounded text-fg-primary font-mono text-[11px] select-all",children:"chrome://extensions"})]}):e.jsxs("button",{onClick:async()=>{ue(!0),Z(null);try{await F.settings.openExtensionsPage()}catch{Z({type:"err",text:s("browserAutomation.extensionOpenError")})}ue(!1)},className:"mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-xs bg-surface-primary border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40",children:[e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),s("browserAutomation.extensionStep2Btn")]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-surface-primary/50",children:[e.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-brand-500 text-white text-[10px] font-bold shrink-0 mt-0.5",children:"3"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.extensionStep3")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("browserAutomation.extensionStep3Desc")})]})]})]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border-default flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mr-4",children:s("browserAutomation.backendVerifyDesc")}),e.jsx("button",{onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.testConcurrentBrowserQuick();Z({type:l.connected?"ok":"err",text:l.connected?s("browserAutomation.backendVerifyOk"):s("browserAutomation.backendVerifyFail",{error:l.summary||"backend not reachable"})})}catch(l){Z({type:"err",text:s("browserAutomation.backendVerifyFail",{error:l?.message||l||"unknown"})})}ue(!1)},disabled:he,className:"px-3 py-1.5 text-xs bg-surface-primary border border-border text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40 shrink-0",children:s(he?"browserAutomation.backendVerifying":"browserAutomation.backendVerify")})]})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 space-y-4 mb-4",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:s("browserAutomation.generalSettings")}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.bringToFront")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("browserAutomation.bringToFrontDesc")})]}),e.jsx("button",{onClick:async()=>{const l=!Ss;Zt(l),ue(!0),Z(null);try{const N=await F.settings.updateBrowser({bringToFront:l});Zt(N.bringToFront),Z({type:"ok",text:s(l?"browserAutomation.tabsForeground":"browserAutomation.tabsBackground")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")}),Zt(!l)}ue(!1)},disabled:he,className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${Ss?"bg-green-500":"bg-gray-600"} ${he?"opacity-50":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Ss?"translate-x-4":"translate-x-1"}`})})]}),e.jsxs("div",{className:"flex flex-col gap-3 border-t border-border-default pt-4 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.autoCloseTabs")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("browserAutomation.autoCloseTabsDesc")})]}),e.jsx("button",{onClick:async()=>{const l=!Ps;Xt(l),ue(!0),Z(null);try{const N=await F.settings.updateBrowser({autoCloseTabs:l});Xt(N.autoCloseTabs),Z({type:"ok",text:s("agentExecution.saved")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")}),Xt(!l)}ue(!1)},disabled:he,className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${Ps?"bg-green-500":"bg-gray-600"} ${he?"opacity-50":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Ps?"translate-x-4":"translate-x-1"}`})})]})]}),ut==="system-chrome"&&!ze&&e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-4 md:p-5 mb-4 space-y-4",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:s("browserAutomation.advancedOptions")}),e.jsx("div",{children:e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 md:mr-4",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.autoClickAllowDialog")}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:s("browserAutomation.autoClickAllowDialogDesc")}),e.jsxs("div",{className:"text-xs text-fg-tertiary mt-2 space-y-0.5",children:[e.jsx("div",{children:s("browserAutomation.autoClickAllowDialogMacNote")}),e.jsx("div",{children:s("browserAutomation.autoClickAllowDialogWinNote")}),e.jsx("div",{children:s("browserAutomation.autoClickAllowDialogLinuxNote")})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{disabled:he,onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.testAutoClick(),N={success:{type:"ok",text:s("browserAutomation.autoClickTestSuccess",{title:l.pageTitle||"example.com"})},no_permission:{type:"err",text:s("browserAutomation.autoClickTestNoPermission")},chrome_not_running:{type:"err",text:s("browserAutomation.autoClickTestChromeNotRunning")},unsupported:{type:"err",text:s("browserAutomation.autoClickTestUnsupported")},error:{type:"err",text:s("browserAutomation.autoClickTestError",{error:l.error||"unknown"})}};Z(N[l.clickResult]??{type:"err",text:l.clickResult})}catch{Z({type:"err",text:s("browserAutomation.autoClickTestError",{error:"request failed"})})}ue(!1)},className:"px-3 py-1.5 text-xs bg-surface-primary border border-border-default text-fg-primary rounded-lg hover:bg-surface-elevated transition-colors disabled:opacity-40",children:s(he?"browserAutomation.autoClickTesting":"browserAutomation.autoClickTest")}),e.jsx("button",{onClick:async()=>{const l=!Ms;es(l),ue(!0),Z(null);try{const N=await F.settings.updateBrowser({autoClickAllowDialog:l});es(N.autoClickAllowDialog),Z({type:"ok",text:s("agentExecution.saved")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")}),es(!l)}ue(!1)},disabled:he,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Ms?"bg-green-500":"bg-gray-600"} ${he?"opacity-50":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Ms?"translate-x-4":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"border-t border-border-default pt-4",children:e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:s("browserAutomation.remoteDebuggingPort")}),e.jsxs("div",{className:"text-xs text-fg-tertiary mt-0.5",children:[s("browserAutomation.remoteDebuggingPortDescLead")," ",e.jsx("code",{className:"text-fg-secondary bg-surface-primary px-1 rounded",children:"--remote-debugging-port=9222"})," ",s("browserAutomation.remoteDebuggingPortDescTail")]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("input",{type:"number",min:0,max:65535,value:Tr,onChange:l=>{As(Number(l.target.value)),Z(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right",placeholder:"0"}),e.jsx("button",{disabled:he,onClick:async()=>{ue(!0),Z(null);try{const l=await F.settings.updateBrowser({remoteDebuggingPort:Tr});As(l.remoteDebuggingPort),Z({type:"ok",text:l.remoteDebuggingPort>0?s("browserAutomation.usingPort",{port:l.remoteDebuggingPort}):s("browserAutomation.usingAutoConnect")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}ue(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:s(he?"common:saving":"common:save")})]})]})})]}),Ts&&e.jsx("div",{className:"mt-4",children:e.jsx(Ie,{type:Ts.type,text:Ts.text})})]}),!1]}),h==="search"&&e.jsx(bl,{}),h==="storage"&&e.jsx(e.Fragment,{children:e.jsx(Te,{title:s("dataStorage.title"),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5 space-y-5",children:[Es&&!$e&&e.jsx("div",{className:"text-sm text-fg-tertiary",children:s("dataStorage.scanning")}),$e&&(()=>{const l=[...$e.breakdown].filter(J=>J.size>0).sort((J,be)=>be.size-J.size),N=Math.max($e.totalSize,1),G=l.filter(J=>fr[J.name]==="safe").reduce((J,be)=>J+be.size,0),Y=J=>J==="safe"?"bg-fg-secondary/55":J==="caution"?"bg-fg-tertiary/45":"bg-fg-primary/25";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-2xl font-semibold tracking-tight text-fg-primary tabular-nums",children:pt($e.totalSize,s)}),e.jsx("div",{className:"text-xs text-fg-tertiary font-mono mt-1 truncate",title:$e.dataDir,children:$e.dataDir})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>mt(),disabled:Es,className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-primary/60 rounded-lg text-fg-secondary transition-colors disabled:opacity-40",children:s(Es?"dataStorage.scanning":"common:refresh")}),e.jsx("button",{onClick:()=>{F.system.openPath($e.dataDir)},className:"px-3 py-1.5 text-xs border border-border-default hover:bg-surface-primary/60 rounded-lg text-fg-secondary transition-colors",children:s("dataStorage.openInFinder")})]})]}),e.jsx("div",{className:"h-2 rounded-full bg-surface-primary overflow-hidden flex","aria-hidden":!0,children:l.map(J=>{const be=fr[J.name]??"caution",A=Math.max(J.size/N*100,J.size>0?.8:0);return e.jsx("div",{className:`h-full ${Y(be)}`,style:{width:`${A}%`},title:`${J.name}: ${pt(J.size,s)}`},J.name)})}),G>0&&e.jsx("p",{className:"text-xs text-fg-tertiary leading-relaxed",children:s("dataStorage.clearableHint",{size:pt(G,s),percent:Math.round(G/N*100)})})]}),e.jsxs("div",{className:"border-t border-border-default pt-4",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-3",children:[e.jsx("h4",{className:"text-xs font-semibold text-fg-secondary",children:s("dataStorage.storageBreakdown")}),e.jsx("span",{className:"text-[11px] text-fg-tertiary",children:s("dataStorage.sortedBySize")})]}),e.jsx("div",{className:"divide-y divide-border-default/70 rounded-xl border border-border-default/70 overflow-hidden",children:l.map(J=>{const be=yl[J.name],A=fr[J.name]??"caution",q=be?s(`dataStorage.items.${be}.label`):J.name,gt=be?s(`dataStorage.items.${be}.blurb`):J.description,Fs=Math.round(J.size/N*100);return e.jsxs("div",{className:"flex items-center gap-3 px-3.5 py-3 bg-surface-primary/25 hover:bg-surface-primary/45 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:q}),A==="safe"&&e.jsx("span",{className:"shrink-0 text-[10px] px-1.5 py-0.5 rounded-md bg-surface-elevated text-fg-secondary border border-border-default/80",children:s("dataStorage.safetyLevel.safe")})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 leading-relaxed",children:gt})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary tabular-nums",children:pt(J.size,s)}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary tabular-nums mt-0.5",children:[Fs,"%"]})]}),e.jsx("button",{type:"button",onClick:()=>{F.system.openPath(J.path)},className:"shrink-0 px-2.5 py-1 text-xs border border-border-default hover:bg-surface-elevated rounded-lg text-fg-secondary transition-colors",title:J.path,children:s("dataStorage.openFolder")})]},J.name)})})]}),ts&&(ts.orphanAgents.length>0||ts.orphanTeams.length>0)&&e.jsx(Ml,{orphanInfo:ts,dataDir:$e.dataDir,onPurged:mt,formatBytes:J=>pt(J,s)})]})})()]})})}),(h==="account"||h==="users"||h==="organization"||h==="license")&&e.jsx(El,{authUser:i}),h==="remote"&&e.jsx(el,{}),h==="integrations"&&e.jsx(e.Fragment,{children:e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-4",children:s("nav.integrations")}),e.jsx(Zo,{})]})})]}),e.jsx("div",{className:"h-8"})]}),$s&&e.jsx(fs,{title:s("common:delete"),message:s("modelProviders.deleteConfirm",{name:$s.label}),confirmLabel:s("common:delete"),onConfirm:()=>{const l=$s.name;Vs(null),Wa(l)},onCancel:()=>Vs(null)}),j&&a&&e.jsx(fs,{title:s("common:signOutConfirmTitle"),message:s("common:signOutConfirmMessage"),confirmLabel:s("common:signOut"),variant:"primary",onConfirm:()=>{w(!1),a()},onCancel:()=>w(!1)})]})]})}const na=["owner","admin","member","guest"],Nl={owner:"bg-amber-500/10 text-amber-600 border-amber-500/30",admin:"bg-brand-500/10 text-brand-500 border-brand-500/30",member:"bg-green-500/10 text-green-600 border-green-500/30",guest:"bg-gray-500/10 text-gray-500 border-gray-500/30"};function wl({authUser:t}){const{t:r}=xe(["settings","common"]),[i,a]=o.useState([]),[n,s]=o.useState(!0),[c,d]=o.useState(null),[u,p]=o.useState(""),[x,k]=o.useState(""),[y,j]=o.useState(""),[w,b]=o.useState(null),[S,h]=o.useState(""),[P,m]=o.useState(null),[v,$]=o.useState(null),[I,R]=o.useState(null),[V,C]=o.useState(!1),[M,B]=o.useState(""),[L,U]=o.useState(""),[H,W]=o.useState("member"),[O,_]=o.useState(""),X=o.useCallback(()=>{F.users.list(t?.orgId).then(f=>a(f.users)).catch(()=>{}).finally(()=>s(!1))},[t?.orgId]);o.useEffect(()=>{X()},[X]);const ce=f=>{d(f.id),p(f.name),k(f.role),j(f.email??""),R(null)},oe=async()=>{if(c)try{await F.users.update(c,{name:u,role:x,email:y||void 0}),d(null),R({type:"ok",text:r("settings:userManagement.updateSuccess")}),X()}catch(f){R({type:"err",text:`${r("settings:userManagement.error")}: ${String(f)}`})}},ee=async()=>{if(!(!w||!S))try{await F.users.resetPassword(w,S),b(null),h(""),R({type:"ok",text:r("settings:userManagement.resetSuccess")})}catch(f){R({type:"err",text:`${r("settings:userManagement.error")}: ${String(f)}`})}},g=async f=>{if(f===t?.id){R({type:"err",text:r("settings:userManagement.cannotDeleteSelf")}),m(null);return}if(i.find(z=>z.id===f)?.role==="owner"){R({type:"err",text:r("settings:userManagement.cannotDeleteOwner")}),m(null);return}try{await F.users.remove(f),m(null),R({type:"ok",text:r("settings:userManagement.deleteSuccess")}),X()}catch(z){R({type:"err",text:`${r("settings:userManagement.error")}: ${String(z)}`})}},T=async()=>{if(M.trim())try{const f=await F.users.create(M.trim(),H,void 0,L.trim()||void 0,O||void 0);C(!1),B(""),U(""),W("member"),_(""),R({type:"ok",text:r("settings:userManagement.addSuccess",{defaultValue:"User created"})}),f.inviteToken&&$(`${window.location.origin}/#invite?token=${f.inviteToken}`),X()}catch(f){R({type:"err",text:`${r("settings:userManagement.error")}: ${f instanceof Error?f.message:String(f)}`})}};return e.jsxs(Te,{title:r("settings:userManagement.title"),children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-xs text-fg-tertiary leading-relaxed",children:r("settings:userManagement.sharedInstanceDesc")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:r("settings:userManagement.orgHint")})]}),V?e.jsxs("div",{className:"mb-3 p-4 rounded-lg border border-border-default space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-fg-tertiary mb-1 block",children:r("settings:userManagement.name")}),e.jsx("input",{value:M,onChange:f=>B(f.target.value),autoFocus:!0,className:"w-full px-3 py-1.5 text-sm bg-surface-elevated border border-border-default rounded-md text-fg-primary"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-fg-tertiary mb-1 block",children:r("settings:userManagement.email")}),e.jsx("input",{value:L,onChange:f=>U(f.target.value),type:"email",className:"w-full px-3 py-1.5 text-sm bg-surface-elevated border border-border-default rounded-md text-fg-primary"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-fg-tertiary mb-1 block",children:r("settings:userManagement.role")}),e.jsx("select",{value:H,onChange:f=>W(f.target.value),className:"w-full px-3 py-1.5 text-sm bg-surface-elevated border border-border-default rounded-md text-fg-primary",children:na.map(f=>e.jsx("option",{value:f,children:r(`settings:userManagement.roles.${f}`)},f))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-fg-tertiary mb-1 block",children:r("settings:userManagement.password",{defaultValue:"Password"})}),e.jsx("input",{value:O,onChange:f=>_(f.target.value),type:"password",className:"w-full px-3 py-1.5 text-sm bg-surface-elevated border border-border-default rounded-md text-fg-primary"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx("button",{onClick:()=>{C(!1),B(""),U(""),W("member"),_("")},className:"px-3 py-1.5 text-xs text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:T,disabled:!M.trim(),className:"px-4 py-1.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-xs font-medium rounded-lg",children:r("settings:userManagement.save")})]})]}):e.jsx("button",{onClick:()=>C(!0),className:"mb-3 px-4 py-2 bg-brand-600 hover:bg-brand-500 text-white text-xs font-medium rounded-lg transition-colors",children:r("settings:userManagement.addUser",{defaultValue:"Add User"})}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl overflow-hidden",children:[I&&e.jsx("div",{className:`px-4 py-2 text-xs border-b ${I.type==="ok"?"bg-green-500/10 text-green-600 border-green-500/20":"bg-red-500/10 text-red-500 border-red-500/20"}`,children:I.text}),v&&e.jsxs("div",{className:"px-4 py-3 bg-brand-500/5 border-b border-brand-500/20 flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[11px] text-fg-tertiary mb-1",children:r("settings:userManagement.copyInviteLink")}),e.jsx("code",{className:"text-[10px] text-brand-500 bg-surface-elevated px-2 py-1 rounded block truncate",children:v})]}),e.jsx("button",{onClick:()=>{navigator.clipboard.writeText(v),R({type:"ok",text:r("settings:userManagement.linkCopied")})},className:"shrink-0 px-3 py-1.5 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg font-medium",children:r("settings:userManagement.copy")}),e.jsx("button",{onClick:()=>$(null),className:"shrink-0 text-fg-tertiary hover:text-fg-secondary text-sm",children:"×"})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border-default/60 text-fg-tertiary text-[11px] uppercase tracking-wider",children:[e.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:r("settings:userManagement.name")}),e.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:r("settings:userManagement.email")}),e.jsx("th",{className:"text-left px-4 py-2.5 font-medium",children:r("settings:userManagement.role")}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:r("settings:userManagement.actions")})]})}),e.jsxs("tbody",{children:[n&&i.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-4 py-6",children:e.jsx(vi,{rows:3,variant:"skeleton"})})}),!n&&i.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-4 py-6 text-center text-fg-tertiary text-xs",children:r("settings:userManagement.noUsers")})}),i.map(f=>{const K=c===f.id,z=w===f.id,se=P===f.id,ae=f.id===t?.id,ge=f.role==="owner";return e.jsxs("tr",{className:"border-b border-border-default/40 last:border-b-0 hover:bg-surface-elevated/40 transition-colors",children:[e.jsx("td",{className:"px-4 py-2.5",children:K?e.jsx("input",{value:u,onChange:te=>p(te.target.value),className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-fg-primary font-medium text-xs",children:f.name}),ae&&e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500",children:"you"})]})}),e.jsx("td",{className:"px-4 py-2.5",children:K?e.jsx("input",{value:y,onChange:te=>j(te.target.value),placeholder:"email@example.com",className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):e.jsx("span",{className:"text-fg-secondary text-xs",children:f.email||"—"})}),e.jsx("td",{className:"px-4 py-2.5",children:K?e.jsx("select",{value:x,onChange:te=>k(te.target.value),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50",children:na.map(te=>e.jsx("option",{value:te,children:r(`settings:userManagement.roles.${te}`)},te))}):e.jsx("span",{className:`inline-block text-[10px] px-2 py-0.5 rounded-full border font-medium ${Nl[f.role]??""}`,children:r(`settings:userManagement.roles.${f.role}`)})}),e.jsx("td",{className:"px-4 py-2.5 text-right",children:K?e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>d(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:oe,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium",children:r("settings:userManagement.save")})]}):z?e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("input",{type:"password",value:S,onChange:te=>h(te.target.value),placeholder:r("settings:userManagement.newPassword"),autoFocus:!0,className:"w-32 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),e.jsx("button",{onClick:()=>{b(null),h("")},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:ee,disabled:S.length<6,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium disabled:opacity-40",children:r("settings:userManagement.confirmReset")})]}):se?e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("span",{className:"text-[10px] text-red-500",children:r("settings:userManagement.confirmDelete")}),e.jsx("button",{onClick:()=>m(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:()=>g(f.id),className:"text-[11px] text-red-500 hover:text-red-400 font-medium",children:r("settings:userManagement.deleteUser")})]}):e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("button",{onClick:()=>ce(f),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary px-1.5 py-0.5 rounded hover:bg-surface-elevated",children:r("settings:userManagement.editUser")}),f.email&&e.jsx("button",{onClick:()=>{b(f.id),h(""),R(null)},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary px-1.5 py-0.5 rounded hover:bg-surface-elevated",children:r("settings:userManagement.resetPassword")}),f.email&&!ge&&!f.hasJoined&&e.jsx("button",{onClick:async()=>{try{const{inviteToken:te}=await F.users.reinvite(f.id),Je=`${window.location.origin}/#invite?token=${te}`;$(Je),R({type:"ok",text:r("settings:userManagement.inviteLinkGenerated")})}catch(te){R({type:"err",text:String(te)})}},className:"text-[11px] text-brand-400 hover:text-brand-500 px-1.5 py-0.5 rounded hover:bg-brand-500/10",children:r("settings:userManagement.inviteLink")}),!ge&&!ae&&e.jsx("button",{onClick:()=>{m(f.id),R(null)},className:"text-[11px] text-red-400 hover:text-red-500 px-1.5 py-0.5 rounded hover:bg-red-500/10",children:r("settings:userManagement.deleteUser")})]})})]},f.id)})]})]})})]})]})}const kl={audio_speech:{label:"TTS",color:"bg-purple-500/20 text-purple-400"},image_generation:{label:"Image",color:"bg-blue-500/20 text-blue-400"},video_generation:{label:"Video",color:"bg-pink-500/20 text-pink-400"},audio_transcription:{label:"STT",color:"bg-teal-500/20 text-teal-400"},ocr:{label:"OCR",color:"bg-orange-500/20 text-orange-400"}},aa={chat:0,image_generation:1,video_generation:2,audio_speech:3,audio_transcription:4,ocr:5},ia=5;function Cl({models:t,providerName:r,activeModelId:i,t:a,onDeleteCustom:n}){const s=t.length>ia,[c,d]=o.useState(!s),[u,p]=o.useState(""),x=o.useMemo(()=>{const y=u.trim().toLowerCase();return y?t.filter(j=>j.id.toLowerCase().includes(y)||j.name.toLowerCase().includes(y)):t},[t,u]),k=c?x:x.slice(0,ia);return e.jsxs("div",{className:"space-y-1",children:[s&&e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1 mb-1",children:[e.jsxs("button",{type:"button",onClick:()=>d(y=>!y),className:"flex items-center gap-1.5 text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:[e.jsx("svg",{className:`w-3 h-3 transition-transform ${c?"rotate-90":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),c?a("modelProviders.collapseModels"):a("modelProviders.showAllModels",{count:t.length})]}),c&&e.jsx("input",{value:u,onChange:y=>p(y.target.value),placeholder:a("modelProviders.filterModels"),className:"flex-1 min-w-0 max-w-[220px] px-2 py-1 text-[10px] rounded-md bg-surface-overlay/50 border border-border-default text-fg-secondary placeholder:text-fg-tertiary"})]}),e.jsx("div",{className:c&&s?"max-h-64 overflow-y-auto space-y-1 pr-0.5":"space-y-1",children:k.map(y=>{const j=y.source==="custom",w=y.capabilities??[],b=i===y.id;return e.jsxs("div",{className:`flex items-center justify-between px-3 py-1.5 rounded-lg text-xs ${b?"bg-brand-500/10 border border-brand-500/20":"bg-surface-elevated/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-w-0",children:[e.jsx("span",{className:"text-fg-secondary truncate",children:y.name}),b&&e.jsx("span",{className:"text-[9px] bg-brand-500/15 text-brand-500 px-1 py-0.5 rounded shrink-0",children:a("modelProviders.badgeDefault")}),e.jsx(Il,{modelId:y.id,tier:y.tier}),y.reasoning&&e.jsx("span",{className:"text-[9px] bg-amber-500/15 text-amber-600 px-1 py-0.5 rounded",children:a("modelProviders.reasoning")}),(y.inputTypes?.includes("image")||w.includes("vision"))&&e.jsx("span",{className:"text-[9px] bg-blue-500/15 text-blue-600 px-1 py-0.5 rounded",children:a("modelProviders.vision")}),w.includes("imageGeneration")&&e.jsx("span",{className:"text-[9px] bg-cyan-500/15 text-cyan-600 px-1 py-0.5 rounded",children:a("modelProviders.capImageGen")}),(w.includes("tts")||w.includes("audioOutput"))&&e.jsx("span",{className:"text-[9px] bg-emerald-500/15 text-emerald-600 px-1 py-0.5 rounded",children:a("modelProviders.capTts")}),(w.includes("stt")||w.includes("audioInput"))&&e.jsx("span",{className:"text-[9px] bg-teal-500/15 text-teal-600 px-1 py-0.5 rounded",children:a("modelProviders.capStt")}),w.includes("videoGeneration")&&e.jsx("span",{className:"text-[9px] bg-orange-500/15 text-orange-600 px-1 py-0.5 rounded",children:a("modelProviders.capVideo")}),j&&r!=="markus"&&e.jsx("span",{className:"text-[9px] bg-purple-500/15 text-purple-400 px-1 py-0.5 rounded",children:a("modelProviders.custom")})]}),e.jsxs("div",{className:"flex items-center gap-3 text-fg-tertiary shrink-0",children:[(y.contextWindow??0)>0&&e.jsx("span",{children:a("modelProviders.ctxTokens",{size:((y.contextWindow??0)/1e3).toFixed(0)})}),j&&r!=="markus"&&e.jsx("button",{onClick:S=>{S.stopPropagation(),n(y.id)},className:"text-red-400 hover:text-red-300 transition-colors",title:a("modelProviders.deleteCustomModelTitle"),children:e.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]},y.id)})}),s&&!c&&e.jsx("button",{type:"button",onClick:()=>d(!0),className:"w-full text-[10px] text-fg-tertiary hover:text-brand-500 transition-colors py-1.5",children:a("modelProviders.showAllModels",{count:t.length})}),c&&u&&x.length===0&&e.jsx("div",{className:"text-[10px] text-fg-tertiary px-1 py-2",children:a("modelProviders.noFilterMatches")})]})}function Sl({models:t,providerName:r,t:i,onAdd:a}){const[n,s]=o.useState(!1),c=o.useMemo(()=>[...t].sort((d,u)=>{const p=aa[d.mode??"chat"]??99,x=aa[u.mode??"chat"]??99;return p!==x?p-x:String(d.id??"").localeCompare(String(u.id??""))}),[t]);return e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{onClick:()=>s(!n),className:"flex items-center gap-1.5 text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors px-1",children:[e.jsx("svg",{className:`w-3 h-3 transition-transform ${n?"rotate-90":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),i("modelProviders.catalogModelsAvailable",{count:t.length})]}),n&&e.jsx("div",{className:"mt-1 space-y-0.5 pl-1 max-h-64 overflow-y-auto",children:c.map(d=>{const u=String(d.id??""),p=d.mode??"chat",x=kl[p];return e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded hover:bg-surface-overlay/60 group",children:[e.jsx("span",{className:"text-[11px] text-fg-secondary flex-1 truncate",children:u}),x&&e.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full shrink-0 ${x.color}`,children:x.label}),e.jsx("button",{onClick:()=>a(u),className:"text-[9px] text-brand-500 hover:text-brand-400 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity shrink-0",children:i("modelProviders.addModel")})]},u)})})]})}function Al({providerName:t,addModelForm:r,setAddModelForm:i,addModelSaving:a,onAdd:n,onCancel:s,t:c}){const[d,u]=o.useState([]),[p,x]=o.useState(!1),[k,y]=o.useState(!1),j=async()=>{x(!0);try{const w=await F.modelCatalog.getByProvider(t);u(w.models),y(!0)}catch{u([])}finally{x(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-[10px] text-fg-secondary",children:c("modelProviders.addModelTitle")}),e.jsx("button",{onClick:()=>{j()},disabled:p,className:"text-[10px] text-brand-500 hover:text-brand-400 disabled:opacity-40 transition-colors",children:p?"...":c("modelProviders.browseFromCatalog")})]}),k&&d.length>0&&e.jsx("div",{className:"border border-border-default rounded-lg p-2 mb-2",children:e.jsx(da,{provider:t,models:d,selectedModel:r.id,showTiers:!0,onSelect:w=>{const b=d.find(S=>S.id===w);b&&i(S=>({...S,id:b.id,name:b.id,contextWindow:b.maxInputTokens,maxOutputTokens:b.maxOutputTokens,costInput:b.inputCostPer1MTokens,costOutput:b.outputCostPer1MTokens,reasoning:b.capabilities.reasoning,vision:b.capabilities.vision}))},compact:!0,maxVisible:5})}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsx("input",{type:"text",placeholder:c("modelProviders.modelId"),value:r.id,onChange:w=>i({...r,id:w.target.value}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),e.jsx("input",{type:"text",placeholder:c("modelProviders.displayName"),value:r.name,onChange:w=>i({...r,name:w.target.value}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"}),e.jsx("input",{type:"number",placeholder:c("modelProviders.placeholderContextTokens"),value:r.contextWindow,onChange:w=>i({...r,contextWindow:Number(w.target.value)}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"}),e.jsx("input",{type:"number",placeholder:c("modelProviders.maxOutput"),value:r.maxOutputTokens,onChange:w=>i({...r,maxOutputTokens:Number(w.target.value)}),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:c("modelProviders.costPerMillionIn")}),e.jsx("input",{type:"number",step:"0.01",value:r.costInput,onChange:w=>i({...r,costInput:Number(w.target.value)}),className:"w-16 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:c("modelProviders.costPerMillionOut")}),e.jsx("input",{type:"number",step:"0.01",value:r.costOutput,onChange:w=>i({...r,costOutput:Number(w.target.value)}),className:"w-16 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded text-fg-primary focus:border-brand-500 outline-none"})]}),e.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-fg-tertiary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.reasoning,onChange:w=>i({...r,reasoning:w.target.checked}),className:"rounded"}),c("modelProviders.reasoning")]}),e.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-fg-tertiary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r.vision,onChange:w=>i({...r,vision:w.target.checked}),className:"rounded"}),c("modelProviders.vision")]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:n,disabled:a||!r.id||!r.name,className:"px-2 py-1 text-[10px] bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white rounded transition-colors whitespace-nowrap",children:c(a?"modelProviders.adding":"common:create")}),e.jsx("button",{onClick:s,className:"px-2 py-1 text-[10px] border border-border-default text-fg-secondary hover:bg-surface-elevated rounded transition-colors whitespace-nowrap",children:c("common:cancel")})]})]})}function Ie({type:t,text:r}){return e.jsx("div",{className:`text-xs px-3 py-2 rounded-lg ${t==="ok"?"bg-green-500/10 text-green-600 border border-green-500/30":"bg-red-500/10 text-red-500 border border-red-500/30"}`,children:r})}function Pl({title:t,defaultCollapsed:r,configuredProviders:i,t:a,children:n,onBadgeClick:s}){const[c,d]=o.useState(r);return e.jsxs("section",{children:[e.jsxs("button",{type:"button",onClick:()=>d(!c),className:"flex items-center justify-between w-full group mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider",children:t}),c&&i.length>0&&e.jsxs("span",{className:"text-xs text-fg-tertiary",children:["(",i.length," ",a("modelProviders.configuredCount"),")"]})]}),e.jsx("span",{className:`text-fg-tertiary text-xs transition-transform group-hover:text-fg-secondary ${c?"-rotate-90":""}`,children:"▼"})]}),c&&i.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[i.map(([u,p])=>e.jsxs("button",{type:"button",onClick:x=>{x.stopPropagation(),d(!1),s?.(u)},className:`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs rounded-lg border cursor-pointer transition-colors ${p.enabled?"bg-green-500/10 border-green-500/30 text-green-400 hover:bg-green-500/20":"bg-surface-elevated border-border-default text-fg-tertiary hover:border-gray-500"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${p.enabled?"bg-green-400":"bg-gray-500"}`}),p.displayName??u]},u)),e.jsxs("button",{type:"button",onClick:()=>d(!1),title:a("modelProviders.manageProvidersHint"),"aria-label":a("modelProviders.addProviderCta"),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg border border-brand-500/50 bg-brand-500/10 text-brand-500 hover:bg-brand-500/20 hover:border-brand-500 transition-colors",children:[e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4.5v15m7.5-7.5h-15"})}),a("modelProviders.addProviderCta")]})]}),!c&&e.jsx("div",{className:"space-y-4",children:n})]})}function Te({title:t,children:r}){return e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-4",children:t}),e.jsx("div",{className:"space-y-4",children:r})]})}function pr({title:t,children:r,defaultOpen:i=!0}){const[a,n]=o.useState(i);return e.jsxs("section",{children:[e.jsxs("button",{type:"button",onClick:()=>n(!a),className:"flex items-center justify-between w-full group mb-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider",children:t}),e.jsx("span",{className:`text-fg-tertiary text-xs transition-transform group-hover:text-fg-secondary ${a?"":"-rotate-90"}`,children:"▼"})]}),a&&e.jsx("div",{className:"space-y-4",children:r})]})}function hr({label:t,value:r,color:i}){const a=i==="green"?"bg-green-500/10 text-green-600":"bg-brand-500/10 text-brand-500";return e.jsxs("div",{className:`rounded-xl px-5 py-4 ${a}`,children:[e.jsx("div",{className:"text-2xl font-bold",children:r}),e.jsx("div",{className:"text-xs mt-1 opacity-70",children:t})]})}function pt(t,r){if(t===0)return r?r("dataStorage.bytesZero"):"0 B";const i=r?[r("dataStorage.unitB"),r("dataStorage.unitKB"),r("dataStorage.unitMB"),r("dataStorage.unitGB")]:["B","KB","MB","GB"],a=Math.min(Math.floor(Math.log(t)/Math.log(1024)),i.length-1),n=t/Math.pow(1024,a);return`${n<10?n.toFixed(1):Math.round(n)} ${i[a]}`}function Ml({orphanInfo:t,dataDir:r,onPurged:i,formatBytes:a}){const{t:n}=xe(["settings","common"]),s=[...t.orphanAgents.map(h=>({...h,kind:"agent"})),...t.orphanTeams.map(h=>({...h,kind:"team"}))],[c,d]=o.useState(new Set),[u,p]=o.useState(!1),[x,k]=o.useState(null),y=h=>d(P=>{const m=new Set(P);return m.has(h)?m.delete(h):m.add(h),m}),j=c.size===s.length&&s.length>0,w=()=>d(j?new Set:new Set(s.map(h=>h.id))),b=s.filter(h=>c.has(h.id)).reduce((h,P)=>h+P.size,0),S=async h=>{p(!0),k(null);try{const P=await F.system.purgeOrphans(h),m=P.purgedAgents.length+P.purgedTeams.length,v=n("dataStorage.cleaned",{count:m,size:a(P.freedBytes)});k(P.failures.length?n("dataStorage.cleanedWithFailureNote",{base:v,count:P.failures.length}):v),d(new Set),i()}catch{k(n("dataStorage.cleanupFailed"))}finally{p(!1)}};return e.jsxs("div",{className:"border-t border-border-default pt-4",children:[e.jsx("h4",{className:"text-xs font-semibold text-amber-500 mb-2",children:n("dataStorage.orphanedDirectories")}),e.jsxs("p",{className:"text-xs text-fg-tertiary mb-3",children:[n("dataStorage.orphanedDesc")," ",n("dataStorage.orphanedTotal",{size:a(t.totalOrphanSize),count:s.length})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-2 px-1",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-[10px] text-fg-tertiary cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:w,className:"rounded"}),n("common:selectAll")]}),c.size>0&&e.jsx("span",{className:"text-[10px] text-fg-secondary",children:n("dataStorage.selectedWithSize",{count:c.size,size:a(b)})})]}),e.jsx("div",{className:"space-y-0.5 mb-3 max-h-52 overflow-y-auto",children:s.map(h=>e.jsxs("div",{className:`flex items-center gap-2 text-xs py-1.5 px-2 rounded transition-colors ${c.has(h.id)?"bg-amber-500/10":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:[e.jsx("input",{type:"checkbox",checked:c.has(h.id),onChange:()=>y(h.id),className:"rounded shrink-0"}),h.kind==="team"&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:n("dataStorage.teamKind")}),e.jsx("span",{className:"text-fg-tertiary font-mono truncate min-w-0 flex-1",children:h.id}),e.jsx("span",{className:"text-fg-secondary tabular-nums shrink-0",children:a(h.size)}),e.jsx("button",{onClick:()=>{F.system.openPath(h.path)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary shrink-0 underline",children:n("common:open")})]},h.id))}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[c.size>0&&e.jsx("button",{disabled:u,onClick:()=>{S([...c])},className:"px-3 py-1.5 text-xs bg-amber-600 hover:bg-amber-500 text-white rounded-lg transition-colors disabled:opacity-50",children:u?n("dataStorage.cleaning"):n("dataStorage.cleanSelected",{size:a(b)})}),e.jsx("button",{disabled:u,onClick:()=>{S()},className:"px-3 py-1.5 text-xs border border-amber-600/50 hover:bg-amber-600/10 text-amber-500 rounded-lg transition-colors disabled:opacity-50",children:u?n("dataStorage.cleaning"):n("dataStorage.cleanAll",{size:a(t.totalOrphanSize)})})]}),x&&e.jsx("div",{className:"text-xs text-fg-tertiary mt-2",children:x})]})}const Tl={multi_user:"👥",sso:"🔐",audit_enhanced:"📋",multi_instance:"🌐",offline_license:"📡"};function El({authUser:t}){const{t:r}=xe(["settings","common"]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-fg-primary mb-1",children:r("account.title")}),e.jsx("p",{className:"text-xs text-fg-tertiary",children:r("account.subtitle")})]}),e.jsx(Ll,{}),e.jsx(wl,{authUser:t})]})}function Ll(){const{t}=xe(["settings","common"]),[r,i]=o.useState(null),[a,n]=o.useState(!0),[s,c]=o.useState([]),[d,u]=o.useState([]),[p,x]=o.useState(null),[k,y]=o.useState(!0),[j,w]=o.useState(!1),[b,S]=o.useState(null),[h,P]=o.useState(!1),m=o.useCallback((W=!1)=>{y(!0),F.hubOrgs.mine().catch(O=>(W&&x({type:"err",text:O instanceof Error?O.message:t("org.loadFailed")}),{orgs:[]})).then(O=>{c(O.orgs),F.hubOrgs.invitations().then(_=>u(_.invitations)).catch(()=>{})}).finally(()=>y(!1))},[t]);o.useEffect(()=>{if(!oa()&&!Us()){y(!1),n(!1);return}m(),Ot.user.plan().then(W=>i(W)).catch(()=>{}).finally(()=>n(!1))},[m]);const v=o.useCallback((W=!1)=>{P(!0),(W?F.license.refresh():F.license.get()).then(_=>S(_)).catch(()=>{}).finally(()=>setTimeout(()=>P(!1),400))},[]);o.useEffect(()=>{v(!0)},[v]);const $=b?.plan==="enterprise",I=async W=>{try{await F.hubOrgs.acceptInvitation(W),u(O=>O.filter(_=>_.orgId!==W)),m()}catch(O){x({type:"err",text:O instanceof Error?O.message:"Failed"})}},R=b?.validUntil?Math.max(0,Math.ceil((new Date(b.validUntil).getTime()-Date.now())/864e5)):null,V=["multi_user","multi_instance"],C={multi_user:t("license.featureMultiUser"),multi_instance:t("license.featureMultiInstance")},M=s.find(W=>W.id===r?.orgId)??s[0],B=r?r.creditsBudgetCu??(r.monthlyQuotaCu??0)+(r.bonusCu??0)+(r.purchasedCu??0):0,L=!!(r?.memberCuLimit!=null&&r.memberCuLimit>0&&M&&M.role!=="owner"&&M.role!=="admin"&&M.memberCount>1),U=Math.round(L?r?.memberCuUsed??0:r?.totalConsumedThisPeriod??r?.cuUsed??0),H=L?r?.memberCuLimit??0:B;return k||a?e.jsx("div",{className:"text-center py-8 text-fg-tertiary text-sm",children:t("common:loading")}):e.jsxs("div",{className:"space-y-6",children:[p&&e.jsxs("div",{className:`flex items-center gap-2 text-sm px-4 py-3 rounded-lg ${p.type==="ok"?"bg-green-500/10 text-green-600 border border-green-500/20":"bg-red-500/10 text-red-500 border border-red-500/20"}`,children:[e.jsx("span",{children:p.type==="ok"?"✓":"✕"}),e.jsx("span",{children:p.text})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-3",children:t("account.cloudAiTitle")}),e.jsxs("div",{className:"rounded-lg border border-border-default bg-gradient-to-r from-brand-600/5 to-transparent px-5 py-4 space-y-3",children:[r?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-fg-tertiary",children:t("account.currentPlan")}),e.jsx("span",{className:"px-2 py-0.5 rounded text-xs font-semibold capitalize bg-brand-600/10 text-brand-500 border border-brand-500/15",children:r.planType})]}),H>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:t(L?"account.personalLimit":"account.credits")}),e.jsxs("span",{className:"font-medium text-fg-primary tabular-nums",children:[U.toLocaleString()," / ",H.toLocaleString()]})]})]}):e.jsx("p",{className:"text-xs text-fg-secondary",children:t("license.cloudAiDesc")}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs("a",{href:`${Ot.getUrl()}/settings?tab=billing`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-4 py-2 bg-brand-600 hover:bg-brand-500 text-white text-xs font-medium rounded-lg transition-colors no-underline",children:[e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),t("account.manageBilling")]})})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider mb-3",children:t("account.orgSection")}),d.length>0&&e.jsx("div",{className:"space-y-2 mb-3",children:d.map(W=>e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 rounded-lg border border-amber-500/20 bg-amber-500/5",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-fg-primary",children:W.orgName}),e.jsxs("span",{className:"text-fg-tertiary ml-1",children:["— ",t("org.invitedBy")," ",W.invitedBy]})]}),e.jsx("button",{onClick:()=>{I(W.orgId)},className:"px-3 py-1.5 bg-brand-600 hover:bg-brand-500 text-white text-xs font-medium rounded-lg transition-colors",children:t("org.accept")})]},W.orgId))}),M?e.jsxs("div",{className:"rounded-lg border border-border-default px-5 py-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:t("org.nameLabel")}),e.jsx("span",{className:"font-medium text-fg-primary",children:M.name})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:t("account.memberCount")}),e.jsx("span",{className:"font-medium text-fg-primary",children:M.memberCount})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:t("org.orgId")}),e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-surface-elevated text-fg-secondary text-[11px]",children:M.id})]}),e.jsxs("a",{href:`${Ot.getUrl()}/settings?tab=organization`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-4 py-2 border border-border-default text-fg-secondary hover:bg-surface-elevated text-xs font-medium rounded-lg transition-colors no-underline",children:[e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),t("account.manageOrg")]})]}):e.jsxs("div",{className:"rounded-lg border border-border-default px-5 py-6 text-center space-y-3",children:[e.jsx("div",{className:"text-sm text-fg-tertiary",children:t("org.noOrg")}),!!Us()&&e.jsx("div",{className:"text-xs text-amber-500/90",children:t("org.staleSessionHint")}),e.jsxs("button",{disabled:j,onClick:()=>{x(null),w(!0),la({force:!0}).then(()=>m(!0)).catch(W=>{const O=W instanceof Error?W.message:String(W),_=O.includes("Popup blocked")?t("org.popupBlocked"):O.includes("cancelled")?t("org.loginCancelled"):O;x({type:"err",text:_})}).finally(()=>w(!1))},className:"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-60 text-white text-sm font-medium rounded-lg transition-colors inline-flex items-center gap-2",children:[j&&e.jsx("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:e.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeDasharray:"30 70",strokeLinecap:"round"})}),j?t("org.connecting"):Us()?t("org.reconnectHub"):t("org.connectHub")]})]})]}),$&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-secondary uppercase tracking-wider",children:t("license.title")}),e.jsxs("button",{onClick:()=>v(!0),disabled:h,className:"ml-auto flex items-center gap-1.5 text-xs text-fg-tertiary hover:text-fg-secondary disabled:opacity-50 transition-colors",children:[e.jsx("svg",{className:`w-3.5 h-3.5 ${h?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 4v5h5M20 20v-5h-5M4.05 11A8 8 0 0119.95 9M19.95 13A8 8 0 014.05 15"})}),t("license.refresh")]})]}),e.jsx(Rl,{isEnterprise:!0,licenseInfo:b,daysRemaining:R,effectiveValidUntil:b?.validUntil,effectiveMaxSeats:b?.maxSeats,effectiveUsedSeats:M?.memberCount??b?.usedSeats??0,effectiveOrgName:M?.name??b?.orgName,featureKeys:V,featureI18n:C,t})]}),e.jsxs("div",{className:"flex items-center gap-4 text-[11px] text-fg-tertiary pt-1",children:[e.jsx("a",{href:"https://markus.global",target:"_blank",rel:"noopener noreferrer",className:"hover:text-fg-secondary transition-colors",children:t("license.website")}),e.jsx("a",{href:`mailto:${t("license.salesEmail")}`,className:"hover:text-fg-secondary transition-colors",children:t("license.salesEmail")})]})]})}function Rl({isEnterprise:t,licenseInfo:r,daysRemaining:i,effectiveValidUntil:a,effectiveMaxSeats:n,effectiveUsedSeats:s,effectiveOrgName:c,featureKeys:d,featureI18n:u,t:p}){return t?e.jsx("div",{className:"rounded-lg border border-brand-500/20 overflow-hidden",children:e.jsxs("div",{className:"px-5 py-4 bg-gradient-to-r from-brand-600/5 to-transparent",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-base font-semibold text-fg-primary",children:p("license.planEnterprise")}),e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-500/12 text-green-600 border border-green-500/15",children:p("license.statusActive")}),r?.isTrial&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-amber-500/12 text-amber-600 border border-amber-500/15",children:p("license.trial")})]}),i!==null&&e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:`text-sm font-semibold tabular-nums ${i===0?"text-red-500":i<=7?"text-amber-500":i<=60?"text-amber-600":"text-fg-primary"}`,children:i>0?p("license.daysRemaining",{count:i}):p("license.expired")}),e.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:p("license.expiresOn",{date:new Date(a).toLocaleDateString()})})]})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5",children:d.map(x=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium text-brand-500 bg-brand-600/6 border border-brand-500/10",children:[Tl[x]," ",u[x]]},x))}),c&&e.jsxs("div",{className:"mt-3 grid grid-cols-1 md:grid-cols-2 gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg bg-surface-primary/40 border border-border-default/30",children:[e.jsx("span",{className:"text-fg-tertiary",children:p("license.organization")}),e.jsx("span",{className:"font-medium text-fg-primary",children:c})]}),n!=null&&e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg bg-surface-primary/40 border border-border-default/30",children:[e.jsx("span",{className:"text-fg-tertiary",children:p("license.seats")}),e.jsxs("span",{className:"font-medium text-fg-primary",children:[s," / ",n]})]})]})]})}):null}function Il({modelId:t,tier:r}){const{t:i}=xe("settings");let a;if(r==="max"||r==="pro"||r==="base")a=r;else{const s=t.toLowerCase(),c=/opus|5\.4|o3-(?!mini)|o1-(?!mini)|gemini.*ultra|sonnet-4-20/,d=/haiku|flash|nano|lite|small|fast|free|8b|7b|1b|3b/;/o4-mini|o3-mini|o1-mini|gpt-4o-mini/.test(s)?a="pro":c.test(s)?a="max":d.test(s)?a="base":a="pro"}const n={max:"bg-purple-500/15 text-purple-400",pro:"bg-blue-500/15 text-blue-400",base:"bg-gray-500/15 text-gray-400"};return e.jsx("span",{className:`text-[9px] px-1 py-0.5 rounded font-semibold uppercase ${n[a]}`,children:i(`modelRouting.tier.${a}`)})}export{Ma as SETTINGS_TABS,gr as SETTINGS_TAB_GROUPS,Fl as Settings,jl as resolveSettingsTab};
|