@markus-global/cli 0.12.2 → 0.12.3-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.
Files changed (88) hide show
  1. package/dist/commands/start.d.ts.map +1 -1
  2. package/dist/commands/start.js +15 -12
  3. package/dist/commands/start.js.map +1 -1
  4. package/dist/markus.mjs +2602 -2594
  5. package/dist/web-ui/assets/{AsyncState-C4a4KQ04.js → AsyncState-Co9o9Bjm.js} +1 -1
  6. package/dist/web-ui/assets/ChatComponents-CuWlVFJz.js +12 -0
  7. package/dist/web-ui/assets/{ContentRenderer-CkTLvnEu.js → ContentRenderer-B9gsL4I6.js} +6 -6
  8. package/dist/web-ui/assets/DeliverableShareModal-BUdo2qSE.js +1 -0
  9. package/dist/web-ui/assets/Deliverables-CDBY53C5.js +3 -0
  10. package/dist/web-ui/assets/MarkdownMessage-C3gog80t.js +4 -0
  11. package/dist/web-ui/assets/Search-DClPgzaq.js +1 -0
  12. package/dist/web-ui/assets/SendToChat-A26aOPb3.js +1 -0
  13. package/dist/web-ui/assets/Settings-BZ8jYVDO.js +8 -0
  14. package/dist/web-ui/assets/Store-Djm15pAq.js +1 -0
  15. package/dist/web-ui/assets/{Switch-CZAYoGju.js → Switch-BsePV-zC.js} +1 -1
  16. package/dist/web-ui/assets/Team-BhwiXwfp.js +85 -0
  17. package/dist/web-ui/assets/Work-C0v0dHzp.js +142 -0
  18. package/dist/web-ui/assets/{arc-C7xiSR_L.js → arc-DLLbWPzU.js} +1 -1
  19. package/dist/web-ui/assets/architectureDiagram-3BPJPVTR-DHB20fXN.js +36 -0
  20. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-Bl9V85eo.js → blockDiagram-GPEHLZMM-hGFNjiSE.js} +1 -1
  21. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BgyqGUI_.js → c4Diagram-AAUBKEIU-CpsBleVs.js} +1 -1
  22. package/dist/web-ui/assets/channel-ehfg-vdK.js +1 -0
  23. package/dist/web-ui/assets/chatChips-DVIRVTpT.js +1 -0
  24. package/dist/web-ui/assets/{chunk-2J33WTMH-2znVHbo8.js → chunk-2J33WTMH-txB49n9B.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-4BX2VUAB-BGXPYXO3.js → chunk-4BX2VUAB-ceih3NkH.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-55IACEB6-B4GQDwv-.js → chunk-55IACEB6-Bim3xVp2.js} +1 -1
  27. package/dist/web-ui/assets/{chunk-727SXJPM-D9WRILj0.js → chunk-727SXJPM-CrMJuX-q.js} +1 -1
  28. package/dist/web-ui/assets/{chunk-AQP2D5EJ-DQb0__Jh.js → chunk-AQP2D5EJ-Dx-Cmb2E.js} +1 -1
  29. package/dist/web-ui/assets/{chunk-FMBD7UC4-lEuLc0aj.js → chunk-FMBD7UC4-CQr40Nnm.js} +1 -1
  30. package/dist/web-ui/assets/{chunk-ND2GUHAM-Dd5SDfdJ.js → chunk-ND2GUHAM-BwcD6_Y7.js} +1 -1
  31. package/dist/web-ui/assets/{chunk-QZHKN3VN-Ds8u_1wB.js → chunk-QZHKN3VN-Byaq12B1.js} +1 -1
  32. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-D7qJkeZM.js +1 -0
  33. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-D7qJkeZM.js +1 -0
  34. package/dist/web-ui/assets/cose-bilkent-S5V4N54A-CLXxIaDa.js +1 -0
  35. package/dist/web-ui/assets/{dagre-BM42HDAG-D1B-Tulw.js → dagre-BM42HDAG-DdXf9urh.js} +1 -1
  36. package/dist/web-ui/assets/{diagram-2AECGRRQ-DITdhssl.js → diagram-2AECGRRQ-smJ2CryU.js} +1 -1
  37. package/dist/web-ui/assets/{diagram-5GNKFQAL-CEQxFHzH.js → diagram-5GNKFQAL-D9J88vfp.js} +1 -1
  38. package/dist/web-ui/assets/{diagram-KO2AKTUF-DxCnKGbb.js → diagram-KO2AKTUF-DFW95y1-.js} +1 -1
  39. package/dist/web-ui/assets/{diagram-LMA3HP47-BOYuGZIr.js → diagram-LMA3HP47-B8RJaXa8.js} +1 -1
  40. package/dist/web-ui/assets/{diagram-OG6HWLK6-BNJgh7s8.js → diagram-OG6HWLK6-CRDK8ZKU.js} +1 -1
  41. package/dist/web-ui/assets/{docx-preview-CrUr10-f.js → docx-preview-DOe2cigo.js} +1 -1
  42. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-BuCa252h.js → erDiagram-TEJ5UH35-7cnIAhD9.js} +1 -1
  43. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-CVvFCkDE.js → flowDiagram-I6XJVG4X-Cdc7tjsm.js} +1 -1
  44. package/dist/web-ui/assets/ganttDiagram-6RSMTGT7-BVMk6ZGl.js +292 -0
  45. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DkQpA-Z8.js → gitGraphDiagram-PVQCEYII-Bu7IjszT.js} +1 -1
  46. package/dist/web-ui/assets/index-BY_HjdWI.js +867 -0
  47. package/dist/web-ui/assets/index-CnyolIne.css +1 -0
  48. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-C_rWcDW7.js → infoDiagram-5YYISTIA-B1PiHzF5.js} +1 -1
  49. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-C0KnGaRN.js → ishikawaDiagram-YF4QCWOH-Bkz8bgJH.js} +1 -1
  50. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-CuC-5aLM.js → journeyDiagram-JHISSGLW-DnxZwAvG.js} +1 -1
  51. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-DU1_VSXa.js → kanban-definition-UN3LZRKU-CfmP8vuE.js} +1 -1
  52. package/dist/web-ui/assets/{mermaid.core-Bc0iYQ8k.js → mermaid.core-CVQWE7ug.js} +5 -5
  53. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BVU3rzyG.js → mindmap-definition-RKZ34NQL-CwURI_4d.js} +1 -1
  54. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-B7Lis7Cn.js → pieDiagram-4H26LBE5-DhtzkQBJ.js} +1 -1
  55. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-DFFsDwCW.js → quadrantDiagram-W4KKPZXB-DyCAqF3Q.js} +1 -1
  56. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-DFMxzahh.js → requirementDiagram-4Y6WPE33-DXlQ98TY.js} +1 -1
  57. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CQFj5LUY.js → sankeyDiagram-5OEKKPKP-Cymt2A_C.js} +1 -1
  58. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-DN_1Aiqe.js → sequenceDiagram-3UESZ5HK-UcPHNPcv.js} +1 -1
  59. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DmePUv3C.js → stateDiagram-AJRCARHV-4YyVx5n7.js} +1 -1
  60. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-D-aZF8vI.js +1 -0
  61. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-Cm8EYLTZ.js → timeline-definition-PNZ67QCA-B9XFBLaA.js} +1 -1
  62. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-BhoN_mu0.js → vennDiagram-CIIHVFJN-Cn1fCIU1.js} +1 -1
  63. package/dist/web-ui/assets/{wardley-L42UT6IY-DiYqNtfo.js → wardley-L42UT6IY-CZB5Iwi7.js} +1 -1
  64. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-Bd8vpNb4.js → wardleyDiagram-YWT4CUSO-NHaRrC9h.js} +1 -1
  65. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-CHboDSbi.js → xychartDiagram-2RQKCTM6-415yqDyz.js} +1 -1
  66. package/dist/web-ui/index.html +2 -2
  67. package/docs/design/agent-stop-intent-audit.md +185 -0
  68. package/docs/design/overview-attention-redesign.md +233 -0
  69. package/package.json +1 -1
  70. package/dist/web-ui/assets/CommentInput-jN8Pjpy4.js +0 -1
  71. package/dist/web-ui/assets/DeliverableShareModal-BjrQLmcX.js +0 -1
  72. package/dist/web-ui/assets/Deliverables-Cipn4z3F.js +0 -3
  73. package/dist/web-ui/assets/Notifications-DBYrWqIL.js +0 -1
  74. package/dist/web-ui/assets/Search-poQncU26.js +0 -1
  75. package/dist/web-ui/assets/SendToChat-Xk5zlNy3.js +0 -1
  76. package/dist/web-ui/assets/Settings-DlhRiM77.js +0 -8
  77. package/dist/web-ui/assets/Store-Dp0MGa-t.js +0 -1
  78. package/dist/web-ui/assets/Team-D5wmT4Mj.js +0 -84
  79. package/dist/web-ui/assets/Work-B8VUHTW7.js +0 -142
  80. package/dist/web-ui/assets/architectureDiagram-3BPJPVTR-BCM1UC9H.js +0 -36
  81. package/dist/web-ui/assets/channel-xHjc9vd-.js +0 -1
  82. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-XGbYdlgY.js +0 -1
  83. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-XGbYdlgY.js +0 -1
  84. package/dist/web-ui/assets/cose-bilkent-S5V4N54A-DZTfdLi_.js +0 -1
  85. package/dist/web-ui/assets/ganttDiagram-6RSMTGT7-DmTrMDic.js +0 -292
  86. package/dist/web-ui/assets/index-BEhLix2_.css +0 -1
  87. package/dist/web-ui/assets/index-CIrsLoqm.js +0 -883
  88. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CFaxbhDx.js +0 -1
@@ -0,0 +1,8 @@
1
+ import{u as xe,r as i,j as e,a4 as Cs,k as F,a3 as $o,a1 as Vo,a5 as _o,a6 as Fo,h as _t,a7 as $a,a8 as Uo,a9 as Ko,U as Ho,aa as zo,$ as Va,ab as qo,ac as Wo,ad as Go,ae as Vn,af as Jo,n as Ns,P as $r,_ as Yo,ag as Qo,ah as _n,ai as Zo,a as Xo,b as ei,c as ti,aj as Fn,ak as si,al as ri,am as Un,an as _a,i as ni,ao as ai,V as dr}from"./index-BY_HjdWI.js";import{L as oi}from"./AsyncState-Co9o9Bjm.js";import{i as ii,S as Ut}from"./Switch-BsePV-zC.js";function li(t,r){for(var o=0;o<r.length;o++){const a=r[o];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 di(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 ci(t){return t.maxInputTokens>0||t.inputCostPer1MTokens>0||t.outputCostPer1MTokens>0}function cr(t){if(t.tier)return t.tier;const r=t.id.toLowerCase(),o=/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":o.test(r)?"max":a.test(r)?"base":"pro"}const Kn={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 Fa({models:t,selectedModel:r,onSelect:o,loading:a,compact:n,maxVisible:s,showTiers:c}){const{t:d}=xe("settings"),[u,h]=i.useState(""),[x,k]=i.useState(!1),[v,y]=i.useState(""),S=i.useMemo(()=>{let m=t;if(u){const w=u.toLowerCase();m=m.filter($=>$.id.toLowerCase().includes(w))}return v&&(m=m.filter(w=>cr(w)===v)),m},[t,u,v]),N=i.useMemo(()=>{const m={max:0,pro:0,base:0};for(const w of t)m[cr(w)]++;return m},[t]),j=s??(n?5:10),p=x?S:S.slice(0,j),A=S.length>j;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:()=>y(""),className:`px-2 py-0.5 rounded text-[10px] transition-colors ${v?"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=>N[m]>0).map(m=>e.jsx("button",{onClick:()=>y(v===m?"":m),className:`px-2 py-0.5 rounded text-[10px] font-medium uppercase transition-colors border ${v===m?Kn[m]:"border-transparent bg-surface-overlay text-fg-tertiary hover:text-fg-secondary"}`,children:d("modelPicker.tierCount",{tier:d(`modelRouting.tier.${m}`),count:N[m]})},m))]}),t.length>5&&e.jsx("input",{type:"text",value:u,onChange:m=>{h(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:p.map(m=>{const w=m.id===r,$=cr(m);return e.jsxs("button",{type:"button",onClick:()=>o(m.id),className:`w-full text-left px-3 py-2 rounded-lg transition-colors ${w?"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 ${w?"border-brand-500":"border-border-default"}`,children:w&&e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})}),e.jsx("span",{className:`text-xs font-medium ${w?"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 ${Kn[$]}`,children:d(`modelRouting.tier.${$}`)})]}),e.jsx("div",{className:"flex items-center gap-2",children:w&&e.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:d("modelPicker.active")})})]}),ci(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:[di(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(Lt,{label:d("modelPicker.capabilities.tools")}),m.capabilities.vision&&e.jsx(Lt,{label:d("modelPicker.capabilities.vision")}),m.capabilities.reasoning&&e.jsx(Lt,{label:d("modelPicker.capabilities.reasoning")}),m.capabilities.promptCaching&&e.jsx(Lt,{label:d("modelPicker.capabilities.caching")}),m.capabilities.webSearch&&e.jsx(Lt,{label:d("modelPicker.capabilities.search")})]})]},m.id)})}),A&&!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:S.length})}),x&&A&&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 Lt({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 Kt({value:t,options:r,placeholder:o,onChange:a}){const{t:n}=xe("settings"),[s,c]=i.useState(!1),[d,u]=i.useState(""),h=i.useRef(null),x=i.useRef(null),k=i.useRef(null),[v,y]=i.useState(-1);i.useEffect(()=>{function m(w){h.current&&!h.current.contains(w.target)&&c(!1)}return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]),i.useEffect(()=>{s&&x.current&&x.current.focus()},[s]);const S=i.useMemo(()=>{if(!d.trim())return r;const m=d.toLowerCase();return r.filter(w=>w.modelId.toLowerCase().includes(m)||w.modelName.toLowerCase().includes(m)||w.provider.toLowerCase().includes(m)||w.providerLabel.toLowerCase().includes(m)||w.tier&&w.tier.toLowerCase().includes(m))},[r,d]),N=i.useMemo(()=>{const m=new Map;for(const $ of S){const B=$.providerLabel;m.has(B)||m.set(B,[]),m.get(B).push($)}const w={max:0,pro:1,base:2};for(const $ of m.values())$.sort((B,I)=>(w[B.tier??"base"]??9)-(w[I.tier??"base"]??9));return m},[S]),j=i.useMemo(()=>{const m=[];for(const w of N.values())m.push(...w);return m},[N]),p=i.useMemo(()=>{if(!t)return o??n("modelRouting.auto");const m=r.find(w=>`${w.provider}/${w.modelId}`===t);return m?`${m.providerLabel}/${m.modelName}`:t},[t,r,o,n]);function A(m){if(!s){(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),c(!0));return}switch(m.key){case"ArrowDown":m.preventDefault(),y(w=>Math.min(w+1,j.length-1));break;case"ArrowUp":m.preventDefault(),y(w=>Math.max(w-1,-1));break;case"Enter":m.preventDefault(),v===-1?a(""):j[v]&&a(`${j[v].provider}/${j[v].modelId}`),c(!1),u("");break;case"Escape":c(!1),u("");break}}return i.useEffect(()=>{k.current&&v>=0&&k.current.querySelector(`[data-focus-index="${v}"]`)?.scrollIntoView({block:"nearest"})},[v]),e.jsxs("div",{ref:h,className:"relative min-w-0",onKeyDown:A,children:[e.jsx("button",{type:"button",onClick:()=>{c(!s),u(""),y(-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:p}),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),y(-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 ${v===-1?"bg-brand-500/20 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,onClick:()=>{a(""),c(!1),u("")},children:o??n("modelRouting.auto")}),[...N.entries()].map(([m,w])=>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}),w.map($=>{const B=j.indexOf($),I=`${$.provider}/${$.modelId}`===t;return e.jsxs("div",{"data-focus-index":B,className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${B===v?"bg-brand-500/20":I?"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(ui,{tier:$.tier}),$.costTier&&e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:$.costTier})]},`${$.provider}/${$.modelId}`)})]},m)),j.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:n("modelPicker.empty")})]})]})]})}function ui({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 mi=500,Hn=[{groupKey:"image",capabilities:["image_recognition","image_generation"]},{groupKey:"audio",capabilities:["audio_tts","audio_stt"]},{groupKey:"video",capabilities:["video_generation"]}];function xi({onSave:t,configuredProviders:r}){const{t:o}=xe(["settings","common"]),[a,n]=i.useState({}),[s,c]=i.useState(null),[d,u]=i.useState(!1),[h,x]=i.useState(null),[k,v]=i.useState(!0),[y,S]=i.useState("idle"),[N,j]=i.useState(null),[p,A]=i.useState({}),[m,w]=i.useState(!1),[$,B]=i.useState("idle"),[I,V]=i.useState(null),[C,M]=i.useState(!1),O=i.useRef(null),L=i.useRef(null),U=i.useMemo(()=>r.map(g=>g.name).sort().join(","),[r]);i.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]),i.useEffect(()=>{let g=!1;return v(!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 q of K.models)f.push({provider:K.provider,providerLabel:K.displayName,modelId:q.id,modelName:q.name,mode:q.mode,tier:q.tier,costTier:q.costTier,capabilities:q.capabilities});j(f)}).catch(()=>{g||j(null)}).finally(()=>{g||v(!1)}),()=>{g=!0}},[U]),i.useEffect(()=>{fetch("/api/models/suggested-assignments",{credentials:"include"}).then(g=>{if(!g.ok)throw new Error(`HTTP ${g.status}`);return g.json()}).then(g=>{A(g.suggestions),w(!0)}).catch(()=>w(!0))},[U]);const H=i.useCallback(g=>{S("saving"),t(g).then(()=>{S("saved"),setTimeout(()=>S(T=>T==="saved"?"idle":T),2e3)}).catch(()=>{S("error"),setTimeout(()=>S(T=>T==="error"?"idle":T),3e3)})},[t]),J=i.useCallback((g,T)=>{L.current={capabilityRouting:g!==void 0?{assignments:g}:L.current?.capabilityRouting,routingDefaultModel:T!==void 0?T:L.current?.routingDefaultModel},O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{const f=L.current;L.current=null,f&&H(f)},mi)},[H]),D=i.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]),_=N??D,ee=i.useMemo(()=>Object.entries(a).map(([g,T])=>`${g}:${T?.provider??""}/${T?.model??""}`).sort().join("|"),[a]);i.useEffect(()=>{!d||!N||N.length===0||N.some(g=>!!g.modelId)&&(n(g=>{let T=!1;const f={...g};for(const K of Hn)for(const q of K.capabilities){const ne=f[q];if(!ne?.model)continue;const oe=Ua(N,q);if(oe.length===0)continue;oe.some(se=>se.provider===ne.provider&&se.modelId===ne.model)||(delete f[q],T=!0)}return T?(J(f),f):g}),c(g=>{if(!g?.model||N.some(q=>q.provider===g.provider&&q.modelId===g.model))return g;const f=N.find(q=>q.provider==="markus"),K=f?{provider:f.provider,model:f.modelId}:{provider:N[0].provider,model:N[0].modelId};return t({routingDefaultModel:K}),K}))},[d,N,U,J,ee]);const ue=i.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(()=>{}),v(!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});j(T)}).catch(()=>{}).finally(()=>v(!1))},[]),le=i.useCallback(async()=>{if($!=="working"){B("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),ue(),B("idle"),S("saved"),setTimeout(()=>S(f=>f==="saved"?"idle":f),2e3)}catch(g){B("error"),V(g instanceof Error?g.message:String(g)),setTimeout(()=>B("idle"),4e3)}}},[$,ue]),te=_.length>0;return d?h?e.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-xs text-red-400",children:o("modelRouting.loadError",{error:h})}):k&&!te?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:o("modelRouting.loadingModels")})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(pi,{status:y,t:o}),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:o($==="working"?"modelRouting.restoreWorking":"modelRouting.restoreRecommended")}),I&&e.jsx("span",{className:"text-[10px] text-red-400 max-w-xs text-right",children:I})]})]}),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:o("modelRouting.defaultModelTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:o("modelRouting.defaultModelDesc")})]}),e.jsx("div",{className:"max-w-md",children:e.jsx(Kt,{value:s?`${s.provider}/${s.model}`:"",options:_,placeholder:o("modelRouting.defaultModelPlaceholder"),onChange:g=>{if(!g)c(null),J(void 0,null);else{const[T,...f]=g.split("/"),K={provider:T,model:f.join("/")};if(c(K),a.text){const q={...a};delete q.text,n(q),J(q,K)}else J(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:o("modelRouting.capabilityAssignTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:o("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:o("modelRouting.noProvidersHint")}),r.length>0&&e.jsx("div",{className:"space-y-4",children:Hn.map(g=>e.jsx(gi,{groupKey:g.groupKey,capabilities:g.capabilities,assignments:a,suggestions:p,allModels:_,configuredProviderNames:new Set(r.map(T=>T.name)),t:o,onAssign:(T,f)=>{const K={...a};f?K[T]=f:delete K[T],n(K),J(K)}},g.groupKey))})]}),C&&e.jsx(Cs,{variant:"primary",title:o("modelRouting.restoreRecommended"),message:o("modelRouting.restoreConfirm"),confirmLabel:o("common:confirm"),onConfirm:()=>{M(!1),le()},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 gi({groupKey:t,capabilities:r,assignments:o,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 h=o[u],x=a[u],k=h?`${h.provider}/${h.model}`:"",v=Ua(n,u),y=x?v.find(A=>A.provider===x.provider&&A.modelId===x.model)?.modelName??x.model:void 0,S=v.length>0,N=h?fi(n,h.provider,h.model):void 0,j=h&&!s.has(h.provider),p=!!(h&&S&&u!=="text"&&!v.some(A=>A.provider===h.provider&&A.modelId===h.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 ${p?"bg-red-500/10 border border-red-500/30":j?"bg-yellow-500/10 border border-yellow-500/30":!S&&!h?"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:p?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:["⚠ ",h.model]}),e.jsx("span",{className:"text-[10px] text-red-400/70",children:c("modelRouting.mismatchHint")})]}),e.jsx(Kt,{value:"",options:v,placeholder:c("modelRouting.selectModel"),onChange:A=>{if(!A)d(u,null);else{const[m,...w]=A.split("/");d(u,{provider:m,model:w.join("/")})}}})]}):S?e.jsx(Kt,{value:k,options:v,placeholder:y?`${y} (${c("modelRouting.suggested")})`:c("modelRouting.selectModel"),onChange:A=>{if(!A)d(u,null);else{const[m,...w]=A.split("/");d(u,{provider:m,model:w.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:[p&&e.jsx("span",{className:"text-[10px] text-red-400 font-medium",title:c("modelRouting.mismatchHint"),children:"⚠"}),!p&&j&&e.jsx("span",{className:"text-[10px] text-yellow-400 font-medium",title:c("modelRouting.staleProvider"),children:"⚠"}),!p&&!j&&N&&e.jsx(zn,{tier:N}),!p&&!j&&!N&&h&&e.jsx(zn,{tier:"unknown"})]}),e.jsx("div",{className:"w-8 shrink-0 flex justify-end",children:h&&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 fi(t,r,o){return t.find(n=>n.provider===r&&n.modelId===o)?.tier}function pi({status:t,t:r}){if(t==="idle")return null;const o={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 ${o[t]}`,children:a[t]})}function zn({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 Ua(t,r){if(r==="text")return t.filter(c=>ii(c));const o={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=o[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 hi({configuredProviders:t}){const{t:r}=xe("settings"),[o,a]=i.useState(null),[n,s]=i.useState([]),[c,d]=i.useState(null),[u,h]=i.useState(null),x=i.useMemo(()=>t.map(N=>`${N.name}:${N.models?.length??0}`).sort().join(","),[t]),k=i.useCallback(async()=>{d(null);try{const[{agents:N},j]=await Promise.all([F.agents.list({lean:!0}),F.teams.list()]),p=j.teams.map(m=>({id:m.id,name:m.name}));s(p);const A=await Promise.all(N.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(N.length?A:null)}catch(N){d(String(N))}},[x]);i.useEffect(()=>{k()},[k,x]);const v=i.useMemo(()=>{const N=[];for(const j of t)for(const p of j.models??[])N.push({provider:j.name,providerLabel:j.displayName??j.name,modelId:p.id,modelName:p.name??p.id});return N},[t]),y=async(N,j)=>{h(N),d(null);try{if(j){const[p,A]=[j.slice(0,j.lastIndexOf("/")),j.slice(j.lastIndexOf("/")+1)];await F.agents.updateConfig(N,{llmConfig:{modelMode:"custom",primary:p,defaultModel:A}})}else await F.agents.updateConfig(N,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}});a(p=>p?.map(A=>A.id===N?{...A,override:j}:A)??p)}catch(p){d(String(p))}finally{h(null)}},S=i.useMemo(()=>{if(!o)return[];const N=new Map,j=[];for(const A of o)if(A.teamId){const m=N.get(A.teamId)??[];m.push(A),N.set(A.teamId,m)}else j.push(A);const p=[];j.length&&p.push({key:"ungrouped",label:r("perAgentModel.ungrouped",{defaultValue:"Ungrouped"}),rows:j});for(const A of n){const m=N.get(A.id);m?.length&&p.push({key:`team:${A.id}`,label:A.name,rows:m})}for(const[A,m]of N)n.some(w=>w.id===A)||p.push({key:`team:${A}`,label:A,rows:m});return p},[o,n,r]);return o===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}),(!o||o.length===0)&&!c&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:r("perAgentModel.noAgents",{defaultValue:"No agents available."})}),o&&o.length>0&&e.jsx("div",{className:"space-y-5",children:S.map(N=>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:N.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary/70 tabular-nums shrink-0",children:N.rows.length})]}),e.jsx("div",{className:"space-y-2",children:N.rows.map(j=>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:j.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-2 truncate",children:j.id})]}),e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 md:w-[320px]",children:[j.override?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{value:j.override,options:v,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:p=>{y(j.id,p||null)}}),e.jsx("button",{type:"button",disabled:u===j.id,onClick:()=>{y(j.id,null)},className:"shrink-0 px-2.5 py-1.5 text-xs border border-border-default rounded-lg hover:bg-surface-primary disabled:opacity-40 transition-colors",children:r("perAgentModel.reset",{defaultValue:"Reset"})})]}):e.jsx(Kt,{value:"",options:v,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:p=>{y(j.id,p||null)}}),u===j.id&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary",children:r("common:loading",{defaultValue:"…"})})]})]},j.id))})]},N.key))})]})}let ws=[],ps=null;async function bi(){return ps||(ps=(async()=>{try{ws=(await F.modelCatalog.providerCatalog()).providers??[]}catch{ws=[]}return ws})(),ps)}function yi(){const[t,r]=i.useState(ws);return i.useEffect(()=>{let o=!0;return bi().then(a=>{o&&r(a)}),()=>{o=!1}},[]),t}const vi="integrations.platforms",zr=(t,r)=>`settings:${vi}.${t}.${r}`,ji={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 Ni(t){return ji[t]}function wi(t,r){return t(zr(r.id,"label"),{defaultValue:r.label})}function Ka(t,r,o){const a=zr(r,`fields.${o.key}`);return{label:t(`${a}.label`,{defaultValue:o.label}),help:o.help?t(`${a}.help`,{defaultValue:o.help}):void 0,placeholder:o.placeholder?t(`${a}.placeholder`,{defaultValue:o.placeholder}):void 0,options:o.options?.map(n=>({value:n.value,label:t(`${a}.options.${n.value}`,{defaultValue:n.label})}))}}function ki(t,r,o){const a=[],n=zr(o,"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 Ci(t){return t("settings:integrations.guide.heading",{defaultValue:"Setup guide"})}function Si(t){return t.type==="boolean"?t.default===!0:t.multiple?Array.isArray(t.default)?[...t.default]:[]:t.default!==void 0?t.default:""}function Ss(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 qn(t){const r={};for(const o of t.fields){if(o.secret){r[o.key]="";continue}const a=t.values[o.key];r[o.key]=a??Si(o)}return r}function Wn(t,r,o={}){const a=[];for(const n of t)if(n.required){if(n.secret){if(!Ss(n,r[n.key]))continue;o[n.key]?.hasValue||a.push(n.key);continue}Ss(n,r[n.key])&&a.push(n.key)}return a}function Ai(t,r,o){const a={enabled:o};for(const n of t.fields){const s=r[n.key];if(n.secret){if(Ss(n,s))continue;a[n.key]=s;continue}s!==void 0&&(a[n.key]=s)}return a}function Pi(t){return t.filter(r=>r.required||r.type==="agent")}function Mi(t){return t.filter(r=>!(r.required||r.type==="agent"))}function Vr(t){return Array.isArray(t)?`[${t.map(Vr).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,o])=>o!==void 0).sort(([o],[a])=>o<a?-1:o>a?1:0).map(([o,a])=>`${JSON.stringify(o)}:${Vr(a)}`).join(",")}}`:JSON.stringify(t)??"null"}function Ti(t){return Vr({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 Ei(t){const r=t.ok===!0||t.success===!0;return{ok:r,text:t.message??t.error??(r?"OK":"Failed"),code:t.code}}function Ri(t){return t?.status==="awaiting_reply"||t?.status==="awaiting_inbound"}function Li(t,r=!1){return t.hasConfig?t.enabled?t.lastVerifiedAt||r?"verified":"unverified":"off":"unconfigured"}function Ii(t){return{id:"",platform:t.id,label:"",enabled:!0,connected:!1,hasConfig:!1,capabilities:t.capabilities,fields:t.fields,values:{},secrets:Bi(t.fields),agentId:null,notifyAgentId:null,channels:[],lastError:null,canListChannels:!1,lastVerifiedAt:null}}function Bi(t){const r={};for(const o of t)o.secret&&(r[o.key]={hasValue:!1});return r}function Oi(t){return t.id===""}function Gn(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 ur(t,r){return t.find(o=>o.nativeId===r)}function Jn(t,r,o,a){const n=t.filter(s=>s.nativeId!==r);return n.push({nativeId:r,kind:a??null,agentId:o}),n.sort((s,c)=>s.nativeId.localeCompare(c.nativeId))}function Yn(t,r){return t.filter(o=>o.nativeId!==r)}function Di(t,r){const o=new Set(r.map(a=>a.id));return t.filter(a=>!o.has(a.nativeId))}function $i(t,r){const o=r.trim().toLowerCase();return o?t.filter(a=>a.name.toLowerCase().includes(o)||a.id.toLowerCase().includes(o)):t}function Vi(t){const r=new Map;for(const o of t){const a=r.get(o.platform);a?a.push(o):r.set(o.platform,[o])}return[...r.entries()].map(([o,a])=>({platform:o,instances:a}))}function _i(t,r,o={}){const a=o.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 Fi(t,r,o){const[a,n]=i.useState([]),[s,c]=i.useState(null),[d,u]=i.useState(!1),h=i.useRef(t);h.current=t;const x=i.useRef(0),k=i.useCallback(()=>{if(!o||!r)return;const v=++x.current;u(!0),h.current(r).then(y=>{v===x.current&&(n(y.channels??[]),c(y.error??null))}).catch(y=>{v===x.current&&(n([]),c(y instanceof Error?y.message:String(y)))}).finally(()=>{v===x.current&&u(!1)})},[o,r]);return i.useEffect(()=>(k(),()=>{x.current+=1}),[k]),{channels:a,error:s,loading:d,reloadChannels:k}}const Ha=/^notify[A-Z]/,za="notifyEnabled";function Ui(t){return t.find(r=>r.key===za)}function Ki(t){return t.notifyTarget==="chat"||t.notifyTarget==="user"||Ha.test(t.key)}function Ht(t){return t.filter(r=>r.notifyTarget==="chat"||r.notifyTarget==="user")}function Hi(t){return t.filter(r=>!r.notifyTarget&&!r.secret&&r.key!==za&&Ha.test(r.key))}function zi(t){return t.filter(Ki)}function qa(t){return Ht(t).find(r=>r.notifyTarget==="chat")}function qi(t,r){const o=Ht(t);return o.length===0?"unsupported":o.some(a=>!Ss(a,r[a.key]))?"configured":"not-configured"}function Qn(t){return typeof t=="string"?{value:t,label:t}:{value:t.value,label:t.label??t.value,hint:t.hint}}function Zn(t,r,o){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(o)||n.startsWith(o))return 0;const c=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[\\s./:_-])${c}`).test(a)?1:2}function Wa({value:t,options:r,onChange:o,placeholder:a,filterPlaceholder:n,emptyText:s,customHint:c,disabled:d,ariaLabel:u,className:h}){const[x,k]=i.useState(!1),[v,y]=i.useState(""),[S,N]=i.useState(!1),[j,p]=i.useState(-1),A=i.useRef(null),m=i.useRef(null),w=i.useRef(null),$=i.useRef(null),B=i.useId(),[I,V]=i.useState({}),C=i.useMemo(()=>t?r.map(Qn).find(D=>D.value===t)?.label??t:a??"",[t,r,a]);i.useEffect(()=>{x||(y(C),N(!1))},[C,x]),i.useEffect(()=>{function D(_){const ee=_.target;$.current?.contains(ee)||A.current&&!A.current.contains(ee)&&k(!1)}return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[]);function M(){const D=m.current;if(!D)return;const _=D.getBoundingClientRect(),ee=Math.max(_.width,240),ue=window.innerHeight-_.bottom-8,le=ue<180&&_.top>ue;V({position:"fixed",left:_.left,width:ee,maxHeight:Math.min(260,le?Math.max(_.top-12,120):ue),...le?{bottom:window.innerHeight-_.top+4}:{top:_.bottom+4}})}i.useLayoutEffect(()=>{if(!x)return;M();const D=()=>M();return window.addEventListener("scroll",D,!0),window.addEventListener("resize",D),()=>{window.removeEventListener("scroll",D,!0),window.removeEventListener("resize",D)}},[x]);const O=i.useMemo(()=>{const D=r.map(Qn),_=v.trim(),ee=S?_.toLowerCase().split(/\s+/).filter(Boolean):[],ue=[];D.forEach((g,T)=>{const f=ee.length?Zn(g,ee,_.toLowerCase()):0;f!==null&&ue.push({row:g,score:f,idx:T})}),ue.sort((g,T)=>g.score-T.score||g.idx-T.idx);const le=[];if(a!==void 0){const g={value:"",label:a};(ee.length?Zn(g,ee,_.toLowerCase()):0)!==null&&le.push(g)}le.push(...ue.map(g=>g.row));const te=_&&!D.some(g=>g.value.toLowerCase()===_.toLowerCase());return c&&S&&te&&le.push({value:_,label:_,custom:!0}),le},[r,v,S,a,c]);i.useEffect(()=>{if(!x||j<0||!w.current)return;w.current.querySelector(`[data-index="${j}"]`)?.scrollIntoView({block:"nearest"})},[j,x,O.length]);function L(){d||(y(C),N(!1),p(O.findIndex(D=>D.value===t)),k(!0),requestAnimationFrame(()=>m.current?.select()))}function U(){k(!1),y(C),N(!1),p(-1)}function H(D){o(D.value),k(!1),y(D.value?D.label:a??""),N(!1),p(-1),m.current?.focus()}function J(D){if(D.key==="ArrowDown"||D.key==="ArrowUp"){if(D.preventDefault(),!x){L();return}p(_=>{const ee=D.key==="ArrowDown"?_+1:_-1;return Math.max(-1,Math.min(ee,O.length-1))});return}if(D.key==="Enter"){if(!x){D.preventDefault(),L();return}const _=O[j];_?(D.preventDefault(),H(_)):U();return}if(D.key==="Escape"&&x){D.preventDefault(),D.stopPropagation(),U();return}D.key==="Tab"&&x&&U()}return e.jsxs("div",{ref:A,className:`relative ${h??""}`,children:[e.jsx("input",{ref:m,type:"text",role:"combobox","aria-expanded":x,"aria-controls":x?B:void 0,"aria-autocomplete":"list","aria-label":u,"aria-activedescendant":x&&j>=0?`${B}-opt-${j}`:void 0,disabled:d,value:x?v:C,placeholder:n,onMouseDown:()=>{x?k(!1):L()},onChange:D=>{x||k(!0),y(D.target.value),N(!0),p(0)},onKeyDown:J,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&&$o.createPortal(e.jsxs("div",{id:B,role:"listbox",ref:D=>{w.current=D,$.current=D},style:I,onMouseDown:D=>D.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:[O.map((D,_)=>e.jsxs("div",{id:`${B}-opt-${_}`,"data-index":_,role:"option","aria-selected":D.value===t,onMouseDown:ee=>{ee.preventDefault(),H(D)},className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${_===j?"bg-brand-500/20":D.value===t?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,children:[e.jsx("span",{className:`flex-1 truncate ${D.custom?"text-brand-500":"text-fg-primary"}`,children:D.label}),D.hint&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:D.hint}),D.custom&&c&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:typeof c=="function"?c(D.value):c})]},`${D.custom?"custom:":""}${D.value}`)),O.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:s})]}),document.body)]})}async function Wi(){const{agents:t}=await F.agents.list({lean:!0});return t.map(r=>({id:r.id,name:r.name,role:r.role}))}let hs=null;function Ga(){return hs||(hs=Wi().catch(t=>{throw hs=null,t})),hs}function Gi(t=Ga,r=!0){const[o,a]=i.useState([]);return i.useEffect(()=>{if(!r)return;let n=!0;return t().then(s=>{n&&a(s)}).catch(()=>{n&&a([])}),()=>{n=!1}},[t,r]),o}function As({value:t,options:r,onChange:o,fieldKey:a,ariaLabel:n,disabled:s}){const{t:c}=xe(["settings"]);return e.jsx(Wa,{value:typeof t=="string"?t:"",options:r.map(d=>({value:d.id,label:d.name,hint:d.role})),onChange:d=>o(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 Ja({loading:t,error:r,onReload:o,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:o,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 ks="rounded-xl border border-border-default bg-surface-secondary p-4",Vt="text-sm font-semibold text-fg-primary",Ya="flex flex-wrap items-center justify-between gap-x-4 gap-y-2",Ji="flex flex-wrap items-start justify-between gap-x-4 gap-y-2",_r="shrink-0 text-sm text-fg-secondary",Qa="flex-1 min-w-[10rem] flex justify-end",vt="text-xs text-fg-tertiary",Fr="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 Ur(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 Yi={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"},Qi={verified:"bg-green-500",unverified:"bg-amber-400",off:"bg-gray-400",unconfigured:"bg-gray-400"},Zi={verified:"settings:integrations.status.verified",unverified:"settings:integrations.status.unverified",off:"settings:integrations.status.off",unconfigured:"settings:integrations.status.unconfigured"},Xi={verified:"Connected",unverified:"Not verified",off:"Off",unconfigured:"Not configured"};function el({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 ${Yi[t]}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Qi[t]}`}),r(Zi[t],{defaultValue:Xi[t]})]})}function Ft({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 It({label:t,control:r,help:o,htmlFor:a,start:n=!1}){return e.jsxs("div",{children:[e.jsxs("div",{className:n?Ji:Ya,children:[a?e.jsx("label",{htmlFor:a,className:_r,children:t}):e.jsx("span",{className:_r,children:t}),e.jsx("div",{className:Qa,children:r})]}),o?e.jsx("p",{className:`${vt} mt-1.5`,children:o}):null]})}function tl({field:t,value:r,hasStored:o,onChange:a,platformId:n="",agentOptions:s=[]}){const{t:c}=xe(["settings"]),d=`integration-field-${t.key}`,[u,h]=i.useState(!1),x=i.useMemo(()=>n?Ka(c,n,t):{label:t.label,help:t.help,placeholder:t.placeholder,options:t.options},[c,n,t]),k=x.label,v=x.help,y=x.placeholder,S=x.options??t.options??[],N=e.jsxs(e.Fragment,{children:[k,t.required&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),j=t.secret&&o?c("settings:integrations.secretStored"):v||void 0;if(t.type==="boolean"){const m=r===!0;return e.jsx(It,{label:k,help:v,control:e.jsx(Ut,{checked:m,onChange:w=>a(t.key,w),label:k,size:"md",testId:`integration-field-${t.key}`})})}if(t.type==="agent")return e.jsx(It,{label:N,help:j,control:e.jsx("div",{className:"w-full","data-testid":`integration-field-${t.key}`,children:e.jsx(As,{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(It,{start:!0,label:N,help:j,control:e.jsx("div",{className:"flex flex-wrap justify-end gap-1.5","data-testid":`integration-field-${t.key}`,children:S.map(w=>{const $=m.includes(w.value);return e.jsx("button",{type:"button","aria-pressed":$,"data-option":w.value,onClick:()=>a(t.key,$?m.filter(B=>B!==w.value):[...m,w.value]),className:Ur($),children:w.label},w.value)})})})}if(t.type==="select")return e.jsx(It,{label:N,help:j,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:Fr,children:(t.options??[]).map(m=>{const w=S.find($=>$.value===m.value)?.label??m.label;return e.jsx("option",{value:m.value,children:w},m.value)})})});const p=t.type==="password",A=t.type==="number";return e.jsx(It,{label:N,help:j,htmlFor:d,control:e.jsxs("div",{className:"relative w-full",children:[e.jsx("input",{id:d,"data-testid":`integration-field-${t.key}`,type:A?"number":p&&!u?"password":"text",value:r==null?"":String(r),placeholder:p&&o?c("settings:integrations.secretStoredPlaceholder"):y,onChange:m=>a(t.key,m.target.value),className:`${Fr}${p?" font-mono pr-10":""}`}),p&&e.jsx("button",{type:"button","aria-label":u?c("settings:integrations.hide",{defaultValue:"Hide"}):c("settings:integrations.show",{defaultValue:"Show"}),onClick:()=>h(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 jt({status:t,draft:r,fields:o=t.fields,onChange:a,agentOptions:n=[]}){return e.jsx(e.Fragment,{children:o.map(s=>e.jsx(tl,{field:s,platformId:t.id,value:r[s.key],hasStored:t.secrets[s.key]?.hasValue===!0,agentOptions:n,onChange:a},s.key))})}const Xn={pending:"bg-amber-400 animate-pulse",ok:"bg-emerald-500",failed:"bg-red-500"};function ea({label:t,hint:r,leg:o}){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 ${Xn[o.state]??Xn.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:o.state==="ok"?o.detail??a("integrations.connectionTest.legOk",{defaultValue:"Verified"}):o.state==="failed"?o.detail??a("integrations.connectionTest.legFailed",{defaultValue:"Failed"}):r})]})]})}function sl(t,r){const o=new Date(t);return Number.isNaN(o.getTime())?t:o.toLocaleString(r,{dateStyle:"medium",timeStyle:"short"})}function rl({test:t,starting:r,onStart:o,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(ea,{label:n("integrations.connectionTest.outbound",{defaultValue:"Outbound (bot → IM)"}),hint:n("integrations.connectionTest.outboundPending",{defaultValue:"Not sent yet"}),leg:t.outbound}),e.jsx(ea,{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(Ft,{type:t.status==="verified"?"ok":"err",text:c}):e.jsx("div",{className:"px-3 py-2 rounded-lg text-xs bg-surface-elevated text-fg-secondary",children:c}))]}):a?e.jsx(Ft,{type:"ok",text:n("integrations.connectionTest.lastVerified",{defaultValue:"Verified {{when}}.",when:sl(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:o,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-elevated 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 nl({status:t,values:r,setValue:o,channels:a=[],canListChannels:n=!1,channelsLoading:s=!1,channelsError:c=null,onReloadChannels:d=()=>{},channelsGuidance:u=null,testSlot:h}){const{t:x}=xe(["settings","common"]),[k,v]=i.useState(!1),y=Ht(t.fields),S=Hi(t.fields),N=Ui(t.fields),j=qi(t.fields,r),p=qa(t.fields),A=N?r[N.key]!==!1:!0,m=n&&p?p.key:null,w=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"})},B={configured:"text-green-600","not-configured":"text-amber-600",unsupported:"text-fg-tertiary"},I={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&&w!==""&&!a.some(L=>L.id===w),O="text-xs font-medium text-fg-secondary mb-2";return e.jsxs("section",{"data-testid":"notification-panel","data-reachability":j,className:ks,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsx("h3",{className:Vt,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 ${B[j]}`,"data-testid":"notification-reachability","data-state":j,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I[j]}`}),$[j]]}),N&&e.jsx(Ut,{checked:A,onChange:L=>o(N.key,L),label:x("settings:instances.notify.masterLabel",{defaultValue:"Enable notifications"}),size:"md",testId:`integration-field-${N.key}`})]})]}),e.jsxs("div",{className:`space-y-4${A?"":" opacity-60"}`,children:[y.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:O,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(Ja,{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":w===L.id,"data-testid":`notification-chat-pick-${L.id}`,onClick:()=>o(m,L.id),className:Ur(w===L.id),children:L.name},L.id))}),a.length===0&&!s&&!c&&e.jsx("p",{"data-testid":"notification-chat-empty",className:vt,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:()=>o(m,w),className:Ur(!0),children:w})})]}),m===null&&e.jsx("p",{"data-testid":"notification-chat-guidance",className:vt,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:()=>v(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(jt,{status:t,draft:r,fields:y,onChange:o})})]}):e.jsx("div",{className:"mt-2",children:e.jsx(jt,{status:t,draft:r,fields:y,onChange:o})})]}),S.length>0&&e.jsxs("div",{"data-testid":"notification-preferences",className:"space-y-3",children:[e.jsx("div",{className:O,children:x("settings:instances.notify.content",{defaultValue:"What to send"})}),e.jsx(jt,{status:t,draft:r,fields:S,onChange:o})]}),h]})]})}const yt={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"},al={color:"#64748b",glyph:e.jsx("g",{...yt,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"})})},ol={feishu:{color:"#3370ff",glyph:e.jsx("g",{...yt,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",{...yt,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",{...yt,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",{...yt,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",{...yt,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 il(t){return ol[t]??al}function Za({id:t,size:r=36}){const o=il(t);return e.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded-lg",style:{width:r,height:r,backgroundColor:`${o.color}1a`,color:o.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:o.glyph})})}function ll({status:t,configured:r,canListChannels:o=!1,channelsGuidance:a=null}){const{t:n,i18n:s}=xe(["settings","common"]),[c,d]=i.useState(!r),u=i.useMemo(()=>{const k=ki(s,n,t.id);if(Ht(t.fields).length===0)return k;const v=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."}),y=o?{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:v}):v};return[...k,y]},[s,n,t.id,t.fields,o,a]),h=Ni(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:Ci(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,v)=>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:v+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:[h&&e.jsxs("a",{href:h,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-on-brand 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 Xa={create:(t,r)=>F.settings.createInstance(t,r).then(o=>o.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(o=>o.test),getConnectionTest:t=>F.settings.getConnectionTest(t).then(r=>r.test)},dl=700;function ta({instance:t,client:r=Xa,extras:o={},onChanged:a,onCreated:n,loadAgents:s,defaultExpanded:c}){const{t:d}=xe(["settings","common"]),u=Oi(t),[h,x]=i.useState(c??u),[k,v]=i.useState(!1),y=i.useMemo(()=>Gn(t),[t]),[S,N]=i.useState(t.label),[j,p]=i.useState(()=>qn(y)),[A,m]=i.useState(t.enabled),[w,$]=i.useState(t.channels),[B,I]=i.useState(typeof t.notifyAgentId=="string"?t.notifyAgentId:""),[V,C]=i.useState({kind:"idle"}),M=!!o[t.platform]?.guidedSetup,[O,L]=i.useState(M&&!t.hasConfig?"guided":"manual"),U=M&&O==="guided",{channels:H,error:J,loading:D,reloadChannels:_}=Fi(r.listChannels,t.id,h&&t.canListChannels),[ee,ue]=i.useState(""),[le,te]=i.useState(null),[g,T]=i.useState(!1),[f,K]=i.useState(null),q=Ri(le),[ne,oe]=i.useState(!1),ge=t.fields.some(E=>E.type==="agent"),se=Gi(i.useMemo(()=>s??Ga,[s]),ge),Je=i.useCallback(E=>E?se.find(ae=>ae.id===E)?.name??E:"",[se]),Ae=Ti(y),Se=i.useRef(t);Se.current=t;const Oe=i.useRef(!1),rt=i.useRef(!1);i.useEffect(()=>{if(Oe.current)return;const E=Se.current;N(E.label),p(qn(Gn(E))),m(E.enabled),$(E.channels),I(typeof E.notifyAgentId=="string"?E.notifyAgentId:"")},[Ae]),i.useEffect(()=>{C({kind:"idle"}),te(null),K(null),it(!1)},[t.id]),i.useEffect(()=>{L(M&&!t.hasConfig?"guided":"manual")},[t.id,t.hasConfig,M]);const we=i.useCallback(()=>{Oe.current=!0,C({kind:"idle"})},[]),fe=i.useCallback((E,ae)=>{we(),p(Z=>({...Z,[E]:ae}))},[we]),zt=i.useCallback(E=>{we(),N(E)},[we]),Ye=i.useCallback(E=>{we(),m(E)},[we]),Nt=i.useRef(()=>Promise.resolve()),De=i.useCallback(async()=>{if(!rt.current){rt.current=!0,C({kind:"saving"});try{let E=Se.current.id;E||(E=(await r.create(Se.current.platform,S.trim())).id),await r.save(E,{...Ai(y,j,A),notifyAgentId:B}),Se.current.canListChannels&&await r.saveChannels(E,w);let ae=null;try{const{ok:Z,text:Ze,code:Xt}=Ei(await r.test(E,{}));!Z&&!/not supported/i.test(Ze)&&(ae=Xt==="network_unreachable"?d("settings:integrations.savedNotVerifiedNetwork"):d("settings:integrations.savedNotVerified",{reason:Ze}))}catch(Z){ae=d("settings:integrations.savedNotVerified",{reason:String(Z)})}Oe.current=!1,C(ae?{kind:"error",text:ae}:{kind:"saved"}),await a?.(),Se.current.id===""&&n?.(E)}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}finally{rt.current=!1}}},[r,y,j,A,B,w,S,d,a,n]);Nt.current=De;const nt=Wn(y.fields,j,t.secrets),qt=u&&S.trim()==="",Wt=w.every(E=>E.agentId),Qe=!U&&!qt&&nt.length===0&&Wt,Re=i.useMemo(()=>JSON.stringify([S,A,B,w,j]),[S,A,B,w,j]);i.useEffect(()=>{if(!Oe.current||!Qe)return;const E=setTimeout(()=>{Nt.current()},dl);return()=>clearTimeout(E)},[Re,Qe]),i.useEffect(()=>{if(!h||u)return;let E=!0;return r.getConnectionTest(t.id).then(ae=>{E&&ae&&te(ae)}).catch(()=>{}),()=>{E=!1}},[h,u,r,t.id]),i.useEffect(()=>{if(!h||!q)return;let E=!0;const ae=setInterval(()=>{r.getConnectionTest(t.id).then(Z=>{E&&Z&&te(Z)}).catch(()=>{})},2500);return()=>{E=!1,clearInterval(ae)}},[h,q,r,t.id]);const wt=i.useRef(null);i.useEffect(()=>{le?.status==="verified"&&wt.current!==t.id&&(wt.current=t.id,a?.())},[le?.status,t.id,a]);const Gt=i.useCallback(async()=>{T(!0),K(null);try{te(await r.startConnectionTest(t.id))}catch(E){K(E instanceof Error?E.message:String(E))}finally{T(!1)}},[r,t.id]),ye=o[t.platform],_e=i.useMemo(()=>({platformId:t.platform,instanceId:t.id||void 0,status:y,values:j,setValue:fe,reload:()=>{a?.()},agents:se,onCreated:n,setupMethod:M?O:void 0,setSetupMethod:M?L:void 0}),[t.platform,t.id,y,j,fe,a,se,n,M,O]),Jt=i.useMemo(()=>new Set(ye?.ownedFields??[]),[ye]),at=Ht(y.fields).length>0,Yt=i.useMemo(()=>new Set(at?zi(y.fields).map(E=>E.key):[]),[y.fields,at]),ot=i.useMemo(()=>y.fields.filter(E=>!Jt.has(E.key)&&!Yt.has(E.key)),[y.fields,Jt,Yt]),kt=i.useMemo(()=>Pi(ot),[ot]),Qt=i.useMemo(()=>Mi(ot),[ot]),Zt=i.useMemo(()=>kt.filter(E=>E.type==="agent"),[kt]),Ct=i.useMemo(()=>kt.filter(E=>E.type!=="agent"),[kt]),[Ps,it]=i.useState(!1),Ms=i.useMemo(()=>Wn(t.fields,t.values,t.secrets),[t.fields,t.values,t.secrets]),lt=t.hasConfig&&!Ms.some(E=>Ct.some(ae=>ae.key===E)),dt=i.useMemo(()=>$i(H,ee),[H,ee]),St=i.useMemo(()=>Di(w,H),[w,H]),Fe=w.filter(E=>!E.agentId).length,Ts=i.useCallback((E,ae)=>{we(),$(Z=>ae?Jn(Z,E.id,ur(Z,E.id)?.agentId??t.agentId??"",E.kind??null):Yn(Z,E.id))},[we,t.agentId]),Pe=i.useCallback((E,ae)=>{we(),$(Z=>Jn(Z,E,ae,ur(Z,E)?.kind??null))},[we]),Es=i.useCallback(async()=>{oe(!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=Li(t,le?.status==="verified"),re=t.id||`new-${t.platform}`,ct=`instance-name-${re}`,At=nt.map(E=>{const ae=y.fields.find(Z=>Z.key===E);return ae?Ka(d,t.platform,ae).label:E}).join(", ");return e.jsxs("div",{className:"bg-surface-elevated rounded-xl overflow-hidden border border-border-default","data-testid":`instance-card-${re}`,"data-instance":t.id,"data-platform":t.platform,"data-draft":u?"true":"false","data-expanded":h?"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":h,"data-testid":`instance-toggle-${re}`,className:"flex-1 min-w-0 flex items-center gap-3 text-left",children:[e.jsx(Za,{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-${re}`,children:S.trim()===""?d("settings:instances.newBot",{defaultValue:"New bot"}):S}),!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-${re}`,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-${re}`,title:d("settings:instances.boundAgent",{defaultValue:"Bound agent"}),children:[e.jsx("span",{className:"text-fg-muted",children:"→"}),Je(t.agentId)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5 shrink-0",children:[e.jsx(el,{state:Ue}),!u&&e.jsx(Ut,{checked:A,onChange:Ye,size:"md",testId:`instance-enabled-${re}`,label:d("settings:instances.toggleLabel",{defaultValue:"Turn this bot on or off"})}),e.jsx("button",{type:"button",onClick:()=>x(E=>!E),"aria-expanded":h,"data-testid":`instance-chevron-${re}`,className:"p-1 text-fg-tertiary hover:text-fg-secondary transition-colors",children:e.jsx("svg",{className:`w-4 h-4 transition-transform ${h?"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"})})})]})]}),h&&e.jsxs("div",{className:"px-6 pb-6 pt-5 border-t border-border-default space-y-6",children:[!t.hasConfig&&!U&&e.jsx(ll,{status:y,configured:t.hasConfig,canListChannels:t.canListChannels,channelsGuidance:t.channelsGuidance??null}),!M&&ye?.placement==="before"&&ye.render(_e),e.jsxs("section",{"data-testid":`instance-credentials-${re}`,className:ks,children:[e.jsx("h3",{className:`${Vt} 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":O===E,onClick:()=>L(E),"data-testid":`setup-method-${E}-${re}`,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${O===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:Ya,children:[e.jsxs("label",{htmlFor:ct,className:_r,children:[d("settings:instances.addBot.name",{defaultValue:"Bot name"}),e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),e.jsx("div",{className:Qa,children:e.jsx("input",{id:ct,"data-testid":`new-bot-name-${t.platform}`,value:S,onChange:E=>zt(E.target.value),placeholder:d("settings:instances.addBot.namePlaceholder",{defaultValue:"e.g. Sales"}),className:Fr})})]}),Zt.length>0&&e.jsx(jt,{status:y,draft:j,fields:Zt,onChange:fe,agentOptions:se}),Ct.length>0&&(lt&&!Ps?e.jsx("div",{"data-testid":`instance-credentials-configured-${re}`,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:()=>it(!0),"data-testid":`instance-credentials-edit-${re}`,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:[lt&&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:()=>it(!1),"data-testid":`instance-credentials-hide-${re}`,className:"text-xs text-brand-600 hover:text-brand-700",children:d("settings:instances.credentialsHide",{defaultValue:"Hide"})})]}),e.jsx(jt,{status:y,draft:j,fields:Ct,onChange:fe,agentOptions:se})]}))]}),e.jsx("div",{className:"mt-3 min-h-[1.25rem]","data-testid":`instance-save-state-${re}`,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-${re}`,children:nt.length>0?d("settings:integrations.missingRequired",{defaultValue:"Required: {{fields}}",fields:At}):d("settings:instances.addBot.labelRequired",{defaultValue:"Give the bot a name."})})]})}),V.kind==="error"&&e.jsx("div",{className:"mt-2",children:e.jsx(Ft,{type:"err",text:V.text})})]}),!u&&e.jsxs("section",{children:[e.jsx(rl,{test:le,starting:g,lastVerifiedAt:t.lastVerifiedAt,onStart:()=>{Gt()}}),f&&e.jsx("div",{className:"mt-3",children:e.jsx(Ft,{type:"err",text:f})})]}),!u&&at&&e.jsx(nl,{status:y,values:j,setValue:fe,channels:H,canListChannels:t.canListChannels,channelsLoading:D,channelsError:J,onReloadChannels:_,channelsGuidance:t.channelsGuidance??null,testSlot:ye?.sendTest?.(_e)}),e.jsxs("section",{"data-testid":`instance-more-${re}`,children:[e.jsxs("button",{type:"button",onClick:()=>v(E=>!E),"aria-expanded":k,"data-testid":`instance-more-toggle-${re}`,className:"w-full flex items-center gap-2 text-left group px-1",children:[e.jsx("span",{className:Vt,children:d("settings:instances.moreSettings",{defaultValue:"Advanced"})}),e.jsx("span",{className:`${vt} 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:[Qt.length>0&&e.jsxs("div",{className:ks,children:[e.jsx("h4",{className:`${Vt} mb-1`,children:d("settings:instances.advancedTitle",{defaultValue:"Platform options"})}),!u&&e.jsx("p",{className:`${vt} 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(jt,{status:y,draft:j,fields:Qt,onChange:fe,agentOptions:se})]}),!u&&e.jsxs("div",{className:ks,children:[e.jsx("h4",{className:`${Vt} mb-1`,children:d("settings:instances.routing.chats",{defaultValue:"Chat routing"})}),e.jsx("p",{className:`${vt} 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-${re}`,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(Ja,{loading:D,error:J,onReload:_,empty:H.length===0,buttonTestId:`instance-chats-refresh-${re}`,errorTestId:`instance-chats-error-${re}`})}),t.canListChannels&&H.length>0&&e.jsx("input",{type:"text",value:ee,onChange:E=>ue(E.target.value),placeholder:d("settings:instances.routing.searchChats",{defaultValue:"Search chats…"}),"data-testid":`instance-chat-search-${re}`,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-${re}`,children:[dt.map(E=>{const ae=ur(w,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:!!ae,"data-testid":`instance-chat-toggle-${re}-${E.id}`,onChange:Z=>Ts(E,Z.target.checked),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate",title:E.id,children:E.name})]}),ae&&e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${re}-${E.id}`,children:e.jsx(As,{value:ae.agentId,options:se,onChange:(Z,Ze)=>Pe(E.id,typeof Ze=="string"?Ze:""),fieldKey:"agentId",ariaLabel:d("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.id)}),St.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-${re}-${E.nativeId}`,onChange:()=>$(ae=>Yn(ae,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-${re}-${E.nativeId}`,children:e.jsx(As,{value:E.agentId,options:se,onChange:(ae,Z)=>Pe(E.nativeId,typeof Z=="string"?Z:""),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."})}),Fe>0&&e.jsx("div",{className:"mt-3",children:e.jsx(Ft,{type:"err",text:d("settings:instances.routing.agentRequired",{defaultValue:"Pick an agent for every selected chat ({{count}} still unassigned).",count:Fe})})})]})]})]}),!M&&ye&&ye.placement!=="before"&&ye.render(_e),!u&&e.jsx("div",{className:"pt-1",children:e.jsx("button",{type:"button",onClick:()=>oe(!0),"data-testid":`instance-disconnect-${re}`,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"})})})]}),ne&&e.jsx(Cs,{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:()=>{Es()},onCancel:()=>oe(!1)})]})}var ht={},mr,sa;function cl(){return sa||(sa=1,mr=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),mr}var xr={},We={},ra;function tt(){if(ra)return We;ra=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 We.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},We.getSymbolTotalCodewords=function(a){return r[a]},We.getBCHDigit=function(o){let a=0;for(;o!==0;)a++,o>>>=1;return a},We.setToSJISFunction=function(a){if(typeof a!="function")throw new Error('"toSJISFunc" is not a valid function.');t=a},We.isKanjiModeEnabled=function(){return typeof t<"u"},We.toSJIS=function(a){return t(a)},We}var gr={},na;function qr(){return na||(na=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.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: "+o)}}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}}})(gr)),gr}var fr,aa;function ul(){if(aa)return fr;aa=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(r){const o=Math.floor(r/8);return(this.buffer[o]>>>7-r%8&1)===1},put:function(r,o){for(let a=0;a<o;a++)this.putBit((r>>>o-a-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){const o=Math.floor(this.length/8);this.buffer.length<=o&&this.buffer.push(0),r&&(this.buffer[o]|=128>>>this.length%8),this.length++}},fr=t,fr}var pr,oa;function ml(){if(oa)return pr;oa=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,o,a,n){const s=r*this.size+o;this.data[s]=a,n&&(this.reservedBit[s]=!0)},t.prototype.get=function(r,o){return this.data[r*this.size+o]},t.prototype.xor=function(r,o,a){this.data[r*this.size+o]^=a},t.prototype.isReserved=function(r,o){return this.reservedBit[r*this.size+o]},pr=t,pr}var hr={},ia;function xl(){return ia||(ia=1,(function(t){const r=tt().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}})(hr)),hr}var br={},la;function gl(){if(la)return br;la=1;const t=tt().getSymbolSize,r=7;return br.getPositions=function(a){const n=t(a);return[[0,0],[n-r,0],[0,n-r]]},br}var yr={},da;function fl(){return da||(da=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,h=null,x=null;for(let k=0;k<s;k++){d=u=0,h=x=null;for(let v=0;v<s;v++){let y=n.get(k,v);y===h?d++:(d>=5&&(c+=r.N1+(d-5)),h=y,d=1),y=n.get(v,k),y===x?u++:(u>=5&&(c+=r.N1+(u-5)),x=y,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 h=n.get(d,u)+n.get(d,u+1)+n.get(d+1,u)+n.get(d+1,u+1);(h===4||h===0)&&c++}return c*r.N2},t.getPenaltyN3=function(n){const s=n.size;let c=0,d=0,u=0;for(let h=0;h<s;h++){d=u=0;for(let x=0;x<s;x++)d=d<<1&2047|n.get(h,x),x>=10&&(d===1488||d===93)&&c++,u=u<<1&2047|n.get(x,h),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 o(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,o(n,u,d))},t.getBestMask=function(n,s){const c=Object.keys(t.Patterns).length;let d=0,u=1/0;for(let h=0;h<c;h++){s(h),t.applyMask(h,n);const x=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(h,n),x<u&&(u=x,d=h)}return d}})(yr)),yr}var bs={},ca;function eo(){if(ca)return bs;ca=1;const t=qr(),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],o=[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 bs.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}},bs.getTotalCodewordsCount=function(n,s){switch(s){case t.L:return o[(n-1)*4+0];case t.M:return o[(n-1)*4+1];case t.Q:return o[(n-1)*4+2];case t.H:return o[(n-1)*4+3];default:return}},bs}var vr={},Bt={},ua;function pl(){if(ua)return Bt;ua=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]})(),Bt.log=function(a){if(a<1)throw new Error("log("+a+")");return r[a]},Bt.exp=function(a){return t[a]},Bt.mul=function(a,n){return a===0||n===0?0:t[r[a]+r[n]]},Bt}var ma;function hl(){return ma||(ma=1,(function(t){const r=pl();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}})(vr)),vr}var jr,xa;function bl(){if(xa)return jr;xa=1;const t=hl();function r(o){this.genPoly=void 0,this.degree=o,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},jr=r,jr}var Nr={},wr={},kr={},ga;function to(){return ga||(ga=1,kr.isValid=function(r){return!isNaN(r)&&r>=1&&r<=40}),kr}var Ie={},fa;function so(){if(fa)return Ie;fa=1;const t="[0-9]+",r="[A-Z $%*+\\-./:]+";let o="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";o=o.replace(/u/g,"\\u");const a="(?:(?![A-Z0-9 $%*+\\-./:]|"+o+`)(?:.|[\r
2
+ ]))+`;Ie.KANJI=new RegExp(o,"g"),Ie.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Ie.BYTE=new RegExp(a,"g"),Ie.NUMERIC=new RegExp(t,"g"),Ie.ALPHANUMERIC=new RegExp(r,"g");const n=new RegExp("^"+o+"$"),s=new RegExp("^"+t+"$"),c=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Ie.testKanji=function(u){return n.test(u)},Ie.testNumeric=function(u){return s.test(u)},Ie.testAlphanumeric=function(u){return c.test(u)},Ie}var pa;function st(){return pa||(pa=1,(function(t){const r=to(),o=so();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 o.testNumeric(s)?t.NUMERIC:o.testAlphanumeric(s)?t.ALPHANUMERIC:o.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}}})(wr)),wr}var ha;function yl(){return ha||(ha=1,(function(t){const r=tt(),o=eo(),a=qr(),n=st(),s=to(),c=7973,d=r.getBCHDigit(c);function u(v,y,S){for(let N=1;N<=40;N++)if(y<=t.getCapacity(N,S,v))return N}function h(v,y){return n.getCharCountIndicator(v,y)+4}function x(v,y){let S=0;return v.forEach(function(N){const j=h(N.mode,y);S+=j+N.getBitsLength()}),S}function k(v,y){for(let S=1;S<=40;S++)if(x(v,S)<=t.getCapacity(S,y,n.MIXED))return S}t.from=function(y,S){return s.isValid(y)?parseInt(y,10):S},t.getCapacity=function(y,S,N){if(!s.isValid(y))throw new Error("Invalid QR Code version");typeof N>"u"&&(N=n.BYTE);const j=r.getSymbolTotalCodewords(y),p=o.getTotalCodewordsCount(y,S),A=(j-p)*8;if(N===n.MIXED)return A;const m=A-h(N,y);switch(N){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(y,S){let N;const j=a.from(S,a.M);if(Array.isArray(y)){if(y.length>1)return k(y,j);if(y.length===0)return 1;N=y[0]}else N=y;return u(N.mode,N.getLength(),j)},t.getEncodedBits=function(y){if(!s.isValid(y)||y<7)throw new Error("Invalid QR Code version");let S=y<<12;for(;r.getBCHDigit(S)-d>=0;)S^=c<<r.getBCHDigit(S)-d;return y<<12|S}})(Nr)),Nr}var Cr={},ba;function vl(){if(ba)return Cr;ba=1;const t=tt(),r=1335,o=21522,a=t.getBCHDigit(r);return Cr.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)^o},Cr}var Sr={},Ar,ya;function jl(){if(ya)return Ar;ya=1;const t=st();function r(o){this.mode=t.NUMERIC,this.data=o.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))},Ar=r,Ar}var Pr,va;function Nl(){if(va)return Pr;va=1;const t=st(),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 o(a){this.mode=t.ALPHANUMERIC,this.data=a}return o.getBitsLength=function(n){return 11*Math.floor(n/2)+6*(n%2)},o.prototype.getLength=function(){return this.data.length},o.prototype.getBitsLength=function(){return o.getBitsLength(this.data.length)},o.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)},Pr=o,Pr}var Mr,ja;function wl(){if(ja)return Mr;ja=1;const t=st();function r(o){this.mode=t.BYTE,typeof o=="string"?this.data=new TextEncoder().encode(o):this.data=new Uint8Array(o)}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(o){for(let a=0,n=this.data.length;a<n;a++)o.put(this.data[a],8)},Mr=r,Mr}var Tr,Na;function kl(){if(Na)return Tr;Na=1;const t=st(),r=tt();function o(a){this.mode=t.KANJI,this.data=a}return o.getBitsLength=function(n){return n*13},o.prototype.getLength=function(){return this.data.length},o.prototype.getBitsLength=function(){return o.getBitsLength(this.data.length)},o.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)}},Tr=o,Tr}var Er={exports:{}},wa;function Cl(){return wa||(wa=1,(function(t){var r={single_source_shortest_paths:function(o,a,n){var s={},c={};c[a]=0;var d=r.PriorityQueue.make();d.push(a,0);for(var u,h,x,k,v,y,S,N,j;!d.empty();){u=d.pop(),h=u.value,k=u.cost,v=o[h]||{};for(x in v)v.hasOwnProperty(x)&&(y=v[x],S=k+y,N=c[x],j=typeof c[x]>"u",(j||N>S)&&(c[x]=S,d.push(x,S),s[x]=h))}if(typeof n<"u"&&typeof c[n]>"u"){var p=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(o,a){for(var n=[],s=a;s;)n.push(s),o[s],s=o[s];return n.reverse(),n},find_path:function(o,a,n){var s=r.single_source_shortest_paths(o,a,n);return r.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(o){var a=r.PriorityQueue,n={},s;o=o||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=o.sorter||a.default_sorter,n},default_sorter:function(o,a){return o.cost-a.cost},push:function(o,a){var n={value:o,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})(Er)),Er.exports}var ka;function Sl(){return ka||(ka=1,(function(t){const r=st(),o=jl(),a=Nl(),n=wl(),s=kl(),c=so(),d=tt(),u=Cl();function h(p){return unescape(encodeURIComponent(p)).length}function x(p,A,m){const w=[];let $;for(;($=p.exec(m))!==null;)w.push({data:$[0],index:$.index,mode:A,length:$[0].length});return w}function k(p){const A=x(c.NUMERIC,r.NUMERIC,p),m=x(c.ALPHANUMERIC,r.ALPHANUMERIC,p);let w,$;return d.isKanjiModeEnabled()?(w=x(c.BYTE,r.BYTE,p),$=x(c.KANJI,r.KANJI,p)):(w=x(c.BYTE_KANJI,r.BYTE,p),$=[]),A.concat(m,w,$).sort(function(I,V){return I.index-V.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function v(p,A){switch(A){case r.NUMERIC:return o.getBitsLength(p);case r.ALPHANUMERIC:return a.getBitsLength(p);case r.KANJI:return s.getBitsLength(p);case r.BYTE:return n.getBitsLength(p)}}function y(p){return p.reduce(function(A,m){const w=A.length-1>=0?A[A.length-1]:null;return w&&w.mode===m.mode?(A[A.length-1].data+=m.data,A):(A.push(m),A)},[])}function S(p){const A=[];for(let m=0;m<p.length;m++){const w=p[m];switch(w.mode){case r.NUMERIC:A.push([w,{data:w.data,mode:r.ALPHANUMERIC,length:w.length},{data:w.data,mode:r.BYTE,length:w.length}]);break;case r.ALPHANUMERIC:A.push([w,{data:w.data,mode:r.BYTE,length:w.length}]);break;case r.KANJI:A.push([w,{data:w.data,mode:r.BYTE,length:h(w.data)}]);break;case r.BYTE:A.push([{data:w.data,mode:r.BYTE,length:h(w.data)}])}}return A}function N(p,A){const m={},w={start:{}};let $=["start"];for(let B=0;B<p.length;B++){const I=p[B],V=[];for(let C=0;C<I.length;C++){const M=I[C],O=""+B+C;V.push(O),m[O]={node:M,lastCount:0},w[O]={};for(let L=0;L<$.length;L++){const U=$[L];m[U]&&m[U].node.mode===M.mode?(w[U][O]=v(m[U].lastCount+M.length,M.mode)-v(m[U].lastCount,M.mode),m[U].lastCount+=M.length):(m[U]&&(m[U].lastCount=M.length),w[U][O]=v(M.length,M.mode)+4+r.getCharCountIndicator(M.mode,A))}}$=V}for(let B=0;B<$.length;B++)w[$[B]].end=0;return{map:w,table:m}}function j(p,A){let m;const w=r.getBestModeForData(p);if(m=r.from(A,w),m!==r.BYTE&&m.bit<w.bit)throw new Error('"'+p+'" cannot be encoded with mode '+r.toString(m)+`.
4
+ Suggested mode is: `+r.toString(w));switch(m===r.KANJI&&!d.isKanjiModeEnabled()&&(m=r.BYTE),m){case r.NUMERIC:return new o(p);case r.ALPHANUMERIC:return new a(p);case r.KANJI:return new s(p);case r.BYTE:return new n(p)}}t.fromArray=function(A){return A.reduce(function(m,w){return typeof w=="string"?m.push(j(w,null)):w.data&&m.push(j(w.data,w.mode)),m},[])},t.fromString=function(A,m){const w=k(A,d.isKanjiModeEnabled()),$=S(w),B=N($,m),I=u.find_path(B.map,"start","end"),V=[];for(let C=1;C<I.length-1;C++)V.push(B.table[I[C]].node);return t.fromArray(y(V))},t.rawSplit=function(A){return t.fromArray(k(A,d.isKanjiModeEnabled()))}})(Sr)),Sr}var Ca;function Al(){if(Ca)return xr;Ca=1;const t=tt(),r=qr(),o=ul(),a=ml(),n=xl(),s=gl(),c=fl(),d=eo(),u=bl(),h=yl(),x=vl(),k=st(),v=Sl();function y(B,I){const V=B.size,C=s.getPositions(I);for(let M=0;M<C.length;M++){const O=C[M][0],L=C[M][1];for(let U=-1;U<=7;U++)if(!(O+U<=-1||V<=O+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?B.set(O+U,L+H,!0,!0):B.set(O+U,L+H,!1,!0))}}function S(B){const I=B.size;for(let V=8;V<I-8;V++){const C=V%2===0;B.set(V,6,C,!0),B.set(6,V,C,!0)}}function N(B,I){const V=n.getPositions(I);for(let C=0;C<V.length;C++){const M=V[C][0],O=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?B.set(M+L,O+U,!0,!0):B.set(M+L,O+U,!1,!0)}}function j(B,I){const V=B.size,C=h.getEncodedBits(I);let M,O,L;for(let U=0;U<18;U++)M=Math.floor(U/3),O=U%3+V-8-3,L=(C>>U&1)===1,B.set(M,O,L,!0),B.set(O,M,L,!0)}function p(B,I,V){const C=B.size,M=x.getEncodedBits(I,V);let O,L;for(O=0;O<15;O++)L=(M>>O&1)===1,O<6?B.set(O,8,L,!0):O<8?B.set(O+1,8,L,!0):B.set(C-15+O,8,L,!0),O<8?B.set(8,C-O-1,L,!0):O<9?B.set(8,15-O-1+1,L,!0):B.set(8,15-O-1,L,!0);B.set(C-8,8,1,!0)}function A(B,I){const V=B.size;let C=-1,M=V-1,O=7,L=0;for(let U=V-1;U>0;U-=2)for(U===6&&U--;;){for(let H=0;H<2;H++)if(!B.isReserved(M,U-H)){let J=!1;L<I.length&&(J=(I[L]>>>O&1)===1),B.set(M,U-H,J),O--,O===-1&&(L++,O=7)}if(M+=C,M<0||V<=M){M-=C,C=-C;break}}}function m(B,I,V){const C=new o;V.forEach(function(H){C.put(H.mode.bit,4),C.put(H.getLength(),k.getCharCountIndicator(H.mode,B)),H.write(C)});const M=t.getSymbolTotalCodewords(B),O=d.getTotalCodewordsCount(B,I),L=(M-O)*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 w(C,B,I)}function w(B,I,V){const C=t.getSymbolTotalCodewords(I),M=d.getTotalCodewordsCount(I,V),O=C-M,L=d.getBlocksCount(I,V),U=C%L,H=L-U,J=Math.floor(C/L),D=Math.floor(O/L),_=D+1,ee=J-D,ue=new u(ee);let le=0;const te=new Array(L),g=new Array(L);let T=0;const f=new Uint8Array(B.buffer);for(let ge=0;ge<L;ge++){const se=ge<H?D:_;te[ge]=f.slice(le,le+se),g[ge]=ue.encode(te[ge]),le+=se,T=Math.max(T,se)}const K=new Uint8Array(C);let q=0,ne,oe;for(ne=0;ne<T;ne++)for(oe=0;oe<L;oe++)ne<te[oe].length&&(K[q++]=te[oe][ne]);for(ne=0;ne<ee;ne++)for(oe=0;oe<L;oe++)K[q++]=g[oe][ne];return K}function $(B,I,V,C){let M;if(Array.isArray(B))M=v.fromArray(B);else if(typeof B=="string"){let J=I;if(!J){const D=v.rawSplit(B);J=h.getBestVersionForData(D,V)}M=v.fromString(B,J||40)}else throw new Error("Invalid data");const O=h.getBestVersionForData(M,V);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=O;else if(I<O)throw new Error(`
5
+ The chosen QR Code version cannot contain this amount of data.
6
+ Minimum version required to store current data is: `+O+`.
7
+ `);const L=m(I,V,M),U=t.getSymbolSize(I),H=new a(U);return y(H,I),S(H),N(H,I),p(H,V,0),I>=7&&j(H,I),A(H,L),isNaN(C)&&(C=c.getBestMask(H,p.bind(null,H,V))),c.applyMask(C,H),p(H,V,C),{modules:H,version:I,errorCorrectionLevel:V,maskPattern:C,segments:M}}return xr.create=function(I,V){if(typeof I>"u"||I==="")throw new Error("No input text");let C=r.M,M,O;return typeof V<"u"&&(C=r.from(V.errorCorrectionLevel,r.M),M=h.from(V.version),O=c.from(V.maskPattern),V.toSJISFunc&&t.setToSJISFunction(V.toSJISFunc)),$(I,M,C,O)},xr}var Rr={},Lr={},Sa;function ro(){return Sa||(Sa=1,(function(t){function r(o){if(typeof o=="number"&&(o=o.toString()),typeof o!="string")throw new Error("Color should be defined as hex string");let a=o.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+o);(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),h=Math.floor((c+s.margin*2)*u),x=s.margin*u,k=[s.color.light,s.color.dark];for(let v=0;v<h;v++)for(let y=0;y<h;y++){let S=(v*h+y)*4,N=s.color.light;if(v>=x&&y>=x&&v<h-x&&y<h-x){const j=Math.floor((v-x)/u),p=Math.floor((y-x)/u);N=k[d[j*c+p]?1:0]}a[S++]=N.r,a[S++]=N.g,a[S++]=N.b,a[S]=N.a}}})(Lr)),Lr}var Aa;function Pl(){return Aa||(Aa=1,(function(t){const r=ro();function o(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,h=c;typeof u>"u"&&(!c||!c.getContext)&&(u=c,c=void 0),c||(h=a()),u=r.getOptions(u);const x=r.getImageWidth(s.modules.size,u),k=h.getContext("2d"),v=k.createImageData(x,x);return r.qrToImageData(v.data,s,u),o(k,h,x),k.putImageData(v,0,0),h},t.renderToDataURL=function(s,c,d){let u=d;typeof u>"u"&&(!c||!c.getContext)&&(u=c,c=void 0),u||(u={});const h=t.render(s,c,u),x=u.type||"image/png",k=u.rendererOpts||{};return h.toDataURL(x,k.quality)}})(Rr)),Rr}var Ir={},Pa;function Ml(){if(Pa)return Ir;Pa=1;const t=ro();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 o(n,s,c){let d=n+s;return typeof c<"u"&&(d+=" "+c),d}function a(n,s,c){let d="",u=0,h=!1,x=0;for(let k=0;k<n.length;k++){const v=Math.floor(k%s),y=Math.floor(k/s);!v&&!h&&(h=!0),n[k]?(x++,k>0&&v>0&&n[k-1]||(d+=h?o("M",v+c,.5+y+c):o("m",u,0),u=0,h=!1),v+1<s&&n[k+1]||(d+=o("h",x),x=0)):u++}return d}return Ir.render=function(s,c,d){const u=t.getOptions(c),h=s.modules.size,x=s.modules.data,k=h+u.margin*2,v=u.color.light.a?"<path "+r(u.color.light,"fill")+' d="M0 0h'+k+"v"+k+'H0z"/>':"",y="<path "+r(u.color.dark,"stroke")+' d="'+a(x,h,u.margin)+'"/>',S='viewBox="0 0 '+k+" "+k+'"',j='<svg xmlns="http://www.w3.org/2000/svg" '+(u.width?'width="'+u.width+'" height="'+u.width+'" ':"")+S+' shape-rendering="crispEdges">'+v+y+`</svg>
8
+ `;return typeof d=="function"&&d(null,j),j},Ir}var Ma;function Tl(){if(Ma)return ht;Ma=1;const t=cl(),r=Al(),o=Pl(),a=Ml();function n(s,c,d,u,h){const x=[].slice.call(arguments,1),k=x.length,v=typeof x[k-1]=="function";if(!v&&!t())throw new Error("Callback required as last argument");if(v){if(k<2)throw new Error("Too few arguments provided");k===2?(h=d,d=c,c=u=void 0):k===3&&(c.getContext&&typeof h>"u"?(h=u,u=void 0):(h=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(y,S){try{const N=r.create(d,u);y(s(N,c,u))}catch(N){S(N)}})}try{const y=r.create(d,u);h(null,s(y,c,u))}catch(y){h(y)}}return ht.create=r.create,ht.toCanvas=n.bind(null,o.render),ht.toDataURL=n.bind(null,o.renderToDataURL),ht.toString=n.bind(null,function(s,c,d){return a.render(s,d)}),ht}var no=Tl();const ao=Vo(no),El=li({__proto__:null,default:ao},[no]);function Rl({ctx:t}){const{t:r}=xe(["settings","common"]),{values:o,reload:a,onCreated:n,agents:s=[]}=t,[c,d]=i.useState(null),[u,h]=i.useState("idle"),[x,k]=i.useState(null),[v,y]=i.useState(()=>String(o.agentId??"")),S=i.useRef(null),N=u!=="idle";i.useEffect(()=>()=>{S.current&&clearInterval(S.current)},[]);const j=i.useCallback(()=>{S.current&&(clearInterval(S.current),S.current=null)},[]),p=i.useCallback(async()=>{h("waiting_qr"),k(null),d(null),S.current=setInterval(async()=>{try{const m=await F.settings.getFeishuRegisterStatus();if(m.active&&m.url){h("scanning");try{k(await ao.toDataURL(m.url,{width:192,margin:2,color:{dark:"#000000",light:"#ffffff"}}))}catch{}}}catch{}},1e3);try{const m=await F.settings.registerFeishuApp({agentId:v||void 0});j(),m.success&&m.appId?(h("done"),d({type:"ok",text:r("settings:feishu.registerSuccess",{defaultValue:"App created successfully! Integration is now active."})}),await a(),m.instanceId&&n?.(m.instanceId)):(h("error"),d({type:"err",text:m.message??r("settings:feishu.registerFailed",{defaultValue:"Registration failed"})}))}catch(m){j(),h("error"),d({type:"err",text:m instanceof Error?m.message:String(m)})}},[a,n,v,r,j]),A=i.useCallback(()=>{j(),h("idle"),k(null),d(null)},[j]);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(As,{value:v,options:s,onChange:(m,w)=>y(typeof w=="string"?w:""),fieldKey:"agentId",disabled:N,ariaLabel:r("settings:feishu.bindAgent",{defaultValue:"Agent that answers for this bot"})}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-1",children:N?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:p,disabled:!v||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"})}),N&&u!=="done"&&e.jsx("button",{type:"button",onClick:A,"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 Ll({ctx:t}){const{t:r}=xe(["settings","common"]),[o,a]=i.useState(!1),[n,s]=i.useState(null),c=qa(t.status.fields),d=String(c?t.values[c.key]??"":"").trim(),u=t.instanceId,h=i.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:h,disabled:o,"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:[o?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 Il={feishu:{placement:"before",guidedSetup:{credentialFields:["appId","appSecret"]},render:t=>e.jsx(Rl,{ctx:t}),sendTest:t=>e.jsx(Ll,{ctx:t})}};async function Bl(){return(await F.settings.listInstances()).instances??[]}async function Ol(){return(await F.settings.listIntegrations()).platforms??[]}function Dl({loadPlatforms:t=Ol,loadInstances:r=Bl,client:o=Xa,extras:a=Il,loadAgents:n,devMode:s=!1,defaultExpanded:c=!1}){const{t:d}=xe(["settings","common"]),[u,h]=i.useState([]),[x,k]=i.useState([]),[v,y]=i.useState(!0),[S,N]=i.useState(null),[j,p]=i.useState(null),[A,m]=i.useState(null),w=i.useCallback(async()=>{const[C,M]=await Promise.all([r(),t()]);h(C),k(M),N(null)},[r,t]);i.useEffect(()=>{let C=!1;return(async()=>{y(!0);try{const[M,O]=await Promise.all([r(),t()]);if(C)return;h(M),k(O),N(null)}catch(M){C||N(M instanceof Error?M.message:String(M))}finally{C||y(!1)}})(),()=>{C=!0}},[r,t]);const $=i.useMemo(()=>Vi(u),[u]),B=i.useCallback(C=>{const M=x.find(O=>O.id===C);return M?wi(d,M):C},[x,d]),I=i.useMemo(()=>_i(x,u,{devMode:s}),[x,u,s]),V=i.useCallback(C=>{p(C)},[]);return v?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…"})})]}):S?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"}),": ",S]}):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."})}),I.map(C=>{const O=$.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(Za,{id:C}),e.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:B(C)}),O.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:O.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"})]})]}),j===C&&e.jsx(ta,{instance:Ii(x.find(L=>L.id===C)??{id:C,label:B(C),capabilities:{inbound:!1,outbound:!1,threads:!1},fields:[]}),client:o,extras:a,loadAgents:n,onChanged:w,onCreated:L=>{p(null),m(L)},defaultExpanded:!0}),O.map(L=>e.jsx(ta,{instance:L,client:o,extras:a,loadAgents:n,onChanged:w,defaultExpanded:c||L.id===A},L.id)),O.length===0&&j!==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 $l=["macos","linux","windows"];function Vl(){const{t}=xe(["settings","common"]),[r,o]=i.useReducer(_o,Fo),[a,n]=i.useState(null),[s,c]=i.useState("linux"),[d,u]=i.useState(!1),[h,x]=i.useState(null),[k,v]=i.useState(null),[y,S]=i.useState(""),[N,j]=i.useState(!1),[p,A]=i.useState(null),[m,w]=i.useState(""),$=i.useRef(!0),B=_t.isAuthenticated(),I=$a(),{kind:V,phase:C}=r,M=V?Uo(V):null;i.useEffect(()=>{c(Ko(typeof navigator>"u"?"":navigator.userAgent))},[]),i.useEffect(()=>($.current=!0,F.settings.getRemoteV2().then(f=>{$.current&&f&&o({type:"status",status:f})}).catch(()=>{}),F.settings.remoteDetect().then(f=>{$.current&&n(f)}).catch(()=>{$.current&&n(null)}),F.settings.remoteSetupTargets().then(f=>{$.current&&(A(f),w(K=>K||f.recommendedId||f.agents[0]?.id||""))}).catch(()=>{$.current&&A(null)}),()=>{$.current=!1}),[]),i.useEffect(()=>Ho.on("remote:status",f=>{const K=zo(f.payload);K&&o({type:"status",status:K})}),[]);const O=i.useCallback((f,K)=>{navigator.clipboard?.writeText(f),v(K),setTimeout(()=>v(q=>q===K?null:q),2e3)},[]),L=i.useCallback(async()=>{try{const f=await F.settings.getRemoteV2();return f&&o({type:"status",status:f}),f}catch{return null}},[]),U=i.useCallback(async()=>{try{await Va()}catch{}},[]),H=f=>{x(null),j(!1),o({type:"selectKind",kind:f})},J=async()=>{x(null),o({type:"choosePath",path:"self"}),o({type:"beginInstall"}),o({type:"installSucceeded"});const f=await L();o(Jo(f))},D=async()=>{const f=y.trim();if(f){u(!0),x(null);try{await F.settings.remoteTunnelRegister({kind:V??"custom",publicUrl:f}),o({type:"addressResolved",publicUrl:f}),await L()}catch(K){const q=String(K instanceof Error?K.message:K);x(q),o({type:"userError",message:q})}finally{u(!1)}}},_=()=>{x(null),o({type:"choosePath",path:"agent"})},ee=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}:{},...I?.username?{username:I.username}:{}});f.ok&&f.agentId&&f.prompt?(o({type:"handedToChat",contract:f.contract??null}),Ns.navigate($r.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)}},ue=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"?o({type:"reset"}):await L()}catch(K){x(String(K instanceof Error?K.message:K))}finally{u(!1)}},le=()=>{ue("stop")},te=r.entryUrl??qo(I?.username??null),g=C==="ready"||C==="reconnecting",T=V?Go(V,s):null;return e.jsx(_l,{title:t("settings:remoteAccess.title"),children:e.jsxs("div",{className:"space-y-5",children:[e.jsx("p",{className:"text-sm text-fg-secondary",children:t("settings:remoteAccess.description")}),B?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-fg-secondary",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),t("settings:remoteAccess.signedInAs")," ",e.jsx("strong",{children:I?.username??I?.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(Fl,{}),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-on-brand rounded-lg transition-colors",children:t("settings:remoteAccess.signIn")})]}),B&&e.jsx(e.Fragment,{children:g&&M?e.jsx(ed,{t,phase:C,meta:M,entryUrl:te,publicUrl:r.publicUrl,health:r.health,latencyMs:r.latencyMs,message:r.message,busy:d,copied:k,onCopy:O,onRestart:()=>{ue("restart")},onRotate:()=>{ue("rotate")},onClose:le}):e.jsxs(e.Fragment,{children:[e.jsx(Gl,{t,detected:a,selected:V,onSelect:H}),V&&M&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Jl,{t,phase:C}),C==="error"&&e.jsx(Xl,{t,message:r.message,verifyFailure:r.verifyFailure,showManual:N,manualUrl:y,busy:d,onToggleManual:()=>j(f=>!f),onManualChange:S,onManualSubmit:()=>{D()},onRetry:()=>{x(null),o({type:"verifyStarted"}),L()},onStartOver:()=>{x(null),j(!1),o({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(oo,{}),e.jsx("span",{children:t("settings:remoteAccess.wizard.reconnecting")})]}),e.jsx(Yl,{t,setupPath:r.path,busy:d,onSelf:()=>o({type:"choosePath",path:"self"}),onAgent:()=>_()}),r.path==="self"&&T&&e.jsx(Ql,{t,platform:s,onPlatform:c,commands:T,meta:M,detected:a,copied:k,onCopy:O,onDone:()=>{J()},busy:d}),r.path==="self"&&C==="resolve"&&e.jsx(Zl,{t,value:y,busy:d,onChange:S,onSubmit:()=>{D()}}),r.path==="agent"&&e.jsxs("div",{className:"space-y-3",children:[p&&p.agents.length>0?e.jsxs("label",{className:"block text-sm",children:[e.jsx("span",{className:"text-fg-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=>{w(f.target.value),o({type:"selectAgent",agentId:f.target.value})},children:p.agents.map(f=>e.jsxs("option",{value:f.id,children:[f.name,f.id===p.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-fg-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-fg-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-fg-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-fg-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-on-brand hover:bg-brand-500 disabled:opacity-50",disabled:d||!p||p.agents.length===0,onClick:()=>{ee()},children:t("settings:remoteAccess.path.agent.handOff")})]}),h&&e.jsx("div",{className:"p-2 rounded-lg bg-red-500/10 text-red-500 text-sm",children:h})]})]})}),e.jsx(td,{t})]})})}function _l({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 Fl(){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 oo(){return e.jsxs("svg",{className:"w-4 h-4 animate-spin text-fg-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 Ul({url:t}){const r=i.useRef(null),[o,a]=i.useState(!1);return i.useEffect(()=>{const n=r.current;n&&(a(!1),Yo(()=>Promise.resolve().then(()=>El),void 0).then(s=>{s.toCanvas(n,t,{width:200,margin:2,color:{dark:"#000000",light:"#ffffff"},errorCorrectionLevel:"M"})}).catch(()=>a(!0)))},[t]),o?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 Kl={install:"settings:remoteAccess.stepInstall",start:"settings:remoteAccess.stepStart",resolve:"settings:remoteAccess.stepResolve",register:"settings:remoteAccess.stepRegister",verify:"settings:remoteAccess.stepVerify",ready:"settings:remoteAccess.stepReady"},Kr={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"}},Hl={low:"settings:remoteAccess.barrierLow",medium:"settings:remoteAccess.barrierMedium",high:"settings:remoteAccess.barrierHigh"},zl={high:"settings:remoteAccess.stabilityHigh",medium:"settings:remoteAccess.stabilityMedium",low:"settings:remoteAccess.stabilityLow"},ql={macos:"settings:remoteAccess.platformMacos",linux:"settings:remoteAccess.platformLinux",windows:"settings:remoteAccess.platformWindows"},Wl={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 Gl({t,detected:r,selected:o,onSelect:a}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary uppercase tracking-wider mb-2",children:t("settings:remoteAccess.methodTitle")}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Wo.map(n=>{const s=o===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-fg-primary",children:t(Kr[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-fg-tertiary mt-1 leading-snug",children:t(Kr[n.kind].desc)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[e.jsx(Ot,{children:t(Hl[n.barrier])}),e.jsx(Ot,{children:t(zl[n.stability])}),e.jsx(Ot,{children:n.needsAccount?t("settings:remoteAccess.badgeNeedsAccount"):t("settings:remoteAccess.badgeNoAccount")}),e.jsx(Ot,{children:n.needsDomain?t("settings:remoteAccess.badgeNeedsDomain"):t("settings:remoteAccess.badgeNoDomain")}),c!==null&&e.jsxs(Ot,{tone:c?"good":"warn",children:[c?"✓ ":"✕ ",n.binary," ",t(c?"settings:remoteAccess.badgeDetected":"settings:remoteAccess.badgeNotDetected")]})]})]},n.kind)})})]})}function Ot({children:t,tone:r="default"}){const o=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-secondary text-fg-tertiary";return e.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded ${o}`,children:t})}function Jl({t,phase:r}){const o=Qo(r),a=r==="error";return e.jsx("div",{className:"flex items-center gap-1",children:Vn.map((n,s)=>{const c=o>=0&&s<o,d=o>=0&&s===o,u=a&&s===Math.max(0,o);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-on-brand":c?"bg-green-500 text-on-brand":d?"bg-brand-600 text-on-brand":"bg-surface-secondary text-fg-tertiary"}`,children:c?"✓":u?"!":s+1}),e.jsx("span",{className:`text-[10px] leading-tight text-center truncate ${d||u?"text-fg-primary":"text-fg-tertiary"}`,children:t(Kl[n])})]}),s<Vn.length-1&&e.jsx("span",{className:`h-px flex-1 ${c?"bg-green-500/50":"bg-border-default"}`})]},n)})})}function Yl({t,setupPath:r,busy:o,onSelf:a,onAgent:n}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-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-fg-primary",children:t("settings:remoteAccess.pathSelfTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:t("settings:remoteAccess.pathSelfDesc")})]}),e.jsxs("button",{type:"button",onClick:n,disabled:o,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-fg-primary",children:t("settings:remoteAccess.pathAgentTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:t("settings:remoteAccess.pathAgentDesc")})]})]})]})}function Ql({t,platform:r,onPlatform:o,commands:a,meta:n,detected:s,copied:c,onCopy:d,onDone:u,busy:h}){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:$l.map(k=>e.jsx("button",{type:"button",onClick:()=>o(k),className:`px-2 py-1 text-xs rounded-md transition-colors ${r===k?"bg-brand-600 text-on-brand":"bg-surface-secondary text-fg-secondary hover:text-fg-primary"}`,children:t(ql[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-fg-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-secondary 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:h,className:"w-full px-3 py-2 text-sm font-medium bg-brand-600 hover:bg-brand-500 text-on-brand rounded-lg transition-colors disabled:opacity-60",children:t("settings:remoteAccess.commandsDone")})]})}function Zl({t,value:r,busy:o,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-fg-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-secondary border border-border-default rounded font-mono"}),e.jsx("button",{type:"button",onClick:n,disabled:o||!r.trim(),className:"px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-on-brand rounded-lg disabled:opacity-60",children:t("settings:remoteAccess.errorManualSubmit")})]})]})}function Xl({t,message:r,verifyFailure:o,showManual:a,manualUrl:n,busy:s,onToggleManual:c,onManualChange:d,onManualSubmit:u,onRetry:h,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-fg-secondary",children:o?t(Wl[o]):r??t("settings:remoteAccess.errorGeneric")}),o==="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-secondary 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-on-brand 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:h,className:"px-3 py-1.5 text-xs font-medium bg-brand-600 hover:bg-brand-500 text-on-brand 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-fg-secondary hover:text-fg-primary",children:t("settings:remoteAccess.errorStartOver")})]})]})}function ed({t,phase:r,meta:o,entryUrl:a,publicUrl:n,health:s,latencyMs:c,message:d,busy:u,copied:h,onCopy:x,onRestart:k,onRotate:v,onClose:y}){const S=r==="reconnecting",N=s==="up"&&!S;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 ${N?"bg-green-500 animate-pulse":S?"bg-blue-500 animate-pulse":"bg-amber-500"}`}),e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t(N?"settings:remoteAccess.readyOnline":S?"settings:remoteAccess.wizard.reconnecting":"settings:remoteAccess.readyDegraded")}),N&&c!=null&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:t("settings:remoteAccess.readyLatency",{ms:c})}),e.jsxs("span",{className:"text-xs text-fg-tertiary",children:["· ",t(Kr[o.kind].name)]})]}),S&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-blue-600 dark:text-blue-400",children:[e.jsx(oo,{}),t("settings:remoteAccess.wizard.reconnectingHint")]}),!S&&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-fg-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-secondary 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 ${h==="entry"?"border-green-500 text-green-600 dark:text-green-400":"border-border-default hover:bg-surface-elevated"}`,children:t(h==="entry"?"settings:remoteAccess.copied":"settings:remoteAccess.copy")})]}),e.jsx("p",{className:"text-xs text-fg-secondary",children:t("settings:remoteAccess.readyEntryHint")}),e.jsxs("div",{className:"pt-1",children:[e.jsx(Ul,{url:a}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:t("settings:remoteAccess.readyScanQr")})]}),e.jsx("p",{className:"text-xs text-fg-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-fg-tertiary uppercase tracking-wider",children:t("settings:remoteAccess.readyPublicUrl")}),e.jsx("code",{className:"block text-xs font-mono break-all text-fg-secondary",children:n}),e.jsx("p",{className:"text-xs text-fg-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:v,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:y,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 td({t}){const[r,o]=i.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:()=>o(n=>!n),className:"flex items-center justify-between w-full px-3 py-2 text-sm text-fg-secondary hover:text-fg-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-fg-tertiary leading-snug",children:n},s))})]})}const Dt=[{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"}],sd=800,Ta=[{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 ys({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 rd(){const{t}=xe(["settings","common"]),[r,o]=i.useState(null),[a,n]=i.useState(!0),[s,c]=i.useState(new Set),[d,u]=i.useState({}),[h,x]=i.useState({}),[k,v]=i.useState(!1),[y,S]=i.useState(!1),[N,j]=i.useState({}),[p,A]=i.useState({}),[m,w]=i.useState({}),[$,B]=i.useState({}),I=i.useRef({}),V=i.useCallback(async()=>{n(!0);try{const g=await F.settings.getSearch();g&&(o(g),Dt.some(f=>!!g[f.id]?.configured)&&S(!0))}catch{}n(!1)},[]);i.useEffect(()=>{V()},[V]),i.useEffect(()=>()=>{Object.values(I.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})),I.current[g]&&clearTimeout(I.current[g]),I.current[g]=setTimeout(()=>{O(g)},sd)},O=async g=>{const T=Dt.find(q=>q.id===g);if(!T)return;const f=d[T.field]?.trim(),K=T.extraField?d[T.extraField]?.trim():void 0;if(!(!f&&!K)){x(q=>({...q,[g]:!0})),j(q=>{const ne={...q};return delete ne[g],ne});try{const q={};f&&(q[T.field]=f),K&&T.extraField&&(q[T.extraField]=K);const ne=await F.settings.updateSearch(q);o(ne),u(oe=>{const ge={...oe};return delete ge[T.field],T.extraField&&delete ge[T.extraField],ge}),j(oe=>({...oe,[g]:{type:"ok",text:t("searchApi.saved")}})),setTimeout(()=>j(oe=>{const ge={...oe};return delete ge[g],ge}),3e3)}catch{j(q=>({...q,[g]:{type:"err",text:t("searchApi.failedToSave")}}))}x(q=>({...q,[g]:!1}))}},L=g=>r?.[g],U=g=>L(g)?.configured??!1,H=g=>L(g)?.enabled!==!1,J=async(g,T)=>{B(f=>({...f,[g]:!0}));try{const f={[`${g}Enabled`]:T},K=await F.settings.updateSearch(f);o(K)}catch{}B(f=>({...f,[g]:!1}))},D=async g=>{I.current[g]&&(clearTimeout(I.current[g]),delete I.current[g],await O(g)),A(T=>({...T,[g]:!0})),w(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)),w(K=>({...K,[g]:{ok:!0,text:f.join(" · ")}}))}else w(f=>({...f,[g]:{ok:!1,text:T.error||t("searchApi.testFailed")}}))}catch{w(T=>({...T,[g]:{ok:!1,text:t("searchApi.testFailed")}}))}A(T=>({...T,[g]:!1}))},_=async g=>{v(!0);try{const T=await F.settings.updateSearch(g);o(T)}catch{}v(!1)},ee=({id:g,disabled:T})=>{const f=p[g];return e.jsxs("button",{type:"button",onClick:()=>{D(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(ys,{}):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")]})},ue=({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},le=({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(ys,{className:"w-3 h-3 text-fg-tertiary"}),e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:T,disabled:f,onChange:K=>{J(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"})]})},te=r?.markus;return e.jsx("section",{children: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")})]}),te?.available&&te.enabled&&e.jsx(ee,{id:"markus"}),te?.available?e.jsxs("label",{className:"inline-flex items-center gap-2 cursor-pointer shrink-0",children:[k&&e.jsx(ys,{className:"w-3 h-3 text-fg-tertiary"}),e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:te.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")})]}),!te?.available&&e.jsx("div",{className:"text-[11px] text-amber-500/90",children:t("searchApi.markusUnavailableHint")}),te?.available&&te.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:te.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:[Ta.map(g=>e.jsx("option",{value:g.id,children:t(g.labelKey)},g.id)),te.markusSearchModel&&!Ta.some(g=>g.id===te.markusSearchModel)&&e.jsx("option",{value:te.markusSearchModel,children:te.markusSearchModel})]})]}),e.jsx("div",{className:"text-[11px] text-fg-tertiary",children:t("searchApi.modelHint")}),e.jsx(ue,{id:"markus"})]}),e.jsxs("div",{className:"rounded-xl border border-border-default overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>S(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:y}),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:[Dt.filter(g=>U(g.id)).length,"/",Dt.length]})]}),y&&e.jsx("div",{className:"border-t border-border-default px-2 pb-2 space-y-1",children:Dt.map(g=>{const T=U(g.id),f=s.has(g.id),K=N[g.id],q=h[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(le,{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:ne=>M(g.id,g.field,ne.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:ne=>M(g.id,g.extraField,ne.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(ee,{id:g.id,disabled:!T&&!d[g.field]?.trim()}),q&&e.jsxs("span",{className:"text-[10px] text-fg-tertiary flex items-center gap-1",children:[e.jsx(ys,{}),t("common:saving")]}),K&&e.jsx("span",{className:`text-[10px] ${K.type==="ok"?"text-green-500":"text-red-500"}`,children:K.text})]}),e.jsx(ue,{id:g.id})]})})]},g.id)})})]})]})]})})}async function io(t,r={}){try{if(r.apiKey){const a=await F.modelCatalog.validateKey(t,r.apiKey,r.baseUrl);return _n(a.models??[])}const o=await F.modelCatalog.getByProvider(t);return _n(o.models??[])}catch(o){return Zo(o)}}const Wr=[{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:"network",labelKey:"nav.network",adminOnly:!0},{id:"account",labelKey:"nav.account"}],Br=[{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","network"]},{labelKey:"nav.group.account",tabs:["account"]}];function nd(t){switch(t){case"providers":return["llm","network","oauth","authProfiles"];case"network":return["network"];case"execution":return["agent"];case"browser":return["browser"];case"storage":return["storage"];default:return[]}}const ad={Database:"database",Agents:"agents",Skills:"skills","LLM Logs":"llmLogs","Builder Artifacts":"builderArtifacts",Teams:"teams",Shared:"shared",Knowledge:"knowledge"},Or={Database:"keep",Agents:"keep",Skills:"caution","LLM Logs":"safe","Builder Artifacts":"caution",Teams:"keep",Shared:"caution",Knowledge:"caution"},Ra={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",network:"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 Hr({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:Ra[t]??Ra._default})})}const od={users:"account",organization:"account",license:"account",remote:"network"};function id(t){const o=(t.startsWith("#")?t.slice(1):t).split("/");if(o[0]==="settings"&&o[1]){const a=o[1],s=od[a]??a;if(Wr.some(c=>c.id===s))return s}return null}function La(){return id(window.location.hash)}function Md({theme:t,onThemeChange:r,authUser:o,onLogout:a,onUserUpdated:n}={}){const{t:s,i18n:c}=xe(["settings","common"]),d=Xo(),u=ei($r.SETTINGS),h=ti(),x=h?.keyboardPane??"content",[k,v]=i.useState(La),[y,S]=i.useState(!1);i.useEffect(()=>{const l=()=>v(La());return window.addEventListener("hashchange",l),()=>window.removeEventListener("hashchange",l)},[]);const N=i.useCallback(l=>{v(l),history.pushState(null,"",`#settings/${l}`)},[]),j=i.useCallback(()=>{v(null),history.pushState(null,"","#settings")},[]),p=k??(d?null:"appearance"),[A,m]=i.useState(!1),[w,$]=i.useState(!1);i.useEffect(()=>{!Fn()||!window.markusDesktop?.getLoginItemSettings||window.markusDesktop.getLoginItemSettings().then(l=>m(!!l.openAtLogin)).catch(()=>{})},[]);const B=i.useCallback(async()=>{if(!window.markusDesktop?.setLoginItemSettings||w)return;const l=!A;$(!0),m(l);try{const b=await window.markusDesktop.setLoginItemSettings(l);m(!!b.openAtLogin)}catch{m(!l)}finally{$(!1)}},[A,w]),[I,V]=i.useState(null),[C,M]=i.useState(null),[O,L]=i.useState(""),[U,H]=i.useState(!1),[J,D]=i.useState(null),[_,ee]=i.useState(null),[ue,le]=i.useState(null),[te,g]=i.useState({}),[T,f]=i.useState(null),[K,q]=i.useState(null),[ne,oe]=i.useState(null),[ge,se]=i.useState(!1),[Je,Ae]=i.useState(null),[Se,Oe]=i.useState({}),[rt,we]=i.useState(!1),[fe,zt]=i.useState(null),[Ye,Nt]=i.useState(!1),[De,nt]=i.useState(""),[qt,Wt]=i.useState(!1),[Qe,Re]=i.useState(null),[wt,Gt]=i.useState(""),[ye,_e]=i.useState(!0),[Jt,at]=i.useState([]),[Yt,ot]=i.useState(""),[kt,Qt]=i.useState("none"),[Zt,Ct]=i.useState(null),[Ps,it]=i.useState(!1),[Ms,lt]=i.useState(null),[dt,St]=i.useState("0.0.0.0"),[Fe,Ts]=i.useState("0.0.0.0"),[Pe,Es]=i.useState(!1),[Ue,re]=i.useState(""),[ct,At]=i.useState(!1),[E,ae]=i.useState(!1),[Z,Ze]=i.useState(null),[Xt,Gr]=i.useState(!1),[Rs,es]=i.useState(null),[Jr,lo]=i.useState([]),[Yr,Ls]=i.useState([]),[Pt,ut]=i.useState(null),[Is,je]=i.useState(null),[ts,Qr]=i.useState(""),[co,Mt]=i.useState(null),[Tt,Bs]=i.useState(null),ve=i.useRef(null),Zr=i.useRef(!1),Xr=i.useRef(!1),[en,Os]=i.useState(200),[tn,Ds]=i.useState(20),[ss,rs]=i.useState(!1),[$s,Ke]=i.useState(null),[ns,Vs]=i.useState(!1),[sn,_s]=i.useState(3),[rn,Fs]=i.useState("auto"),[nn,an]=i.useState(!1),[Us,mt]=i.useState(null),[xt,Ks]=i.useState("embedded"),[as,Hs]=i.useState("direct"),[zs,os]=i.useState(!1),[on,qs]=i.useState(0),[Ws,is]=i.useState(!0),[Gs,ls]=i.useState(!1),[He,ln]=i.useState(!1),[wd,uo]=i.useState(9333),[pe,me]=i.useState(!1),[Js,X]=i.useState(null),[$e,mo]=i.useState(null),[Ys,dn]=i.useState(!1),[ds,xo]=i.useState(null),[kd,Cd]=i.useState(!1),de=()=>({"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("markus_token")??""}`}),Qs=i.useRef(new Set),cn=i.useCallback(()=>{F.health().then(V).catch(()=>{})},[]),ze=i.useCallback(()=>si({force:!0}).then(l=>l&&typeof l=="object"&&"providers"in l?(M(l),L(l.defaultProvider??""),!0):!1).catch(()=>!1),[]),Xe=i.useCallback(()=>fetch("/api/settings/network").then(l=>l.ok?l.json():Promise.reject(l.status)).then(l=>{Gt(l.network?.proxy??""),_e(l.network?.proxyEnabled!==!1),Ze(l.effective);const b=l.egress;return b&&(at(b.noProxy??[]),Qt(b.source??"none"),Ct(b.error??null)),St(l.server?.host??"0.0.0.0"),Ts(l.server?.effectiveHost??"0.0.0.0"),Es(l.server?.source==="env"),At(!!l.server?.pendingRestart),!0}).catch(()=>!1),[]),un=i.useCallback(()=>fetch("/api/settings/oauth/providers").then(l=>l.ok?l.json():Promise.reject(l.status)).then(l=>(lo(l.providers??[]),!0)).catch(()=>!1),[]),cs=i.useCallback((l=!1)=>fetch(`/api/settings/oauth/profiles${l?"?validate=1":""}`,{headers:de()}).then(R=>R.ok?R.json():Promise.reject(R.status)).then(R=>(Ls(R.profiles??[]),!0)).catch(()=>!1),[]),mn=i.useCallback(()=>F.settings.getAgent().then(l=>(l&&typeof l.maxToolIterations=="number"&&Os(l.maxToolIterations),l&&typeof l.maxPendingTasksPerAgent=="number"&&Ds(l.maxPendingTasksPerAgent),l?.concurrent&&(Vs(l.concurrent.enabled??!0),_s(l.concurrent.maxWorkers??3),Fs(l.concurrent.conflictPolicy??"auto")),!0)).catch(()=>!1),[]),xn=i.useCallback(()=>F.settings.getBrowser().then(l=>(l&&(Ks(l.mode??"embedded"),Hs(l.elementSelection??"direct"),os(l.bringToFront??!1),qs(l.remoteDebuggingPort??0),is(l.autoCloseTabs??!0),ls(l.autoClickAllowDialog??!1),ln(l.extensionConnected??!1),uo(l.extensionBridgePort??9333)),!0)).catch(()=>!1),[]),gt=i.useCallback(()=>{dn(!0);const l=F.system.storage().then(mo).then(()=>!0).catch(()=>!1).finally(()=>dn(!1));return F.system.orphans().then(xo).catch(()=>{}),l},[]);i.useEffect(()=>{cn()},[cn]);const[go,fo]=i.useState(0);i.useEffect(()=>{if(!p||Qs.current.has(p))return;const l=nd(p),b=[];if(l.includes("llm")&&b.push(ze()),l.includes("network")&&b.push(Xe()),l.includes("oauth")&&b.push(un()),l.includes("authProfiles")&&b.push(cs(!0)),l.includes("agent")&&b.push(mn()),l.includes("browser")&&b.push(xn()),l.includes("storage")&&b.push(gt()),b.length===0){Qs.current.add(p);return}let R=null,z=!1;return Promise.all(b).then(W=>{if(!z){if(W.every(Boolean)){Qs.current.add(p);return}R=setTimeout(()=>fo(Y=>Y+1),1500)}}),()=>{z=!0,R&&clearTimeout(R)}},[p,go,ze,Xe,un,cs,mn,xn,gt]),i.useEffect(()=>{const l=()=>gt();return window.addEventListener("markus:data-changed",l),()=>window.removeEventListener("markus:data-changed",l)},[gt]),i.useEffect(()=>{!_||te[_]||(f(_),_==="markus"&&q(null),F.modelCatalog.getLive(_).then(l=>{g(b=>({...b,[_]:l.models})),_==="markus"&&(l.error&&q(String(l.error)),ze())}).catch(l=>{_==="markus"&&q(l instanceof Error?l.message:String(l)),F.modelCatalog.getByProvider(_).then(b=>{g(R=>({...R,[_]:b.models}))}).catch(()=>{})}).finally(()=>f(null)))},[_]);const Zs=i.useCallback(async()=>{se(!0),Ae(null),oe(null),Oe({});try{const l=await fetch("/api/settings/env-models",{headers:de()});if(!l.ok){Ae({type:"err",text:s("envConfig.detectionFailedHttp",{status:l.status})});return}const b=await l.json();if(oe(b),b.detected.length===0)Ae({type:"err",text:s("envConfig.noKeysFound")});else{const R={};for(const z of b.detected)R[z.provider]=!0;Oe(R)}}catch{Ae({type:"err",text:s("envConfig.failedToDetect")})}finally{se(!1)}},[s]),Et=i.useCallback(async()=>{Nt(!0),Re(null),zt(null);try{const l=await fetch("/api/settings/detect-ollama",{headers:de()});if(!l.ok){Re({type:"err",text:s("ollama.detectFailed")});return}const b=await l.json();zt(b),b.found&&b.models&&b.models.length>0?nt(b.models[0].name):b.found||Re({type:"err",text:b.error||s("ollama.notRunning")})}catch{Re({type:"err",text:s("ollama.detectFailed")})}finally{Nt(!1)}},[s]),gn=C?Object.values(C.providers).some(l=>l.configured):!1;i.useEffect(()=>{C&&!gn&&!Zr.current&&(Zr.current=!0,Zs(),Et())},[C,gn,Zs,Et]),i.useEffect(()=>{_==="ollama"&&!fe&&!Ye&&!Xr.current&&(Xr.current=!0,Et())},[_,fe,Ye,Et]);const po=async()=>{if(!(!O||O===C?.defaultProvider)){H(!0),D(null);try{const l=await fetch("/api/settings/llm",{method:"POST",headers:de(),body:JSON.stringify({defaultProvider:O})}),b=await l.json();l.ok?(M(b),D({type:"ok",text:s("defaultProvider.updated",{name:b.defaultProvider})})):D({type:"err",text:b.error??s("modelProviders.saveFailed")})}catch{D({type:"err",text:s("common:networkError")})}finally{H(!1)}}},ho=async(l,b)=>{le(l);try{const R=await fetch(`/api/settings/llm/providers/${l}/toggle`,{method:"POST",headers:de(),body:JSON.stringify({enabled:b})});if(R.ok){const z=await R.json();M(z)}}catch{}finally{le(null)}},bo=async()=>{if(!ne)return;const l=ne.detected.filter(b=>Se[b.provider]);if(l.length===0){Ae({type:"err",text:s("envConfig.selectAtLeastOne")});return}we(!0),Ae(null);try{const b=await fetch("/api/settings/env-models",{method:"POST",headers:de(),body:JSON.stringify({providers:l.map(z=>({provider:z.provider,model:z.model,baseUrl:z.baseUrl,enabled:!0}))})});if(!b.ok){Ae({type:"err",text:s("envConfig.applyFailed",{status:b.status})});return}const R=await b.json();Ae({type:"ok",text:R.message}),oe(null),Oe({}),ze()}catch{Ae({type:"err",text:s("envConfig.failedToApply")})}finally{we(!1)}},yo=async()=>{if(!(!fe?.found||!De)){Wt(!0),Re(null);try{const l=await fetch("/api/settings/llm/providers",{method:"POST",headers:de(),body:JSON.stringify({name:"ollama",model:De,baseUrl:fe.baseUrl||"http://localhost:11434"})});if(l.ok){const b=await l.json();M(b),Re({type:"ok",text:s("ollama.configured",{model:De})})}else{const b=await l.json();Re({type:"err",text:b.error||s("ollama.applyFailed")})}}catch{Re({type:"err",text:s("ollama.applyFailed")})}finally{Wt(!1)}}},fn=async l=>{ut(l),je(null);try{const b=await fetch("/api/settings/oauth/login",{method:"POST",headers:de(),body:JSON.stringify({provider:l})}),R=await b.json();if(!b.ok||R.error){je({type:"err",text:R.error??s("oauth.loginFailed")});return}R.authorizeUrl&&(window.open(R.authorizeUrl,"_blank","noopener"),Mt(l),je({type:"ok",text:s("browserOpened")}),ve.current&&clearInterval(ve.current),ve.current=setInterval(async()=>{try{const W=await(await fetch(`/api/settings/oauth/status?provider=${l}`,{headers:de()})).json();!W.pending&&W.profiles.some(Y=>Y.provider===l&&Y.hasOAuth)&&(ve.current&&clearInterval(ve.current),ve.current=null,Mt(null),Ls(W.profiles),je({type:"ok",text:s("oauthConnected",{provider:l})}),ze())}catch{}},2e3))}catch{je({type:"err",text:s("oauth.networkErrorDuringLogin")})}finally{ut(null)}},vo=async l=>{ut(l),je(null),Bs(null);try{const b=await fetch("/api/settings/oauth/device-code",{method:"POST",headers:de(),body:JSON.stringify({provider:l})}),R=await b.json();if(!b.ok||R.error){je({type:"err",text:R.error??s("oauthAuth.deviceCodeFailed")});return}R.userCode&&R.verificationUri&&(Bs({userCode:R.userCode,verificationUri:R.verificationUri,provider:l}),Mt(l),je({type:"ok",text:s("oauthAuth.deviceInstructions")}),ve.current&&clearInterval(ve.current),ve.current=setInterval(async()=>{try{const W=await(await fetch(`/api/settings/oauth/status?provider=${l}`,{headers:de()})).json();!W.pending&&W.profiles.some(Y=>Y.provider===l&&Y.hasOAuth)&&(ve.current&&clearInterval(ve.current),ve.current=null,Mt(null),Bs(null),Ls(W.profiles),je({type:"ok",text:s("oauthConnected",{provider:l})}),ze())}catch{}},3e3))}catch{je({type:"err",text:s("oauth.networkErrorDuringLogin")})}finally{ut(null)}},jo=async()=>{if(ts.trim()){ut("manual"),je(null);try{const l=await fetch("/api/settings/oauth/callback",{method:"POST",headers:de(),body:JSON.stringify({callbackUrl:ts})}),b=await l.json();if(!l.ok||b.error){je({type:"err",text:b.error??s("oauth.callbackFailed")});return}je({type:"ok",text:s("oauthConnected",{provider:b.profile?.provider??s("common:unknown")})}),Qr(""),Mt(null),ve.current&&(clearInterval(ve.current),ve.current=null),cs(),ze()}catch{je({type:"err",text:s("common:networkError")})}finally{ut(null)}}},No=async l=>{try{(await fetch(`/api/settings/oauth/profiles/${encodeURIComponent(l)}`,{method:"DELETE",headers:de()})).ok&&(cs(),ze(),je({type:"ok",text:s("authProfileDeleted")}))}catch{}};i.useEffect(()=>()=>{ve.current&&clearInterval(ve.current)},[]),i.useEffect(()=>{if(p!=="browser"||He)return;const l=setInterval(async()=>{try{(await F.settings.getBrowser()).extensionConnected&&(ln(!0),clearInterval(l))}catch{}},5e3);return()=>clearInterval(l)},[p,He]);const[wo,Xs]=i.useState(!1),[ce,qe]=i.useState({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),[us,pn]=i.useState(!1),[er,hn]=i.useState(null),[tr,et]=i.useState([]),[bn,sr]=i.useState(null),[ko,yn]=i.useState(!1),[Co,rr]=i.useState(null),[be,nr]=i.useState({apiKey:"",baseUrl:"",model:"",contextWindow:0,maxOutputTokens:0,costInput:0,costOutput:0}),[vn,jn]=i.useState(!1),[Nn,wn]=i.useState(null),[ar,or]=i.useState(null),[Ve,ft]=i.useState(""),[kn,Cn]=i.useState(!1),[ir,ke]=i.useState(null),[Sn,ms]=i.useState(null),xs=yi(),[Me,gs]=i.useState({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1}),[So,An]=i.useState(!1),Pn=async(l,b)=>{if(!l||l==="__custom__")return;yn(!0),ke(null),sr(null);const R=xs.find(W=>W.id===l),z=ce.baseUrl||R?.baseUrl;try{if(b){const W=await F.modelCatalog.validateKey(l,b,z||void 0);!W.valid&&W.error&&ke({type:"err",text:W.error}),et(W.models)}else{const W=await io(l);et(W.state==="ok"?[...W.items]:[]),W.state==="error"&&sr(W.error??"读取失败")}}catch(W){et([]),sr(ai(W))}finally{yn(!1)}},Mn=async()=>{if(!(!ce.name||!ce.model)){pn(!0),hn(null),ke(null);try{const l=await fetch("/api/settings/llm/providers",{method:"POST",headers:de(),body:JSON.stringify({name:ce.name,apiKey:ce.apiKey||void 0,baseUrl:ce.baseUrl||void 0,model:ce.model,contextWindow:ce.contextWindow||void 0,maxOutputTokens:ce.maxOutputTokens||void 0,cost:ce.costInput||ce.costOutput?{input:ce.costInput,output:ce.costOutput}:void 0})}),b=await l.json();l.ok?(M(b),Xs(!1),ft(""),et([]),qe({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),ke({type:"ok",text:s("modelProviders.providerAdded",{name:ce.name})})):ke({type:"err",text:b.error??s("modelProviders.failedToAdd")})}catch{ke({type:"err",text:s("common:networkError")})}finally{pn(!1)}}},Ao=async(l,b)=>{if(!Ve.trim())return;Cn(!0),ke(null);const R=xs.find(Y=>Y.id===l),z=R?.baseUrl;let W=R?.defaultModel??l;try{const Y=await F.modelCatalog.getLive(l);Y?.recommended&&(W=Y.recommended)}catch{}try{const Y=await fetch("/api/settings/llm/providers",{method:"POST",headers:de(),body:JSON.stringify({name:l,apiKey:Ve.trim(),model:W,baseUrl:z})}),he=await Y.json();Y.ok?(M(he),ft(""),et([]),ke({type:"ok",text:s("modelProviders.quickSetupSuccess",{name:R?.label??l})})):ke({type:"err",text:he.error??s("modelProviders.failedToAdd")})}catch{ke({type:"err",text:s("common:networkError")})}finally{Cn(!1)}},Po=(l,b)=>{rr(l),nr({apiKey:"",baseUrl:b.baseUrl??"",model:b.model,contextWindow:b.contextWindow??0,maxOutputTokens:b.maxOutputTokens??0,costInput:b.cost?.input??0,costOutput:b.cost?.output??0})},Mo=async l=>{jn(!0);try{const b={};be.apiKey&&(b.apiKey=be.apiKey),be.baseUrl!==void 0&&(b.baseUrl=be.baseUrl),be.model&&(b.model=be.model),be.contextWindow&&(b.contextWindow=be.contextWindow),be.maxOutputTokens&&(b.maxOutputTokens=be.maxOutputTokens),(be.costInput||be.costOutput)&&(b.cost={input:be.costInput,output:be.costOutput});const R=await fetch(`/api/settings/llm/providers/${l}`,{method:"PUT",headers:de(),body:JSON.stringify(b)});if(R.ok){const z=await R.json();M(z),rr(null)}}catch{}finally{jn(!1)}},To=async l=>{wn(l);try{const b=await fetch(`/api/settings/llm/providers/${l}`,{method:"DELETE",headers:de()});if(b.ok){const R=await b.json();M(R),L(R.defaultProvider)}}catch{}finally{wn(null)}},Eo=async l=>{if(!(!Me.id||!Me.name)){An(!0);try{const b=await fetch(`/api/settings/llm/providers/${l}/models`,{method:"POST",headers:de(),body:JSON.stringify({id:Me.id,name:Me.name,contextWindow:Me.contextWindow,maxOutputTokens:Me.maxOutputTokens,cost:{input:Me.costInput,output:Me.costOutput},reasoning:Me.reasoning||void 0,inputTypes:Me.vision?["text","image"]:["text"]})});if(b.ok){const R=await b.json();M(R),ms(null),gs({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})}}catch{}finally{An(!1)}}},Ro=async(l,b)=>{try{const R=await fetch(`/api/settings/llm/providers/${l}/models/${encodeURIComponent(b)}`,{method:"DELETE",headers:de()});if(R.ok){const z=await R.json();M(z)}}catch{}},[Tn,En]=i.useState(null),[Rn,Lo]=i.useState({}),[ie,fs]=i.useState({}),Io=async l=>{En(l),fs(b=>{const R={...b};return delete R[l],R});try{const b=await fetch(`/api/settings/llm/providers/${l}/test`,{method:"POST",headers:de(),body:JSON.stringify({model:Rn[l]||void 0})});if(!b.ok){const z=await b.json().catch(()=>({}));fs(W=>({...W,[l]:{ok:!1,error:z.error??`HTTP ${b.status}`,errorCode:b.status,code:z.code}}));return}const R=await b.json();fs(z=>({...z,[l]:R}))}catch{fs(b=>({...b,[l]:{ok:!1,error:s("common:networkError")}}))}finally{En(null)}},Bo=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")),Oo=l=>{const b=new Set,R=C?.providers?.[l];R?.model&&b.add(R.model);const z=te[l];if(z)for(const W of z)W.id&&b.add(String(W.id));if(R?.models)for(const W of R.models)W.id&&b.add(W.id);if(l==="ollama"&&fe?.models)for(const W of fe.models)W.name&&b.add(W.name);return[...b]},Ln=C?.providers?Object.entries(C.providers).filter(([,l])=>l.configured&&l.enabled).map(([l])=>l):[],In=o?.role==="owner"||o?.role==="admin",Rt=Wr.filter(l=>!l.adminOnly||In),Bn=i.useMemo(()=>{const l=[];for(const b of Br)for(const R of b.tabs){const z=Rt.find(W=>W.id===R);z&&l.push(z)}return l},[Rt]),On=i.useRef(Bn);On.current=Bn;const Dn=i.useRef(p);Dn.current=p;const $n=!d&&u&&x==="l1";return i.useEffect(()=>{if(d||!u)return;const l=b=>{if(h?.keyboardPane==="l0"||b.metaKey||b.ctrlKey||b.altKey||ni(b.target))return;const R=b.key.length===1?b.key.toLowerCase():b.key;if(R==="h"||R==="ArrowLeft")return;const z=R==="j"||R==="ArrowDown"?1:R==="k"||R==="ArrowUp"?-1:0;if(!z)return;b.preventDefault(),b.stopPropagation(),h?.setKeyboardPane("l1");const W=On.current;if(W.length===0)return;const Y=Dn.current;let he=Y?W.findIndex(pt=>pt.id===Y):-1;he<0&&(he=z>0?-1:0);const P=Math.max(0,Math.min(W.length-1,he+z)),G=W[P];N(G.id),requestAnimationFrame(()=>{document.querySelector(`[data-settings-tab-id="${G.id}"]`)?.scrollIntoView({block:"nearest"})})};return document.addEventListener("keydown",l,!0),()=>document.removeEventListener("keydown",l,!0)},[d,u,h,N]),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 ${$n?"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:()=>{Ns.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:Br.map(l=>{const b=l.tabs.map(R=>Rt.find(z=>z.id===R)).filter(R=>!!R);return b.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:b.map(R=>e.jsxs("button",{"data-settings-tab-id":R.id,onClick:()=>{N(R.id),h?.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 ${p===R.id?$n?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(Hr,{id:R.id,className:p===R.id?"text-fg-secondary":"text-fg-tertiary"}),e.jsx("span",{className:"truncate",children:s(`settings:${R.labelKey}`)})]},R.id))})]},l.labelKey)})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[d&&p===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:()=>Ns.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:[Br.map((l,b)=>{const R=l.tabs.map(z=>Rt.find(W=>W.id===z)).filter(z=>!!z);return R.length===0?null:e.jsxs("div",{children:[b>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}`)}),R.map(z=>e.jsxs("button",{onClick:()=>N(z.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(Hr,{id:z.id,className:"text-fg-tertiary"}),e.jsx("span",{className:"flex-1 text-left",children:s(`settings:${z.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"})})]},z.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:()=>S(!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&&p!==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:j,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:${Rt.find(l=>l.id===p)?.labelKey||"title"}`)})]}),p!==null&&e.jsxs("div",{className:"p-4 md:p-8 space-y-8 max-w-4xl mx-auto w-full",children:[e.jsx(fd,{tab:p}),p==="appearance"&&e.jsxs(e.Fragment,{children:[e.jsx(Ee,{title:s("systemStatus.title"),children:I?e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 md:gap-4",children:[e.jsx(Dr,{label:s("systemStatus.status"),value:I.status==="ok"?s("systemStatus.healthy"):I.status,color:"green"}),e.jsx(Dr,{label:s("systemStatus.version"),value:I.version,color:"indigo"}),e.jsx(Dr,{label:s("systemStatus.activeAgents"),value:String(I.agents),color:"purple"})]}):e.jsx("div",{className:"text-sm text-fg-tertiary",children:s("common:loading")})}),e.jsx(Ee,{title:s("appearance.title"),children:e.jsxs("div",{className:`${Ne} p-5 divide-y divide-border-default/40`,children:[e.jsx(Ge,{label:s("appearance.theme"),description:s("appearance.themeDesc"),children:e.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-secondary/60 rounded-lg p-0.5",children:ri.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-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary"}`,children:s(`appearance.modes.${l}`)},l))})}),e.jsx("div",{className:"pt-4",children:e.jsx(Ge,{label:s("appearance.language"),description:s("appearance.languageDesc"),children:e.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-secondary/60 rounded-lg p-0.5",children:Un.map(({code:l,label:b})=>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(R=>R.code===c.language)?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary"}`,children:b},l))})})}),Fn()&&e.jsx("div",{className:"pt-4",children:e.jsx(Ge,{label:s("appearance.launchAtLogin"),description:s("appearance.launchAtLoginDesc"),children:e.jsx(Ut,{checked:A,onChange:()=>{B()},label:s("appearance.launchAtLogin"),disabled:w})})})]})})]}),In&&e.jsxs(e.Fragment,{children:[p==="providers"&&e.jsxs(e.Fragment,{children:[C&&(()=>{const l=[],b=new Set,R=[],z=[];for(const[P,G]of Object.entries(C.providers))G.configured?R.push([P,G]):P!=="markus"&&z.push([P,G]),b.add(P);for(const P of xs)!b.has(P.id)&&P.id!=="markus"&&(z.push([P.id,{name:P.id,displayName:P.label,model:P.defaultModel,configured:!1,enabled:!1}]),b.add(P.id));R.sort((P,G)=>(G[1].enabled?1:0)-(P[1].enabled?1:0)),l.push(...R,...z);const W=R.length>0,he=C.providers.markus?.configured??!1;return e.jsxs(e.Fragment,{children:[!he&&e.jsx(Ee,{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:()=>{ee(_==="markus"?null:"markus"),ft(""),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:()=>Ns.navigate($r.SETTINGS,{tab:"account"}),className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 text-on-brand text-sm rounded-lg transition-colors",children:s("modelProviders.goToAccount")})]})]})}),e.jsxs(gd,{title:s("modelProviders.title"),defaultCollapsed:W,configuredProviders:R,t:s,onBadgeClick:P=>{ee(P),ft(""),ke(null),setTimeout(()=>{document.querySelector(`[data-provider-id="${P}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},80)},children:[e.jsxs("div",{className:"space-y-3",children:[W&&e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-1",children:s("modelProviders.groupConfigured",{count:R.length})}),l.map(([P,G],pt)=>{const lr=!G.configured&&(pt===0||l[pt-1][1].configured);return e.jsxs("div",{"data-provider-id":P,children:[lr&&W&&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 ${G.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:()=>{ee(_===P?null:P),ft(""),ke(null),et([]),qe(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 ${G.configured&&G.enabled?"bg-green-400":G.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:G.displayName??P}),P===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")}),G.configured&&!G.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")}),G.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[P]?.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[P].durationMs})}),ie[P]?.ok===!1&&e.jsx("span",{className:"text-[10px] bg-red-500/15 text-red-500 px-1.5 py-0.5 rounded",title:ie[P].error,children:ie[P].errorCode?s("modelProviders.testFailedCode",{code:ie[P].errorCode}):ie[P].code==="PROVIDER_DISABLED"?s("modelProviders.testDisabled"):s("modelProviders.testFailed")})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:G.configured?e.jsxs(e.Fragment,{children:[G.models&&G.models.length>0?s("modelProviders.modelsAvailable",{count:G.models.length}):"",P!=="markus"&&G.apiKeyPreview&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("code",{className:"text-fg-secondary",children:G.apiKeyPreview})]})]}):s("modelProviders.notConfigured")})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-4",children:[G.configured&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),ho(P,!G.enabled)},disabled:ue===P,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${G.enabled?"bg-green-500":"bg-gray-600"} ${ue===P?"opacity-50":""}`,title:G.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 ${G.enabled?"translate-x-4":"translate-x-1"}`})}),e.jsx("span",{className:"text-fg-tertiary text-xs",children:_===P?"▲":"▼"})]})]}),_===P&&e.jsxs("div",{className:"px-4 md:px-5 pb-4 border-t border-border-default pt-4 space-y-4",children:[P==="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:()=>{Et()},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:()=>nt(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:bt(Q.size)})]})]})]})},Q.name))}),e.jsx("button",{onClick:()=>{yo()},disabled:qt||!De,className:`px-4 py-2 text-sm rounded-lg transition-colors disabled:opacity-40 ${G.configured?"border border-brand-500/40 text-brand-500 hover:bg-brand-500/10":"bg-brand-600 hover:bg-brand-500 text-on-brand"}`,children:qt?s("common:applying"):G.configured?s("ollama.switchModel"):s("ollama.useModel",{model:De})}),Qe&&e.jsx(Be,{type:Qe.type,text:Qe.text})]}),fe&&!fe.found&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:fe.error||s("ollama.notRunning")})]}),G.configured&&e.jsxs(e.Fragment,{children:[Co===P?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:be.apiKey,onChange:Q=>nr({...be,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:be.baseUrl,onChange:Q=>nr({...be,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:()=>{Mo(P)},disabled:vn,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-on-brand rounded-lg transition-colors whitespace-nowrap",children:s(vn?"common:saving":"common:save")}),e.jsx("button",{onClick:()=>rr(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(Wa,{value:Rn[P]??"",options:Oo(P),onChange:Q=>Lo(Le=>({...Le,[P]: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(),Io(P)},disabled:Tn===P,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:Tn===P?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")}),P!=="markus"&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),Po(P,G)},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")}),P!=="markus"&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),or({name:P,label:G.displayName??P})},disabled:Nn===P,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(Nn===P?"common:deleting":"common:delete")})]})]}),ie[P]&&e.jsxs("details",{className:`text-xs rounded-lg border ${ie[P].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[P].ok?"text-green-600":"text-red-500"}`,children:ie[P].ok?s("modelProviders.testSuccess",{ms:ie[P].durationMs,reply:ie[P].reply}):Bo(ie[P])}),e.jsxs("div",{className:"px-3 pb-2 pt-1 space-y-1 text-[11px] text-fg-muted border-t border-current/10",children:[P!=="markus"&&ie[P].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[P].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[P].model??G.model})]}),!!ie[P].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[P].requestBody,null,2)})]}),ie[P].ok&&ie[P].reply&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.response"),":"]})," ",ie[P].reply]}),ie[P].usage&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.tokens"),":"]})," ",s("modelProviders.testDetail.inputTokens")," ",ie[P].usage.inputTokens??ie[P].usage.prompt_tokens??"-"," / ",s("modelProviders.testDetail.outputTokens")," ",ie[P].usage.outputTokens??ie[P].usage.completion_tokens??"-"]}),ie[P].durationMs!=null&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.duration"),":"]})," ",ie[P].durationMs,"ms"]})]})]})]}),P==="markus"&&G.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")}),G.configured&&P!=="markus"&&Sn!==P&&e.jsx("button",{onClick:()=>{ms(P),gs({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")})]}),Sn===P&&e.jsx("div",{className:"bg-surface-elevated/40 rounded-lg p-3 mb-2 space-y-2",children:e.jsx(xd,{providerName:P,addModelForm:Me,setAddModelForm:gs,addModelSaving:So,onAdd:()=>{Eo(P)},onCancel:()=>ms(null),t:s})}),P==="markus"&&G.configured&&(!G.models||G.models.length===0)&&(T===P?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")})),G.models&&G.models.length>0&&e.jsx(ud,{models:G.models,providerName:P,activeModelId:G.model,t:s,onDeleteCustom:Q=>{Ro(P,Q)}}),G.configured&&T===P&&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")]}),G.configured&&te[P]&&te[P].length>0&&(()=>{const Q=new Set(G.models?.map(Ce=>Ce.id)??[]),Le=te[P].filter(Ce=>!Q.has(String(Ce.id??"")));return Le.length===0?null:e.jsx(md,{models:Le,providerName:P,t:s,onAdd:Ce=>{const Te=Le.find(Do=>String(Do.id??"")===Ce);Te&&(ms(P),gs({id:String(Te.id??""),name:String(Te.id??""),contextWindow:Te.maxInputTokens??128e3,maxOutputTokens:Te.maxOutputTokens??16384,costInput:Te.inputCostPer1MTokens??1,costOutput:Te.outputCostPer1MTokens??5,reasoning:Te.capabilities?.reasoning??!1,vision:Te.capabilities?.vision??!1}))}})})()]}),!G.configured&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:s("modelProviders.quickSetupHint")}),P==="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:`${_t.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:_===P?Ve:"",onChange:Q=>ft(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&&_===P&&Pn(P,Ve.trim())},onKeyDown:Q=>{Q.key==="Enter"&&Ve.trim().length>=8&&Pn(P,Ve.trim())}}),ko&&_===P&&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")]})]}),_===P&&bn&&e.jsx(_a,{variant:"inline",subject:"模型目录",error:bn,notEquals:"该 provider 没有模型",hint:"稍后重新选择 provider 重试"}),_===P&&tr.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(Fa,{provider:P,models:tr,selectedModel:ce.model,showTiers:!0,onSelect:Q=>{const Le=tr.find(Ce=>Ce.id===Q);qe(Ce=>({...Ce,name:P,model:Q,apiKey:Ve.trim(),baseUrl:xs.find(Te=>Te.id===P)?.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})]}),_===P&&Ve.trim()&&e.jsx("button",{onClick:()=>{ce.model&&ce.name===P?Mn():Ao(P)},disabled:kn||us,className:$t,children:s(kn||us?"modelProviders.quickSetupSaving":"modelProviders.quickSetupSubmit")}),ir&&_===P&&e.jsx(Be,{type:ir.type,text:ir.text})]})]})]})]},P)})]}),wo?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:ce.name==="__custom__"?"":ce.name,onChange:P=>qe(G=>({...G,name:P.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:ce.baseUrl,onChange:P=>qe({...ce,baseUrl:P.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:ce.apiKey,onChange:P=>qe({...ce,apiKey:P.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:ce.model,onChange:P=>qe({...ce,model:P.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:()=>{Mn()},disabled:us||!ce.name||ce.name==="__custom__"||!ce.model,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-on-brand rounded-lg transition-colors whitespace-nowrap",children:s(us?"modelProviders.adding":"modelProviders.addProviderSubmit")}),e.jsx("button",{onClick:()=>{Xs(!1),hn(null),et([]),qe({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")})]}),er&&e.jsx(Be,{type:er.type,text:er.text})]}):e.jsxs("button",{onClick:()=>Xs(!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(js,{title:s("autoDetect.title"),defaultOpen:!1,children:e.jsxs("div",{className:`${Ne} 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:()=>{Zs()},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")]})]}),ne&&ne.detected.length>0&&e.jsxs("div",{className:"space-y-2",children:[ne.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:b=>Oe({...Se,[l.provider]:b.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(b=>e.jsx("div",{children:e.jsx("code",{children:b})},b))})]},l.provider)),ne.timeoutMs&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("envConfig.llmTimeout",{ms:ne.timeoutMs})}),e.jsx("button",{onClick:()=>{bo()},disabled:rt||Object.values(Se).filter(Boolean).length===0,className:"px-4 py-2 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-on-brand text-sm rounded-lg transition-colors",children:rt?s("common:applying"):s("envConfig.applyToConfig",{count:Object.values(Se).filter(Boolean).length})})]}),Je&&e.jsx(Be,{type:Je.type,text:Je.text})]})]})}),e.jsx(js,{title:s("oauthAuth.title"),defaultOpen:!1,children:e.jsxs("div",{className:`${Ne} 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:[Jr.map(l=>e.jsxs("div",{className:"flex",children:[e.jsx("button",{onClick:()=>fn(l.name),disabled:!!Pt,className:"px-3 py-2 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-on-brand rounded-l-lg transition-colors",children:Pt===l.name?s("oauthAuth.connecting"):s("oauthAuth.signInWith",{name:l.displayName})}),e.jsx("button",{onClick:()=>vo(l.name),disabled:!!Pt,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-elevated disabled:opacity-40 transition-colors",children:s("oauthAuth.device")})]},l.name)),Jr.length===0&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:s("oauthAuth.noProviders")})]}),Tt&&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:Tt.verificationUri,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-brand-500 underline hover:text-brand-400",children:Tt.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:Tt.userCode})]}),e.jsx("p",{className:"text-[10px] text-fg-muted",children:s("oauthAuth.deviceWaiting")})]}),co&&!Tt&&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:ts,onChange:l=>Qr(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:jo,disabled:!ts.trim()||Pt==="manual",className:"px-3 py-2 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-on-brand rounded-lg transition-colors",children:s("oauthAuth.submit")})]})]}),Is&&e.jsx(Be,{type:Is.type,text:Is.text}),Yr.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")}),Yr.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:()=>fn(l.provider),disabled:!!Pt,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:()=>No(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(Ee,{title:s("defaultProvider.title"),children:e.jsxs("div",{className:`${Ne} 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:O,onChange:l=>{L(l.target.value),D(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:Ln.length>0?Ln.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")}),O!==C?.defaultProvider&&e.jsx("button",{onClick:()=>{po()},disabled:U,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-on-brand rounded-lg transition-colors shrink-0 whitespace-nowrap",children:s(U?"common:saving":"common:save")})]})]}),J&&e.jsx(Be,{type:J.type,text:J.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 b=await fetch("/api/settings/llm",{method:"POST",headers:de(),body:JSON.stringify({autoFallback:l})});if(b.ok){const R=await b.json();M(R)}}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(Ee,{title:s("modelRouting.title"),children:e.jsx(xi,{configuredProviders:Object.entries(C?.providers??{}).filter(([,l])=>l.configured&&l.enabled).map(([l,b])=>({name:l,displayName:b.displayName,model:b.model,models:b.models?.map(R=>({id:R.id,name:R.name}))})),onSave:async l=>{const b=await fetch("/api/settings/llm",{method:"POST",headers:de(),body:JSON.stringify(l)});if(!b.ok)throw new Error(`HTTP ${b.status}`)}},C?.defaultProvider??"no-default")}),e.jsx(Ee,{title:s("perAgentModel.section",{defaultValue:"Agent Default Models"}),children:e.jsx(hi,{configuredProviders:(()=>{try{return Object.entries(C?.providers??{}).filter(([,l])=>l.configured&&l.enabled).map(([l,b])=>({name:l,displayName:b.displayName,model:b.model,models:b.models?.map(R=>({id:R.id,name:R.name}))}))}catch{return[]}})()})})]}),p==="network"&&e.jsxs(e.Fragment,{children:[e.jsx(js,{title:s("accessScope.title"),defaultOpen:!0,children:e.jsxs("div",{className:`${Ne} p-5 space-y-4`,children:[e.jsx("p",{className:"text-[13px] text-fg-secondary leading-relaxed",children:s("accessScope.description")}),e.jsxs("div",{className:"flex rounded-lg bg-surface-secondary/80 p-1 gap-1",children:[e.jsx("button",{disabled:Pe,onClick:()=>St("127.0.0.1"),className:`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-all text-center ${dt==="127.0.0.1"&&!Pe?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary hover:bg-surface-elevated"} ${Pe?"opacity-40 cursor-not-allowed":""}`,children:s("accessScope.localOnly")}),e.jsx("button",{disabled:Pe,onClick:()=>St("0.0.0.0"),className:`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-all text-center ${dt==="0.0.0.0"&&!Pe?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary hover:bg-surface-elevated"} ${Pe?"opacity-40 cursor-not-allowed":""}`,children:s("accessScope.lan")})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-fg-secondary",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Fe==="0.0.0.0"?"bg-emerald-500":"bg-fg-muted"}`}),e.jsx("span",{children:s("accessScope.current",{host:Fe})}),e.jsx("span",{className:Fe==="0.0.0.0"?"text-emerald-600 dark:text-emerald-400":"text-fg-muted",children:s(Fe==="0.0.0.0"?"accessScope.lanHint":"accessScope.localOnlyHint")})]}),Pe&&e.jsxs("p",{className:"text-[13px] text-amber-500 flex items-center gap-1.5",children:["⚠ ",s("accessScope.envControlled")]}),e.jsxs("div",{className:"flex items-center gap-3 pt-0.5",children:[e.jsx("button",{disabled:o?.role!=="owner"||Pe||E,onClick:async()=>{if(ct){ae(!0),re(s("accessScope.applying"));try{const z=await fetch("/api/settings/network/apply",{method:"POST",headers:de(),body:JSON.stringify({})});if(z.status===202||z.ok)re("⏳ Markus 正在重启,页面将自动刷新…");else throw new Error(`HTTP ${z.status}`)}catch{re("⏳ Markus 正在重启,页面将自动刷新…")}let b=0;const R=setInterval(async()=>{b++;try{if((await fetch("/api/health",{signal:AbortSignal.timeout(1500)})).ok){clearInterval(R),ae(!1),At(!1),re(s("accessScope.applied")),Xe();return}}catch{}b>20&&(clearInterval(R),ae(!1),re(s("accessScope.applyFailed")))},400);return}const l=Fe;try{const b=await fetch("/api/settings/network",{method:"POST",headers:de(),body:JSON.stringify({host:dt})});if(!b.ok)throw new Error(`HTTP ${b.status}`);const Y=!!(await b.json()).restartRequired||dt!==l;At(Y),re(s(Y?"accessScope.restartRequired":"accessScope.saved"))}catch{re(s("accessScope.saveFailed"))}},className:`inline-flex items-center justify-center gap-1.5 px-5 py-2 text-sm font-semibold rounded-lg transition-all disabled:opacity-40 disabled:cursor-not-allowed min-w-[100px] ${ct?"bg-amber-500 text-on-brand hover:bg-amber-400 active:bg-amber-600":"bg-brand-600 text-on-brand hover:bg-brand-500 active:bg-brand-700"}`,children:E?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"w-3.5 h-3.5 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"})]}),s("accessScope.applying")]}):s(ct?"accessScope.applyNow":"accessScope.save")}),Ue&&e.jsx("span",{className:`text-[13px] ${Ue.includes("重启")||Ue.includes("切换")||Ue.includes("已生效")?"text-amber-500":"text-fg-muted"}`,children:Ue})]}),e.jsx("p",{className:"text-[12px] text-fg-muted leading-relaxed",children:s("accessScope.remoteNote")})]})}),e.jsx(js,{title:s("networkProxy.title"),defaultOpen:!0,children:e.jsxs("div",{className:`${Ne} p-5 space-y-4`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsx("p",{className:"text-[13px] text-fg-secondary leading-relaxed",children:s("networkProxy.description")}),e.jsx("button",{onClick:async()=>{const l=!ye;_e(l);try{await fetch("/api/settings/network",{method:"POST",headers:de(),body:JSON.stringify({proxyEnabled:l})}),Xe()}catch{_e(!l)}},className:`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors mt-0.5 ${ye?"bg-green-500":"bg-fg-muted/30"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 rounded-full bg-white shadow-sm transition-transform ${ye?"translate-x-[22px]":"translate-x-1"}`})})]}),Z&&e.jsxs("div",{className:`flex items-center gap-2.5 rounded-lg px-3.5 py-2.5 transition-opacity ${ye?"":"opacity-40"} ${Z.proxy?"bg-emerald-500/5 border border-emerald-500/12":"bg-surface-secondary/60 border border-border-default/50"}`,children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Z.proxy?"bg-emerald-500":"bg-fg-muted"}`}),e.jsx("span",{className:"text-[13px]",children:ye?Z.proxy?e.jsxs(e.Fragment,{children:[s("networkProxy.active")," ",e.jsx("code",{className:"font-mono text-brand-600 dark:text-brand-400 font-medium",children:Z.proxy})]}):s("networkProxy.noProxy"):s("networkProxy.disabled")}),ye&&Z.source!=="none"&&Z.source!=="disabled"&&e.jsx("span",{className:`text-[11px] px-1.5 py-0.5 rounded font-medium ${Z.source==="config"?"bg-brand-500/10 text-brand-600 dark:text-brand-400":Z.source==="env"?"bg-amber-500/10 text-amber-600 dark:text-amber-400":Z.source==="system"?"bg-blue-500/10 text-blue-500":"bg-fg-muted/10 text-fg-muted"}`,children:Z.source==="config"?s("networkProxy.sourceConfig"):Z.source==="env"?s("networkProxy.sourceEnv"):Z.source==="system"?s("networkProxy.sourceSystem"):""}),e.jsxs("button",{onClick:()=>Xe(),className:"ml-auto text-[11px] text-fg-muted hover:text-fg-secondary transition-colors flex items-center gap-1",title:s("networkProxy.refresh"),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:"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("networkProxy.refresh")]})]}),e.jsxs("div",{className:`flex gap-2.5 items-center transition-opacity ${ye?"":"opacity-40 pointer-events-none"}`,children:[e.jsx("input",{type:"text",value:wt,onChange:l=>Gt(l.target.value),placeholder:s("networkProxy.placeholder"),className:"flex-1 min-w-0 px-3.5 py-2.5 text-sm bg-surface-secondary/70 border border-border-default rounded-lg text-fg-primary placeholder:text-fg-muted/40 focus:border-brand-500 focus:bg-transparent outline-none transition-colors"}),e.jsx("button",{onClick:async()=>{Gr(!0),es(null);try{const l=await fetch("/api/settings/network",{method:"POST",headers:de(),body:JSON.stringify({proxy:wt.trim()})});if(l.ok)es({type:"ok",text:s("networkProxy.saved")}),Xe();else{const b=await l.json();es({type:"err",text:b.error??s("networkProxy.saveFailed")})}}catch{es({type:"err",text:s("networkProxy.networkError")})}finally{Gr(!1)}},disabled:Xt,className:`${$t} shrink-0`,children:s(Xt?"networkProxy.saving":"networkProxy.save")})]}),Rs&&e.jsx(Be,{type:Rs.type,text:Rs.text}),e.jsx(Nd,{noProxyList:Jt,setNoProxyList:at,noProxyEntry:Yt,setNoProxyEntry:ot,egressTesting:Ps,egressTest:Ms,egressError:Zt,onTest:()=>{it(!0),lt(null),fetch("/api/settings/network/test",{method:"POST",headers:de(),body:JSON.stringify({})}).then(async l=>{const b=await l.json();if(!l.ok)throw new Error(b.error??`HTTP ${l.status}`);lt({ok:!!b.ok,text:b.ok?s("networkProxy.testResult",{ip:b.exitIp??"—",ms:b.latencyMs??0,route:b.proxied?s("networkProxy.viaProxy"):s("networkProxy.direct")}):s("networkProxy.testFailed",{error:b.error??"unknown"})})}).catch(l=>lt({ok:!1,text:s("networkProxy.testFailed",{error:String(l)})})).finally(()=>it(!1))},authHeaders:de,loadNetworkSettings:Xe,t:s}),e.jsxs("div",{className:"rounded-lg bg-surface-secondary/40 border border-border-default/30 px-4 py-2.5 space-y-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-fg-secondary/80",children:s("networkProxy.coverageTitle")}),e.jsx("p",{className:"text-[11px] text-fg-muted/70 leading-relaxed",children:s("networkProxy.coverageCovered")}),e.jsx("p",{className:"text-[11px] text-amber-500/60 leading-relaxed",children:s("networkProxy.coverageNotCovered")})]})]})}),e.jsx(Vl,{})]}),p==="execution"&&e.jsxs(e.Fragment,{children:[e.jsx(Ee,{title:s("agentExecution.title"),children:e.jsxs("div",{className:`${Ne} p-5 space-y-4`,children:[e.jsx(Ge,{label:s("agentExecution.maxToolIterations"),description:s("agentExecution.maxToolIterationsDesc"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",min:0,value:en,onChange:l=>{Os(Number(l.target.value)),Ke(null)},className:`${vs} w-24 text-right tabular-nums`}),e.jsx("button",{disabled:ss,onClick:async()=>{rs(!0),Ke(null);try{const l=await F.settings.updateAgent({maxToolIterations:en});Os(l.maxToolIterations),Ke({type:"ok",text:s("agentExecution.saved")})}catch{Ke({type:"err",text:s("agentExecution.failedToSave")})}rs(!1)},className:$t,children:s(ss?"common:saving":"common:save")})]})}),e.jsx("div",{className:"border-t border-border-default/40"}),e.jsx(Ge,{label:s("agentExecution.maxPendingTasksPerAgent"),description:s("agentExecution.maxPendingTasksPerAgentDesc"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",min:1,value:tn,onChange:l=>{Ds(Number(l.target.value)),Ke(null)},className:`${vs} w-24 text-right tabular-nums`}),e.jsx("button",{disabled:ss,onClick:async()=>{rs(!0),Ke(null);try{const l=await F.settings.updateAgent({maxPendingTasksPerAgent:tn});Ds(l.maxPendingTasksPerAgent),Ke({type:"ok",text:s("agentExecution.saved")})}catch{Ke({type:"err",text:s("agentExecution.failedToSave")})}rs(!1)},className:$t,children:s(ss?"common:saving":"common:save")})]})}),$s&&e.jsx(Be,{type:$s.type,text:$s.text})]})}),e.jsx(Ee,{title:s("concurrent.title"),description:s("concurrent.description"),children:e.jsxs("div",{className:`${Ne} p-5 space-y-4`,children:[e.jsx(Ge,{label:s("concurrent.enabled"),description:s("concurrent.enabledDesc"),children:e.jsx(Ut,{checked:ns,onChange:l=>{Vs(l),mt(null)},label:s("concurrent.enabled")})}),e.jsx(Ge,{label:s("concurrent.maxWorkers"),description:s("concurrent.maxWorkersDesc"),children:e.jsx("input",{type:"number",min:1,max:10,disabled:!ns,value:sn,onChange:l=>{_s(Number(l.target.value)),mt(null)},className:`${vs} w-24 text-right tabular-nums disabled:opacity-40`})}),e.jsx(Ge,{label:s("concurrent.conflictPolicy"),description:s("concurrent.conflictPolicyDesc"),children:e.jsxs("select",{value:rn,disabled:!ns,onChange:l=>{Fs(l.target.value),mt(null)},className:`${vs} 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",children:e.jsx("button",{disabled:nn,onClick:async()=>{an(!0),mt(null);try{const l=await F.settings.updateAgent({concurrent:{enabled:ns,maxWorkers:sn,conflictPolicy:rn}});Vs(l.concurrent.enabled),_s(l.concurrent.maxWorkers??3),Fs(l.concurrent.conflictPolicy??"auto"),mt({type:"ok",text:s("concurrent.saved")})}catch{mt({type:"err",text:s("concurrent.failedToSave")})}an(!1)},className:$t,children:s(nn?"common:saving":"common:save")})}),Us&&e.jsx(Be,{type:Us.type,text:Us.text})]})})]}),p==="browser"&&e.jsxs(e.Fragment,{children:[e.jsxs(Ee,{title:s("browserAutomation.title"),children:[e.jsxs("div",{className:`${Ne} 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()=>{me(!0),X(null);try{const l=await F.settings.updateBrowser({mode:"embedded"});Ks(l.mode??"embedded"),X({type:"ok",text:s("browserAutomation.backendSwitchToEmbedded")})}catch{X({type:"err",text:s("agentExecution.failedToSave")})}me(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${xt==="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 ${xt==="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()=>{me(!0),X(null);try{const l=await F.settings.updateBrowser({mode:"system-chrome"});Ks(l.mode??"system-chrome"),X({type:"ok",text:s("browserAutomation.backendSwitchToSystemChrome")})}catch{X({type:"err",text:s("agentExecution.failedToSave")})}me(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${xt==="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 ${xt==="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:`${Ne} 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()=>{me(!0),X(null);try{const l=await F.settings.updateBrowser({elementSelection:"direct"});Hs(l.elementSelection??"direct"),X({type:"ok",text:s("browserAutomation.elementSelectionSwitchToDirect")})}catch{X({type:"err",text:s("agentExecution.failedToSave")})}me(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${as==="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 ${as==="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()=>{me(!0),X(null);try{const l=await F.settings.updateBrowser({elementSelection:"jev"});Hs(l.elementSelection??"jev"),X({type:"ok",text:s("browserAutomation.elementSelectionSwitchToJev")})}catch{X({type:"err",text:s("agentExecution.failedToSave")})}me(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${as==="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 ${as==="jev"?"bg-brand-400":"bg-gray-500"}`})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-1",children:s("browserAutomation.elementSelectionJevDesc")})]})]})]}),xt==="embedded"?e.jsxs("div",{className:`${Ne} 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()=>{me(!0),X(null);try{const l=await F.settings.testConcurrentBrowserQuick();X({type:l.connected?"ok":"err",text:l.connected?s("browserAutomation.backendVerifyOk"):s("browserAutomation.backendVerifyFail",{error:l.summary||"backend not reachable"})})}catch(l){X({type:"err",text:s("browserAutomation.backendVerifyFail",{error:l?.message||l||"unknown"})})}me(!1)},disabled:pe,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(pe?"browserAutomation.backendVerifying":"browserAutomation.backendVerify")})]}):e.jsxs("div",{className:`rounded-xl p-4 md:p-5 mb-4 ${He?"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 ${He?"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 ${He?"bg-green-400":"bg-gray-400"}`}),s(He?"browserAutomation.extensionConnected":"browserAutomation.extensionDisconnected")]})]}),e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("browserAutomation.extensionStatusDesc")}),He?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-on-brand 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:pe,onClick:async()=>{me(!0),X(null);try{await F.settings.downloadExtensionZip()}catch{X({type:"err",text:s("browserAutomation.extensionDownloadError")})}me(!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-on-brand 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(pe?"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-on-brand 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()=>{me(!0),X(null);try{await F.settings.openExtensionsPage()}catch{X({type:"err",text:s("browserAutomation.extensionOpenError")})}me(!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-on-brand 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()=>{me(!0),X(null);try{const l=await F.settings.testConcurrentBrowserQuick();X({type:l.connected?"ok":"err",text:l.connected?s("browserAutomation.backendVerifyOk"):s("browserAutomation.backendVerifyFail",{error:l.summary||"backend not reachable"})})}catch(l){X({type:"err",text:s("browserAutomation.backendVerifyFail",{error:l?.message||l||"unknown"})})}me(!1)},disabled:pe,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(pe?"browserAutomation.backendVerifying":"browserAutomation.backendVerify")})]})]}),e.jsxs("div",{className:`${Ne} 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=!zs;os(l),me(!0),X(null);try{const b=await F.settings.updateBrowser({bringToFront:l});os(b.bringToFront),X({type:"ok",text:s(l?"browserAutomation.tabsForeground":"browserAutomation.tabsBackground")})}catch{X({type:"err",text:s("agentExecution.failedToSave")}),os(!l)}me(!1)},disabled:pe,className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${zs?"bg-green-500":"bg-gray-600"} ${pe?"opacity-50":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${zs?"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=!Ws;is(l),me(!0),X(null);try{const b=await F.settings.updateBrowser({autoCloseTabs:l});is(b.autoCloseTabs),X({type:"ok",text:s("agentExecution.saved")})}catch{X({type:"err",text:s("agentExecution.failedToSave")}),is(!l)}me(!1)},disabled:pe,className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${Ws?"bg-green-500":"bg-gray-600"} ${pe?"opacity-50":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Ws?"translate-x-4":"translate-x-1"}`})})]})]}),xt==="system-chrome"&&!He&&e.jsxs("div",{className:`${Ne} 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:pe,onClick:async()=>{me(!0),X(null);try{const l=await F.settings.testAutoClick(),b={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"})}};X(b[l.clickResult]??{type:"err",text:l.clickResult})}catch{X({type:"err",text:s("browserAutomation.autoClickTestError",{error:"request failed"})})}me(!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(pe?"browserAutomation.autoClickTesting":"browserAutomation.autoClickTest")}),e.jsx("button",{onClick:async()=>{const l=!Gs;ls(l),me(!0),X(null);try{const b=await F.settings.updateBrowser({autoClickAllowDialog:l});ls(b.autoClickAllowDialog),X({type:"ok",text:s("agentExecution.saved")})}catch{X({type:"err",text:s("agentExecution.failedToSave")}),ls(!l)}me(!1)},disabled:pe,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Gs?"bg-green-500":"bg-gray-600"} ${pe?"opacity-50":""}`,children:e.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${Gs?"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:on,onChange:l=>{qs(Number(l.target.value)),X(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:pe,onClick:async()=>{me(!0),X(null);try{const l=await F.settings.updateBrowser({remoteDebuggingPort:on});qs(l.remoteDebuggingPort),X({type:"ok",text:l.remoteDebuggingPort>0?s("browserAutomation.usingPort",{port:l.remoteDebuggingPort}):s("browserAutomation.usingAutoConnect")})}catch{X({type:"err",text:s("agentExecution.failedToSave")})}me(!1)},className:"px-3 py-1.5 text-xs bg-brand-500 text-on-brand rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-40",children:s(pe?"common:saving":"common:save")})]})]})})]}),Js&&e.jsx("div",{className:"mt-4",children:e.jsx(Be,{type:Js.type,text:Js.text})})]}),!1]}),p==="search"&&e.jsx(rd,{}),p==="storage"&&e.jsx(e.Fragment,{children:e.jsx(Ee,{title:s("dataStorage.title"),children:e.jsxs("div",{className:`${Ne} p-5 space-y-5`,children:[Ys&&!$e&&e.jsx("div",{className:"text-sm text-fg-tertiary",children:s("dataStorage.scanning")}),$e&&(()=>{const l=[...$e.breakdown].filter(Y=>Y.size>0).sort((Y,he)=>he.size-Y.size),b=Math.max($e.totalSize,1),z=l.filter(Y=>Or[Y.name]==="safe").reduce((Y,he)=>Y+he.size,0),W=Y=>Y==="safe"?"bg-fg-secondary/55":Y==="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:bt($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:()=>gt(),disabled:Ys,className:Da,children:s(Ys?"dataStorage.scanning":"common:refresh")}),e.jsx("button",{onClick:()=>{F.system.openPath($e.dataDir)},className:Da,children:s("dataStorage.openInFinder")})]})]}),e.jsx("div",{className:"h-2 rounded-full bg-surface-primary overflow-hidden flex","aria-hidden":!0,children:l.map(Y=>{const he=Or[Y.name]??"caution",P=Math.max(Y.size/b*100,Y.size>0?.8:0);return e.jsx("div",{className:`h-full ${W(he)}`,style:{width:`${P}%`},title:`${Y.name}: ${bt(Y.size,s)}`},Y.name)})}),z>0&&e.jsx("p",{className:"text-xs text-fg-tertiary leading-relaxed",children:s("dataStorage.clearableHint",{size:bt(z,s),percent:Math.round(z/b*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(Y=>{const he=ad[Y.name],P=Or[Y.name]??"caution",G=he?s(`dataStorage.items.${he}.label`):Y.name,pt=he?s(`dataStorage.items.${he}.blurb`):Y.description,lr=Math.round(Y.size/b*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:G}),P==="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:pt})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary tabular-nums",children:bt(Y.size,s)}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary tabular-nums mt-0.5",children:[lr,"%"]})]}),e.jsx("button",{type:"button",onClick:()=>{F.system.openPath(Y.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:Y.path,children:s("dataStorage.openFolder")})]},Y.name)})})]}),ds&&(ds.orphanAgents.length>0||ds.orphanTeams.length>0)&&e.jsx(pd,{orphanInfo:ds,dataDir:$e.dataDir,onPurged:gt,formatBytes:Y=>bt(Y,s)})]})})()]})})}),(p==="account"||p==="users"||p==="organization"||p==="license")&&e.jsx(bd,{authUser:o}),p==="integrations"&&e.jsx(Dl,{})]}),e.jsx("div",{className:"h-8"})]}),ar&&e.jsx(Cs,{title:s("common:delete"),message:s("modelProviders.deleteConfirm",{name:ar.label}),confirmLabel:s("common:delete"),onConfirm:()=>{const l=ar.name;or(null),To(l)},onCancel:()=>or(null)}),y&&a&&e.jsx(Cs,{title:s("common:signOutConfirmTitle"),message:s("common:signOutConfirmMessage"),confirmLabel:s("common:signOut"),variant:"primary",onConfirm:()=>{S(!1),a()},onCancel:()=>S(!1)})]})]})}const Ia=["owner","admin","member","guest"],ld={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 dd({authUser:t}){const{t:r}=xe(["settings","common"]),[o,a]=i.useState([]),[n,s]=i.useState(!0),[c,d]=i.useState(null),[u,h]=i.useState(""),[x,k]=i.useState(""),[v,y]=i.useState(""),[S,N]=i.useState(null),[j,p]=i.useState(""),[A,m]=i.useState(null),[w,$]=i.useState(null),[B,I]=i.useState(null),[V,C]=i.useState(!1),[M,O]=i.useState(""),[L,U]=i.useState(""),[H,J]=i.useState("member"),[D,_]=i.useState(""),ee=i.useCallback(()=>{F.users.list(t?.orgId).then(f=>a(f.users)).catch(()=>{}).finally(()=>s(!1))},[t?.orgId]);i.useEffect(()=>{ee()},[ee]);const ue=f=>{d(f.id),h(f.name),k(f.role),y(f.email??""),I(null)},le=async()=>{if(c)try{await F.users.update(c,{name:u,role:x,email:v||void 0}),d(null),I({type:"ok",text:r("settings:userManagement.updateSuccess")}),ee()}catch(f){I({type:"err",text:`${r("settings:userManagement.error")}: ${String(f)}`})}},te=async()=>{if(!(!S||!j))try{await F.users.resetPassword(S,j),N(null),p(""),I({type:"ok",text:r("settings:userManagement.resetSuccess")})}catch(f){I({type:"err",text:`${r("settings:userManagement.error")}: ${String(f)}`})}},g=async f=>{if(f===t?.id){I({type:"err",text:r("settings:userManagement.cannotDeleteSelf")}),m(null);return}if(o.find(q=>q.id===f)?.role==="owner"){I({type:"err",text:r("settings:userManagement.cannotDeleteOwner")}),m(null);return}try{await F.users.remove(f),m(null),I({type:"ok",text:r("settings:userManagement.deleteSuccess")}),ee()}catch(q){I({type:"err",text:`${r("settings:userManagement.error")}: ${String(q)}`})}},T=async()=>{if(M.trim())try{const f=await F.users.create(M.trim(),H,void 0,L.trim()||void 0,D||void 0);C(!1),O(""),U(""),J("member"),_(""),I({type:"ok",text:r("settings:userManagement.addSuccess",{defaultValue:"User created"})}),f.inviteToken&&$(`${window.location.origin}/#invite?token=${f.inviteToken}`),ee()}catch(f){I({type:"err",text:`${r("settings:userManagement.error")}: ${f instanceof Error?f.message:String(f)}`})}};return e.jsxs(Ee,{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=>O(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=>J(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:Ia.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:D,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),O(""),U(""),J("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-on-brand 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-on-brand 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:[B&&e.jsx("div",{className:`px-4 py-2 text-xs border-b ${B.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:B.text}),w&&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:w})]}),e.jsx("button",{onClick:()=>{navigator.clipboard.writeText(w),I({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-on-brand 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&&o.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-4 py-6",children:e.jsx(oi,{rows:3,variant:"skeleton"})})}),!n&&o.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")})}),o.map(f=>{const K=c===f.id,q=S===f.id,ne=A===f.id,oe=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:se=>h(se.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}),oe&&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:v,onChange:se=>y(se.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:se=>k(se.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:Ia.map(se=>e.jsx("option",{value:se,children:r(`settings:userManagement.roles.${se}`)},se))}):e.jsx("span",{className:`inline-block text-[10px] px-2 py-0.5 rounded-full border font-medium ${ld[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:le,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium",children:r("settings:userManagement.save")})]}):q?e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("input",{type:"password",value:j,onChange:se=>p(se.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:()=>{N(null),p("")},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:te,disabled:j.length<6,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium disabled:opacity-40",children:r("settings:userManagement.confirmReset")})]}):ne?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:()=>ue(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:()=>{N(f.id),p(""),I(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:se}=await F.users.reinvite(f.id),Je=`${window.location.origin}/#invite?token=${se}`;$(Je),I({type:"ok",text:r("settings:userManagement.inviteLinkGenerated")})}catch(se){I({type:"err",text:String(se)})}},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&&!oe&&e.jsx("button",{onClick:()=>{m(f.id),I(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 cd={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"}},Ba={chat:0,image_generation:1,video_generation:2,audio_speech:3,audio_transcription:4,ocr:5},Oa=5;function ud({models:t,providerName:r,activeModelId:o,t:a,onDeleteCustom:n}){const s=t.length>Oa,[c,d]=i.useState(!s),[u,h]=i.useState(""),x=i.useMemo(()=>{const v=u.trim().toLowerCase();return v?t.filter(y=>y.id.toLowerCase().includes(v)||y.name.toLowerCase().includes(v)):t},[t,u]),k=c?x:x.slice(0,Oa);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(v=>!v),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:v=>h(v.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(v=>{const y=v.source==="custom",S=v.capabilities??[],N=o===v.id;return e.jsxs("div",{className:`flex items-center justify-between px-3 py-1.5 rounded-lg text-xs ${N?"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:v.name}),N&&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(jd,{modelId:v.id,tier:v.tier}),v.reasoning&&e.jsx("span",{className:"text-[9px] bg-amber-500/15 text-amber-600 px-1 py-0.5 rounded",children:a("modelProviders.reasoning")}),(v.inputTypes?.includes("image")||S.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")}),S.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")}),(S.includes("tts")||S.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")}),(S.includes("stt")||S.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")}),S.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")}),y&&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:[(v.contextWindow??0)>0&&e.jsx("span",{children:a("modelProviders.ctxTokens",{size:((v.contextWindow??0)/1e3).toFixed(0)})}),y&&r!=="markus"&&e.jsx("button",{onClick:j=>{j.stopPropagation(),n(v.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"})})})]})]},v.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 md({models:t,providerName:r,t:o,onAdd:a}){const[n,s]=i.useState(!1),c=i.useMemo(()=>[...t].sort((d,u)=>{const h=Ba[d.mode??"chat"]??99,x=Ba[u.mode??"chat"]??99;return h!==x?h-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"})}),o("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??""),h=d.mode??"chat",x=cd[h];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:o("modelProviders.addModel")})]},u)})})]})}function xd({providerName:t,addModelForm:r,setAddModelForm:o,addModelSaving:a,onAdd:n,onCancel:s,t:c}){const[d,u]=i.useState([]),[h,x]=i.useState(!1),[k,v]=i.useState(null),[y,S]=i.useState(!1),N=async()=>{x(!0),v(null);const j=await io(t);u(j.state==="ok"?[...j.items]:[]),j.state==="error"&&v(j.error??"读取失败"),S(j.state==="ok"),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:()=>{N()},disabled:h,className:"text-[10px] text-brand-500 hover:text-brand-400 disabled:opacity-40 transition-colors",children:h?"...":c("modelProviders.browseFromCatalog")})]}),k&&e.jsx(_a,{variant:"inline",subject:"模型目录",error:k,notEquals:"该 provider 没有模型",onRetry:()=>{N()}}),y&&d.length>0&&e.jsx("div",{className:"border border-border-default rounded-lg p-2 mb-2",children:e.jsx(Fa,{provider:t,models:d,selectedModel:r.id,showTiers:!0,onSelect:j=>{const p=d.find(A=>A.id===j);p&&o(A=>({...A,id:p.id,name:p.id,contextWindow:p.maxInputTokens,maxOutputTokens:p.maxOutputTokens,costInput:p.inputCostPer1MTokens,costOutput:p.outputCostPer1MTokens,reasoning:p.capabilities.reasoning,vision:p.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:j=>o({...r,id:j.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:j=>o({...r,name:j.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:j=>o({...r,contextWindow:Number(j.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:j=>o({...r,maxOutputTokens:Number(j.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:j=>o({...r,costInput:Number(j.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:j=>o({...r,costOutput:Number(j.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:j=>o({...r,reasoning:j.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:j=>o({...r,vision:j.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-on-brand 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 Be({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 gd({title:t,defaultCollapsed:r,configuredProviders:o,t:a,children:n,onBadgeClick:s}){const[c,d]=i.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-[13px] font-semibold text-fg-primary",children:t}),c&&o.length>0&&e.jsxs("span",{className:"text-xs text-fg-tertiary",children:["(",o.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&&o.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[o.map(([u,h])=>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 ${h.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 ${h.enabled?"bg-green-400":"bg-gray-500"}`}),h.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})]})}const Ne="bg-surface-elevated rounded-xl border border-border-default/40",vs="px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder:text-fg-tertiary/50 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15 outline-none transition-colors",$t="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-sm font-medium bg-brand-600 hover:bg-brand-500 text-on-brand disabled:opacity-40 rounded-lg transition-colors",Da="inline-flex items-center justify-center gap-1.5 px-3 py-2 text-sm font-medium border border-border-default text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary disabled:opacity-40 rounded-lg transition-colors";function fd({tab:t}){const{t:r}=xe(["settings","common"]),o=Wr.find(s=>s.id===t),a=r(o?`settings:${o.labelKey}`:"settings:title"),n=r(`settings:tabDesc.${t}`,{defaultValue:""});return e.jsxs("header",{className:"flex items-center gap-3 pb-1",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-10 h-10 rounded-xl bg-brand-500/10 text-brand-500 shrink-0",children:e.jsx(Hr,{id:t,className:"w-[18px] h-[18px]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-lg font-semibold text-fg-primary tracking-tight leading-tight",children:a}),n&&e.jsx("p",{className:"text-[13px] text-fg-tertiary mt-0.5 leading-snug",children:n})]})]})}function Ge({label:t,description:r,children:o}){return e.jsxs("div",{className:"flex flex-col gap-2.5 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:t}),r&&e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 leading-relaxed",children:r})]}),e.jsx("div",{className:"shrink-0",children:o})]})}function Ee({title:t,description:r,action:o,children:a}){return e.jsxs("section",{className:"space-y-3.5",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-fg-primary",children:t}),r&&e.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 leading-relaxed",children:r})]}),o]}),e.jsx("div",{className:"space-y-3",children:a})]})}function js({title:t,description:r,children:o,defaultOpen:a=!0}){const[n,s]=i.useState(a);return e.jsxs("section",{className:"space-y-3.5",children:[e.jsxs("button",{type:"button",onClick:()=>s(!n),className:"flex items-start justify-between w-full group text-left",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-fg-primary",children:t}),r&&e.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 leading-relaxed",children:r})]}),e.jsx("span",{className:`text-fg-tertiary mt-0.5 transition-transform group-hover:text-fg-secondary ${n?"":"-rotate-90"}`,children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),n&&e.jsx("div",{className:"space-y-3",children:o})]})}function Dr({label:t,value:r,color:o}){const a=o==="green"?"bg-green-500/10 text-green-600":"bg-brand-500/10 text-brand-500";return e.jsxs("div",{className:`rounded-xl border border-border-default/40 px-5 py-4 ${a}`,children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:r}),e.jsx("div",{className:"text-xs mt-1 opacity-70",children:t})]})}function bt(t,r){if(t===0)return r?r("dataStorage.bytesZero"):"0 B";const o=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)),o.length-1),n=t/Math.pow(1024,a);return`${n<10?n.toFixed(1):Math.round(n)} ${o[a]}`}function pd({orphanInfo:t,dataDir:r,onPurged:o,formatBytes:a}){const{t:n}=xe(["settings","common"]),s=[...t.orphanAgents.map(p=>({...p,kind:"agent"})),...t.orphanTeams.map(p=>({...p,kind:"team"}))],[c,d]=i.useState(new Set),[u,h]=i.useState(!1),[x,k]=i.useState(null),v=p=>d(A=>{const m=new Set(A);return m.has(p)?m.delete(p):m.add(p),m}),y=c.size===s.length&&s.length>0,S=()=>d(y?new Set:new Set(s.map(p=>p.id))),N=s.filter(p=>c.has(p.id)).reduce((p,A)=>p+A.size,0),j=async p=>{h(!0),k(null);try{const A=await F.system.purgeOrphans(p),m=A.purgedAgents.length+A.purgedTeams.length,w=n("dataStorage.cleaned",{count:m,size:a(A.freedBytes)});k(A.failures.length?n("dataStorage.cleanedWithFailureNote",{base:w,count:A.failures.length}):w),d(new Set),o()}catch{k(n("dataStorage.cleanupFailed"))}finally{h(!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:y,onChange:S,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(N)})})]}),e.jsx("div",{className:"space-y-0.5 mb-3 max-h-52 overflow-y-auto",children:s.map(p=>e.jsxs("div",{className:`flex items-center gap-2 text-xs py-1.5 px-2 rounded transition-colors ${c.has(p.id)?"bg-amber-500/10":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:[e.jsx("input",{type:"checkbox",checked:c.has(p.id),onChange:()=>v(p.id),className:"rounded shrink-0"}),p.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:p.id}),e.jsx("span",{className:"text-fg-secondary tabular-nums shrink-0",children:a(p.size)}),e.jsx("button",{onClick:()=>{F.system.openPath(p.path)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary shrink-0 underline",children:n("common:open")})]},p.id))}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[c.size>0&&e.jsx("button",{disabled:u,onClick:()=>{j([...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(N)})}),e.jsx("button",{disabled:u,onClick:()=>{j()},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 hd={multi_user:"👥",sso:"🔐",audit_enhanced:"📋",multi_instance:"🌐",offline_license:"📡"};function bd({authUser:t}){const{t:r}=xe(["settings","common"]);return e.jsxs("div",{className:"space-y-8",children:[e.jsx(yd,{}),e.jsx(dd,{authUser:t})]})}function yd(){const{t}=xe(["settings","common"]),[r,o]=i.useState(null),[a,n]=i.useState(!0),[s,c]=i.useState([]),[d,u]=i.useState([]),[h,x]=i.useState(null),[k,v]=i.useState(!0),[y,S]=i.useState(!1),[N,j]=i.useState(null),[p,A]=i.useState(!1),m=i.useCallback((J=!1)=>{v(!0),F.hubOrgs.mine().catch(D=>(J&&x({type:"err",text:D instanceof Error?D.message:t("org.loadFailed")}),{orgs:[]})).then(D=>{c(D.orgs),F.hubOrgs.invitations().then(_=>u(_.invitations)).catch(()=>{})}).finally(()=>v(!1))},[t]);i.useEffect(()=>{if(!$a()&&!dr()){v(!1),n(!1);return}m(),_t.user.plan().then(J=>o(J)).catch(()=>{}).finally(()=>n(!1))},[m]);const w=i.useCallback((J=!1)=>{A(!0),(J?F.license.refresh():F.license.get()).then(_=>j(_)).catch(()=>{}).finally(()=>setTimeout(()=>A(!1),400))},[]);i.useEffect(()=>{w(!0)},[w]);const $=N?.plan==="enterprise",B=async J=>{try{await F.hubOrgs.acceptInvitation(J),u(D=>D.filter(_=>_.orgId!==J)),m()}catch(D){x({type:"err",text:D instanceof Error?D.message:"Failed"})}},I=N?.validUntil?Math.max(0,Math.ceil((new Date(N.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(J=>J.id===r?.orgId)??s[0],O=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:O;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:[h&&e.jsxs("div",{className:`flex items-center gap-2 text-sm px-4 py-3 rounded-lg ${h.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:h.type==="ok"?"✓":"✕"}),e.jsx("span",{children:h.text})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-fg-primary 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:`${_t.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-on-brand 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-[13px] font-semibold text-fg-primary mb-3",children:t("account.orgSection")}),d.length>0&&e.jsx("div",{className:"space-y-2 mb-3",children:d.map(J=>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:J.orgName}),e.jsxs("span",{className:"text-fg-tertiary ml-1",children:["— ",t("org.invitedBy")," ",J.invitedBy]})]}),e.jsx("button",{onClick:()=>{B(J.orgId)},className:"px-3 py-1.5 bg-brand-600 hover:bg-brand-500 text-on-brand text-xs font-medium rounded-lg transition-colors",children:t("org.accept")})]},J.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:`${_t.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")}),!!dr()&&e.jsx("div",{className:"text-xs text-amber-500/90",children:t("org.staleSessionHint")}),e.jsxs("button",{disabled:y,onClick:()=>{x(null),S(!0),Va({force:!0}).then(()=>m(!0)).catch(J=>{const D=J instanceof Error?J.message:String(J),_=D.includes("Popup blocked")?t("org.popupBlocked"):D.includes("cancelled")?t("org.loginCancelled"):D;x({type:"err",text:_})}).finally(()=>S(!1))},className:"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-60 text-on-brand text-sm font-medium rounded-lg transition-colors inline-flex items-center gap-2",children:[y&&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"})}),y?t("org.connecting"):dr()?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-[13px] font-semibold text-fg-primary",children:t("license.title")}),e.jsxs("button",{onClick:()=>w(!0),disabled:p,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 ${p?"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(vd,{isEnterprise:!0,licenseInfo:N,daysRemaining:I,effectiveValidUntil:N?.validUntil,effectiveMaxSeats:N?.maxSeats,effectiveUsedSeats:M?.memberCount??N?.usedSeats??0,effectiveOrgName:M?.name??N?.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 vd({isEnterprise:t,licenseInfo:r,daysRemaining:o,effectiveValidUntil:a,effectiveMaxSeats:n,effectiveUsedSeats:s,effectiveOrgName:c,featureKeys:d,featureI18n:u,t:h}){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:h("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:h("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:h("license.trial")})]}),o!==null&&e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:`text-sm font-semibold tabular-nums ${o===0?"text-red-500":o<=7?"text-amber-500":o<=60?"text-amber-600":"text-fg-primary"}`,children:o>0?h("license.daysRemaining",{count:o}):h("license.expired")}),e.jsx("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:h("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:[hd[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:h("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:h("license.seats")}),e.jsxs("span",{className:"font-medium text-fg-primary",children:[s," / ",n]})]})]})]})}):null}function jd({modelId:t,tier:r}){const{t:o}=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:o(`modelRouting.tier.${a}`)})}function Nd({noProxyList:t,setNoProxyList:r,noProxyEntry:o,setNoProxyEntry:a,egressTesting:n,egressTest:s,egressError:c,onTest:d,authHeaders:u,loadNetworkSettings:h,t:x}){const[k,v]=i.useState(!1);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("button",{onClick:()=>v(!k),className:"flex items-center gap-2 text-[13px] font-medium text-fg-primary hover:text-fg-secondary transition-colors",children:[e.jsx("span",{className:`transition-transform ${k?"rotate-90":""}`,children:"▸"}),x("networkProxy.noProxyTitle"),e.jsx("span",{className:"text-[11px] tabular-nums text-fg-muted bg-surface-secondary px-1.5 py-0.5 rounded",children:t.length})]}),e.jsxs("button",{onClick:d,disabled:n,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md border border-border-default/60 text-fg-secondary hover:text-fg-primary hover:border-fg-muted transition-colors disabled:opacity-40",children:[n&&e.jsxs("svg",{className:"w-3 h-3 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"})]}),x(n?"networkProxy.testing":"networkProxy.test")]})]}),s&&e.jsx("span",{className:`text-[12px] ${s.ok?"text-emerald-600":"text-red-400"}`,children:s.text}),c&&e.jsx("span",{className:"text-[12px] text-amber-500",children:c}),k&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-border-default/30",children:[t.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(y=>e.jsxs("span",{className:"inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded bg-surface-secondary border border-border-default/50 text-[11px] font-mono text-fg-secondary",children:[y,e.jsx("button",{onClick:()=>{const S=t.filter(N=>N!==y);r(S),fetch("/api/settings/network",{method:"POST",headers:u(),body:JSON.stringify({noProxy:S})}).then(()=>h()).catch(()=>{})},className:"w-3.5 h-3.5 rounded flex items-center justify-center text-fg-muted/50 hover:text-red-400 hover:bg-red-500/10 transition-all text-[10px]",title:x("networkProxy.remove"),children:"×"})]},y))}),t.length===0&&e.jsx("p",{className:"text-[11px] text-fg-muted italic",children:x("networkProxy.noProxyEmpty")}),e.jsx("input",{type:"text",value:o,onChange:y=>a(y.target.value),onKeyDown:y=>{if(y.key!=="Enter"||!o.trim())return;const S=[...new Set([...t,o.trim()])];r(S),a(""),fetch("/api/settings/network",{method:"POST",headers:u(),body:JSON.stringify({noProxy:S})}).then(()=>h()).catch(()=>{})},placeholder:x("networkProxy.noProxyPlaceholder"),className:"w-full px-3 py-1.5 text-[13px] font-mono bg-surface-secondary/50 border border-border-default/50 rounded-lg text-fg-primary placeholder:text-fg-muted/40 focus:border-brand-500 outline-none transition-colors"}),e.jsx("p",{className:"text-[11px] text-fg-muted leading-relaxed",children:x("networkProxy.noProxyHint")})]})]})}export{Wr as SETTINGS_TABS,Br as SETTINGS_TAB_GROUPS,Md as Settings,id as resolveSettingsTab,nd as settingsTabLoads};