@runfusion/fusion 0.56.1 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/dist/bin.js +5998 -4649
  2. package/dist/client/.vite/manifest.json +241 -241
  3. package/dist/client/assets/AgentDetailView-DexqYfz4.js +18 -0
  4. package/dist/client/assets/{AgentPermissionPolicyEditor-DQDzCWq_.js → AgentPermissionPolicyEditor-B65iWSFw.js} +1 -1
  5. package/dist/client/assets/AgentsView-DWBHXG4w.js +24 -0
  6. package/dist/client/assets/ChatView-BaGockES.js +6 -0
  7. package/dist/client/assets/{CommandCenter-CZ856YOj.js → CommandCenter-DNSpf5Nq.js} +2 -2
  8. package/dist/client/assets/{DevServerView-BqsnMChS.js → DevServerView-T7YAMRMr.js} +1 -1
  9. package/dist/client/assets/{DirectoryPicker-cW1rnVoG.js → DirectoryPicker-p_bMALI6.js} +1 -1
  10. package/dist/client/assets/{DocumentsView-C6a5tuBQ.js → DocumentsView-CSZ1_bEk.js} +1 -1
  11. package/dist/client/assets/{EvalsView-DZd_TM3I.js → EvalsView-C03NFn9p.js} +1 -1
  12. package/dist/client/assets/{ExperimentalAgentOnboardingModal-cA-aWWsB.js → ExperimentalAgentOnboardingModal-DaYU4VlV.js} +1 -1
  13. package/dist/client/assets/{GoalsView-Bzvw1aDV.js → GoalsView-CwXL_l6r.js} +1 -1
  14. package/dist/client/assets/{InsightsView-B3WQIXKs.js → InsightsView-D-pumdKK.js} +1 -1
  15. package/dist/client/assets/{MemoryView-BZ2KwFO5.js → MemoryView--frKZACq.js} +1 -1
  16. package/dist/client/assets/{PiExtensionsManager-D5x6GZOP.js → PiExtensionsManager-HTYWFcsw.js} +1 -1
  17. package/dist/client/assets/PluginManager-47FXVbWv.js +1 -0
  18. package/dist/client/assets/{PluginManager-DSiHizRD.css → PluginManager-Bm9FXhxQ.css} +1 -1
  19. package/dist/client/assets/{PullRequestView-DX3J4hgm.js → PullRequestView-jqo0u_qP.js} +1 -1
  20. package/dist/client/assets/{ResearchView-MZV2S2kT.js → ResearchView-lUFw0eBY.js} +1 -1
  21. package/dist/client/assets/{SecretsView--R3u3G4b.js → SecretsView-DZ1NCe-c.js} +1 -1
  22. package/dist/client/assets/{SessionTerminal-BQWc1_Ty.js → SessionTerminal-B10eN86g.js} +1 -1
  23. package/dist/client/assets/SettingsModal-BIIWHPyY.js +21 -0
  24. package/dist/client/assets/SettingsModal-BqIOpGm9.css +1 -0
  25. package/dist/client/assets/{SettingsModal-Coqvlmud.js → SettingsModal-C3PIQwOw.js} +1 -1
  26. package/dist/client/assets/SettingsModal-D-z02qbd.css +1 -0
  27. package/dist/client/assets/{SetupWizardModal-CoReXugb.js → SetupWizardModal-BtCAK9gq.js} +2 -2
  28. package/dist/client/assets/{ShadcnColorPicker-D-u_ECbM.js → ShadcnColorPicker-CgbOh2Vh.js} +1 -1
  29. package/dist/client/assets/{SkillsView-D21ils_G.js → SkillsView-xknpWJDp.js} +1 -1
  30. package/dist/client/assets/{TodoView-BFZQSkv4.js → TodoView-BOIUCi-b.js} +1 -1
  31. package/dist/client/assets/{WorkflowNodeEditor-E-7d5R9z.js → WorkflowNodeEditor-BoGuTbgL.js} +1 -1
  32. package/dist/client/assets/{agentSkills-CM_yYVTx.js → agentSkills-HBp0qQK2.js} +1 -1
  33. package/dist/client/assets/app-CC21pBBX.js +13 -0
  34. package/dist/client/assets/app-D5aQhT6F.js +13 -0
  35. package/dist/client/assets/app-DRTCMx1I.js +13 -0
  36. package/dist/client/assets/{app-CEtD1B9K.js → app-gWIFDNxJ.js} +2 -2
  37. package/dist/client/assets/app-pKygaS_p.js +13 -0
  38. package/dist/client/assets/app-usRdP6KP.js +13 -0
  39. package/dist/client/assets/{architectureDiagram-3BPJPVTR-DhgVYwmg.js → architectureDiagram-3BPJPVTR-DFSc_ojZ.js} +1 -1
  40. package/dist/client/assets/{blockDiagram-GPEHLZMM-AlG0kVWu.js → blockDiagram-GPEHLZMM-BeWCvgkB.js} +1 -1
  41. package/dist/client/assets/{c4Diagram-AAUBKEIU-BOzpW3F7.js → c4Diagram-AAUBKEIU-53kLf9YA.js} +1 -1
  42. package/dist/client/assets/channel-DqmRVQcu.js +1 -0
  43. package/dist/client/assets/{chunk-2J33WTMH-BAmZfsv0.js → chunk-2J33WTMH-oiPMiLQk.js} +1 -1
  44. package/dist/client/assets/{chunk-4BX2VUAB-Cs587QhG.js → chunk-4BX2VUAB-DtEYW63S.js} +1 -1
  45. package/dist/client/assets/{chunk-55IACEB6-qpIQSO06.js → chunk-55IACEB6-CRyY-eBJ.js} +1 -1
  46. package/dist/client/assets/{chunk-727SXJPM-DF3vZtMc.js → chunk-727SXJPM-DpPz5T23.js} +1 -1
  47. package/dist/client/assets/{chunk-AQP2D5EJ-BuETIys5.js → chunk-AQP2D5EJ-DsvlwOK0.js} +1 -1
  48. package/dist/client/assets/{chunk-FMBD7UC4-B8D1TSR9.js → chunk-FMBD7UC4-B4PI9bUA.js} +1 -1
  49. package/dist/client/assets/{chunk-ND2GUHAM-BJv9aIQn.js → chunk-ND2GUHAM-CNvgVhAJ.js} +1 -1
  50. package/dist/client/assets/{chunk-QZHKN3VN-BJbK2pNR.js → chunk-QZHKN3VN-PzmFXGK3.js} +1 -1
  51. package/dist/client/assets/classDiagram-4FO5ZUOK-BkGcNuxB.js +1 -0
  52. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-BkGcNuxB.js +1 -0
  53. package/dist/client/assets/{cose-bilkent-S5V4N54A-BWRikddb.js → cose-bilkent-S5V4N54A-B2hi4baG.js} +1 -1
  54. package/dist/client/assets/{dagre-BM42HDAG-DpAxJj7T.js → dagre-BM42HDAG-CtfJbsAQ.js} +1 -1
  55. package/dist/client/assets/{dashboard-view-qq3ayA0B.js → dashboard-view-DmxFuwxK.js} +1 -1
  56. package/dist/client/assets/{dashboard-view-Dw8L8k-2.js → dashboard-view-Y7yFASOR.js} +1 -1
  57. package/dist/client/assets/{diagram-2AECGRRQ-DRRIILsg.js → diagram-2AECGRRQ-CCNdu-lI.js} +1 -1
  58. package/dist/client/assets/{diagram-5GNKFQAL-DSOu28ss.js → diagram-5GNKFQAL-CRFRDKo6.js} +1 -1
  59. package/dist/client/assets/{diagram-KO2AKTUF-CWzbnTBM.js → diagram-KO2AKTUF-qzA8EYKe.js} +1 -1
  60. package/dist/client/assets/{diagram-LMA3HP47-CGqf3bt6.js → diagram-LMA3HP47-BcVh_7JQ.js} +1 -1
  61. package/dist/client/assets/{diagram-OG6HWLK6-C1axXteT.js → diagram-OG6HWLK6-ti62bhwU.js} +1 -1
  62. package/dist/client/assets/{erDiagram-TEJ5UH35-bBdlc4OY.js → erDiagram-TEJ5UH35-R-0m-loG.js} +1 -1
  63. package/dist/client/assets/{flowDiagram-I6XJVG4X-BTCJ2J3b.js → flowDiagram-I6XJVG4X-DmchEhZJ.js} +1 -1
  64. package/dist/client/assets/{folder-open-BN3_NdbL.js → folder-open-BnJacMSp.js} +1 -1
  65. package/dist/client/assets/{ganttDiagram-6RSMTGT7-CiFY9oBj.js → ganttDiagram-6RSMTGT7-CRZY8cRF.js} +1 -1
  66. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CxubcP4l.js → gitGraphDiagram-PVQCEYII-DJ6KnPoF.js} +1 -1
  67. package/dist/client/assets/index-BxaBW271.css +1 -0
  68. package/dist/client/assets/index-C-IxdGPX.js +2526 -0
  69. package/dist/client/assets/{infoDiagram-5YYISTIA-ToDlIyOV.js → infoDiagram-5YYISTIA-BEXH-GHB.js} +1 -1
  70. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-BgO681xo.js → ishikawaDiagram-YF4QCWOH-CVuF17Yd.js} +1 -1
  71. package/dist/client/assets/{journeyDiagram-JHISSGLW-OJZ3op9w.js → journeyDiagram-JHISSGLW-CCcBBtY4.js} +1 -1
  72. package/dist/client/assets/{kanban-definition-UN3LZRKU-q2OOqX8K.js → kanban-definition-UN3LZRKU-B5bqvapW.js} +1 -1
  73. package/dist/client/assets/{mermaid.core-BmDOYmFS.js → mermaid.core-DfKOBw3p.js} +4 -4
  74. package/dist/client/assets/{mindmap-definition-RKZ34NQL-Dw8JehwG.js → mindmap-definition-RKZ34NQL-D6YDtYgW.js} +1 -1
  75. package/dist/client/assets/{pieDiagram-4H26LBE5-D5Li6GnX.js → pieDiagram-4H26LBE5-BokP1BTt.js} +1 -1
  76. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-B4s-2jdZ.js → quadrantDiagram-W4KKPZXB-B9NJMDnf.js} +1 -1
  77. package/dist/client/assets/{requirementDiagram-4Y6WPE33-Drc3rc_E.js → requirementDiagram-4Y6WPE33-CkVaSHtt.js} +1 -1
  78. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-C_R01GQC.js → sankeyDiagram-5OEKKPKP-BoU2JDPH.js} +1 -1
  79. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-gyl7Yhgc.js → sequenceDiagram-3UESZ5HK-Damqlxg5.js} +1 -1
  80. package/dist/client/assets/{shield-alert-DjhYmFaV.js → shield-alert-BTMxVnOy.js} +1 -1
  81. package/dist/client/assets/{stateDiagram-AJRCARHV-BY53czZh.js → stateDiagram-AJRCARHV-BC72nvu_.js} +1 -1
  82. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-C53cIaWg.js → stateDiagram-v2-BHNVJYJU-BSoMYClQ.js} +1 -1
  83. package/dist/client/assets/{timeline-definition-PNZ67QCA-BYwv2FZJ.js → timeline-definition-PNZ67QCA-DxHz0a6F.js} +1 -1
  84. package/dist/client/assets/{upload-BKpOp-Bn.js → upload-1isayrJo.js} +1 -1
  85. package/dist/client/assets/{users-BUMHTZuX.js → users-C3jhPg5Q.js} +1 -1
  86. package/dist/client/assets/{vennDiagram-CIIHVFJN-Dt94bP0k.js → vennDiagram-CIIHVFJN-B3nVtXfZ.js} +1 -1
  87. package/dist/client/assets/{wardley-L42UT6IY-536kdB5p.js → wardley-L42UT6IY-D-hb-Ks4.js} +1 -1
  88. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-D8iNQ_MW.js → wardleyDiagram-YWT4CUSO-DVqAvZPQ.js} +1 -1
  89. package/dist/client/assets/{xychartDiagram-2RQKCTM6-CXqp8mzh.js → xychartDiagram-2RQKCTM6-0RALveCq.js} +1 -1
  90. package/dist/client/index.html +2 -2
  91. package/dist/client/version.json +1 -1
  92. package/dist/droid-cli/package.json +1 -1
  93. package/dist/extension.js +2784 -1191
  94. package/dist/pi-claude-cli/package.json +1 -1
  95. package/dist/plugin-sdk/index.d.ts +35 -0
  96. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  97. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  98. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  99. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  100. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  101. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  102. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +21 -8
  103. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  104. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  105. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  106. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  107. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  108. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  109. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  110. package/package.json +1 -1
  111. package/skill/fusion/references/extension-tools.md +4 -2
  112. package/skill/fusion/references/fusion-capabilities.md +2 -2
  113. package/dist/client/assets/AgentDetailView-BICsleMh.js +0 -18
  114. package/dist/client/assets/AgentsView-DRpFG7gE.js +0 -24
  115. package/dist/client/assets/ChatView-5vVkIiNh.js +0 -6
  116. package/dist/client/assets/PluginManager-YfHRH24B.js +0 -1
  117. package/dist/client/assets/SettingsModal-CNYosRF3.js +0 -21
  118. package/dist/client/assets/SettingsModal-CaE4JYxi.css +0 -1
  119. package/dist/client/assets/SettingsModal-D8AyVDar.css +0 -1
  120. package/dist/client/assets/app-0jcSCRQr.js +0 -13
  121. package/dist/client/assets/app-BPzPEE6G.js +0 -13
  122. package/dist/client/assets/app-BSZU5Uns.js +0 -13
  123. package/dist/client/assets/app-CVyRSEUX.js +0 -13
  124. package/dist/client/assets/app-DoLz_4Dg.js +0 -13
  125. package/dist/client/assets/channel-DHSVrpL1.js +0 -1
  126. package/dist/client/assets/classDiagram-4FO5ZUOK-CTu3cN1i.js +0 -1
  127. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-CTu3cN1i.js +0 -1
  128. package/dist/client/assets/index-CbmH1ED8.css +0 -1
  129. package/dist/client/assets/index-rfsTNfpA.js +0 -2511
@@ -1,21 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-YfHRH24B.js","assets/vendor-react-SZ_qB27O.js","assets/index-rfsTNfpA.js","assets/vendor-i18n-GF3RlKbq.js","assets/vendor-reactflow-CnI7NMXG.js","assets/vendor-reactflow-C5ap-Sga.css","assets/vendor-codemirror-jBKmHyH0.js","assets/vendor-xterm-BNq00GSj.js","assets/vendor-xterm-LZoznX6r.css","assets/index-CbmH1ED8.css","assets/DirectoryPicker-cW1rnVoG.js","assets/folder-open-BN3_NdbL.js","assets/DirectoryPicker-0rspvcMz.css","assets/PluginManager-DSiHizRD.css","assets/PiExtensionsManager-D5x6GZOP.js","assets/AgentPermissionPolicyEditor-DQDzCWq_.js","assets/AgentPermissionPolicyEditor-TpdlOWZW.css","assets/PiExtensionsManager-kgTOHPE9.css"])))=>i.map(i=>d[i]);
2
- import{r as o,j as e}from"./vendor-react-SZ_qB27O.js";import{c as Bi,fw as it,fx as Gi,fy as _i,fz as Ui,c5 as Hi,fA as fa,fB as Wi,fC as St,fD as es,bP as lt,fE as $i,fF as Ki,fG as qi,fH as zi,fI as kn,fJ as wa,fK as va,fL as gr,fM as Vi,fN as Yi,fO as jn,dy as At,h as Qi,bb as Ji,fP as Xi,fQ as Qs,fR as Zi,fS as Js,fT as eo,fU as to,fV as br,fW as xa,P as as,R as ns,co as so,I as rs,J as ls,fn as ao,a8 as wn,X as no,an as Ze,bS as Xe,fX as ro,fY as lo,fZ as io,f_ as oo,f$ as co,g0 as uo,g1 as mo,L as ze,q as Cn,aM as Nn,g2 as ho,g3 as ya,dw as Tt,g4 as po,g5 as go,g6 as bo,g7 as fr,aa as vr,g8 as fo,g9 as vo,ay as Ca,ga as xo,gb as yo,as as ot,gc as ko,gd as jo,ge as wo,gf as Co,gg as No,gh as So,gi as Sn,gj as Pn,gk as Po,dm as Vt,dl as Xs,af as Ao,o as To,eH as An,gl as Mo,fb as Ro,gm as Io,gn as Eo,et as Fo,bI as Tn,eu as Lo,go as Do,gp as Oo,gq as Bo,bg as Go,b9 as _o,_ as xr,ak as Uo,ag as yr,dz as Ho,c2 as Wo,W as $o,ch as Ko,gr as qo,gs as Zs,u as zo,aU as Mn,cQ as Vo,gt as Rn,gu as In,bs as me,gv as Yo,gw as Qo,gx as Jo,gy as Xo,c4 as En,gz as Fn,bO as Zo,gA as Ln,gB as ec,gC as ea,gD as tc,gE as sc,gF as Dn,gG as ac,aW as On,aV as nc,gH as rc,gI as lc,gJ as ic,gK as oc,gL as cc,gM as dc,gN as uc,gO as mc,gP as hc,gQ as pc,gR as gc,dp as bc,aY as ta,gS as fc,gT as vc,aZ as xc,b5 as yc,a$ as kc,b4 as jc,a_ as wc,gU as Cc,a4 as Nc,cd as Sc,ae as Bn,fd as Pc,gV as sa,ft as Ac,gW as Tc,gX as Mc}from"./index-rfsTNfpA.js";import{T as Rc,S as Ic,M as Ec,C as Gn,a as Fc}from"./ShadcnColorPicker-D-u_ECbM.js";import{u as Z,T as ka}from"./vendor-i18n-GF3RlKbq.js";import{U as Lc}from"./upload-BKpOp-Bn.js";import{SecretsView as Dc}from"./SecretsView--R3u3G4b.js";import{B as Oc,A as Bc}from"./AgentPermissionPolicyEditor-DQDzCWq_.js";import{U as Gc}from"./users-BUMHTZuX.js";import{u as _c}from"./SettingsModal-Coqvlmud.js";import"./vendor-reactflow-CnI7NMXG.js";import"./vendor-codemirror-jBKmHyH0.js";import"./vendor-xterm-BNq00GSj.js";/**
3
- * @license lucide-react v1.7.0 - ISC
4
- *
5
- * This source code is licensed under the ISC license.
6
- * See the LICENSE file in the root directory of this source tree.
7
- */const Uc=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],Hc=Bi("settings-2",Uc);function Se(a,t,s){return{path:a,code:t,message:s}}function Wc(a,t){return a===void 0?{value:void 0,errors:[]}:!Array.isArray(a)||!a.every(s=>typeof s=="string"&&s.trim().length>0)?{errors:[Se(t,"invalid-args","Expected an array of non-empty strings")]}:{value:a.map(s=>s.trim()),errors:[]}}function _n(a,t){if(a===void 0)return{value:void 0,errors:[]};if(!a||typeof a!="object"||Array.isArray(a))return{errors:[Se(t,"invalid-sensitive-map","Expected an object whose values are secret references")]};const s={},c=[];for(const[n,m]of Object.entries(a)){if(!n.trim()){c.push(Se(`${t}.${n}`,"invalid-sensitive-map","Sensitive field names must be non-empty"));continue}if(typeof m=="string"){c.push(Se(`${t}.${n}`,"plaintext-secret","Sensitive MCP values must be Fusion secret references, never plaintext strings"));continue}if(!it(m)){c.push(Se(`${t}.${n}`,"invalid-sensitive-map","Sensitive MCP values must be { secretRef, scope } objects"));continue}s[n.trim()]={secretRef:m.secretRef.trim(),scope:m.scope}}return c.length>0?{errors:c}:{value:s,errors:[]}}function Na(a,t="server"){if(!a||typeof a!="object"||Array.isArray(a))return{errors:[Se(t,"invalid-shape","MCP server definition must be an object")]};const s=a,c=[];(typeof s.name!="string"||s.name.trim().length===0)&&c.push(Se(`${t}.name`,"invalid-name","MCP server name is required"));const n=typeof s.enabled=="boolean"?s.enabled:void 0;if(s.transport==="stdio"){(typeof s.command!="string"||s.command.trim().length===0)&&c.push(Se(`${t}.command`,"missing-command","stdio MCP servers require a command"));const m=Wc(s.args,`${t}.args`),i=_n(s.env,`${t}.env`);return c.push(...m.errors,...i.errors),c.length>0?{errors:c}:{value:{name:s.name.trim(),...n!==void 0?{enabled:n}:{},transport:"stdio",command:s.command.trim(),...m.value?{args:m.value}:{},...i.value?{env:i.value}:{}},errors:[]}}if(s.transport==="sse"||s.transport==="streamable-http"){(typeof s.url!="string"||s.url.trim().length===0)&&c.push(Se(`${t}.url`,"missing-url",`${s.transport} MCP servers require a url`));const m=_n(s.headers,`${t}.headers`);return c.push(...m.errors),c.length>0?{errors:c}:{value:{name:s.name.trim(),...n!==void 0?{enabled:n}:{},transport:s.transport,url:s.url.trim(),...m.value?{headers:m.value}:{}},errors:[]}}return c.push(Se(`${t}.transport`,"invalid-transport","MCP transport must be stdio, sse, or streamable-http")),{errors:c}}function is(a){return Na(a).value}function $c(a,t="servers"){if(!Array.isArray(a))return{errors:[Se(t,"invalid-shape","MCP servers must be an array")]};const s=[],c=[],n=new Set;return a.forEach((m,i)=>{const r=Na(m,`${t}.${i}`);if(s.push(...r.errors),!!r.value){if(n.has(r.value.name)){s.push(Se(`${t}.${i}.name`,"duplicate-name",`Duplicate MCP server name: ${r.value.name}`));return}n.add(r.value.name),c.push(r.value)}}),s.length>0?{errors:s}:{value:c,errors:[]}}function kr(a){return{enabled:a?.enabled===!0,servers:Array.isArray(a?.servers)?a.servers:[]}}function Un(a){return kr(a).servers?.map(is).filter(t=>!!t)??[]}function Kc(a,t){try{const s=kr(a?.mcpServers),c=t?.mcpServers;if(!(typeof c?.enabled=="boolean"?c.enabled:s.enabled))return[];const m=new Map;for(const i of Un(a?.mcpServers))i.enabled!==!1&&m.set(i.name,i);for(const i of Un(c)){if(i.enabled===!1){m.delete(i.name);continue}m.set(i.name,i)}return[...m.values()].filter(i=>i.enabled!==!1)}catch{return[]}}function qc(a){if(typeof a!="string")return{data:a};try{return{data:JSON.parse(a)}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}function zc(a,t,s){const c=n=>n.trim().replace(/[^A-Za-z0-9_.-]+/gu,"_").replace(/^_+|_+$/gu,"");return["mcp",c(a),c(t),c(s)].filter(Boolean).join(".")}function Hn(a){const{value:t,serverName:s,field:c,scope:n,secretsToCreate:m,errors:i}=a;if(t===void 0)return;if(!t||typeof t!="object"||Array.isArray(t)){i.push(`${s}.${c} must be an object`);return}const r={};for(const[h,k]of Object.entries(t)){if(it(k)){r[h]={secretRef:k.secretRef.trim(),scope:k.scope};continue}if(typeof k=="string"){const v=zc(s,c,h);r[h]={secretRef:v,scope:n},m.push({serverName:s,field:c,key:h,scope:n,suggestedKey:v,plaintextValue:k});continue}i.push(`${s}.${c}.${h} must be a string or MCP secret reference`)}return Object.keys(r).length>0?r:void 0}function Vc(a,t={}){const s=qc(a);if(s.error)return{definitions:[],secretsToCreate:[],errors:[s.error]};const c=[],n=[],m=t.scope??"project",i=s.data;if(!i||typeof i!="object"||Array.isArray(i))return{definitions:[],secretsToCreate:n,errors:["MCP import data must be an object"]};const r=i.mcpServers;if(!r||typeof r!="object"||Array.isArray(r))return{definitions:[],secretsToCreate:n,errors:["MCP import data must contain an mcpServers object"]};const h=[],k=new Set;for(const[v,d]of Object.entries(r)){if(!d||typeof d!="object"||Array.isArray(d)){c.push(`${v} must be an object`);continue}const u=d,j=typeof u.enabled=="boolean"?u.enabled:void 0,x={name:typeof u.name=="string"&&u.name.trim()?u.name.trim():v,...j!==void 0?{enabled:j}:{}},b=typeof u.transport=="string"?u.transport:typeof u.command=="string"?"stdio":void 0;let S;if(b==="stdio"?S=is({...x,transport:"stdio",command:u.command,args:u.args,env:Hn({value:u.env,serverName:x.name,field:"env",scope:m,secretsToCreate:n,errors:c})}):b==="sse"||b==="streamable-http"?S=is({...x,transport:b,url:u.url,headers:Hn({value:u.headers,serverName:x.name,field:"headers",scope:m,secretsToCreate:n,errors:c})}):c.push(`${v}.transport must be stdio, sse, or streamable-http`),!S){c.push(`${v} is not a valid MCP server definition`);continue}if(k.has(S.name)){c.push(`Duplicate MCP server name: ${S.name}`);continue}k.add(S.name),h.push(S)}return{definitions:h,secretsToCreate:n,errors:c}}function Wn(a){if(!a)return;const t={};for(const[s,c]of Object.entries(a))it(c)&&(t[s]={secretRef:c.secretRef,scope:c.scope});return Object.keys(t).length>0?t:void 0}function Yc(a){const t={};for(const s of a){const c=is(s);if(c){if(c.transport==="stdio"){t[c.name]={transport:"stdio",...c.enabled!==void 0?{enabled:c.enabled}:{},command:c.command,...c.args?{args:c.args}:{},...c.env?{env:Wn(c.env)}:{}};continue}t[c.name]={transport:c.transport,...c.enabled!==void 0?{enabled:c.enabled}:{},url:c.url,...c.headers?{headers:Wn(c.headers)}:{}}}}return{mcpServers:t}}const $n="https://gitlab.com",Qc="https://gitlab.com/api/v4";function Jc(a={}){return typeof a.project?.gitlabEnabled=="boolean"?a.project.gitlabEnabled:typeof a.global?.gitlabEnabled=="boolean"?a.global.gitlabEnabled:!0}function Yt(a){if(typeof a!="string")return;const t=a.trim();return t.length>0?t:void 0}function Kn(a,t){let s;try{s=new URL(a)}catch{throw new Error(`${t} must be a valid absolute http(s) URL`)}if(s.protocol!=="http:"&&s.protocol!=="https:")throw new Error(`${t} must use http:// or https://`);if(s.username||s.password)throw new Error(`${t} must not include username or password userinfo`);if(!s.hostname)throw new Error(`${t} must include a hostname`);return s.hash="",s.search="",s.pathname=s.pathname.replace(/\/+$/u,"")||"/",s.toString().replace(/\/$/u,"")}function Xc(a){const t=new URL(a),s=t.pathname.replace(/\/+$/u,"");return t.pathname=`${s}/api/v4`.replace(/\/+/gu,"/"),t.search="",t.hash="",t.toString().replace(/\/$/u,"")}function qn(a={}){const t=Jc(a),s=Yt(a.project?.gitlabInstanceUrl),c=Yt(a.global?.gitlabInstanceUrl),n=Yt(a.project?.gitlabApiBaseUrl),m=Yt(a.global?.gitlabApiBaseUrl),i=Kn(s??c??$n,"GitLab instance URL"),r=n??m?Kn(n??m??"","GitLab API base URL"):i===$n?Qc:Xc(i);return{enabled:t,instanceUrl:i,apiBaseUrl:r}}const jr=["defaultProviderOverride","defaultModelIdOverride","titleSummarizerProvider","titleSummarizerModelId","titleSummarizerFallbackProvider","titleSummarizerFallbackModelId"],Zc=new Set(jr),ed=new Set(["gitlabEnabled","gitlabInstanceUrl","gitlabApiBaseUrl","gitlabAuthToken","gitlabAuthTokenType"]),wr={appearance:new Set(["themeMode","colorTheme","dashboardFontScalePct","shadcnCustomColors"]),notifications:new Set(["ntfyEnabled","ntfyTopic","ntfyBaseUrl","ntfyAccessToken","ntfyEvents","ntfyDashboardHost","failureNotificationDelayMs","failureNotificationMode","webhookEnabled","webhookUrl","webhookFormat","webhookEvents","notificationProviders"]),experimental:new Set(["experimentalFeatures"]),"global-general":new Set(["githubTrackingDefaultRepo","gitlabEnabled","gitlabInstanceUrl","gitlabApiBaseUrl","gitlabAuthToken","gitlabAuthTokenType","language","dismissModalsOnOutsideClick","persistAgentToolOutput","persistAgentThinkingLogPermanent","persistAgentThinkingLogEphemeral","fnBinaryCheckEnabled","updateCheckEnabled","updateCheckFrequency","autoReloadOnVersionChange"]),"keyboard-shortcuts":new Set(["dashboardKeyboardShortcuts"]),"global-mcp":new Set(["mcpServers"]),"global-models":new Set(["defaultProvider","defaultModelId","fallbackProvider","fallbackModelId","defaultThinkingLevel","modelRouterEnabled","modelRouterCheapProvider","modelRouterCheapModelId","opencodeGoModelSync","openrouterAppAttribution","openrouterModelFilters","openrouterModelSync","openrouterProviderPreferences","executionGlobalProvider","executionGlobalModelId","planningGlobalProvider","planningGlobalModelId","validatorGlobalProvider","validatorGlobalModelId","titleSummarizerGlobalProvider","titleSummarizerGlobalModelId"]),"project-models":new Set(["defaultProvider","defaultModelId","fallbackProvider","fallbackModelId","defaultThinkingLevel","modelRouterEnabled","modelRouterCheapProvider","modelRouterCheapModelId","opencodeGoModelSync","openrouterAppAttribution","openrouterModelFilters","openrouterModelSync","openrouterProviderPreferences","executionGlobalProvider","executionGlobalModelId","planningGlobalProvider","planningGlobalModelId","validatorGlobalProvider","validatorGlobalModelId","titleSummarizerGlobalProvider","titleSummarizerGlobalModelId"]),"node-sync":new Set(["settingsSyncEnabled","settingsSyncAuth","settingsSyncInterval","settingsSyncConflictResolution"]),"research-global":new Set(["researchGlobalDefaults","researchGlobalEnabled","researchGlobalMaxConcurrentRuns","researchGlobalDefaultTimeout","researchGlobalMaxSourcesPerRun","researchGlobalMaxSynthesisRounds","researchGlobalWebSearchProvider","researchGlobalSearxngUrl","researchGlobalBraveApiKey","researchGlobalGoogleSearchApiKey","researchGlobalGoogleSearchCx","researchGlobalTavilyApiKey","researchGlobalGitHubEnabled","researchGlobalLocalDocsEnabled","researchGlobalMaxSearchResults","researchGlobalFetchTimeoutMs","researchGlobalUserAgent"]),remote:new Set(["remoteAccess"])};function td(a,t){const s=wr[t];return!s||s.has(a)}function _e(a,t){return!!a&&Object.prototype.hasOwnProperty.call(a,t)}function Qt(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function Pt(a,t){if(Object.is(a,t))return!0;if(Array.isArray(a)||Array.isArray(t))return!Array.isArray(a)||!Array.isArray(t)||a.length!==t.length?!1:a.every((s,c)=>Pt(s,t[c]));if(Qt(a)||Qt(t)){if(!Qt(a)||!Qt(t))return!1;const s=Object.keys(a),c=Object.keys(t);return s.length!==c.length?!1:s.every(n=>_e(t,n)&&Pt(a[n],t[n]))}return!1}function aa(a,t){if(!(!_e(a,t)||a[t]===void 0))return String(a[t]??"")}function sd(a,t){if(!(!_e(a,t)||a[t]===void 0))return a[t]?String(a[t]):null}function Je(a,t){if(!(!_e(a,t)||a[t]===void 0))return!!a[t]}function na(a,t,s){if(!(!_e(a,t)||a[t]===void 0))return Number(a[t]??s)}function je(a,t,s){s!==void 0&&(a[t]=s)}function ad(a){const t={},s=_e(a,"remoteActiveProvider")?a.remoteActiveProvider:void 0;s!==void 0&&(t.activeProvider=s);const c={};je(c,"enabled",Je(a,"remoteTailscaleEnabled")),je(c,"hostname",aa(a,"remoteTailscaleHostname")),je(c,"targetPort",na(a,"remoteTailscaleTargetPort",4040)),je(c,"acceptRoutes",Je(a,"remoteTailscaleAcceptRoutes")),s==="tailscale"&&(c.enabled=!0);const n={};je(n,"enabled",Je(a,"remoteCloudflareEnabled")),je(n,"quickTunnel",Je(a,"remoteCloudflareQuickTunnel")),je(n,"tunnelName",aa(a,"remoteCloudflareTunnelName")),je(n,"tunnelToken",sd(a,"remoteCloudflareTunnelToken")),je(n,"ingressUrl",aa(a,"remoteCloudflareIngressUrl")),s==="cloudflare"&&(n.enabled=!0),(Object.keys(c).length>0||Object.keys(n).length>0)&&(t.providers={},Object.keys(c).length>0&&(t.providers.tailscale=c),Object.keys(n).length>0&&(t.providers.cloudflare=n));const m={};je(m,"enabled",Je(a,"remoteShortLivedEnabled")),je(m,"ttlMs",na(a,"remoteShortLivedTtlMs",9e5)),je(m,"maxTtlMs",na(a,"remoteShortLivedMaxTtlMs",864e5)),Object.keys(m).length>0&&(t.tokenStrategy={shortLived:m});const i={};return je(i,"rememberLastRunning",Je(a,"remoteRememberLastRunning")),je(i,"wasRunningOnShutdown",Je(a,"remoteWasRunningOnShutdown")),_e(a,"remoteLastStartedProvider")&&a.remoteLastStartedProvider!==void 0&&(i.lastRunningProvider=a.remoteLastStartedProvider),Object.keys(i).length>0&&(t.lifecycle=i),Object.keys(t).length>0?t:null}function nd({payload:a,initialValues:t,initialScopedValues:s,activeSection:c}){const n={};if(c==="remote"){const i=ad(a);i&&(n.remoteAccess=i)}for(const[i,r]of Object.entries(a))if(!(i==="githubTrackingDefaultRepo"&&c!=="global-general")&&!((i==="gitlabEnabled"||i==="gitlabInstanceUrl"||i==="gitlabApiBaseUrl"||i==="gitlabAuthToken"||i==="gitlabAuthTokenType")&&c!=="global-general")&&!(i==="mcpServers"&&c!=="global-mcp")&&i!=="persistAgentThinkingLog"&&i!=="customProviders"&&Gi(i)){if(!td(i,c))continue;if(r===void 0&&i==="ntfyAccessToken"&&c==="notifications"){n[i]=null;continue}const h=ed.has(i),k=_e(s?.global,i),v=!h&&_e(t,i),d=k?s?.global?.[i]:h?void 0:t?.[i],u=k||v;if(Pt(r,d))continue;r===void 0&&u&&d!==void 0?n[i]=null:r!==void 0&&(n[i]=r)}const m={};for(const[i,r]of Object.entries(a)){if(i==="githubTokenConfigured"||i==="prAuthAvailable"||i==="customProviders"||i==="githubTrackingDefaultRepo"&&c==="global-general"||(i==="gitlabEnabled"||i==="gitlabInstanceUrl"||i==="gitlabApiBaseUrl"||i==="gitlabAuthToken"||i==="gitlabAuthTokenType")&&c==="global-general"||i==="mcpServers"&&c==="global-mcp"||!_i(i))continue;const h=s?.project?.[i];Zc.has(i)?Pt(r,h)||(r==null&&h!==void 0&&h!==null?m[i]=null:r!==void 0&&(m[i]=r)):Pt(r,h)||(r===void 0&&h!==void 0&&h!==null?m[i]=null:r!==void 0&&(m[i]=r))}return{globalPatch:n,projectPatch:m}}const rd={general:["allowAbsoluteFileBrowserPaths","capacityRiskBannerEnabled","capacityRiskTodoThreshold","chatAutoCleanupDays","chatRoomCompactionFetchLimit","chatRoomRecentVerbatimMessages","chatRoomSummaryMaxChars","completionDocumentationMode","enabledBuiltinWorkflowIds","ephemeralAgentsCanCreateTasks","ephemeralAgentsEnabled","githubLinkImportedIssuesToTracking","githubTrackingDedupEnabled","githubTrackingDefaultRepo","githubTrackingEnabledByDefault","gitlabApiBaseUrl","gitlabEnabled","gitlabInstanceUrl","mailAutoCleanupDays","operationalLogRetentionDays","quickChatButtonMode","quickChatCloseOnOutsideClick","showQuickChatFAB","showTaskChatsInCommonFeed","taskPrefix","workspaceMode"],commands:["buildCommand","testCommand"],worktrees:["executorAllowSiblingBranchRename","maxWorktrees","recycleWorktrees","showWorktreeGrouping","worktreeCopyFiles","worktreeInitCommand","worktreeNaming","worktreeRebaseBeforeMerge","worktreeRebaseLocalBase","worktreeRebaseRemote","worktreesDir","worktrunk"],scheduling:["archiveAgentLogMode","autoArchiveDoneAfterMs","autoArchiveDoneTasksEnabled","engineerBacklogAutoClaim","groupOverlappingFiles","heartbeatScopeDiscipline","ignoreHiddenOverlapPaths","maxConcurrent","maxStuckKills","maxTriageConcurrent","overlapIgnorePaths","pollIntervalMs","preserveProgressOnStuckRequeue","specStalenessEnabled","specStalenessMaxAgeMs","staleHighFanoutBlockerAgeThresholdMs","taskStuckTimeoutMs"],"scheduled-evals":["evalSettings"],"node-routing":["defaultNodeId","unavailableNodePolicy"],merge:["autoMerge","autoResolveConflicts","commitAuthorEmail","commitAuthorEnabled","commitAuthorName","directMergeCommitStrategy","githubAuthMode","githubAuthToken","gitlabAuthToken","gitlabAuthTokenType","includeTaskIdInCommit","integrationBranch","maxAutoMergeRetries","mergeAdvanceAutoSync","mergeConflictStrategy","mergeIntegrationWorktree","mergeStrategy","mergeStrategyOverlapBehavior","merger","planApprovalMode","postMergeAuditMode","pushAfterMerge","pushRemote","smartConflictResolution","testMode"],"agent-permissions":["agentProvisioning","defaultAgentPermissionPolicy"],backups:["autoBackupDir","autoBackupEnabled","autoBackupRetention","autoBackupSchedule","memoryBackupDir","memoryBackupEnabled","memoryBackupRetention","memoryBackupSchedule","memoryBackupScope"],"research-project":["researchSettings"],"project-models":["autoSelectModelPreset","autoSummarizeTitles","defaultPresetBySize","defaultWorkflowId","modelPresets","prDescriptionPromptInstructions","prTitlePromptInstructions","tokenCap","useAiMergeCommitSummary",...jr]},Cr={secrets:"Secrets are managed by the Secrets store, not the settings form.","global-mcp":"MCP servers are managed by their own add/edit/remove flow.",mcp:"MCP servers are managed by their own add/edit/remove flow.",plugins:"Plugins and Pi extensions are managed by the Plugin Manager.",memory:"Memory files are edited directly, not as a settings blob.",authentication:"Authentication/provider credentials are managed by their own OAuth/API-key flow.",prompts:"Prompt library entries are managed by their own editor, not bulk-reset here.","cli-agents":"Per-adapter CLI agent settings are managed by their own approval/config flow.","hermes-runtime":"Runtime plugin settings are managed by the plugin's own config surface.","openclaw-runtime":"Runtime plugin settings are managed by the plugin's own config surface.","paperclip-runtime":"Runtime plugin settings are managed by the plugin's own config surface."};function ld(a){if(Cr[a])return null;const t=rd[a];if(t)return{scope:"project",keys:t};const s=wr[a];return s?{scope:"global",keys:Array.from(s)}:null}function id(a){return Cr[a]}const od=Ui,cd=[{value:90,label:"Small"},{value:100,label:"Default"},{value:110,label:"Large"},{value:120,label:"Largest"}];function dd({themeMode:a,colorTheme:t,dashboardFontScalePct:s=100,shadcnCustomColors:c={},resolvedThemeMode:n=a==="light"?"light":"dark",onThemeModeChange:m,onColorThemeChange:i,onDashboardFontScaleChange:r=()=>{},onShadcnCustomColorsChange:h=()=>{}}){const{t:k}=Z("app"),v=o.useCallback(()=>{m("system"),i("shadcn-ember"),r(100),h({})},[m,i,r,h]);return e.jsxs("div",{className:"theme-selector",children:[e.jsx("div",{className:"theme-mode-toggle",role:"radiogroup","aria-label":k("theme.modeLabel","Theme mode"),children:Rc.map(({value:d,label:u,icon:j})=>e.jsxs("button",{className:`theme-mode-btn${a===d?" active":""}`,onClick:()=>m(d),"aria-pressed":a===d,"aria-label":k(`theme.${d}Mode`,`${u} mode`),title:k(`theme.${d}Mode`,`${u} mode`),children:[e.jsx(j,{size:16}),e.jsx("span",{children:k(`theme.${d}`,u)})]},d))}),e.jsxs("div",{className:"theme-current-preview",children:[e.jsx("div",{className:"theme-preview-icon",children:a==="light"?e.jsx(Ic,{size:20}):a==="dark"?e.jsx(Ec,{size:20}):e.jsx(Hi,{size:20})}),e.jsxs("div",{className:"theme-preview-info",children:[e.jsx("div",{className:"theme-preview-label",children:k("theme.currentTheme","Current theme")}),e.jsxs("div",{className:"theme-preview-value",children:[a==="system"?"System":`${a.charAt(0).toUpperCase()+a.slice(1)}`," / ",Gn.find(d=>d.value===t)?.label]})]})]}),e.jsx("div",{className:"theme-section-title",children:k("theme.fontSize","Font Size")}),e.jsx("div",{className:"theme-font-size-toggle",role:"radiogroup","aria-label":k("theme.fontSizeLabel","Dashboard font size"),children:cd.map(({value:d,label:u})=>e.jsx("button",{className:`theme-font-size-btn${s===d?" active":""}`,onClick:()=>r(d),"aria-pressed":s===d,children:e.jsx("span",{children:k(`theme.fontSize.${u}`,u)})},d))}),e.jsx("div",{className:"theme-section-title",children:k("theme.colorTheme","Color Theme")}),e.jsx("div",{className:"theme-grid",role:"radiogroup","aria-label":k("theme.colorThemeLabel","Color theme"),children:Gn.map(({value:d,label:u,className:j})=>e.jsxs("button",{className:`theme-option${t===d?" active":""}`,onClick:()=>i(d),"aria-pressed":t===d,"aria-label":k(`theme.colorTheme.${d}`,`${u} theme`),title:k(`theme.colorTheme.${d}`,u),children:[e.jsxs("div",{className:`theme-option-swatch ${j}`,"aria-hidden":"true",children:[e.jsx("span",{className:"theme-option-swatch-sample theme-option-swatch-sample-1"}),e.jsx("span",{className:"theme-option-swatch-sample theme-option-swatch-sample-2"}),e.jsx("span",{className:"theme-option-swatch-sample theme-option-swatch-sample-3"}),e.jsx("span",{className:"theme-option-swatch-sample theme-option-swatch-sample-4"})]}),e.jsx("span",{className:"theme-option-label",children:k(`theme.colorTheme.${d}`,u)})]},d))}),t==="shadcn-custom"?e.jsx(Fc,{value:c,onChange:h,resolvedThemeMode:n}):null,e.jsx("button",{className:"theme-reset-btn",onClick:v,"aria-label":k("theme.resetLabel","Reset to default theme"),children:e.jsx("span",{children:k("theme.resetButton","Reset to defaults")})})]})}const os=typeof window<"u";function zn(){if(os)try{const a=localStorage.getItem(es);return St(a)?a:void 0}catch{return}}function Vn(){if(!os)return fa;for(const a of navigator.languages??[navigator.language]){const t=Ki(a);if(t)return t}return fa}function ud(){const{i18n:a}=Z(),t=a.resolvedLanguage??a.language,s=St(t)?t:fa,[c,n]=o.useState(s),[m,i]=o.useState(()=>zn()!==void 0),r=o.useRef(!1);o.useEffect(()=>{const v=d=>{St(d)&&n(d)};return a.on("languageChanged",v),()=>{a.off("languageChanged",v)}},[a]),o.useEffect(()=>{if(!os)return;const v=d=>{if(d.key===es){if(St(d.newValue))i(!0),d.newValue!==a.resolvedLanguage&&a.changeLanguage(d.newValue);else if(d.newValue===null){i(!1);const u=Vn();u!==a.resolvedLanguage&&a.changeLanguage(u)}}};return window.addEventListener("storage",v),()=>{window.removeEventListener("storage",v)}},[a]),o.useEffect(()=>{if(!os)return;let v=!1;return Wi().then(d=>{if(v||r.current)return;const u=St(d.language)?d.language:void 0;u&&!zn()&&u!==a.resolvedLanguage&&a.changeLanguage(u)}).catch(d=>{console.warn("[useLanguage] Failed to hydrate language from global settings",d)}),()=>{v=!0}},[a]);const h=o.useCallback(v=>{r.current=!0,n(v),i(!0),a.changeLanguage(v);try{localStorage.setItem(es,v)}catch{}lt({language:v}).catch(d=>{console.warn("[useLanguage] Failed to persist language to global settings",d)})},[a]),k=o.useCallback(()=>{r.current=!0,i(!1);try{localStorage.removeItem(es)}catch{}lt({language:null}).catch(v=>{console.warn("[useLanguage] Failed to clear language in global settings",v)}),a.changeLanguage(Vn())},[a]);return{language:c,supportedLocales:$i,setLanguage:h,clearLanguage:k,hasExplicitChoice:m}}const md={en:"English","zh-CN":"简体中文","zh-TW":"繁體中文",fr:"Français",es:"Español",ko:"한국어"};function hd(){const{t:a}=Z("app"),{language:t,supportedLocales:s,setLanguage:c,clearLanguage:n,hasExplicitChoice:m}=ud(),i=a("settings.appearance.language","Language");return e.jsxs("div",{className:"language-selector",children:[e.jsx("div",{className:"language-selector-title",children:i}),e.jsxs("div",{className:"language-options",role:"group","aria-label":i,children:[e.jsx("button",{type:"button",className:`language-option${m?"":" active"}`,onClick:n,"aria-pressed":!m,title:a("settings.appearance.languageAutoHint","Follow the browser language"),children:a("settings.appearance.languageAuto","Auto")}),s.map(r=>e.jsx("button",{type:"button",className:`language-option${m&&t===r?" active":""}`,onClick:()=>c(r),"aria-pressed":m&&t===r,lang:r,children:md[r]},r))]})]})}function pd({scopeBanner:a,form:t,setForm:s,themeMode:c,colorTheme:n,dashboardFontScalePct:m,shadcnCustomColors:i={},resolvedThemeMode:r,onThemeModeChange:h,onColorThemeChange:k,onDashboardFontScaleChange:v,onShadcnCustomColorsChange:d,sessionBannersHidden:u,setSessionBannersHidden:j}){const{t:x}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:x("settings.appearance.title","Appearance")}),e.jsx(dd,{themeMode:c,colorTheme:n,dashboardFontScalePct:m,onThemeModeChange:b=>{s(S=>({...S,themeMode:b})),h?.(b)},onColorThemeChange:b=>{s(S=>({...S,colorTheme:b})),k?.(b)},onDashboardFontScaleChange:b=>{s(S=>({...S,dashboardFontScalePct:b})),v?.(b)},shadcnCustomColors:i,resolvedThemeMode:r,onShadcnCustomColorsChange:b=>{s(S=>({...S,shadcnCustomColors:b})),d?.(b)}}),e.jsx(hd,{}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:t.openTasksInRightSidebar===!0,onChange:b=>s(S=>({...S,openTasksInRightSidebar:b.target.checked}))}),e.jsx("span",{children:x("settings.appearance.openTasksInRightSidebar","Open tasks in the right sidebar")})]}),e.jsx("small",{className:"form-text text-muted",children:x("settings.appearance.openTasksInRightSidebarHelp","When enabled, board task cards open detail in the right sidebar when it is available; mobile and hidden-sidebar states keep the full task panel. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:t.openMobileTasksInPopup===!0,onChange:b=>s(S=>({...S,openMobileTasksInPopup:b.target.checked}))}),e.jsx("span",{children:x("settings.appearance.openMobileTasksInPopup","Open tasks as popups")})]}),e.jsx("small",{className:"form-text text-muted",children:x("settings.appearance.openMobileTasksInPopupHelp","When enabled, ordinary board task-card and right-dock Tasks-list clicks open the existing task popup so the board or list remains visible. Deep-tab and other task opens keep their current behavior. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:t.taskDetailChatFirst===!0,onChange:b=>s(S=>({...S,taskDetailChatFirst:b.target.checked}))}),e.jsx("span",{children:x("settings.appearance.taskDetailChatFirst","Open task details with Chat first")})]}),e.jsx("small",{className:"form-text text-muted",children:x("settings.appearance.taskDetailChatFirstHelp","Off by default: task details list Activity first and omitted non-done opens land on Activity. Turn on to restore Chat-first order/default; explicit Chat links still work either way.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:b=>j(b.target.checked)}),e.jsx("span",{children:x("settings.appearance.hideAISessionNotificationBanners","Hide AI session notification banners")})]}),e.jsx("small",{className:"form-text text-muted",children:x("settings.appearance.suppressTheLdquoNeedsYourInputRdquoBanner"," Suppress the &ldquo;needs your input&rdquo; banner that appears when AI sessions are awaiting input or have failed. ")})]})]})}function gd({scopeBanner:a,form:t,setForm:s,knownFeatures:c,legacyAliases:n,getCanonicalKey:m,isFeatureEnabled:i,hiddenFeatureKeys:r}){const{t:h}=Z("app"),k=t.experimentalFeatures??{},d=Array.from(new Set([...Object.keys(c),...Object.keys(k).map(m)])).filter(u=>!r?.has(u)).sort((u,j)=>u.localeCompare(j)).map(u=>[u,i(k,u)]);return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:h("settings.experimental.experimentalFeatures","Experimental Features")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{children:h("settings.experimental.experimentalFeaturesAreEarlyCapabilitiesThatAreNot"," Experimental features are early capabilities that are not yet fully stable. Enable them to test new functionality, but be aware they may change or be removed. Default: disabled for every feature flag below. ")})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:h("settings.experimental.featureFlags","Feature Flags")}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:d.map(([u,j])=>e.jsxs("label",{htmlFor:`experimental-${u}`,className:"checkbox-label",children:[e.jsx("input",{id:`experimental-${u}`,type:"checkbox",checked:j,onChange:x=>{s(b=>{const S={...b.experimentalFeatures??{},[u]:x.target.checked};for(const[E,C]of Object.entries(n))C===u&&delete S[E];return{...b,experimentalFeatures:S}})}}),e.jsx("span",{children:c[u]??u})]},u))})]})]})}function bd({scopeBanner:a,form:t,setForm:s}){const{t:c}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.nodeSync.nodeSync","Node Sync")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"settingsSyncEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"settingsSyncEnabled",type:"checkbox",checked:t.settingsSyncEnabled||!1,onChange:n=>s(m=>({...m,settingsSyncEnabled:n.target.checked}))}),c("settings.nodeSync.enableAutomaticSettingsSync"," Enable automatic settings sync ")]}),e.jsx("small",{children:c("settings.nodeSync.automaticallySynchronizeSettingsBetweenThisNodeAndConnected","Automatically synchronize settings between this node and connected remote nodes. Default: disabled.")})]}),t.settingsSyncEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"settingsSyncAuth",className:"checkbox-label",children:[e.jsx("input",{id:"settingsSyncAuth",type:"checkbox",checked:t.settingsSyncAuth||!1,onChange:n=>s(m=>({...m,settingsSyncAuth:n.target.checked}))}),c("settings.nodeSync.syncModelAuthCredentials"," Sync model auth credentials ")]}),e.jsx("small",{children:c("settings.nodeSync.includeAPIKeysAndOAuthTokensInSync","Include API keys and OAuth tokens in sync operations. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"settingsSyncInterval",children:c("settings.nodeSync.syncInterval","Sync interval")}),e.jsxs("select",{id:"settingsSyncInterval",className:"select",value:t.settingsSyncInterval||9e5,onChange:n=>s(m=>({...m,settingsSyncInterval:parseInt(n.target.value,10)})),children:[e.jsx("option",{value:3e5,children:c("settings.nodeSync.every5Minutes","Every 5 minutes")}),e.jsx("option",{value:9e5,children:c("settings.nodeSync.every15Minutes","Every 15 minutes")}),e.jsx("option",{value:18e5,children:c("settings.nodeSync.every30Minutes","Every 30 minutes")}),e.jsx("option",{value:36e5,children:c("settings.nodeSync.every1Hour","Every 1 hour")})]}),e.jsx("small",{children:c("settings.nodeSync.syncIntervalHint","Default: every 15 minutes.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"settingsSyncConflictResolution",children:c("settings.nodeSync.conflictResolution","Conflict resolution")}),e.jsxs("select",{id:"settingsSyncConflictResolution",className:"select",value:t.settingsSyncConflictResolution||"last-write-wins",onChange:n=>s(m=>({...m,settingsSyncConflictResolution:n.target.value})),children:[e.jsx("option",{value:"last-write-wins",children:c("settings.nodeSync.lastWriteWins","Last write wins")}),e.jsx("option",{value:"always-ask",children:c("settings.nodeSync.alwaysAsk","Always ask")}),e.jsx("option",{value:"keep-local",children:c("settings.nodeSync.keepLocal","Keep local")}),e.jsx("option",{value:"keep-remote",children:c("settings.nodeSync.keepRemote","Keep remote")})]}),e.jsx("small",{children:c("settings.nodeSync.conflictResolutionHint","Default: last write wins.")})]})]}),e.jsx("p",{className:"settings-sync-workflow-note text-muted",role:"note",children:c("settings.nodeSync.workflowSettingsNotSynced","Workflow settings are not synced across nodes yet.")})]})}const ra=["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","cli-agent-awaiting-input","gridlock","fallback-used","memory-dreams-processed","message:agent-to-user","message:agent-to-agent","message:room","oauth-token-expired"],Yn=[{event:"in-review",label:"Task completed (in-review)",description:"When a task moves to In Review (ready for review)"},{event:"merged",label:"Task merged",description:"When a task is successfully merged to main"},{event:"failed",label:"Task failed",description:"When a task fails during execution (high priority)"},{event:"awaiting-approval",label:"Plan needs approval",description:"When a task specification needs manual approval before execution"},{event:"awaiting-user-review",label:"User review needed",description:"When an agent hands off a task for human review (high priority)"},{event:"planning-awaiting-input",label:"Planning needs input",description:"When planning mode is waiting for your response to continue"},{event:"cli-agent-awaiting-input",label:"CLI agent needs input",description:"When a CLI agent is blocked on a tool permission or terminal input prompt"},{event:"gridlock",label:"Pipeline gridlocked",description:"When all schedulable todo tasks are blocked and work cannot advance"},{event:"fallback-used",label:"Fallback model used (recovered)",description:"When Fusion recovers from a retryable model failure by switching to a fallback model"},{event:"task-created",label:"Agent created a task",description:"When an agent files a new task on the board"},{event:"memory-dreams-processed",label:"DREAMS.md entry added",description:"When manual dream processing writes a new entry to project or agent DREAMS.md"},{event:"message:agent-to-user",label:"Agent → user message",description:"An agent sent you a direct message"},{event:"message:agent-to-agent",label:"Agent → agent message",description:"Agents are talking to each other (including replies)"},{event:"message:room",label:"Agent message in room",description:"An agent posted a reply in a chat room you're watching"},{event:"oauth-token-expired",label:"OAuth token expired",description:"Notify when a provider OAuth token (Codex, Claude, etc.) expires."}];function fd({scopeBanner:a,form:t,setForm:s,testNotificationLoading:c,testNotificationResult:n,onTestProviderNotification:m}){const{t:i}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:i("settings.notifications.notifications","Notifications")}),e.jsxs("div",{className:"notification-provider-card",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"failureNotificationMode",children:i("settings.notifications.failureNotificationMode","Failure notification mode")}),e.jsxs("select",{id:"failureNotificationMode",value:t.failureNotificationMode??"sticky-only",onChange:r=>{const h=r.target.value;s(k=>({...k,failureNotificationMode:h}))},children:[e.jsx("option",{value:"sticky-only",children:i("settings.notifications.stickyFailuresOnlyDefault","Sticky failures only (default)")}),e.jsx("option",{value:"terminal-only",children:i("settings.notifications.terminalFailuresOnlySuppressAutoRetried","Terminal failures only (suppress auto-retried)")}),e.jsx("option",{value:"all",children:i("settings.notifications.allFailuresLegacy","All failures (legacy)")})]}),e.jsx("small",{children:i("settings.notifications.stickyOnlySuppressesRecoveredFailuresTerminalOnlyWaits","Sticky-only suppresses recovered failures; terminal-only waits for paused/in-review failed tasks; all restores legacy alerts.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"failureNotificationDelayMs",children:i("settings.notifications.failureNotificationDelayMs","Failure notification delay (ms)")}),e.jsx("input",{id:"failureNotificationDelayMs",type:"number",min:0,step:1e3,disabled:(t.failureNotificationMode??"sticky-only")==="all",value:t.failureNotificationDelayMs??3e4,onChange:r=>{const h=Number(r.target.value);s(k=>({...k,failureNotificationDelayMs:Number.isFinite(h)&&h>=0?h:0}))}}),e.jsx("small",{children:i("settings.notifications.howLongAFailureMustPersistBeforeA"," How long a failure must persist before a push notification is sent. 0 = notify immediately. Default: 30000 (30 seconds). ")})]})]}),e.jsxs("div",{className:"notification-provider-card",children:[e.jsxs("div",{className:"notification-provider-header",children:[e.jsx("strong",{children:i("settings.notifications.ntfy","ntfy")}),e.jsxs("label",{htmlFor:"ntfyEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"ntfyEnabled",type:"checkbox",checked:t.ntfyEnabled||!1,onChange:r=>s(h=>({...h,ntfyEnabled:r.target.checked}))}),i("settings.notifications.enable"," Enable ")]}),e.jsx("small",{children:i("settings.notifications.ntfyEnabledHint","Default: disabled.")})]}),t.ntfyEnabled&&e.jsxs("div",{className:"notification-provider-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"ntfyTopic",children:i("settings.notifications.ntfyTopic","ntfy Topic")}),e.jsx("input",{id:"ntfyTopic",type:"text",placeholder:i("settings.notifications.myTopicName","my-topic-name"),value:t.ntfyTopic||"",onChange:r=>{const h=r.target.value;s(k=>({...k,ntfyTopic:h||void 0}))}}),e.jsxs("small",{children:[i("settings.notifications.yourNtfyShTopicName164Alphanumeric"," Your ntfy.sh topic name (1–64 alphanumeric/hyphen/underscore characters). No default — unset.")," ",e.jsx("a",{href:"https://ntfy.sh",target:"_blank",rel:"noopener noreferrer",className:"settings-inline-link",children:i("settings.notifications.learnMoreAboutNtfySh"," Learn more about ntfy.sh ")})]}),t.ntfyTopic&&!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic)&&e.jsx("small",{className:"field-error",children:i("settings.notifications.topicMustBe164AlphanumericHyphenOr"," Topic must be 1–64 alphanumeric, hyphen, or underscore characters ")}),e.jsxs("details",{className:"ntfy-advanced-disclosure",children:[e.jsx("summary",{children:i("settings.notifications.advanced","Advanced")}),e.jsxs("div",{className:"ntfy-advanced-content",children:[e.jsx("label",{htmlFor:"ntfyBaseUrl",children:i("settings.notifications.customNtfyServerURLOptional","Custom ntfy server URL (optional)")}),e.jsx("input",{id:"ntfyBaseUrl",type:"url",placeholder:i("settings.notifications.httpsNtfySh","https://ntfy.sh"),value:t.ntfyBaseUrl||"",onChange:r=>{const h=r.target.value;s(k=>({...k,ntfyBaseUrl:h||void 0}))}}),e.jsx("small",{children:i("settings.notifications.leaveBlankToKeepTheDefaultServerHttps"," Leave blank to keep the default server: https://ntfy.sh. Custom servers must use http:// or https://. No default — unset. ")}),e.jsx("label",{htmlFor:"ntfyAccessToken",children:i("settings.notifications.accessTokenOptional","Access token (optional)")}),e.jsx("input",{id:"ntfyAccessToken",type:"password",autoComplete:"off",placeholder:i("settings.notifications.tk","tk_..."),value:t.ntfyAccessToken||"",onChange:r=>{const h=r.target.value;s(k=>({...k,ntfyAccessToken:h||void 0}))}}),e.jsx("small",{children:i("settings.notifications.leaveBlankToPublishWithoutAuthenticationWhenSet"," Leave blank to publish without authentication. When set, Fusion sends an Authorization Bearer header with ntfy requests. No default — unset. ")})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:i("settings.notifications.notifyOnEvents","Notify on events")}),e.jsx("div",{className:"ntfy-events-list",children:Yn.map(({event:r,label:h,description:k})=>{const v=t.ntfyEvents?.includes(r)??!0;return e.jsxs("div",{children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:d=>{const u=t.ntfyEvents??[...ra],j=d.target.checked?u.includes(r)?u:[...u,r]:u.filter(x=>x!==r);s(x=>({...x,ntfyEvents:j.length>0?j:void 0}))}}),h]}),e.jsx("small",{children:k})]},`ntfy-${r}`)})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"ntfyDashboardHost",children:i("settings.notifications.dashboardHostname","Dashboard Hostname")}),e.jsx("input",{id:"ntfyDashboardHost",type:"text",placeholder:i("settings.notifications.httpLocalhost3000","http://localhost:3000"),value:t.ntfyDashboardHost||"",onChange:r=>{const h=r.target.value;s(k=>({...k,ntfyDashboardHost:h||void 0}))}}),e.jsx("small",{children:i("settings.notifications.baseURLForDeepLinksInNotificationsWhen"," Base URL for deep links in notifications. When set, clicking a notification opens the dashboard directly to the task. No default — unset. ")}),t.ntfyDashboardHost&&!/^https?:\/\/.+/.test(t.ntfyDashboardHost)&&e.jsx("small",{className:"field-error",children:i("settings.notifications.mustBeAValidURLStartingWithHttp"," Must be a valid URL starting with http:// or https:// ")})]}),e.jsxs("div",{className:"notification-provider-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m("ntfy"),disabled:c.ntfy||c["ntfy-message"]||c["ntfy-room"]||!t.ntfyEnabled||!t.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic),children:c.ntfy?i("settings.notifications.sending","Sending…"):i("settings.notifications.testNotification","Test notification")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m("ntfy-message"),disabled:c.ntfy||c["ntfy-message"]||c["ntfy-room"]||!t.ntfyEnabled||!t.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic),children:c["ntfy-message"]?i("settings.notifications.sending","Sending…"):i("settings.notifications.testMessageInbox","Test message inbox")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m("ntfy-room"),disabled:c.ntfy||c["ntfy-message"]||c["ntfy-room"]||!t.ntfyEnabled||!t.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic),children:c["ntfy-room"]?i("settings.notifications.sending","Sending…"):i("settings.notifications.testRoomReply","Test room reply")})]}),(n.ntfy||n["ntfy-message"]||n["ntfy-room"])&&e.jsxs("div",{className:"notification-test-feedback","aria-live":"polite",children:[n.ntfy&&e.jsxs("small",{className:`notification-test-feedback-item notification-test-feedback-item--${n.ntfy.status}`,children:[i("settings.notifications.general"," General: "),n.ntfy.message]}),n["ntfy-message"]&&e.jsxs("small",{className:`notification-test-feedback-item notification-test-feedback-item--${n["ntfy-message"].status}`,children:[i("settings.notifications.messageInbox"," Message inbox: "),n["ntfy-message"].message]}),n["ntfy-room"]&&e.jsxs("small",{className:`notification-test-feedback-item notification-test-feedback-item--${n["ntfy-room"].status}`,children:[i("settings.notifications.roomReply"," Room reply: "),n["ntfy-room"].message]})]})]})]}),e.jsxs("div",{className:"notification-provider-card",children:[e.jsxs("div",{className:"notification-provider-header",children:[e.jsx("strong",{children:i("settings.notifications.webhook","Webhook")}),e.jsxs("label",{htmlFor:"webhookEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"webhookEnabled",type:"checkbox",checked:t.webhookEnabled||!1,onChange:r=>s(h=>({...h,webhookEnabled:r.target.checked}))}),i("settings.notifications.webhookNotifications"," Webhook notifications ")]}),e.jsx("small",{children:i("settings.notifications.webhookEnabledHint","Default: disabled.")})]}),t.webhookEnabled&&e.jsxs("div",{className:"notification-provider-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"webhookUrl",children:i("settings.notifications.webhookURL","Webhook URL")}),e.jsx("input",{id:"webhookUrl",type:"text",placeholder:i("settings.notifications.httpsHooksExampleCom","https://hooks.example.com/..."),value:t.webhookUrl||"",onChange:r=>{const h=r.target.value;s(k=>({...k,webhookUrl:h||void 0}))}}),e.jsx("small",{children:i("settings.notifications.webhookUrlHint","No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"webhookFormat",children:i("settings.notifications.format","Format")}),e.jsxs("select",{id:"webhookFormat",value:t.webhookFormat||"generic",onChange:r=>{const h=r.target.value;s(k=>({...k,webhookFormat:h}))},children:[e.jsx("option",{value:"slack",children:i("settings.notifications.slack","Slack")}),e.jsx("option",{value:"discord",children:i("settings.notifications.discord","Discord")}),e.jsx("option",{value:"generic",children:i("settings.notifications.generic","Generic")})]}),e.jsx("small",{children:i("settings.notifications.webhookFormatHint","Default: generic.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:i("settings.notifications.notifyOnEvents","Notify on events")}),e.jsx("div",{className:"ntfy-events-list",children:Yn.map(({event:r,label:h,description:k})=>{const d=(t.webhookEvents??[...ra]).includes(r);return e.jsxs("div",{children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:d,onChange:u=>{const j=t.webhookEvents??[...ra],x=u.target.checked?j.includes(r)?j:[...j,r]:j.filter(b=>b!==r);s(b=>({...b,webhookEvents:x.length>0?x:void 0}))}}),h]}),e.jsx("small",{children:k})]},`webhook-${r}`)})})]}),e.jsx("div",{className:"notification-provider-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m("webhook"),disabled:c.webhook||!t.webhookUrl,children:c.webhook?i("settings.notifications.sending","Sending…"):i("settings.notifications.testNotification","Test notification")})}),n.webhook&&e.jsx("div",{className:"notification-test-feedback","aria-live":"polite",children:e.jsx("small",{className:`notification-test-feedback-item notification-test-feedback-item--${n.webhook.status}`,children:n.webhook.message})})]})]})]})}const Jt="__custom__";function vd(a){const t=new Map;for(const s of a){const c=s.value.trim();!c||t.has(c)||t.set(c,{...s,value:c,label:s.label?.trim()||c})}return[...t.values()].sort((s,c)=>s.value.localeCompare(c.value))}function Nr({id:a,value:t,onChange:s,options:c,loading:n=!1,error:m,placeholder:i="owner/repo",ariaLabel:r}){const{t:h}=Z("app"),k=o.useRef(null),v=o.useId(),[d,u]=o.useState(!1),j=o.useMemo(()=>vd(c),[c]),x=j.find(C=>C.value===t),b=x?x.value:Jt;o.useEffect(()=>{u(b===Jt)},[b]);const S=C=>{if(C===Jt){u(!0),requestAnimationFrame(()=>{k.current?.focus()});return}u(!1),s(C)},E=m||(n?h("trackingRepoSelect.loadingHint","Loading detected GitHub remotes…"):null);return e.jsxs("div",{className:"tracking-repo-select",children:[e.jsxs("select",{id:a,className:"select",value:b,onChange:C=>S(C.target.value),"aria-label":r,"aria-describedby":E?v:void 0,children:[j.map(C=>e.jsx("option",{value:C.value,children:C.source?`${C.label} — ${C.source}`:C.label},C.value)),e.jsx("option",{value:Jt,children:h("trackingRepoSelect.customOption","Custom…")})]}),d?e.jsx("input",{ref:k,className:"input tracking-repo-select__custom-input",type:"text",value:t,placeholder:i,onChange:C=>s(C.target.value),"aria-describedby":E?v:void 0}):null,E?e.jsx("small",{id:v,className:m?"tracking-repo-select__hint tracking-repo-select__hint--error":"tracking-repo-select__hint",children:E}):null]})}function xd({defer:a=!1}){const{t}=Z("app"),[s,c]=o.useState(null),[n,m]=o.useState(!1),[i,r]=o.useState(!1),[h,k]=o.useState(null),[v,d]=o.useState(null),[u,j]=o.useState(null),x=L=>{switch(L){case"installed":return{text:t("cliBinary.stateInstalled","Installed"),tone:"ok"};case"missing":return{text:t("cliBinary.stateMissing","Not installed"),tone:"err"};case"version-mismatch":return{text:t("cliBinary.stateVersionMismatch","Version mismatch"),tone:"warn"};case"skipped":return{text:t("cliBinary.stateCheckDisabled","Check disabled"),tone:"warn"}}},b=o.useCallback(async()=>{m(!0),d(null);try{const L=await qi();c(L)}catch(L){d(L instanceof Error?L.message:String(L))}finally{m(!1)}},[]);o.useEffect(()=>{a||b()},[a,b]);const S=o.useCallback(async()=>{r(!0),k(null),d(null);try{const L=await zi();c({binary:L.binary,expectedVersion:L.expectedVersion,state:L.state,install:L.install}),k(L.installResult)}catch(L){d(L instanceof Error?L.message:String(L))}finally{r(!1)}},[]),E=o.useCallback(async(L,y)=>{try{await navigator.clipboard.writeText(y),j(L),setTimeout(()=>j(p=>p===L?null:p),1500)}catch{}},[]),C=s?x(s.state):null;return e.jsxs("div",{className:"cli-binary-panel",children:[e.jsxs("div",{className:"cli-binary-header",children:[e.jsx("h4",{className:"settings-section-heading",children:t("cliBinary.heading","CLI Binary")}),C&&e.jsx("span",{className:`cli-binary-pill cli-binary-pill--${C.tone}`,children:C.text})]}),e.jsx("small",{className:"cli-binary-help",children:t("cliBinary.help","Installing the global CLI lets you run fn and fusion from any terminal. Automations and scripts work without it via npx, but a global install is faster and more convenient.")}),n&&!s&&e.jsx("p",{className:"cli-binary-status-line",children:t("cliBinary.checking","Checking…")}),s&&e.jsxs("div",{className:"cli-binary-detail",children:[s.binary.installed?e.jsxs("ul",{className:"cli-binary-info-list",children:[e.jsxs("li",{children:[e.jsx("span",{children:t("cliBinary.binaryLabel","Binary:")}),e.jsx("code",{children:s.binary.binary})]}),s.binary.path&&e.jsxs("li",{children:[e.jsx("span",{children:t("cliBinary.pathLabel","Path:")}),e.jsx("code",{children:s.binary.path})]}),e.jsxs("li",{children:[e.jsx("span",{children:t("cliBinary.versionLabel","Version:")}),e.jsx("code",{children:s.binary.version??"unknown"}),e.jsx("span",{className:"cli-binary-expected",children:t("cliBinary.expectedVersion","(expected {{version}})",{version:s.expectedVersion})})]})]}):e.jsx("p",{className:"cli-binary-status-line",children:t("cliBinary.notOnPath","Neither fn nor fusion was found on PATH.")}),e.jsxs("div",{className:"cli-binary-actions",children:[e.jsx("button",{type:"button",className:"cli-binary-install-btn",onClick:S,disabled:i,children:i?t("cliBinary.installing","Installing…"):s.binary.installed?t("cliBinary.reinstall","Reinstall"):t("cliBinary.installWithNpm","Install with npm")}),e.jsx("button",{type:"button",className:"cli-binary-refresh-btn",onClick:()=>void b(),disabled:n||i,children:t("cliBinary.refresh","Refresh")})]}),e.jsxs("div",{className:"cli-binary-commands",children:[e.jsx("label",{children:t("cliBinary.orCopyLabel","Or copy and run yourself:")}),[{label:"npm",command:s.install.npm},{label:"curl",command:s.install.curl}].map(({label:L,command:y})=>e.jsxs("div",{className:"cli-binary-command-row",children:[e.jsx("code",{children:y}),e.jsx("button",{type:"button",onClick:()=>void E(L,y),className:"cli-binary-copy-btn",children:u===L?t("cliBinary.copied","Copied"):t("cliBinary.copy","Copy")})]},L))]})]}),h&&e.jsxs("details",{className:"cli-binary-install-log",open:!h.success,children:[e.jsx("summary",{children:h.success?t("cliBinary.succeededDuration","Install succeeded in {{duration}}s",{duration:(h.durationMs/1e3).toFixed(1)}):t("cliBinary.failedExit","Install failed (exit {{code}})",{code:h.exitCode??"n/a"})}),h.permissionsHint&&e.jsx("p",{className:"cli-binary-permissions-hint",children:h.permissionsHint}),h.stdout&&e.jsx("pre",{className:"cli-binary-install-output",children:h.stdout}),h.stderr&&e.jsx("pre",{className:"cli-binary-install-output cli-binary-install-output--err",children:h.stderr})]}),v&&e.jsx("p",{className:"field-error",children:v})]})}function yd({scopeBanner:a,form:t,setForm:s,globalSettings:c,onGlobalGitlabSettingsChange:n,globalTrackingRepoOptions:m,globalTrackingRepoLoading:i,globalTrackingRepoError:r}){const{t:h}=Z("app"),k=c??t;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:h("settings.globalGeneral.general","General")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalGithubTrackingDefaultRepo",children:h("settings.globalGeneral.globalDefaultTrackingRepo","Global default tracking repo")}),e.jsx(Nr,{id:"globalGithubTrackingDefaultRepo",ariaLabel:"Global default tracking repo",value:t.githubTrackingDefaultRepo??"",options:m,loading:i,error:r??void 0,placeholder:h("settings.globalGeneral.ownerRepo","owner/repo"),onChange:v=>s(d=>({...d,githubTrackingDefaultRepo:v||void 0}))}),e.jsx("small",{children:h("settings.globalGeneral.projectsInheritThisValueWhenTheyDoNot","Projects inherit this value when they do not set a project default tracking repo. No default — unset.")})]}),e.jsxs("details",{className:"settings-gitlab-disclosure","data-testid":"global-gitlab-configuration-disclosure",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"settings-gitlab-disclosure__title",children:h("settings.globalGeneral.gitLabConfiguration","GitLab Configuration")}),e.jsxs("label",{className:"checkbox-label settings-gitlab-disclosure__toggle",htmlFor:"globalGitlabEnabled",onClick:v=>v.stopPropagation(),children:[e.jsx("input",{id:"globalGitlabEnabled",type:"checkbox",checked:k.gitlabEnabled!==!1,onChange:v=>n({gitlabEnabled:v.target.checked})}),h("settings.globalGeneral.enableGitLabIntegration","Enable GitLab integration")]})]}),e.jsx("small",{className:"settings-description",children:k.gitlabEnabled===!1?h("settings.globalGeneral.gitLabDisabledHint","GitLab API operations are disabled by global default. Saved URL and token fallbacks remain stored for re-enable."):h("settings.globalGeneral.gitLabEnabledHint","Global GitLab URL and token fallbacks apply to projects that do not set their own values. No default — unset (unset behaves as enabled until explicitly disabled).")}),e.jsxs("div",{className:"settings-gitlab-disclosure__body","aria-disabled":k.gitlabEnabled===!1,children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalGitlabInstanceUrl",children:h("settings.globalGeneral.gitLabInstanceUrl","Global GitLab instance URL")}),e.jsx("input",{id:"globalGitlabInstanceUrl",className:"input",type:"url",placeholder:"https://gitlab.com",value:k.gitlabInstanceUrl??"",disabled:k.gitlabEnabled===!1,onChange:v=>n({gitlabInstanceUrl:v.target.value||void 0})}),e.jsx("small",{children:h("settings.globalGeneral.gitLabInstanceUrlHint","Blank defaults to GitLab.com. Projects inherit this self-managed GitLab URL unless they set their own project value. No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalGitlabApiBaseUrl",children:h("settings.globalGeneral.gitLabApiBaseUrlOptional","Global GitLab API base URL (optional / advanced)")}),e.jsx("input",{id:"globalGitlabApiBaseUrl",className:"input",type:"url",placeholder:"https://gitlab.com/api/v4",value:k.gitlabApiBaseUrl??"",disabled:k.gitlabEnabled===!1,onChange:v=>n({gitlabApiBaseUrl:v.target.value||void 0})}),e.jsx("small",{children:h("settings.globalGeneral.gitLabApiBaseUrlHint","Blank derives <instance>/api/v4. Override only for self-managed GitLab API gateways that use a different absolute http:// or https:// URL. No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalGitlabAuthTokenType",children:h("settings.globalGeneral.gitLabTokenType","Global GitLab token type")}),e.jsxs("select",{id:"globalGitlabAuthTokenType",className:"select",value:k.gitlabAuthTokenType??"personal",disabled:k.gitlabEnabled===!1,onChange:v=>n({gitlabAuthTokenType:v.target.value}),children:[e.jsx("option",{value:"personal",children:h("settings.globalGeneral.gitLabPersonalAccessToken","Personal access token")}),e.jsx("option",{value:"project",children:h("settings.globalGeneral.gitLabProjectAccessToken","Project access token")}),e.jsx("option",{value:"group",children:h("settings.globalGeneral.gitLabGroupAccessToken","Group access token")})]}),e.jsx("small",{children:h("settings.globalGeneral.gitLabTokenTypeHint","No default — unset (the selector falls back to personal access token until you choose otherwise).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalGitlabAuthToken",children:h("settings.globalGeneral.gitLabAccessToken","Global GitLab access token")}),e.jsx("input",{id:"globalGitlabAuthToken",className:"input",type:"password",autoComplete:"off",value:k.gitlabAuthToken??"",disabled:k.gitlabEnabled===!1,onChange:v=>n({gitlabAuthToken:v.target.value||void 0})}),e.jsx("small",{className:"settings-description",children:h("settings.globalGeneral.gitLabAuthTokenHint","Projects inherit this fallback only when they do not set a project GitLab token. Read-only operations need read_api or api; write actions need api; project/group tokens remain limited by resource membership. No default — unset.")})]})]})]}),e.jsx(xd,{}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"dismissModalsOnOutsideClick",className:"checkbox-label",children:[e.jsx("input",{id:"dismissModalsOnOutsideClick",type:"checkbox",checked:t.dismissModalsOnOutsideClick===!0,onChange:v=>s(d=>({...d,dismissModalsOnOutsideClick:v.target.checked}))}),h("settings.globalGeneral.dismissModalsByClickingOutside"," Dismiss modals by clicking outside ")]}),e.jsx("small",{children:h("settings.globalGeneral.dismissModalsByClickingOutsideHint"," When enabled, clicking or tapping a modal backdrop closes the modal. Default: disabled, to prevent accidental dismissal. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"persistAgentToolOutput",className:"checkbox-label",children:[e.jsx("input",{id:"persistAgentToolOutput",type:"checkbox",checked:t.persistAgentToolOutput===!0,onChange:v=>s(d=>({...d,persistAgentToolOutput:v.target.checked}))}),h("settings.globalGeneral.saveToolOutputInAgentLogs"," Save tool output in agent logs ")]}),e.jsx("small",{children:h("settings.globalGeneral.whenDisabledToolRowsAreStillLoggedBut"," When disabled, tool rows are still logged but detailed tool payloads are omitted. Very large tool payloads may still be clipped even when this stays enabled. Default: disabled. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("h5",{className:"settings-section-heading",children:h("settings.globalGeneral.saveAIThinkingLogs","Save AI thinking logs")}),e.jsxs("label",{htmlFor:"persistAgentThinkingLogPermanent",className:"checkbox-label",children:[e.jsx("input",{id:"persistAgentThinkingLogPermanent",type:"checkbox",checked:kn(t,{ephemeral:!1}),onChange:v=>s(d=>({...d,persistAgentThinkingLogPermanent:v.target.checked}))}),h("settings.globalGeneral.saveAIThinkingForPermanentAgents"," Save AI thinking for permanent agents ")]}),e.jsxs("label",{htmlFor:"persistAgentThinkingLogEphemeral",className:"checkbox-label",children:[e.jsx("input",{id:"persistAgentThinkingLogEphemeral",type:"checkbox",checked:kn(t,{ephemeral:!0}),onChange:v=>s(d=>({...d,persistAgentThinkingLogEphemeral:v.target.checked}))}),h("settings.globalGeneral.saveAIThinkingForEphemeralTaskWorkerAgents"," Save AI thinking for ephemeral / task-worker agents ")]}),e.jsxs("small",{children:[h("settings.globalGeneral.leaveBothThinkingTogglesOffToKeepThe"," Leave both thinking toggles off to keep the original default behavior. This only controls persisted "),e.jsx("code",{children:"thinking"}),h("settings.globalGeneral.rowsAndDoesNotAffectAssistantTextOr"," rows and does not affect assistant text or tool rows. Default: disabled for both permanent and ephemeral agents. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"fnBinaryCheckEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"fnBinaryCheckEnabled",type:"checkbox",checked:t.fnBinaryCheckEnabled!==!1,onChange:v=>s(d=>({...d,fnBinaryCheckEnabled:v.target.checked}))}),h("settings.globalGeneral.checkForThe"," Check for the "),e.jsx("code",{children:"fn"}),h("settings.globalGeneral.cLIBinaryOnPATH"," CLI binary on PATH ")]}),e.jsxs("small",{children:[h("settings.globalGeneral.whenEnabledTheDashboardProbesForAGlobally"," When enabled, the dashboard probes for a globally-installed")," ",e.jsx("code",{children:"fn"})," / ",e.jsx("code",{children:"fusion"}),h("settings.globalGeneral.cLIBySpawning"," CLI by spawning")," ",e.jsx("code",{children:"<bin> --version"}),h("settings.globalGeneral.disableThisIfYourLocalDevProcessIs",". Disable this if your local dev process is the source of truth and you don't want any outdated globally-installed binary executed during the probe. Default: enabled. ")]})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:h("settings.globalGeneral.updates","Updates")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"updateCheckEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"updateCheckEnabled",type:"checkbox",checked:t.updateCheckEnabled!==!1,onChange:v=>s(d=>({...d,updateCheckEnabled:v.target.checked}))}),h("settings.globalGeneral.checkForUpdatesAutomatically"," Check for updates automatically ")]}),e.jsxs("small",{children:[h("settings.globalGeneral.whenEnabledFusionChecksNpmForNewVersions"," When enabled, Fusion checks npm for new versions of")," ",e.jsx("code",{children:"@runfusion/fusion"}),h("settings.globalGeneral.andShowsUpdateNoticesInTheCLIAnd"," and shows update notices in the CLI and dashboard. Cadence is governed by the frequency below. Default: enabled. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"updateCheckFrequency",children:h("settings.globalGeneral.frequency","Frequency")}),e.jsxs("select",{id:"updateCheckFrequency",value:t.updateCheckFrequency??"daily",onChange:v=>s(d=>({...d,updateCheckFrequency:v.target.value})),disabled:t.updateCheckEnabled===!1,children:[e.jsx("option",{value:"manual",children:h("settings.globalGeneral.manualOnlyNeverAutoCheck","Manual only — never auto-check")}),e.jsx("option",{value:"on-startup",children:h("settings.globalGeneral.onStartupOncePerServerLaunch","On startup — once per server launch")}),e.jsx("option",{value:"daily",children:h("settings.globalGeneral.dailyRecommended","Daily (recommended)")}),e.jsx("option",{value:"weekly",children:h("settings.globalGeneral.weekly","Weekly")})]}),e.jsx("small",{children:h("settings.globalGeneral.controlsHowOftenTheDashboardReFetchesThe"," Controls how often the dashboard re-fetches the npm registry. Use the version + refresh control in the header to trigger an immediate check at any time. Default: daily. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoReloadOnVersionChange",className:"checkbox-label",children:[e.jsx("input",{id:"autoReloadOnVersionChange",type:"checkbox",checked:t.autoReloadOnVersionChange!==!1,onChange:v=>s(d=>({...d,autoReloadOnVersionChange:v.target.checked}))}),h("settings.globalGeneral.autoReloadDashboardOnVersionChange"," Auto-reload dashboard on version change ")]}),e.jsx("small",{children:h("settings.globalGeneral.whenEnabledDefaultTheDashboardAutomaticallyReloadsWhen"," When enabled (default), the dashboard automatically reloads when it detects a new build version — either from server rebuilds or service worker updates. Disable this to stay on the current version until you manually refresh. Default: enabled. ")})]})]})}function kd({id:a,value:t,defaultValue:s,invalid:c,describedById:n,onChange:m}){const{t:i}=Z("app"),[r,h]=o.useState(!1),k=o.useRef(null),v=o.useCallback(()=>{k.current?.(),k.current=null,h(!1)},[]);o.useEffect(()=>()=>{k.current?.(),k.current=null},[]);const d=o.useCallback(()=>{if(typeof document>"u")return;h(!0);const u=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){v();return}if(["Control","Alt","Shift","Meta"].includes(j.key))return;const x=[];j.ctrlKey&&x.push("Ctrl"),j.altKey&&x.push("Alt"),j.shiftKey&&x.push("Shift"),j.metaKey&&x.push("Meta"),x.push(j.key===" "?"Space":j.key);const b=wa(x.join("+"));b.valid&&!b.disabled&&m(b.normalized),v()};document.addEventListener("keydown",u,{capture:!0}),k.current=()=>document.removeEventListener("keydown",u,{capture:!0})},[m,v]);return e.jsxs("div",{className:"shortcut-capture","data-shortcuts-ignore":"true",children:[e.jsx("input",{id:a,className:`input shortcut-capture__input${c?" shortcut-capture__input--invalid":""}`,value:r?i("settings.keyboardShortcuts.recording","Press keys… (Esc to cancel)"):t,placeholder:s,readOnly:r,"aria-invalid":c||void 0,"aria-describedby":n,"data-shortcuts-ignore":"true",onFocus:u=>{r&&u.currentTarget.blur()},onChange:u=>m(u.target.value)}),e.jsx("button",{type:"button",className:`btn btn-sm shortcut-capture__record${r?" shortcut-capture__record--active":""}`,"aria-pressed":r,title:r?i("settings.keyboardShortcuts.recordingTitle","Recording… press Escape to cancel"):i("settings.keyboardShortcuts.recordTitle","Record a new shortcut"),onClick:()=>r?v():d(),children:r?i("settings.keyboardShortcuts.recordingLabel","Recording…"):i("settings.keyboardShortcuts.recordLabel","Record")}),e.jsx("button",{type:"button",className:"btn btn-sm shortcut-capture__clear",title:i("settings.keyboardShortcuts.clearTitle","Disable this shortcut"),onClick:()=>{r&&v(),m("")},children:i("settings.keyboardShortcuts.clearLabel","Clear")})]})}function jd({scopeBanner:a,form:t,setForm:s}){const{t:c}=Z("app"),n=va(t.dashboardKeyboardShortcuts),m=gr(n),i=(r,h)=>s(k=>({...k,dashboardKeyboardShortcuts:{...va(k.dashboardKeyboardShortcuts),[r]:h}}));return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.keyboardShortcuts.title","Keyboard Shortcuts")}),e.jsx("p",{className:"settings-description",children:c("settings.keyboardShortcuts.hint","Configure global dashboard shortcuts. Click Record and press a combination, or type one manually. Shortcuts are ignored while typing in inputs, editors, chat composers, and terminal fields. Leave blank to disable an action.")}),e.jsxs("div",{className:"form-group settings-keyboard-shortcuts","data-testid":"keyboard-shortcuts-settings",children:[Vi.map(r=>e.jsxs("div",{className:"shortcut-category",children:[e.jsx("h5",{className:"settings-section-heading",children:c(`settings.keyboardShortcuts.category.${r.id}`,r.label)}),r.actions.map(h=>{const k=wa(n[h]),v=`dashboardShortcut-${h}`,d=`${v}Hint`;return e.jsxs("div",{className:"shortcut-row",children:[e.jsx("label",{htmlFor:v,children:c(`settings.keyboardShortcuts.action.${h}`,Yi(h))}),e.jsx(kd,{id:v,value:n[h],defaultValue:jn[h],invalid:!k.valid,describedById:d,onChange:u=>i(h,u)}),e.jsx("small",{id:d,children:k.valid?c("settings.keyboardShortcuts.rowHint","Default: {{default}}. Leave blank to disable.",{default:jn[h]}):k.error})]},h)})]},r.id)),m&&e.jsx("small",{className:"settings-description shortcut-conflict-banner",role:"alert",children:m})]})]})}function wd({scopeBanner:a,form:t,setForm:s,authProviders:c,onNavigateToSection:n}){const{t:m}=Z("app"),i=t.researchGlobalWebSearchProvider??t.researchGlobalDefaults?.searchProvider??"builtin",r=i==="searxng"||i==="brave"||i==="google"||i==="tavily",h=i==="brave"||i==="tavily"?i:null,k=h?c.some(d=>d.id===h&&!d.authenticated):!1,v=d=>{s(u=>({...u,researchGlobalWebSearchProvider:d,researchGlobalDefaults:{...u.researchGlobalDefaults??{},searchProvider:d}}))};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:m("settings.researchGlobal.researchDefaults","Research Defaults")}),e.jsxs("div",{className:"form-group settings-research-provider-group",children:[e.jsxs("label",{htmlFor:"research-global-provider-builtin",className:"checkbox-label",children:[e.jsx("input",{id:"research-global-provider-builtin",type:"radio",name:"research-global-search-provider",checked:!r,onChange:()=>v("builtin")}),m("settings.researchGlobal.builtInUsesAgentWebTools"," Built-in (uses agent web tools) (default) ")]}),e.jsx("small",{children:m("settings.researchGlobal.searchesAndFetchesUseTheAgentsNativeWebSearch"," Searches and fetches use the agent's native WebSearch/WebFetch tools. No API key required. Default: builtin. ")}),e.jsxs("details",{className:"settings-option-details settings-research-provider-advanced-details",children:[e.jsx("summary",{children:m("settings.researchGlobal.advancedExternalSearchProviders","Advanced — external search providers")}),e.jsxs("div",{className:"settings-research-provider-advanced-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"research-global-search-provider-advanced",children:m("settings.researchGlobal.searchProvider","Search Provider")}),e.jsxs("select",{id:"research-global-search-provider-advanced",className:"input",value:r?i:"searxng",onChange:d=>v(d.target.value),children:[e.jsx("option",{value:"searxng",children:m("settings.researchGlobal.searXNG","SearXNG")}),e.jsx("option",{value:"brave",children:m("settings.researchGlobal.brave","Brave")}),e.jsx("option",{value:"google",children:m("settings.researchGlobal.googleCustomSearch","Google Custom Search")}),e.jsx("option",{value:"tavily",children:m("settings.researchGlobal.tavily","Tavily")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"research-global-searxng-url",children:m("settings.researchGlobal.searXNGURL","SearXNG URL")}),e.jsx("input",{id:"research-global-searxng-url",className:"input",value:t.researchGlobalSearxngUrl??"",onChange:d=>s(u=>({...u,researchGlobalSearxngUrl:d.target.value||void 0})),placeholder:m("settings.researchGlobal.httpsSearxExampleCom","https://searx.example.com")}),e.jsx("small",{children:m("settings.researchGlobal.searXNGURLHint","No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"research-global-google-cx",children:m("settings.researchGlobal.googleSearchCX","Google Search CX")}),e.jsx("input",{id:"research-global-google-cx",className:"input",value:t.researchGlobalGoogleSearchCx??"",onChange:d=>s(u=>({...u,researchGlobalGoogleSearchCx:d.target.value||void 0})),placeholder:m("settings.researchGlobal.customSearchEngineId","custom-search-engine-id")}),e.jsx("small",{children:m("settings.researchGlobal.googleSearchCXHint","No default — unset.")})]}),e.jsxs("div",{className:"settings-empty-state settings-research-empty-state",role:"note",children:[m("settings.researchGlobal.configureBraveTavilyAndGoogleAPIKeysIn"," Configure Brave, Tavily, and Google API keys in Authentication. "),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>n("authentication"),children:m("settings.researchGlobal.openAuthenticationSettings"," Open Authentication Settings ")})]})]})]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-research-limits-grid",children:[e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-global-max-concurrent",children:m("settings.researchGlobal.defaultMaxConcurrentRuns","Default Max Concurrent Runs")}),e.jsx("input",{id:"research-global-max-concurrent",className:"input",type:"number",min:1,value:t.researchGlobalMaxConcurrentRuns??3,onChange:d=>s(u=>({...u,researchGlobalMaxConcurrentRuns:d.target.value===""?void 0:Number(d.target.value)}))}),e.jsx("small",{children:m("settings.researchGlobal.maxConcurrentRunsHint","Default: 3.")})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-global-max-sources",children:m("settings.researchGlobal.defaultMaxSourcesPerRun","Default Max Sources Per Run")}),e.jsx("input",{id:"research-global-max-sources",className:"input",type:"number",min:1,value:t.researchGlobalMaxSourcesPerRun??20,onChange:d=>s(u=>({...u,researchGlobalMaxSourcesPerRun:d.target.value===""?void 0:Number(d.target.value),researchGlobalDefaults:{...u.researchGlobalDefaults??{},maxSourcesPerRun:d.target.value===""?void 0:Number(d.target.value)}}))}),e.jsx("small",{children:m("settings.researchGlobal.maxSourcesPerRunHint","Default: 20.")})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-global-default-timeout",children:m("settings.researchGlobal.defaultMaxDurationMs","Default Max Duration (ms)")}),e.jsx("input",{id:"research-global-default-timeout",className:"input",type:"number",min:1e3,value:t.researchGlobalDefaultTimeout??3e5,onChange:d=>s(u=>({...u,researchGlobalDefaultTimeout:d.target.value===""?void 0:Number(d.target.value)}))}),e.jsx("small",{children:m("settings.researchGlobal.defaultMaxDurationMsHint","Default: 300000 (5 minutes).")})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-global-fetch-timeout",children:m("settings.researchGlobal.requestTimeoutMs","Request Timeout (ms)")}),e.jsx("input",{id:"research-global-fetch-timeout",className:"input",type:"number",min:1e3,value:t.researchGlobalFetchTimeoutMs??3e4,onChange:d=>s(u=>({...u,researchGlobalFetchTimeoutMs:d.target.value===""?void 0:Number(d.target.value)}))}),e.jsx("small",{children:m("settings.researchGlobal.requestTimeoutMsHint","Default: 30000 (30 seconds).")})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-global-max-synthesis-rounds",children:m("settings.researchGlobal.maxSynthesisRounds","Max Synthesis Rounds")}),e.jsx("input",{id:"research-global-max-synthesis-rounds",className:"input",type:"number",min:1,value:t.researchGlobalMaxSynthesisRounds??2,onChange:d=>s(u=>({...u,researchGlobalMaxSynthesisRounds:d.target.value===""?void 0:Number(d.target.value)}))}),e.jsx("small",{children:m("settings.researchGlobal.maxSynthesisRoundsHint","Default: 2.")})]})]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:m("settings.researchGlobal.enabledSources","Enabled Sources")}),e.jsxs("label",{htmlFor:"research-global-source-webSearch",className:"checkbox-label settings-research-source-locked",children:[e.jsx("input",{id:"research-global-source-webSearch",type:"checkbox",checked:!0,disabled:!0,readOnly:!0}),m("settings.researchGlobal.webSearch"," Web Search "),e.jsx("span",{className:"settings-muted",children:m("settings.researchGlobal.alwaysOn","Always on")})]}),e.jsxs("div",{className:"settings-research-source-grid",children:[e.jsxs("label",{htmlFor:"research-global-source-github",className:"checkbox-label",children:[e.jsx("input",{id:"research-global-source-github",type:"checkbox",checked:t.researchGlobalGitHubEnabled??!1,onChange:d=>s(u=>({...u,researchGlobalGitHubEnabled:d.target.checked}))}),m("settings.researchGlobal.gitHub"," GitHub "),e.jsx("small",{children:m("settings.researchGlobal.gitHubSourceHint"," Default: disabled. ")})]}),e.jsxs("label",{htmlFor:"research-global-source-local-docs",className:"checkbox-label",children:[e.jsx("input",{id:"research-global-source-local-docs",type:"checkbox",checked:t.researchGlobalLocalDocsEnabled??!0,onChange:d=>s(u=>({...u,researchGlobalLocalDocsEnabled:d.target.checked}))}),m("settings.researchGlobal.localDocs"," Local Docs "),e.jsx("small",{children:m("settings.researchGlobal.localDocsSourceHint"," Default: enabled. ")})]})]})]}),k&&e.jsxs("div",{className:"settings-empty-state",role:"alert",children:[m("settings.researchGlobal.missingCredentialsForTheSelectedResearchProvider"," Missing credentials for the selected research provider. "),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>n("authentication"),children:m("settings.researchGlobal.openAuthentication"," Open Authentication ")})]})]})}function Cd({scopeBanner:a,form:t,setForm:s,remote:c}){const{t:n}=Z("app"),{projectId:m,addToast:i,remoteStatus:r,externalTunnel:h,tunnelShareLink:k,remoteBusyAction:v,cloudflaredInstalling:d,cloudflaredInstallError:u,cloudflaredManualInstallCommand:j,cloudflaredMacFallbackCommand:x,handleInstallCloudflared:b,runRemoteAction:S,remoteShortLivedToken:E,setRemoteShortLivedToken:C,remoteAuthLinkTokenType:L,setRemoteAuthLinkTokenType:y,remoteUrlPreview:p,setRemoteUrlPreview:P,remoteQrSvg:f,setRemoteQrSvg:J}=c,W=t,X=W.remoteActiveProvider??null,Q=r?.state??"stopped",ne=Q==="running"?"running":Q==="starting"?"starting":Q==="failed"||Q==="error"?"error":"stopped",ae=V=>{const $=t;return{remoteActiveProvider:V,remoteTailscaleEnabled:V==="tailscale",remoteTailscaleHostname:String($.remoteTailscaleHostname??""),remoteTailscaleTargetPort:Number($.remoteTailscaleTargetPort??4040),remoteTailscaleAcceptRoutes:!!$.remoteTailscaleAcceptRoutes,remoteCloudflareEnabled:V==="cloudflare",remoteCloudflareQuickTunnel:!!($.remoteCloudflareQuickTunnel??!0),remoteCloudflareTunnelName:String($.remoteCloudflareTunnelName??""),remoteCloudflareTunnelToken:$.remoteCloudflareTunnelToken||null,remoteCloudflareIngressUrl:String($.remoteCloudflareIngressUrl??""),remoteShortLivedEnabled:!!$.remoteShortLivedEnabled,remoteShortLivedTtlMs:Number($.remoteShortLivedTtlMs??9e5),remoteRememberLastRunning:!!$.remoteRememberLastRunning}};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.remote.remoteAccess","Remote Access")}),e.jsxs("div",{className:`remote-status-bar remote-status-bar--${ne}`,children:[e.jsx("span",{className:`remote-status-dot remote-status-dot--${ne}`}),e.jsx("strong",{children:Q}),r?.provider&&e.jsxs("span",{children:[" · ",r.provider]}),r?.url&&e.jsx("code",{className:"remote-status-url",children:r.url}),r?.lastError&&e.jsx("span",{className:"field-error",children:r.lastError})]}),Q==="stopped"&&h&&e.jsxs("div",{className:"remote-external-tunnel-panel",role:"status",children:[e.jsxs("div",{className:"remote-external-tunnel-header",children:[e.jsx(At,{"aria-hidden":"true"}),e.jsxs("strong",{children:[n("settings.remote.external","External "),h.provider,n("settings.remote.tunnelDetected"," tunnel detected")]})]}),h.url&&e.jsx("code",{className:"settings-url-output",children:h.url}),k?.qrSvg&&e.jsxs("div",{className:"remote-external-tunnel-qr",children:[e.jsx("small",{children:n("settings.remote.scanToOpen","Scan to open:")}),e.jsx("img",{src:`data:image/svg+xml;utf8,${encodeURIComponent(k.qrSvg)}`,alt:n("settings.remote.externalTunnelQRCode","External tunnel QR code"),className:"settings-qr-preview-image"})]})]}),Q==="running"&&(r?.url||k)&&(()=>{let V=null,$=r?.url??null;if(k?.url)try{const T=new URL(k.url);V=T.searchParams.get("rt"),$||($=`${T.origin}/`)}catch{}return e.jsxs("div",{className:"remote-share-block",children:[$&&e.jsxs("div",{className:"remote-share-row",children:[e.jsx("small",{children:n("settings.remote.tailnetURL","Tailnet URL:")}),e.jsx("code",{className:"settings-url-output",children:$})]}),V&&e.jsxs("div",{className:"remote-share-row",children:[e.jsx("small",{children:n("settings.remote.remoteAccessCode","Remote access code:")}),e.jsx("code",{className:"settings-url-output",children:V})]}),k?.qrSvg&&e.jsxs("div",{className:"remote-share-row",children:[e.jsx("small",{children:n("settings.remote.scanToConnect","Scan to connect:")}),e.jsx("img",{src:`data:image/svg+xml;utf8,${encodeURIComponent(k.qrSvg)}`,alt:n("settings.remote.remoteAccessQRCode","Remote access QR code"),className:"settings-qr-preview-image"})]})]})})(),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"remote-provider-selector",role:"radiogroup","aria-label":n("settings.remote.remoteProvider","Remote provider"),children:[e.jsxs("label",{className:"remote-provider-option",children:[e.jsx("input",{type:"radio",name:"remoteProvider",value:"tailscale",checked:X==="tailscale",onChange:()=>s(V=>({...V,remoteActiveProvider:"tailscale"}))}),e.jsx("span",{children:e.jsxs("span",{className:"remote-provider-option-content",children:[e.jsx("span",{"data-testid":"remote-provider-icon-tailscale","aria-hidden":"true",children:e.jsx(At,{size:16})}),e.jsx("span",{children:n("settings.remote.tailscale","Tailscale")})]})})]}),e.jsxs("label",{className:"remote-provider-option",children:[e.jsx("input",{type:"radio",name:"remoteProvider",value:"cloudflare",checked:X==="cloudflare",onChange:()=>s(V=>({...V,remoteActiveProvider:"cloudflare"}))}),e.jsx("span",{children:e.jsxs("span",{className:"remote-provider-option-content",children:[e.jsx("span",{"data-testid":"remote-provider-icon-cloudflare","aria-hidden":"true",className:"remote-provider-option-icon",children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"remote-cloudflare-option-icon",children:e.jsx("path",{d:"M7 16.5h10.8a2.9 2.9 0 0 0 .3-5.8 4.9 4.9 0 0 0-9.3-1.6A3.6 3.6 0 0 0 7 16.5m-1.9 0h3.2a2.5 2.5 0 0 0 .2-5 3.4 3.4 0 0 0-3.4 3.4c0 .6 0 1 .2 1.6",fill:"var(--provider-cloudflare)"})})}),e.jsx("span",{children:n("settings.remote.cloudflare","Cloudflare")})]})})]})]}),!X&&e.jsx("small",{children:n("settings.remote.selectAProviderAboveToConfigureRemoteAccess","Select a provider above to configure remote access.")})]}),X==="cloudflare"&&r?.cloudflaredAvailable===!0&&e.jsxs("div",{className:"remote-cli-detection remote-cli-detection--available",role:"status",children:[e.jsx(Qi,{"aria-hidden":"true"}),e.jsx("span",{children:n("settings.remote.cloudflaredIsInstalled","cloudflared is installed")})]}),X==="cloudflare"&&r?.cloudflaredAvailable===!1&&e.jsxs("div",{className:"remote-cli-detection remote-cli-detection--missing",role:"status",children:[e.jsx(Ji,{"aria-hidden":"true"}),e.jsxs("div",{className:"remote-cli-detection-content",children:[e.jsx("span",{children:n("settings.remote.cloudflaredIsNotInstalled","cloudflared is not installed")}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:d||v!==null,onClick:()=>void b(),children:d?n("settings.remote.installing","Installing…"):n("settings.remote.installCloudflared","Install cloudflared")}),u&&e.jsx("small",{className:"remote-cli-install-error",children:u}),e.jsxs("small",{className:"remote-cli-manual",children:[n("settings.remote.manualInstall","Manual install: "),e.jsx("code",{children:j()})]}),x()?e.jsxs("small",{className:"remote-cli-manual",children:[n("settings.remote.ifHomebrewIsUnavailable","If Homebrew is unavailable: "),e.jsx("code",{children:x()})]}):null]})]}),X&&e.jsx("div",{className:"form-group remote-provider-settings",children:X==="tailscale"?e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:[n("settings.remote.tailscaleFunnelWillExposeThisDashboardOnYour","Tailscale Funnel will expose this dashboard on your tailnet's public "),"https://<machine>.<tailnet>.ts.net/",n("settings.remote.uRLNoHostnameOrPortConfigurationNeeded"," URL — no hostname or port configuration needed.")]}),e.jsxs("label",{htmlFor:"remoteTailscaleAcceptRoutes",className:"checkbox-label",children:[e.jsx("input",{id:"remoteTailscaleAcceptRoutes",type:"checkbox",checked:!!W.remoteTailscaleAcceptRoutes,onChange:V=>s($=>({...$,remoteTailscaleAcceptRoutes:V.target.checked}))}),n("settings.remote.acceptRoutes"," Accept routes ")]}),e.jsx("small",{children:n("settings.remote.acceptRoutesHint","Default: disabled.")})]}):e.jsxs(e.Fragment,{children:[e.jsx("small",{children:W.remoteCloudflareQuickTunnel??!0?n("settings.remote.usingQuickTunnel","Using Quick Tunnel — automatically creates a random trycloudflare.com URL, no account needed. Default: enabled."):n("settings.remote.namedTunnelModeEnabled","Named Tunnel mode enabled — configure tunnel name, token, and ingress URL below.")}),e.jsxs("details",{className:"remote-cf-advanced-details",open:!(W.remoteCloudflareQuickTunnel??!0),onToggle:V=>{const $=V.currentTarget.open;s(T=>{const U=!!(T.remoteCloudflareQuickTunnel??!0),re=!$;return U===re?T:{...T,remoteCloudflareQuickTunnel:re}})},children:[e.jsx("summary",{children:n("settings.remote.advancedNamedTunnel","Advanced (Named Tunnel)")}),W.remoteCloudflareQuickTunnel??!0?null:e.jsxs("div",{className:"remote-cf-advanced-fields",children:[e.jsx("label",{htmlFor:"remoteCloudflareTunnelName",children:n("settings.remote.tunnelName","Tunnel name")}),e.jsx("input",{id:"remoteCloudflareTunnelName",type:"text",placeholder:n("settings.remote.tunnelName","Tunnel name"),value:String(W.remoteCloudflareTunnelName??""),onChange:V=>s($=>({...$,remoteCloudflareTunnelName:V.target.value}))}),e.jsx("label",{htmlFor:"remoteCloudflareTunnelToken",children:n("settings.remote.tunnelToken","Tunnel token")}),e.jsx("input",{id:"remoteCloudflareTunnelToken",type:"password",placeholder:n("settings.remote.tunnelToken","Tunnel token"),value:String(W.remoteCloudflareTunnelToken??""),onChange:V=>s($=>({...$,remoteCloudflareTunnelToken:V.target.value}))}),e.jsx("label",{htmlFor:"remoteCloudflareIngressUrl",children:n("settings.remote.ingressURL","Ingress URL")}),e.jsx("input",{id:"remoteCloudflareIngressUrl",type:"text",placeholder:n("settings.remote.httpsYourDomainExample","https://your-domain.example"),value:String(W.remoteCloudflareIngressUrl??""),onChange:V=>s($=>({...$,remoteCloudflareIngressUrl:V.target.value}))})]})]})]})}),e.jsx("div",{className:"form-group remote-tunnel-actions",children:Q==="running"||Q==="starting"?e.jsx("button",{type:"button",className:"btn btn-danger",disabled:v!==null,onClick:()=>void S("stop",async()=>{await Xi(m),i(n("settings.remote.tunnelStopped","Remote tunnel stopped"),"success")}),children:v==="stop"?n("settings.remote.stopping","Stopping…"):n("settings.remote.stopTunnel","Stop Tunnel")}):e.jsxs(e.Fragment,{children:[h?e.jsxs("div",{className:"remote-external-tunnel-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:!X||v!==null,onClick:()=>void S("start fresh",async()=>{X&&(await Qs(ae(X),m),await Zi(m),await Js(m),i(n("settings.remote.tunnelRestarted","Remote tunnel restarted"),"success"))}),children:v==="start fresh"?n("settings.remote.restarting","Restarting…"):n("settings.remote.startFresh","Start Fresh")}),e.jsx("button",{type:"button",className:"btn btn-primary",disabled:!X||v!==null,onClick:()=>void S("use existing",async()=>{X&&(await Qs(ae(X),m),await Js(m),i(n("settings.remote.tunnelStarted","Remote tunnel started"),"success"))}),children:v==="use existing"?n("settings.remote.starting","Starting…"):n("settings.remote.useExisting","Use Existing")})]}):e.jsx("button",{type:"button",className:"btn btn-primary",disabled:!X||v!==null,onClick:()=>void S("start",async()=>{X&&(await Qs(ae(X),m),await Js(m),i(n("settings.remote.tunnelStarted","Remote tunnel started"),"success"))}),children:v==="start"?n("settings.remote.starting","Starting…"):n("settings.remote.startTunnel","Start Tunnel")}),X==="cloudflare"&&r?.cloudflaredAvailable===!1?e.jsx("small",{className:"field-error",children:n("settings.remote.cloudflaredMustBeInstalledToStartTheTunnel","cloudflared must be installed to start the tunnel")}):null]})}),e.jsxs("details",{className:"remote-advanced-details",children:[e.jsx("summary",{children:n("settings.remote.advancedSettings","Advanced Settings")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"remoteShortLivedEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"remoteShortLivedEnabled",type:"checkbox",checked:!!W.remoteShortLivedEnabled,onChange:V=>s($=>({...$,remoteShortLivedEnabled:V.target.checked}))}),n("settings.remote.enableShortLivedTokens"," Enable short-lived tokens ")]}),e.jsx("small",{children:n("settings.remote.shortLivedEnabledHint","Default: disabled.")}),e.jsx("label",{htmlFor:"remoteShortLivedTtlMs",children:n("settings.remote.shortLivedTTLMs","Short-lived TTL (ms)")}),e.jsx("input",{id:"remoteShortLivedTtlMs",type:"number",min:6e4,max:864e5,value:Number(W.remoteShortLivedTtlMs??9e5),onChange:V=>s($=>({...$,remoteShortLivedTtlMs:Number(V.target.value||9e5)}))}),e.jsx("small",{children:n("settings.remote.shortLivedTtlMsHint","Default: 900000 (15 minutes).")}),E&&e.jsxs("small",{children:[n("settings.remote.lastShortLivedTokenExpiresAt","Last short-lived token expires at "),new Date(E.expiresAt).toLocaleString()," (",E.ttlMs,n("settings.remote.ms","ms)")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"remoteRememberLastRunning",className:"checkbox-label",children:[e.jsx("input",{id:"remoteRememberLastRunning",type:"checkbox",checked:!!W.remoteRememberLastRunning,onChange:V=>s($=>({...$,remoteRememberLastRunning:V.target.checked}))}),n("settings.remote.rememberLastRunningState"," Remember last running state ")]}),e.jsx("small",{children:n("settings.remote.automaticallyRestoreTunnelOnStartupIfItWas","Automatically restore tunnel on startup if it was running when last stopped. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:n("settings.remote.authLinks","Auth Links")}),e.jsxs("div",{className:"settings-button-row",children:[e.jsx("button",{type:"button",className:"btn btn-sm",disabled:v!==null,onClick:()=>void S("regenerate persistent token",async()=>{await eo(m),i(n("settings.remote.persistentTokenRegenerated","Persistent token regenerated"),"success")}),children:n("settings.remote.regeneratePersistentToken","Regenerate persistent token")}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:v!==null,onClick:()=>void S("generate short-lived token",async()=>{const V=Number(W.remoteShortLivedTtlMs??9e5),$=await to(V,m);C($),i(n("settings.remote.shortLivedTokenGenerated","Short-lived token generated"),"success")}),children:n("settings.remote.generateShortLivedToken","Generate short-lived token")}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:v!==null,onClick:()=>void S("fetch remote url",async()=>{const V=Number(W.remoteShortLivedTtlMs??9e5),$=await br({projectId:m,tokenType:L,ttlMs:L==="short-lived"?V:void 0});P($),J(null)}),children:n("settings.remote.showURL","Show URL")}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:v!==null,onClick:()=>void S("generate QR",async()=>{const V=Number(W.remoteShortLivedTtlMs??9e5),$=await xa("image/svg",{projectId:m,tokenType:L,ttlMs:L==="short-lived"?V:void 0});P({url:$.url,expiresAt:$.expiresAt,tokenType:$.tokenType}),J($.data??null)}),children:n("settings.remote.generateQR","Generate QR")})]}),e.jsx("label",{htmlFor:"remoteAuthLinkTokenType",children:n("settings.remote.authLinkTokenType","Auth link token type")}),e.jsxs("select",{id:"remoteAuthLinkTokenType",value:L,onChange:V=>y(V.target.value),children:[e.jsx("option",{value:"persistent",children:n("settings.remote.persistentToken","Persistent token")}),e.jsx("option",{value:"short-lived",children:n("settings.remote.shortLivedToken","Short-lived token")})]}),e.jsxs("small",{children:[n("settings.remote.uRLAndQRGenerationUseTheSelectedToken"," URL and QR generation use the selected token type. "),L==="short-lived"?` TTL: ${Number(W.remoteShortLivedTtlMs??9e5)}ms.`:""]}),p?.url&&e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:[n("settings.remote.authenticatedURL","Authenticated URL:"),e.jsx("code",{className:"settings-url-output",children:p.url})]}),e.jsxs("small",{children:[n("settings.remote.tokenType"," Token type: "),e.jsx("strong",{children:p.tokenType}),p.expiresAt?n("settings.remote.expiresAt"," · Expires at {{expiresAt}}",{expiresAt:new Date(p.expiresAt).toLocaleString()}):n("settings.remote.noExpiry"," · No expiry")]})]}),f&&e.jsxs("div",{className:"settings-qr-preview","aria-live":"polite",children:[e.jsx("p",{className:"settings-qr-preview-label",children:n("settings.remote.scanThisQRCodeOnYourPhone","Scan this QR code on your phone")}),e.jsx("div",{className:"settings-qr-preview-image-wrap",children:e.jsx("img",{src:`data:image/svg+xml;utf8,${encodeURIComponent(f)}`,alt:n("settings.remote.remoteAccessQRCode","Remote access QR code"),className:"settings-qr-preview-image"})}),e.jsxs("details",{children:[e.jsx("summary",{children:n("settings.remote.qRSVGMarkup","QR SVG markup")}),e.jsx("pre",{className:"settings-raw-output",children:f})]})]})]})]})]})}const Nd={enabled:!1,servers:[]};let Qn=0;function Sa(){return Qn+=1,`mcp-sensitive-${Qn}`}function Jn(a){return{enabled:a?.enabled===!0,servers:Array.isArray(a?.servers)?a.servers:[]}}function Xn(a){return Object.entries(a??{}).map(([t,s])=>{const c=it(s)?s:{secretRef:"",scope:"project"};return{id:Sa(),key:t,secretRef:c.secretRef,scope:c.scope,createKey:t,createValue:"",required:!1}})}function ts(a){return a?{originalName:a.name,name:a.name,enabled:a.enabled!==!1,transport:a.transport,command:a.transport==="stdio"?a.command:"",argsText:a.transport==="stdio"?(a.args??[]).join(" "):"",url:a.transport==="stdio"?"":a.url,env:a.transport==="stdio"?Xn(a.env):[],headers:a.transport==="stdio"?[]:Xn(a.headers)}:{name:"",enabled:!0,transport:"stdio",command:"",argsText:"",url:"",env:[],headers:[]}}function Sd(a,t){const s=ts(a),c=n=>t.filter(m=>m.field===n||n==="headers"&&m.field==="token").map(m=>({id:Sa(),key:m.key,secretRef:"",scope:m.scope,createKey:m.suggestedKey,createValue:"",required:!0}));return a.transport==="stdio"?{...s,env:c("env")}:{...s,headers:c("headers")}}function Xt(a){const t={};for(const s of a){const c=s.key.trim();!c||!s.secretRef.trim()||(t[c]={secretRef:s.secretRef.trim(),scope:s.scope})}return Object.keys(t).length>0?t:void 0}function Pd(a){const t={name:a.name.trim(),...a.enabled?{}:{enabled:!1}};if(a.transport==="stdio"){const s=a.argsText.split(/\s+/u).map(c=>c.trim()).filter(Boolean);return{...t,transport:"stdio",command:a.command.trim(),...s.length>0?{args:s}:{},...Xt(a.env)?{env:Xt(a.env)}:{}}}return{...t,transport:a.transport,url:a.url.trim(),...Xt(a.headers)?{headers:Xt(a.headers)}:{}}}function jt(a,t){return fetch(a,{...t,headers:{"Content-Type":"application/json",...t?.headers??{}}}).then(async s=>{if(!s.ok){const c=await s.json().catch(()=>({error:"Request failed"}));throw new Error(String(c?.error??"Request failed"))}return s.json()})}function Zn(a){return a.transport==="stdio"?`${a.command}${a.args?.length?` ${a.args.join(" ")}`:""}`:a.url}function Ad(a){return a==="valid"?"status-dot status-dot--online":a==="pending"?"status-dot status-dot--pending":a==="unreachable"||a==="error"?"status-dot status-dot--error":"status-dot"}function Td(a){return a==="disabled-global"?"disabled global":a==="project-local"?"project local":a}function er(a){return a==="idle"?"Not tested":a==="pending"?"Testing…":a}function Sr({scope:a,form:t,setForm:s,globalSettings:c,projectId:n,addToast:m}){const{t:i}=Z("app"),r=o.useRef(null),h=Jn(t.mcpServers??Nd),k=Jn(c?.mcpServers),v=h.servers??[],d=k.servers??[],[u,j]=o.useState(null),[x,b]=o.useState(null),[S,E]=o.useState([]),[C,L]=o.useState(null),[y,p]=o.useState(""),[P,f]=o.useState(null),[J,W]=o.useState(""),[X,Q]=o.useState({}),[ne,ae]=o.useState(null),[V,$]=o.useState(!1),[T,U]=o.useState(null),re=o.useCallback(async()=>{try{const w=await jt("/api/secrets");E(w.secrets),L(null)}catch(w){L(w instanceof Error?w.message:String(w))}},[]);o.useEffect(()=>{re()},[re]);const q=o.useCallback(async()=>{$(!0),U(null);try{const w=new URLSearchParams({scope:a});n&&w.set("projectId",n),ae(await jt(`/api/mcp/discovered?${w.toString()}`))}catch(w){U(w instanceof Error?w.message:String(w)),ae({sources:[],servers:[],errors:[]})}finally{$(!1)}},[n,a]);o.useEffect(()=>{q()},[q]);const F=o.useMemo(()=>a==="project"?Kc({mcpServers:k},{mcpServers:t.mcpServers}):v.filter(w=>w.enabled!==!1),[v,t.mcpServers,k,a]),K=o.useMemo(()=>new Map(d.map(w=>[w.name,w])),[d]),R=o.useMemo(()=>new Map(v.map(w=>[w.name,w])),[v]),pe=o.useMemo(()=>new Set(v.map(w=>w.name)),[v]),ge=o.useMemo(()=>{const w=new Map;for(const D of ne?.servers??[]){const O=w.get(D.source.label)??[];O.push(D),w.set(D.source.label,O)}return[...w.entries()]},[ne?.servers]),fe=o.useMemo(()=>{if(a==="global")return v.map(O=>({server:O,state:O.enabled===!1?"disabled":"configured"}));const w=new Set(F.map(O=>O.name)),D=[];for(const O of d){const ee=R.get(O.name);ee?.enabled===!1?D.push({server:ee,state:"disabled-global"}):ee?D.push({server:ee,state:w.has(ee.name)?"overridden":"disabled"}):D.push({server:O,state:w.has(O.name)?"inherited":"disabled"})}for(const O of v)K.has(O.name)||D.push({server:O,state:O.enabled===!1||!w.has(O.name)?"disabled":"project-local"});return D},[v,F,K,d,R,a]),be=w=>{s(D=>({...D,mcpServers:w}))},Pe=w=>be({...h,enabled:w}),A=()=>{if(!u)return;if(b(null),[...u.env,...u.headers].filter(oe=>oe.required&&(!oe.key.trim()||!oe.secretRef.trim())).length>0){b(i("settings.mcp.discoverySecretsRequired","Bind or create Fusion secret references before saving this discovered server."));return}const D=Na(Pd(u));if(!D.value){b(D.errors.map(oe=>oe.message).join("; "));return}const O=v.filter(oe=>oe.name!==(u.originalName??D.value.name));if(O.some(oe=>oe.name===D.value.name)){b(i("settings.mcp.duplicateName","Duplicate MCP server name"));return}const le=[...O,D.value],ue=$c(le);if(!ue.value){b(ue.errors.map(oe=>oe.message).join("; "));return}be({...h,enabled:!0,servers:ue.value}),j(null)},G=w=>{be({...h,servers:v.filter(D=>D.name!==w)}),Q(D=>{const O={...D};return delete O[w],O})},se=w=>{if(pe.has(w.definition.name))return;if(w.secretDescriptors.length>0||w.hasPlaintextSecrets){j(Sd(w.definition,w.secretDescriptors)),b(i("settings.mcp.discoverySecretsRequired","Bind or create Fusion secret references before saving this discovered server."));return}const D=[...v.filter(O=>O.name!==w.definition.name),w.definition];be({...h,enabled:!0,servers:D}),m(i("settings.mcp.discoveredAdded","Discovered MCP server added"),"success")},ce=w=>{const D=K.get(w),O=D?.transport==="sse"||D?.transport==="streamable-http"?{name:w,enabled:!1,transport:D.transport,url:D.url}:{name:w,enabled:!1,transport:"stdio",command:D?.transport==="stdio"?D.command:"disabled"};be({...h,enabled:!0,servers:[...v.filter(ee=>ee.name!==w),O]})},B=async(w,D)=>{if(!u)return;const O=w.createKey.trim()||w.key.trim();if(!O||!w.createValue){b(i("settings.mcp.secretCreateRequired","Secret key and value are required."));return}try{const ee=await jt("/api/secrets",{method:"POST",body:JSON.stringify({scope:w.scope,key:O,value:w.createValue,description:`MCP ${u.name||"server"} ${D} ${w.key}`,accessPolicy:"prompt",envExportable:!1,envExportKey:null})});j(le=>le&&{...le,[D]:le[D].map(ue=>ue.id===w.id?{...ue,secretRef:ee.id,scope:ee.scope,createKey:ee.key,createValue:""}:ue)}),await re(),m(i("settings.mcp.secretCreated","Secret created"),"success")}catch(ee){b(ee instanceof Error?ee.message:String(ee))}},z=async w=>{Q(D=>({...D,[w.name]:{status:"pending",message:i("settings.mcp.testing","Testing…")}}));try{const D=await jt("/api/mcp/validate",{method:"POST",body:JSON.stringify({server:w})});Q(O=>({...O,[w.name]:{status:D.status,message:D.message??er(D.status)}}))}catch(D){Q(O=>({...O,[w.name]:{status:"error",message:D instanceof Error?D.message:String(D)}}))}},M=async w=>{f(null);const D=Vc(w,{scope:a});if(D.errors.length>0){f(D.errors.join("; "));return}const O=new Set(v.map(le=>le.name)),ee=D.definitions.find(le=>O.has(le.name));if(ee){f(i("settings.mcp.importDuplicate","Duplicate MCP server name: {{name}}",{name:ee.name}));return}try{const le=new Map;for(const oe of D.secretsToCreate){const ve=await jt("/api/secrets",{method:"POST",body:JSON.stringify({scope:oe.scope,key:oe.suggestedKey,value:oe.plaintextValue,description:`MCP import ${oe.serverName} ${oe.field} ${oe.key}`,accessPolicy:"prompt",envExportable:!1,envExportKey:null})});le.set(oe.suggestedKey,{secretRef:ve.id,scope:ve.scope})}const ue=D.definitions.map(oe=>{if(oe.transport==="stdio"){const Ae=Object.fromEntries(Object.entries(oe.env??{}).map(([Ue,Ve])=>[Ue,it(Ve)&&le.has(Ve.secretRef)?le.get(Ve.secretRef):Ve]));return{...oe,...Object.keys(Ae).length>0?{env:Ae}:{}}}const ve=Object.fromEntries(Object.entries(oe.headers??{}).map(([Ae,Ue])=>[Ae,it(Ue)&&le.has(Ue.secretRef)?le.get(Ue.secretRef):Ue]));return{...oe,...Object.keys(ve).length>0?{headers:ve}:{}}});be({...h,enabled:!0,servers:[...v,...ue]}),p(""),await re(),m(i("settings.mcp.imported","MCP servers imported"),"success")}catch(le){f(le instanceof Error?le.message:String(le))}},I=async()=>{const w=JSON.stringify(Yc(v),null,2);W(w);try{await navigator.clipboard?.writeText(w),m(i("settings.mcp.exportCopied","MCP JSON copied"),"success")}catch{m(i("settings.mcp.exportReady","MCP JSON ready to copy"),"info")}},H=(w,D)=>e.jsxs("div",{className:"mcp-sensitive-list","data-testid":`mcp-${w}-rows`,children:[e.jsx("div",{className:"mcp-subheading",children:w==="env"?i("settings.mcp.env","Environment secret refs"):i("settings.mcp.headers","Header secret refs")}),D.length===0?e.jsx("p",{className:"mcp-empty-inline",children:i("settings.mcp.noSensitiveRows","No secret references configured.")}):null,D.map(O=>e.jsxs("div",{className:"mcp-sensitive-row",children:[e.jsx("input",{className:"input","aria-label":i("settings.mcp.sensitiveKey","Sensitive field name"),value:O.key,onChange:ee=>j(le=>le&&{...le,[w]:le[w].map(ue=>ue.id===O.id?{...ue,key:ee.target.value}:ue)}),placeholder:w==="env"?"API_KEY":"Authorization",readOnly:O.required}),O.required?e.jsx("span",{className:"mcp-state-badge mcp-state-badge--required",children:i("settings.mcp.requiredSecret","Required")}):null,e.jsxs("select",{className:"select","aria-label":i("settings.mcp.secretReference","Secret reference"),value:`${O.scope}:${O.secretRef}`,onChange:ee=>{const[le,ue]=ee.target.value.split(":");j(oe=>oe&&{...oe,[w]:oe[w].map(ve=>ve.id===O.id?{...ve,scope:le,secretRef:ue}:ve)})},children:[e.jsx("option",{value:`${O.scope}:`,children:i("settings.mcp.chooseSecret","Choose a secret…")}),S.map(ee=>e.jsxs("option",{value:`${ee.scope}:${ee.id}`,children:[ee.scope,": ",ee.key]},`${ee.scope}:${ee.id}`))]}),e.jsx("input",{className:"input","aria-label":i("settings.mcp.newSecretKey","New secret key"),value:O.createKey,onChange:ee=>j(le=>le&&{...le,[w]:le[w].map(ue=>ue.id===O.id?{...ue,createKey:ee.target.value}:ue)}),placeholder:i("settings.mcp.newSecretKey","New secret key")}),e.jsx("input",{className:"input",type:"password","aria-label":i("settings.mcp.newSecretValue","New secret value (not stored in settings)"),value:O.createValue,onChange:ee=>j(le=>le&&{...le,[w]:le[w].map(ue=>ue.id===O.id?{...ue,createValue:ee.target.value}:ue)}),placeholder:i("settings.mcp.createSecretPlaceholder","Create secret value")}),e.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void B(O,w),children:i("settings.mcp.createSecret","Create secret")}),O.required?null:e.jsx("button",{type:"button",className:"btn btn-icon touch-target","aria-label":i("settings.mcp.removeSensitive","Remove secret reference"),onClick:()=>j(ee=>ee&&{...ee,[w]:ee[w].filter(le=>le.id!==O.id)}),children:e.jsx(ls,{"aria-hidden":"true"})})]},O.id)),e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>j(O=>O&&{...O,[w]:[...O[w],{id:Sa(),key:"",secretRef:"",scope:a,createKey:"",createValue:"",required:!1}]}),children:[e.jsx(as,{"aria-hidden":"true"})," ",i("settings.mcp.addSecretRef","Add secret reference")]}),C?e.jsx("p",{className:"form-error",children:C}):null]});return e.jsxs("section",{className:"card mcp-servers-card","data-testid":`mcp-servers-card-${a}`,children:[e.jsxs("div",{className:"mcp-servers-card__header",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"mcp-servers-card__title",children:a==="global"?i("settings.mcp.globalTitle","Global MCP servers"):i("settings.mcp.projectTitle","Project MCP servers")}),e.jsx("p",{className:"mcp-servers-card__description",children:a==="global"?i("settings.mcp.globalDescription","Configure MCP servers shared by all projects. Project settings may override or disable these servers by name."):i("settings.mcp.projectDescription","Configure project-specific MCP servers, overrides, and disabled inherited servers.")})]}),e.jsxs("button",{type:"button",className:"btn btn-primary touch-target",onClick:()=>{j(ts()),b(null)},children:[e.jsx(as,{"aria-hidden":"true"})," ",i("settings.mcp.addServer","Add server")]})]}),e.jsxs("label",{className:"checkbox-label mcp-enabled-toggle",children:[e.jsx("input",{type:"checkbox",checked:h.enabled===!0,onChange:w=>Pe(w.target.checked)}),i("settings.mcp.enabled","Enable MCP servers for this scope")]}),e.jsx("small",{className:"settings-description",children:i("settings.mcp.enabledHint","Default: disabled, with no servers configured.")}),e.jsxs("div",{className:"mcp-discovery card","data-testid":`mcp-discovery-${a}`,children:[e.jsxs("div",{className:"mcp-discovery__header",children:[e.jsxs("div",{children:[e.jsx("h6",{children:i("settings.mcp.discoveryTitle","Discovered on this machine")}),e.jsx("p",{children:i("settings.mcp.discoveryDescription","Read-only scan of Claude, Cursor, Windsurf, and VS Code MCP config files. Add a server to enable it in Fusion.")})]}),e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void q(),disabled:V,children:[e.jsx(ns,{"aria-hidden":"true"})," ",V?i("settings.mcp.scanning","Scanning…"):i("settings.mcp.scanAgain","Scan again")]})]}),T?e.jsx("p",{className:"form-error",children:T}):null,(ne?.errors?.length??0)>0?e.jsx("div",{className:"mcp-discovery__notes",role:"note",children:ne?.errors?.map(w=>e.jsx("p",{children:w},w))}):null,!V&&ge.length===0?e.jsx("p",{className:"mcp-empty","data-testid":`mcp-discovery-empty-${a}`,children:i("settings.mcp.discoveryEmpty","No MCP servers found in supported tool configs yet.")}):null,ge.map(([w,D])=>e.jsxs("div",{className:"mcp-discovery__group",children:[e.jsx("div",{className:"mcp-subheading",children:w}),D.map(O=>{const ee=O.alreadyConfigured||pe.has(O.definition.name);return e.jsxs("article",{className:"mcp-discovery-row","data-testid":`mcp-discovery-row-${a}-${O.source.id}-${O.definition.name}`,children:[e.jsxs("div",{className:"mcp-server-row__main",children:[e.jsxs("div",{className:"mcp-server-row__titleline",children:[e.jsx("strong",{children:O.definition.name}),e.jsx("span",{className:"mcp-transport-badge",children:O.definition.transport}),ee?e.jsx("span",{className:"mcp-state-badge mcp-state-badge--configured",children:i("settings.mcp.configuredBadge","Configured")}):null]}),e.jsx("p",{children:Zn(O.definition)}),O.secretDescriptors.length>0?e.jsx("p",{className:"mcp-discovery-row__note",children:i("settings.mcp.discoverySecrets","Requires Fusion secret references before saving.")}):null]}),e.jsx("div",{className:"mcp-server-row__actions",children:e.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>se(O),disabled:ee,children:ee?i("settings.mcp.configured","Configured"):i("settings.mcp.addDiscovered","Add")})})]},`${O.source.id}:${O.definition.name}`)})]},w))]}),fe.length===0?e.jsx("p",{className:"mcp-empty","data-testid":`mcp-empty-${a}`,children:i("settings.mcp.empty","No MCP servers configured.")}):e.jsx("div",{className:"mcp-server-list",children:fe.map(({server:w,state:D})=>{const O=X[w.name]??{status:"idle"},ee=a==="global"||D!=="inherited";return e.jsxs("article",{className:"mcp-server-row","data-testid":`mcp-server-row-${w.name}`,children:[e.jsxs("div",{className:"mcp-server-row__main",children:[e.jsxs("div",{className:"mcp-server-row__titleline",children:[e.jsx("strong",{children:w.name}),e.jsx("span",{className:`mcp-state-badge mcp-state-badge--${D}`,"data-state":D,children:Td(D)}),e.jsx("span",{className:"mcp-transport-badge",children:w.transport})]}),e.jsx("p",{children:Zn(w)}),e.jsxs("p",{className:`mcp-validation-status mcp-validation-status--${O.status}`,"data-testid":`mcp-validation-${w.name}`,"aria-live":"polite",children:[e.jsx("span",{className:Ad(O.status),"aria-hidden":"true"})," ",e.jsx("span",{className:"mcp-validation-status__badge",children:O.status==="idle"?i("settings.mcp.notTested","Not tested"):er(O.status)}),O.message?e.jsx("span",{children:O.message}):null]})]}),e.jsxs("div",{className:"mcp-server-row__actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void z(w),disabled:O.status==="pending",children:[e.jsx(so,{"aria-hidden":"true"})," ",O.status==="pending"?i("settings.mcp.testing","Testing…"):i("settings.mcp.test","Test")]}),D==="inherited"?e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>{j(ts(w)),b(null)},children:[e.jsx(rs,{"aria-hidden":"true"})," ",i("settings.mcp.override","Override")]}):null,D==="inherited"?e.jsx("button",{type:"button",className:"btn btn-warning btn-sm touch-target",onClick:()=>ce(w.name),children:i("settings.mcp.disableInherited","Disable")}):null,ee?e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>{j(ts(w)),b(null)},children:[e.jsx(rs,{"aria-hidden":"true"})," ",i("actions.edit","Edit")]}):null,ee?e.jsx("button",{type:"button",className:"btn btn-icon touch-target","aria-label":i("settings.mcp.removeServer","Remove {{name}}",{name:w.name}),onClick:()=>G(w.name),children:e.jsx(ls,{"aria-hidden":"true"})}):null]})]},`${D}:${w.name}`)})}),u?e.jsxs("div",{className:"mcp-editor card","data-testid":"mcp-server-editor",children:[e.jsxs("div",{className:"mcp-editor-grid",children:[e.jsxs("label",{className:"form-group",children:[e.jsx("span",{children:i("settings.mcp.name","Name")}),e.jsx("input",{className:"input",value:u.name,onChange:w=>j({...u,name:w.target.value})})]}),e.jsxs("label",{className:"form-group",children:[e.jsx("span",{children:i("settings.mcp.transport","Transport")}),e.jsxs("select",{className:"select",value:u.transport,onChange:w=>j({...u,transport:w.target.value}),children:[e.jsx("option",{value:"stdio",children:"stdio"}),e.jsx("option",{value:"sse",children:"SSE"}),e.jsx("option",{value:"streamable-http",children:"HTTP"})]})]}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:u.enabled,onChange:w=>j({...u,enabled:w.target.checked})})," ",i("settings.mcp.serverEnabled","Server enabled")]}),u.transport==="stdio"?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"form-group",children:[e.jsx("span",{children:i("settings.mcp.command","Command")}),e.jsx("input",{className:"input",value:u.command,onChange:w=>j({...u,command:w.target.value})})]}),e.jsxs("label",{className:"form-group",children:[e.jsx("span",{children:i("settings.mcp.args","Arguments")}),e.jsx("input",{className:"input",value:u.argsText,onChange:w=>j({...u,argsText:w.target.value})})]})]}):e.jsxs("label",{className:"form-group mcp-editor-grid__wide",children:[e.jsx("span",{children:i("settings.mcp.url","URL")}),e.jsx("input",{className:"input",value:u.url,onChange:w=>j({...u,url:w.target.value})})]})]}),u.transport==="stdio"?H("env",u.env):H("headers",u.headers),x?e.jsx("p",{className:"form-error",children:x}):null,e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>{j(null),b(null)},children:i("actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:A,children:i("actions.save","Save")})]})]}):null,e.jsxs("div",{className:"mcp-import-export",children:[e.jsxs("div",{className:"mcp-import-export__pane",children:[e.jsx("h6",{children:i("settings.mcp.import","Import")}),e.jsx("textarea",{className:"input mcp-json-textarea",value:y,onChange:w=>p(w.target.value),placeholder:i("settings.mcp.importPlaceholder","Paste Claude Desktop mcpServers JSON")}),e.jsx("input",{ref:r,className:"visually-hidden",type:"file",accept:"application/json,.json",onChange:w=>{const D=w.target.files?.[0];D&&(D.text().then(p),w.target.value="")}}),e.jsxs("div",{className:"mcp-inline-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>r.current?.click(),children:[e.jsx(Lc,{"aria-hidden":"true"})," ",i("settings.mcp.uploadJson","Upload JSON")]}),e.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void M(y),children:i("settings.mcp.import","Import")})]}),P?e.jsx("p",{className:"form-error",children:P}):null]}),e.jsxs("div",{className:"mcp-import-export__pane",children:[e.jsx("h6",{children:i("settings.mcp.export","Export")}),e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void I(),children:[e.jsx(ao,{"aria-hidden":"true"})," ",i("settings.mcp.copyExport","Copy Fusion MCP JSON")]}),J?e.jsx("a",{className:"btn btn-sm touch-target",download:"fusion-mcp-servers.json",href:`data:application/json;charset=utf-8,${encodeURIComponent(J)}`,children:i("settings.mcp.downloadExport","Download JSON")}):null,J?e.jsx("textarea",{className:"input mcp-json-textarea",readOnly:!0,value:J,"aria-label":i("settings.mcp.exportedJson","Exported MCP JSON")}):null]})]}),a==="project"?e.jsx("p",{className:"mcp-effective-count",children:i("settings.mcp.effectiveCount","Effective enabled servers: {{count}}",{count:F.length})}):null]})}function Md({scopeBanner:a,form:t,setForm:s,projectId:c,addToast:n}){const{t:m}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:m("settings.nav.globalMcp","MCP Servers")}),e.jsx(Sr,{scope:"global",form:t,setForm:s,projectId:c,addToast:n})]})}function Rd(a,t){return{key:a,...t}}function Id(a){return a.trim().toLowerCase()}function qe(a){const t=Number(a);return Number.isFinite(t)?t:0}function Ed(a){return a?`/command-center/pricing/fetch?projectId=${encodeURIComponent(a)}`:"/command-center/pricing/fetch"}function la(a,t){a(s=>({...s,modelPricingOverrides:t}))}function Fd({form:a,setForm:t,addToast:s,projectId:c}){const{t:n}=Z("app"),[m,i]=o.useState({key:"",inputPer1M:0,outputPer1M:0,cacheReadPer1M:0,cacheWritePer1M:0,source:"manual"}),[r,h]=o.useState(!1),[k,v]=o.useState(!1),d=o.useMemo(()=>Object.entries(a.modelPricingOverrides??{}).sort(([p],[P])=>p.localeCompare(P)),[a.modelPricingOverrides]),u=o.useCallback(()=>v(!1),[]);o.useEffect(()=>{if(!k)return;const p=P=>{P.key==="Escape"&&(P.preventDefault(),u())};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[u,k]);const j=o.useCallback(p=>{p.target===p.currentTarget&&u()},[u]),x=(p,P)=>{const f=a.modelPricingOverrides??{},J=f[p];J&&la(t,{...f,[p]:{...J,...P}})},b=p=>{const P={...a.modelPricingOverrides??{}};delete P[p],la(t,P)},S=()=>{const p=Id(m.key);if(!p||!p.includes(":")){s(n("settings.modelPricing.invalidKey","Use a provider:model key before adding a pricing row."),"error");return}la(t,{...a.modelPricingOverrides??{},[p]:{inputPer1M:m.inputPer1M,outputPer1M:m.outputPer1M,cacheReadPer1M:m.cacheReadPer1M,cacheWritePer1M:m.cacheWritePer1M,source:m.source||"manual"}}),i({key:"",inputPer1M:0,outputPer1M:0,cacheReadPer1M:0,cacheWritePer1M:0,source:"manual"})},E=async()=>{h(!0);try{const p=await wn(Ed(c),{method:"POST"}),P=await wn("/settings/global");t(f=>({...f,modelPricingOverrides:P.modelPricingOverrides??f.modelPricingOverrides,modelPricingFetchedAt:P.modelPricingFetchedAt??p.fetchedAt,modelPricingSource:P.modelPricingSource??p.source})),s(n("settings.modelPricing.fetchSuccess","Fetched {{count}} model prices.",{count:p.count}),"success")}catch(p){s(p instanceof Error?p.message:n("settings.modelPricing.fetchFailed","Failed to fetch latest model prices."),"error")}finally{h(!1)}},C=n("settings.modelPricing.empty","No model pricing overrides yet. Add one manually or fetch the latest LiteLLM prices."),L=n("settings.modelPricing.overrideCount",d.length===1?"{{count}} pricing override":"{{count}} pricing overrides",{count:d.length}),y=()=>k?e.jsx("div",{className:"modal-overlay open",onClick:j,role:"dialog","aria-modal":"true","aria-labelledby":"model-pricing-table-title","data-testid":"model-pricing-table-modal",children:e.jsxs("div",{className:"modal modal-lg model-pricing-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"model-pricing-table-title",children:n("settings.modelPricing.tableTitle","Model pricing table")}),e.jsx("p",{className:"settings-muted model-pricing-modal__subtitle",children:n("settings.modelPricing.saveHint","Manual edits are saved with the rest of Global settings.")})]}),e.jsx("button",{type:"button",className:"modal-close",onClick:u,"aria-label":n("actions.close","Close"),"data-testid":"model-pricing-close",children:e.jsx(no,{size:20})})]}),e.jsx("div",{className:"model-pricing-modal__body",children:e.jsxs("div",{className:"model-pricing-table",role:"table","aria-label":n("settings.modelPricing.overrides","Model pricing overrides"),children:[e.jsxs("div",{className:"model-pricing-row model-pricing-row--head",role:"row",children:[e.jsx("span",{role:"columnheader",children:n("settings.modelPricing.modelKey","provider:model")}),e.jsx("span",{role:"columnheader",children:n("settings.modelPricing.input","Input / 1M")}),e.jsx("span",{role:"columnheader",children:n("settings.modelPricing.output","Output / 1M")}),e.jsx("span",{role:"columnheader",children:n("settings.modelPricing.cacheRead","Cache read / 1M")}),e.jsx("span",{role:"columnheader",children:n("settings.modelPricing.cacheWrite","Cache write / 1M")}),e.jsx("span",{role:"columnheader",children:n("settings.modelPricing.source","Source")}),e.jsx("span",{role:"columnheader",children:n("settings.modelPricing.actions","Actions")})]}),d.length===0?e.jsx("div",{className:"settings-empty-state model-pricing-empty",role:"row",children:C}):d.map(([p,P])=>{const f=Rd(p,P);return e.jsxs("div",{className:"model-pricing-row",role:"row",children:[e.jsx("code",{className:"model-pricing-key",role:"cell",children:f.key}),e.jsx("input",{"aria-label":`${p} input per 1M`,className:"input",type:"number",step:"any",value:f.inputPer1M,onChange:J=>x(p,{inputPer1M:qe(J.target.value)})}),e.jsx("input",{"aria-label":`${p} output per 1M`,className:"input",type:"number",step:"any",value:f.outputPer1M,onChange:J=>x(p,{outputPer1M:qe(J.target.value)})}),e.jsx("input",{"aria-label":`${p} cache read per 1M`,className:"input",type:"number",step:"any",value:f.cacheReadPer1M,onChange:J=>x(p,{cacheReadPer1M:qe(J.target.value)})}),e.jsx("input",{"aria-label":`${p} cache write per 1M`,className:"input",type:"number",step:"any",value:f.cacheWritePer1M,onChange:J=>x(p,{cacheWritePer1M:qe(J.target.value)})}),e.jsx("input",{"aria-label":`${p} source`,className:"input",value:f.source,onChange:J=>x(p,{source:J.target.value})}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>b(p),children:n("settings.modelPricing.delete","Delete")})]},p)}),e.jsxs("div",{className:"model-pricing-row model-pricing-row--add",role:"row",children:[e.jsx("input",{"aria-label":n("settings.modelPricing.newKey","New provider:model key"),className:"input",placeholder:"openai:gpt-4o",value:m.key,onChange:p=>i(P=>({...P,key:p.target.value}))}),e.jsx("input",{"aria-label":n("settings.modelPricing.newInput","New input rate"),className:"input",type:"number",step:"any",value:m.inputPer1M,onChange:p=>i(P=>({...P,inputPer1M:qe(p.target.value)}))}),e.jsx("input",{"aria-label":n("settings.modelPricing.newOutput","New output rate"),className:"input",type:"number",step:"any",value:m.outputPer1M,onChange:p=>i(P=>({...P,outputPer1M:qe(p.target.value)}))}),e.jsx("input",{"aria-label":n("settings.modelPricing.newCacheRead","New cache read rate"),className:"input",type:"number",step:"any",value:m.cacheReadPer1M,onChange:p=>i(P=>({...P,cacheReadPer1M:qe(p.target.value)}))}),e.jsx("input",{"aria-label":n("settings.modelPricing.newCacheWrite","New cache write rate"),className:"input",type:"number",step:"any",value:m.cacheWritePer1M,onChange:p=>i(P=>({...P,cacheWritePer1M:qe(p.target.value)}))}),e.jsx("input",{"aria-label":n("settings.modelPricing.newSource","New source"),className:"input",value:m.source,onChange:p=>i(P=>({...P,source:p.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:S,children:n("settings.modelPricing.addRow","Add row")})]})]})})]})}):null;return e.jsxs("section",{className:"model-pricing-section","aria-label":n("settings.modelPricing.title","Model pricing overrides"),children:[e.jsxs("div",{className:"model-pricing-section__header",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.modelPricing.title","Model Pricing")}),e.jsx("p",{className:"settings-description",children:n("settings.modelPricing.description","Override per-1M token rates used by Command Center cost estimates. Overrides win over the built-in baseline; unlisted models still use the baseline. No default — unset (no overrides).")}),e.jsxs("p",{className:"settings-muted model-pricing-section__meta",children:[a.modelPricingFetchedAt?n("settings.modelPricing.pricesAsOf","Prices as of {{date}}",{date:new Date(a.modelPricingFetchedAt).toLocaleString()}):n("settings.modelPricing.noFetchYet","No fetched pricing snapshot yet."),a.modelPricingSource?` · ${a.modelPricingSource}`:""]})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void E(),disabled:r,children:r?n("settings.modelPricing.fetching","Fetching…"):n("settings.modelPricing.fetchLatest","Fetch latest prices")})]}),e.jsxs("div",{className:"model-pricing-summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:L}),d.length===0?e.jsx("p",{className:"settings-muted model-pricing-summary__empty",children:C}):null]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v(!0),children:n("settings.modelPricing.viewTable","View pricing table")})]}),e.jsx("small",{children:n("settings.modelPricing.saveHint","Manual edits are saved with the rest of Global settings.")}),y()]})}function wt(a){return a?.join(", ")??""}function Ct(a){return a.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Ld({scopeBanner:a,form:t,setForm:s,availableModels:c,modelsLoading:n,globalModelLanes:m,favoriteProviders:i,favoriteModels:r,onToggleFavorite:h,onToggleModelFavorite:k,addToast:v,projectId:d}){const{t:u}=Z("app"),j=t.defaultProvider&&t.defaultModelId?`${t.defaultProvider}/${t.defaultModelId}`:"";return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.globalModels.defaultModel","Default Model")}),n?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Ze,{label:u("settings.models.loadingModels","Loading available models…")})}):c.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:u("settings.models.noModels","No models available. Configure authentication first.")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultModel",children:u("settings.globalModels.defaultModel","Default Model")}),e.jsx(Xe,{id:"defaultModel",label:"Default Model",models:c,value:j,onChange:x=>{if(!x)s(b=>({...b,defaultProvider:void 0,defaultModelId:void 0}));else{const b=x.indexOf("/");s(S=>({...S,defaultProvider:x.slice(0,b),defaultModelId:x.slice(b+1)}))}},placeholder:u("settings.globalModels.useDefault","Use default"),favoriteProviders:i,onToggleFavorite:h,favoriteModels:r,onToggleModelFavorite:k}),e.jsx("small",{children:u("settings.globalModels.defaultAIModelUsedForTaskExecutionWhen","Default AI model used for task execution when no per-task override is set. &quot;Use default&quot; lets the engine choose automatically. No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"fallbackModel",children:u("settings.globalModels.fallbackModel","Fallback Model")}),e.jsx(Xe,{id:"fallbackModel",label:"Fallback Model",models:c,value:t.fallbackProvider&&t.fallbackModelId?`${t.fallbackProvider}/${t.fallbackModelId}`:"",onChange:x=>{if(!x)s(b=>({...b,fallbackProvider:void 0,fallbackModelId:void 0}));else{const b=x.indexOf("/");s(S=>({...S,fallbackProvider:x.slice(0,b),fallbackModelId:x.slice(b+1)}))}},placeholder:u("settings.globalModels.noFallback","No fallback"),favoriteProviders:i,onToggleFavorite:h,favoriteModels:r,onToggleModelFavorite:k}),e.jsx("small",{children:u("settings.globalModels.usedAutomaticallyIfThePrimaryDefaultModelHits","Used automatically if the primary default model hits a retryable provider error like rate limiting or overload. No default — unset.")})]})]}),(()=>{const x=c.find(b=>b.provider===t.defaultProvider&&b.id===t.defaultModelId);return x&&!x.reasoning?null:e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultThinkingLevel",children:u("settings.globalModels.thinkingEffort","Thinking Effort")}),e.jsxs("select",{id:"defaultThinkingLevel",value:t.defaultThinkingLevel||"",onChange:b=>{const S=b.target.value;s(E=>({...E,defaultThinkingLevel:S||void 0}))},children:[e.jsx("option",{value:"",children:u("settings.globalModels.default","Default")}),ro.map(b=>e.jsx("option",{value:b,children:b.charAt(0).toUpperCase()+b.slice(1)},b))]}),e.jsx("small",{children:u("settings.globalModels.controlsHowMuchReasoningEffortTheAIModel","Controls how much reasoning effort the AI model uses. Higher levels produce better results but cost more. No default — unset (model's own default effort applies).")})]})})(),c.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:u("settings.globalModels.modelLanes","Model Lanes")}),e.jsx("p",{className:"settings-description",children:u("settings.globalModels.globalBaselineModelsForEachAIRoleProject"," Global baseline models for each AI role. Project settings can override these per-project. ")}),m.map(x=>{const b=t[x.globalProviderKey],S=t[x.globalModelKey],E=b&&S?`${b}/${S}`:"";return e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`global-${x.laneId}-model`,children:x.label}),e.jsx(Xe,{id:`global-${x.laneId}-model`,label:x.label,models:c,value:E,onChange:C=>{if(!C){s(y=>({...y,[x.globalProviderKey]:void 0,[x.globalModelKey]:void 0}));return}const L=C.indexOf("/");s(y=>({...y,[x.globalProviderKey]:C.slice(0,L),[x.globalModelKey]:C.slice(L+1)}))},placeholder:u("settings.globalModels.useDefault","Use default"),favoriteProviders:i,onToggleFavorite:h,favoriteModels:r,onToggleModelFavorite:k}),e.jsx("small",{children:x.helperText})]},`global-${x.laneId}`)})]}),e.jsx(Fd,{form:t,setForm:s,addToast:v,projectId:d}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:u("settings.globalModels.startupModelSync","Startup Model Sync")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"openrouterModelSync",className:"checkbox-label",children:[e.jsx("input",{id:"openrouterModelSync",type:"checkbox",checked:t.openrouterModelSync!==!1,onChange:x=>s(b=>({...b,openrouterModelSync:x.target.checked}))}),u("settings.globalModels.syncOpenRouterModelListAtStartup"," Sync OpenRouter model list at startup ")]}),e.jsx("small",{children:u("settings.globalModels.whenEnabledStartupFetchesTheLatestAvailableModels"," When enabled, startup fetches the latest available models from the OpenRouter API so model pickers always include the newest catalog. Default: enabled. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"opencodeGoModelSync",className:"checkbox-label",children:[e.jsx("input",{id:"opencodeGoModelSync",type:"checkbox",checked:t.opencodeGoModelSync!==!1,onChange:x=>s(b=>({...b,opencodeGoModelSync:x.target.checked}))}),u("settings.globalModels.syncOpencodeGoModelListAtStartup"," Sync opencode-go model list at startup ")]}),e.jsxs("small",{children:[u("settings.globalModels.whenEnabledStartupRefreshesModelsThroughTheLocal"," When enabled, startup refreshes models through the local "),e.jsx("code",{children:"opencode models opencode --refresh"}),u("settings.globalModels.flowAndPublishesThemUnderTheOpencodeGo"," flow and publishes them under the opencode-go provider in model pickers. Default: enabled. ")]})]}),e.jsxs("details",{children:[e.jsx("summary",{children:u("settings.globalModels.openRouterAdvanced","OpenRouter advanced")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterAppAttributionReferer",children:u("settings.globalModels.openRouterHTTPReferer","OpenRouter HTTP-Referer")}),e.jsx("input",{id:"openrouterAppAttributionReferer",className:"input",placeholder:u("settings.globalModels.httpsRunfusionAi","https://runfusion.ai"),value:t.openrouterAppAttribution?.referer??"",onChange:x=>s(b=>({...b,openrouterAppAttribution:{...b.openrouterAppAttribution||{},referer:x.target.value}}))}),e.jsx("small",{children:u("settings.globalModels.leaveEmptyToOmitThisHeaderDefaultHttps","Leave empty to omit this header. No default — unset (Fusion falls back to https://runfusion.ai when unset).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterAppAttributionTitle",children:u("settings.globalModels.openRouterXTitle","OpenRouter X-Title")}),e.jsx("input",{id:"openrouterAppAttributionTitle",className:"input",placeholder:u("settings.globalModels.fusion","Fusion"),value:t.openrouterAppAttribution?.title??"",onChange:x=>s(b=>({...b,openrouterAppAttribution:{...b.openrouterAppAttribution||{},title:x.target.value}}))}),e.jsx("small",{children:u("settings.globalModels.leaveEmptyToOmitThisHeaderDefaultFusion",'Leave empty to omit this header. No default — unset (Fusion falls back to the title "Fusion" when unset).')})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterModelFiltersSupportedParameters",children:u("settings.globalModels.openRouterSupportedParametersFilter","OpenRouter supported_parameters filter")}),e.jsx("input",{id:"openrouterModelFiltersSupportedParameters",className:"input",placeholder:u("settings.globalModels.toolsStructuredOutputs","tools, structured_outputs"),value:wt(t.openrouterModelFilters?.supported_parameters),onChange:x=>{const b=Ct(x.target.value);s(S=>({...S,openrouterModelFilters:{...S.openrouterModelFilters||{},supported_parameters:b.length>0?b:void 0}}))}}),e.jsx("small",{children:u("settings.globalModels.commaSeparatedValuesSentToOpenRouterModelSync","Comma-separated values sent to OpenRouter model sync. No default — unset (unfiltered).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterModelFiltersOutputModalities",children:u("settings.globalModels.openRouterOutputModalitiesFilter","OpenRouter output_modalities filter")}),e.jsx("input",{id:"openrouterModelFiltersOutputModalities",className:"input",placeholder:u("settings.globalModels.text","text"),value:wt(t.openrouterModelFilters?.output_modalities),onChange:x=>{const b=Ct(x.target.value);s(S=>({...S,openrouterModelFilters:{...S.openrouterModelFilters||{},output_modalities:b.length>0?b:void 0}}))}}),e.jsx("small",{children:u("settings.globalModels.commaSeparatedValuesSentToOpenRouterModelSyncOutputModalities","Comma-separated values sent to OpenRouter model sync. No default — unset (unfiltered).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterProviderPreferencesOrder",children:u("settings.globalModels.openRouterRoutingOrder","OpenRouter routing order")}),e.jsx("input",{id:"openrouterProviderPreferencesOrder",className:"input",placeholder:u("settings.globalModels.openaiAnthropic","openai, anthropic"),value:wt(t.openrouterProviderPreferences?.order),onChange:x=>{const b=Ct(x.target.value);s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},order:b.length>0?b:void 0}}))}}),e.jsx("small",{children:u("settings.globalModels.openRouterRoutingOrderHint","No default — unset (OpenRouter's own default routing order applies).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterProviderPreferencesIgnore",children:u("settings.globalModels.openRouterRoutingIgnore","OpenRouter routing ignore")}),e.jsx("input",{id:"openrouterProviderPreferencesIgnore",className:"input",placeholder:u("settings.globalModels.providerName","provider-name"),value:wt(t.openrouterProviderPreferences?.ignore),onChange:x=>{const b=Ct(x.target.value);s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},ignore:b.length>0?b:void 0}}))}}),e.jsx("small",{children:u("settings.globalModels.openRouterRoutingIgnoreHint","No default — unset (no providers ignored).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterProviderPreferencesOnly",children:u("settings.globalModels.openRouterRoutingOnly","OpenRouter routing only")}),e.jsx("input",{id:"openrouterProviderPreferencesOnly",className:"input",placeholder:u("settings.globalModels.providerName","provider-name"),value:wt(t.openrouterProviderPreferences?.only),onChange:x=>{const b=Ct(x.target.value);s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},only:b.length>0?b:void 0}}))}}),e.jsx("small",{children:u("settings.globalModels.openRouterRoutingOnlyHint","No default — unset (no provider restriction).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterProviderPreferencesAllowFallbacks",children:u("settings.globalModels.openRouterAllowFallbacks","OpenRouter allow fallbacks")}),e.jsxs("select",{id:"openrouterProviderPreferencesAllowFallbacks",className:"select",value:t.openrouterProviderPreferences?.allow_fallbacks===void 0?"default":t.openrouterProviderPreferences.allow_fallbacks?"allow":"deny",onChange:x=>{const b=x.target.value;s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},allow_fallbacks:b==="default"?void 0:b==="allow"}}))},children:[e.jsx("option",{value:"default",children:u("settings.globalModels.default2","default")}),e.jsx("option",{value:"allow",children:u("settings.globalModels.allow","allow")}),e.jsx("option",{value:"deny",children:u("settings.globalModels.deny","deny")})]}),e.jsx("small",{children:u("settings.globalModels.openRouterAllowFallbacksHint","No default — unset (OpenRouter's own default fallback behavior applies).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openrouterProviderPreferencesSort",children:u("settings.globalModels.openRouterRoutingSort","OpenRouter routing sort")}),e.jsxs("select",{id:"openrouterProviderPreferencesSort",className:"select",value:t.openrouterProviderPreferences?.sort??"default",onChange:x=>{const b=x.target.value;s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},sort:b==="default"?void 0:b}}))},children:[e.jsx("option",{value:"default",children:u("settings.globalModels.default2","default")}),e.jsx("option",{value:"price",children:u("settings.globalModels.price","price")}),e.jsx("option",{value:"throughput",children:u("settings.globalModels.throughput","throughput")}),e.jsx("option",{value:"latency",children:u("settings.globalModels.latency","latency")})]}),e.jsx("small",{children:u("settings.globalModels.openRouterRoutingSortHint","No default — unset (OpenRouter's own default sort applies).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"openrouterProviderPreferencesRequireParameters",className:"checkbox-label",children:[e.jsx("input",{id:"openrouterProviderPreferencesRequireParameters",type:"checkbox",checked:t.openrouterProviderPreferences?.require_parameters===!0,onChange:x=>s(b=>({...b,openrouterProviderPreferences:{...b.openrouterProviderPreferences||{},require_parameters:x.target.checked}}))}),u("settings.globalModels.requireParameters"," Require parameters ")]}),e.jsx("small",{children:u("settings.globalModels.requireParametersHint","Default: disabled.")})]})]})]})}const Dd=["openai-compatible","openai-responses","anthropic-compatible","google-generative-ai"];function Od(a){return(Array.isArray(a)?a:a.providers??[]).map(s=>"apiType"in s?s:{id:s.id,name:s.name?.trim()||s.id,apiType:s.api==="anthropic-messages"?"anthropic-compatible":s.api==="openai-responses"?"openai-responses":s.api==="google-generative-ai"?"google-generative-ai":"openai-compatible",baseUrl:s.baseUrl,...s.apiKey?{apiKey:s.apiKey}:{},models:(s.models??[]).map(c=>({id:c.id,name:c.name??c.id}))})}function Bd(a){return a.split(",").map(t=>t.trim()).filter(Boolean).map(t=>({id:t,name:t}))}function Gd({embedded:a=!1,onProviderChange:t}){const{t:s}=Z("app"),[c,n]=o.useState([]),[m,i]=o.useState(!1),[r,h]=o.useState(!1),[k,v]=o.useState(null),[d,u]=o.useState(null),[j,x]=o.useState(!1),[b,S]=o.useState(""),[E,C]=o.useState("openai-compatible"),[L,y]=o.useState(""),[p,P]=o.useState(""),[f,J]=o.useState(""),[W,X]=o.useState(!1),[Q,ne]=o.useState(null),[ae,V]=o.useState(!1),[$,T]=o.useState(null),[U,re]=o.useState(null),[q,F]=o.useState(null),K=o.useCallback(async()=>{i(!0),v(null);try{const B=await lo();n(Od(B)),h(!0)}catch(B){v(B instanceof Error?B.message:s("providers.failedLoad","Failed to load custom providers."))}finally{i(!1)}},[s]),R=o.useCallback(B=>{B&&!r&&!m&&K()},[r,m,K]);o.useEffect(()=>{a&&!r&&!m&&K()},[a,r,m,K]);const pe=o.useCallback(()=>{u(null),S(""),C("openai-compatible"),y(""),P(""),J(""),ne(null),T(null),V(!1),x(!1)},[]),ge=o.useCallback(()=>{u(null),S(""),C("openai-compatible"),y(""),P(""),J(""),ne(null),T(null),V(!1),x(!0)},[]),fe=o.useCallback(B=>{u(B),S(B.name),C(B.apiType),y(B.baseUrl),P(""),J((B.models??[]).map(z=>z.id).join(", ")),ne(null),T(null),V(!1),x(!0)},[]),be=o.useCallback(()=>{if(!b.trim())return s("providers.nameRequired","Provider name is required.");if(!L.trim())return s("providers.urlRequired","Base URL is required.");let B=!1;try{const z=new URL(L.trim());B=z.protocol==="http:"||z.protocol==="https:"}catch{B=!1}return B?Dd.includes(E)?null:s("providers.apiTypeInvalid","API type is invalid."):s("providers.urlInvalid","Base URL must be a valid http/https URL.")},[E,L,b,s]),Pe=o.useCallback(async()=>{const B=L.trim();if(!B){T(s("providers.urlRequiredForDetect","Base URL is required to detect models."));return}V(!0),T(null);try{const z=await io({baseUrl:B,apiKey:p.trim()||void 0,apiType:E});z.models.length>0?J(M=>{const I=new Set(M.split(",").map(D=>D.trim()).filter(Boolean)),H=z.models.map(D=>D.id.trim()).filter(D=>!I.has(D));if(H.length===0)return M;const w=M.trim();return H.join(", ")+(w?", "+w:"")}):T(s("providers.noModelsFound","No models found. The provider may require an API key."))}catch(z){T(z instanceof Error?z.message:s("providers.failedDetect","Failed to detect models"))}finally{V(!1)}},[L,p,E,s]),A=o.useCallback(async()=>{const B=be();if(ne(B),B)return;const z=Bd(f),M={name:b.trim(),apiType:E,baseUrl:L.trim(),...p.trim()?{apiKey:p.trim()}:{},...z.length>0?{models:z}:{}};X(!0),v(null);try{d?await oo(d.id,M):await co(M),await K(),t?.(),pe()}catch(I){ne(I instanceof Error?I.message:s("providers.failedSave","Failed to save provider."))}finally{X(!1)}},[p,E,L,d,K,f,b,pe,be,s]),G=o.useCallback(async B=>{if(window.confirm(s("providers.deleteConfirm",'Delete custom provider "{{name}}"?',{name:B.name}))){v(null);try{await uo(B.id),await K(),t?.()}catch(z){v(z instanceof Error?z.message:s("providers.failedDelete","Failed to delete provider."))}}},[K,t,s]),se=o.useCallback(async B=>{re(B.id),F(null),v(null);try{const z=await mo(B.id);if(n(M=>M.map(I=>I.id===B.id?z.provider:I)),d?.id===B.id){const M=(z.provider.models??[]).map(I=>I.id).join(", ");J(M),u(I=>I?.id===B.id?{...I,models:z.provider.models??[]}:I)}t?.(),F({providerId:B.id,type:"success",message:s("providers.refreshModelsSuccess","Refreshed {{count}} model(s).",{count:z.modelsRefreshed})})}catch(z){F({providerId:B.id,type:"error",message:z instanceof Error?z.message:s("providers.refreshModelsFailed","Failed to refresh models.")})}finally{re(null)}},[d?.id,t,s]),ce=e.jsxs(e.Fragment,{children:[a?null:m?e.jsxs("div",{className:"custom-provider-empty",role:"status",children:[e.jsx(ze,{"aria-hidden":"true",className:"custom-provider-spin"})," ",s("providers.loading","Loading custom providers…")]}):null,a?null:!m&&k?e.jsxs("div",{className:"custom-provider-form-error",role:"alert",children:[e.jsx(Cn,{"aria-hidden":"true"}),e.jsx("span",{children:k})]}):null,!m&&c.length>0?e.jsx("div",{className:"custom-provider-list",children:c.map(B=>{const z=j&&d?.id===B.id,M=U===B.id,I=q?.providerId===B.id?q:null;return e.jsxs("div",{children:[e.jsxs("div",{className:"auth-provider-card custom-provider-item",children:[e.jsxs("div",{className:"custom-provider-item-info",children:[e.jsx("div",{className:"custom-provider-item-name",children:B.name}),e.jsxs("div",{className:"custom-provider-item-meta",children:[e.jsx("span",{className:"custom-provider-badge",children:B.apiType})," ",B.baseUrl]})]}),e.jsxs("div",{className:"custom-provider-item-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm custom-provider-refresh-btn",onClick:()=>void se(B),disabled:M,"aria-label":s("providers.refreshModelsLabel","Refresh models for {{name}}",{name:B.name}),children:[M?e.jsx(ze,{"aria-hidden":"true",className:"custom-provider-spin"}):e.jsx(ns,{"aria-hidden":"true"}),e.jsx("span",{children:M?s("providers.refreshingModels","Refreshing…"):s("providers.refreshModels","Refresh Models")})]}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>fe(B),"aria-label":s("providers.editLabel","Edit {{name}}",{name:B.name}),children:e.jsx(rs,{"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>void G(B),"aria-label":s("providers.deleteLabel","Delete {{name}}",{name:B.name}),children:e.jsx(ls,{"aria-hidden":"true"})})]})]}),I?e.jsxs("div",{className:`custom-provider-row-message custom-provider-row-message--${I.type}`,role:I.type==="error"?"alert":"status",children:[I.type==="error"?e.jsx(Cn,{"aria-hidden":"true"}):null,e.jsx("span",{children:I.message})]}):null,z?e.jsxs("div",{className:"custom-provider-form custom-provider-item-edit-form",children:[e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-name",children:s("providers.nameLabel","Provider name")}),e.jsx("input",{id:"custom-provider-name",className:"input",value:b,onChange:H=>S(H.target.value),disabled:W})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-type",children:s("providers.apiTypeLabel","API type")}),e.jsxs("select",{id:"custom-provider-api-type",className:"select",value:E,onChange:H=>C(H.target.value),disabled:W,children:[e.jsx("option",{value:"openai-compatible",children:s("providers.apiTypeOpenAi","OpenAI-compatible")}),e.jsx("option",{value:"openai-responses",children:s("providers.apiTypeOpenAiResp","OpenAI Responses")}),e.jsx("option",{value:"anthropic-compatible",children:s("providers.apiTypeAnthropic","Anthropic-compatible")}),e.jsx("option",{value:"google-generative-ai",children:s("providers.apiTypeGoogle","Google Generative AI")})]})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-base-url",children:s("providers.baseUrlLabel","Base URL")}),e.jsx("input",{id:"custom-provider-base-url",className:"input",placeholder:"https://api.example.com/v1",value:L,onChange:H=>y(H.target.value),disabled:W})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-key",children:s("providers.apiKeyLabel","API key")}),e.jsx("input",{id:"custom-provider-api-key",type:"password",className:"input",placeholder:d?.apiKey?s("providers.apiKeyKeepPlaceholder","Leave blank to keep current key"):void 0,value:p,onChange:H=>P(H.target.value),disabled:W})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-models",children:s("providers.modelsLabel","Available models")}),e.jsx("input",{id:"custom-provider-models",className:"input",placeholder:"e.g., gpt-4, gpt-3.5-turbo",value:f,onChange:H=>J(H.target.value),disabled:W})]}),e.jsx("div",{className:"custom-provider-detect-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Pe(),disabled:W||ae||!L.trim(),title:s("providers.detectTitle","Auto-detect models from the provider's /models endpoint"),children:ae?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"custom-provider-spin",size:14})," ",s("providers.detecting","Detecting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{size:14})," ",s("providers.detectModels","Detect Models")]})})}),$?e.jsx("div",{className:"custom-provider-form-error",children:$}):null,Q?e.jsx("div",{className:"custom-provider-form-error",children:Q}):null,e.jsxs("div",{className:"custom-provider-form-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:pe,disabled:W,children:s("actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void A(),disabled:W,children:W?s("providers.saving","Saving…"):s("providers.saveChanges","Save Changes")})]})]}):null]},B.id)})}):null,!m&&c.length===0&&!k?e.jsx("div",{className:"custom-provider-empty",children:s("providers.noneConfigured","No custom providers configured.")}):null,e.jsxs("button",{type:"button",className:"btn btn-sm custom-provider-add-btn",onClick:ge,children:[e.jsx(as,{"aria-hidden":"true"})," ",s("providers.addCustom","Add Custom Provider")]}),j&&!d?e.jsxs("div",{className:"custom-provider-form",children:[e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-name",children:s("providers.nameLabel","Provider name")}),e.jsx("input",{id:"custom-provider-name",className:"input",value:b,onChange:B=>S(B.target.value),disabled:W})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-type",children:s("providers.apiTypeLabel","API type")}),e.jsxs("select",{id:"custom-provider-api-type",className:"select",value:E,onChange:B=>C(B.target.value),disabled:W,children:[e.jsx("option",{value:"openai-compatible",children:s("providers.apiTypeOpenAi","OpenAI-compatible")}),e.jsx("option",{value:"openai-responses",children:s("providers.apiTypeOpenAiResp","OpenAI Responses")}),e.jsx("option",{value:"anthropic-compatible",children:s("providers.apiTypeAnthropic","Anthropic-compatible")}),e.jsx("option",{value:"google-generative-ai",children:s("providers.apiTypeGoogle","Google Generative AI")})]})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-base-url",children:s("providers.baseUrlLabel","Base URL")}),e.jsx("input",{id:"custom-provider-base-url",className:"input",placeholder:"https://api.example.com/v1",value:L,onChange:B=>y(B.target.value),disabled:W})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-key",children:s("providers.apiKeyLabel","API key")}),e.jsx("input",{id:"custom-provider-api-key",type:"password",className:"input",value:p,onChange:B=>P(B.target.value),disabled:W})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-models",children:s("providers.modelsLabel","Available models")}),e.jsx("input",{id:"custom-provider-models",className:"input",placeholder:"e.g., gpt-4, gpt-3.5-turbo",value:f,onChange:B=>J(B.target.value),disabled:W})]}),e.jsx("div",{className:"custom-provider-detect-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Pe(),disabled:W||ae||!L.trim(),title:s("providers.detectTitle","Auto-detect models from the provider's /models endpoint"),children:ae?e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"custom-provider-spin",size:14})," ",s("providers.detecting","Detecting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{size:14})," ",s("providers.detectModels","Detect Models")]})})}),$?e.jsx("div",{className:"custom-provider-form-error",children:$}):null,Q?e.jsx("div",{className:"custom-provider-form-error",children:Q}):null,e.jsxs("div",{className:"custom-provider-form-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:pe,disabled:W,children:s("actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void A(),disabled:W,children:W?s("providers.saving","Saving…"):s("providers.saveProvider","Save Provider")})]})]}):null]});return e.jsx("div",{className:"custom-providers-section",children:a?ce:e.jsx(ho,{summary:"Advanced: Custom Providers",onToggle:R,children:ce})})}const _d={"claude-cli":0,"anthropic-subscription":1,"anthropic-api-key":2,anthropic:3},tr=a=>_d[a.id]??Number.POSITIVE_INFINITY,Ud=(a,t)=>{if(a.authenticated!==t.authenticated)return a.authenticated?-1:1;const s=tr(a),c=tr(t);if(s!==c)return s-c;const n=a.name.localeCompare(t.name);return n!==0?n:a.id.localeCompare(t.id)};function Hd({auth:a}){const{t}=Z("app"),{projectId:s,addToast:c,authProviders:n,authLoading:m,authActionInProgress:i,apiKeyInputs:r,setApiKeyInputs:h,apiKeyErrors:k,opencodeApiKeyRefreshStatus:v,deviceCodes:d,loginInstructions:u,manualCodeConfigs:j,manualCodeInputs:x,setManualCodeInputs:b,manualCodeSubmitInProgress:S,loadAuthStatus:E,handleLogin:C,handleLogout:L,handleCancelLogin:y,handleSaveApiKey:p,handleClearApiKey:P,handleSubmitManualCode:f,onReopenOnboarding:J}=a,X=n.some(R=>R.id==="anthropic-subscription"||R.id==="anthropic-api-key")?n.filter(R=>R.id!=="anthropic"):n,Q=R=>R.id==="claude-cli"||R.id==="cursor-cli"||R.id==="llama-cpp",ne=[...X].filter(R=>R.type!=="cli"||Q(R)).sort(Ud),ae=ne.filter(R=>R.authenticated),V=ne.filter(R=>!R.authenticated),$=R=>R.id==="claude-cli"?e.jsx(po,{compact:!0,authenticated:R.authenticated,onToggled:()=>{E()}},R.id):R.id==="cursor-cli"?e.jsx(go,{compact:!0,authenticated:R.authenticated,onToggled:()=>{E()}},R.id):e.jsx(bo,{compact:!0,authenticated:R.authenticated,onToggled:()=>{E()}},R.id),T=ae.length>0,U=V.length>0,re=R=>R.type==="api_key",q=R=>e.jsxs("div",{className:"auth-apikey-section",children:[e.jsxs("div",{className:"auth-apikey-input-row",children:[e.jsx("input",{type:"password",className:"auth-apikey-input",placeholder:t("settings.authentication.enterAPIKey","Enter API key"),value:r[R.id]??"",onChange:pe=>h(ge=>({...ge,[R.id]:pe.target.value})),disabled:i===R.id}),R.keyHint&&!r[R.id]?e.jsx("button",{className:"btn btn-sm",onClick:()=>P(R.id),disabled:i===R.id,children:t("settings.auth.clearKey","Clear")}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>p(R.id),disabled:i===R.id,children:t("settings.actions.save","Save")})]}),i===R.id&&e.jsx("small",{className:"auth-apikey-progress",children:t("settings.auth.savingKey","Saving…")}),k[R.id]&&e.jsx("small",{className:"auth-apikey-error",children:k[R.id]}),(R.id==="opencode"||R.id==="opencode-go")&&v[R.id]&&e.jsx("small",{className:v[R.id].tone==="error"?"form-error":"text-muted",children:v[R.id].message})]}),F=R=>e.jsx("div",{children:i===R.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:t("settings.auth.loggingOut","Logging out…")}):R.loginInProgress?e.jsxs("div",{className:"auth-provider-actions-row",children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:t("settings.auth.waitingForLogin","Waiting for login…")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>y(R.id),children:t("settings.actions.cancel","Cancel")})]}):e.jsx("button",{className:"btn btn-sm",onClick:()=>L(R.id),children:t("settings.auth.logout","Logout")})}),K=R=>e.jsxs("div",{children:[i===R.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:t("settings.auth.waitingForLogin","Waiting for login…")}):R.loginInProgress?e.jsxs("div",{className:"auth-provider-actions-row",children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:t("settings.auth.waitingForLogin","Waiting for login…")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>y(R.id),children:t("settings.actions.cancel","Cancel")})]}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>C(R.id),children:t("settings.auth.login","Login")}),R.id==="github-copilot"&&d[R.id]&&(R.loginInProgress||i===R.id)&&e.jsxs("div",{className:"auth-device-code-panel","data-testid":`auth-device-code-${R.id}`,children:[e.jsx("strong",{children:t("settings.auth.enterCodeOnGitHub","Enter this code on GitHub")}),e.jsx("div",{className:"auth-device-code-pill",children:d[R.id].userCode}),e.jsxs("div",{className:"auth-provider-actions-row",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{(async()=>{if(await fr(d[R.id].userCode)){c(t("settings.auth.copiedCodeToClipboard","Copied code to clipboard"),"success");return}c(t("settings.auth.failedToCopyCode","Failed to copy code — copy it manually from the box above"),"error")})()},children:t("settings.auth.copyCode","Copy code")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>window.open(vr(d[R.id].verificationUri),"_blank"),children:t("settings.auth.openGitHub","Open GitHub")})]})]}),u[R.id]&&(R.loginInProgress||i===R.id)&&e.jsx(fo,{instructions:u[R.id],"data-testid":`auth-login-instructions-${R.id}`}),j[R.id]&&(R.loginInProgress||i===R.id)&&e.jsx(vo,{value:x[R.id]??"",onChange:pe=>b(ge=>({...ge,[R.id]:pe})),onSubmit:()=>void f(R.id),prompt:j[R.id].prompt,placeholder:j[R.id].placeholder,helpText:j[R.id].helpText,disabled:S===R.id,submitLabel:S===R.id?"Submitting…":"Submit code","data-testid":`auth-manual-code-${R.id}`})]});return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:t("settings.auth.title","Authentication")}),m?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Ze,{label:t("settings.auth.loadingStatus","Loading authentication status…")})}):n.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:t("settings.auth.noProviders","No providers available")}):e.jsxs("div",{className:"auth-panel-body",children:[e.jsx(ya,{slotId:"settings-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{E()}}}),e.jsx(ya,{slotId:"settings-integration-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{E()}}}),!T&&e.jsx("div",{className:"auth-section-hint",children:t("settings.auth.signInHint","Sign in to at least one provider to get started with AI models.")}),T&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:t("settings.auth.groupAuthenticated","Authenticated")}),ae.map(R=>R.type==="cli"?$(R):e.jsx("div",{className:"auth-provider-card auth-provider-card--authenticated",children:e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx("span",{className:"auth-provider-icon-slot","data-testid":`auth-provider-icon-${R.id}`,"aria-hidden":"true",children:e.jsx(Tt,{provider:R.id,size:"md"})}),e.jsx("strong",{children:R.name}),e.jsx("span",{"data-testid":`auth-status-${R.id}`,className:`auth-status-badge ${R.authenticated?"authenticated":"not-authenticated"}`,children:t("settings.auth.statusActive","✓ Active")}),R.authenticated&&R.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:[t("settings.authentication.key","Key: "),R.keyHint]})]}),R.type!=="api_key"&&F(R),re(R)&&q(R)]})},R.id))]}),U&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:t("settings.auth.groupAvailable","Available")}),V.map(R=>R.type==="cli"?$(R):e.jsx("div",{className:"auth-provider-card",children:e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx("span",{className:"auth-provider-icon-slot","data-testid":`auth-provider-icon-${R.id}`,"aria-hidden":"true",children:e.jsx(Tt,{provider:R.id,size:"md"})}),e.jsx("strong",{children:R.name}),e.jsx("span",{"data-testid":`auth-status-${R.id}`,className:`auth-status-badge ${R.authenticated?"authenticated":"not-authenticated"}`,children:t("settings.auth.statusNotConnected","✗ Not connected")}),R.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:[t("settings.authentication.key","Key: "),R.keyHint]})]}),R.type!=="api_key"&&K(R),re(R)&&q(R)]})},R.id))]})]}),e.jsx("small",{className:"auth-hint",children:t("settings.auth.hint","Authentication changes take effect immediately — no need to save.")}),J&&e.jsxs("div",{className:"form-group",style:{marginTop:"var(--space-md)"},children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:J,children:t("settings.auth.reopenOnboarding","Reopen onboarding guide")}),e.jsx("small",{className:"settings-muted",children:t("settings.auth.reopenOnboardingHint","Re-run the setup wizard to review or update your AI provider and model configuration.")})]}),e.jsx(Gd,{})]})}function Pa(a){const{t}=Z("app"),{name:s,subname:c,logo:n,learnMoreHref:m,statusKind:i,statusText:r,description:h,tabs:k,children:v,busy:d,canTest:u=!0,toast:j,onTest:x,onSave:b,onSaveAndTest:S,belowForm:E,testId:C}=a,L=i==="ok"?"runtime-card__status runtime-card__status--ok":i==="err"?"runtime-card__status runtime-card__status--err":"runtime-card__status runtime-card__status--neutral";return e.jsxs("div",{className:"runtime-card","data-testid":C,"aria-live":"polite",children:[e.jsxs("header",{className:"runtime-card__header",children:[e.jsx("span",{className:"runtime-card__logo",children:n}),e.jsxs("div",{className:"runtime-card__title",children:[e.jsx("h3",{className:"runtime-card__name",children:s}),c&&e.jsx("small",{className:"runtime-card__cobrand",children:c}),e.jsxs("small",{className:L,children:[i==="loading"&&e.jsx(ze,{size:12,className:"animate-spin"}),r]})]}),e.jsx("a",{className:"runtime-card__learn-more btn btn-sm btn-ghost",href:m,target:"_blank",rel:"noreferrer",children:t("common.learnMore","Learn more →")})]}),e.jsx("p",{className:"runtime-card__description",children:h}),k,e.jsx("div",{className:"runtime-card__form",children:v}),E,e.jsxs("footer",{className:"runtime-card__footer",children:[j&&e.jsx("span",{className:j.kind==="ok"?"runtime-card__toast runtime-card__toast--ok":"runtime-card__toast runtime-card__toast--err",role:"status",children:j.message}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:x,disabled:d!==null||!u,children:d==="testing"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{size:12,className:"animate-spin"})," ",t("common.testing","Testing…")]}):t("common.test","Test")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:b,disabled:d!==null,children:d==="saving"?t("common.saving","Saving…"):t("common.save","Save")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:S,disabled:d!==null||!u,children:d==="save-test"?e.jsxs(e.Fragment,{children:[e.jsx(ze,{size:12,className:"animate-spin"})," ",t("common.saving","Saving…")]}):t("common.saveAndTest","Save & Test")})]})]})}const ia="fusion-plugin-hermes-runtime",sr="https://github.com/NousResearch/hermes-agent",Wd=["auto","anthropic","openrouter","gemini","openai-codex","copilot","copilot-acp","huggingface","zai","kimi-coding","minimax","minimax-cn","kilocode","xiaomi","nous"],Fe={binaryPath:"",model:"",provider:"auto",maxTurns:12,yolo:!1,cliTimeoutMs:3e5,profile:""};function $d(a){return{binaryPath:typeof a.binaryPath=="string"?a.binaryPath:Fe.binaryPath,model:typeof a.model=="string"?a.model:Fe.model,provider:typeof a.provider=="string"?a.provider:Fe.provider,maxTurns:typeof a.maxTurns=="number"?a.maxTurns:Fe.maxTurns,yolo:typeof a.yolo=="boolean"?a.yolo:Fe.yolo,cliTimeoutMs:typeof a.cliTimeoutMs=="number"?a.cliTimeoutMs:Fe.cliTimeoutMs,profile:typeof a.profile=="string"?a.profile:Fe.profile}}function Kd(){const{t:a}=Z("app"),[t,s]=o.useState(Fe),[c,n]=o.useState(null),[m,i]=o.useState([]),[r,h]=o.useState(null),[k,v]=o.useState(null),d=o.useRef(!0);o.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]),o.useEffect(()=>{h("loading"),Ca(ia).then(y=>{d.current&&s($d(y))}).catch(()=>{}).finally(()=>{d.current&&h(null)})},[]),o.useEffect(()=>{xo(t.binaryPath?{binaryPath:t.binaryPath}:{}).then(y=>{d.current&&i(y)}).catch(()=>{})},[t.binaryPath]);const u=o.useCallback(async()=>{try{const y=await yo(t.binaryPath?{binaryPath:t.binaryPath}:{});return d.current&&n(y),y}catch(y){return d.current&&v({kind:"err",message:y instanceof Error?y.message:String(y)}),null}},[t.binaryPath]);o.useEffect(()=>{u()},[u]);const j=o.useCallback(()=>({binaryPath:t.binaryPath,model:t.model,provider:t.provider,maxTurns:t.maxTurns,yolo:t.yolo,cliTimeoutMs:t.cliTimeoutMs,profile:t.profile}),[t]),x=o.useCallback(async()=>{h("testing"),v(null);const y=await u();d.current&&(h(null),y?y.binary.available?v({kind:"ok",message:a("hermes.detected","✓ hermes detected{{version}}{{path}}.",{version:y.binary.version?` (${y.binary.version})`:"",path:y.binary.binaryPath?` at ${y.binary.binaryPath}`:""})}):v({kind:"err",message:a("hermes.notFound","✗ {{reason}}",{reason:y.binary.reason??"hermes not found"})}):v({kind:"err",message:a("hermes.testFailed","Test failed — see status above.")}))},[u,a]),b=o.useCallback(async()=>{h("saving"),v(null);try{await ot(ia,j()),d.current&&v({kind:"ok",message:a("hermes.settingsSaved","Settings saved.")})}catch(y){d.current&&v({kind:"err",message:y instanceof Error?y.message:String(y)})}finally{d.current&&h(null)}},[j,a]),S=o.useCallback(async()=>{h("save-test"),v(null);try{await ot(ia,j());const y=await u();if(!d.current)return;y?y.binary.available?v({kind:"ok",message:a("hermes.savedDetected","Saved · ✓ hermes detected{{version}}.",{version:y.binary.version?` (${y.binary.version})`:""})}):v({kind:"err",message:a("hermes.savedNotFound","Saved · ✗ {{reason}}",{reason:y.binary.reason??"hermes not found"})}):v({kind:"err",message:a("hermes.savedProbeFailed","Saved, but probe failed.")})}catch(y){d.current&&v({kind:"err",message:y instanceof Error?y.message:String(y)})}finally{d.current&&h(null)}},[j,u,a]),E=c?.binary,C=c===null?"loading":E?.available?"ok":"err",L=c===null?a("hermes.probing","Probing local hermes binary…"):E?.available?a("hermes.statusDetected","✓ Detected{{version}}{{path}}",{version:E.version?` ${E.version}`:"",path:E.binaryPath?` · ${E.binaryPath}`:""}):a("hermes.statusNotDetected","✗ {{reason}}",{reason:E?.reason??"not detected on PATH"});return e.jsxs(Pa,{testId:"hermes-runtime-card",logo:e.jsx("span",{style:{width:40,height:40,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:"50%",background:"#fff"},children:e.jsx("img",{src:"/brands/hermes-logo.svg",alt:a("runtimes.nousResearchLogoAlt","Nous Research"),style:{width:28,height:28,display:"block",filter:"invert(1) brightness(0)"}})}),name:"Hermes",subname:a("hermes.subname","by Nous Research"),learnMoreHref:sr,statusKind:C,statusText:L,description:e.jsx(e.Fragment,{children:a("hermes.description","Drives the local {{cmd}} CLI as a subprocess. Each Fusion prompt is sent as {{chatCmd}}; subsequent prompts resume the same hermes session via {{resumeFlag}}. Provider, model, and skills are configured inside hermes itself; this card only chooses overrides.",{cmd:"hermes",chatCmd:"hermes chat -q …",resumeFlag:"--resume"})}),busy:r,toast:k,onTest:()=>void x(),onSave:()=>void b(),onSaveAndTest:()=>void S(),belowForm:E?.available===!1?e.jsxs("div",{className:"onboarding-helper-text",children:[e.jsx("p",{children:a("hermes.notDetected","{{cmd}} not detected. Install the upstream agent:",{cmd:"hermes"})}),e.jsx("pre",{children:e.jsx("code",{children:"pipx install hermes-agent"})}),e.jsx("p",{children:e.jsx("a",{href:sr,target:"_blank",rel:"noreferrer",children:a("hermes.gitHubLink","Hermes on GitHub")})})]}):null,children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-profile",children:a("hermes.profileLabel","Profile (optional)")}),e.jsxs("select",{id:"hermes-profile",value:t.profile,onChange:y=>s(p=>({...p,profile:y.target.value})),children:[e.jsx("option",{value:"",children:a("hermes.autoProfile","Auto / use Hermes default")}),m.map(y=>e.jsxs("option",{value:y.name,children:[y.name,y.model?a("hermes.profileModelSeparator"," — {{model}}",{model:y.model}):"",y.isDefault?a("hermes.defaultProfile"," (default)"):""]},y.name))]}),e.jsx("small",{children:a("hermes.profileHelp","Select a Hermes profile to use. Activates the profile by setting {{env}} to the profile directory when invoking {{cmd}}.",{env:"HERMES_HOME",cmd:"hermes chat"})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-binary",children:a("hermes.binaryPathLabel","Binary path")}),e.jsx("input",{id:"hermes-binary",type:"text",placeholder:a("hermes.binaryPathPlaceholder","hermes (defaults to PATH)"),value:t.binaryPath,onChange:y=>s(p=>({...p,binaryPath:y.target.value}))}),e.jsx("small",{children:a("hermes.binaryPathHelp","Leave blank to resolve {{cmd}} from your PATH.",{cmd:"hermes"})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-model",children:a("hermes.modelLabel","Model override")}),e.jsx("input",{id:"hermes-model",type:"text",placeholder:a("hermes.modelPlaceholder","e.g. claude-sonnet-4-5, MiniMax-M3"),value:t.model,disabled:!!t.profile,onChange:y=>s(p=>({...p,model:y.target.value}))}),t.profile?e.jsx("small",{children:a("hermes.modelControlled","Controlled by profile: {{profile}}",{profile:t.profile})}):e.jsx("small",{children:a("hermes.modelHelp","Optional — overrides Hermes's configured default model.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-provider",children:a("hermes.providerLabel","Provider")}),e.jsx("select",{id:"hermes-provider",value:t.provider,disabled:!!t.profile,onChange:y=>s(p=>({...p,provider:y.target.value})),children:Wd.map(y=>e.jsx("option",{value:y,children:y},y))}),t.profile?e.jsx("small",{children:a("hermes.providerControlled","Controlled by profile: {{profile}}",{profile:t.profile})}):e.jsx("small",{children:a("hermes.providerHelp","Inference provider Hermes routes calls through (default: {{default}}).",{default:"auto"})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-maxTurns",children:a("hermes.maxTurnsLabel","Max turns")}),e.jsx("input",{id:"hermes-maxTurns",type:"number",min:1,max:500,value:t.maxTurns,onChange:y=>s(p=>({...p,maxTurns:Number(y.target.value)||Fe.maxTurns}))}),e.jsx("small",{children:a("hermes.maxTurnsHelp","Cap per Hermes turn. Hermes's own default is 90; we cap lower.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"hermes-yolo",style:{display:"inline-flex",alignItems:"center",gap:"var(--space-xs)"},children:[e.jsx("input",{id:"hermes-yolo",type:"checkbox",checked:t.yolo,onChange:y=>s(p=>({...p,yolo:y.target.checked}))}),a("hermes.yoloLabel","Auto-approve dangerous tool calls ({{flag}})",{flag:"--yolo"})]}),e.jsx("small",{children:a("hermes.yoloHelp","Required for non-interactive sessions that trigger shell-style tools.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-timeoutMs",children:a("hermes.timeoutLabel","CLI hard-kill timeout (ms)")}),e.jsx("input",{id:"hermes-timeoutMs",type:"number",min:1e3,step:1e3,value:t.cliTimeoutMs,onChange:y=>s(p=>({...p,cliTimeoutMs:Number(y.target.value)||Fe.cliTimeoutMs}))}),e.jsx("small",{children:a("hermes.timeoutHelp","Fusion-side hard cap. Default 5 min.")})]})]})}const oa="fusion-plugin-openclaw-runtime",qd="https://docs.openclaw.ai/",zd="https://github.com/openclaw/openclaw",Pr=["off","minimal","low","medium","high","xhigh","adaptive","max"],Le={binaryPath:"",agentId:"main",model:"",thinking:"off",useGateway:!1,cliTimeoutSec:0,cliTimeoutMs:3e5};function Vd(a){return{binaryPath:typeof a.binaryPath=="string"?a.binaryPath:Le.binaryPath,agentId:typeof a.agentId=="string"?a.agentId:Le.agentId,model:typeof a.model=="string"?a.model:Le.model,thinking:Pr.includes(a.thinking)?a.thinking:Le.thinking,useGateway:typeof a.useGateway=="boolean"?a.useGateway:Le.useGateway,cliTimeoutSec:typeof a.cliTimeoutSec=="number"?a.cliTimeoutSec:Le.cliTimeoutSec,cliTimeoutMs:typeof a.cliTimeoutMs=="number"?a.cliTimeoutMs:Le.cliTimeoutMs}}function Yd(){const{t:a}=Z("app"),[t,s]=o.useState(Le),[c,n]=o.useState(null),[m,i]=o.useState(null),[r,h]=o.useState(null),k=o.useRef(!0);o.useEffect(()=>(k.current=!0,()=>{k.current=!1}),[]),o.useEffect(()=>{i("loading"),Ca(oa).then(C=>{k.current&&s(Vd(C))}).catch(()=>{}).finally(()=>{k.current&&i(null)})},[]);const v=o.useCallback(async()=>{try{const C=await ko(t.binaryPath?{binaryPath:t.binaryPath}:void 0);return k.current&&n(C),C}catch(C){return k.current&&h({kind:"err",message:C instanceof Error?C.message:String(C)}),null}},[t.binaryPath]);o.useEffect(()=>{v()},[v]);const d=o.useCallback(()=>({binaryPath:t.binaryPath,agentId:t.agentId,model:t.model,thinking:t.thinking,useGateway:t.useGateway,cliTimeoutSec:t.cliTimeoutSec,cliTimeoutMs:t.cliTimeoutMs}),[t]),u=o.useCallback(async()=>{i("testing"),h(null);const C=await v();k.current&&(i(null),C?C.binary.available?h({kind:"ok",message:a("openclaw.detected","✓ openclaw detected{{version}}{{path}}.",{version:C.binary.version?` (${C.binary.version})`:"",path:C.binary.binaryPath?` at ${C.binary.binaryPath}`:""})}):h({kind:"err",message:a("openclaw.notFound",`✗ ${C.binary.reason??"openclaw not found"}`)}):h({kind:"err",message:a("openclaw.testFailed","Test failed — see status above.")}))},[v,a]),j=o.useCallback(async()=>{i("saving"),h(null);try{await ot(oa,d()),k.current&&h({kind:"ok",message:a("openclaw.saved","Settings saved.")})}catch(C){k.current&&h({kind:"err",message:C instanceof Error?C.message:String(C)})}finally{k.current&&i(null)}},[d,a]),x=o.useCallback(async()=>{i("save-test"),h(null);try{await ot(oa,d());const C=await v();if(!k.current)return;C?C.binary.available?h({kind:"ok",message:a("openclaw.savedDetected","Saved · ✓ openclaw detected{{version}}{{path}}.",{version:C.binary.version?` (${C.binary.version})`:"",path:C.binary.binaryPath?` at ${C.binary.binaryPath}`:""})}):h({kind:"err",message:a("openclaw.savedNotFound",`Saved · ✗ ${C.binary.reason??"openclaw not found"}`)}):h({kind:"err",message:a("openclaw.savedProbeFailed","Saved, but probe failed.")})}catch(C){k.current&&h({kind:"err",message:C instanceof Error?C.message:String(C)})}finally{k.current&&i(null)}},[d,v,a]),b=c?.binary,S=c===null?"loading":b?.available?"ok":"err",E=c===null?a("openclaw.probing","Probing local openclaw binary…"):b?.available?a("openclaw.statusDetected","✓ Detected{{version}}{{path}}",{version:b.version?` ${b.version}`:"",path:b.binaryPath?` · ${b.binaryPath}`:""}):a("openclaw.statusNotFound",`✗ ${b?.reason??"not detected on PATH"}`);return e.jsxs(Pa,{testId:"openclaw-runtime-card",logo:e.jsx(Tt,{provider:"openclaw",size:"lg"}),name:"OpenClaw",learnMoreHref:qd,statusKind:S,statusText:E,description:e.jsx(ka,{i18nKey:"app:openclaw.description",defaults:"Drives the local <code1>openclaw</code1> CLI as a subprocess. Each Fusion prompt is dispatched via <code2>openclaw agent --local --json</code2>; the agent definition, model, and thinking level are resolved by OpenClaw. This card only sets overrides and the binary path.",components:{code1:e.jsx("code",{}),code2:e.jsx("code",{})}}),busy:m,toast:r,onTest:()=>void u(),onSave:()=>void j(),onSaveAndTest:()=>void x(),belowForm:b?.available===!1?e.jsxs("div",{className:"onboarding-helper-text",children:[e.jsx("p",{children:e.jsx(ka,{i18nKey:"app:openclaw.notDetectedInstall",defaults:"<code>openclaw</code> not detected. Install the upstream agent:",components:{code:e.jsx("code",{})}})}),e.jsx("pre",{children:e.jsx("code",{children:"npm install -g openclaw"})}),e.jsx("p",{children:e.jsx("a",{href:zd,target:"_blank",rel:"noreferrer",children:a("openclaw.githubLink","openclaw on GitHub")})})]}):null,children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-binaryPath",children:a("openclaw.binaryPath","Binary path")}),e.jsx("input",{id:"openclaw-binaryPath",type:"text",placeholder:a("openclaw.binaryPathPlaceholder","openclaw (defaults to PATH)"),value:t.binaryPath,onChange:C=>s(L=>({...L,binaryPath:C.target.value}))}),e.jsx("small",{children:a("openclaw.binaryPathHint","Leave blank to resolve openclaw from your PATH.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-agentId",children:a("openclaw.agentId","Agent ID")}),e.jsx("input",{id:"openclaw-agentId",type:"text",placeholder:a("openclaw.agentIdPlaceholder","main"),value:t.agentId,onChange:C=>s(L=>({...L,agentId:C.target.value}))}),e.jsx("small",{children:a("openclaw.agentIdHint","OpenClaw agent definition to run (default: main).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-model",children:a("openclaw.model","Model override")}),e.jsx("input",{id:"openclaw-model",type:"text",placeholder:a("openclaw.modelPlaceholder","e.g. anthropic/claude-haiku-4-5, minimax/MiniMax-M3"),value:t.model,onChange:C=>s(L=>({...L,model:C.target.value}))}),e.jsx("small",{children:a("openclaw.modelHint","Optional — overrides the OpenClaw default model.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-thinking",children:a("openclaw.thinking","Thinking level")}),e.jsx("select",{id:"openclaw-thinking",value:t.thinking,onChange:C=>s(L=>({...L,thinking:C.target.value})),children:Pr.map(C=>e.jsx("option",{value:C,children:C},C))}),e.jsx("small",{children:a("openclaw.thinkingHint","Controls how much extended thinking the model uses.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"openclaw-useGateway",style:{display:"inline-flex",alignItems:"center",gap:"var(--space-xs)"},children:[e.jsx("input",{id:"openclaw-useGateway",type:"checkbox",checked:t.useGateway,onChange:C=>s(L=>({...L,useGateway:C.target.checked}))}),a("openclaw.gateway","Route through OpenClaw gateway (otherwise embedded)")]}),e.jsx("small",{children:a("openclaw.gatewayHint","When enabled, calls pass through the OpenClaw gateway service.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-cliTimeoutSec",children:a("openclaw.cliTimeout","OpenClaw timeout (sec)")}),e.jsx("input",{id:"openclaw-cliTimeoutSec",type:"number",min:0,step:1,value:t.cliTimeoutSec,onChange:C=>s(L=>({...L,cliTimeoutSec:parseInt(C.target.value,10)||0}))}),e.jsx("small",{children:a("openclaw.cliTimeoutHint","OpenClaw-side run timeout in seconds (0 = no timeout).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-cliTimeoutMs",children:a("openclaw.subprocess","CLI subprocess timeout (ms)")}),e.jsx("input",{id:"openclaw-cliTimeoutMs",type:"number",min:0,step:1e3,value:t.cliTimeoutMs,onChange:C=>s(L=>({...L,cliTimeoutMs:parseInt(C.target.value,10)||Le.cliTimeoutMs}))}),e.jsx("small",{children:a("openclaw.subprocessHint","Fusion-side hard cap before the CLI subprocess is killed (default: {{default}}s).",{default:Le.cliTimeoutMs/1e3})})]})]})}const ca="fusion-plugin-paperclip-runtime",ar="https://paperclip.ing/",Qd="https://github.com/paperclipai/paperclip",nr=[{value:"rolling-issue",label:"Rolling issue (default)",help:"One Paperclip issue per Fusion session; subsequent prompts are added as comments. Closest to a chat experience."},{value:"issue-per-prompt",label:"Issue per prompt",help:"Each prompt creates a new top-level Paperclip issue. Maximally explicit; tends to clutter the board."},{value:"wakeup-only",label:"Wakeup only (advanced)",help:"No issue side-effects; the prompt is delivered via the wakeup payload only. Requires the agent's prompt template to know how to handle a payload-driven wake."}],Ce={transport:"api",apiUrl:"http://localhost:3100",apiKey:"",cliBinaryPath:"paperclipai",cliConfigPath:"",agentId:"",companyId:"",mode:"rolling-issue",parentIssueId:"",projectId:"",goalId:"",runTimeoutMs:6e5},Jd=new Set(["issue-per-prompt","rolling-issue","wakeup-only"]);function Xd(a){const t=(m,i)=>typeof a[m]=="string"?a[m]:i,s=(m,i)=>typeof a[m]=="number"?a[m]:i,c=a.transport==="cli"?"cli":"api",n=Jd.has(a.mode)?a.mode:Ce.mode;return{transport:c,apiUrl:t("apiUrl",Ce.apiUrl),apiKey:t("apiKey",Ce.apiKey),cliBinaryPath:t("cliBinaryPath",Ce.cliBinaryPath),cliConfigPath:t("cliConfigPath",Ce.cliConfigPath),agentId:t("agentId",Ce.agentId),companyId:t("companyId",Ce.companyId),mode:n,parentIssueId:t("parentIssueId",Ce.parentIssueId),projectId:t("projectId",Ce.projectId),goalId:t("goalId",Ce.goalId),runTimeoutMs:s("runTimeoutMs",Ce.runTimeoutMs)}}function Zd(){const{t:a}=Z("app"),[t,s]=o.useState(Ce),[c,n]=o.useState(null),[m,i]=o.useState(null),[r,h]=o.useState([]),[k,v]=o.useState([]),[d,u]=o.useState(null),[j,x]=o.useState(null),[b,S]=o.useState(!1),E=o.useRef(!0);o.useEffect(()=>(E.current=!0,()=>{E.current=!1}),[]);const C=o.useMemo(()=>t.transport==="cli"&&m&&m.ok?{apiUrl:m.apiUrl,apiKey:t.apiKey||m.apiKey||void 0}:{apiUrl:t.apiUrl,apiKey:t.apiKey||void 0},[t.transport,t.apiUrl,t.apiKey,m]);o.useEffect(()=>{u("loading"),Ca(ca).then(T=>{E.current&&s(Xd(T))}).catch(()=>{}).finally(()=>{E.current&&u(null)})},[]),o.useEffect(()=>{if(t.transport!=="cli"){i(null);return}let T=!1;return jo({cliConfigPath:t.cliConfigPath||void 0}).then(U=>{!T&&E.current&&i(U)}).catch(()=>{!T&&E.current&&i({ok:!1,reason:"Discovery request failed"})}),()=>{T=!0}},[t.transport,t.cliConfigPath]);const L=t.transport==="cli",y=o.useMemo(()=>({cliBinaryPath:t.cliBinaryPath||void 0,cliConfigPath:t.cliConfigPath||void 0}),[t.cliBinaryPath,t.cliConfigPath]),p=o.useCallback(async()=>{if(!L&&!C.apiUrl)return null;try{const T=L?await wo(y):await Co(C);E.current&&n(T);const U=L?await No(y):await So(C);if(!E.current)return T;h(U);let re=t.companyId;if(U.some(q=>q.id===re)||(re=T.connection.identity?.companyId??U[0]?.id??"",re&&re!==t.companyId&&s(q=>({...q,companyId:re}))),re){const q=L?await Sn({...y,companyId:re}):await Pn({...C,companyId:re});if(E.current&&(v(q),!q.some(F=>F.id===t.agentId))){const F=T.connection.identity?.agentId??q[0]?.id??"";F&&F!==t.agentId&&s(K=>({...K,agentId:F}))}}else E.current&&v([]);return T}catch(T){return E.current&&x({kind:"err",message:T instanceof Error?T.message:String(T)}),null}},[L,y,C.apiUrl,C.apiKey,t.companyId,t.agentId]);o.useEffect(()=>{p()},[p]),o.useEffect(()=>{if(!t.companyId){v([]);return}if(!L&&!C.apiUrl){v([]);return}let T=!1;return(L?Sn({...y,companyId:t.companyId}):Pn({...C,companyId:t.companyId})).then(re=>{!T&&E.current&&v(re)}).catch(()=>{!T&&E.current&&v([])}),()=>{T=!0}},[L,y,C.apiUrl,C.apiKey,t.companyId]);const P=o.useCallback(()=>{const T={transport:t.transport,mode:t.mode,parentIssueId:t.parentIssueId,projectId:t.projectId,goalId:t.goalId,runTimeoutMs:t.runTimeoutMs,agentId:t.agentId,companyId:t.companyId};return t.transport==="api"?T.apiUrl=t.apiUrl:(T.cliBinaryPath=t.cliBinaryPath,t.cliConfigPath&&(T.cliConfigPath=t.cliConfigPath)),b&&(T.apiKey=t.apiKey),T},[t,b]),f=o.useCallback(async()=>{u("testing"),x(null);const T=await p();if(E.current)if(u(null),!T)t.transport==="cli"&&m&&!m.ok?x({kind:"err",message:a("paperclip.cliDiscoveryFailed","✗ CLI discovery failed: {{reason}}",{reason:m.reason})}):x({kind:"err",message:a("paperclip.testFailed","Test failed — see status above.")});else if(T.connection.available){const U=T.connection.identity;x({kind:"ok",message:U?a("paperclip.connectedAsAgent","✓ Connected as {{agentName}}{{companyInfo}}.",{agentName:U.agentName,companyInfo:U.companyName?` at ${U.companyName}`:""}):a("paperclip.connected","✓ Connected.")})}else x({kind:"err",message:a("paperclip.unreachable","✗ {{reason}}",{reason:T.connection.reason??"Paperclip server unreachable"})})},[p,t.transport,m,a]),J=o.useCallback(async()=>{u("saving"),x(null);try{await ot(ca,P()),E.current&&(x({kind:"ok",message:a("paperclip.settingsSaved","Settings saved.")}),S(!1))}catch(T){E.current&&x({kind:"err",message:T instanceof Error?T.message:String(T)})}finally{E.current&&u(null)}},[P,a]),W=o.useCallback(async()=>{u("save-test"),x(null);try{await ot(ca,P()),E.current&&S(!1);const T=await p();if(!E.current)return;if(!T)t.transport==="cli"&&m&&!m.ok?x({kind:"err",message:a("paperclip.savedCliDiscoveryFailed","Saved · ✗ CLI discovery failed: {{reason}}",{reason:m.reason})}):x({kind:"err",message:a("paperclip.savedProbeFailed","Saved, but probe failed.")});else if(T.connection.available){const U=T.connection.identity;x({kind:"ok",message:U?a("paperclip.savedConnectedAsAgent","Saved · ✓ Connected as {{agentName}}{{companyInfo}}.",{agentName:U.agentName,companyInfo:U.companyName?` at ${U.companyName}`:""}):a("paperclip.savedConnected","Saved · ✓ Connected.")})}else x({kind:"err",message:a("paperclip.savedUnreachable","Saved · ✗ {{reason}}",{reason:T.connection.reason??"Paperclip server unreachable"})})}catch(T){E.current&&x({kind:"err",message:T instanceof Error?T.message:String(T)})}finally{E.current&&u(null)}},[P,p,t.transport,m,a]),X=c?.connection.available??null,Q=c?.connection.identity,ne=m?.ok===!0,ae=c===null?"loading":X?"ok":"err",V=c===null?t.transport==="cli"&&m&&!ne?a("paperclip.statusCliDiscoveryFailed","✗ CLI discovery failed: {{reason}}",{reason:m.reason}):a("paperclip.statusProbing","Probing Paperclip server…"):X?Q?a("paperclip.statusConnectedAs","✓ Connected as {{agentName}}{{roleInfo}}{{companyInfo}}",{agentName:Q.agentName,roleInfo:Q.role?` (${Q.role})`:"",companyInfo:Q.companyName?` at ${Q.companyName}`:""}):a("paperclip.statusConnected","✓ Connected"):a("paperclip.statusUnreachable","✗ {{reason}}",{reason:c.connection.reason??"Unreachable"}),$=e.jsxs("div",{className:"runtime-card__tabs",role:"tablist","aria-label":a("paperclip.connectionModeAriaLabel","Paperclip connection mode"),children:[e.jsx("button",{type:"button",role:"tab","aria-selected":t.transport==="api",className:"runtime-card__tab",onClick:()=>s(T=>({...T,transport:"api"})),children:a("paperclip.tabApi","API (URL + token)")}),e.jsx("button",{type:"button",role:"tab","aria-selected":t.transport==="cli",className:"runtime-card__tab",onClick:()=>s(T=>({...T,transport:"cli"})),children:a("paperclip.tabCliAutoDerve","Local CLI (auto-derive)")})]});return e.jsxs(Pa,{testId:"paperclip-runtime-card",logo:e.jsx(Tt,{provider:"paperclip",size:"lg"}),name:a("paperclip.name","Paperclip"),learnMoreHref:ar,statusKind:ae,statusText:V,description:e.jsx(e.Fragment,{children:a("paperclip.description",'Drive a Paperclip agent ("employee") in a Paperclip company. Each prompt dispatches a task-shaped request; governance, budgets, and approvals are enforced by Paperclip. Expect seconds-to-minutes latency per turn.')}),tabs:$,busy:d,toast:j,onTest:()=>void f(),onSave:()=>void J(),onSaveAndTest:()=>void W(),belowForm:X===!1?e.jsxs("div",{className:"onboarding-helper-text",children:[e.jsx("p",{children:a("paperclip.onboardingStep1","Make sure a Paperclip server is running. To install Paperclip:")}),e.jsx("pre",{children:e.jsx("code",{children:"npm install -g paperclipai"})}),e.jsxs("p",{children:[e.jsx("a",{href:ar,target:"_blank",rel:"noreferrer",children:a("paperclip.docsLink","Paperclip docs")})," ","·"," ",e.jsx("a",{href:Qd,target:"_blank",rel:"noreferrer",children:a("paperclip.githubLink","GitHub")})]})]}):null,children:[t.transport==="cli"&&m&&e.jsx("div",{className:"settings-muted",style:{marginBottom:"var(--space-sm)"},children:ne?e.jsxs("small",{children:[a("paperclip.cliConfigLabel","CLI config:")," ",e.jsx("code",{children:m.configPath})," ","· ",a("paperclip.resolved","resolved")," ",e.jsx("code",{children:m.apiUrl}),m.deploymentMode?` · ${m.deploymentMode}`:""]}):e.jsx("small",{children:a("paperclip.cliDiscoveryFailedLabel","CLI discovery failed: {{reason}}",{reason:m.reason})})}),t.transport==="api"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-apiUrl",children:a("paperclip.apiUrlLabel","API URL")}),e.jsx("input",{id:"paperclip-apiUrl",type:"text",placeholder:"http://localhost:3100",value:t.apiUrl,onChange:T=>s(U=>({...U,apiUrl:T.target.value}))}),e.jsx("small",{children:a("paperclip.apiUrlHelp","Base URL of the Paperclip server.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-apiKey",children:a("paperclip.apiKeyLabel","API key")}),e.jsx("input",{id:"paperclip-apiKey",type:"password",placeholder:b?"":a("paperclip.apiKeyPlaceholder","•••••••• (leave blank to keep existing)"),value:t.apiKey,onChange:T=>{s(U=>({...U,apiKey:T.target.value})),S(!0)}}),e.jsx("small",{children:a("paperclip.apiKeyHelp","Agent API key. Local-trusted deployments may leave this blank.")})]})]}),t.transport==="cli"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-cliBinaryPath",children:a("paperclip.cliBinaryLabel","paperclipai binary")}),e.jsx("input",{id:"paperclip-cliBinaryPath",type:"text",placeholder:"paperclipai",value:t.cliBinaryPath,onChange:T=>s(U=>({...U,cliBinaryPath:T.target.value}))}),e.jsx("small",{children:a("paperclip.cliBinaryHelp","Optional — informational; the adapter currently reads the instance config file directly.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-cliConfigPath",children:a("paperclip.cliConfigPathLabel","Instance config path")}),e.jsx("input",{id:"paperclip-cliConfigPath",type:"text",placeholder:"~/.paperclip/instances/default/config.json",value:t.cliConfigPath,onChange:T=>s(U=>({...U,cliConfigPath:T.target.value}))}),e.jsx("small",{children:a("paperclip.cliConfigPathHelp","Override the path to config.json. Leave blank for the default.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-cli-apikey",children:a("paperclip.cliApiKeyLabel","API key (override, optional)")}),e.jsx("input",{id:"paperclip-cli-apikey",type:"password",placeholder:b?"":a("paperclip.cliApiKeyPlaceholder","Optional — only required for non-local-trusted modes"),value:t.apiKey,onChange:T=>{s(U=>({...U,apiKey:T.target.value})),S(!0)}}),e.jsx("small",{children:a("paperclip.cliApiKeyHelp","Local-trusted deployments do not require a key.")}),c!==null&&X===!1&&t.agentId&&e.jsx("button",{type:"button",className:"btn btn--sm",style:{marginTop:"0.4rem"},disabled:d!==null,onClick:async()=>{const T=t.agentId,U=t.companyId.trim();if(!T||!U){x({kind:"err",message:a("paperclip.companyIdRequired","✗ Company ID is required to mint a Paperclip API key.")});return}u("testing"),x(null);const re=await Po({cliBinaryPath:t.cliBinaryPath||void 0,agentRef:T,companyId:U,keyName:"fusion-runtime",configPath:t.cliConfigPath||void 0});E.current&&(u(null),re.ok?(s(q=>({...q,apiKey:re.key.apiKey})),S(!0),x({kind:"ok",message:a("paperclip.apiKeyMinted","✓ API key minted via paperclipai (key 'fusion-runtime' installed for agent {{agentId}}). Click Save to persist.",{agentId:T})}),p()):x({kind:"err",message:a("paperclip.mintFailed","✗ Mint failed: {{reason}}. Run `paperclipai onboard` first if your CLI isn't authenticated.",{reason:re.reason})}))},children:a("paperclip.mintButton","✨ Mint API key via paperclipai")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-companyId",children:a("paperclip.companyLabel","Company")}),e.jsx("select",{id:"paperclip-companyId",value:t.companyId,onChange:T=>s(U=>({...U,companyId:T.target.value})),disabled:r.length===0,children:r.length===0?e.jsx("option",{value:"",children:X?a("paperclip.noCompaniesDiscovered","No companies discovered"):a("paperclip.connectToPopulate","Connect to populate")}):r.map(T=>e.jsxs("option",{value:T.id,children:[T.name," (",T.id,")"]},T.id))}),e.jsx("small",{children:a("paperclip.companyHelp","Select a Paperclip company.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-agentId",children:a("paperclip.agentLabel","Agent")}),e.jsx("select",{id:"paperclip-agentId",value:t.agentId,onChange:T=>s(U=>({...U,agentId:T.target.value})),disabled:k.length===0,children:k.length===0?e.jsx("option",{value:"",children:t.companyId?a("paperclip.noAgentsDiscovered","No agents discovered"):a("paperclip.pickCompanyFirst","Pick a company first")}):k.map(T=>e.jsxs("option",{value:T.id,children:[T.name,T.role?` (${T.role})`:""]},T.id))}),e.jsx("small",{children:a("paperclip.agentHelp","Pick the Paperclip agent this Fusion runtime will proxy.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-mode",children:a("paperclip.modeLabel","Conversation mode")}),e.jsx("select",{id:"paperclip-mode",value:t.mode,onChange:T=>s(U=>({...U,mode:T.target.value})),children:nr.map(T=>e.jsx("option",{value:T.value,children:a(`paperclip.mode.${T.value}`,T.label)},T.value))}),e.jsx("small",{children:a(`paperclip.modeHelp.${t.mode}`,nr.find(T=>T.value===t.mode)?.help??"")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-projectId",children:a("paperclip.projectIdLabel","Project ID (optional)")}),e.jsx("input",{id:"paperclip-projectId",type:"text",placeholder:a("paperclip.optionalPlaceholder","Optional"),value:t.projectId,onChange:T=>s(U=>({...U,projectId:T.target.value}))}),e.jsx("small",{children:a("paperclip.projectIdHelp","Pin work to a specific Paperclip project.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-parentIssueId",children:a("paperclip.parentIssueIdLabel","Parent issue ID (optional)")}),e.jsx("input",{id:"paperclip-parentIssueId",type:"text",placeholder:a("paperclip.optionalPlaceholder","Optional"),value:t.parentIssueId,onChange:T=>s(U=>({...U,parentIssueId:T.target.value}))}),e.jsx("small",{children:a("paperclip.parentIssueIdHelp","Scope work under an existing parent issue.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-goalId",children:a("paperclip.goalIdLabel","Goal ID (optional)")}),e.jsx("input",{id:"paperclip-goalId",type:"text",placeholder:a("paperclip.optionalPlaceholder","Optional"),value:t.goalId,onChange:T=>s(U=>({...U,goalId:T.target.value}))}),e.jsx("small",{children:a("paperclip.goalIdHelp","Associate work with a Paperclip goal.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-runTimeoutMs",children:a("paperclip.runTimeoutLabel","Run timeout (ms)")}),e.jsx("input",{id:"paperclip-runTimeoutMs",type:"number",min:0,step:1e3,value:t.runTimeoutMs,onChange:T=>s(U=>({...U,runTimeoutMs:parseInt(T.target.value,10)||Ce.runTimeoutMs}))}),e.jsx("small",{children:a("paperclip.runTimeoutHelp","Local cap before Fusion gives up on a Paperclip run.")})]})]})}function eu(){const{t:a}=Z("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.runtimesRuntimes.hermesRuntime","Hermes Runtime")}),e.jsx(Kd,{})]})}function tu(){const{t:a}=Z("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.runtimesRuntimes.openClawRuntime","OpenClaw Runtime")}),e.jsx(Yd,{})]})}function su(){const{t:a}=Z("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.runtimesRuntimes.paperclipRuntime","Paperclip Runtime")}),e.jsx(Zd,{})]})}function au({scopeBanner:a,addToast:t}){const{t:s}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:s("settings.nav.secrets","Secrets")}),e.jsx(Dc,{addToast:t})]})}const rt=[{id:"default-executor",name:"Default Executor",description:"Standard task execution agent with full tooling and review support.",role:"executor",prompt:`You are a task execution agent for "fn", an AI-orchestrated task board.
8
-
9
- You are working in a git worktree isolated from the main branch. Your job is to implement the task described in the PROMPT.md specification you're given.`,builtIn:!0},{id:"default-triage",name:"Default Triage",description:"Standard task specification agent producing detailed PROMPT.md files.",role:"triage",prompt:`You are a task specification agent for "fn", an AI-orchestrated task board.
10
-
11
- Your job: take a rough task description and produce a fully specified PROMPT.md that another AI agent can execute autonomously.`,builtIn:!0},{id:"default-reviewer",name:"Default Reviewer",description:"Standard independent code and plan reviewer with balanced criteria.",role:"reviewer",prompt:`You are an independent code and plan reviewer.
12
-
13
- You provide quality assessment for task implementations with full read access to the codebase.`,builtIn:!0},{id:"default-merger",name:"Default Merger",description:"Standard merge agent for squash merges with conflict resolution.",role:"merger",prompt:`You are a merge agent for "fn", an AI-orchestrated task board.
14
-
15
- Your job is to finalize a squash merge: resolve any conflicts and write a good commit message.`,builtIn:!0},{id:"senior-engineer",name:"Senior Engineer",description:"Autonomous executor with architectural awareness, performance focus, and minimal hand-holding.",role:"executor",prompt:`You are a senior engineering agent for "fn", an AI-orchestrated task board.
16
-
17
- You operate with a high degree of autonomy, making architectural decisions and balancing trade-offs independently.`,builtIn:!0},{id:"strict-reviewer",name:"Strict Reviewer",description:"Rigorous reviewer with stricter criteria for security, edge cases, and type safety.",role:"reviewer",prompt:`You are a strict code and plan reviewer with rigorous standards.
18
-
19
- You hold all submissions to a high bar for correctness, security, and maintainability.`,builtIn:!0},{id:"concise-triage",name:"Concise Triage",description:"Shorter, more focused specification format with minimal prose.",role:"triage",prompt:`You are a task specification agent for "fn". Produce a concise, actionable PROMPT.md from the given task description.
20
-
21
- Be brief and precise — avoid verbosity.`,builtIn:!0}],nu={"executor-welcome":{key:"executor-welcome",name:"Executor Welcome",roles:["executor"],description:"Introductory section for the executor agent",defaultContent:"You are a task execution agent..."},"executor-guardrails":{key:"executor-guardrails",name:"Executor Guardrails",roles:["executor"],description:"Behavioral guardrails and constraints for the executor",defaultContent:"Treat the File Scope in PROMPT.md..."},"executor-spawning":{key:"executor-spawning",name:"Executor Spawning",roles:["executor"],description:"Instructions for spawning child agents",defaultContent:"You can spawn child agents..."},"executor-completion":{key:"executor-completion",name:"Executor Completion",roles:["executor"],description:"Completion criteria and signaling for executor",defaultContent:"After all steps are done..."},"triage-welcome":{key:"triage-welcome",name:"Triage Welcome",roles:["triage"],description:"Introductory section for the triage/specification agent",defaultContent:"You are a task specification agent..."},"triage-context":{key:"triage-context",name:"Triage Context",roles:["triage"],description:"Context-gathering instructions for triage",defaultContent:"What you receive: A raw task title..."},"reviewer-verdict":{key:"reviewer-verdict",name:"Reviewer Verdict",roles:["reviewer"],description:"Verdict criteria and format for code/review agent",defaultContent:"APPROVE — Step will achieve its stated outcomes..."},"merger-conflicts":{key:"merger-conflicts",name:"Merger Conflicts",roles:["merger"],description:"Merge conflict resolution instructions for merger",defaultContent:"If there are merge conflicts..."},"agent-generation-system":{key:"agent-generation-system",name:"Agent Generation System",roles:["executor"],description:"System prompt for generating agent specifications",defaultContent:"You are an agent specification generator..."},"workflow-step-refine":{key:"workflow-step-refine",name:"Workflow Step Refine",roles:["executor"],description:"System prompt for refining workflow step descriptions",defaultContent:"You are an expert at creating detailed agent prompts..."},"planning-system":{key:"planning-system",name:"Planning System",roles:["triage"],description:"System prompt for the AI planning assistant",defaultContent:"You are a planning assistant for the fn task board system..."},"subtask-breakdown-system":{key:"subtask-breakdown-system",name:"Subtask Breakdown System",roles:["executor"],description:"System prompt for AI subtask decomposition",defaultContent:"You are a task decomposition assistant..."},"mission-interview-system":{key:"mission-interview-system",name:"Mission Interview System",roles:["triage"],description:"System prompt for AI-assisted mission planning",defaultContent:"You are a mission planning assistant..."},"ai-refine-system":{key:"ai-refine-system",name:"AI Refine System",roles:["executor"],description:"System prompt for AI-powered text refinement",defaultContent:"You are a text refinement assistant..."},"agent-onboarding-system":{key:"agent-onboarding-system",name:"Agent Onboarding System",roles:["executor"],description:"System prompt for AI-guided agent onboarding interview",defaultContent:"You are an agent onboarding assistant for the fn task board system..."}},rr=["executor","triage","reviewer","merger"],ru={executor:{key:"agentPrompts.roles.executor",defaultValue:"Executor Agent"},triage:{key:"agentPrompts.roles.triage",defaultValue:"Triage Agent"},reviewer:{key:"agentPrompts.roles.reviewer",defaultValue:"Reviewer Agent"},merger:{key:"agentPrompts.roles.merger",defaultValue:"Merger Agent"},scheduler:{key:"agentPrompts.roles.scheduler",defaultValue:"Scheduler Agent"},engineer:{key:"agentPrompts.roles.engineer",defaultValue:"Engineer Agent"},custom:{key:"agentPrompts.roles.custom",defaultValue:"Custom Agent"}},Nt=a=>`prompt-role-tone--${a}`,da={name:"",description:"",role:"executor",prompt:""};function lu(a,t){const s=a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),c=new Set(rt.map(i=>i.id)),n=new Set(t.map(i=>i.id));if(!c.has(s)&&!n.has(s))return s;let m=2;for(;c.has(`${s}-${m}`)||n.has(`${s}-${m}`);)m++;return`${s}-${m}`}function iu({value:a,onChange:t,promptOverrides:s,onPromptOverridesChange:c}){const{t:n}=Z("app"),m=A=>{const G=ru[A];return n(G.key,G.defaultValue)},[i,r]=o.useState("templates"),[h,k]=o.useState(null),[v,d]=o.useState(!1),[u,j]=o.useState(da),[x,b]=o.useState(null),[S,E]=o.useState(null),[C,L]=o.useState(new Set),[y,p]=o.useState(null),[P,f]=o.useState(!1),[J,W]=o.useState(null),X=o.useRef(null),Q=a?.templates??[],ne=a?.roleAssignments??{},ae=J===null?null:J.source==="builtin"?rt.find(A=>A.id===J.id):Q.find(A=>A.id===J.id),V=o.useCallback(A=>{const G=rt.filter(ce=>ce.role===A),se=Q.filter(ce=>ce.role===A);return[...G,...se]},[Q]);o.useEffect(()=>{J!==null&&X.current?.focus()},[J]);const $=o.useCallback(()=>{d(!0),k(null),j(da),b(null),W(null)},[]),T=o.useCallback(A=>{k(A.id),d(!1),j({name:A.name,description:A.description,role:A.role,prompt:A.prompt}),b(null),W(null)},[]),U=o.useCallback(()=>{k(null),d(!1),j(da),b(null),W(null),f(!1)},[]),re=o.useCallback(()=>{const A=u.name.trim();if(!A){b(n("agentPrompts.errors.nameRequired","Template name is required"));return}let G;if(v){if(G=lu(A,Q),new Set(rt.map(M=>M.id)).has(G)){b(n("agentPrompts.errors.idConflict",'Template ID "{{templateId}}" conflicts with a built-in template. Please use a different name.',{templateId:G}));return}}else G=h;const se={id:G,name:A,description:u.description.trim(),role:u.role,prompt:u.prompt,builtIn:!1};let ce;v?ce=[...Q,se]:ce=Q.map(z=>z.id===G?se:z);const B={...ne};for(const[z,M]of Object.entries(B))M===G&&u.role!==z&&delete B[z];t({...a,templates:ce,roleAssignments:Object.keys(B).length>0?B:void 0}),U()},[u,v,h,Q,ne,a,t,U]),q=o.useCallback(A=>{const G=Q.filter(B=>B.id!==A),se={...ne};let ce=!1;for(const[B,z]of Object.entries(se))z===A&&(delete se[B],ce=!0);t({...a,templates:G.length>0?G:void 0,roleAssignments:Object.keys(se).length>0||ce?Object.keys(se).length>0?se:void 0:ne}),E(null),h===A&&U()},[Q,ne,a,t,h,U]),F=o.useCallback((A,G)=>{const se={...ne};G===""?delete se[A]:se[A]=G,t({...a,roleAssignments:Object.keys(se).length>0?se:void 0})},[ne,a,t]),K=o.useCallback((A,G)=>{const se={...s};se[A]=G||null,c(se)},[s,c]),R=o.useCallback(A=>{const G={...s};G[A]=null,c(G)},[s,c]),pe=o.useCallback(A=>{L(G=>{const se=new Set(G);return se.has(A)?se.delete(A):se.add(A),se})},[]),ge=o.useCallback(A=>{p(G=>G===A?null:A)},[]),fe=o.useCallback((A,G)=>{f(!1),W({source:A,id:G})},[]),be=o.useCallback(()=>{W(null),f(A=>!A)},[]),Pe=A=>rt.some(G=>G.id===A);return e.jsxs("div",{className:"prompt-manager",children:[e.jsxs("div",{className:"prompt-manager-tabs",children:[e.jsxs("button",{type:"button",className:`prompt-manager-tab ${i==="templates"?"active":""}`,onClick:()=>r("templates"),"data-testid":"tab-templates",children:[e.jsx(Oc,{size:14}),n("agentPrompts.tabs.templates","Templates")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${i==="assignments"?"active":""}`,onClick:()=>r("assignments"),"data-testid":"tab-assignments",children:[e.jsx(Gc,{size:14}),n("agentPrompts.tabs.assignments","Assignments")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${i==="overrides"?"active":""}`,onClick:()=>r("overrides"),"data-testid":"tab-overrides",children:[e.jsx(Hc,{size:14}),n("agentPrompts.tabs.overrides","Overrides")]})]}),e.jsxs("div",{className:"prompt-manager-content",children:[i==="templates"&&e.jsxs("div",{className:"prompt-manager-templates-tab","data-testid":"templates-tab",children:[(v||h!==null)&&e.jsxs("div",{className:"prompt-template-editor","data-testid":"template-editor",children:[e.jsx("h4",{className:"prompt-template-editor-title",children:v?n("agentPrompts.editor.newTemplate","New Custom Template"):n("agentPrompts.editor.editTemplate","Edit Custom Template")}),e.jsxs("div",{className:"prompt-template-editor-fields",children:[e.jsxs("div",{className:"prompt-template-field",children:[e.jsx("label",{htmlFor:"template-name",children:n("agentPrompts.labels.name","Name")}),e.jsx("input",{id:"template-name",type:"text",value:u.name,onChange:A=>j(G=>({...G,name:A.target.value})),placeholder:n("agentPrompts.placeholders.templateName","e.g. My Custom Executor"),"data-testid":"template-name-input"})]}),e.jsxs("div",{className:"prompt-template-field",children:[e.jsx("label",{htmlFor:"template-description",children:n("agentPrompts.labels.description","Description")}),e.jsx("input",{id:"template-description",type:"text",value:u.description,onChange:A=>j(G=>({...G,description:A.target.value})),placeholder:n("agentPrompts.placeholders.description","Brief description of this template"),"data-testid":"template-description-input"})]}),e.jsxs("div",{className:"prompt-template-field",children:[e.jsx("label",{htmlFor:"template-role",children:n("agentPrompts.labels.role","Role")}),e.jsx("select",{id:"template-role",value:u.role,onChange:A=>j(G=>({...G,role:A.target.value})),"data-testid":"template-role-select",children:rr.map(A=>e.jsx("option",{value:A,children:m(A)},A))})]}),e.jsxs("div",{className:"prompt-template-field",children:[e.jsxs("div",{className:"prompt-template-prompt-label-row",children:[e.jsx("label",{htmlFor:"template-prompt",children:n("agentPrompts.labels.prompt","Prompt")}),e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:be,"aria-label":n("agentPrompts.ariaLabels.expandPrompt","Expand prompt to fullscreen"),"data-testid":"template-prompt-fullscreen",children:e.jsx(Vt,{size:14})})]}),P?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:A=>{A.key==="Escape"&&(A.preventDefault(),f(!1))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsx("div",{className:"prompt-override-fullscreen-title",children:n("agentPrompts.titles.editPrompt","Edit Prompt")}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>f(!1),"data-testid":"template-prompt-collapse",children:[e.jsx(Xs,{size:14}),n("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:"template-prompt-fullscreen","aria-label":n("agentPrompts.ariaLabels.templatePromptFullscreen","Template prompt - fullscreen"),className:"prompt-template-prompt-textarea",value:u.prompt,onChange:A=>j(G=>({...G,prompt:A.target.value})),placeholder:n("agentPrompts.placeholders.prompt","Enter the system prompt for this template..."),rows:30,autoFocus:!0,"data-testid":"template-prompt-input-fullscreen"}),e.jsx("div",{className:"prompt-override-footer",children:e.jsx("small",{className:"prompt-override-hint",children:n("agents.charactersCount","{{count}} characters",{count:u.prompt.length})})})]}):e.jsx("textarea",{id:"template-prompt",value:u.prompt,onChange:A=>j(G=>({...G,prompt:A.target.value})),placeholder:n("agentPrompts.placeholders.prompt","Enter the system prompt for this template..."),rows:8,className:"prompt-template-prompt-textarea","data-testid":"template-prompt-input"})]}),x&&e.jsx("div",{className:"prompt-template-error","data-testid":"template-error",children:x}),e.jsxs("div",{className:"prompt-template-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:U,"data-testid":"cancel-template-btn",children:n("agentPrompts.actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:re,"data-testid":"save-template-btn",children:v?n("agentPrompts.actions.create","Create"):n("agentPrompts.actions.save","Save")})]})]})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"builtin-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:n("agentPrompts.sections.builtinTemplates","Built-in Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:n("agentPrompts.descriptions.builtinTemplates","These templates are provided by Fusion and cannot be modified.")}),e.jsx("div",{className:"prompt-template-list",children:rt.map(A=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${A.id}`,children:[e.jsxs("div",{className:"prompt-template-card-header",children:[e.jsxs("div",{className:"prompt-template-card-info",children:[e.jsx("span",{className:"prompt-template-card-name",children:A.name}),e.jsx("span",{className:`prompt-template-badge-built-in ${Nt(A.role)}`,children:n("agentPrompts.badges.builtin","Built-in")}),e.jsx("span",{className:`prompt-template-badge-role ${Nt(A.role)}`,children:m(A.role)})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>fe("builtin",A.id),title:n("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":n("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:A.name}),"data-testid":`expand-view-${A.id}`,children:e.jsx(Vt,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:A.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:A.prompt})})]},A.id))})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"custom-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:n("agentPrompts.sections.customTemplates","Custom Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:n("agentPrompts.descriptions.customTemplates","Create custom templates to override built-in prompts for specific roles.")}),Q.length===0&&!v&&e.jsx("div",{className:"prompt-template-empty",children:n("agentPrompts.emptyStates.noCustomTemplates","No custom templates yet. Create one to get started.")}),Q.length>0&&e.jsx("div",{className:"prompt-template-list",children:Q.map(A=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${A.id}`,children:S===A.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsx("p",{children:n("agentPrompts.confirmations.deleteTemplate",'Delete "{{name}}"?',{name:A.name})}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>q(A.id),"data-testid":`confirm-delete-${A.id}`,children:n("agentPrompts.actions.delete","Delete")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>E(null),"data-testid":`cancel-delete-${A.id}`,children:n("agentPrompts.actions.cancel","Cancel")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"prompt-template-card-header",children:[e.jsxs("div",{className:"prompt-template-card-info",children:[e.jsx("span",{className:"prompt-template-card-name",children:A.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:n("agentPrompts.badges.custom","Custom")}),e.jsx("span",{className:`prompt-template-badge-role ${Nt(A.role)}`,children:m(A.role)}),Pe(A.id)&&e.jsx("span",{className:"prompt-template-badge-override",children:n("agentPrompts.badges.overridesBuiltin","Overrides built-in")})]}),e.jsxs("div",{className:"prompt-template-card-actions",children:[e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>fe("custom",A.id),title:n("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":n("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:A.name}),"data-testid":`expand-view-${A.id}`,children:e.jsx(Vt,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>T(A),title:n("agentPrompts.titles.edit","Edit"),"aria-label":n("agentPrompts.ariaLabels.editTemplate","Edit {{name}}",{name:A.name}),"data-testid":`edit-${A.id}`,children:e.jsx(rs,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>E(A.id),title:n("agentPrompts.titles.delete","Delete"),"aria-label":n("agentPrompts.ariaLabels.deleteTemplate","Delete {{name}}",{name:A.name}),"data-testid":`delete-${A.id}`,children:e.jsx(ls,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:A.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:A.prompt})})]})},A.id))}),!v&&h===null&&e.jsxs("button",{type:"button",className:"btn btn-primary prompt-template-add-btn",onClick:$,"data-testid":"add-template-btn",children:[e.jsx(as,{size:14}),n("agentPrompts.actions.addCustomTemplate","Add Custom Template")]})]}),ae&&e.jsxs("div",{ref:X,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:A=>{A.key==="Escape"&&(A.preventDefault(),W(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[ae.name,e.jsx("span",{className:`prompt-template-badge-role ${Nt(ae.role)}`,children:m(ae.role)})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>W(null),"data-testid":`collapse-view-${ae.id}`,children:[e.jsx(Xs,{size:14}),n("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:ae.prompt})]})]}),i==="assignments"&&e.jsxs("div",{className:"prompt-manager-assignments-tab","data-testid":"assignments-tab",children:[e.jsx("p",{className:"prompt-assignments-desc",children:n("agentPrompts.descriptions.assignments","Assign specific templates to agent roles. When a role has an assignment, that template will be used instead of the default built-in.")}),e.jsx("div",{className:"prompt-role-assignment-list",children:rr.map(A=>{const G=V(A),se=ne[A]??"",ce=G.find(z=>z.id===se),B=!!se;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${A}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:`prompt-role-badge ${Nt(A)}`,children:m(A)}),B&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[ce?.name??n("agentPrompts.labels.custom","Custom")," (",n("agentPrompts.labels.overridesDefault","overrides default"),")"]})]}),e.jsxs("select",{className:"prompt-role-select",value:se,onChange:z=>F(A,z.target.value),"data-testid":`select-${A}`,children:[e.jsx("option",{value:"",children:n("agentPrompts.options.useDefault","Use default")}),G.map(z=>e.jsxs("option",{value:z.id,children:[z.name,Pe(z.id)?` (${n("agentPrompts.labels.builtIn","built-in")})`:` (${n("agentPrompts.labels.custom","custom")})`]},z.id))]})]},A)})}),Object.keys(ne).length>0&&e.jsxs("div",{className:"prompt-assignments-note",children:[e.jsxs("strong",{children:[n("agentPrompts.labels.note","Note"),":"]})," ",n("agentPrompts.descriptions.assignmentNote","Role assignments are stored in the agentPrompts configuration. Custom templates override built-ins by ID.")]})]}),i==="overrides"&&e.jsxs("div",{className:"prompt-manager-overrides-tab","data-testid":"overrides-tab",children:[e.jsx("p",{className:"prompt-overrides-desc",children:n("agentPrompts.descriptions.overrides","Customize specific segments of AI agent prompts. Edits override built-in defaults. Use the Reset button to restore the original default for any prompt.")}),e.jsx("div",{className:"prompt-overrides-list",children:Object.values(nu).map(A=>{const G=A.key,se=s?.[G]??"",ce=se!=="",B=C.has(G);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${G}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("button",{type:"button",className:"prompt-override-info",onClick:()=>pe(G),children:[e.jsx("span",{className:"prompt-override-name",children:A.name}),e.jsx("code",{className:"prompt-override-key",children:G}),ce&&e.jsx("span",{className:"prompt-override-badge",children:n("agentPrompts.badges.customized","customized")})]}),e.jsxs("div",{className:"prompt-override-header-actions",children:[B&&e.jsx("button",{type:"button",className:"prompt-override-fullscreen-btn",onClick:z=>{z.stopPropagation(),ge(G)},"aria-label":n("agentPrompts.ariaLabels.expandToFullscreen","Expand to fullscreen"),"data-testid":`fullscreen-${G}`,children:e.jsx(Vt,{size:14})}),e.jsx("button",{type:"button",className:"prompt-override-expand-btn","aria-label":B?n("agentPrompts.ariaLabels.collapse","Collapse"):n("agentPrompts.ariaLabels.expand","Expand"),"data-testid":`expand-${G}`,onClick:z=>{z.stopPropagation(),pe(G)},children:B?e.jsx(Ao,{size:16}):e.jsx(To,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:A.description}),B&&(y===G?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:z=>{z.key==="Escape"&&(z.preventDefault(),p(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[A.name,e.jsx("code",{className:"prompt-override-key",children:G})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>p(null),"data-testid":`collapse-fullscreen-${G}`,children:[e.jsx(Xs,{size:14}),n("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:`prompt-${G}-fullscreen`,"aria-label":n("agentPrompts.ariaLabels.promptOverrideFullscreen","{{name}} prompt override ({{key}}) - fullscreen",{name:A.name,key:G}),className:"prompt-override-textarea",value:se,onChange:z=>{K(G,z.target.value)},placeholder:`Default: ${A.defaultContent.slice(0,100)}${A.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${G}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ce&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>R(G),"data-testid":`reset-fullscreen-${G}`,children:n("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ce?n("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):n("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:A.defaultContent.length})})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${G}`,"aria-label":n("agentPrompts.ariaLabels.promptOverride","{{name}} prompt override ({{key}})",{name:A.name,key:G}),className:"prompt-override-textarea",value:se,onChange:z=>{K(G,z.target.value)},placeholder:n("agentPrompts.placeholders.promptDefault","Default: {{preview}}",{preview:A.defaultContent.slice(0,100)+(A.defaultContent.length>100?"...":"")}),rows:4,"data-testid":`override-input-${G}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ce&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:z=>{z.stopPropagation(),R(G)},"data-testid":`reset-${G}`,children:n("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ce?n("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):n("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:A.defaultContent.length})})]})]}))]},G)})})]})]})]})}function Aa({message:a,onOpenWorkflowSettings:t}){const{t:s}=Z("app");return e.jsxs("div",{className:"settings-moved-stub",role:"note",children:[e.jsx("p",{className:"settings-moved-stub__message",children:a}),e.jsx("button",{type:"button",className:"settings-moved-stub__action",onClick:t,disabled:!t,children:s("settings.movedStub.openWorkflowSettings","Open workflow settings")})]})}function ou({scopeBanner:a,form:t,setForm:s,onOpenWorkflowSettings:c}){const{t:n}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.nav.prompts","Prompts")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{children:n("settings.prompts.surfaceExplanation","Use this section for agent role system prompt templates, role assignments, and global PromptKey segment overrides. Per-workflow step prompts for prompt and gate nodes are edited in the Workflow Editor. No default — unset (built-in role prompts apply until overridden).")})}),e.jsx(Aa,{message:n("settings.prompts.workflowPromptsRedirect","Per-workflow step prompts for prompt and gate nodes live in the Workflow Editor."),onOpenWorkflowSettings:c}),e.jsx(iu,{value:t.agentPrompts,onChange:m=>{s(i=>({...i,agentPrompts:m}))},promptOverrides:t.promptOverrides,onPromptOverridesChange:m=>{s(i=>({...i,promptOverrides:m}))}})]})}function cu({scopeBanner:a,form:t,setForm:s,projectId:c,addToast:n,prefixError:m,setPrefixError:i,projectTrackingRepoOptions:r,projectTrackingRepoLoading:h,projectTrackingRepoError:k,onQuickChatButtonModeChange:v}){const{t:d}=Z("app"),[u,j]=o.useState([]);o.useEffect(()=>{let p=!1;return An(c,{includeDisabledBuiltins:!0}).then(P=>{p||j(P.filter(f=>f.id.startsWith("builtin:")&&f.kind!=="fragment"))}).catch(()=>{p||j([])}),()=>{p=!0}},[c]);const[x,b]=o.useState([]);o.useEffect(()=>{let p=!1;return An(c).then(P=>{p||b(P.filter(f=>f.kind!=="fragment"))}).catch(()=>{p||b([])}),()=>{p=!0}},[c]);const S=t.aiUndoTaskWorkflowId??"builtin:review-heavy",E=S===""||x.some(p=>p.id===S),C=o.useMemo(()=>{const p=Array.isArray(t.enabledBuiltinWorkflowIds)?t.enabledBuiltinWorkflowIds:void 0;return new Set(p??u.map(P=>P.id))},[u,t.enabledBuiltinWorkflowIds]),L=(p,P)=>{s(f=>{const J=u.map(Q=>Q.id),W=new Set(Array.isArray(f.enabledBuiltinWorkflowIds)?f.enabledBuiltinWorkflowIds:J);P?W.add(p):W.delete(p);const X=J.filter(Q=>W.has(Q));return{...f,enabledBuiltinWorkflowIds:X.length===J.length?void 0:X}})},y=()=>{window.confirm(d("settings.general.clearLocalDataConfirm","Clear all cached data and UI preferences stored in this browser? This frees space used by stale chat, task, and board caches. Your tasks and project settings are safe (stored server-side). The dashboard will reload."))&&(Io(),window.location.reload())};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:d("settings.general.general","General")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskPrefix",children:d("settings.general.taskPrefix","Task Prefix")}),e.jsx("input",{id:"taskPrefix",type:"text",placeholder:d("settings.general.fN","FN"),value:t.taskPrefix||"",onChange:p=>{const P=p.target.value;s(f=>({...f,taskPrefix:P||void 0})),P&&!/^[A-Z]{1,5}$/.test(P)?i(d("settings.general.prefixMustBe15UppercaseLetters","Prefix must be 1–5 uppercase letters")):i(null)}}),m&&e.jsx("small",{className:"field-error",children:m}),!m&&e.jsx("small",{children:d("settings.general.prefixForNewTaskIDsEGKB","Prefix for new task IDs (e.g. KB, PROJ). No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx(Mo,{projectId:c,addToast:n}),e.jsx("small",{children:d("settings.general.newTasksInheritThisCustomWorkflowsStepsOverridable","New tasks inherit this custom workflow's steps (overridable per task). No default — unset (built-in default workflow).")})]}),u.length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:d("settings.general.fusionWorkflows","Fusion workflows")}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:u.map(p=>e.jsxs("label",{htmlFor:`builtin-workflow-${p.id}`,className:"checkbox-label",children:[e.jsx("input",{id:`builtin-workflow-${p.id}`,type:"checkbox",checked:C.has(p.id),onChange:P=>L(p.id,P.target.checked)}),e.jsx(Ro,{workflowId:p.id,decorative:!0}),e.jsx("span",{children:p.name})]},p.id))}),e.jsx("small",{children:d("settings.general.disabledFusionWorkflowsAreHiddenFromWorkflow","Disabled Fusion workflows are hidden from workflow pickers. Existing tasks that already use one continue to resolve. Default: all built-in workflows enabled (unset).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"aiUndoTaskWorkflowId",children:d("settings.general.aiUndoTaskWorkflow","AI-undo task workflow")}),e.jsxs("select",{id:"aiUndoTaskWorkflowId",className:"select","data-testid":"ai-undo-workflow-select",value:S,onChange:p=>s(P=>({...P,aiUndoTaskWorkflowId:p.target.value})),children:[e.jsx("option",{value:"",children:d("settings.general.aiUndoTaskWorkflowInherit","Inherit project default workflow")}),x.map(p=>e.jsx("option",{value:p.id,children:p.name},p.id)),!E&&e.jsx("option",{value:S,children:S})]}),e.jsx("small",{children:d("settings.general.aiUndoTaskWorkflowHelp",'Workflow assigned to AI-undo (revert) tasks, which reverse already-shipped code and warrant stricter review. Choose "Inherit project default workflow" to leave them on the project default. Default: review-heavy.')})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"ephemeralAgentsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"ephemeralAgentsEnabled",type:"checkbox",checked:t.ephemeralAgentsEnabled!==!1,onChange:p=>s(P=>({...P,ephemeralAgentsEnabled:p.target.checked}))}),d("settings.general.useEphemeralTaskWorkerAgents"," Use ephemeral task-worker agents ")]}),e.jsxs("small",{children:[d("settings.general.whenEnabledDefaultFusionSpawnsShortLived"," When enabled (default), Fusion spawns short-lived "),e.jsx("code",{children:"executor-FN-XXXX"}),d("settings.general.agentsToRunEachTaskWhenDisabledOnly"," agents to run each task. When disabled, only permanent agents execute tasks and the scheduler auto-assigns work using the agent reporting chain. Tasks with no eligible permanent agent stay queued. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"ephemeralAgentsCanCreateTasks",className:"checkbox-label",children:[e.jsx("input",{id:"ephemeralAgentsCanCreateTasks",type:"checkbox",checked:t.ephemeralAgentsCanCreateTasks!==!1,onChange:p=>s(P=>({...P,ephemeralAgentsCanCreateTasks:p.target.checked}))}),d("settings.general.allowEphemeralAgentsToCreateTasks"," Allow ephemeral agents to create tasks ")]}),e.jsx("small",{children:d("settings.general.allowEphemeralAgentsToCreateTasksHint","When enabled (default), ephemeral task-worker agents can open follow-up tasks via fn_task_create. When disabled, only humans and permanent agents can create tasks; ephemeral callers are rejected.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"workspaceMode",className:"checkbox-label",children:[e.jsx("input",{id:"workspaceMode",type:"checkbox",checked:t.workspaceMode===!0,onChange:p=>s(P=>({...P,workspaceMode:p.target.checked}))}),d("settings.general.workspaceMode"," Workspace mode (multi-repo) ")]}),e.jsx("small",{children:d("settings.general.workspaceModeHint","When enabled, the project root is treated as a workspace containing multiple git sub-repos. Tasks run per-sub-repo and no git repo is created at the root. Disable for single-repo projects. No default — unset (disabled).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"allowAbsoluteFileBrowserPaths",className:"checkbox-label",children:[e.jsx("input",{id:"allowAbsoluteFileBrowserPaths",type:"checkbox",checked:t.allowAbsoluteFileBrowserPaths===!0,onChange:p=>s(P=>({...P,allowAbsoluteFileBrowserPaths:p.target.checked}))}),d("settings.general.allowAbsoluteFileBrowserPaths"," Allow absolute file-browser paths ")]}),e.jsx("small",{children:d("settings.general.allowAbsoluteFileBrowserPathsHint","When enabled, slash-prefixed paths such as /tmp can be opened in the workspace file browser. Windows drive-letter paths remain blocked, and other path validators are unchanged. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"completionDocumentationMode",children:d("settings.general.completionDocumentationAutomation","Completion Documentation Automation")}),e.jsxs("select",{id:"completionDocumentationMode",value:t.completionDocumentationMode||"off",onChange:p=>s(P=>({...P,completionDocumentationMode:p.target.value})),children:[e.jsx("option",{value:"off",children:d("settings.general.off","Off")}),e.jsx("option",{value:"changeset",children:d("settings.general.requireChangesetChangesetMd","Require changeset (.changeset/*.md)")}),e.jsx("option",{value:"changelog",children:d("settings.general.requireChangelogUpdateExistingChangelog","Require changelog update (existing changelog)")})]}),e.jsxs("small",{children:[d("settings.general.controlsHowFutureTaskSpecsHandleReleaseNote"," Controls how future task specs handle release-note artifacts at completion. Use changeset mode for repositories that follow "),e.jsx("code",{children:".changeset"}),d("settings.general.workflowsOrChangelogModeWhenContributorsShouldUpdate"," workflows, or changelog mode when contributors should update an existing changelog file. Default: off. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"quickChatButtonMode",children:d("settings.general.quickChatLauncher","Quick Chat launcher")}),e.jsxs("select",{id:"quickChatButtonMode",className:"select",value:t.quickChatButtonMode??(t.showQuickChatFAB?"floating":"off"),onChange:p=>s(P=>{const f=p.target.value;return v?.(f),{...P,quickChatButtonMode:f,showQuickChatFAB:f==="floating"}}),children:[e.jsx("option",{value:"floating",children:d("settings.general.quickChatLauncherFloating","Floating button")}),e.jsx("option",{value:"footer",children:d("settings.general.quickChatLauncherFooter","Footer button")}),e.jsx("option",{value:"off",children:d("settings.general.off","Off")})]}),e.jsx("small",{children:d("settings.general.quickChatLauncherHint","Choose whether Quick Chat opens from the draggable floating button, a footer button beside Terminal, or stays hidden. Default: off (hidden).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"quickChatCloseOnOutsideClick",className:"checkbox-label",children:[e.jsx("input",{id:"quickChatCloseOnOutsideClick",type:"checkbox",checked:t.quickChatCloseOnOutsideClick!==!1,onChange:p=>s(P=>({...P,quickChatCloseOnOutsideClick:p.target.checked}))}),d("settings.general.quickChatCloseOnOutsideClick","Close Quick Chat on outside click")]}),e.jsx("small",{children:d("settings.general.quickChatCloseOnOutsideClickHint","When enabled, clicking outside the Quick Chat window closes it. Disable to keep it open until you close it explicitly. Default: enabled.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.general.chatHistory","Chat history")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"showTaskChatsInCommonFeed",className:"checkbox-label",children:[e.jsx("input",{id:"showTaskChatsInCommonFeed",type:"checkbox",checked:t.showTaskChatsInCommonFeed===!0,onChange:p=>s(P=>({...P,showTaskChatsInCommonFeed:p.target.checked}))}),d("settings.general.showTaskChatsInCommonFeed","Show task chats in common Chat feed")]}),e.jsx("small",{children:d("settings.general.showTaskChatsInCommonFeedHint","When enabled, populated task-detail Chat conversations appear in the common Direct feed. Empty task chats stay hidden. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatAutoCleanupDays",children:d("settings.general.autoCleanupOldChats","Auto-cleanup old chats")}),e.jsxs("select",{id:"chatAutoCleanupDays",className:"select",value:t.chatAutoCleanupDays??0,onChange:p=>s(P=>({...P,chatAutoCleanupDays:Number(p.target.value)||0})),children:[e.jsx("option",{value:0,children:d("settings.general.off","Off")}),e.jsx("option",{value:7,children:d("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:d("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:d("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:d("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:d("settings.general.90Days","90 days")})]}),e.jsx("small",{children:d("settings.general.deleteChatSessionsAndRoomsThatHaveBeen","Delete chat sessions and rooms that have been idle for this many days. Default: Off.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mailAutoCleanupDays",children:d("settings.general.autoPruneOldMail","Auto-prune old mail")}),e.jsxs("select",{id:"mailAutoCleanupDays",className:"select",value:t.mailAutoCleanupDays??0,onChange:p=>s(P=>({...P,mailAutoCleanupDays:Number(p.target.value)||0})),children:[e.jsx("option",{value:0,children:d("settings.general.off","Off")}),e.jsx("option",{value:7,children:d("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:d("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:d("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:d("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:d("settings.general.90Days","90 days")})]}),e.jsx("small",{children:d("settings.general.deleteInboxOutboxMessagesOlderThanThisMany","Delete inbox/outbox messages older than this many days. Default: Off. 7 days is the suggested setting.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"operationalLogRetentionDays",children:d("settings.general.operationalLogRetention","Operational log retention")}),e.jsxs("select",{id:"operationalLogRetentionDays",className:"select",value:t.operationalLogRetentionDays??30,onChange:p=>s(P=>({...P,operationalLogRetentionDays:Number(p.target.value)||0})),children:[e.jsx("option",{value:0,children:d("settings.general.off","Off")}),e.jsx("option",{value:7,children:d("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:d("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:d("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:d("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:d("settings.general.90Days","90 days")})]}),e.jsx("small",{children:d("settings.general.loweringThisWindowMeansReliabilityMetricsChartsAnd"," Lowering this window means Reliability metrics/charts and the Activity feed will not show history older than the selected range. Per-task task detail history is unaffected. Default: 30 days. ")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.general.chatRooms","Chat Rooms")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomRecentVerbatimMessages",children:d("settings.general.recentVerbatimRoomMessages","Recent verbatim room messages")}),e.jsx("input",{id:"chatRoomRecentVerbatimMessages",type:"number",min:"1",className:"input",placeholder:d("settings.general.25","25"),value:t.chatRoomRecentVerbatimMessages??"",onChange:p=>s(P=>({...P,chatRoomRecentVerbatimMessages:Number(p.target.value)||void 0}))}),e.jsx("small",{children:d("settings.general.numberOfMostRecentChatRoomMessagesKept","Number of most-recent chat-room messages kept verbatim in the responder transcript. Older messages are compacted into a summary block. Default: 25.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomCompactionFetchLimit",children:d("settings.general.roomCompactionFetchLimit","Room compaction fetch limit")}),e.jsx("input",{id:"chatRoomCompactionFetchLimit",type:"number",min:"1",className:"input",placeholder:d("settings.general.200","200"),value:t.chatRoomCompactionFetchLimit??"",onChange:p=>s(P=>({...P,chatRoomCompactionFetchLimit:Number(p.target.value)||void 0}))}),e.jsx("small",{children:d("settings.general.upperBoundOnMessagesFetchedFromTheRoom","Upper bound on messages fetched from the room store for compaction consideration. Default: 200.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomSummaryMaxChars",children:d("settings.general.roomSummaryMaxCharacters","Room summary max characters")}),e.jsx("input",{id:"chatRoomSummaryMaxChars",type:"number",min:"200",className:"input",placeholder:d("settings.general.3000","3000"),value:t.chatRoomSummaryMaxChars??"",onChange:p=>s(P=>({...P,chatRoomSummaryMaxChars:Number(p.target.value)||void 0}))}),e.jsx("small",{children:d("settings.general.hardCapOnTheSynthesizedEarlierRoomContext",'Hard cap on the synthesized "Earlier room context" summary block. Default: 3000.')})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.general.capacityRiskBanner","Capacity Risk Banner")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"capacityRiskBannerEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"capacityRiskBannerEnabled",type:"checkbox",checked:t.capacityRiskBannerEnabled===!0,onChange:p=>s(P=>({...P,capacityRiskBannerEnabled:p.target.checked}))}),d("settings.general.showCapacityRiskBanner"," Show capacity risk banner ")]}),e.jsx("small",{children:d("settings.general.warnOnTheBoardWhenTodoWorkExceeds","Warn on the board when todo work exceeds the threshold and no idle agents are available. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"capacityRiskTodoThresholdGeneral",children:d("settings.general.todoThreshold","Todo threshold")}),e.jsx("input",{id:"capacityRiskTodoThresholdGeneral",type:"number",min:0,className:"input",value:t.capacityRiskTodoThreshold??20,onChange:p=>s(P=>({...P,capacityRiskTodoThreshold:p.target.value===""?0:Math.max(0,Number.parseInt(p.target.value,10)||0)}))}),e.jsx("small",{children:d("settings.general.bannerFiresWhenTodoCountIsStrictlyGreater","Banner fires when todo count is strictly greater than this value (default 20). Applies when the banner is enabled.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.general.gitHubTracking","GitHub Tracking")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubTrackingMode",children:d("settings.general.defaultTrackingModeForNewTasks","Default tracking mode for new tasks")}),e.jsxs("select",{id:"githubTrackingMode",className:"select",value:t.githubTrackingEnabledByDefault?"new-tasks":"off",onChange:p=>s(P=>({...P,githubTrackingEnabledByDefault:p.target.value==="new-tasks"})),children:[e.jsx("option",{value:"off",children:d("settings.general.offDefault","Off (default)")}),e.jsx("option",{value:"new-tasks",children:d("settings.general.onForNewTasks","On for new tasks")})]}),e.jsx("small",{children:d("settings.general.controlsWhetherNewlyCreatedTasksHaveGitHubIssue"," Controls whether newly created tasks have GitHub issue tracking enabled by default. Individual tasks can still override this from the task detail modal. ")}),e.jsxs("small",{children:[d("settings.general.trackingIssuesUseThisTaskAposSTitle"," Tracking issues use this task's title. If a task has no title yet, Fusion can summarize its description using the title summarization model in Project Models. "),!t.autoSummarizeTitles&&!t.useAiMergeCommitSummary&&!t.githubTrackingEnabledByDefault?d("settings.general.enableSummarizationInProjectModelsToConfigureThatModel"," Enable summarization in Project Models to configure that model."):""]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"githubLinkImportedIssuesToTracking",className:"checkbox-label",children:[e.jsx("input",{id:"githubLinkImportedIssuesToTracking",type:"checkbox",checked:t.githubLinkImportedIssuesToTracking===!0,onChange:p=>s(P=>({...P,githubLinkImportedIssuesToTracking:p.target.checked}))}),d("settings.general.alwaysLinkImportedGitHubIssuesToTracking"," Always link imported GitHub issues to GitHub tracking ")]}),e.jsx("small",{children:d("settings.general.whenEnabledImportedGitHubIssuesUseTheirSource","When enabled, GitHub issue imports become tracked tasks that adopt the source issue. This does not turn GitHub tracking on for ordinary new tasks. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"projectGithubTrackingDefaultRepoGeneral",children:d("settings.general.projectDefaultTrackingRepo","Project default tracking repo")}),e.jsx(Nr,{id:"projectGithubTrackingDefaultRepoGeneral",ariaLabel:"Project default tracking repo",value:t.githubTrackingDefaultRepo??"",options:r,loading:h,error:k??void 0,placeholder:d("settings.general.ownerRepo","owner/repo"),onChange:p=>s(P=>({...P,githubTrackingDefaultRepo:p||void 0}))}),e.jsx("small",{children:d("settings.general.defaultRepoUsedWhenCreatingGitHubIssuesFor","Default repo used when creating GitHub issues for tracked tasks. Falls back to the global default if blank.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"githubTrackingDedupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"githubTrackingDedupEnabled",type:"checkbox",checked:t.githubTrackingDedupEnabled!==!1,onChange:p=>s(P=>({...P,githubTrackingDedupEnabled:p.target.checked}))}),d("settings.general.searchTheTrackingRepoForLikelyDuplicatesBefore"," Search the tracking repo for likely duplicates before opening a new issue ")]}),e.jsx("small",{children:d("settings.general.whenEnabledFusionChecksOpenAndClosedIssues"," When enabled, Fusion checks open and closed issues in the target repo for likely duplicates (using File Scope paths and key symptoms) before creating a new tracking issue. Uncheck to always create a new issue. Default: enabled. ")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.general.gitLabConfiguration","GitLab Configuration")}),e.jsxs("details",{className:"settings-gitlab-disclosure","data-testid":"project-gitlab-configuration-disclosure",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"settings-gitlab-disclosure__title",children:d("settings.general.gitLabConfiguration","GitLab Configuration")}),e.jsxs("label",{className:"checkbox-label settings-gitlab-disclosure__toggle",htmlFor:"gitlabEnabled",onClick:p=>p.stopPropagation(),children:[e.jsx("input",{id:"gitlabEnabled",type:"checkbox",checked:t.gitlabEnabled!==!1,onChange:p=>s(P=>({...P,gitlabEnabled:p.target.checked}))}),d("settings.general.enableGitLabIntegration","Enable GitLab integration")]})]}),e.jsx("small",{className:"settings-description",children:t.gitlabEnabled===!1?d("settings.general.gitLabDisabledHint","GitLab API imports, comments, close/reopen, and refresh operations are disabled. Saved URLs and tokens remain stored for re-enable."):d("settings.general.gitLabEnabledHint","Configure GitLab.com or self-managed GitLab URLs. Blank values inherit global fallbacks and then GitLab.com. No default — unset (unset behaves as enabled until explicitly disabled).")}),e.jsxs("div",{className:"settings-gitlab-disclosure__body","aria-disabled":t.gitlabEnabled===!1,children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"gitlabInstanceUrl",children:d("settings.general.gitLabInstanceUrl","GitLab instance URL")}),e.jsx("input",{id:"gitlabInstanceUrl",className:"input",type:"url",placeholder:"https://gitlab.com",value:t.gitlabInstanceUrl??"",disabled:t.gitlabEnabled===!1,onChange:p=>s(P=>({...P,gitlabInstanceUrl:p.target.value||void 0}))}),e.jsx("small",{children:d("settings.general.gitLabInstanceUrlHint","Blank uses GitLab.com or the global default. Set an absolute http:// or https:// URL for self-managed GitLab, such as https://gitlab.example.com/gitlab.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"gitlabApiBaseUrl",children:d("settings.general.gitLabApiBaseUrlOptional","GitLab API base URL (optional / advanced)")}),e.jsx("input",{id:"gitlabApiBaseUrl",className:"input",type:"url",placeholder:"https://gitlab.com/api/v4",value:t.gitlabApiBaseUrl??"",disabled:t.gitlabEnabled===!1,onChange:p=>s(P=>({...P,gitlabApiBaseUrl:p.target.value||void 0}))}),e.jsx("small",{children:d("settings.general.gitLabApiBaseUrlHint","Blank derives <instance>/api/v4. Override only when a self-managed GitLab API is served from a different absolute http:// or https:// URL.")})]})]})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.general.browserData","Browser Data")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:d("settings.general.clearLocalData","Clear local data")}),e.jsx("small",{children:d("settings.general.clearLocalDataHint","Remove cached board snapshots, chat threads, and UI preferences stored in this browser. Frees space when the dashboard runs low on browser storage. Your tasks and project settings are stored server-side and are not affected.")}),e.jsx("div",{style:{marginTop:"var(--space-sm)"},children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:y,children:d("settings.general.clearLocalDataButton","Clear local data")})})]})]})}const ua="builtin:coding",du=[{id:"planning",providerId:"planningProvider",modelId:"planningModelId",label:"Plan/Triage Model",help:"Provider and model used when planning or triaging tasks. Leave unset to inherit from the workflow default."},{id:"execution",providerId:"executionProvider",modelId:"executionModelId",label:"Executor Model",help:"Provider and model used while executing workflow steps. Leave unset to inherit from the workflow default."},{id:"validator",providerId:"validatorProvider",modelId:"validatorModelId",label:"Reviewer Model",help:"Provider and model used for workflow review or validation lanes. Leave unset to inherit from the workflow default."},{id:"planning-fallback",providerId:"planningFallbackProvider",modelId:"planningFallbackModelId",label:"Planning Fallback Model",help:"Fallback provider and model used when the primary Plan/Triage model cannot be used."},{id:"validator-fallback",providerId:"validatorFallbackProvider",modelId:"validatorFallbackModelId",label:"Reviewer Fallback Model",help:"Fallback provider and model used when the primary Reviewer model cannot be used."},{id:"title-summarizer-fallback",providerId:"titleSummarizerFallbackProvider",modelId:"titleSummarizerFallbackModelId",label:"Title Summarizer Fallback Model",help:"Fallback provider and model used when the primary Title Summarizer model cannot be used."}];function uu(a){const t=new Map((a??[]).map(s=>[s.id,s]));return du.filter(s=>{const c=t.get(s.providerId),n=t.get(s.modelId);return c?.type==="string"&&n?.type==="string"})}function mu(a,t){const s=a[t.providerId],c=a[t.modelId];return typeof s=="string"&&typeof c=="string"&&s&&c?`${s}/${c}`:""}function hu(a,t){return Object.is(a,t)?!0:Array.isArray(a)&&Array.isArray(t)?a.length===t.length&&a.every((s,c)=>Object.is(s,t[c])):!1}class Ar extends Error{rejections;constructor(t){super("Workflow model lane settings were rejected"),this.name="WorkflowLaneFlushRejection",this.rejections=t}}function pu({scopeBanner:a,form:t,setForm:s,models:c,projectId:n,onOpenWorkflowSettings:m,registerWorkflowLaneSaver:i}){const{t:r}=Z("app"),{modelLanes:h,getLaneStatus:k,getLaneValue:v,updateLaneValue:d,resetLaneValue:u,availableModels:j,modelsLoading:x,favoriteProviders:b,favoriteModels:S,onToggleFavorite:E,onToggleModelFavorite:C,editingPresetId:L,setEditingPresetId:y,presetDraft:p,setPresetDraft:P,onSavePresetDraft:f,confirmDelete:J}=c,W=t.modelPresets||[],X=W.map(M=>({id:M.id,name:M.name})),Q=new Set(Object.values(t.defaultPresetBySize||{}).filter(Boolean)),ne=typeof t.defaultWorkflowId=="string"&&t.defaultWorkflowId.trim()?t.defaultWorkflowId:ua,[ae,V]=o.useState(ne),[$,T]=o.useState(null),[U,re]=o.useState(!1),[q,F]=o.useState({}),[K,R]=o.useState({}),[pe,ge]=o.useState([]),fe=o.useRef(0),be=Object.keys(q).length>0;o.useEffect(()=>{V(ne)},[ne]),o.useEffect(()=>{if(!n){T(null),F({}),R({}),ge([]);return}const M=++fe.current;re(!0),Promise.all([Eo(ae,n),Fo(ae,n)]).then(([I,H])=>{if(fe.current!==M)return;T(H),F({}),R({});const w="settings"in I.ir?I.ir.settings:void 0;ge(uu(w))}).catch(I=>{if(fe.current===M){if(I instanceof Tn&&I.status===404&&ae!==ua){V(ua);return}T({stored:{},effective:{},orphaned:[]}),ge([])}}).finally(()=>{fe.current===M&&re(!1)})},[n,ae]);const Pe=o.useMemo(()=>({...$?.effective??{},...Object.fromEntries(Object.entries(q).filter(([,M])=>M!==null))}),[$,q]),A=o.useCallback((M,I)=>{R(H=>{const w={...H};return delete w[M.providerId],delete w[M.modelId],w}),F(H=>{if(!I)return{...H,[M.providerId]:null,[M.modelId]:null};const w=I.indexOf("/");return w<=0?H:{...H,[M.providerId]:I.slice(0,w),[M.modelId]:I.slice(w+1)}})},[]),G=o.useCallback(M=>{A(M,"")},[A]),se=o.useCallback(async()=>{if(!n||!be)return;const M={...q},I=Object.keys(M);try{const H=await Lo(ae,M,n);T(H),F(w=>{const D={...w};for(const O of I)hu(w[O],M[O])&&delete D[O];return D}),R({})}catch(H){if(H instanceof Tn&&H.status===400&&H.details){const w=H.details.rejections??[];if(w.length>0)throw R(Object.fromEntries(w.map(D=>[D.settingId,D]))),new Ar(w)}throw H}},[n,be,ae,q]);o.useEffect(()=>(i?.(se),()=>i?.(null)),[i,se]);const ce=h.filter(M=>["default","summarization"].includes(M.laneId)),B=M=>M.laneId==="default"?"Project Default Model":M.laneId==="summarization"?"Project Summarization Model":M.label,z=M=>M.laneId==="default"?"Project-wide default AI model used when no more specific task or project lane override is set.":M.laneId==="summarization"?"Model used for title auto-summarization, merge commit summaries, GitHub tracking issue titles, and PR title/body generation.":M.helperText;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.projectModels.tokenCap","Token Cap")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"tokenCap",children:r("settings.projectModels.tokenCap","Token Cap")}),e.jsxs("div",{className:"settings-token-cap-row",children:[e.jsx("input",{id:"tokenCap",type:"number",placeholder:r("settings.projectModels.noCap","No cap"),value:t.tokenCap??"",onChange:M=>{const I=M.target.value;s(H=>({...H,tokenCap:I?parseInt(I,10):null}))}}),t.tokenCap!=null&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:r("settings.projectModels.resetToDefaultNoCap","Reset to default (no cap)"),onClick:()=>s(M=>({...M,tokenCap:null})),style:{whiteSpace:"nowrap"},children:r("settings.projectModels.reset"," Reset ")})]}),e.jsx("small",{children:r("settings.projectModels.automaticallyCompactContextWhenApproachingThisTokenCount","Automatically compact context when approaching this token count. Leave empty for no cap (compact only on overflow errors). Set a number to proactively compact when reaching this token count. No default — unset (no cap).")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:r("settings.projectModels.modelLanes","Model Lanes")}),e.jsx("p",{className:"settings-description",children:r("settings.projectModels.overrideGlobalModelSettingsAtTheProjectLevel"," Override global model settings at the project level. Each lane controls a specific AI usage context. Unset lanes inherit from the corresponding global lane. The Project Default Model is the fallback for this project when a more specific lane is unset. ")}),x?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Ze,{label:r("settings.projectModels.loadingAvailableModels","Loading available models…")})}):j.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:r("settings.projectModels.noModelsAvailableConfigureAuthenticationFirst"," No models available. Configure authentication first. ")}):e.jsx(e.Fragment,{children:ce.map(M=>{const I=k(M),H=v(M),w=I==="overridden",D=B(M);return e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`${M.laneId}Model`,children:D}),e.jsx("span",{className:`settings-lane-badge ${w?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:w?"Explicitly set for this project":"Inherited from global settings",children:w?"Override (Project)":"Inherited (Global)"})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(Xe,{id:`${M.laneId}Model`,label:D,models:j,value:H,onChange:O=>d(M,O),placeholder:M.laneId==="default"?"Use global default":"Use global",favoriteProviders:b,onToggleFavorite:E,favoriteModels:S,onToggleModelFavorite:C,menuWidth:"readable"})}),w&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:r("settings.projectModels.resetToInheritFromGlobal","Reset to inherit from global"),onClick:()=>u(M),style:{whiteSpace:"nowrap"},children:r("settings.projectModels.reset"," Reset ")})]}),e.jsxs("small",{children:[z(M),r("settings.projectModels.fallsBackTo"," Falls back to: "),M.fallbackOrder,"."]})]},M.laneId)})}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:r("settings.projectModels.defaultWorkflowModelLanes","Default workflow model lanes")}),e.jsxs("p",{className:"settings-description",children:[r("settings.movedStub.modelLanes","Per-phase model lanes (execution, planning, reviewer, and their fallbacks) now live on the workflow."),r("settings.projectModels.theseProjectOverridesApplyToTheActiveDefault"," These project overrides apply to the active default workflow. ")]}),n?U?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Ze,{label:r("settings.projectModels.loadingWorkflowModelLanes","Loading workflow model lanes…")})}):j.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:r("settings.projectModels.noModelsAvailableConfigureAuthenticationBeforeSelectingWorkflow"," No models available. Configure authentication before selecting workflow model lanes. ")}):e.jsxs(e.Fragment,{children:[pe.map(M=>{const I=mu(Pe,M),H=Object.prototype.hasOwnProperty.call(q,M.providerId)?q[M.providerId]!==null:!!($?.stored&&(Object.prototype.hasOwnProperty.call($.stored,M.providerId)||Object.prototype.hasOwnProperty.call($.stored,M.modelId))),w=K[M.providerId]?.message??K[M.modelId]?.message;return e.jsxs("div",{className:"form-group","data-testid":`workflow-model-lane-${M.id}`,children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`workflow-${M.id}-model`,children:M.label}),e.jsx("span",{className:`settings-lane-badge ${H?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:H?"Explicitly set for this project workflow":"Inherited from workflow defaults",children:H?"Override (Project)":"Inherited (Workflow)"})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(Xe,{id:`workflow-${M.id}-model`,label:M.label,models:j,value:I,onChange:D=>A(M,D),placeholder:r("settings.projectModels.useWorkflowDefault","Use workflow default"),defaultOptionLabel:"Use workflow default",favoriteProviders:b,onToggleFavorite:E,favoriteModels:S,onToggleModelFavorite:C,menuWidth:"readable"})}),H&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:r("settings.projectModels.resetToInheritFromWorkflow","Reset to inherit from workflow"),onClick:()=>G(M),style:{whiteSpace:"nowrap"},children:r("settings.projectModels.reset"," Reset ")})]}),e.jsx("small",{children:M.help}),w?e.jsx("small",{className:"settings-error","data-testid":`workflow-model-lane-error-${M.id}`,children:w}):null]},M.id)}),m?e.jsx("div",{className:"settings-model-lane-actions","aria-label":r("settings.projectModels.defaultWorkflowModelLaneActions","Default workflow model lane actions"),children:e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:m,children:r("settings.projectModels.advancedWorkflowPolicy"," Advanced workflow policy ")})}):null]}):e.jsx("div",{className:"settings-empty-state settings-muted",children:r("settings.projectModels.openAProjectToEditWorkflowModelLanes","Open a project to edit workflow model lanes.")}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:r("settings.projectModels.modelPresets","Model Presets")}),e.jsxs("div",{className:"form-group settings-model-presets",children:[e.jsx("label",{children:r("settings.projectModels.configuredPresets","Configured presets")}),W.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:r("settings.projectModels.noPresetsConfiguredYet","No presets configured yet.")}):e.jsx("div",{className:"settings-preset-list",children:W.map(M=>{const I=Do(M),H=`${I.executorValue||"default"} / ${I.validatorValue||"default"}`;return e.jsxs("div",{className:"settings-preset-item",children:[e.jsxs("div",{className:"settings-preset-item-meta",children:[e.jsx("strong",{children:M.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:H})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{y(M.id),P({...M})},children:r("settings.projectModels.edit"," Edit ")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:async()=>{Q.has(M.id)&&!await J({title:r("settings.models.deletePresetTitle","Delete Preset"),message:r("settings.models.deletePresetMessage",'Preset "{{name}}" is used in auto-selection. Delete it anyway?',{name:M.name}),danger:!0})||(s(w=>({...w,modelPresets:(w.modelPresets||[]).filter(D=>D.id!==M.id),defaultPresetBySize:Object.fromEntries(Object.entries(w.defaultPresetBySize||{}).filter(([,D])=>D!==M.id))})),L===M.id&&(y(null),P(null)))},children:r("settings.projectModels.delete"," Delete ")})]})]},M.id)})}),p?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{y(null),P({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:r("settings.projectModels.addPreset"," Add Preset ")})})]}),p?e.jsxs("div",{className:"form-group settings-preset-editor",children:[e.jsx("label",{children:r("settings.projectModels.presetEditor","Preset editor")}),e.jsxs("div",{className:"settings-preset-editor-fields",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-name",children:r("settings.projectModels.name","Name")}),e.jsx("input",{id:"preset-name",type:"text",value:p.name,onChange:M=>{const I=M.target.value;P(H=>H&&{...H,name:I})}})]}),j.length===0?e.jsx("small",{children:r("settings.projectModels.noModelsAvailableConfigureAuthenticationFirst2","No models available. Configure authentication first.")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-executor-model",children:r("settings.projectModels.executorModel","Executor model")}),e.jsx(Xe,{id:"preset-executor-model",label:"Preset executor model",models:j,value:p.executorProvider&&p.executorModelId?`${p.executorProvider}/${p.executorModelId}`:"",onChange:M=>{if(!M){P(H=>H&&{...H,executorProvider:void 0,executorModelId:void 0});return}const I=M.indexOf("/");P(H=>H&&{...H,executorProvider:M.slice(0,I),executorModelId:M.slice(I+1)})},placeholder:r("settings.projectModels.useDefault","Use default"),favoriteProviders:b,onToggleFavorite:E,favoriteModels:S,onToggleModelFavorite:C,menuWidth:"readable"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:r("settings.projectModels.reviewerModel","Reviewer model")}),e.jsx(Xe,{id:"preset-validator-model",label:"Preset reviewer model",models:j,value:p.validatorProvider&&p.validatorModelId?`${p.validatorProvider}/${p.validatorModelId}`:"",onChange:M=>{if(!M){P(H=>H&&{...H,validatorProvider:void 0,validatorModelId:void 0});return}const I=M.indexOf("/");P(H=>H&&{...H,validatorProvider:M.slice(0,I),validatorModelId:M.slice(I+1)})},placeholder:r("settings.projectModels.useDefault","Use default"),favoriteProviders:b,onToggleFavorite:E,favoriteModels:S,onToggleModelFavorite:C,menuWidth:"readable"})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:f,children:r("settings.models.savePreset","Save preset")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{y(null),P(null)},children:r("settings.actions.cancel","Cancel")})]})]}):null,e.jsxs("div",{className:"form-group settings-preset-auto-select",children:[e.jsxs("label",{htmlFor:"autoSelectModelPreset",className:"checkbox-label",children:[e.jsx("input",{id:"autoSelectModelPreset",type:"checkbox",checked:t.autoSelectModelPreset||!1,onChange:M=>s(I=>({...I,autoSelectModelPreset:M.target.checked}))}),r("settings.projectModels.autoSelectPresetBasedOnTaskSize"," Auto-select preset based on task size ")]}),e.jsx("small",{children:r("settings.projectModels.autoSelectModelPresetHint","Default: disabled.")})]}),t.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(M=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${M}`,children:M==="S"?"Small tasks (S):":M==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${M}`,value:t.defaultPresetBySize?.[M]||"",onChange:I=>{const H=I.target.value||void 0;s(w=>({...w,defaultPresetBySize:{...w.defaultPresetBySize||{},[M]:H}}))},children:[e.jsx("option",{value:"",children:r("settings.projectModels.noPreset","No preset")}),X.map(I=>e.jsx("option",{value:I.id,children:I.name},I.id))]})]},M))}):null,e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:r("settings.projectModels.aITitleAndGitCommitMessageSummarization"," AI Title and Git Commit Message Summarization ")}),e.jsx("p",{className:"settings-description",children:r("settings.projectModels.configuresTheModelUsedForTwoShortSummary"," Configures the model used for two short-summary jobs: auto-generating task titles from long descriptions, and generating merge commit summaries from step commits and diff stats. ")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoSummarizeTitles",className:"checkbox-label",children:[e.jsx("input",{id:"autoSummarizeTitles",type:"checkbox",checked:t.autoSummarizeTitles||!1,onChange:M=>s(I=>({...I,autoSummarizeTitles:M.target.checked}))}),r("settings.projectModels.autoSummarizeLongDescriptionsAsTitles"," Auto-summarize long descriptions as titles ")]}),e.jsx("small",{children:r("settings.projectModels.whenEnabledTasksCreatedWithoutATitleBut"," When enabled, tasks created without a title but with descriptions over 200 characters will automatically get an AI-generated title (max 60 characters). The same model is also used to generate fallback merge commit message bodies when the branch's commit log is empty (e.g. squash merges with no unique commits), and GitHub tracking issue titles when a tracked task has no title yet. Default: disabled. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"useAiMergeCommitSummary",className:"checkbox-label",children:[e.jsx("input",{id:"useAiMergeCommitSummary",type:"checkbox",checked:t.useAiMergeCommitSummary||!1,onChange:M=>s(I=>({...I,useAiMergeCommitSummary:M.target.checked}))}),r("settings.projectModels.aIMergeCommitSummaries"," AI merge commit summaries ")]}),e.jsx("small",{children:r("settings.projectModels.whenEnabledMergeCommitMessagesIncludeAnAI"," When enabled, merge commit messages include an AI-generated subject plus body summary (narrative + bullets + diff-stat) instead of just listing step commit subjects. Uses the title summarization model. Default: enabled. ")})]}),(t.autoSummarizeTitles||t.useAiMergeCommitSummary||t.githubTrackingEnabledByDefault||!1)&&e.jsx("p",{className:"settings-description",children:r("settings.movedStub.summarizerModelInline","The summarization model lane above controls title auto-summarization, merge commit summaries, GitHub tracking titles, and PR metadata generation.")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"prTitlePromptInstructions",children:r("settings.projectModels.prTitlePromptInstructions","PR title prompt guidance")}),e.jsx("textarea",{id:"prTitlePromptInstructions",value:t.prTitlePromptInstructions||"",onChange:M=>s(I=>({...I,prTitlePromptInstructions:M.target.value})),rows:3,placeholder:r("settings.projectModels.prTitlePromptInstructionsPlaceholder","Example: Use conventional-commit style and keep titles under 72 characters.")}),e.jsx("small",{children:r("settings.projectModels.prTitlePromptInstructionsHelp","Guides the AI-generated Create PR title. Leave blank to use the default PR metadata prompt. No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"prDescriptionPromptInstructions",children:r("settings.projectModels.prDescriptionPromptInstructions","PR description prompt guidance")}),e.jsx("textarea",{id:"prDescriptionPromptInstructions",value:t.prDescriptionPromptInstructions||"",onChange:M=>s(I=>({...I,prDescriptionPromptInstructions:M.target.value})),rows:4,placeholder:r("settings.projectModels.prDescriptionPromptInstructionsPlaceholder","Example: Emphasize operator-facing behavior and list verification commands exactly.")}),e.jsx("small",{children:r("settings.projectModels.prDescriptionPromptInstructionsHelp","Guides the AI-generated Create PR summary, changes, and testing sections. Leave blank to use the default PR metadata prompt. No default — unset.")})]})]})}const lr=1440*60*1e3,gu=2;function ir({title:a,caption:t,badgeLabel:s,scope:c}){return e.jsxs("div",{className:"settings-scope-group",children:[e.jsxs("div",{className:"settings-scope-group-header",children:[e.jsx("h5",{className:"settings-section-heading",children:a}),e.jsx("span",{className:`settings-scope-badge settings-scope-badge--${c}`,children:s})]}),e.jsx("small",{className:"settings-scope-caption",children:t})]})}function bu({scopeBanner:a,form:t,setForm:s,globalMaxConcurrent:c,concurrencyLoading:n=!1,onGlobalMaxConcurrentChange:m,onOverlapIgnorePathChange:i,onOpenOverlapPathPicker:r,onRemoveOverlapIgnorePath:h,onAddOverlapIgnorePath:k,onOpenWorkflowSettings:v}){const{t:d}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:d("settings.scheduling.scheduling","Scheduling")}),e.jsx(ir,{scope:"global",title:d("settings.scheduling.scopeGlobalTitle","Global — applies to all projects"),caption:d("settings.scheduling.scopeGlobalCaption","Shared by every project on this machine."),badgeLabel:d("settings.scheduling.scopeBadgeGlobal","Global")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalMaxConcurrent",children:d("settings.scheduling.globalMaxConcurrent","Global Max Concurrent")}),e.jsx("input",{id:"globalMaxConcurrent",type:"number",min:0,max:1e4,disabled:n,value:c??"",onChange:u=>{const j=u.target.value;m(j===""?void 0:Number(j))}}),e.jsx("small",{className:"form-text text-muted",children:d("settings.scheduling.maximumConcurrentAgentsAcrossAllProjects","Maximum concurrent agents across all projects. Default: 4.")})]}),e.jsx("div",{className:"settings-section-divider"}),e.jsx(ir,{scope:"project",title:d("settings.scheduling.scopeProjectTitle","This project"),caption:d("settings.scheduling.scopeProjectCaption","Only affects the currently selected project."),badgeLabel:d("settings.scheduling.scopeBadgeProject","Project")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxConcurrent",children:d("settings.scheduling.maxConcurrentTasks","Max Concurrent Tasks")}),e.jsx("input",{id:"maxConcurrent",type:"number",min:1,max:10,disabled:n,value:t.maxConcurrent??"",onChange:u=>{const j=u.target.value;s(x=>({...x,maxConcurrent:j===""?void 0:Number(j)}))}}),e.jsx("small",{children:d("settings.scheduling.maxConcurrentTasksHint","Default: 2.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxTriageConcurrent",children:d("settings.scheduling.maxTriageConcurrent","Max Triage Concurrent")}),e.jsx("input",{id:"maxTriageConcurrent",type:"number",min:1,max:10,disabled:n,value:t.maxTriageConcurrent??"",onChange:u=>{const j=u.target.value;s(x=>({...x,maxTriageConcurrent:j===""?void 0:Number(j)}))}}),e.jsx("small",{children:d("settings.scheduling.maximumConcurrentPlanningAgents","Maximum concurrent planning agents. Default: 2.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pollIntervalMs",children:d("settings.scheduling.pollIntervalMs","Poll Interval (ms)")}),e.jsx("input",{id:"pollIntervalMs",type:"number",min:5e3,step:1e3,value:t.pollIntervalMs??"",onChange:u=>{const j=u.target.value;s(x=>({...x,pollIntervalMs:j===""?void 0:Number(j)}))}}),e.jsx("small",{children:d("settings.scheduling.pollIntervalMsHint","Default: 15000 (15 seconds).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"heartbeatScopeDiscipline",children:d("settings.scheduling.heartbeatScopeDiscipline","Heartbeat Scope Discipline")}),e.jsxs("select",{id:"heartbeatScopeDiscipline",className:"select",value:t.heartbeatScopeDiscipline??"strict",onChange:u=>{s(j=>({...j,heartbeatScopeDiscipline:u.target.value}))},children:[e.jsx("option",{value:"strict",children:d("settings.scheduling.strictDefault","Strict (default)")}),e.jsx("option",{value:"lite",children:d("settings.scheduling.lite","Lite")}),e.jsx("option",{value:"off",children:d("settings.scheduling.off","Off")})]}),e.jsx("small",{children:d("settings.scheduling.strictCoordinationFocusedHigherPerTickTokensLite","Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"engineerBacklogAutoClaim",className:"checkbox-label",children:[e.jsx("input",{id:"engineerBacklogAutoClaim",type:"checkbox",checked:t.engineerBacklogAutoClaim===!0,onChange:u=>s(j=>({...j,engineerBacklogAutoClaim:u.target.checked}))}),d("settings.scheduling.letEngineerAgentsAutoClaimBacklogTasks"," Let engineer agents auto-claim backlog tasks ")]}),e.jsx("small",{children:d("settings.scheduling.backlogNoTaskAutoClaimIsExecutorOnly","Backlog/no-task auto-claim is executor-only by default. Enable to let engineer-role agents auto-claim unowned backlog tasks; explicit routing and delegation are unchanged. Default: off.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskStuckTimeoutMs",children:d("settings.scheduling.stuckTaskTimeoutMinutes","Stuck Task Timeout (minutes)")}),e.jsx("input",{id:"taskStuckTimeoutMs",type:"number",min:1,step:1,value:t.taskStuckTimeoutMs?Math.round(t.taskStuckTimeoutMs/6e4):"",onChange:u=>{const j=u.target.value,x=Number(j);s(b=>({...b,taskStuckTimeoutMs:j&&x>0?x*6e4:void 0}))}}),e.jsx("small",{children:d("settings.scheduling.timeoutInMinutesForDetectingStuckTasksWhen","Timeout in minutes for detecting stuck tasks. When a task's agent session shows no activity for longer than this duration, the task is terminated and retried. Leave empty to disable. Suggested: 10. Default: 10 minutes (600000ms).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"staleHighFanoutBlockerAgeThresholdMs",children:d("settings.scheduling.staleHighFanOutEscalationHours","Stale High Fan-out Escalation (hours)")}),e.jsx("input",{id:"staleHighFanoutBlockerAgeThresholdMs",type:"number",min:1,step:1,value:t.staleHighFanoutBlockerAgeThresholdMs?Math.round(t.staleHighFanoutBlockerAgeThresholdMs/36e5):"",onChange:u=>{const j=u.target.value,x=Number(j);s(b=>({...b,staleHighFanoutBlockerAgeThresholdMs:j&&x>0?x*36e5:void 0}))}}),e.jsx("small",{children:d("settings.scheduling.escalateHighFanOutBlockersOnlyAfterThey","Escalate high fan-out blockers only after they remain in in-progress or in-review for this many hours (age source: columnMovedAt, fallback updatedAt). Default: 2 hours.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"preserveProgressOnStuckRequeue",className:"checkbox-label",children:[e.jsx("input",{id:"preserveProgressOnStuckRequeue",type:"checkbox",checked:t.preserveProgressOnStuckRequeue!==!1,onChange:u=>s(j=>({...j,preserveProgressOnStuckRequeue:u.target.checked}))}),d("settings.scheduling.preserveStepProgressOnStuckTaskRequeue"," Preserve step progress on stuck-task requeue ")]}),e.jsx("small",{children:d("settings.scheduling.whenTheStuckDetectorKillsAndReQueues","When the stuck detector kills and re-queues a task, keep completed step statuses so the agent can resume from where it left off. Disable to reset every step to pending on each stuck retry. Default: enabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"specStalenessEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"specStalenessEnabled",type:"checkbox",checked:t.specStalenessEnabled||!1,onChange:u=>s(j=>({...j,specStalenessEnabled:u.target.checked}))}),d("settings.scheduling.enablePlanStalenessEnforcement"," Enable plan staleness enforcement ")]}),e.jsx("small",{children:d("settings.scheduling.whenEnabledTasksWithStalePlansPROMPTMd","When enabled, tasks with stale plans (PROMPT.md older than the threshold) are automatically sent back to planning for replanning. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"specStalenessMaxAgeMs",children:d("settings.scheduling.staleSpecThresholdHours","Stale Spec Threshold (hours)")}),e.jsx("input",{id:"specStalenessMaxAgeMs",type:"number",min:0,step:1,value:t.specStalenessMaxAgeMs!==void 0?Math.round(t.specStalenessMaxAgeMs/36e5):"",onChange:u=>{const j=u.target.value,x=Number(j);s(b=>({...b,specStalenessMaxAgeMs:j!==""?x*36e5:void 0}))},disabled:!t.specStalenessEnabled}),e.jsx("small",{children:d("settings.scheduling.maximumAgeInHoursBeforeAPlanIs","Maximum age in hours before a plan is considered stale. Default: 6 hours.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoArchiveDoneTasksEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoArchiveDoneTasksEnabled",type:"checkbox",checked:t.autoArchiveDoneTasksEnabled??!0,onChange:u=>s(j=>({...j,autoArchiveDoneTasksEnabled:u.target.checked}))}),d("settings.scheduling.enableAutomaticTaskArchiving"," Enable automatic task archiving ")]}),e.jsx("small",{children:d("settings.scheduling.completedTasksOlderThanTheThresholdAreMoved","Completed tasks older than the threshold are moved out of the active task database. Default: enabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoArchiveDoneAfterMs",children:d("settings.scheduling.archiveCompletedTasksAfterDays","Archive Completed Tasks After (days)")}),e.jsx("input",{id:"autoArchiveDoneAfterMs",type:"number",min:1,step:1,value:t.autoArchiveDoneAfterMs!==void 0?Math.round(t.autoArchiveDoneAfterMs/lr):gu,onChange:u=>{const j=u.target.value,x=Number(j);s(b=>({...b,autoArchiveDoneAfterMs:j===""?void 0:x*lr}))},disabled:t.autoArchiveDoneTasksEnabled===!1}),e.jsx("small",{children:d("settings.scheduling.numberOfDaysATaskCanStayIn","Number of days a task can stay in Done before it is archived. Default: 2 days (48 hours).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"archiveAgentLogMode",children:d("settings.scheduling.archiveAgentLog","Archive Agent Log")}),e.jsxs("select",{id:"archiveAgentLogMode",value:t.archiveAgentLogMode??"compact",onChange:u=>s(j=>({...j,archiveAgentLogMode:u.target.value})),disabled:t.autoArchiveDoneTasksEnabled===!1,children:[e.jsx("option",{value:"compact",children:d("settings.scheduling.compactSummaryAndRecentEntries","Compact summary and recent entries")}),e.jsx("option",{value:"none",children:d("settings.scheduling.doNotArchiveAgentLogs","Do not archive agent logs")}),e.jsx("option",{value:"full",children:d("settings.scheduling.fullAgentLog","Full agent log")})]}),e.jsx("small",{children:d("settings.scheduling.compactModeKeepsArchiveSizeLowWhilePreserving","Compact mode keeps archive size low while preserving recent agent activity for context. Default: compact.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxStuckKills",children:d("settings.scheduling.maxStuckRetries","Max Stuck Retries")}),e.jsx("input",{id:"maxStuckKills",type:"number",min:1,step:1,value:t.maxStuckKills??"",onChange:u=>{const j=u.target.value,x=Number(j);s(b=>({...b,maxStuckKills:j&&x>0?x:void 0}))}}),e.jsx("small",{children:d("settings.scheduling.maximumStuckDetectorRetriesBeforeATaskIs","Maximum stuck-detector retries before a task is marked failed. Default: 6.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"groupOverlappingFiles",className:"checkbox-label",children:[e.jsx("input",{id:"groupOverlappingFiles",type:"checkbox",checked:t.groupOverlappingFiles,onChange:u=>s(j=>({...j,groupOverlappingFiles:u.target.checked}))}),d("settings.scheduling.serializeTasksWithOverlappingFiles"," Serialize tasks with overlapping files ")]}),e.jsx("small",{children:d("settings.scheduling.whenEnabledTasksThatModifyTheSameFiles","When enabled, tasks that modify the same files are queued serially to avoid merge conflicts. Default: enabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"ignoreHiddenOverlapPaths",className:"checkbox-label",children:[e.jsx("input",{id:"ignoreHiddenOverlapPaths",type:"checkbox",checked:t.ignoreHiddenOverlapPaths!==!1,onChange:u=>s(j=>({...j,ignoreHiddenOverlapPaths:u.target.checked}))}),d("settings.scheduling.ignoreHiddenDotPathsInOverlapChecks"," Ignore hidden dot paths in overlap checks ")]}),e.jsx("small",{children:d("settings.scheduling.ignoreHiddenDotPathsHelp","When enabled, overlap checks ignore hidden path segments such as .fusion/, .changeset/, .github/, .env, and nested .cache/ directories. Uncheck to restore legacy counting for stricter serialization. Default: enabled.")})]}),e.jsxs("div",{className:"form-group settings-overlap-ignore-group",children:[e.jsx("label",{children:d("settings.scheduling.ignoredOverlapPaths","Ignored overlap paths")}),e.jsxs("small",{children:[d("settings.scheduling.optionalFileOrDirectoryPathsToIgnoreWhen"," No default — unset (empty). Optional file or directory paths to ignore when overlap serialization is enabled. Paths are project-relative (for example "),e.jsx("code",{children:"docs/"}),d("settings.scheduling.or"," or "),e.jsx("code",{children:"generated/*"}),d("settings.scheduling.closeParenPeriod",").")]}),e.jsx("div",{className:"settings-overlap-ignore-list",children:(t.overlapIgnorePaths&&t.overlapIgnorePaths.length>0?t.overlapIgnorePaths:[""]).map((u,j)=>e.jsxs("div",{className:"settings-overlap-ignore-row",children:[e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{type:"text",value:u,placeholder:d("settings.scheduling.docs","docs/"),onChange:x=>i(j,x.target.value)}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>r(j),"aria-label":`Browse path for ignored overlap entry ${j+1}`,children:d("settings.scheduling.browse"," Browse ")})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>h(j),disabled:(t.overlapIgnorePaths??[]).length===0&&j===0,children:d("settings.scheduling.remove"," Remove ")})]},`overlap-ignore-${j}`))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:k,children:d("settings.scheduling.addIgnoredPath"," Add ignored path ")})]}),e.jsx("div",{className:"settings-section-divider"}),e.jsx("h5",{className:"settings-section-heading",children:d("settings.scheduling.stepExecution","Step Execution")}),e.jsx(Aa,{message:d("settings.movedStub.stepExecution","Step execution settings (run steps in new sessions, max parallel steps) now live on the workflow."),onOpenWorkflowSettings:v})]})}function fu({scopeBanner:a,form:t,setForm:s}){const{t:c}=Z("app"),n=t.evalSettings??{},m=n.enabled??!1;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.scheduledEvals.scheduledEvals","Scheduled Evals")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"scheduled-evals-enabled",className:"checkbox-label",children:[e.jsx("input",{id:"scheduled-evals-enabled",type:"checkbox",checked:m,onChange:i=>s(r=>({...r,evalSettings:{...r.evalSettings??{},enabled:i.target.checked}}))}),c("settings.scheduledEvals.enableScheduledEvalRunsForThisProject"," Enable scheduled eval runs for this project ")]}),e.jsx("small",{children:c("settings.scheduledEvals.enabledHint","Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-interval",children:c("settings.scheduledEvals.intervalMs","Interval (ms)")}),e.jsx("input",{id:"scheduled-evals-interval",className:"input",type:"number",min:6e4,max:6048e5,step:1e3,disabled:!m,value:n.intervalMs??864e5,onChange:i=>s(r=>({...r,evalSettings:{...r.evalSettings??{},intervalMs:i.target.value===""?void 0:Number(i.target.value)}}))}),e.jsx("small",{children:c("settings.scheduledEvals.intervalMsHint","Default: 86400000 (24 hours).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-provider",children:c("settings.scheduledEvals.evaluatorProvider","Evaluator Provider")}),e.jsx("input",{id:"scheduled-evals-provider",className:"input",value:n.evaluatorProvider??"",onChange:i=>s(r=>({...r,evalSettings:{...r.evalSettings??{},evaluatorProvider:i.target.value.trim()===""?void 0:i.target.value}})),placeholder:c("settings.scheduledEvals.openai","openai")}),e.jsx("small",{children:c("settings.scheduledEvals.evaluatorProviderHint","No default — unset (inherits the project validator lane provider).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-model",children:c("settings.scheduledEvals.evaluatorModel","Evaluator Model")}),e.jsx("input",{id:"scheduled-evals-model",className:"input",value:n.evaluatorModelId??"",onChange:i=>s(r=>({...r,evalSettings:{...r.evalSettings??{},evaluatorModelId:i.target.value.trim()===""?void 0:i.target.value}})),placeholder:c("settings.scheduledEvals.gpt5","gpt-5")}),e.jsx("small",{className:"form-text text-muted",children:c("settings.scheduledEvals.leaveProviderAndModelBlankToInheritThe"," Leave provider and model blank to inherit the project validator lane model settings. No default — unset. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-follow-up-policy",children:c("settings.scheduledEvals.followUpPolicy","Follow-up Policy")}),e.jsxs("select",{id:"scheduled-evals-follow-up-policy",className:"select",disabled:!m,value:n.followUpPolicy??"suggest-only",onChange:i=>s(r=>({...r,evalSettings:{...r.evalSettings??{},followUpPolicy:i.target.value}})),children:[e.jsx("option",{value:"disabled",children:c("settings.scheduledEvals.disabled","Disabled")}),e.jsx("option",{value:"suggest-only",children:c("settings.scheduledEvals.suggestOnly","Suggest only")}),e.jsx("option",{value:"auto-create",children:c("settings.scheduledEvals.autoCreateTasks","Auto-create tasks")})]}),e.jsx("small",{children:c("settings.scheduledEvals.followUpPolicyHint","Default: suggest only.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-retention-days",children:c("settings.scheduledEvals.retentionDays","Retention (days)")}),e.jsx("input",{id:"scheduled-evals-retention-days",className:"input",type:"number",min:1,max:365,step:1,disabled:!m,value:n.retentionDays??30,onChange:i=>s(r=>({...r,evalSettings:{...r.evalSettings??{},retentionDays:i.target.value===""?void 0:Number(i.target.value)}}))}),e.jsx("small",{children:c("settings.scheduledEvals.retentionDaysHint","Default: 30.")})]})]})}function vu(a,t){return a==="online"?t("settings.nodeRouting.statusOnline","Online"):a==="connecting"?t("settings.nodeRouting.statusConnecting","Connecting"):a==="error"?t("settings.nodeRouting.statusError","Error"):t("settings.nodeRouting.statusOffline","Offline")}function xu({scopeBanner:a,form:t,setForm:s,nodes:c}){const{t:n}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.nodeRouting.nodeRouting","Node Routing")}),e.jsx("p",{className:"settings-section-description",children:n("settings.nodeRouting.configureHowTasksAreRoutedToExecutionNodes","Configure how tasks are routed to execution nodes.")}),e.jsx("p",{className:"settings-node-routing-note",children:n("settings.nodeRouting.theseSettingsApplyAtTheProjectLevel","These settings apply at the project level.")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultNodeId",children:n("settings.nodeRouting.defaultExecutionNode","Default Execution Node")}),e.jsxs("select",{id:"defaultNodeId",className:"select",value:typeof t.defaultNodeId=="string"?t.defaultNodeId:"",onChange:m=>{const i=m.target.value;s(r=>({...r,defaultNodeId:i||void 0}))},children:[e.jsx("option",{value:"",children:n("settings.nodeRouting.localExecutionNoDefaultNode","Local execution (no default node)")}),c.map(m=>e.jsxs("option",{value:m.id,children:[m.name," (",vu(m.status,n),")"]},m.id))]}),(()=>{const m=c.find(i=>i.id===t.defaultNodeId);return m?e.jsxs("div",{className:"settings-node-status",children:[e.jsx("span",{children:n("settings.nodeRouting.selectedNode","Selected node:")}),e.jsx(Oo,{status:m.status,showLabel:!0})]}):null})(),e.jsx("small",{children:n("settings.nodeRouting.usedWhenATaskHasNoNodeOverride","Used when a task has no node override. Node status is shown for safer routing selection. No default — unset (local execution).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"unavailableNodePolicy",children:n("settings.nodeRouting.unavailableNodePolicy","Unavailable Node Policy")}),e.jsxs("select",{id:"unavailableNodePolicy",className:"select",value:t.unavailableNodePolicy==="fallback-local"?"fallback-local":"block",onChange:m=>s(i=>({...i,unavailableNodePolicy:m.target.value})),children:[e.jsx("option",{value:"block",children:n("settings.nodeRouting.blockExecution","Block execution")}),e.jsx("option",{value:"fallback-local",children:n("settings.nodeRouting.fallBackToLocal","Fall back to local")})]}),e.jsx("small",{children:n("settings.nodeRouting.unavailableNodePolicyHint","Default: block execution.")})]})]})}function yu({scopeBanner:a,form:t,setForm:s,gitRemotes:c,worktrunkInstall:n,worktrunkInstallVerified:m,onOpenWorktreesDirPicker:i,onWorktreeCopyFileChange:r,onRemoveWorktreeCopyFile:h,onAddWorktreeCopyFile:k,onOpenWorktreeCopyFilePicker:v,onOpenApprovals:d}){const{t:u}=Z("app"),j=(t.worktreeCopyFiles?.length??0)>0?t.worktreeCopyFiles??[]:[""];return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.worktrees.worktrees","Worktrees")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxWorktrees",children:u("settings.worktrees.maxWorktrees","Max Worktrees")}),e.jsx("input",{id:"maxWorktrees",type:"number",min:1,max:20,value:t.maxWorktrees??"",onChange:x=>{const b=x.target.value;s(S=>({...S,maxWorktrees:b===""?void 0:Number(b)}))}}),e.jsx("small",{children:u("settings.worktrees.limitsTotalGitWorktreesIncludingInReviewTasks","Limits total git worktrees including in-review tasks. Default: 4.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeInitCommand",children:u("settings.worktrees.worktreeInitCommand","Worktree Init Command")}),e.jsx("input",{id:"worktreeInitCommand",type:"text",placeholder:u("settings.worktrees.pnpmInstallFrozenLockfile","pnpm install --frozen-lockfile"),value:t.worktreeInitCommand||"",onChange:x=>s(b=>({...b,worktreeInitCommand:x.target.value}))}),e.jsx("small",{children:u("settings.worktrees.shellCommandToRunInEachNewWorktree","Shell command to run in each new worktree after creation. No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"recycleWorktrees",className:"checkbox-label",children:[e.jsx("input",{id:"recycleWorktrees",type:"checkbox",checked:t.recycleWorktrees,onChange:x=>s(b=>({...b,recycleWorktrees:x.target.checked}))}),u("settings.worktrees.recycleWorktrees"," Recycle worktrees ")]}),e.jsx("small",{children:u("settings.worktrees.offByDefaultOptInWhenEnabledCompleted","Off by default (opt-in). When enabled, completed task worktrees are returned to an idle pool instead of being deleted, preserving build caches for faster startup")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"showWorktreeGrouping",className:"checkbox-label",children:[e.jsx("input",{id:"showWorktreeGrouping",type:"checkbox",checked:t.showWorktreeGrouping===!0,onChange:x=>s(b=>({...b,showWorktreeGrouping:x.target.checked}))}),u("settings.worktrees.showWorktreeGrouping"," Show worktree grouping on the board ")]}),e.jsx("small",{children:u("settings.worktrees.showWorktreeGroupingHelp","Off by default. When enabled, WIP and processing columns always group tasks by worktree and show worktree names, including workflow-mode processing columns.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:u("settings.worktrees.filesToCopyIntoNewWorktrees","Files to copy into new worktrees")}),e.jsx("div",{className:"settings-overlap-ignore-list","data-testid":"worktree-copy-files-list",children:j.map((x,b)=>e.jsxs("div",{className:"settings-overlap-ignore-row",children:[e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{id:`worktreeCopyFile-${b}`,type:"text",className:"input",placeholder:u("settings.worktrees.copyFilePlaceholder",".env"),value:x,onChange:S=>r(b,S.target.value),"aria-label":u("settings.worktrees.copyFilePathLabel","File to copy into new worktrees")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v(b),"aria-label":u("settings.worktrees.browseCopyFile","Browse file to copy into new worktrees"),children:u("settings.worktrees.browse"," Browse ")})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>h(b),"aria-label":u("settings.worktrees.removeCopyFile","Remove copied worktree file"),children:u("settings.worktrees.remove","Remove")})]},b))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:k,children:u("settings.worktrees.addCopyFile","Add file")}),e.jsx("small",{children:u("settings.worktrees.copyFilesHelp","Optional. Repository-root-relative regular files are copied into fresh or pooled task worktrees before init commands run. Missing files or directories are skipped without exposing contents. Default: empty (no files copied).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"executorAllowSiblingBranchRename",className:"checkbox-label",children:[e.jsx("input",{id:"executorAllowSiblingBranchRename",type:"checkbox",checked:t.executorAllowSiblingBranchRename===!0,onChange:x=>s(b=>({...b,executorAllowSiblingBranchRename:x.target.checked}))}),u("settings.worktrees.allowSilentSiblingBranchRenameDuringExecutorConflicts"," Allow silent sibling branch rename during executor conflicts ")]}),e.jsxs("small",{children:[u("settings.worktrees.discouragedThisRestoresTheLegacyBehaviorWhereA"," Discouraged. This restores the legacy behavior where a live "),e.jsx("code",{children:"fusion/<task-id>"}),u("settings.worktrees.branchCollisionSilentlyForksWorkOntoSiblingBranches"," branch collision silently forks work onto sibling branches like "),e.jsx("code",{children:"-2"}),u("settings.worktrees.andCanHidePriorCommitsFromTheDefault"," and can hide prior commits from the default recovery flow. Default: disabled. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeNaming",children:u("settings.worktrees.worktreeNamingStyle","Worktree Naming Style")}),e.jsxs("select",{id:"worktreeNaming",value:t.worktreeNaming||"random",onChange:x=>s(b=>({...b,worktreeNaming:x.target.value})),disabled:t.recycleWorktrees,children:[e.jsx("option",{value:"random",children:u("settings.worktrees.randomNamesEGSwiftFalcon","Random names (e.g., swift-falcon)")}),e.jsx("option",{value:"task-id",children:u("settings.worktrees.taskIDEGFN042","Task ID (e.g., FN-042)")}),e.jsx("option",{value:"task-title",children:u("settings.worktrees.taskTitleEGFixLoginBug","Task title (e.g., fix-login-bug)")})]}),e.jsx("small",{children:t.recycleWorktrees?u("settings.worktrees.namingStyleNotApplicableWhenRecycling","Naming style is not applicable when recycling worktrees — pooled worktrees retain their existing names"):u("settings.worktrees.howToNameFreshWorktreeDirectories","How to name fresh worktree directories. Only applies when recycling is off. Default: random.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreesDir",children:u("settings.worktrees.worktreesDirectory","Worktrees Directory")}),e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{id:"worktreesDir",type:"text",placeholder:u("settings.worktrees.defaultsToWorktreesLeaveEmptyUnlessOverriding","Defaults to .worktrees — leave empty unless overriding"),value:t.worktreesDir||"",disabled:t.worktrunk?.enabled===!0,onChange:x=>s(b=>({...b,worktreesDir:x.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:i,"aria-label":u("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),disabled:t.worktrunk?.enabled===!0,children:u("settings.worktrees.browse"," Browse ")})]}),e.jsx("small",{children:t.worktrunk?.enabled===!0?"Disabled because Worktrunk integration is enabled — worktrunk manages the worktree directory layout. Disable worktrunk integration to use a custom directory.":e.jsxs(e.Fragment,{children:[u("settings.worktrees.optionalSupports"," Optional. Supports "),e.jsx("code",{children:"~"}),u("settings.worktrees.and"," and "),e.jsx("code",{children:"{repo}"}),u("settings.worktrees.defaultsTo",". Defaults to "),e.jsx("code",{children:"<projectRoot>/.worktrees"}),u("settings.worktrees.whenUnsetOnlyAffectsNewlyCreatedWorktrees"," when unset. Only affects newly-created worktrees. ")]})})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktreeRebaseBeforeMerge",className:"checkbox-label",children:[e.jsx("input",{id:"worktreeRebaseBeforeMerge",type:"checkbox",checked:t.worktreeRebaseBeforeMerge!==!1,onChange:x=>s(b=>({...b,worktreeRebaseBeforeMerge:x.target.checked}))}),u("settings.worktrees.rebaseFromRemoteBeforeMerge"," Rebase from remote before merge ")]}),e.jsx("small",{children:u("settings.worktrees.whenEnabledTheMergerFetchesFromTheConfigured","When enabled, the merger fetches from the configured remote and rebases the task branch onto the latest default-branch tip before merging — catching concurrent pushes from other collaborators or fusion workers. Any conflicts the rebase surfaces flow into the existing smart/AI resolve pipeline. Default: enabled.")})]}),t.worktreeRebaseBeforeMerge!==!1&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeRebaseRemote",children:u("settings.worktrees.rebaseRemote","Rebase Remote")}),e.jsxs("select",{id:"worktreeRebaseRemote",value:t.worktreeRebaseRemote??"",onChange:x=>s(b=>({...b,worktreeRebaseRemote:x.target.value||void 0})),children:[e.jsx("option",{value:"",children:u("settings.worktrees.useGitDefault","Use git default")}),c.map(x=>e.jsxs("option",{value:x.name,children:[x.name," (",x.fetchUrl,")"]},x.name))]}),e.jsxs("small",{children:[u("settings.worktrees.whichRemoteToFetchForThePreMerge",' Which remote to fetch for the pre-merge rebase. "Use git default" falls back to the remote configured for the default branch (typically '),e.jsx("code",{children:"origin"}),u("settings.worktrees.closeParenPeriod",").")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktreeRebaseLocalBase",className:"checkbox-label",children:[e.jsx("input",{id:"worktreeRebaseLocalBase",type:"checkbox",checked:t.worktreeRebaseLocalBase!==!1,onChange:x=>s(b=>({...b,worktreeRebaseLocalBase:x.target.checked}))}),u("settings.worktrees.alsoRebaseOntoLocalDefaultBranchHEAD"," Also rebase onto local default-branch HEAD ")]}),e.jsx("small",{children:u("settings.worktrees.inAdditionToTheRemoteRebaseAboveAlso"," In addition to the remote rebase above, also rebase the task branch onto the local default-branch HEAD (rootDir). This catches sibling tasks that merged locally but haven't been pushed yet — without it, two concurrent tasks where one deletes code can have the other silently re-introduce it via the fallback strategy. Enabled by default; only disable if it causes issues with your workflow. ")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:u("settings.worktrees.worktrunkIntegration","Worktrunk integration")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktrunkEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"worktrunkEnabled",type:"checkbox",checked:t.worktrunk?.enabled===!0,disabled:!m&&t.worktrunk?.enabled!==!0,onChange:x=>s(b=>({...b,worktrunk:{enabled:x.target.checked,binaryPath:b.worktrunk?.binaryPath??"",onFailure:b.worktrunk?.onFailure??"fail"}}))}),u("settings.worktrees.enableWorktrunkIntegration"," Enable worktrunk integration ")]}),e.jsxs("small",{children:[u("settings.worktrees.disabledByDefaultOptInWhenEnabledFusion"," Disabled by default (opt-in). When enabled, Fusion shells out to "),e.jsx("code",{children:"worktrunk"}),u("settings.worktrees.forWorktreeCreateSyncPruneAndRemoveOperations"," for worktree create, sync, prune, and remove operations and follows worktrunk's directory layout. ")]}),!m&&t.worktrunk?.enabled!==!0&&e.jsx("small",{className:"settings-muted",children:u("settings.worktrees.installTheWorktrunkBinaryBelowToEnableThis","Install the worktrunk binary below to enable this integration.")})]}),e.jsxs("div",{className:"form-group","data-testid":"worktrunk-install-affordance",children:[n.status==="installed"&&e.jsxs("small",{className:"settings-muted",children:[u("settings.worktrees.worktrunk"," worktrunk "),n.version??"",u("settings.worktrees.installedAt"," installed at "),n.installPath??"~/.fusion/bin/worktrunk"]}),(n.status==="missing"||n.status==="installing")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void n.requestInstall(),disabled:n.requesting||n.status==="installing",children:u("settings.worktrees.installWorktrunk","Install worktrunk binary")}),e.jsx("small",{className:"settings-muted",children:u("settings.worktrees.enableWorktrunkAndRequestApprovalToInstallThe","Enable worktrunk and request approval to install the pinned release.")})]}),n.status==="pending-approval"&&e.jsxs(e.Fragment,{children:[e.jsx("small",{className:"settings-muted",children:u("settings.worktrees.awaitingApproval","Awaiting approval — open Approvals to continue.")}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>d?.(n.pendingApprovalId),children:u("settings.worktrees.openApprovals","Open Approvals")})]}),(n.status==="denied"||n.status==="failed")&&e.jsxs(e.Fragment,{children:[e.jsx("small",{style:{color:"var(--color-error)"},children:n.error??"Worktrunk install failed."}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void n.requestInstall(),children:u("settings.worktrees.tryAgain","Try again")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktrunkBinaryPath",children:u("settings.worktrees.worktrunkBinaryPath","Worktrunk binary path")}),e.jsx("input",{id:"worktrunkBinaryPath",type:"text",className:"input",placeholder:u("settings.worktrees.autoDetectFusionBinWorktrunkOrPATH","auto-detect (~/.fusion/bin/worktrunk or $PATH)"),value:t.worktrunk?.binaryPath??"",disabled:t.worktrunk?.enabled!==!0,onChange:x=>s(b=>({...b,worktrunk:{enabled:b.worktrunk?.enabled===!0,binaryPath:x.target.value,onFailure:b.worktrunk?.onFailure??"fail"}}))}),e.jsx("small",{children:u("settings.worktrees.optionalLeaveBlankToAutoResolveFusionWill","Optional. Leave blank to auto-resolve; Fusion will offer to install on first use.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktrunkOnFailure",children:u("settings.worktrees.worktrunkFailureBehavior","Worktrunk failure behavior")}),e.jsxs("select",{id:"worktrunkOnFailure",className:"select",value:t.worktrunk?.onFailure??"fail",disabled:t.worktrunk?.enabled!==!0,onChange:x=>s(b=>({...b,worktrunk:{enabled:b.worktrunk?.enabled===!0,binaryPath:b.worktrunk?.binaryPath??"",onFailure:x.target.value}})),children:[e.jsx("option",{value:"fail",children:u("settings.worktrees.failAndPauseTheTaskDefault","Fail and pause the task (default)")}),e.jsx("option",{value:"fallback-native",children:u("settings.worktrees.fallBackToFusionsNativeWorktreeBackend","Fall back to Fusion's native worktree backend")})]}),e.jsxs("small",{children:[e.jsx("code",{children:"fail"}),u("settings.worktrees.stopsOnWorktrunkErrorsForExplicitOperatorRecovery"," stops on worktrunk errors for explicit operator recovery; "),e.jsx("code",{children:"fallback-native"}),u("settings.worktrees.keepsProgressMovingBySwitchingToFusionApos"," keeps progress moving by switching to Fusion's built-in worktree backend. ")]})]})]})}function ku({scopeBanner:a,form:t,setForm:s}){const{t:c}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.commands.commands","Commands")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"testCommand",children:c("settings.commands.testCommand","Test Command")}),e.jsx("input",{id:"testCommand",type:"text",placeholder:c("settings.commands.eGPnpmTest","e.g. pnpm test"),value:t.testCommand||"",onChange:n=>s(m=>({...m,testCommand:n.target.value||void 0}))}),e.jsx("small",{children:c("settings.commands.commandUsedToRunTestsInjectedIntoGenerated","Command used to run tests — injected into generated task specs. No default — unset.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"buildCommand",children:c("settings.commands.buildCommand","Build Command")}),e.jsx("input",{id:"buildCommand",type:"text",placeholder:c("settings.commands.eGPnpmBuild","e.g. pnpm build"),value:t.buildCommand||"",onChange:n=>s(m=>({...m,buildCommand:n.target.value||void 0}))}),e.jsx("small",{children:c("settings.commands.commandUsedToBuildTheProjectInjectedInto","Command used to build the project — injected into generated task specs. No default — unset.")})]})]})}function ju(a){const t=Number(a);return Number.isFinite(t)&&t>0?Math.floor(t):3}async function wu(a){if(!a.ok)throw new Error(await a.text()||"Failed to load legacy auto-merge stamps");return a.json()}function Cu({scopeBanner:a,form:t,setForm:s,integrationBranchOptions:c,integrationBranchCustomMode:n,setIntegrationBranchCustomMode:m,onOpenWorkflowSettings:i}){const{t:r}=Z("app"),[h,k]=o.useState([]),[v,d]=o.useState(!0),[u,j]=o.useState(!1),[x,b]=o.useState(null),[S,E]=o.useState(null),C=o.useCallback(async()=>{d(!0),b(null);try{const y=await wu(await fetch("/api/maintenance/legacy-automerge-stamps"));k(Array.isArray(y.candidates)?y.candidates:[])}catch(y){b(y instanceof Error?y.message:"Failed to load legacy auto-merge stamps")}finally{d(!1)}},[]);o.useEffect(()=>{C()},[C]);const L=async()=>{if(window.confirm("Apply cleanup for legacy auto-merge stamps? This clears only legacy non-override in-review stamps returned by the store and never touches genuine per-task overrides.")){j(!0),b(null),E(null);try{const p=await fetch("/api/maintenance/legacy-automerge-stamps/apply",{method:"POST"});if(!p.ok)throw new Error(await p.text()||"Failed to apply legacy auto-merge stamp cleanup");const P=await p.json();E(`Cleared ${P.count} legacy auto-merge stamp${P.count===1?"":"s"}.`),await C()}catch(p){b(p instanceof Error?p.message:"Failed to apply legacy auto-merge stamp cleanup")}finally{j(!1)}}};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.merge.merge","Merge")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoMerge",className:"checkbox-label",children:[e.jsx("input",{id:"autoMerge",type:"checkbox",checked:t.autoMerge,onChange:y=>s(p=>({...p,autoMerge:y.target.checked}))}),r("settings.merge.autoMergeCompletedTasks"," Auto-merge completed tasks ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.whenEnabledTasksThatPassReviewAreAutomatically","When enabled, tasks that pass review are automatically merged into the main branch. Default: enabled.")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"planApprovalMode",children:r("settings.merge.planApprovalMode","Plan approval mode")}),e.jsxs("select",{id:"planApprovalMode",className:"select",value:t.planApprovalMode??"auto-approve-all",onChange:y=>{const p=y.target.value;s(P=>({...P,planApprovalMode:p}))},"data-testid":"plan-approval-mode-select",children:[e.jsx("option",{value:"workflow",children:r("settings.merge.planApprovalModeWorkflow","Use workflow setting")}),e.jsx("option",{value:"auto-approve-all",children:r("settings.merge.planApprovalModeAutoApproveAll","Auto-approve all tasks (default)")}),e.jsx("option",{value:"require-all",children:r("settings.merge.planApprovalModeRequireAll","Require approval for all tasks")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.planApprovalModeHelp","Project-wide override for the planning approval gate. Leave on workflow to use each workflow's Require plan approval setting, or force all approved specs to bypass or wait for manual approval.")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxAutoMergeRetries",children:r("settings.merge.autoMergeConflictRetries","Auto-merge conflict retries")}),e.jsx("input",{id:"maxAutoMergeRetries",type:"number",min:1,step:1,value:t.maxAutoMergeRetries??3,onChange:y=>s(p=>({...p,maxAutoMergeRetries:y.target.value===""?void 0:ju(y.target.value)}))}),e.jsx("small",{children:r("settings.merge.positiveIntegerRetryCapForAutoMergeConflict","Positive integer retry cap for auto-merge conflict resolution before a task parks for human recovery. Default 3.")})]}),e.jsxs("div",{className:"form-group","data-testid":"legacy-automerge-stamp-cleanup-panel",children:[e.jsx("h5",{className:"settings-section-heading",children:r("settings.merge.legacyAutoMergeStampCleanup","Legacy auto-merge stamp cleanup")}),e.jsx("small",{children:r("settings.merge.findsInReviewTasksWhoseAutoMergeValue"," Finds in-review tasks whose auto-merge value came from the legacy review-entry stamp. Dry-run is automatic; applying delegates to the store cleanup and preserves genuine per-task overrides. ")}),v?e.jsx("small",{"aria-live":"polite",children:r("settings.merge.checkingForLegacyAutoMergeStamps","Checking for legacy auto-merge stamps…")}):h.length===0?e.jsx("small",{"data-testid":"legacy-automerge-stamp-empty-state",children:r("settings.merge.noLegacyAutoMergeStampsToCleanUp"," No legacy auto-merge stamps to clean up. ")}):e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:[h.length,r("settings.merge.legacyAutoMergeStamp"," legacy auto-merge stamp"),h.length===1?"":"s",r("settings.merge.readyToCleanUp"," ready to clean up.")]}),e.jsx("ul",{children:h.map(y=>e.jsxs("li",{"data-testid":"legacy-automerge-stamp-candidate-row",children:[e.jsx("strong",{children:y.taskId})," — ",y.column]},y.taskId))}),e.jsx("button",{type:"button",className:"btn",onClick:L,disabled:u,"data-testid":"legacy-automerge-stamp-apply-button",children:u?"Applying cleanup…":"Apply cleanup"})]}),S?e.jsx("small",{className:"settings-success","aria-live":"polite",children:S}):null,x?e.jsx("small",{className:"settings-error",role:"alert",children:x}):null]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergerMode",children:r("settings.merge.aIMerge","AI merge")}),e.jsxs("select",{id:"mergerMode",className:"select",value:t.merger?.mode??"ai",onChange:y=>s(p=>({...p,merger:{...p.merger??{},mode:y.target.value}})),children:[e.jsx("option",{value:"ai",children:r("settings.merge.aIMergeDefaultAIMergesInAClean","AI merge (default) — AI merges in a clean room, an AI reviewer audits with retries, then lands")}),e.jsx("option",{value:"deterministic",children:r("settings.merge.deterministicLegacyRebaseConflictStrategyAuditPipeline","Deterministic (legacy) — rebase / conflict-strategy / audit pipeline")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[r("settings.merge.aIModeMergesTheTaskBranchIntoAn"," AI mode merges the task branch into an isolated clean-room checkout at the target branch's tip, has an AI reviewer audit the squash (with corrective retries — advisory concerns land with a logged warning, an unfixable correctness concern hard-fails), then fast-forwards the target branch and syncs your local checkout (AI reconciles a conflicting restore). Each task merges to its own target branch, or the default integration branch. "),e.jsx("strong",{children:r("settings.merge.theLegacyMergeSettingsBelowDoNotApply","The legacy merge settings below do not apply while AI merge is on.")})]})]})]}),(t.merger?.mode??"ai")==="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergerMaxReviewPasses",children:r("settings.merge.maxAIReviewPasses","Max AI review passes")}),e.jsx("input",{id:"mergerMaxReviewPasses",type:"number",min:0,max:10,value:t.merger?.maxReviewPasses??3,onChange:y=>s(p=>({...p,merger:{...p.merger??{},maxReviewPasses:y.target.value===""?void 0:Number(y.target.value)}}))}),e.jsx("small",{children:r("settings.merge.aICorrectiveRoundsBeforeLandingTheBestResult","AI corrective rounds before landing the best result (advisory concern) or hard-failing (unfixable correctness concern). Default 3. The reviewer uses your project's reviewer/validator model.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"mergerAllowDirtyLocalCheckoutSync",className:"checkbox-label",children:[e.jsx("input",{id:"mergerAllowDirtyLocalCheckoutSync",type:"checkbox",checked:t.merger?.allowDirtyLocalCheckoutSync===!0,onChange:y=>s(p=>({...p,merger:{...p.merger??{},allowDirtyLocalCheckoutSync:y.target.checked}}))}),r("settings.merge.allowAIMergeToSyncADirtyChecked"," Allow AI merge to sync a dirty checked-out integration branch ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.dangerousCompatibilityEscapeHatchLeaveOffUnlessYou"," Dangerous compatibility escape hatch — restores the legacy stash → fast-forward → restore behavior when your checked-out integration branch has unrelated local edits. When off, AI merge blocks before advancing the branch so dirty project-root edits cannot contaminate a completed merge. Default: enabled (new/unconfigured projects sync a dirty checkout). ")})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"testMode",className:"checkbox-label",children:[e.jsx("input",{id:"testMode",type:"checkbox",checked:t.testMode===!0,onChange:y=>s(p=>({...p,testMode:y.target.checked}))}),r("settings.merge.enableTestMode"," Enable test mode ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.forcesAllAILanesToUseTheDeterministic","Forces all AI lanes to use the deterministic mock provider. No network calls, zero token cost. No default — unset (disabled).")})]})]}),e.jsx(Aa,{message:r("settings.movedStub.reviewVerification","Review, verification auto-fix, and scope-enforcement settings now live on the workflow."),onOpenWorkflowSettings:i}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeStrategy",children:r("settings.merge.autoCompletionMode","Auto-completion mode")}),e.jsxs("select",{id:"mergeStrategy",value:t.mergeStrategy||"direct",onChange:y=>s(p=>({...p,mergeStrategy:y.target.value})),children:[e.jsx("option",{value:"direct",children:r("settings.merge.directMergeIntoTheCurrentBranch","Direct merge into the current branch (default)")}),e.jsx("option",{value:"pull-request",children:r("settings.merge.createMonitorAndMergeAGitHubPullRequest","Create, monitor, and merge a GitHub pull request")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.controlsWhatHappensAfterATaskReachesIn"," Controls what happens after a task reaches In Review. Direct mode merges into the current branch locally. Pull request mode keeps the task in In Review while Fusion waits for GitHub reviews and required checks before merging the PR. ")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"integrationBranch",children:r("settings.merge.integrationBranch","Integration branch")}),(()=>{const y=t.integrationBranch??"",p=y.length>0&&c.includes(y);if(n||y.length>0&&!p)return e.jsxs("div",{className:"form-inline-group",children:[e.jsx("input",{id:"integrationBranch",type:"text",className:"input",placeholder:r("settings.merge.branchName","branch name"),value:y,onChange:W=>{const X=W.target.value.trim();s(Q=>({...Q,integrationBranch:X.length===0?void 0:X}))},"data-testid":"integration-branch-custom-input"}),e.jsx("button",{type:"button",className:"btn-link",onClick:()=>{m(!1),s(W=>({...W,integrationBranch:void 0}))},"data-testid":"integration-branch-use-dropdown",children:r("settings.merge.useDropdown"," Use dropdown ")})]});const f="__fusion-custom__",J="";return e.jsxs("select",{id:"integrationBranch",className:"select",value:y,onChange:W=>{const X=W.target.value;if(X===f){m(!0);return}s(Q=>({...Q,integrationBranch:X===J?void 0:X}))},"data-testid":"integration-branch-select",children:[e.jsx("option",{value:J,children:r("settings.merge.autoDetectOriginHEADMain","(auto-detect — origin/HEAD → main)")}),c.map(W=>e.jsx("option",{value:W,children:W},W)),e.jsx("option",{value:f,children:r("settings.merge.custom","Custom…")})]})})(),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[r("settings.merge.theCanonicalBranchFusionMergesTasksIntoAnd"," No default — unset (auto-detect). The canonical branch Fusion merges tasks into and uses as the reference for all ahead/behind / overlap / pre-rebase computations. Leave on "),e.jsx("em",{children:r("settings.merge.autoDetect","auto-detect")}),r("settings.merge.toResolveViaTheStandardCascade"," to resolve via the standard cascade ("),e.jsx("code",{children:"integrationBranch"}),r("settings.merge.legacy"," → legacy "),e.jsx("code",{children:"baseBranch"})," →",e.jsx("code",{children:"origin/HEAD"}),r("settings.merge.symbolicRefFallback"," symbolic ref → fallback "),e.jsx("code",{children:"main"}),r("settings.merge.pickALocalBranchFromTheDropdownCommon","). Pick a local branch from the dropdown — common integration names like "),e.jsx("code",{children:"main"}),",",e.jsx("code",{children:"master"}),", ",e.jsx("code",{children:"trunk"}),r("settings.merge.and",", and "),e.jsx("code",{children:"develop"}),r("settings.merge.areListedFirstOrChoose"," are listed first — or choose "),e.jsx("em",{children:r("settings.merge.custom","Custom…")}),r("settings.merge.toTypeABranchThatDoesnAposT"," to type a branch that doesn't exist locally yet. Applies to both direct merges and pull-request mode; individual tasks can still override via task metadata. ")]})]})]}),t.mergeStrategy!=="pull-request"&&(t.merger?.mode??"ai")!=="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"directMergeCommitStrategy",children:r("settings.merge.directMergeCommitRouting","Direct merge commit routing")}),e.jsxs("select",{id:"directMergeCommitStrategy",className:"select",value:t.directMergeCommitStrategy??"always-squash",onChange:y=>s(p=>({...p,directMergeCommitStrategy:y.target.value})),children:[e.jsx("option",{value:"auto",children:r("settings.merge.autoSquashSingleSubstantiveBranchesPreserveMultiSubstantive","Auto — squash single-substantive branches, preserve multi-substantive history")}),e.jsx("option",{value:"always-squash",children:r("settings.merge.alwaysSquashDirectMerges","Always squash direct merges (default)")}),e.jsx("option",{value:"always-rebase",children:r("settings.merge.alwaysPreserveDirectMergeCommitHistory","Always preserve direct-merge commit history")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[r("settings.merge.autoKeepsTodayAposSSquashBehaviorFor"," Auto keeps today's squash behavior for branches with zero or one substantive commit, but switches multi-substantive branches to a history-preserving rebase-and-merge path. Individual tasks can override this in PROMPT.md with "),e.jsx("code",{children:"**Direct Merge Commit Strategy:** auto|always-squash|always-rebase"}),"."]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeIntegrationWorktree",children:r("settings.merge.integrationWorktree","Integration worktree")}),e.jsxs("select",{id:"mergeIntegrationWorktree",className:"select",value:t.mergeIntegrationWorktree??"reuse-task-worktree",onChange:y=>s(p=>({...p,mergeIntegrationWorktree:y.target.value})),children:[e.jsx("option",{value:"reuse-task-worktree",children:r("settings.merge.reuseTaskWorktreeDefault","Reuse task worktree (default)")}),e.jsx("option",{value:"cwd-main",children:r("settings.merge.useProjectRootLegacy","Use project root (legacy)")})]}),e.jsx("small",{children:r("settings.merge.autoMergeRunsInTheTaskWorktreeBy"," Auto-merge runs in the task worktree by default. Switch to the legacy project-root path only if you need the pre-FN-5279 fallback; worktrunk-managed projects still defer to worktrunk. ")}),(t.mergeIntegrationWorktree??"reuse-task-worktree")!=="reuse-task-worktree"&&e.jsxs("div",{className:"settings-warning-banner",role:"alert","aria-live":"polite","data-testid":"merge-integration-worktree-warning",children:[e.jsx("strong",{children:r("settings.merge.legacyIntegrationBranchMode","Legacy integration-branch mode.")})," ",r("settings.merge.autoMergeWillRunRebaseConflictResolutionAnd"," Auto-merge will run rebase, conflict resolution, and squash commits inside the project root (the user's checked-out integration-branch worktree) instead of the task worktree. Fusion assumes that directory is already on the integration branch and clean; if it isn't, merges may fail or touch the user's working tree. Reuse-task-worktree is the recommended default (FN-5279). Switch back unless you have a specific reason to opt in (FN-5348). ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeAdvanceAutoSync",children:r("settings.merge.autoSyncProjectCheckoutAfterMerge","Auto-sync project checkout after merge")}),e.jsxs("select",{id:"mergeAdvanceAutoSync",className:"select",value:t.mergeAdvanceAutoSync??"stash-and-ff",onChange:y=>s(p=>({...p,mergeAdvanceAutoSync:y.target.value})),"data-testid":"merge-advance-auto-sync-select",children:[e.jsx("option",{value:"stash-and-ff",children:r("settings.merge.stashFastForwardDefaultPreserveLocalEdits","Stash + fast-forward (default) — preserve local edits")}),e.jsx("option",{value:"ff-only",children:r("settings.merge.fastForwardOnlySkipDirtyWorktrees","Fast-forward only — skip dirty worktrees")}),e.jsx("option",{value:"off",children:r("settings.merge.offLeaveTheProjectRootStaleLegacyBehavior","Off — leave the project root stale (legacy behavior)")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[r("settings.merge.afterFusionAdvancesTheIntegrationBranchRefThe"," After Fusion advances the integration branch ref, the merger can auto-sync other worktrees still checked out on that branch (typically your project-root checkout). "),e.jsx("code",{children:"Stash + fast-forward"}),r("settings.merge.snapshotsRealLocalEditsAsAPatchAgainst"," snapshots real local edits as a patch against the previous tip, snaps the worktree to the new tip, then reapplies the patch — untracked files that collide with newly-tracked paths are left in a temp dir for manual recovery. "),e.jsx("code",{children:"Fast-forward only"}),r("settings.merge.snapsCleanlyWhenTheWorktreeHasNoEdits"," snaps cleanly when the worktree has no edits and skips otherwise. "),e.jsx("code",{children:"Off"}),r("settings.merge.isTheLegacyBehavior"," is the legacy behavior: "),e.jsx("code",{children:"git status"}),r("settings.merge.inYourProjectRootWillShowTheNew"," in your project root will show the new commits inverted as &quot;staged changes&quot; until you pull manually. Only applies to direct merges. ")]})]})]})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:r("settings.merge.gitHubAuthentication","GitHub Authentication")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubAuthMode",children:r("settings.merge.gitHubAuthMode","GitHub auth mode")}),e.jsxs("select",{id:"githubAuthMode",className:"select",value:t.githubAuthMode??"gh-cli",onChange:y=>s(p=>({...p,githubAuthMode:y.target.value})),children:[e.jsx("option",{value:"gh-cli",children:r("settings.merge.gitHubCLIGhAuth","GitHub CLI (gh auth) (default)")}),e.jsx("option",{value:"token",children:r("settings.merge.personalAccessToken","Personal access token")})]})]}),(t.githubAuthMode??"gh-cli")==="token"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubAuthToken",children:r("settings.merge.gitHubPersonalAccessToken","GitHub personal access token")}),e.jsx("input",{id:"githubAuthToken",type:"password",className:"input",value:t.githubAuthToken??"",onChange:y=>s(p=>({...p,githubAuthToken:y.target.value||void 0}))}),e.jsx("small",{children:r("settings.merge.githubAuthTokenHint","No default — unset.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:r("settings.merge.gitLabAuthentication","GitLab Authentication")}),e.jsxs("details",{className:"settings-gitlab-disclosure","data-testid":"project-gitlab-authentication-disclosure",children:[e.jsxs("summary",{children:[e.jsx("span",{className:"settings-gitlab-disclosure__title",children:r("settings.merge.gitLabAuthentication","GitLab Authentication")}),e.jsxs("label",{className:"checkbox-label settings-gitlab-disclosure__toggle",htmlFor:"mergeGitlabEnabled",onClick:y=>y.stopPropagation(),children:[e.jsx("input",{id:"mergeGitlabEnabled",type:"checkbox",checked:t.gitlabEnabled!==!1,onChange:y=>s(p=>({...p,gitlabEnabled:y.target.checked}))}),r("settings.merge.enableGitLabIntegration","Enable GitLab integration")]})]}),e.jsx("small",{className:"settings-description",children:t.gitlabEnabled===!1?r("settings.merge.gitLabDisabledHint","GitLab comments, close/reopen, import fetches, and refresh operations are disabled. Saved tokens remain stored for re-enable."):r("settings.merge.gitLabAuthDetails","Fusion uses GitLab REST API token authentication with the PRIVATE-TOKEN header. Leave the token blank to clear the project override and fall back to a configured global GitLab token or GITLAB_TOKEN where available. No default — unset (unset behaves as enabled until explicitly disabled).")}),e.jsxs("div",{className:"settings-gitlab-disclosure__body","aria-disabled":t.gitlabEnabled===!1,children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"gitlabAuthTokenType",children:r("settings.merge.gitLabTokenType","GitLab token type")}),e.jsxs("select",{id:"gitlabAuthTokenType",className:"select",value:t.gitlabAuthTokenType??"personal",disabled:t.gitlabEnabled===!1,onChange:y=>s(p=>({...p,gitlabAuthTokenType:y.target.value})),children:[e.jsx("option",{value:"personal",children:r("settings.merge.gitLabPersonalAccessToken","Personal access token (default)")}),e.jsx("option",{value:"project",children:r("settings.merge.gitLabProjectAccessToken","Project access token")}),e.jsx("option",{value:"group",children:r("settings.merge.gitLabGroupAccessToken","Group access token")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"gitlabAuthToken",children:r("settings.merge.gitLabAccessToken","GitLab access token")}),e.jsx("input",{id:"gitlabAuthToken",type:"password",className:"input",autoComplete:"off",value:t.gitlabAuthToken??"",disabled:t.gitlabEnabled===!1,onChange:y=>s(p=>({...p,gitlabAuthToken:y.target.value||void 0}))}),e.jsx("small",{className:"settings-description",children:r("settings.merge.gitLabAuthTokenHint","Read-only GitLab operations need read_api or api. Future write actions such as comments and auto-close need api. Project and group tokens are limited to their associated resource and role membership. No default — unset.")})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"includeTaskIdInCommit",className:"checkbox-label",children:[e.jsx("input",{id:"includeTaskIdInCommit",type:"checkbox",checked:t.includeTaskIdInCommit!==!1,onChange:y=>s(p=>({...p,includeTaskIdInCommit:y.target.checked}))}),r("settings.merge.includeTaskIDInCommitScope"," Include task ID in commit scope ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[r("settings.merge.whenDisabledMergeCommitMessagesOmitTheTask","When disabled, merge commit messages omit the task ID from the scope (e.g. "),e.jsx("code",{children:"feat: ..."}),r("settings.merge.insteadOf"," instead of "),e.jsx("code",{children:"feat(KB-001): ..."}),r("settings.merge.includeTaskIdInCommitDefault","). Default: enabled.")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"commitAuthorEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"commitAuthorEnabled",type:"checkbox",checked:t.commitAuthorEnabled!==!1,onChange:y=>s(p=>({...p,commitAuthorEnabled:y.target.checked}))}),r("settings.merge.addFusionAsCoAuthorOnCommits"," Add Fusion as co-author on commits ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[r("settings.merge.whenEnabledCommitsMadeByFusionKeepYour"," When enabled, commits made by Fusion keep your git identity as the primary author and append a "),e.jsx("code",{children:"Co-authored-by"}),r("settings.merge.trailerCreditingFusionRecognizedByGitHubForShared"," trailer crediting Fusion (recognized by GitHub for shared attribution). Default: enabled. ")]})]})]}),t.commitAuthorEnabled!==!1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorName",children:r("settings.merge.coAuthorName","Co-author Name")}),e.jsx("input",{id:"commitAuthorName",type:"text",value:t.commitAuthorName??"",placeholder:r("settings.merge.fusion","Fusion"),onChange:y=>s(p=>({...p,commitAuthorName:y.target.value||void 0}))}),e.jsxs("small",{children:[r("settings.merge.nameUsedInThe","Name used in the "),e.jsx("code",{children:"Co-authored-by"}),r("settings.merge.trailer"," trailer. Default: Fusion.")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorEmail",children:r("settings.merge.coAuthorEmail","Co-author Email")}),e.jsx("input",{id:"commitAuthorEmail",type:"email",value:t.commitAuthorEmail??"",placeholder:r("settings.merge.noreplyRunfusionAi","noreply@runfusion.ai"),onChange:y=>s(p=>({...p,commitAuthorEmail:y.target.value||void 0}))}),e.jsxs("small",{children:[r("settings.merge.emailUsedInThe","Email used in the "),e.jsx("code",{children:"Co-authored-by"}),r("settings.merge.trailerEmail"," trailer. Default: noreply@runfusion.ai.")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoResolveConflicts",className:"checkbox-label",children:[e.jsx("input",{id:"autoResolveConflicts",type:"checkbox",checked:t.autoResolveConflicts!==!1,onChange:y=>s(p=>({...p,autoResolveConflicts:y.target.checked}))}),r("settings.merge.autoResolveConflictsInLockFilesAndGenerated"," Auto-resolve conflicts in lock files and generated files ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.whenEnabledLockFilesPackageLockJsonPnpm","When enabled, lock files (package-lock.json, pnpm-lock.yaml, etc.), generated files (dist/*, *.gen.ts), and trivial whitespace conflicts are resolved automatically without AI intervention. Complex code conflicts still require AI review. Default: enabled.")})]})]}),(t.merger?.mode??"ai")!=="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"smartConflictResolution",className:"checkbox-label",children:[e.jsx("input",{id:"smartConflictResolution",type:"checkbox",checked:t.smartConflictResolution!==!1,onChange:y=>s(p=>({...p,smartConflictResolution:y.target.checked}))}),r("settings.merge.smartConflictResolution"," Smart conflict resolution ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.whenEnabledLockFilesPackageLockJsonPnpm2","When enabled, lock files (package-lock.json, pnpm-lock.yaml, etc.) are resolved using 'ours' strategy, generated files (dist/*, *.gen.ts) using 'theirs' strategy, and trivial whitespace conflicts are auto-resolved without spawning an AI agent. Complex code conflicts still require AI review. Default: enabled.")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeConflictStrategy",children:r("settings.merge.conflictFallbackStrategy","Conflict Fallback Strategy")}),e.jsxs("select",{id:"mergeConflictStrategy",value:t.mergeConflictStrategy??"smart-prefer-main",onChange:y=>s(p=>({...p,mergeConflictStrategy:y.target.value})),children:[e.jsx("option",{value:"smart-prefer-main",children:r("settings.merge.smartPreferMainOnFallbackFetchFfOrigin","Smart, prefer main on fallback — fetch+ff origin → AI → auto-resolve → -X ours (default; protects just-merged sibling work)")}),e.jsx("option",{value:"smart-prefer-branch",children:r("settings.merge.smartPreferTaskOnFallbackFetchFfOrigin",'Smart, prefer task on fallback — fetch+ff origin → AI → auto-resolve → -X theirs (legacy "smart" behavior; task branch wins)')}),e.jsx("option",{value:"ai-only",children:r("settings.merge.aIOnlyAIAutoResolveAIRetryNever","AI only — AI → auto-resolve → AI retry; never silently pick a side")}),e.jsx("option",{value:"abort",children:r("settings.merge.abortOneAIAttemptRequireManualResolutionIf","Abort — one AI attempt; require manual resolution if it fails")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[r("settings.merge.both"," Both "),e.jsx("strong",{children:r("settings.merge.smart","Smart")}),r("settings.merge.optionsStartWithABestEffort"," options start with a best-effort "),e.jsx("code",{children:"git fetch"}),r("settings.merge.fastForwardOfLocalMainFrom"," + fast-forward of local main from "),e.jsx("code",{children:"origin"}),r("settings.merge.soAFreshlyPushedSiblingCommitDoesntGet"," (so a freshly-pushed sibling commit doesn't get clobbered), then run an AI agent, then auto-resolve handles lock/generated/trivial files. They differ only in the "),e.jsx("em",{children:r("settings.merge.finalFallback","final fallback")}),":"," ",e.jsx("strong",{children:r("settings.merge.smartPreferMain","Smart, prefer main")}),r("settings.merge.uses"," uses "),e.jsx("code",{children:"-X ours"}),r("settings.merge.soMainWinsProtectsJustMergedSiblingWork"," so main wins — protects just-merged sibling work and is the new default. ")," ",e.jsx("strong",{children:r("settings.merge.smartPreferTask","Smart, prefer task")}),r("settings.merge.uses"," uses "),e.jsx("code",{children:"-X theirs"}),r("settings.merge.soTheTaskBranchWinsFastButCan"," so the task branch wins — fast, but can resurrect code an earlier sibling task deleted (the FN-2887 class of regression). ")," ",e.jsx("strong",{children:r("settings.merge.aIOnly","AI only")}),r("settings.merge.retriesTheAIAgentRatherThanAutoPicking"," retries the AI agent rather than auto-picking a side. ")," ",e.jsx("strong",{children:r("settings.merge.abort","Abort")}),r("settings.merge.stopsAfterTheFirstAIAttemptAndWaits"," stops after the first AI attempt and waits for a human. ")," ",e.jsxs("em",{children:[r("settings.merge.legacy2","Legacy "),e.jsx("code",{children:'"smart"'}),r("settings.merge.and2"," and "),e.jsx("code",{children:'"prefer-main"'}),r("settings.merge.valuesFromOlderSettingsAreMigratedAutomatically"," values from older settings are migrated automatically.")]})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeStrategyOverlapBehavior",children:r("settings.merge.smartPreferMainOverlapGuard","Smart Prefer Main Overlap Guard")}),e.jsxs("select",{id:"mergeStrategyOverlapBehavior",value:t.mergeStrategyOverlapBehavior??"flip-to-prefer-branch",onChange:y=>s(p=>({...p,mergeStrategyOverlapBehavior:y.target.value})),children:[e.jsx("option",{value:"flip-to-prefer-branch",children:r("settings.merge.flipOverlappingFilesToPreferTheTaskBranch","Flip overlapping files to prefer the task branch (default)")}),e.jsx("option",{value:"warn-only",children:r("settings.merge.warnOnlyKeepLegacyMainWinsFallback","Warn only — keep legacy main-wins fallback")}),e.jsx("option",{value:"ignore",children:r("settings.merge.ignoreOverlapDetectionPreserveLegacyBehavior","Ignore overlap detection — preserve legacy behavior")})]}),e.jsx("small",{children:r("settings.merge.whenUsingSmartPreferMainAutomaticallyPreferThe"," When using smart-prefer-main, automatically prefer the branch side for files that main has recently modified to avoid silently discarding branch work. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"postMergeAuditMode",children:r("settings.merge.postMergeAuditMode","Post-merge audit mode")}),e.jsxs("select",{className:"select",id:"postMergeAuditMode",value:t.postMergeAuditMode??"warn",onChange:y=>s(p=>({...p,postMergeAuditMode:y.target.value})),children:[e.jsx("option",{value:"block",children:r("settings.merge.blockStrict","Block (strict)")}),e.jsx("option",{value:"warn",children:r("settings.merge.warnDefaultLogFindingsContinue","Warn (default; log findings, continue)")}),e.jsx("option",{value:"off",children:r("settings.merge.offSkipAudit","Off (skip audit)")})]}),e.jsxs("small",{children:[r("settings.merge.controlsThePostMergeAuditGate"," Controls the post-merge audit gate. "),e.jsx("strong",{children:r("settings.merge.warn","Warn")}),r("settings.merge.defaultLogsFindingsButAutoCompletesTheMerge"," (default) logs findings but auto-completes the merge. "),e.jsx("strong",{children:r("settings.merge.block","Block")}),r("settings.merge.isTheStricterOptInModeThatRefuses"," is the stricter opt-in mode that refuses to auto-complete merges with duplicate-subject or touched-file overlap risks. "),e.jsx("strong",{children:r("settings.merge.off","Off")}),r("settings.merge.skipsTheAuditEntirelySwitchingToOffIs"," skips the audit entirely. Switching to Off is recommended only if you trust your branches don't silently drop edits. ")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"pushAfterMerge",className:"checkbox-label",children:[e.jsx("input",{id:"pushAfterMerge",type:"checkbox",checked:t.pushAfterMerge===!0,onChange:y=>s(p=>({...p,pushAfterMerge:y.target.checked}))}),r("settings.merge.pushToRemoteAfterMerge"," Push to remote after merge ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.whenEnabledTheMergedResultIsAutomaticallyPushed","When enabled, the merged result is automatically pushed to the configured git remote. This includes pulling the latest from the remote first (rebase) and resolving any conflicts with AI if needed. Default: disabled.")})]})]}),t.pushAfterMerge&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pushRemote",children:r("settings.merge.pushRemote","Push Remote")}),e.jsx("input",{id:"pushRemote",type:"text",placeholder:r("settings.merge.origin","origin"),value:t.pushRemote||"",onChange:y=>s(p=>({...p,pushRemote:y.target.value||void 0}))}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:r("settings.merge.moreDetails","More details")}),e.jsx("small",{children:r("settings.merge.gitRemoteToPushToEGOrigin",'Git remote to push to (e.g. "origin"). Can include branch name (e.g. "origin main"). Default: "origin".')})]})]})]})}function or(a){return Array.from(new Set(a.split(/[\n,]+/).map(t=>t.trim()).filter(t=>t.length>0)))}function Nu({value:a,onChange:t,disabled:s=!1}){const{t:c}=Z("app"),n=a?.approvalMode??"trusted-only",m=a?.alwaysApproveDelete??!0,i={always:{label:c("agentProvisioning.always","Always require approval"),description:c("agentProvisioning.alwaysDesc","All fn_agent_create/fn_agent_delete requests require approval unless caller is trusted.")},"trusted-only":{label:c("agentProvisioning.trustedOnly","Trusted-only"),description:c("agentProvisioning.trustedOnlyDesc","Trusted roles/agent IDs bypass approval; other callers require approval.")},never:{label:c("agentProvisioning.never","Never require approval"),description:c("agentProvisioning.neverDesc","Allow provisioning without approval for non-privileged callers.")}},r=h=>{t({...a??{},...h})};return e.jsxs("div",{className:"agent-provisioning-policy-editor card",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-provisioning-approval-mode",children:c("agentProvisioning.approvalMode","Approval mode")}),e.jsx("select",{id:"agent-provisioning-approval-mode",className:"select",value:n,onChange:h=>r({approvalMode:h.target.value}),disabled:s,children:Bo.map(h=>e.jsx("option",{value:h,children:i[h].label},h))}),e.jsx("small",{className:"agent-provisioning-policy-help",children:i[n].description})]}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{className:"checkbox-label",htmlFor:"agent-provisioning-always-approve-delete",children:[e.jsx("input",{id:"agent-provisioning-always-approve-delete",type:"checkbox",checked:m,onChange:h=>r({alwaysApproveDelete:h.target.checked}),disabled:s}),c("agentProvisioning.alwaysApproveDelete","Always require approval for fn_agent_delete")]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-provisioning-trusted-roles",children:c("agentProvisioning.trustedRoles","Trusted roles")}),e.jsx("textarea",{id:"agent-provisioning-trusted-roles",className:"input agent-provisioning-policy-textarea",value:(a?.trustedRoles??[]).join(", "),onChange:h=>r({trustedRoles:or(h.target.value)}),disabled:s,placeholder:c("agentProvisioning.trustedRolesPlaceholder","reviewer, ceo"),rows:2})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-provisioning-trusted-agent-ids",children:c("agentProvisioning.trustedAgentIds","Trusted agent IDs")}),e.jsx("textarea",{id:"agent-provisioning-trusted-agent-ids",className:"input agent-provisioning-policy-textarea",value:(a?.trustedAgentIds??[]).join(", "),onChange:h=>r({trustedAgentIds:or(h.target.value)}),disabled:s,placeholder:c("agentProvisioning.trustedAgentIdsPlaceholder","agent-abc123"),rows:2})]}),e.jsx("p",{className:"agent-provisioning-policy-help",children:e.jsx(ka,{i18nKey:"app:agentProvisioning.helpText",defaults:"These settings govern durable provisioning tools only: <code>fn_agent_create</code> and <code>fn_agent_delete</code>. Ephemeral <code2>fn_spawn_agent</code2> requests stay under the task/agent mutation approval gate (FN-3973).",components:{code:e.jsx("code",{}),code2:e.jsx("code",{})}})})]})}function ma(a){return Go.reduce((t,s)=>(t[s]=a?.[s]??"allow",t),{})}function Su({scopeBanner:a,form:t,setForm:s}){const{t:c}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.agentPermissions.agentPermissions","Agent Permissions")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:c("settings.agentPermissions.perAgentSettingsOverrideProjectDefaultsEachCategory","Project defaults apply to permanent agents, ephemeral task workers, and fallback executor workers unless a per-agent override is set. Exact tool rules compose with the legacy ephemeral create-task toggle. Default: unset — every action category defaults to allow until a category is explicitly restricted.")})}),e.jsx(Bc,{mode:"project-default",value:t.defaultAgentPermissionPolicy?{presetId:"custom",rules:ma(t.defaultAgentPermissionPolicy.rules),...t.defaultAgentPermissionPolicy.toolRules?{toolRules:t.defaultAgentPermissionPolicy.toolRules}:{}}:{presetId:"custom",rules:ma()},onChange:n=>s(m=>({...m,defaultAgentPermissionPolicy:{rules:ma(n?.rules),...n?.toolRules?{toolRules:n.toolRules}:{}}}))}),e.jsx("h4",{className:"settings-section-heading",children:c("settings.agentPermissions.agentProvisioningApprovals","Agent Provisioning Approvals")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:c("settings.agentPermissions.configureProjectLevelApprovalBehaviorForDurableProvisioning"," Configure project-level approval behavior for durable provisioning tools (fn_agent_create/fn_agent_delete). Default: no approval policy configured (empty). ")})}),e.jsx(Nu,{value:t.agentProvisioning,onChange:n=>s(m=>({...m,agentProvisioning:n}))})]})}const Pu=72;function Au(a,t){if(a.length<=t)return a;const s=Math.max(1,t-1),c=Math.ceil(s/2),n=Math.floor(s/2);return`${a.slice(0,c)}…${a.slice(a.length-n)}`}function Tu(a){const t=`${a.label} — ${a.path}`;return Au(t,Pu)}function Mu({scopeBanner:a,form:t,setForm:s,memory:c}){const{t:n}=Z("app"),{memoryCapabilities:m,memoryBackendStatus:i,memoryBackendLoading:r,memoryBackendError:h,memoryFiles:k,selectedMemoryPath:v,setSelectedMemoryPath:d,memoryContent:u,setMemoryContent:j,memoryLoading:x,memoryDirty:b,setMemoryDirty:S,memoryTestQuery:E,setMemoryTestQuery:C,memoryTestLoading:L,memoryTestResult:y,qmdInstallLoading:p,dreamRunning:P,memoryCompactLoading:f,onInstallQmd:J,onTestMemoryRetrieval:W,onDreamNow:X,onCompactMemory:Q,onSaveMemory:ne}=c,ae=t.memoryEnabled!==!1,V=!r&&i!==null,$=V?m?.writable??!0:!0,T=ae&&$,U=k.find(q=>q.path===v),re={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.memory.memory","Memory")}),e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"settings-muted",children:[n("settings.memory.memoryLivesIn"," Memory lives in "),e.jsx("code",{children:".fusion/memory/"}),n("settings.memory.agentsSearchWithQmdFirstFallBackTo",". Agents search with qmd first, fall back to local files when qmd is missing, and open exact line windows only when needed. ")]})}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryEnabled",type:"checkbox",checked:t.memoryEnabled!==!1,onChange:q=>s(F=>({...F,memoryEnabled:q.target.checked}))}),n("settings.memory.enableMemoryTools"," Enable memory tools ")]}),e.jsx("small",{children:n("settings.memory.agentsGetMemorySearchMemoryGetAndMemory","Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback. Default: enabled.")})]}),r?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:n("settings.memory.checkingMemoryWriteAccess","Checking memory write access...")})}):h?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[n("settings.memory.failedToLoadBackendStatus","Failed to load backend status: "),h]})}):null,V&&i.qmdAvailable===!1&&e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:[n("settings.memory.qmdIsNotInstalledSearchWillUseLocal"," qmd is not installed. Search will use local files. Install indexed retrieval: "),e.jsx("code",{children:i.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:J,disabled:p,children:p?n("settings.memory.installing","Installing…"):n("settings.memory.installQmd","Install qmd")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryAutoSummarizeEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryAutoSummarizeEnabled",type:"checkbox",checked:t.memoryAutoSummarizeEnabled||!1,onChange:q=>s(F=>({...F,memoryAutoSummarizeEnabled:q.target.checked}))}),n("settings.memory.autoSummarizeMemory"," Auto-Summarize Memory ")]}),e.jsx("small",{children:n("settings.memory.automaticallyCompactMemoryWhenItExceedsTheThreshold","Automatically compact memory when it exceeds the threshold on a schedule. Default: disabled.")})]}),(t.memoryAutoSummarizeEnabled||!1)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeThresholdChars",children:n("settings.memory.compactionThresholdChars","Compaction Threshold (chars)")}),e.jsx("input",{id:"memoryAutoSummarizeThresholdChars",type:"number",className:"input",value:t.memoryAutoSummarizeThresholdChars??5e4,onChange:q=>s(F=>({...F,memoryAutoSummarizeThresholdChars:parseInt(q.target.value,10)||5e4})),min:1e3}),e.jsx("small",{children:n("settings.memory.memoryWillBeCompactedWhenItExceedsThis","Memory will be compacted when it exceeds this character count. Default: 50000.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeSchedule",children:n("settings.memory.scheduleCron","Schedule (cron)")}),e.jsx("input",{id:"memoryAutoSummarizeSchedule",type:"text",className:"input",value:t.memoryAutoSummarizeSchedule??"0 3 * * *",onChange:q=>s(F=>({...F,memoryAutoSummarizeSchedule:q.target.value})),placeholder:n("settings.memory.03","0 3 * * *")}),e.jsx("small",{children:n("settings.memory.cronExpressionForAutoSummarizeScheduleDefaultDaily","Cron expression for auto-summarize schedule. Default: 0 3 * * * (daily at 3 AM).")})]})]}),e.jsx("div",{style:{borderTop:"1px solid var(--border)",margin:"var(--space-lg) 0"}}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryDreamsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryDreamsEnabled",type:"checkbox",checked:t.memoryDreamsEnabled===!0,onChange:q=>s(F=>({...F,memoryDreamsEnabled:q.target.checked})),disabled:!ae}),n("settings.memory.processDreamsFromDailyMemory"," Process dreams from daily memory ")]}),e.jsx("small",{children:n("settings.memory.turnsDailyNotesIntoDREAMSMdAndPromotes","Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md. Default: disabled.")})]}),ae&&t.memoryDreamsEnabled===!0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryDreamsSchedule",children:n("settings.memory.dreamSchedule","Dream Schedule")}),e.jsx("input",{id:"memoryDreamsSchedule",type:"text",value:t.memoryDreamsSchedule??"0 4 * * *",onChange:q=>s(F=>({...F,memoryDreamsSchedule:q.target.value}))}),e.jsx("small",{children:n("settings.memory.cronExpressionForDreamProcessing","Cron expression for dream processing. Default: 0 4 * * * (daily at 4 AM).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:X,disabled:P||t.memoryDreamsEnabled!==!0,children:P?e.jsxs(e.Fragment,{children:[e.jsx(ze,{size:14,className:"animate-spin"}),n("settings.memory.dreaming"," Dreaming… ")]}):n("settings.memory.dreamNow","Dream Now")}),e.jsx("small",{children:n("settings.memory.manuallyTriggerDreamProcessingNow","Manually trigger dream processing now.")})]})]}),e.jsxs("div",{className:"memory-retrieval-test",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryRetrievalQuery",children:n("settings.memory.testRetrieval","Test Retrieval")}),e.jsx("input",{id:"memoryRetrievalQuery",type:"text",value:E,onChange:q=>C(q.target.value),placeholder:n("settings.memory.searchMemoryWithQmd","Search memory with qmd")}),e.jsx("small",{children:n("settings.memory.runsTheSameQmdBackedMemorySearchPath","Runs the same qmd-backed memory_search path agents use.")})]}),e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:W,disabled:L,children:L?n("settings.memory.testing","Testing…"):n("settings.memory.testRetrieval","Test Retrieval")})}),y&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[y.results.length,n("settings.memory.result"," result"),y.results.length===1?"":"s"," ",n("settings.memory.for",'for "'),y.query,'"']}),e.jsxs("small",{children:[n("settings.memory.qmd"," qmd "),y.qmdAvailable?"available":"missing"," · ",y.usedFallback?"local fallback used":"qmd path used"]}),y.results.length>0?e.jsx("ul",{children:y.results.map((q,F)=>e.jsxs("li",{children:[e.jsxs("span",{children:[q.path,":",q.lineStart]}),e.jsx("p",{children:q.snippet})]},`${q.path}-${q.lineStart}-${F}`))}):e.jsx("small",{children:n("settings.memory.noMatchingMemoryFound","No matching memory found.")})]})]}),!ae&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:n("settings.memory.memoryIsCurrentlyDisabledYouCanViewThe"," Memory is currently disabled. You can view the file, but editing is read-only until memory is re-enabled. ")}),ae&&V&&!$&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:n("settings.memory.memoryIsConfiguredWithAReadOnlyBackend"," Memory is configured with a read-only backend. You can view the file, but saving is disabled. ")}),x?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Ze,{label:n("settings.memory.loadingMemory","Loading memory…")})}):e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryFilePath",children:n("settings.memory.memoryFile","Memory File")}),e.jsx("select",{id:"memoryFilePath",value:v,onChange:q=>{d(q.target.value),S(!1)},disabled:b,children:k.map(q=>e.jsx("option",{value:q.path,title:`${q.label} — ${q.path}`,children:Tu(q)},q.path))}),e.jsx("small",{children:b?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit. Dreams is selected by default."})]}),U&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:re[U.layer]}),e.jsx("strong",{children:U.path}),e.jsxs("small",{children:[U.size.toLocaleString(),n("settings.memory.bytesUpdated"," bytes · updated "),new Date(U.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group memory-editor-form-group",children:[e.jsx("label",{children:U?.label||"Memory Editor"}),e.jsxs("small",{children:[U?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",U?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",U?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!U&&"Edits the selected memory file."]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(_o,{content:u,onChange:q=>{j(q),S(!0)},readOnly:!T,filePath:v})})]})]}),!x&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Q,disabled:!T||b||f,children:f?n("settings.memory.compacting","Compacting…"):n("settings.memory.compactSelectedFile","Compact Selected File")}),e.jsx("small",{children:b?"Save or discard edits before compacting this file.":`Compacts ${v} and writes the result back to the same file.`})]}),b&&T&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:ne,children:n("settings.memory.saveMemory","Save Memory")})}),b&&!T&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[n("settings.memory.cannotSave","Cannot save: "),ae?"Backend is read-only":"Memory is disabled"]})})]})}function Ru({scopeBanner:a,form:t,setForm:s,researchLimitError:c}){const{t:n}=Z("app"),m=t.researchSettings?.limits,i=t.researchSettings?.enabledSources;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.researchProject.projectResearchSettings","Project Research Settings")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"research-project-enabled",className:"checkbox-label",children:[e.jsx("input",{id:"research-project-enabled",type:"checkbox",checked:t.researchSettings?.enabled??!0,onChange:r=>s(h=>({...h,researchSettings:{...h.researchSettings??{},enabled:r.target.checked}}))}),n("settings.researchProject.enableResearchInThisProject"," Enable research in this project ")]}),e.jsx("small",{children:n("settings.researchProject.enableResearchInThisProjectHint","Default: enabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:n("settings.researchProject.enabledSources","Enabled Sources")}),e.jsxs("label",{htmlFor:"research-project-source-webSearch",className:"checkbox-label settings-research-source-locked",children:[e.jsx("input",{id:"research-project-source-webSearch",type:"checkbox",checked:!0,disabled:!0,readOnly:!0}),n("settings.researchProject.webSearch"," Web Search "),e.jsx("span",{className:"settings-muted",children:n("settings.researchProject.alwaysOn","Always on")})]}),e.jsx("small",{className:"settings-muted",children:n("settings.researchProject.webSearchIsAlwaysEnabledConfigureTheSearch"," Web search is always enabled. Configure the search provider under Research Defaults. ")}),e.jsx("div",{className:"settings-research-source-grid",children:[["pageFetch",n("settings.researchProject.pageFetch","Page Fetch"),"Default: enabled."],["github",n("settings.researchProject.github","GitHub"),"Default: disabled."],["localDocs",n("settings.researchProject.localDocs","Local Docs"),"Default: enabled."],["llmSynthesis",n("settings.researchProject.llmSynthesis","LLM Synthesis"),"Default: enabled."]].map(([r,h,k])=>e.jsxs("label",{htmlFor:`research-project-source-${r}`,className:"checkbox-label",children:[e.jsx("input",{id:`research-project-source-${r}`,type:"checkbox",checked:i?.[r]??!1,onChange:v=>s(d=>({...d,researchSettings:{...d.researchSettings??{},enabledSources:{...d.researchSettings?.enabledSources??{},[r]:v.target.checked}}}))}),h,e.jsx("small",{children:k})]},r))})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-research-limits-grid",children:[e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-concurrent",children:n("settings.researchProject.maxConcurrentRuns","Max Concurrent Runs")}),e.jsx("input",{id:"research-project-max-concurrent",className:"input",type:"number",min:1,value:m?.maxConcurrentRuns??3,onChange:r=>s(h=>({...h,researchSettings:{...h.researchSettings??{},limits:{...h.researchSettings?.limits??{},maxConcurrentRuns:r.target.value===""?void 0:Number(r.target.value)}}}))}),e.jsx("small",{children:n("settings.researchProject.maxConcurrentRunsHint","Default: 3.")})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-sources",children:n("settings.researchProject.maxSourcesPerRun","Max Sources Per Run")}),e.jsx("input",{id:"research-project-max-sources",className:"input",type:"number",min:1,value:m?.maxSourcesPerRun??20,onChange:r=>s(h=>({...h,researchSettings:{...h.researchSettings??{},limits:{...h.researchSettings?.limits??{},maxSourcesPerRun:r.target.value===""?void 0:Number(r.target.value)}}}))}),e.jsx("small",{children:n("settings.researchProject.maxSourcesPerRunHint","Default: 20.")})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-duration",children:n("settings.researchProject.maxDurationMs","Max Duration (ms)")}),e.jsx("input",{id:"research-project-max-duration",className:"input",type:"number",min:1e3,value:m?.maxDurationMs??3e5,onChange:r=>s(h=>({...h,researchSettings:{...h.researchSettings??{},limits:{...h.researchSettings?.limits??{},maxDurationMs:r.target.value===""?void 0:Number(r.target.value)}}}))}),e.jsx("small",{children:n("settings.researchProject.maxDurationMsHint","Default: 300000 (5 minutes).")})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-request-timeout",children:n("settings.researchProject.requestTimeoutMs","Request Timeout (ms)")}),e.jsx("input",{id:"research-project-request-timeout",className:"input",type:"number",min:1e3,value:m?.requestTimeoutMs??3e4,onChange:r=>s(h=>({...h,researchSettings:{...h.researchSettings??{},limits:{...h.researchSettings?.limits??{},requestTimeoutMs:r.target.value===""?void 0:Number(r.target.value)}}}))}),e.jsx("small",{children:n("settings.researchProject.requestTimeoutMsHint","Default: 30000 (30 seconds).")})]}),c&&e.jsx("small",{className:"field-error settings-research-limits-error",children:c})]})})]})}function Iu({scopeBanner:a,form:t,setForm:s,globalSettings:c,projectId:n,addToast:m}){const{t:i}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:i("settings.nav.mcp","MCP Servers")}),e.jsx(Sr,{scope:"project",form:t,setForm:s,globalSettings:c,projectId:n,addToast:m})]})}function Eu({scopeBanner:a,form:t,setForm:s,backupInfo:c,backupLoading:n,onBackupNow:m}){const{t:i}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:i("settings.backups.databaseBackups","Database Backups")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoBackupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoBackupEnabled",type:"checkbox",checked:t.autoBackupEnabled||!1,onChange:r=>s(h=>({...h,autoBackupEnabled:r.target.checked}))}),i("settings.backups.enableAutomaticDatabaseBackups"," Enable automatic database backups ")]}),e.jsx("small",{children:i("settings.backups.whenEnabledTheDatabaseIsBackedUpAutomatically","When enabled, the database is backed up automatically on a schedule. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupSchedule",children:i("settings.backups.backupScheduleCron","Backup Schedule (Cron)")}),e.jsx("input",{id:"autoBackupSchedule",type:"text",placeholder:i("settings.backups.02","0 2 * * *"),value:t.autoBackupSchedule||"0 2 * * *",onChange:r=>s(h=>({...h,autoBackupSchedule:r.target.value})),disabled:!t.autoBackupEnabled}),e.jsx("small",{children:i("settings.backups.cronExpressionForBackupTimingDefault02"," Cron expression for backup timing. Default: 0 2 * * * (daily at 2 AM). Examples: 0 * * * * (hourly), 0 0 * * 0 (weekly), */15 * * * * (every 15 min) ")}),t.autoBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.autoBackupSchedule)&&e.jsx("small",{className:"field-error",children:i("settings.backups.invalidCronExpressionFormat","Invalid cron expression format")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupRetention",children:i("settings.backups.retentionCount","Retention Count")}),e.jsx("input",{id:"autoBackupRetention",type:"number",min:1,max:100,value:t.autoBackupRetention??"",onChange:r=>{const h=r.target.value;s(k=>({...k,autoBackupRetention:h===""?void 0:Number(h)}))},disabled:!t.autoBackupEnabled}),e.jsx("small",{children:i("settings.backups.numberOfBackupFilesToKeepOldestAre","Number of backup files to keep (oldest are deleted first). Range: 1-100. Default: 7.")}),t.autoBackupRetention!==void 0&&(t.autoBackupRetention<1||t.autoBackupRetention>100)&&e.jsx("small",{className:"field-error",children:i("settings.backups.mustBeBetween1And100","Must be between 1 and 100")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupDir",children:i("settings.backups.backupDirectory","Backup Directory")}),e.jsx("input",{id:"autoBackupDir",type:"text",placeholder:i("settings.backups.fusionBackups",".fusion/backups"),value:t.autoBackupDir||".fusion/backups",onChange:r=>s(h=>({...h,autoBackupDir:r.target.value})),disabled:!t.autoBackupEnabled}),e.jsx("small",{children:i("settings.backups.directoryForBackupFilesRelativeToProjectRoot","Directory for backup files, relative to project root. Default: .fusion/backups.")}),t.autoBackupDir&&t.autoBackupDir.includes("..")&&e.jsx("small",{className:"field-error",children:i("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)")})]}),e.jsx("h4",{className:"settings-section-heading",children:i("settings.backups.memoryBackups","Memory Backups")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryBackupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryBackupEnabled",type:"checkbox",checked:t.memoryBackupEnabled||!1,onChange:r=>s(h=>({...h,memoryBackupEnabled:r.target.checked}))}),i("settings.backups.enableAutomaticMemoryBackups"," Enable automatic memory backups ")]}),e.jsx("small",{children:i("settings.backups.whenEnabledProjectAndAgentMemoryFilesAre","When enabled, project and agent memory files are backed up automatically on a schedule. Default: disabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupSchedule",children:i("settings.backups.memoryBackupScheduleCron","Memory Backup Schedule (Cron)")}),e.jsx("input",{id:"memoryBackupSchedule",type:"text",placeholder:i("settings.backups.03","0 3 * * *"),value:t.memoryBackupSchedule||"0 3 * * *",onChange:r=>s(h=>({...h,memoryBackupSchedule:r.target.value})),disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:i("settings.backups.cronExpressionForMemoryBackupTimingDefault0","Cron expression for memory backup timing. Default: 0 3 * * * (daily at 3 AM).")}),t.memoryBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.memoryBackupSchedule)&&e.jsx("small",{className:"field-error",children:i("settings.backups.invalidCronExpressionFormat","Invalid cron expression format")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupRetention",children:i("settings.backups.memoryRetentionCount","Memory Retention Count")}),e.jsx("input",{id:"memoryBackupRetention",type:"number",min:1,max:100,value:t.memoryBackupRetention??"",onChange:r=>{const h=r.target.value;s(k=>({...k,memoryBackupRetention:h===""?void 0:Number(h)}))},disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:i("settings.backups.numberOfMemoryBackupsToKeepOldestAre","Number of memory backups to keep (oldest are deleted first). Range: 1-100. Default: 14.")}),t.memoryBackupRetention!==void 0&&(t.memoryBackupRetention<1||t.memoryBackupRetention>100)&&e.jsx("small",{className:"field-error",children:i("settings.backups.mustBeBetween1And100","Must be between 1 and 100")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupDir",children:i("settings.backups.memoryBackupDirectory","Memory Backup Directory")}),e.jsx("input",{id:"memoryBackupDir",type:"text",placeholder:i("settings.backups.fusionBackupsMemory",".fusion/backups/memory"),value:t.memoryBackupDir||".fusion/backups/memory",onChange:r=>s(h=>({...h,memoryBackupDir:r.target.value})),disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:i("settings.backups.directoryForMemoryBackupsRelativeToProjectRoot","Directory for memory backups, relative to project root. Default: .fusion/backups/memory.")}),t.memoryBackupDir&&t.memoryBackupDir.includes("..")&&e.jsx("small",{className:"field-error",children:i("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupScope",children:i("settings.backups.memoryBackupScope","Memory Backup Scope")}),e.jsxs("select",{id:"memoryBackupScope",value:t.memoryBackupScope||"all",onChange:r=>s(h=>({...h,memoryBackupScope:r.target.value})),disabled:!t.memoryBackupEnabled,children:[e.jsx("option",{value:"all",children:i("settings.backups.allProjectAgents","All (project + agents)")}),e.jsx("option",{value:"project",children:i("settings.backups.projectOnlyFusionMemory","Project only (.fusion/memory)")}),e.jsx("option",{value:"agents",children:i("settings.backups.agentsOnlyFusionAgentMemory","Agents only (.fusion/agent-memory)")})]}),e.jsx("small",{children:i("settings.backups.memoryBackupScopeHint","Default: all (project + agents).")})]}),n?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Ze,{label:i("settings.backups.loadingBackupInfo","Loading backup info…")})}):c?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:i("settings.backups.currentBackups","Current Backups")}),e.jsxs("div",{className:"backup-stats",children:[e.jsxs("div",{className:"backup-stat",children:[e.jsx("span",{className:"backup-stat-value",children:c.count}),e.jsx("span",{className:"backup-stat-label",children:i("settings.backups.backups","backups")})]}),e.jsxs("div",{className:"backup-stat",children:[e.jsx("span",{className:"backup-stat-value",children:c.totalSize>1024*1024?`${(c.totalSize/(1024*1024)).toFixed(1)} MB`:`${(c.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:i("settings.backups.totalSize","total size")})]})]}),c.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:[i("settings.backups.view","View "),c.backups.length,i("settings.backups.backupS"," backup(s)")]}),e.jsxs("ul",{children:[c.backups.slice(0,10).map(r=>e.jsxs("li",{children:[e.jsx("code",{children:r.filename}),e.jsx("span",{className:"backup-size",children:r.size>1024*1024?`${(r.size/(1024*1024)).toFixed(1)} MB`:`${(r.size/1024).toFixed(1)} KB`})]},r.filename)),c.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:[i("settings.backups.and","...and "),c.backups.length-10,i("settings.backups.more"," more")]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:m,disabled:n,children:n?i("settings.backups.creating","Creating…"):i("settings.backups.backupNow","Backup Now")})})]})}const Fu=o.lazy(()=>xr(()=>import("./PluginManager-YfHRH24B.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(a=>({default:a.PluginManager}))),Lu=o.lazy(()=>xr(()=>import("./PiExtensionsManager-D5x6GZOP.js"),__vite__mapDeps([14,1,2,3,4,5,6,7,8,9,15,16,17])).then(a=>({default:a.PiExtensionsManager})));function Du({scopeBanner:a,projectId:t,addToast:s,activePluginsSubsection:c,setActivePluginsSubsection:n}){const{t:m}=Z("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:m("settings.plugins.plugins","Plugins")}),e.jsxs("div",{className:"settings-plugins-subsection-toggle",role:"tablist","aria-label":m("settings.plugins.pluginManagerType","Plugin manager type"),children:[e.jsx("button",{type:"button",id:"plugins-tab-fusion-plugins",role:"tab","aria-controls":"plugins-panel-fusion-plugins","aria-selected":c==="fusion-plugins",tabIndex:c==="fusion-plugins"?0:-1,className:`settings-plugins-subsection-btn${c==="fusion-plugins"?" active":""}`,onClick:()=>n("fusion-plugins"),children:m("settings.plugins.fusionPlugins"," Fusion Plugins ")}),e.jsx("button",{type:"button",id:"plugins-tab-pi-extensions",role:"tab","aria-controls":"plugins-panel-pi-extensions","aria-selected":c==="pi-extensions",tabIndex:c==="pi-extensions"?0:-1,className:`settings-plugins-subsection-btn${c==="pi-extensions"?" active":""}`,onClick:()=>n("pi-extensions"),children:m("settings.plugins.piExtensions"," Pi Extensions ")})]}),e.jsx("div",{id:"plugins-panel-fusion-plugins",role:"tabpanel","aria-labelledby":"plugins-tab-fusion-plugins",className:"settings-plugins-subsection-panel",hidden:c!=="fusion-plugins",children:c==="fusion-plugins"&&e.jsxs(e.Fragment,{children:[e.jsx(o.Suspense,{fallback:null,children:e.jsx(Fu,{addToast:s,projectId:t})}),e.jsx(ya,{slotId:"settings-section",projectId:t})]})}),e.jsx("div",{id:"plugins-panel-pi-extensions",role:"tabpanel","aria-labelledby":"plugins-tab-pi-extensions",className:"settings-plugins-subsection-panel",hidden:c!=="pi-extensions",children:c==="pi-extensions"&&e.jsx(o.Suspense,{fallback:null,children:e.jsx(Lu,{addToast:s,projectId:t})})})]})}function ha(a,t){if(!t)return a;const s=a.includes("?")?"&":"?";return`${a}${s}projectId=${encodeURIComponent(t)}`}async function cr(a,t){const s=await fetch(a,{credentials:"same-origin",...t,headers:{"Content-Type":"application/json",...t?.headers??{}}}),c=await s.json();if(!s.ok)throw new Error(c.error??`Request failed (${s.status})`);return c}function Ou(a,t){const s=t?.enabled===!0,[c,n]=o.useState({status:"missing"}),[m,i]=o.useState(!1),r=o.useCallback(async()=>{try{const k=await cr(ha("/api/worktrunk/status",a));return n(k),k}catch(k){const v={status:"failed",error:k instanceof Error?k.message:"Failed to load worktrunk status"};return n(v),v}},[a]);o.useEffect(()=>{s&&r()},[s,r]),o.useEffect(()=>Uo(ha("/api/events",a),{events:{"approval:updated":()=>{c.pendingApprovalId&&r()},"approval:decided":()=>{c.pendingApprovalId&&r()}}}),[a,r,c.pendingApprovalId]);const h=o.useCallback(async()=>{i(!0),n(k=>({...k,status:"installing",error:void 0}));try{const k=await cr(ha("/api/worktrunk/install-request",a),{method:"POST",body:JSON.stringify({})});n({status:k.status,version:k.version,installPath:k.installPath,pendingApprovalId:k.pendingApprovalId??k.approvalRequestId,error:k.error})}catch(k){n({status:"failed",error:k instanceof Error?k.message:"Failed to request install"})}finally{i(!1)}},[a]);return{...c,refresh:r,requestInstall:h,requesting:m}}const pa="fusion_github_star_count",dr=3600*1e3,ur="fusion:github-star-clicked";function Zt(a){return a.startsWith("/")}function Bu({size:a=13}){return e.jsx("svg",{"data-testid":"discord-icon",width:a,height:a,viewBox:"0 0 24 24",role:"img","aria-hidden":"true",fill:"currentColor",children:e.jsx("path",{d:"M20.317 4.369A19.791 19.791 0 0 0 15.885 3a13.66 13.66 0 0 0-.696 1.412 18.27 18.27 0 0 0-6.378 0A13.627 13.627 0 0 0 8.115 3a19.736 19.736 0 0 0-4.432 1.369C.878 8.604.111 12.734.494 16.803a19.916 19.916 0 0 0 5.993 3.048 14.43 14.43 0 0 0 1.286-2.106 12.94 12.94 0 0 1-2.024-.977c.17-.122.337-.249.499-.381 3.908 1.838 8.149 1.838 12.01 0 .163.132.329.259.5.381a12.936 12.936 0 0 1-2.028.978 14.344 14.344 0 0 0 1.287 2.105 19.85 19.85 0 0 0 5.996-3.049c.449-4.713-.766-8.806-3.696-12.433zM8.02 14.335c-1.184 0-2.157-1.085-2.157-2.419 0-1.334.95-2.418 2.157-2.418 1.217 0 2.167 1.095 2.157 2.418 0 1.334-.95 2.419-2.157 2.419zm7.975 0c-1.184 0-2.157-1.085-2.157-2.419 0-1.334.95-2.418 2.157-2.418 1.217 0 2.167 1.095 2.157 2.418 0 1.334-.94 2.419-2.157 2.419z"})})}function Gu(a){const t=new Map;for(const s of a){const c=`${s.owner}/${s.repo}`;t.has(c)||t.set(c,{value:c,label:c})}return[...t.values()].sort((s,c)=>s.value.localeCompare(c.value))}function _u(){const[a,t]=o.useState(()=>{try{return localStorage.getItem(ur)==="true"}catch{return!1}}),s=o.useCallback(()=>{t(!0);try{localStorage.setItem(ur,"true")}catch{}},[]);return[a,s]}function Uu(){const[a,t]=o.useState(()=>{try{const s=localStorage.getItem(pa);if(s){const c=JSON.parse(s);if(Date.now()-c.fetchedAt<dr)return c.count}}catch{}return null});return o.useEffect(()=>{try{const s=localStorage.getItem(pa);if(s){const c=JSON.parse(s);if(Date.now()-c.fetchedAt<dr)return}}catch{}fetch("https://api.github.com/repos/Runfusion/Fusion").then(s=>{if(s.ok)return s.json()}).then(s=>{if(s&&typeof s.stargazers_count=="number"){const c={count:s.stargazers_count,fetchedAt:Date.now()};try{localStorage.setItem(pa,JSON.stringify(c))}catch{}t(s.stargazers_count)}}).catch(()=>{})},[]),a}const mr="(max-width: 768px)",ga=".fusion/memory/DREAMS.md";function Tr(a){return a.trim().toLocaleLowerCase()}function Hu(a,t,s,c){return!t||a.isGroupHeader?!0:[s,...a.searchableText??[],...(a.searchableKeys??[]).map(n=>c(n))].map(Tr).some(n=>n.includes(t))}function Wu(a,t,s,c){if(!t)return a;const n=new Set(a.filter(m=>!m.isGroupHeader&&Hu(m,t,s(m),c)).map(m=>m.id));return a.filter((m,i)=>{if(!m.isGroupHeader)return n.has(m.id);for(const r of a.slice(i+1)){if(r.isGroupHeader)return!1;if(n.has(r.id))return!0}return!1})}function hr(a,t){return a.find(s=>!s.isGroupHeader)?.id??t}function $u(a){const t=new Map;let s;for(const c of a){if(c.isGroupHeader){s=c.label;continue}s!==void 0&&t.set(c.id,s)}return t}function Ku(a,t){return a.scope==="global"?`Global — ${t}`:a.scope==="project"?`Project — ${t}`:qu.get(a.id)==="Global"?`Global — ${t}`:t}function pr(a){const t=Number(a?.maxAutoMergeRetries);return Number.isFinite(t)&&t>0?Math.floor(t):3}const ss=[{id:"__global_header",label:"Global",labelKey:"settings.nav.globalHeader",scope:void 0,isGroupHeader:!0},{id:"global-general",label:"General",labelKey:"settings.nav.globalGeneral",scope:"global",searchableText:["global defaults","modal outside dismiss","agent logs","persist tool output","thinking logs","GitLab instance URL","global tracking repo"]},{id:"keyboard-shortcuts",label:"Keyboard Shortcuts",labelKey:"settings.nav.keyboardShortcuts",scope:"global",searchableText:["keyboard shortcuts","hotkeys","quick chat shortcut","terminal shortcut","open files","open settings","command center","new task shortcut","record shortcut"]},{id:"authentication",label:"Authentication",labelKey:"settings.nav.authentication",scope:void 0,icon:At,searchableText:["login","OAuth","API key","custom providers","Anthropic","OpenAI","provider credentials"]},{id:"appearance",label:"Appearance",labelKey:"settings.nav.appearance",scope:"global",searchableText:["theme","color","sidebar","dock","task popup","open tasks as popups","quick chat"]},{id:"notifications",label:"Notifications",labelKey:"settings.nav.notifications",scope:"global",searchableText:["ntfy","webhook","events","failure notifications","sticky","toast"]},{id:"node-sync",label:"Node Sync",labelKey:"settings.nav.nodeSync",scope:"global",searchableText:["sync","node","distributed","heartbeat","coordination"]},{id:"global-models",label:"Models",labelKey:"settings.nav.globalModels",scope:"global",searchableText:["global models","model presets","favorite providers","model pricing overrides","LiteLLM pricing","token pricing"]},{id:"global-mcp",label:"MCP Servers",labelKey:"settings.nav.globalMcp",scope:"global",searchableText:["global MCP servers","shared MCP","user MCP","tool servers"]},{id:"cli-agents",label:"CLI Agents",labelKey:"settings.nav.cliAgents",scope:"global",searchableText:["Droid CLI","Cursor CLI","agent runtime","command line agents","Adapter","Command override","Path or name of the binary to launch","Extra arguments","Appended after the adapter's computed arguments","Environment variable additions","Comma-separated variable names forwarded","Autonomy mode","Elevated autonomy requires a per-project approval"],searchableKeys:["settings.cliAgents.adapterLabel","settings.cliAgents.commandLabel","settings.cliAgents.commandHelp","settings.cliAgents.extraArgsLabel","settings.cliAgents.extraArgsHelp","settings.cliAgents.envLabel","settings.cliAgents.envHelp","settings.cliAgents.autonomyLabel","settings.cliAgents.autonomyHelp","settings.cliAgents.approvedNote"]},{id:"research-global",label:"Research Defaults",labelKey:"settings.nav.researchGlobal",scope:"global",searchableText:["research providers","external search providers","fetch limits","global research defaults","citations"]},{id:"remote",label:"Remote Access",labelKey:"settings.nav.remote",scope:"global",searchableText:["cloudflared","tunnel","QR","persistent token","remote URL"]},{id:"experimental",label:"Experimental Features",labelKey:"settings.nav.experimental",scope:"global",searchableText:["feature flags","experiments","research view","evals view","sandbox","subtask breakdown"]},{id:"__runtimes_header",label:"Runtimes",labelKey:"settings.nav.runtimesHeader",scope:void 0,isGroupHeader:!0},{id:"hermes-runtime",label:"Hermes",labelKey:"settings.nav.hermesRuntime",scope:"global",searchableText:["Hermes runtime","plugin runtime","printer runtime"]},{id:"openclaw-runtime",label:"OpenClaw",labelKey:"settings.nav.openclawRuntime",scope:"global",searchableText:["OpenClaw runtime","plugin runtime","open claw"]},{id:"paperclip-runtime",label:"Paperclip",labelKey:"settings.nav.paperclipRuntime",scope:"global",searchableText:["Paperclip runtime","plugin runtime"]},{id:"__project_header",label:"Project",labelKey:"settings.nav.projectHeader",scope:void 0,isGroupHeader:!0},{id:"general",label:"Project General",labelKey:"settings.nav.projectGeneral",scope:"project",searchableText:["project general","Completion Documentation Automation","Quick Chat launcher","ephemeral task-worker agents","GitHub tracking","GitLab integration","chat rooms","auto-cleanup old chats"]},{id:"commands",label:"Commands & Scripts",labelKey:"settings.nav.commands",scope:"project",searchableText:["test command","build command","verification command","workflow scripts","commands"]},{id:"worktrees",label:"Worktrees",labelKey:"settings.nav.worktrees",scope:"project",searchableText:["worktree directory","copy files","recycle worktrees","branch naming","sibling branch rename"]},{id:"scheduling",label:"Scheduling & Capacity",labelKey:"settings.nav.scheduling",scope:"project",searchableText:["max concurrent","capacity","stuck tasks","poll interval","parallel steps","scheduler"]},{id:"scheduled-evals",label:"Scheduled Evals",labelKey:"settings.nav.scheduledEvals",scope:"project",searchableText:["scheduled evals","evaluation schedule","eval runs","quality jobs"]},{id:"node-routing",label:"Node Routing",labelKey:"settings.nav.nodeRouting",scope:"project",searchableText:["node routing","routing rules","node selection","execution nodes"]},{id:"merge",label:"Merge",labelKey:"settings.nav.merge",scope:"project",searchableText:["auto merge","AI merge","merge strategy","plan approval","direct merge","integration branch","push after merge"]},{id:"agent-permissions",label:"Agents & Permissions",labelKey:"settings.nav.agentPermissions",scope:"project",searchableText:["agent provisioning","approval","permissions","policy","agent creation"]},{id:"memory",label:"Memory",labelKey:"settings.nav.memory",scope:"project",searchableText:["memory backend","Dreams","long-term memory","qmd","memory file","retrieval"]},{id:"backups",label:"Backups",labelKey:"settings.nav.backups",scope:"project",searchableText:["backup","restore","settings export","settings import"]},{id:"research-project",label:"Research",labelKey:"settings.nav.researchProject",scope:"project",searchableText:["project research","research runs","citations","search limits","fetch synthesis"]},{id:"project-models",label:"Project Models",labelKey:"settings.nav.projectModels",scope:"project",searchableText:["default provider","default model","workflow model lanes","Plan/Triage","Executor","Reviewer","summarization model"]},{id:"secrets",label:"Secrets",labelKey:"settings.nav.secrets",scope:"project",searchableText:["secrets","secret storage","environment","credentials"]},{id:"mcp",label:"MCP Servers",labelKey:"settings.nav.mcp",scope:"project",searchableText:["project MCP servers","workspace MCP","project tool servers","mcp config"]},{id:"prompts",label:"Prompts",labelKey:"settings.nav.prompts",scope:"project",searchableText:["prompt instructions","PR title prompt","PR description prompt","custom prompts"]},{id:"plugins",label:"Plugins",labelKey:"settings.nav.plugins",scope:"project",searchableText:["Fusion plugins","Pi extensions","plugin manager","extension marketplace"]}],qu=$u(ss),zu={insights:"Insights",memoryView:"Memory Editor",skillsView:"Skills View",nodesView:"Nodes View",devServerView:"Dev Server",todoView:"Todo List",researchView:"Research View",evalsView:"Evals View",goalsView:"Goals View",subtaskBreakdown:"Subtask Breakdown",leftSidebarNav:"Left Sidebar Navigation",sandbox:"Sandbox (command isolation)",chatRooms:"Chat Rooms",agentOnboarding:"Planning-style Agent Onboarding",workflowInterpreterDualObserve:"Workflow Graph Engine — dual-observe parity (diagnostic)"},Vu=new Set(["chatRooms","goalsView","insights","memoryView","remoteAccess","roadmap","rightDock","skillsView","todoView","workflowColumns","workflowGraphExecutor","workflowInterpreterDualObserve"]),Mr=new Set(["leftSidebarNav"]),cs={devServer:"devServerView"};function Ta(a){return cs[a]??a}function ja(a,t){return a[t]===!0?!0:a[t]===!1?!1:Object.entries(cs).some(([s,c])=>c===t&&a[s]===!0)?!0:Mr.has(t)}function Yu(a,t){const s=Ta(t);return Mr.has(s)&&a[s]===void 0?!0:ja(a,s)}function Qu(a){if(!a)return{};const t={};for(const[s,c]of Object.entries(a))t[Ta(s)]=c;for(const[s,c]of Object.entries(cs))t[c]!==void 0&&!(s in t)&&(t[s]=null);return t}function Ju(a){const t=new Set,s=[];for(const c of a??[]){const n=c.trim();!n||t.has(n)||(t.add(n),s.push(n))}return s}const ba="global-general";function Xu({projectId:a,addToast:t}){const{t:s}=Z("app"),{confirm:c}=yr(),[n,m]=o.useState([]),[i,r]=o.useState({}),[h,k]=o.useState({}),[v,d]=o.useState("");o.useEffect(()=>{let S=!1;return(async()=>{try{const[E,C]=await Promise.all([fetch("/api/cli-agents"),fetch("/api/cli-agents/settings")]),L=E.ok?await E.json():{adapters:[]},y=C.ok?await C.json():{cliAgents:{}};if(S)return;const p=L.adapters??[];m(p),r(y.cliAgents??{}),p.length>0&&d(P=>P||p[0].id)}catch{}})(),()=>{S=!0}},[]),o.useEffect(()=>{if(!v)return;let S=!1;return fetch(`/api/cli-agents/${v}/autonomy`).then(E=>E.ok?E.json():null).then(E=>{S||!E||k(C=>({...C,[v]:!!E.approved}))}).catch(()=>{}),()=>{S=!0}},[v]);const u=i[v]??{},j=o.useCallback(async(S,E)=>{try{const C=await fetch("/api/cli-agents/settings",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({adapterId:S,config:E})});if(!C.ok)throw new Error(`HTTP ${C.status}`);const L=await C.json();r(L.cliAgents??{})}catch(C){t(me(C)||s("settings.cliAgents.saveFailed"),"error")}},[t,s]),x=o.useCallback(S=>{if(!v)return;const E={...u,...S};r(C=>({...C,[v]:E})),j(v,E)},[v,u,j]),b=o.useCallback(async S=>{if(v){if(S==="elevated"){if(!await c({title:s("settings.cliAgents.elevatedConfirmTitle"),message:s("settings.cliAgents.elevatedConfirmBody"),confirmLabel:s("settings.cliAgents.elevatedConfirmAction"),danger:!0}))return;try{const C=await fetch(`/api/cli-agents/${v}/approve-autonomy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:!0})});if(!C.ok)throw new Error(`HTTP ${C.status}`);k(L=>({...L,[v]:!0}))}catch(C){t(me(C)||s("settings.cliAgents.approveFailed"),"error");return}}x({autonomyMode:S})}},[v,c,s,t,x]);return e.jsxs("div",{"data-testid":"cli-agents-settings",children:[e.jsx("h4",{className:"settings-section-heading",children:s("settings.cliAgents.heading")}),e.jsx("p",{className:"settings-section-description",children:s("settings.cliAgents.description")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAdapter",children:s("settings.cliAgents.adapterLabel")}),e.jsx("select",{id:"cliAgentAdapter",value:v,onChange:S=>d(S.target.value),children:n.map(S=>e.jsxs("option",{value:S.id,children:[S.name," (",s(`settings.cliAgents.tier.${S.tier}`),")"]},S.id))})]}),v&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentCommand",children:s("settings.cliAgents.commandLabel")}),e.jsx("input",{id:"cliAgentCommand",type:"text",placeholder:n.find(S=>S.id===v)?.defaultCommand??"",value:u.commandOverride??"",onChange:S=>x({commandOverride:S.target.value||void 0})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.commandHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentExtraArgs",children:s("settings.cliAgents.extraArgsLabel")}),e.jsx("input",{id:"cliAgentExtraArgs",type:"text",value:(u.extraArgs??[]).join(" "),onChange:S=>x({extraArgs:S.target.value.split(/\s+/).filter(E=>E.length>0)})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.extraArgsHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentEnv",children:s("settings.cliAgents.envLabel")}),e.jsx("input",{id:"cliAgentEnv",type:"text",value:(u.envAdditions??[]).join(", "),onChange:S=>x({envAdditions:S.target.value.split(",").map(E=>E.trim()).filter(E=>E.length>0)})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.envHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAutonomy",children:s("settings.cliAgents.autonomyLabel")}),e.jsxs("select",{id:"cliAgentAutonomy",value:u.autonomyMode??"default",onChange:S=>void b(S.target.value),children:[e.jsx("option",{value:"default",children:s("settings.cliAgents.autonomy.default")}),e.jsx("option",{value:"elevated",children:s("settings.cliAgents.autonomy.elevated")})]}),e.jsx("p",{className:"settings-field-help",children:h[v]?s("settings.cliAgents.approvedNote"):s("settings.cliAgents.autonomyHelp")})]})]})]})}function Zu({onClose:a,addToast:t,projectId:s,initialSection:c,themeMode:n="system",colorTheme:m="shadcn-ember",onThemeModeChange:i,onColorThemeChange:r,dashboardFontScalePct:h=100,shadcnCustomColors:k={},resolvedThemeMode:v,onDashboardFontScaleChange:d,onShadcnCustomColorsChange:u,onQuickChatButtonModeChange:j,onReopenOnboarding:x,onOpenApprovals:b,onOpenWorkflowSettings:S,presentation:E="modal"}){const{isEmbedded:C,scrollLockEnabled:L,resizePersistEnabled:y,escapeEnabled:p,overlayDismissEnabled:P}=Ac(E),{t:f}=Z("app"),{confirm:J}=yr(),W=Ho();Wo(L);const{keyboardOverlap:X,viewportHeight:Q,viewportOffsetTop:ne,keyboardOpen:ae}=$o({enabled:W==="mobile"}),V=ae?{"--keyboard-overlap":`${X}px`,"--vv-offset-top":`${ne}px`,...Q!==null?{"--vv-height":`${Q}px`}:{}}:{},$=o.useRef(null),T=o.useRef(null),U=o.useRef(null),re=o.useCallback(l=>{U.current=l},[]);Ko($,y,"fusion:settings-modal-size");const q=qo(),[F,K]=o.useState({maxConcurrent:2,maxTriageConcurrent:2,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,ignoreHiddenOverlapPaths:!0,overlapIgnorePaths:[],allowAbsoluteFileBrowserPaths:!1,autoMerge:!0,planApprovalMode:"auto-approve-all",mergeStrategy:"direct",maxAutoMergeRetries:3,mergeIntegrationWorktree:"reuse-task-worktree",mergeAdvanceAutoSync:"stash-and-ff",merger:{mode:"ai",maxReviewPasses:3,allowDirtyLocalCheckoutSync:!0},recycleWorktrees:!1,showWorktreeGrouping:!1,openTasksInRightSidebar:!1,openMobileTasksInPopup:!1,taskDetailChatFirst:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",worktreeCopyFiles:[],worktreesDir:"",worktrunk:{enabled:!1,binaryPath:"",onFailure:"fail"},includeTaskIdInCommit:!0,worktreeInitCommand:"",ntfyEnabled:!1,ntfyTopic:void 0,ntfyAccessToken:void 0,failureNotificationMode:"sticky-only",failureNotificationDelayMs:3e4,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:void 0,githubLinkImportedIssuesToTracking:!1,prTitlePromptInstructions:"",prDescriptionPromptInstructions:""}),[R,pe]=o.useState(!0),[ge,fe]=o.useState(!1),[be,Pe]=o.useState(null),[A,G]=o.useState(null),[se,ce]=o.useState(null),[B,z]=o.useState(null),M=ss.find(l=>!l.isGroupHeader),[I,H]=o.useState(()=>c==="pi-extensions"?"plugins":c??ba),w=Ou(s,{enabled:I==="worktrees"||F.worktrunk?.enabled===!0}),D=w.status==="installed",[O,ee]=o.useState(()=>c==="pi-extensions"?"pi-extensions":"fusion-plugins"),[le,ue]=o.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(mr)?.matches===!0:!1),[oe,ve]=o.useState(""),[Ae,Ue]=o.useState(null),[Ve,Ma]=o.useState(!1),[ye,Ra]=o.useState(null),[ds,Ia]=o.useState(!1),[Mt,Rt]=o.useState(null),ct=Uu(),[Rr,Ir]=_u(),[us,Er]=o.useState(null),[Fr,dt]=o.useState(null),[Te,ms]=o.useState(null),[Ea,Fa]=o.useState(!1),[Me,hs]=o.useState(null),[ut,It]=o.useState(!1),[De,Et]=o.useState(!1),{entries:Lr,currentPath:Oe,setPath:ps,loading:Dr,error:Or,refresh:Br}=Zs("project",Te!==null,s,{allowAbsolutePaths:!1}),{entries:Gr,currentPath:Be,setPath:gs,loading:_r,error:Ur,refresh:Hr}=Zs("project",Ea,s,{allowAbsolutePaths:!1}),{entries:Wr,currentPath:bs,setPath:fs,loading:$r,error:Kr,refresh:qr}=Zs("project",Me!==null,s,{allowAbsolutePaths:!1}),{nodes:zr}=zo(),La=F.experimentalFeatures??{},Ft=ja(La,"researchView"),Lt=ja(La,"evalsView"),Ye=o.useMemo(()=>ss.filter(l=>l.id==="research-global"||l.id==="research-project"?Ft:l.id==="scheduled-evals"?Lt:!0),[Ft,Lt]),mt=Ye.some(l=>l.id===ba)?ba:hr(Ye,M?.id??"general"),vs=Tr(oe),ht=o.useMemo(()=>Wu(Ye,vs,l=>f(l.labelKey,l.label),l=>f(l)),[vs,f,Ye]),xs=ht.filter(l=>!l.isGroupHeader),pt=vs.length>0,gt=xs.length>0,Da=hr(ht,mt),bt=Ye.find(l=>l.id===I)?.scope;o.useEffect(()=>{if((I==="research-global"||I==="research-project")&&!Ft){H(mt);return}if(I==="scheduled-evals"&&!Lt){H(mt);return}if(!Ye.some(l=>l.id===I)){H(mt);return}pt&&gt&&!ht.some(l=>l.id===I)&&H(Da)},[I,Ft,Lt,mt,Da,pt,gt,ht,Ye]);const[He,ys]=o.useState([]),[Vr,Oa]=o.useState(!1),[Yr,Ne]=o.useState(null),[Qr,ks]=o.useState({}),[Jr,Ba]=o.useState({}),[js,Ga]=o.useState({}),[ws,Cs]=o.useState({}),[Xr,Ns]=o.useState(null),[Ss,Ps]=o.useState({}),[Zr,Dt]=o.useState({}),[el,ft]=o.useState({}),we=o.useRef(null),vt=o.useRef({}),[_a,Ua]=o.useState([]),[Ha,Wa]=o.useState(!1),[et,As]=o.useState([]),[tt,Ts]=o.useState([]),[tl,$a]=o.useState({}),[sl,Ot]=o.useState({}),[xt,Ka]=o.useState(null),[Ge,qa]=o.useState(null),[al,Ms]=o.useState(null),[nl,Bt]=o.useState(!1),[Re,Gt]=o.useState(null),[Rs,Is]=o.useState(null),[rl,za]=o.useState(null),[ll,Va]=o.useState(!1),[il,Es]=o.useState(null),[ol,cl]=o.useState("persistent"),[dl,ul]=o.useState(null),[ml,hl]=o.useState(null),[pl,gl]=o.useState(null),[bl,st]=o.useState(null),[Fs,_t]=o.useState(""),[fl,Ya]=o.useState(!1),[Ls,Ut]=o.useState(!1),[vl,Qa]=o.useState([]),[xl,Ja]=o.useState([]),[yl,kl]=o.useState(!1),[jl,Xa]=o.useState([]),[wl,Za]=o.useState(!1),[Cl,en]=o.useState(null),[Nl,tn]=o.useState([]),[Sl,sn]=o.useState(!1),[Pl,Ds]=o.useState(null),Os=o.useRef(!1),[Al,an]=o.useState([]),[Ie,Bs]=o.useState(ga),[Gs,Tl]=o.useState(""),[Ml,nn]=o.useState(!1),[Rl,rn]=o.useState(null),[Il,ln]=o.useState(!1),[El,on]=o.useState(!1),[Fl,cn]=o.useState(!1),_s=o.useRef(!1),[Ht,dn]=o.useState(4),un=o.useRef(4),mn=o.useRef(!1),Us=o.useRef(!1),[Ll,hn]=o.useState(!1),[Dl,yt]=o.useState(!1),[,Hs]=o.useState(null),[Ee,pn]=o.useState(null),[Wt,$t]=o.useState(!1),[Ws,Ol]=o.useState("both"),[$s,Bl]=o.useState(!0),gn=o.useRef(null),{status:Gl,capabilities:_l,loading:Ul,error:Hl,refresh:bn}=_c({projectId:s,enabled:I==="memory"});o.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia(mr);if(!l)return;const g=N=>{ue(N?N.matches:l.matches)};return g(),l.addEventListener("change",g),()=>l.removeEventListener("change",g)},[]);const kt=o.useCallback(l=>Promise.all([Mn(s),Vo(s)]).then(([g,N])=>{const _={...g,ignoreHiddenOverlapPaths:g.ignoreHiddenOverlapPaths??!0,allowAbsoluteFileBrowserPaths:g.allowAbsoluteFileBrowserPaths===!0,taskDetailChatFirst:g.taskDetailChatFirst===!0,githubLinkImportedIssuesToTracking:g.githubLinkImportedIssuesToTracking===!0,mergeIntegrationWorktree:In(g.mergeIntegrationWorktree),mergeAdvanceAutoSync:Rn(g.mergeAdvanceAutoSync),maxAutoMergeRetries:pr(g),worktreeCopyFiles:Array.isArray(g.worktreeCopyFiles)?g.worktreeCopyFiles:[]};K(_),Pe(_),G(N),ce({gitlabEnabled:N.global.gitlabEnabled,gitlabInstanceUrl:N.global.gitlabInstanceUrl,gitlabApiBaseUrl:N.global.gitlabApiBaseUrl,gitlabAuthToken:N.global.gitlabAuthToken,gitlabAuthTokenType:N.global.gitlabAuthTokenType}),z({...N,project:{...N.project,mergeIntegrationWorktree:N.project.mergeIntegrationWorktree===void 0?void 0:In(N.project.mergeIntegrationWorktree),mergeAdvanceAutoSync:N.project.mergeAdvanceAutoSync===void 0?void 0:Rn(N.project.mergeAdvanceAutoSync)}}),l&&pe(!1)}).catch(g=>{t(me(g),"error"),l&&pe(!1)}),[t,s]);o.useEffect(()=>{kt(!0)},[t,s]),o.useEffect(()=>{if(I!=="scheduling"||mn.current)return;let l=!1;return Yo().then(g=>{l||(Us.current||dn(g.globalMaxConcurrent),un.current=g.globalMaxConcurrent,mn.current=!0,hn(!0))}).catch(()=>{hn(!0)}),()=>{l=!0}},[I]),o.useEffect(()=>{let l=!1;return Qo().then(g=>{l||typeof g.version=="string"&&g.version.trim().length>0&&Ue(g.version)}).catch(()=>{}),()=>{l=!0}},[]);const Wl=o.useCallback(async()=>{Ma(!0),Rt(null);try{const l=await Jo();Ra(l),l.error&&t(l.error,"error")}catch(l){const g=me(l)||f("settings.general.updateCheckFailed","Failed to check for updates");Ra({currentVersion:Ae??"unknown",latestVersion:null,updateAvailable:!1,error:g}),t(g,"error")}finally{Ma(!1)}},[t,Ae,f]),fn=o.useCallback(async()=>{Ia(!0),Rt(null);try{const l=await Xo(s);if(Rt(l),l.error){t(l.error,"error");return}l.updated&&t(f("settings.general.updateSuccessToast","Update installed. Restart Fusion to apply it."),"success")}catch(l){const g=me(l)||f("settings.general.updateFailed","Update failed");Rt({currentVersion:ye?.currentVersion??Ae??"unknown",latestVersion:ye?.latestVersion??null,updated:!1,error:g}),t(g,"error")}finally{Ia(!1)}},[t,Ae,s,f,ye]),$l=o.useCallback(()=>{if(!ye)return null;if(ye.error)return ye.error;if(ye.updateAvailable&&ye.latestVersion){const l=Mt?.updated===!0,g=Mt?.error;return e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[f("settings.general.updateAvailablePrefix","v{{version}} available",{version:ye.latestVersion})," ·"," ",e.jsx("a",{href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",className:"settings-update-result-link",children:f("settings.general.learnMore","Learn more")})]}),l?e.jsx("span",{className:"settings-update-install-status settings-update-install-status--success","aria-live":"polite",children:f("settings.general.updateSuccess","Updated to v{{version}} — restart Fusion to apply",{version:Mt.latestVersion??ye.latestVersion})}):e.jsx("button",{type:"button",className:"btn btn-sm settings-update-now-btn",onClick:()=>{fn()},disabled:ds,children:ds?e.jsxs(e.Fragment,{children:[e.jsx(ns,{size:12,className:"spinning","aria-hidden":"true"}),f("settings.general.updating","Updating…")]}):f("settings.general.updateNow","Update now")}),g&&e.jsx("span",{className:"settings-update-install-status settings-update-install-status--error","aria-live":"polite",children:f("settings.general.updateFailedWithMessage","Update failed: {{message}}",{message:g})})]})}return f("settings.general.upToDate","You're up to date ✓")},[fn,f,ye,ds,Mt]),xe=o.useCallback(async()=>{try{const{providers:l}=await En(),g=Fn(l);ys(g),ks(N=>{const _={};for(const[Y,te]of Object.entries(N)){const ie=g.find(he=>he.id===Y);ie&&!ie.authenticated&&(_[Y]=te)}return Object.keys(_).length===Object.keys(N).length?N:_})}catch{}},[]);o.useEffect(()=>{(I==="global-models"||I==="project-models")&&(Wa(!0),Zo().then(l=>{Ua(l.models),As(l.favoriteProviders),Ts(l.favoriteModels)}).catch(()=>Ua([])).finally(()=>Wa(!1)))},[I]),o.useEffect(()=>{I==="backups"&&(Bt(!0),Ln(s).then(l=>Ms(l)).catch(()=>Ms(null)).finally(()=>Bt(!1)))},[I,s]);const Kt=o.useCallback(async()=>{const[l,g]=await Promise.allSettled([ec(s),ea(s)]);l.status==="fulfilled"&&K(N=>({...N,...l.value.settings})),g.status==="fulfilled"&&(Gt(g.value),Is(g.value.externalTunnel??null))},[s]);o.useEffect(()=>{const l=Re?.state;(l==="running"||l==="starting")&&Is(null)},[Re?.state]),o.useEffect(()=>{I==="remote"&&Kt().catch(()=>{Gt(null)})},[I,Kt]),o.useEffect(()=>{if(I!=="remote")return;const l=Re?.state;if(l!=="starting"&&l!=="stopping")return;const g=setInterval(()=>{ea(s).then(N=>{Gt(N),Is(N.externalTunnel??null)}).catch(()=>{})},1e3);return()=>clearInterval(g)},[I,s,Re?.state]),o.useEffect(()=>{if(I!=="remote")return;if(Re?.state!=="running"){st(null);return}let l=!1;return(async()=>{try{const g=await xa("image/svg",{projectId:s,tokenType:"persistent"});if(l)return;st({url:g.url,qrSvg:g.data??null})}catch{if(l)return;try{const g=await br({projectId:s,tokenType:"persistent"});if(l)return;st({url:g.url,qrSvg:null})}catch{l||st(null)}}})(),()=>{l=!0}},[I,s,Re?.state,Re?.url]),o.useEffect(()=>{if(I!=="remote")return;const l=Rs?.url;if(Re?.state!=="stopped"||!l)return;let g=!1;return(async()=>{try{const N=await xa("image/svg",{projectId:s,tokenType:"persistent"});if(g)return;st({url:l,qrSvg:N.data??null})}catch{g||st({url:l,qrSvg:null})}})(),()=>{g=!0}},[I,Rs?.url,s,Re?.state]),o.useEffect(()=>{I==="worktrees"&&tc(s).then(l=>Qa(l)).catch(()=>Qa([]))},[I,s]),o.useEffect(()=>{I==="merge"&&sc(s).then(l=>{const g=l.map(te=>te.name).filter(te=>typeof te=="string"&&te.length>0),N=new Set,_=["main","master","trunk","develop"],Y=[];for(const te of _)g.includes(te)&&!N.has(te)&&(Y.push(te),N.add(te));for(const te of[...g].sort((ie,he)=>ie.localeCompare(he)))N.has(te)||(N.add(te),Y.push(te));Ja(Y)}).catch(()=>Ja([]))},[I,s]),o.useEffect(()=>{if(I!=="general")return;let l=!1;return Za(!0),en(null),Dn(s).then(g=>{l||Xa(Gu(g))}).catch(()=>{l||(Xa([]),en("Could not load detected remotes. Enter a custom owner/repo value."))}).finally(()=>{l||Za(!1)}),()=>{l=!0}},[I,s]),o.useEffect(()=>{if(I!=="global-general"||Os.current)return;let l=!1;return sn(!0),Ds(null),ac().then(async g=>{const N=await Promise.allSettled(g.map(async ie=>(await Dn(ie.id)).map(ke=>({value:`${ke.owner}/${ke.repo}`,label:`${ke.owner}/${ke.repo}`,source:ie.name}))));if(l)return;const _=new Map;let Y=0;for(const ie of N)if(ie.status==="fulfilled"){Y+=1;for(const he of ie.value)_.has(he.value)||_.set(he.value,he)}const te=[..._.values()].sort((ie,he)=>ie.value.localeCompare(he.value));tn(te),g.length>0&&Y===0&&Ds("Could not load remotes from registered projects. Enter a custom owner/repo value."),Os.current=!0}).catch(()=>{l||(tn([]),Ds("Could not load project list. Enter a custom owner/repo value."),Os.current=!0)}).finally(()=>{l||sn(!1)}),()=>{l=!0}},[I,s]),o.useEffect(()=>{if(I!=="memory"||Ls)return;if(_s.current){_s.current=!1;return}let l=!1;return Ya(!0),On(s).then(async({files:g})=>{if(l)return;an(g);const N=g.some(Y=>Y.path===Ie)?Ie:g.find(Y=>Y.path===ga)?.path??g.find(Y=>Y.layer==="dreams")?.path??g[0]?.path??ga;Bs(N);const{content:_}=await nc(N,s);l||(_t(_),Ut(!1))}).catch(g=>{l||(t(me(g)||"Failed to load project memory","error"),_t(""))}).finally(()=>{l||Ya(!1)}),()=>{l=!0}},[I,Ls,Ie,s,t]),o.useEffect(()=>((I==="authentication"||I==="research-global")&&(Oa(!0),xe().finally(()=>Oa(!1))),()=>{we.current&&(clearInterval(we.current),we.current=null)}),[I,xe]),o.useEffect(()=>{if(I!=="authentication"||!He.some(N=>N.type!=="api_key"&&N.loginInProgress))return;const g=setInterval(()=>{xe()},2e3);return()=>clearInterval(g)},[I,He,xe]);const qt=o.useRef({});o.useEffect(()=>{for(const l of He){const g=l.loginError;if(!g){l.id in qt.current&&delete qt.current[l.id];continue}qt.current[l.id]!==g&&(qt.current[l.id]=g,t(`${l.name} login failed: ${g}`,"error"))}},[He,t]);const zt=o.useCallback(()=>{T.current?.scrollTo({top:0,behavior:"smooth"})},[]),Qe=o.useCallback(l=>{if(l in vt.current){const g={...vt.current};delete g[l],vt.current=g}ks(g=>{if(!(l in g))return g;const N={...g};return delete N[l],N}),Ba(g=>{if(!(l in g))return g;const N={...g};return delete N[l],N}),Cs(g=>{if(!(l in g))return g;const N={...g};return delete N[l],N}),Ga(g=>{if(!(l in g))return g;const N={...g};return delete N[l],N})},[]);o.useEffect(()=>{const l=js["github-copilot"];l?.userCode&&vt.current["github-copilot"]!==l.userCode&&(vt.current["github-copilot"]=l.userCode,fr(l.userCode))},[js]);const Kl=o.useCallback(async l=>{const g=He.find(N=>N.id===l);if(!(g?.requiresManualCode===!0&&!await J({title:f("settings.auth.manualPasteTitle","Heads up — manual paste-back required"),message:f("settings.auth.manualPasteMessage","After you sign in with {{name}}, the browser will try to redirect to a localhost address that this dashboard can't reach. The redirect tab will look like it failed. Before that happens, copy the full URL from the browser address bar — you'll paste it back here to finish login. Continue?",{name:g.name}),confirmLabel:f("settings.auth.continueToLogin","Continue to login"),cancelLabel:f("settings.actions.cancel","Cancel")}))){Ne(l),Qe(l);try{const{url:N,instructions:_,manualCode:Y,deviceCode:te}=await rc(l);_?.trim()&&!(l==="github-copilot"&&te)&&ks(ie=>({...ie,[l]:_})),Y&&Ba(ie=>({...ie,[l]:Y})),te&&l==="github-copilot"&&Ga(ie=>({...ie,[l]:te})),(l!=="github-copilot"||!te)&&window.open(vr(te?.verificationUri??N),"_blank"),we.current=setInterval(async()=>{try{const{providers:ie}=await En(),he=Fn(ie);ys(he);const ke=he.find(Ys=>Ys.id===l);if(ke?.authenticated){we.current&&(clearInterval(we.current),we.current=null),Ne(null),Qe(l),t(f("settings.auth.loginSuccessful","Login successful"),"success"),window.dispatchEvent(new CustomEvent(lc,{detail:{providerId:l}})),zt();return}ke?.loginInProgress||(we.current&&(clearInterval(we.current),we.current=null),Ne(null),Qe(l),t(f("settings.auth.loginDidNotComplete","Login did not complete. Please try again."),"error"))}catch{}},2e3)}catch(N){const _=me(N)||"Login failed";_.includes("already in progress")||typeof N=="object"&&N!==null&&"status"in N&&N.status===409?(t(f("settings.auth.loginAlreadyInProgress","Login already in progress. You can cancel it and retry."),"warning"),await xe()):t(_,"error"),Ne(null),Qe(l)}}},[t,He,Qe,J,xe,zt]),ql=o.useCallback(async l=>{const g=ws[l]?.trim();if(!g){t(f("settings.auth.pasteRedirectUrlFirst","Paste the full redirect URL or authorization code first."),"warning");return}Ns(l);try{(await ic(l,g)).submitted?(Cs(_=>{if(!(l in _))return _;const Y={..._};return delete Y[l],Y}),t(f("settings.auth.authCodeReceived","Authorization code received. Finishing login…"),"success")):t(f("settings.auth.authCodeAlreadySubmitted","That authorization code was already submitted. Waiting for login…"),"warning")}catch(N){t(me(N)||"Failed to submit authorization code","error")}finally{Ns(null)}},[t,ws]),zl=o.useCallback(async l=>{Ne(l),ys(g=>g.map(N=>N.id===l?{...N,loginInProgress:!1}:N));try{await oc(l),Qe(l),await xe().catch(()=>{}),t(f("settings.auth.loginCancelled","Login cancelled"),"success")}catch(g){t(me(g)||"Failed to cancel login","error")}finally{Ne(null),Ns(g=>g===l?null:g),we.current&&(clearInterval(we.current),we.current=null)}},[t,Qe,xe]),Vl=o.useCallback(async l=>{Ne(l);try{await cc(l),await xe(),t(f("settings.auth.loggedOut","Logged out"),"success")}catch(g){t(me(g)||"Logout failed","error")}finally{Ne(null)}},[t,xe]),Yl=o.useCallback(async l=>{const g=Ss[l]?.trim();if(!g){Dt(N=>({...N,[l]:"API key is required"}));return}Ne(l),Dt(N=>{const _={...N};return delete _[l],_});try{const N=await dc(l,g);if(Ps(_=>{const Y={..._};return delete Y[l],Y}),await xe(),l==="opencode"||l==="opencode-go"){const _=N.modelsRefreshed,Y=N.refreshReason,te=N.refreshError;te?ft(ie=>({...ie,[l]:{tone:"error",message:`Saved, but model refresh failed: ${te}. Make sure the \`opencode\` CLI is installed on PATH.`}})):Y==="no-models-from-cli"?ft(ie=>({...ie,[l]:{tone:"error",message:"Saved. The local `opencode` CLI returned no models — run `opencode auth login` and `opencode models opencode --refresh`, then click Save again."}})):typeof _=="number"&&_>0?ft(ie=>({...ie,[l]:{tone:"success",message:`Refreshed ${_} opencode-go models.`}})):ft(ie=>{const he={...ie};return delete he[l],he})}t(f("settings.auth.apiKeySaved","API key saved"),"success"),zt()}catch(N){Dt(_=>({..._,[l]:me(N)||"Failed to save API key"})),(l==="opencode"||l==="opencode-go")&&ft(_=>{const Y={..._};return delete Y[l],Y})}finally{Ne(null)}},[Ss,t,xe,zt]),Ql=o.useCallback(async l=>{Ne(l);try{await uc(l),Ps(g=>{const N={...g};return delete N[l],N}),Dt(g=>{const N={...g};return delete N[l],N}),await xe(),t(f("settings.auth.apiKeyCleared","API key cleared"),"success")}catch(g){t(me(g)||"Failed to clear API key","error")}finally{Ne(null)}},[t,xe]),Jl=o.useCallback(async l=>{if(!((l==="ntfy"||l==="ntfy-message"||l==="ntfy-room")&&(!F.ntfyEnabled||!F.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(F.ntfyTopic)))){if(l==="webhook"){if(!F.webhookEnabled||!F.webhookUrl?.trim())return;try{const g=new URL(F.webhookUrl.trim());if(g.protocol!=="http:"&&g.protocol!=="https:")return}catch{return}}$a(g=>({...g,[l]:!0})),Ot(g=>{const N={...g};return delete N[l],N});try{const g={ntfyEnabled:F.ntfyEnabled,ntfyTopic:F.ntfyTopic,...F.ntfyBaseUrl?.trim()?{ntfyBaseUrl:F.ntfyBaseUrl.trim()}:{},...F.ntfyAccessToken?.trim()?{ntfyAccessToken:F.ntfyAccessToken.trim()}:{}},N=l==="ntfy"?g:l==="ntfy-message"?{...g,messageEventType:"message:agent-to-user"}:l==="ntfy-room"?{...g,messageEventType:"message:room"}:{webhookUrl:F.webhookUrl,webhookFormat:F.webhookFormat||"generic"};if((await mc(l==="ntfy-message"||l==="ntfy-room"?"ntfy":l,N,s)).success){const Y=l==="ntfy"?"Test notification sent — check your ntfy app!":l==="ntfy-message"?"Message inbox test sent — check your ntfy inbox for the agent-to-user message.":l==="ntfy-room"?"Room reply test sent — check your ntfy inbox for the room reply.":"Test notification sent — check your webhook endpoint!";Ot(te=>({...te,[l]:{status:"success",message:Y}})),t(Y,"success")}else{const Y=l==="ntfy-message"?"Failed to send message inbox test":l==="ntfy-room"?"Failed to send room reply test":"Failed to send test notification";Ot(te=>({...te,[l]:{status:"error",message:Y}})),t(Y,"error")}}catch(g){const N=me(g)||"Failed to send test notification";Ot(_=>({..._,[l]:{status:"error",message:N}})),t(N,"error")}finally{$a(g=>({...g,[l]:!1}))}}},[t,F.ntfyAccessToken,F.ntfyBaseUrl,F.ntfyEnabled,F.ntfyTopic,F.webhookEnabled,F.webhookFormat,F.webhookUrl,s]),Xl=o.useCallback(async()=>{Bt(!0);try{const l=await hc(s);if(l.success){t(f("settings.backups.backupCreated","Backup created successfully"),"success");const g=await Ln(s);Ms(g)}else t(l.error||f("settings.backups.createFailed","Failed to create backup"),"error")}catch(l){t(me(l)||f("settings.backups.createFailed","Failed to create backup"),"error")}finally{Bt(!1)}},[t,s]),Zl=o.useCallback(async()=>{try{const l=bt==="global"?"global":bt==="project"?"project":"both",g=await pc(l,s),N=new Blob([JSON.stringify(g,null,2)],{type:"application/json"}),_=URL.createObjectURL(N),Y=document.createElement("a"),te=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;Y.href=_,Y.download=te,document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),URL.revokeObjectURL(_);const ie=l==="global"?f("settings.importExport.scopeLabel.global","global"):l==="project"?f("settings.importExport.scopeLabel.project","project"):f("settings.importExport.scopeLabel.all","all");t(f("settings.importExport.exported","Settings exported ({{scope}} scope)",{scope:ie}),"success")}catch(l){t(me(l)||f("settings.importExport.exportFailed","Failed to export settings"),"error")}},[t,bt,s]),ei=o.useCallback(async l=>{const g=l.target.files?.[0];if(g){Hs(g),$t(!0);try{const N=await g.text(),_=JSON.parse(N);pn(_),yt(!0)}catch(N){t(f("settings.importExport.invalidJson","Invalid JSON file: {{error}}",{error:me(N)}),"error"),Hs(null)}finally{$t(!1)}}},[t]),ti=o.useCallback(async()=>{if(Ee){$t(!0);try{const l=await gc(Ee,{scope:Ws,merge:$s},s);if(l.success){const g=[];l.globalCount>0&&g.push(f("settings.importExport.counts.global","{{count}} global",{count:l.globalCount})),l.projectCount>0&&g.push(f("settings.importExport.counts.project","{{count}} project",{count:l.projectCount})),l.workflowSettingsCount>0&&g.push(f("settings.importExport.counts.workflowSettings","{{count}} workflow setting value",{count:l.workflowSettingsCount})),t(f("settings.importExport.imported","Imported {{counts}} setting(s)",{counts:g.join(", ")}),"success"),yt(!1),pn(null),Hs(null);const N=await Mn(s);K({...N,ignoreHiddenOverlapPaths:N.ignoreHiddenOverlapPaths??!0,allowAbsoluteFileBrowserPaths:N.allowAbsoluteFileBrowserPaths===!0})}else t(l.error||f("settings.importExport.importFailed","Import failed"),"error")}catch(l){t(me(l)||f("settings.importExport.importFailedDetailed","Failed to import settings"),"error")}finally{$t(!1)}}},[t,Ee,Ws,$s,s]),vn=o.useCallback(async l=>{const g=et,_=g.includes(l)?g.filter(Y=>Y!==l):[l,...g];As(_);try{await lt({favoriteProviders:_,favoriteModels:tt})}catch{As(g)}},[et,tt]),xn=o.useCallback(async l=>{const g=tt,_=g.includes(l)?g.filter(Y=>Y!==l):[l,...g];Ts(_);try{await lt({favoriteProviders:et,favoriteModels:_})}catch{Ts(g)}},[tt,et]);o.useEffect(()=>{if(!p)return;const l=g=>{g.key==="Escape"&&!ut&&a()};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[a,p,ut]);const si=bc(a),ai=P?si:{},yn=[{laneId:"default",label:"Default Model",globalProviderKey:"defaultProvider",globalModelKey:"defaultModelId",projectProviderKey:"defaultProviderOverride",projectModelKey:"defaultModelIdOverride",helperText:"Default AI model used for task execution when no per-task override is set.",fallbackOrder:"Project override → Global default lane → Automatic resolution"},{laneId:"execution",label:"Execution Model",globalProviderKey:"executionGlobalProvider",globalModelKey:"executionGlobalModelId",projectProviderKey:"executionProvider",projectModelKey:"executionModelId",helperText:"AI model used for task implementation (executor agent).",fallbackOrder:"Project override → Global execution lane → Global default lane → Automatic resolution"},{laneId:"planning",label:"Planning Model",globalProviderKey:"planningGlobalProvider",globalModelKey:"planningGlobalModelId",projectProviderKey:"planningProvider",projectModelKey:"planningModelId",helperText:"AI model used for task planning.",fallbackOrder:"Project override → Global planning lane → Global default lane → Automatic resolution"},{laneId:"validator",label:"Reviewer Model",globalProviderKey:"validatorGlobalProvider",globalModelKey:"validatorGlobalModelId",projectProviderKey:"validatorProvider",projectModelKey:"validatorModelId",helperText:"AI model used for code and specification review.",fallbackOrder:"Project override → Global reviewer lane → Global default lane → Automatic resolution"},{laneId:"summarization",label:"Title and Git Commit Message Summarization Model",globalProviderKey:"titleSummarizerGlobalProvider",globalModelKey:"titleSummarizerGlobalModelId",projectProviderKey:"titleSummarizerProvider",projectModelKey:"titleSummarizerModelId",helperText:"AI model used for auto-generating task titles and merge commit summaries.",fallbackOrder:"Project override → Global summarization lane → Project planning lane → Project default lane → Global default lane → Automatic resolution"}];function Ks(l){if(!A?.project)return"inherited";const g=A.project[l.projectProviderKey],N=A.project[l.projectModelKey];return g!==void 0||N!==void 0?"overridden":"inherited"}function ni(l){const g=F[l.projectProviderKey],N=F[l.projectModelKey];return g&&N?`${g}/${N}`:""}function ri(l,g){if(g){const N=g.indexOf("/");K(_=>({..._,[l.projectProviderKey]:g.slice(0,N),[l.projectModelKey]:g.slice(N+1)}))}else{if(Ks(l)==="inherited")return;K(_=>({..._,[l.projectProviderKey]:void 0,[l.projectModelKey]:void 0}))}}function li(l){Ks(l)!=="inherited"&&K(N=>({...N,[l.projectProviderKey]:void 0,[l.projectModelKey]:void 0}))}const ii=o.useCallback(l=>{ms(l),ps(".")},[ps]),We=o.useCallback(()=>{ms(null)},[]),qs=o.useCallback(l=>{Te!==null&&(Zt(l)||(K(g=>{const N=g.overlapIgnorePaths&&g.overlapIgnorePaths.length>0?[...g.overlapIgnorePaths]:[""];return N[Te]=l,{...g,overlapIgnorePaths:N}}),We()))},[Te,We]),oi=o.useCallback(()=>{if(Oe===".")return;const l=Oe.endsWith("/")?Oe:`${Oe}/`;qs(l)},[Oe,qs]),ci=o.useCallback(l=>{l.target===l.currentTarget&&We()},[We]),di=o.useCallback(()=>{gs("."),Fa(!0)},[gs]),$e=o.useCallback(()=>{Fa(!1)},[]),ui=o.useCallback(l=>{if(Zt(l))return;const g=l.endsWith("/")?l:`${l}/`;K(N=>({...N,worktreesDir:g})),$e()},[$e]),mi=o.useCallback(()=>{if(Zt(Be))return;const l=Be==="."?"./":Be.endsWith("/")?Be:`${Be}/`;K(g=>({...g,worktreesDir:l})),$e()},[Be,$e]),hi=o.useCallback(l=>{l.target===l.currentTarget&&$e()},[$e]),pi=o.useCallback(l=>{hs(l),fs(".")},[fs]),Ke=o.useCallback(()=>{hs(null)},[]),gi=o.useCallback(l=>{Me!==null&&(Zt(l)||(K(g=>{const N=g.worktreeCopyFiles&&g.worktreeCopyFiles.length>0?[...g.worktreeCopyFiles]:[""];return N[Me]=l,{...g,worktreeCopyFiles:N}}),Ke()))},[Me,Ke]),bi=o.useCallback(l=>{l.target===l.currentTarget&&Ke()},[Ke]),fi=o.useCallback((l,g)=>{K(N=>{const _=N.worktreeCopyFiles&&N.worktreeCopyFiles.length>0?[...N.worktreeCopyFiles]:[""];return _[l]=g,{...N,worktreeCopyFiles:_}})},[]),vi=o.useCallback(l=>{if(K(g=>{const _=(g.worktreeCopyFiles&&g.worktreeCopyFiles.length>0?[...g.worktreeCopyFiles]:[""]).filter((Y,te)=>te!==l);return{...g,worktreeCopyFiles:_.length>0?_:[]}}),Me===l){Ke();return}Me!==null&&Me>l&&hs(Me-1)},[Me,Ke]),xi=o.useCallback(()=>{K(l=>{const g=l.worktreeCopyFiles&&l.worktreeCopyFiles.length>0?l.worktreeCopyFiles:[""];return{...l,worktreeCopyFiles:[...g,""]}})},[]),yi=o.useCallback((l,g)=>{K(N=>{const _=N.overlapIgnorePaths&&N.overlapIgnorePaths.length>0?[...N.overlapIgnorePaths]:[""];return _[l]=g,{...N,overlapIgnorePaths:_}})},[]),ki=o.useCallback(l=>{if(K(g=>{const _=(g.overlapIgnorePaths&&g.overlapIgnorePaths.length>0?[...g.overlapIgnorePaths]:[""]).filter((Y,te)=>te!==l);return{...g,overlapIgnorePaths:_.length>0?_:[]}}),Te===l){We();return}Te!==null&&Te>l&&ms(Te-1)},[Te,We]),ji=o.useCallback(()=>{K(l=>{const g=l.overlapIgnorePaths&&l.overlapIgnorePaths.length>0?l.overlapIgnorePaths:[""];return{...l,overlapIgnorePaths:[...g,""]}})},[]),wi=o.useCallback(async()=>{if(ge||us||Ge)return;const l=F.researchSettings?.limits;if(l?.maxConcurrentRuns!==void 0&&(!Number.isFinite(l.maxConcurrentRuns)||l.maxConcurrentRuns<1)){dt("Research max concurrent runs must be at least 1.");return}if(l?.maxSourcesPerRun!==void 0&&(!Number.isFinite(l.maxSourcesPerRun)||l.maxSourcesPerRun<1)){dt("Research max sources per run must be at least 1.");return}if(l?.maxDurationMs!==void 0&&(!Number.isFinite(l.maxDurationMs)||l.maxDurationMs<1e3)){dt("Research max duration must be at least 1000 ms.");return}if(l?.requestTimeoutMs!==void 0&&(!Number.isFinite(l.requestTimeoutMs)||l.requestTimeoutMs<1e3)){dt("Research request timeout must be at least 1000 ms.");return}dt(null);const g=gr(F.dashboardKeyboardShortcuts??{});if(g){t(g,"error");return}fe(!0);try{const N=Ju(F.worktreeCopyFiles);let _=D;F.worktrunk?.enabled===!0&&!_&&(_=(await w.refresh()).status==="installed");const Y=I==="global-general"&&se?se:F,te={...F,worktreeInitCommand:F.worktreeInitCommand?.trim()||void 0,worktreesDir:F.worktreesDir?.trim()||void 0,worktrunk:{enabled:_&&F.worktrunk?.enabled===!0,binaryPath:F.worktrunk?.binaryPath?.trim()||void 0,onFailure:F.worktrunk?.onFailure??"fail"},maxAutoMergeRetries:pr(F),taskPrefix:F.taskPrefix?.trim()||void 0,githubTrackingDefaultRepo:F.githubTrackingDefaultRepo?.trim()||void 0,dashboardKeyboardShortcuts:Object.fromEntries(Object.entries(va(F.dashboardKeyboardShortcuts)).map(([ke,Ys])=>[ke,wa(Ys).normalized])),gitlabEnabled:Y.gitlabEnabled,gitlabInstanceUrl:Y.gitlabInstanceUrl?.trim()||void 0,gitlabApiBaseUrl:Y.gitlabApiBaseUrl?.trim()||void 0,gitlabAuthToken:Y.gitlabAuthToken?.trim()||void 0,gitlabAuthTokenType:Y.gitlabAuthTokenType??"personal",githubAuthToken:F.githubAuthToken?.trim()||void 0,prTitlePromptInstructions:F.prTitlePromptInstructions?.trim()||void 0,prDescriptionPromptInstructions:F.prDescriptionPromptInstructions?.trim()||void 0,pushRemote:F.pushAfterMerge&&F.pushRemote?.trim()||void 0,overlapIgnorePaths:(F.overlapIgnorePaths??[]).map(ke=>ke.trim()).filter(ke=>ke.length>0),worktreeCopyFiles:N.length>0||B?.project?.worktreeCopyFiles!==void 0?N:void 0,experimentalFeatures:Qu(F.experimentalFeatures)};I==="general"&&qn({project:{gitlabInstanceUrl:te.gitlabInstanceUrl,gitlabApiBaseUrl:te.gitlabApiBaseUrl}}),I==="global-general"&&qn({global:{gitlabInstanceUrl:te.gitlabInstanceUrl,gitlabApiBaseUrl:te.gitlabApiBaseUrl}});const{globalPatch:ie,projectPatch:he}=nd({payload:te,initialValues:be,initialScopedValues:B,activeSection:I});await Promise.all([Object.keys(ie).length>0?lt(ie):Promise.resolve(),Object.keys(he).length>0?ta(he,s):Promise.resolve(),Ht!==un.current?fc({globalMaxConcurrent:Ht??4}):Promise.resolve()]),await U.current?.(),t(f("settings.general.settingsSaved","Settings saved"),"success"),a()}catch(N){if(N instanceof Ar)return;t(me(N),"error")}finally{fe(!1)}},[F,se,Ht,us,Ge,be,B,a,t,s,I,ge,f]),at=o.useMemo(()=>ld(I),[I]),zs=o.useMemo(()=>id(I),[I]),Vs=o.useMemo(()=>{const l=ss.find(g=>g.id===I);return l?f(l.labelKey,l.label):I},[I,f]),Ci=o.useCallback(async()=>{if(!(De||!at)){Et(!0);try{if(at.scope==="global"){const l={};for(const g of at.keys)l[g]=vc[g];await lt(l)}else{const l={};for(const g of at.keys)l[g]=null;await ta(l,s)}await kt(!1),t(f("settings.reset.menuResetSuccess","{{section}} settings reset to defaults",{section:Vs}),"success"),It(!1)}catch(l){t(me(l),"error")}finally{Et(!1)}}},[De,at,s,kt,t,f,Vs]),Ni=o.useCallback(async()=>{if(!De){Et(!0);try{const l={};for(const g of od)l[g]=null;await ta(l,s),await kt(!1),t(f("settings.reset.allProjectResetSuccess","All project settings reset to defaults"),"success"),It(!1)}catch(l){t(me(l),"error")}finally{Et(!1)}}},[De,s,kt,t,f]),nt=o.useCallback(()=>{De||It(!1)},[De]),Si=o.useCallback(l=>{l.target===l.currentTarget&&nt()},[nt]);o.useEffect(()=>{if(!ut)return;const l=g=>{g.key==="Escape"&&(g.stopPropagation(),nt())};return document.addEventListener("keydown",l,!0),()=>document.removeEventListener("keydown",l,!0)},[ut,nt]);const Pi=o.useCallback(async()=>{try{await xc(Ie,Fs,s),Ut(!1),t(f("settings.memory.memorySaved","Memory saved"),"success")}catch(l){t(me(l)||"Failed to save memory","error")}},[Ie,Fs,s,t]),Ai=o.useCallback(async()=>{on(!0);try{const{path:l,content:g}=await yc(Ie,s),N=l??Ie;Ie!==N&&(_s.current=!0),Bs(N),_t(g),Ut(!1);const{files:_}=await On(s);an(_),t(f("settings.memory.memoryCompacted","Memory file compacted"),"success")}catch(l){t(me(l)||"Failed to compact memory","error")}finally{on(!1)}},[Ie,s,t]),Ti=o.useCallback(async()=>{nn(!0),rn(null);try{const l=await kc(Gs,s);rn(l),t(l.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",l.qmdAvailable?"success":"warning")}catch(l){t(me(l)||"Failed to test memory retrieval","error")}finally{nn(!1)}},[Gs,s,t]),Mi=o.useCallback(async()=>{ln(!0);try{await jc(s),t(f("settings.memory.dreamCompleted","Dream processing completed"),"success")}catch(l){t(l instanceof Error?l.message:"Failed to run dream processing","error")}finally{ln(!1)}},[s,t]),Ri=o.useCallback(async()=>{cn(!0);try{const l=await wc(s);await bn(),t(l.qmdAvailable?f("settings.memory.qmdInstalled","qmd installed successfully"):f("settings.memory.qmdInstallUnavailable","qmd install finished, but qmd is still unavailable"),l.qmdAvailable?"success":"warning")}catch(l){t(me(l)||f("settings.memory.qmdInstallFailed","Failed to install qmd"),"error")}finally{cn(!1)}},[s,bn,t]),Ii=()=>{if(!Ge)return;const l=Ge.name.trim();if(!l){t(f("settings.models.presetNameRequired","Preset name is required"),"error");return}const g=F.modelPresets||[];let N;xt?N=xt:N=Mc(l,g);const _={id:N,name:l,executorProvider:Ge.executorProvider,executorModelId:Ge.executorModelId,validatorProvider:Ge.validatorProvider,validatorModelId:Ge.validatorModelId};K(Y=>{const te=Y.modelPresets||[],ie=xt?te.map(he=>he.id===xt?_:he):[...te,_];return{...Y,modelPresets:ie}}),Ka(null),qa(null)},Ei=o.useCallback(async(l,g)=>{za(l);try{await g(),await Kt()}catch(N){t(me(N)||`Failed to ${l}`,"error")}finally{za(null)}},[t,Kt]),Fi=o.useCallback(()=>{if(typeof navigator<"u"&&navigator.userAgent.includes("Windows"))return"winget install Cloudflare.cloudflared";const l=typeof navigator<"u"?navigator.platform:"",g=typeof navigator<"u"?navigator.userAgent:"",N=/(Mac|iPhone|iPad|iPod)/i.test(l),_=/(arm64|aarch64)/i.test(`${l} ${g}`);return N?"brew install cloudflared":`curl -L --output /tmp/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${_?"arm64":"amd64"} && chmod +x /tmp/cloudflared && sudo mv /tmp/cloudflared /usr/local/bin/cloudflared # If sudo is unavailable, use: mkdir -p ~/.local/bin && mv /tmp/cloudflared ~/.local/bin/cloudflared`},[]),Li=o.useCallback(()=>typeof navigator>"u"||!/(Mac|iPhone|iPad|iPod)/i.test(navigator.platform)?null:`curl -L --output /tmp/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-${/(arm64|aarch64)/i.test(`${navigator.platform} ${navigator.userAgent}`)?"arm64":"amd64"} && chmod +x /tmp/cloudflared && sudo mv /tmp/cloudflared /usr/local/bin/cloudflared`,[]),Di=o.useCallback(async()=>{Va(!0),Es(null);try{const l=await Cc(s);if(!l.success){Es(l.error??f("settings.remote.installationFailed","Installation failed"));return}const g=await ea(s);Gt(g),t(f("settings.remote.cloudflaredInstalled","cloudflared installed successfully"),"success")}catch(l){Es(l instanceof Error?l.message:f("settings.remote.installationFailed","Installation failed"))}finally{Va(!1)}},[t,s]),de=()=>bt==="global"?e.jsxs("div",{className:"settings-scope-banner settings-scope-global",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(At,{size:14})}),e.jsx("span",{children:f("settings.scope.globalBanner","These settings are shared across all your Fusion projects.")})]}):bt==="project"?e.jsxs("div",{className:"settings-scope-banner settings-scope-project",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(Bn,{size:14})}),e.jsx("span",{children:f("settings.scope.projectBanner","These settings only affect this project.")})]}):null,Oi=()=>{switch(I){case"cli-agents":return e.jsxs(e.Fragment,{children:[de(),e.jsx(Xu,{projectId:s,addToast:t})]});case"general":return e.jsx(cu,{scopeBanner:de(),form:F,setForm:K,projectId:s,addToast:t,prefixError:us,setPrefixError:Er,projectTrackingRepoOptions:jl,projectTrackingRepoLoading:wl,projectTrackingRepoError:Cl,onQuickChatButtonModeChange:j});case"global-general":return e.jsx(yd,{scopeBanner:de(),form:F,setForm:K,globalSettings:se,onGlobalGitlabSettingsChange:l=>ce(g=>({gitlabEnabled:g?.gitlabEnabled,gitlabInstanceUrl:g?.gitlabInstanceUrl,gitlabApiBaseUrl:g?.gitlabApiBaseUrl,gitlabAuthToken:g?.gitlabAuthToken,gitlabAuthTokenType:g?.gitlabAuthTokenType,...l})),globalTrackingRepoOptions:Nl,globalTrackingRepoLoading:Sl,globalTrackingRepoError:Pl});case"keyboard-shortcuts":return e.jsx(jd,{scopeBanner:de(),form:F,setForm:K});case"global-models":return e.jsx(Ld,{scopeBanner:de(),form:F,setForm:K,availableModels:_a,modelsLoading:Ha,globalModelLanes:yn.filter(l=>l.laneId!=="default"),favoriteProviders:et,favoriteModels:tt,onToggleFavorite:vn,onToggleModelFavorite:xn,addToast:t,projectId:s});case"secrets":return e.jsx(au,{scopeBanner:de(),addToast:t});case"global-mcp":return e.jsx(Md,{scopeBanner:de(),form:F,setForm:K,projectId:s,addToast:t});case"mcp":return e.jsx(Iu,{scopeBanner:de(),form:F,setForm:K,globalSettings:A?.global??null,projectId:s,addToast:t});case"project-models":return e.jsx(pu,{scopeBanner:de(),form:F,setForm:K,projectId:s,addToast:t,onOpenWorkflowSettings:S,registerWorkflowLaneSaver:re,models:{modelLanes:yn,getLaneStatus:Ks,getLaneValue:ni,updateLaneValue:ri,resetLaneValue:li,availableModels:_a,modelsLoading:Ha,favoriteProviders:et,favoriteModels:tt,onToggleFavorite:vn,onToggleModelFavorite:xn,editingPresetId:xt,setEditingPresetId:Ka,presetDraft:Ge,setPresetDraft:qa,onSavePresetDraft:Ii,confirmDelete:J}});case"appearance":return e.jsx(pd,{scopeBanner:de(),form:F,setForm:K,themeMode:n,colorTheme:m,dashboardFontScalePct:h,shadcnCustomColors:k,resolvedThemeMode:v,onThemeModeChange:i,onColorThemeChange:r,onDashboardFontScaleChange:d,onShadcnCustomColorsChange:u,sessionBannersHidden:q,setSessionBannersHidden:Tc});case"scheduling":return e.jsx(bu,{scopeBanner:de(),form:F,setForm:K,globalMaxConcurrent:Ht,concurrencyLoading:I==="scheduling"&&!Ll&&!Us.current,onGlobalMaxConcurrentChange:l=>{Us.current=!0,dn(l)},onOverlapIgnorePathChange:yi,onOpenOverlapPathPicker:ii,onRemoveOverlapIgnorePath:ki,onAddOverlapIgnorePath:ji,onOpenWorkflowSettings:S});case"scheduled-evals":return e.jsx(fu,{scopeBanner:de(),form:F,setForm:K});case"node-routing":return e.jsx(xu,{scopeBanner:de(),form:F,setForm:K,nodes:zr});case"worktrees":return e.jsx(yu,{scopeBanner:de(),form:F,setForm:K,gitRemotes:vl,worktrunkInstall:w,worktrunkInstallVerified:D,onOpenWorktreesDirPicker:di,onWorktreeCopyFileChange:fi,onRemoveWorktreeCopyFile:vi,onAddWorktreeCopyFile:xi,onOpenWorktreeCopyFilePicker:pi,onOpenApprovals:b});case"commands":return e.jsx(ku,{scopeBanner:de(),form:F,setForm:K});case"merge":return e.jsx(Cu,{scopeBanner:de(),form:F,setForm:K,integrationBranchOptions:xl,integrationBranchCustomMode:yl,setIntegrationBranchCustomMode:kl,onOpenWorkflowSettings:S});case"agent-permissions":return e.jsx(Su,{scopeBanner:de(),form:F,setForm:K});case"memory":return e.jsx(Mu,{scopeBanner:de(),form:F,setForm:K,memory:{memoryCapabilities:_l,memoryBackendStatus:Gl,memoryBackendLoading:Ul,memoryBackendError:Hl,memoryFiles:Al,selectedMemoryPath:Ie,setSelectedMemoryPath:Bs,memoryContent:Fs,setMemoryContent:_t,memoryLoading:fl,memoryDirty:Ls,setMemoryDirty:Ut,memoryTestQuery:Gs,setMemoryTestQuery:Tl,memoryTestLoading:Ml,memoryTestResult:Rl,qmdInstallLoading:Fl,dreamRunning:Il,memoryCompactLoading:El,onInstallQmd:Ri,onTestMemoryRetrieval:Ti,onDreamNow:Mi,onCompactMemory:Ai,onSaveMemory:Pi}});case"research-global":return e.jsx(wd,{scopeBanner:de(),form:F,setForm:K,authProviders:He,onNavigateToSection:H});case"research-project":return e.jsx(Ru,{scopeBanner:de(),form:F,setForm:K,researchLimitError:Fr});case"experimental":return e.jsx(gd,{scopeBanner:de(),form:F,setForm:K,knownFeatures:zu,legacyAliases:cs,getCanonicalKey:Ta,isFeatureEnabled:Yu,hiddenFeatureKeys:Vu});case"backups":return e.jsx(Eu,{scopeBanner:de(),form:F,setForm:K,backupInfo:al,backupLoading:nl,onBackupNow:Xl});case"notifications":return e.jsx(fd,{scopeBanner:de(),form:F,setForm:K,testNotificationLoading:tl,testNotificationResult:sl,onTestProviderNotification:Jl});case"node-sync":return e.jsx(bd,{scopeBanner:de(),form:F,setForm:K});case"remote":return e.jsx(Cd,{scopeBanner:de(),form:F,setForm:K,remote:{projectId:s,addToast:t,remoteStatus:Re,externalTunnel:Rs,tunnelShareLink:bl,remoteBusyAction:rl,cloudflaredInstalling:ll,cloudflaredInstallError:il,cloudflaredManualInstallCommand:Fi,cloudflaredMacFallbackCommand:Li,handleInstallCloudflared:Di,runRemoteAction:Ei,remoteShortLivedToken:pl,setRemoteShortLivedToken:gl,remoteAuthLinkTokenType:ol,setRemoteAuthLinkTokenType:cl,remoteUrlPreview:dl,setRemoteUrlPreview:ul,remoteQrSvg:ml,setRemoteQrSvg:hl}});case"prompts":return e.jsx(ou,{scopeBanner:de(),form:F,setForm:K,onOpenWorkflowSettings:S});case"plugins":return e.jsx(Du,{scopeBanner:de(),projectId:s,addToast:t,activePluginsSubsection:O,setActivePluginsSubsection:ee});case"authentication":return e.jsx(Hd,{auth:{projectId:s,addToast:t,authProviders:He,authLoading:Vr,authActionInProgress:Yr,apiKeyInputs:Ss,setApiKeyInputs:Ps,apiKeyErrors:Zr,opencodeApiKeyRefreshStatus:el,deviceCodes:js,loginInstructions:Qr,manualCodeConfigs:Jr,manualCodeInputs:ws,setManualCodeInputs:Cs,manualCodeSubmitInProgress:Xr,loadAuthStatus:xe,handleLogin:Kl,handleLogout:Vl,handleCancelLogin:zl,handleSaveApiKey:Yl,handleClearApiKey:Ql,handleSubmitManualCode:ql,onReopenOnboarding:x}});case"hermes-runtime":return e.jsx(eu,{});case"openclaw-runtime":return e.jsx(tu,{});case"paperclip-runtime":return e.jsx(su,{})}};return e.jsxs("div",{className:C?"settings-embedded right-dock-embedded-view":"modal-overlay open settings-modal-overlay",...ai,"data-testid":C?"settings-view":void 0,role:C?"region":"dialog","aria-label":C?f("settings.title","Settings"):void 0,"aria-modal":C?void 0:"true",children:[e.jsxs("div",{className:C?"modal modal-lg settings-modal settings-modal--embedded":"modal modal-lg settings-modal",ref:$,style:C?void 0:V,children:[e.jsxs("div",{className:C?"modal-header modal-header--embedded":"modal-header",children:[e.jsx("div",{className:"settings-modal-heading",children:e.jsxs("h3",{children:[C&&e.jsx(Nc,{size:20,"aria-hidden":"true"}),e.jsx("span",{children:f("settings.title","Settings")})]})}),e.jsxs("div",{className:"settings-header-actions",children:[e.jsxs("a",{href:"https://github.com/Runfusion/Fusion",target:"_blank",rel:"noopener noreferrer",className:"settings-github-star-btn","aria-label":f("settings.header.starFusion","Star Fusion on GitHub"),title:f("settings.header.starFusion","Star Fusion on GitHub"),onClick:Ir,"data-clicked":Rr?"true":"false",children:[e.jsxs("span",{className:"settings-github-star-btn__action",children:[e.jsx(Tt,{provider:"github",size:"sm"}),e.jsx(Sc,{size:11,"aria-hidden":"true"}),f("settings.header.star","Star")]}),ct!==null&&e.jsx("span",{className:"settings-github-star-btn__count","aria-label":`${ct.toLocaleString()} stars`,children:ct>=1e3?`${(ct/1e3).toFixed(1)}k`:ct.toLocaleString()})]}),e.jsxs("a",{href:"https://discord.gg/ksrfuy7WYR",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-header-discord-btn","aria-label":f("settings.header.joinDiscord","Join our Discord"),title:f("settings.header.joinDiscord","Join our Discord"),children:[e.jsx(Bu,{size:13}),f("settings.header.discord","Discord")]})]}),!C&&e.jsx("button",{className:"modal-close",onClick:a,"aria-label":f("actions.close","Close"),children:"×"})]}),R?e.jsx("div",{className:"settings-empty-state settings-loading",children:e.jsx(Ze,{label:f("settings.loading","Loading…")})}):e.jsxs("div",{className:"settings-layout",children:[e.jsxs("aside",{className:"settings-navigation","aria-label":f("settings.search.navigationLabel","Settings navigation"),children:[e.jsxs("div",{className:"settings-search","data-testid":"settings-search",children:[e.jsx("label",{className:"settings-search-label",htmlFor:"settings-search-input",children:f("settings.search.label","Search settings")}),e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx("input",{id:"settings-search-input","data-testid":"settings-search-input",className:"input settings-search-input",type:"search",value:oe,onChange:l=>ve(l.target.value),onKeyDown:l=>{l.key==="Escape"&&pt&&(l.stopPropagation(),ve(""))},placeholder:f("settings.search.placeholder","Search by setting or section"),"aria-describedby":"settings-search-results"}),pt&&e.jsx("button",{type:"button",className:"btn btn-sm settings-search-clear",onClick:()=>ve(""),"aria-label":f("settings.search.clear","Clear settings search"),children:f("actions.clear","Clear")})]}),e.jsx("div",{id:"settings-search-results",className:"settings-search-results","aria-live":"polite",children:pt?f("settings.search.resultCount","{{count}} matching sections",{count:xs.length}):f("settings.search.allSections","Showing all settings sections")})]}),le&&e.jsxs("div",{className:"settings-mobile-section-picker",children:[e.jsx("label",{htmlFor:"settings-mobile-section",children:f("settings.mobileNav.label","Settings Section")}),gt?e.jsx("select",{id:"settings-mobile-section",className:"select touch-target",value:I,onChange:l=>H(l.target.value),children:xs.map(l=>{const g=f(l.labelKey,l.label);return e.jsx("option",{value:l.id,children:Ku(l,g)},l.id)})}):e.jsx("p",{className:"settings-search-empty-hint",children:f("settings.search.noMobileOptions","No sections match this search.")})]}),e.jsx("nav",{className:"settings-sidebar",children:gt?ht.map(l=>l.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:f(l.labelKey,l.label)},l.id):e.jsxs("button",{className:`settings-nav-item${I===l.id?" active":""}`,onClick:()=>H(l.id),title:l.scope==="global"?f("settings.nav.tooltip.global","Shared across all projects"):l.scope==="project"?f("settings.nav.tooltip.project","Specific to this project"):void 0,children:[l.scope==="global"&&e.jsx(At,{className:"settings-scope-icon","aria-label":f("settings.nav.aria.global","Global setting"),size:16}),l.scope==="project"&&e.jsx(Bn,{className:"settings-scope-icon","aria-label":f("settings.nav.aria.project","Project setting"),size:16}),l.icon&&!l.scope&&e.jsx(l.icon,{className:"settings-scope-icon","aria-label":f("settings.nav.aria.global","Global setting"),size:16}),f(l.labelKey,l.label)]},l.id)):e.jsxs("div",{className:"settings-search-empty",role:"status",children:[e.jsx("p",{children:f("settings.search.noResults",'No settings sections match "{{query}}".',{query:oe.trim()})}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ve(""),children:f("settings.search.clear","Clear settings search")})]})})]}),e.jsx("div",{className:"settings-content",ref:T,children:gt?Oi():e.jsxs("div",{className:"settings-empty-state settings-search-content-empty",role:"status",children:[e.jsx("p",{children:f("settings.search.noResults",'No settings sections match "{{query}}".',{query:oe.trim()})}),e.jsx("button",{type:"button",className:"btn",onClick:()=>ve(""),children:f("settings.search.clear","Clear settings search")})]})})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"settings-modal-footer-version",children:[e.jsxs("a",{href:"https://github.com/Runfusion/Fusion/discussions",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-footer-help-btn","aria-label":f("settings.footer.helpDiscussions","Help and discussions"),title:f("settings.footer.helpDiscussions","Help and discussions"),children:[e.jsx(Pc,{size:13,"aria-hidden":"true"}),f("settings.footer.help","Help")]}),e.jsxs("div",{className:"settings-update-check",children:[Ae&&e.jsxs("button",{type:"button",className:"settings-version-check-btn",onClick:()=>{Wl()},disabled:Ve,"aria-label":f("settings.footer.checkUpdates","Check for updates"),title:f("settings.footer.checkUpdates","Check for updates"),children:[e.jsx("span",{className:"settings-modal-version",children:f("settings.footer.version","Version {{version}}",{version:Ae})}),e.jsx(ns,{size:12,className:Ve?"spinning":void 0})]}),ye&&e.jsx("span",{"aria-live":"polite",className:`settings-update-result ${ye.error?"settings-update-result--error":ye.updateAvailable?"settings-update-result--available":"settings-update-result--up-to-date"}`,children:$l()})]})]}),e.jsxs("div",{className:"modal-actions-left",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Zl,title:f("settings.importExport.exportTitle","Export settings to JSON file"),children:f("settings.importExport.exportBtn","Export")}),e.jsx("input",{type:"file",ref:gn,accept:".json,application/json",style:{display:"none"},onChange:ei}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>gn.current?.click(),disabled:Wt,title:f("settings.importExport.importTitleAttr","Import settings from JSON file"),children:Wt?f("settings.importExport.loadingFile","Loading…"):f("settings.importExport.importBtn","Import")}),e.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"settings-reset",onClick:()=>It(!0),disabled:R,title:f("settings.reset.buttonTitle","Reset settings to their defaults"),children:f("settings.reset.button","Reset Settings")})]}),e.jsxs("div",{className:"modal-actions-right",children:[!C&&e.jsx("button",{className:"btn btn-sm",onClick:a,children:f("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:wi,disabled:R||ge,children:f("settings.actions.save","Save")})]})]})]}),Te!==null&&e.jsx("div",{className:"modal-overlay open",onClick:ci,role:"dialog","aria-modal":"true","aria-label":f("settings.scheduling.browseWorkspacePath","Browse workspace path"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:f("settings.scheduling.selectIgnoredOverlapPath","Select ignored overlap path")}),e.jsx("button",{className:"modal-close",onClick:We,"aria-label":f("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body settings-overlap-path-picker-body",children:[e.jsx("p",{className:"settings-overlap-path-picker-note",children:f("settings.scheduling.overlapPickerNote","Choose a file to ignore directly, or navigate into a folder and select the current directory.")}),e.jsx(sa,{entries:Lr,currentPath:Oe,onSelectFile:qs,onNavigate:ps,loading:Dr,error:Or,onRetry:Br,workspace:"project",projectId:s})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[f("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:Oe==="."?f("settings.fileBrowser.projectRoot","(project root)"):Oe})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:We,children:f("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:oi,disabled:Oe===".",children:f("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),Ea&&e.jsx("div",{className:"modal-overlay open",onClick:hi,role:"dialog","aria-modal":"true","aria-label":f("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:f("settings.worktrees.selectWorktreesDir","Select worktrees directory")}),e.jsx("button",{className:"modal-close",onClick:$e,"aria-label":f("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body settings-overlap-path-picker-body",children:[e.jsx("p",{className:"settings-overlap-path-picker-note",children:f("settings.worktrees.worktreesPickerNote","Navigate to the folder where Fusion should create task worktrees, then select the current directory.")}),e.jsx(sa,{entries:Gr,currentPath:Be,onSelectFile:ui,onNavigate:gs,loading:_r,error:Ur,onRetry:Hr,workspace:"project",projectId:s})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[f("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:Be==="."?f("settings.fileBrowser.projectRoot","(project root)"):Be})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:$e,children:f("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:mi,children:f("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),Me!==null&&e.jsx("div",{className:"modal-overlay open",onClick:bi,role:"dialog","aria-modal":"true","aria-label":f("settings.worktrees.browseCopyFile","Browse file to copy into new worktrees"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:f("settings.worktrees.selectCopyFile","Select file to copy")}),e.jsx("button",{className:"modal-close",onClick:Ke,"aria-label":f("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body settings-overlap-path-picker-body",children:[e.jsx("p",{className:"settings-overlap-path-picker-note",children:f("settings.worktrees.copyFilePickerNote","Choose a repository file to copy into each newly assigned task worktree. Directories are not selected from this picker.")}),e.jsx(sa,{entries:Wr,currentPath:bs,onSelectFile:gi,onNavigate:fs,loading:$r,error:Kr,onRetry:qr,workspace:"project",projectId:s})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[f("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:bs==="."?f("settings.fileBrowser.projectRoot","(project root)"):bs})]})}),e.jsx("div",{className:"modal-actions-right",children:e.jsx("button",{className:"btn btn-sm",onClick:Ke,children:f("settings.actions.cancel","Cancel")})})]})]})}),Dl&&Ee&&e.jsx("div",{className:"modal-overlay open",onClick:l=>l.target===l.currentTarget&&yt(!1),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-md",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:f("settings.importExport.importTitle","Import Settings")}),e.jsx("button",{className:"modal-close",onClick:()=>yt(!1),"aria-label":f("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:f("settings.importExport.reviewPrompt","Review the settings to be imported:")}),Ee.global&&Object.keys(Ee.global).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:f("settings.importExport.globalSettings","Global Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(Ee.global).filter(([,l])=>l!==void 0).map(([l])=>e.jsx("li",{children:l},l))})]}),Ee.project&&Object.keys(Ee.project).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:f("settings.importExport.projectSettings","Project Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(Ee.project).filter(([,l])=>l!==void 0).map(([l])=>e.jsx("li",{children:l},l))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"import-scope",children:f("settings.importExport.importScope","Import Scope:")}),e.jsxs("select",{id:"import-scope",value:Ws,onChange:l=>Ol(l.target.value),children:[e.jsx("option",{value:"both",children:f("settings.importExport.scopeBoth","Both global and project settings")}),e.jsx("option",{value:"global",children:f("settings.importExport.scopeGlobal","Global settings only")}),e.jsx("option",{value:"project",children:f("settings.importExport.scopeProject","Project settings only")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"import-merge",className:"checkbox-label",children:[e.jsx("input",{id:"import-merge",type:"checkbox",checked:$s,onChange:l=>Bl(l.target.checked)}),f("settings.importExport.mergeExisting","Merge with existing settings (recommended)")]}),e.jsx("small",{children:f("settings.importExport.replaceWarning","If unchecked, existing settings will be replaced with imported values.")})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>yt(!1),children:f("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:ti,disabled:Wt,children:Wt?f("settings.importExport.importing","Importing…"):f("settings.importExport.confirmImport","Confirm Import")})]})]})}),ut&&e.jsx("div",{className:"modal-overlay open",onClick:Si,role:"dialog","aria-modal":"true","aria-label":f("settings.reset.dialogAriaLabel","Reset settings"),"data-testid":"settings-reset-dialog",children:e.jsxs("div",{className:"modal modal-md settings-reset-dialog",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:f("settings.reset.dialogTitle","Reset Settings")}),e.jsx("button",{className:"modal-close",onClick:nt,"aria-label":f("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:f("settings.reset.dialogBody","Choose what to reset to its defaults. This cannot be undone.")}),e.jsxs("div",{className:"settings-reset-dialog__choice",children:[e.jsx("button",{type:"button",className:"btn btn-danger settings-reset-dialog__choice-btn","data-testid":"settings-reset-menu",onClick:()=>void Ci(),disabled:De||!at,title:zs,children:f("settings.reset.resetMenuAction","Reset this menu ({{section}})",{section:Vs})}),zs&&e.jsx("small",{className:"settings-reset-dialog__ineligible-reason",children:zs})]}),e.jsx("div",{className:"settings-reset-dialog__choice",children:e.jsx("button",{type:"button",className:"btn btn-danger settings-reset-dialog__choice-btn","data-testid":"settings-reset-all-project",onClick:()=>void Ni(),disabled:De,children:f("settings.reset.resetAllProjectAction","Reset all project settings")})})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("div",{className:"modal-actions-right",children:e.jsx("button",{className:"btn btn-sm",onClick:nt,disabled:De,children:f("settings.actions.cancel","Cancel")})})})]})})]})}function mm(a){return e.jsx(Zu,{presentation:"embedded",...a})}export{Zu as SettingsModal,mm as SettingsView};