@markus-global/cli 0.12.3 → 0.12.5-rc.1

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 (159) hide show
  1. package/dist/background-maintenance.d.ts +25 -0
  2. package/dist/background-maintenance.d.ts.map +1 -1
  3. package/dist/background-maintenance.js +61 -0
  4. package/dist/background-maintenance.js.map +1 -1
  5. package/dist/commands/im-inbound-origin.d.ts +38 -0
  6. package/dist/commands/im-inbound-origin.d.ts.map +1 -0
  7. package/dist/commands/im-inbound-origin.js +48 -0
  8. package/dist/commands/im-inbound-origin.js.map +1 -0
  9. package/dist/commands/start.d.ts.map +1 -1
  10. package/dist/commands/start.js +211 -46
  11. package/dist/commands/start.js.map +1 -1
  12. package/dist/markus.mjs +18523 -9866
  13. package/dist/web-ui/assets/{AsyncState-_UC7xcxJ.js → AsyncState-fJJNUOXK.js} +1 -1
  14. package/dist/web-ui/assets/ChatComponents-S7d2CAAU.js +14 -0
  15. package/dist/web-ui/assets/{ContentRenderer-C-V5k_3K.js → ContentRenderer-DWqhC0uq.js} +6 -6
  16. package/dist/web-ui/assets/DeliverableShareModal-B7DwzEnt.js +1 -0
  17. package/dist/web-ui/assets/{Deliverables-CQnWqbTb.js → Deliverables-CueBYYpx.js} +2 -2
  18. package/dist/web-ui/assets/MarkdownMessage-D8BsJzvD.js +4 -0
  19. package/dist/web-ui/assets/{Search-CVYQIy_D.js → Search-CaYXz3u-.js} +1 -1
  20. package/dist/web-ui/assets/{SendToChat-IOAvuta-.js → SendToChat-_9sm7UBY.js} +1 -1
  21. package/dist/web-ui/assets/Settings-DTL14pY8.js +8 -0
  22. package/dist/web-ui/assets/{Store-BEsLd_RN.js → Store-DpGqUMS2.js} +1 -1
  23. package/dist/web-ui/assets/Switch-NYQTn8wl.js +1 -0
  24. package/dist/web-ui/assets/Team-DB-JytPl.js +93 -0
  25. package/dist/web-ui/assets/Work-sQq-gy3S.js +142 -0
  26. package/dist/web-ui/assets/{arc-DP1Vf7Sx.js → arc-JtkmqkSR.js} +1 -1
  27. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-Buq8JYN8.js → architectureDiagram-3BPJPVTR-B8zM5fky.js} +1 -1
  28. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BCa2p2_X.js → blockDiagram-GPEHLZMM-BQgjaOcE.js} +1 -1
  29. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BxsgggQY.js → c4Diagram-AAUBKEIU-BnZvYRwj.js} +1 -1
  30. package/dist/web-ui/assets/channel-Zno2q8Ba.js +1 -0
  31. package/dist/web-ui/assets/{chunk-2J33WTMH-BJZZ60c9.js → chunk-2J33WTMH-KONx1qvt.js} +1 -1
  32. package/dist/web-ui/assets/{chunk-4BX2VUAB-C5hc4E6J.js → chunk-4BX2VUAB-BqkxAkWs.js} +1 -1
  33. package/dist/web-ui/assets/{chunk-55IACEB6-CbyvZ6Mk.js → chunk-55IACEB6-DxLiTj85.js} +1 -1
  34. package/dist/web-ui/assets/{chunk-727SXJPM-JmNt9TVA.js → chunk-727SXJPM-Dhj-9NIs.js} +1 -1
  35. package/dist/web-ui/assets/{chunk-AQP2D5EJ-BTk0v5ba.js → chunk-AQP2D5EJ-M1vQ4YYc.js} +1 -1
  36. package/dist/web-ui/assets/{chunk-FMBD7UC4-BO-dhB1U.js → chunk-FMBD7UC4-DaXv58SH.js} +1 -1
  37. package/dist/web-ui/assets/{chunk-ND2GUHAM-BdjCcLdb.js → chunk-ND2GUHAM-Brkz9FCu.js} +1 -1
  38. package/dist/web-ui/assets/{chunk-QZHKN3VN-BAzRC82n.js → chunk-QZHKN3VN-DIsEGiBf.js} +1 -1
  39. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-hI59DDUw.js +1 -0
  40. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-hI59DDUw.js +1 -0
  41. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-CVffmErT.js → cose-bilkent-S5V4N54A-CSjC_YL5.js} +1 -1
  42. package/dist/web-ui/assets/{dagre-BM42HDAG-Dd9pB2fX.js → dagre-BM42HDAG-BevSxaQN.js} +1 -1
  43. package/dist/web-ui/assets/{diagram-2AECGRRQ-BG_AUqzM.js → diagram-2AECGRRQ-CT3Hj8jy.js} +1 -1
  44. package/dist/web-ui/assets/{diagram-5GNKFQAL-D5qFMRFf.js → diagram-5GNKFQAL-CAebHy6q.js} +1 -1
  45. package/dist/web-ui/assets/{diagram-KO2AKTUF-B3qTxSWl.js → diagram-KO2AKTUF-BvRWS7BX.js} +1 -1
  46. package/dist/web-ui/assets/{diagram-LMA3HP47-BrxC1636.js → diagram-LMA3HP47-gR9HBKc4.js} +1 -1
  47. package/dist/web-ui/assets/{diagram-OG6HWLK6-BvXyEQ9-.js → diagram-OG6HWLK6-B5HGsfNo.js} +1 -1
  48. package/dist/web-ui/assets/{docx-preview-DBAZFeEb.js → docx-preview-pRjmDg6F.js} +1 -1
  49. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-CMap9oy_.js → erDiagram-TEJ5UH35-mrPW01aQ.js} +1 -1
  50. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BZerJtvk.js → flowDiagram-I6XJVG4X-BrZ1G-Tt.js} +1 -1
  51. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CagPMHMO.js → ganttDiagram-6RSMTGT7-Dq_5mate.js} +1 -1
  52. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DZ5dDKRu.js → gitGraphDiagram-PVQCEYII-Cb3yTWUy.js} +1 -1
  53. package/dist/web-ui/assets/index-9SXWNIl0.css +1 -0
  54. package/dist/web-ui/assets/index-Bco6UnT7.js +867 -0
  55. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CHLdsDUZ.js → infoDiagram-5YYISTIA-CcnNlnvs.js} +1 -1
  56. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-SdeinQaS.js → ishikawaDiagram-YF4QCWOH-BqHTPtO1.js} +1 -1
  57. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-BtlL2fi0.js → journeyDiagram-JHISSGLW-DKBB9B-C.js} +1 -1
  58. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-BKPQYXkB.js → kanban-definition-UN3LZRKU-BVO5tbNl.js} +1 -1
  59. package/dist/web-ui/assets/{mermaid.core-MkJR6w4B.js → mermaid.core-bMoKRCj4.js} +5 -5
  60. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-CbOmHX_u.js → mindmap-definition-RKZ34NQL-Bk0lFKmi.js} +1 -1
  61. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CypGjJP1.js → pieDiagram-4H26LBE5-BRPnBLeL.js} +1 -1
  62. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CGtemfUz.js → quadrantDiagram-W4KKPZXB-CAqdqT5W.js} +1 -1
  63. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-N7YfpCvE.js → requirementDiagram-4Y6WPE33-Vv5YNzCu.js} +1 -1
  64. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CYnSrei-.js → sankeyDiagram-5OEKKPKP-Ciq1EgmQ.js} +1 -1
  65. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CsB7dCPF.js → sequenceDiagram-3UESZ5HK-DVRqp161.js} +1 -1
  66. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DTDFUXFP.js → stateDiagram-AJRCARHV-zbjDSKA3.js} +1 -1
  67. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C54VSYn7.js +1 -0
  68. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-C_bWAN9B.js → timeline-definition-PNZ67QCA-D0hr0d1U.js} +1 -1
  69. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CX_qAuUT.js → vennDiagram-CIIHVFJN-CtuZLcPo.js} +1 -1
  70. package/dist/web-ui/assets/{wardley-L42UT6IY-q53jQ293.js → wardley-L42UT6IY-nP2-eCDJ.js} +1 -1
  71. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-D34dKCJU.js → wardleyDiagram-YWT4CUSO-Dxc7OveP.js} +1 -1
  72. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BFAngp66.js → xychartDiagram-2RQKCTM6-Bm2LvPhZ.js} +1 -1
  73. package/dist/web-ui/index.html +2 -2
  74. package/docs/README.md +50 -16
  75. package/docs/api/guides/websocket.md +43 -0
  76. package/docs/api/reference.md +657 -0
  77. package/docs/architecture/a2a-communication.md +303 -0
  78. package/docs/architecture/agent-runtime.md +145 -28
  79. package/docs/architecture/architecture.md +30 -11
  80. package/docs/architecture/cognitive-architecture.md +189 -15
  81. package/docs/architecture/concurrent-processing.md +190 -31
  82. package/docs/architecture/context-assembly.md +264 -0
  83. package/docs/architecture/derived-views.md +463 -0
  84. package/docs/architecture/desktop-auto-update.md +185 -0
  85. package/docs/architecture/facts.md +406 -0
  86. package/docs/architecture/learning-loop.md +11 -0
  87. package/docs/architecture/limits.md +79 -0
  88. package/docs/architecture/mailbox-system.md +786 -668
  89. package/docs/architecture/memory-system.md +1 -1
  90. package/docs/architecture/messaging-gateway.md +7 -0
  91. package/docs/architecture/notification-delivery.md +221 -0
  92. package/docs/architecture/notification-sounds.md +177 -0
  93. package/docs/architecture/prompt-engineering.md +171 -700
  94. package/docs/{design/remote-access-contract.md → architecture/remote-access.md} +4 -0
  95. package/docs/architecture/state-machines.md +288 -5
  96. package/docs/architecture/tool-loop-harness.md +362 -0
  97. package/docs/architecture/tool-system.md +40 -16
  98. package/docs/design/background-callback-in-turn-delivery-2026-11-22.md +95 -0
  99. package/docs/design/c10-0b-pick-identity-leak-2026-11-22.md +233 -0
  100. package/docs/design/c10-a-identity-columns-2026-11-22.md +182 -0
  101. package/docs/design/c10-c-trust-boundary-2026-11-23.md +222 -0
  102. package/docs/design/c10-external-adapters-plan-2026-11-19.md +448 -0
  103. package/docs/design/c8-residual-mechanisms-2026-11-15.md +984 -0
  104. package/docs/design/external-signal-decision-loop-2026-11-25.md +579 -0
  105. package/docs/guides/development.md +1 -1
  106. package/docs/{architecture → guides}/mailbox-audit-checklist.md +7 -0
  107. package/docs/guides/remote-access.md +1 -1
  108. package/docs/{design/agent-stop-intent-audit.md → records/agent-stop-intent-audit-2026-11-08.md} +4 -0
  109. package/docs/records/c10-l5-gate-verification-2026-11-26.md +72 -0
  110. package/docs/records/c10-l5-live-verification-2026-11-25.md +117 -0
  111. package/docs/records/cut6-c4-verification-2026-11-12.md +268 -0
  112. package/docs/records/cut6-mailbox-address-envelope-design-2026-11-12.md +871 -0
  113. package/docs/records/cut7-c7a-red-green-evidence-2026-11-13.md +105 -0
  114. package/docs/records/cut7-c7a-workunit-implementation-2026-11-13.md +116 -0
  115. package/docs/records/cut7-c7b-verification-2026-11-14.md +90 -0
  116. package/docs/records/cut7-live-verification-2026-11-14.md +33 -0
  117. package/docs/records/cut7-wiring-negative-cache-2026-11-14.md +64 -0
  118. package/docs/records/cut7-workunit-execution-plan-2026-11-13.md +206 -0
  119. package/docs/records/cut8-a-entity-keys-design-2026-11-14.md +377 -0
  120. package/docs/records/cut8-b-turn-delta-injection-2026-11-14.md +362 -0
  121. package/docs/records/cut8-c-single-clock-2026-11-14.md +119 -0
  122. package/docs/records/cut8-c-single-clock-design-2026-11-14.md +150 -0
  123. package/docs/records/cut8-d-2026-11-14.md +231 -0
  124. package/docs/records/cut8-live-verification-2026-11-14.md +1018 -0
  125. package/docs/records/cut9-adjacent-identity-paths-2026-11-15.md +200 -0
  126. package/docs/records/cut9-identity-declaration-2026-11-15.md +163 -0
  127. package/docs/records/cut9-inbox-dual-run-diff-2026-11-15.md +117 -0
  128. package/docs/records/cut9-live-verification-2026-11-15.md +222 -0
  129. package/docs/records/cut9-runtime-probe-2026-11-19.md +520 -0
  130. package/docs/{design/deliverable-sharing.md → records/deliverable-sharing-2026-08-12.md} +10 -3
  131. package/docs/records/identity-backlog-disposition-2026-11-22.md +143 -0
  132. package/docs/records/marketplace-orphan-freeze-2026-11-22.md +239 -0
  133. package/docs/{architecture/notify-user-context-truth.md → records/notify-user-context-truth-2026-10-28.md} +6 -0
  134. package/docs/{handoff → records}/remote-access-handoff.md +1 -1
  135. package/package.json +1 -1
  136. package/templates/roles/HANDBOOK.md +1 -1
  137. package/templates/skills/agent-building/SKILL.md +1 -1
  138. package/dist/web-ui/assets/ChatComponents-Ca9tWI9W.js +0 -12
  139. package/dist/web-ui/assets/DeliverableShareModal-BvpyowYJ.js +0 -1
  140. package/dist/web-ui/assets/MarkdownMessage-DedA8Zob.js +0 -4
  141. package/dist/web-ui/assets/Settings-BQDqf4q5.js +0 -8
  142. package/dist/web-ui/assets/Switch-C6InTNUi.js +0 -1
  143. package/dist/web-ui/assets/Team-nfNyWj-s.js +0 -85
  144. package/dist/web-ui/assets/Work-BQvgkynj.js +0 -142
  145. package/dist/web-ui/assets/channel-BTSrOo6c.js +0 -1
  146. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BSYlcnF9.js +0 -1
  147. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BSYlcnF9.js +0 -1
  148. package/dist/web-ui/assets/index-CKPQYzzR.js +0 -867
  149. package/dist/web-ui/assets/index-CzHSs0Vd.css +0 -1
  150. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-AVnDjlzF.js +0 -1
  151. package/docs/api/api.md +0 -353
  152. package/docs/architecture/llm-provider-timeouts.md +0 -60
  153. package/docs/architecture/state-ownership.md +0 -83
  154. /package/docs/architecture/{frontend/team-chat.md → team-chat.md} +0 -0
  155. /package/docs/{analysis → records}/2026-10-29-a2a-cache-hit-rate.md +0 -0
  156. /package/docs/{fixes → records}/2026-11-12-session-expiry-and-mention-thinking.md +0 -0
  157. /package/docs/{handoff → records}/approval-tri-state-handoff.md +0 -0
  158. /package/docs/{design → records}/overview-attention-redesign.md +0 -0
  159. /package/docs/{remote-access/fast-path-plan.md → records/remote-access-fast-path-plan-2026-10-17.md} +0 -0
@@ -0,0 +1,8 @@
1
+ import{j as e,r as i,u as ce,a7 as Cs,aa as Hr,V as Un,k as U,h as Gt,a5 as zo,ab as Wo,a1 as Go,a3 as Jo,ac as Yo,ad as Qo,ae as Zo,af as Xo,U as ei,ag as ti,a0 as si,ah as ri,ai as ni,aj as ai,ak as Kn,al as oi,n as ws,P as qr,_ as ii,am as li,an as di,ao as ci,ap as ui,aq as mi,ar as Hn,as as gr,at as fr,au as qn,av as xi,a as gi,b as fi,c as pi,aw as zn,ax as hi,ay as bi,az as Wn,aA as Ha,aB as yi,i as vi,aC as ji}from"./index-Bco6UnT7.js";import{L as Ni}from"./AsyncState-fJJNUOXK.js";import{i as wi,n as ki,S as Ye}from"./Switch-NYQTn8wl.js";function Si(t,r){for(var n=0;n<r.length;n++){const a=r[n];if(typeof a!="string"&&!Array.isArray(a)){for(const o in a)if(o!=="default"&&!(o in t)){const s=Object.getOwnPropertyDescriptor(a,o);s&&Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:()=>a[o]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}const Ci=/ECONNREFUSED|EPIPE|ECONNRESET/i,Ai=/ENOTFOUND|EAI_AGAIN/i,Pi=/TIMEDOUT|timeout|ABORT_ERR|UND_ERR_(CONNECT|HEADERS|BODY)_TIMEOUT/i;function Mi(t){const r=(t?.detail??"").trim(),n=t?.code??"",a=r||n||"unknown";return n==="probe_http_error"?{key:"networkProxy.failProbeHttp",params:{detail:a}}:n==="network_unreachable"?Ci.test(r)?{key:"networkProxy.failRefused",params:{detail:a}}:Ai.test(r)?{key:"networkProxy.failDns",params:{detail:a}}:Pi.test(r)?{key:"networkProxy.failTimeout",params:{detail:a}}:{key:"networkProxy.failUnreachable",params:{detail:a}}:{key:"networkProxy.failUnknown",params:{detail:a}}}const we="bg-surface-elevated rounded-xl border border-border-default/40",Fe={pageTitle:"text-lg font-semibold",groupTitle:"text-[13px] font-semibold",groupDesc:"text-xs leading-relaxed",hint:"text-[11px] leading-relaxed",badge:"text-[11px] font-medium"},Qe={strong:"text-fg-primary",desc:"text-fg-tertiary"},kt="px-3 py-2 text-[13px] 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",zr="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 text-[13px] font-medium bg-brand-600 hover:bg-brand-500 text-on-brand disabled:opacity-40 rounded-lg transition-colors",it="inline-flex items-center justify-center gap-1.5 px-3 py-2 text-[13px] 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 Je({tone:t="neutral",children:r,title:n}){const a={neutral:"bg-fg-tertiary/10 text-fg-tertiary",ok:"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",warn:"bg-amber-500/15 text-amber-600 dark:text-amber-400",danger:"bg-red-500/15 text-red-500",brand:"bg-brand-500/15 text-brand-500"};return e.jsx("span",{title:n,className:`${Fe.badge} rounded px-1.5 py-0.5 ${a[t]}`,children:r})}function je({label:t,hint:r,children:n}){return e.jsxs("div",{className:"flex flex-wrap items-start gap-x-6 gap-y-2 px-5 py-3.5",children:[e.jsxs("div",{className:"min-w-[7rem] flex-1",children:[t&&e.jsx("div",{className:"text-[13px] font-medium text-fg-primary",children:t}),r&&e.jsx("div",{className:"mt-0.5 text-[11px] leading-relaxed text-fg-tertiary",children:r})]}),n&&e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:n})]})}function ke({title:t,description:r,action:n,children:a}){return e.jsxs("section",{className:"space-y-6",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:`${Fe.groupTitle} ${Qe.strong}`,children:t}),r&&e.jsx("p",{className:`mt-0.5 ${Fe.groupDesc} ${Qe.desc}`,children:r})]}),n]}),e.jsx("div",{className:"space-y-3",children:a})]})}function Gn({title:t,description:r,children:n,defaultOpen:a=!0}){const[o,s]=i.useState(a);return e.jsxs("section",{className:"space-y-6",children:[e.jsxs("button",{type:"button",onClick:()=>s(!o),className:"flex items-start justify-between w-full group text-left",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:`${Fe.groupTitle} ${Qe.strong}`,children:t}),r&&e.jsx("p",{className:`mt-0.5 ${Fe.groupDesc} ${Qe.desc}`,children:r})]}),e.jsx("span",{className:`text-fg-tertiary mt-0.5 transition-transform group-hover:text-fg-secondary ${o?"":"-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"})})})]}),o&&e.jsx("div",{className:"space-y-3",children:n})]})}function Ti(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 Ei(t){return t.maxInputTokens>0||t.inputCostPer1MTokens>0||t.outputCostPer1MTokens>0}function pr(t){if(t.tier)return t.tier;const r=t.id.toLowerCase(),n=/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":n.test(r)?"max":a.test(r)?"base":"pro"}const Jn={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 qa({models:t,selectedModel:r,onSelect:n,loading:a,compact:o,maxVisible:s,showTiers:d}){const{t:c}=ce("settings"),[u,h]=i.useState(""),[x,v]=i.useState(!1),[j,k]=i.useState(""),P=i.useMemo(()=>{let m=t;if(u){const w=u.toLowerCase();m=m.filter(V=>V.id.toLowerCase().includes(w))}return j&&(m=m.filter(w=>pr(w)===j)),m},[t,u,j]),N=i.useMemo(()=>{const m={max:0,pro:0,base:0};for(const w of t)m[pr(w)]++;return m},[t]),y=s??(o?5:10),b=x?P:P.slice(0,y),A=P.length>y;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"}),c("modelPicker.loading")]}):t.length===0?e.jsx("div",{className:"py-3 text-sm text-fg-tertiary",children:c("modelPicker.empty")}):e.jsxs("div",{className:"space-y-2",children:[d&&t.length>3&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>k(""),className:`px-2 py-0.5 rounded text-[10px] transition-colors ${j?"bg-surface-overlay text-fg-tertiary hover:text-fg-secondary":"bg-brand-500/20 text-brand-500"}`,children:c("modelPicker.allCount",{count:t.length})}),["max","pro","base"].filter(m=>N[m]>0).map(m=>e.jsx("button",{onClick:()=>k(j===m?"":m),className:`px-2 py-0.5 rounded text-[10px] font-medium uppercase transition-colors border ${j===m?Jn[m]:"border-transparent bg-surface-overlay text-fg-tertiary hover:text-fg-secondary"}`,children:c("modelPicker.tierCount",{tier:c(`modelRouting.tier.${m}`),count:N[m]})},m))]}),t.length>5&&e.jsx("input",{type:"text",value:u,onChange:m=>{h(m.target.value),v(!1)},placeholder:c("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 ${o?"max-h-[280px] overflow-y-auto":""}`,children:b.map(m=>{const w=m.id===r,V=pr(m);return e.jsxs("button",{type:"button",onClick:()=>n(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}),d&&e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-semibold uppercase border ${Jn[V]}`,children:c(`modelRouting.tier.${V}`)})]}),e.jsx("div",{className:"flex items-center gap-2",children:w&&e.jsx("span",{className:"text-[10px] text-brand-500 font-medium",children:c("modelPicker.active")})})]}),Ei(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:[Ti(m.maxInputTokens)," ",c("modelPicker.ctx")]})}),!o&&e.jsxs("div",{className:"ml-5 mt-1 flex items-center gap-1.5 flex-wrap",children:[m.capabilities.functionCalling&&e.jsx(Ft,{label:c("modelPicker.capabilities.tools")}),m.capabilities.vision&&e.jsx(Ft,{label:c("modelPicker.capabilities.vision")}),m.capabilities.reasoning&&e.jsx(Ft,{label:c("modelPicker.capabilities.reasoning")}),m.capabilities.promptCaching&&e.jsx(Ft,{label:c("modelPicker.capabilities.caching")}),m.capabilities.webSearch&&e.jsx(Ft,{label:c("modelPicker.capabilities.search")})]})]},m.id)})}),A&&!x&&e.jsx("button",{type:"button",onClick:()=>v(!0),className:"text-xs text-brand-500 hover:text-brand-400 px-3",children:c("modelPicker.showAll",{count:P.length})}),x&&A&&e.jsx("button",{type:"button",onClick:()=>v(!1),className:"text-xs text-fg-tertiary hover:text-fg-secondary px-3",children:c("modelPicker.showLess")})]})}function Ft({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 Yt({value:t,options:r,placeholder:n,onChange:a}){const{t:o}=ce("settings"),[s,d]=i.useState(!1),[c,u]=i.useState(""),h=i.useRef(null),x=i.useRef(null),v=i.useRef(null),[j,k]=i.useState(-1);i.useEffect(()=>{function m(w){h.current&&!h.current.contains(w.target)&&d(!1)}return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]),i.useEffect(()=>{s&&x.current&&x.current.focus()},[s]);const P=i.useMemo(()=>{if(!c.trim())return r;const m=c.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,c]),N=i.useMemo(()=>{const m=new Map;for(const V of P){const T=V.providerLabel;m.has(T)||m.set(T,[]),m.get(T).push(V)}const w={max:0,pro:1,base:2};for(const V of m.values())V.sort((T,I)=>(w[T.tier??"base"]??9)-(w[I.tier??"base"]??9));return m},[P]),y=i.useMemo(()=>{const m=[];for(const w of N.values())m.push(...w);return m},[N]),b=i.useMemo(()=>{if(!t)return n??o("modelRouting.auto");const m=r.find(w=>`${w.provider}/${w.modelId}`===t);return m?`${m.providerLabel}/${m.modelName}`:t},[t,r,n,o]);function A(m){if(!s){(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),d(!0));return}switch(m.key){case"ArrowDown":m.preventDefault(),k(w=>Math.min(w+1,y.length-1));break;case"ArrowUp":m.preventDefault(),k(w=>Math.max(w-1,-1));break;case"Enter":if(m.preventDefault(),j===-1)a("",null);else if(y[j]){const w=y[j];a(`${w.provider}/${w.modelId}`,w)}d(!1),u("");break;case"Escape":d(!1),u("");break}}return i.useEffect(()=>{v.current&&j>=0&&v.current.querySelector(`[data-focus-index="${j}"]`)?.scrollIntoView({block:"nearest"})},[j]),e.jsxs("div",{ref:h,className:"relative min-w-0",onKeyDown:A,children:[e.jsx("button",{type:"button",onClick:()=>{d(!s),u(""),k(-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:b}),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:c,onChange:m=>{u(m.target.value),k(-1)},placeholder:o("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:v,className:"overflow-y-auto flex-1",children:[e.jsx("div",{className:`px-3 py-1.5 text-xs cursor-pointer ${j===-1?"bg-brand-500/20 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,onClick:()=>{a("",null),d(!1),u("")},children:n??o("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(V=>{const T=y.indexOf(V),I=`${V.provider}/${V.modelId}`===t;return e.jsxs("div",{"data-focus-index":T,className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${T===j?"bg-brand-500/20":I?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,onClick:()=>{a(`${V.provider}/${V.modelId}`,V),d(!1),u("")},children:[e.jsx("span",{className:"flex-1 truncate text-fg-primary",children:V.modelName}),V.tier&&e.jsx(Ri,{tier:V.tier}),V.costTier&&e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:V.costTier})]},`${V.provider}/${V.modelId}`)})]},m)),y.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:o("modelPicker.empty")})]})]})]})}function Ri({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 Ii=500,Yn=[{groupKey:"image",capabilities:["image_recognition","image_generation"]},{groupKey:"audio",capabilities:["audio_tts","audio_stt"]},{groupKey:"video",capabilities:["video_generation"]}];function Li({onSave:t,configuredProviders:r}){const{t:n}=ce(["settings","common"]),[a,o]=i.useState({}),[s,d]=i.useState(null),[c,u]=i.useState(!1),[h,x]=i.useState(null),[v,j]=i.useState(!0),[k,P]=i.useState("idle"),[N,y]=i.useState(null),[b,A]=i.useState({}),[m,w]=i.useState(!1),[V,T]=i.useState("idle"),[I,F]=i.useState(null),[C,$]=i.useState(!1),D=i.useRef(null),B=i.useRef(null),S=i.useMemo(()=>r.map(f=>f.name).sort().join(","),[r]);i.useEffect(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{o(f.capabilityRouting?.assignments??{}),d(f.routingDefaultModel??null),u(!0)}).catch(f=>{x(String(f)),u(!0)})},[S]),i.useEffect(()=>{let f=!1;return j(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(R=>{if(!R.ok)throw new Error(`HTTP ${R.status}`);return R.json()}).then(R=>{if(f)return;const p=[];for(const K of R.providers)for(const z of K.models)p.push({provider:K.provider,providerLabel:K.displayName,modelId:z.id,modelName:z.name,mode:z.mode,tier:z.tier,costTier:z.costTier,capabilities:z.capabilities});y(p)}).catch(()=>{f||y(null)}).finally(()=>{f||j(!1)}),()=>{f=!0}},[S]),i.useEffect(()=>{fetch("/api/models/suggested-assignments",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{A(f.suggestions),w(!0)}).catch(()=>w(!0))},[S]);const L=i.useCallback(f=>{P("saving"),t(f).then(()=>{P("saved"),setTimeout(()=>P(R=>R==="saved"?"idle":R),2e3)}).catch(()=>{P("error"),setTimeout(()=>P(R=>R==="error"?"idle":R),3e3)})},[t]),J=i.useCallback((f,R)=>{B.current={capabilityRouting:f!==void 0?{assignments:f}:B.current?.capabilityRouting,routingDefaultModel:R!==void 0?R:B.current?.routingDefaultModel},D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{const p=B.current;B.current=null,p&&L(p)},Ii)},[L]),_=i.useMemo(()=>r.flatMap(f=>(f.models??[{id:f.model,name:f.model}]).map(R=>({provider:f.name,providerLabel:f.displayName??f.name,modelId:R.id,modelName:R.name}))),[r]),H=N??_,X=i.useMemo(()=>Object.entries(a).map(([f,R])=>`${f}:${R?.provider??""}/${R?.model??""}`).sort().join("|"),[a]);i.useEffect(()=>{!c||!N||N.length===0||N.some(f=>!!f.modelId)&&(o(f=>{let R=!1;const p={...f};for(const K of Yn)for(const z of K.capabilities){const se=p[z];if(!se?.model)continue;const ae=za(N,z);if(ae.length===0)continue;ae.some(te=>te.provider===se.provider&&te.modelId===se.model)||(delete p[z],R=!0)}return R?(J(p),p):f}),d(f=>{if(!f?.model||N.some(z=>z.provider===f.provider&&z.modelId===f.model))return f;const p=N.find(z=>z.provider==="markus"),K=p?{provider:p.provider,model:p.modelId}:{provider:N[0].provider,model:N[0].modelId};return t({routingDefaultModel:K}),K}))},[c,N,S,J,X]);const me=i.useCallback(()=>{fetch("/api/settings/llm/routing",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{o(f.capabilityRouting?.assignments??{}),d(f.routingDefaultModel??null)}).catch(()=>{}),j(!0),fetch("/api/models/routing-candidates",{credentials:"include"}).then(f=>{if(!f.ok)throw new Error(`HTTP ${f.status}`);return f.json()}).then(f=>{const R=[];for(const p of f.providers)for(const K of p.models)R.push({provider:p.provider,providerLabel:p.displayName,modelId:K.id,modelName:K.name,mode:K.mode,tier:K.tier,costTier:K.costTier,capabilities:K.capabilities});y(R)}).catch(()=>{}).finally(()=>j(!1))},[]),ie=i.useCallback(async()=>{if(V!=="working"){T("working"),F(null);try{const f=await fetch("/api/settings/llm/restore-recommended",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}}),R=await f.json().catch(()=>({}));if(!f.ok||!R.ok)throw new Error(R.error??`HTTP ${f.status}`);R.capabilityRouting&&o(R.capabilityRouting.assignments??{}),R.routingDefaultModel!==void 0&&d(R.routingDefaultModel),me(),T("idle"),P("saved"),setTimeout(()=>P(p=>p==="saved"?"idle":p),2e3)}catch(f){T("error"),F(f instanceof Error?f.message:String(f)),setTimeout(()=>T("idle"),4e3)}}},[V,me]),ee=H.length>0;return c?h?e.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-xs text-red-400",children:n("modelRouting.loadError",{error:h})}):v&&!ee?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"bg-surface-elevated rounded-xl p-5",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-secondary",children:[e.jsxs("svg",{className:"w-4 h-4 animate-spin text-brand-500",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),e.jsx("span",{children:n("modelRouting.loadingModels")})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(Bi,{status:k,t:n}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx("button",{type:"button",onClick:()=>$(!0),disabled:V==="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:n(V==="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:n("modelRouting.defaultModelTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:n("modelRouting.defaultModelDesc")})]}),e.jsx("div",{className:"max-w-md",children:e.jsx(Yt,{value:s?`${s.provider}/${s.model}`:"",options:H,placeholder:n("modelRouting.defaultModelPlaceholder"),onChange:f=>{if(!f)d(null),J(void 0,null);else{const[R,...p]=f.split("/"),K={provider:R,model:p.join("/")};if(d(K),a.text){const z={...a};delete z.text,o(z),J(z,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:n("modelRouting.capabilityAssignTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:n("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:n("modelRouting.noProvidersHint")}),r.length>0&&e.jsx("div",{className:"space-y-4",children:Yn.map(f=>e.jsx(Oi,{groupKey:f.groupKey,capabilities:f.capabilities,assignments:a,suggestions:b,allModels:H,configuredProviderNames:new Set(r.map(R=>R.name)),t:n,onAssign:(R,p)=>{const K={...a};p?K[R]=p:delete K[R],o(K),J(K)}},f.groupKey))})]}),C&&e.jsx(Cs,{variant:"primary",title:n("modelRouting.restoreRecommended"),message:n("modelRouting.restoreConfirm"),confirmLabel:n("common:confirm"),onConfirm:()=>{$(!1),ie()},onCancel:()=>$(!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(f=>e.jsx("div",{className:"h-10 bg-surface-overlay rounded-lg"},f))})]})})}function Oi({groupKey:t,capabilities:r,assignments:n,suggestions:a,allModels:o,configuredProviderNames:s,t:d,onAssign:c}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider mb-2 px-1",children:d(`modelRouting.capabilityGroups.${t}`)}),e.jsx("div",{className:"space-y-1",children:r.map(u=>{const h=n[u],x=a[u],v=h?`${h.provider}/${h.model}`:"",j=za(o,u),k=x?j.find(A=>A.provider===x.provider&&A.modelId===x.model)?.modelName??x.model:void 0,P=j.length>0,N=h?$i(o,h.provider,h.model):void 0,y=h&&!s.has(h.provider),b=!!(h&&P&&u!=="text"&&!j.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 ${b?"bg-red-500/10 border border-red-500/30":y?"bg-yellow-500/10 border border-yellow-500/30":!P&&!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:d(`modelRouting.capabilities.${u}`)})}),e.jsx("div",{className:"flex-1 min-w-0",children:b?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:d("modelRouting.mismatchHint")})]}),e.jsx(Yt,{value:"",options:j,placeholder:d("modelRouting.selectModel"),onChange:A=>{if(!A)c(u,null);else{const[m,...w]=A.split("/");c(u,{provider:m,model:w.join("/")})}}})]}):P?e.jsx(Yt,{value:v,options:j,placeholder:k?`${k} (${d("modelRouting.suggested")})`:d("modelRouting.selectModel"),onChange:A=>{if(!A)c(u,null);else{const[m,...w]=A.split("/");c(u,{provider:m,model:w.join("/")})}}}):e.jsxs("span",{className:"text-xs text-amber-400",children:[d("modelRouting.noModelAvailable"),e.jsxs("span",{className:"text-fg-tertiary ml-1",children:["— ",d("modelRouting.addProviderHint")]})]})}),e.jsxs("div",{className:"w-14 shrink-0 flex justify-end",children:[b&&e.jsx("span",{className:"text-[10px] text-red-400 font-medium",title:d("modelRouting.mismatchHint"),children:"⚠"}),!b&&y&&e.jsx("span",{className:"text-[10px] text-yellow-400 font-medium",title:d("modelRouting.staleProvider"),children:"⚠"}),!b&&!y&&N&&e.jsx(Qn,{tier:N}),!b&&!y&&!N&&h&&e.jsx(Qn,{tier:"unknown"})]}),e.jsx("div",{className:"w-8 shrink-0 flex justify-end",children:h&&e.jsx("button",{onClick:()=>c(u,null),className:"text-fg-tertiary hover:text-red-400 transition-colors",title:d("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 $i(t,r,n){return t.find(o=>o.provider===r&&o.modelId===n)?.tier}function Bi({status:t,t:r}){if(t==="idle")return null;const n={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 ${n[t]}`,children:a[t]})}function Qn({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 za(t,r){if(r==="text")return t.filter(d=>wi(d));const n={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"]},o=n[r],s=a[r];return t.filter(d=>!!(d.capabilities&&d.capabilities.length>0&&s&&s.some(c=>d.capabilities.includes(c))||o&&d.mode&&o.includes(d.mode)))}function Di({orgId:t}){const{t:r}=ce("settings"),[n,a]=i.useState(null);return i.useEffect(()=>{if(!t)return;let o=!1;return fetch(`/api/orgs/${t}/slug`,{credentials:"include"}).then(s=>s.ok?s.json():null).then(s=>{!o&&s&&a(s)}).catch(()=>{}),()=>{o=!0}},[t]),n?.hubOrgId?e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-brand-500/25 bg-brand-600/[0.06] px-3 py-2",children:[e.jsx("span",{className:"shrink-0 text-xs text-fg-tertiary",children:r("orgIdentity.label")}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("code",{className:"truncate font-mono text-xs text-fg-primary",children:n.orgSlug||r("orgIdentity.unset")}),e.jsx("span",{className:"shrink-0 rounded bg-green-500/15 px-1.5 py-0.5 text-[10px] text-green-600",children:r("orgIdentity.synced")})]})]}):null}function Ut({w:t="w-16"}){return e.jsx("span",{className:`inline-block h-3 ${t} animate-pulse rounded bg-surface-elevated`,"aria-hidden":"true"})}function Vi({authUser:t}){const{t:r}=ce(["settings","common"]),[n,a]=i.useState(null),[o,s]=i.useState([]),[d,c]=i.useState([]),[u,h]=i.useState(()=>Hr()||Un()?"loading":"not-connected"),x=u==="loading",[v,j]=i.useState(null),k=i.useCallback(()=>{U.hubOrgs.mine().catch(T=>(j({type:"err",text:T instanceof Error?T.message:r("org.loadFailed")}),{orgs:[]})).then(T=>{s(T.orgs),U.hubOrgs.invitations().then(I=>c(I.invitations)).catch(()=>{})})},[r]);i.useEffect(()=>{if(!Hr()&&!Un()){h("not-connected");return}k(),Gt.user.plan().then(T=>a(T)).catch(()=>{}).finally(()=>h("ready"))},[k]);const P=async T=>{try{await U.hubOrgs.acceptInvitation(T),c(I=>I.filter(F=>F.orgId!==T)),k()}catch(I){j({type:"err",text:I instanceof Error?I.message:"Failed"})}},N=o.find(T=>T.id===n?.orgId)??o[0],y=n?n.creditsBudgetCu??(n.monthlyQuotaCu??0)+(n.bonusCu??0)+(n.purchasedCu??0):0,b=!!(n?.memberCuLimit!=null&&n.memberCuLimit>0&&N&&N.role!=="owner"&&N.role!=="admin"&&N.memberCount>1),A=Math.round(b?n?.memberCuUsed??0:n?.totalConsumedThisPeriod??n?.cuUsed??0),m=b?n?.memberCuLimit??0:y,w=x||m>0,V=x||!!N;return e.jsxs("div",{className:"space-y-3",children:[v&&e.jsxs("div",{className:`flex items-center gap-2 rounded-lg px-4 py-3 text-sm ${v.type==="ok"?"border border-green-500/20 bg-green-500/10 text-green-600":"border border-red-500/20 bg-red-500/10 text-red-500"}`,children:[e.jsx("span",{children:v.type==="ok"?"✓":"✕"}),e.jsx("span",{children:v.text})]}),d.length>0&&e.jsx("div",{className:"space-y-2",children:d.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-amber-500/20 bg-amber-500/5 px-4 py-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-fg-primary",children:T.orgName}),e.jsxs("span",{className:"ml-1 text-fg-tertiary",children:["— ",r("org.invitedBy")," ",T.invitedBy]})]}),e.jsx("button",{type:"button",onClick:()=>{P(T.orgId)},className:"rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-medium text-on-brand transition-colors hover:bg-brand-500",children:r("org.accept")})]},T.orgId))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Di,{orgId:t?.orgId}),e.jsx("div",{className:"space-y-3 rounded-lg border border-border-default px-5 py-4",children:u==="not-connected"?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary",children:r("orgSummary.notConnectedTitle")}),e.jsx("p",{className:"text-xs leading-relaxed text-fg-tertiary",children:r("orgSummary.notConnectedDesc")}),e.jsx("button",{type:"button",onClick:()=>{zo(Wo("markus://auth"))},className:"inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-xs font-medium text-on-brand transition-colors hover:bg-brand-500",children:r("orgSummary.connectHub")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("orgSummary.plan")}),x?e.jsx(Ut,{w:"w-14"}):e.jsx("span",{className:"rounded border border-brand-500/15 bg-brand-600/10 px-2 py-0.5 text-xs font-semibold capitalize text-brand-500",children:n?.planType??r("orgSummary.planUnknown")})]}),w&&e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r(b?"account.personalLimit":"account.credits")}),e.jsx("span",{className:"font-medium tabular-nums text-fg-primary",children:x?e.jsx(Ut,{w:"w-24"}):e.jsxs(e.Fragment,{children:[A.toLocaleString()," / ",m.toLocaleString()]})})]}),V?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("org.nameLabel")}),x?e.jsx(Ut,{w:"w-28"}):e.jsx("span",{className:"font-medium text-fg-primary",children:N?.name})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("account.memberCount")}),x?e.jsx(Ut,{w:"w-6"}):e.jsx("span",{className:"font-medium text-fg-primary",children:N?.memberCount})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"text-fg-tertiary",children:r("org.orgId")}),x?e.jsx(Ut,{w:"w-40"}):e.jsx("code",{className:"rounded bg-surface-elevated px-1.5 py-0.5 text-[11px] text-fg-secondary",children:N?.id})]})]}):e.jsx("p",{className:"text-xs text-fg-tertiary",children:r("account.noOrg")}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsx("a",{href:`${Gt.getUrl()}/settings?tab=billing`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-4 py-2 text-xs font-medium text-on-brand no-underline transition-colors hover:bg-brand-500",children:r("orgSummary.manageBilling")}),e.jsx("a",{href:`${Gt.getUrl()}/settings?tab=organization`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-lg border border-border-default px-4 py-2 text-xs font-medium text-fg-secondary no-underline transition-colors hover:bg-surface-elevated",children:r("orgSummary.manageMembers")})]})]})})]})]})}function _i({configuredProviders:t}){const{t:r}=ce("settings"),[n,a]=i.useState(null),[o,s]=i.useState([]),[d,c]=i.useState(null),[u,h]=i.useState(null),x=i.useMemo(()=>t.map(N=>`${N.name}:${N.models?.length??0}`).sort().join(","),[t]),v=i.useCallback(async()=>{c(null);try{const[{agents:N},y]=await Promise.all([U.agents.list({lean:!0}),U.teams.list()]),b=y.teams.map(m=>({id:m.id,name:m.name}));s(b);const A=await Promise.all(N.map(async m=>{try{const V=(await U.agents.get(m.id)).config?.llmConfig;return{id:m.id,name:m.name||m.id,teamId:m.teamId,override:V?.modelMode==="custom"&&V.primary&&V.defaultModel?`${V.primary}/${V.defaultModel}`:null,llmConfig:{modelMode:V?.modelMode,primary:V?.primary??"",defaultModel:V?.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){c(String(N))}},[x]);i.useEffect(()=>{v()},[v,x]);const j=i.useMemo(()=>{const N=[];for(const y of t)for(const b of y.models??[])N.push({provider:y.name,providerLabel:y.displayName??y.name,modelId:b.id,modelName:b.name??b.id});return N},[t]),k=async(N,y)=>{h(N),c(null);try{y?await U.agents.updateConfig(N,{llmConfig:{modelMode:"custom",primary:y.provider,defaultModel:y.modelId}}):await U.agents.updateConfig(N,{llmConfig:{modelMode:"default",primary:"",defaultModel:null}});const b=y?`${y.provider}/${y.modelId}`:null;a(A=>A?.map(m=>m.id===N?{...m,override:b}:m)??A),ki(N)}catch(b){c(String(b))}finally{h(null)}},P=i.useMemo(()=>{if(!n)return[];const N=new Map,y=[];for(const A of n)if(A.teamId){const m=N.get(A.teamId)??[];m.push(A),N.set(A.teamId,m)}else y.push(A);const b=[];y.length&&b.push({key:"ungrouped",label:r("perAgentModel.ungrouped",{defaultValue:"Ungrouped"}),rows:y});for(const A of o){const m=N.get(A.id);m?.length&&b.push({key:`team:${A.id}`,label:A.name,rows:m})}for(const[A,m]of N)o.some(w=>w.id===A)||b.push({key:`team:${A}`,label:A,rows:m});return b},[n,o,r]);return n===null&&!d?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.'})})]})}),d&&e.jsx("div",{className:"text-xs text-red-500",children:d}),(!n||n.length===0)&&!d&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:r("perAgentModel.noAgents",{defaultValue:"No agents available."})}),n&&n.length>0&&e.jsx("div",{className:"space-y-5",children:P.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(y=>e.jsxs("div",{title:y.id,className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:y.name}),e.jsxs("div",{className:"flex w-[55%] max-w-[320px] min-w-0 shrink-0 items-center gap-1.5 sm:w-[320px]",children:[y.override?e.jsxs(e.Fragment,{children:[e.jsx(Yt,{value:y.override,options:j,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:(b,A)=>{k(y.id,A)}}),e.jsx("button",{type:"button",disabled:u===y.id,onClick:()=>{k(y.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(Yt,{value:"",options:j,placeholder:r("perAgentModel.followGlobal",{defaultValue:"Follow global"}),onChange:(b,A)=>{k(y.id,A)}}),u===y.id&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary",children:r("common:loading",{defaultValue:"…"})})]})]},y.id))})]},N.key))})]})}let ks=[],ys=null;async function Fi(){return ys||(ys=(async()=>{try{ks=(await U.modelCatalog.providerCatalog()).providers??[]}catch{ks=[]}return ks})(),ys)}function Ui(){const[t,r]=i.useState(ks);return i.useEffect(()=>{let n=!0;return Fi().then(a=>{n&&r(a)}),()=>{n=!1}},[]),t}const Ki="integrations.platforms",Xr=(t,r)=>`settings:${Ki}.${t}.${r}`,Hi={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 qi(t){return Hi[t]}function zi(t,r){return t(Xr(r.id,"label"),{defaultValue:r.label})}function Wa(t,r,n){const a=Xr(r,`fields.${n.key}`);return{label:t(`${a}.label`,{defaultValue:n.label}),help:n.help?t(`${a}.help`,{defaultValue:n.help}):void 0,placeholder:n.placeholder?t(`${a}.placeholder`,{defaultValue:n.placeholder}):void 0,options:n.options?.map(o=>({value:o.value,label:t(`${a}.options.${o.value}`,{defaultValue:o.label})}))}}function Wi(t,r,n){const a=[],o=Xr(n,"guide");for(let s=1;s<=20;s+=1){const d=`${o}.step${s}.title`;if(!t.exists(d))break;const c=`${o}.step${s}.desc`,u=t.exists(c)?r(c):void 0;a.push({title:r(d),...u?{desc:u}:{}})}return a}function Gi(t){return t("settings:integrations.guide.heading",{defaultValue:"Setup guide"})}function Ji(t){return t.type==="boolean"?t.default===!0:t.multiple?Array.isArray(t.default)?[...t.default]:[]:t.default!==void 0?t.default:""}function As(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 Zn(t){const r={};for(const n of t.fields){if(n.secret){r[n.key]="";continue}const a=t.values[n.key];r[n.key]=a??Ji(n)}return r}function Xn(t,r,n={}){const a=[];for(const o of t)if(o.required){if(o.secret){if(!As(o,r[o.key]))continue;n[o.key]?.hasValue||a.push(o.key);continue}As(o,r[o.key])&&a.push(o.key)}return a}function Yi(t,r,n){const a={enabled:n};for(const o of t.fields){const s=r[o.key];if(o.secret){if(As(o,s))continue;a[o.key]=s;continue}s!==void 0&&(a[o.key]=s)}return a}function Qi(t){return t.filter(r=>r.required||r.type==="agent")}function Zi(t){return t.filter(r=>!(r.required||r.type==="agent"))}function Wr(t){return Array.isArray(t)?`[${t.map(Wr).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[a])=>n<a?-1:n>a?1:0).map(([n,a])=>`${JSON.stringify(n)}:${Wr(a)}`).join(",")}}`:JSON.stringify(t)??"null"}function Xi(t){return Wr({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 el(t){const r=t.ok===!0||t.success===!0;return{ok:r,text:t.message??t.error??(r?"OK":"Failed"),code:t.code}}function tl(t){return t?.status==="awaiting_reply"||t?.status==="awaiting_inbound"}function sl(t,r=!1){return t.hasConfig?t.enabled?t.lastVerifiedAt||r?"verified":"unverified":"off":"unconfigured"}function rl(t){return{id:"",platform:t.id,label:"",enabled:!0,connected:!1,hasConfig:!1,capabilities:t.capabilities,fields:t.fields,values:{},secrets:nl(t.fields),agentId:null,notifyAgentId:null,channels:[],lastError:null,canListChannels:!1,lastVerifiedAt:null}}function nl(t){const r={};for(const n of t)n.secret&&(r[n.key]={hasValue:!1});return r}function al(t){return t.id===""}function ea(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 hr(t,r){return t.find(n=>n.nativeId===r)}function ta(t,r,n,a){const o=t.filter(s=>s.nativeId!==r);return o.push({nativeId:r,kind:a??null,agentId:n}),o.sort((s,d)=>s.nativeId.localeCompare(d.nativeId))}function sa(t,r){return t.filter(n=>n.nativeId!==r)}function ol(t,r){const n=new Set(r.map(a=>a.id));return t.filter(a=>!n.has(a.nativeId))}function il(t,r){const n=r.trim().toLowerCase();return n?t.filter(a=>a.name.toLowerCase().includes(n)||a.id.toLowerCase().includes(n)):t}function ll(t){const r=new Map;for(const n of t){const a=r.get(n.platform);a?a.push(n):r.set(n.platform,[n])}return[...r.entries()].map(([n,a])=>({platform:n,instances:a}))}function dl(t,r,n={}){const a=n.devMode??!1,o=new Set(t.filter(c=>c.devOnly&&!a).map(c=>c.id)),s=[],d=new Set;for(const c of t)o.has(c.id)||d.has(c.id)||(d.add(c.id),s.push(c.id));for(const c of r)o.has(c.platform)||d.has(c.platform)||(d.add(c.platform),s.push(c.platform));return s}function cl(t,r,n){const[a,o]=i.useState([]),[s,d]=i.useState(null),[c,u]=i.useState(!1),h=i.useRef(t);h.current=t;const x=i.useRef(0),v=i.useCallback(()=>{if(!n||!r)return;const j=++x.current;u(!0),h.current(r).then(k=>{j===x.current&&(o(k.channels??[]),d(k.error??null))}).catch(k=>{j===x.current&&(o([]),d(k instanceof Error?k.message:String(k)))}).finally(()=>{j===x.current&&u(!1)})},[n,r]);return i.useEffect(()=>(v(),()=>{x.current+=1}),[v]),{channels:a,error:s,loading:c,reloadChannels:v}}const Ga=/^notify[A-Z]/,Ja="notifyEnabled";function ul(t){return t.find(r=>r.key===Ja)}function ml(t){return t.notifyTarget==="chat"||t.notifyTarget==="user"||Ga.test(t.key)}function Qt(t){return t.filter(r=>r.notifyTarget==="chat"||r.notifyTarget==="user")}function xl(t){return t.filter(r=>!r.notifyTarget&&!r.secret&&r.key!==Ja&&Ga.test(r.key))}function gl(t){return t.filter(ml)}function Ya(t){return Qt(t).find(r=>r.notifyTarget==="chat")}function fl(t,r){const n=Qt(t);return n.length===0?"unsupported":n.some(a=>!As(a,r[a.key]))?"configured":"not-configured"}function ra(t){return typeof t=="string"?{value:t,label:t}:{value:t.value,label:t.label??t.value,hint:t.hint}}function na(t,r,n){const a=t.label.toLowerCase(),o=t.value.toLowerCase(),s=`${a} ${o} ${(t.hint??"").toLowerCase()}`;for(const c of r)if(!s.includes(c))return null;if(a.startsWith(n)||o.startsWith(n))return 0;const d=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[\\s./:_-])${d}`).test(a)?1:2}function Qa({value:t,options:r,onChange:n,placeholder:a,filterPlaceholder:o,emptyText:s,customHint:d,disabled:c,ariaLabel:u,className:h}){const[x,v]=i.useState(!1),[j,k]=i.useState(""),[P,N]=i.useState(!1),[y,b]=i.useState(-1),A=i.useRef(null),m=i.useRef(null),w=i.useRef(null),V=i.useRef(null),T=i.useId(),[I,F]=i.useState({}),C=i.useMemo(()=>t?r.map(ra).find(_=>_.value===t)?.label??t:a??"",[t,r,a]);i.useEffect(()=>{x||(k(C),N(!1))},[C,x]),i.useEffect(()=>{function _(H){const X=H.target;V.current?.contains(X)||A.current&&!A.current.contains(X)&&v(!1)}return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);function $(){const _=m.current;if(!_)return;const H=_.getBoundingClientRect(),X=Math.max(H.width,240),me=window.innerHeight-H.bottom-8,ie=me<180&&H.top>me;F({position:"fixed",left:H.left,width:X,maxHeight:Math.min(260,ie?Math.max(H.top-12,120):me),...ie?{bottom:window.innerHeight-H.top+4}:{top:H.bottom+4}})}i.useLayoutEffect(()=>{if(!x)return;$();const _=()=>$();return window.addEventListener("scroll",_,!0),window.addEventListener("resize",_),()=>{window.removeEventListener("scroll",_,!0),window.removeEventListener("resize",_)}},[x]);const D=i.useMemo(()=>{const _=r.map(ra),H=j.trim(),X=P?H.toLowerCase().split(/\s+/).filter(Boolean):[],me=[];_.forEach((f,R)=>{const p=X.length?na(f,X,H.toLowerCase()):0;p!==null&&me.push({row:f,score:p,idx:R})}),me.sort((f,R)=>f.score-R.score||f.idx-R.idx);const ie=[];if(a!==void 0){const f={value:"",label:a};(X.length?na(f,X,H.toLowerCase()):0)!==null&&ie.push(f)}ie.push(...me.map(f=>f.row));const ee=H&&!_.some(f=>f.value.toLowerCase()===H.toLowerCase());return d&&P&&ee&&ie.push({value:H,label:H,custom:!0}),ie},[r,j,P,a,d]);i.useEffect(()=>{if(!x||y<0||!w.current)return;w.current.querySelector(`[data-index="${y}"]`)?.scrollIntoView({block:"nearest"})},[y,x,D.length]);function B(){c||(k(C),N(!1),b(D.findIndex(_=>_.value===t)),v(!0),requestAnimationFrame(()=>m.current?.select()))}function S(){v(!1),k(C),N(!1),b(-1)}function L(_){n(_.value),v(!1),k(_.value?_.label:a??""),N(!1),b(-1),m.current?.focus()}function J(_){if(_.key==="ArrowDown"||_.key==="ArrowUp"){if(_.preventDefault(),!x){B();return}b(H=>{const X=_.key==="ArrowDown"?H+1:H-1;return Math.max(-1,Math.min(X,D.length-1))});return}if(_.key==="Enter"){if(!x){_.preventDefault(),B();return}const H=D[y];H?(_.preventDefault(),L(H)):S();return}if(_.key==="Escape"&&x){_.preventDefault(),_.stopPropagation(),S();return}_.key==="Tab"&&x&&S()}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?T:void 0,"aria-autocomplete":"list","aria-label":u,"aria-activedescendant":x&&y>=0?`${T}-opt-${y}`:void 0,disabled:c,value:x?j:C,placeholder:o,onMouseDown:()=>{x?v(!1):B()},onChange:_=>{x||v(!0),k(_.target.value),N(!0),b(0)},onKeyDown:J,onBlur:()=>{x&&S()},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&&Go.createPortal(e.jsxs("div",{id:T,role:"listbox",ref:_=>{w.current=_,V.current=_},style:I,onMouseDown:_=>_.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:[D.map((_,H)=>e.jsxs("div",{id:`${T}-opt-${H}`,"data-index":H,role:"option","aria-selected":_.value===t,onMouseDown:X=>{X.preventDefault(),L(_)},className:`px-3 py-1.5 text-xs cursor-pointer flex items-center gap-2 ${H===y?"bg-brand-500/20":_.value===t?"bg-surface-overlay":"hover:bg-surface-overlay/50"}`,children:[e.jsx("span",{className:`flex-1 truncate ${_.custom?"text-brand-500":"text-fg-primary"}`,children:_.label}),_.hint&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:_.hint}),_.custom&&d&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:typeof d=="function"?d(_.value):d})]},`${_.custom?"custom:":""}${_.value}`)),D.length===0&&e.jsx("div",{className:"px-3 py-3 text-xs text-fg-tertiary text-center",children:s})]}),document.body)]})}async function pl(){const{agents:t}=await U.agents.list({lean:!0});return t.map(r=>({id:r.id,name:r.name,role:r.role}))}let vs=null;function Za(){return vs||(vs=pl().catch(t=>{throw vs=null,t})),vs}function hl(t=Za,r=!0){const[n,a]=i.useState([]);return i.useEffect(()=>{if(!r)return;let o=!0;return t().then(s=>{o&&a(s)}).catch(()=>{o&&a([])}),()=>{o=!1}},[t,r]),n}function Ps({value:t,options:r,onChange:n,fieldKey:a,ariaLabel:o,disabled:s}){const{t:d}=ce(["settings"]);return e.jsx(Qa,{value:typeof t=="string"?t:"",options:r.map(c=>({value:c.id,label:c.name,hint:c.role})),onChange:c=>n(a,c),disabled:s,placeholder:d("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),filterPlaceholder:d("settings:integrations.agentSelect.search",{defaultValue:"Search agents…"}),emptyText:d("settings:integrations.agentSelect.empty",{defaultValue:"No matching agent"}),ariaLabel:o??d("settings:integrations.agentSelect.none",{defaultValue:"Not bound"}),className:"w-full"})}function Xa({loading:t,error:r,onReload:n,buttonTestId:a,errorTestId:o,empty:s=!1}){const{t:d}=ce(["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:n,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?d("settings:instances.channels.refreshing",{defaultValue:"Refreshing…"}):s?d("settings:integrations.loadGroups",{defaultValue:"Load groups"}):d("settings:instances.channels.refresh",{defaultValue:"Refresh"})]}),r&&e.jsx("span",{"data-testid":o,className:"text-[11px] text-red-600",children:r})]})}const Ss="rounded-xl border border-border-default bg-surface-secondary p-4",Wt="text-sm font-semibold text-fg-primary",eo="flex flex-wrap items-center justify-between gap-x-4 gap-y-2",bl="flex flex-wrap items-start justify-between gap-x-4 gap-y-2",Gr="shrink-0 text-sm text-fg-secondary",to="flex-1 min-w-[10rem] flex justify-end",Ct="text-xs text-fg-tertiary",Jr="w-full px-3 py-2 text-sm bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500 transition-colors";function Yr(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 yl={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"},vl={verified:"bg-green-500",unverified:"bg-amber-400",off:"bg-gray-400",unconfigured:"bg-gray-400"},jl={verified:"settings:integrations.status.verified",unverified:"settings:integrations.status.unverified",off:"settings:integrations.status.off",unconfigured:"settings:integrations.status.unconfigured"},Nl={verified:"Connected",unverified:"Not verified",off:"Off",unconfigured:"Not configured"};function wl({state:t}){const{t:r}=ce(["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 ${yl[t]}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${vl[t]}`}),r(jl[t],{defaultValue:Nl[t]})]})}function Jt({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 Kt({label:t,control:r,help:n,htmlFor:a,start:o=!1}){return e.jsxs("div",{children:[e.jsxs("div",{className:o?bl:eo,children:[a?e.jsx("label",{htmlFor:a,className:Gr,children:t}):e.jsx("span",{className:Gr,children:t}),e.jsx("div",{className:to,children:r})]}),n?e.jsx("p",{className:`${Ct} mt-1.5`,children:n}):null]})}function kl({field:t,value:r,hasStored:n,onChange:a,platformId:o="",agentOptions:s=[]}){const{t:d}=ce(["settings"]),c=`integration-field-${t.key}`,[u,h]=i.useState(!1),x=i.useMemo(()=>o?Wa(d,o,t):{label:t.label,help:t.help,placeholder:t.placeholder,options:t.options},[d,o,t]),v=x.label,j=x.help,k=x.placeholder,P=x.options??t.options??[],N=e.jsxs(e.Fragment,{children:[v,t.required&&e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),y=t.secret&&n?d("settings:integrations.secretStored"):j||void 0;if(t.type==="boolean"){const m=r===!0;return e.jsx(Kt,{label:v,help:j,control:e.jsx(Ye,{checked:m,onChange:w=>a(t.key,w),label:v,size:"md",testId:`integration-field-${t.key}`})})}if(t.type==="agent")return e.jsx(Kt,{label:N,help:y,control:e.jsx("div",{className:"w-full","data-testid":`integration-field-${t.key}`,children:e.jsx(Ps,{value:r,options:s,onChange:a,fieldKey:t.key,ariaLabel:v})})});if(t.type==="select"&&t.multiple){const m=Array.isArray(r)?r.map(String):[];return e.jsx(Kt,{start:!0,label:N,help:y,control:e.jsx("div",{className:"flex flex-wrap justify-end gap-1.5","data-testid":`integration-field-${t.key}`,children:P.map(w=>{const V=m.includes(w.value);return e.jsx("button",{type:"button","aria-pressed":V,"data-option":w.value,onClick:()=>a(t.key,V?m.filter(T=>T!==w.value):[...m,w.value]),className:Yr(V),children:w.label},w.value)})})})}if(t.type==="select")return e.jsx(Kt,{label:N,help:y,htmlFor:c,control:e.jsx("select",{id:c,"data-testid":`integration-field-${t.key}`,value:typeof r=="string"?r:"",onChange:m=>a(t.key,m.target.value),className:Jr,children:(t.options??[]).map(m=>{const w=P.find(V=>V.value===m.value)?.label??m.label;return e.jsx("option",{value:m.value,children:w},m.value)})})});const b=t.type==="password",A=t.type==="number";return e.jsx(Kt,{label:N,help:y,htmlFor:c,control:e.jsxs("div",{className:"relative w-full",children:[e.jsx("input",{id:c,"data-testid":`integration-field-${t.key}`,type:A?"number":b&&!u?"password":"text",value:r==null?"":String(r),placeholder:b&&n?d("settings:integrations.secretStoredPlaceholder"):k,onChange:m=>a(t.key,m.target.value),className:`${Jr}${b?" font-mono pr-10":""}`}),b&&e.jsx("button",{type:"button","aria-label":u?d("settings:integrations.hide",{defaultValue:"Hide"}):d("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 At({status:t,draft:r,fields:n=t.fields,onChange:a,agentOptions:o=[]}){return e.jsx(e.Fragment,{children:n.map(s=>e.jsx(kl,{field:s,platformId:t.id,value:r[s.key],hasStored:t.secrets[s.key]?.hasValue===!0,agentOptions:o,onChange:a},s.key))})}const aa={pending:"bg-amber-400 animate-pulse",ok:"bg-emerald-500",failed:"bg-red-500"};function oa({label:t,hint:r,leg:n}){const{t:a}=ce("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 ${aa[n.state]??aa.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:n.state==="ok"?n.detail??a("integrations.connectionTest.legOk",{defaultValue:"Verified"}):n.state==="failed"?n.detail??a("integrations.connectionTest.legFailed",{defaultValue:"Failed"}):r})]})]})}function Sl(t,r){const n=new Date(t);return Number.isNaN(n.getTime())?t:n.toLocaleString(r,{dateStyle:"medium",timeStyle:"short"})}function Cl({test:t,starting:r,onStart:n,lastVerifiedAt:a=null}){const{t:o,i18n:s}=ce("settings"),d=(()=>{if(!t)return null;switch(t.status){case"awaiting_reply":return o("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 o("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 o("integrations.connectionTest.verified",{defaultValue:"Both directions work — Markus can send to and receive from this bot."});case"expired":return o("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:o("integrations.connectionTest.title",{defaultValue:"Connection verification"})}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5",children:o("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(oa,{label:o("integrations.connectionTest.outbound",{defaultValue:"Outbound (bot → IM)"}),hint:o("integrations.connectionTest.outboundPending",{defaultValue:"Not sent yet"}),leg:t.outbound}),e.jsx(oa,{label:o("integrations.connectionTest.inbound",{defaultValue:"Inbound (IM → bot)"}),hint:o("integrations.connectionTest.inboundPending",{defaultValue:"Waiting for your reply"}),leg:t.inbound})]}),d&&(t.status==="verified"||t.status==="expired"?e.jsx(Jt,{type:t.status==="verified"?"ok":"err",text:d}):e.jsx("div",{className:"px-3 py-2 rounded-lg text-xs bg-surface-elevated text-fg-secondary",children:d}))]}):a?e.jsx(Jt,{type:"ok",text:o("integrations.connectionTest.lastVerified",{defaultValue:"Verified {{when}}.",when:Sl(a,s.language)})}):e.jsx("div",{className:"text-xs text-fg-tertiary",children:o("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:n,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?o("integrations.connectionTest.retry",{defaultValue:"Verify again"}):o("integrations.connectionTest.start",{defaultValue:"Verify connection"})," "]})]})}function Al({status:t,values:r,setValue:n,channels:a=[],canListChannels:o=!1,channelsLoading:s=!1,channelsError:d=null,onReloadChannels:c=()=>{},channelsGuidance:u=null,testSlot:h}){const{t:x}=ce(["settings","common"]),[v,j]=i.useState(!1),k=Qt(t.fields),P=xl(t.fields),N=ul(t.fields),y=fl(t.fields,r),b=Ya(t.fields),A=N?r[N.key]!==!1:!0,m=o&&b?b.key:null,w=m!==null?String(r[m]??""):"",V={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"})},T={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"},F=x("settings:instances.notify.guidanceFallback",{defaultValue:"This platform can’t list its conversations — enter the destination ID manually."}),C=u?x(u,{defaultValue:F}):F,$=m!==null&&!s&&w!==""&&!a.some(B=>B.id===w),D="text-xs font-medium text-fg-secondary mb-2";return e.jsxs("section",{"data-testid":"notification-panel","data-reachability":y,className:Ss,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[e.jsx("h3",{className:Wt,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 ${T[y]}`,"data-testid":"notification-reachability","data-state":y,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I[y]}`}),V[y]]}),N&&e.jsx(Ye,{checked:A,onChange:B=>n(N.key,B),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:[k.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:D,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(Xa,{loading:s,error:d,onReload:c,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(B=>e.jsx("button",{type:"button","aria-pressed":w===B.id,"data-testid":`notification-chat-pick-${B.id}`,onClick:()=>n(m,B.id),className:Yr(w===B.id),children:B.name},B.id))}),a.length===0&&!s&&!d&&e.jsx("p",{"data-testid":"notification-chat-empty",className:Ct,children:x("settings:instances.notify.pickEmpty",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}),$&&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:()=>n(m,w),className:Yr(!0),children:w})})]}),m===null&&e.jsx("p",{"data-testid":"notification-chat-guidance",className:Ct,children:C}),m!==null?e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button","aria-expanded":v,"data-testid":"notification-manual-toggle",onClick:()=>j(B=>!B),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 ${v?"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"})]}),v&&e.jsx("div",{className:"space-y-4 mt-3","data-testid":"notification-manual-fields",children:e.jsx(At,{status:t,draft:r,fields:k,onChange:n})})]}):e.jsx("div",{className:"mt-2",children:e.jsx(At,{status:t,draft:r,fields:k,onChange:n})})]}),P.length>0&&e.jsxs("div",{"data-testid":"notification-preferences",className:"space-y-3",children:[e.jsx("div",{className:D,children:x("settings:instances.notify.content",{defaultValue:"What to send"})}),e.jsx(At,{status:t,draft:r,fields:P,onChange:n})]}),h]})]})}const St={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"},Pl={color:"#64748b",glyph:e.jsx("g",{...St,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"})})},Ml={feishu:{color:"#3370ff",glyph:e.jsx("g",{...St,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",{...St,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",{...St,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",{...St,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",{...St,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 Tl(t){return Ml[t]??Pl}function so({id:t,size:r=36}){const n=Tl(t);return e.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded-lg",style:{width:r,height:r,backgroundColor:`${n.color}1a`,color:n.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:n.glyph})})}function El({status:t,configured:r,canListChannels:n=!1,channelsGuidance:a=null}){const{t:o,i18n:s}=ce(["settings","common"]),[d,c]=i.useState(!r),u=i.useMemo(()=>{const v=Wi(s,o,t.id);if(Qt(t.fields).length===0)return v;const j=o("settings:integrations.guide.destinationStep.desc",{defaultValue:"Pick the chat or user that should receive approvals and notifications — without it they have nowhere to go."}),k=n?{title:o("settings:integrations.guide.selectChatStep.title",{defaultValue:"Pick the notification group"}),desc:o("settings:integrations.guide.selectChatStep.desc",{defaultValue:"Add the bot to a group in your IM → click “Load groups” → pick it from the list."})}:{title:o("settings:integrations.guide.destinationStep.title",{defaultValue:"Set a notification destination"}),desc:a?o(a,{defaultValue:j}):j};return[...v,k]},[s,o,t.id,t.fields,n,a]),h=qi(t.id),x=o(`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":d?"true":"false",children:[e.jsxs("button",{type:"button",onClick:()=>c(v=>!v),"aria-expanded":d,"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:Gi(o)}),e.jsx("svg",{className:`w-4 h-4 text-fg-tertiary transition-transform ${d?"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"})})]}),d&&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((v,j)=>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:j+1}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-xs font-medium text-fg-primary",children:v.title}),v.desc&&e.jsx("span",{className:"block text-[11px] text-fg-tertiary mt-0.5",children:v.desc})]})]},v.title))}):e.jsx("p",{className:"text-xs text-fg-tertiary",children:o("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:[o("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:o("settings:integrations.docs",{defaultValue:"Setup docs"})})]})]})]})}const ro={create:(t,r)=>U.settings.createInstance(t,r).then(n=>n.instance),save:(t,r)=>U.settings.saveInstance(t,r).then(()=>{}),test:(t,r)=>U.settings.testInstance(t,r),remove:t=>U.settings.deleteInstance(t).then(()=>{}),listChannels:t=>U.settings.listInstanceChannels(t),saveChannels:(t,r)=>U.settings.saveInstanceChannels(t,r).then(()=>{}),startConnectionTest:(t,r)=>U.settings.startConnectionTest(t,r).then(n=>n.test),getConnectionTest:t=>U.settings.getConnectionTest(t).then(r=>r.test)},Rl=700;function ia({instance:t,client:r=ro,extras:n={},onChanged:a,onCreated:o,loadAgents:s,defaultExpanded:d}){const{t:c}=ce(["settings","common"]),u=al(t),[h,x]=i.useState(d??u),[v,j]=i.useState(!1),k=i.useMemo(()=>ea(t),[t]),[P,N]=i.useState(t.label),[y,b]=i.useState(()=>Zn(k)),[A,m]=i.useState(t.enabled),[w,V]=i.useState(t.channels),[T,I]=i.useState(typeof t.notifyAgentId=="string"?t.notifyAgentId:""),[F,C]=i.useState({kind:"idle"}),$=!!n[t.platform]?.guidedSetup,[D,B]=i.useState($&&!t.hasConfig?"guided":"manual"),S=$&&D==="guided",{channels:L,error:J,loading:_,reloadChannels:H}=cl(r.listChannels,t.id,h&&t.canListChannels),[X,me]=i.useState(""),[ie,ee]=i.useState(null),[f,R]=i.useState(!1),[p,K]=i.useState(null),z=tl(ie),[se,ae]=i.useState(!1),ge=t.fields.some(E=>E.type==="agent"),te=hl(i.useMemo(()=>s??Za,[s]),ge),Ze=i.useCallback(E=>E?te.find(ne=>ne.id===E)?.name??E:"",[te]),Me=Xi(k),Pe=i.useRef(t);Pe.current=t;const Be=i.useRef(!1),ct=i.useRef(!1);i.useEffect(()=>{if(Be.current)return;const E=Pe.current;N(E.label),b(Zn(ea(E))),m(E.enabled),V(E.channels),I(typeof E.notifyAgentId=="string"?E.notifyAgentId:"")},[Me]),i.useEffect(()=>{C({kind:"idle"}),ee(null),K(null),gt(!1)},[t.id]),i.useEffect(()=>{B($&&!t.hasConfig?"guided":"manual")},[t.id,t.hasConfig,$]);const Se=i.useCallback(()=>{Be.current=!0,C({kind:"idle"})},[]),fe=i.useCallback((E,ne)=>{Se(),b(ue=>({...ue,[E]:ne}))},[Se]),Zt=i.useCallback(E=>{Se(),N(E)},[Se]),Xe=i.useCallback(E=>{Se(),m(E)},[Se]),Pt=i.useRef(()=>Promise.resolve()),De=i.useCallback(async()=>{if(!ct.current){ct.current=!0,C({kind:"saving"});try{let E=Pe.current.id;E||(E=(await r.create(Pe.current.platform,P.trim())).id),await r.save(E,{...Yi(k,y,A),notifyAgentId:T}),Pe.current.canListChannels&&await r.saveChannels(E,w);let ne=null;try{const{ok:ue,text:He,code:Le}=el(await r.test(E,{}));!ue&&!/not supported/i.test(He)&&(ne=Le==="network_unreachable"?c("settings:integrations.savedNotVerifiedNetwork"):c("settings:integrations.savedNotVerified",{reason:He}))}catch(ue){ne=c("settings:integrations.savedNotVerified",{reason:String(ue)})}Be.current=!1,C(ne?{kind:"error",text:ne}:{kind:"saved"}),await a?.(),Pe.current.id===""&&o?.(E)}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}finally{ct.current=!1}}},[r,k,y,A,T,w,P,c,a,o]);Pt.current=De;const ut=Xn(k.fields,y,t.secrets),Xt=u&&P.trim()==="",es=w.every(E=>E.agentId),et=!S&&!Xt&&ut.length===0&&es,Ie=i.useMemo(()=>JSON.stringify([P,A,T,w,y]),[P,A,T,w,y]);i.useEffect(()=>{if(!Be.current||!et)return;const E=setTimeout(()=>{Pt.current()},Rl);return()=>clearTimeout(E)},[Ie,et]),i.useEffect(()=>{if(!h||u)return;let E=!0;return r.getConnectionTest(t.id).then(ne=>{E&&ne&&ee(ne)}).catch(()=>{}),()=>{E=!1}},[h,u,r,t.id]),i.useEffect(()=>{if(!h||!z)return;let E=!0;const ne=setInterval(()=>{r.getConnectionTest(t.id).then(ue=>{E&&ue&&ee(ue)}).catch(()=>{})},2500);return()=>{E=!1,clearInterval(ne)}},[h,z,r,t.id]);const Mt=i.useRef(null);i.useEffect(()=>{ie?.status==="verified"&&Mt.current!==t.id&&(Mt.current=t.id,a?.())},[ie?.status,t.id,a]);const ts=i.useCallback(async()=>{R(!0),K(null);try{ee(await r.startConnectionTest(t.id))}catch(E){K(E instanceof Error?E.message:String(E))}finally{R(!1)}},[r,t.id]),ye=n[t.platform],Ue=i.useMemo(()=>({platformId:t.platform,instanceId:t.id||void 0,status:k,values:y,setValue:fe,reload:()=>{a?.()},agents:te,onCreated:o,setupMethod:$?D:void 0,setSetupMethod:$?B:void 0}),[t.platform,t.id,k,y,fe,a,te,o,$,D]),ss=i.useMemo(()=>new Set(ye?.ownedFields??[]),[ye]),mt=Qt(k.fields).length>0,rs=i.useMemo(()=>new Set(mt?gl(k.fields).map(E=>E.key):[]),[k.fields,mt]),xt=i.useMemo(()=>k.fields.filter(E=>!ss.has(E.key)&&!rs.has(E.key)),[k.fields,ss,rs]),Tt=i.useMemo(()=>Qi(xt),[xt]),ns=i.useMemo(()=>Zi(xt),[xt]),Ts=i.useMemo(()=>Tt.filter(E=>E.type==="agent"),[Tt]),Et=i.useMemo(()=>Tt.filter(E=>E.type!=="agent"),[Tt]),[Rt,gt]=i.useState(!1),It=i.useMemo(()=>Xn(t.fields,t.values,t.secrets),[t.fields,t.values,t.secrets]),tt=t.hasConfig&&!It.some(E=>Et.some(ne=>ne.key===E)),tn=i.useMemo(()=>il(L,X),[L,X]),as=i.useMemo(()=>ol(w,L),[w,L]),Lt=w.filter(E=>!E.agentId).length,Es=i.useCallback((E,ne)=>{Se(),V(ue=>ne?ta(ue,E.id,hr(ue,E.id)?.agentId??t.agentId??"",E.kind??null):sa(ue,E.id))},[Se,t.agentId]),Te=i.useCallback((E,ne)=>{Se(),V(ue=>ta(ue,E,ne,hr(ue,E)?.kind??null))},[Se]),Rs=i.useCallback(async()=>{ae(!1);try{await r.remove(t.id),await a?.()}catch(E){C({kind:"error",text:E instanceof Error?E.message:String(E)})}},[r,t.id,a]),ft=sl(t,ie?.status==="verified"),re=t.id||`new-${t.platform}`,Ke=`instance-name-${re}`,pt=ut.map(E=>{const ne=k.fields.find(ue=>ue.key===E);return ne?Wa(c,t.platform,ne).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":ft,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(so,{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:P.trim()===""?c("settings:instances.newBot",{defaultValue:"New bot"}):P}),!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:c("settings:instances.boundAgent",{defaultValue:"Bound agent"}),children:[e.jsx("span",{className:"text-fg-muted",children:"→"}),Ze(t.agentId)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2.5 shrink-0",children:[e.jsx(wl,{state:ft}),!u&&e.jsx(Ye,{checked:A,onChange:Xe,size:"md",testId:`instance-enabled-${re}`,label:c("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&&!S&&e.jsx(El,{status:k,configured:t.hasConfig,canListChannels:t.canListChannels,channelsGuidance:t.channelsGuidance??null}),!$&&ye?.placement==="before"&&ye.render(Ue),e.jsxs("section",{"data-testid":`instance-credentials-${re}`,className:Ss,children:[e.jsx("h3",{className:`${Wt} mb-3`,children:t.hasConfig?c("settings:instances.setup.configuredTitle",{defaultValue:"Bot setup"}):$?c("settings:instances.setup.title",{defaultValue:"Connection"}):c("settings:instances.credentials",{defaultValue:"Credentials"})}),$&&!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":D===E,onClick:()=>B(E),"data-testid":`setup-method-${E}-${re}`,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${D===E?"bg-surface-elevated text-fg-primary shadow-sm":"text-fg-tertiary hover:text-fg-secondary"}`,children:E==="guided"?c("settings:instances.setup.guided",{defaultValue:"Scan to create (recommended)"}):c("settings:instances.setup.manual",{defaultValue:"Enter credentials manually"})},E))}),S?e.jsx("div",{className:"space-y-4",children:ye.render(Ue)}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:eo,children:[e.jsxs("label",{htmlFor:Ke,className:Gr,children:[c("settings:instances.addBot.name",{defaultValue:"Bot name"}),e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]}),e.jsx("div",{className:to,children:e.jsx("input",{id:Ke,"data-testid":`new-bot-name-${t.platform}`,value:P,onChange:E=>Zt(E.target.value),placeholder:c("settings:instances.addBot.namePlaceholder",{defaultValue:"e.g. Sales"}),className:Jr})})]}),Ts.length>0&&e.jsx(At,{status:k,draft:y,fields:Ts,onChange:fe,agentOptions:te}),Et.length>0&&(tt&&!Rt?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:"✓"}),c("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>gt(!0),"data-testid":`instance-credentials-edit-${re}`,className:"text-xs text-brand-600 hover:text-brand-700",children:c("settings:instances.credentialsEdit",{defaultValue:"Change"})})]})}):e.jsxs("div",{className:"space-y-3",children:[tt&&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:"✓"}),c("settings:instances.credentialsSet",{defaultValue:"Credentials set"})]}),e.jsx("button",{type:"button",onClick:()=>gt(!1),"data-testid":`instance-credentials-hide-${re}`,className:"text-xs text-brand-600 hover:text-brand-700",children:c("settings:instances.credentialsHide",{defaultValue:"Hide"})})]}),e.jsx(At,{status:k,draft:y,fields:Et,onChange:fe,agentOptions:te})]}))]}),e.jsx("div",{className:"mt-3 min-h-[1.25rem]","data-testid":`instance-save-state-${re}`,children:e.jsxs("span",{"data-state":F.kind,className:"inline-flex items-center gap-2 text-xs text-fg-tertiary",children:[F.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"}),c("settings:instances.autosave.saving",{defaultValue:"Saving…"})]}),F.kind==="saved"&&e.jsxs("span",{className:"text-green-600",children:["✓ ",c("settings:instances.autosave.saved",{defaultValue:"Saved"})]}),!et&&!S&&e.jsx("span",{"data-testid":`instance-missing-${re}`,children:ut.length>0?c("settings:integrations.missingRequired",{defaultValue:"Required: {{fields}}",fields:pt}):c("settings:instances.addBot.labelRequired",{defaultValue:"Give the bot a name."})})]})}),F.kind==="error"&&e.jsx("div",{className:"mt-2",children:e.jsx(Jt,{type:"err",text:F.text})})]}),!u&&e.jsxs("section",{children:[e.jsx(Cl,{test:ie,starting:f,lastVerifiedAt:t.lastVerifiedAt,onStart:()=>{ts()}}),p&&e.jsx("div",{className:"mt-3",children:e.jsx(Jt,{type:"err",text:p})})]}),!u&&mt&&e.jsx(Al,{status:k,values:y,setValue:fe,channels:L,canListChannels:t.canListChannels,channelsLoading:_,channelsError:J,onReloadChannels:H,channelsGuidance:t.channelsGuidance??null,testSlot:ye?.sendTest?.(Ue)}),e.jsxs("section",{"data-testid":`instance-more-${re}`,children:[e.jsxs("button",{type:"button",onClick:()=>j(E=>!E),"aria-expanded":v,"data-testid":`instance-more-toggle-${re}`,className:"w-full flex items-center gap-2 text-left group px-1",children:[e.jsx("span",{className:Wt,children:c("settings:instances.moreSettings",{defaultValue:"Advanced"})}),e.jsx("span",{className:`${Ct} truncate hidden sm:inline`,children:c("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 ${v?"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"})})]}),v&&e.jsxs("div",{className:"mt-3 space-y-4",children:[ns.length>0&&e.jsxs("div",{className:Ss,children:[e.jsx("h4",{className:`${Wt} mb-1`,children:c("settings:instances.advancedTitle",{defaultValue:"Platform options"})}),!u&&e.jsx("p",{className:`${Ct} mb-3`,children:c("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(At,{status:k,draft:y,fields:ns,onChange:fe,agentOptions:te})]}),!u&&e.jsxs("div",{className:Ss,children:[e.jsx("h4",{className:`${Wt} mb-1`,children:c("settings:instances.routing.chats",{defaultValue:"Chat routing"})}),e.jsx("p",{className:`${Ct} mb-3`,children:c("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?c(t.channelsGuidance,{defaultValue:c("settings:instances.routing.unsupported",{defaultValue:"This platform does not let us list its chats."})}):c("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(Xa,{loading:_,error:J,onReload:H,empty:L.length===0,buttonTestId:`instance-chats-refresh-${re}`,errorTestId:`instance-chats-error-${re}`})}),t.canListChannels&&L.length>0&&e.jsx("input",{type:"text",value:X,onChange:E=>me(E.target.value),placeholder:c("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:[tn.map(E=>{const ne=hr(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:!!ne,"data-testid":`instance-chat-toggle-${re}-${E.id}`,onChange:ue=>Es(E,ue.target.checked),className:"rounded border-border-default"}),e.jsx("span",{className:"truncate",title:E.id,children:E.name})]}),ne&&e.jsx("div",{className:"w-56","data-testid":`instance-chat-agent-${re}-${E.id}`,children:e.jsx(Ps,{value:ne.agentId,options:te,onChange:(ue,He)=>Te(E.id,typeof He=="string"?He:""),fieldKey:"agentId",ariaLabel:c("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.id)}),as.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:()=>V(ne=>sa(ne,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(Ps,{value:E.agentId,options:te,onChange:(ne,ue)=>Te(E.nativeId,typeof ue=="string"?ue:""),fieldKey:"agentId",ariaLabel:c("settings:instances.routing.chatAgent",{defaultValue:"Agent for this chat"})})})]},E.nativeId))]}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-2",children:c("settings:instances.routing.autoSaved",{defaultValue:"Changes are saved automatically."})}),Lt>0&&e.jsx("div",{className:"mt-3",children:e.jsx(Jt,{type:"err",text:c("settings:instances.routing.agentRequired",{defaultValue:"Pick an agent for every selected chat ({{count}} still unassigned).",count:Lt})})})]})]})]}),!$&&ye&&ye.placement!=="before"&&ye.render(Ue),!u&&e.jsx("div",{className:"pt-1",children:e.jsx("button",{type:"button",onClick:()=>ae(!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:c("settings:integrations.disconnect",{defaultValue:"Disconnect"})})})]}),se&&e.jsx(Cs,{title:c("settings:integrations.disconnectConfirmTitle",{defaultValue:"Disconnect this bot?"}),message:c("settings:integrations.disconnectConfirmMessage",{defaultValue:"Its stored credentials are removed and it stops sending and receiving messages. This cannot be undone."}),confirmLabel:c("settings:integrations.disconnect",{defaultValue:"Disconnect"}),variant:"danger",onConfirm:()=>{Rs()},onCancel:()=>ae(!1)})]})}var Nt={},br,la;function Il(){return la||(la=1,br=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),br}var yr={},Ge={},da;function lt(){if(da)return Ge;da=1;let t;const r=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ge.getSymbolSize=function(a){if(!a)throw new Error('"version" cannot be null or undefined');if(a<1||a>40)throw new Error('"version" should be in range from 1 to 40');return a*4+17},Ge.getSymbolTotalCodewords=function(a){return r[a]},Ge.getBCHDigit=function(n){let a=0;for(;n!==0;)a++,n>>>=1;return a},Ge.setToSJISFunction=function(a){if(typeof a!="function")throw new Error('"toSJISFunc" is not a valid function.');t=a},Ge.isKanjiModeEnabled=function(){return typeof t<"u"},Ge.toSJIS=function(a){return t(a)},Ge}var vr={},ca;function en(){return ca||(ca=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function r(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.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: "+n)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,o){if(t.isValid(a))return a;try{return r(a)}catch{return o}}})(vr)),vr}var jr,ua;function Ll(){if(ua)return jr;ua=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(r){const n=Math.floor(r/8);return(this.buffer[n]>>>7-r%8&1)===1},put:function(r,n){for(let a=0;a<n;a++)this.putBit((r>>>n-a-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),r&&(this.buffer[n]|=128>>>this.length%8),this.length++}},jr=t,jr}var Nr,ma;function Ol(){if(ma)return Nr;ma=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,n,a,o){const s=r*this.size+n;this.data[s]=a,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(r,n){return this.data[r*this.size+n]},t.prototype.xor=function(r,n,a){this.data[r*this.size+n]^=a},t.prototype.isReserved=function(r,n){return this.reservedBit[r*this.size+n]},Nr=t,Nr}var wr={},xa;function $l(){return xa||(xa=1,(function(t){const r=lt().getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const o=Math.floor(a/7)+2,s=r(a),d=s===145?26:Math.ceil((s-13)/(2*o-2))*2,c=[s-7];for(let u=1;u<o-1;u++)c[u]=c[u-1]-d;return c.push(6),c.reverse()},t.getPositions=function(a){const o=[],s=t.getRowColCoords(a),d=s.length;for(let c=0;c<d;c++)for(let u=0;u<d;u++)c===0&&u===0||c===0&&u===d-1||c===d-1&&u===0||o.push([s[c],s[u]]);return o}})(wr)),wr}var kr={},ga;function Bl(){if(ga)return kr;ga=1;const t=lt().getSymbolSize,r=7;return kr.getPositions=function(a){const o=t(a);return[[0,0],[o-r,0],[0,o-r]]},kr}var Sr={},fa;function Dl(){return fa||(fa=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(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let d=0,c=0,u=0,h=null,x=null;for(let v=0;v<s;v++){c=u=0,h=x=null;for(let j=0;j<s;j++){let k=o.get(v,j);k===h?c++:(c>=5&&(d+=r.N1+(c-5)),h=k,c=1),k=o.get(j,v),k===x?u++:(u>=5&&(d+=r.N1+(u-5)),x=k,u=1)}c>=5&&(d+=r.N1+(c-5)),u>=5&&(d+=r.N1+(u-5))}return d},t.getPenaltyN2=function(o){const s=o.size;let d=0;for(let c=0;c<s-1;c++)for(let u=0;u<s-1;u++){const h=o.get(c,u)+o.get(c,u+1)+o.get(c+1,u)+o.get(c+1,u+1);(h===4||h===0)&&d++}return d*r.N2},t.getPenaltyN3=function(o){const s=o.size;let d=0,c=0,u=0;for(let h=0;h<s;h++){c=u=0;for(let x=0;x<s;x++)c=c<<1&2047|o.get(h,x),x>=10&&(c===1488||c===93)&&d++,u=u<<1&2047|o.get(x,h),x>=10&&(u===1488||u===93)&&d++}return d*r.N3},t.getPenaltyN4=function(o){let s=0;const d=o.data.length;for(let u=0;u<d;u++)s+=o.data[u];return Math.abs(Math.ceil(s*100/d/5)-10)*r.N4};function n(a,o,s){switch(a){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(o,s){const d=s.size;for(let c=0;c<d;c++)for(let u=0;u<d;u++)s.isReserved(u,c)||s.xor(u,c,n(o,u,c))},t.getBestMask=function(o,s){const d=Object.keys(t.Patterns).length;let c=0,u=1/0;for(let h=0;h<d;h++){s(h),t.applyMask(h,o);const x=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(h,o),x<u&&(u=x,c=h)}return c}})(Sr)),Sr}var js={},pa;function no(){if(pa)return js;pa=1;const t=en(),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],n=[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 js.getBlocksCount=function(o,s){switch(s){case t.L:return r[(o-1)*4+0];case t.M:return r[(o-1)*4+1];case t.Q:return r[(o-1)*4+2];case t.H:return r[(o-1)*4+3];default:return}},js.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},js}var Cr={},Ht={},ha;function Vl(){if(ha)return Ht;ha=1;const t=new Uint8Array(512),r=new Uint8Array(256);return(function(){let a=1;for(let o=0;o<255;o++)t[o]=a,r[a]=o,a<<=1,a&256&&(a^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Ht.log=function(a){if(a<1)throw new Error("log("+a+")");return r[a]},Ht.exp=function(a){return t[a]},Ht.mul=function(a,o){return a===0||o===0?0:t[r[a]+r[o]]},Ht}var ba;function _l(){return ba||(ba=1,(function(t){const r=Vl();t.mul=function(a,o){const s=new Uint8Array(a.length+o.length-1);for(let d=0;d<a.length;d++)for(let c=0;c<o.length;c++)s[d+c]^=r.mul(a[d],o[c]);return s},t.mod=function(a,o){let s=new Uint8Array(a);for(;s.length-o.length>=0;){const d=s[0];for(let u=0;u<o.length;u++)s[u]^=r.mul(o[u],d);let c=0;for(;c<s.length&&s[c]===0;)c++;s=s.slice(c)}return s},t.generateECPolynomial=function(a){let o=new Uint8Array([1]);for(let s=0;s<a;s++)o=t.mul(o,new Uint8Array([1,r.exp(s)]));return o}})(Cr)),Cr}var Ar,ya;function Fl(){if(ya)return Ar;ya=1;const t=_l();function r(n){this.genPoly=void 0,this.degree=n,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 o=new Uint8Array(a.length+this.degree);o.set(a);const s=t.mod(o,this.genPoly),d=this.degree-s.length;if(d>0){const c=new Uint8Array(this.degree);return c.set(s,d),c}return s},Ar=r,Ar}var Pr={},Mr={},Tr={},va;function ao(){return va||(va=1,Tr.isValid=function(r){return!isNaN(r)&&r>=1&&r<=40}),Tr}var $e={},ja;function oo(){if(ja)return $e;ja=1;const t="[0-9]+",r="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const a="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
2
+ ]))+`;$e.KANJI=new RegExp(n,"g"),$e.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),$e.BYTE=new RegExp(a,"g"),$e.NUMERIC=new RegExp(t,"g"),$e.ALPHANUMERIC=new RegExp(r,"g");const o=new RegExp("^"+n+"$"),s=new RegExp("^"+t+"$"),d=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return $e.testKanji=function(u){return o.test(u)},$e.testNumeric=function(u){return s.test(u)},$e.testAlphanumeric=function(u){return d.test(u)},$e}var Na;function dt(){return Na||(Na=1,(function(t){const r=ao(),n=oo();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,d){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!r.isValid(d))throw new Error("Invalid version: "+d);return d>=1&&d<10?s.ccBits[0]:d<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return n.testNumeric(s)?t.NUMERIC:n.testAlphanumeric(s)?t.ALPHANUMERIC:n.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(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.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: "+o)}}t.from=function(s,d){if(t.isValid(s))return s;try{return a(s)}catch{return d}}})(Mr)),Mr}var wa;function Ul(){return wa||(wa=1,(function(t){const r=lt(),n=no(),a=en(),o=dt(),s=ao(),d=7973,c=r.getBCHDigit(d);function u(j,k,P){for(let N=1;N<=40;N++)if(k<=t.getCapacity(N,P,j))return N}function h(j,k){return o.getCharCountIndicator(j,k)+4}function x(j,k){let P=0;return j.forEach(function(N){const y=h(N.mode,k);P+=y+N.getBitsLength()}),P}function v(j,k){for(let P=1;P<=40;P++)if(x(j,P)<=t.getCapacity(P,k,o.MIXED))return P}t.from=function(k,P){return s.isValid(k)?parseInt(k,10):P},t.getCapacity=function(k,P,N){if(!s.isValid(k))throw new Error("Invalid QR Code version");typeof N>"u"&&(N=o.BYTE);const y=r.getSymbolTotalCodewords(k),b=n.getTotalCodewordsCount(k,P),A=(y-b)*8;if(N===o.MIXED)return A;const m=A-h(N,k);switch(N){case o.NUMERIC:return Math.floor(m/10*3);case o.ALPHANUMERIC:return Math.floor(m/11*2);case o.KANJI:return Math.floor(m/13);case o.BYTE:default:return Math.floor(m/8)}},t.getBestVersionForData=function(k,P){let N;const y=a.from(P,a.M);if(Array.isArray(k)){if(k.length>1)return v(k,y);if(k.length===0)return 1;N=k[0]}else N=k;return u(N.mode,N.getLength(),y)},t.getEncodedBits=function(k){if(!s.isValid(k)||k<7)throw new Error("Invalid QR Code version");let P=k<<12;for(;r.getBCHDigit(P)-c>=0;)P^=d<<r.getBCHDigit(P)-c;return k<<12|P}})(Pr)),Pr}var Er={},ka;function Kl(){if(ka)return Er;ka=1;const t=lt(),r=1335,n=21522,a=t.getBCHDigit(r);return Er.getEncodedBits=function(s,d){const c=s.bit<<3|d;let u=c<<10;for(;t.getBCHDigit(u)-a>=0;)u^=r<<t.getBCHDigit(u)-a;return(c<<10|u)^n},Er}var Rr={},Ir,Sa;function Hl(){if(Sa)return Ir;Sa=1;const t=dt();function r(n){this.mode=t.NUMERIC,this.data=n.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 o,s,d;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),d=parseInt(s,10),a.put(d,10);const c=this.data.length-o;c>0&&(s=this.data.substr(o),d=parseInt(s,10),a.put(d,c*3+1))},Ir=r,Ir}var Lr,Ca;function ql(){if(Ca)return Lr;Ca=1;const t=dt(),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 n(a){this.mode=t.ALPHANUMERIC,this.data=a}return n.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let d=r.indexOf(this.data[s])*45;d+=r.indexOf(this.data[s+1]),o.put(d,11)}this.data.length%2&&o.put(r.indexOf(this.data[s]),6)},Lr=n,Lr}var Or,Aa;function zl(){if(Aa)return Or;Aa=1;const t=dt();function r(n){this.mode=t.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}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(n){for(let a=0,o=this.data.length;a<o;a++)n.put(this.data[a],8)},Or=r,Or}var $r,Pa;function Wl(){if(Pa)return $r;Pa=1;const t=dt(),r=lt();function n(a){this.mode=t.KANJI,this.data=a}return n.getBitsLength=function(o){return o*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(a){let o;for(o=0;o<this.data.length;o++){let s=r.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
3
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),a.put(s,13)}},$r=n,$r}var Br={exports:{}},Ma;function Gl(){return Ma||(Ma=1,(function(t){var r={single_source_shortest_paths:function(n,a,o){var s={},d={};d[a]=0;var c=r.PriorityQueue.make();c.push(a,0);for(var u,h,x,v,j,k,P,N,y;!c.empty();){u=c.pop(),h=u.value,v=u.cost,j=n[h]||{};for(x in j)j.hasOwnProperty(x)&&(k=j[x],P=v+k,N=d[x],y=typeof d[x]>"u",(y||N>P)&&(d[x]=P,c.push(x,P),s[x]=h))}if(typeof o<"u"&&typeof d[o]>"u"){var b=["Could not find a path from ",a," to ",o,"."].join("");throw new Error(b)}return s},extract_shortest_path_from_predecessor_list:function(n,a){for(var o=[],s=a;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,a,o){var s=r.single_source_shortest_paths(n,a,o);return r.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var a=r.PriorityQueue,o={},s;n=n||{};for(s in a)a.hasOwnProperty(s)&&(o[s]=a[s]);return o.queue=[],o.sorter=n.sorter||a.default_sorter,o},default_sorter:function(n,a){return n.cost-a.cost},push:function(n,a){var o={value:n,cost:a};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=r})(Br)),Br.exports}var Ta;function Jl(){return Ta||(Ta=1,(function(t){const r=dt(),n=Hl(),a=ql(),o=zl(),s=Wl(),d=oo(),c=lt(),u=Gl();function h(b){return unescape(encodeURIComponent(b)).length}function x(b,A,m){const w=[];let V;for(;(V=b.exec(m))!==null;)w.push({data:V[0],index:V.index,mode:A,length:V[0].length});return w}function v(b){const A=x(d.NUMERIC,r.NUMERIC,b),m=x(d.ALPHANUMERIC,r.ALPHANUMERIC,b);let w,V;return c.isKanjiModeEnabled()?(w=x(d.BYTE,r.BYTE,b),V=x(d.KANJI,r.KANJI,b)):(w=x(d.BYTE_KANJI,r.BYTE,b),V=[]),A.concat(m,w,V).sort(function(I,F){return I.index-F.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function j(b,A){switch(A){case r.NUMERIC:return n.getBitsLength(b);case r.ALPHANUMERIC:return a.getBitsLength(b);case r.KANJI:return s.getBitsLength(b);case r.BYTE:return o.getBitsLength(b)}}function k(b){return b.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 P(b){const A=[];for(let m=0;m<b.length;m++){const w=b[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(b,A){const m={},w={start:{}};let V=["start"];for(let T=0;T<b.length;T++){const I=b[T],F=[];for(let C=0;C<I.length;C++){const $=I[C],D=""+T+C;F.push(D),m[D]={node:$,lastCount:0},w[D]={};for(let B=0;B<V.length;B++){const S=V[B];m[S]&&m[S].node.mode===$.mode?(w[S][D]=j(m[S].lastCount+$.length,$.mode)-j(m[S].lastCount,$.mode),m[S].lastCount+=$.length):(m[S]&&(m[S].lastCount=$.length),w[S][D]=j($.length,$.mode)+4+r.getCharCountIndicator($.mode,A))}}V=F}for(let T=0;T<V.length;T++)w[V[T]].end=0;return{map:w,table:m}}function y(b,A){let m;const w=r.getBestModeForData(b);if(m=r.from(A,w),m!==r.BYTE&&m.bit<w.bit)throw new Error('"'+b+'" cannot be encoded with mode '+r.toString(m)+`.
4
+ Suggested mode is: `+r.toString(w));switch(m===r.KANJI&&!c.isKanjiModeEnabled()&&(m=r.BYTE),m){case r.NUMERIC:return new n(b);case r.ALPHANUMERIC:return new a(b);case r.KANJI:return new s(b);case r.BYTE:return new o(b)}}t.fromArray=function(A){return A.reduce(function(m,w){return typeof w=="string"?m.push(y(w,null)):w.data&&m.push(y(w.data,w.mode)),m},[])},t.fromString=function(A,m){const w=v(A,c.isKanjiModeEnabled()),V=P(w),T=N(V,m),I=u.find_path(T.map,"start","end"),F=[];for(let C=1;C<I.length-1;C++)F.push(T.table[I[C]].node);return t.fromArray(k(F))},t.rawSplit=function(A){return t.fromArray(v(A,c.isKanjiModeEnabled()))}})(Rr)),Rr}var Ea;function Yl(){if(Ea)return yr;Ea=1;const t=lt(),r=en(),n=Ll(),a=Ol(),o=$l(),s=Bl(),d=Dl(),c=no(),u=Fl(),h=Ul(),x=Kl(),v=dt(),j=Jl();function k(T,I){const F=T.size,C=s.getPositions(I);for(let $=0;$<C.length;$++){const D=C[$][0],B=C[$][1];for(let S=-1;S<=7;S++)if(!(D+S<=-1||F<=D+S))for(let L=-1;L<=7;L++)B+L<=-1||F<=B+L||(S>=0&&S<=6&&(L===0||L===6)||L>=0&&L<=6&&(S===0||S===6)||S>=2&&S<=4&&L>=2&&L<=4?T.set(D+S,B+L,!0,!0):T.set(D+S,B+L,!1,!0))}}function P(T){const I=T.size;for(let F=8;F<I-8;F++){const C=F%2===0;T.set(F,6,C,!0),T.set(6,F,C,!0)}}function N(T,I){const F=o.getPositions(I);for(let C=0;C<F.length;C++){const $=F[C][0],D=F[C][1];for(let B=-2;B<=2;B++)for(let S=-2;S<=2;S++)B===-2||B===2||S===-2||S===2||B===0&&S===0?T.set($+B,D+S,!0,!0):T.set($+B,D+S,!1,!0)}}function y(T,I){const F=T.size,C=h.getEncodedBits(I);let $,D,B;for(let S=0;S<18;S++)$=Math.floor(S/3),D=S%3+F-8-3,B=(C>>S&1)===1,T.set($,D,B,!0),T.set(D,$,B,!0)}function b(T,I,F){const C=T.size,$=x.getEncodedBits(I,F);let D,B;for(D=0;D<15;D++)B=($>>D&1)===1,D<6?T.set(D,8,B,!0):D<8?T.set(D+1,8,B,!0):T.set(C-15+D,8,B,!0),D<8?T.set(8,C-D-1,B,!0):D<9?T.set(8,15-D-1+1,B,!0):T.set(8,15-D-1,B,!0);T.set(C-8,8,1,!0)}function A(T,I){const F=T.size;let C=-1,$=F-1,D=7,B=0;for(let S=F-1;S>0;S-=2)for(S===6&&S--;;){for(let L=0;L<2;L++)if(!T.isReserved($,S-L)){let J=!1;B<I.length&&(J=(I[B]>>>D&1)===1),T.set($,S-L,J),D--,D===-1&&(B++,D=7)}if($+=C,$<0||F<=$){$-=C,C=-C;break}}}function m(T,I,F){const C=new n;F.forEach(function(L){C.put(L.mode.bit,4),C.put(L.getLength(),v.getCharCountIndicator(L.mode,T)),L.write(C)});const $=t.getSymbolTotalCodewords(T),D=c.getTotalCodewordsCount(T,I),B=($-D)*8;for(C.getLengthInBits()+4<=B&&C.put(0,4);C.getLengthInBits()%8!==0;)C.putBit(0);const S=(B-C.getLengthInBits())/8;for(let L=0;L<S;L++)C.put(L%2?17:236,8);return w(C,T,I)}function w(T,I,F){const C=t.getSymbolTotalCodewords(I),$=c.getTotalCodewordsCount(I,F),D=C-$,B=c.getBlocksCount(I,F),S=C%B,L=B-S,J=Math.floor(C/B),_=Math.floor(D/B),H=_+1,X=J-_,me=new u(X);let ie=0;const ee=new Array(B),f=new Array(B);let R=0;const p=new Uint8Array(T.buffer);for(let ge=0;ge<B;ge++){const te=ge<L?_:H;ee[ge]=p.slice(ie,ie+te),f[ge]=me.encode(ee[ge]),ie+=te,R=Math.max(R,te)}const K=new Uint8Array(C);let z=0,se,ae;for(se=0;se<R;se++)for(ae=0;ae<B;ae++)se<ee[ae].length&&(K[z++]=ee[ae][se]);for(se=0;se<X;se++)for(ae=0;ae<B;ae++)K[z++]=f[ae][se];return K}function V(T,I,F,C){let $;if(Array.isArray(T))$=j.fromArray(T);else if(typeof T=="string"){let J=I;if(!J){const _=j.rawSplit(T);J=h.getBestVersionForData(_,F)}$=j.fromString(T,J||40)}else throw new Error("Invalid data");const D=h.getBestVersionForData($,F);if(!D)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=D;else if(I<D)throw new Error(`
5
+ The chosen QR Code version cannot contain this amount of data.
6
+ Minimum version required to store current data is: `+D+`.
7
+ `);const B=m(I,F,$),S=t.getSymbolSize(I),L=new a(S);return k(L,I),P(L),N(L,I),b(L,F,0),I>=7&&y(L,I),A(L,B),isNaN(C)&&(C=d.getBestMask(L,b.bind(null,L,F))),d.applyMask(C,L),b(L,F,C),{modules:L,version:I,errorCorrectionLevel:F,maskPattern:C,segments:$}}return yr.create=function(I,F){if(typeof I>"u"||I==="")throw new Error("No input text");let C=r.M,$,D;return typeof F<"u"&&(C=r.from(F.errorCorrectionLevel,r.M),$=h.from(F.version),D=d.from(F.maskPattern),F.toSJISFunc&&t.setToSJISFunction(F.toSJISFunc)),V(I,$,C,D)},yr}var Dr={},Vr={},Ra;function io(){return Ra||(Ra=1,(function(t){function r(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let a=n.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+n);(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 o=parseInt(a.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const o=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,d=a.scale||4;return{width:s,scale:s?4:d,margin:o,color:{dark:r(a.color.dark||"#000000ff"),light:r(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,o){return o.width&&o.width>=a+o.margin*2?o.width/(a+o.margin*2):o.scale},t.getImageWidth=function(a,o){const s=t.getScale(a,o);return Math.floor((a+o.margin*2)*s)},t.qrToImageData=function(a,o,s){const d=o.modules.size,c=o.modules.data,u=t.getScale(d,s),h=Math.floor((d+s.margin*2)*u),x=s.margin*u,v=[s.color.light,s.color.dark];for(let j=0;j<h;j++)for(let k=0;k<h;k++){let P=(j*h+k)*4,N=s.color.light;if(j>=x&&k>=x&&j<h-x&&k<h-x){const y=Math.floor((j-x)/u),b=Math.floor((k-x)/u);N=v[c[y*d+b]?1:0]}a[P++]=N.r,a[P++]=N.g,a[P++]=N.b,a[P]=N.a}}})(Vr)),Vr}var Ia;function Ql(){return Ia||(Ia=1,(function(t){const r=io();function n(o,s,d){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=d,s.width=d,s.style.height=d+"px",s.style.width=d+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,d,c){let u=c,h=d;typeof u>"u"&&(!d||!d.getContext)&&(u=d,d=void 0),d||(h=a()),u=r.getOptions(u);const x=r.getImageWidth(s.modules.size,u),v=h.getContext("2d"),j=v.createImageData(x,x);return r.qrToImageData(j.data,s,u),n(v,h,x),v.putImageData(j,0,0),h},t.renderToDataURL=function(s,d,c){let u=c;typeof u>"u"&&(!d||!d.getContext)&&(u=d,d=void 0),u||(u={});const h=t.render(s,d,u),x=u.type||"image/png",v=u.rendererOpts||{};return h.toDataURL(x,v.quality)}})(Dr)),Dr}var _r={},La;function Zl(){if(La)return _r;La=1;const t=io();function r(o,s){const d=o.a/255,c=s+'="'+o.hex+'"';return d<1?c+" "+s+'-opacity="'+d.toFixed(2).slice(1)+'"':c}function n(o,s,d){let c=o+s;return typeof d<"u"&&(c+=" "+d),c}function a(o,s,d){let c="",u=0,h=!1,x=0;for(let v=0;v<o.length;v++){const j=Math.floor(v%s),k=Math.floor(v/s);!j&&!h&&(h=!0),o[v]?(x++,v>0&&j>0&&o[v-1]||(c+=h?n("M",j+d,.5+k+d):n("m",u,0),u=0,h=!1),j+1<s&&o[v+1]||(c+=n("h",x),x=0)):u++}return c}return _r.render=function(s,d,c){const u=t.getOptions(d),h=s.modules.size,x=s.modules.data,v=h+u.margin*2,j=u.color.light.a?"<path "+r(u.color.light,"fill")+' d="M0 0h'+v+"v"+v+'H0z"/>':"",k="<path "+r(u.color.dark,"stroke")+' d="'+a(x,h,u.margin)+'"/>',P='viewBox="0 0 '+v+" "+v+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(u.width?'width="'+u.width+'" height="'+u.width+'" ':"")+P+' shape-rendering="crispEdges">'+j+k+`</svg>
8
+ `;return typeof c=="function"&&c(null,y),y},_r}var Oa;function Xl(){if(Oa)return Nt;Oa=1;const t=Il(),r=Yl(),n=Ql(),a=Zl();function o(s,d,c,u,h){const x=[].slice.call(arguments,1),v=x.length,j=typeof x[v-1]=="function";if(!j&&!t())throw new Error("Callback required as last argument");if(j){if(v<2)throw new Error("Too few arguments provided");v===2?(h=c,c=d,d=u=void 0):v===3&&(d.getContext&&typeof h>"u"?(h=u,u=void 0):(h=u,u=c,c=d,d=void 0))}else{if(v<1)throw new Error("Too few arguments provided");return v===1?(c=d,d=u=void 0):v===2&&!d.getContext&&(u=c,c=d,d=void 0),new Promise(function(k,P){try{const N=r.create(c,u);k(s(N,d,u))}catch(N){P(N)}})}try{const k=r.create(c,u);h(null,s(k,d,u))}catch(k){h(k)}}return Nt.create=r.create,Nt.toCanvas=o.bind(null,n.render),Nt.toDataURL=o.bind(null,n.renderToDataURL),Nt.toString=o.bind(null,function(s,d,c){return a.render(s,c)}),Nt}var lo=Xl();const co=Jo(lo),ed=Si({__proto__:null,default:co},[lo]);function td({ctx:t}){const{t:r}=ce(["settings","common"]),{values:n,reload:a,onCreated:o,agents:s=[]}=t,[d,c]=i.useState(null),[u,h]=i.useState("idle"),[x,v]=i.useState(null),[j,k]=i.useState(()=>String(n.agentId??"")),P=i.useRef(null),N=u!=="idle";i.useEffect(()=>()=>{P.current&&clearInterval(P.current)},[]);const y=i.useCallback(()=>{P.current&&(clearInterval(P.current),P.current=null)},[]),b=i.useCallback(async()=>{h("waiting_qr"),v(null),c(null),P.current=setInterval(async()=>{try{const m=await U.settings.getFeishuRegisterStatus();if(m.active&&m.url){h("scanning");try{v(await co.toDataURL(m.url,{width:192,margin:2,color:{dark:"#000000",light:"#ffffff"}}))}catch{}}}catch{}},1e3);try{const m=await U.settings.registerFeishuApp({agentId:j||void 0});y(),m.success&&m.appId?(h("done"),c({type:"ok",text:r("settings:feishu.registerSuccess",{defaultValue:"App created successfully! Integration is now active."})}),await a(),m.instanceId&&o?.(m.instanceId)):(h("error"),c({type:"err",text:m.message??r("settings:feishu.registerFailed",{defaultValue:"Registration failed"})}))}catch(m){y(),h("error"),c({type:"err",text:m instanceof Error?m.message:String(m)})}},[a,o,j,r,y]),A=i.useCallback(()=>{y(),h("idle"),v(null),c(null)},[y]);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(Ps,{value:j,options:s,onChange:(m,w)=>k(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:b,disabled:!j||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:r("settings:feishu.qrAlt"),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"})})]}),d&&e.jsx("div",{"data-testid":d.type==="ok"?"feishu-msg-ok":"feishu-msg-err",className:`px-3 py-2 rounded-lg text-xs ${d.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:d.text})]})}function sd({ctx:t}){const{t:r}=ce(["settings","common"]),[n,a]=i.useState(!1),[o,s]=i.useState(null),d=Ya(t.status.fields),c=String(d?t.values[d.key]??"":"").trim(),u=t.instanceId,h=i.useCallback(async()=>{if(!c){s({type:"err",text:r("settings:feishu.chatIdRequired",{defaultValue:"Please select a group chat first"})});return}a(!0),s(null);try{const x=await U.settings.sendFeishuTestMessage({chatId:c,...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)}},[c,u,r]);return e.jsxs("div",{className:"space-y-2","data-testid":"feishu-test",children:[e.jsxs("button",{type:"button",onClick:h,disabled:n,"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:[n?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"})]}),o&&e.jsx("div",{"data-testid":o.type==="ok"?"feishu-msg-ok":"feishu-msg-err",className:`px-3 py-2 rounded-lg text-xs ${o.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:o.text})]})}const rd={feishu:{placement:"before",guidedSetup:{credentialFields:["appId","appSecret"]},render:t=>e.jsx(td,{ctx:t}),sendTest:t=>e.jsx(sd,{ctx:t})}};async function nd(){return(await U.settings.listInstances()).instances??[]}async function ad(){return(await U.settings.listIntegrations()).platforms??[]}function od({loadPlatforms:t=ad,loadInstances:r=nd,client:n=ro,extras:a=rd,loadAgents:o,devMode:s=!1,defaultExpanded:d=!1}){const{t:c}=ce(["settings","common"]),[u,h]=i.useState([]),[x,v]=i.useState([]),[j,k]=i.useState(!0),[P,N]=i.useState(null),[y,b]=i.useState(null),[A,m]=i.useState(null),w=i.useCallback(async()=>{const[C,$]=await Promise.all([r(),t()]);h(C),v($),N(null)},[r,t]);i.useEffect(()=>{let C=!1;return(async()=>{k(!0);try{const[$,D]=await Promise.all([r(),t()]);if(C)return;h($),v(D),N(null)}catch($){C||N($ instanceof Error?$.message:String($))}finally{C||k(!1)}})(),()=>{C=!0}},[r,t]);const V=i.useMemo(()=>ll(u),[u]),T=i.useCallback(C=>{const $=x.find(D=>D.id===C);return $?zi(c,$):C},[x,c]),I=i.useMemo(()=>dl(x,u,{devMode:s}),[x,u,s]),F=i.useCallback(C=>{b(C)},[]);return j?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:c("common:loading",{defaultValue:"Loading…"})})]}):P?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:[c("settings:integrations.loadFailed",{defaultValue:"Failed to load integrations"}),": ",P]}):e.jsxs("div",{"data-testid":"instances-section",className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-fg-tertiary",children:c("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 D=V.find(B=>B.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(so,{id:C}),e.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:T(C)}),D.length>0&&e.jsx("span",{className:"text-[11px] text-fg-tertiary","data-testid":`platform-bot-count-${C}`,children:c("settings:instances.botCount",{defaultValue:"{{count}} bot(s)",count:D.length})}),e.jsx("div",{className:"flex-1"}),e.jsxs("button",{type:"button",onClick:()=>F(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:["+ ",c("settings:instances.addBot.label",{defaultValue:"Add bot"})]})]}),y===C&&e.jsx(ia,{instance:rl(x.find(B=>B.id===C)??{id:C,label:T(C),capabilities:{inbound:!1,outbound:!1,threads:!1},fields:[]}),client:n,extras:a,loadAgents:o,onChanged:w,onCreated:B=>{b(null),m(B)},defaultExpanded:!0}),D.map(B=>e.jsx(ia,{instance:B,client:n,extras:a,loadAgents:o,onChanged:w,defaultExpanded:d||B.id===A},B.id)),D.length===0&&y!==C&&e.jsx("p",{className:"text-[11px] text-fg-tertiary pl-7","data-testid":`platform-empty-${C}`,children:c("settings:instances.noBots",{defaultValue:"No bots yet."})})]},C)})]})}const id=["macos","linux","windows"];function ld(){const{t}=ce(["settings","common"]),[r,n]=i.useReducer(Yo,Qo),[a,o]=i.useState(null),[s,d]=i.useState("linux"),[c,u]=i.useState(!1),[h,x]=i.useState(null),[v,j]=i.useState(null),[k,P]=i.useState(""),[N,y]=i.useState(!1),[b,A]=i.useState(null),[m,w]=i.useState(""),V=i.useRef(!0),T=Gt.isAuthenticated(),I=Hr(),{kind:F,phase:C}=r,$=F?Zo(F):null;i.useEffect(()=>{d(Xo(typeof navigator>"u"?"":navigator.userAgent))},[]),i.useEffect(()=>(V.current=!0,U.settings.getRemoteV2().then(p=>{V.current&&p&&n({type:"status",status:p})}).catch(()=>{}),U.settings.remoteDetect().then(p=>{V.current&&o(p)}).catch(()=>{V.current&&o(null)}),U.settings.remoteSetupTargets().then(p=>{V.current&&(A(p),w(K=>K||p.recommendedId||p.agents[0]?.id||""))}).catch(()=>{V.current&&A(null)}),()=>{V.current=!1}),[]),i.useEffect(()=>ei.on("remote:status",p=>{const K=ti(p.payload);K&&n({type:"status",status:K})}),[]);const D=i.useCallback((p,K)=>{navigator.clipboard?.writeText(p),j(K),setTimeout(()=>j(z=>z===K?null:z),2e3)},[]),B=i.useCallback(async()=>{try{const p=await U.settings.getRemoteV2();return p&&n({type:"status",status:p}),p}catch{return null}},[]),S=i.useCallback(async()=>{try{await si()}catch{}},[]),L=p=>{x(null),y(!1),n({type:"selectKind",kind:p})},J=async()=>{x(null),n({type:"choosePath",path:"self"}),n({type:"beginInstall"}),n({type:"installSucceeded"});const p=await B();n(oi(p))},_=async()=>{const p=k.trim();if(p){u(!0),x(null);try{await U.settings.remoteTunnelRegister({kind:F??"custom",publicUrl:p}),n({type:"addressResolved",publicUrl:p}),await B()}catch(K){const z=String(K instanceof Error?K.message:K);x(z),n({type:"userError",message:z})}finally{u(!1)}}},H=()=>{x(null),n({type:"choosePath",path:"agent"})},X=async()=>{if(x(null),!F){x(t("settings:remoteAccess.path.agent.pickFirst"));return}u(!0);try{const p=await U.settings.remoteAgentSetup({kind:F,platform:s,...m?{agentId:m}:{},...I?.username?{username:I.username}:{}});p.ok&&p.agentId&&p.prompt?(n({type:"handedToChat",contract:p.contract??null}),ws.navigate(qr.TEAM,{agentId:p.agentId,prefillMessage:p.prompt})):x(p.error??t("settings:remoteAccess.path.agent.unavailable"))}catch(p){const K=String(p instanceof Error?p.message:p);x(K||t("settings:remoteAccess.path.agent.unavailable"))}finally{u(!1)}},me=async p=>{u(!0),x(null);try{p==="restart"?await U.settings.remoteTunnelRestart():p==="rotate"?await U.settings.remoteTunnelRotate():(await U.settings.remoteTunnelStop().catch(()=>{}),await U.settings.disableRemote().catch(()=>{})),p==="stop"?n({type:"reset"}):await B()}catch(K){x(String(K instanceof Error?K.message:K))}finally{u(!1)}},ie=()=>{me("stop")},ee=r.entryUrl??ri(I?.username??null),f=C==="ready"||C==="reconnecting",R=F?ai(F,s):null;return e.jsx(dd,{title:t("settings:remoteAccess.title"),description:e.jsxs(e.Fragment,{children:[t("settings:remoteAccess.description"),e.jsx("br",{}),t("settings:accessScope.remoteNote")]}),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default/40 p-5 space-y-5",children:[T?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 bg-green-500"}),t("settings:remoteAccess.signedInAs")," ",e.jsx("strong",{className:"font-semibold",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(cd,{}),e.jsx("span",{className:"text-[13px] text-amber-600 dark:text-amber-400",children:t("settings:remoteAccess.loginRequired")}),e.jsx("button",{onClick:()=>{S()},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")})]}),T&&e.jsx(e.Fragment,{children:f&&$?e.jsx(wd,{t,phase:C,meta:$,entryUrl:ee,publicUrl:r.publicUrl,health:r.health,latencyMs:r.latencyMs,message:r.message,busy:c,copied:v,onCopy:D,onRestart:()=>{me("restart")},onRotate:()=>{me("rotate")},onClose:ie}):e.jsxs(e.Fragment,{children:[e.jsx(hd,{t,detected:a,selected:F,onSelect:L}),F&&$&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(bd,{t,phase:C}),C==="error"&&e.jsx(Nd,{t,message:r.message,verifyFailure:r.verifyFailure,showManual:N,manualUrl:k,busy:c,onToggleManual:()=>y(p=>!p),onManualChange:P,onManualSubmit:()=>{_()},onRetry:()=>{x(null),n({type:"verifyStarted"}),B()},onStartOver:()=>{x(null),y(!1),n({type:"reset"})}}),C==="reconnecting"&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-brand-500/10 border border-brand-500/20 text-[13px] text-brand-600 dark:text-brand-400",children:[e.jsx(uo,{}),e.jsx("span",{children:t("settings:remoteAccess.wizard.reconnecting")})]}),e.jsx(yd,{t,setupPath:r.path,busy:c,onSelf:()=>n({type:"choosePath",path:"self"}),onAgent:()=>H()}),r.path==="self"&&R&&e.jsx(vd,{t,platform:s,onPlatform:d,commands:R,meta:$,detected:a,copied:v,onCopy:D,onDone:()=>{J()},busy:c}),r.path==="self"&&C==="resolve"&&e.jsx(jd,{t,value:k,busy:c,onChange:P,onSubmit:()=>{_()}}),r.path==="agent"&&e.jsxs("div",{className:"space-y-3",children:[b&&b.agents.length>0?e.jsxs("label",{className:"block text-[13px]",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-[13px]",value:m,onChange:p=>{w(p.target.value),n({type:"selectAgent",agentId:p.target.value})},children:b.agents.map(p=>e.jsxs("option",{value:p.id,children:[p.name,p.id===b.recommendedId?` — ${t("settings:remoteAccess.path.agent.recommended")}`:""]},p.id))})]}):e.jsx("div",{className:"p-3 rounded-xl bg-surface-secondary border border-border-default text-[13px] 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-[13px] 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(p=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"shrink-0",children:p.sensitive?t("settings:remoteAccess.path.agent.sensitive"):"›"}),e.jsx("code",{className:"break-all text-fg-primary",children:p.run})]},p.id))})]}),F&&e.jsx("button",{type:"button",className:"w-full rounded-lg bg-brand-600 px-4 py-2 text-[13px] font-medium text-on-brand hover:bg-brand-500 disabled:opacity-50",disabled:c||!b||b.agents.length===0,onClick:()=>{X()},children:t("settings:remoteAccess.path.agent.handOff")})]}),h&&e.jsx("div",{className:"p-2 rounded-lg bg-red-500/10 text-red-500 text-[13px]",children:h})]})]})}),e.jsx(kd,{t})]})})}function dd({title:t,description:r,children:n}){return e.jsxs("section",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-fg-primary",children:t}),r&&e.jsx("p",{className:"mt-0.5 text-xs leading-relaxed text-fg-tertiary",children:r})]}),e.jsx("div",{className:"space-y-4",children:n})]})}function cd(){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 uo(){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 ud({url:t}){const r=i.useRef(null),[n,a]=i.useState(!1);return i.useEffect(()=>{const o=r.current;o&&(a(!1),ii(()=>Promise.resolve().then(()=>ed),void 0).then(s=>{s.toCanvas(o,t,{width:200,margin:2,color:{dark:"#000000",light:"#ffffff"},errorCorrectionLevel:"M"})}).catch(()=>a(!0)))},[t]),n?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 md={install:"settings:remoteAccess.stepInstall",start:"settings:remoteAccess.stepStart",resolve:"settings:remoteAccess.stepResolve",register:"settings:remoteAccess.stepRegister",verify:"settings:remoteAccess.stepVerify",ready:"settings:remoteAccess.stepReady"},Qr={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"}},xd={low:"settings:remoteAccess.barrierLow",medium:"settings:remoteAccess.barrierMedium",high:"settings:remoteAccess.barrierHigh"},gd={high:"settings:remoteAccess.stabilityHigh",medium:"settings:remoteAccess.stabilityMedium",low:"settings:remoteAccess.stabilityLow"},fd={macos:"settings:remoteAccess.platformMacos",linux:"settings:remoteAccess.platformLinux",windows:"settings:remoteAccess.platformWindows"},pd={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 hd({t,detected:r,selected:n,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:ni.map(o=>{const s=n===o.kind,d=r&&o.binary?r[o.binary]:null;return e.jsxs("button",{type:"button",onClick:()=>a(o.kind),className:`text-left p-2.5 rounded-lg 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-[13px] font-medium text-fg-primary",children:t(Qr[o.kind].name)}),o.recommended&&e.jsxs("span",{className:"px-1.5 py-0.5 text-[11px] font-medium rounded bg-brand-500/15 text-brand-500",children:["★ ",t("settings:remoteAccess.badgeRecommended")]})]}),e.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-snug text-fg-tertiary",children:t(Qr[o.kind].desc)}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1",children:[e.jsx(qt,{children:t(xd[o.barrier])}),e.jsx(qt,{children:t(gd[o.stability])}),e.jsx(qt,{children:o.needsAccount?t("settings:remoteAccess.badgeNeedsAccount"):t("settings:remoteAccess.badgeNoAccount")}),e.jsx(qt,{children:o.needsDomain?t("settings:remoteAccess.badgeNeedsDomain"):t("settings:remoteAccess.badgeNoDomain")}),d!==null&&e.jsxs(qt,{tone:d?"good":"warn",children:[d?"✓ ":"✕ ",o.binary," ",t(d?"settings:remoteAccess.badgeDetected":"settings:remoteAccess.badgeNotDetected")]})]})]},o.kind)})})]})}function qt({children:t,tone:r="default"}){const n=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-[11px] rounded ${n}`,children:t})}function bd({t,phase:r}){const n=li(r),a=r==="error";return e.jsx("div",{className:"flex items-center gap-1",children:Kn.map((o,s)=>{const d=n>=0&&s<n,c=n>=0&&s===n,u=a&&s===Math.max(0,n);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":d?"bg-green-500 text-on-brand":c?"bg-brand-600 text-on-brand":"bg-surface-secondary text-fg-tertiary"}`,children:d?"✓":u?"!":s+1}),e.jsx("span",{className:`text-[10px] leading-tight text-center truncate ${c||u?"text-fg-primary":"text-fg-tertiary"}`,children:t(md[o])})]}),s<Kn.length-1&&e.jsx("span",{className:`h-px flex-1 ${d?"bg-green-500/50":"bg-border-default"}`})]},o)})})}function yd({t,setupPath:r,busy:n,onSelf:a,onAgent:o}){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:o,disabled:n,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 vd({t,platform:r,onPlatform:n,commands:a,meta:o,detected:s,copied:d,onCopy:c,onDone:u,busy:h}){const x=!!(o.binary&&s&&!s[o.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:id.map(v=>e.jsx("button",{type:"button",onClick:()=>n(v),className:`px-2 py-1 text-xs rounded-md transition-colors ${r===v?"bg-brand-600 text-on-brand":"bg-surface-secondary text-fg-secondary hover:text-fg-primary"}`,children:t(fd[v])},v))}),x&&o.binary&&e.jsx("div",{className:"text-xs text-amber-600 dark:text-amber-400",children:t("settings:remoteAccess.commandsMissingBinary",{binary:o.binary})}),["install","run"].map(v=>e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:t(v==="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[v]}),e.jsx("button",{type:"button",onClick:()=>c(a[v],v),className:`px-2 py-1.5 text-xs border rounded transition-colors shrink-0 ${d===v?"border-green-500 text-green-600 dark:text-green-400":"border-border-default hover:bg-surface-elevated"}`,children:t(d===v?"settings:remoteAccess.commandsCopied":"settings:remoteAccess.commandsCopy")})]})]},v)),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 jd({t,value:r,busy:n,onChange:a,onSubmit:o}){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:o,disabled:n||!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 Nd({t,message:r,verifyFailure:n,showManual:a,manualUrl:o,busy:s,onToggleManual:d,onManualChange:c,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:n?t(pd[n]):r??t("settings:remoteAccess.errorGeneric")}),n==="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:o,onChange:v=>c(v.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||!o.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:d,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 wd({t,phase:r,meta:n,entryUrl:a,publicUrl:o,health:s,latencyMs:d,message:c,busy:u,copied:h,onCopy:x,onRestart:v,onRotate:j,onClose:k}){const P=r==="reconnecting",N=s==="up"&&!P;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":P?"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":P?"settings:remoteAccess.wizard.reconnecting":"settings:remoteAccess.readyDegraded")}),N&&d!=null&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:t("settings:remoteAccess.readyLatency",{ms:d})}),e.jsxs("span",{className:"text-xs text-fg-tertiary",children:["· ",t(Qr[n.kind].name)]})]}),P&&e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-brand-600 dark:text-brand-400",children:[e.jsx(uo,{}),t("settings:remoteAccess.wizard.reconnectingHint")]}),!P&&c&&e.jsx("div",{className:"text-xs text-amber-600 dark:text-amber-400",children:c}),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(ud,{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")})]}),o&&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:o}),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: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.readyRestart")}),e.jsx("button",{type:"button",onClick:j,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:k,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 kd({t}){const[r,n]=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:()=>n(o=>!o),className:"flex items-center justify-between w-full px-3 py-2 text-[13px] 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((o,s)=>e.jsx("li",{className:"text-xs text-fg-tertiary leading-snug",children:o},s))})]})}const Sd=["off","observe","accept"];function Cd(t){return t==="off"||t==="observe"||t==="accept"}function Ad(t,r){const n=(t??"").trim().replace(/\/+$/,"");return n?{url:`${n}${r}`,external:!0}:{url:r,external:!1}}function Pd(t){if(!t)return{kind:"unknown"};const r=(t.publicUrl??"").trim();return r?{kind:"url",url:r}:{kind:"none"}}function Md(t,r){return r==="off"?"blocked_by_policy":t.enabled?"delivering":"paused"}function Td(){const{t}=ce("settings"),[r,n]=i.useState(null),[a,o]=i.useState([]),[s,d]=i.useState(""),[c,u]=i.useState("off"),[h,x]=i.useState([]),[v,j]=i.useState(null),[k,P]=i.useState(null),[N,y]=i.useState(null),[b,A]=i.useState(null),[m,w]=i.useState(null),[V,T]=i.useState(null);i.useEffect(()=>{let S=!1;return(async()=>{try{const[{org:L},J]=await Promise.all([U.settings.getOrg(),U.agents.list({lean:!0})]);if(S)return;n(L.id),o(J.agents.map(_=>({id:_.id,name:_.name}))),d(_=>_||(J.agents[0]?.id??""))}catch(L){S||A(L instanceof Error?L.message:String(L))}try{const L=await U.settings.getRemoteV2();S||j(Pd(L))}catch{S||j({kind:"unknown"})}})(),()=>{S=!0}},[]);const I=i.useCallback(async S=>{if(S)try{const L=await U.externalSignals.list(S);u(Cd(L.policy)?L.policy:"off"),x(L.sources),A(null)}catch(L){A(L instanceof Error?L.message:String(L))}},[]);i.useEffect(()=>{I(s)},[s,I]);const F=i.useCallback(async S=>{if(!(!r||S===c)){P(S),A(null);try{await U.externalSignals.setIngress(r,S),u(S)}catch(L){A(L instanceof Error?L.message:String(L))}finally{P(null)}}},[r,c]),C=i.useCallback(async(S,L)=>{y(S.id),A(null);try{const J=await U.externalSignals.setEnabled(s,S.id,L);J.status!=="toggled"?A(J.hint??J.status):x(_=>_.map(H=>H.id===S.id?{...H,enabled:L}:H))}catch(J){A(J instanceof Error?J.message:String(J))}finally{y(null)}},[s]),$=i.useCallback(async S=>{y(S.id),A(null);try{const L=await U.externalSignals.rotateSecret(s,S.id);L.status==="rotated"&&L.secret?(w({sourceId:S.id,value:L.secret}),x(J=>J.map(_=>_.id===S.id?{..._,hasSecret:!0,secretPreview:L.secretPreview??_.secretPreview}:_))):A(L.hint??L.status)}catch(L){A(L instanceof Error?L.message:String(L))}finally{y(null)}},[s]),D=i.useCallback(async(S,L)=>{try{await navigator.clipboard.writeText(L),T(S),window.setTimeout(()=>T(J=>J===S?null:J),1500)}catch{A(t("externalSignals.copyFailed"))}},[t]),B=i.useMemo(()=>v?.kind==="url"?v.url:null,[v]);return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(ke,{title:t("externalSignals.title"),description:t("externalSignals.intro"),children:[e.jsx("div",{className:"space-y-1",children:Sd.map(S=>{const L=c===S;return e.jsxs("button",{type:"button",onClick:()=>{F(S)},disabled:k!==null||!r,"data-testid":`external-ingress-${S}`,"aria-pressed":L,className:`w-full rounded-lg border px-3 py-2.5 text-left transition-colors disabled:opacity-50 ${L?"border-brand-500 bg-brand-600/10":"border-border-default hover:bg-surface-overlay"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[13px] font-medium text-fg-primary",children:t(`externalSignals.policy.${S}.label`)}),L&&e.jsx(Je,{tone:"ok",children:t("externalSignals.policy.current")}),k===S&&e.jsx("span",{className:"text-[12px] text-fg-tertiary",children:t("externalSignals.saving")})]}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-relaxed text-fg-tertiary",children:t(`externalSignals.policy.${S}.detail`)})]},S)})}),e.jsx("p",{className:"mt-2 text-[12px] leading-relaxed text-fg-tertiary",children:t("externalSignals.agentCaveat")})]}),e.jsxs(ke,{title:t("externalSignals.sourcesTitle"),description:t("externalSignals.sourcesIntro"),children:[e.jsx(je,{label:t("externalSignals.agentFilter"),hint:t("externalSignals.agentFilterHint"),children:e.jsx("select",{className:kt,value:s,onChange:S=>d(S.target.value),"data-testid":"external-sources-agent",children:a.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))})}),v?.kind==="none"&&e.jsx("p",{className:"mt-3 rounded-lg border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2 text-[12px] leading-relaxed text-fg-secondary","data-testid":"external-sources-no-tunnel",children:t("externalSignals.noTunnel")}),v?.kind==="unknown"&&e.jsx("p",{className:"mt-3 rounded-lg border border-border-default px-3 py-2 text-[12px] leading-relaxed text-fg-secondary","data-testid":"external-sources-tunnel-unknown",children:t("externalSignals.tunnelUnknown")}),h.length===0?e.jsx("p",{className:"mt-3 text-[12px] leading-relaxed text-fg-tertiary","data-testid":"external-sources-empty",children:t("externalSignals.empty")}):e.jsx("ul",{className:"mt-3 space-y-3",children:h.map(S=>{const L=Md(S,c),J=S.urlPath?Ad(B,S.urlPath):null;return e.jsxs("li",{className:"rounded-lg border border-border-default/60 px-3 py-3","data-testid":`external-source-${S.id}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Je,{tone:S.kind==="webhook"?"brand":"neutral",children:S.kind}),e.jsx("code",{className:"font-mono text-[12px] text-fg-primary",children:S.address}),e.jsx(Je,{tone:L==="delivering"?"ok":L==="paused"?"warn":"neutral",children:t(`externalSignals.state.${L}`)}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsx(Ye,{checked:S.enabled,onChange:_=>{C(S,_)},disabled:N===S.id,testId:`external-source-toggle-${S.id}`,label:t("externalSignals.toggleSource")})})]}),J&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate rounded bg-surface-primary px-2 py-1 font-mono text-[12px] text-fg-secondary",children:J.url}),e.jsx("button",{type:"button",className:it,onClick:()=>{D(`url-${S.id}`,J.url)},children:V===`url-${S.id}`?t("externalSignals.copied"):t("externalSignals.copy")})]}),S.feedUrl&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate rounded bg-surface-primary px-2 py-1 font-mono text-[12px] text-fg-secondary",children:S.feedUrl}),e.jsx("button",{type:"button",className:it,onClick:()=>{D(`feed-${S.id}`,S.feedUrl??"")},children:V===`feed-${S.id}`?t("externalSignals.copied"):t("externalSignals.copy")})]}),S.kind==="webhook"&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-[12px] text-fg-tertiary",children:S.hasSecret?t("externalSignals.secretSet",{preview:S.secretPreview??"••••"}):t("externalSignals.secretMissing")}),e.jsx("button",{type:"button",className:it,disabled:N===S.id,onClick:()=>{$(S)},"data-testid":`external-source-rotate-${S.id}`,children:t("externalSignals.rotate")})]}),m?.sourceId===S.id&&e.jsxs("div",{className:"mt-2 rounded-lg border border-brand-500/40 bg-brand-600/[0.08] px-3 py-2",children:[e.jsx("p",{className:"text-[12px] text-fg-secondary",children:t("externalSignals.secretOnce")}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[12px] text-fg-primary","data-testid":"external-source-minted-secret",children:m.value}),e.jsx("button",{type:"button",className:zr,onClick:()=>{D(`secret-${S.id}`,m.value)},children:V===`secret-${S.id}`?t("externalSignals.copied"):t("externalSignals.copy")})]})]}),e.jsxs("div",{className:"mt-2 text-[12px] text-fg-tertiary",children:[S.lastEventAt?t("externalSignals.lastEvent",{at:new Date(S.lastEventAt).toLocaleString()}):t("externalSignals.noEventYet"),S.lastError&&e.jsx("span",{className:"ml-2 text-amber-500",children:S.lastError})]})]},S.id)})}),b&&e.jsx("p",{className:"mt-3 text-[12px] text-red-500","data-testid":"external-sources-error",children:b})]})]})}const zt=[{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"}],Ed=800,$a=[{id:"perplexity/sonar",labelKey:"searchApi.modelSonar"},{id:"perplexity/sonar-pro",labelKey:"searchApi.modelSonarPro"}];function Ba({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 Ns({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}=ce(["settings","common"]),[r,n]=i.useState(null),[a,o]=i.useState(!0),[s,d]=i.useState(new Set),[c,u]=i.useState({}),[h,x]=i.useState({}),[v,j]=i.useState(!1),[k,P]=i.useState(!1),[N,y]=i.useState({}),[b,A]=i.useState({}),[m,w]=i.useState({}),[V,T]=i.useState({}),I=i.useRef({}),F=i.useCallback(async()=>{o(!0);try{const f=await U.settings.getSearch();f&&(n(f),zt.some(p=>!!f[p.id]?.configured)&&P(!0))}catch{}o(!1)},[]);i.useEffect(()=>{F()},[F]),i.useEffect(()=>()=>{Object.values(I.current).forEach(clearTimeout)},[]);const C=f=>{d(R=>{const p=new Set(R);return p.has(f)?p.delete(f):p.add(f),p})},$=(f,R,p)=>{u(K=>({...K,[R]:p})),I.current[f]&&clearTimeout(I.current[f]),I.current[f]=setTimeout(()=>{D(f)},Ed)},D=async f=>{const R=zt.find(z=>z.id===f);if(!R)return;const p=c[R.field]?.trim(),K=R.extraField?c[R.extraField]?.trim():void 0;if(!(!p&&!K)){x(z=>({...z,[f]:!0})),y(z=>{const se={...z};return delete se[f],se});try{const z={};p&&(z[R.field]=p),K&&R.extraField&&(z[R.extraField]=K);const se=await U.settings.updateSearch(z);n(se),u(ae=>{const ge={...ae};return delete ge[R.field],R.extraField&&delete ge[R.extraField],ge}),y(ae=>({...ae,[f]:{type:"ok",text:t("searchApi.saved")}})),setTimeout(()=>y(ae=>{const ge={...ae};return delete ge[f],ge}),3e3)}catch{y(z=>({...z,[f]:{type:"err",text:t("searchApi.failedToSave")}}))}x(z=>({...z,[f]:!1}))}},B=f=>r?.[f],S=f=>B(f)?.configured??!1,L=f=>B(f)?.enabled!==!1,J=async(f,R)=>{T(p=>({...p,[f]:!0}));try{const p={[`${f}Enabled`]:R},K=await U.settings.updateSearch(p);n(K)}catch{}T(p=>({...p,[f]:!1}))},_=async f=>{I.current[f]&&(clearTimeout(I.current[f]),delete I.current[f],await D(f)),A(R=>({...R,[f]:!0})),w(R=>{const p={...R};return delete p[f],p});try{const R=await U.settings.testSearch(f);if(R.ok){const p=[t("searchApi.testOk",{count:R.count??0})];R.latencyMs!=null&&p.push(`${R.latencyMs}ms`),R.sample?.title&&p.push(R.sample.title.slice(0,48)),w(K=>({...K,[f]:{ok:!0,text:p.join(" · ")}}))}else w(p=>({...p,[f]:{ok:!1,text:R.error||t("searchApi.testFailed")}}))}catch{w(R=>({...R,[f]:{ok:!1,text:t("searchApi.testFailed")}}))}A(R=>({...R,[f]:!1}))},H=async f=>{j(!0);try{const R=await U.settings.updateSearch(f);n(R)}catch{}j(!1)},X=({id:f,disabled:R})=>{const p=b[f];return e.jsxs("button",{type:"button",onClick:()=>{_(f)},disabled:p||R,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:[p?e.jsx(Ns,{}):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(p?"searchApi.testing":"searchApi.test")]})},me=({id:f})=>{const R=m[f];return R?e.jsxs("div",{className:`text-[11px] flex items-start gap-1.5 ${R.ok?"text-green-500":"text-red-500"}`,children:[e.jsx("span",{className:"shrink-0 mt-px",children:R.ok?"✓":"✕"}),e.jsx("span",{className:"break-all",children:R.text})]}):null},ie=({id:f})=>{const R=L(f),p=V[f];return e.jsxs("label",{className:"inline-flex items-center gap-2 cursor-pointer shrink-0",onClick:K=>K.stopPropagation(),title:t(R?"searchApi.enabled":"searchApi.disabled"),children:[p&&e.jsx(Ns,{className:"w-3 h-3 text-fg-tertiary"}),e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:R,disabled:p,onChange:K=>{J(f,K.target.checked)}}),e.jsx("span",{className:"relative w-9 h-5 rounded-full bg-gray-500/40 peer-checked:bg-brand-500 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:w-4 after:h-4 after:rounded-full after:bg-white after:transition-transform peer-checked:after:translate-x-4"})]})},ee=r?.markus;return e.jsx("section",{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:t("searchApi.description")}),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-border-default px-4 py-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t("searchApi.markus")}),e.jsx("span",{className:"text-[10px] font-medium text-brand-400",children:t("searchApi.markusBadge")})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-0.5 truncate",children:t("searchApi.markusHint")})]}),ee?.available&&ee.enabled&&e.jsx(X,{id:"markus"}),a?e.jsx("span",{className:"inline-block h-5 w-9 shrink-0 animate-pulse rounded-full bg-surface-elevated","aria-hidden":"true"}):ee?.available?e.jsxs("label",{className:"inline-flex items-center gap-2 cursor-pointer shrink-0",children:[v&&e.jsx(Ns,{className:"w-3 h-3 text-fg-tertiary"}),e.jsx("input",{type:"checkbox",className:"sr-only peer",checked:ee.enabled,disabled:v,onChange:f=>{H({useMarkusHosted:f.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")})]}),!a&&!ee?.available&&e.jsx("div",{className:"text-[11px] text-amber-500/90",children:t("searchApi.markusUnavailableHint")}),ee?.available&&ee.enabled&&e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("label",{className:"text-[11px] text-fg-tertiary shrink-0",htmlFor:"markus-search-model",children:t("searchApi.modelLabel")}),e.jsxs("select",{id:"markus-search-model",value:ee.markusSearchModel||"perplexity/sonar",disabled:v,onChange:f=>{H({markusSearchModel:f.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:[$a.map(f=>e.jsx("option",{value:f.id,children:t(f.labelKey)},f.id)),ee.markusSearchModel&&!$a.some(f=>f.id===ee.markusSearchModel)&&e.jsx("option",{value:ee.markusSearchModel,children:ee.markusSearchModel})]})]}),e.jsx("div",{className:"text-[11px] text-fg-tertiary",children:t("searchApi.modelHint")}),e.jsx(me,{id:"markus"})]}),e.jsxs("div",{className:"rounded-xl border border-border-default overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>P(f=>!f),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(Ba,{expanded:k}),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:[zt.filter(f=>S(f.id)).length,"/",zt.length]})]}),k&&e.jsx("div",{className:"border-t border-border-default px-2 pb-2 space-y-1",children:zt.map(f=>{const R=S(f.id),p=s.has(f.id),K=N[f.id],z=h[f.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(f.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 ${R&&!L(f.id)?"opacity-50":""}`,children:[e.jsx(Ba,{expanded:p}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:t(f.labelKey)}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-2 hidden sm:inline",children:t(f.hintKey)})]}),e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:R?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(ie,{id:f.id})})]}),p&&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:c[f.field]??"",onChange:se=>$(f.id,f.field,se.target.value),placeholder:t(R?"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"}),f.extraField&&e.jsx("input",{type:"text",value:c[f.extraField]??"",onChange:se=>$(f.id,f.extraField,se.target.value),placeholder:f.extraPlaceholderKey?t(f.extraPlaceholderKey):"",className:"w-full px-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none font-mono"}),e.jsxs("div",{className:"flex items-center gap-2 min-h-[28px] flex-wrap",children:[e.jsx(X,{id:f.id,disabled:!R&&!c[f.field]?.trim()}),z&&e.jsxs("span",{className:"text-[10px] text-fg-tertiary flex items-center gap-1",children:[e.jsx(Ns,{}),t("common:saving")]}),K&&e.jsx("span",{className:`text-[10px] ${K.type==="ok"?"text-green-500":"text-red-500"}`,children:K.text})]}),e.jsx(me,{id:f.id})]})})]},f.id)})})]})]})]})})}function Id(){const{t}=ce(["settings","common"]),[r,n]=i.useState(di);i.useEffect(()=>ci(n),[]);const a=d=>n(fr({enabled:d})),o=d=>{n(fr({volume:d})),Hn(gr("agent-reply-complete"),d)},s=(d,c)=>{const u=new Set(r.disabledEvents);c?u.delete(d):u.add(d),n(fr({disabledEvents:[...u]}))};return e.jsxs(ke,{title:t("sounds.title"),description:t("sounds.description"),children:[e.jsxs("div",{className:`${we} divide-y divide-border-default/40`,children:[e.jsx(je,{label:t("sounds.enabled"),hint:t("sounds.enabledDesc"),children:e.jsx(Ye,{checked:r.enabled,onChange:a,label:t("sounds.enabled"),testId:"sound-master-switch"})}),e.jsx(je,{label:t("sounds.volume"),hint:t("sounds.volumeDesc"),children:e.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-secondary/60 rounded-lg p-0.5",children:ui.map(d=>e.jsx("button",{type:"button",disabled:!r.enabled,onClick:()=>o(d),"data-testid":`sound-volume-${d}`,className:`px-3 py-1.5 text-[11px] rounded-md transition-colors disabled:opacity-40 ${r.volume===d?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary"}`,children:t(`sounds.volumes.${d}`)},d))})}),mi.map(d=>{const c=r.enabled&&!r.disabledEvents.includes(d.id);return e.jsxs(je,{label:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:t(d.labelKey)}),e.jsx("span",{className:`${Fe.badge} ${Qe.desc} rounded px-1.5 py-0.5 bg-surface-secondary`,children:t(`sounds.cues.${gr(d.id)}`)})]}),hint:t(d.descKey),children:[e.jsx("button",{type:"button",className:it,disabled:!r.enabled,onClick:()=>Hn(gr(d.id)),"data-testid":`sound-preview-${d.id}`,children:t("sounds.preview")}),e.jsx(Ye,{checked:c,onChange:u=>s(d.id,u),label:t(d.labelKey),disabled:!r.enabled,testId:`sound-event-switch-${d.id}`})]},d.id)})]}),e.jsx("p",{className:`px-1 ${Fe.hint} ${Qe.desc}`,children:t("sounds.deviceNote")})]})}function Da(t,r={}){const{delayMs:n=600,savedMs:a=2e3}=r,[o,s]=i.useState("idle"),d=i.useRef(null),c=i.useRef(null),u=i.useRef(0),h=i.useRef(null),x=i.useRef(t);x.current=t;const v=i.useCallback(async()=>{const P=c.current;if(c.current=null,!P)return;const N=++u.current;s("saving");try{if(await x.current(P.value),N!==u.current)return;s("saved"),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{s(y=>y==="saved"?"idle":y)},a)}catch{if(N!==u.current)return;s("error")}},[a]),j=i.useCallback(P=>{c.current={value:P},d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,v()},n)},[n,v]),k=i.useCallback(()=>{d.current&&(clearTimeout(d.current),d.current=null),v()},[v]);return i.useEffect(()=>()=>{d.current&&clearTimeout(d.current),h.current&&clearTimeout(h.current),d.current=null,v()},[v]),{state:o,schedule:j,flush:k}}async function mo(t,r={}){try{if(r.apiKey){const a=await U.modelCatalog.validateKey(t,r.apiKey,r.baseUrl);return qn(a.models??[])}const n=await U.modelCatalog.getByProvider(t);return qn(n.models??[])}catch(n){return xi(n)}}const Ms=[{id:"appearance",labelKey:"nav.appearance"},{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:"external-sources",labelKey:"nav.externalSignals",adminOnly:!0,devOnly:!0},{id:"network",labelKey:"nav.network",adminOnly:!0},{id:"account",labelKey:"nav.account"},{id:"storage",labelKey:"nav.storage",adminOnly:!0},{id:"facts",labelKey:"nav.facts",adminOnly:!0}],Fr=[{labelKey:"nav.group.general",tabs:["appearance"]},{labelKey:"nav.group.aiConfig",tabs:["providers","execution"]},{labelKey:"nav.group.tools",tabs:["browser","search"]},{labelKey:"nav.group.connections",tabs:["integrations","external-sources","network"]},{labelKey:"nav.group.account",tabs:["account"]},{labelKey:"nav.group.data",tabs:["storage","facts"]}],xo=!1;function Ld(t){return Ms.filter(r=>(!r.adminOnly||t.canManageOrg)&&(!r.devOnly||t.dev))}function Od(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"];case"facts":return[];default:return[]}}const $d={Database:"database",Agents:"agents",Skills:"skills","LLM Logs":"llmLogs","Builder Artifacts":"builderArtifacts",Teams:"teams",Shared:"shared",Knowledge:"knowledge"},Ur={Database:"keep",Agents:"keep",Skills:"caution","LLM Logs":"safe","Builder Artifacts":"caution",Teams:"keep",Shared:"caution",Knowledge:"caution"},Va={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",facts:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M8.5 14.5l2.5 2.5 4-4.5",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","external-sources":"M4 10a7.31 7.31 0 0 0 10 10Z M9 15l3-3 M17 13a6 6 0 0 0-6-6 M21 13A10 10 0 0 0 11 3",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 Zr({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:Va[t]??Va._default})})}const Bd={users:"account",organization:"account",license:"account",orgIdentity:"account",remote:"network"};function Dd(t){const n=(t.startsWith("#")?t.slice(1):t).split("/");if(n[0]==="settings"&&n[1]){const a=n[1],s=Bd[a]??a;if(Ms.some(d=>d.id===s))return s}return null}function Vd(t,r=xo){return t?Ms.find(a=>a.id===t)?.devOnly&&!r?null:t:null}function _a(){return Vd(Dd(window.location.hash))}function nc({theme:t,onThemeChange:r,authUser:n,onLogout:a,onUserUpdated:o}={}){const{t:s,i18n:d}=ce(["settings","common"]),c=gi(),u=fi(qr.SETTINGS),h=pi(),x=h?.keyboardPane??"content",[v,j]=i.useState(_a),[k,P]=i.useState(!1);i.useEffect(()=>{const l=()=>j(_a());return window.addEventListener("hashchange",l),()=>window.removeEventListener("hashchange",l)},[]);const N=i.useCallback(l=>{j(l),history.pushState(null,"",`#settings/${l}`)},[]),y=i.useCallback(()=>{j(null),history.pushState(null,"","#settings")},[]),b=v??(c?null:"appearance"),[A,m]=i.useState(!1),[w,V]=i.useState(!1);i.useEffect(()=>{!zn()||!window.markusDesktop?.getLoginItemSettings||window.markusDesktop.getLoginItemSettings().then(l=>m(!!l.openAtLogin)).catch(()=>{})},[]);const T=i.useCallback(async()=>{if(!window.markusDesktop?.setLoginItemSettings||w)return;const l=!A;V(!0),m(l);try{const g=await window.markusDesktop.setLoginItemSettings(l);m(!!g.openAtLogin)}catch{m(!l)}finally{V(!1)}},[A,w]),[I,F]=i.useState(null),[C,$]=i.useState(null),[D,B]=i.useState(""),[S,L]=i.useState(!1),[J,_]=i.useState(null),[H,X]=i.useState(null),[me,ie]=i.useState(null),[ee,f]=i.useState({}),[R,p]=i.useState(null),[K,z]=i.useState(null),[se,ae]=i.useState(null),[ge,te]=i.useState(!1),[Ze,Me]=i.useState(null),[Pe,Be]=i.useState({}),[ct,Se]=i.useState(!1),[fe,Zt]=i.useState(null),[Xe,Pt]=i.useState(!1),[De,ut]=i.useState(""),[Xt,es]=i.useState(!1),[et,Ie]=i.useState(null),[Mt,ts]=i.useState(""),[ye,Ue]=i.useState(!0),[ss,mt]=i.useState([]),[rs,xt]=i.useState(""),[Tt,ns]=i.useState("none"),[Ts,Et]=i.useState(null),[Rt,gt]=i.useState(!1),[It,tt]=i.useState(null),[tn,as]=i.useState("0.0.0.0"),[Lt,Es]=i.useState("0.0.0.0"),[Te,Rs]=i.useState(!1),[ft,re]=i.useState(null),[Ke,pt]=i.useState(!1),[E,ne]=i.useState(()=>{try{const l=localStorage.getItem("markus.settings.accessMode");if(l==="local"||l==="lan"||l==="remote")return l}catch{}return"lan"}),ue=l=>{ne(l);try{localStorage.setItem("markus.settings.accessMode",l)}catch{}},He=async l=>{if(Te||Ke||n?.role!=="owner")return;const g=l==="local"?"127.0.0.1":"0.0.0.0";if(ue(l),as(g),g===Lt){re(null);return}pt(!0),re({text:s("accessScope.applying"),warn:!0});try{const W=await fetch("/api/settings/network",{method:"POST",headers:le(),body:JSON.stringify({host:g})});if(!W.ok)throw new Error(`HTTP ${W.status}`)}catch{pt(!1),re({text:s("accessScope.saveFailed"),warn:!0});return}fetch("/api/settings/network/apply",{method:"POST",headers:le(),body:JSON.stringify({})}).catch(()=>{});let O=0;const q=setInterval(async()=>{O++;try{if((await fetch("/api/health",{signal:AbortSignal.timeout(1500)})).ok){clearInterval(q),pt(!1),re({text:s("accessScope.applied"),warn:!1}),nt();return}}catch{}O>20&&(clearInterval(q),pt(!1),re({text:s("accessScope.applyFailed"),warn:!0}))},400)},[Le,go]=i.useState(null),[sn,rn]=i.useState(!1),[Is,os]=i.useState(null),[nn,fo]=i.useState([]),[an,Ls]=i.useState([]),[Ot,ht]=i.useState(null),[Os,Ne]=i.useState(null),[is,on]=i.useState(""),[po,$t]=i.useState(null),[Bt,$s]=i.useState(null),ve=i.useRef(null),ln=i.useRef(!1),dn=i.useRef(!1),[Bs,Ds]=i.useState(200),[Vs,_s]=i.useState(20),[Fs,Us]=i.useState(10),[Dt,Ks]=i.useState(!1),[Hs,qs]=i.useState(3),[zs,Ws]=i.useState("auto"),ho=i.useCallback(async l=>{const g=await U.settings.updateAgent(l);Ds(g.maxToolIterations),_s(g.maxPendingTasksPerAgent),Us(g.maxPendingRequirementProposals)},[]),st=Da(ho),bo=i.useCallback(async l=>{const g=await U.settings.updateAgent({concurrent:l});Ks(g.concurrent.enabled),qs(g.concurrent.maxWorkers??1),Ws(g.concurrent.conflictPolicy??"auto")},[]),rt=Da(bo),[bt,Gs]=i.useState("embedded"),[ls,Js]=i.useState("direct"),[Ys,ds]=i.useState(!1),[cn,Qs]=i.useState(0),[Zs,cs]=i.useState(!0),[Xs,us]=i.useState(!1),[qe,un]=i.useState(!1),[Zd,yo]=i.useState(9333),[pe,xe]=i.useState(!1),[er,Z]=i.useState(null),[Ve,vo]=i.useState(null),[tr,mn]=i.useState(!1),[ms,jo]=i.useState(null),[Xd,ec]=i.useState(!1),le=()=>({"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("markus_token")??""}`}),sr=i.useRef(new Set),xn=i.useCallback(()=>{U.health().then(F).catch(()=>{})},[]),ze=i.useCallback(()=>hi({force:!0}).then(l=>l&&typeof l=="object"&&"providers"in l?($(l),B(l.defaultProvider??""),!0):!1).catch(()=>!1),[]),nt=i.useCallback(()=>fetch("/api/settings/network").then(l=>l.ok?l.json():Promise.reject(l.status)).then(l=>{ts(l.network?.proxy??""),Ue(l.network?.proxyEnabled!==!1),go(l.effective);const g=l.egress;g&&(mt(g.noProxy??[]),ns(g.source??"none"),Et(g.error??null));const O=l.server?.host??"0.0.0.0";return as(O),ne(q=>{try{if(localStorage.getItem("markus.settings.accessMode"))return q}catch{}return O==="0.0.0.0"?"lan":"local"}),Es(l.server?.effectiveHost??"0.0.0.0"),Rs(l.server?.source==="env"),!0}).catch(()=>!1),[]),gn=i.useCallback(()=>fetch("/api/settings/oauth/providers").then(l=>l.ok?l.json():Promise.reject(l.status)).then(l=>(fo(l.providers??[]),!0)).catch(()=>!1),[]),xs=i.useCallback((l=!1)=>fetch(`/api/settings/oauth/profiles${l?"?validate=1":""}`,{headers:le()}).then(O=>O.ok?O.json():Promise.reject(O.status)).then(O=>(Ls(O.profiles??[]),!0)).catch(()=>!1),[]),fn=i.useCallback(()=>U.settings.getAgent().then(l=>(l&&typeof l.maxToolIterations=="number"&&Ds(l.maxToolIterations),l&&typeof l.maxPendingTasksPerAgent=="number"&&_s(l.maxPendingTasksPerAgent),l&&typeof l.maxPendingRequirementProposals=="number"&&Us(l.maxPendingRequirementProposals),l?.concurrent&&(Ks(l.concurrent.enabled??!0),qs(l.concurrent.maxWorkers??1),Ws(l.concurrent.conflictPolicy??"auto")),!0)).catch(()=>!1),[]),pn=i.useCallback(()=>U.settings.getBrowser().then(l=>(l&&(Gs(l.mode??"embedded"),Js(l.elementSelection??"direct"),ds(l.bringToFront??!1),Qs(l.remoteDebuggingPort??0),cs(l.autoCloseTabs??!0),us(l.autoClickAllowDialog??!1),un(l.extensionConnected??!1),yo(l.extensionBridgePort??9333)),!0)).catch(()=>!1),[]),yt=i.useCallback(()=>{mn(!0);const l=U.system.storage().then(vo).then(()=>!0).catch(()=>!1).finally(()=>mn(!1));return U.system.orphans().then(jo).catch(()=>{}),l},[]);i.useEffect(()=>{xn()},[xn]);const[No,wo]=i.useState(0);i.useEffect(()=>{if(!b||sr.current.has(b))return;const l=Od(b),g=[];if(l.includes("llm")&&g.push(ze()),l.includes("network")&&g.push(nt()),l.includes("oauth")&&g.push(gn()),l.includes("authProfiles")&&g.push(xs(!0)),l.includes("agent")&&g.push(fn()),l.includes("browser")&&g.push(pn()),l.includes("storage")&&g.push(yt()),g.length===0){sr.current.add(b);return}let O=null,q=!1;return Promise.all(g).then(W=>{if(!q){if(W.every(Boolean)){sr.current.add(b);return}O=setTimeout(()=>wo(Y=>Y+1),1500)}}),()=>{q=!0,O&&clearTimeout(O)}},[b,No,ze,nt,gn,xs,fn,pn,yt]),i.useEffect(()=>{const l=()=>yt();return window.addEventListener("markus:data-changed",l),()=>window.removeEventListener("markus:data-changed",l)},[yt]),i.useEffect(()=>{!H||ee[H]||(p(H),H==="markus"&&z(null),U.modelCatalog.getLive(H).then(l=>{f(g=>({...g,[H]:l.models})),H==="markus"&&(l.error&&z(String(l.error)),ze())}).catch(l=>{H==="markus"&&z(l instanceof Error?l.message:String(l)),U.modelCatalog.getByProvider(H).then(g=>{f(O=>({...O,[H]:g.models}))}).catch(()=>{})}).finally(()=>p(null)))},[H]);const rr=i.useCallback(async()=>{te(!0),Me(null),ae(null),Be({});try{const l=await fetch("/api/settings/env-models",{headers:le()});if(!l.ok){Me({type:"err",text:s("envConfig.detectionFailedHttp",{status:l.status})});return}const g=await l.json();if(ae(g),g.detected.length===0)Me({type:"err",text:s("envConfig.noKeysFound")});else{const O={};for(const q of g.detected)O[q.provider]=!0;Be(O)}}catch{Me({type:"err",text:s("envConfig.failedToDetect")})}finally{te(!1)}},[s]),Vt=i.useCallback(async()=>{Pt(!0),Ie(null),Zt(null);try{const l=await fetch("/api/settings/detect-ollama",{headers:le()});if(!l.ok){Ie({type:"err",text:s("ollama.detectFailed")});return}const g=await l.json();Zt(g),g.found&&g.models&&g.models.length>0?ut(g.models[0].name):g.found||Ie({type:"err",text:g.error||s("ollama.notRunning")})}catch{Ie({type:"err",text:s("ollama.detectFailed")})}finally{Pt(!1)}},[s]),hn=C?Object.values(C.providers).some(l=>l.configured):!1;i.useEffect(()=>{C&&!hn&&!ln.current&&(ln.current=!0,rr(),Vt())},[C,hn,rr,Vt]),i.useEffect(()=>{H==="ollama"&&!fe&&!Xe&&!dn.current&&(dn.current=!0,Vt())},[H,fe,Xe,Vt]);const ko=async()=>{if(!(!D||D===C?.defaultProvider)){L(!0),_(null);try{const l=await fetch("/api/settings/llm",{method:"POST",headers:le(),body:JSON.stringify({defaultProvider:D})}),g=await l.json();l.ok?($(g),_({type:"ok",text:s("defaultProvider.updated",{name:g.defaultProvider})})):_({type:"err",text:g.error??s("modelProviders.saveFailed")})}catch{_({type:"err",text:s("common:networkError")})}finally{L(!1)}}},So=async(l,g)=>{ie(l);try{const O=await fetch(`/api/settings/llm/providers/${l}/toggle`,{method:"POST",headers:le(),body:JSON.stringify({enabled:g})});if(O.ok){const q=await O.json();$(q)}}catch{}finally{ie(null)}},Co=async()=>{if(!se)return;const l=se.detected.filter(g=>Pe[g.provider]);if(l.length===0){Me({type:"err",text:s("envConfig.selectAtLeastOne")});return}Se(!0),Me(null);try{const g=await fetch("/api/settings/env-models",{method:"POST",headers:le(),body:JSON.stringify({providers:l.map(q=>({provider:q.provider,model:q.model,baseUrl:q.baseUrl,enabled:!0}))})});if(!g.ok){Me({type:"err",text:s("envConfig.applyFailed",{status:g.status})});return}const O=await g.json();Me({type:"ok",text:O.message}),ae(null),Be({}),ze()}catch{Me({type:"err",text:s("envConfig.failedToApply")})}finally{Se(!1)}},Ao=async()=>{if(!(!fe?.found||!De)){es(!0),Ie(null);try{const l=await fetch("/api/settings/llm/providers",{method:"POST",headers:le(),body:JSON.stringify({name:"ollama",model:De,baseUrl:fe.baseUrl||"http://localhost:11434"})});if(l.ok){const g=await l.json();$(g),Ie({type:"ok",text:s("ollama.configured",{model:De})})}else{const g=await l.json();Ie({type:"err",text:g.error||s("ollama.applyFailed")})}}catch{Ie({type:"err",text:s("ollama.applyFailed")})}finally{es(!1)}}},bn=async l=>{ht(l),Ne(null);try{const g=await fetch("/api/settings/oauth/login",{method:"POST",headers:le(),body:JSON.stringify({provider:l})}),O=await g.json();if(!g.ok||O.error){Ne({type:"err",text:O.error??s("oauth.loginFailed")});return}O.authorizeUrl&&(window.open(O.authorizeUrl,"_blank","noopener"),$t(l),Ne({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:le()})).json();!W.pending&&W.profiles.some(Y=>Y.provider===l&&Y.hasOAuth)&&(ve.current&&clearInterval(ve.current),ve.current=null,$t(null),Ls(W.profiles),Ne({type:"ok",text:s("oauthConnected",{provider:l})}),ze())}catch{}},2e3))}catch{Ne({type:"err",text:s("oauth.networkErrorDuringLogin")})}finally{ht(null)}},Po=async l=>{ht(l),Ne(null),$s(null);try{const g=await fetch("/api/settings/oauth/device-code",{method:"POST",headers:le(),body:JSON.stringify({provider:l})}),O=await g.json();if(!g.ok||O.error){Ne({type:"err",text:O.error??s("oauthAuth.deviceCodeFailed")});return}O.userCode&&O.verificationUri&&($s({userCode:O.userCode,verificationUri:O.verificationUri,provider:l}),$t(l),Ne({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:le()})).json();!W.pending&&W.profiles.some(Y=>Y.provider===l&&Y.hasOAuth)&&(ve.current&&clearInterval(ve.current),ve.current=null,$t(null),$s(null),Ls(W.profiles),Ne({type:"ok",text:s("oauthConnected",{provider:l})}),ze())}catch{}},3e3))}catch{Ne({type:"err",text:s("oauth.networkErrorDuringLogin")})}finally{ht(null)}},Mo=async()=>{if(is.trim()){ht("manual"),Ne(null);try{const l=await fetch("/api/settings/oauth/callback",{method:"POST",headers:le(),body:JSON.stringify({callbackUrl:is})}),g=await l.json();if(!l.ok||g.error){Ne({type:"err",text:g.error??s("oauth.callbackFailed")});return}Ne({type:"ok",text:s("oauthConnected",{provider:g.profile?.provider??s("common:unknown")})}),on(""),$t(null),ve.current&&(clearInterval(ve.current),ve.current=null),xs(),ze()}catch{Ne({type:"err",text:s("common:networkError")})}finally{ht(null)}}},To=async l=>{try{(await fetch(`/api/settings/oauth/profiles/${encodeURIComponent(l)}`,{method:"DELETE",headers:le()})).ok&&(xs(),ze(),Ne({type:"ok",text:s("authProfileDeleted")}))}catch{}};i.useEffect(()=>()=>{ve.current&&clearInterval(ve.current)},[]),i.useEffect(()=>{if(b!=="browser"||qe)return;const l=setInterval(async()=>{try{(await U.settings.getBrowser()).extensionConnected&&(un(!0),clearInterval(l))}catch{}},5e3);return()=>clearInterval(l)},[b,qe]);const[Eo,nr]=i.useState(!1),[de,We]=i.useState({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),[gs,yn]=i.useState(!1),[ar,vn]=i.useState(null),[or,at]=i.useState([]),[jn,ir]=i.useState(null),[Ro,Nn]=i.useState(!1),[Io,lr]=i.useState(null),[be,dr]=i.useState({apiKey:"",baseUrl:"",model:"",contextWindow:0,maxOutputTokens:0,costInput:0,costOutput:0}),[wn,kn]=i.useState(!1),[Sn,Cn]=i.useState(null),[cr,ur]=i.useState(null),[_e,vt]=i.useState(""),[An,Pn]=i.useState(!1),[mr,Ce]=i.useState(null),[Mn,fs]=i.useState(null),ps=Ui(),[Ee,hs]=i.useState({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1}),[Lo,Tn]=i.useState(!1),En=async(l,g)=>{if(!l||l==="__custom__")return;Nn(!0),Ce(null),ir(null);const O=ps.find(W=>W.id===l),q=de.baseUrl||O?.baseUrl;try{if(g){const W=await U.modelCatalog.validateKey(l,g,q||void 0);!W.valid&&W.error&&Ce({type:"err",text:W.error}),at(W.models)}else{const W=await mo(l);at(W.state==="ok"?[...W.items]:[]),W.state==="error"&&ir(W.error??s("common:readFailed"))}}catch(W){at([]),ir(ji(W))}finally{Nn(!1)}},Rn=async()=>{if(!(!de.name||!de.model)){yn(!0),vn(null),Ce(null);try{const l=await fetch("/api/settings/llm/providers",{method:"POST",headers:le(),body:JSON.stringify({name:de.name,apiKey:de.apiKey||void 0,baseUrl:de.baseUrl||void 0,model:de.model,contextWindow:de.contextWindow||void 0,maxOutputTokens:de.maxOutputTokens||void 0,cost:de.costInput||de.costOutput?{input:de.costInput,output:de.costOutput}:void 0})}),g=await l.json();l.ok?($(g),nr(!1),vt(""),at([]),We({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5}),Ce({type:"ok",text:s("modelProviders.providerAdded",{name:de.name})})):Ce({type:"err",text:g.error??s("modelProviders.failedToAdd")})}catch{Ce({type:"err",text:s("common:networkError")})}finally{yn(!1)}}},Oo=async(l,g)=>{if(!_e.trim())return;Pn(!0),Ce(null);const O=ps.find(Y=>Y.id===l),q=O?.baseUrl;let W=O?.defaultModel??l;try{const Y=await U.modelCatalog.getLive(l);Y?.recommended&&(W=Y.recommended)}catch{}try{const Y=await fetch("/api/settings/llm/providers",{method:"POST",headers:le(),body:JSON.stringify({name:l,apiKey:_e.trim(),model:W,baseUrl:q})}),he=await Y.json();Y.ok?($(he),vt(""),at([]),Ce({type:"ok",text:s("modelProviders.quickSetupSuccess",{name:O?.label??l})})):Ce({type:"err",text:he.error??s("modelProviders.failedToAdd")})}catch{Ce({type:"err",text:s("common:networkError")})}finally{Pn(!1)}},$o=(l,g)=>{lr(l),dr({apiKey:"",baseUrl:g.baseUrl??"",model:g.model,contextWindow:g.contextWindow??0,maxOutputTokens:g.maxOutputTokens??0,costInput:g.cost?.input??0,costOutput:g.cost?.output??0})},Bo=async l=>{kn(!0);try{const g={};be.apiKey&&(g.apiKey=be.apiKey),be.baseUrl!==void 0&&(g.baseUrl=be.baseUrl),be.model&&(g.model=be.model),be.contextWindow&&(g.contextWindow=be.contextWindow),be.maxOutputTokens&&(g.maxOutputTokens=be.maxOutputTokens),(be.costInput||be.costOutput)&&(g.cost={input:be.costInput,output:be.costOutput});const O=await fetch(`/api/settings/llm/providers/${l}`,{method:"PUT",headers:le(),body:JSON.stringify(g)});if(O.ok){const q=await O.json();$(q),lr(null)}}catch{}finally{kn(!1)}},Do=async l=>{Cn(l);try{const g=await fetch(`/api/settings/llm/providers/${l}`,{method:"DELETE",headers:le()});if(g.ok){const O=await g.json();$(O),B(O.defaultProvider)}}catch{}finally{Cn(null)}},Vo=async l=>{if(!(!Ee.id||!Ee.name)){Tn(!0);try{const g=await fetch(`/api/settings/llm/providers/${l}/models`,{method:"POST",headers:le(),body:JSON.stringify({id:Ee.id,name:Ee.name,contextWindow:Ee.contextWindow,maxOutputTokens:Ee.maxOutputTokens,cost:{input:Ee.costInput,output:Ee.costOutput},reasoning:Ee.reasoning||void 0,inputTypes:Ee.vision?["text","image"]:["text"]})});if(g.ok){const O=await g.json();$(O),fs(null),hs({id:"",name:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5,reasoning:!1,vision:!1})}}catch{}finally{Tn(!1)}}},_o=async(l,g)=>{try{const O=await fetch(`/api/settings/llm/providers/${l}/models/${encodeURIComponent(g)}`,{method:"DELETE",headers:le()});if(O.ok){const q=await O.json();$(q)}}catch{}},[In,Ln]=i.useState(null),[On,Fo]=i.useState({}),[oe,bs]=i.useState({}),Uo=async l=>{Ln(l),bs(g=>{const O={...g};return delete O[l],O});try{const g=await fetch(`/api/settings/llm/providers/${l}/test`,{method:"POST",headers:le(),body:JSON.stringify({model:On[l]||void 0})});if(!g.ok){const q=await g.json().catch(()=>({}));bs(W=>({...W,[l]:{ok:!1,error:q.error??`HTTP ${g.status}`,errorCode:g.status,code:q.code}}));return}const O=await g.json();bs(q=>({...q,[l]:O}))}catch{bs(g=>({...g,[l]:{ok:!1,error:s("common:networkError")}}))}finally{Ln(null)}},Ko=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")),Ho=l=>{const g=new Set,O=C?.providers?.[l];O?.model&&g.add(O.model);const q=ee[l];if(q)for(const W of q)W.id&&g.add(String(W.id));if(O?.models)for(const W of O.models)W.id&&g.add(W.id);if(l==="ollama"&&fe?.models)for(const W of fe.models)W.name&&g.add(W.name);return[...g]},$n=C?.providers?Object.entries(C.providers).filter(([,l])=>l.configured&&l.enabled).map(([l])=>l):[],Bn=n?.role==="owner"||n?.role==="admin",_t=Ld({dev:xo,canManageOrg:Bn}),Dn=i.useMemo(()=>{const l=[];for(const g of Fr)for(const O of g.tabs){const q=_t.find(W=>W.id===O);q&&l.push(q)}return l},[_t]),Vn=i.useRef(Dn);Vn.current=Dn;const _n=i.useRef(b);_n.current=b;const Fn=!c&&u&&x==="l1";return i.useEffect(()=>{if(c||!u)return;const l=g=>{if(h?.keyboardPane==="l0"||g.metaKey||g.ctrlKey||g.altKey||vi(g.target))return;const O=g.key.length===1?g.key.toLowerCase():g.key;if(O==="h"||O==="ArrowLeft")return;const q=O==="j"||O==="ArrowDown"?1:O==="k"||O==="ArrowUp"?-1:0;if(!q)return;g.preventDefault(),g.stopPropagation(),h?.setKeyboardPane("l1");const W=Vn.current;if(W.length===0)return;const Y=_n.current;let he=Y?W.findIndex(jt=>jt.id===Y):-1;he<0&&(he=q>0?-1:0);const M=Math.max(0,Math.min(W.length-1,he+q)),G=W[M];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)},[c,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 ${Fn?"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:()=>{ws.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:Fr.map(l=>{const g=l.tabs.map(O=>_t.find(q=>q.id===O)).filter(O=>!!O);return g.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:g.map(O=>e.jsxs("button",{"data-settings-tab-id":O.id,onClick:()=>{N(O.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 ${b===O.id?Fn?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(Zr,{id:O.id,className:b===O.id?"text-fg-secondary":"text-fg-tertiary"}),e.jsx("span",{className:"truncate",children:s(`settings:${O.labelKey}`)})]},O.id))})]},l.labelKey)})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[c&&b===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:()=>ws.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:[Fr.map((l,g)=>{const O=l.tabs.map(q=>_t.find(W=>W.id===q)).filter(q=>!!q);return O.length===0?null:e.jsxs("div",{children:[g>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}`)}),O.map(q=>e.jsxs("button",{onClick:()=>N(q.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(Zr,{id:q.id,className:"text-fg-tertiary"}),e.jsx("span",{className:"flex-1 text-left",children:s(`settings:${q.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"})})]},q.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:()=>P(!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")})]})]})]})]}),c&&b!==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:y,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:${_t.find(l=>l.id===b)?.labelKey||"title"}`)})]}),b!==null&&e.jsxs("div",{className:"p-4 md:p-8 space-y-8 max-w-4xl mx-auto w-full",children:[e.jsx(Wd,{tab:b}),b==="appearance"&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{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(Kr,{label:s("systemStatus.status"),value:I.status==="ok"?s("systemStatus.healthy"):I.status,color:"green"}),e.jsx(Kr,{label:s("systemStatus.version"),value:I.version,color:"indigo"}),e.jsx(Kr,{label:s("systemStatus.activeAgents"),value:String(I.agents),color:"purple"})]}):e.jsx("div",{className:"text-sm text-fg-tertiary",children:s("common:loading")})}),e.jsxs("div",{className:`${we} divide-y divide-border-default/40`,children:[e.jsx(je,{label:s("appearance.theme"),hint:s("appearance.themeDesc"),children:e.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-secondary/60 rounded-lg p-0.5",children:bi.map(({value:l})=>e.jsx("button",{onClick:()=>r?.(l),className:`px-3 py-1.5 text-[11px] 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(je,{label:s("appearance.language"),hint:s("appearance.languageDesc"),children:e.jsx("div",{className:"flex flex-wrap gap-1 bg-surface-secondary/60 rounded-lg p-0.5",children:Wn.map(({code:l,label:g})=>e.jsx("button",{onClick:()=>{d.changeLanguage(l),U.settings.updateSearch({language:l}).catch(()=>{})},className:`px-3 py-1.5 text-[11px] rounded-md transition-colors ${d.language===l||l==="en"&&!Wn.some(O=>O.code===d.language)?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary"}`,children:g},l))})}),zn()&&e.jsx(je,{label:s("appearance.launchAtLogin"),hint:s("appearance.launchAtLoginDesc"),children:e.jsx(Ye,{checked:A,onChange:()=>{T()},label:s("appearance.launchAtLogin"),disabled:w})})]}),e.jsx(Id,{})]}),Bn&&e.jsxs(e.Fragment,{children:[b==="providers"&&e.jsxs(e.Fragment,{children:[C&&(()=>{const l=[],g=new Set,O=[],q=[];for(const[M,G]of Object.entries(C.providers))G.configured?O.push([M,G]):M!=="markus"&&q.push([M,G]),g.add(M);for(const M of ps)!g.has(M.id)&&M.id!=="markus"&&(q.push([M.id,{name:M.id,displayName:M.label,model:M.defaultModel,configured:!1,enabled:!1}]),g.add(M.id));O.sort((M,G)=>(G[1].enabled?1:0)-(M[1].enabled?1:0)),l.push(...O,...q);const W=O.length>0,he=C.providers.markus?.configured??!1;return e.jsxs(e.Fragment,{children:[!he&&e.jsx(ke,{title:"Markus Cloud AI",children:e.jsxs("div",{className:"bg-surface-secondary border border-brand-500/30 rounded-xl overflow-hidden transition-colors hover:border-brand-500/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-4 md:px-5 cursor-pointer",onClick:()=>{X(H==="markus"?null:"markus"),vt(""),Ce(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 ${H==="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"})})]}),H==="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:()=>ws.navigate(qr.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(zd,{title:s("modelProviders.title"),defaultCollapsed:W,configuredProviders:O,t:s,onBadgeClick:M=>{X(M),vt(""),Ce(null),setTimeout(()=>{document.querySelector(`[data-provider-id="${M}"]`)?.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:O.length})}),l.map(([M,G],jt)=>{const xr=!G.configured&&(jt===0||l[jt-1][1].configured);return e.jsxs("div",{"data-provider-id":M,children:[xr&&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:()=>{X(H===M?null:M),vt(""),Ce(null),at([]),We(Q=>({...Q,name:"",model:""}))},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-2 h-2 shrink-0 rounded-full ${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-[13px] font-medium",children:G.displayName??M}),M===C.defaultProvider&&e.jsx(Je,{tone:"brand",children:s("modelProviders.badgeDefault")}),G.configured&&!G.enabled&&e.jsx(Je,{tone:"warn",children:s("modelProviders.disabled")}),G.oauthConnected&&e.jsx(Je,{tone:"ok",children:s("modelProviders.badgeOAuth")}),oe[M]?.ok===!0&&e.jsx(Je,{tone:"ok",children:s("modelProviders.testOk",{ms:oe[M].durationMs})}),oe[M]?.ok===!1&&e.jsx(Je,{tone:"danger",title:oe[M].error,children:oe[M].errorCode?s("modelProviders.testFailedCode",{code:oe[M].errorCode}):oe[M].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}):"",M!=="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(),So(M,!G.enabled)},disabled:me===M,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${G.enabled?"bg-green-500":"bg-gray-600"} ${me===M?"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:H===M?"▲":"▼"})]})]}),H===M&&e.jsxs("div",{className:"px-4 md:px-5 pb-4 border-t border-border-default pt-4 space-y-4",children:[M==="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:()=>{Vt()},disabled:Xe,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 ${Xe?"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(Xe?"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:()=>ut(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:wt(Q.size)})]})]})]})},Q.name))}),e.jsx("button",{onClick:()=>{Ao()},disabled:Xt||!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:Xt?s("common:applying"):G.configured?s("ollama.switchModel"):s("ollama.useModel",{model:De})}),et&&e.jsx(ot,{type:et.type,text:et.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:[Io===M?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=>dr({...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=>dr({...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:()=>{Bo(M)},disabled:wn,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(wn?"common:saving":"common:save")}),e.jsx("button",{onClick:()=>lr(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(Qa,{value:On[M]??"",options:Ho(M),onChange:Q=>Fo(Oe=>({...Oe,[M]: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(),Uo(M)},disabled:In===M,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:In===M?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")}),M!=="markus"&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),$o(M,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")}),M!=="markus"&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),ur({name:M,label:G.displayName??M})},disabled:Sn===M,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(Sn===M?"common:deleting":"common:delete")})]})]}),oe[M]&&e.jsxs("details",{className:`text-xs rounded-lg border ${oe[M].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 ${oe[M].ok?"text-green-600":"text-red-500"}`,children:oe[M].ok?s("modelProviders.testSuccess",{ms:oe[M].durationMs,reply:oe[M].reply}):Ko(oe[M])}),e.jsxs("div",{className:"px-3 pb-2 pt-1 space-y-1 text-[11px] text-fg-muted border-t border-current/10",children:[M!=="markus"&&oe[M].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:oe[M].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:oe[M].model??G.model})]}),!!oe[M].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(oe[M].requestBody,null,2)})]}),oe[M].ok&&oe[M].reply&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.response"),":"]})," ",oe[M].reply]}),oe[M].usage&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.tokens"),":"]})," ",s("modelProviders.testDetail.inputTokens")," ",oe[M].usage.inputTokens??oe[M].usage.prompt_tokens??"-"," / ",s("modelProviders.testDetail.outputTokens")," ",oe[M].usage.outputTokens??oe[M].usage.completion_tokens??"-"]}),oe[M].durationMs!=null&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-fg-secondary",children:[s("modelProviders.testDetail.duration"),":"]})," ",oe[M].durationMs,"ms"]})]})]})]}),M==="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&&M!=="markus"&&Mn!==M&&e.jsx("button",{onClick:()=>{fs(M),hs({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")})]}),Mn===M&&e.jsx("div",{className:"bg-surface-elevated/40 rounded-lg p-3 mb-2 space-y-2",children:e.jsx(qd,{providerName:M,addModelForm:Ee,setAddModelForm:hs,addModelSaving:Lo,onAdd:()=>{Vo(M)},onCancel:()=>fs(null),t:s})}),M==="markus"&&G.configured&&(!G.models||G.models.length===0)&&(R===M?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(Kd,{models:G.models,providerName:M,activeModelId:G.model,t:s,onDeleteCustom:Q=>{_o(M,Q)}}),G.configured&&R===M&&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&&ee[M]&&ee[M].length>0&&(()=>{const Q=new Set(G.models?.map(Ae=>Ae.id)??[]),Oe=ee[M].filter(Ae=>!Q.has(String(Ae.id??"")));return Oe.length===0?null:e.jsx(Hd,{models:Oe,providerName:M,t:s,onAdd:Ae=>{const Re=Oe.find(qo=>String(qo.id??"")===Ae);Re&&(fs(M),hs({id:String(Re.id??""),name:String(Re.id??""),contextWindow:Re.maxInputTokens??128e3,maxOutputTokens:Re.maxOutputTokens??16384,costInput:Re.inputCostPer1MTokens??1,costOutput:Re.outputCostPer1MTokens??5,reasoning:Re.capabilities?.reasoning??!1,vision:Re.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")}),M==="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:`${Gt.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:H===M?_e:"",onChange:Q=>vt(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:()=>{_e.trim().length>=8&&H===M&&En(M,_e.trim())},onKeyDown:Q=>{Q.key==="Enter"&&_e.trim().length>=8&&En(M,_e.trim())}}),Ro&&H===M&&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")]})]}),H===M&&jn&&e.jsx(Ha,{variant:"inline",subject:s("settings:modelCatalog.subject"),error:jn,notEquals:s("settings:modelCatalog.noModels"),hint:s("settings:modelCatalog.retryHint")}),H===M&&or.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(qa,{provider:M,models:or,selectedModel:de.model,showTiers:!0,onSelect:Q=>{const Oe=or.find(Ae=>Ae.id===Q);We(Ae=>({...Ae,name:M,model:Q,apiKey:_e.trim(),baseUrl:ps.find(Re=>Re.id===M)?.baseUrl??"",contextWindow:Oe?.maxInputTokens??Ae.contextWindow,maxOutputTokens:Oe?.maxOutputTokens??Ae.maxOutputTokens,costInput:Oe?.inputCostPer1MTokens??Ae.costInput,costOutput:Oe?.outputCostPer1MTokens??Ae.costOutput}))},compact:!0,maxVisible:8})]}),H===M&&_e.trim()&&e.jsx("button",{onClick:()=>{de.model&&de.name===M?Rn():Oo(M)},disabled:An||gs,className:zr,children:s(An||gs?"modelProviders.quickSetupSaving":"modelProviders.quickSetupSubmit")}),mr&&H===M&&e.jsx(ot,{type:mr.type,text:mr.text})]})]})]})]},M)})]}),Eo?e.jsxs("div",{className:"mt-3 bg-surface-secondary border border-brand-500/30 rounded-xl p-4 space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-fg-primary",children:s("modelProviders.customProvider")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.providerName")}),e.jsx("input",{type:"text",value:de.name==="__custom__"?"":de.name,onChange:M=>We(G=>({...G,name:M.target.value||"__custom__"})),placeholder:"my-provider",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.baseUrl")}),e.jsx("input",{type:"text",value:de.baseUrl,onChange:M=>We({...de,baseUrl:M.target.value}),placeholder:"https://api.example.com/v1",className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.apiKey")}),e.jsx("input",{type:"password",value:de.apiKey,onChange:M=>We({...de,apiKey:M.target.value}),placeholder:s("modelProviders.placeholderApiKeySk"),className:"w-full px-3 py-2 text-sm bg-surface-elevated border border-border-default rounded-lg text-fg-primary placeholder-fg-tertiary focus:border-brand-500 outline-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] text-fg-tertiary uppercase block mb-1",children:s("modelProviders.defaultModel")}),e.jsx("input",{type:"text",value:de.model,onChange:M=>We({...de,model:M.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:()=>{Rn()},disabled:gs||!de.name||de.name==="__custom__"||!de.model,className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-on-brand rounded-lg transition-colors whitespace-nowrap",children:s(gs?"modelProviders.adding":"modelProviders.addProviderSubmit")}),e.jsx("button",{onClick:()=>{nr(!1),vn(null),at([]),We({name:"",apiKey:"",baseUrl:"",model:"",contextWindow:128e3,maxOutputTokens:16384,costInput:1,costOutput:5})},className:"px-4 py-2 text-sm border border-border-default text-fg-secondary hover:bg-surface-elevated rounded-lg transition-colors whitespace-nowrap",children:s("common:cancel")})]}),ar&&e.jsx(ot,{type:ar.type,text:ar.text})]}):e.jsxs("button",{onClick:()=>nr(!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(Gn,{title:s("autoDetect.title"),defaultOpen:!1,children:e.jsxs("div",{className:`${we} 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:()=>{rr()},disabled:ge,className:"px-3 py-1 border border-border-default hover:bg-surface-elevated disabled:opacity-40 text-fg-tertiary text-xs rounded-md transition-colors flex items-center gap-1.5",children:[e.jsx("svg",{className:`w-3.5 h-3.5 ${ge?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),s(ge?"common:detecting":"envConfig.refreshEnv")]})]}),se&&se.detected.length>0&&e.jsxs("div",{className:"space-y-2",children:[se.detected.map(l=>e.jsxs("label",{className:"flex items-center justify-between gap-3 bg-surface-elevated/30 rounded-lg px-4 py-3 cursor-pointer hover:bg-surface-elevated/50 transition-colors",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("input",{type:"checkbox",checked:Pe[l.provider]??!1,onChange:g=>Be({...Pe,[l.provider]:g.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(g=>e.jsx("div",{children:e.jsx("code",{children:g})},g))})]},l.provider)),se.timeoutMs&&e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("envConfig.llmTimeout",{ms:se.timeoutMs})}),e.jsx("button",{onClick:()=>{Co()},disabled:ct||Object.values(Pe).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:ct?s("common:applying"):s("envConfig.applyToConfig",{count:Object.values(Pe).filter(Boolean).length})})]}),Ze&&e.jsx(ot,{type:Ze.type,text:Ze.text})]})]})}),e.jsx(Gn,{title:s("oauthAuth.title"),defaultOpen:!1,children:e.jsxs("div",{className:`${we} 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:[nn.map(l=>e.jsxs("div",{className:"flex",children:[e.jsx("button",{onClick:()=>bn(l.name),disabled:!!Ot,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:Ot===l.name?s("oauthAuth.connecting"):s("oauthAuth.signInWith",{name:l.displayName})}),e.jsx("button",{onClick:()=>Po(l.name),disabled:!!Ot,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)),nn.length===0&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:s("oauthAuth.noProviders")})]}),Bt&&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:Bt.verificationUri,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-brand-500 underline hover:text-brand-400",children:Bt.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:Bt.userCode})]}),e.jsx("p",{className:"text-[10px] text-fg-muted",children:s("oauthAuth.deviceWaiting")})]}),po&&!Bt&&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:is,onChange:l=>on(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:Mo,disabled:!is.trim()||Ot==="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")})]})]}),Os&&e.jsx(ot,{type:Os.type,text:Os.text}),an.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")}),an.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:()=>bn(l.provider),disabled:!!Ot,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:()=>To(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(ke,{title:s("defaultProvider.title"),children:e.jsxs("div",{className:`${we} 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:D,onChange:l=>{B(l.target.value),_(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:$n.length>0?$n.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")}),D!==C?.defaultProvider&&e.jsx("button",{onClick:()=>{ko()},disabled:S,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(S?"common:saving":"common:save")})]})]}),J&&e.jsx(ot,{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 g=await fetch("/api/settings/llm",{method:"POST",headers:le(),body:JSON.stringify({autoFallback:l})});if(g.ok){const O=await g.json();$(O)}}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(ke,{title:s("modelRouting.title"),children:e.jsx(Li,{configuredProviders:Object.entries(C?.providers??{}).filter(([,l])=>l.configured&&l.enabled).map(([l,g])=>({name:l,displayName:g.displayName,model:g.model,models:g.models?.map(O=>({id:O.id,name:O.name}))})),onSave:async l=>{const g=await fetch("/api/settings/llm",{method:"POST",headers:le(),body:JSON.stringify(l)});if(!g.ok)throw new Error(`HTTP ${g.status}`)}},C?.defaultProvider??"no-default")}),e.jsx(ke,{title:s("perAgentModel.section",{defaultValue:"Agent Default Models"}),children:e.jsx(_i,{configuredProviders:(()=>{try{return Object.entries(C?.providers??{}).filter(([,l])=>l.configured&&l.enabled).map(([l,g])=>({name:l,displayName:g.displayName,model:g.model,models:g.models?.map(O=>({id:O.id,name:O.name}))}))}catch{return[]}})()})})]}),b==="network"&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{title:s("networkProxy.title"),description:s("networkProxy.description"),children:e.jsxs("div",{className:`${we} divide-y divide-border-default/40`,children:[e.jsx(je,{label:s("networkProxy.enabledLabel"),children:e.jsx("button",{onClick:async()=>{const l=!ye;Ue(l);try{await fetch("/api/settings/network",{method:"POST",headers:le(),body:JSON.stringify({proxyEnabled:l})}),nt()}catch{Ue(!l)}},className:`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors ${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"}`})})}),e.jsx(je,{label:s("networkProxy.addressLabel"),hint:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ye&&Le?.proxy?"bg-emerald-500":"bg-fg-muted"}`}),e.jsx("span",{children:ye?Le?.proxy?s("networkProxy.active"):s("networkProxy.noProxy"):s("networkProxy.disabled")}),ye&&Le&&Le.source!=="none"&&Le.source!=="disabled"&&e.jsx("span",{className:`rounded px-1.5 py-0.5 text-[11px] font-medium ${Le.source==="env"?"bg-amber-500/10 text-amber-600 dark:text-amber-400":"bg-brand-500/10 text-brand-600 dark:text-brand-400"}`,children:Le.source==="config"?s("networkProxy.sourceConfig"):Le.source==="env"?s("networkProxy.sourceEnv"):s("networkProxy.sourceSystem")}),e.jsxs("button",{onClick:()=>nt(),className:"inline-flex items-center gap-1 text-[11px] text-fg-tertiary transition-colors hover:text-fg-secondary",title:s("networkProxy.refresh"),children:[e.jsx("svg",{className:"h-3 w-3",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")]})]}),It&&e.jsx("div",{className:It.ok?"text-emerald-600 dark:text-emerald-400":"text-red-500",children:It.text}),Is&&e.jsx("div",{className:Is.type==="ok"?"text-emerald-600 dark:text-emerald-400":"text-red-500",children:Is.text})]}),children:e.jsxs("div",{className:`flex w-full flex-wrap items-center gap-2 transition-opacity sm:w-auto ${ye?"":"pointer-events-none opacity-40"}`,children:[e.jsx("input",{type:"text",value:Mt,onChange:l=>ts(l.target.value),placeholder:s("networkProxy.placeholder"),className:"w-full min-w-0 px-3 py-1.5 text-[13px] 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 sm:w-[250px]"}),e.jsx("button",{onClick:async()=>{rn(!0),os(null);try{const l=await fetch("/api/settings/network",{method:"POST",headers:le(),body:JSON.stringify({proxy:Mt.trim()})});if(l.ok)os({type:"ok",text:s("networkProxy.saved")}),nt();else{const g=await l.json();os({type:"err",text:g.error??s("networkProxy.saveFailed")})}}catch{os({type:"err",text:s("networkProxy.networkError")})}finally{rn(!1)}},disabled:sn,className:`${zr} min-w-[72px] shrink-0`,children:s(sn?"networkProxy.saving":"networkProxy.save")}),e.jsxs("button",{onClick:()=>{gt(!0),tt(null),fetch("/api/settings/network/test",{method:"POST",headers:le(),body:JSON.stringify({})}).then(async l=>{const g=await l.json();if(!l.ok)throw new Error(`HTTP ${l.status}`);if(g.ok)tt({ok:!0,text:s("networkProxy.testResult",{ip:g.exitIp??"—",ms:g.latencyMs??0,route:g.proxied?s("networkProxy.viaProxy"):s("networkProxy.direct")})});else{const O=Mi(g.failure);tt({ok:!1,text:s(O.key,O.params)})}}).catch(l=>tt({ok:!1,text:s("networkProxy.failClient",{detail:l instanceof Error?l.message:String(l)})})).finally(()=>gt(!1))},disabled:Rt,className:`${it} shrink-0`,title:s("networkProxy.testHint"),children:[Rt?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"})]}):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:"M13 10V3L4 14h7v7l9-11h-7z"})}),s(Rt?"networkProxy.testing":"networkProxy.test")]})]})}),e.jsx("div",{className:"px-5 py-3.5",children:e.jsx(Qd,{noProxyList:ss,setNoProxyList:mt,noProxyEntry:rs,setNoProxyEntry:xt,authHeaders:le,loadNetworkSettings:nt,t:s})})]})}),e.jsx(ke,{title:s("accessScope.title"),description:s("accessScope.description"),children:e.jsxs("div",{className:`${we} divide-y divide-border-default/40`,children:[e.jsx(je,{label:s("accessScope.scopeLabel"),hint:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`mr-1.5 inline-block h-1.5 w-1.5 rounded-full align-middle ${E!=="local"?"bg-emerald-500":"bg-fg-muted"}`}),s("accessScope.current",{host:Lt})," · ",e.jsx("span",{className:E==="lan"?"text-emerald-600 dark:text-emerald-400":void 0,children:s(E==="local"?"accessScope.localOnlyHint":E==="lan"?"accessScope.lanHint":"accessScope.remoteHint")}),Te&&e.jsxs("span",{className:"text-amber-500",children:[" · ⚠ ",s("accessScope.envControlled")]})]}),children:e.jsxs("div",{className:"inline-flex flex-wrap gap-1 rounded-lg bg-surface-secondary/80 p-1",children:[e.jsx("button",{disabled:Te||Ke||n?.role!=="owner",onClick:()=>{He("local")},className:`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${E==="local"&&!Te?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary"} ${Te||Ke||n?.role!=="owner"?"cursor-not-allowed opacity-40":""}`,children:s("accessScope.localOnly")}),e.jsx("button",{disabled:Te||Ke||n?.role!=="owner",onClick:()=>{He("lan")},className:`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${E==="lan"&&!Te?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary"} ${Te||Ke||n?.role!=="owner"?"cursor-not-allowed opacity-40":""}`,children:s("accessScope.lan")}),e.jsx("button",{onClick:()=>ue("remote"),className:`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${E==="remote"?"bg-brand-600 text-on-brand shadow-sm":"text-fg-secondary hover:text-fg-primary"}`,children:s("accessScope.remote")})]})}),ft&&e.jsx("div",{className:`px-5 py-3 text-[11px] ${ft.warn?"text-amber-500":"text-emerald-600 dark:text-emerald-400"}`,children:ft.text})]})}),E==="remote"&&e.jsx(ld,{})]}),b==="execution"&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{title:s("agentExecution.title"),children:e.jsxs("div",{className:`${we} divide-y divide-border-default/40`,children:[e.jsx(je,{label:s("agentExecution.maxToolIterations"),hint:s("agentExecution.maxToolIterationsDesc"),children:e.jsx("input",{type:"number",min:0,value:Bs,onChange:l=>{const g=Number(l.target.value);Ds(g),st.schedule({maxToolIterations:g,maxPendingTasksPerAgent:Vs,maxPendingRequirementProposals:Fs})},className:`${kt} w-24 text-right tabular-nums`})}),e.jsx(je,{label:s("agentExecution.maxPendingTasksPerAgent"),hint:s("agentExecution.maxPendingTasksPerAgentDesc"),children:e.jsx("input",{type:"number",min:1,value:Vs,onChange:l=>{const g=Number(l.target.value);_s(g),st.schedule({maxToolIterations:Bs,maxPendingTasksPerAgent:g,maxPendingRequirementProposals:Fs})},className:`${kt} w-24 text-right tabular-nums`})}),e.jsx(je,{label:s("agentExecution.maxPendingRequirementProposals"),hint:s("agentExecution.maxPendingRequirementProposalsDesc"),children:e.jsx("input",{type:"number",min:1,value:Fs,onChange:l=>{const g=Number(l.target.value);Us(g),st.schedule({maxToolIterations:Bs,maxPendingTasksPerAgent:Vs,maxPendingRequirementProposals:g})},className:`${kt} w-24 text-right tabular-nums`})}),e.jsx("div",{className:"flex items-center justify-end px-5 py-3.5 min-h-[2.75rem]",children:st.state!=="idle"&&e.jsx("span",{className:`text-xs ${st.state==="error"?"text-red-500":"text-fg-tertiary"}`,"data-testid":"agent-autosave-state",children:st.state==="saving"?s("common:saving"):st.state==="saved"?s("agentExecution.saved"):s("agentExecution.failedToSave")})})]})}),e.jsx(ke,{title:s("concurrent.title"),description:s("concurrent.description"),children:e.jsxs("div",{className:`${we} divide-y divide-border-default/40`,children:[e.jsx(je,{label:s("concurrent.enabled"),hint:s("concurrent.enabledDesc"),children:e.jsx(Ye,{checked:Dt,onChange:l=>{Ks(l),rt.schedule({enabled:l,maxWorkers:Hs,conflictPolicy:zs})},label:s("concurrent.enabled")})}),e.jsx(je,{label:s("concurrent.maxWorkers"),hint:s("concurrent.maxWorkersDesc"),children:e.jsx("input",{type:"number",min:1,max:10,disabled:!Dt,value:Hs,onChange:l=>{const g=Number(l.target.value);qs(g),rt.schedule({enabled:Dt,maxWorkers:g,conflictPolicy:zs})},className:`${kt} w-24 text-right tabular-nums disabled:opacity-40`})}),e.jsx(je,{label:s("concurrent.conflictPolicy"),hint:s("concurrent.conflictPolicyDesc"),children:e.jsxs("select",{value:zs,disabled:!Dt,onChange:l=>{const g=l.target.value;Ws(g),rt.schedule({enabled:Dt,maxWorkers:Hs,conflictPolicy:g})},className:`${kt} 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 px-5 py-3.5 min-h-[2.75rem]",children:rt.state!=="idle"&&e.jsx("span",{className:`text-xs ${rt.state==="error"?"text-red-500":"text-fg-tertiary"}`,"data-testid":"conc-autosave-state",children:rt.state==="saving"?s("common:saving"):rt.state==="saved"?s("concurrent.saved"):s("concurrent.failedToSave")})})]})})]}),b==="browser"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3.5",children:[e.jsxs("div",{className:`${we} 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()=>{xe(!0),Z(null);try{const l=await U.settings.updateBrowser({mode:"embedded"});Gs(l.mode??"embedded"),Z({type:"ok",text:s("browserAutomation.backendSwitchToEmbedded")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}xe(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${bt==="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 ${bt==="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()=>{xe(!0),Z(null);try{const l=await U.settings.updateBrowser({mode:"system-chrome"});Gs(l.mode??"system-chrome"),Z({type:"ok",text:s("browserAutomation.backendSwitchToSystemChrome")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}xe(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${bt==="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 ${bt==="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:`${we} 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()=>{xe(!0),Z(null);try{const l=await U.settings.updateBrowser({elementSelection:"direct"});Js(l.elementSelection??"direct"),Z({type:"ok",text:s("browserAutomation.elementSelectionSwitchToDirect")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}xe(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${ls==="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 ${ls==="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()=>{xe(!0),Z(null);try{const l=await U.settings.updateBrowser({elementSelection:"jev"});Js(l.elementSelection??"jev"),Z({type:"ok",text:s("browserAutomation.elementSelectionSwitchToJev")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}xe(!1)},disabled:pe,className:`text-left p-4 rounded-xl border transition-colors ${ls==="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 ${ls==="jev"?"bg-brand-400":"bg-gray-500"}`})]}),e.jsx("div",{className:"text-xs text-fg-tertiary mt-1",children:s("browserAutomation.elementSelectionJevDesc")})]})]})]}),bt==="embedded"?e.jsxs("div",{className:`${we} 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()=>{xe(!0),Z(null);try{const l=await U.settings.testConcurrentBrowserQuick();Z({type:l.connected?"ok":"err",text:l.connected?s("browserAutomation.backendVerifyOk"):s("browserAutomation.backendVerifyFail",{error:l.summary||"backend not reachable"})})}catch(l){Z({type:"err",text:s("browserAutomation.backendVerifyFail",{error:l?.message||l||"unknown"})})}xe(!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 ${qe?"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 ${qe?"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 ${qe?"bg-green-400":"bg-gray-400"}`}),s(qe?"browserAutomation.extensionConnected":"browserAutomation.extensionDisconnected")]})]}),e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("browserAutomation.extensionStatusDesc")}),qe?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()=>{xe(!0),Z(null);try{await U.settings.downloadExtensionZip()}catch{Z({type:"err",text:s("browserAutomation.extensionDownloadError")})}xe(!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()=>{xe(!0),Z(null);try{await U.settings.openExtensionsPage()}catch{Z({type:"err",text:s("browserAutomation.extensionOpenError")})}xe(!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()=>{xe(!0),Z(null);try{const l=await U.settings.testConcurrentBrowserQuick();Z({type:l.connected?"ok":"err",text:l.connected?s("browserAutomation.backendVerifyOk"):s("browserAutomation.backendVerifyFail",{error:l.summary||"backend not reachable"})})}catch(l){Z({type:"err",text:s("browserAutomation.backendVerifyFail",{error:l?.message||l||"unknown"})})}xe(!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:`${we} 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=!Ys;ds(l),xe(!0),Z(null);try{const g=await U.settings.updateBrowser({bringToFront:l});ds(g.bringToFront),Z({type:"ok",text:s(l?"browserAutomation.tabsForeground":"browserAutomation.tabsBackground")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")}),ds(!l)}xe(!1)},disabled:pe,className:`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${Ys?"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 ${Ys?"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=!Zs;cs(l),xe(!0),Z(null);try{const g=await U.settings.updateBrowser({autoCloseTabs:l});cs(g.autoCloseTabs),Z({type:"ok",text:s("agentExecution.saved")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")}),cs(!l)}xe(!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"}`})})]})]}),bt==="system-chrome"&&!qe&&e.jsxs("div",{className:`${we} 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()=>{xe(!0),Z(null);try{const l=await U.settings.testAutoClick(),g={success:{type:"ok",text:s("browserAutomation.autoClickTestSuccess",{title:l.pageTitle||"example.com"})},no_permission:{type:"err",text:s("browserAutomation.autoClickTestNoPermission")},chrome_not_running:{type:"err",text:s("browserAutomation.autoClickTestChromeNotRunning")},unsupported:{type:"err",text:s("browserAutomation.autoClickTestUnsupported")},error:{type:"err",text:s("browserAutomation.autoClickTestError",{error:l.error||"unknown"})}};Z(g[l.clickResult]??{type:"err",text:l.clickResult})}catch{Z({type:"err",text:s("browserAutomation.autoClickTestError",{error:"request failed"})})}xe(!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=!Xs;us(l),xe(!0),Z(null);try{const g=await U.settings.updateBrowser({autoClickAllowDialog:l});us(g.autoClickAllowDialog),Z({type:"ok",text:s("agentExecution.saved")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")}),us(!l)}xe(!1)},disabled:pe,className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${Xs?"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 ${Xs?"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:cn,onChange:l=>{Qs(Number(l.target.value)),Z(null)},className:"w-24 px-3 py-1.5 text-sm border border-border-default rounded-lg bg-surface-primary text-fg-primary text-right",placeholder:"0"}),e.jsx("button",{disabled:pe,onClick:async()=>{xe(!0),Z(null);try{const l=await U.settings.updateBrowser({remoteDebuggingPort:cn});Qs(l.remoteDebuggingPort),Z({type:"ok",text:l.remoteDebuggingPort>0?s("browserAutomation.usingPort",{port:l.remoteDebuggingPort}):s("browserAutomation.usingAutoConnect")})}catch{Z({type:"err",text:s("agentExecution.failedToSave")})}xe(!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")})]})]})})]}),er&&e.jsx("div",{className:"mt-4",children:e.jsx(ot,{type:er.type,text:er.text})})]}),!1]}),b==="search"&&e.jsx(Rd,{}),b==="storage"&&e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-3.5",children:e.jsxs("div",{className:`${we} p-5 space-y-5`,children:[tr&&!Ve&&e.jsxs("div",{className:"space-y-5","data-testid":"data-storage-skeleton",role:"status","aria-busy":"true",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 space-y-2",children:[e.jsx("div",{className:"h-8 w-32 animate-pulse rounded bg-surface-secondary"}),e.jsx("div",{className:"h-3 w-64 animate-pulse rounded bg-surface-secondary"})]}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[e.jsx("div",{className:"h-8 w-20 animate-pulse rounded-lg bg-surface-secondary"}),e.jsx("div",{className:"h-8 w-24 animate-pulse rounded-lg bg-surface-secondary"})]})]}),e.jsx("div",{className:"h-2 w-full animate-pulse rounded-full bg-surface-secondary"}),e.jsx("div",{className:"h-3 w-72 animate-pulse rounded bg-surface-secondary"})]}),e.jsxs("div",{className:"border-t border-border-default pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-baseline justify-between gap-3",children:[e.jsx("div",{className:"h-3 w-20 animate-pulse rounded bg-surface-secondary"}),e.jsx("div",{className:"h-3 w-16 animate-pulse rounded bg-surface-secondary"})]}),e.jsx("div",{className:"divide-y divide-border-default/70 overflow-hidden rounded-xl border border-border-default/70",children:[0,1,2,3,4].map(l=>e.jsxs("div",{className:"flex items-center gap-3 px-3.5 py-3",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 animate-pulse rounded bg-surface-secondary",style:{width:`${30+l*13%30}%`}}),e.jsx("div",{className:"h-3 animate-pulse rounded bg-surface-secondary",style:{width:`${55+l*9%25}%`}})]}),e.jsxs("div",{className:"shrink-0 space-y-1.5 text-right",children:[e.jsx("div",{className:"ml-auto h-4 w-14 animate-pulse rounded bg-surface-secondary"}),e.jsx("div",{className:"ml-auto h-3 w-8 animate-pulse rounded bg-surface-secondary"})]}),e.jsx("div",{className:"h-7 w-[4.5rem] shrink-0 animate-pulse rounded-lg bg-surface-secondary"})]},l))})]}),e.jsxs("div",{className:"flex items-start gap-2 text-xs leading-relaxed text-fg-tertiary",children:[e.jsx("span",{className:"mt-0.5 inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-2 border-border-default border-t-fg-tertiary","aria-hidden":!0}),e.jsx("span",{children:s("dataStorage.scanningHint")})]})]}),Ve&&(()=>{const l=[...Ve.breakdown].filter(Y=>Y.size>0).sort((Y,he)=>he.size-Y.size),g=Math.max(Ve.totalSize,1),q=l.filter(Y=>Ur[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:wt(Ve.totalSize,s)}),e.jsx("div",{className:"text-xs text-fg-tertiary font-mono mt-1 truncate",title:Ve.dataDir,children:Ve.dataDir})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>yt(),disabled:tr,className:it,children:s(tr?"dataStorage.scanning":"common:refresh")}),e.jsx("button",{onClick:()=>{U.system.openPath(Ve.dataDir)},className:it,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=Ur[Y.name]??"caution",M=Math.max(Y.size/g*100,Y.size>0?.8:0);return e.jsx("div",{className:`h-full ${W(he)}`,style:{width:`${M}%`},title:`${Y.name}: ${wt(Y.size,s)}`},Y.name)})}),q>0&&e.jsx("p",{className:"text-xs text-fg-tertiary leading-relaxed",children:s("dataStorage.clearableHint",{size:wt(q,s),percent:Math.round(q/g*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=$d[Y.name],M=Ur[Y.name]??"caution",G=he?s(`dataStorage.items.${he}.label`):Y.name,jt=he?s(`dataStorage.items.${he}.blurb`):Y.description,xr=Math.round(Y.size/g*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}),M==="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:jt})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary tabular-nums",children:wt(Y.size,s)}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary tabular-nums mt-0.5",children:[xr,"%"]})]}),e.jsx("button",{type:"button",onClick:()=>{U.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)})})]}),ms&&(ms.orphanAgents.length>0||ms.orphanTeams.length>0)&&e.jsx(Gd,{orphanInfo:ms,dataDir:Ve.dataDir,onPurged:yt,formatBytes:Y=>wt(Y,s)})]})})()]})})}),b==="facts"&&e.jsx(yi,{role:n?.role,authUser:n}),b==="account"&&e.jsx(Jd,{authUser:n}),b==="integrations"&&e.jsx(od,{}),b==="external-sources"&&e.jsx(Td,{})]}),e.jsx("div",{className:"h-8"})]}),cr&&e.jsx(Cs,{title:s("common:delete"),message:s("modelProviders.deleteConfirm",{name:cr.label}),confirmLabel:s("common:delete"),onConfirm:()=>{const l=cr.name;ur(null),Do(l)},onCancel:()=>ur(null)}),k&&a&&e.jsx(Cs,{title:s("common:signOutConfirmTitle"),message:s("common:signOutConfirmMessage"),confirmLabel:s("common:signOut"),variant:"primary",onConfirm:()=>{P(!1),a()},onCancel:()=>P(!1)})]})]})}const Fa=["owner","admin","member","guest"],_d={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 Fd({authUser:t}){const{t:r}=ce(["settings","common"]),[n,a]=i.useState([]),[o,s]=i.useState(!0),[d,c]=i.useState(null),[u,h]=i.useState(""),[x,v]=i.useState(""),[j,k]=i.useState(""),[P,N]=i.useState(null),[y,b]=i.useState(""),[A,m]=i.useState(null),[w,V]=i.useState(null),[T,I]=i.useState(null),[F,C]=i.useState(!1),[$,D]=i.useState(""),[B,S]=i.useState(""),[L,J]=i.useState("member"),[_,H]=i.useState(""),X=i.useCallback(()=>{U.users.list(t?.orgId).then(p=>a(p.users)).catch(()=>{}).finally(()=>s(!1))},[t?.orgId]);i.useEffect(()=>{X()},[X]);const me=p=>{c(p.id),h(p.name),v(p.role),k(p.email??""),I(null)},ie=async()=>{if(d)try{await U.users.update(d,{name:u,role:x,email:j||void 0}),c(null),I({type:"ok",text:r("settings:userManagement.updateSuccess")}),X()}catch(p){I({type:"err",text:`${r("settings:userManagement.error")}: ${String(p)}`})}},ee=async()=>{if(!(!P||!y))try{await U.users.resetPassword(P,y),N(null),b(""),I({type:"ok",text:r("settings:userManagement.resetSuccess")})}catch(p){I({type:"err",text:`${r("settings:userManagement.error")}: ${String(p)}`})}},f=async p=>{if(p===t?.id){I({type:"err",text:r("settings:userManagement.cannotDeleteSelf")}),m(null);return}if(n.find(z=>z.id===p)?.role==="owner"){I({type:"err",text:r("settings:userManagement.cannotDeleteOwner")}),m(null);return}try{await U.users.remove(p),m(null),I({type:"ok",text:r("settings:userManagement.deleteSuccess")}),X()}catch(z){I({type:"err",text:`${r("settings:userManagement.error")}: ${String(z)}`})}},R=async()=>{if($.trim())try{const p=await U.users.create($.trim(),L,void 0,B.trim()||void 0,_||void 0);C(!1),D(""),S(""),J("member"),H(""),I({type:"ok",text:r("settings:userManagement.addSuccess",{defaultValue:"User created"})}),p.inviteToken&&V(`${window.location.origin}/#invite?token=${p.inviteToken}`),X()}catch(p){I({type:"err",text:`${r("settings:userManagement.error")}: ${p instanceof Error?p.message:String(p)}`})}};return e.jsxs("div",{className:"space-y-3",children:[F?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:$,onChange:p=>D(p.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:B,onChange:p=>S(p.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:L,onChange:p=>J(p.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:Fa.map(p=>e.jsx("option",{value:p,children:r(`settings:userManagement.roles.${p}`)},p))})]}),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:_,onChange:p=>H(p.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),D(""),S(""),J("member"),H("")},className:"px-3 py-1.5 text-xs text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:R,disabled:!$.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:[T&&e.jsx("div",{className:`px-4 py-2 text-xs border-b ${T.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:T.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:()=>V(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:[o&&n.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"px-4 py-6",children:e.jsx(Ni,{rows:3,variant:"skeleton"})})}),!o&&n.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")})}),n.map(p=>{const K=d===p.id,z=P===p.id,se=A===p.id,ae=p.id===t?.id,ge=p.role==="owner";return e.jsxs("tr",{className:"border-b border-border-default/40 last:border-b-0 hover:bg-surface-elevated/40 transition-colors",children:[e.jsx("td",{className:"px-4 py-2.5",children:K?e.jsx("input",{value:u,onChange:te=>h(te.target.value),className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-fg-primary font-medium text-xs",children:p.name}),ae&&e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500",children:"you"})]})}),e.jsx("td",{className:"px-4 py-2.5",children:K?e.jsx("input",{value:j,onChange:te=>k(te.target.value),placeholder:"email@example.com",className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}):e.jsx("span",{className:"text-fg-secondary text-xs",children:p.email||"—"})}),e.jsx("td",{className:"px-4 py-2.5",children:K?e.jsx("select",{value:x,onChange:te=>v(te.target.value),className:"px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50",children:Fa.map(te=>e.jsx("option",{value:te,children:r(`settings:userManagement.roles.${te}`)},te))}):e.jsx("span",{className:`inline-block text-[10px] px-2 py-0.5 rounded-full border font-medium ${_d[p.role]??""}`,children:r(`settings:userManagement.roles.${p.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:()=>c(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:ie,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium",children:r("settings:userManagement.save")})]}):z?e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("input",{type:"password",value:y,onChange:te=>b(te.target.value),placeholder:r("settings:userManagement.newPassword"),autoFocus:!0,className:"w-32 px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-brand-500/50"}),e.jsx("button",{onClick:()=>{N(null),b("")},className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:ee,disabled:y.length<6,className:"text-[11px] text-brand-500 hover:text-brand-400 font-medium disabled:opacity-40",children:r("settings:userManagement.confirmReset")})]}):se?e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("span",{className:"text-[10px] text-red-500",children:r("settings:userManagement.confirmDelete")}),e.jsx("button",{onClick:()=>m(null),className:"text-[11px] text-fg-tertiary hover:text-fg-secondary",children:r("settings:userManagement.cancel")}),e.jsx("button",{onClick:()=>f(p.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:()=>me(p),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")}),p.email&&e.jsx("button",{onClick:()=>{N(p.id),b(""),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")}),p.email&&!ge&&!p.hasJoined&&e.jsx("button",{onClick:async()=>{try{const{inviteToken:te}=await U.users.reinvite(p.id),Ze=`${window.location.origin}/#invite?token=${te}`;V(Ze),I({type:"ok",text:r("settings:userManagement.inviteLinkGenerated")})}catch(te){I({type:"err",text:String(te)})}},className:"text-[11px] text-brand-400 hover:text-brand-500 px-1.5 py-0.5 rounded hover:bg-brand-500/10",children:r("settings:userManagement.inviteLink")}),!ge&&!ae&&e.jsx("button",{onClick:()=>{m(p.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")})]})})]},p.id)})]})]})})]})]})}const Ud={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"}},Ua={chat:0,image_generation:1,video_generation:2,audio_speech:3,audio_transcription:4,ocr:5},Ka=5;function Kd({models:t,providerName:r,activeModelId:n,t:a,onDeleteCustom:o}){const s=t.length>Ka,[d,c]=i.useState(!s),[u,h]=i.useState(""),x=i.useMemo(()=>{const j=u.trim().toLowerCase();return j?t.filter(k=>k.id.toLowerCase().includes(j)||k.name.toLowerCase().includes(j)):t},[t,u]),v=d?x:x.slice(0,Ka);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:()=>c(j=>!j),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 ${d?"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"})}),d?a("modelProviders.collapseModels"):a("modelProviders.showAllModels",{count:t.length})]}),d&&e.jsx("input",{value:u,onChange:j=>h(j.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:d&&s?"max-h-64 overflow-y-auto space-y-1 pr-0.5":"space-y-1",children:v.map(j=>{const k=j.source==="custom",P=j.capabilities??[],N=n===j.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:j.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(Yd,{modelId:j.id,tier:j.tier}),j.reasoning&&e.jsx("span",{className:"text-[9px] bg-amber-500/15 text-amber-600 px-1 py-0.5 rounded",children:a("modelProviders.reasoning")}),(j.inputTypes?.includes("image")||P.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")}),P.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")}),(P.includes("tts")||P.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")}),(P.includes("stt")||P.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")}),P.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")}),k&&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:[(j.contextWindow??0)>0&&e.jsx("span",{children:a("modelProviders.ctxTokens",{size:((j.contextWindow??0)/1e3).toFixed(0)})}),k&&r!=="markus"&&e.jsx("button",{onClick:y=>{y.stopPropagation(),o(j.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"})})})]})]},j.id)})}),s&&!d&&e.jsx("button",{type:"button",onClick:()=>c(!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})}),d&&u&&x.length===0&&e.jsx("div",{className:"text-[10px] text-fg-tertiary px-1 py-2",children:a("modelProviders.noFilterMatches")})]})}function Hd({models:t,providerName:r,t:n,onAdd:a}){const[o,s]=i.useState(!1),d=i.useMemo(()=>[...t].sort((c,u)=>{const h=Ua[c.mode??"chat"]??99,x=Ua[u.mode??"chat"]??99;return h!==x?h-x:String(c.id??"").localeCompare(String(u.id??""))}),[t]);return e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{onClick:()=>s(!o),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 ${o?"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"})}),n("modelProviders.catalogModelsAvailable",{count:t.length})]}),o&&e.jsx("div",{className:"mt-1 space-y-0.5 pl-1 max-h-64 overflow-y-auto",children:d.map(c=>{const u=String(c.id??""),h=c.mode??"chat",x=Ud[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:n("modelProviders.addModel")})]},u)})})]})}function qd({providerName:t,addModelForm:r,setAddModelForm:n,addModelSaving:a,onAdd:o,onCancel:s,t:d}){const[c,u]=i.useState([]),[h,x]=i.useState(!1),[v,j]=i.useState(null),[k,P]=i.useState(!1),N=async()=>{x(!0),j(null);const y=await mo(t);u(y.state==="ok"?[...y.items]:[]),y.state==="error"&&j(y.error??d("common:readFailed")),P(y.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:d("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?"...":d("modelProviders.browseFromCatalog")})]}),v&&e.jsx(Ha,{variant:"inline",subject:d("settings:modelCatalog.subject"),error:v,notEquals:d("settings:modelCatalog.noModels"),onRetry:()=>{N()}}),k&&c.length>0&&e.jsx("div",{className:"border border-border-default rounded-lg p-2 mb-2",children:e.jsx(qa,{provider:t,models:c,selectedModel:r.id,showTiers:!0,onSelect:y=>{const b=c.find(A=>A.id===y);b&&n(A=>({...A,id:b.id,name:b.id,contextWindow:b.maxInputTokens,maxOutputTokens:b.maxOutputTokens,costInput:b.inputCostPer1MTokens,costOutput:b.outputCostPer1MTokens,reasoning:b.capabilities.reasoning,vision:b.capabilities.vision}))},compact:!0,maxVisible:5})}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsx("input",{type:"text",placeholder:d("modelProviders.modelId"),value:r.id,onChange:y=>n({...r,id:y.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:d("modelProviders.displayName"),value:r.name,onChange:y=>n({...r,name:y.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:d("modelProviders.placeholderContextTokens"),value:r.contextWindow,onChange:y=>n({...r,contextWindow:Number(y.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:d("modelProviders.maxOutput"),value:r.maxOutputTokens,onChange:y=>n({...r,maxOutputTokens:Number(y.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:d("modelProviders.costPerMillionIn")}),e.jsx("input",{type:"number",step:"0.01",value:r.costInput,onChange:y=>n({...r,costInput:Number(y.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:d("modelProviders.costPerMillionOut")}),e.jsx("input",{type:"number",step:"0.01",value:r.costOutput,onChange:y=>n({...r,costOutput:Number(y.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:y=>n({...r,reasoning:y.target.checked}),className:"rounded"}),d("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:y=>n({...r,vision:y.target.checked}),className:"rounded"}),d("modelProviders.vision")]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:o,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:d(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:d("common:cancel")})]})]})}function ot({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 zd({title:t,defaultCollapsed:r,configuredProviders:n,t:a,children:o,onBadgeClick:s}){const[d,c]=i.useState(r);return e.jsxs("section",{children:[e.jsxs("button",{type:"button",onClick:()=>c(!d),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}),d&&n.length>0&&e.jsxs("span",{className:"text-xs text-fg-tertiary",children:["(",n.length," ",a("modelProviders.configuredCount"),")"]})]}),e.jsx("span",{className:`text-fg-tertiary text-xs transition-transform group-hover:text-fg-secondary ${d?"-rotate-90":""}`,children:"▼"})]}),d&&n.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[n.map(([u,h])=>e.jsxs("button",{type:"button",onClick:x=>{x.stopPropagation(),c(!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:()=>c(!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")]})]}),!d&&e.jsx("div",{className:"space-y-4",children:o})]})}function Wd({tab:t}){const{t:r}=ce(["settings","common"]),n=Ms.find(s=>s.id===t),a=r(n?`settings:${n.labelKey}`:"settings:title"),o=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(Zr,{id:t,className:"w-[18px] h-[18px]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:`${Fe.pageTitle} ${Qe.strong} tracking-tight leading-tight`,children:a}),o&&e.jsx("p",{className:`mt-0.5 ${Fe.groupDesc} ${Qe.desc} leading-snug`,children:o})]})]})}function Kr({label:t,value:r,color:n}){const a=n==="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 wt(t,r){if(t===0)return r?r("dataStorage.bytesZero"):"0 B";const n=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)),n.length-1),o=t/Math.pow(1024,a);return`${o<10?o.toFixed(1):Math.round(o)} ${n[a]}`}function Gd({orphanInfo:t,dataDir:r,onPurged:n,formatBytes:a}){const{t:o}=ce(["settings","common"]),s=[...t.orphanAgents.map(b=>({...b,kind:"agent"})),...t.orphanTeams.map(b=>({...b,kind:"team"}))],[d,c]=i.useState(new Set),[u,h]=i.useState(!1),[x,v]=i.useState(null),j=b=>c(A=>{const m=new Set(A);return m.has(b)?m.delete(b):m.add(b),m}),k=d.size===s.length&&s.length>0,P=()=>c(k?new Set:new Set(s.map(b=>b.id))),N=s.filter(b=>d.has(b.id)).reduce((b,A)=>b+A.size,0),y=async b=>{h(!0),v(null);try{const A=await U.system.purgeOrphans(b),m=A.purgedAgents.length+A.purgedTeams.length,w=o("dataStorage.cleaned",{count:m,size:a(A.freedBytes)});v(A.failures.length?o("dataStorage.cleanedWithFailureNote",{base:w,count:A.failures.length}):w),c(new Set),n()}catch{v(o("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:o("dataStorage.orphanedDirectories")}),e.jsxs("p",{className:"text-xs text-fg-tertiary mb-3",children:[o("dataStorage.orphanedDesc")," ",o("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:k,onChange:P,className:"rounded"}),o("common:selectAll")]}),d.size>0&&e.jsx("span",{className:"text-[10px] text-fg-secondary",children:o("dataStorage.selectedWithSize",{count:d.size,size:a(N)})})]}),e.jsx("div",{className:"space-y-0.5 mb-3 max-h-52 overflow-y-auto",children:s.map(b=>e.jsxs("div",{className:`flex items-center gap-2 text-xs py-1.5 px-2 rounded transition-colors ${d.has(b.id)?"bg-amber-500/10":"bg-surface-elevated/30 hover:bg-surface-elevated/50"}`,children:[e.jsx("input",{type:"checkbox",checked:d.has(b.id),onChange:()=>j(b.id),className:"rounded shrink-0"}),b.kind==="team"&&e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:o("dataStorage.teamKind")}),e.jsx("span",{className:"text-fg-tertiary font-mono truncate min-w-0 flex-1",children:b.id}),e.jsx("span",{className:"text-fg-secondary tabular-nums shrink-0",children:a(b.size)}),e.jsx("button",{onClick:()=>{U.system.openPath(b.path)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary shrink-0 underline",children:o("common:open")})]},b.id))}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[d.size>0&&e.jsx("button",{disabled:u,onClick:()=>{y([...d])},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?o("dataStorage.cleaning"):o("dataStorage.cleanSelected",{size:a(N)})}),e.jsx("button",{disabled:u,onClick:()=>{y()},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?o("dataStorage.cleaning"):o("dataStorage.cleanAll",{size:a(t.totalOrphanSize)})})]}),x&&e.jsx("div",{className:"text-xs text-fg-tertiary mt-2",children:x})]})}function Jd({authUser:t}){const{t:r}=ce("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{title:r("account.localTitle"),description:r("account.localDesc"),children:e.jsx(Fd,{authUser:t})}),e.jsx(ke,{title:r("account.subscriptionTitle"),description:r("account.subscriptionDesc"),children:e.jsx(Vi,{authUser:t})})]})}function Yd({modelId:t,tier:r}){const{t:n}=ce("settings");let a;if(r==="max"||r==="pro"||r==="base")a=r;else{const s=t.toLowerCase(),d=/opus|5\.4|o3-(?!mini)|o1-(?!mini)|gemini.*ultra|sonnet-4-20/,c=/haiku|flash|nano|lite|small|fast|free|8b|7b|1b|3b/;/o4-mini|o3-mini|o1-mini|gpt-4o-mini/.test(s)?a="pro":d.test(s)?a="max":c.test(s)?a="base":a="pro"}const o={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 ${o[a]}`,children:n(`modelRouting.tier.${a}`)})}function Qd({noProxyList:t,setNoProxyList:r,noProxyEntry:n,setNoProxyEntry:a,authHeaders:o,loadNetworkSettings:s,t:d}){const[c,u]=i.useState(!1);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>u(!c),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 ${c?"rotate-90":""}`,children:"▸"}),d("networkProxy.noProxyTitle"),e.jsx("span",{className:"text-[11px] tabular-nums text-fg-tertiary bg-surface-secondary px-1.5 py-0.5 rounded",children:t.length})]}),c&&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(h=>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:[h,e.jsx("button",{onClick:()=>{const x=t.filter(v=>v!==h);r(x),fetch("/api/settings/network",{method:"POST",headers:o(),body:JSON.stringify({noProxy:x})}).then(()=>s()).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:d("networkProxy.remove"),children:"×"})]},h))}),t.length===0&&e.jsx("p",{className:"text-[11px] text-fg-tertiary italic",children:d("networkProxy.noProxyEmpty")}),e.jsx("input",{type:"text",value:n,onChange:h=>a(h.target.value),onKeyDown:h=>{if(h.key!=="Enter"||!n.trim())return;const x=[...new Set([...t,n.trim()])];r(x),a(""),fetch("/api/settings/network",{method:"POST",headers:o(),body:JSON.stringify({noProxy:x})}).then(()=>s()).catch(()=>{})},placeholder:d("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-tertiary leading-relaxed",children:d("networkProxy.noProxyHint")})]})]})}export{xo as DEV_BUILD,Ms as SETTINGS_TABS,Fr as SETTINGS_TAB_GROUPS,Va as SETTINGS_TAB_ICONS,nc as Settings,Vd as normalizeSettingsTab,Dd as resolveSettingsTab,Od as settingsTabLoads,Ld as visibleSettingsTabs};