@runfusion/fusion 0.76.0-beta.2 → 0.76.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +323 -59
- package/dist/child-process-worker.js +274 -42
- package/dist/client/.vite/manifest.json +273 -273
- package/dist/client/assets/{AgentDetailView-gak4EWTI.js → AgentDetailView-T767kKTg.js} +1 -1
- package/dist/client/assets/{AgentPermissionPolicyEditor-DP1QbZL-.js → AgentPermissionPolicyEditor--u9jyUf2.js} +1 -1
- package/dist/client/assets/{AgentsView-DAMRTKzI.js → AgentsView-6Ifu7qDr.js} +5 -5
- package/dist/client/assets/{ChatView-iE-2gf5P.js → ChatView-BV3lixQi.js} +1 -1
- package/dist/client/assets/{CommandCenter-B6RnkLYm.js → CommandCenter-CSRYoveB.js} +1 -1
- package/dist/client/assets/{DevServerView-DcFL_LzK.js → DevServerView-B9So_oYx.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-CtjqrYoO.js → DirectoryPicker-BhyDL_2m.js} +1 -1
- package/dist/client/assets/{DocumentsView-BkAe2S4H.js → DocumentsView-pbERA7O-.js} +1 -1
- package/dist/client/assets/{EvalsView-CbGA9dMn.js → EvalsView-DJQ4ltCg.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-CMgO_S8T.js → ExperimentalAgentOnboardingModal-BwJuzkzB.js} +1 -1
- package/dist/client/assets/{GoalsView-_3P9J5sf.js → GoalsView-B6X5_0Ve.js} +1 -1
- package/dist/client/assets/InsightsView-CJgI0J7S.js +11 -0
- package/dist/client/assets/{InsightsView-Gn5lOBA0.css → InsightsView-DAAXuX4v.css} +1 -1
- package/dist/client/assets/{MemoryView-DwJas8vi.js → MemoryView-BHq1AHPu.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-B_LiW_e9.js → PiExtensionsManager-B8At6fO8.js} +1 -1
- package/dist/client/assets/{PluginManager-BkB6WLQc.js → PluginManager-k7hV7_9e.js} +1 -1
- package/dist/client/assets/{PullRequestView-DcH5tmYc.js → PullRequestView-B1hZFrWo.js} +1 -1
- package/dist/client/assets/{ReportModal-BOEbqtqG.js → ReportModal-C46V_zEa.js} +1 -1
- package/dist/client/assets/{ResearchView-Dp6V42pI.js → ResearchView-D8G85BYN.js} +2 -2
- package/dist/client/assets/{SecretsView-BCqXHB2L.js → SecretsView-CTri9LRK.js} +1 -1
- package/dist/client/assets/{SessionTerminal-CkdoQv4y.js → SessionTerminal-BRf6r4Vp.js} +1 -1
- package/dist/client/assets/SettingsModal-D0RBeZik.js +21 -0
- package/dist/client/assets/{SettingsModal-Dc7YG6KB.js → SettingsModal-rUQcSTJp.js} +1 -1
- package/dist/client/assets/{SettingsTextareaRow-WSkBoAOO.js → SettingsTextareaRow-BirlBcem.js} +1 -1
- package/dist/client/assets/{SetupWizardModal-VTrJAsKd.js → SetupWizardModal-xnCBM9EL.js} +2 -2
- package/dist/client/assets/{SkillsView-CXeXOxfF.js → SkillsView-O5U0ep50.js} +1 -1
- package/dist/client/assets/{WorkflowNodeEditor-DoxLGPRF.js → WorkflowNodeEditor-BX4d2qqF.js} +3 -3
- package/dist/client/assets/{agent-import-generation-upc0yw-M.js → agent-import-generation-DnqVkPkz.js} +1 -1
- package/dist/client/assets/{agentsOrgChartLayout-C3iumMrW.js → agentsOrgChartLayout-CKuzbhFf.js} +1 -1
- package/dist/client/assets/app-B2FwULu2.js +5 -0
- package/dist/client/assets/{app-BA9gw9hx.js → app-B6nJaqAl.js} +2 -2
- package/dist/client/assets/{app-B_lScKc1.js → app-CGXZeIRc.js} +2 -2
- package/dist/client/assets/{app-DG_vjDw5.js → app-CGtkeBF5.js} +3 -3
- package/dist/client/assets/{app-GBgoY-oh.js → app-CNzN1Plu.js} +2 -2
- package/dist/client/assets/{app-B0KFGP8D.js → app-DLs-f5yM.js} +3 -3
- package/dist/client/assets/{app-DeHIOCEP.js → app-DsvtcRUG.js} +2 -2
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-D6jqc3fJ.js → architectureDiagram-3BPJPVTR-gi467xY0.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-DY3AKuPD.js → blockDiagram-GPEHLZMM-B_gpcYiR.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-CpD52V4g.js → c4Diagram-AAUBKEIU-DeylEYsQ.js} +1 -1
- package/dist/client/assets/channel-BoE8DeM4.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-CPeIHyAX.js → chunk-2J33WTMH-BL2WY0HN.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-ivAwI4xM.js → chunk-4BX2VUAB-BkLExGMe.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-BtVQ5XaZ.js → chunk-55IACEB6-CSTvCF5T.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-1eap1vDU.js → chunk-727SXJPM-9J8pKk4x.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-B2NB3BW9.js → chunk-AQP2D5EJ-DXC1vPWr.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-Hk_smNYv.js → chunk-FMBD7UC4-CFRUb-zD.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-BmGCAojk.js → chunk-ND2GUHAM-B87HFYS8.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-D0aXZ8CV.js → chunk-QZHKN3VN-CTjHiGbd.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-qnbLX_9_.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-qnbLX_9_.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-DAbu_gnF.js → cose-bilkent-S5V4N54A-D3Edq3L9.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-BdmLlrDJ.js → dagre-BM42HDAG-CwwbeQfN.js} +1 -1
- package/dist/client/assets/{dashboard-view-CULL1yhL.js → dashboard-view-BLAoW3D4.js} +1 -1
- package/dist/client/assets/{dashboard-view-PRCWCSLm.js → dashboard-view-DAlJxqiJ.js} +1 -1
- package/dist/client/assets/{dashboard-view-BoFBSXUn.js → dashboard-view-QxQwJFLz.js} +1 -1
- package/dist/client/assets/{dashboard-view-CxXMDfNY.js → dashboard-view-aPzfv99T.js} +1 -1
- package/dist/client/assets/{diagram-2AECGRRQ-PpqLbVUA.js → diagram-2AECGRRQ-koJWWXE4.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-9rkGmTwh.js → diagram-5GNKFQAL-Yob5cOKT.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-BT-efOMo.js → diagram-KO2AKTUF-DelvFSkK.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-w79OWFxg.js → diagram-LMA3HP47-CMput2h2.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-Bye9I5IO.js → diagram-OG6HWLK6-04VXDl79.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-aodREgDf.js → erDiagram-TEJ5UH35-C9iP8Uyp.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-D0DKItY3.js → flowDiagram-I6XJVG4X-DENQvu_t.js} +1 -1
- package/dist/client/assets/{folder-open-CqvaMJvx.js → folder-open-D-554oji.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-CZVApkvw.js → ganttDiagram-6RSMTGT7-BqOttZAT.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII-D_ynwJ4p.js → gitGraphDiagram-PVQCEYII-CDcydi-5.js} +1 -1
- package/dist/client/assets/{index-BzAldNrK.css → index-CXTd3LAB.css} +1 -1
- package/dist/client/assets/{index-DWRJyaa3.js → index-CtYRoouR.js} +264 -264
- package/dist/client/assets/{infoDiagram-5YYISTIA-pJG6zxjk.js → infoDiagram-5YYISTIA-B5LQQnxt.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-nFZ5laUo.js → ishikawaDiagram-YF4QCWOH-DpFEt7D2.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-CWpCaAIe.js → journeyDiagram-JHISSGLW-MELtgu22.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-ATkPspKa.js → kanban-definition-UN3LZRKU-h33PLATd.js} +1 -1
- package/dist/client/assets/{mermaid.core-CDXPNs7a.js → mermaid.core-Dk2mUPOq.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-BkqS9tpe.js → mindmap-definition-RKZ34NQL-B_T4O2-B.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-DEUyVLs-.js → pieDiagram-4H26LBE5-B1YIFkRl.js} +1 -1
- package/dist/client/assets/{puzzle-DQ0y1-XK.js → puzzle-hvecxlpJ.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-ESBJNK5c.js → quadrantDiagram-W4KKPZXB-BoGQR_hO.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-CqPs7zcv.js → requirementDiagram-4Y6WPE33-BSDmUBIx.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-CkFN0m14.js → sankeyDiagram-5OEKKPKP-Dz_GqOa5.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-Dx2nDuMO.js → sequenceDiagram-3UESZ5HK-B6twjYUH.js} +1 -1
- package/dist/client/assets/{shield-alert-BS05s4RM.js → shield-alert-BX4WRJOv.js} +1 -1
- package/dist/client/assets/{standing-instructions-template-xprxYNHm.js → standing-instructions-template-BJY317CC.js} +1 -1
- package/dist/client/assets/{stateDiagram-AJRCARHV-EUPmRFGd.js → stateDiagram-AJRCARHV-DuwqWLx-.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-DcQ2mhi5.js → stateDiagram-v2-BHNVJYJU-Bu8Sk187.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-D4YO_3V-.js → timeline-definition-PNZ67QCA-BS6VnqSI.js} +1 -1
- package/dist/client/assets/{upload-BjyBtxo7.js → upload-CaDoyaMW.js} +1 -1
- package/dist/client/assets/{users-D5ogZ7WQ.js → users-C5uCLwVM.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-BT5_XuQL.js → vennDiagram-CIIHVFJN-CUbzqT5Y.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-X_ZMW457.js → wardley-L42UT6IY-Mv-NotFS.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-GK9nONHU.js → wardleyDiagram-YWT4CUSO-DuYpvLZX.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-Dw3zXHAq.js → xychartDiagram-2RQKCTM6-24_7QXdw.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +285 -47
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugin-sdk/index.d.ts +23 -0
- package/dist/plugin-sdk/index.js +2 -0
- package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-linear-import/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
- package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-quality/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-quality/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-reports/package.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-todos/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-todos/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +2 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/dist/client/assets/InsightsView-DOhO7xH5.js +0 -11
- package/dist/client/assets/SettingsModal-D4Fn4GlS.js +0 -21
- package/dist/client/assets/app-DBCGrz-f.js +0 -5
- package/dist/client/assets/channel-CaxOu15c.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-DXIkGbsl.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DXIkGbsl.js +0 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-k7hV7_9e.js","assets/vendor-react-SZ_qB27O.js","assets/index-CtYRoouR.js","assets/vendor-i18n-Duky4gdQ.js","assets/vendor-codemirror-CcrtqoCy.js","assets/vendor-reactflow-BlIeoTu4.js","assets/vendor-reactflow-BnuhLJ6X.css","assets/vendor-xterm-BNq00GSj.js","assets/vendor-xterm-LZoznX6r.css","assets/index-CXTd3LAB.css","assets/DirectoryPicker-BhyDL_2m.js","assets/folder-open-D-554oji.js","assets/DirectoryPicker-0rspvcMz.css","assets/PluginManager-HPxNBpmi.css","assets/PiExtensionsManager-B8At6fO8.js","assets/puzzle-hvecxlpJ.js","assets/AgentPermissionPolicyEditor--u9jyUf2.js","assets/AgentPermissionPolicyEditor-CXib-igK.css","assets/PiExtensionsManager-kgTOHPE9.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as i,j as e}from"./vendor-react-SZ_qB27O.js";import{c as zc,a as Ue,w as $e,fE as qc,fF as Vc,fG as Yc,fH as Bn,fI as Qc,fJ as ns,fK as ha,cW as ls,fL as ai,fM as Jc,fN as Jl,fO as zn,fP as Gn,fQ as ni,fR as Xc,fS as Zc,fT as Xl,eg as ba,an as ed,a$ as td,P as fa,R as Ts,bV as sd,v as ya,x as va,aS as ad,X as li,aJ as Et,cw as lt,dH as nd,fU as Zl,fV as ld,fW as rd,L as bt,dY as jt,fX as er,fY as id,fZ as od,f_ as cd,f$ as dd,g0 as ud,g1 as pd,g2 as gd,g3 as hd,h as tr,aI as Hn,g4 as md,g5 as _n,g6 as bd,g7 as fd,g8 as yd,g9 as xt,ga as vd,gb as kd,gc as xd,y as qn,ah as ri,a5 as ii,gd as jd,ge as wd,gf as Cd,gg as Sd,be as xa,br as Vn,gh as Nd,gi as Pd,bl as rs,gj as Id,gk as Td,gl as Ad,gm as Md,gn as Rd,go as Ed,gp as sr,gq as ar,gr as Dd,dd as sa,dc as mn,aa as Fd,C as Ld,f9 as nr,gs as Od,gt as Kd,fx as Bd,gu as lr,gv as Gd,gw as rr,gx as Hd,gy as _d,gz as Ud,dN as Wd,gA as $d,eX as zd,cO as ir,eY as qd,gB as Vd,gC as Yd,gD as Qd,gE as Jd,gF as Xd,gG as Zd,b5 as eu,aK as tu,ab as Yn,b1 as su,a3 as oi,bh as ci,c0 as or,f2 as au,dQ as nu,d7 as lu,K as ru,gH as iu,gI as bn,ae as ou,aX as cr,cp as cu,bL as De,gJ as du,gK as uu,gL as pu,gM as dr,gN as gu,gO as hu,ag as ur,gP as mu,cr as bu,gQ as pr,gR as fu,gS as gr,gT as yu,gU as fn,gV as vu,gW as hr,gX as mr,gY as br,gZ as fr,g_ as yr,g$ as ku,aY as yn,h0 as xu,_ as ju,bG as wu,a9 as Cu,h1 as vn,F as Su,h2 as Nu,h3 as Pu}from"./index-CtYRoouR.js";import{u as Iu,a as vr,f as Tu,s as Au,h as Mu,t as Ru,g as Eu,i as Du}from"./SettingsModal-rUQcSTJp.js";import{a as kr,b as Fu,e as Lu,i as Ou}from"./agent-import-generation-DnqVkPkz.js";import{e as ae,f as G,c as Ae,d as Pe,a as be,S as As,b as xr,g as Ku}from"./SettingsTextareaRow-BirlBcem.js";import{T as Bu,a as Gu,r as Hu,l as _u,R as Uu,b as Wu}from"./ReportModal-C46V_zEa.js";import{u as le,T as Un}from"./vendor-i18n-Duky4gdQ.js";import{U as $u}from"./upload-CaDoyaMW.js";import{SecretsView as zu}from"./SecretsView-CTri9LRK.js";import{B as qu,A as Vu}from"./AgentPermissionPolicyEditor--u9jyUf2.js";import{U as Yu}from"./users-C5uCLwVM.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.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 Qu=[["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"}]],Ju=zc("settings-2",Qu);function at(t,s,a){return{path:t,code:s,message:a}}function Xu(t,s){return t===void 0?{value:void 0,errors:[]}:!Array.isArray(t)||!t.every(a=>typeof a=="string"&&a.trim().length>0)?{errors:[at(s,"invalid-args","Expected an array of non-empty strings")]}:{value:t.map(a=>a.trim()),errors:[]}}function jr(t,s){if(t===void 0)return{value:void 0,errors:[]};if(!t||typeof t!="object"||Array.isArray(t))return{errors:[at(s,"invalid-sensitive-map","Expected an object whose values are secret references")]};const a={},n=[];for(const[o,d]of Object.entries(t)){if(!o.trim()){n.push(at(`${s}.${o}`,"invalid-sensitive-map","Sensitive field names must be non-empty"));continue}if(typeof d=="string"){n.push(at(`${s}.${o}`,"plaintext-secret","Sensitive MCP values must be Fusion secret references, never plaintext strings"));continue}if(!is(d)){n.push(at(`${s}.${o}`,"invalid-sensitive-map","Sensitive MCP values must be { secretRef, scope } objects"));continue}a[o.trim()]={secretRef:d.secretRef.trim(),scope:d.scope}}return n.length>0?{errors:n}:{value:a,errors:[]}}function Qn(t,s="server"){if(!t||typeof t!="object"||Array.isArray(t))return{errors:[at(s,"invalid-shape","MCP server definition must be an object")]};const a=t,n=[];(typeof a.name!="string"||a.name.trim().length===0)&&n.push(at(`${s}.name`,"invalid-name","MCP server name is required"));const o=typeof a.enabled=="boolean"?a.enabled:void 0;if(a.transport==="stdio"){(typeof a.command!="string"||a.command.trim().length===0)&&n.push(at(`${s}.command`,"missing-command","stdio MCP servers require a command"));const d=Xu(a.args,`${s}.args`),u=jr(a.env,`${s}.env`);return n.push(...d.errors,...u.errors),n.length>0?{errors:n}:{value:{name:a.name.trim(),...o!==void 0?{enabled:o}:{},transport:"stdio",command:a.command.trim(),...d.value?{args:d.value}:{},...u.value?{env:u.value}:{}},errors:[]}}if(a.transport==="sse"||a.transport==="streamable-http"){(typeof a.url!="string"||a.url.trim().length===0)&&n.push(at(`${s}.url`,"missing-url",`${a.transport} MCP servers require a url`));const d=jr(a.headers,`${s}.headers`);return n.push(...d.errors),n.length>0?{errors:n}:{value:{name:a.name.trim(),...o!==void 0?{enabled:o}:{},transport:a.transport,url:a.url.trim(),...d.value?{headers:d.value}:{}},errors:[]}}return n.push(at(`${s}.transport`,"invalid-transport","MCP transport must be stdio, sse, or streamable-http")),{errors:n}}function Wt(t){return Qn(t).value}function Zu(t,s="servers"){if(!Array.isArray(t))return{errors:[at(s,"invalid-shape","MCP servers must be an array")]};const a=[],n=[],o=new Set;return t.forEach((d,u)=>{const c=Qn(d,`${s}.${u}`);if(a.push(...c.errors),!!c.value){if(o.has(c.value.name)){a.push(at(`${s}.${u}.name`,"duplicate-name",`Duplicate MCP server name: ${c.value.name}`));return}o.add(c.value.name),n.push(c.value)}}),a.length>0?{errors:a}:{value:n,errors:[]}}function wr(t){return{enabled:t?.enabled===!0,servers:Array.isArray(t?.servers)?t.servers:[]}}function di(t){if(!t||typeof t!="object"||Array.isArray(t))return;const s=t;if(!("enabled"in s||s.enabledByDefault!==void 0&&typeof s.enabledByDefault!="boolean"))return Wt(s)}function ep(t,s,a=[],n=[]){try{const o=wr(t?.mcpServers),d=s?.mcpServers;if(!(typeof d?.enabled=="boolean"?d.enabled:o.enabled))return[];const c=new Map;for(const h of n.map(Wt).filter(p=>!!p))c.set(h.name,h);const l=new Map(c);for(const h of o.servers??[]){if(h?.enabled===!1){l.delete(h.name);continue}const p=Wt(h);p&&l.set(p.name,p)}for(const h of a){if(!h||typeof h!="object"||Array.isArray(h))continue;const p=h.server;if(!p||typeof p!="object"||Array.isArray(p)||p.enabledByDefault===!1)continue;const m=di(p);m&&l.set(m.name,m)}for(const h of wr(d).servers??[]){if(h?.enabled===!1){l.delete(h.name);continue}const p=Wt(h);if(p)l.set(p.name,p);else if(h?.enabled===!0&&typeof h.name=="string"){const m=c.get(h.name);m&&l.set(h.name,m)}}return[...l.values()].filter(h=>h.enabled!==!1)}catch{return[]}}function tp(t){if(typeof t!="string")return{data:t};try{return{data:JSON.parse(t)}}catch(s){return{error:s instanceof Error?s.message:String(s)}}}function sp(t,s,a){const n=o=>o.trim().replace(/[^A-Za-z0-9_.-]+/gu,"_").replace(/^_+|_+$/gu,"");return["mcp",n(t),n(s),n(a)].filter(Boolean).join(".")}function Cr(t){const{value:s,serverName:a,field:n,scope:o,secretsToCreate:d,errors:u}=t;if(s===void 0)return;if(!s||typeof s!="object"||Array.isArray(s)){u.push(`${a}.${n} must be an object`);return}const c={};for(const[l,h]of Object.entries(s)){if(is(h)){c[l]={secretRef:h.secretRef.trim(),scope:h.scope};continue}if(typeof h=="string"){const p=sp(a,n,l);c[l]={secretRef:p,scope:o},d.push({serverName:a,field:n,key:l,scope:o,suggestedKey:p,plaintextValue:h});continue}u.push(`${a}.${n}.${l} must be a string or MCP secret reference`)}return Object.keys(c).length>0?c:void 0}function ap(t,s={}){const a=tp(t);if(a.error)return{definitions:[],secretsToCreate:[],errors:[a.error]};const n=[],o=[],d=s.scope??"project",u=a.data;if(!u||typeof u!="object"||Array.isArray(u))return{definitions:[],secretsToCreate:o,errors:["MCP import data must be an object"]};const c=u.mcpServers;if(!c||typeof c!="object"||Array.isArray(c))return{definitions:[],secretsToCreate:o,errors:["MCP import data must contain an mcpServers object"]};const l=[],h=new Set;for(const[p,m]of Object.entries(c)){if(!m||typeof m!="object"||Array.isArray(m)){n.push(`${p} must be an object`);continue}const x=m,w=typeof x.enabled=="boolean"?x.enabled:void 0,f={name:typeof x.name=="string"&&x.name.trim()?x.name.trim():p,...w!==void 0?{enabled:w}:{}},E=typeof x.transport=="string"?x.transport:typeof x.command=="string"?"stdio":void 0;let N;if(E==="stdio"?N=Wt({...f,transport:"stdio",command:x.command,args:x.args,env:Cr({value:x.env,serverName:f.name,field:"env",scope:d,secretsToCreate:o,errors:n})}):E==="sse"||E==="streamable-http"?N=Wt({...f,transport:E,url:x.url,headers:Cr({value:x.headers,serverName:f.name,field:"headers",scope:d,secretsToCreate:o,errors:n})}):n.push(`${p}.transport must be stdio, sse, or streamable-http`),!N){n.push(`${p} is not a valid MCP server definition`);continue}if(h.has(N.name)){n.push(`Duplicate MCP server name: ${N.name}`);continue}h.add(N.name),l.push(N)}return{definitions:l,secretsToCreate:o,errors:n}}function Sr(t){if(!t)return;const s={};for(const[a,n]of Object.entries(t))is(n)&&(s[a]={secretRef:n.secretRef,scope:n.scope});return Object.keys(s).length>0?s:void 0}function np(t){const s={};for(const a of t){const n=Wt(a);if(n){if(n.transport==="stdio"){s[n.name]={transport:"stdio",...n.enabled!==void 0?{enabled:n.enabled}:{},command:n.command,...n.args?{args:n.args}:{},...n.env?{env:Sr(n.env)}:{}};continue}s[n.name]={transport:n.transport,...n.enabled!==void 0?{enabled:n.enabled}:{},url:n.url,...n.headers?{headers:Sr(n.headers)}:{}}}}return{mcpServers:s}}const Nr="https://gitlab.com",lp="https://gitlab.com/api/v4";function rp(t={}){return typeof t.project?.gitlabEnabled=="boolean"?t.project.gitlabEnabled:typeof t.global?.gitlabEnabled=="boolean"?t.global.gitlabEnabled:!0}function aa(t){if(typeof t!="string")return;const s=t.trim();return s.length>0?s:void 0}function Pr(t,s){let a;try{a=new URL(t)}catch{throw new Error(`${s} must be a valid absolute http(s) URL`)}if(a.protocol!=="http:"&&a.protocol!=="https:")throw new Error(`${s} must use http:// or https://`);if(a.username||a.password)throw new Error(`${s} must not include username or password userinfo`);if(!a.hostname)throw new Error(`${s} must include a hostname`);return a.hash="",a.search="",a.pathname=a.pathname.replace(/\/+$/u,"")||"/",a.toString().replace(/\/$/u,"")}function ip(t){const s=new URL(t),a=s.pathname.replace(/\/+$/u,"");return s.pathname=`${a}/api/v4`.replace(/\/+/gu,"/"),s.search="",s.hash="",s.toString().replace(/\/$/u,"")}function Ir(t={}){const s=rp(t),a=aa(t.project?.gitlabInstanceUrl),n=aa(t.global?.gitlabInstanceUrl),o=aa(t.project?.gitlabApiBaseUrl),d=aa(t.global?.gitlabApiBaseUrl),u=Pr(a??n??Nr,"GitLab instance URL"),c=o??d?Pr(o??d??"","GitLab API base URL"):u===Nr?lp:ip(u);return{enabled:s,instanceUrl:u,apiBaseUrl:c}}function kn(t){if(!Array.isArray(t?.requiredChecks))return[];const s=new Set;for(const a of t.requiredChecks){if(typeof a!="string")continue;const n=a.trim();n&&s.add(n)}return[...s]}var op={};const cp="\0fnlvl=",dp="\0";function na(t,s){return`${cp}${t}${dp}${s}`}function up(t){const s=op.FUSION_DEBUG?.trim();return s?s==="1"||s==="true"||s==="all"||s==="*"?!0:s.split(",").map(a=>a.trim()).includes(t):!1}function pp(t){const s=`[${t}]`;return{log(a,...n){console.error(na("info",`${s} ${a}`),...n)},debug(a,...n){up(t)&&console.error(na("info",`${s} ${a}`),...n)},warn(a,...n){console.warn(na("warn",`${s} ${a}`),...n)},error(a,...n){console.error(na("error",`${s} ${a}`),...n)}}}const gp=pp("core-merge-policy");let Tr=!1;function Ar(t){return t==="reuse-task-worktree"||t==="cwd-integration-branch"?t:t==="cwd-main"?(Tr||(Tr=!0,gp.warn("[merger] settings.mergeIntegrationWorktree=cwd-main is legacy; normalized to cwd-integration-branch")),"cwd-integration-branch"):"reuse-task-worktree"}function Mr(t){return t==="off"||t==="ff-only"||t==="stash-and-ff"?t:"stash-and-ff"}function is(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const s=t;return typeof s.secretRef=="string"&&s.secretRef.trim().length>0&&(s.scope==="project"||s.scope==="global")}const mt="fusion-memory",hp="Fusion memory",mp="Built-in Fusion knowledge graph and durable recall tools.";function bp(t,s){const a=(t?.servers??[]).filter(n=>n.name!==mt);return s.intent==="disable"&&a.push({name:mt,enabled:!1}),s.intent==="enable"&&s.scope==="project"&&s.lowerScopeTombstoned&&a.push({name:mt,enabled:!0}),{enabled:t?.enabled??!0,servers:a}}function fp(t){return Ue($e("/remote/settings",t))}function xn(t,s){return Ue($e("/remote/settings",s),{method:"PUT",body:JSON.stringify(t)})}function jn(t){return Ue($e("/remote/status",t))}function yp(t){return Ue($e("/remote/install-cloudflared",t),{method:"POST"})}function wn(t){return Ue($e("/remote/tunnel/start",t),{method:"POST"})}function vp(t){return Ue($e("/remote/tunnel/stop",t),{method:"POST"})}function kp(t){return Ue($e("/remote/tunnel/kill-external",t),{method:"POST"})}function xp(t){return Ue($e("/remote/token/persistent/regenerate",t),{method:"POST"})}function jp(t,s){return Ue($e("/remote/token/short-lived/generate",s),{method:"POST",body:JSON.stringify({ttlMs:t})})}function ui(t,s,a){const n=new URLSearchParams;t&&n.set("format",t),n.set("tokenType",s),s==="short-lived"&&typeof a=="number"&&Number.isFinite(a)&&n.set("ttlMs",String(a));const o=n.toString();return o?`?${o}`:""}function pi(t={}){const{projectId:s,tokenType:a="persistent",ttlMs:n}=t,o=ui(null,a,n);return Ue($e(`/remote/url${o}`,s))}function Wn(t="text",s={}){const{projectId:a,tokenType:n="persistent",ttlMs:o}=s,d=ui(t,n,o);return Ue($e(`/remote/qr${d}`,a))}const gi=["defaultProviderOverride","defaultModelIdOverride","titleSummarizerProvider","titleSummarizerModelId","titleSummarizerFallbackProvider","titleSummarizerFallbackModelId","titleSummarizerFallbackThinkingLevel","mergerProvider","mergerModelId","mergerThinkingLevel","mergerFallbackProvider","mergerFallbackModelId","mergerFallbackThinkingLevel","githubImportAutoTranslate","importTranslateTargetLocale","importTranslateProvider","importTranslateModelId","importTranslateThinkingLevel"],wp=new Set(gi),Cp=new Set(["gitlabEnabled","gitlabInstanceUrl","gitlabApiBaseUrl","gitlabAuthToken","gitlabAuthTokenType","reportRoadmapDedupeEnabled","reportRoadmapLabel","reportRoadmapRepo"]),hi={"backups-global":new Set(["autoBackupEnabled","autoBackupSchedule","autoBackupRetention","autoBackupDir","embeddedPostgresMaxConnections"]),appearance:new Set(["themeMode","colorTheme","dashboardFontScalePct","shadcnCustomColors"]),notifications:new Set(["ntfyEnabled","agentClarificationEnabled","ntfyTopic","ntfyBaseUrl","ntfyAccessToken","ntfyEvents","ntfyDashboardHost","failureNotificationDelayMs","wedgeNotificationSettleMs","failureNotificationMode","webhookEnabled","webhookUrl","webhookFormat","webhookEvents","notificationProviders"]),experimental:new Set(["experimentalFeatures"]),"source-control-global":new Set(["githubTrackingDefaultRepo","gitlabEnabled","gitlabInstanceUrl","gitlabApiBaseUrl","gitlabAuthToken","gitlabAuthTokenType","reportRoadmapDedupeEnabled","reportRoadmapLabel","reportRoadmapRepo"]),"global-general":new Set(["language","dismissModalsOnOutsideClick","skipConfirmationDialogs","persistAgentToolOutput","agentToolOutputMaxChars","proactiveTaskChatEnabled","persistAgentThinkingLogPermanent","persistAgentThinkingLogEphemeral","fnBinaryCheckEnabled","updateCheckEnabled","updateCheckFrequency","updateChannel","autoUpdateAndRestart","autoReloadOnVersionChange"]),"keyboard-shortcuts":new Set(["dashboardKeyboardShortcuts"]),"global-mcp":new Set(["mcpServers"]),"global-models":new Set(["defaultProvider","defaultModelId","fallbackProvider","fallbackModelId","fallbackThinkingLevel","defaultThinkingLevel","modelRouterEnabled","modelRouterCheapProvider","modelRouterCheapModelId","opencodeGoModelSync","openrouterAppAttribution","openrouterModelFilters","openrouterModelSync","openrouterProviderPreferences","executionGlobalProvider","executionGlobalModelId","planningGlobalProvider","planningGlobalModelId","validatorGlobalProvider","validatorGlobalModelId","titleSummarizerGlobalProvider","titleSummarizerGlobalModelId","mergerGlobalProvider","mergerGlobalModelId","mergerGlobalThinkingLevel","importTranslateGlobalProvider","importTranslateGlobalModelId","importTranslateGlobalThinkingLevel"]),"project-models":new Set(["defaultProvider","defaultModelId","fallbackProvider","fallbackModelId","fallbackThinkingLevel","defaultThinkingLevel","modelRouterEnabled","modelRouterCheapProvider","modelRouterCheapModelId","opencodeGoModelSync","openrouterAppAttribution","openrouterModelFilters","openrouterModelSync","openrouterProviderPreferences","executionGlobalProvider","executionGlobalModelId","planningGlobalProvider","planningGlobalModelId","validatorGlobalProvider","validatorGlobalModelId","titleSummarizerGlobalProvider","titleSummarizerGlobalModelId","mergerGlobalProvider","mergerGlobalModelId","mergerGlobalThinkingLevel","importTranslateGlobalProvider","importTranslateGlobalModelId","importTranslateGlobalThinkingLevel"]),"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 Sp(t,s){const a=hi[s];return!a||a.has(t)}function Rt(t,s){return t==="global"?s?.global.mcpServers:s?.project.mcpServers}function wt(t,s){return!!t&&Object.prototype.hasOwnProperty.call(t,s)}function la(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ut(t,s){if(Object.is(t,s))return!0;if(Array.isArray(t)||Array.isArray(s))return!Array.isArray(t)||!Array.isArray(s)||t.length!==s.length?!1:t.every((a,n)=>Ut(a,s[n]));if(la(t)||la(s)){if(!la(t)||!la(s))return!1;const a=Object.keys(t),n=Object.keys(s);return a.length!==n.length?!1:a.every(o=>wt(s,o)&&Ut(t[o],s[o]))}return!1}function Cn(t,s){if(!(!wt(t,s)||t[s]===void 0))return String(t[s]??"")}function Np(t,s){if(!(!wt(t,s)||t[s]===void 0))return t[s]?String(t[s]):null}function Ht(t,s){if(!(!wt(t,s)||t[s]===void 0))return!!t[s]}function Sn(t,s,a){if(!(!wt(t,s)||t[s]===void 0))return Number(t[s]??a)}function Je(t,s,a){a!==void 0&&(t[s]=a)}function Pp(t){const s={},a=wt(t,"remoteActiveProvider")?t.remoteActiveProvider:void 0;a!==void 0&&(s.activeProvider=a);const n={};Je(n,"enabled",Ht(t,"remoteTailscaleEnabled")),Je(n,"hostname",Cn(t,"remoteTailscaleHostname")),Je(n,"targetPort",Sn(t,"remoteTailscaleTargetPort",4040)),Je(n,"acceptRoutes",Ht(t,"remoteTailscaleAcceptRoutes")),a==="tailscale"&&(n.enabled=!0);const o={};Je(o,"enabled",Ht(t,"remoteCloudflareEnabled")),Je(o,"quickTunnel",Ht(t,"remoteCloudflareQuickTunnel")),Je(o,"tunnelName",Cn(t,"remoteCloudflareTunnelName")),Je(o,"tunnelToken",Np(t,"remoteCloudflareTunnelToken")),Je(o,"ingressUrl",Cn(t,"remoteCloudflareIngressUrl")),a==="cloudflare"&&(o.enabled=!0),(Object.keys(n).length>0||Object.keys(o).length>0)&&(s.providers={},Object.keys(n).length>0&&(s.providers.tailscale=n),Object.keys(o).length>0&&(s.providers.cloudflare=o));const d={};Je(d,"enabled",Ht(t,"remoteShortLivedEnabled")),Je(d,"ttlMs",Sn(t,"remoteShortLivedTtlMs",9e5)),Je(d,"maxTtlMs",Sn(t,"remoteShortLivedMaxTtlMs",864e5)),Object.keys(d).length>0&&(s.tokenStrategy={shortLived:d});const u={};return Je(u,"rememberLastRunning",Ht(t,"remoteRememberLastRunning")),Je(u,"wasRunningOnShutdown",Ht(t,"remoteWasRunningOnShutdown")),wt(t,"remoteLastStartedProvider")&&t.remoteLastStartedProvider!==void 0&&(u.lastRunningProvider=t.remoteLastStartedProvider),Object.keys(u).length>0&&(s.lifecycle=u),Object.keys(s).length>0?s:null}function Rr({payload:t,initialValues:s,initialScopedValues:a,activeSection:n,scopedMcpValues:o}){const d={};if(n==="remote"){const c=Pp(t);c&&(d.remoteAccess=c)}for(const[c,l]of Object.entries(t))if(!(c==="githubTrackingDefaultRepo"&&n!=="source-control-global")&&!((c==="gitlabEnabled"||c==="gitlabInstanceUrl"||c==="gitlabApiBaseUrl"||c==="gitlabAuthToken"||c==="gitlabAuthTokenType")&&n!=="source-control-global")&&!(c==="mcpServers"&&o)&&!(c==="mcpServers"&&n!=="global-mcp")&&c!=="persistAgentThinkingLog"&&c!=="customProviders"&&qc(c)){if(!Sp(c,n))continue;if(l===void 0&&c==="ntfyAccessToken"&&n==="notifications"){d[c]=null;continue}const h=Cp.has(c),p=wt(a?.global,c),m=!h&&wt(s,c),x=p?a?.global?.[c]:h?void 0:s?.[c],w=p||m;if(Ut(l,x))continue;l===void 0&&w&&x!==void 0?d[c]=null:l!==void 0&&(d[c]=l)}const u={};for(const[c,l]of Object.entries(t)){if(c==="githubTokenConfigured"||c==="prAuthAvailable"||c==="customProviders"||c==="githubTrackingDefaultRepo"&&n==="source-control-global"||(c==="gitlabEnabled"||c==="gitlabInstanceUrl"||c==="gitlabApiBaseUrl"||c==="gitlabAuthToken"||c==="gitlabAuthTokenType"||c==="reportRoadmapDedupeEnabled"||c==="reportRoadmapLabel"||c==="reportRoadmapRepo")&&n==="source-control-global"||c==="mcpServers"&&o||c==="mcpServers"&&n==="global-mcp"||!Vc(c))continue;const h=a?.project?.[c];wp.has(c)?Ut(l,h)||(l==null&&h!==void 0&&h!==null?u[c]=null:l!==void 0&&(u[c]=l)):Ut(l,h)||(l===void 0&&h!==void 0&&h!==null?u[c]=null:l!==void 0&&(u[c]=l))}if(o){const c=Rt("global",a);Ut(o.global,c)||(d.mcpServers=o.global??null);const l=Rt("project",a);Ut(o.project,l)||(u.mcpServers=o.project??null)}return{globalPatch:d,projectPatch:u}}const Ip={general:["allowAbsoluteFileBrowserPaths","capacityRiskBannerEnabled","capacityRiskTodoThreshold","chatAutoCleanupDays","chatRoomCompactionFetchLimit","chatRoomRecentVerbatimMessages","chatRoomSummaryMaxChars","completionDocumentationMode","reviewArtifacts","enabledBuiltinWorkflowIds","taskCreateWorkflowId","refinementTaskWorkflowId","ephemeralAgentTaskCreationPolicy","sessionAdvisorEnabledByDefault","mailAutoCleanupDays","maxRecommendationsPerTask","recommendationMailboxNoticeEnabled","mobileNavPrimaryItems","operationalLogRetentionDays","quickChatButtonMode","quickChatCloseOnOutsideClick","showQuickChatFAB","showTaskChatsInCommonFeed","taskPrefix","workspaceMode","reportMode","reportModeByAction","reportRoadmapDedupeEnabled","reportRoadmapLabel","reportRoadmapRepo"],"source-control":["githubAuthMode","githubAuthToken","githubLinkImportedIssuesToTracking","githubTrackingDedupEnabled","githubTrackingDefaultRepo","githubTrackingEnabledByDefault","gitlabApiBaseUrl","gitlabAuthToken","gitlabAuthTokenType","gitlabEnabled","gitlabInstanceUrl"],commands:["buildCommand","testCommand"],worktrees:["executorAllowSiblingBranchRename","maxWorktrees","worktreeLimitEnabled","recycleWorktrees","showWorktreeGrouping","worktreeCopyFiles","worktreeInitCommand","worktreeNaming","worktreeRebaseBeforeMerge","worktreeRebaseLocalBase","worktreeRebaseRemote","worktreesDir","worktrunk"],scheduling:["archiveAgentLogMode","autoArchiveDoneAfterMs","autoArchiveDoneTasksEnabled","engineerBacklogAutoClaim","executorToolFailureRetryCount","executorToolFailureRetryBackoffMs","executorToolFailureThreshold","executorModelEscalationEnabled","executorEscalationNodeId","groupOverlappingFiles","heartbeatScopeDiscipline","ignoreHiddenOverlapPaths","maxConcurrent","maxConcurrentVerifications","maxStuckKills","overlapIgnorePaths","pollIntervalMs","preserveProgressOnStuckRequeue","specStalenessEnabled","specStalenessMaxAgeMs","staleHighFanoutBlockerAgeThresholdMs","taskStuckTimeoutMs"],"scheduled-evals":["evalSettings"],"node-routing":["defaultNodeId","unavailableNodePolicy"],merge:["autoMerge","autoResolveConflicts","commitAuthorEmail","commitAuthorEnabled","commitAuthorName","directMergeCommitStrategy","includeTaskIdInCommit","integrationBranch","maxAutoMergeRetries","mergeAdvanceAutoSync","mergeConflictStrategy","mergeIntegrationWorktree","mergeStrategy","githubNativeAutoMerge","requiredChecks","mergeStrategyOverlapBehavior","merger","planApprovalMode","postMergeAuditMode","pushAfterMerge","pushRemote","smartConflictResolution","testMode"],"agent-permissions":["agentProvisioning","defaultAgentPermissionPolicy"],backups:["memoryBackupDir","memoryBackupEnabled","memoryBackupRetention","memoryBackupSchedule","memoryBackupScope"],"research-project":["researchSettings"],"voice-input":["voiceInput"],"project-models":["autoSelectModelPreset","autoSummarizeTitles","defaultPresetBySize","taskDefinitionInInputLanguage","defaultWorkflowId","modelPresets","prDescriptionPromptInstructions","prTitlePromptInstructions","tokenCap","useAiMergeCommitSummary","executorEscalationProvider","executorEscalationModelId",...gi]},mi={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 Tp(t){if(mi[t])return null;const s=Ip[t];if(s)return{scope:"project",keys:s};const a=hi[t];return a?{scope:"global",keys:Array.from(a)}:null}function Ap(t){return mi[t]}const Mp=Yc,Rp=[{value:90,label:"Small"},{value:100,label:"Default"},{value:110,label:"Large"},{value:120,label:"Largest"}];function Ep({themeMode:t,colorTheme:s,dashboardFontScalePct:a=100,shadcnCustomColors:n={},resolvedThemeMode:o=t==="light"?"light":"dark",onThemeModeChange:d,onColorThemeChange:u,onDashboardFontScaleChange:c=()=>{},onShadcnCustomColorsChange:l=()=>{}}){const{t:h}=le("app"),p=i.useCallback(()=>{d("system"),u("shadcn-ember"),c(100),l({})},[d,u,c,l]);return e.jsxs("div",{className:"theme-selector",children:[e.jsx("div",{className:"theme-mode-toggle",role:"radiogroup","aria-label":h("theme.modeLabel","Theme mode"),children:Bu.map(({value:m,label:x,icon:w})=>e.jsxs("button",{className:`theme-mode-btn${t===m?" active":""}`,onClick:()=>d(m),"aria-pressed":t===m,"aria-label":h(`theme.${m}Mode`,`${x} mode`),title:h(`theme.${m}Mode`,`${x} mode`),children:[e.jsx(w,{size:16}),e.jsx("span",{children:h(`theme.${m}`,x)})]},m))}),e.jsx(Gu,{triggerVariant:"current-row",colorTheme:s,themeMode:t,onColorThemeChange:u,shadcnCustomColors:n,resolvedThemeMode:o,onShadcnCustomColorsChange:l}),e.jsx("div",{className:"theme-section-title",children:h("theme.fontSize","Font Size")}),e.jsx("div",{className:"theme-font-size-toggle",role:"radiogroup","aria-label":h("theme.fontSizeLabel","Dashboard font size"),children:Rp.map(({value:m,label:x})=>e.jsx("button",{className:`theme-font-size-btn${a===m?" active":""}`,onClick:()=>c(m),"aria-pressed":a===m,children:e.jsx("span",{children:h(`theme.fontSize.${x}`,x)})},m))}),e.jsx("button",{className:"theme-reset-btn",onClick:p,"aria-label":h("theme.resetLabel","Reset to default theme"),children:e.jsx("span",{children:h("theme.resetButton","Reset to defaults")})})]})}const ka=typeof window<"u";function Er(){if(ka)try{const t=localStorage.getItem(ha);return ns(t)?t:void 0}catch{return}}function Dr(){if(!ka)return Bn;for(const t of navigator.languages??[navigator.language]){const s=Jc(t);if(s)return s}return Bn}function Dp(){const{i18n:t}=le(),s=t.resolvedLanguage??t.language,a=ns(s)?s:Bn,[n,o]=i.useState(a),[d,u]=i.useState(()=>Er()!==void 0),c=i.useRef(!1);i.useEffect(()=>{const p=m=>{ns(m)&&o(m)};return t.on("languageChanged",p),()=>{t.off("languageChanged",p)}},[t]),i.useEffect(()=>{if(!ka)return;const p=m=>{if(m.key===ha){if(ns(m.newValue))u(!0),m.newValue!==t.resolvedLanguage&&t.changeLanguage(m.newValue);else if(m.newValue===null){u(!1);const x=Dr();x!==t.resolvedLanguage&&t.changeLanguage(x)}}};return window.addEventListener("storage",p),()=>{window.removeEventListener("storage",p)}},[t]),i.useEffect(()=>{if(!ka)return;let p=!1;return Qc().then(m=>{if(p||c.current)return;const x=ns(m.language)?m.language:void 0;x&&!Er()&&x!==t.resolvedLanguage&&t.changeLanguage(x)}).catch(m=>{console.warn("[useLanguage] Failed to hydrate language from global settings",m)}),()=>{p=!0}},[t]);const l=i.useCallback(p=>{c.current=!0,o(p),u(!0),t.changeLanguage(p);try{localStorage.setItem(ha,p)}catch{}ls({language:p}).catch(m=>{console.warn("[useLanguage] Failed to persist language to global settings",m)})},[t]),h=i.useCallback(()=>{c.current=!0,u(!1);try{localStorage.removeItem(ha)}catch{}ls({language:null}).catch(p=>{console.warn("[useLanguage] Failed to clear language in global settings",p)}),t.changeLanguage(Dr())},[t]);return{language:n,supportedLocales:ai,setLanguage:l,clearLanguage:h,hasExplicitChoice:d}}const Fp={en:"English","zh-CN":"简体中文","zh-TW":"繁體中文",fr:"Français",es:"Español",ko:"한국어","pt-BR":"Português (Brasil)"};function Lp(){const{t}=le("app"),{language:s,supportedLocales:a,setLanguage:n,clearLanguage:o,hasExplicitChoice:d}=Dp(),u=t("settings.appearance.language","Language");return e.jsxs("div",{className:"language-selector",children:[e.jsx("div",{className:"language-selector-title",children:u}),e.jsxs("div",{className:"language-options",role:"group","aria-label":u,children:[e.jsx("button",{type:"button",className:`language-option${d?"":" active"}`,onClick:o,"aria-pressed":!d,title:t("settings.appearance.languageAutoHint","Follow the browser language"),children:t("settings.appearance.languageAuto","Auto")}),a.map(c=>e.jsx("button",{type:"button",className:`language-option${d&&s===c?" active":""}`,onClick:()=>n(c),"aria-pressed":d&&s===c,lang:c,children:Fp[c]},c))]})]})}function Op({form:t,setForm:s,themeMode:a,colorTheme:n,dashboardFontScalePct:o,shadcnCustomColors:d={},resolvedThemeMode:u,onThemeModeChange:c,onColorThemeChange:l,onDashboardFontScaleChange:h,onShadcnCustomColorsChange:p,sessionBannersHidden:m,setSessionBannersHidden:x}){const{t:w}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:w("settings.appearance.title","Appearance")}),e.jsx(Ep,{themeMode:a,colorTheme:n,dashboardFontScalePct:o,onThemeModeChange:f=>{s(E=>({...E,themeMode:f})),c?.(f)},onColorThemeChange:f=>{s(E=>({...E,colorTheme:f})),l?.(f)},onDashboardFontScaleChange:f=>{s(E=>({...E,dashboardFontScalePct:f})),h?.(f)},shadcnCustomColors:d,resolvedThemeMode:u,onShadcnCustomColorsChange:f=>{s(E=>({...E,shadcnCustomColors:f})),p?.(f)}}),e.jsx(Lp,{}),e.jsx(ae,{descriptor:{key:"openTasksInRightSidebar",label:w("settings.appearance.openTasksInRightSidebar","Open tasks in the right sidebar"),help:w("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."),scope:"project"},value:t.openTasksInRightSidebar===!0,onChange:f=>s(E=>({...E,openTasksInRightSidebar:f===!0}))}),e.jsx(ae,{descriptor:{key:"openMobileTasksInPopup",label:w("settings.appearance.openMobileTasksInPopup","Open tasks as popups"),help:w("settings.appearance.openMobileTasksInPopupHelp","When enabled, board task-card clicks including Changes, Retries, and Workflow chips, plus ordinary List row/card and right-dock Tasks-list clicks, open the existing movable task popup so the board or list remains visible. Other task opens keep their current behavior. Default: disabled."),scope:"project"},value:t.openMobileTasksInPopup===!0,onChange:f=>s(E=>({...E,openMobileTasksInPopup:f===!0}))}),e.jsx(ae,{descriptor:{key:"taskPopupsBoardListOnly",label:w("settings.appearance.taskPopupsBoardListOnly","Keep task popups on the view where they were opened"),help:w("settings.appearance.taskPopupsBoardListOnlyHelp","When enabled, each open task-detail popup appears only on the view where it was opened. Switching views hides it without closing; returning restores it in the same position. Default: enabled."),scope:"project"},value:t.taskPopupsBoardListOnly===!0,onChange:f=>s(E=>({...E,taskPopupsBoardListOnly:f===!0}))}),e.jsx(ae,{descriptor:{key:"showCostBadgeOnCards",label:w("settings.appearance.showCostBadgeOnCards","Show cost badges on task cards"),help:w("settings.appearance.showCostBadgeOnCardsHelp","Default: disabled. When enabled, board cards show derived model cost next to execution time; unavailable pricing displays — and tasks without token usage show no badge."),scope:"project"},value:t.showCostBadgeOnCards===!0,onChange:f=>s(E=>({...E,showCostBadgeOnCards:f===!0}))}),e.jsx(ae,{descriptor:{key:"taskDetailChatFirst",label:w("settings.appearance.taskDetailChatFirst","Open task details with Chat first"),help:w("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."),scope:"project"},value:t.taskDetailChatFirst===!0,onChange:f=>s(E=>({...E,taskDetailChatFirst:f===!0}))}),e.jsx(ae,{descriptor:{key:"sessionBannersHidden",label:w("settings.appearance.hideAISessionNotificationBanners","Hide AI session notification banners"),help:w("settings.appearance.suppressTheLdquoNeedsYourInputRdquoBanner","Suppress the “needs your input” banner that appears when AI sessions are awaiting input or have failed.")},value:m,onChange:f=>x(f===!0)})]})}function Kp({form:t,setForm:s,knownFeatures:a,legacyAliases:n,getCanonicalKey:o,isFeatureEnabled:d,hiddenFeatureKeys:u}){const{t:c}=le("app"),l=t.experimentalFeatures??{},p=Array.from(new Set([...Object.keys(a),...Object.keys(l).map(o)])).filter(m=>!u?.has(m)).sort((m,x)=>m.localeCompare(x)).map(m=>[m,d(l,m)]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading",children:c("settings.experimental.experimentalFeatures","Experimental Features")}),e.jsx(G,{settingKey:"experimental-section",children:c("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:c("settings.experimental.featureFlags","Feature Flags")}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:p.map(([m,x])=>e.jsxs("label",{htmlFor:`experimental-${m}`,className:"checkbox-label",children:[e.jsx("input",{id:`experimental-${m}`,type:"checkbox",checked:x,onChange:w=>{s(f=>{const E={...f.experimentalFeatures??{},[m]:w.target.checked};for(const[N,S]of Object.entries(n))S===m&&delete E[N];return{...f,experimentalFeatures:E}})}}),e.jsx("span",{children:a[m]??m})]},m))})]})]})}function Bp({form:t,setForm:s}){const{t:a}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.nodeSync.nodeSync","Node Sync")}),e.jsx(ae,{descriptor:{key:"settingsSyncEnabled",label:a("settings.nodeSync.enableAutomaticSettingsSync"," Enable automatic settings sync "),help:a("settings.nodeSync.automaticallySynchronizeSettingsBetweenThisNodeAndConnected","Automatically synchronize settings between this node and connected remote nodes. Default: disabled."),scope:"global"},value:t.settingsSyncEnabled||!1,onChange:n=>s(o=>({...o,settingsSyncEnabled:n===!0}))}),t.settingsSyncEnabled&&e.jsxs(e.Fragment,{children:[e.jsx(ae,{descriptor:{key:"settingsSyncAuth",label:a("settings.nodeSync.syncModelAuthCredentials"," Sync model auth credentials "),help:a("settings.nodeSync.includeAPIKeysAndOAuthTokensInSync","Include API keys and OAuth tokens in sync operations. Default: disabled."),scope:"global"},value:t.settingsSyncAuth||!1,onChange:n=>s(o=>({...o,settingsSyncAuth:n===!0}))}),e.jsx(Ae,{descriptor:{key:"settingsSyncInterval",label:a("settings.nodeSync.syncInterval","Sync interval"),help:a("settings.nodeSync.syncIntervalHint","Default: every 15 minutes."),scope:"global",options:[{value:"300000",label:a("settings.nodeSync.every5Minutes","Every 5 minutes")},{value:"900000",label:a("settings.nodeSync.every15Minutes","Every 15 minutes")},{value:"1800000",label:a("settings.nodeSync.every30Minutes","Every 30 minutes")},{value:"3600000",label:a("settings.nodeSync.every1Hour","Every 1 hour")}]},value:String(t.settingsSyncInterval||9e5),onChange:n=>s(o=>({...o,settingsSyncInterval:parseInt(n??"",10)}))}),e.jsx(Ae,{descriptor:{key:"settingsSyncConflictResolution",label:a("settings.nodeSync.conflictResolution","Conflict resolution"),help:a("settings.nodeSync.conflictResolutionHint","Default: last write wins."),scope:"global",options:[{value:"last-write-wins",label:a("settings.nodeSync.lastWriteWins","Last write wins")},{value:"always-ask",label:a("settings.nodeSync.alwaysAsk","Always ask")},{value:"keep-local",label:a("settings.nodeSync.keepLocal","Keep local")},{value:"keep-remote",label:a("settings.nodeSync.keepRemote","Keep remote")}]},value:t.settingsSyncConflictResolution||"last-write-wins",onChange:n=>s(o=>({...o,settingsSyncConflictResolution:n}))})]}),e.jsx("p",{className:"settings-sync-workflow-note text-muted",role:"note",children:a("settings.nodeSync.workflowSettingsNotSynced","Workflow settings are not synced across nodes yet.")})]})}const Nn=["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"],Fr=[{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 Gp({form:t,setForm:s,testNotificationLoading:a,testNotificationResult:n,onTestProviderNotification:o}){const{t:d}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:d("settings.notifications.notifications","Notifications")}),e.jsx("div",{className:"notification-provider-card",children:e.jsxs("div",{className:"notification-provider-body",children:[e.jsx(Ae,{descriptor:{key:"failureNotificationMode",label:d("settings.notifications.failureNotificationMode","Failure notification mode"),help:d("settings.notifications.stickyOnlySuppressesRecoveredFailuresTerminalOnlyWaits","Sticky-only suppresses recovered failures; terminal-only waits for paused/in-review failed tasks; all restores legacy alerts."),scope:"global",options:[{value:"sticky-only",label:d("settings.notifications.stickyFailuresOnlyDefault","Sticky failures only (default)")},{value:"terminal-only",label:d("settings.notifications.terminalFailuresOnlySuppressAutoRetried","Terminal failures only (suppress auto-retried)")},{value:"all",label:d("settings.notifications.allFailuresLegacy","All failures (legacy)")}]},value:t.failureNotificationMode??"sticky-only",onChange:u=>s(c=>({...c,failureNotificationMode:u??"sticky-only"}))}),e.jsx(Pe,{descriptor:{key:"failureNotificationDelayMs",label:d("settings.notifications.failureNotificationDelayMs","Failure notification delay (ms)"),help:d("settings.notifications.howLongAFailureMustPersistBeforeA"," How long a failure must persist before a push notification is sent. 0 = notify immediately. Default: 30000 (30 seconds). "),scope:"global",min:0,step:1e3,disabled:(t.failureNotificationMode??"sticky-only")==="all"},value:t.failureNotificationDelayMs??3e4,onChange:u=>s(c=>({...c,failureNotificationDelayMs:u!==null&&Number.isFinite(u)&&u>=0?u:0}))}),e.jsx(Pe,{descriptor:{key:"wedgeNotificationSettleMs",label:d("settings.notifications.wedgeNotificationSettleMs","Terminal-wedge settle window (ms)"),help:d("settings.notifications.wedgeNotificationSettleMsHelp","How long a terminal failure must persist before an operator alert. 0 = notify immediately. Default: 300000 (5 minutes)."),scope:"global",min:0,step:1e3},value:t.wedgeNotificationSettleMs??3e5,onChange:u=>s(c=>({...c,wedgeNotificationSettleMs:u!==null&&Number.isFinite(u)&&u>=0?u:0}))})]})}),e.jsx("div",{className:"notification-provider-card",children:e.jsxs("div",{className:"notification-provider-header",children:[e.jsx("strong",{children:d("settings.notifications.agentClarification","Agent clarification")}),e.jsxs("label",{htmlFor:"agentClarificationEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"agentClarificationEnabled",type:"checkbox",checked:t.agentClarificationEnabled??!1,onChange:u=>s(c=>({...c,agentClarificationEnabled:u.target.checked}))}),d("settings.notifications.agentClarificationEnable"," Allow the planner to ask questions")]}),e.jsx(G,{settingKey:"agentClarificationEnabled",children:d("settings.notifications.agentClarificationHint","Default: disabled. When enabled, planner questions pause planning and notify your mailbox.")})]})}),e.jsxs("div",{className:"notification-provider-card",children:[e.jsxs("div",{className:"notification-provider-header",children:[e.jsx("strong",{children:d("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:u=>s(c=>({...c,ntfyEnabled:u.target.checked}))}),d("settings.notifications.enable"," Enable ")]}),e.jsx(G,{settingKey:"ntfyEnabled",children:d("settings.notifications.ntfyEnabledHint","Default: disabled.")})]}),t.ntfyEnabled&&e.jsxs("div",{className:"notification-provider-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"ntfyTopic",children:d("settings.notifications.ntfyTopic","ntfy Topic")}),e.jsxs(G,{settingKey:"ntfyTopic",children:[d("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:d("settings.notifications.learnMoreAboutNtfySh"," Learn more about ntfy.sh ")})]})]}),e.jsx("input",{id:"ntfyTopic",type:"text",placeholder:d("settings.notifications.myTopicName","my-topic-name"),value:t.ntfyTopic||"",onChange:u=>{const c=u.target.value;s(l=>({...l,ntfyTopic:c||void 0}))}}),t.ntfyTopic&&!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic)&&e.jsx("small",{className:"field-error",children:d("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:d("settings.notifications.advanced","Advanced")}),e.jsxs("div",{className:"ntfy-advanced-content",children:[e.jsx(be,{descriptor:{key:"ntfyBaseUrl",label:d("settings.notifications.customNtfyServerURLOptional","Custom ntfy server URL (optional)"),help:d("settings.notifications.leaveBlankToKeepTheDefaultServerHttps"," Leave blank to keep the default server: https://ntfy.sh. Custom servers must use http:// or https://. No default — unset. "),placeholder:d("settings.notifications.httpsNtfySh","https://ntfy.sh"),type:"url",scope:"global"},value:t.ntfyBaseUrl??null,onChange:u=>s(c=>({...c,ntfyBaseUrl:u||void 0}))}),e.jsx(be,{descriptor:{key:"ntfyAccessToken",label:d("settings.notifications.accessTokenOptional","Access token (optional)"),help:d("settings.notifications.leaveBlankToPublishWithoutAuthenticationWhenSet"," Leave blank to publish without authentication. When set, Fusion sends an Authorization Bearer header with ntfy requests. No default — unset. "),placeholder:d("settings.notifications.tk","tk_..."),type:"password",scope:"global"},value:t.ntfyAccessToken??null,onChange:u=>s(c=>({...c,ntfyAccessToken:u||void 0}))})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:d("settings.notifications.notifyOnEvents","Notify on events")}),e.jsx("div",{className:"ntfy-events-list",children:Fr.map(({event:u,label:c,description:l})=>{const h=t.ntfyEvents?.includes(u)??!0;return e.jsx("div",{children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:h,onChange:p=>{const m=t.ntfyEvents??[...Nn],x=p.target.checked?m.includes(u)?m:[...m,u]:m.filter(w=>w!==u);s(w=>({...w,ntfyEvents:x.length>0?x:void 0}))}}),c]}),e.jsx(G,{settingKey:`ntfy-event-${u}`,children:l})]})},`ntfy-${u}`)})})]}),e.jsx(be,{descriptor:{key:"ntfyDashboardHost",label:d("settings.notifications.dashboardHostname","Dashboard Hostname"),help:d("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. "),scope:"global",placeholder:d("settings.notifications.httpLocalhost3000","http://localhost:3000")},value:t.ntfyDashboardHost||"",onChange:u=>s(c=>({...c,ntfyDashboardHost:u||void 0})),error:t.ntfyDashboardHost&&!/^https?:\/\/.+/.test(t.ntfyDashboardHost)?d("settings.notifications.mustBeAValidURLStartingWithHttp"," Must be a valid URL starting with http:// or https:// "):void 0}),e.jsxs("div",{className:"notification-provider-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ntfy"),disabled:a.ntfy||a["ntfy-message"]||a["ntfy-room"]||!t.ntfyEnabled||!t.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic),children:a.ntfy?d("settings.notifications.sending","Sending…"):d("settings.notifications.testNotification","Test notification")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ntfy-message"),disabled:a.ntfy||a["ntfy-message"]||a["ntfy-room"]||!t.ntfyEnabled||!t.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic),children:a["ntfy-message"]?d("settings.notifications.sending","Sending…"):d("settings.notifications.testMessageInbox","Test message inbox")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ntfy-room"),disabled:a.ntfy||a["ntfy-message"]||a["ntfy-room"]||!t.ntfyEnabled||!t.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(t.ntfyTopic),children:a["ntfy-room"]?d("settings.notifications.sending","Sending…"):d("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:[d("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:[d("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:[d("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:d("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:u=>s(c=>({...c,webhookEnabled:u.target.checked}))}),d("settings.notifications.webhookNotifications"," Webhook notifications ")]}),e.jsx(G,{settingKey:"webhookEnabled",children:d("settings.notifications.webhookEnabledHint","Default: disabled.")})]}),t.webhookEnabled&&e.jsxs("div",{className:"notification-provider-body",children:[e.jsx(be,{descriptor:{key:"webhookUrl",label:d("settings.notifications.webhookURL","Webhook URL"),help:d("settings.notifications.webhookUrlHint","No default — unset."),scope:"global",placeholder:d("settings.notifications.httpsHooksExampleCom","https://hooks.example.com/...")},value:t.webhookUrl||"",onChange:u=>s(c=>({...c,webhookUrl:u||void 0}))}),e.jsx(Ae,{descriptor:{key:"webhookFormat",label:d("settings.notifications.format","Format"),help:d("settings.notifications.webhookFormatHint","Default: generic."),scope:"global",options:[{value:"slack",label:d("settings.notifications.slack","Slack")},{value:"discord",label:d("settings.notifications.discord","Discord")},{value:"generic",label:d("settings.notifications.generic","Generic")}]},value:t.webhookFormat||"generic",onChange:u=>s(c=>({...c,webhookFormat:u??"generic"}))}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:d("settings.notifications.notifyOnEvents","Notify on events")}),e.jsx("div",{className:"ntfy-events-list",children:Fr.map(({event:u,label:c,description:l})=>{const p=(t.webhookEvents??[...Nn]).includes(u);return e.jsx("div",{children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:m=>{const x=t.webhookEvents??[...Nn],w=m.target.checked?x.includes(u)?x:[...x,u]:x.filter(f=>f!==u);s(f=>({...f,webhookEvents:w.length>0?w:void 0}))}}),c]}),e.jsx(G,{settingKey:`webhook-event-${u}`,children:l})]})},`webhook-${u}`)})})]}),e.jsx("div",{className:"notification-provider-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>o("webhook"),disabled:a.webhook||!t.webhookUrl,children:a.webhook?d("settings.notifications.sending","Sending…"):d("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})})]})]})]})}function Hp({form:t,setForm:s}){const{t:a}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.globalGeneral.general","General")}),e.jsx(ae,{descriptor:{key:"dismissModalsOnOutsideClick",label:a("settings.globalGeneral.dismissModalsByClickingOutside"," Dismiss modals by clicking outside "),help:a("settings.globalGeneral.dismissModalsByClickingOutsideHint"," When enabled, clicking or tapping a modal backdrop closes the modal. Default: disabled, to prevent accidental dismissal. "),scope:"global"},value:t.dismissModalsOnOutsideClick===!0,onChange:n=>s(o=>({...o,dismissModalsOnOutsideClick:n===!0}))}),e.jsx(ae,{descriptor:{key:"skipConfirmationDialogs",label:a("settings.globalGeneral.skipConfirmationDialogs"," Skip confirmation dialogs for critical actions "),help:a("settings.globalGeneral.skipConfirmationDialogsHint"," When enabled, destructive actions such as deleting a task or resetting progress run immediately without a prompt. Default: disabled"),scope:"global"},value:t.skipConfirmationDialogs===!0,onChange:n=>s(o=>({...o,skipConfirmationDialogs:n===!0}))}),e.jsx(ae,{descriptor:{key:"persistAgentToolOutput",label:a("settings.globalGeneral.saveToolOutputInAgentLogs"," Save tool output in agent logs "),help:a("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. "),scope:"global"},value:t.persistAgentToolOutput===!0,onChange:n=>s(o=>({...o,persistAgentToolOutput:n===!0}))}),e.jsx(ae,{descriptor:{key:"agentToolOutputMaxCharsNoLimit",label:a("settings.globalGeneral.noLimitOnAgentToolOutput"," No limit on agent tool output "),help:a("settings.globalGeneral.noLimitOnAgentToolOutputHint"," Disable the shared tool-output clamp. A single tool result can consume the agent context window. Default: disabled; when unset, the budget inherits the 16,000-character engine default. "),scope:"global"},value:t.agentToolOutputMaxChars===0,onChange:n=>s(o=>({...o,agentToolOutputMaxChars:n?0:null}))}),e.jsx(Pe,{descriptor:{key:"agentToolOutputMaxChars",label:a("settings.globalGeneral.agentToolOutputLimit"," Agent tool-output limit "),help:a("settings.globalGeneral.agentToolOutputLimitHint"," Maximum characters returned from each engine-injected tool result. When unset, inherits the 16,000-character engine default. Leave empty to use the default. "),scope:"global",min:1,step:1e3,placeholder:"16000",disabled:t.agentToolOutputMaxChars===0},value:t.agentToolOutputMaxChars===0?null:t.agentToolOutputMaxChars??null,clearable:!0,onChange:n=>s(o=>({...o,agentToolOutputMaxChars:n}))}),e.jsx(ae,{descriptor:{key:"proactiveTaskChatEnabled",label:a("settings.globalGeneral.enableProactiveTaskChat"," Enable proactive task-chat updates "),help:a("settings.globalGeneral.enableProactiveTaskChatHint"," When enabled, Task chat reports step progress, failures, reviews, and rollbacks in real time. Default: disabled. "),scope:"global"},value:t.proactiveTaskChatEnabled===!0,onChange:n=>s(o=>({...o,proactiveTaskChatEnabled:n===!0}))}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h5",{className:"settings-section-heading",children:a("settings.globalGeneral.saveAIThinkingLogs","Save AI thinking logs")}),e.jsxs(G,{settingKey:"persistAgentThinkingLog",children:[a("settings.globalGeneral.leaveBothThinkingTogglesOffToKeepThe"," Leave both thinking toggles off to keep the original default behavior. This only controls persisted "),e.jsx("code",{children:"thinking"}),a("settings.globalGeneral.rowsAndDoesNotAffectAssistantTextOr"," rows and does not affect assistant text or tool rows. Default: disabled for both permanent and ephemeral agents. ")]})]}),e.jsxs("label",{htmlFor:"persistAgentThinkingLogPermanent",className:"checkbox-label",children:[e.jsx("input",{id:"persistAgentThinkingLogPermanent",type:"checkbox",checked:Jl(t,{ephemeral:!1}),onChange:n=>s(o=>({...o,persistAgentThinkingLogPermanent:n.target.checked}))}),a("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:Jl(t,{ephemeral:!0}),onChange:n=>s(o=>({...o,persistAgentThinkingLogEphemeral:n.target.checked}))}),a("settings.globalGeneral.saveAIThinkingForEphemeralTaskWorkerAgents"," Save AI thinking for ephemeral / task-worker agents ")]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"fnBinaryCheckEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"fnBinaryCheckEnabled",type:"checkbox",checked:t.fnBinaryCheckEnabled!==!1,onChange:n=>s(o=>({...o,fnBinaryCheckEnabled:n.target.checked}))}),a("settings.globalGeneral.checkForThe"," Check for the "),e.jsx("code",{children:"fn"}),a("settings.globalGeneral.cLIBinaryOnPATH"," CLI binary on PATH ")]}),e.jsxs(G,{settingKey:"fnBinaryCheckEnabled",children:[a("settings.globalGeneral.whenEnabledTheDashboardProbesForAGlobally"," When enabled, the dashboard probes for a globally-installed")," ",e.jsx("code",{children:"fn"})," / ",e.jsx("code",{children:"fusion"}),a("settings.globalGeneral.cLIBySpawning"," CLI by spawning")," ",e.jsx("code",{children:"<bin> --version"}),a("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:a("settings.globalGeneral.updates","Updates")}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"updateCheckEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"updateCheckEnabled",type:"checkbox",checked:t.updateCheckEnabled!==!1,onChange:n=>s(o=>({...o,updateCheckEnabled:n.target.checked}))}),a("settings.globalGeneral.checkForUpdatesAutomatically"," Check for updates automatically ")]}),e.jsxs(G,{settingKey:"updateCheckEnabled",children:[a("settings.globalGeneral.whenEnabledFusionChecksNpmForNewVersions"," When enabled, Fusion checks npm for new versions of")," ",e.jsx("code",{children:"@runfusion/fusion"}),a("settings.globalGeneral.andShowsUpdateNoticesInTheCLIAnd"," and shows update notices in the CLI and dashboard. Cadence is governed by the frequency below. Default: enabled. ")]})]})}),e.jsx(Ae,{descriptor:{key:"updateCheckFrequency",label:a("settings.globalGeneral.frequency","Frequency"),help:a("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. "),scope:"global",disabled:t.updateCheckEnabled===!1,options:[{value:"manual",label:a("settings.globalGeneral.manualOnlyNeverAutoCheck","Manual only — never auto-check")},{value:"on-startup",label:a("settings.globalGeneral.onStartupOncePerServerLaunch","On startup — once per server launch")},{value:"daily",label:a("settings.globalGeneral.dailyRecommended","Daily (recommended)")},{value:"weekly",label:a("settings.globalGeneral.weekly","Weekly")}]},value:t.updateCheckFrequency??"daily",onChange:n=>s(o=>({...o,updateCheckFrequency:n}))}),e.jsx(Ae,{descriptor:{key:"updateChannel",label:a("settings.globalGeneral.releaseChannel","Release channel"),help:a("settings.globalGeneral.releaseChannelHelp"," Stable follows official releases. Beta follows pre-releases cut from main (versions like 0.73.0-beta.2) and also picks up each stable release once it overtakes the beta. Switching back to Stable never downgrades; you stay on the installed beta until the next stable release passes it. Default: stable. "),scope:"global",options:[{value:"stable",label:a("settings.globalGeneral.channelStable","Stable (recommended)")},{value:"beta",label:a("settings.globalGeneral.channelBeta","Beta — early builds from main")}]},value:t.updateChannel??"stable",onChange:n=>s(o=>({...o,updateChannel:n}))}),e.jsx(ae,{descriptor:{key:"autoUpdateAndRestart",label:a("settings.globalGeneral.autoUpdateAndRestart"," Auto-update and restart "),help:a("settings.globalGeneral.autoUpdateAndRestartHelp",' When enabled, Fusion installs available updates on the selected release channel by itself and then restarts to apply them — the same install + restart the "Update now" button performs, without asking. Requires a supervising parent (the default for `fn dashboard`); hosts started with --no-supervise skip the install. Default: disabled. '),scope:"global"},value:t.autoUpdateAndRestart===!0,onChange:n=>s(o=>({...o,autoUpdateAndRestart:n===!0}))}),e.jsx(ae,{descriptor:{key:"autoReloadOnVersionChange",label:a("settings.globalGeneral.autoReloadDashboardOnVersionChange"," Auto-reload dashboard on version change "),help:a("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. "),scope:"global"},value:t.autoReloadOnVersionChange!==!1,onChange:n=>s(o=>({...o,autoReloadOnVersionChange:n===!0}))})]})}function _p({id:t,value:s,defaultValue:a,invalid:n,describedById:o,onChange:d}){const{t:u}=le("app"),[c,l]=i.useState(!1),h=i.useRef(null),p=i.useCallback(()=>{h.current?.(),h.current=null,l(!1)},[]);i.useEffect(()=>()=>{h.current?.(),h.current=null},[]);const m=i.useCallback(()=>{if(typeof document>"u")return;l(!0);const x=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){p();return}if(["Control","Alt","Shift","Meta"].includes(w.key))return;const f=[];w.ctrlKey&&f.push("Ctrl"),w.altKey&&f.push("Alt"),w.shiftKey&&f.push("Shift"),w.metaKey&&f.push("Meta"),f.push(w.key===" "?"Space":w.key);const E=zn(f.join("+"));E.valid&&!E.disabled&&d(E.normalized),p()};document.addEventListener("keydown",x,{capture:!0}),h.current=()=>document.removeEventListener("keydown",x,{capture:!0})},[d,p]);return e.jsxs("div",{className:"shortcut-capture","data-shortcuts-ignore":"true",children:[e.jsx("input",{id:t,className:`input shortcut-capture__input${n?" shortcut-capture__input--invalid":""}`,value:c?u("settings.keyboardShortcuts.recording","Press keys… (Esc to cancel)"):s,placeholder:a,readOnly:c,"aria-invalid":n||void 0,"aria-describedby":o,"data-shortcuts-ignore":"true",onFocus:x=>{c&&x.currentTarget.blur()},onChange:x=>d(x.target.value)}),e.jsx("button",{type:"button",className:`btn btn-sm shortcut-capture__record${c?" shortcut-capture__record--active":""}`,"aria-pressed":c,title:c?u("settings.keyboardShortcuts.recordingTitle","Recording… press Escape to cancel"):u("settings.keyboardShortcuts.recordTitle","Record a new shortcut"),onClick:()=>c?p():m(),children:c?u("settings.keyboardShortcuts.recordingLabel","Recording…"):u("settings.keyboardShortcuts.recordLabel","Record")}),e.jsx("button",{type:"button",className:"btn btn-sm shortcut-capture__clear",title:u("settings.keyboardShortcuts.clearTitle","Disable this shortcut"),onClick:()=>{c&&p(),d("")},children:u("settings.keyboardShortcuts.clearLabel","Clear")})]})}function Up({form:t,setForm:s}){const{t:a}=le("app"),n=Gn(t.dashboardKeyboardShortcuts),o=ni(n),d=(u,c)=>s(l=>({...l,dashboardKeyboardShortcuts:{...Gn(l.dashboardKeyboardShortcuts),[u]:c}}));return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.keyboardShortcuts.title","Keyboard Shortcuts")}),e.jsx(G,{settingKey:"dashboardKeyboardShortcuts",children:a("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:[Xc.map(u=>e.jsxs("div",{className:"shortcut-category",children:[e.jsx("h5",{className:"settings-section-heading",children:a(`settings.keyboardShortcuts.category.${u.id}`,u.label)}),u.actions.map(c=>{const l=zn(n[c]),h=`dashboardShortcut-${c}`,p=`${h}Hint`;return e.jsxs("div",{className:"shortcut-row",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:h,children:a(`settings.keyboardShortcuts.action.${c}`,Zc(c))}),e.jsx(G,{settingKey:h,children:a("settings.keyboardShortcuts.rowHint","Default: {{default}}. Leave blank to disable.",{default:Xl[c]})})]}),e.jsx(_p,{id:h,value:n[c],defaultValue:Xl[c],invalid:!l.valid,describedById:p,onChange:m=>d(c,m)}),e.jsx("small",{id:p,children:l.valid?null:l.error})]},c)})]},u.id)),o&&e.jsx("small",{className:"settings-description shortcut-conflict-banner",role:"alert",children:o})]})]})}function Wp({form:t,setForm:s,authProviders:a,onNavigateToSection:n}){const{t:o}=le("app"),d=t.researchGlobalWebSearchProvider??t.researchGlobalDefaults?.searchProvider??"builtin",u=d==="searxng"||d==="brave"||d==="google"||d==="tavily",c=d==="brave"||d==="tavily"?d:null,l=c?a.some(p=>p.id===c&&!p.authenticated):!1,h=p=>{s(m=>({...m,researchGlobalWebSearchProvider:p,researchGlobalDefaults:{...m.researchGlobalDefaults??{},searchProvider:p}}))};return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:o("settings.researchGlobal.researchDefaults","Research Defaults")}),e.jsxs("div",{className:"form-group settings-research-provider-group",children:[e.jsxs("div",{className:"settings-field-label-row",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:!u,onChange:()=>h("builtin")}),o("settings.researchGlobal.builtInUsesAgentWebTools"," Built-in (uses agent web tools) (default) ")]}),e.jsx(G,{settingKey:"research-global-provider-builtin",children:o("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:o("settings.researchGlobal.advancedExternalSearchProviders","Advanced — external search providers")}),e.jsxs("div",{className:"settings-research-provider-advanced-body",children:[e.jsx(Ae,{descriptor:{key:"researchGlobalWebSearchProvider",label:o("settings.researchGlobal.searchProvider","Search Provider"),scope:"global",options:[{value:"searxng",label:o("settings.researchGlobal.searXNG","SearXNG")},{value:"brave",label:o("settings.researchGlobal.brave","Brave")},{value:"google",label:o("settings.researchGlobal.googleCustomSearch","Google Custom Search")},{value:"tavily",label:o("settings.researchGlobal.tavily","Tavily")}]},value:u?d:"searxng",onChange:p=>h(p)}),e.jsx(be,{descriptor:{key:"researchGlobalSearxngUrl",label:o("settings.researchGlobal.searXNGURL","SearXNG URL"),help:o("settings.researchGlobal.searXNGURLHint","No default — unset."),scope:"global",placeholder:o("settings.researchGlobal.httpsSearxExampleCom","https://searx.example.com")},value:t.researchGlobalSearxngUrl??null,onChange:p=>s(m=>({...m,researchGlobalSearxngUrl:p||void 0}))}),e.jsx(be,{descriptor:{key:"researchGlobalGoogleSearchCx",label:o("settings.researchGlobal.googleSearchCX","Google Search CX"),help:o("settings.researchGlobal.googleSearchCXHint","No default — unset."),scope:"global",placeholder:o("settings.researchGlobal.customSearchEngineId","custom-search-engine-id")},value:t.researchGlobalGoogleSearchCx??null,onChange:p=>s(m=>({...m,researchGlobalGoogleSearchCx:p||void 0}))}),e.jsxs("div",{className:"settings-empty-state settings-research-empty-state",role:"note",children:[o("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:o("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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-global-max-concurrent",children:o("settings.researchGlobal.defaultMaxConcurrentRuns","Default Max Concurrent Runs")}),e.jsx(G,{settingKey:"research-global-max-concurrent",children:o("settings.researchGlobal.maxConcurrentRunsHint","Default: 3.")})]}),e.jsx("input",{id:"research-global-max-concurrent",className:"input",type:"number",min:1,value:t.researchGlobalMaxConcurrentRuns??3,onChange:p=>s(m=>({...m,researchGlobalMaxConcurrentRuns:p.target.value===""?void 0:Number(p.target.value)}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-global-max-sources",children:o("settings.researchGlobal.defaultMaxSourcesPerRun","Default Max Sources Per Run")}),e.jsx(G,{settingKey:"research-global-max-sources",children:o("settings.researchGlobal.maxSourcesPerRunHint","Default: 20.")})]}),e.jsx("input",{id:"research-global-max-sources",className:"input",type:"number",min:1,value:t.researchGlobalMaxSourcesPerRun??20,onChange:p=>s(m=>({...m,researchGlobalMaxSourcesPerRun:p.target.value===""?void 0:Number(p.target.value),researchGlobalDefaults:{...m.researchGlobalDefaults??{},maxSourcesPerRun:p.target.value===""?void 0:Number(p.target.value)}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-global-default-timeout",children:o("settings.researchGlobal.defaultMaxDurationMs","Default Max Duration (ms)")}),e.jsx(G,{settingKey:"research-global-default-timeout",children:o("settings.researchGlobal.defaultMaxDurationMsHint","Default: 300000 (5 minutes).")})]}),e.jsx("input",{id:"research-global-default-timeout",className:"input",type:"number",min:1e3,value:t.researchGlobalDefaultTimeout??3e5,onChange:p=>s(m=>({...m,researchGlobalDefaultTimeout:p.target.value===""?void 0:Number(p.target.value)}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-global-fetch-timeout",children:o("settings.researchGlobal.requestTimeoutMs","Request Timeout (ms)")}),e.jsx(G,{settingKey:"research-global-fetch-timeout",children:o("settings.researchGlobal.requestTimeoutMsHint","Default: 30000 (30 seconds).")})]}),e.jsx("input",{id:"research-global-fetch-timeout",className:"input",type:"number",min:1e3,value:t.researchGlobalFetchTimeoutMs??3e4,onChange:p=>s(m=>({...m,researchGlobalFetchTimeoutMs:p.target.value===""?void 0:Number(p.target.value)}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-global-max-synthesis-rounds",children:o("settings.researchGlobal.maxSynthesisRounds","Max Synthesis Rounds")}),e.jsx(G,{settingKey:"research-global-max-synthesis-rounds",children:o("settings.researchGlobal.maxSynthesisRoundsHint","Default: 2.")})]}),e.jsx("input",{id:"research-global-max-synthesis-rounds",className:"input",type:"number",min:1,value:t.researchGlobalMaxSynthesisRounds??2,onChange:p=>s(m=>({...m,researchGlobalMaxSynthesisRounds:p.target.value===""?void 0:Number(p.target.value)}))})]})]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:o("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}),o("settings.researchGlobal.webSearch"," Web Search "),e.jsx("span",{className:"settings-muted",children:o("settings.researchGlobal.alwaysOn","Always on")})]}),e.jsxs("div",{className:"settings-research-source-grid",children:[e.jsxs("div",{className:"settings-field-label-row",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:p=>s(m=>({...m,researchGlobalGitHubEnabled:p.target.checked}))}),o("settings.researchGlobal.gitHub"," GitHub ")]}),e.jsx(G,{settingKey:"research-global-source-github",children:o("settings.researchGlobal.gitHubSourceHint"," Default: disabled. ")})]}),e.jsxs("div",{className:"settings-field-label-row",children:[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:p=>s(m=>({...m,researchGlobalLocalDocsEnabled:p.target.checked}))}),o("settings.researchGlobal.localDocs"," Local Docs ")]}),e.jsx(G,{settingKey:"research-global-source-local-docs",children:o("settings.researchGlobal.localDocsSourceHint"," Default: enabled. ")})]})]})]}),l&&e.jsxs("div",{className:"settings-empty-state",role:"alert",children:[o("settings.researchGlobal.missingCredentialsForTheSelectedResearchProvider"," Missing credentials for the selected research provider. "),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>n("authentication"),children:o("settings.researchGlobal.openAuthentication"," Open Authentication ")})]})]})}function $p({form:t,setForm:s,remote:a}){const{t:n}=le("app"),{projectId:o,addToast:d,remoteStatus:u,externalTunnel:c,tunnelShareLink:l,remoteBusyAction:h,cloudflaredInstalling:p,cloudflaredInstallError:m,cloudflaredManualInstallCommand:x,cloudflaredMacFallbackCommand:w,handleInstallCloudflared:f,runRemoteAction:E,remoteShortLivedToken:N,setRemoteShortLivedToken:S,remoteAuthLinkTokenType:L,setRemoteAuthLinkTokenType:F,remoteUrlPreview:K,setRemoteUrlPreview:R,remoteQrSvg:T,setRemoteQrSvg:b}=a,V=t,X=V.remoteActiveProvider??null,k=u?.state??"stopped",I=k==="running"?"running":k==="starting"?"starting":k==="failed"||k==="error"?"error":"stopped",B=v=>{const M=t;return{remoteActiveProvider:v,remoteTailscaleEnabled:v==="tailscale",remoteTailscaleHostname:String(M.remoteTailscaleHostname??""),remoteTailscaleTargetPort:Number(M.remoteTailscaleTargetPort??4040),remoteTailscaleAcceptRoutes:!!M.remoteTailscaleAcceptRoutes,remoteCloudflareEnabled:v==="cloudflare",remoteCloudflareQuickTunnel:!!(M.remoteCloudflareQuickTunnel??!0),remoteCloudflareTunnelName:String(M.remoteCloudflareTunnelName??""),remoteCloudflareTunnelToken:M.remoteCloudflareTunnelToken||null,remoteCloudflareIngressUrl:String(M.remoteCloudflareIngressUrl??""),remoteShortLivedEnabled:!!M.remoteShortLivedEnabled,remoteShortLivedTtlMs:Number(M.remoteShortLivedTtlMs??9e5),remoteRememberLastRunning:!!M.remoteRememberLastRunning}};return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:n("settings.remote.remoteAccess","Remote Access")}),e.jsxs("div",{className:`remote-status-bar remote-status-bar--${I}`,children:[e.jsx("span",{className:`remote-status-dot remote-status-dot--${I}`}),e.jsx("strong",{children:k}),u?.provider&&e.jsxs("span",{children:[" · ",u.provider]}),u?.url&&e.jsx("code",{className:"remote-status-url",children:u.url}),u?.lastError&&e.jsx("span",{className:"field-error",children:u.lastError})]}),k==="stopped"&&c&&e.jsxs("div",{className:"remote-external-tunnel-panel",role:"status",children:[e.jsxs("div",{className:"remote-external-tunnel-header",children:[e.jsx(ba,{"aria-hidden":"true"}),e.jsxs("strong",{children:[n("settings.remote.external","External "),c.provider,n("settings.remote.tunnelDetected"," tunnel detected")]})]}),c.url&&e.jsx("code",{className:"settings-url-output",children:c.url}),l?.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(l.qrSvg)}`,alt:n("settings.remote.externalTunnelQRCode","External tunnel QR code"),className:"settings-qr-preview-image"})]})]}),k==="running"&&(u?.url||l)&&(()=>{let v=null,M=u?.url??null;if(l?.url)try{const se=new URL(l.url);v=se.searchParams.get("rt"),M||(M=`${se.origin}/`)}catch{}return e.jsxs("div",{className:"remote-share-block",children:[M&&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:M})]}),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})]}),l?.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(l.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(ba,{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"&&u?.cloudflaredAvailable===!0&&e.jsxs("div",{className:"remote-cli-detection remote-cli-detection--available",role:"status",children:[e.jsx(ed,{"aria-hidden":"true"}),e.jsx("span",{children:n("settings.remote.cloudflaredIsInstalled","cloudflared is installed")})]}),X==="cloudflare"&&u?.cloudflaredAvailable===!1&&e.jsxs("div",{className:"remote-cli-detection remote-cli-detection--missing",role:"status",children:[e.jsx(td,{"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:p||h!==null,onClick:()=>void f(),children:p?n("settings.remote.installing","Installing…"):n("settings.remote.installCloudflared","Install cloudflared")}),m&&e.jsx("small",{className:"remote-cli-install-error",children:m}),e.jsxs("small",{className:"remote-cli-manual",children:[n("settings.remote.manualInstall","Manual install: "),e.jsx("code",{children:x()})]}),w()?e.jsxs("small",{className:"remote-cli-manual",children:[n("settings.remote.ifHomebrewIsUnavailable","If Homebrew is unavailable: "),e.jsx("code",{children:w()})]}):null]})]}),X==="tailscale"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"form-group remote-provider-settings",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.jsx(ae,{descriptor:{key:"remoteTailscaleAcceptRoutes",label:n("settings.remote.acceptRoutes"," Accept routes "),help:n("settings.remote.acceptRoutesHint","Default: disabled."),scope:"global"},value:!!V.remoteTailscaleAcceptRoutes,onChange:v=>s(M=>({...M,remoteTailscaleAcceptRoutes:v===!0}))})]}),X==="cloudflare"&&e.jsxs("div",{className:"form-group remote-provider-settings",children:[e.jsx("small",{children:V.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:!(V.remoteCloudflareQuickTunnel??!0),onToggle:v=>{const M=v.currentTarget.open;s(se=>{const ne=!!(se.remoteCloudflareQuickTunnel??!0),pe=!M;return ne===pe?se:{...se,remoteCloudflareQuickTunnel:pe}})},children:[e.jsx("summary",{children:n("settings.remote.advancedNamedTunnel","Advanced (Named Tunnel)")}),V.remoteCloudflareQuickTunnel??!0?null:e.jsxs("div",{className:"remote-cf-advanced-fields",children:[e.jsx(be,{descriptor:{key:"remoteCloudflareTunnelName",label:n("settings.remote.tunnelName","Tunnel name"),placeholder:n("settings.remote.tunnelName","Tunnel name"),scope:"global"},value:String(V.remoteCloudflareTunnelName??""),onChange:v=>s(M=>({...M,remoteCloudflareTunnelName:v??""}))}),e.jsx(be,{descriptor:{key:"remoteCloudflareTunnelToken",label:n("settings.remote.tunnelToken","Tunnel token"),placeholder:n("settings.remote.tunnelToken","Tunnel token"),type:"password",scope:"global"},value:String(V.remoteCloudflareTunnelToken??""),onChange:v=>s(M=>({...M,remoteCloudflareTunnelToken:v??""}))}),e.jsx(be,{descriptor:{key:"remoteCloudflareIngressUrl",label:n("settings.remote.ingressURL","Ingress URL"),placeholder:n("settings.remote.httpsYourDomainExample","https://your-domain.example"),scope:"global"},value:String(V.remoteCloudflareIngressUrl??""),onChange:v=>s(M=>({...M,remoteCloudflareIngressUrl:v??""}))})]})]})]}),e.jsx("div",{className:"form-group remote-tunnel-actions",children:k==="running"||k==="starting"?e.jsx("button",{type:"button",className:"btn btn-danger",disabled:h!==null,onClick:()=>void E("stop",async()=>{await vp(o),d(n("settings.remote.tunnelStopped","Remote tunnel stopped"),"success")}),children:h==="stop"?n("settings.remote.stopping","Stopping…"):n("settings.remote.stopTunnel","Stop Tunnel")}):e.jsxs(e.Fragment,{children:[c?e.jsxs("div",{className:"remote-external-tunnel-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:!X||h!==null,onClick:()=>void E("start fresh",async()=>{X&&(await xn(B(X),o),await kp(o),await wn(o),d(n("settings.remote.tunnelRestarted","Remote tunnel restarted"),"success"))}),children:h==="start fresh"?n("settings.remote.restarting","Restarting…"):n("settings.remote.startFresh","Start Fresh")}),e.jsx("button",{type:"button",className:"btn btn-primary",disabled:!X||h!==null,onClick:()=>void E("use existing",async()=>{X&&(await xn(B(X),o),await wn(o),d(n("settings.remote.tunnelStarted","Remote tunnel started"),"success"))}),children:h==="use existing"?n("settings.remote.starting","Starting…"):n("settings.remote.useExisting","Use Existing")})]}):e.jsx("button",{type:"button",className:"btn btn-primary",disabled:!X||h!==null,onClick:()=>void E("start",async()=>{X&&(await xn(B(X),o),await wn(o),d(n("settings.remote.tunnelStarted","Remote tunnel started"),"success"))}),children:h==="start"?n("settings.remote.starting","Starting…"):n("settings.remote.startTunnel","Start Tunnel")}),X==="cloudflare"&&u?.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.jsx(ae,{descriptor:{key:"remoteShortLivedEnabled",label:n("settings.remote.enableShortLivedTokens"," Enable short-lived tokens "),help:n("settings.remote.shortLivedEnabledHint","Default: disabled."),scope:"global"},value:!!V.remoteShortLivedEnabled,onChange:v=>s(M=>({...M,remoteShortLivedEnabled:v===!0}))}),e.jsx(Pe,{descriptor:{key:"remoteShortLivedTtlMs",label:n("settings.remote.shortLivedTTLMs","Short-lived TTL (ms)"),help:n("settings.remote.shortLivedTtlMsHint","Default: 900000 (15 minutes)."),scope:"global",min:6e4,max:864e5},value:Number(V.remoteShortLivedTtlMs??9e5),onChange:v=>s(M=>({...M,remoteShortLivedTtlMs:v===null?9e5:v}))}),N&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{children:[n("settings.remote.lastShortLivedTokenExpiresAt","Last short-lived token expires at "),new Date(N.expiresAt).toLocaleString()," (",N.ttlMs,n("settings.remote.ms","ms)")]})}),e.jsx(ae,{descriptor:{key:"remoteRememberLastRunning",label:n("settings.remote.rememberLastRunningState"," Remember last running state "),help:n("settings.remote.automaticallyRestoreTunnelOnStartupIfItWas","Automatically restore tunnel on startup if it was running when last stopped. Default: disabled."),scope:"global"},value:!!V.remoteRememberLastRunning,onChange:v=>s(M=>({...M,remoteRememberLastRunning:v===!0}))}),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:h!==null,onClick:()=>void E("regenerate persistent token",async()=>{await xp(o),d(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:h!==null,onClick:()=>void E("generate short-lived token",async()=>{const v=Number(V.remoteShortLivedTtlMs??9e5),M=await jp(v,o);S(M),d(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:h!==null,onClick:()=>void E("fetch remote url",async()=>{const v=Number(V.remoteShortLivedTtlMs??9e5),M=await pi({projectId:o,tokenType:L,ttlMs:L==="short-lived"?v:void 0});R(M),b(null)}),children:n("settings.remote.showURL","Show URL")}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:h!==null,onClick:()=>void E("generate QR",async()=>{const v=Number(V.remoteShortLivedTtlMs??9e5),M=await Wn("image/svg",{projectId:o,tokenType:L,ttlMs:L==="short-lived"?v:void 0});R({url:M.url,expiresAt:M.expiresAt,tokenType:M.tokenType}),b(M.data??null)}),children:n("settings.remote.generateQR","Generate QR")})]}),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"remoteAuthLinkTokenType",children:n("settings.remote.authLinkTokenType","Auth link token type")}),e.jsxs(G,{settingKey:"remoteAuthLinkTokenType",children:[n("settings.remote.uRLAndQRGenerationUseTheSelectedToken"," URL and QR generation use the selected token type. "),L==="short-lived"?` TTL: ${Number(V.remoteShortLivedTtlMs??9e5)}ms.`:""]})]}),e.jsxs("select",{id:"remoteAuthLinkTokenType",value:L,onChange:v=>F(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")})]}),K?.url&&e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:[n("settings.remote.authenticatedURL","Authenticated URL:"),e.jsx("code",{className:"settings-url-output",children:K.url})]}),e.jsxs("small",{children:[n("settings.remote.tokenType"," Token type: "),e.jsx("strong",{children:K.tokenType}),K.expiresAt?n("settings.remote.expiresAt"," · Expires at {{expiresAt}}",{expiresAt:new Date(K.expiresAt).toLocaleString()}):n("settings.remote.noExpiry"," · No expiry")]})]}),T&&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(T)}`,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:T})]})]})]})]})]})}function zp(){return{name:mt,transport:"stdio",command:"",args:[]}}const qp={enabled:!1,servers:[]},_t=14,Vp=16;let Lr=0;function Jn(){return Lr+=1,`mcp-sensitive-${Lr}`}function Or(t){return{enabled:t?.enabled===!0,servers:Array.isArray(t?.servers)?t.servers:[]}}function Kr(t){return Object.entries(t??{}).map(([s,a])=>{const n=is(a)?a:{secretRef:"",scope:"project"};return{id:Jn(),key:s,secretRef:n.secretRef,scope:n.scope,createKey:s,createValue:"",required:!1}})}function ma(t){return t?{originalName:t.name,name:t.name,enabled:t.enabled!==!1,transport:t.transport,command:t.transport==="stdio"?t.command:"",argsText:t.transport==="stdio"?(t.args??[]).join(" "):"",url:t.transport==="stdio"?"":t.url,env:t.transport==="stdio"?Kr(t.env):[],headers:t.transport==="stdio"?[]:Kr(t.headers)}:{name:"",enabled:!0,transport:"stdio",command:"",argsText:"",url:"",env:[],headers:[]}}function Yp(t,s){const a=ma(t),n=o=>s.filter(d=>d.field===o||o==="headers"&&d.field==="token").map(d=>({id:Jn(),key:d.key,secretRef:"",scope:d.scope,createKey:d.suggestedKey,createValue:"",required:!0}));return t.transport==="stdio"?{...a,env:n("env")}:{...a,headers:n("headers")}}function ra(t){const s={};for(const a of t){const n=a.key.trim();!n||!a.secretRef.trim()||(s[n]={secretRef:a.secretRef.trim(),scope:a.scope})}return Object.keys(s).length>0?s:void 0}function Qp(t){const s={name:t.name.trim(),...t.enabled?{}:{enabled:!1}};if(t.transport==="stdio"){const a=t.argsText.split(/\s+/u).map(n=>n.trim()).filter(Boolean);return{...s,transport:"stdio",command:t.command.trim(),...a.length>0?{args:a}:{},...ra(t.env)?{env:ra(t.env)}:{}}}return{...s,transport:t.transport,url:t.url.trim(),...ra(t.headers)?{headers:ra(t.headers)}:{}}}function Cs(t,s){return fetch(t,{...s,headers:{"Content-Type":"application/json",...s?.headers??{}}}).then(async a=>{if(!a.ok){const n=await a.json().catch(()=>({error:"Request failed"}));throw new Error(String(n?.error??"Request failed"))}return a.json()})}function Br(t){return t.transport==="stdio"?`${t.command}${t.args?.length?` ${t.args.join(" ")}`:""}`:t.url}function Jp(t){return t==="valid"?"status-dot status-dot--online":t==="pending"?"status-dot status-dot--pending":t==="unreachable"||t==="error"?"status-dot status-dot--error":"status-dot"}function Xp(t){return t==="disabled-global"?"disabled global":t==="project-local"?"project local":t==="plugin-overridden"?"plugin overridden":t==="plugin-disabled"?"plugin disabled":t==="builtin"?"built-in":t==="builtin-disabled"?"built-in disabled":t==="builtin-unavailable"?"built-in unavailable":t}function Gr(t){return t==="idle"?"Not tested":t==="pending"?"Testing…":t}function bi({scope:t,form:s,setForm:a,globalSettings:n,projectId:o,pluginServers:d=[],builtInAvailable:u=!0,addToast:c}){const{t:l}=le("app"),h=i.useRef(null),p=Or(s.mcpServers??qp),m=Or(n?.mcpServers),x=p.servers??[],w=m.servers??[],[f,E]=i.useState(null),[N,S]=i.useState(null),[L,F]=i.useState([]),[K,R]=i.useState(),[T,b]=i.useState(null),[V,X]=i.useState(""),[k,I]=i.useState(null),[B,v]=i.useState(""),[M,se]=i.useState({}),[ne,pe]=i.useState(null),[j,W]=i.useState(!1),[ce,Ie]=i.useState(null),Oe=i.useRef(0),H=i.useRef(o);H.current!==o&&(H.current=o,Oe.current+=1);const Z=i.useCallback(async()=>{const A=o;if(H.current!==A)return;const z=++Oe.current;try{const Y=await Cs($e("/api/secrets",A));Oe.current===z&&H.current===A&&(F(Y.secrets),R(A),b(null))}catch(Y){Oe.current===z&&H.current===A&&b(Y instanceof Error?Y.message:String(Y))}},[o]);i.useEffect(()=>{F([]),R(void 0),b(null),E(null),S(null),Z()},[Z]);const Te=i.useCallback(async()=>{W(!0),Ie(null);try{const A=new URLSearchParams({scope:t});o&&A.set("projectId",o),pe(await Cs(`/api/mcp/discovered?${A.toString()}`))}catch(A){Ie(A instanceof Error?A.message:String(A)),pe({sources:[],servers:[],errors:[]})}finally{W(!1)}},[o,t]);i.useEffect(()=>{Te()},[Te]);const _e=i.useMemo(()=>t==="project"?ep({mcpServers:m},{mcpServers:s.mcpServers},d):x.filter(A=>A.enabled!==!1),[x,s.mcpServers,m,d,t]),Ke=i.useMemo(()=>new Map(d.filter(A=>A.server.enabledByDefault!==!1).map(A=>({...A,definition:di(A.server)})).filter(A=>!!A.definition).map(A=>[A.definition.name,A])),[d]),D=i.useMemo(()=>new Map(w.map(A=>[A.name,A])),[w]),U=i.useMemo(()=>new Map(x.map(A=>[A.name,A])),[x]),te=i.useMemo(()=>new Set(x.map(A=>A.name)),[x]),ke=i.useMemo(()=>{const A=new Map;for(const z of ne?.servers??[]){const Y=A.get(z.source.label)??[];Y.push(z),A.set(z.source.label,Y)}return[...A.entries()]},[ne?.servers]),Ne=i.useMemo(()=>{const A=zp(),z=u?"builtin":"builtin-unavailable";if(t==="global"){const oe=x.map(Ge=>({server:Ge,state:Ge.enabled===!1?"disabled":"configured"})),Fe=x.find(Ge=>Ge.name===mt);return p.enabled&&(!Fe||!Fe.transport)&&oe.unshift({server:A,state:Fe?.enabled===!1?"builtin-disabled":z}),oe}const Y=new Set(_e.map(oe=>oe.name)),de=[],ue=new Map;for(const oe of w)oe.name===mt&&!oe.transport||ue.set(oe.name,{server:oe,plugin:!1});for(const[oe,Fe]of Ke)ue.set(oe,{server:Fe.definition,plugin:!0});for(const[oe,Fe]of ue){const Ge=U.get(oe);Ge?.enabled===!1?de.push({server:Ge,state:Fe.plugin?"plugin-disabled":"disabled-global"}):Ge?de.push({server:Ge,state:Fe.plugin?"plugin-overridden":Y.has(oe)?"overridden":"disabled"}):de.push({server:Fe.server,state:Fe.plugin?Y.has(oe)?"plugin":"plugin-disabled":Y.has(oe)?"inherited":"disabled"})}for(const oe of x)oe.name===mt&&!oe.transport||ue.has(oe.name)||de.push({server:oe,state:oe.enabled===!1||!Y.has(oe.name)?"disabled":"project-local"});const me=D.get(mt),Se=U.get(mt);if(p.enabled&&!me?.transport&&!Se?.transport){const oe=me?.enabled===!1&&Se?.enabled!==!0;de.unshift({server:A,state:Se?.enabled===!1||oe?"builtin-disabled":z})}return de},[u,x,_e,D,w,Ke,U,t,p.enabled]),re=A=>{a(z=>({...z,mcpServers:A}))},$=A=>re({...p,enabled:A}),he=A=>{const z=t==="project"&&D.get(mt)?.enabled===!1;re(bp(p,{scope:t,intent:A?"enable":"disable",lowerScopeTombstoned:z}))},xe=()=>{if(!f)return;if(S(null),[...f.env,...f.headers].filter(Se=>Se.required&&(!Se.key.trim()||!Se.secretRef.trim())).length>0){S(l("settings.mcp.discoverySecretsRequired","Bind or create Fusion secret references before saving this discovered server."));return}const z=Qn(Qp(f));if(!z.value){S(z.errors.map(Se=>Se.message).join("; "));return}const Y=x.filter(Se=>Se.name!==(f.originalName??z.value.name));if(Y.some(Se=>Se.name===z.value.name)){S(l("settings.mcp.duplicateName","Duplicate MCP server name"));return}const ue=[...Y,z.value],me=Zu(ue);if(!me.value){S(me.errors.map(Se=>Se.message).join("; "));return}re({...p,enabled:!0,servers:me.value}),E(null)},je=A=>{re({...p,servers:x.filter(z=>z.name!==A)}),se(z=>{const Y={...z};return delete Y[A],Y})},Me=A=>{if(te.has(A.definition.name))return;if(A.secretDescriptors.length>0||A.hasPlaintextSecrets){E(Yp(A.definition,A.secretDescriptors)),S(l("settings.mcp.discoverySecretsRequired","Bind or create Fusion secret references before saving this discovered server."));return}const z=[...x.filter(Y=>Y.name!==A.definition.name),A.definition];re({...p,enabled:!0,servers:z}),c(l("settings.mcp.discoveredAdded","Discovered MCP server added"),"success")},P=A=>{const z=Ke.get(A)?.definition??D.get(A),Y=z?.transport==="sse"||z?.transport==="streamable-http"?{name:A,enabled:!1,transport:z.transport,url:z.url}:{name:A,enabled:!1,transport:"stdio",command:z?.transport==="stdio"?z.command:"disabled"};re({...p,enabled:!0,servers:[...x.filter(de=>de.name!==A),Y]})},Ce=async(A,z)=>{if(!f)return;const Y=o,de=A.createKey.trim()||A.key.trim();if(!de||!A.createValue){S(l("settings.mcp.secretCreateRequired","Secret key and value are required."));return}try{const ue=await Cs($e("/api/secrets",Y),{method:"POST",body:JSON.stringify({scope:A.scope,key:de,value:A.createValue,description:`MCP ${f.name||"server"} ${z} ${A.key}`,accessPolicy:"prompt",envExportable:!1,envExportKey:null})});if(H.current!==Y)return;E(me=>me&&{...me,[z]:me[z].map(Se=>Se.id===A.id?{...Se,secretRef:ue.id,scope:ue.scope,createKey:ue.key,createValue:""}:Se)}),await Z(),H.current===Y&&c(l("settings.mcp.secretCreated","Secret created"),"success")}catch(ue){H.current===Y&&S(ue instanceof Error?ue.message:String(ue))}},Re=async A=>{se(z=>({...z,[A.name]:{status:"pending",message:l("settings.mcp.testing","Testing…")}}));try{const z=await Cs("/api/mcp/validate",{method:"POST",body:JSON.stringify({server:A})});se(Y=>({...Y,[A.name]:{status:z.status,message:z.message??Gr(z.status)}}))}catch(z){se(Y=>({...Y,[A.name]:{status:"error",message:z instanceof Error?z.message:String(z)}}))}},ve=async A=>{I(null);const z=ap(A,{scope:t});if(z.errors.length>0){I(z.errors.join("; "));return}const Y=new Set(x.map(me=>me.name)),de=z.definitions.find(me=>Y.has(me.name));if(de){I(l("settings.mcp.importDuplicate","Duplicate MCP server name: {{name}}",{name:de.name}));return}const ue=o;try{const me=new Map;for(const oe of z.secretsToCreate){if(H.current!==ue)return;const Fe=await Cs($e("/api/secrets",ue),{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})});me.set(oe.suggestedKey,{secretRef:Fe.id,scope:Fe.scope})}if(H.current!==ue)return;const Se=z.definitions.map(oe=>{if(oe.transport==="stdio"){const Ge=Object.fromEntries(Object.entries(oe.env??{}).map(([Ye,ee])=>[Ye,is(ee)&&me.has(ee.secretRef)?me.get(ee.secretRef):ee]));return{...oe,...Object.keys(Ge).length>0?{env:Ge}:{}}}const Fe=Object.fromEntries(Object.entries(oe.headers??{}).map(([Ge,Ye])=>[Ge,is(Ye)&&me.has(Ye.secretRef)?me.get(Ye.secretRef):Ye]));return{...oe,...Object.keys(Fe).length>0?{headers:Fe}:{}}});re({...p,enabled:!0,servers:[...x,...Se]}),X(""),await Z(),H.current===ue&&c(l("settings.mcp.imported","MCP servers imported"),"success")}catch(me){H.current===ue&&I(me instanceof Error?me.message:String(me))}},we=async()=>{const A=JSON.stringify(np(x),null,2);v(A);try{await navigator.clipboard?.writeText(A),c(l("settings.mcp.exportCopied","MCP JSON copied"),"success")}catch{c(l("settings.mcp.exportReady","MCP JSON ready to copy"),"info")}},ie=K===o?L:[],Ee=(A,z)=>e.jsxs("div",{className:"mcp-sensitive-list","data-testid":`mcp-${A}-rows`,children:[e.jsx("div",{className:"mcp-subheading",children:A==="env"?l("settings.mcp.env","Environment secret refs"):l("settings.mcp.headers","Header secret refs")}),z.length===0?e.jsx("p",{className:"mcp-empty-inline",children:l("settings.mcp.noSensitiveRows","No secret references configured.")}):null,z.map(Y=>e.jsxs("div",{className:"mcp-sensitive-row",children:[e.jsx("input",{className:"input","aria-label":l("settings.mcp.sensitiveKey","Sensitive field name"),value:Y.key,onChange:de=>E(ue=>ue&&{...ue,[A]:ue[A].map(me=>me.id===Y.id?{...me,key:de.target.value}:me)}),placeholder:A==="env"?"API_KEY":"Authorization",readOnly:Y.required}),Y.required?e.jsx("span",{className:"mcp-state-badge mcp-state-badge--required",children:l("settings.mcp.requiredSecret","Required")}):null,e.jsxs("select",{className:"select","aria-label":l("settings.mcp.secretReference","Secret reference"),value:`${Y.scope}:${Y.secretRef}`,onChange:de=>{const[ue,me]=de.target.value.split(":");E(Se=>Se&&{...Se,[A]:Se[A].map(oe=>oe.id===Y.id?{...oe,scope:ue,secretRef:me}:oe)})},children:[e.jsx("option",{value:`${Y.scope}:`,children:l("settings.mcp.chooseSecret","Choose a secret…")}),ie.map(de=>e.jsxs("option",{value:`${de.scope}:${de.id}`,children:[de.scope,": ",de.key]},`${de.scope}:${de.id}`))]}),e.jsx("input",{className:"input","aria-label":l("settings.mcp.newSecretKey","New secret key"),value:Y.createKey,onChange:de=>E(ue=>ue&&{...ue,[A]:ue[A].map(me=>me.id===Y.id?{...me,createKey:de.target.value}:me)}),placeholder:l("settings.mcp.newSecretKey","New secret key")}),e.jsx("input",{className:"input",type:"password","aria-label":l("settings.mcp.newSecretValue","New secret value (not stored in settings)"),value:Y.createValue,onChange:de=>E(ue=>ue&&{...ue,[A]:ue[A].map(me=>me.id===Y.id?{...me,createValue:de.target.value}:me)}),placeholder:l("settings.mcp.createSecretPlaceholder","Create secret value")}),e.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void Ce(Y,A),children:l("settings.mcp.createSecret","Create secret")}),Y.required?null:e.jsx("button",{type:"button",className:"btn btn-icon touch-target","aria-label":l("settings.mcp.removeSensitive","Remove secret reference"),onClick:()=>E(de=>de&&{...de,[A]:de[A].filter(ue=>ue.id!==Y.id)}),children:e.jsx(va,{"aria-hidden":"true"})})]},Y.id)),e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>E(Y=>Y&&{...Y,[A]:[...Y[A],{id:Jn(),key:"",secretRef:"",scope:t,createKey:"",createValue:"",required:!1}]}),children:[e.jsx(fa,{"aria-hidden":"true",size:_t})," ",l("settings.mcp.addSecretRef","Add secret reference")]}),T?e.jsx("p",{className:"form-error",children:T}):null]});return e.jsxs("section",{className:"card mcp-servers-card","data-testid":`mcp-servers-card-${t}`,children:[e.jsxs("div",{className:"mcp-servers-card__header",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"mcp-servers-card__title",children:t==="global"?l("settings.mcp.globalTitle","Global MCP servers"):l("settings.mcp.projectTitle","Project MCP servers")}),e.jsx("p",{className:"mcp-servers-card__description",children:t==="global"?l("settings.mcp.globalDescription","Configure MCP servers shared by all projects. Project settings may override or disable these servers by name."):l("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:()=>{E(ma()),S(null)},children:[e.jsx(fa,{"aria-hidden":"true",size:Vp})," ",l("settings.mcp.addServer","Add server")]})]}),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{className:"checkbox-label mcp-enabled-toggle",children:[e.jsx("input",{type:"checkbox",checked:p.enabled===!0,onChange:A=>$(A.target.checked)}),l("settings.mcp.enabled","Enable MCP servers for this scope")]}),e.jsx(G,{settingKey:`mcp-enabled-${t}`,children:l("settings.mcp.enabledHint","Default: disabled, with no servers configured.")})]}),e.jsxs("div",{className:"mcp-discovery card","data-testid":`mcp-discovery-${t}`,children:[e.jsxs("div",{className:"mcp-discovery__header",children:[e.jsxs("div",{children:[e.jsx("h6",{children:l("settings.mcp.discoveryTitle","Discovered on this machine")}),e.jsx("p",{children:l("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 Te(),disabled:j,children:[e.jsx(Ts,{"aria-hidden":"true",size:_t})," ",j?l("settings.mcp.scanning","Scanning…"):l("settings.mcp.scanAgain","Scan again")]})]}),ce?e.jsx("p",{className:"form-error",children:ce}):null,(ne?.errors?.length??0)>0?e.jsx("div",{className:"mcp-discovery__notes",role:"note",children:ne?.errors?.map(A=>e.jsx("p",{children:A},A))}):null,!j&&ke.length===0?e.jsx("p",{className:"mcp-empty","data-testid":`mcp-discovery-empty-${t}`,children:l("settings.mcp.discoveryEmpty","No MCP servers found in supported tool configs yet.")}):null,ke.map(([A,z])=>e.jsxs("div",{className:"mcp-discovery__group",children:[e.jsx("div",{className:"mcp-subheading",children:A}),z.map(Y=>{const de=Y.alreadyConfigured||te.has(Y.definition.name);return e.jsxs("article",{className:"mcp-discovery-row","data-testid":`mcp-discovery-row-${t}-${Y.source.id}-${Y.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:Y.definition.name}),e.jsx("span",{className:"mcp-transport-badge",children:Y.definition.transport}),de?e.jsx("span",{className:"mcp-state-badge mcp-state-badge--configured",children:l("settings.mcp.configuredBadge","Configured")}):null]}),e.jsx("p",{children:Br(Y.definition)}),Y.secretDescriptors.length>0?e.jsx("p",{className:"mcp-discovery-row__note",children:l("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:()=>Me(Y),disabled:de,children:de?l("settings.mcp.configured","Configured"):l("settings.mcp.addDiscovered","Add")})})]},`${Y.source.id}:${Y.definition.name}`)})]},A))]}),Ne.length===0?e.jsx("p",{className:"mcp-empty","data-testid":`mcp-empty-${t}`,children:l("settings.mcp.empty","No MCP servers configured.")}):e.jsx("div",{className:"mcp-server-list",children:Ne.map(({server:A,state:z})=>{const Y=M[A.name]??{status:"idle"},de=t==="global"||z!=="inherited",ue=z==="builtin"||z==="builtin-disabled"||z==="builtin-unavailable";return e.jsxs("article",{className:"mcp-server-row","data-testid":`mcp-server-row-${A.name}`,children:[e.jsxs("div",{className:"mcp-server-row__main",children:[e.jsxs("div",{className:"mcp-server-row__titleline",children:[e.jsx("strong",{children:ue?hp:A.name}),e.jsx("span",{className:`mcp-state-badge mcp-state-badge--${z}`,"data-state":z,children:Xp(z)}),t==="project"&&Ke.has(A.name)?e.jsx("span",{className:"mcp-state-badge","data-testid":`mcp-plugin-provenance-${A.name}`,children:`plugin:${Ke.get(A.name).pluginId}`}):null,e.jsx("span",{className:"mcp-transport-badge",children:A.transport})]}),ue?e.jsx("p",{children:z==="builtin-unavailable"?l("settings.mcp.builtinUnavailable","Built-in entry is unavailable in this installation."):mp}):e.jsx("p",{children:Br(A)}),e.jsxs("p",{className:`mcp-validation-status mcp-validation-status--${Y.status}`,"data-testid":`mcp-validation-${A.name}`,"aria-live":"polite",children:[e.jsx("span",{className:Jp(Y.status),"aria-hidden":"true"})," ",e.jsx("span",{className:"mcp-validation-status__badge",children:Y.status==="idle"?l("settings.mcp.notTested","Not tested"):Gr(Y.status)}),Y.message?e.jsx("span",{children:Y.message}):null]})]}),e.jsxs("div",{className:"mcp-server-row__actions",children:[ue?e.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>he(z==="builtin-disabled"),disabled:z==="builtin-unavailable",children:z==="builtin-disabled"?l("settings.mcp.enableBuiltin","Enable"):l("settings.mcp.disableBuiltin","Disable")}):e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void Re(A),disabled:Y.status==="pending",children:[e.jsx(sd,{"aria-hidden":"true",size:_t})," ",Y.status==="pending"?l("settings.mcp.testing","Testing…"):l("settings.mcp.test","Test")]}),z==="inherited"||z==="plugin"?e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>{E(ma(A)),S(null)},children:[e.jsx(ya,{"aria-hidden":"true",size:_t})," ",l("settings.mcp.override","Override")]}):null,z==="inherited"||z==="plugin"?e.jsx("button",{type:"button",className:"btn btn-warning btn-sm touch-target",onClick:()=>P(A.name),children:l("settings.mcp.disableInherited","Disable")}):null,de&&!ue?e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>{E(ma(A)),S(null)},children:[e.jsx(ya,{"aria-hidden":"true",size:_t})," ",l("actions.edit","Edit")]}):null,de&&!ue?e.jsx("button",{type:"button",className:"btn btn-icon touch-target","aria-label":l("settings.mcp.removeServer","Remove {{name}}",{name:A.name}),onClick:()=>je(A.name),children:e.jsx(va,{"aria-hidden":"true"})}):null]})]},A.name)})}),f?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:l("settings.mcp.name","Name")}),e.jsx("input",{className:"input",value:f.name,onChange:A=>E({...f,name:A.target.value})})]}),e.jsxs("label",{className:"form-group",children:[e.jsx("span",{children:l("settings.mcp.transport","Transport")}),e.jsxs("select",{className:"select",value:f.transport,onChange:A=>E({...f,transport:A.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:f.enabled,onChange:A=>E({...f,enabled:A.target.checked})})," ",l("settings.mcp.serverEnabled","Server enabled")]}),f.transport==="stdio"?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"form-group",children:[e.jsx("span",{children:l("settings.mcp.command","Command")}),e.jsx("input",{className:"input",value:f.command,onChange:A=>E({...f,command:A.target.value})})]}),e.jsxs("label",{className:"form-group",children:[e.jsx("span",{children:l("settings.mcp.args","Arguments")}),e.jsx("input",{className:"input",value:f.argsText,onChange:A=>E({...f,argsText:A.target.value})})]})]}):e.jsxs("label",{className:"form-group mcp-editor-grid__wide",children:[e.jsx("span",{children:l("settings.mcp.url","URL")}),e.jsx("input",{className:"input",value:f.url,onChange:A=>E({...f,url:A.target.value})})]})]}),f.transport==="stdio"?Ee("env",f.env):Ee("headers",f.headers),N?e.jsx("p",{className:"form-error",children:N}):null,e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>{E(null),S(null)},children:l("actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:xe,children:l("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:l("settings.mcp.import","Import")}),e.jsx("textarea",{className:"input mcp-json-textarea",value:V,onChange:A=>X(A.target.value),placeholder:l("settings.mcp.importPlaceholder","Paste Claude Desktop mcpServers JSON")}),e.jsx("input",{ref:h,className:"visually-hidden",type:"file",accept:"application/json,.json",onChange:A=>{const z=A.target.files?.[0];z&&(z.text().then(X),A.target.value="")}}),e.jsxs("div",{className:"mcp-inline-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>h.current?.click(),children:[e.jsx($u,{"aria-hidden":"true",size:_t})," ",l("settings.mcp.uploadJson","Upload JSON")]}),e.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void ve(V),children:l("settings.mcp.import","Import")})]}),k?e.jsx("p",{className:"form-error",children:k}):null]}),e.jsxs("div",{className:"mcp-import-export__pane",children:[e.jsx("h6",{children:l("settings.mcp.export","Export")}),e.jsxs("button",{type:"button",className:"btn btn-sm touch-target",onClick:()=>void we(),children:[e.jsx(ad,{"aria-hidden":"true",size:_t})," ",l("settings.mcp.copyExport","Copy Fusion MCP JSON")]}),B?e.jsx("a",{className:"btn btn-sm touch-target",download:"fusion-mcp-servers.json",href:`data:application/json;charset=utf-8,${encodeURIComponent(B)}`,children:l("settings.mcp.downloadExport","Download JSON")}):null,B?e.jsx("textarea",{className:"input mcp-json-textarea",readOnly:!0,value:B,"aria-label":l("settings.mcp.exportedJson","Exported MCP JSON")}):null]})]}),t==="project"?e.jsx("p",{className:"mcp-effective-count",children:l("settings.mcp.effectiveCount","Effective enabled servers: {{count}}",{count:_e.length})}):null]})}function Zp({form:t,setForm:s,projectId:a,addToast:n}){const{t:o}=le("app"),[d,u]=i.useState(!1);return i.useEffect(()=>{const c=new AbortController,l=a?`?projectId=${encodeURIComponent(a)}`:"";return fetch(`/api/mcp/plugin-servers${l}`,{signal:c.signal}).then(async h=>h.ok?h.json():null).then(h=>{c.signal.aborted||u(h?.fusionMemoryMcpAvailable===!0)}).catch(()=>{c.signal.aborted||u(!1)}),()=>c.abort()},[a]),e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:o("settings.nav.globalMcp","MCP Servers")}),e.jsx(bi,{scope:"global",form:t,setForm:s,projectId:a,builtInAvailable:d,addToast:n})]})}function eg(t,s){return{key:t,...s}}function tg(t){return t.trim().toLowerCase()}function Mt(t){const s=Number(t);return Number.isFinite(s)?s:0}function sg(t){return t?`/command-center/pricing/fetch?projectId=${encodeURIComponent(t)}`:"/command-center/pricing/fetch"}function Pn(t,s){t(a=>({...a,modelPricingOverrides:s}))}function ag({form:t,setForm:s,addToast:a,projectId:n}){const{t:o}=le("app"),[d,u]=i.useState({key:"",inputPer1M:0,outputPer1M:0,cacheReadPer1M:0,cacheWritePer1M:0,source:"manual"}),[c,l]=i.useState(!1),[h,p]=i.useState(!1),m=i.useMemo(()=>Object.entries(t.modelPricingOverrides??{}).sort(([R],[T])=>R.localeCompare(T)),[t.modelPricingOverrides]),x=i.useCallback(()=>p(!1),[]);i.useEffect(()=>{if(!h)return;const R=T=>{T.key==="Escape"&&(T.preventDefault(),x())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[x,h]);const w=i.useCallback(R=>{R.target===R.currentTarget&&x()},[x]),f=(R,T)=>{const b=t.modelPricingOverrides??{},V=b[R];V&&Pn(s,{...b,[R]:{...V,...T}})},E=R=>{const T={...t.modelPricingOverrides??{}};delete T[R],Pn(s,T)},N=()=>{const R=tg(d.key);if(!R||!R.includes(":")){a(o("settings.modelPricing.invalidKey","Use a provider:model key before adding a pricing row."),"error");return}Pn(s,{...t.modelPricingOverrides??{},[R]:{inputPer1M:d.inputPer1M,outputPer1M:d.outputPer1M,cacheReadPer1M:d.cacheReadPer1M,cacheWritePer1M:d.cacheWritePer1M,source:d.source||"manual"}}),u({key:"",inputPer1M:0,outputPer1M:0,cacheReadPer1M:0,cacheWritePer1M:0,source:"manual"})},S=async()=>{l(!0);try{const R=await Ue(sg(n),{method:"POST"}),T=await Ue("/settings/global");s(b=>({...b,modelPricingOverrides:T.modelPricingOverrides??b.modelPricingOverrides,modelPricingFetchedAt:T.modelPricingFetchedAt??R.fetchedAt,modelPricingSource:T.modelPricingSource??R.source})),a(o("settings.modelPricing.fetchSuccess","Fetched {{count}} model prices.",{count:R.count}),"success")}catch(R){a(R instanceof Error?R.message:o("settings.modelPricing.fetchFailed","Failed to fetch latest model prices."),"error")}finally{l(!1)}},L=o("settings.modelPricing.empty","No model pricing overrides yet. Add one manually or fetch the latest LiteLLM prices."),F=o("settings.modelPricing.overrideCount",m.length===1?"{{count}} pricing override":"{{count}} pricing overrides",{count:m.length}),K=()=>h?e.jsx("div",{className:"modal-overlay open",onClick:w,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:o("settings.modelPricing.tableTitle","Model pricing table")}),e.jsx("p",{className:"settings-muted model-pricing-modal__subtitle",children:o("settings.modelPricing.saveHint","Manual edits are saved with the rest of Global settings.")})]}),e.jsx("button",{type:"button",className:"modal-close",onClick:x,"aria-label":o("actions.close","Close"),"data-testid":"model-pricing-close",children:e.jsx(li,{size:20})})]}),e.jsx("div",{className:"model-pricing-modal__body",children:e.jsxs("div",{className:"model-pricing-table",role:"table","aria-label":o("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:o("settings.modelPricing.modelKey","provider:model")}),e.jsx("span",{role:"columnheader",children:o("settings.modelPricing.input","Input / 1M")}),e.jsx("span",{role:"columnheader",children:o("settings.modelPricing.output","Output / 1M")}),e.jsx("span",{role:"columnheader",children:o("settings.modelPricing.cacheRead","Cache read / 1M")}),e.jsx("span",{role:"columnheader",children:o("settings.modelPricing.cacheWrite","Cache write / 1M")}),e.jsx("span",{role:"columnheader",children:o("settings.modelPricing.source","Source")}),e.jsx("span",{role:"columnheader",children:o("settings.modelPricing.actions","Actions")})]}),m.length===0?e.jsx("div",{className:"settings-empty-state model-pricing-empty",role:"row",children:L}):m.map(([R,T])=>{const b=eg(R,T);return e.jsxs("div",{className:"model-pricing-row",role:"row",children:[e.jsx("code",{className:"model-pricing-key",role:"cell",children:b.key}),e.jsx("input",{"aria-label":`${R} input per 1M`,className:"input",type:"number",step:"any",value:b.inputPer1M,onChange:V=>f(R,{inputPer1M:Mt(V.target.value)})}),e.jsx("input",{"aria-label":`${R} output per 1M`,className:"input",type:"number",step:"any",value:b.outputPer1M,onChange:V=>f(R,{outputPer1M:Mt(V.target.value)})}),e.jsx("input",{"aria-label":`${R} cache read per 1M`,className:"input",type:"number",step:"any",value:b.cacheReadPer1M,onChange:V=>f(R,{cacheReadPer1M:Mt(V.target.value)})}),e.jsx("input",{"aria-label":`${R} cache write per 1M`,className:"input",type:"number",step:"any",value:b.cacheWritePer1M,onChange:V=>f(R,{cacheWritePer1M:Mt(V.target.value)})}),e.jsx("input",{"aria-label":`${R} source`,className:"input",value:b.source,onChange:V=>f(R,{source:V.target.value})}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>E(R),children:o("settings.modelPricing.delete","Delete")})]},R)}),e.jsxs("div",{className:"model-pricing-row model-pricing-row--add",role:"row",children:[e.jsx("input",{"aria-label":o("settings.modelPricing.newKey","New provider:model key"),className:"input",placeholder:"openai:gpt-4o",value:d.key,onChange:R=>u(T=>({...T,key:R.target.value}))}),e.jsx("input",{"aria-label":o("settings.modelPricing.newInput","New input rate"),className:"input",type:"number",step:"any",value:d.inputPer1M,onChange:R=>u(T=>({...T,inputPer1M:Mt(R.target.value)}))}),e.jsx("input",{"aria-label":o("settings.modelPricing.newOutput","New output rate"),className:"input",type:"number",step:"any",value:d.outputPer1M,onChange:R=>u(T=>({...T,outputPer1M:Mt(R.target.value)}))}),e.jsx("input",{"aria-label":o("settings.modelPricing.newCacheRead","New cache read rate"),className:"input",type:"number",step:"any",value:d.cacheReadPer1M,onChange:R=>u(T=>({...T,cacheReadPer1M:Mt(R.target.value)}))}),e.jsx("input",{"aria-label":o("settings.modelPricing.newCacheWrite","New cache write rate"),className:"input",type:"number",step:"any",value:d.cacheWritePer1M,onChange:R=>u(T=>({...T,cacheWritePer1M:Mt(R.target.value)}))}),e.jsx("input",{"aria-label":o("settings.modelPricing.newSource","New source"),className:"input",value:d.source,onChange:R=>u(T=>({...T,source:R.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:N,children:o("settings.modelPricing.addRow","Add row")})]})]})})]})}):null;return e.jsxs("section",{className:"model-pricing-section","aria-label":o("settings.modelPricing.title","Model pricing overrides"),children:[e.jsxs("div",{className:"model-pricing-section__header",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:o("settings.modelPricing.title","Model Pricing")}),e.jsxs(G,{settingKey:"model-pricing-section",children:[o("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).")," ",o("settings.modelPricing.saveHint","Manual edits are saved with the rest of Global settings.")]})]}),e.jsxs("p",{className:"settings-muted model-pricing-section__meta",children:[t.modelPricingFetchedAt?o("settings.modelPricing.pricesAsOf","Prices as of {{date}}",{date:new Date(t.modelPricingFetchedAt).toLocaleString()}):o("settings.modelPricing.noFetchYet","No fetched pricing snapshot yet."),t.modelPricingSource?` · ${t.modelPricingSource}`:""]})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void S(),disabled:c,children:c?o("settings.modelPricing.fetching","Fetching…"):o("settings.modelPricing.fetchLatest","Fetch latest prices")})]}),e.jsxs("div",{className:"model-pricing-summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:F}),m.length===0?e.jsx("p",{className:"settings-muted model-pricing-summary__empty",children:L}):null]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>p(!0),children:o("settings.modelPricing.viewTable","View pricing table")})]}),K()]})}function Ss(t){return t?.join(", ")??""}function Ns(t){return t.split(",").map(s=>s.trim()).filter(s=>s.length>0)}const ng={execution:"executionGlobalCredentialInstanceId",planning:"planningGlobalCredentialInstanceId",validator:"validatorGlobalCredentialInstanceId",merger:"mergerGlobalCredentialInstanceId",summarization:"titleSummarizerGlobalCredentialInstanceId","import-translate":"importTranslateGlobalCredentialInstanceId"};function lg({form:t,setForm:s,availableModels:a,modelsLoading:n,globalModelLanes:o,getLaneThinkingValue:d,updateLaneThinkingValue:u,resetLaneThinkingValue:c,favoriteProviders:l,favoriteModels:h,onToggleFavorite:p,onToggleModelFavorite:m,addToast:x,projectId:w}){const{t:f}=le("app"),E=t.defaultProvider&&t.defaultModelId?`${t.defaultProvider}/${t.defaultModelId}`:"";return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:f("settings.globalModels.defaultModel","Default Model")}),n?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Et,{label:f("settings.models.loadingModels","Loading available models…")})}):a.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:f("settings.models.noModels","No models available. Configure authentication first.")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"defaultModel",children:f("settings.globalModels.defaultModel","Default Model")}),e.jsx(G,{settingKey:"defaultModel",children:f("settings.globalModels.defaultAIModelUsedForTaskExecutionWhen","Default AI model used for task execution when no per-task override is set. "Use default" lets the engine choose automatically. No default — unset.")})]}),e.jsx(lt,{id:"defaultModel",label:"Default Model",models:a,value:E,onChange:N=>{if(!N)s(S=>({...S,defaultProvider:void 0,defaultModelId:void 0,defaultCredentialInstanceId:void 0}));else{const S=N.indexOf("/");s(L=>({...L,defaultProvider:N.slice(0,S),defaultModelId:N.slice(S+1),defaultCredentialInstanceId:void 0}))}},credentialInstanceId:t.defaultCredentialInstanceId,onCredentialInstanceChange:N=>s(S=>({...S,defaultCredentialInstanceId:N||void 0})),placeholder:f("settings.globalModels.useDefault","Use default"),favoriteProviders:l,onToggleFavorite:p,favoriteModels:h,onToggleModelFavorite:m})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"fallbackModel",children:f("settings.globalModels.fallbackModel","Fallback Model")}),e.jsx(G,{settingKey:"fallbackModel",children:f("settings.globalModels.usedAutomaticallyIfThePrimaryDefaultModelHits","Used automatically if the primary default model hits a retryable provider error like rate limiting or overload. No default — unset.")})]}),e.jsx(lt,{id:"fallbackModel",label:"Fallback Model",models:a,value:t.fallbackProvider&&t.fallbackModelId?`${t.fallbackProvider}/${t.fallbackModelId}`:"",onChange:N=>{if(!N)s(S=>({...S,fallbackProvider:void 0,fallbackModelId:void 0,fallbackThinkingLevel:void 0,fallbackCredentialInstanceId:void 0}));else{const S=N.indexOf("/");s(L=>({...L,fallbackProvider:N.slice(0,S),fallbackModelId:N.slice(S+1),fallbackCredentialInstanceId:void 0}))}},credentialInstanceId:t.fallbackCredentialInstanceId,onCredentialInstanceChange:N=>s(S=>({...S,fallbackCredentialInstanceId:N||void 0})),placeholder:f("settings.globalModels.noFallback","No fallback"),favoriteProviders:l,onToggleFavorite:p,favoriteModels:h,onToggleModelFavorite:m,showThinkingLevel:(()=>{const N=a.find(S=>S.provider===t.fallbackProvider&&S.id===t.fallbackModelId);return N?!!N.reasoning:!0})(),thinkingLevel:t.fallbackThinkingLevel||"",onThinkingLevelChange:N=>s(S=>({...S,fallbackThinkingLevel:N||void 0})),defaultThinkingLevel:t.defaultThinkingLevel})]})]}),(()=>{const N=a.find(S=>S.provider===t.defaultProvider&&S.id===t.defaultModelId);return N&&!N.reasoning?null:e.jsx(Ae,{descriptor:{key:"defaultThinkingLevel",label:f("settings.globalModels.thinkingEffort","Thinking Effort"),help:f("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)."),scope:"global",options:[{value:"",label:f("settings.globalModels.default","Default")},...nd.map(S=>({value:S,label:S.charAt(0).toUpperCase()+S.slice(1)}))]},value:t.defaultThinkingLevel||"",onChange:S=>s(L=>({...L,defaultThinkingLevel:S||void 0}))})})(),a.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:f("settings.globalModels.modelLanes","Model Lanes")}),e.jsx("p",{className:"settings-description",children:f("settings.globalModels.globalBaselineModelsForEachAIRoleProject"," Global baseline models for each AI role. Project settings can override these per-project. ")}),o.map(N=>{const S=t[N.globalProviderKey],L=t[N.globalModelKey],F=S&&L?`${S}/${L}`:"",K=d(N),R=ng[N.laneId],T=R?t[R]:void 0;return e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:`global-${N.laneId}-model`,children:N.label}),e.jsx(G,{settingKey:`global-${N.laneId}-model`,children:N.helperText})]}),e.jsx(lt,{id:`global-${N.laneId}-model`,label:N.label,models:a,value:F,onChange:b=>{if(!b){s(X=>({...X,[N.globalProviderKey]:void 0,[N.globalModelKey]:void 0,...R?{[R]:void 0}:{}})),c(N);return}const V=b.indexOf("/");s(X=>({...X,[N.globalProviderKey]:b.slice(0,V),[N.globalModelKey]:b.slice(V+1),...R?{[R]:void 0}:{}}))},credentialInstanceId:T,onCredentialInstanceChange:R?b=>s(V=>({...V,[R]:b||void 0})):void 0,placeholder:f("settings.globalModels.useDefault","Use default"),favoriteProviders:l,onToggleFavorite:p,favoriteModels:h,onToggleModelFavorite:m,showThinkingLevel:!!N.globalThinkingKey,thinkingLevel:K,onThinkingLevelChange:b=>u(N,b),defaultThinkingLevel:t.defaultThinkingLevel})]},`global-${N.laneId}`)})]}),e.jsx(ag,{form:t,setForm:s,addToast:x,projectId:w}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:f("settings.globalModels.startupModelSync","Startup Model Sync")}),e.jsx(ae,{descriptor:{key:"openrouterModelSync",label:f("settings.globalModels.syncOpenRouterModelListAtStartup"," Sync OpenRouter model list at startup "),help:f("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. "),scope:"global"},value:t.openrouterModelSync!==!1,onChange:N=>s(S=>({...S,openrouterModelSync:N===!0}))}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"opencodeGoModelSync",className:"checkbox-label",children:[e.jsx("input",{id:"opencodeGoModelSync",type:"checkbox",checked:t.opencodeGoModelSync!==!1,onChange:N=>s(S=>({...S,opencodeGoModelSync:N.target.checked}))}),f("settings.globalModels.syncOpencodeGoModelListAtStartup"," Sync opencode-go model list at startup ")]}),e.jsxs(G,{settingKey:"opencodeGoModelSync",children:[f("settings.globalModels.whenEnabledStartupRefreshesModelsThroughTheLocal"," When enabled, startup refreshes models through the local "),e.jsx("code",{children:"opencode models opencode --refresh"}),f("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:f("settings.globalModels.openRouterAdvanced","OpenRouter advanced")}),e.jsx(be,{descriptor:{key:"openrouterAppAttribution.referer",label:f("settings.globalModels.openRouterHTTPReferer","OpenRouter HTTP-Referer"),help:f("settings.globalModels.leaveEmptyToOmitThisHeaderDefaultHttps","Leave empty to omit this header. No default — unset (Fusion falls back to https://runfusion.ai when unset)."),scope:"global",placeholder:f("settings.globalModels.httpsRunfusionAi","https://runfusion.ai")},value:t.openrouterAppAttribution?.referer??"",onChange:N=>s(S=>({...S,openrouterAppAttribution:{...S.openrouterAppAttribution||{},referer:N??""}}))}),e.jsx(be,{descriptor:{key:"openrouterAppAttribution.title",label:f("settings.globalModels.openRouterXTitle","OpenRouter X-Title"),help:f("settings.globalModels.leaveEmptyToOmitThisHeaderDefaultFusion",'Leave empty to omit this header. No default — unset (Fusion falls back to the title "Fusion" when unset).'),scope:"global",placeholder:f("settings.globalModels.fusion","Fusion")},value:t.openrouterAppAttribution?.title??"",onChange:N=>s(S=>({...S,openrouterAppAttribution:{...S.openrouterAppAttribution||{},title:N??""}}))}),e.jsx(be,{descriptor:{key:"openrouterModelFilters.supported_parameters",label:f("settings.globalModels.openRouterSupportedParametersFilter","OpenRouter supported_parameters filter"),help:f("settings.globalModels.commaSeparatedValuesSentToOpenRouterModelSync","Comma-separated values sent to OpenRouter model sync. No default — unset (unfiltered)."),scope:"global",placeholder:f("settings.globalModels.toolsStructuredOutputs","tools, structured_outputs")},value:Ss(t.openrouterModelFilters?.supported_parameters),onChange:N=>{const S=Ns(N??"");s(L=>({...L,openrouterModelFilters:{...L.openrouterModelFilters||{},supported_parameters:S.length>0?S:void 0}}))}}),e.jsx(be,{descriptor:{key:"openrouterModelFilters.output_modalities",label:f("settings.globalModels.openRouterOutputModalitiesFilter","OpenRouter output_modalities filter"),help:f("settings.globalModels.commaSeparatedValuesSentToOpenRouterModelSyncOutputModalities","Comma-separated values sent to OpenRouter model sync. No default — unset (unfiltered)."),scope:"global",placeholder:f("settings.globalModels.text","text")},value:Ss(t.openrouterModelFilters?.output_modalities),onChange:N=>{const S=Ns(N??"");s(L=>({...L,openrouterModelFilters:{...L.openrouterModelFilters||{},output_modalities:S.length>0?S:void 0}}))}}),e.jsx(be,{descriptor:{key:"openrouterProviderPreferences.order",label:f("settings.globalModels.openRouterRoutingOrder","OpenRouter routing order"),help:f("settings.globalModels.openRouterRoutingOrderHint","No default — unset (OpenRouter's own default routing order applies)."),scope:"global",placeholder:f("settings.globalModels.openaiAnthropic","openai, anthropic")},value:Ss(t.openrouterProviderPreferences?.order),onChange:N=>{const S=Ns(N??"");s(L=>({...L,openrouterProviderPreferences:{...L.openrouterProviderPreferences||{},order:S.length>0?S:void 0}}))}}),e.jsx(be,{descriptor:{key:"openrouterProviderPreferences.ignore",label:f("settings.globalModels.openRouterRoutingIgnore","OpenRouter routing ignore"),help:f("settings.globalModels.openRouterRoutingIgnoreHint","No default — unset (no providers ignored)."),scope:"global",placeholder:f("settings.globalModels.providerName","provider-name")},value:Ss(t.openrouterProviderPreferences?.ignore),onChange:N=>{const S=Ns(N??"");s(L=>({...L,openrouterProviderPreferences:{...L.openrouterProviderPreferences||{},ignore:S.length>0?S:void 0}}))}}),e.jsx(be,{descriptor:{key:"openrouterProviderPreferences.only",label:f("settings.globalModels.openRouterRoutingOnly","OpenRouter routing only"),help:f("settings.globalModels.openRouterRoutingOnlyHint","No default — unset (no provider restriction)."),scope:"global",placeholder:f("settings.globalModels.providerName","provider-name")},value:Ss(t.openrouterProviderPreferences?.only),onChange:N=>{const S=Ns(N??"");s(L=>({...L,openrouterProviderPreferences:{...L.openrouterProviderPreferences||{},only:S.length>0?S:void 0}}))}}),e.jsx(Ae,{descriptor:{key:"openrouterProviderPreferences.allow_fallbacks",label:f("settings.globalModels.openRouterAllowFallbacks","OpenRouter allow fallbacks"),help:f("settings.globalModels.openRouterAllowFallbacksHint","No default — unset (OpenRouter's own default fallback behavior applies)."),scope:"global",options:[{value:"default",label:f("settings.globalModels.default2","default")},{value:"allow",label:f("settings.globalModels.allow","allow")},{value:"deny",label:f("settings.globalModels.deny","deny")}]},value:t.openrouterProviderPreferences?.allow_fallbacks===void 0?"default":t.openrouterProviderPreferences.allow_fallbacks?"allow":"deny",onChange:N=>s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},allow_fallbacks:N==="default"?void 0:N==="allow"}}))}),e.jsx(Ae,{descriptor:{key:"openrouterProviderPreferences.sort",label:f("settings.globalModels.openRouterRoutingSort","OpenRouter routing sort"),help:f("settings.globalModels.openRouterRoutingSortHint","No default — unset (OpenRouter's own default sort applies)."),scope:"global",options:[{value:"default",label:f("settings.globalModels.default2","default")},{value:"price",label:f("settings.globalModels.price","price")},{value:"throughput",label:f("settings.globalModels.throughput","throughput")},{value:"latency",label:f("settings.globalModels.latency","latency")}]},value:t.openrouterProviderPreferences?.sort??"default",onChange:N=>s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},sort:N==="default"?void 0:N}}))}),e.jsx(ae,{descriptor:{key:"openrouterProviderPreferences.require_parameters",label:f("settings.globalModels.requireParameters"," Require parameters "),help:f("settings.globalModels.requireParametersHint","Default: disabled."),scope:"global"},value:t.openrouterProviderPreferences?.require_parameters===!0,onChange:N=>s(S=>({...S,openrouterProviderPreferences:{...S.openrouterProviderPreferences||{},require_parameters:N===!0}}))})]})]})}function rg({authenticated:t,compact:s=!1,onToggled:a}){const{t:n}=le("app"),[o,d]=i.useState(null),[u,c]=i.useState(null),[l,h]=i.useState(""),[p,m]=i.useState(null),x=i.useRef(!1),w=i.useRef(!0);i.useEffect(()=>(w.current=!0,()=>{w.current=!1}),[]);const f=i.useCallback(async()=>{try{const B=await Zl();return w.current&&(d(B),h(v=>x.current?v:B.binaryPath??"")),B}catch{return null}},[]);i.useEffect(()=>{f()},[f]);const E=i.useCallback(async B=>{c(B?"enabling":"disabling");try{const v=await ld(B);a?.(v.enabled),await f()}finally{w.current&&c(null)}},[a,f]),N=o?.enabled??t,S=o?.binary.available??!1,L=o?.binary.apiKeyDetected??!1,F=l.trim(),K=o?.binaryPath??"",R=F!==K,T=i.useCallback(B=>{h(B),x.current=!0,m(null)},[]),b=i.useCallback(async()=>{c("saving-path"),m(null);try{if(await rd(F||null),!w.current)return;x.current=!1;const B=await Zl();w.current&&(d(B),h(B.binaryPath??""),m({tone:"success",text:F?n("setup.grokCli.pathSaved","Binary path saved and tested."):n("setup.grokCli.pathCleared","Binary path cleared; PATH auto-detection is active.")}))}catch(B){if(w.current){const v=B instanceof Error?B.message:String(B);m({tone:"error",text:v})}}finally{w.current&&c(null)}},[n,F]),V=s?e.jsxs("div",{className:"grok-cli-binary-path-control",children:[e.jsx("label",{className:"grok-cli-binary-path-label",htmlFor:"grok-cli-binary-path",children:n("setup.grokCli.binaryPathLabel","Grok CLI binary path")}),e.jsxs("div",{className:"grok-cli-binary-path-row",children:[e.jsx("input",{id:"grok-cli-binary-path",className:"grok-cli-binary-path-input",type:"text",value:l,onChange:B=>T(B.target.value),placeholder:n("setup.grokCli.binaryPathPlaceholder","/usr/local/bin/grok"),disabled:u!==null}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void b(),disabled:u!==null||!R,children:u==="saving-path"?n("setup.grokCli.savingPath","Saving…"):n("setup.grokCli.saveAndTestPath","Save & Test")})]}),e.jsx("small",{className:"settings-muted",children:n("setup.grokCli.binaryPathHelp","Leave blank to use PATH auto-detection (`grok`).")}),p?e.jsx("small",{className:p.tone==="error"?"form-error":"text-muted",children:p.text}):null]}):null,X=e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{c("testing"),f().finally(()=>{w.current&&c(null)})},disabled:u!==null,children:u==="testing"?e.jsxs(e.Fragment,{children:[e.jsx(bt,{size:12,className:"animate-spin"})," ",n("setup.grokCli.testing","Testing…")]}):n("setup.grokCli.test","Test")}),N?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void E(!1),disabled:u!==null,children:u==="disabling"?n("setup.grokCli.disabling","Disabling…"):n("setup.grokCli.disable","Disable")}):e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void E(!0),disabled:u!==null||!S,children:u==="enabling"?n("setup.grokCli.enabling","Enabling…"):n("setup.grokCli.enable","Enable")})]}),k=o?o.binary.available?N?n("setup.grokCli.connected","Connected{{version}}",{version:o.binary.version?` — ${o.binary.version}`:""}):n("setup.grokCli.detectedPrompt","Detected. Click Enable to route calls through Grok CLI."):o.binary.reason??n("setup.grokCli.binaryNotFound","`grok` not found on PATH"):n("setup.grokCli.probing","Probing local CLI…"),I=o?.binary.available&&!L?n("setup.grokCli.noApiKeyHint","No Grok API key detected by Fusion; the CLI will use its own credentials. The direct xAI streaming path uses GROK_API_KEY when present."):null;return s?e.jsxs("div",{className:`grok-cli-provider-card auth-provider-card auth-provider-card--cli${t?" auth-provider-card--authenticated":""}`,"data-testid":"grok-cli-provider-card",children:[e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx(jt,{provider:"grok-cli",size:"sm"}),e.jsx("strong",{children:n("setup.grokCli.providerName","Grok — via Grok CLI")}),e.jsx("span",{className:`auth-status-badge ${N?"authenticated":"not-authenticated"}`,children:N?n("setup.grokCli.active","✓ Active"):n("setup.grokCli.notConnected","✗ Not connected")})]}),e.jsx("div",{className:"auth-provider-cli-actions",children:X})]}),e.jsxs("div",{className:"grok-cli-provider-card__body","data-testid":"grok-cli-provider-card-body",children:[e.jsx("small",{className:"settings-muted",children:k}),I?e.jsx("small",{className:"settings-muted grok-cli-provider-card__key-hint",children:I}):null,V]})]}):e.jsxs("div",{className:`grok-cli-provider-card onboarding-provider-card${t?" onboarding-provider-card--connected":""}`,"data-testid":"grok-cli-provider-card",children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(jt,{provider:"grok-cli",size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:n("setup.grokCli.providerName","Grok — via Grok CLI")}),e.jsx("span",{className:"onboarding-provider-card__description",children:n("setup.grokCli.description","Route AI calls through your local Grok CLI runtime.")}),e.jsx("small",{className:"settings-muted",children:k}),I?e.jsx("small",{className:"settings-muted grok-cli-provider-card__key-hint",children:I}):null]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:X})]})}function ig({authenticated:t,compact:s=!1,onToggled:a}){const{t:n}=le("app"),[o,d]=i.useState(null),[u,c]=i.useState(null),[l,h]=i.useState(""),[p,m]=i.useState(null),[x,w]=i.useState(null),f=i.useRef(!1),E=i.useRef(!0);i.useEffect(()=>(E.current=!0,()=>{E.current=!1}),[]);const N=i.useCallback(async()=>{try{const B=await er();return E.current&&(d(B),h(v=>f.current?v:B.binaryPath??""),w(null)),B}catch(B){if(E.current){const v=B instanceof Error?B.message:String(B);w({tone:"error",text:v||n("setup.ompCli.probeFailed","Failed to probe local omp CLI.")})}return null}},[n]);i.useEffect(()=>{N()},[N]);const S=i.useCallback(async B=>{c(B?"enabling":"disabling"),w(null);try{const v=await id(B);a?.(v.enabled),await N()}catch(v){if(E.current){const M=v instanceof Error?v.message:String(v);w({tone:"error",text:M||n("setup.ompCli.toggleFailed","Failed to update OMP CLI enable state.")})}}finally{E.current&&c(null)}},[a,N,n]),L=o?.enabled??t,F=o?.binary.available??!1,K=l.trim(),R=o?.binaryPath??"",T=K!==R,b=i.useCallback(B=>{h(B),f.current=!0,m(null)},[]),V=i.useCallback(async()=>{c("saving-path"),m(null);try{if(await od(K||null),!E.current)return;f.current=!1;const B=await er();E.current&&(d(B),h(B.binaryPath??""),m({tone:"success",text:K?n("setup.ompCli.pathSaved","Binary path saved and tested."):n("setup.ompCli.pathCleared","Binary path cleared; PATH auto-detection is active.")}))}catch(B){if(E.current){const v=B instanceof Error?B.message:String(B);m({tone:"error",text:v})}}finally{E.current&&c(null)}},[n,K]),X=s?e.jsxs("div",{className:"omp-cli-binary-path-control",children:[e.jsx("label",{className:"omp-cli-binary-path-label",htmlFor:"omp-cli-binary-path",children:n("setup.ompCli.binaryPathLabel","OMP CLI binary path")}),e.jsxs("div",{className:"omp-cli-binary-path-row",children:[e.jsx("input",{id:"omp-cli-binary-path",className:"omp-cli-binary-path-input",type:"text",value:l,onChange:B=>b(B.target.value),placeholder:n("setup.ompCli.binaryPathPlaceholder","/usr/local/bin/omp"),disabled:u!==null}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void V(),disabled:u!==null||!T,children:u==="saving-path"?n("setup.ompCli.savingPath","Saving…"):n("setup.ompCli.saveAndTestPath","Save & Test")})]}),e.jsx("small",{className:"settings-muted",children:n("setup.ompCli.binaryPathHelp","Leave blank to use PATH auto-detection (`omp`).")}),p?e.jsx("small",{className:p.tone==="error"?"form-error":"text-muted",children:p.text}):null]}):null,k=e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{c("testing"),N().finally(()=>{E.current&&c(null)})},disabled:u!==null,children:u==="testing"?e.jsxs(e.Fragment,{children:[e.jsx(bt,{size:12,className:"animate-spin"})," ",n("setup.ompCli.testing","Testing…")]}):n("setup.ompCli.test","Test")}),L?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void S(!1),disabled:u!==null,children:u==="disabling"?n("setup.ompCli.disabling","Disabling…"):n("setup.ompCli.disable","Disable")}):e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void S(!0),disabled:u!==null||!F,children:u==="enabling"?n("setup.ompCli.enabling","Enabling…"):n("setup.ompCli.enable","Enable")})]}),I=o?o.binary.available?L?n("setup.ompCli.connected","Connected{{version}}",{version:o.binary.version?` — ${o.binary.version}`:""}):n("setup.ompCli.detectedPrompt","Detected. Click Enable to route through omp ACP."):o.binary.reason??n("setup.ompCli.binaryNotFound","`omp` not found on PATH"):n("setup.ompCli.probing","Probing local CLI…");return s?e.jsxs("div",{className:`omp-cli-provider-card auth-provider-card auth-provider-card--cli${t?" auth-provider-card--authenticated":""}`,"data-testid":"omp-cli-provider-card",children:[e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx(jt,{provider:"omp-cli",size:"sm"}),e.jsx("strong",{children:n("setup.ompCli.providerName","Oh My Pi — via omp ACP")}),e.jsx("span",{className:`auth-status-badge ${L?"authenticated":"not-authenticated"}`,children:L?n("setup.ompCli.active","✓ Active"):n("setup.ompCli.notConnected","✗ Not connected")})]}),e.jsx("div",{className:"auth-provider-cli-actions",children:k})]}),e.jsxs("div",{className:"omp-cli-provider-card__body","data-testid":"omp-cli-provider-card-body",children:[e.jsx("small",{className:"settings-muted",children:I}),x?e.jsx("small",{className:x.tone==="error"?"form-error":"text-muted",children:x.text}):null,e.jsx("small",{className:"settings-muted omp-cli-provider-card__hint",children:n("setup.ompCli.authHint","Credentials live under ~/.omp (agent auth). Fusion does not store omp API keys.")}),X]})]}):e.jsxs("div",{className:`omp-cli-provider-card onboarding-provider-card${t?" onboarding-provider-card--connected":""}`,"data-testid":"omp-cli-provider-card",children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(jt,{provider:"omp-cli",size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:n("setup.ompCli.providerName","Oh My Pi — via omp ACP")}),e.jsx("span",{className:"onboarding-provider-card__description",children:n("setup.ompCli.description","Drive sessions through your local omp ACP server (`omp acp`).")}),e.jsx("small",{className:"settings-muted",children:I})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:k})]})}const og=["openai-compatible","openai-responses","anthropic-compatible","google-generative-ai"];function cg(t){return(Array.isArray(t)?t:t.providers??[]).map(a=>"apiType"in a?a:{id:a.id,name:a.name?.trim()||a.id,apiType:a.api==="anthropic-messages"?"anthropic-compatible":a.api==="openai-responses"?"openai-responses":a.api==="google-generative-ai"?"google-generative-ai":"openai-compatible",baseUrl:a.baseUrl,...a.apiKey?{apiKey:a.apiKey}:{},...a.anthropicPromptCaching?{anthropicPromptCaching:!0}:{},models:(a.models??[]).map(n=>({id:n.id,name:n.name??n.id}))})}function dg(t){return t.split(",").map(s=>s.trim()).filter(Boolean).map(s=>({id:s,name:s}))}function ug({embedded:t=!1,onProviderChange:s}){const{t:a}=le("app"),[n,o]=i.useState([]),[d,u]=i.useState(!1),[c,l]=i.useState(!1),[h,p]=i.useState(null),[m,x]=i.useState(null),[w,f]=i.useState(!1),[E,N]=i.useState(""),[S,L]=i.useState("openai-compatible"),[F,K]=i.useState(""),[R,T]=i.useState(""),[b,V]=i.useState(""),[X,k]=i.useState(!1),[I,B]=i.useState(!1),[v,M]=i.useState(null),[se,ne]=i.useState(!1),[pe,j]=i.useState(null),[W,ce]=i.useState(null),[Ie,Oe]=i.useState(null),H=i.useCallback(async()=>{u(!0),p(null);try{const $=await cd();o(cg($)),l(!0)}catch($){p($ instanceof Error?$.message:a("providers.failedLoad","Failed to load custom providers."))}finally{u(!1)}},[a]),Z=i.useCallback($=>{$&&!c&&!d&&H()},[c,d,H]);i.useEffect(()=>{t&&!c&&!d&&H()},[t,c,d,H]);const Te=i.useCallback(()=>{x(null),N(""),L("openai-compatible"),K(""),T(""),V(""),k(!1),M(null),j(null),ne(!1),f(!1)},[]),_e=i.useCallback(()=>{x(null),N(""),L("openai-compatible"),K(""),T(""),V(""),k(!1),M(null),j(null),ne(!1),f(!0)},[]),Ke=i.useCallback($=>{x($),N($.name),L($.apiType),K($.baseUrl),T(""),V(($.models??[]).map(he=>he.id).join(", ")),k($.anthropicPromptCaching===!0),M(null),j(null),ne(!1),f(!0)},[]),D=i.useCallback(()=>{if(!E.trim())return a("providers.nameRequired","Provider name is required.");if(!F.trim())return a("providers.urlRequired","Base URL is required.");let $=!1;try{const he=new URL(F.trim());$=he.protocol==="http:"||he.protocol==="https:"}catch{$=!1}return $?og.includes(S)?null:a("providers.apiTypeInvalid","API type is invalid."):a("providers.urlInvalid","Base URL must be a valid http/https URL.")},[S,F,E,a]),U=i.useCallback(async()=>{const $=F.trim();if(!$){j(a("providers.urlRequiredForDetect","Base URL is required to detect models."));return}ne(!0),j(null);try{const he=await dd({baseUrl:$,apiKey:R.trim()||void 0,apiType:S});he.models.length>0?V(xe=>{const je=new Set(xe.split(",").map(Ce=>Ce.trim()).filter(Boolean)),Me=he.models.map(Ce=>Ce.id.trim()).filter(Ce=>!je.has(Ce));if(Me.length===0)return xe;const P=xe.trim();return Me.join(", ")+(P?", "+P:"")}):j(a("providers.noModelsFound","No models found. The provider may require an API key."))}catch(he){j(he instanceof Error?he.message:a("providers.failedDetect","Failed to detect models"))}finally{ne(!1)}},[F,R,S,a]),te=i.useCallback(async()=>{const $=D();if(M($),$)return;const he=dg(b),xe={name:E.trim(),apiType:S,baseUrl:F.trim(),...R.trim()?{apiKey:R.trim()}:{},...he.length>0?{models:he}:{},...X?{anthropicPromptCaching:!0}:{}};B(!0),p(null);try{m?await ud(m.id,xe):await pd(xe),await H(),s?.(),Te()}catch(je){M(je instanceof Error?je.message:a("providers.failedSave","Failed to save provider."))}finally{B(!1)}},[X,R,S,F,m,H,b,E,Te,D,a]),ke=i.useCallback(async $=>{if(window.confirm(a("providers.deleteConfirm",'Delete custom provider "{{name}}"?',{name:$.name}))){p(null);try{await gd($.id),await H(),s?.()}catch(he){p(he instanceof Error?he.message:a("providers.failedDelete","Failed to delete provider."))}}},[H,s,a]),Ne=i.useCallback(async $=>{ce($.id),Oe(null),p(null);try{const he=await hd($.id);if(o(xe=>xe.map(je=>je.id===$.id?he.provider:je)),m?.id===$.id){const xe=(he.provider.models??[]).map(je=>je.id).join(", ");V(xe),x(je=>je?.id===$.id?{...je,models:he.provider.models??[]}:je)}s?.(),Oe({providerId:$.id,type:"success",message:a("providers.refreshModelsSuccess","Refreshed {{count}} model(s).",{count:he.modelsRefreshed})})}catch(he){Oe({providerId:$.id,type:"error",message:he instanceof Error?he.message:a("providers.refreshModelsFailed","Failed to refresh models.")})}finally{ce(null)}},[m?.id,s,a]),re=e.jsxs(e.Fragment,{children:[t?null:d?e.jsxs("div",{className:"custom-provider-empty",role:"status",children:[e.jsx(bt,{"aria-hidden":"true",className:"custom-provider-spin"})," ",a("providers.loading","Loading custom providers…")]}):null,t?null:!d&&h?e.jsxs("div",{className:"custom-provider-form-error",role:"alert",children:[e.jsx(tr,{"aria-hidden":"true"}),e.jsx("span",{children:h})]}):null,!d&&n.length>0?e.jsx("div",{className:"custom-provider-list",children:n.map($=>{const he=w&&m?.id===$.id,xe=W===$.id,je=Ie?.providerId===$.id?Ie: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:$.name}),e.jsxs("div",{className:"custom-provider-item-meta",children:[e.jsx("span",{className:"custom-provider-badge",children:$.apiType})," ",$.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 Ne($),disabled:xe,"aria-label":a("providers.refreshModelsLabel","Refresh models for {{name}}",{name:$.name}),children:[xe?e.jsx(bt,{"aria-hidden":"true",className:"custom-provider-spin"}):e.jsx(Ts,{"aria-hidden":"true"}),e.jsx("span",{children:xe?a("providers.refreshingModels","Refreshing…"):a("providers.refreshModels","Refresh Models")})]}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ke($),"aria-label":a("providers.editLabel","Edit {{name}}",{name:$.name}),children:e.jsx(ya,{"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>void ke($),"aria-label":a("providers.deleteLabel","Delete {{name}}",{name:$.name}),children:e.jsx(va,{"aria-hidden":"true"})})]})]}),je?e.jsxs("div",{className:`custom-provider-row-message custom-provider-row-message--${je.type}`,role:je.type==="error"?"alert":"status",children:[je.type==="error"?e.jsx(tr,{"aria-hidden":"true"}):null,e.jsx("span",{children:je.message})]}):null,he?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:a("providers.nameLabel","Provider name")}),e.jsx("input",{id:"custom-provider-name",className:"input",value:E,onChange:Me=>N(Me.target.value),disabled:I})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-type",children:a("providers.apiTypeLabel","API type")}),e.jsxs("select",{id:"custom-provider-api-type",className:"select",value:S,onChange:Me=>L(Me.target.value),disabled:I,children:[e.jsx("option",{value:"openai-compatible",children:a("providers.apiTypeOpenAi","OpenAI-compatible")}),e.jsx("option",{value:"openai-responses",children:a("providers.apiTypeOpenAiResp","OpenAI Responses")}),e.jsx("option",{value:"anthropic-compatible",children:a("providers.apiTypeAnthropic","Anthropic-compatible")}),e.jsx("option",{value:"google-generative-ai",children:a("providers.apiTypeGoogle","Google Generative AI")})]})]}),S==="openai-compatible"||S==="openai-responses"?e.jsxs("div",{className:"form-group custom-provider-form-row custom-provider-form-checkbox-row",children:[e.jsxs("label",{htmlFor:"custom-provider-anthropic-caching",children:[e.jsx("input",{id:"custom-provider-anthropic-caching",type:"checkbox",checked:X,onChange:Me=>k(Me.target.checked),disabled:I})," ",a("providers.anthropicPromptCaching","Enable Anthropic-style prompt caching")]}),e.jsx("p",{className:"custom-provider-form-hint",children:a("providers.anthropicPromptCachingHint","Enable if this gateway proxies an Anthropic model (e.g. Claude via a custom router). Reduces re-billing the full context every turn.")})]}):null,e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-base-url",children:a("providers.baseUrlLabel","Base URL")}),e.jsx("input",{id:"custom-provider-base-url",className:"input",placeholder:"https://api.example.com/v1",value:F,onChange:Me=>K(Me.target.value),disabled:I})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-key",children:a("providers.apiKeyLabel","API key")}),e.jsx("input",{id:"custom-provider-api-key",type:"password",className:"input",placeholder:m?.apiKey?a("providers.apiKeyKeepPlaceholder","Leave blank to keep current key"):void 0,value:R,onChange:Me=>T(Me.target.value),disabled:I})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-models",children:a("providers.modelsLabel","Available models")}),e.jsx("input",{id:"custom-provider-models",className:"input",placeholder:"e.g., gpt-4, gpt-3.5-turbo",value:b,onChange:Me=>V(Me.target.value),disabled:I})]}),e.jsx("div",{className:"custom-provider-detect-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void U(),disabled:I||se||!F.trim(),title:a("providers.detectTitle","Auto-detect models from the provider's /models endpoint"),children:se?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"custom-provider-spin",size:14})," ",a("providers.detecting","Detecting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Hn,{size:14})," ",a("providers.detectModels","Detect Models")]})})}),pe?e.jsx("div",{className:"custom-provider-form-error",children:pe}):null,v?e.jsx("div",{className:"custom-provider-form-error",children:v}):null,e.jsxs("div",{className:"custom-provider-form-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Te,disabled:I,children:a("actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void te(),disabled:I,children:I?a("providers.saving","Saving…"):a("providers.saveChanges","Save Changes")})]})]}):null]},$.id)})}):null,!d&&n.length===0&&!h?e.jsx("div",{className:"custom-provider-empty",children:a("providers.noneConfigured","No custom providers configured.")}):null,e.jsxs("button",{type:"button",className:"btn btn-sm custom-provider-add-btn",onClick:_e,children:[e.jsx(fa,{"aria-hidden":"true"})," ",a("providers.addCustom","Add Custom Provider")]}),w&&!m?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:a("providers.nameLabel","Provider name")}),e.jsx("input",{id:"custom-provider-name",className:"input",value:E,onChange:$=>N($.target.value),disabled:I})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-type",children:a("providers.apiTypeLabel","API type")}),e.jsxs("select",{id:"custom-provider-api-type",className:"select",value:S,onChange:$=>L($.target.value),disabled:I,children:[e.jsx("option",{value:"openai-compatible",children:a("providers.apiTypeOpenAi","OpenAI-compatible")}),e.jsx("option",{value:"openai-responses",children:a("providers.apiTypeOpenAiResp","OpenAI Responses")}),e.jsx("option",{value:"anthropic-compatible",children:a("providers.apiTypeAnthropic","Anthropic-compatible")}),e.jsx("option",{value:"google-generative-ai",children:a("providers.apiTypeGoogle","Google Generative AI")})]})]}),S==="openai-compatible"||S==="openai-responses"?e.jsxs("div",{className:"form-group custom-provider-form-row custom-provider-form-checkbox-row",children:[e.jsxs("label",{htmlFor:"custom-provider-anthropic-caching-new",children:[e.jsx("input",{id:"custom-provider-anthropic-caching-new",type:"checkbox",checked:X,onChange:$=>k($.target.checked),disabled:I})," ",a("providers.anthropicPromptCaching","Enable Anthropic-style prompt caching")]}),e.jsx("p",{className:"custom-provider-form-hint",children:a("providers.anthropicPromptCachingHint","Enable if this gateway proxies an Anthropic model (e.g. Claude via a custom router). Reduces re-billing the full context every turn.")})]}):null,e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-base-url",children:a("providers.baseUrlLabel","Base URL")}),e.jsx("input",{id:"custom-provider-base-url",className:"input",placeholder:"https://api.example.com/v1",value:F,onChange:$=>K($.target.value),disabled:I})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-api-key",children:a("providers.apiKeyLabel","API key")}),e.jsx("input",{id:"custom-provider-api-key",type:"password",className:"input",value:R,onChange:$=>T($.target.value),disabled:I})]}),e.jsxs("div",{className:"form-group custom-provider-form-row",children:[e.jsx("label",{htmlFor:"custom-provider-models",children:a("providers.modelsLabel","Available models")}),e.jsx("input",{id:"custom-provider-models",className:"input",placeholder:"e.g., gpt-4, gpt-3.5-turbo",value:b,onChange:$=>V($.target.value),disabled:I})]}),e.jsx("div",{className:"custom-provider-detect-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void U(),disabled:I||se||!F.trim(),title:a("providers.detectTitle","Auto-detect models from the provider's /models endpoint"),children:se?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"custom-provider-spin",size:14})," ",a("providers.detecting","Detecting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Hn,{size:14})," ",a("providers.detectModels","Detect Models")]})})}),pe?e.jsx("div",{className:"custom-provider-form-error",children:pe}):null,v?e.jsx("div",{className:"custom-provider-form-error",children:v}):null,e.jsxs("div",{className:"custom-provider-form-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Te,disabled:I,children:a("actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void te(),disabled:I,children:I?a("providers.saving","Saving…"):a("providers.saveProvider","Save Provider")})]})]}):null]});return e.jsx("div",{className:"custom-providers-section",children:t?re:e.jsx(md,{summary:"Advanced: Custom Providers",onToggle:Z,children:re})})}const In="anthropic-api-key",Tn="anthropic-subscription",pg={"claude-cli":0,"anthropic-subscription":1,"anthropic-api-key":2,anthropic:3},Hr=t=>pg[t.id]??Number.POSITIVE_INFINITY,gg=(t,s)=>{if(t.authenticated!==s.authenticated)return t.authenticated?-1:1;const a=Hr(t),n=Hr(s);if(a!==n)return a-n;const o=t.name.localeCompare(s.name);return o!==0?o:t.id.localeCompare(s.id)};function hg({auth:t,form:s,setForm:a}){const{t:n}=le("app"),{projectId:o,addToast:d,authProviders:u,authLoading:c,authActionInProgress:l,apiKeyInputs:h,setApiKeyInputs:p,apiKeyErrors:m,opencodeApiKeyRefreshStatus:x,deviceCodes:w,loginInstructions:f,manualCodeConfigs:E,manualCodeInputs:N,setManualCodeInputs:S,manualCodeSubmitInProgress:L,loadAuthStatus:F,handleLogin:K,handleLogout:R,handleCancelLogin:T,handleSaveApiKey:b,handleClearApiKey:V,handleSubmitManualCode:X,onReopenOnboarding:k}=t,[I,B]=i.useState({}),v=P=>typeof l=="string"?l===P:!!l?.[P],se=u.some(P=>P.id==="anthropic-subscription"||P.id==="anthropic-api-key")?u.filter(P=>P.id!=="anthropic"):u,ne=P=>P.id==="claude-cli"||P.id==="cursor-cli"||P.id==="grok-cli"||P.id==="omp-cli"||P.id==="llama-cpp",pe=[...se].filter(P=>P.type!=="cli"||ne(P)).sort(gg),j=pe.filter(P=>P.authenticated),W=pe.filter(P=>!P.authenticated),ce=()=>{F(),Cd()},Ie=P=>P.id==="claude-cli"?e.jsx(bd,{compact:!0,authenticated:P.authenticated,onToggled:ce},P.id):P.id==="cursor-cli"?e.jsx(fd,{compact:!0,authenticated:P.authenticated,onToggled:ce},P.id):P.id==="grok-cli"?e.jsx(rg,{compact:!0,authenticated:P.authenticated,onToggled:ce},P.id):P.id==="omp-cli"?e.jsx(ig,{compact:!0,authenticated:P.authenticated,onToggled:ce},P.id):e.jsx(yd,{compact:!0,authenticated:P.authenticated,onToggled:ce},P.id),Oe=u.some(P=>P.id===In&&P.authenticated),H=u.some(P=>P.id===Tn&&P.authenticated),Z=!!(s&&a)&&Oe&&H,Te=s?.anthropicAuthPreference==="subscription"?"subscription":"api-key",_e=P=>Z&&(Te==="subscription"?P===Tn:P===In),Ke=P=>!Z||P.id!==In&&P.id!==Tn?null:_e(P.id)?e.jsx("span",{className:"auth-status-badge authenticated","data-testid":`auth-precedence-active-${P.id}`,children:n("settings.auth.credentialInUse","In use")}):e.jsx("span",{className:"auth-key-hint","data-testid":`auth-precedence-overridden-${P.id}`,children:n("settings.auth.credentialOverridden","Overridden below")}),D=()=>Z?e.jsx(Ae,{descriptor:{key:"anthropicAuthPreference",label:n("settings.auth.anthropicPreferenceLabel","Anthropic credential to use"),help:n("settings.auth.anthropicPreferenceHint","You have both an Anthropic API key and a Claude subscription connected. Choose which one Fusion sends when a lane calls Anthropic directly. Default: API key."),scope:"global",options:[{value:"api-key",label:n("settings.auth.anthropicPreferenceApiKey","API key")},{value:"subscription",label:n("settings.auth.anthropicPreferenceSubscription","Claude subscription")}]},value:Te,onChange:P=>a?.(Ce=>({...Ce,anthropicAuthPreference:P==="subscription"?"subscription":"api-key"}))}):null,U=j.length>0,te=W.length>0,ke=P=>P.type==="api_key",Ne=P=>(P.instances?.length??0)>1,re=(P,Ce)=>({...P,authenticated:Ce.authenticated,expired:Ce.expired,keyHint:Ce.keyHint,instanceId:Ce.instanceId,type:Ce.type??P.type,loginInProgress:!1}),$=P=>{if(P.type==="cli")return null;const Ce=P.instances??[],Re=I[P.id],ve=()=>B(ie=>({...ie,[P.id]:{instanceId:Sd(Ce.map(Ee=>Ee.instanceId)),label:""}})),we=()=>B(ie=>{const Ee={...ie};return delete Ee[P.id],Ee});return e.jsxs("div",{className:"auth-instance-controls",children:[Ce.length>1&&e.jsx("div",{className:"auth-instance-list","data-testid":`auth-instances-${P.id}`,children:Ce.map(ie=>{const Ee=re(P,ie);return e.jsxs("div",{className:"auth-instance-row",children:[e.jsxs("span",{children:[ie.label||ie.instanceId,ie.isDefault?` (${n("settings.auth.default","Default")})`:""]}),!ie.isDefault&&e.jsx("button",{className:"btn btn-sm",onClick:()=>void vd(P.id,ie.instanceId).then(F),children:n("settings.auth.makeDefault","Make default")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{const A=window.prompt(n("settings.auth.renameAccount","Account name"),ie.label||"");A!==null&&kd(P.id,ie.instanceId,A).then(F)},children:n("settings.actions.rename","Rename")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void xd(P.id,ie.instanceId).then(F),children:n("settings.actions.remove","Remove")}),ke(Ee)?xe(Ee,ie.instanceId):ie.authenticated?je(Ee,ie.instanceId):Me(Ee,ie.instanceId)]},ie.instanceId)})}),Re&&e.jsxs("div",{className:"auth-instance-pending","data-testid":`auth-pending-instance-${P.id}`,children:[e.jsxs("div",{className:"auth-pending-instance-field",children:[e.jsx("label",{className:"auth-pending-instance-label",htmlFor:`auth-pending-instance-${P.id}-label`,children:n("settings.auth.accountLabel","Account name")}),e.jsx("input",{id:`auth-pending-instance-${P.id}-label`,className:"input",value:Re.label,onChange:ie=>B(Ee=>({...Ee,[P.id]:{...Re,label:ie.target.value}}))})]}),ke(P)?xe(P,Re.instanceId,Re.label,!0):Me(P,Re.instanceId,Re.label||void 0),e.jsx("button",{className:"btn btn-sm",onClick:we,children:n("settings.actions.cancel","Cancel")})]}),!Re&&e.jsx("button",{className:"btn btn-sm",onClick:ve,children:n("settings.auth.addAnotherAccount","Add another account")})]})},he=P=>P.loginError?e.jsx("small",{className:"form-error",role:"alert",children:P.loginError}):null,xe=(P,Ce,Re,ve=!1)=>{const we=Ce??P.instanceId,ie=xt({providerId:P.id,instanceId:we??"default"});return 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:n("settings.authentication.enterAPIKey","Enter API key"),value:h[ie]??"",onChange:Ee=>p(A=>({...A,[ie]:Ee.target.value})),disabled:v(ie)}),P.keyHint&&!ve&&!h[ie]?e.jsx("button",{className:"btn btn-sm",onClick:()=>we?V(P.id,we):V(P.id),disabled:v(ie),children:n("settings.auth.clearKey","Clear")}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>we?b(P.id,we,Re||void 0):b(P.id),disabled:v(ie),children:n("settings.actions.save","Save")})]}),v(ie)&&e.jsx("small",{className:"auth-apikey-progress",children:n("settings.auth.savingKey","Saving…")}),m[ie]&&e.jsx("small",{className:"auth-apikey-error",children:m[ie]}),(P.id==="opencode"||P.id==="opencode-go")&&x[ie]&&e.jsx("small",{className:x[ie].tone==="error"?"form-error":"text-muted",children:x[ie].message})]})},je=(P,Ce)=>{const Re=Ce??P.instanceId,ve=xt({providerId:P.id,instanceId:Re??"default"});return e.jsx("div",{children:v(ve)?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:n("settings.auth.loggingOut","Logging out…")}):P.loginInProgress?e.jsxs("div",{className:"auth-provider-actions-row",children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:n("settings.auth.waitingForLogin","Waiting for login…")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Re?T(P.id,Re):T(P.id),children:n("settings.actions.cancel","Cancel")})]}):e.jsx("button",{className:"btn btn-sm",onClick:()=>Re?R(P.id,Re):R(P.id),children:n("settings.auth.logout","Logout")})})},Me=(P,Ce,Re)=>{const ve=Ce??P.instanceId,we=xt({providerId:P.id,instanceId:ve??"default"}),ie=P.loginInProgress||v(we);return e.jsxs("div",{children:[v(we)?e.jsxs("div",{className:"auth-provider-actions-row",children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:n("settings.auth.waitingForLogin","Waiting for login…")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>ve?T(P.id,ve):T(P.id),children:n("settings.actions.cancel","Cancel")})]}):P.loginInProgress?e.jsxs("div",{className:"auth-provider-actions-row",children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:n("settings.auth.waitingForLogin","Waiting for login…")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>ve?T(P.id,ve):T(P.id),children:n("settings.actions.cancel","Cancel")})]}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ve?K(P.id,ve,Re):K(P.id),children:n("settings.auth.login","Login")}),P.id==="github-copilot"&&w[we]&&ie&&e.jsxs("div",{className:"auth-device-code-panel","data-testid":`auth-device-code-${we}`,children:[e.jsx("strong",{children:n("settings.auth.enterCodeOnGitHub","Enter this code on GitHub")}),e.jsx("div",{className:"auth-device-code-pill",children:w[we].userCode}),e.jsxs("div",{className:"auth-provider-actions-row",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>void qn(w[we].userCode).then(Ee=>d(Ee?n("settings.auth.copiedCodeToClipboard","Copied code to clipboard"):n("settings.auth.failedToCopyCode","Failed to copy code — copy it manually from the box above"),Ee?"success":"error")),children:n("settings.auth.copyCode","Copy code")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>ri(ii(w[we].verificationUri)),children:n("settings.auth.openGitHub","Open GitHub")})]})]}),f[we]&&ie&&e.jsx(jd,{instructions:f[we],"data-testid":`auth-login-instructions-${we}`}),E[we]&&ie&&e.jsx(wd,{value:N[we]??"",onChange:Ee=>S(A=>({...A,[we]:Ee})),onSubmit:()=>void X(P.id,ve),prompt:E[we].prompt,placeholder:E[we].placeholder,helpText:E[we].helpText,disabled:L===we,submitLabel:L===we?"Submitting…":"Submit code","data-testid":`auth-manual-code-${we}`})]})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading",children:n("settings.auth.title","Authentication")}),e.jsx(G,{settingKey:"auth-section",children:n("settings.auth.hint","Authentication changes take effect immediately — no need to save.")})]}),c?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Et,{label:n("settings.auth.loadingStatus","Loading authentication status…")})}):u.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.auth.noProviders","No providers available")}):e.jsxs("div",{className:"auth-panel-body",children:[e.jsx(_n,{slotId:"settings-provider-card",projectId:o,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{F()}}}),e.jsx(_n,{slotId:"settings-integration-card",projectId:o,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{F()}}}),!U&&e.jsx("div",{className:"auth-section-hint",children:n("settings.auth.signInHint","Sign in to at least one provider to get started with AI models.")}),U&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:n("settings.auth.groupAuthenticated","Authenticated")}),j.map(P=>P.type==="cli"?Ie(P):e.jsxs("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-${P.id}`,"aria-hidden":"true",children:e.jsx(jt,{provider:P.id,size:"md"})}),e.jsx("strong",{children:P.name}),e.jsx("span",{"data-testid":`auth-status-${P.id}`,className:`auth-status-badge ${P.authenticated?"authenticated":"not-authenticated"}`,children:n("settings.auth.statusActive","✓ Active")}),Ke(P),P.authenticated&&P.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:[n("settings.authentication.key","Key: "),P.keyHint]})]}),P.type!=="api_key"&&!Ne(P)&&e.jsxs("div",{children:[je(P),he(P)]}),ke(P)&&!Ne(P)&&xe(P)]}),$(P)]},P.id)),D()]}),te&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:n("settings.auth.groupAvailable","Available")}),W.map(P=>P.type==="cli"?Ie(P):e.jsxs("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-${P.id}`,"aria-hidden":"true",children:e.jsx(jt,{provider:P.id,size:"md"})}),e.jsx("strong",{children:P.name}),e.jsx("span",{"data-testid":`auth-status-${P.id}`,className:`auth-status-badge ${P.authenticated?"authenticated":"not-authenticated"}`,children:n("settings.auth.statusNotConnected","✗ Not connected")}),P.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:[n("settings.authentication.key","Key: "),P.keyHint]})]}),P.type!=="api_key"&&!Ne(P)&&e.jsxs("div",{children:[Me(P),he(P)]}),ke(P)&&!Ne(P)&&xe(P)]}),$(P)]},P.id))]})]}),k&&e.jsx("div",{className:"form-group",style:{marginTop:"var(--space-md)"},children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:k,children:n("settings.auth.reopenOnboarding","Reopen onboarding guide")}),e.jsx(G,{settingKey:"reopen-onboarding",children:n("settings.auth.reopenOnboardingHint","Re-run the setup wizard to review or update your AI provider and model configuration.")})]})}),e.jsx(ug,{})]})}function Xn(t){const{t:s}=le("app"),{name:a,subname:n,logo:o,learnMoreHref:d,statusKind:u,statusText:c,description:l,tabs:h,children:p,busy:m,canTest:x=!0,toast:w,onTest:f,onSave:E,onSaveAndTest:N,belowForm:S,testId:L}=t,F=u==="ok"?"runtime-card__status runtime-card__status--ok":u==="err"?"runtime-card__status runtime-card__status--err":"runtime-card__status runtime-card__status--neutral";return e.jsxs("div",{className:"runtime-card","data-testid":L,"aria-live":"polite",children:[e.jsxs("header",{className:"runtime-card__header",children:[e.jsx("span",{className:"runtime-card__logo",children:o}),e.jsxs("div",{className:"runtime-card__title",children:[e.jsx("h3",{className:"runtime-card__name",children:a}),n&&e.jsx("small",{className:"runtime-card__cobrand",children:n}),e.jsxs("small",{className:F,children:[u==="loading"&&e.jsx(bt,{size:12,className:"animate-spin"}),c]})]}),e.jsx("a",{className:"runtime-card__learn-more btn btn-sm btn-ghost",href:d,target:"_blank",rel:"noreferrer",children:s("common.learnMore","Learn more →")})]}),e.jsx("p",{className:"runtime-card__description",children:l}),h,e.jsx("div",{className:"runtime-card__form",children:p}),S,e.jsxs("footer",{className:"runtime-card__footer",children:[w&&e.jsx("span",{className:w.kind==="ok"?"runtime-card__toast runtime-card__toast--ok":"runtime-card__toast runtime-card__toast--err",role:"status",children:w.message}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:f,disabled:m!==null||!x,children:m==="testing"?e.jsxs(e.Fragment,{children:[e.jsx(bt,{size:12,className:"animate-spin"})," ",s("common.testing","Testing…")]}):s("common.test","Test")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:E,disabled:m!==null,children:m==="saving"?s("common.saving","Saving…"):s("common.save","Save")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,disabled:m!==null||!x,children:m==="save-test"?e.jsxs(e.Fragment,{children:[e.jsx(bt,{size:12,className:"animate-spin"})," ",s("common.saving","Saving…")]}):s("common.saveAndTest","Save & Test")})]})]})}const ia="fusion-plugin-hermes-runtime",_r="https://github.com/NousResearch/hermes-agent",mg=["auto","anthropic","openrouter","gemini","openai-codex","copilot","copilot-acp","huggingface","zai","kimi-coding","minimax","minimax-cn","kilocode","xiaomi","nous"],gt={binaryPath:"",model:"",provider:"auto",maxTurns:12,yolo:!1,cliTimeoutMs:3e5,profile:""};function bg(t){return{binaryPath:typeof t.binaryPath=="string"?t.binaryPath:gt.binaryPath,model:typeof t.model=="string"?t.model:gt.model,provider:typeof t.provider=="string"?t.provider:gt.provider,maxTurns:typeof t.maxTurns=="number"?t.maxTurns:gt.maxTurns,yolo:typeof t.yolo=="boolean"?t.yolo:gt.yolo,cliTimeoutMs:typeof t.cliTimeoutMs=="number"?t.cliTimeoutMs:gt.cliTimeoutMs,profile:typeof t.profile=="string"?t.profile:gt.profile}}function fg(){const{t}=le("app"),[s,a]=i.useState(gt),[n,o]=i.useState(null),[d,u]=i.useState([]),[c,l]=i.useState(null),[h,p]=i.useState(null),[m,x]=i.useState(!1),w=i.useRef(!0);i.useEffect(()=>(w.current=!0,()=>{w.current=!1}),[]),i.useEffect(()=>{let T=!1;return xa().then(b=>{if(T)return;const V=b.find(X=>X.id===ia);x(V?!V.enabled:!1)}).catch(()=>{}),()=>{T=!0}},[]),i.useEffect(()=>{l("loading"),Vn(ia).then(T=>{w.current&&a(bg(T))}).catch(()=>{}).finally(()=>{w.current&&l(null)})},[]),i.useEffect(()=>{Nd(s.binaryPath?{binaryPath:s.binaryPath}:{}).then(T=>{w.current&&u(T)}).catch(()=>{})},[s.binaryPath]);const f=i.useCallback(async()=>{try{const T=await Pd(s.binaryPath?{binaryPath:s.binaryPath}:{});return w.current&&o(T),T}catch(T){return w.current&&p({kind:"err",message:T instanceof Error?T.message:String(T)}),null}},[s.binaryPath]);i.useEffect(()=>{f()},[f]);const E=i.useCallback(()=>({binaryPath:s.binaryPath,model:s.model,provider:s.provider,maxTurns:s.maxTurns,yolo:s.yolo,cliTimeoutMs:s.cliTimeoutMs,profile:s.profile}),[s]),N=i.useCallback(async()=>{l("testing"),p(null);const T=await f();w.current&&(l(null),T?T.binary.available?p({kind:"ok",message:t("hermes.detected","✓ hermes detected{{version}}{{path}}.",{version:T.binary.version?` (${T.binary.version})`:"",path:T.binary.binaryPath?` at ${T.binary.binaryPath}`:""})}):p({kind:"err",message:t("hermes.notFound","✗ {{reason}}",{reason:T.binary.reason??"hermes not found"})}):p({kind:"err",message:t("hermes.testFailed","Test failed — see status above.")}))},[f,t]),S=i.useCallback(async()=>{l("saving"),p(null);try{await rs(ia,E()),w.current&&p({kind:"ok",message:t("hermes.settingsSaved","Settings saved.")})}catch(T){w.current&&p({kind:"err",message:T instanceof Error?T.message:String(T)})}finally{w.current&&l(null)}},[E,t]),L=i.useCallback(async()=>{l("save-test"),p(null);try{await rs(ia,E());const T=await f();if(!w.current)return;T?T.binary.available?p({kind:"ok",message:t("hermes.savedDetected","Saved · ✓ hermes detected{{version}}.",{version:T.binary.version?` (${T.binary.version})`:""})}):p({kind:"err",message:t("hermes.savedNotFound","Saved · ✗ {{reason}}",{reason:T.binary.reason??"hermes not found"})}):p({kind:"err",message:t("hermes.savedProbeFailed","Saved, but probe failed.")})}catch(T){w.current&&p({kind:"err",message:T instanceof Error?T.message:String(T)})}finally{w.current&&l(null)}},[E,f,t]),F=n?.binary,K=m?"neutral":n===null?"loading":F?.available?"ok":"err",R=m?t("hermes.statusDisabledInPluginManager","Disabled in Plugin Manager"):n===null?t("hermes.probing","Probing local hermes binary…"):F?.available?t("hermes.statusDetected","✓ Detected{{version}}{{path}}",{version:F.version?` ${F.version}`:"",path:F.binaryPath?` · ${F.binaryPath}`:""}):t("hermes.statusNotDetected","✗ {{reason}}",{reason:F?.reason??"not detected on PATH"});return e.jsxs(Xn,{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:t("runtimes.nousResearchLogoAlt","Nous Research"),style:{width:28,height:28,display:"block",filter:"invert(1) brightness(0)"}})}),name:"Hermes",subname:t("hermes.subname","by Nous Research"),learnMoreHref:_r,statusKind:K,statusText:R,description:e.jsx(e.Fragment,{children:t("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:c,toast:h,onTest:()=>void N(),onSave:()=>void S(),onSaveAndTest:()=>void L(),belowForm:F?.available===!1?e.jsxs("div",{className:"onboarding-helper-text",children:[e.jsx("p",{children:t("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:_r,target:"_blank",rel:"noreferrer",children:t("hermes.gitHubLink","Hermes on GitHub")})})]}):null,children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-profile",children:t("hermes.profileLabel","Profile (optional)")}),e.jsxs("select",{id:"hermes-profile",value:s.profile,onChange:T=>a(b=>({...b,profile:T.target.value})),children:[e.jsx("option",{value:"",children:t("hermes.autoProfile","Auto / use Hermes default")}),d.map(T=>e.jsxs("option",{value:T.name,children:[T.name,T.model?t("hermes.profileModelSeparator"," — {{model}}",{model:T.model}):"",T.isDefault?t("hermes.defaultProfile"," (default)"):""]},T.name))]}),e.jsx("small",{children:t("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:t("hermes.binaryPathLabel","Binary path")}),e.jsx("input",{id:"hermes-binary",type:"text",placeholder:t("hermes.binaryPathPlaceholder","hermes (defaults to PATH)"),value:s.binaryPath,onChange:T=>a(b=>({...b,binaryPath:T.target.value}))}),e.jsx("small",{children:t("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:t("hermes.modelLabel","Model override")}),e.jsx("input",{id:"hermes-model",type:"text",placeholder:t("hermes.modelPlaceholder","e.g. claude-sonnet-4-5, MiniMax-M3"),value:s.model,disabled:!!s.profile,onChange:T=>a(b=>({...b,model:T.target.value}))}),s.profile?e.jsx("small",{children:t("hermes.modelControlled","Controlled by profile: {{profile}}",{profile:s.profile})}):e.jsx("small",{children:t("hermes.modelHelp","Optional — overrides Hermes's configured default model.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"hermes-provider",children:t("hermes.providerLabel","Provider")}),e.jsx("select",{id:"hermes-provider",value:s.provider,disabled:!!s.profile,onChange:T=>a(b=>({...b,provider:T.target.value})),children:mg.map(T=>e.jsx("option",{value:T,children:T},T))}),s.profile?e.jsx("small",{children:t("hermes.providerControlled","Controlled by profile: {{profile}}",{profile:s.profile})}):e.jsx("small",{children:t("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:t("hermes.maxTurnsLabel","Max turns")}),e.jsx("input",{id:"hermes-maxTurns",type:"number",min:1,max:500,value:s.maxTurns,onChange:T=>a(b=>({...b,maxTurns:Number(T.target.value)||gt.maxTurns}))}),e.jsx("small",{children:t("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:s.yolo,onChange:T=>a(b=>({...b,yolo:T.target.checked}))}),t("hermes.yoloLabel","Auto-approve dangerous tool calls ({{flag}})",{flag:"--yolo"})]}),e.jsx("small",{children:t("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:t("hermes.timeoutLabel","CLI hard-kill timeout (ms)")}),e.jsx("input",{id:"hermes-timeoutMs",type:"number",min:1e3,step:1e3,value:s.cliTimeoutMs,onChange:T=>a(b=>({...b,cliTimeoutMs:Number(T.target.value)||gt.cliTimeoutMs}))}),e.jsx("small",{children:t("hermes.timeoutHelp","Fusion-side hard cap. Default 5 min.")})]})]})}const oa="fusion-plugin-openclaw-runtime",yg="https://docs.openclaw.ai/",vg="https://github.com/openclaw/openclaw",fi=["off","minimal","low","medium","high","xhigh","adaptive","max"],ht={binaryPath:"",agentId:"main",model:"",thinking:"off",useGateway:!1,cliTimeoutSec:0,cliTimeoutMs:3e5};function kg(t){return{binaryPath:typeof t.binaryPath=="string"?t.binaryPath:ht.binaryPath,agentId:typeof t.agentId=="string"?t.agentId:ht.agentId,model:typeof t.model=="string"?t.model:ht.model,thinking:fi.includes(t.thinking)?t.thinking:ht.thinking,useGateway:typeof t.useGateway=="boolean"?t.useGateway:ht.useGateway,cliTimeoutSec:typeof t.cliTimeoutSec=="number"?t.cliTimeoutSec:ht.cliTimeoutSec,cliTimeoutMs:typeof t.cliTimeoutMs=="number"?t.cliTimeoutMs:ht.cliTimeoutMs}}function xg(){const{t}=le("app"),[s,a]=i.useState(ht),[n,o]=i.useState(null),[d,u]=i.useState(null),[c,l]=i.useState(null),[h,p]=i.useState(!1),m=i.useRef(!0);i.useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]),i.useEffect(()=>{let K=!1;return xa().then(R=>{if(K)return;const T=R.find(b=>b.id===oa);p(T?!T.enabled:!1)}).catch(()=>{}),()=>{K=!0}},[]),i.useEffect(()=>{u("loading"),Vn(oa).then(K=>{m.current&&a(kg(K))}).catch(()=>{}).finally(()=>{m.current&&u(null)})},[]);const x=i.useCallback(async()=>{try{const K=await Id(s.binaryPath?{binaryPath:s.binaryPath}:void 0);return m.current&&o(K),K}catch(K){return m.current&&l({kind:"err",message:K instanceof Error?K.message:String(K)}),null}},[s.binaryPath]);i.useEffect(()=>{x()},[x]);const w=i.useCallback(()=>({binaryPath:s.binaryPath,agentId:s.agentId,model:s.model,thinking:s.thinking,useGateway:s.useGateway,cliTimeoutSec:s.cliTimeoutSec,cliTimeoutMs:s.cliTimeoutMs}),[s]),f=i.useCallback(async()=>{u("testing"),l(null);const K=await x();m.current&&(u(null),K?K.binary.available?l({kind:"ok",message:t("openclaw.detected","✓ openclaw detected{{version}}{{path}}.",{version:K.binary.version?` (${K.binary.version})`:"",path:K.binary.binaryPath?` at ${K.binary.binaryPath}`:""})}):l({kind:"err",message:t("openclaw.notFound",`✗ ${K.binary.reason??"openclaw not found"}`)}):l({kind:"err",message:t("openclaw.testFailed","Test failed — see status above.")}))},[x,t]),E=i.useCallback(async()=>{u("saving"),l(null);try{await rs(oa,w()),m.current&&l({kind:"ok",message:t("openclaw.saved","Settings saved.")})}catch(K){m.current&&l({kind:"err",message:K instanceof Error?K.message:String(K)})}finally{m.current&&u(null)}},[w,t]),N=i.useCallback(async()=>{u("save-test"),l(null);try{await rs(oa,w());const K=await x();if(!m.current)return;K?K.binary.available?l({kind:"ok",message:t("openclaw.savedDetected","Saved · ✓ openclaw detected{{version}}{{path}}.",{version:K.binary.version?` (${K.binary.version})`:"",path:K.binary.binaryPath?` at ${K.binary.binaryPath}`:""})}):l({kind:"err",message:t("openclaw.savedNotFound",`Saved · ✗ ${K.binary.reason??"openclaw not found"}`)}):l({kind:"err",message:t("openclaw.savedProbeFailed","Saved, but probe failed.")})}catch(K){m.current&&l({kind:"err",message:K instanceof Error?K.message:String(K)})}finally{m.current&&u(null)}},[w,x,t]),S=n?.binary,L=h?"neutral":n===null?"loading":S?.available?"ok":"err",F=h?t("openclaw.statusDisabledInPluginManager","Disabled in Plugin Manager"):n===null?t("openclaw.probing","Probing local openclaw binary…"):S?.available?t("openclaw.statusDetected","✓ Detected{{version}}{{path}}",{version:S.version?` ${S.version}`:"",path:S.binaryPath?` · ${S.binaryPath}`:""}):t("openclaw.statusNotFound",`✗ ${S?.reason??"not detected on PATH"}`);return e.jsxs(Xn,{testId:"openclaw-runtime-card",logo:e.jsx(jt,{provider:"openclaw",size:"lg"}),name:"OpenClaw",learnMoreHref:yg,statusKind:L,statusText:F,description:e.jsx(Un,{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:d,toast:c,onTest:()=>void f(),onSave:()=>void E(),onSaveAndTest:()=>void N(),belowForm:S?.available===!1?e.jsxs("div",{className:"onboarding-helper-text",children:[e.jsx("p",{children:e.jsx(Un,{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:vg,target:"_blank",rel:"noreferrer",children:t("openclaw.githubLink","openclaw on GitHub")})})]}):null,children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-binaryPath",children:t("openclaw.binaryPath","Binary path")}),e.jsx("input",{id:"openclaw-binaryPath",type:"text",placeholder:t("openclaw.binaryPathPlaceholder","openclaw (defaults to PATH)"),value:s.binaryPath,onChange:K=>a(R=>({...R,binaryPath:K.target.value}))}),e.jsx("small",{children:t("openclaw.binaryPathHint","Leave blank to resolve openclaw from your PATH.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-agentId",children:t("openclaw.agentId","Agent ID")}),e.jsx("input",{id:"openclaw-agentId",type:"text",placeholder:t("openclaw.agentIdPlaceholder","main"),value:s.agentId,onChange:K=>a(R=>({...R,agentId:K.target.value}))}),e.jsx("small",{children:t("openclaw.agentIdHint","OpenClaw agent definition to run (default: main).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-model",children:t("openclaw.model","Model override")}),e.jsx("input",{id:"openclaw-model",type:"text",placeholder:t("openclaw.modelPlaceholder","e.g. anthropic/claude-haiku-4-5, minimax/MiniMax-M3"),value:s.model,onChange:K=>a(R=>({...R,model:K.target.value}))}),e.jsx("small",{children:t("openclaw.modelHint","Optional — overrides the OpenClaw default model.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"openclaw-thinking",children:t("openclaw.thinking","Thinking level")}),e.jsx("select",{id:"openclaw-thinking",value:s.thinking,onChange:K=>a(R=>({...R,thinking:K.target.value})),children:fi.map(K=>e.jsx("option",{value:K,children:K},K))}),e.jsx("small",{children:t("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:s.useGateway,onChange:K=>a(R=>({...R,useGateway:K.target.checked}))}),t("openclaw.gateway","Route through OpenClaw gateway (otherwise embedded)")]}),e.jsx("small",{children:t("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:t("openclaw.cliTimeout","OpenClaw timeout (sec)")}),e.jsx("input",{id:"openclaw-cliTimeoutSec",type:"number",min:0,step:1,value:s.cliTimeoutSec,onChange:K=>a(R=>({...R,cliTimeoutSec:parseInt(K.target.value,10)||0}))}),e.jsx("small",{children:t("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:t("openclaw.subprocess","CLI subprocess timeout (ms)")}),e.jsx("input",{id:"openclaw-cliTimeoutMs",type:"number",min:0,step:1e3,value:s.cliTimeoutMs,onChange:K=>a(R=>({...R,cliTimeoutMs:parseInt(K.target.value,10)||ht.cliTimeoutMs}))}),e.jsx("small",{children:t("openclaw.subprocessHint","Fusion-side hard cap before the CLI subprocess is killed (default: {{default}}s).",{default:ht.cliTimeoutMs/1e3})})]})]})}const ca="fusion-plugin-paperclip-runtime",Ur="https://paperclip.ing/",jg="https://github.com/paperclipai/paperclip",Wr=[{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."}],et={transport:"api",apiUrl:"http://localhost:3100",apiKey:"",cliBinaryPath:"paperclipai",cliConfigPath:"",agentId:"",companyId:"",mode:"rolling-issue",parentIssueId:"",projectId:"",goalId:"",runTimeoutMs:6e5},wg=new Set(["issue-per-prompt","rolling-issue","wakeup-only"]);function Cg(t){const s=(d,u)=>typeof t[d]=="string"?t[d]:u,a=(d,u)=>typeof t[d]=="number"?t[d]:u,n=t.transport==="cli"?"cli":"api",o=wg.has(t.mode)?t.mode:et.mode;return{transport:n,apiUrl:s("apiUrl",et.apiUrl),apiKey:s("apiKey",et.apiKey),cliBinaryPath:s("cliBinaryPath",et.cliBinaryPath),cliConfigPath:s("cliConfigPath",et.cliConfigPath),agentId:s("agentId",et.agentId),companyId:s("companyId",et.companyId),mode:o,parentIssueId:s("parentIssueId",et.parentIssueId),projectId:s("projectId",et.projectId),goalId:s("goalId",et.goalId),runTimeoutMs:a("runTimeoutMs",et.runTimeoutMs)}}function Sg(){const{t}=le("app"),[s,a]=i.useState(et),[n,o]=i.useState(null),[d,u]=i.useState(null),[c,l]=i.useState([]),[h,p]=i.useState([]),[m,x]=i.useState(null),[w,f]=i.useState(null),[E,N]=i.useState(!1),[S,L]=i.useState(!1),F=i.useRef(!0);i.useEffect(()=>(F.current=!0,()=>{F.current=!1}),[]),i.useEffect(()=>{let j=!1;return xa().then(W=>{if(j)return;const ce=W.find(Ie=>Ie.id===ca);L(ce?!ce.enabled:!1)}).catch(()=>{}),()=>{j=!0}},[]);const K=i.useMemo(()=>s.transport==="cli"&&d&&d.ok?{apiUrl:d.apiUrl,apiKey:s.apiKey||d.apiKey||void 0}:{apiUrl:s.apiUrl,apiKey:s.apiKey||void 0},[s.transport,s.apiUrl,s.apiKey,d]);i.useEffect(()=>{x("loading"),Vn(ca).then(j=>{F.current&&a(Cg(j))}).catch(()=>{}).finally(()=>{F.current&&x(null)})},[]),i.useEffect(()=>{if(s.transport!=="cli"){u(null);return}let j=!1;return Td({cliConfigPath:s.cliConfigPath||void 0}).then(W=>{!j&&F.current&&u(W)}).catch(()=>{!j&&F.current&&u({ok:!1,reason:"Discovery request failed"})}),()=>{j=!0}},[s.transport,s.cliConfigPath]);const R=s.transport==="cli",T=i.useMemo(()=>({cliBinaryPath:s.cliBinaryPath||void 0,cliConfigPath:s.cliConfigPath||void 0}),[s.cliBinaryPath,s.cliConfigPath]),b=i.useCallback(async()=>{if(!R&&!K.apiUrl)return null;try{const j=R?await Ad(T):await Md(K);F.current&&o(j);const W=R?await Rd(T):await Ed(K);if(!F.current)return j;l(W);let ce=s.companyId;if(W.some(Ie=>Ie.id===ce)||(ce=j.connection.identity?.companyId??W[0]?.id??"",ce&&ce!==s.companyId&&a(Ie=>({...Ie,companyId:ce}))),ce){const Ie=R?await sr({...T,companyId:ce}):await ar({...K,companyId:ce});if(F.current&&(p(Ie),!Ie.some(Oe=>Oe.id===s.agentId))){const Oe=j.connection.identity?.agentId??Ie[0]?.id??"";Oe&&Oe!==s.agentId&&a(H=>({...H,agentId:Oe}))}}else F.current&&p([]);return j}catch(j){return F.current&&f({kind:"err",message:j instanceof Error?j.message:String(j)}),null}},[R,T,K.apiUrl,K.apiKey,s.companyId,s.agentId]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{if(!s.companyId){p([]);return}if(!R&&!K.apiUrl){p([]);return}let j=!1;return(R?sr({...T,companyId:s.companyId}):ar({...K,companyId:s.companyId})).then(ce=>{!j&&F.current&&p(ce)}).catch(()=>{!j&&F.current&&p([])}),()=>{j=!0}},[R,T,K.apiUrl,K.apiKey,s.companyId]);const V=i.useCallback(()=>{const j={transport:s.transport,mode:s.mode,parentIssueId:s.parentIssueId,projectId:s.projectId,goalId:s.goalId,runTimeoutMs:s.runTimeoutMs,agentId:s.agentId,companyId:s.companyId};return s.transport==="api"?j.apiUrl=s.apiUrl:(j.cliBinaryPath=s.cliBinaryPath,s.cliConfigPath&&(j.cliConfigPath=s.cliConfigPath)),E&&(j.apiKey=s.apiKey),j},[s,E]),X=i.useCallback(async()=>{x("testing"),f(null);const j=await b();if(F.current)if(x(null),!j)s.transport==="cli"&&d&&!d.ok?f({kind:"err",message:t("paperclip.cliDiscoveryFailed","✗ CLI discovery failed: {{reason}}",{reason:d.reason})}):f({kind:"err",message:t("paperclip.testFailed","Test failed — see status above.")});else if(j.connection.available){const W=j.connection.identity;f({kind:"ok",message:W?t("paperclip.connectedAsAgent","✓ Connected as {{agentName}}{{companyInfo}}.",{agentName:W.agentName,companyInfo:W.companyName?` at ${W.companyName}`:""}):t("paperclip.connected","✓ Connected.")})}else f({kind:"err",message:t("paperclip.unreachable","✗ {{reason}}",{reason:j.connection.reason??"Paperclip server unreachable"})})},[b,s.transport,d,t]),k=i.useCallback(async()=>{x("saving"),f(null);try{await rs(ca,V()),F.current&&(f({kind:"ok",message:t("paperclip.settingsSaved","Settings saved.")}),N(!1))}catch(j){F.current&&f({kind:"err",message:j instanceof Error?j.message:String(j)})}finally{F.current&&x(null)}},[V,t]),I=i.useCallback(async()=>{x("save-test"),f(null);try{await rs(ca,V()),F.current&&N(!1);const j=await b();if(!F.current)return;if(!j)s.transport==="cli"&&d&&!d.ok?f({kind:"err",message:t("paperclip.savedCliDiscoveryFailed","Saved · ✗ CLI discovery failed: {{reason}}",{reason:d.reason})}):f({kind:"err",message:t("paperclip.savedProbeFailed","Saved, but probe failed.")});else if(j.connection.available){const W=j.connection.identity;f({kind:"ok",message:W?t("paperclip.savedConnectedAsAgent","Saved · ✓ Connected as {{agentName}}{{companyInfo}}.",{agentName:W.agentName,companyInfo:W.companyName?` at ${W.companyName}`:""}):t("paperclip.savedConnected","Saved · ✓ Connected.")})}else f({kind:"err",message:t("paperclip.savedUnreachable","Saved · ✗ {{reason}}",{reason:j.connection.reason??"Paperclip server unreachable"})})}catch(j){F.current&&f({kind:"err",message:j instanceof Error?j.message:String(j)})}finally{F.current&&x(null)}},[V,b,s.transport,d,t]),B=n?.connection.available??null,v=n?.connection.identity,M=d?.ok===!0,se=S?"neutral":n===null?"loading":B?"ok":"err",ne=S?t("paperclip.statusDisabledInPluginManager","Disabled in Plugin Manager"):n===null?s.transport==="cli"&&d&&!M?t("paperclip.statusCliDiscoveryFailed","✗ CLI discovery failed: {{reason}}",{reason:d.reason}):t("paperclip.statusProbing","Probing Paperclip server…"):B?v?t("paperclip.statusConnectedAs","✓ Connected as {{agentName}}{{roleInfo}}{{companyInfo}}",{agentName:v.agentName,roleInfo:v.role?` (${v.role})`:"",companyInfo:v.companyName?` at ${v.companyName}`:""}):t("paperclip.statusConnected","✓ Connected"):t("paperclip.statusUnreachable","✗ {{reason}}",{reason:n.connection.reason??"Unreachable"}),pe=e.jsxs("div",{className:"runtime-card__tabs",role:"tablist","aria-label":t("paperclip.connectionModeAriaLabel","Paperclip connection mode"),children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s.transport==="api",className:"runtime-card__tab",onClick:()=>a(j=>({...j,transport:"api"})),children:t("paperclip.tabApi","API (URL + token)")}),e.jsx("button",{type:"button",role:"tab","aria-selected":s.transport==="cli",className:"runtime-card__tab",onClick:()=>a(j=>({...j,transport:"cli"})),children:t("paperclip.tabCliAutoDerve","Local CLI (auto-derive)")})]});return e.jsxs(Xn,{testId:"paperclip-runtime-card",logo:e.jsx(jt,{provider:"paperclip",size:"lg"}),name:t("paperclip.name","Paperclip"),learnMoreHref:Ur,statusKind:se,statusText:ne,description:e.jsx(e.Fragment,{children:t("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:pe,busy:m,toast:w,onTest:()=>void X(),onSave:()=>void k(),onSaveAndTest:()=>void I(),belowForm:B===!1?e.jsxs("div",{className:"onboarding-helper-text",children:[e.jsx("p",{children:t("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:Ur,target:"_blank",rel:"noreferrer",children:t("paperclip.docsLink","Paperclip docs")})," ","·"," ",e.jsx("a",{href:jg,target:"_blank",rel:"noreferrer",children:t("paperclip.githubLink","GitHub")})]})]}):null,children:[s.transport==="cli"&&d&&e.jsx("div",{className:"settings-muted",style:{marginBottom:"var(--space-sm)"},children:M?e.jsxs("small",{children:[t("paperclip.cliConfigLabel","CLI config:")," ",e.jsx("code",{children:d.configPath})," ","· ",t("paperclip.resolved","resolved")," ",e.jsx("code",{children:d.apiUrl}),d.deploymentMode?` · ${d.deploymentMode}`:""]}):e.jsx("small",{children:t("paperclip.cliDiscoveryFailedLabel","CLI discovery failed: {{reason}}",{reason:d.reason})})}),s.transport==="api"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-apiUrl",children:t("paperclip.apiUrlLabel","API URL")}),e.jsx("input",{id:"paperclip-apiUrl",type:"text",placeholder:"http://localhost:3100",value:s.apiUrl,onChange:j=>a(W=>({...W,apiUrl:j.target.value}))}),e.jsx("small",{children:t("paperclip.apiUrlHelp","Base URL of the Paperclip server.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-apiKey",children:t("paperclip.apiKeyLabel","API key")}),e.jsx("input",{id:"paperclip-apiKey",type:"password",placeholder:E?"":t("paperclip.apiKeyPlaceholder","•••••••• (leave blank to keep existing)"),value:s.apiKey,onChange:j=>{a(W=>({...W,apiKey:j.target.value})),N(!0)}}),e.jsx("small",{children:t("paperclip.apiKeyHelp","Agent API key. Local-trusted deployments may leave this blank.")})]})]}),s.transport==="cli"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-cliBinaryPath",children:t("paperclip.cliBinaryLabel","paperclipai binary")}),e.jsx("input",{id:"paperclip-cliBinaryPath",type:"text",placeholder:"paperclipai",value:s.cliBinaryPath,onChange:j=>a(W=>({...W,cliBinaryPath:j.target.value}))}),e.jsx("small",{children:t("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:t("paperclip.cliConfigPathLabel","Instance config path")}),e.jsx("input",{id:"paperclip-cliConfigPath",type:"text",placeholder:"~/.paperclip/instances/default/config.json",value:s.cliConfigPath,onChange:j=>a(W=>({...W,cliConfigPath:j.target.value}))}),e.jsx("small",{children:t("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:t("paperclip.cliApiKeyLabel","API key (override, optional)")}),e.jsx("input",{id:"paperclip-cli-apikey",type:"password",placeholder:E?"":t("paperclip.cliApiKeyPlaceholder","Optional — only required for non-local-trusted modes"),value:s.apiKey,onChange:j=>{a(W=>({...W,apiKey:j.target.value})),N(!0)}}),e.jsx("small",{children:t("paperclip.cliApiKeyHelp","Local-trusted deployments do not require a key.")}),n!==null&&B===!1&&s.agentId&&e.jsx("button",{type:"button",className:"btn btn--sm",style:{marginTop:"0.4rem"},disabled:m!==null,onClick:async()=>{const j=s.agentId,W=s.companyId.trim();if(!j||!W){f({kind:"err",message:t("paperclip.companyIdRequired","✗ Company ID is required to mint a Paperclip API key.")});return}x("testing"),f(null);const ce=await Dd({cliBinaryPath:s.cliBinaryPath||void 0,agentRef:j,companyId:W,keyName:"fusion-runtime",configPath:s.cliConfigPath||void 0});F.current&&(x(null),ce.ok?(a(Ie=>({...Ie,apiKey:ce.key.apiKey})),N(!0),f({kind:"ok",message:t("paperclip.apiKeyMinted","✓ API key minted via paperclipai (key 'fusion-runtime' installed for agent {{agentId}}). Click Save to persist.",{agentId:j})}),b()):f({kind:"err",message:t("paperclip.mintFailed","✗ Mint failed: {{reason}}. Run `paperclipai onboard` first if your CLI isn't authenticated.",{reason:ce.reason})}))},children:t("paperclip.mintButton","✨ Mint API key via paperclipai")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-companyId",children:t("paperclip.companyLabel","Company")}),e.jsx("select",{id:"paperclip-companyId",value:s.companyId,onChange:j=>a(W=>({...W,companyId:j.target.value})),disabled:c.length===0,children:c.length===0?e.jsx("option",{value:"",children:B?t("paperclip.noCompaniesDiscovered","No companies discovered"):t("paperclip.connectToPopulate","Connect to populate")}):c.map(j=>e.jsxs("option",{value:j.id,children:[j.name," (",j.id,")"]},j.id))}),e.jsx("small",{children:t("paperclip.companyHelp","Select a Paperclip company.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-agentId",children:t("paperclip.agentLabel","Agent")}),e.jsx("select",{id:"paperclip-agentId",value:s.agentId,onChange:j=>a(W=>({...W,agentId:j.target.value})),disabled:h.length===0,children:h.length===0?e.jsx("option",{value:"",children:s.companyId?t("paperclip.noAgentsDiscovered","No agents discovered"):t("paperclip.pickCompanyFirst","Pick a company first")}):h.map(j=>e.jsxs("option",{value:j.id,children:[j.name,j.role?` (${j.role})`:""]},j.id))}),e.jsx("small",{children:t("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:t("paperclip.modeLabel","Conversation mode")}),e.jsx("select",{id:"paperclip-mode",value:s.mode,onChange:j=>a(W=>({...W,mode:j.target.value})),children:Wr.map(j=>e.jsx("option",{value:j.value,children:t(`paperclip.mode.${j.value}`,j.label)},j.value))}),e.jsx("small",{children:t(`paperclip.modeHelp.${s.mode}`,Wr.find(j=>j.value===s.mode)?.help??"")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-projectId",children:t("paperclip.projectIdLabel","Project ID (optional)")}),e.jsx("input",{id:"paperclip-projectId",type:"text",placeholder:t("paperclip.optionalPlaceholder","Optional"),value:s.projectId,onChange:j=>a(W=>({...W,projectId:j.target.value}))}),e.jsx("small",{children:t("paperclip.projectIdHelp","Pin work to a specific Paperclip project.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-parentIssueId",children:t("paperclip.parentIssueIdLabel","Parent issue ID (optional)")}),e.jsx("input",{id:"paperclip-parentIssueId",type:"text",placeholder:t("paperclip.optionalPlaceholder","Optional"),value:s.parentIssueId,onChange:j=>a(W=>({...W,parentIssueId:j.target.value}))}),e.jsx("small",{children:t("paperclip.parentIssueIdHelp","Scope work under an existing parent issue.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-goalId",children:t("paperclip.goalIdLabel","Goal ID (optional)")}),e.jsx("input",{id:"paperclip-goalId",type:"text",placeholder:t("paperclip.optionalPlaceholder","Optional"),value:s.goalId,onChange:j=>a(W=>({...W,goalId:j.target.value}))}),e.jsx("small",{children:t("paperclip.goalIdHelp","Associate work with a Paperclip goal.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"paperclip-runTimeoutMs",children:t("paperclip.runTimeoutLabel","Run timeout (ms)")}),e.jsx("input",{id:"paperclip-runTimeoutMs",type:"number",min:0,step:1e3,value:s.runTimeoutMs,onChange:j=>a(W=>({...W,runTimeoutMs:parseInt(j.target.value,10)||et.runTimeoutMs}))}),e.jsx("small",{children:t("paperclip.runTimeoutHelp","Local cap before Fusion gives up on a Paperclip run.")})]})]})}function Ng(){const{t}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:t("settings.runtimesRuntimes.hermesRuntime","Hermes Runtime")}),e.jsx(fg,{})]})}function Pg(){const{t}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:t("settings.runtimesRuntimes.openClawRuntime","OpenClaw Runtime")}),e.jsx(xg,{})]})}function Ig(){const{t}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:t("settings.runtimesRuntimes.paperclipRuntime","Paperclip Runtime")}),e.jsx(Sg,{})]})}function Tg({addToast:t,projectId:s}){const{t:a}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.nav.secrets","Secrets")}),e.jsx(zu,{addToast:t,projectId:s})]})}const as=[{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}],Ag={"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:"Explicit full system-prompt replacement for Planning Mode's dedicated collaborative prompt",defaultContent:"Runtime default: a dedicated collaborative Planning Mode prompt with a user-validated JSON interview."},"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..."}},$r=["executor","triage","reviewer","merger"],Mg={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"}},Ps=t=>`prompt-role-tone--${t}`,An={name:"",description:"",role:"executor",prompt:""};function Rg(t,s){const a=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),n=new Set(as.map(u=>u.id)),o=new Set(s.map(u=>u.id));if(!n.has(a)&&!o.has(a))return a;let d=2;for(;n.has(`${a}-${d}`)||o.has(`${a}-${d}`);)d++;return`${a}-${d}`}function Eg({value:t,onChange:s,promptOverrides:a,onPromptOverridesChange:n}){const{t:o}=le("app"),d=D=>{const U=Mg[D];return o(U.key,U.defaultValue)},[u,c]=i.useState("templates"),[l,h]=i.useState(null),[p,m]=i.useState(!1),[x,w]=i.useState(An),[f,E]=i.useState(null),[N,S]=i.useState(null),[L,F]=i.useState(new Set),[K,R]=i.useState(null),[T,b]=i.useState(!1),[V,X]=i.useState(null),k=i.useRef(null),I=t?.templates??[],B=t?.roleAssignments??{},v=V===null?null:V.source==="builtin"?as.find(D=>D.id===V.id):I.find(D=>D.id===V.id),M=i.useCallback(D=>{const U=as.filter(ke=>ke.role===D),te=I.filter(ke=>ke.role===D);return[...U,...te]},[I]);i.useEffect(()=>{V!==null&&k.current?.focus()},[V]);const se=i.useCallback(()=>{m(!0),h(null),w(An),E(null),X(null)},[]),ne=i.useCallback(D=>{h(D.id),m(!1),w({name:D.name,description:D.description,role:D.role,prompt:D.prompt}),E(null),X(null)},[]),pe=i.useCallback(()=>{h(null),m(!1),w(An),E(null),X(null),b(!1)},[]),j=i.useCallback(()=>{const D=x.name.trim();if(!D){E(o("agentPrompts.errors.nameRequired","Template name is required"));return}let U;if(p){if(U=Rg(D,I),new Set(as.map($=>$.id)).has(U)){E(o("agentPrompts.errors.idConflict",'Template ID "{{templateId}}" conflicts with a built-in template. Please use a different name.',{templateId:U}));return}}else U=l;const te={id:U,name:D,description:x.description.trim(),role:x.role,prompt:x.prompt,builtIn:!1};let ke;p?ke=[...I,te]:ke=I.map(re=>re.id===U?te:re);const Ne={...B};for(const[re,$]of Object.entries(Ne))$===U&&x.role!==re&&delete Ne[re];s({...t,templates:ke,roleAssignments:Object.keys(Ne).length>0?Ne:void 0}),pe()},[x,p,l,I,B,t,s,pe]),W=i.useCallback(D=>{const U=I.filter(Ne=>Ne.id!==D),te={...B};let ke=!1;for(const[Ne,re]of Object.entries(te))re===D&&(delete te[Ne],ke=!0);s({...t,templates:U.length>0?U:void 0,roleAssignments:Object.keys(te).length>0||ke?Object.keys(te).length>0?te:void 0:B}),S(null),l===D&&pe()},[I,B,t,s,l,pe]),ce=i.useCallback((D,U)=>{const te={...B};U===""?delete te[D]:te[D]=U,s({...t,roleAssignments:Object.keys(te).length>0?te:void 0})},[B,t,s]),Ie=i.useCallback((D,U)=>{const te={...a};te[D]=U||null,n(te)},[a,n]),Oe=i.useCallback(D=>{const U={...a};U[D]=null,n(U)},[a,n]),H=i.useCallback(D=>{F(U=>{const te=new Set(U);return te.has(D)?te.delete(D):te.add(D),te})},[]),Z=i.useCallback(D=>{R(U=>U===D?null:D)},[]),Te=i.useCallback((D,U)=>{b(!1),X({source:D,id:U})},[]),_e=i.useCallback(()=>{X(null),b(D=>!D)},[]),Ke=D=>as.some(U=>U.id===D);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 ${u==="templates"?"active":""}`,onClick:()=>c("templates"),"data-testid":"tab-templates",children:[e.jsx(qu,{size:14}),o("agentPrompts.tabs.templates","Templates")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${u==="assignments"?"active":""}`,onClick:()=>c("assignments"),"data-testid":"tab-assignments",children:[e.jsx(Yu,{size:14}),o("agentPrompts.tabs.assignments","Assignments")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${u==="overrides"?"active":""}`,onClick:()=>c("overrides"),"data-testid":"tab-overrides",children:[e.jsx(Ju,{size:14}),o("agentPrompts.tabs.overrides","Overrides")]})]}),e.jsxs("div",{className:"prompt-manager-content",children:[u==="templates"&&e.jsxs("div",{className:"prompt-manager-templates-tab","data-testid":"templates-tab",children:[(p||l!==null)&&e.jsxs("div",{className:"prompt-template-editor","data-testid":"template-editor",children:[e.jsx("h4",{className:"prompt-template-editor-title",children:p?o("agentPrompts.editor.newTemplate","New Custom Template"):o("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:o("agentPrompts.labels.name","Name")}),e.jsx("input",{id:"template-name",type:"text",value:x.name,onChange:D=>w(U=>({...U,name:D.target.value})),placeholder:o("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:o("agentPrompts.labels.description","Description")}),e.jsx("input",{id:"template-description",type:"text",value:x.description,onChange:D=>w(U=>({...U,description:D.target.value})),placeholder:o("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:o("agentPrompts.labels.role","Role")}),e.jsx("select",{id:"template-role",value:x.role,onChange:D=>w(U=>({...U,role:D.target.value})),"data-testid":"template-role-select",children:$r.map(D=>e.jsx("option",{value:D,children:d(D)},D))})]}),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:o("agentPrompts.labels.prompt","Prompt")}),e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:_e,"aria-label":o("agentPrompts.ariaLabels.expandPrompt","Expand prompt to fullscreen"),"data-testid":"template-prompt-fullscreen",children:e.jsx(sa,{size:14})})]}),T?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:D=>{D.key==="Escape"&&(D.preventDefault(),b(!1))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsx("div",{className:"prompt-override-fullscreen-title",children:o("agentPrompts.titles.editPrompt","Edit Prompt")}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>b(!1),"data-testid":"template-prompt-collapse",children:[e.jsx(mn,{size:14}),o("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:"template-prompt-fullscreen","aria-label":o("agentPrompts.ariaLabels.templatePromptFullscreen","Template prompt - fullscreen"),className:"prompt-template-prompt-textarea",value:x.prompt,onChange:D=>w(U=>({...U,prompt:D.target.value})),placeholder:o("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:o("agents.charactersCount","{{count}} characters",{count:x.prompt.length})})})]}):e.jsx("textarea",{id:"template-prompt",value:x.prompt,onChange:D=>w(U=>({...U,prompt:D.target.value})),placeholder:o("agentPrompts.placeholders.prompt","Enter the system prompt for this template..."),rows:8,className:"prompt-template-prompt-textarea","data-testid":"template-prompt-input"})]}),f&&e.jsx("div",{className:"prompt-template-error","data-testid":"template-error",children:f}),e.jsxs("div",{className:"prompt-template-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:pe,"data-testid":"cancel-template-btn",children:o("agentPrompts.actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:j,"data-testid":"save-template-btn",children:p?o("agentPrompts.actions.create","Create"):o("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:o("agentPrompts.sections.builtinTemplates","Built-in Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:o("agentPrompts.descriptions.builtinTemplates","These templates are provided by Fusion and cannot be modified.")}),e.jsx("div",{className:"prompt-template-list",children:as.map(D=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${D.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:D.name}),e.jsx("span",{className:`prompt-template-badge-built-in ${Ps(D.role)}`,children:o("agentPrompts.badges.builtin","Built-in")}),e.jsx("span",{className:`prompt-template-badge-role ${Ps(D.role)}`,children:d(D.role)})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>Te("builtin",D.id),title:o("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":o("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:D.name}),"data-testid":`expand-view-${D.id}`,children:e.jsx(sa,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:D.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:D.prompt})})]},D.id))})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"custom-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:o("agentPrompts.sections.customTemplates","Custom Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:o("agentPrompts.descriptions.customTemplates","Create custom templates to override built-in prompts for specific roles.")}),I.length===0&&!p&&e.jsx("div",{className:"prompt-template-empty",children:o("agentPrompts.emptyStates.noCustomTemplates","No custom templates yet. Create one to get started.")}),I.length>0&&e.jsx("div",{className:"prompt-template-list",children:I.map(D=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${D.id}`,children:N===D.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsx("p",{children:o("agentPrompts.confirmations.deleteTemplate",'Delete "{{name}}"?',{name:D.name})}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>W(D.id),"data-testid":`confirm-delete-${D.id}`,children:o("agentPrompts.actions.delete","Delete")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>S(null),"data-testid":`cancel-delete-${D.id}`,children:o("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:D.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:o("agentPrompts.badges.custom","Custom")}),e.jsx("span",{className:`prompt-template-badge-role ${Ps(D.role)}`,children:d(D.role)}),Ke(D.id)&&e.jsx("span",{className:"prompt-template-badge-override",children:o("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:()=>Te("custom",D.id),title:o("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":o("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:D.name}),"data-testid":`expand-view-${D.id}`,children:e.jsx(sa,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>ne(D),title:o("agentPrompts.titles.edit","Edit"),"aria-label":o("agentPrompts.ariaLabels.editTemplate","Edit {{name}}",{name:D.name}),"data-testid":`edit-${D.id}`,children:e.jsx(ya,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>S(D.id),title:o("agentPrompts.titles.delete","Delete"),"aria-label":o("agentPrompts.ariaLabels.deleteTemplate","Delete {{name}}",{name:D.name}),"data-testid":`delete-${D.id}`,children:e.jsx(va,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:D.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:D.prompt})})]})},D.id))}),!p&&l===null&&e.jsxs("button",{type:"button",className:"btn btn-primary prompt-template-add-btn",onClick:se,"data-testid":"add-template-btn",children:[e.jsx(fa,{size:14}),o("agentPrompts.actions.addCustomTemplate","Add Custom Template")]})]}),v&&e.jsxs("div",{ref:k,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:D=>{D.key==="Escape"&&(D.preventDefault(),X(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[v.name,e.jsx("span",{className:`prompt-template-badge-role ${Ps(v.role)}`,children:d(v.role)})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>X(null),"data-testid":`collapse-view-${v.id}`,children:[e.jsx(mn,{size:14}),o("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:v.prompt})]})]}),u==="assignments"&&e.jsxs("div",{className:"prompt-manager-assignments-tab","data-testid":"assignments-tab",children:[e.jsx("p",{className:"prompt-assignments-desc",children:o("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:$r.map(D=>{const U=M(D),te=B[D]??"",ke=U.find(re=>re.id===te),Ne=!!te;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${D}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:`prompt-role-badge ${Ps(D)}`,children:d(D)}),Ne&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[ke?.name??o("agentPrompts.labels.custom","Custom")," (",o("agentPrompts.labels.overridesDefault","overrides default"),")"]})]}),e.jsxs("select",{className:"prompt-role-select",value:te,onChange:re=>ce(D,re.target.value),"data-testid":`select-${D}`,children:[e.jsx("option",{value:"",children:o("agentPrompts.options.useDefault","Use default")}),U.map(re=>e.jsxs("option",{value:re.id,children:[re.name,Ke(re.id)?` (${o("agentPrompts.labels.builtIn","built-in")})`:` (${o("agentPrompts.labels.custom","custom")})`]},re.id))]})]},D)})}),Object.keys(B).length>0&&e.jsxs("div",{className:"prompt-assignments-note",children:[e.jsxs("strong",{children:[o("agentPrompts.labels.note","Note"),":"]})," ",o("agentPrompts.descriptions.assignmentNote","Role assignments are stored in the agentPrompts configuration. Custom templates override built-ins by ID.")]})]}),u==="overrides"&&e.jsxs("div",{className:"prompt-manager-overrides-tab","data-testid":"overrides-tab",children:[e.jsx("p",{className:"prompt-overrides-desc",children:o("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(Ag).map(D=>{const U=D.key,te=a?.[U]??"",ke=te!=="",Ne=L.has(U);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${U}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("button",{type:"button",className:"prompt-override-info",onClick:()=>H(U),children:[e.jsx("span",{className:"prompt-override-name",children:D.name}),e.jsx("code",{className:"prompt-override-key",children:U}),ke&&e.jsx("span",{className:"prompt-override-badge",children:o("agentPrompts.badges.customized","customized")})]}),e.jsxs("div",{className:"prompt-override-header-actions",children:[Ne&&e.jsx("button",{type:"button",className:"prompt-override-fullscreen-btn",onClick:re=>{re.stopPropagation(),Z(U)},"aria-label":o("agentPrompts.ariaLabels.expandToFullscreen","Expand to fullscreen"),"data-testid":`fullscreen-${U}`,children:e.jsx(sa,{size:14})}),e.jsx("button",{type:"button",className:"prompt-override-expand-btn","aria-label":Ne?o("agentPrompts.ariaLabels.collapse","Collapse"):o("agentPrompts.ariaLabels.expand","Expand"),"data-testid":`expand-${U}`,onClick:re=>{re.stopPropagation(),H(U)},children:Ne?e.jsx(Fd,{size:16}):e.jsx(Ld,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:D.description}),Ne&&(K===U?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:re=>{re.key==="Escape"&&(re.preventDefault(),R(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[D.name,e.jsx("code",{className:"prompt-override-key",children:U})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>R(null),"data-testid":`collapse-fullscreen-${U}`,children:[e.jsx(mn,{size:14}),o("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:`prompt-${U}-fullscreen`,"aria-label":o("agentPrompts.ariaLabels.promptOverrideFullscreen","{{name}} prompt override ({{key}}) - fullscreen",{name:D.name,key:U}),className:"prompt-override-textarea",value:te,onChange:re=>{Ie(U,re.target.value)},placeholder:`Default: ${D.defaultContent.slice(0,100)}${D.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${U}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ke&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>Oe(U),"data-testid":`reset-fullscreen-${U}`,children:o("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ke?o("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):o("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:D.defaultContent.length})})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${U}`,"aria-label":o("agentPrompts.ariaLabels.promptOverride","{{name}} prompt override ({{key}})",{name:D.name,key:U}),className:"prompt-override-textarea",value:te,onChange:re=>{Ie(U,re.target.value)},placeholder:o("agentPrompts.placeholders.promptDefault","Default: {{preview}}",{preview:D.defaultContent.slice(0,100)+(D.defaultContent.length>100?"...":"")}),rows:4,"data-testid":`override-input-${U}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ke&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:re=>{re.stopPropagation(),Oe(U)},"data-testid":`reset-${U}`,children:o("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ke?o("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):o("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:D.defaultContent.length})})]})]}))]},U)})})]})]})]})}function Zn({message:t,onOpenWorkflowSettings:s}){const{t:a}=le("app");return e.jsxs("div",{className:"settings-moved-stub",role:"note",children:[e.jsx("p",{className:"settings-moved-stub__message",children:t}),e.jsx("button",{type:"button",className:"settings-moved-stub__action",onClick:s,disabled:!s,children:a("settings.movedStub.openWorkflowSettings","Open workflow settings")})]})}function Dg({form:t,setForm:s,onOpenWorkflowSettings:a}){const{t:n}=le("app");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading",children:n("settings.nav.prompts","Prompts")}),e.jsx(G,{settingKey:"prompts-section",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(Zn,{message:n("settings.prompts.workflowPromptsRedirect","Per-workflow step prompts for prompt and gate nodes live in the Workflow Editor."),onOpenWorkflowSettings:a}),e.jsx(Eg,{value:t.agentPrompts,onChange:o=>{s(d=>({...d,agentPrompts:o}))},promptOverrides:t.promptOverrides,onPromptOverridesChange:o=>{s(d=>({...d,promptOverrides:o}))}})]})}function Fg({form:t,setForm:s,projectId:a,addToast:n,prefixError:o,setPrefixError:d,onQuickChatButtonModeChange:u,onMobileNavPrimaryItemsChange:c}){const{t:l}=le("app"),[h,p]=i.useState([]),[m,x]=i.useState(null),[w,f]=i.useState([]),E=typeof window>"u"?void 0:Hu(window.location);i.useEffect(()=>{let k=!1;return _u().then(I=>{k||f(Array.isArray(I.categories)?I.categories:[])}).catch(()=>{k||f([])}),()=>{k=!0}},[]),i.useEffect(()=>{let k=!1;return nr(a,{includeDisabledBuiltins:!0}).then(I=>{k||p(I.filter(B=>B.id.startsWith("builtin:")&&B.kind!=="fragment"&&!Od.has(B.id)))}).catch(()=>{k||p([])}),()=>{k=!0}},[a]);const[N,S]=i.useState([]);i.useEffect(()=>{let k=!1;return nr(a).then(I=>{k||S(I.filter(B=>B.kind!=="fragment"))}).catch(()=>{k||S([])}),()=>{k=!0}},[a]);const L=k=>k===""||N.some(I=>I.id===k),F=t.aiUndoTaskWorkflowId??"builtin:review-heavy",K=L(F),R=t.taskCreateWorkflowId??"",T=t.refinementTaskWorkflowId??"",b=i.useMemo(()=>{const k=Array.isArray(t.enabledBuiltinWorkflowIds)?t.enabledBuiltinWorkflowIds:void 0;return new Set(k??h.map(I=>I.id))},[h,t.enabledBuiltinWorkflowIds]),V=(k,I)=>{s(B=>{const v=h.map(ne=>ne.id),M=new Set(Array.isArray(B.enabledBuiltinWorkflowIds)?B.enabledBuiltinWorkflowIds:v);I?M.add(k):M.delete(k);const se=v.filter(ne=>M.has(ne));return{...B,enabledBuiltinWorkflowIds:se.length===v.length?void 0:se}})},X=()=>{window.confirm(l("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."))&&(Ud(),window.location.reload())};return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:l("settings.general.general","General")}),e.jsx(As,{htmlFor:"report-action-menu",label:l("settings.general.report","Report"),help:l("settings.general.reportHelp","Report a bug, send feedback, share an idea, or get help from Fusion."),scope:"project",children:e.jsx(Uu,{onSelect:x})}),e.jsx(Pe,{descriptor:{key:"maxRecommendationsPerTask",label:l("settings.general.maxRecommendationsPerTask","Maximum recommendations per task"),help:l("settings.general.maxRecommendationsPerTaskHelp","Default: 3. Set 0 to disable recommendations; choose a whole number from 1 to 20 to cap each completed task."),scope:"project",min:0,max:20,placeholder:"3"},value:t.maxRecommendationsPerTask??3,onChange:k=>s(I=>({...I,maxRecommendationsPerTask:k??3}))}),e.jsx(ae,{descriptor:{key:"recommendationMailboxNoticeEnabled",label:l("settings.general.recommendationMailboxNoticeEnabled","Recommendation mailbox notices"),help:l("settings.general.recommendationMailboxNoticeEnabledHelp","Default: enabled. When a completed task captures recommendations, send a summary to your mailbox. Turning this off does not change whether recommendations are captured."),scope:"project"},value:t.recommendationMailboxNoticeEnabled!==!1,onChange:k=>s(I=>({...I,recommendationMailboxNoticeEnabled:k===!0}))}),e.jsx(be,{descriptor:{key:"taskPrefix",label:l("settings.general.taskPrefix","Task Prefix"),help:l("settings.general.prefixForNewTaskIDsEGKB","Prefix for new task IDs (e.g. KB, PROJ). No default — unset."),scope:"project",placeholder:l("settings.general.fN","FN")},value:t.taskPrefix||"",onChange:k=>{const I=k??"";s(B=>({...B,taskPrefix:I||void 0})),I&&!/^[A-Z]{1,5}$/.test(I)?d(l("settings.general.prefixMustBe15UppercaseLetters","Prefix must be 1–5 uppercase letters")):d(null)},error:o??void 0}),e.jsxs("div",{className:"form-group",children:[e.jsx(Kd,{projectId:a,addToast:n}),e.jsx(G,{settingKey:"projectDefaultWorkflow",children:l("settings.general.newTasksInheritThisCustomWorkflowsStepsOverridable","New tasks inherit this custom workflow's steps (overridable per task). No default — unset (built-in default workflow).")})]}),h.length>0&&e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{children:l("settings.general.fusionWorkflows","Fusion workflows")}),e.jsx(G,{settingKey:"enabledBuiltinWorkflowIds",children:l("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.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:h.map(k=>e.jsxs("label",{htmlFor:`builtin-workflow-${k.id}`,className:"checkbox-label",children:[e.jsx("input",{id:`builtin-workflow-${k.id}`,type:"checkbox",checked:b.has(k.id),onChange:I=>V(k.id,I.target.checked)}),e.jsx(Bd,{workflowId:k.id,decorative:!0}),e.jsx("span",{children:k.name})]},k.id))})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"aiUndoTaskWorkflowId",children:l("settings.general.aiUndoTaskWorkflow","AI-undo task workflow")}),e.jsx(G,{settingKey:"aiUndoTaskWorkflowId",children:l("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("select",{id:"aiUndoTaskWorkflowId",className:"select","data-testid":"ai-undo-workflow-select",value:F,onChange:k=>s(I=>({...I,aiUndoTaskWorkflowId:k.target.value})),children:[e.jsx("option",{value:"",children:l("settings.general.aiUndoTaskWorkflowInherit","Inherit project default workflow")}),N.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id)),!K&&e.jsx("option",{value:F,children:F})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"taskCreateWorkflowId",children:l("settings.general.taskCreateWorkflow","CLI/agent-created task workflow")}),e.jsx(G,{settingKey:"taskCreateWorkflowId",children:l("settings.general.taskCreateWorkflowHelp",'Workflow applied to tasks opened by `fn task create` and the fn_task_create agent tool, which have no workflow picker. Choose "Selected workflow" to follow your current board workflow (falling back to the project default workflow). No default — unset means Selected workflow. An explicit workflow_id passed to fn_task_create still wins.')})]}),e.jsxs("select",{id:"taskCreateWorkflowId",className:"select","data-testid":"task-create-workflow-select",value:R,onChange:k=>s(I=>({...I,taskCreateWorkflowId:k.target.value})),children:[e.jsx("option",{value:"",children:l("settings.general.originWorkflowSelected","Selected workflow")}),N.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id)),!L(R)&&e.jsx("option",{value:R,children:R})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"refinementTaskWorkflowId",children:l("settings.general.refinementTaskWorkflow","Refinement task workflow")}),e.jsx(G,{settingKey:"refinementTaskWorkflowId",children:l("settings.general.refinementTaskWorkflowHelp",'Workflow applied to refinement tasks — the follow-up card spawned from a done or in-review task plus your feedback. Choose "Selected workflow" to follow your current board workflow (falling back to the project default workflow). No default — unset means Selected workflow.')})]}),e.jsxs("select",{id:"refinementTaskWorkflowId",className:"select","data-testid":"refinement-task-workflow-select",value:T,onChange:k=>s(I=>({...I,refinementTaskWorkflowId:k.target.value})),children:[e.jsx("option",{value:"",children:l("settings.general.originWorkflowSelected","Selected workflow")}),N.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id)),!L(T)&&e.jsx("option",{value:T,children:T})]})]}),e.jsx(Ae,{descriptor:{key:"ephemeralAgentTaskCreationPolicy",label:l("settings.general.ephemeralAgentTaskCreationPolicy","Ephemeral agent follow-up tasks"),help:l("settings.general.ephemeralAgentTaskCreationPolicyHint","No default — unset policy falls back to Allow. Upon validation sends a proposal to your mailbox for one-click approval; Deny rejects follow-up task creation."),scope:"project",options:[{value:"allow",label:l("settings.general.ephemeralAgentTaskCreationPolicyAllow","Allow")},{value:"upon_validation",label:l("settings.general.ephemeralAgentTaskCreationPolicyUponValidation","Upon validation")},{value:"deny",label:l("settings.general.ephemeralAgentTaskCreationPolicyDeny","Deny")}]},value:t.ephemeralAgentTaskCreationPolicy??(t.ephemeralAgentsCanCreateTasks===!1?"deny":"allow"),onChange:k=>s(I=>({...I,ephemeralAgentTaskCreationPolicy:k}))}),e.jsx(ae,{descriptor:{key:"workspaceMode",label:l("settings.general.workspaceMode"," Workspace mode (multi-repo) "),help:l("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)."),scope:"project"},value:t.workspaceMode===!0,onChange:k=>s(I=>({...I,workspaceMode:k===!0}))}),e.jsx(ae,{descriptor:{key:"allowAbsoluteFileBrowserPaths",label:l("settings.general.allowAbsoluteFileBrowserPaths"," Allow absolute file-browser paths "),help:l("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."),scope:"project"},value:t.allowAbsoluteFileBrowserPaths===!0,onChange:k=>s(I=>({...I,allowAbsoluteFileBrowserPaths:k===!0}))}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"completionDocumentationMode",children:l("settings.general.completionDocumentationAutomation","Completion Documentation Automation")}),e.jsxs(G,{settingKey:"completionDocumentationMode",children:[l("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"}),l("settings.general.workflowsOrChangelogModeWhenContributorsShouldUpdate"," workflows, or changelog mode when contributors should update an existing changelog file. Default: off. ")]})]}),e.jsxs("select",{id:"completionDocumentationMode",value:t.completionDocumentationMode||"off",onChange:k=>s(I=>({...I,completionDocumentationMode:k.target.value})),children:[e.jsx("option",{value:"off",children:l("settings.general.off","Off")}),e.jsx("option",{value:"changeset",children:l("settings.general.requireChangesetChangesetMd","Require changeset (.changeset/*.md)")}),e.jsx("option",{value:"changelog",children:l("settings.general.requireChangelogUpdateExistingChangelog","Require changelog update (existing changelog)")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"reviewArtifacts",children:l("settings.general.reviewArtifacts","Review Artifacts")}),e.jsx(G,{settingKey:"reviewArtifacts",children:l("settings.general.reviewArtifactsHint"," Controls whether eligible future tasks generate review deliverables. User-facing limits generation to user-facing work; on enables it for all eligible tasks. Individual PROMPT.md headers can override this. Default: off.")})]}),e.jsxs("select",{id:"reviewArtifacts",value:t.reviewArtifacts||"off",onChange:k=>s(I=>({...I,reviewArtifacts:k.target.value})),children:[e.jsx("option",{value:"off",children:l("settings.general.off","Off")}),e.jsx("option",{value:"user-facing",children:l("settings.general.userFacing","User-facing work")}),e.jsx("option",{value:"on",children:l("settings.general.on","On")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"reportMode",children:l("settings.general.reportMode","In-app report mode")}),e.jsx(G,{settingKey:"reportMode",children:l("settings.general.reportModeHelp","How in-app bug/feedback/idea/help reports are filed. Default: draft-review (operator reviews a draft before filing).")})]}),e.jsxs("select",{id:"reportMode",value:t.reportMode??"draft-review",onChange:k=>s(I=>({...I,reportMode:k.target.value})),children:[e.jsx("option",{value:"draft-review",children:l("settings.general.reportModeDraftReview","Review draft before filing")}),e.jsx("option",{value:"auto-file",children:l("settings.general.reportModeAutoFile","File automatically")})]}),["bug","feedback","idea","help"].map(k=>e.jsxs("div",{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:`reportMode-${k}`,children:l(`settings.general.reportModeOverride.${k}`,`${k[0].toUpperCase()}${k.slice(1)} report override`)}),e.jsx(G,{settingKey:`reportModeByAction-${k}`,children:l("settings.general.reportModeByActionHelp","Optional per-action override of the project report mode for bug, feedback, idea, or help. No default — unset actions inherit reportMode.")})]}),e.jsxs("select",{id:`reportMode-${k}`,value:t.reportModeByAction?.[k]??"",onChange:I=>s(B=>{const v={...B.reportModeByAction},M=I.target.value;return M?v[k]=M:delete v[k],{...B,reportModeByAction:Object.keys(v).length?v:void 0}}),children:[e.jsx("option",{value:"",children:l("settings.general.reportModeUseProjectDefault","Use project default")}),e.jsx("option",{value:"draft-review",children:l("settings.general.reportModeDraftReview","Review draft before filing")}),e.jsx("option",{value:"auto-file",children:l("settings.general.reportModeAutoFile","File automatically")})]})]},k)),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"reportTarget",children:l("settings.general.reportTarget","Default report target")}),e.jsx(G,{settingKey:"reportTarget",children:l("settings.general.reportTargetHelp","Optional Issue or Discussion target. When unset, action defaults are preserved.")})]}),e.jsxs("select",{id:"reportTarget",value:t.reportTarget??"",onChange:k=>s(I=>({...I,reportTarget:k.target.value||void 0})),children:[e.jsx("option",{value:"",children:l("settings.general.reportTargetInherit","Preserve action default")}),e.jsx("option",{value:"issue",children:l("settings.general.reportTargetIssue","GitHub Issue")}),e.jsx("option",{value:"discussion",children:l("settings.general.reportTargetDiscussion","GitHub Discussion")})]}),["bug","feedback","idea","help"].map(k=>e.jsxs("div",{children:[e.jsx("label",{htmlFor:`reportTarget-${k}`,children:l(`settings.general.reportTargetOverride.${k}`,`${k[0].toUpperCase()}${k.slice(1)} target override`)}),e.jsxs("select",{id:`reportTarget-${k}`,value:t.reportTargetByAction?.[k]??"",onChange:I=>s(B=>{const v={...B.reportTargetByAction},M=I.target.value;return M?v[k]=M:delete v[k],{...B,reportTargetByAction:Object.keys(v).length?v:void 0}}),children:[e.jsx("option",{value:"",children:l("settings.general.reportTargetInherit","Preserve action default")}),e.jsx("option",{value:"issue",children:l("settings.general.reportTargetIssue","GitHub Issue")}),e.jsx("option",{value:"discussion",children:l("settings.general.reportTargetDiscussion","GitHub Discussion")})]})]},`report-target-${k}`)),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"reportDiscussionCategory",children:l("settings.general.reportDiscussionCategory","Discussion category")}),e.jsx(G,{settingKey:"reportDiscussionCategory",children:l("settings.general.reportDiscussionCategoryHelp","Required when filing to GitHub Discussions.")})]}),e.jsxs("select",{id:"reportDiscussionCategory",value:t.reportDiscussionCategory??"",onChange:k=>s(I=>({...I,reportDiscussionCategory:k.target.value||void 0})),disabled:!w.length,children:[e.jsx("option",{value:"",children:l("settings.general.reportDiscussionCategorySelect","Select a Discussion category")}),w.map(k=>e.jsx("option",{value:k.id,children:k.name},k.id))]}),e.jsx(ae,{descriptor:{key:"reportRoadmapDedupeEnabled",label:l("settings.general.reportRoadmapDedupeEnabled","Deduplicate reports against public roadmap"),help:l("settings.general.reportRoadmapDedupeEnabledHelp","Match open, labeled roadmap issues before filing. Default: on."),scope:"project"},value:t.reportRoadmapDedupeEnabled??!0,onChange:k=>s(I=>({...I,reportRoadmapDedupeEnabled:k??!0}))}),e.jsx(be,{descriptor:{key:"reportRoadmapLabel",label:l("settings.general.reportRoadmapLabel","Public roadmap label"),help:l("settings.general.reportRoadmapLabelHelp","Open GitHub Issues with this label are considered roadmap items. Default: roadmap.")},value:t.reportRoadmapLabel??"roadmap",onChange:k=>s(I=>({...I,reportRoadmapLabel:k||void 0}))}),e.jsx(be,{descriptor:{key:"reportRoadmapRepo",label:l("settings.general.reportRoadmapRepo","Public roadmap repository (optional)"),help:l("settings.general.reportRoadmapRepoHelp","GitHub owner/repository containing public roadmap issues. When unset, uses the tracking repository. No default — unset."),placeholder:"owner/repository"},value:t.reportRoadmapRepo??"",onChange:k=>s(I=>({...I,reportRoadmapRepo:k||void 0}))})]}),e.jsx(Ae,{descriptor:{key:"quickChatButtonMode",label:l("settings.general.quickChatLauncher","Quick Chat launcher"),help:l("settings.general.quickChatLauncherHint","Choose whether Quick Chat opens from the draggable floating button, a footer button beside Terminal, or stays hidden. Default: off (hidden)."),scope:"project",options:[{value:"floating",label:l("settings.general.quickChatLauncherFloating","Floating button")},{value:"footer",label:l("settings.general.quickChatLauncherFooter","Footer button")},{value:"off",label:l("settings.general.off","Off")}]},value:t.quickChatButtonMode??(t.showQuickChatFAB?"floating":"off"),onChange:k=>s(I=>{const B=k??"off";return u?.(B),{...I,quickChatButtonMode:B,showQuickChatFAB:B==="floating"}})}),e.jsx(As,{htmlFor:"mobileNavPrimaryItems",label:l("settings.general.mobileNavPrimaryItems","Mobile footer quick actions"),help:l("settings.general.mobileNavPrimaryItemsHint","Default: Dashboard, Tasks, Agents, Missions, Chat, Mailbox. Add eligible destinations; unselected destinations remain in More."),scope:"project",children:e.jsx("div",{role:"group","aria-label":l("settings.general.mobileNavPrimaryItems","Mobile footer quick actions"),children:(()=>{const k=Array.isArray(t.mobileNavPrimaryItems)&&t.mobileNavPrimaryItems.length>0?t.mobileNavPrimaryItems.filter(v=>lr.includes(v)):[...Gd],I=v=>{s(M=>({...M,mobileNavPrimaryItems:v})),c?.(v)},B=lr.filter(v=>!k.includes(v));return e.jsxs(e.Fragment,{children:[k.map((v,M)=>{const se=l(rr[v],v),ne=pe=>{const j=[...k];[j[M],j[M+pe]]=[j[M+pe],j[M]],I(j)};return e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("span",{children:se}),e.jsxs("span",{children:[e.jsx("button",{type:"button",className:"btn btn-icon",disabled:M===0,"aria-label":l("settings.general.moveNavItemEarlier","Move {{item}} earlier",{item:se}),onClick:()=>ne(-1),children:"↑"}),e.jsx("button",{type:"button",className:"btn btn-icon",disabled:M===k.length-1,"aria-label":l("settings.general.moveNavItemLater","Move {{item}} later",{item:se}),onClick:()=>ne(1),children:"↓"}),e.jsx("button",{type:"button",className:"btn btn-icon","aria-label":l("settings.general.removeNavItem","Remove {{item}}",{item:se}),onClick:()=>I(k.filter(pe=>pe!==v)),children:"×"})]})]},v)}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("span",{children:l("settings.general.addNavItem","Add quick action")}),e.jsxs("select",{id:"mobileNavPrimaryItems",value:"",disabled:k.length>=Hd,onChange:v=>{v.target.value&&I([...k,v.target.value])},children:[e.jsx("option",{value:"",children:l("settings.general.selectNavItem","Choose a destination")}),B.map(v=>e.jsx("option",{value:v,children:l(rr[v],v)},v))]})]})]})})()})}),e.jsx(ae,{descriptor:{key:"quickChatCloseOnOutsideClick",label:l("settings.general.quickChatCloseOnOutsideClick","Close Quick Chat on outside click"),help:l("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."),scope:"project"},value:t.quickChatCloseOnOutsideClick!==!1,onChange:k=>s(I=>({...I,quickChatCloseOnOutsideClick:k===!0}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:l("settings.general.chatHistory","Chat history")}),e.jsx(ae,{descriptor:{key:"showTaskChatsInCommonFeed",label:l("settings.general.showTaskChatsInCommonFeed","Show task chats in common Chat feed"),help:l("settings.general.showTaskChatsInCommonFeedHint","When enabled, populated task-detail Chat conversations appear in the common Direct feed. Empty task chats stay hidden. Default: disabled."),scope:"project"},value:t.showTaskChatsInCommonFeed===!0,onChange:k=>s(I=>({...I,showTaskChatsInCommonFeed:k===!0}))}),e.jsx(Ae,{descriptor:{key:"chatAutoCleanupDays",label:l("settings.general.autoCleanupOldChats","Auto-cleanup old chats"),help:l("settings.general.deleteChatSessionsAndRoomsThatHaveBeen","Delete chat sessions and rooms that have been idle for this many days. Default: Off."),scope:"project",options:[{value:"0",label:l("settings.general.off","Off")},{value:"7",label:l("settings.general.7Days","7 days")},{value:"14",label:l("settings.general.14Days","14 days")},{value:"30",label:l("settings.general.30Days","30 days")},{value:"60",label:l("settings.general.60Days","60 days")},{value:"90",label:l("settings.general.90Days","90 days")}]},value:String(t.chatAutoCleanupDays??0),onChange:k=>s(I=>({...I,chatAutoCleanupDays:Number(k)||0}))}),e.jsx(Ae,{descriptor:{key:"mailAutoCleanupDays",label:l("settings.general.autoPruneOldMail","Auto-prune old mail"),help:l("settings.general.deleteInboxOutboxMessagesOlderThanThisMany","Delete inbox/outbox messages older than this many days. Default: Off. 7 days is the suggested setting."),scope:"project",options:[{value:"0",label:l("settings.general.off","Off")},{value:"7",label:l("settings.general.7Days","7 days")},{value:"14",label:l("settings.general.14Days","14 days")},{value:"30",label:l("settings.general.30Days","30 days")},{value:"60",label:l("settings.general.60Days","60 days")},{value:"90",label:l("settings.general.90Days","90 days")}]},value:String(t.mailAutoCleanupDays??0),onChange:k=>s(I=>({...I,mailAutoCleanupDays:Number(k)||0}))}),e.jsx(Ae,{descriptor:{key:"operationalLogRetentionDays",label:l("settings.general.operationalLogRetention","Operational log retention"),help:l("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. "),scope:"project",options:[{value:"0",label:l("settings.general.off","Off")},{value:"7",label:l("settings.general.7Days","7 days")},{value:"14",label:l("settings.general.14Days","14 days")},{value:"30",label:l("settings.general.30Days","30 days")},{value:"60",label:l("settings.general.60Days","60 days")},{value:"90",label:l("settings.general.90Days","90 days")}]},value:String(t.operationalLogRetentionDays??30),onChange:k=>s(I=>({...I,operationalLogRetentionDays:Number(k)||0}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:l("settings.general.chatRooms","Chat Rooms")}),e.jsx(Pe,{descriptor:{key:"chatRoomRecentVerbatimMessages",label:l("settings.general.recentVerbatimRoomMessages","Recent verbatim room messages"),help:l("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."),scope:"project",min:1,placeholder:l("settings.general.25","25")},value:t.chatRoomRecentVerbatimMessages??null,onChange:k=>s(I=>({...I,chatRoomRecentVerbatimMessages:k||void 0}))}),e.jsx(Pe,{descriptor:{key:"chatRoomCompactionFetchLimit",label:l("settings.general.roomCompactionFetchLimit","Room compaction fetch limit"),help:l("settings.general.upperBoundOnMessagesFetchedFromTheRoom","Upper bound on messages fetched from the room store for compaction consideration. Default: 200."),scope:"project",min:1,placeholder:l("settings.general.200","200")},value:t.chatRoomCompactionFetchLimit??null,onChange:k=>s(I=>({...I,chatRoomCompactionFetchLimit:k||void 0}))}),e.jsx(Pe,{descriptor:{key:"chatRoomSummaryMaxChars",label:l("settings.general.roomSummaryMaxCharacters","Room summary max characters"),help:l("settings.general.hardCapOnTheSynthesizedEarlierRoomContext",'Hard cap on the synthesized "Earlier room context" summary block. Default: 3000.'),scope:"project",min:200,placeholder:l("settings.general.3000","3000")},value:t.chatRoomSummaryMaxChars??null,onChange:k=>s(I=>({...I,chatRoomSummaryMaxChars:k||void 0}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:l("settings.general.capacityRiskBanner","Capacity Risk Banner")}),e.jsx(ae,{descriptor:{key:"capacityRiskBannerEnabled",label:l("settings.general.showCapacityRiskBanner"," Show capacity risk banner "),help:l("settings.general.warnOnTheBoardWhenTodoWorkExceeds","Warn on the board when todo work exceeds the threshold and no idle agents are available. Default: disabled."),scope:"project"},value:t.capacityRiskBannerEnabled===!0,onChange:k=>s(I=>({...I,capacityRiskBannerEnabled:k===!0}))}),e.jsx(Pe,{descriptor:{key:"capacityRiskTodoThreshold",label:l("settings.general.todoThreshold","Todo threshold"),help:l("settings.general.bannerFiresWhenTodoCountIsStrictlyGreater","Banner fires when todo count is strictly greater than this value (default 20). Applies when the banner is enabled."),scope:"project",min:0},value:t.capacityRiskTodoThreshold??20,onChange:k=>s(I=>({...I,capacityRiskTodoThreshold:k===null?0:Math.max(0,Math.trunc(k)||0)}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:l("settings.general.sessionAdvisor","Session advisor (overseer agent)")}),e.jsx(Ae,{descriptor:{key:"sessionAdvisorEnabledByDefault",label:l("settings.general.defaultSessionAdvisorForNewTasks","Default for new tasks"),help:l("settings.general.sessionAdvisorHelp","Controls whether newly created tasks enable the session advisor (live LLM overseer of the executor). Individual tasks can override this from Quick Add or task detail. Also set Session advisor model provider and model id under workflow settings before the advisor can run."),scope:"project",options:[{value:"off",label:l("settings.general.offDefault","Off (default)")},{value:"new-tasks",label:l("settings.general.onForNewTasks","On for new tasks")}]},value:t.sessionAdvisorEnabledByDefault?"new-tasks":"off",onChange:k=>s(I=>({...I,sessionAdvisorEnabledByDefault:k==="new-tasks"}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:l("settings.general.gitHubTracking","GitHub Tracking")}),e.jsx(ae,{descriptor:{key:"githubImportAutoTranslate",label:l("settings.general.autoTranslateImportedIssues","Auto-translate imported issues"),help:l("settings.general.autoTranslateImportedIssuesHelp","When enabled, the Import Tasks panel automatically translates foreign-language issue titles and bodies into the target language below and shows the translation by default. You can always switch back to the original text, and imported tasks carry the translated text. Default: disabled."),scope:"project"},value:t.githubImportAutoTranslate===!0,onChange:k=>s(I=>({...I,githubImportAutoTranslate:k===!0?!0:void 0}))}),e.jsx(Ae,{descriptor:{key:"importTranslateTargetLocale",label:l("settings.general.translationTargetLanguage","Translation target language"),help:l("settings.general.translationTargetLanguageHelp","Language imported issues are translated into when auto-translation is enabled. No default — unset inherits the dashboard language."),scope:"project",options:[{value:"",label:l("settings.general.followDashboardLanguage","Follow dashboard language")},...ai.map(k=>({value:k,label:_d(k)}))]},value:t.importTranslateTargetLocale??"",onChange:k=>s(I=>({...I,importTranslateTargetLocale:k&&ns(k)?k:void 0}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:l("settings.general.browserData","Browser Data")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{children:l("settings.general.clearLocalData","Clear local data")}),e.jsx(G,{settingKey:"clearLocalData",children:l("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:X,children:l("settings.general.clearLocalDataButton","Clear local data")})})]}),m&&e.jsx(Wu,{actionType:m,contextRefs:E,onClose:()=>x(null)})]})}const Mn="builtin:coding",Lg={default:"defaultCredentialInstanceIdOverride",merger:"mergerCredentialInstanceId","import-translate":"importTranslateCredentialInstanceId"},Og=[{id:"planning",providerId:"planningProvider",modelId:"planningModelId",thinkingId:"planningThinkingLevel",credentialInstanceId:"planningCredentialInstanceId",label:"Plan/Triage Model",help:"Provider and model used when planning or triaging tasks. Leave unset to fall through to the global lane, then the selected workflow."},{id:"planning-fallback",providerId:"planningFallbackProvider",modelId:"planningFallbackModelId",thinkingId:"planningFallbackThinkingLevel",credentialInstanceId:"planningFallbackCredentialInstanceId",label:"Planning Fallback Model",help:"Fallback provider and model used when the primary Plan/Triage model cannot be used."},{id:"execution",providerId:"executionProvider",modelId:"executionModelId",thinkingId:"executionThinkingLevel",credentialInstanceId:"executionCredentialInstanceId",label:"Executor Model",help:"Provider and model used while executing workflow steps. Leave unset to fall through to the global lane, then the selected workflow."},{id:"execution-fallback",providerId:"executionFallbackProvider",modelId:"executionFallbackModelId",thinkingId:"executionFallbackThinkingLevel",credentialInstanceId:"executionFallbackCredentialInstanceId",label:"Executor Fallback Model",help:"Fallback provider and model used when the primary Executor model cannot be used."},{id:"validator",providerId:"validatorProvider",modelId:"validatorModelId",thinkingId:"validatorThinkingLevel",credentialInstanceId:"validatorCredentialInstanceId",label:"Reviewer Model",help:"Provider and model used for workflow review or validation lanes. Leave unset to fall through to the global lane, then the selected workflow."},{id:"validator-fallback",providerId:"validatorFallbackProvider",modelId:"validatorFallbackModelId",thinkingId:"validatorFallbackThinkingLevel",credentialInstanceId:"validatorFallbackCredentialInstanceId",label:"Reviewer Fallback Model",help:"Fallback provider and model used when the primary Reviewer model cannot be used."}];function Kg(t){const s=new Map((t??[]).map(a=>[a.id,a]));return Og.filter(a=>{const n=s.get(a.providerId),o=s.get(a.modelId),d=a.thinkingId?s.get(a.thinkingId):void 0;return n?.type==="string"&&o?.type==="string"&&(!a.thinkingId||d?.type==="enum"||d?.type==="string")}).map(a=>({...a,credentialInstanceId:s.get(a.credentialInstanceId??"")?.type==="string"?a.credentialInstanceId:void 0}))}function Bg(t,s){const a=t[s.providerId],n=t[s.modelId];return typeof a=="string"&&typeof n=="string"&&a&&n?`${a}/${n}`:""}function Gg(t,s){return Object.is(t,s)?!0:Array.isArray(t)&&Array.isArray(s)?t.length===s.length&&t.every((a,n)=>Object.is(a,s[n])):!1}class yi extends Error{rejections;constructor(s){super("Workflow model lane settings were rejected"),this.name="WorkflowLaneFlushRejection",this.rejections=s}}function Hg({form:t,setForm:s,models:a,projectId:n,onOpenWorkflowSettings:o,registerWorkflowLaneSaver:d,onWorkflowLanesChange:u}){const{t:c}=le("app"),{agents:l,loading:h}=Wd(n),{modelLanes:p,getLaneStatus:m,getLaneValue:x,updateLaneValue:w,resetLaneValue:f,getLaneThinkingValue:E,updateLaneThinkingValue:N,resetLaneThinkingValue:S,availableModels:L,modelsLoading:F,favoriteProviders:K,favoriteModels:R,onToggleFavorite:T,onToggleModelFavorite:b,editingPresetId:V,setEditingPresetId:X,presetDraft:k,setPresetDraft:I,onSavePresetDraft:B,confirmDelete:v}=a,M=t.modelPresets||[],se=M.map(y=>({id:y.id,name:y.name})),ne=new Set(Object.values(t.defaultPresetBySize||{}).filter(Boolean)),pe=typeof t.defaultWorkflowId=="string"&&t.defaultWorkflowId.trim()?t.defaultWorkflowId:Mn,[j,W]=i.useState(pe),[ce,Ie]=i.useState(null),[Oe,H]=i.useState(!1),[Z,Te]=i.useState({}),[_e,Ke]=i.useState({}),[D,U]=i.useState([]),te=i.useRef(0),ke=Object.keys(Z).length>0;i.useEffect(()=>{W(pe)},[pe]),i.useEffect(()=>{if(!n){Ie(null),Te({}),Ke({}),U([]);return}const y=++te.current;H(!0),Promise.all([$d(j,n),zd(j,n)]).then(([_,q])=>{if(te.current!==y)return;Ie(q),Te({}),Ke({});const fe="settings"in _.ir?_.ir.settings:void 0;U(Kg(fe))}).catch(_=>{if(te.current===y){if(_ instanceof ir&&_.status===404&&j!==Mn){W(Mn);return}Ie({stored:{},effective:{},orphaned:[]}),U([])}}).finally(()=>{te.current===y&&H(!1)})},[n,j]);const Ne=i.useMemo(()=>({...ce?.effective??{},...Object.fromEntries(Object.entries(Z).filter(([,y])=>y!==null))}),[ce,Z]),re=i.useCallback((y,_)=>{u?.(),Ke(q=>{const fe={...q};return delete fe[y.providerId],delete fe[y.modelId],y.credentialInstanceId&&delete fe[y.credentialInstanceId],fe}),Te(q=>{if(!_)return{...q,[y.providerId]:null,[y.modelId]:null,...y.credentialInstanceId?{[y.credentialInstanceId]:null}:{}};const fe=_.indexOf("/");return fe<=0?q:{...q,[y.providerId]:_.slice(0,fe),[y.modelId]:_.slice(fe+1),...y.credentialInstanceId?{[y.credentialInstanceId]:null}:{}}})},[u]),$=i.useCallback((y,_)=>{y.credentialInstanceId&&(u?.(),Ke(q=>{if(!q[y.credentialInstanceId])return q;const fe={...q};return delete fe[y.credentialInstanceId],fe}),Te(q=>({...q,[y.credentialInstanceId]:_||null})))},[u]),he=i.useCallback((y,_)=>{y.thinkingId&&(u?.(),Ke(q=>{if(!y.thinkingId||!q[y.thinkingId])return q;const fe={...q};return delete fe[y.thinkingId],fe}),Te(q=>({...q,[y.thinkingId]:_||null})))},[u]),xe=i.useCallback(y=>{re(y,""),he(y,""),$(y,"")},[$,re,he]),je=i.useCallback(async()=>{if(!n||!ke)return;const y={...Z},_=Object.keys(y);try{const q=await qd(j,y,n);Ie(q),Te(fe=>{const Be={...fe};for(const Xe of _)Gg(fe[Xe],y[Xe])&&delete Be[Xe];return Be}),Ke({})}catch(q){if(q instanceof ir&&q.status===400&&q.details){const fe=q.details.rejections??[];if(fe.length>0)throw Ke(Object.fromEntries(fe.map(Be=>[Be.settingId,Be]))),new yi(fe)}throw q}},[n,ke,j,Z]);i.useEffect(()=>(d?.(je),()=>d?.(null)),[d,je]);const Me=p.filter(y=>["default","merger","import-translate"].includes(y.laneId)),P=y=>Lg[y.laneId],Ce=y=>{const _=P(y);return _&&typeof t[_]=="string"?t[_]:""},Re=(y,_)=>{const q=P(y);q&&s(fe=>({...fe,[q]:_||void 0}))},ve=p.find(y=>y.laneId==="summarization"),we=y=>y.laneId==="default"?"Project Default Model":y.laneId==="merger"?"Project Merger Model":y.laneId==="summarization"?"Project Summarization Model":y.laneId==="import-translate"?"Project Import Auto-Translation Model":y.label,ie=y=>y.laneId==="default"?"Project-wide default AI model used when no more specific task or project lane override is set.":y.laneId==="merger"?"Model used for merge conflict resolution, clean-room merge, stash-conflict recovery, and related merger agent sessions.":y.laneId==="summarization"?"Model used for title auto-summarization, merge commit summaries, GitHub tracking issue titles, and PR title/body generation.":y.laneId==="import-translate"?"Model used to translate foreign-language GitHub/GitLab issue titles and bodies in the Import Tasks panel. One short readonly call per issue — a cheap, fast model is usually the right pick.":y.helperText,Ee=t.mergerFallbackProvider&&t.mergerFallbackModelId?`${t.mergerFallbackProvider}/${t.mergerFallbackModelId}`:"",A=typeof t.mergerFallbackThinkingLevel=="string"?t.mergerFallbackThinkingLevel:"",z=!!(Ee||A||t.mergerFallbackCredentialInstanceId),Y=y=>{if(!y){s(q=>({...q,mergerFallbackProvider:void 0,mergerFallbackModelId:void 0,mergerFallbackThinkingLevel:void 0,mergerFallbackCredentialInstanceId:void 0}));return}const _=y.indexOf("/");s(q=>({...q,mergerFallbackProvider:y.slice(0,_),mergerFallbackModelId:y.slice(_+1),mergerFallbackCredentialInstanceId:void 0}))},de=y=>{s(_=>({..._,mergerFallbackThinkingLevel:y||void 0}))},ue=()=>{s(y=>({...y,mergerFallbackProvider:void 0,mergerFallbackModelId:void 0,mergerFallbackThinkingLevel:void 0,mergerFallbackCredentialInstanceId:void 0}))},me=()=>e.jsxs("div",{className:"form-group","data-testid":"project-model-lane-merger-fallback",children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:"mergerFallbackModel",children:c("settings.projectModels.mergerFallbackModel","Merger Fallback Model")}),e.jsx("span",{className:`settings-lane-badge ${z?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:z?"Explicitly set for this project":"Inherited from global settings",children:z?"Override (Project)":"Inherited (Global)"}),e.jsx(G,{settingKey:"mergerFallbackModel",children:c("settings.projectModels.mergerFallbackHelp","Fallback provider and model used when a merger session retries. Leave unset to use the shared global fallback model pair.")})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(lt,{id:"mergerFallbackModel",label:"Merger Fallback Model",models:L,value:Ee,onChange:Y,placeholder:c("settings.projectModels.useGlobal","Use global"),favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable",showThinkingLevel:!0,thinkingLevel:A,onThinkingLevelChange:de,credentialInstanceId:t.mergerFallbackCredentialInstanceId,onCredentialInstanceChange:y=>s(_=>({..._,mergerFallbackCredentialInstanceId:y||void 0})),defaultThinkingLevel:t.defaultThinkingLevel})}),z&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:c("settings.projectModels.resetToInheritFromGlobal","Reset to inherit from global"),onClick:ue,children:c("settings.projectModels.reset"," Reset ")})]})]}),Se=t.titleSummarizerFallbackProvider&&t.titleSummarizerFallbackModelId?`${t.titleSummarizerFallbackProvider}/${t.titleSummarizerFallbackModelId}`:"",oe=typeof t.titleSummarizerFallbackThinkingLevel=="string"?t.titleSummarizerFallbackThinkingLevel:"",Fe=!!(Se||oe||t.titleSummarizerFallbackCredentialInstanceId),Ge=y=>{if(!y){s(q=>({...q,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,titleSummarizerFallbackThinkingLevel:void 0,titleSummarizerFallbackCredentialInstanceId:void 0}));return}const _=y.indexOf("/");s(q=>({...q,titleSummarizerFallbackProvider:y.slice(0,_),titleSummarizerFallbackModelId:y.slice(_+1),titleSummarizerFallbackCredentialInstanceId:void 0}))},Ye=y=>{s(_=>({..._,titleSummarizerFallbackThinkingLevel:y||void 0}))},ee=()=>{s(y=>({...y,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,titleSummarizerFallbackThinkingLevel:void 0,titleSummarizerFallbackCredentialInstanceId:void 0}))},rt=y=>{const _=m(y),q=x(y),fe=E(y),Be=_==="overridden"||!!fe||!!Ce(y),Xe=we(y);return e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`${y.laneId}Model`,children:Xe}),e.jsx("span",{className:`settings-lane-badge ${Be?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:Be?"Explicitly set for this project":"Inherited from global settings",children:Be?"Override (Project)":"Inherited (Global)"}),e.jsxs(G,{settingKey:`${y.laneId}Model`,children:[ie(y),c("settings.projectModels.fallsBackTo"," Falls back to: "),y.fallbackOrder,"."]})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(lt,{id:`${y.laneId}Model`,label:Xe,models:L,value:q,onChange:Ze=>{w(y,Ze),Re(y,"")},credentialInstanceId:Ce(y),onCredentialInstanceChange:Ze=>Re(y,Ze),placeholder:y.laneId==="default"?"Use global default":"Use global",favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable",showThinkingLevel:!!y.projectThinkingKey,thinkingLevel:fe,onThinkingLevelChange:Ze=>N(y,Ze),defaultThinkingLevel:t.defaultThinkingLevel})}),Be&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:c("settings.projectModels.resetToInheritFromGlobal","Reset to inherit from global"),onClick:()=>{f(y),S(y),Re(y,"")},style:{whiteSpace:"nowrap"},children:c("settings.projectModels.reset"," Reset ")})]})]},y.laneId)},Dt=t.chatDefaultKind??"model",os=t.chatDefaultModelProvider&&t.chatDefaultModelId?`${t.chatDefaultModelProvider}/${t.chatDefaultModelId}`:"",Ms=typeof t.chatDefaultThinkingLevel=="string"?t.chatDefaultThinkingLevel:"",Rs=!!(t.chatNewSessionMode||t.chatDefaultKind||t.chatDefaultAgentId||os||Ms||t.chatDefaultCredentialInstanceId),$t=y=>{if(!y){s(q=>({...q,chatDefaultKind:"model",chatDefaultAgentId:void 0,chatDefaultModelProvider:void 0,chatDefaultModelId:void 0,chatDefaultThinkingLevel:void 0,chatDefaultCredentialInstanceId:void 0}));return}const _=y.indexOf("/");_<=0||s(q=>({...q,chatDefaultKind:"model",chatDefaultAgentId:void 0,chatDefaultModelProvider:y.slice(0,_),chatDefaultModelId:y.slice(_+1),chatDefaultCredentialInstanceId:void 0}))},Es=y=>{s(_=>({..._,chatDefaultThinkingLevel:y||void 0}))},zt=()=>{s(y=>({...y,chatNewSessionMode:void 0,chatDefaultKind:void 0,chatDefaultAgentId:void 0,chatDefaultModelProvider:void 0,chatDefaultModelId:void 0,chatDefaultThinkingLevel:void 0,chatDefaultCredentialInstanceId:void 0}))};return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:c("settings.projectModels.tokenCap","Token Cap")}),e.jsx(Pe,{descriptor:{key:"tokenCap",label:c("settings.projectModels.tokenCap","Token Cap"),help:c("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)."),scope:"project",placeholder:c("settings.projectModels.noCap","No cap")},value:t.tokenCap??null,onChange:y=>s(_=>({..._,tokenCap:y?Math.trunc(y):null})),clearable:t.tokenCap!=null}),e.jsx(As,{htmlFor:"executorEscalationModel",label:c("settings.projectModels.executorEscalationModel","Executor Escalation Model"),help:c("settings.projectModels.executorEscalationModelHelp","Alternate model used once tool-failure retries are exhausted. No default — unset means no alternate model; configure escalation policy and an optional node target in Scheduling."),scope:"project",children:e.jsx(lt,{id:"executorEscalationModel",label:c("settings.projectModels.executorEscalationModel","Executor Escalation Model"),models:L,disabled:F||L.length===0,value:t.executorEscalationProvider&&t.executorEscalationModelId?`${t.executorEscalationProvider}/${t.executorEscalationModelId}`:"",onChange:y=>{if(!y){s(q=>({...q,executorEscalationProvider:void 0,executorEscalationModelId:void 0}));return}const _=y.indexOf("/");_<=0||s(q=>({...q,executorEscalationProvider:y.slice(0,_),executorEscalationModelId:y.slice(_+1)}))},placeholder:c("settings.projectModels.selectExecutorEscalationModel","Select an escalation model"),defaultOptionLabel:c("settings.projectModels.noExecutorEscalationModel","No escalation model"),favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable"})}),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.projectModels.modelLanes","Model Lanes")}),e.jsx(G,{settingKey:"project-model-lanes",children:c("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. ")})]}),F?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Et,{label:c("settings.projectModels.loadingAvailableModels","Loading available models…")})}):L.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:c("settings.projectModels.noModelsAvailableConfigureAuthenticationFirst"," No models available. Configure authentication first. ")}):e.jsxs(e.Fragment,{children:[Me.filter(y=>y.laneId==="default"||y.laneId==="merger").map(rt),me(),Me.filter(y=>y.laneId==="import-translate").map(rt)]}),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.projectModels.chatHeading","Chat")}),e.jsx(G,{settingKey:"project-chat-defaults",children:c("settings.projectModels.chatDescription","Choose the default target for new Direct chats and whether New Chat should prompt or immediately use that default.")})]}),e.jsx(Ae,{descriptor:{key:"chatNewSessionMode",label:c("settings.projectModels.chatNewSessionMode","New Chat behavior"),help:c("settings.projectModels.chatNewSessionModeHelp","Prompt mode opens New Chat with this default preselected. Always-default mode skips the dialog when the configured default is complete."),scope:"project",options:[{value:"prompt",label:c("settings.projectModels.chatNewSessionModePrompt","Prompt for model each time")},{value:"always-default",label:c("settings.projectModels.chatNewSessionModeAlwaysDefault","Always use configured default")}]},value:t.chatNewSessionMode??"prompt",onChange:y=>s(_=>({..._,chatNewSessionMode:y==="always-default"?"always-default":void 0}))}),e.jsxs("div",{className:"form-group","data-testid":"project-models-chat-kind",children:[e.jsx("label",{children:c("settings.projectModels.chatDefaultKind","Chat default target")}),e.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"project-models-chat-kind-toggle",children:[e.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${Dt==="model"?" chat-new-dialog-mode-btn--active":""}`,onClick:()=>s(y=>({...y,chatDefaultKind:"model",chatDefaultAgentId:void 0})),children:c("settings.projectModels.chatDefaultKindModel","Model")}),e.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${Dt==="agent"?" chat-new-dialog-mode-btn--active":""}`,onClick:()=>s(y=>({...y,chatDefaultKind:"agent",chatDefaultModelProvider:void 0,chatDefaultModelId:void 0,chatDefaultThinkingLevel:void 0,chatDefaultCredentialInstanceId:void 0})),children:c("settings.projectModels.chatDefaultKindAgent","Agent")})]})]}),Dt==="model"?e.jsxs("div",{className:"form-group","data-testid":"project-models-chat-model",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"chatDefaultModel",children:c("settings.projectModels.chatDefaultModel","Chat Default Model")}),e.jsx(G,{settingKey:"chatDefaultModel",children:c("settings.projectModels.chatDefaultModelHelp","Model-mode New Chat uses the built-in Fusion chat agent with this provider/model pair. Leave empty to fall back to prompting.")})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(lt,{id:"chatDefaultModel",label:c("settings.projectModels.chatDefaultModel","Chat Default Model"),models:L,value:os,onChange:$t,credentialInstanceId:typeof t.chatDefaultCredentialInstanceId=="string"?t.chatDefaultCredentialInstanceId:void 0,onCredentialInstanceChange:y=>s(_=>({..._,chatDefaultCredentialInstanceId:y||void 0})),placeholder:c("settings.projectModels.selectChatDefaultModel","Select a chat default model"),favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable",showThinkingLevel:!0,thinkingLevel:Ms,onThinkingLevelChange:Es,defaultThinkingLevel:t.defaultThinkingLevel})}),Rs&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:c("settings.projectModels.chatDefaultReset","Reset Chat default"),onClick:zt,children:c("settings.projectModels.reset"," Reset ")})]})]}):e.jsxs("div",{className:"form-group","data-testid":"project-models-chat-agent",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"chatDefaultAgentId",children:c("settings.projectModels.chatDefaultAgent","Chat Default Agent")}),e.jsx(G,{settingKey:"chatDefaultAgentId",children:c("settings.projectModels.chatDefaultAgentHelp","Agent-mode New Chat starts a Direct chat with the selected durable agent.")})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsxs("select",{id:"chatDefaultAgentId",value:t.chatDefaultAgentId??"",disabled:h||l.length===0,onChange:y=>s(_=>({..._,chatDefaultKind:"agent",chatDefaultAgentId:y.target.value||void 0,chatDefaultModelProvider:void 0,chatDefaultModelId:void 0,chatDefaultThinkingLevel:void 0,chatDefaultCredentialInstanceId:void 0})),children:[e.jsx("option",{value:"",children:h?c("settings.projectModels.loadingAgents","Loading agents…"):c("settings.projectModels.selectChatDefaultAgent","Select a chat default agent")}),l.map(y=>e.jsxs("option",{value:y.id,children:[y.name," (",y.role,")"]},y.id))]})}),Rs&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:c("settings.projectModels.chatDefaultReset","Reset Chat default"),onClick:zt,children:c("settings.projectModels.reset"," Reset ")})]}),l.length===0&&!h?e.jsx("small",{children:c("settings.projectModels.chatDefaultAgentEmpty","No agents are available for this project yet.")}):null]}),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.projectModels.defaultWorkflowModelLanes","Project workflow model lanes")}),e.jsxs(G,{settingKey:"default-workflow-model-lanes",children:[c("settings.movedStub.modelLanes","Per-phase model lanes (execution, planning, reviewer, and their fallbacks) are stored on the active default workflow."),c("settings.projectModels.theseProjectOverridesApplyToTheActiveDefault"," They apply as the project baseline for every workflow and take precedence over global and per-workflow values; task-specific selections still win. ")]})]}),n?Oe?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Et,{label:c("settings.projectModels.loadingWorkflowModelLanes","Loading workflow model lanes…")})}):L.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:c("settings.projectModels.noModelsAvailableConfigureAuthenticationBeforeSelectingWorkflow"," No models available. Configure authentication before selecting workflow model lanes. ")}):e.jsxs(e.Fragment,{children:[D.map(y=>{const _=Bg(Ne,y),q=y.thinkingId?Ne[y.thinkingId]:void 0,fe=typeof q=="string"?q:"",Be=y.credentialInstanceId?Ne[y.credentialInstanceId]:void 0,Xe=typeof Be=="string"?Be:"",Ze=Object.prototype.hasOwnProperty.call(Z,y.providerId)?Z[y.providerId]!==null:!!(ce?.stored&&(Object.prototype.hasOwnProperty.call(ce.stored,y.providerId)||Object.prototype.hasOwnProperty.call(ce.stored,y.modelId))),qt=y.thinkingId?Object.prototype.hasOwnProperty.call(Z,y.thinkingId)?Z[y.thinkingId]!==null:!!(ce?.stored&&Object.prototype.hasOwnProperty.call(ce.stored,y.thinkingId)):!1,wa=y.credentialInstanceId?Object.prototype.hasOwnProperty.call(Z,y.credentialInstanceId)?Z[y.credentialInstanceId]!==null:!!(ce?.stored&&Object.prototype.hasOwnProperty.call(ce.stored,y.credentialInstanceId)):!1,Vt=Ze||qt||wa,Ft=_e[y.providerId]?.message??_e[y.modelId]?.message??(y.thinkingId?_e[y.thinkingId]?.message:void 0)??(y.credentialInstanceId?_e[y.credentialInstanceId]?.message:void 0);return e.jsxs("div",{className:"form-group","data-testid":`workflow-model-lane-${y.id}`,children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`workflow-${y.id}-model`,children:y.label}),e.jsx("span",{className:`settings-lane-badge ${Vt?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:Vt?"Explicitly set as the project baseline":"Inherited from global, workflow, or default settings",children:Vt?"Project baseline":"Inherited (Workflow)"}),y.help?e.jsx(G,{settingKey:`workflow-${y.id}-model`,children:y.help}):null]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(lt,{id:`workflow-${y.id}-model`,label:y.label,models:L,value:_,onChange:Lt=>re(y,Lt),placeholder:c("settings.projectModels.useWorkflowDefault","Use workflow default"),defaultOptionLabel:"Use workflow default",favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable",credentialInstanceId:Xe,onCredentialInstanceChange:y.credentialInstanceId?Lt=>$(y,Lt):void 0,showThinkingLevel:!!y.thinkingId,thinkingLevel:fe,onThinkingLevelChange:y.thinkingId?Lt=>he(y,Lt):void 0,defaultThinkingLevel:typeof t.defaultThinkingLevel=="string"?t.defaultThinkingLevel:"off"})}),Vt&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:c("settings.projectModels.resetToInheritFromWorkflow","Reset to inherit from workflow"),onClick:()=>xe(y),style:{whiteSpace:"nowrap"},children:c("settings.projectModels.reset"," Reset ")})]}),Ft?e.jsx("small",{className:"settings-error","data-testid":`workflow-model-lane-error-${y.id}`,children:Ft}):null]},y.id)}),o?e.jsx("div",{className:"settings-model-lane-actions","aria-label":c("settings.projectModels.defaultWorkflowModelLaneActions","Default workflow model lane actions"),children:e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:o,children:c("settings.projectModels.advancedWorkflowPolicy"," Advanced workflow policy ")})}):null]}):e.jsx("div",{className:"settings-empty-state settings-muted",children:c("settings.projectModels.openAProjectToEditWorkflowModelLanes","Open a project to edit workflow model lanes.")}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.projectModels.modelPresets","Model Presets")}),e.jsxs("div",{className:"form-group settings-model-presets",children:[e.jsx("label",{children:c("settings.projectModels.configuredPresets","Configured presets")}),M.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:c("settings.projectModels.noPresetsConfiguredYet","No presets configured yet.")}):e.jsx("div",{className:"settings-preset-list",children:M.map(y=>{const _=Vd(y),q=`${_.executorValue||"default"} / ${_.validatorValue||"default"}`;return e.jsxs("div",{className:"settings-preset-item",children:[e.jsxs("div",{className:"settings-preset-item-meta",children:[e.jsx("strong",{children:y.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:q})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{X(y.id),I({...y})},children:c("settings.projectModels.edit"," Edit ")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:async()=>{ne.has(y.id)&&!await v({title:c("settings.models.deletePresetTitle","Delete Preset"),message:c("settings.models.deletePresetMessage",'Preset "{{name}}" is used in auto-selection. Delete it anyway?',{name:y.name}),danger:!0})||(s(fe=>({...fe,modelPresets:(fe.modelPresets||[]).filter(Be=>Be.id!==y.id),defaultPresetBySize:Object.fromEntries(Object.entries(fe.defaultPresetBySize||{}).filter(([,Be])=>Be!==y.id))})),V===y.id&&(X(null),I(null)))},children:c("settings.projectModels.delete"," Delete ")})]})]},y.id)})}),k?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{X(null),I({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:c("settings.projectModels.addPreset"," Add Preset ")})})]}),k?e.jsxs("div",{className:"form-group settings-preset-editor",children:[e.jsx("label",{children:c("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:c("settings.projectModels.name","Name")}),e.jsx("input",{id:"preset-name",type:"text",value:k.name,onChange:y=>{const _=y.target.value;I(q=>q&&{...q,name:_})}})]}),L.length===0?e.jsx("small",{children:c("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:c("settings.projectModels.executorModel","Executor model")}),e.jsx(lt,{id:"preset-executor-model",label:"Preset executor model",models:L,value:k.executorProvider&&k.executorModelId?`${k.executorProvider}/${k.executorModelId}`:"",onChange:y=>{if(!y){I(q=>q&&{...q,executorProvider:void 0,executorModelId:void 0,executorCredentialInstanceId:void 0});return}const _=y.indexOf("/");I(q=>q&&{...q,executorProvider:y.slice(0,_),executorModelId:y.slice(_+1),executorCredentialInstanceId:void 0})},placeholder:c("settings.projectModels.useDefault","Use default"),favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable",credentialInstanceId:k.executorCredentialInstanceId,onCredentialInstanceChange:y=>I(_=>_&&{..._,...y?{executorCredentialInstanceId:y}:{executorCredentialInstanceId:void 0}})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:c("settings.projectModels.reviewerModel","Reviewer model")}),e.jsx(lt,{id:"preset-validator-model",label:"Preset reviewer model",models:L,value:k.validatorProvider&&k.validatorModelId?`${k.validatorProvider}/${k.validatorModelId}`:"",onChange:y=>{if(!y){I(q=>q&&{...q,validatorProvider:void 0,validatorModelId:void 0,validatorCredentialInstanceId:void 0});return}const _=y.indexOf("/");I(q=>q&&{...q,validatorProvider:y.slice(0,_),validatorModelId:y.slice(_+1),validatorCredentialInstanceId:void 0})},placeholder:c("settings.projectModels.useDefault","Use default"),favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable",credentialInstanceId:k.validatorCredentialInstanceId,onCredentialInstanceChange:y=>I(_=>_&&{..._,...y?{validatorCredentialInstanceId:y}:{validatorCredentialInstanceId:void 0}})})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:B,children:c("settings.models.savePreset","Save preset")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{X(null),I(null)},children:c("settings.actions.cancel","Cancel")})]})]}):null,e.jsx(ae,{descriptor:{key:"autoSelectModelPreset",label:c("settings.projectModels.autoSelectPresetBasedOnTaskSize"," Auto-select preset based on task size "),help:c("settings.projectModels.autoSelectModelPresetHint","Default: disabled."),scope:"project"},value:t.autoSelectModelPreset||!1,onChange:y=>s(_=>({..._,autoSelectModelPreset:y===!0}))}),t.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(y=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${y}`,children:y==="S"?"Small tasks (S):":y==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${y}`,value:t.defaultPresetBySize?.[y]||"",onChange:_=>{const q=_.target.value||void 0;s(fe=>({...fe,defaultPresetBySize:{...fe.defaultPresetBySize||{},[y]:q}}))},children:[e.jsx("option",{value:"",children:c("settings.projectModels.noPreset","No preset")}),se.map(_=>e.jsx("option",{value:_.id,children:_.name},_.id))]})]},y))}):null,e.jsx(ae,{descriptor:{key:"taskDefinitionInInputLanguage",label:c("settings.projectModels.taskDefinitionInInputLanguage","Write task definitions in the operator's input language"),help:c("settings.projectModels.taskDefinitionInInputLanguageHelp","When enabled, generated task-definition prose uses supported detectable input languages (Spanish, French, Korean, or Chinese as zh-CN). Headings, markers, and code stay English. Unsupported or undetectable input stays English. Default: disabled."),scope:"project"},value:t.taskDefinitionInInputLanguage||!1,onChange:y=>s(_=>({..._,taskDefinitionInInputLanguage:y===!0}))}),e.jsxs("section",{"data-testid":"project-models-ai-summarization",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.projectModels.aITitleAndGitCommitMessageSummarization"," AI Title and Git Commit Message Summarization ")}),e.jsxs(G,{settingKey:"project-ai-summarization",children:[c("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. "),t.autoSummarizeTitles||t.useAiMergeCommitSummary||t.githubTrackingEnabledByDefault?c("settings.movedStub.summarizerModelInline","These summarization model controls govern title auto-summarization, merge commit summaries, GitHub tracking titles, and PR metadata generation."):""]})]}),F?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Et,{label:c("settings.projectModels.loadingAvailableModels","Loading available models…")})}):L.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:c("settings.projectModels.noModelsAvailableConfigureAuthenticationFirst"," No models available. Configure authentication first. ")}):e.jsxs(e.Fragment,{children:[ve?rt(ve):null,e.jsxs("div",{className:"form-group","data-testid":"project-model-lane-title-summarizer-fallback",children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:"titleSummarizerFallbackModel",children:c("settings.projectModels.titleSummarizerFallbackModel","Title Summarizer Fallback Model")}),e.jsx("span",{className:`settings-lane-badge ${Fe?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:Fe?"Explicitly set for this project":"Inherited from global settings",children:Fe?"Override (Project)":"Inherited (Global)"}),e.jsx(G,{settingKey:"titleSummarizerFallbackModel",children:c("settings.projectModels.titleSummarizerFallbackHelp","Fallback provider and model used when the primary Title Summarizer model cannot be used. Falls back to the global summarization lane and then the default model chain.")})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(lt,{id:"titleSummarizerFallbackModel",label:"Title Summarizer Fallback Model",models:L,value:Se,onChange:Ge,placeholder:c("settings.projectModels.useGlobal","Use global"),favoriteProviders:K,onToggleFavorite:T,favoriteModels:R,onToggleModelFavorite:b,menuWidth:"readable",showThinkingLevel:!0,thinkingLevel:oe,onThinkingLevelChange:Ye,credentialInstanceId:t.titleSummarizerFallbackCredentialInstanceId,onCredentialInstanceChange:y=>s(_=>({..._,titleSummarizerFallbackCredentialInstanceId:y||void 0})),defaultThinkingLevel:t.defaultThinkingLevel})}),Fe&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:c("settings.projectModels.resetToInheritFromGlobal","Reset to inherit from global"),onClick:ee,style:{whiteSpace:"nowrap"},children:c("settings.projectModels.reset"," Reset ")})]})]})]}),e.jsx(ae,{descriptor:{key:"autoSummarizeTitles",label:c("settings.projectModels.autoSummarizeLongDescriptionsAsTitles"," Auto-summarize long descriptions as titles "),help:c("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. "),scope:"project"},value:t.autoSummarizeTitles||!1,onChange:y=>s(_=>({..._,autoSummarizeTitles:y===!0}))}),e.jsx(ae,{descriptor:{key:"useAiMergeCommitSummary",label:c("settings.projectModels.aIMergeCommitSummaries"," AI merge commit summaries "),help:c("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. "),scope:"project"},value:t.useAiMergeCommitSummary||!1,onChange:y=>s(_=>({..._,useAiMergeCommitSummary:y===!0}))}),e.jsx(xr,{descriptor:{key:"prTitlePromptInstructions",label:c("settings.projectModels.prTitlePromptInstructions","PR title prompt guidance"),help:c("settings.projectModels.prTitlePromptInstructionsHelp","Guides the AI-generated Create PR title. Leave blank to use the default PR metadata prompt. No default — unset."),scope:"project",placeholder:c("settings.projectModels.prTitlePromptInstructionsPlaceholder","Example: Use conventional-commit style and keep titles under 72 characters.")},value:t.prTitlePromptInstructions||"",onChange:y=>s(_=>({..._,prTitlePromptInstructions:y??""}))}),e.jsx(xr,{descriptor:{key:"prDescriptionPromptInstructions",label:c("settings.projectModels.prDescriptionPromptInstructions","PR description prompt guidance"),help:c("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."),scope:"project",placeholder:c("settings.projectModels.prDescriptionPromptInstructionsPlaceholder","Example: Emphasize operator-facing behavior and list verification commands exactly.")},value:t.prDescriptionPromptInstructions||"",onChange:y=>s(_=>({..._,prDescriptionPromptInstructions:y??""}))})]})]})}const zr=1440*60*1e3,_g=2;function Ug({form:t,setForm:s,concurrencyLoading:a=!1,onOverlapIgnorePathChange:n,onOpenOverlapPathPicker:o,onRemoveOverlapIgnorePath:d,onAddOverlapIgnorePath:u,onOpenWorkflowSettings:c}){const{t:l}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:l("settings.scheduling.scheduling","Scheduling")}),e.jsx(Pe,{descriptor:{key:"executorToolFailureRetryCount",label:l("settings.scheduling.executorToolFailureRetryCount","Executor tool-failure retries"),help:l("settings.scheduling.executorToolFailureRetryCountHelp","Same-model retries after consecutive tool-call failures. Set 0 to disable. Default: 2."),scope:"project",min:0,step:1},value:t.executorToolFailureRetryCount??2,onChange:h=>s(p=>({...p,executorToolFailureRetryCount:Math.max(0,Math.floor(h??2))}))}),e.jsx(Pe,{descriptor:{key:"executorToolFailureRetryBackoffMs",label:l("settings.scheduling.executorToolFailureRetryBackoffMs","Tool-failure retry backoff (ms)"),help:l("settings.scheduling.executorToolFailureRetryBackoffMsHelp","Unref'd wait before retrying. Default: 2000."),scope:"project",min:0,step:1},value:t.executorToolFailureRetryBackoffMs??2e3,onChange:h=>s(p=>({...p,executorToolFailureRetryBackoffMs:Math.max(0,Math.floor(h??2e3))}))}),e.jsx(Pe,{descriptor:{key:"executorToolFailureThreshold",label:l("settings.scheduling.executorToolFailureThreshold","Consecutive tool failures"),help:l("settings.scheduling.executorToolFailureThresholdHelp","Terminal tool errors required before retrying. Default: 1."),scope:"project",min:1,step:1},value:t.executorToolFailureThreshold??1,onChange:h=>s(p=>({...p,executorToolFailureThreshold:Math.max(1,Math.floor(h??1))}))}),e.jsx(ae,{descriptor:{key:"executorModelEscalationEnabled",label:l("settings.scheduling.executorModelEscalationEnabled","Escalate after tool-failure retries"),help:l("settings.scheduling.executorModelEscalationEnabledHelp","After same-model retries are exhausted, try one configured alternate model or node. Disabled by default."),scope:"project"},value:t.executorModelEscalationEnabled===!0,onChange:h=>s(p=>({...p,executorModelEscalationEnabled:h===!0}))}),e.jsx(be,{descriptor:{key:"executorEscalationNodeId",label:l("settings.scheduling.executorEscalationNodeId","Escalation node ID"),help:l("settings.scheduling.executorEscalationNodeIdHelp","Optional configured node; a node target re-enters scheduler routing."),scope:"project"},value:t.executorEscalationNodeId??"",onChange:h=>s(p=>({...p,executorEscalationNodeId:h??""}))}),e.jsx(Pe,{descriptor:{key:"maxConcurrent",label:l("settings.scheduling.maxConcurrentTasks","Max Concurrent Tasks"),help:l("settings.scheduling.maxConcurrentTasksHint","Default: 2."),scope:"project",min:1,max:10,disabled:a},value:t.maxConcurrent??null,onChange:h=>s(p=>({...p,maxConcurrent:h??void 0}))}),e.jsx(Pe,{descriptor:{key:"maxConcurrentVerifications",label:l("settings.scheduling.maxConcurrentVerifications","Max Concurrent Verifications"),help:l("settings.scheduling.maxConcurrentVerificationsHint","Caps stacked typecheck/build verification across tasks. Default: 1. Range: 1–8."),scope:"project",min:1,max:8,disabled:a},value:t.maxConcurrentVerifications??null,onChange:h=>{if(h===null){s(m=>({...m,maxConcurrentVerifications:void 0}));return}const p=Math.min(8,Math.max(1,Math.floor(h)||1));s(m=>({...m,maxConcurrentVerifications:p}))}}),e.jsx(Pe,{descriptor:{key:"pollIntervalMs",label:l("settings.scheduling.pollIntervalMs","Poll Interval (ms)"),help:l("settings.scheduling.pollIntervalMsHint","Default: 15000 (15 seconds)."),scope:"project",min:5e3,step:1e3},value:t.pollIntervalMs??null,onChange:h=>s(p=>({...p,pollIntervalMs:h??void 0}))}),e.jsx(Ae,{descriptor:{key:"heartbeatScopeDiscipline",label:l("settings.scheduling.heartbeatScopeDiscipline","Heartbeat Scope Discipline"),help:l("settings.scheduling.strictCoordinationFocusedHigherPerTickTokensLite","Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure."),scope:"project",options:[{value:"strict",label:l("settings.scheduling.strictDefault","Strict (default)")},{value:"lite",label:l("settings.scheduling.lite","Lite")},{value:"off",label:l("settings.scheduling.off","Off")}]},value:t.heartbeatScopeDiscipline??"strict",onChange:h=>s(p=>({...p,heartbeatScopeDiscipline:h}))}),e.jsx(ae,{descriptor:{key:"engineerBacklogAutoClaim",label:l("settings.scheduling.letEngineerAgentsAutoClaimBacklogTasks"," Let engineer agents auto-claim backlog tasks "),help:l("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."),scope:"project"},value:t.engineerBacklogAutoClaim===!0,onChange:h=>s(p=>({...p,engineerBacklogAutoClaim:h===!0}))}),e.jsx(Pe,{descriptor:{key:"taskStuckTimeoutMs",label:l("settings.scheduling.stuckTaskTimeoutMinutes","Stuck Task Timeout (minutes)"),help:l("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)."),scope:"project",min:1,step:1},value:t.taskStuckTimeoutMs?Math.round(t.taskStuckTimeoutMs/6e4):null,onChange:h=>s(p=>({...p,taskStuckTimeoutMs:h!==null&&h>0?h*6e4:void 0}))}),e.jsx(Pe,{descriptor:{key:"buildTimeoutMs",label:l("settings.scheduling.buildTimeoutMinutes","Build/Verification Timeout (minutes)"),help:l("settings.scheduling.maximumTimeInMinutesForBuildVerificationCommands","Maximum time in minutes for build/verification commands before they are killed. Raise for large monorepo or Docker builds. Default: 5."),scope:"project",min:1,step:1},value:t.buildTimeoutMs?Math.round(t.buildTimeoutMs/6e4):null,onChange:h=>s(p=>({...p,buildTimeoutMs:h!==null&&h>0?h*6e4:void 0}))}),e.jsx(Pe,{descriptor:{key:"staleHighFanoutBlockerAgeThresholdMs",label:l("settings.scheduling.staleHighFanOutEscalationHours","Stale High Fan-out Escalation (hours)"),help:l("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."),scope:"project",min:1,step:1},value:t.staleHighFanoutBlockerAgeThresholdMs?Math.round(t.staleHighFanoutBlockerAgeThresholdMs/36e5):null,onChange:h=>s(p=>({...p,staleHighFanoutBlockerAgeThresholdMs:h!==null&&h>0?h*36e5:void 0}))}),e.jsx(ae,{descriptor:{key:"preserveProgressOnStuckRequeue",label:l("settings.scheduling.preserveStepProgressOnStuckTaskRequeue"," Preserve step progress on stuck-task requeue "),help:l("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."),scope:"project"},value:t.preserveProgressOnStuckRequeue!==!1,onChange:h=>s(p=>({...p,preserveProgressOnStuckRequeue:h===!0}))}),e.jsx(ae,{descriptor:{key:"specStalenessEnabled",label:l("settings.scheduling.enablePlanStalenessEnforcement"," Enable plan staleness enforcement "),help:l("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."),scope:"project"},value:t.specStalenessEnabled||!1,onChange:h=>s(p=>({...p,specStalenessEnabled:h===!0}))}),e.jsx(Pe,{descriptor:{key:"specStalenessMaxAgeMs",label:l("settings.scheduling.staleSpecThresholdHours","Stale Spec Threshold (hours)"),help:l("settings.scheduling.maximumAgeInHoursBeforeAPlanIs","Maximum age in hours before a plan is considered stale. Default: 6 hours."),scope:"project",min:0,step:1,disabled:!t.specStalenessEnabled},value:t.specStalenessMaxAgeMs!==void 0?Math.round(t.specStalenessMaxAgeMs/36e5):null,onChange:h=>s(p=>({...p,specStalenessMaxAgeMs:h!==null?h*36e5:void 0}))}),e.jsx(ae,{descriptor:{key:"autoArchiveDoneTasksEnabled",label:l("settings.scheduling.enableAutomaticTaskArchiving"," Enable automatic task archiving "),help:l("settings.scheduling.completedTasksOlderThanTheThresholdAreMoved","Completed tasks older than the threshold are moved out of the active task database. Default: enabled."),scope:"project"},value:t.autoArchiveDoneTasksEnabled??!0,onChange:h=>s(p=>({...p,autoArchiveDoneTasksEnabled:h===!0}))}),e.jsx(Pe,{descriptor:{key:"autoArchiveDoneAfterMs",label:l("settings.scheduling.archiveCompletedTasksAfterDays","Archive Completed Tasks After (days)"),help:l("settings.scheduling.numberOfDaysATaskCanStayIn","Number of days a task can stay in Done before it is archived. Default: 2 days (48 hours)."),scope:"project",min:1,step:1,disabled:t.autoArchiveDoneTasksEnabled===!1},value:t.autoArchiveDoneAfterMs!==void 0?Math.round(t.autoArchiveDoneAfterMs/zr):_g,onChange:h=>s(p=>({...p,autoArchiveDoneAfterMs:h===null?void 0:h*zr}))}),e.jsx(Ae,{descriptor:{key:"archiveAgentLogMode",label:l("settings.scheduling.archiveAgentLog","Archive Agent Log"),help:l("settings.scheduling.compactModeKeepsArchiveSizeLowWhilePreserving","Compact mode keeps archive size low while preserving recent agent activity for context. Default: compact."),scope:"project",disabled:t.autoArchiveDoneTasksEnabled===!1,options:[{value:"compact",label:l("settings.scheduling.compactSummaryAndRecentEntries","Compact summary and recent entries")},{value:"none",label:l("settings.scheduling.doNotArchiveAgentLogs","Do not archive agent logs")},{value:"full",label:l("settings.scheduling.fullAgentLog","Full agent log")}]},value:t.archiveAgentLogMode??"compact",onChange:h=>s(p=>({...p,archiveAgentLogMode:h}))}),e.jsx(ae,{descriptor:{key:"autoArchiveDuplicateTasksEnabled",label:l("settings.scheduling.autoArchiveDuplicateTasks"," Automatically archive duplicate tasks "),help:l("settings.scheduling.autoArchiveDuplicateTasksHelp","Automatically archive tasks detected as same-agent duplicates on creation (off by default). When disabled, duplicates are flagged in place with the yellow Duplicate chip and Keep/Archive actions instead of being archived automatically."),scope:"project"},value:t.autoArchiveDuplicateTasksEnabled??!1,onChange:h=>s(p=>({...p,autoArchiveDuplicateTasksEnabled:h===!0}))}),e.jsx(Ae,{descriptor:{key:"triageDuplicateResolution",label:l("settings.scheduling.triageDuplicateResolution","Triage duplicate resolution"),help:l("settings.scheduling.triageDuplicateResolutionHelp","Block triage duplicates for a linked Keep/Delete decision (default), keep automatically, or delete automatically."),scope:"project",options:[{value:"prompt",label:l("settings.scheduling.triageDuplicateResolutionPrompt","Block for decision (default)")},{value:"keep",label:l("settings.scheduling.triageDuplicateResolutionKeep","Keep automatically")},{value:"delete",label:l("settings.scheduling.triageDuplicateResolutionDelete","Delete automatically")}]},value:t.triageDuplicateResolution??"prompt",onChange:h=>s(p=>({...p,triageDuplicateResolution:h}))}),e.jsx(Pe,{descriptor:{key:"maxStuckKills",label:l("settings.scheduling.maxStuckRetries","Max Stuck Retries"),help:l("settings.scheduling.maximumStuckDetectorRetriesBeforeATaskIs","Maximum stuck-detector retries before a task is marked failed. Default: 6."),scope:"project",min:1,step:1},value:t.maxStuckKills??null,onChange:h=>s(p=>({...p,maxStuckKills:h!==null&&h>0?h:void 0}))}),e.jsx(ae,{descriptor:{key:"groupOverlappingFiles",label:l("settings.scheduling.serializeTasksWithOverlappingFiles"," Serialize tasks with overlapping files "),help:l("settings.scheduling.whenEnabledTasksThatModifyTheSameFiles","When enabled, tasks that modify the same files are queued serially to avoid merge conflicts. Default: enabled."),scope:"project"},value:t.groupOverlappingFiles,onChange:h=>s(p=>({...p,groupOverlappingFiles:h===!0}))}),e.jsx(ae,{descriptor:{key:"ignoreHiddenOverlapPaths",label:l("settings.scheduling.ignoreHiddenDotPathsInOverlapChecks"," Ignore hidden dot paths in overlap checks "),help:l("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."),scope:"project"},value:t.ignoreHiddenOverlapPaths!==!1,onChange:h=>s(p=>({...p,ignoreHiddenOverlapPaths:h===!0}))}),e.jsxs("div",{className:"form-group settings-overlap-ignore-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{children:l("settings.scheduling.ignoredOverlapPaths","Ignored overlap paths")}),e.jsxs(G,{settingKey:"overlapIgnorePaths",children:[l("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/"}),l("settings.scheduling.or"," or "),e.jsx("code",{children:"generated/*"}),l("settings.scheduling.closeParenPeriod",").")]})]}),e.jsx("div",{className:"settings-overlap-ignore-list",children:(t.overlapIgnorePaths&&t.overlapIgnorePaths.length>0?t.overlapIgnorePaths:[""]).map((h,p)=>e.jsxs("div",{className:"settings-overlap-ignore-row",children:[e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{className:"input",type:"text",value:h,placeholder:l("settings.scheduling.docs","docs/"),onChange:m=>n(p,m.target.value)}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>o(p),"aria-label":`Browse path for ignored overlap entry ${p+1}`,children:l("settings.scheduling.browse"," Browse ")})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>d(p),disabled:(t.overlapIgnorePaths??[]).length===0&&p===0,children:l("settings.scheduling.remove"," Remove ")})]},`overlap-ignore-${p}`))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,children:l("settings.scheduling.addIgnoredPath"," Add ignored path ")})]}),e.jsx("div",{className:"settings-section-divider"}),e.jsx("h5",{className:"settings-section-heading",children:l("settings.scheduling.stepExecution","Step Execution")}),e.jsx(Zn,{message:l("settings.movedStub.stepExecution","Step execution settings (run steps in new sessions, max parallel steps) now live on the workflow."),onOpenWorkflowSettings:c})]})}function Wg({defer:t=!1}){const{t:s}=le("app"),[a,n]=i.useState(null),[o,d]=i.useState(!1),[u,c]=i.useState(!1),[l,h]=i.useState(null),[p,m]=i.useState(null),[x,w]=i.useState(null),f=F=>{switch(F){case"installed":return{text:s("cliBinary.stateInstalled","Installed"),tone:"ok"};case"missing":return{text:s("cliBinary.stateMissing","Not installed"),tone:"err"};case"version-mismatch":return{text:s("cliBinary.stateVersionMismatch","Version mismatch"),tone:"warn"};case"skipped":return{text:s("cliBinary.stateCheckDisabled","Check disabled"),tone:"warn"}}},E=i.useCallback(async()=>{d(!0),m(null);try{const F=await Yd();n(F)}catch(F){m(F instanceof Error?F.message:String(F))}finally{d(!1)}},[]);i.useEffect(()=>{t||E()},[t,E]);const N=i.useCallback(async()=>{c(!0),h(null),m(null);try{const F=await Qd();n({binary:F.binary,expectedVersion:F.expectedVersion,state:F.state,install:F.install}),h(F.installResult)}catch(F){m(F instanceof Error?F.message:String(F))}finally{c(!1)}},[]),S=i.useCallback(async(F,K)=>{await qn(K)&&(w(F),setTimeout(()=>w(T=>T===F?null:T),1500))},[]),L=a?f(a.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:s("cliBinary.heading","CLI Binary")}),L&&e.jsx("span",{className:`cli-binary-pill cli-binary-pill--${L.tone}`,children:L.text})]}),e.jsx("small",{className:"cli-binary-help",children:s("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.")}),o&&!a&&e.jsx("p",{className:"cli-binary-status-line",children:s("cliBinary.checking","Checking…")}),a&&e.jsxs("div",{className:"cli-binary-detail",children:[a.binary.installed?e.jsxs("ul",{className:"cli-binary-info-list",children:[e.jsxs("li",{children:[e.jsx("span",{children:s("cliBinary.binaryLabel","Binary:")}),e.jsx("code",{children:a.binary.binary})]}),a.binary.path&&e.jsxs("li",{children:[e.jsx("span",{children:s("cliBinary.pathLabel","Path:")}),e.jsx("code",{children:a.binary.path})]}),e.jsxs("li",{children:[e.jsx("span",{children:s("cliBinary.versionLabel","Version:")}),e.jsx("code",{children:a.binary.version??"unknown"}),e.jsx("span",{className:"cli-binary-expected",children:s("cliBinary.expectedVersion","(expected {{version}})",{version:a.expectedVersion})})]})]}):e.jsx("p",{className:"cli-binary-status-line",children:s("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:N,disabled:u,children:u?s("cliBinary.installing","Installing…"):a.binary.installed?s("cliBinary.reinstall","Reinstall"):s("cliBinary.installWithNpm","Install with npm")}),e.jsx("button",{type:"button",className:"cli-binary-refresh-btn",onClick:()=>void E(),disabled:o||u,children:s("cliBinary.refresh","Refresh")})]}),e.jsxs("div",{className:"cli-binary-commands",children:[e.jsx("label",{children:s("cliBinary.orCopyLabel","Or copy and run yourself:")}),[{label:"npm",command:a.install.npm},{label:"curl",command:a.install.curl}].map(({label:F,command:K})=>e.jsxs("div",{className:"cli-binary-command-row",children:[e.jsx("code",{children:K}),e.jsx("button",{type:"button",onClick:()=>void S(F,K),className:"cli-binary-copy-btn",children:x===F?s("cliBinary.copied","Copied"):s("cliBinary.copy","Copy")})]},F))]})]}),l&&e.jsxs("details",{className:"cli-binary-install-log",open:!l.success,children:[e.jsx("summary",{children:l.success?s("cliBinary.succeededDuration","Install succeeded in {{duration}}s",{duration:(l.durationMs/1e3).toFixed(1)}):s("cliBinary.failedExit","Install failed (exit {{code}})",{code:l.exitCode??"n/a"})}),l.permissionsHint&&e.jsx("p",{className:"cli-binary-permissions-hint",children:l.permissionsHint}),l.stdout&&e.jsx("pre",{className:"cli-binary-install-output",children:l.stdout}),l.stderr&&e.jsx("pre",{className:"cli-binary-install-output cli-binary-install-output--err",children:l.stderr})]}),p&&e.jsx("p",{className:"field-error",children:p})]})}function $g(){const{t}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:t("settings.nav.cliBinary","CLI Binary")}),e.jsx(Wg,{})]})}function zg({form:t,setForm:s}){const{t:a}=le("app"),n=t.evalSettings??{},o=n.enabled??!1;return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.scheduledEvals.scheduledEvals","Scheduled Evals")}),e.jsx(ae,{descriptor:{key:"evalSettings.enabled",label:a("settings.scheduledEvals.enableScheduledEvalRunsForThisProject"," Enable scheduled eval runs for this project "),help:a("settings.scheduledEvals.enabledHint","Default: disabled."),scope:"project"},value:o,onChange:d=>s(u=>({...u,evalSettings:{...u.evalSettings??{},enabled:d===!0}}))}),e.jsx(Pe,{descriptor:{key:"evalSettings.intervalMs",label:a("settings.scheduledEvals.intervalMs","Interval (ms)"),help:a("settings.scheduledEvals.intervalMsHint","Default: 86400000 (24 hours)."),scope:"project",disabled:!o,min:6e4,max:6048e5,step:1e3},value:n.intervalMs??864e5,onChange:d=>s(u=>({...u,evalSettings:{...u.evalSettings??{},intervalMs:d===null?void 0:d}}))}),e.jsx(be,{descriptor:{key:"evalSettings.evaluatorProvider",label:a("settings.scheduledEvals.evaluatorProvider","Evaluator Provider"),help:a("settings.scheduledEvals.evaluatorProviderHint","No default — unset (inherits the project validator lane provider)."),scope:"project",placeholder:a("settings.scheduledEvals.openai","openai")},value:n.evaluatorProvider??"",onChange:d=>s(u=>({...u,evalSettings:{...u.evalSettings??{},evaluatorProvider:(d??"").trim()===""?void 0:d??void 0}}))}),e.jsx(be,{descriptor:{key:"evalSettings.evaluatorModelId",label:a("settings.scheduledEvals.evaluatorModel","Evaluator Model"),help:a("settings.scheduledEvals.leaveProviderAndModelBlankToInheritThe"," Leave provider and model blank to inherit the project validator lane model settings. No default — unset. "),scope:"project",placeholder:a("settings.scheduledEvals.gpt5","gpt-5")},value:n.evaluatorModelId??"",onChange:d=>s(u=>({...u,evalSettings:{...u.evalSettings??{},evaluatorModelId:(d??"").trim()===""?void 0:d??void 0}}))}),e.jsx(Ae,{descriptor:{key:"evalSettings.followUpPolicy",label:a("settings.scheduledEvals.followUpPolicy","Follow-up Policy"),help:a("settings.scheduledEvals.followUpPolicyHint","Default: suggest only."),scope:"project",disabled:!o,options:[{value:"disabled",label:a("settings.scheduledEvals.disabled","Disabled")},{value:"suggest-only",label:a("settings.scheduledEvals.suggestOnly","Suggest only")},{value:"auto-create",label:a("settings.scheduledEvals.autoCreateTasks","Auto-create tasks")}]},value:n.followUpPolicy??"suggest-only",onChange:d=>s(u=>({...u,evalSettings:{...u.evalSettings??{},followUpPolicy:d}}))}),e.jsx(Pe,{descriptor:{key:"evalSettings.retentionDays",label:a("settings.scheduledEvals.retentionDays","Retention (days)"),help:a("settings.scheduledEvals.retentionDaysHint","Default: 30."),scope:"project",disabled:!o,min:1,max:365,step:1},value:n.retentionDays??30,onChange:d=>s(u=>({...u,evalSettings:{...u.evalSettings??{},retentionDays:d===null?void 0:d}}))})]})}function qg(t,s){return t==="online"?s("settings.nodeRouting.statusOnline","Online"):t==="connecting"?s("settings.nodeRouting.statusConnecting","Connecting"):t==="error"?s("settings.nodeRouting.statusError","Error"):s("settings.nodeRouting.statusOffline","Offline")}function Vg({form:t,setForm:s,nodes:a}){const{t:n}=le("app");return e.jsxs(e.Fragment,{children:[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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"defaultNodeId",children:n("settings.nodeRouting.defaultExecutionNode","Default Execution Node")}),e.jsx(G,{settingKey:"defaultNodeId",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("select",{id:"defaultNodeId",className:"select",value:typeof t.defaultNodeId=="string"?t.defaultNodeId:"",onChange:o=>{const d=o.target.value;s(u=>({...u,defaultNodeId:d||void 0}))},children:[e.jsx("option",{value:"",children:n("settings.nodeRouting.localExecutionNoDefaultNode","Local execution (no default node)")}),a.map(o=>e.jsxs("option",{value:o.id,children:[o.name," (",qg(o.status,n),")"]},o.id))]}),(()=>{const o=a.find(d=>d.id===t.defaultNodeId);return o?e.jsxs("div",{className:"settings-node-status",children:[e.jsx("span",{children:n("settings.nodeRouting.selectedNode","Selected node:")}),e.jsx(Jd,{status:o.status,showLabel:!0})]}):null})()]}),e.jsx(Ae,{descriptor:{key:"unavailableNodePolicy",label:n("settings.nodeRouting.unavailableNodePolicy","Unavailable Node Policy"),help:n("settings.nodeRouting.unavailableNodePolicyHint","Default: block execution."),scope:"project",options:[{value:"block",label:n("settings.nodeRouting.blockExecution","Block execution")},{value:"fallback-local",label:n("settings.nodeRouting.fallBackToLocal","Fall back to local")}]},value:t.unavailableNodePolicy==="fallback-local"?"fallback-local":"block",onChange:o=>s(d=>({...d,unavailableNodePolicy:o}))})]})}function Yg({form:t,setForm:s,gitRemotes:a,worktrunkInstall:n,worktrunkInstallVerified:o,onOpenWorktreesDirPicker:d,onWorktreeCopyFileChange:u,onRemoveWorktreeCopyFile:c,onAddWorktreeCopyFile:l,onOpenWorktreeCopyFilePicker:h,onOpenApprovals:p}){const{t:m}=le("app"),x=(t.worktreeCopyFiles?.length??0)>0?t.worktreeCopyFiles??[]:[""];return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:m("settings.worktrees.worktrees","Worktrees")}),e.jsx(ae,{descriptor:{key:"worktreeLimitEnabled",label:m("settings.worktrees.worktreeLimitEnabled","Limit concurrent worktrees"),help:m("settings.worktrees.worktreeLimitEnabledHelp","When on, Max Worktrees caps how many tasks may hold a worktree at once. When off, Max Concurrent Tasks is the only limit. Tasks always run in their own git worktree either way — this does not change where work executes. Default: on."),scope:"project"},value:t.worktreeLimitEnabled!==!1,onChange:w=>s(f=>({...f,worktreeLimitEnabled:w!==!1}))}),e.jsx(Pe,{descriptor:{key:"maxWorktrees",label:m("settings.worktrees.maxWorktrees","Max Worktrees"),help:m("settings.worktrees.limitsTotalGitWorktreesIncludingInReviewTasks","Limits total git worktrees including in-review tasks. Ignored while “Limit concurrent worktrees” is off. Default: 4."),scope:"project",min:1,max:20,disabled:t.worktreeLimitEnabled===!1},value:t.maxWorktrees??null,onChange:w=>s(f=>({...f,maxWorktrees:w??void 0}))}),e.jsx(be,{descriptor:{key:"worktreeInitCommand",label:m("settings.worktrees.worktreeInitCommand","Worktree Init Command"),help:m("settings.worktrees.shellCommandToRunInEachNewWorktree","Shell command to run in each new worktree after creation. No default — unset."),scope:"project",placeholder:m("settings.worktrees.pnpmInstallFrozenLockfile","pnpm install --frozen-lockfile")},value:t.worktreeInitCommand??null,onChange:w=>s(f=>({...f,worktreeInitCommand:w??""}))}),e.jsx(ae,{descriptor:{key:"recycleWorktrees",label:m("settings.worktrees.recycleWorktrees"," Recycle worktrees "),help:t.worktreeNaming==="task-id"&&t.recycleWorktrees!==!0?m("settings.worktrees.recycleNotApplicableWithTaskIdNaming","Not available with Task ID worktree naming — that mode pins each task to its own worktree directory, which is mutually exclusive with the recycle pool. Switch naming to Random or Task title to enable recycling."):m("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. Mutually exclusive with Task ID worktree naming."),scope:"project",disabled:t.worktreeNaming==="task-id"&&t.recycleWorktrees!==!0},value:t.recycleWorktrees===!0,onChange:w=>s(f=>({...f,recycleWorktrees:w===!0}))}),e.jsx(ae,{descriptor:{key:"showWorktreeGrouping",label:m("settings.worktrees.showWorktreeGrouping"," Show worktree grouping on the board "),help:m("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."),scope:"project"},value:t.showWorktreeGrouping===!0,onChange:w=>s(f=>({...f,showWorktreeGrouping:w===!0}))}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{children:m("settings.worktrees.filesToCopyIntoNewWorktrees","Files to copy into new worktrees")}),e.jsx(G,{settingKey:"worktreeCopyFiles",children:m("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.jsx("div",{className:"settings-overlap-ignore-list","data-testid":"worktree-copy-files-list",children:x.map((w,f)=>e.jsxs("div",{className:"settings-overlap-ignore-row",children:[e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{id:`worktreeCopyFile-${f}`,type:"text",className:"input",placeholder:m("settings.worktrees.copyFilePlaceholder",".env"),value:w,onChange:E=>u(f,E.target.value),"aria-label":m("settings.worktrees.copyFilePathLabel","File to copy into new worktrees")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>h(f),"aria-label":m("settings.worktrees.browseCopyFile","Browse file to copy into new worktrees"),children:m("settings.worktrees.browse"," Browse ")})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>c(f),"aria-label":m("settings.worktrees.removeCopyFile","Remove copied worktree file"),children:m("settings.worktrees.remove","Remove")})]},f))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:l,children:m("settings.worktrees.addCopyFile","Add file")})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"executorAllowSiblingBranchRename",className:"checkbox-label",children:[e.jsx("input",{id:"executorAllowSiblingBranchRename",type:"checkbox",checked:t.executorAllowSiblingBranchRename===!0,onChange:w=>s(f=>({...f,executorAllowSiblingBranchRename:w.target.checked}))}),m("settings.worktrees.allowSilentSiblingBranchRenameDuringExecutorConflicts"," Allow silent sibling branch rename during executor conflicts ")]}),e.jsxs(G,{settingKey:"executorAllowSiblingBranchRename",children:[m("settings.worktrees.discouragedThisRestoresTheLegacyBehaviorWhereA"," Discouraged. This restores the legacy behavior where a live "),e.jsx("code",{children:"fusion/<task-id>"}),m("settings.worktrees.branchCollisionSilentlyForksWorkOntoSiblingBranches"," branch collision silently forks work onto sibling branches like "),e.jsx("code",{children:"-2"}),m("settings.worktrees.andCanHidePriorCommitsFromTheDefault"," and can hide prior commits from the default recovery flow. Default: disabled. ")]})]})}),e.jsx(Ae,{descriptor:{key:"worktreeNaming",label:m("settings.worktrees.worktreeNamingStyle","Worktree Naming Style"),help:t.recycleWorktrees?m("settings.worktrees.namingStyleNotApplicableWhenRecycling",'Naming style is not applicable when recycling worktrees — pooled worktrees retain their existing names. "Task ID" is unavailable here because task-pinned worktrees are mutually exclusive with recycling; turn off Recycle worktrees to use it.'):m("settings.worktrees.howToNameFreshWorktreeDirectories",'How to name fresh worktree directories. Only applies when recycling is off. "Task ID" also pins each task to its own worktree directory for its whole lifecycle (mutually exclusive with recycling). Default: random.'),scope:"project",disabled:t.recycleWorktrees,options:[{value:"random",label:m("settings.worktrees.randomNamesEGSwiftFalcon","Random names (e.g., swift-falcon)")},{value:"task-id",label:m("settings.worktrees.taskIDEGFN042","Task ID (e.g., FN-042)")},{value:"task-title",label:m("settings.worktrees.taskTitleEGFixLoginBug","Task title (e.g., fix-login-bug)")}]},value:t.worktreeNaming||"random",onChange:w=>s(f=>({...f,worktreeNaming:w}))}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"worktreesDir",children:m("settings.worktrees.worktreesDirectory","Worktrees Directory")}),e.jsx(G,{settingKey:"worktreesDir",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:[m("settings.worktrees.optionalSupports"," Optional. Supports "),e.jsx("code",{children:"~"}),m("settings.worktrees.and"," and "),e.jsx("code",{children:"{repo}"}),m("settings.worktrees.defaultsTo",". Defaults to "),e.jsx("code",{children:"<projectRoot>/.worktrees"}),m("settings.worktrees.whenUnsetOnlyAffectsNewlyCreatedWorktrees"," when unset. Only affects newly-created worktrees. ")]})})]}),e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{id:"worktreesDir",type:"text",placeholder:m("settings.worktrees.defaultsToWorktreesLeaveEmptyUnlessOverriding","Defaults to .worktrees — leave empty unless overriding"),value:t.worktreesDir||"",disabled:t.worktrunk?.enabled===!0,onChange:w=>s(f=>({...f,worktreesDir:w.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:d,"aria-label":m("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),disabled:t.worktrunk?.enabled===!0,children:m("settings.worktrees.browse"," Browse ")})]})]}),e.jsx(ae,{descriptor:{key:"worktreeRebaseBeforeMerge",label:m("settings.worktrees.rebaseFromRemoteBeforeMerge"," Rebase from remote before merge "),help:m("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."),scope:"project"},value:t.worktreeRebaseBeforeMerge!==!1,onChange:w=>s(f=>({...f,worktreeRebaseBeforeMerge:w===!0}))}),t.worktreeRebaseBeforeMerge!==!1&&e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"worktreeRebaseRemote",children:m("settings.worktrees.rebaseRemote","Rebase Remote")}),e.jsxs(G,{settingKey:"worktreeRebaseRemote",children:[m("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"}),m("settings.worktrees.closeParenPeriod",").")]})]}),e.jsxs("select",{id:"worktreeRebaseRemote",value:t.worktreeRebaseRemote??"",onChange:w=>s(f=>({...f,worktreeRebaseRemote:w.target.value||void 0})),children:[e.jsx("option",{value:"",children:m("settings.worktrees.useGitDefault","Use git default")}),a.map(w=>e.jsxs("option",{value:w.name,children:[w.name," (",w.fetchUrl,")"]},w.name))]})]}),e.jsx(ae,{descriptor:{key:"worktreeRebaseLocalBase",label:m("settings.worktrees.alsoRebaseOntoLocalDefaultBranchHEAD"," Also rebase onto local default-branch HEAD "),help:m("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. "),scope:"project"},value:t.worktreeRebaseLocalBase!==!1,onChange:w=>s(f=>({...f,worktreeRebaseLocalBase:w===!0}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:m("settings.worktrees.worktrunkIntegration","Worktrunk integration")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"worktrunkEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"worktrunkEnabled",type:"checkbox",checked:t.worktrunk?.enabled===!0,disabled:!o&&t.worktrunk?.enabled!==!0,onChange:w=>s(f=>({...f,worktrunk:{enabled:w.target.checked,binaryPath:f.worktrunk?.binaryPath??"",onFailure:f.worktrunk?.onFailure??"fail"}}))}),m("settings.worktrees.enableWorktrunkIntegration"," Enable worktrunk integration ")]}),e.jsxs(G,{settingKey:"worktrunkEnabled",children:[m("settings.worktrees.disabledByDefaultOptInWhenEnabledFusion"," Disabled by default (opt-in). When enabled, Fusion shells out to "),e.jsx("code",{children:"worktrunk"}),m("settings.worktrees.forWorktreeCreateSyncPruneAndRemoveOperations"," for worktree create, sync, prune, and remove operations and follows worktrunk's directory layout. ")]})]}),!o&&t.worktrunk?.enabled!==!0&&e.jsx("small",{className:"settings-muted",children:m("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:[m("settings.worktrees.worktrunk"," worktrunk "),n.version??"",m("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:m("settings.worktrees.installWorktrunk","Install worktrunk binary")}),e.jsx("small",{className:"settings-muted",children:m("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:m("settings.worktrees.awaitingApproval","Awaiting approval — open Approvals to continue.")}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>p?.(n.pendingApprovalId),children:m("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:m("settings.worktrees.tryAgain","Try again")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"worktrunkBinaryPath",children:m("settings.worktrees.worktrunkBinaryPath","Worktrunk binary path")}),e.jsx(G,{settingKey:"worktrunkBinaryPath",children:m("settings.worktrees.optionalLeaveBlankToAutoResolveFusionWill","Optional. Leave blank to auto-resolve; Fusion will offer to install on first use.")})]}),e.jsx("input",{id:"worktrunkBinaryPath",type:"text",className:"input",placeholder:m("settings.worktrees.autoDetectFusionBinWorktrunkOrPATH","auto-detect (~/.fusion/bin/worktrunk or $PATH)"),value:t.worktrunk?.binaryPath??"",disabled:t.worktrunk?.enabled!==!0,onChange:w=>s(f=>({...f,worktrunk:{enabled:f.worktrunk?.enabled===!0,binaryPath:w.target.value,onFailure:f.worktrunk?.onFailure??"fail"}}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"worktrunkOnFailure",children:m("settings.worktrees.worktrunkFailureBehavior","Worktrunk failure behavior")}),e.jsxs(G,{settingKey:"worktrunkOnFailure",children:[e.jsx("code",{children:"fail"}),m("settings.worktrees.stopsOnWorktrunkErrorsForExplicitOperatorRecovery"," stops on worktrunk errors for explicit operator recovery; "),e.jsx("code",{children:"fallback-native"}),m("settings.worktrees.keepsProgressMovingBySwitchingToFusionApos"," keeps progress moving by switching to Fusion's built-in worktree backend. ")]})]}),e.jsxs("select",{id:"worktrunkOnFailure",className:"select",value:t.worktrunk?.onFailure??"fail",disabled:t.worktrunk?.enabled!==!0,onChange:w=>s(f=>({...f,worktrunk:{enabled:f.worktrunk?.enabled===!0,binaryPath:f.worktrunk?.binaryPath??"",onFailure:w.target.value}})),children:[e.jsx("option",{value:"fail",children:m("settings.worktrees.failAndPauseTheTaskDefault","Fail and pause the task (default)")}),e.jsx("option",{value:"fallback-native",children:m("settings.worktrees.fallBackToFusionsNativeWorktreeBackend","Fall back to Fusion's native worktree backend")})]})]})]})}function Qg({form:t,setForm:s}){const{t:a}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.commands.commands","Commands")}),e.jsx(be,{descriptor:{key:"testCommand",label:a("settings.commands.testCommand","Test Command"),help:a("settings.commands.commandUsedToRunTestsInjectedIntoGenerated","Command used to run tests — injected into generated task specs. No default — unset."),scope:"project",placeholder:a("settings.commands.eGPnpmTest","e.g. pnpm test")},value:t.testCommand??null,onChange:n=>s(o=>({...o,testCommand:n||void 0}))}),e.jsx(be,{descriptor:{key:"buildCommand",label:a("settings.commands.buildCommand","Build Command"),help:a("settings.commands.commandUsedToBuildTheProjectInjectedInto","Command used to build the project — injected into generated task specs. No default — unset."),scope:"project",placeholder:a("settings.commands.eGPnpmBuild","e.g. pnpm build")},value:t.buildCommand??null,onChange:n=>s(o=>({...o,buildCommand:n||void 0}))})]})}function Jg(t){const s=(t??"").trim().split(/\s+/).filter(Boolean);return{remote:s[0]??"origin",branch:s.slice(1).join(" ")}}function da(t,s){const a=t.trim()||"origin",n=s.trim();return n?`${a} ${n}`:a==="origin"?void 0:a}function Xg(t){const s=Number(t);return Number.isFinite(s)&&s>0?Math.floor(s):3}async function Zg(t){if(!t.ok)throw new Error(await t.text()||"Failed to load legacy auto-merge stamps");return t.json()}function eh({form:t,setForm:s,integrationBranchOptions:a,integrationBranchCustomMode:n,setIntegrationBranchCustomMode:o,onOpenWorkflowSettings:d,gitRemoteOptions:u=[],projectId:c}){const{t:l}=le("app"),[h,p]=i.useState(()=>(t.requiredChecks??[]).join(", ")),m=i.useRef(kn(t));i.useEffect(()=>{const v=kn(t);v.join("\0")!==m.current.join("\0")&&p(v.join(", ")),m.current=v},[t.requiredChecks]);const x=Jg(t.pushRemote),[w,f]=i.useState([]),[E,N]=i.useState(!1);i.useEffect(()=>{if(!t.pushAfterMerge||u.length===0)return;let v=!1;return Xd(x.remote,c).then(M=>{v||f(M)}).catch(()=>{v||f([])}),()=>{v=!0}},[t.pushAfterMerge,x.remote,c,u.length]);const[S,L]=i.useState([]),[F,K]=i.useState(!0),[R,T]=i.useState(!1),[b,V]=i.useState(null),[X,k]=i.useState(null),I=i.useCallback(async()=>{K(!0),V(null);try{const v=await Zg(await fetch("/api/maintenance/legacy-automerge-stamps"));L(Array.isArray(v.candidates)?v.candidates:[])}catch(v){V(v instanceof Error?v.message:"Failed to load legacy auto-merge stamps")}finally{K(!1)}},[]);i.useEffect(()=>{I()},[I]);const B=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.")){T(!0),V(null),k(null);try{const M=await fetch("/api/maintenance/legacy-automerge-stamps/apply",{method:"POST"});if(!M.ok)throw new Error(await M.text()||"Failed to apply legacy auto-merge stamp cleanup");const se=await M.json();k(`Cleared ${se.count} legacy auto-merge stamp${se.count===1?"":"s"}.`),await I()}catch(M){V(M instanceof Error?M.message:"Failed to apply legacy auto-merge stamp cleanup")}finally{T(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:l("settings.merge.merge","Merge")}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"autoMerge",className:"checkbox-label",children:[e.jsx("input",{id:"autoMerge",type:"checkbox",checked:t.autoMerge,onChange:v=>s(M=>({...M,autoMerge:v.target.checked}))}),l("settings.merge.autoMergeCompletedTasks"," Auto-merge completed tasks ")]}),e.jsx(G,{settingKey:"autoMerge",children:l("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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"planApprovalMode",children:l("settings.merge.planApprovalMode","Plan approval mode")}),e.jsx(G,{settingKey:"planApprovalMode",children:l("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("select",{id:"planApprovalMode",className:"select",value:t.planApprovalMode??"auto-approve-all",onChange:v=>{const M=v.target.value;s(se=>({...se,planApprovalMode:M}))},"data-testid":"plan-approval-mode-select",children:[e.jsx("option",{value:"workflow",children:l("settings.merge.planApprovalModeWorkflow","Use workflow setting")}),e.jsx("option",{value:"auto-approve-all",children:l("settings.merge.planApprovalModeAutoApproveAll","Auto-approve all tasks (default)")}),e.jsx("option",{value:"require-all",children:l("settings.merge.planApprovalModeRequireAll","Require approval for all tasks")})]})]}),e.jsx(Pe,{descriptor:{key:"maxAutoMergeRetries",label:l("settings.merge.autoMergeConflictRetries","Auto-merge conflict retries"),help:l("settings.merge.positiveIntegerRetryCapForAutoMergeConflict","Positive integer retry cap for auto-merge conflict resolution before a task parks for human recovery. Default 3."),scope:"project",min:1,step:1},value:t.maxAutoMergeRetries??3,onChange:v=>s(M=>({...M,maxAutoMergeRetries:v===null?void 0:Xg(v)}))}),e.jsxs("div",{className:"form-group","data-testid":"legacy-automerge-stamp-cleanup-panel",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h5",{className:"settings-section-heading",children:l("settings.merge.legacyAutoMergeStampCleanup","Legacy auto-merge stamp cleanup")}),e.jsx(G,{settingKey:"legacy-automerge-stamp-cleanup",children:l("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. ")})]}),F?e.jsx("small",{"aria-live":"polite",children:l("settings.merge.checkingForLegacyAutoMergeStamps","Checking for legacy auto-merge stamps…")}):S.length===0?e.jsx("small",{"data-testid":"legacy-automerge-stamp-empty-state",children:l("settings.merge.noLegacyAutoMergeStampsToCleanUp"," No legacy auto-merge stamps to clean up. ")}):e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:[S.length,l("settings.merge.legacyAutoMergeStamp"," legacy auto-merge stamp"),S.length===1?"":"s",l("settings.merge.readyToCleanUp"," ready to clean up.")]}),e.jsx("ul",{children:S.map(v=>e.jsxs("li",{"data-testid":"legacy-automerge-stamp-candidate-row",children:[e.jsx("strong",{children:v.taskId})," — ",v.column]},v.taskId))}),e.jsx("button",{type:"button",className:"btn",onClick:B,disabled:R,"data-testid":"legacy-automerge-stamp-apply-button",children:R?"Applying cleanup…":"Apply cleanup"})]}),X?e.jsx("small",{className:"settings-success","aria-live":"polite",children:X}):null,b?e.jsx("small",{className:"settings-error",role:"alert",children:b}):null]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"mergerMode",children:l("settings.merge.aIMerge","AI merge")}),e.jsxs(G,{settingKey:"mergerMode",children:[l("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:l("settings.merge.theLegacyMergeSettingsBelowDoNotApply","The legacy merge settings below do not apply while AI merge is on.")})]})]}),e.jsxs("select",{id:"mergerMode",className:"select",value:t.merger?.mode??"ai",onChange:v=>s(M=>({...M,merger:{...M.merger??{},mode:v.target.value}})),children:[e.jsx("option",{value:"ai",children:l("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:l("settings.merge.deterministicLegacyRebaseConflictStrategyAuditPipeline","Deterministic (legacy) — rebase / conflict-strategy / audit pipeline")})]})]}),(t.merger?.mode??"ai")==="ai"&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{descriptor:{key:"merger.maxReviewPasses",label:l("settings.merge.maxAIReviewPasses","Max AI review passes"),help:l("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."),scope:"project",min:0,max:10},value:t.merger?.maxReviewPasses??3,onChange:v=>s(M=>({...M,merger:{...M.merger??{},maxReviewPasses:v??void 0}}))}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"mergerAllowDirtyLocalCheckoutSync",className:"checkbox-label",children:[e.jsx("input",{id:"mergerAllowDirtyLocalCheckoutSync",type:"checkbox",checked:t.merger?.allowDirtyLocalCheckoutSync===!0,onChange:v=>s(M=>({...M,merger:{...M.merger??{},allowDirtyLocalCheckoutSync:v.target.checked}}))}),l("settings.merge.allowAIMergeToSyncADirtyChecked"," Allow AI merge to sync a dirty checked-out integration branch ")]}),e.jsx(G,{settingKey:"merger.allowDirtyLocalCheckoutSync",children:l("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.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"testMode",className:"checkbox-label",children:[e.jsx("input",{id:"testMode",type:"checkbox",checked:t.testMode===!0,onChange:v=>s(M=>({...M,testMode:v.target.checked}))}),l("settings.merge.enableTestMode"," Enable test mode ")]}),e.jsx(G,{settingKey:"testMode",children:l("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(Zn,{message:l("settings.movedStub.reviewVerification","Review, verification auto-fix, and scope-enforcement settings now live on the workflow."),onOpenWorkflowSettings:d}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"mergeStrategy",children:l("settings.merge.autoCompletionMode","Auto-completion mode")}),e.jsx(G,{settingKey:"mergeStrategy",children:l("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("select",{id:"mergeStrategy",value:t.mergeStrategy||"direct",onChange:v=>s(M=>({...M,mergeStrategy:v.target.value})),children:[e.jsx("option",{value:"direct",children:l("settings.merge.directMergeIntoTheCurrentBranch","Direct merge into the current branch (default)")}),e.jsx("option",{value:"pull-request",children:l("settings.merge.createMonitorAndMergeAGitHubPullRequest","Create, monitor, and merge a GitHub pull request")})]})]}),t.mergeStrategy==="pull-request"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"requiredChecks",children:l("settings.merge.requiredChecks","Required pull-request checks")}),e.jsx(G,{settingKey:"requiredChecks",children:l("settings.merge.requiredChecksHelp","No default — unset. Comma-separated check names match GitHub exactly (case-sensitive). Leaving this empty uses GitHub required-status checks only; a named check that never reports blocks the merge.")})]}),e.jsx("input",{id:"requiredChecks",className:"input",value:h,onChange:v=>{const M=v.target.value;p(M);const se=kn({requiredChecks:M.split(",")});m.current=se,s(ne=>({...ne,requiredChecks:se.length>0?se:void 0}))}})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"githubNativeAutoMerge",className:"checkbox-label",children:[e.jsx("input",{id:"githubNativeAutoMerge",type:"checkbox",checked:t.githubNativeAutoMerge===!0,onChange:v=>s(M=>({...M,githubNativeAutoMerge:v.target.checked}))}),l("settings.merge.githubNativeAutoMerge","Use GitHub native auto-merge")]}),e.jsx(G,{settingKey:"githubNativeAutoMerge",children:l("settings.merge.githubNativeAutoMergeHelp","GitHub waits for its full ruleset before merging. The repository must allow auto-merge; Fusion fails closed if it is unavailable. Default: disabled.")})]})})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"integrationBranch",children:l("settings.merge.integrationBranch","Integration branch")}),e.jsxs(G,{settingKey:"integrationBranch",children:[l("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:l("settings.merge.autoDetect","auto-detect")}),l("settings.merge.toResolveViaTheStandardCascade"," to resolve via the standard cascade ("),e.jsx("code",{children:"integrationBranch"}),l("settings.merge.legacy"," → legacy "),e.jsx("code",{children:"baseBranch"})," →",e.jsx("code",{children:"origin/HEAD"}),l("settings.merge.symbolicRefFallback"," symbolic ref → fallback "),e.jsx("code",{children:"main"}),l("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"}),l("settings.merge.and",", and "),e.jsx("code",{children:"develop"}),l("settings.merge.areListedFirstOrChoose"," are listed first — or choose "),e.jsx("em",{children:l("settings.merge.custom","Custom…")}),l("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. ")]})]}),(()=>{const v=t.integrationBranch??"",M=v.length>0&&a.includes(v);if(n||v.length>0&&!M)return e.jsxs("div",{className:"form-inline-group",children:[e.jsx("input",{id:"integrationBranch",type:"text",className:"input",placeholder:l("settings.merge.branchName","branch name"),value:v,onChange:j=>{const W=j.target.value.trim();s(ce=>({...ce,integrationBranch:W.length===0?void 0:W}))},"data-testid":"integration-branch-custom-input"}),e.jsx("button",{type:"button",className:"btn-link",onClick:()=>{o(!1),s(j=>({...j,integrationBranch:void 0}))},"data-testid":"integration-branch-use-dropdown",children:l("settings.merge.useDropdown"," Use dropdown ")})]});const ne="__fusion-custom__",pe="";return e.jsxs("select",{id:"integrationBranch",className:"select",value:v,onChange:j=>{const W=j.target.value;if(W===ne){o(!0);return}s(ce=>({...ce,integrationBranch:W===pe?void 0:W}))},"data-testid":"integration-branch-select",children:[e.jsx("option",{value:pe,children:l("settings.merge.autoDetectOriginHEADMain","(auto-detect — origin/HEAD → main)")}),a.map(j=>e.jsx("option",{value:j,children:j},j)),e.jsx("option",{value:ne,children:l("settings.merge.custom","Custom…")})]})})()]}),t.mergeStrategy!=="pull-request"&&(t.merger?.mode??"ai")!=="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"directMergeCommitStrategy",children:l("settings.merge.directMergeCommitRouting","Direct merge commit routing")}),e.jsxs(G,{settingKey:"directMergeCommitStrategy",children:[l("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("select",{id:"directMergeCommitStrategy",className:"select",value:t.directMergeCommitStrategy??"always-squash",onChange:v=>s(M=>({...M,directMergeCommitStrategy:v.target.value})),children:[e.jsx("option",{value:"auto",children:l("settings.merge.autoSquashSingleSubstantiveBranchesPreserveMultiSubstantive","Auto — squash single-substantive branches, preserve multi-substantive history")}),e.jsx("option",{value:"always-squash",children:l("settings.merge.alwaysSquashDirectMerges","Always squash direct merges (default)")}),e.jsx("option",{value:"always-rebase",children:l("settings.merge.alwaysPreserveDirectMergeCommitHistory","Always preserve direct-merge commit history")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"mergeIntegrationWorktree",children:l("settings.merge.integrationWorktree","Integration worktree")}),e.jsx(G,{settingKey:"mergeIntegrationWorktree",children:l("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. ")})]}),e.jsxs("select",{id:"mergeIntegrationWorktree",className:"select",value:t.mergeIntegrationWorktree??"reuse-task-worktree",onChange:v=>s(M=>({...M,mergeIntegrationWorktree:v.target.value})),children:[e.jsx("option",{value:"reuse-task-worktree",children:l("settings.merge.reuseTaskWorktreeDefault","Reuse task worktree (default)")}),e.jsx("option",{value:"cwd-main",children:l("settings.merge.useProjectRootLegacy","Use project root (legacy)")})]}),(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:l("settings.merge.legacyIntegrationBranchMode","Legacy integration-branch mode.")})," ",l("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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"mergeAdvanceAutoSync",children:l("settings.merge.autoSyncProjectCheckoutAfterMerge","Auto-sync project checkout after merge")}),e.jsxs(G,{settingKey:"mergeAdvanceAutoSync",children:[l("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"}),l("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"}),l("settings.merge.snapsCleanlyWhenTheWorktreeHasNoEdits"," snaps cleanly when the worktree has no edits and skips otherwise. "),e.jsx("code",{children:"Off"}),l("settings.merge.isTheLegacyBehavior"," is the legacy behavior: "),e.jsx("code",{children:"git status"}),l("settings.merge.inYourProjectRootWillShowTheNew"," in your project root will show the new commits inverted as "staged changes" until you pull manually. Only applies to direct merges. ")]})]}),e.jsxs("select",{id:"mergeAdvanceAutoSync",className:"select",value:t.mergeAdvanceAutoSync??"stash-and-ff",onChange:v=>s(M=>({...M,mergeAdvanceAutoSync:v.target.value})),"data-testid":"merge-advance-auto-sync-select",children:[e.jsx("option",{value:"stash-and-ff",children:l("settings.merge.stashFastForwardDefaultPreserveLocalEdits","Stash + fast-forward (default) — preserve local edits")}),e.jsx("option",{value:"ff-only",children:l("settings.merge.fastForwardOnlySkipDirtyWorktrees","Fast-forward only — skip dirty worktrees")}),e.jsx("option",{value:"off",children:l("settings.merge.offLeaveTheProjectRootStaleLegacyBehavior","Off — leave the project root stale (legacy behavior)")})]})]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"includeTaskIdInCommit",className:"checkbox-label",children:[e.jsx("input",{id:"includeTaskIdInCommit",type:"checkbox",checked:t.includeTaskIdInCommit!==!1,onChange:v=>s(M=>({...M,includeTaskIdInCommit:v.target.checked}))}),l("settings.merge.includeTaskIDInCommitScope"," Include task ID in commit scope ")]}),e.jsxs(G,{settingKey:"includeTaskIdInCommit",children:[l("settings.merge.whenDisabledMergeCommitMessagesOmitTheTask","When disabled, merge commit messages omit the task ID from the scope (e.g. "),e.jsx("code",{children:"feat: ..."}),l("settings.merge.insteadOf"," instead of "),e.jsx("code",{children:"feat(KB-001): ..."}),l("settings.merge.includeTaskIdInCommitDefault","). Default: enabled.")]})]})}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"commitAuthorEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"commitAuthorEnabled",type:"checkbox",checked:t.commitAuthorEnabled!==!1,onChange:v=>s(M=>({...M,commitAuthorEnabled:v.target.checked}))}),l("settings.merge.addFusionAsCoAuthorOnCommits"," Add Fusion as co-author on commits ")]}),e.jsxs(G,{settingKey:"commitAuthorEnabled",children:[l("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"}),l("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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"commitAuthorName",children:l("settings.merge.coAuthorName","Co-author Name")}),e.jsxs(G,{settingKey:"commitAuthorName",children:[l("settings.merge.nameUsedInThe","Name used in the "),e.jsx("code",{children:"Co-authored-by"}),l("settings.merge.trailer"," trailer. Default: Fusion.")]})]}),e.jsx("input",{id:"commitAuthorName",type:"text",value:t.commitAuthorName??"",placeholder:l("settings.merge.fusion","Fusion"),onChange:v=>s(M=>({...M,commitAuthorName:v.target.value||void 0}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"commitAuthorEmail",children:l("settings.merge.coAuthorEmail","Co-author Email")}),e.jsxs(G,{settingKey:"commitAuthorEmail",children:[l("settings.merge.emailUsedInThe","Email used in the "),e.jsx("code",{children:"Co-authored-by"}),l("settings.merge.trailerEmail"," trailer. Default: noreply@runfusion.ai.")]})]}),e.jsx("input",{id:"commitAuthorEmail",type:"email",value:t.commitAuthorEmail??"",placeholder:l("settings.merge.noreplyRunfusionAi","noreply@runfusion.ai"),onChange:v=>s(M=>({...M,commitAuthorEmail:v.target.value||void 0}))})]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"autoResolveConflicts",className:"checkbox-label",children:[e.jsx("input",{id:"autoResolveConflicts",type:"checkbox",checked:t.autoResolveConflicts!==!1,onChange:v=>s(M=>({...M,autoResolveConflicts:v.target.checked}))}),l("settings.merge.autoResolveConflictsInLockFilesAndGenerated"," Auto-resolve conflicts in lock files and generated files ")]}),e.jsx(G,{settingKey:"autoResolveConflicts",children:l("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.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"smartConflictResolution",className:"checkbox-label",children:[e.jsx("input",{id:"smartConflictResolution",type:"checkbox",checked:t.smartConflictResolution!==!1,onChange:v=>s(M=>({...M,smartConflictResolution:v.target.checked}))}),l("settings.merge.smartConflictResolution"," Smart conflict resolution ")]}),e.jsx(G,{settingKey:"smartConflictResolution",children:l("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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"mergeConflictStrategy",children:l("settings.merge.conflictFallbackStrategy","Conflict Fallback Strategy")}),e.jsxs(G,{settingKey:"mergeConflictStrategy",children:[l("settings.merge.both"," Both "),e.jsx("strong",{children:l("settings.merge.smart","Smart")}),l("settings.merge.optionsStartWithABestEffort"," options start with a best-effort "),e.jsx("code",{children:"git fetch"}),l("settings.merge.fastForwardOfLocalMainFrom"," + fast-forward of local main from "),e.jsx("code",{children:"origin"}),l("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:l("settings.merge.finalFallback","final fallback")}),":"," ",e.jsx("strong",{children:l("settings.merge.smartPreferMain","Smart, prefer main")}),l("settings.merge.uses"," uses "),e.jsx("code",{children:"-X ours"}),l("settings.merge.soMainWinsProtectsJustMergedSiblingWork"," so main wins — protects just-merged sibling work and is the new default. ")," ",e.jsx("strong",{children:l("settings.merge.smartPreferTask","Smart, prefer task")}),l("settings.merge.uses"," uses "),e.jsx("code",{children:"-X theirs"}),l("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:l("settings.merge.aIOnly","AI only")}),l("settings.merge.retriesTheAIAgentRatherThanAutoPicking"," retries the AI agent rather than auto-picking a side. ")," ",e.jsx("strong",{children:l("settings.merge.abort","Abort")}),l("settings.merge.stopsAfterTheFirstAIAttemptAndWaits"," stops after the first AI attempt and waits for a human. ")," ",e.jsxs("em",{children:[l("settings.merge.legacy2","Legacy "),e.jsx("code",{children:'"smart"'}),l("settings.merge.and2"," and "),e.jsx("code",{children:'"prefer-main"'}),l("settings.merge.valuesFromOlderSettingsAreMigratedAutomatically"," values from older settings are migrated automatically.")]})]})]}),e.jsxs("select",{id:"mergeConflictStrategy",value:t.mergeConflictStrategy??"smart-prefer-main",onChange:v=>s(M=>({...M,mergeConflictStrategy:v.target.value})),children:[e.jsx("option",{value:"smart-prefer-main",children:l("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:l("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:l("settings.merge.aIOnlyAIAutoResolveAIRetryNever","AI only — AI → auto-resolve → AI retry; never silently pick a side")}),e.jsx("option",{value:"abort",children:l("settings.merge.abortOneAIAttemptRequireManualResolutionIf","Abort — one AI attempt; require manual resolution if it fails")})]})]}),e.jsx(Ae,{descriptor:{key:"mergeStrategyOverlapBehavior",label:l("settings.merge.smartPreferMainOverlapGuard","Smart Prefer Main Overlap Guard"),help:l("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. "),scope:"project",options:[{value:"flip-to-prefer-branch",label:l("settings.merge.flipOverlappingFilesToPreferTheTaskBranch","Flip overlapping files to prefer the task branch (default)")},{value:"warn-only",label:l("settings.merge.warnOnlyKeepLegacyMainWinsFallback","Warn only — keep legacy main-wins fallback")},{value:"ignore",label:l("settings.merge.ignoreOverlapDetectionPreserveLegacyBehavior","Ignore overlap detection — preserve legacy behavior")}]},value:t.mergeStrategyOverlapBehavior??"flip-to-prefer-branch",onChange:v=>s(M=>({...M,mergeStrategyOverlapBehavior:v}))}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"postMergeAuditMode",children:l("settings.merge.postMergeAuditMode","Post-merge audit mode")}),e.jsxs(G,{settingKey:"postMergeAuditMode",children:[l("settings.merge.controlsThePostMergeAuditGate"," Controls the post-merge audit gate. "),e.jsx("strong",{children:l("settings.merge.warn","Warn")}),l("settings.merge.defaultLogsFindingsButAutoCompletesTheMerge"," (default) logs findings but auto-completes the merge. "),e.jsx("strong",{children:l("settings.merge.block","Block")}),l("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:l("settings.merge.off","Off")}),l("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("select",{className:"select",id:"postMergeAuditMode",value:t.postMergeAuditMode??"warn",onChange:v=>s(M=>({...M,postMergeAuditMode:v.target.value})),children:[e.jsx("option",{value:"block",children:l("settings.merge.blockStrict","Block (strict)")}),e.jsx("option",{value:"warn",children:l("settings.merge.warnDefaultLogFindingsContinue","Warn (default; log findings, continue)")}),e.jsx("option",{value:"off",children:l("settings.merge.offSkipAudit","Off (skip audit)")})]})]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"pushAfterMerge",className:"checkbox-label",children:[e.jsx("input",{id:"pushAfterMerge",type:"checkbox",checked:t.pushAfterMerge===!0,onChange:v=>s(M=>({...M,pushAfterMerge:v.target.checked}))}),l("settings.merge.pushToRemoteAfterMerge"," Push to remote after merge ")]}),e.jsx(G,{settingKey:"pushAfterMerge",children:l("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&&(u.length===0?e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"pushRemote",children:l("settings.merge.pushRemote","Push Remote")}),e.jsx(G,{settingKey:"pushRemote",children:l("settings.merge.gitRemoteToPushToEGOrigin",'Git remote to push to (e.g. "origin"). Can include branch name (e.g. "origin main"). Default: "origin".')})]}),e.jsx("input",{id:"pushRemote",type:"text",placeholder:l("settings.merge.origin","origin"),value:t.pushRemote||"",onChange:v=>s(M=>({...M,pushRemote:v.target.value||void 0}))})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"pushRemote",children:l("settings.merge.pushRemote","Push Remote")}),e.jsx(G,{settingKey:"pushRemote",children:l("settings.merge.gitRemoteThatMergedResultsArePushedTo",'Git remote that merged results are pushed to. Default: "origin".')})]}),e.jsxs("select",{id:"pushRemote",className:"select",value:x.remote,onChange:v=>{const M=v.target.value;N(!1),s(se=>({...se,pushRemote:da(M,"")}))},"data-testid":"push-remote-select",children:[!u.includes(x.remote)&&e.jsx("option",{value:x.remote,children:x.remote}),u.map(v=>e.jsx("option",{value:v,children:v},v))]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"pushRemoteBranch",children:l("settings.merge.pushTargetBranch","Push target branch")}),e.jsx(G,{settingKey:"pushRemoteBranch",children:l("settings.merge.pushTargetBranchHelp","Branch on the remote that merged results are pushed to. Leave on the default to push the integration branch to its same-named remote branch; pick a listed remote branch or choose Custom… to type one that doesn't exist on the remote yet (the push creates it).")})]}),(()=>{const v=x.branch,M=v.length>0&&w.includes(v);if(E||v.length>0&&!M)return e.jsxs("div",{className:"form-inline-group",children:[e.jsx("input",{id:"pushRemoteBranch",type:"text",className:"input",placeholder:l("settings.merge.branchName","branch name"),value:v,onChange:ne=>{const pe=ne.target.value.trim();s(j=>({...j,pushRemote:da(x.remote,pe)}))},"data-testid":"push-remote-branch-custom-input"}),e.jsx("button",{type:"button",className:"btn-link",onClick:()=>{N(!1),s(ne=>({...ne,pushRemote:da(x.remote,"")}))},"data-testid":"push-remote-branch-use-dropdown",children:l("settings.merge.useDropdown"," Use dropdown ")})]});const se="__fusion-custom__";return e.jsxs("select",{id:"pushRemoteBranch",className:"select",value:v,onChange:ne=>{const pe=ne.target.value;if(pe===se){N(!0);return}s(j=>({...j,pushRemote:da(x.remote,pe)}))},"data-testid":"push-remote-branch-select",children:[e.jsx("option",{value:"",children:l("settings.merge.sameAsIntegrationBranchDefault","(same as integration branch — default)")}),w.map(ne=>e.jsx("option",{value:ne,children:ne},ne)),e.jsx("option",{value:se,children:l("settings.merge.custom","Custom…")})]})})()]})]}))]})}const ua="__custom__";function th(t){const s=new Map;for(const a of t){const n=a.value.trim();!n||s.has(n)||s.set(n,{...a,value:n,label:a.label?.trim()||n})}return[...s.values()].sort((a,n)=>a.value.localeCompare(n.value))}function vi({id:t,value:s,onChange:a,options:n,loading:o=!1,error:d,placeholder:u="owner/repo",ariaLabel:c}){const{t:l}=le("app"),h=i.useRef(null),p=i.useId(),[m,x]=i.useState(!1),w=i.useMemo(()=>th(n),[n]),f=w.find(L=>L.value===s),E=f?f.value:ua;i.useEffect(()=>{x(E===ua)},[E]);const N=L=>{if(L===ua){x(!0),requestAnimationFrame(()=>{h.current?.focus()});return}x(!1),a(L)},S=d||(o?l("trackingRepoSelect.loadingHint","Loading detected GitHub remotes…"):null);return e.jsxs("div",{className:"tracking-repo-select",children:[e.jsxs("select",{id:t,className:"select",value:E,onChange:L=>N(L.target.value),"aria-label":c,"aria-describedby":S?p:void 0,children:[w.map(L=>e.jsx("option",{value:L.value,children:L.source?`${L.label} — ${L.source}`:L.label},L.value)),e.jsx("option",{value:ua,children:l("trackingRepoSelect.customOption","Custom…")})]}),m?e.jsx("input",{ref:h,className:"input tracking-repo-select__custom-input",type:"text",value:s,placeholder:u,onChange:L=>a(L.target.value),"aria-describedby":S?p:void 0}):null,S?e.jsx("small",{id:p,className:d?"tracking-repo-select__hint tracking-repo-select__hint--error":"tracking-repo-select__hint",children:S}):null]})}function sh({form:t,setForm:s,projectTrackingRepoOptions:a,projectTrackingRepoLoading:n,projectTrackingRepoError:o}){const{t:d}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:d("settings.general.gitHubTracking","GitHub Tracking")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"githubTrackingMode",children:d("settings.general.defaultTrackingModeForNewTasks","Default tracking mode for new tasks")}),e.jsxs(G,{settingKey:"githubTrackingMode",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. "),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("select",{id:"githubTrackingMode",className:"select",value:t.githubTrackingEnabledByDefault?"new-tasks":"off",onChange:u=>s(c=>({...c,githubTrackingEnabledByDefault:u.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(ae,{descriptor:{key:"githubLinkImportedIssuesToTracking",label:d("settings.general.alwaysLinkImportedGitHubIssuesToTracking"," Always link imported GitHub issues to GitHub tracking "),help: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."),scope:"project"},value:t.githubLinkImportedIssuesToTracking===!0,onChange:u=>s(c=>({...c,githubLinkImportedIssuesToTracking:u===!0}))}),e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"projectGithubTrackingDefaultRepoGeneral",children:d("settings.general.projectDefaultTrackingRepo","Project default tracking repo")}),e.jsx(G,{settingKey:"projectGithubTrackingDefaultRepoGeneral",children:d("settings.general.defaultRepoUsedWhenCreatingGitHubIssuesFor","Default repo used when creating GitHub issues for tracked tasks. Falls back to the global default if blank.")})]}),e.jsx(vi,{id:"projectGithubTrackingDefaultRepoGeneral",ariaLabel:"Project default tracking repo",value:t.githubTrackingDefaultRepo??"",options:a,loading:n,error:o??void 0,placeholder:d("settings.general.ownerRepo","owner/repo"),onChange:u=>s(c=>({...c,githubTrackingDefaultRepo:u||void 0}))})]}),e.jsx(ae,{descriptor:{key:"githubTrackingDedupEnabled",label:d("settings.general.searchTheTrackingRepoForLikelyDuplicatesBefore"," Search the tracking repo for likely duplicates before opening a new issue "),help: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. "),scope:"project"},value:t.githubTrackingDedupEnabled!==!1,onChange:u=>s(c=>({...c,githubTrackingDedupEnabled:u===!0}))}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.merge.gitHubAuthentication","GitHub Authentication")}),e.jsx(Ae,{descriptor:{key:"githubAuthMode",label:d("settings.merge.gitHubAuthMode","GitHub auth mode"),scope:"project",options:[{value:"gh-cli",label:d("settings.merge.gitHubCLIGhAuth","GitHub CLI (gh auth) (default)")},{value:"token",label:d("settings.merge.personalAccessToken","Personal access token")}]},value:t.githubAuthMode??"gh-cli",onChange:u=>s(c=>({...c,githubAuthMode:u}))}),(t.githubAuthMode??"gh-cli")==="token"&&e.jsx(be,{descriptor:{key:"githubAuthToken",label:d("settings.merge.gitHubPersonalAccessToken","GitHub personal access token"),help:d("settings.merge.githubAuthTokenHint","No default — unset."),scope:"project",type:"password"},value:t.githubAuthToken??"",onChange:u=>s(c=>({...c,githubAuthToken:u||void 0}))}),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:u=>u.stopPropagation(),children:[e.jsx("input",{id:"gitlabEnabled",type:"checkbox",checked:t.gitlabEnabled!==!1,onChange:u=>s(c=>({...c,gitlabEnabled:u.target.checked}))}),d("settings.general.enableGitLabIntegration","Enable GitLab integration")]}),e.jsx("span",{onClick:u=>u.stopPropagation(),children:e.jsx(G,{settingKey:"project-gitlab-configuration",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.jsx(be,{descriptor:{key:"gitlabInstanceUrl",label:d("settings.general.gitLabInstanceUrl","GitLab instance URL"),help: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."),type:"url",placeholder:"https://gitlab.com",disabled:t.gitlabEnabled===!1},value:t.gitlabInstanceUrl??"",onChange:u=>s(c=>({...c,gitlabInstanceUrl:u||void 0}))}),e.jsx(be,{descriptor:{key:"gitlabApiBaseUrl",label:d("settings.general.gitLabApiBaseUrlOptional","GitLab API base URL (optional / advanced)"),help: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."),type:"url",placeholder:"https://gitlab.com/api/v4",disabled:t.gitlabEnabled===!1},value:t.gitlabApiBaseUrl??"",onChange:u=>s(c=>({...c,gitlabApiBaseUrl:u||void 0}))}),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h5",{className:"settings-section-heading",children:d("settings.merge.gitLabAuthentication","GitLab Authentication")}),e.jsx(G,{settingKey:"project-gitlab-authentication",children:t.gitlabEnabled===!1?d("settings.merge.gitLabDisabledHint","GitLab comments, close/reopen, import fetches, and refresh operations are disabled. Saved tokens remain stored for re-enable."):d("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.jsx(Ae,{descriptor:{key:"gitlabAuthTokenType",label:d("settings.merge.gitLabTokenType","GitLab token type"),disabled:t.gitlabEnabled===!1,options:[{value:"personal",label:d("settings.merge.gitLabPersonalAccessToken","Personal access token (default)")},{value:"project",label:d("settings.merge.gitLabProjectAccessToken","Project access token")},{value:"group",label:d("settings.merge.gitLabGroupAccessToken","Group access token")}]},value:t.gitlabAuthTokenType??"personal",onChange:u=>s(c=>({...c,gitlabAuthTokenType:u}))}),e.jsx(be,{descriptor:{key:"gitlabAuthToken",label:d("settings.merge.gitLabAccessToken","GitLab access token"),help:d("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."),type:"password",disabled:t.gitlabEnabled===!1},value:t.gitlabAuthToken??"",onChange:u=>s(c=>({...c,gitlabAuthToken:u||void 0}))})]})]})]})}function ah({form:t,setForm:s,globalSettings:a,onGlobalSourceControlSettingsChange:n,globalTrackingRepoOptions:o,globalTrackingRepoLoading:d,globalTrackingRepoError:u}){const{t:c}=le("app"),l=a??t,h=l;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"globalGithubTrackingDefaultRepo",children:c("settings.globalGeneral.globalDefaultTrackingRepo","Global default tracking repo")}),e.jsx(G,{settingKey:"globalGithubTrackingDefaultRepo",children:c("settings.globalGeneral.projectsInheritThisValueWhenTheyDoNot","Projects inherit this value when they do not set a project default tracking repo. No default — unset.")})]}),e.jsx(vi,{id:"globalGithubTrackingDefaultRepo",ariaLabel:"Global default tracking repo",value:t.githubTrackingDefaultRepo??"",options:o,loading:d,error:u??void 0,placeholder:c("settings.globalGeneral.ownerRepo","owner/repo"),onChange:p=>s(m=>({...m,githubTrackingDefaultRepo:p||void 0}))})]}),e.jsx(ae,{descriptor:{key:"reportRoadmapDedupeEnabled",label:c("settings.globalGeneral.reportRoadmapDedupeEnabled","Global public-roadmap deduplication"),help:c("settings.globalGeneral.reportRoadmapDedupeEnabledHelp","Fallback for projects that do not set a public-roadmap deduplication preference. No default — unset (projects default to enabled).")},value:l.reportRoadmapDedupeEnabled??!0,onChange:p=>n({reportRoadmapDedupeEnabled:p??void 0})}),e.jsx(be,{descriptor:{key:"reportRoadmapLabel",label:c("settings.globalGeneral.reportRoadmapLabel","Global public roadmap label"),help:c("settings.globalGeneral.reportRoadmapLabelHelp","Fallback label for open public-roadmap issues when a project does not set one. No default — unset (projects default to roadmap).")},value:l.reportRoadmapLabel??"",onChange:p=>n({reportRoadmapLabel:p||void 0})}),e.jsx(be,{descriptor:{key:"reportRoadmapRepo",label:c("settings.globalGeneral.reportRoadmapRepo","Global public roadmap repository (optional)"),help:c("settings.globalGeneral.reportRoadmapRepoHelp","Fallback GitHub owner/repository for public-roadmap issues. When unset, uses the tracking repository. No default — unset."),placeholder:"owner/repository"},value:l.reportRoadmapRepo??"",onChange:p=>n({reportRoadmapRepo:p||void 0})}),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:c("settings.globalGeneral.gitLabConfiguration","GitLab Configuration")}),e.jsxs("label",{className:"checkbox-label settings-gitlab-disclosure__toggle",htmlFor:"globalGitlabEnabled",onClick:p=>p.stopPropagation(),children:[e.jsx("input",{id:"globalGitlabEnabled",type:"checkbox",checked:h.gitlabEnabled!==!1,onChange:p=>n({gitlabEnabled:p.target.checked})}),c("settings.globalGeneral.enableGitLabIntegration","Enable GitLab integration")]}),e.jsx("span",{onClick:p=>p.stopPropagation(),children:e.jsx(G,{settingKey:"global-gitlab-configuration",children:h.gitlabEnabled===!1?c("settings.globalGeneral.gitLabDisabledHint","GitLab API operations are disabled by global default. Saved URL and token fallbacks remain stored for re-enable."):c("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":h.gitlabEnabled===!1,children:[e.jsx(be,{descriptor:{key:"gitlabInstanceUrl",label:c("settings.globalGeneral.gitLabInstanceUrl","Global GitLab instance URL"),help:c("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."),type:"url",placeholder:"https://gitlab.com",disabled:h.gitlabEnabled===!1},value:h.gitlabInstanceUrl??"",onChange:p=>n({gitlabInstanceUrl:p||void 0})}),e.jsx(be,{descriptor:{key:"gitlabApiBaseUrl",label:c("settings.globalGeneral.gitLabApiBaseUrlOptional","Global GitLab API base URL (optional / advanced)"),help:c("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."),type:"url",placeholder:"https://gitlab.com/api/v4",disabled:h.gitlabEnabled===!1},value:h.gitlabApiBaseUrl??"",onChange:p=>n({gitlabApiBaseUrl:p||void 0})}),e.jsx(Ae,{descriptor:{key:"gitlabAuthTokenType",label:c("settings.globalGeneral.gitLabTokenType","Global GitLab token type"),help:c("settings.globalGeneral.gitLabTokenTypeHint","No default — unset (the selector falls back to personal access token until you choose otherwise)."),disabled:h.gitlabEnabled===!1,options:[{value:"personal",label:c("settings.globalGeneral.gitLabPersonalAccessToken","Personal access token")},{value:"project",label:c("settings.globalGeneral.gitLabProjectAccessToken","Project access token")},{value:"group",label:c("settings.globalGeneral.gitLabGroupAccessToken","Group access token")}]},value:h.gitlabAuthTokenType??"personal",onChange:p=>n({gitlabAuthTokenType:p})}),e.jsx(be,{descriptor:{key:"gitlabAuthToken",label:c("settings.globalGeneral.gitLabAccessToken","Global GitLab access token"),help:c("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."),type:"password",disabled:h.gitlabEnabled===!1},value:h.gitlabAuthToken??"",onChange:p=>n({gitlabAuthToken:p||void 0})})]})]})]})}function qr(t){return Array.from(new Set(t.split(/[\n,]+/).map(s=>s.trim()).filter(s=>s.length>0)))}function nh({value:t,onChange:s,disabled:a=!1}){const{t:n}=le("app"),o=t?.approvalMode??"trusted-only",d=t?.alwaysApproveDelete??!0,u={always:{label:n("agentProvisioning.always","Always require approval"),description:n("agentProvisioning.alwaysDesc","All fn_agent_create/fn_agent_delete requests require approval unless caller is trusted.")},"trusted-only":{label:n("agentProvisioning.trustedOnly","Trusted-only"),description:n("agentProvisioning.trustedOnlyDesc","Trusted roles/agent IDs bypass approval; other callers require approval.")},never:{label:n("agentProvisioning.never","Never require approval"),description:n("agentProvisioning.neverDesc","Allow provisioning without approval for non-privileged callers.")}},c=l=>{s({...t??{},...l})};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:n("agentProvisioning.approvalMode","Approval mode")}),e.jsx("select",{id:"agent-provisioning-approval-mode",className:"select",value:o,onChange:l=>c({approvalMode:l.target.value}),disabled:a,children:Zd.map(l=>e.jsx("option",{value:l,children:u[l].label},l))}),e.jsx("small",{className:"agent-provisioning-policy-help",children:u[o].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:d,onChange:l=>c({alwaysApproveDelete:l.target.checked}),disabled:a}),n("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:n("agentProvisioning.trustedRoles","Trusted roles")}),e.jsx("textarea",{id:"agent-provisioning-trusted-roles",className:"input agent-provisioning-policy-textarea",value:(t?.trustedRoles??[]).join(", "),onChange:l=>c({trustedRoles:qr(l.target.value)}),disabled:a,placeholder:n("agentProvisioning.trustedRolesPlaceholder","reviewer, ceo"),rows:2})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-provisioning-trusted-agent-ids",children:n("agentProvisioning.trustedAgentIds","Trusted agent IDs")}),e.jsx("textarea",{id:"agent-provisioning-trusted-agent-ids",className:"input agent-provisioning-policy-textarea",value:(t?.trustedAgentIds??[]).join(", "),onChange:l=>c({trustedAgentIds:qr(l.target.value)}),disabled:a,placeholder:n("agentProvisioning.trustedAgentIdsPlaceholder","agent-abc123"),rows:2})]}),e.jsx("p",{className:"agent-provisioning-policy-help",children:e.jsx(Un,{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 Rn(t){return eu.reduce((s,a)=>(s[a]=t?.[a]??"allow",s),{})}function lh({form:t,setForm:s}){const{t:a}=le("app");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.agentPermissions.agentPermissions","Agent Permissions")}),e.jsx(G,{settingKey:"defaultAgentPermissionPolicy",children:a("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(Vu,{mode:"project-default",value:t.defaultAgentPermissionPolicy?{presetId:"custom",rules:Rn(t.defaultAgentPermissionPolicy.rules),...t.defaultAgentPermissionPolicy.toolRules?{toolRules:t.defaultAgentPermissionPolicy.toolRules}:{}}:{presetId:"custom",rules:Rn()},onChange:n=>s(o=>({...o,defaultAgentPermissionPolicy:{rules:Rn(n?.rules),...n?.toolRules?{toolRules:n.toolRules}:{}}}))}),e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.agentPermissions.agentProvisioningApprovals","Agent Provisioning Approvals")}),e.jsx(G,{settingKey:"agentProvisioning",children:a("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(nh,{value:t.agentProvisioning,onChange:n=>s(o=>({...o,agentProvisioning:n}))})]})}const rh=72;function ih(t,s){if(t.length<=s)return t;const a=Math.max(1,s-1),n=Math.ceil(a/2),o=Math.floor(a/2);return`${t.slice(0,n)}…${t.slice(t.length-o)}`}function oh(t){const s=`${t.label} — ${t.path}`;return ih(s,rh)}function ch({form:t,setForm:s,memory:a}){const{t:n}=le("app"),{memoryCapabilities:o,memoryBackendStatus:d,memoryBackendLoading:u,memoryBackendError:c,memoryFiles:l,selectedMemoryPath:h,setSelectedMemoryPath:p,memoryContent:m,setMemoryContent:x,memoryLoading:w,memoryDirty:f,setMemoryDirty:E,memoryTestQuery:N,setMemoryTestQuery:S,memoryTestLoading:L,memoryTestResult:F,qmdInstallLoading:K,dreamRunning:R,memoryCompactLoading:T,onInstallQmd:b,onTestMemoryRetrieval:V,onDreamNow:X,onCompactMemory:k,onSaveMemory:I}=a,B=t.memoryEnabled!==!1,v=!u&&d!==null,M=v?o?.writable??!0:!0,se=B&&M,ne=l.find(j=>j.path===h),pe={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("h4",{className:"settings-section-heading",children:n("settings.memory.memory","Memory")}),e.jsxs(G,{settingKey:"memory-section",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.jsx(ae,{descriptor:{key:"memoryEnabled",label:n("settings.memory.enableMemoryTools"," Enable memory tools "),help: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."),scope:"project"},value:t.memoryEnabled!==!1,onChange:j=>s(W=>({...W,memoryEnabled:j===!0}))}),u?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:n("settings.memory.checkingMemoryWriteAccess","Checking memory write access...")})}):c?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[n("settings.memory.failedToLoadBackendStatus","Failed to load backend status: "),c]})}):null,v&&d.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:d.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:b,disabled:K,children:K?n("settings.memory.installing","Installing…"):n("settings.memory.installQmd","Install qmd")})]}),e.jsx(ae,{descriptor:{key:"memoryAutoSummarizeEnabled",label:n("settings.memory.autoSummarizeMemory"," Auto-Summarize Memory "),help:n("settings.memory.automaticallyCompactMemoryWhenItExceedsTheThreshold","Automatically compact memory when it exceeds the threshold on a schedule. Default: disabled."),scope:"project"},value:t.memoryAutoSummarizeEnabled||!1,onChange:j=>s(W=>({...W,memoryAutoSummarizeEnabled:j===!0}))}),(t.memoryAutoSummarizeEnabled||!1)&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{descriptor:{key:"memoryAutoSummarizeThresholdChars",label:n("settings.memory.compactionThresholdChars","Compaction Threshold (chars)"),help:n("settings.memory.memoryWillBeCompactedWhenItExceedsThis","Memory will be compacted when it exceeds this character count. Default: 50000."),scope:"project",min:1e3},value:t.memoryAutoSummarizeThresholdChars??5e4,onChange:j=>s(W=>({...W,memoryAutoSummarizeThresholdChars:j||5e4}))}),e.jsx(be,{descriptor:{key:"memoryAutoSummarizeSchedule",label:n("settings.memory.scheduleCron","Schedule (cron)"),help:n("settings.memory.cronExpressionForAutoSummarizeScheduleDefaultDaily","Cron expression for auto-summarize schedule. Default: 0 3 * * * (daily at 3 AM)."),scope:"project",placeholder:n("settings.memory.03","0 3 * * *")},value:t.memoryAutoSummarizeSchedule??"0 3 * * *",onChange:j=>s(W=>({...W,memoryAutoSummarizeSchedule:j??""}))})]}),e.jsx(ae,{descriptor:{key:"insightExtractionEnabled",label:n("settings.memory.enableInsightExtraction"," Enable Insight Extraction "),help:n("settings.memory.periodicallyExtractDurableInsightsFromCompletedTasks","Periodically extract durable insights/learnings from completed tasks into memory"),scope:"project"},value:t.insightExtractionEnabled||!1,onChange:j=>s(W=>({...W,insightExtractionEnabled:j===!0}))}),(t.insightExtractionEnabled||!1)&&e.jsx(be,{descriptor:{key:"insightExtractionSchedule",label:n("settings.memory.scheduleCron","Schedule (cron)"),help:n("settings.memory.cronExpressionForInsightExtractionScheduleDefaultDaily","Cron expression for insight extraction schedule (default: daily at 2 AM)"),scope:"project",placeholder:n("settings.memory.02","0 2 * * *")},value:t.insightExtractionSchedule??"0 2 * * *",onChange:j=>s(W=>({...W,insightExtractionSchedule:j??""}))}),e.jsx("div",{style:{borderTop:"1px solid var(--border)",margin:"var(--space-lg) 0"}}),e.jsx(ae,{descriptor:{key:"memoryDreamsEnabled",label:n("settings.memory.processDreamsFromDailyMemory"," Process dreams from daily memory "),help:n("settings.memory.turnsDailyNotesIntoDREAMSMdAndPromotes","Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md. Default: disabled."),scope:"project",disabled:!B},value:t.memoryDreamsEnabled===!0,onChange:j=>s(W=>({...W,memoryDreamsEnabled:j===!0}))}),B&&t.memoryDreamsEnabled===!0&&e.jsxs(e.Fragment,{children:[e.jsx(be,{descriptor:{key:"memoryDreamsSchedule",label:n("settings.memory.dreamSchedule","Dream Schedule"),help:n("settings.memory.cronExpressionForDreamProcessing","Cron expression for dream processing. Default: 0 4 * * * (daily at 4 AM)."),scope:"project"},value:t.memoryDreamsSchedule??"0 4 * * *",onChange:j=>s(W=>({...W,memoryDreamsSchedule:j??""}))}),e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:X,disabled:R||t.memoryDreamsEnabled!==!0,children:R?e.jsxs(e.Fragment,{children:[e.jsx(bt,{size:14,className:"animate-spin"}),n("settings.memory.dreaming"," Dreaming… ")]}):n("settings.memory.dreamNow","Dream Now")}),e.jsx(G,{settingKey:"memory-dream-now",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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"memoryRetrievalQuery",children:n("settings.memory.testRetrieval","Test Retrieval")}),e.jsx(G,{settingKey:"memoryRetrievalQuery",children:n("settings.memory.runsTheSameQmdBackedMemorySearchPath","Runs the same qmd-backed memory_search path agents use.")})]}),e.jsx("input",{id:"memoryRetrievalQuery",type:"text",value:N,onChange:j=>S(j.target.value),placeholder:n("settings.memory.searchMemoryWithQmd","Search memory with qmd")})]}),e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:V,disabled:L,children:L?n("settings.memory.testing","Testing…"):n("settings.memory.testRetrieval","Test Retrieval")})}),F&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[F.results.length,n("settings.memory.result"," result"),F.results.length===1?"":"s"," ",n("settings.memory.for",'for "'),F.query,'"']}),e.jsxs("small",{children:[n("settings.memory.qmd"," qmd "),F.qmdAvailable?"available":"missing"," · ",F.usedFallback?"local fallback used":"qmd path used"]}),F.results.length>0?e.jsx("ul",{children:F.results.map((j,W)=>e.jsxs("li",{children:[e.jsxs("span",{children:[j.path,":",j.lineStart]}),e.jsx("p",{children:j.snippet})]},`${j.path}-${j.lineStart}-${W}`))}):e.jsx("small",{children:n("settings.memory.noMatchingMemoryFound","No matching memory found.")})]})]}),!B&&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. ")}),B&&v&&!M&&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. ")}),w?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Et,{label:n("settings.memory.loadingMemory","Loading memory…")})}):e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"memoryFilePath",children:n("settings.memory.memoryFile","Memory File")}),e.jsx(G,{settingKey:"memoryFilePath",children:"Choose any project memory file to view or edit. Dreams is selected by default."})]}),e.jsx("select",{id:"memoryFilePath",value:h,onChange:j=>{p(j.target.value),E(!1)},disabled:f,children:l.map(j=>e.jsx("option",{value:j.path,title:`${j.label} — ${j.path}`,children:oh(j)},j.path))}),f&&e.jsx("small",{children:"Save or discard the current edits before switching files."})]}),ne&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:pe[ne.layer]}),e.jsx("strong",{children:ne.path}),e.jsxs("small",{children:[ne.size.toLocaleString(),n("settings.memory.bytesUpdated"," bytes · updated "),new Date(ne.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group memory-editor-form-group",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{children:ne?.label||"Memory Editor"}),e.jsxs(G,{settingKey:"memory-editor",children:[ne?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",ne?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",ne?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!ne&&"Edits the selected memory file."]})]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(tu,{content:m,onChange:j=>{x(j),E(!0)},readOnly:!se,filePath:h})})]})]}),!w&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:k,disabled:!se||f||T,children:T?n("settings.memory.compacting","Compacting…"):n("settings.memory.compactSelectedFile","Compact Selected File")}),e.jsx(G,{settingKey:"memory-compact-file",children:`Compacts ${h} and writes the result back to the same file.`}),f&&e.jsx("small",{children:"Save or discard edits before compacting this file."})]}),f&&se&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:I,children:n("settings.memory.saveMemory","Save Memory")})}),f&&!se&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[n("settings.memory.cannotSave","Cannot save: "),B?"Backend is read-only":"Memory is disabled"]})})]})}function dh({form:t,setForm:s,researchLimitError:a}){const{t:n}=le("app"),o=t.researchSettings?.limits,d=t.researchSettings?.enabledSources;return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:n("settings.researchProject.projectResearchSettings","Project Research Settings")}),e.jsx(ae,{descriptor:{key:"researchSettings.enabled",label:n("settings.researchProject.enableResearchInThisProject"," Enable research in this project "),help:n("settings.researchProject.enableResearchInThisProjectHint","Default: enabled."),scope:"project"},value:t.researchSettings?.enabled??!0,onChange:u=>s(c=>({...c,researchSettings:{...c.researchSettings??{},enabled:u===!0}}))}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:n("settings.researchProject.enabledSources","Enabled Sources")}),e.jsxs("div",{className:"settings-field-label-row",children:[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(G,{settingKey:"research-project-source-webSearch",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(([u,c,l])=>e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:`research-project-source-${u}`,className:"checkbox-label",children:[e.jsx("input",{id:`research-project-source-${u}`,type:"checkbox",checked:d?.[u]??!1,onChange:h=>s(p=>({...p,researchSettings:{...p.researchSettings??{},enabledSources:{...p.researchSettings?.enabledSources??{},[u]:h.target.checked}}}))}),c]}),e.jsx(G,{settingKey:`research-project-source-${u}`,children:l})]},u))})]}),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.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-project-max-concurrent",children:n("settings.researchProject.maxConcurrentRuns","Max Concurrent Runs")}),e.jsx(G,{settingKey:"research-project-max-concurrent",children:n("settings.researchProject.maxConcurrentRunsHint","Default: 3.")})]}),e.jsx("input",{id:"research-project-max-concurrent",className:"input",type:"number",min:1,value:o?.maxConcurrentRuns??3,onChange:u=>s(c=>({...c,researchSettings:{...c.researchSettings??{},limits:{...c.researchSettings?.limits??{},maxConcurrentRuns:u.target.value===""?void 0:Number(u.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-project-max-sources",children:n("settings.researchProject.maxSourcesPerRun","Max Sources Per Run")}),e.jsx(G,{settingKey:"research-project-max-sources",children:n("settings.researchProject.maxSourcesPerRunHint","Default: 20.")})]}),e.jsx("input",{id:"research-project-max-sources",className:"input",type:"number",min:1,value:o?.maxSourcesPerRun??20,onChange:u=>s(c=>({...c,researchSettings:{...c.researchSettings??{},limits:{...c.researchSettings?.limits??{},maxSourcesPerRun:u.target.value===""?void 0:Number(u.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-project-max-duration",children:n("settings.researchProject.maxDurationMs","Max Duration (ms)")}),e.jsx(G,{settingKey:"research-project-max-duration",children:n("settings.researchProject.maxDurationMsHint","Default: 300000 (5 minutes).")})]}),e.jsx("input",{id:"research-project-max-duration",className:"input",type:"number",min:1e3,value:o?.maxDurationMs??3e5,onChange:u=>s(c=>({...c,researchSettings:{...c.researchSettings??{},limits:{...c.researchSettings?.limits??{},maxDurationMs:u.target.value===""?void 0:Number(u.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsxs("div",{className:"settings-field-label-row",children:[e.jsx("label",{htmlFor:"research-project-request-timeout",children:n("settings.researchProject.requestTimeoutMs","Request Timeout (ms)")}),e.jsx(G,{settingKey:"research-project-request-timeout",children:n("settings.researchProject.requestTimeoutMsHint","Default: 30000 (30 seconds).")})]}),e.jsx("input",{id:"research-project-request-timeout",className:"input",type:"number",min:1e3,value:o?.requestTimeoutMs??3e4,onChange:u=>s(c=>({...c,researchSettings:{...c.researchSettings??{},limits:{...c.researchSettings?.limits??{},requestTimeoutMs:u.target.value===""?void 0:Number(u.target.value)}}}))})]}),a&&e.jsx("small",{className:"field-error settings-research-limits-error",children:a})]})})]})}const uh=1e3;function ph(t){if(!t||typeof t!="object")return!1;const s=t;return["not-installed","queued","downloading","installed","error"].includes(String(s.model?.status))&&["available","unavailable"].includes(String(s.runtime?.status))}function gh({form:t,setForm:s}){const{t:a}=le("app"),[n,o]=i.useState(null),[d,u]=i.useState(!1),c=i.useRef(!0),l=i.useCallback(async()=>{try{const R=await Ue("/voice/status");if(!ph(R))throw new Error("invalid voice status");c.current&&(o(R),u(!1))}catch{c.current&&(o(null),u(!0))}},[]);i.useEffect(()=>(c.current=!0,l(),()=>{c.current=!1}),[l]);const h=n?.model.status;i.useEffect(()=>{if(h!=="downloading"&&h!=="queued")return;const R=window.setInterval(()=>{l()},uh);return()=>window.clearInterval(R)},[l,h]);const p=h==="downloading"||h==="queued",m=n?.model.progress,x=n===null&&!d,w=h==="installed",f=n?.runtime.status==="unavailable",E=x||d||!w||f,N=t.voiceInput?.enabled===!0,S=N&&!E,L=n?.runtime.unavailableReason,F=d?a("settings.voiceInput.statusUnavailable","Voice runtime status could not be determined; voice mode stays disabled."):w?L==="runtime-module-missing"?a("settings.voiceInput.runtimeModuleMissing","Install a Fusion release that includes the optional voice runtime, then reopen Settings."):L==="runtime-platform-load-failed"?a("settings.voiceInput.runtimePlatformLoadFailed","Reinstall Fusion for this platform so the optional voice runtime can load."):L==="runtime-incompatible"?a("settings.voiceInput.runtimeIncompatible","Update or reinstall Fusion because the installed voice runtime is incompatible."):a("settings.voiceInput.runtimeUnavailable",N?"Voice mode is inactive because the sherpa-onnx runtime is unavailable. Your saved preference remains on.":"The sherpa-onnx runtime is unavailable, so voice mode stays disabled."):p?a("settings.voiceInput.modelPreparing","Voice input becomes available after the model installation finishes."):h==="error"?a("settings.voiceInput.modelFailed","Fix or retry the model installation before enabling voice input."):a("settings.voiceInput.modelRequired","Download the Parakeet model before enabling voice input."),K=async(R,T)=>{try{await Ue(R,{method:T})}finally{await l()}};return e.jsxs("section",{className:"voice-input-section","data-testid":"voice-input-section",children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.voiceInput.title","Voice Input")}),e.jsx("div",{"data-effective-enabled":S?"true":"false",children:e.jsx(ae,{descriptor:{key:"voiceInput.enabled",label:a("settings.voiceInput.enable","Enable voice input"),help:a("settings.voiceInput.enableHelp","Default: off. Voice dictation uses the operator-managed Parakeet v3 model."),scope:"project",disabled:E},value:S,onChange:R=>s(T=>({...T,voiceInput:{...T.voiceInput??{},enabled:R===!0}}))})}),!x&&E&&e.jsx("p",{className:"voice-input-section__message",role:"alert","data-testid":d?"voice-input-status-unavailable":"voice-input-runtime-unavailable",children:F}),e.jsx(As,{label:a("settings.voiceInput.modelStatus","Parakeet v3 model status"),help:a("settings.voiceInput.modelStatusHelp","The speech model is installed and managed locally on this device."),scope:"project",children:e.jsx("span",{className:`voice-input-section__status voice-input-section__status--${h??"unknown"}`,"data-testid":"voice-input-model-status",children:d?a("settings.voiceInput.unknown","Status unavailable"):p?typeof m=="number"?a("settings.voiceInput.downloadingProgress","Downloading: {{progress}}%",{progress:Math.round(m*100)}):a("settings.voiceInput.downloading","Downloading model…"):h==="installed"?a("settings.voiceInput.installed","Installed"):h==="error"?a("settings.voiceInput.error","Model error: {{message}}",{message:n?.model.errorMessage??n?.model.errorReason??"Unknown error"}):a("settings.voiceInput.notInstalled","Not installed")})}),e.jsx(As,{label:a("settings.voiceInput.modelActions","Model management"),help:a("settings.voiceInput.modelActionsHelp","Download or remove the Parakeet v3 speech model."),scope:"project",children:e.jsxs("div",{className:"voice-input-section__actions","data-testid":"voice-input-model-actions",children:[!d&&(h==="not-installed"||h==="error")&&e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void K("/voice/model/download","POST"),children:a("settings.voiceInput.download","Download")}),!d&&h==="installed"&&e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void K("/voice/model","DELETE"),children:a("settings.voiceInput.remove","Remove")})]})})]})}function hh({form:t,setForm:s,globalSettings:a,projectId:n,pluginServers:o,addToast:d}){const{t:u}=le("app"),[c,l]=i.useState([]),[h,p]=i.useState(!1);return i.useEffect(()=>{const m=new AbortController,x=n?`?projectId=${encodeURIComponent(n)}`:"";return fetch(`/api/mcp/plugin-servers${x}`,{signal:m.signal}).then(async w=>{if(!w.ok)throw new Error("Failed to load project plugin MCP servers");return w.json()}).then(w=>{m.signal.aborted||(o||l(Array.isArray(w.servers)?w.servers:[]),p(w.fusionMemoryMcpAvailable===!0))}).catch(()=>{m.signal.aborted||(o||l([]),p(!1))}),()=>m.abort()},[o,n]),e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:u("settings.nav.mcp","MCP Servers")}),e.jsx(bi,{scope:"project",form:t,setForm:s,globalSettings:a,projectId:n,pluginServers:o??c,builtInAvailable:h,addToast:d})]})}function mh({form:t,setForm:s}){const{t:a}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.backups.memoryBackups","Memory Backups")}),e.jsx(ae,{descriptor:{key:"memoryBackupEnabled",label:a("settings.backups.enableAutomaticMemoryBackups"," Enable automatic memory backups "),help:a("settings.backups.whenEnabledProjectAndAgentMemoryFilesAre","When enabled, project and agent memory files are backed up automatically on a schedule. Default: disabled."),scope:"project"},value:t.memoryBackupEnabled||!1,onChange:n=>s(o=>({...o,memoryBackupEnabled:n===!0}))}),e.jsx(be,{descriptor:{key:"memoryBackupSchedule",label:a("settings.backups.memoryBackupScheduleCron","Memory Backup Schedule (Cron)"),help:a("settings.backups.cronExpressionForMemoryBackupTimingDefault0","Cron expression for memory backup timing. Default: 0 3 * * * (daily at 3 AM)."),scope:"project",placeholder:a("settings.backups.03","0 3 * * *"),disabled:!t.memoryBackupEnabled},value:t.memoryBackupSchedule||"0 3 * * *",onChange:n=>s(o=>({...o,memoryBackupSchedule:n??""})),error:t.memoryBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.memoryBackupSchedule)?a("settings.backups.invalidCronExpressionFormat","Invalid cron expression format"):void 0}),e.jsx(Pe,{descriptor:{key:"memoryBackupRetention",label:a("settings.backups.memoryRetentionCount","Memory Retention Count"),help:a("settings.backups.numberOfMemoryBackupsToKeepOldestAre","Number of memory backups to keep (oldest are deleted first). Range: 1-100. Default: 14."),scope:"project",min:1,max:100,disabled:!t.memoryBackupEnabled},value:t.memoryBackupRetention??null,onChange:n=>s(o=>({...o,memoryBackupRetention:n??void 0})),error:t.memoryBackupRetention!==void 0&&(t.memoryBackupRetention<1||t.memoryBackupRetention>100)?a("settings.backups.mustBeBetween1And100","Must be between 1 and 100"):void 0}),e.jsx(be,{descriptor:{key:"memoryBackupDir",label:a("settings.backups.memoryBackupDirectory","Memory Backup Directory"),help:a("settings.backups.directoryForMemoryBackupsRelativeToProjectRoot","Directory for memory backups, relative to project root. Default: .fusion/backups/memory."),scope:"project",placeholder:a("settings.backups.fusionBackupsMemory",".fusion/backups/memory"),disabled:!t.memoryBackupEnabled},value:t.memoryBackupDir||".fusion/backups/memory",onChange:n=>s(o=>({...o,memoryBackupDir:n??""})),error:t.memoryBackupDir&&t.memoryBackupDir.includes("..")?a("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)"):void 0}),e.jsx(Ae,{descriptor:{key:"memoryBackupScope",label:a("settings.backups.memoryBackupScope","Memory Backup Scope"),help:a("settings.backups.memoryBackupScopeHint","Default: all (project + agents)."),scope:"project",disabled:!t.memoryBackupEnabled,options:[{value:"all",label:a("settings.backups.allProjectAgents","All (project + agents)")},{value:"project",label:a("settings.backups.projectOnlyFusionMemory","Project only (.fusion/memory)")},{value:"agents",label:a("settings.backups.agentsOnlyFusionAgentMemory","Agents only (.fusion/agent-memory)")}]},value:t.memoryBackupScope||"all",onChange:n=>s(o=>({...o,memoryBackupScope:n??"all"}))})]})}function bh({projectId:t,onSettingsRefresh:s}){const{t:a}=le("app"),{confirm:n}=Yn(),[o,d]=i.useState(null),[u,c]=i.useState(null),[l,h]=i.useState(null),p=async()=>{try{c(null);const x=await Ue($e("/config/revisions",t));d(Array.isArray(x.revisions)?x.revisions:[])}catch(x){d(null),c(x instanceof Error?x.message:a("settings.configVersions.loadError","Unable to load configuration versions"))}};i.useEffect(()=>{p()},[t]);const m=async x=>{if(await n({title:a("settings.configVersions.confirmTitle","Roll back configuration?"),message:a("settings.configVersions.confirmMessage","Restore this version? The rollback is recorded as a new version."),confirmLabel:a("settings.configVersions.confirmRollback","Roll back"),cancelLabel:a("actions.cancel","Cancel")})){h(x.id);try{await Ue($e(`/config/revisions/${encodeURIComponent(x.id)}/rollback`,t),{method:"POST"}),await s(),await p()}catch(f){c(f instanceof Error?f.message:a("settings.configVersions.rollbackError","Unable to roll back configuration"))}finally{h(null)}}};return e.jsxs("section",{className:"configuration-versions-section","data-testid":"settings-config-versions",children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.configVersions.title","Configuration versions")}),e.jsx("p",{className:"settings-section-description",children:a("settings.configVersions.description","Restore any recorded project configuration version.")}),u?e.jsx("p",{className:"configuration-versions-section__error",role:"alert",children:u}):o===null?e.jsx("p",{className:"settings-muted",children:a("settings.configVersions.loading","Loading versions…")}):o.length===0?e.jsx("p",{className:"settings-muted","data-testid":"settings-config-versions-empty",children:a("settings.configVersions.empty","No configuration versions yet.")}):e.jsx("ul",{className:"configuration-versions-section__list","data-testid":"settings-config-versions-list",children:o.map(x=>e.jsxs("li",{className:"configuration-versions-section__item",children:[e.jsxs("span",{children:[e.jsx("strong",{children:x.configKind}),e.jsx("small",{children:new Date(x.createdAt).toLocaleString()})]}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void m(x),disabled:l!==null,children:l===x.id?a("settings.configVersions.rollingBack","Rolling back…"):e.jsxs(e.Fragment,{children:[e.jsx(su,{size:16,"aria-hidden":"true"}),a("settings.configVersions.rollback","Roll back")]})})]},x.id))})]})}function fh({form:t,setForm:s,backupInfo:a,backupLoading:n,onBackupNow:o}){const{t:d}=le("app"),u=t.backupSettingsMigrationConflicts??[],c=(l,h)=>{s(p=>({...p,[l.key]:h.value,backupSettingsMigrationConflicts:u.filter(m=>m.key!==l.key)}))};return e.jsxs(e.Fragment,{children:[u.length>0&&e.jsxs("div",{className:"settings-notice settings-notice-warning",role:"status",children:[e.jsx("strong",{children:d("settings.backups.migrationConflict","Choose database backup settings")}),e.jsx("p",{children:d("settings.backups.migrationConflictHelp","Existing projects used different backup settings. Choose the value to use globally.")}),u.map(l=>e.jsxs("div",{children:[e.jsx("span",{children:l.key}),l.candidates.map((h,p)=>e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>c(l,h),children:h.source==="global"?d("settings.backups.existingGlobalValue","Existing global value"):`${d("settings.backups.projectValue","Project value")}: ${h.projectId}`},`${h.source}-${h.projectId??"global"}-${p}`))]},l.key))]}),e.jsx("h4",{className:"settings-section-heading",children:d("settings.backups.databaseBackups","Database Backups")}),e.jsxs("details",{className:"settings-advanced-disclosure",children:[e.jsx("summary",{children:d("settings.database.advanced","Advanced database settings")}),e.jsx(Pe,{descriptor:{key:"embeddedPostgresMaxConnections",label:d("settings.database.embeddedConnectionCap","Embedded PostgreSQL connection cap"),help:d("settings.database.embeddedConnectionCapHelp","Maximum server connections for Fusion's embedded PostgreSQL. Applies after restarting Fusion. Range: 32–2,000. Unset by default — Fusion picks 500, or 150 on Windows where each connection is a separate process and higher caps can crash backends. External PostgreSQL uses its provider's connection limit."),scope:"global",min:32,max:2e3,placeholder:d("settings.database.embeddedConnectionCapPlaceholder","auto")},value:t.embeddedPostgresMaxConnections??null,onChange:l=>s(h=>({...h,embeddedPostgresMaxConnections:l??void 0})),error:t.embeddedPostgresMaxConnections!==void 0&&(t.embeddedPostgresMaxConnections<32||t.embeddedPostgresMaxConnections>2e3)?d("settings.database.embeddedConnectionCapError","Enter a value between 32 and 2,000."):void 0})]}),e.jsx(ae,{descriptor:{key:"autoBackupEnabled",label:d("settings.backups.enableAutomaticDatabaseBackups"," Enable automatic database backups "),help:d("settings.backups.whenEnabledTheDatabaseIsBackedUpAutomatically","When enabled, the database is backed up automatically on a schedule. Default: disabled."),scope:"global"},value:t.autoBackupEnabled||!1,onChange:l=>s(h=>({...h,autoBackupEnabled:l===!0}))}),e.jsx(be,{descriptor:{key:"autoBackupSchedule",label:d("settings.backups.backupScheduleCron","Backup Schedule (Cron)"),help:d("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) "),scope:"global",placeholder:d("settings.backups.02","0 2 * * *"),disabled:!t.autoBackupEnabled},value:t.autoBackupSchedule||"0 2 * * *",onChange:l=>s(h=>({...h,autoBackupSchedule:l??""})),error:t.autoBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.autoBackupSchedule)?d("settings.backups.invalidCronExpressionFormat","Invalid cron expression format"):void 0}),e.jsx(Pe,{descriptor:{key:"autoBackupRetention",label:d("settings.backups.retentionCount","Retention Count"),help:d("settings.backups.numberOfBackupFilesToKeepOldestAre","Number of backup files to keep (oldest are deleted first). Range: 1-100. Default: 7."),scope:"global",min:1,max:100,disabled:!t.autoBackupEnabled},value:t.autoBackupRetention??null,onChange:l=>s(h=>({...h,autoBackupRetention:l??void 0})),error:t.autoBackupRetention!==void 0&&(t.autoBackupRetention<1||t.autoBackupRetention>100)?d("settings.backups.mustBeBetween1And100","Must be between 1 and 100"):void 0}),e.jsx(be,{descriptor:{key:"autoBackupDir",label:d("settings.backups.backupDirectory","Backup Directory"),help:d("settings.backups.directoryForBackupFilesRelativeToProjectRoot","Directory for backup files, relative to the global Fusion directory. Default: .fusion/backups."),scope:"global",placeholder:d("settings.backups.fusionBackups",".fusion/backups"),disabled:!t.autoBackupEnabled},value:t.autoBackupDir||".fusion/backups",onChange:l=>s(h=>({...h,autoBackupDir:l??""})),error:t.autoBackupDir&&t.autoBackupDir.includes("..")?d("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)"):void 0}),n?e.jsx("div",{className:"settings-empty-state",children:e.jsx(Et,{label:d("settings.backups.loadingBackupInfo","Loading backup info…")})}):a?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:d("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:a.count}),e.jsx("span",{className:"backup-stat-label",children:d("settings.backups.backups","backups")})]}),e.jsxs("div",{className:"backup-stat",children:[e.jsx("span",{className:"backup-stat-value",children:a.totalSize>1024*1024?`${(a.totalSize/(1024*1024)).toFixed(1)} MB`:`${(a.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:d("settings.backups.totalSize","total size")})]})]}),a.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:[d("settings.backups.view","View "),a.backups.length,d("settings.backups.backupS"," backup(s)")]}),e.jsxs("ul",{children:[a.backups.slice(0,10).map(l=>e.jsxs("li",{children:[e.jsx("code",{children:l.filename}),e.jsx("span",{className:"backup-size",children:l.size>1024*1024?`${(l.size/(1024*1024)).toFixed(1)} MB`:`${(l.size/1024).toFixed(1)} KB`})]},l.filename)),a.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:[d("settings.backups.and","...and "),a.backups.length-10,d("settings.backups.more"," more")]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:o,disabled:n,children:n?d("settings.backups.creating","Creating…"):d("settings.backups.backupNow","Backup Now")})})]})}const yh=i.lazy(()=>oi(()=>import("./PluginManager-k7hV7_9e.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(t=>({default:t.PluginManager}))),vh=i.lazy(()=>oi(()=>import("./PiExtensionsManager-B8At6fO8.js"),__vite__mapDeps([14,1,2,3,4,5,6,7,8,9,15,16,17,18])).then(t=>({default:t.PiExtensionsManager})));function kh({projectId:t,addToast:s,activePluginsSubsection:a,setActivePluginsSubsection:n,onPluginsChanged:o}){const{t:d}=le("app");return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:d("settings.plugins.plugins","Plugins")}),e.jsxs("div",{className:"settings-plugins-subsection-toggle",role:"tablist","aria-label":d("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":a==="fusion-plugins",tabIndex:a==="fusion-plugins"?0:-1,className:`settings-plugins-subsection-btn${a==="fusion-plugins"?" active":""}`,onClick:()=>n("fusion-plugins"),children:d("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":a==="pi-extensions",tabIndex:a==="pi-extensions"?0:-1,className:`settings-plugins-subsection-btn${a==="pi-extensions"?" active":""}`,onClick:()=>n("pi-extensions"),children:d("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:a!=="fusion-plugins",children:a==="fusion-plugins"&&e.jsxs(e.Fragment,{children:[e.jsx(i.Suspense,{fallback:null,children:e.jsx(yh,{addToast:s,projectId:t,onPluginsChanged:o})}),e.jsx(_n,{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:a!=="pi-extensions",children:a==="pi-extensions"&&e.jsx(i.Suspense,{fallback:null,children:e.jsx(vh,{addToast:s,projectId:t})})})]})}function En(t,s){if(!s)return t;const a=t.includes("?")?"&":"?";return`${t}${a}projectId=${encodeURIComponent(s)}`}async function Vr(t,s){const a=await fetch(t,{credentials:"same-origin",...s,headers:{"Content-Type":"application/json",...s?.headers??{}}}),n=await a.json();if(!a.ok)throw new Error(n.error??`Request failed (${a.status})`);return n}function xh(t,s){const a=s?.enabled===!0,[n,o]=i.useState({status:"missing"}),[d,u]=i.useState(!1),c=i.useCallback(async()=>{try{const h=await Vr(En("/api/worktrunk/status",t));return o(h),h}catch(h){const p={status:"failed",error:h instanceof Error?h.message:"Failed to load worktrunk status"};return o(p),p}},[t]);i.useEffect(()=>{a&&c()},[a,c]),i.useEffect(()=>{const h=()=>{n.pendingApprovalId&&c()};return ci(En("/api/events",t),{onReconnect:h,events:{"approval:updated":h,"approval:decided":h}})},[t,c,n.pendingApprovalId]);const l=i.useCallback(async()=>{u(!0),o(h=>({...h,status:"installing",error:void 0}));try{const h=await Vr(En("/api/worktrunk/install-request",t),{method:"POST",body:JSON.stringify({})});o({status:h.status,version:h.version,installPath:h.installPath,pendingApprovalId:h.pendingApprovalId??h.approvalRequestId,error:h.error})}catch(h){o({status:"failed",error:h instanceof Error?h.message:"Failed to request install"})}finally{u(!1)}},[t]);return{...n,refresh:c,requestInstall:l,requesting:d}}const jh=[{sectionId:"appearance",key:"openTasksInRightSidebar",labelKey:"settings.appearance.openTasksInRightSidebar",labelFallback:"Open tasks in the right sidebar",helpKey:"settings.appearance.openTasksInRightSidebarHelp",helpFallback:"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.",keywords:["dock","right dock","side panel"]},{sectionId:"appearance",key:"openMobileTasksInPopup",labelKey:"settings.appearance.openMobileTasksInPopup",labelFallback:"Open tasks as popups",helpKey:"settings.appearance.openMobileTasksInPopupHelp",helpFallback:"When enabled, ordinary board task-card, List row/card, and right-dock Tasks-list clicks open the existing movable task popup so the board or list remains visible. Deep-tab and other task opens keep their current behavior. Default: disabled.",keywords:["mobile","floating window","modal"]},{sectionId:"appearance",key:"taskPopupsBoardListOnly",labelKey:"settings.appearance.taskPopupsBoardListOnly",labelFallback:"Keep task popups on the view where they were opened",helpKey:"settings.appearance.taskPopupsBoardListOnlyHelp",helpFallback:"When enabled, each open task-detail popup appears only on the view where it was opened. Switching views hides it without closing; returning restores it in the same position. Default: enabled.",keywords:["popup view attachment","pin popup"]},{sectionId:"appearance",key:"showCostBadgeOnCards",labelKey:"settings.appearance.showCostBadgeOnCards",labelFallback:"Show cost badges on task cards",helpKey:"settings.appearance.showCostBadgeOnCardsHelp",helpFallback:"Default: disabled. When enabled, board cards show derived model cost next to execution time; unavailable pricing displays — and tasks without token usage show no badge.",keywords:["spend","price","tokens","usage"]},{sectionId:"appearance",key:"taskDetailChatFirst",labelKey:"settings.appearance.taskDetailChatFirst",labelFallback:"Open task details with Chat first",helpKey:"settings.appearance.taskDetailChatFirstHelp",helpFallback:"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.",keywords:["activity first","default tab"]},{sectionId:"appearance",key:"sessionBannersHidden",labelKey:"settings.appearance.hideAISessionNotificationBanners",labelFallback:"Hide AI session notification banners",helpKey:"settings.appearance.suppressTheLdquoNeedsYourInputRdquoBanner",helpFallback:"Suppress the “needs your input” banner that appears when AI sessions are awaiting input or have failed.",keywords:["needs your input","toast","alert"]}],wh=[{sectionId:"authentication",key:"anthropicAuthPreference",labelKey:"settings.auth.anthropicPreferenceLabel",labelFallback:"Anthropic credential to use",helpKey:"settings.auth.anthropicPreferenceHint",helpFallback:"You have both an Anthropic API key and a Claude subscription connected. Choose which one Fusion sends when a lane calls Anthropic directly. Default: API key.",keywords:["anthropic","api key","subscription","oauth","credential precedence","claude"]}],Ch=[{sectionId:"backups",key:"memoryBackupEnabled",labelKey:"settings.backups.enableAutomaticMemoryBackups",labelFallback:" Enable automatic memory backups ",helpKey:"settings.backups.whenEnabledProjectAndAgentMemoryFilesAre",helpFallback:"When enabled, project and agent memory files are backed up automatically on a schedule. Default: disabled.",keywords:["snapshot","restore"]},{sectionId:"backups",key:"memoryBackupSchedule",labelKey:"settings.backups.memoryBackupScheduleCron",labelFallback:"Memory Backup Schedule (Cron)",helpKey:"settings.backups.cronExpressionForMemoryBackupTimingDefault0",helpFallback:"Cron expression for memory backup timing. Default: 0 3 * * * (daily at 3 AM).",keywords:["timing","frequency"]},{sectionId:"backups",key:"memoryBackupRetention",labelKey:"settings.backups.memoryRetentionCount",labelFallback:"Memory Retention Count",helpKey:"settings.backups.numberOfMemoryBackupsToKeepOldestAre",helpFallback:"Number of memory backups to keep (oldest are deleted first). Range: 1-100. Default: 14.",keywords:["how many","prune","rotation"]},{sectionId:"backups",key:"memoryBackupDir",labelKey:"settings.backups.memoryBackupDirectory",labelFallback:"Memory Backup Directory",helpKey:"settings.backups.directoryForMemoryBackupsRelativeToProjectRoot",helpFallback:"Directory for memory backups, relative to project root. Default: .fusion/backups/memory.",keywords:["location","folder","destination"]},{sectionId:"backups",key:"memoryBackupScope",labelKey:"settings.backups.memoryBackupScope",labelFallback:"Memory Backup Scope",helpKey:"settings.backups.memoryBackupScopeHint",helpFallback:"Default: all (project + agents).",keywords:["agent memory",".fusion/memory",".fusion/agent-memory","what to back up"]}],Sh=[{sectionId:"backups-global",key:"autoBackupEnabled",labelKey:"settings.backups.enableAutomaticDatabaseBackups",labelFallback:" Enable automatic database backups ",helpKey:"settings.backups.whenEnabledTheDatabaseIsBackedUpAutomatically",helpFallback:"When enabled, the database is backed up automatically on a schedule. Default: disabled.",keywords:["sqlite","snapshot","restore"]},{sectionId:"backups-global",key:"autoBackupSchedule",labelKey:"settings.backups.backupScheduleCron",labelFallback:"Backup Schedule (Cron)",helpKey:"settings.backups.cronExpressionForBackupTimingDefault02",helpFallback:" Cron expression for backup timing. Default: 0 2 * * * (daily at 2 AM). Examples: 0 * * * * (hourly), 0 0 * * 0 (weekly), */15 * * * * (every 15 min) ",keywords:["timing","frequency"]},{sectionId:"backups-global",key:"autoBackupRetention",labelKey:"settings.backups.retentionCount",labelFallback:"Retention Count",helpKey:"settings.backups.numberOfBackupFilesToKeepOldestAre",helpFallback:"Number of backup files to keep (oldest are deleted first). Range: 1-100. Default: 7.",keywords:["how many","prune","rotation"]},{sectionId:"backups-global",key:"autoBackupDir",labelKey:"settings.backups.backupDirectory",labelFallback:"Backup Directory",helpKey:"settings.backups.directoryForBackupFilesRelativeToProjectRoot",helpFallback:"Directory for backup files, relative to project root. Default: .fusion/backups.",keywords:["location","folder","destination"]},{sectionId:"backups-global",key:"embeddedPostgresMaxConnections",labelKey:"settings.database.embeddedConnectionCap",labelFallback:"Embedded PostgreSQL connection cap",helpKey:"settings.database.embeddedConnectionCapHelp",helpFallback:"Maximum server connections for Fusion's embedded PostgreSQL. Applies after restarting Fusion. Range: 32–2,000. Default: 500. External PostgreSQL uses its provider's connection limit.",keywords:["postgres","postgresql","connections","embedded","cap","database"]}],Nh=[{sectionId:"commands",key:"testCommand",labelKey:"settings.commands.testCommand",labelFallback:"Test Command",helpKey:"settings.commands.commandUsedToRunTestsInjectedIntoGenerated",helpFallback:"Command used to run tests — injected into generated task specs. No default — unset.",keywords:["verify","verification","vitest","pnpm test"]},{sectionId:"commands",key:"buildCommand",labelKey:"settings.commands.buildCommand",labelFallback:"Build Command",helpKey:"settings.commands.commandUsedToBuildTheProjectInjectedInto",helpFallback:"Command used to build the project — injected into generated task specs. No default — unset.",keywords:["compile","pnpm build"]}],Ph=[{sectionId:"general",key:"report-action-menu",labelKey:"settings.general.report",labelFallback:"Report",helpKey:"settings.general.reportHelp",helpFallback:"Report a bug, send feedback, share an idea, or get help from Fusion.",keywords:["bug","feedback","idea","help","support"]},{sectionId:"general",key:"taskPrefix",labelKey:"settings.general.taskPrefix",labelFallback:"Task Prefix",helpKey:"settings.general.prefixForNewTaskIDsEGKB",helpFallback:"Prefix for new task IDs (e.g. KB, PROJ). No default — unset.",keywords:["task id","identifier","naming"]},{sectionId:"general",key:"ephemeralAgentTaskCreationPolicy",labelKey:"settings.general.ephemeralAgentTaskCreationPolicy",labelFallback:"Ephemeral agent follow-up tasks",helpKey:"settings.general.ephemeralAgentTaskCreationPolicyHint",helpFallback:"Allow creates follow-up tasks immediately. Upon validation sends a proposal to your mailbox for one-click approval. Deny rejects follow-up task creation.",keywords:["follow-up","permissions","validation","proposal"]},{sectionId:"general",key:"workspaceMode",labelKey:"settings.general.workspaceMode",labelFallback:" Workspace mode (multi-repo) ",helpKey:"settings.general.workspaceModeHint",helpFallback:"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).",keywords:["monorepo","polyrepo"]},{sectionId:"general",key:"allowAbsoluteFileBrowserPaths",labelKey:"settings.general.allowAbsoluteFileBrowserPaths",labelFallback:" Allow absolute file-browser paths ",helpKey:"settings.general.allowAbsoluteFileBrowserPathsHint",helpFallback:"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.",keywords:["outside workspace","root paths"]},{sectionId:"general",key:"mobileNavPrimaryItems",labelKey:"settings.general.mobileNavPrimaryItems",labelFallback:"Mobile footer quick actions",helpKey:"settings.general.mobileNavPrimaryItemsHint",helpFallback:"Default: Dashboard, Tasks, Agents, Missions, Chat, Mailbox. Unselected destinations remain in More.",keywords:["mobile","footer","navigation","planning","more"]},{sectionId:"general",key:"quickChatButtonMode",labelKey:"settings.general.quickChatLauncher",labelFallback:"Quick Chat launcher",helpKey:"settings.general.quickChatLauncherHint",helpFallback:"Choose whether Quick Chat opens from the draggable floating button, a footer button beside Terminal, or stays hidden. Default: off (hidden).",keywords:["FAB","floating action button"]},{sectionId:"general",key:"quickChatCloseOnOutsideClick",labelKey:"settings.general.quickChatCloseOnOutsideClick",labelFallback:"Close Quick Chat on outside click",helpKey:"settings.general.quickChatCloseOnOutsideClickHint",helpFallback:"When enabled, clicking outside the Quick Chat window closes it. Disable to keep it open until you close it explicitly. Default: enabled.",keywords:["dismiss","backdrop"]},{sectionId:"general",key:"showTaskChatsInCommonFeed",labelKey:"settings.general.showTaskChatsInCommonFeed",labelFallback:"Show task chats in common Chat feed",helpKey:"settings.general.showTaskChatsInCommonFeedHint",helpFallback:"When enabled, populated task-detail Chat conversations appear in the common Direct feed. Empty task chats stay hidden. Default: disabled.",keywords:["planner chats","inbox"]},{sectionId:"general",key:"chatAutoCleanupDays",labelKey:"settings.general.autoCleanupOldChats",labelFallback:"Auto-cleanup old chats",helpKey:"settings.general.deleteChatSessionsAndRoomsThatHaveBeen",helpFallback:"Delete chat sessions and rooms that have been idle for this many days. Default: Off.",keywords:["retention","prune","purge"]},{sectionId:"general",key:"mailAutoCleanupDays",labelKey:"settings.general.autoPruneOldMail",labelFallback:"Auto-prune old mail",helpKey:"settings.general.deleteInboxOutboxMessagesOlderThanThisMany",helpFallback:"Delete inbox/outbox messages older than this many days. Default: Off. 7 days is the suggested setting.",keywords:["retention","purge","mailbox"]},{sectionId:"general",key:"operationalLogRetentionDays",labelKey:"settings.general.operationalLogRetention",labelFallback:"Operational log retention",helpKey:"settings.general.loweringThisWindowMeansReliabilityMetricsChartsAnd",helpFallback:" 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. ",keywords:["run audit","database size","purge","disk"]},{sectionId:"general",key:"chatRoomRecentVerbatimMessages",labelKey:"settings.general.recentVerbatimRoomMessages",labelFallback:"Recent verbatim room messages",helpKey:"settings.general.numberOfMostRecentChatRoomMessagesKept",helpFallback:"Number of most-recent chat-room messages kept verbatim in the responder transcript. Older messages are compacted into a summary block. Default: 25.",keywords:["context window","history depth"]},{sectionId:"general",key:"chatRoomCompactionFetchLimit",labelKey:"settings.general.roomCompactionFetchLimit",labelFallback:"Room compaction fetch limit",helpKey:"settings.general.upperBoundOnMessagesFetchedFromTheRoom",helpFallback:"Upper bound on messages fetched from the room store for compaction consideration. Default: 200.",keywords:["summarization","context window"]},{sectionId:"general",key:"chatRoomSummaryMaxChars",labelKey:"settings.general.roomSummaryMaxCharacters",labelFallback:"Room summary max characters",helpKey:"settings.general.hardCapOnTheSynthesizedEarlierRoomContext",helpFallback:'Hard cap on the synthesized "Earlier room context" summary block. Default: 3000.',keywords:["compaction","length limit"]},{sectionId:"general",key:"capacityRiskBannerEnabled",labelKey:"settings.general.showCapacityRiskBanner",labelFallback:" Show capacity risk banner ",helpKey:"settings.general.warnOnTheBoardWhenTodoWorkExceeds",helpFallback:"Warn on the board when todo work exceeds the threshold and no idle agents are available. Default: disabled.",keywords:["backlog warning","overload","alert"]},{sectionId:"general",key:"capacityRiskTodoThreshold",labelKey:"settings.general.todoThreshold",labelFallback:"Todo threshold",helpKey:"settings.general.bannerFiresWhenTodoCountIsStrictlyGreater",helpFallback:"Banner fires when todo count is strictly greater than this value (default 20). Applies when the banner is enabled.",keywords:["capacity risk","backlog limit"]},{sectionId:"general",key:"sessionAdvisorEnabledByDefault",labelKey:"settings.general.defaultSessionAdvisorForNewTasks",labelFallback:"Default for new tasks",helpKey:"settings.general.sessionAdvisorHelp",helpFallback:"Controls whether newly created tasks enable the session advisor (live LLM overseer of the executor). Individual tasks can override this from Quick Add or task detail. Also set Session advisor model provider and model id under workflow settings before the advisor can run.",keywords:["session advisor","overseer","oversight","planner"]},{sectionId:"general",key:"githubImportAutoTranslate",labelKey:"settings.general.autoTranslateImportedIssues",labelFallback:"Auto-translate imported issues",helpKey:"settings.general.autoTranslateImportedIssuesHelp",helpFallback:"When enabled, the Import Tasks panel automatically translates foreign-language issue titles and bodies into the target language below and shows the translation by default. You can always switch back to the original text, and imported tasks carry the translated text. Default: disabled.",keywords:["localization","foreign language"]},{sectionId:"general",key:"importTranslateTargetLocale",labelKey:"settings.general.translationTargetLanguage",labelFallback:"Translation target language",helpKey:"settings.general.translationTargetLanguageHelp",helpFallback:"Language imported issues are translated into when auto-translation is enabled. No default — unset inherits the dashboard language.",keywords:["locale","localization"]},{sectionId:"general",key:"reportRoadmapDedupeEnabled",labelKey:"settings.general.reportRoadmapDedupeEnabled",labelFallback:"Deduplicate reports against public roadmap",helpKey:"settings.general.reportRoadmapDedupeEnabledHelp",helpFallback:"Match open, labeled roadmap issues before filing. Default: on.",keywords:["roadmap","dedup","report","duplicate"]},{sectionId:"general",key:"reportRoadmapLabel",labelKey:"settings.general.reportRoadmapLabel",labelFallback:"Public roadmap label",helpKey:"settings.general.reportRoadmapLabelHelp",helpFallback:"Open GitHub Issues with this label are considered roadmap items. Default: roadmap.",keywords:["roadmap","label","report","duplicate"]},{sectionId:"general",key:"reportRoadmapRepo",labelKey:"settings.general.reportRoadmapRepo",labelFallback:"Public roadmap repository (optional)",helpKey:"settings.general.reportRoadmapRepoHelp",helpFallback:"GitHub owner/repository containing public roadmap issues. When unset, uses the tracking repository. No default — unset.",keywords:["roadmap","repository","repo","tracking"]}],Ih=[{sectionId:"global-general",key:"dismissModalsOnOutsideClick",labelKey:"settings.globalGeneral.dismissModalsByClickingOutside",labelFallback:" Dismiss modals by clicking outside ",helpKey:"settings.globalGeneral.dismissModalsByClickingOutsideHint",helpFallback:" When enabled, clicking or tapping a modal backdrop closes the modal. Default: disabled, to prevent accidental dismissal. ",keywords:["dialog","backdrop","accidental close"]},{sectionId:"global-general",key:"skipConfirmationDialogs",labelKey:"settings.globalGeneral.skipConfirmationDialogs",labelFallback:" Skip confirmation dialogs for critical actions ",helpKey:"settings.globalGeneral.skipConfirmationDialogsHint",helpFallback:" When enabled, destructive actions such as deleting a task or resetting progress run immediately without a prompt. Default: disabled",keywords:["confirm","critical action","delete","reset","destructive"]},{sectionId:"global-general",key:"persistAgentToolOutput",labelKey:"settings.globalGeneral.saveToolOutputInAgentLogs",labelFallback:" Save tool output in agent logs ",helpKey:"settings.globalGeneral.whenDisabledToolRowsAreStillLoggedBut",helpFallback:" 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. ",keywords:["persist","transcript","disk usage"]},{sectionId:"global-general",key:"agentToolOutputMaxChars",labelKey:"settings.globalGeneral.agentToolOutputLimit",labelFallback:" Agent tool-output limit ",helpKey:"settings.globalGeneral.agentToolOutputLimitHint",helpFallback:" Maximum characters returned from each engine-injected tool result. When unset, inherits the 16,000-character engine default. Leave empty to use the default. ",keywords:["tokens","context","truncate","tool output","agent"]},{sectionId:"global-general",key:"agentToolOutputMaxCharsNoLimit",labelKey:"settings.globalGeneral.noLimitOnAgentToolOutput",labelFallback:" No limit on agent tool output ",helpKey:"settings.globalGeneral.noLimitOnAgentToolOutputHint",helpFallback:" Disable the shared tool-output clamp. A single tool result can consume the agent context window. Default: disabled; when unset, the budget inherits the 16,000-character engine default. ",keywords:["unlimited","tokens","context","truncate","tool output"]},{sectionId:"global-general",key:"proactiveTaskChatEnabled",labelKey:"settings.globalGeneral.enableProactiveTaskChat",labelFallback:" Enable proactive task-chat updates ",helpKey:"settings.globalGeneral.enableProactiveTaskChatHint",helpFallback:" When enabled, Task chat reports step progress, failures, reviews, and rollbacks in real time. Default: disabled. ",keywords:["task chat","progress","status","rollback","failure"]},{sectionId:"global-general",key:"updateCheckFrequency",labelKey:"settings.globalGeneral.frequency",labelFallback:"Frequency",helpKey:"settings.globalGeneral.controlsHowOftenTheDashboardReFetchesThe",helpFallback:" 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. ",keywords:["update check","cadence","how often","version check"]},{sectionId:"global-general",key:"updateChannel",labelKey:"settings.globalGeneral.releaseChannel",labelFallback:"Release channel",helpKey:"settings.globalGeneral.releaseChannelHelp",helpFallback:" Stable follows official releases. Beta follows pre-releases cut from main (versions like 0.73.0-beta.2) and also picks up each stable release once it overtakes the beta. Switching back to Stable never downgrades; you stay on the installed beta until the next stable release passes it. Default: stable. ",keywords:["beta","channel","release track","prerelease","early access"]},{sectionId:"global-general",key:"autoUpdateAndRestart",labelKey:"settings.globalGeneral.autoUpdateAndRestart",labelFallback:" Auto-update and restart ",helpKey:"settings.globalGeneral.autoUpdateAndRestartHelp",helpFallback:' When enabled, Fusion installs available updates on the selected release channel by itself and then restarts to apply them — the same install + restart the "Update now" button performs, without asking. Requires a supervising parent (the default for `fn dashboard`); hosts started with --no-supervise skip the install. Default: disabled. ',keywords:["auto update","automatic update","self update","unattended","restart"]},{sectionId:"global-general",key:"autoReloadOnVersionChange",labelKey:"settings.globalGeneral.autoReloadDashboardOnVersionChange",labelFallback:" Auto-reload dashboard on version change ",helpKey:"settings.globalGeneral.whenEnabledDefaultTheDashboardAutomaticallyReloadsWhen",helpFallback:" 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. ",keywords:["refresh","service worker","hot reload"]}],Th=[{sectionId:"global-models",key:"defaultThinkingLevel",labelKey:"settings.globalModels.thinkingEffort",labelFallback:"Thinking Effort",helpKey:"settings.globalModels.controlsHowMuchReasoningEffortTheAIModel",helpFallback:"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).",keywords:["high","low","medium","xhigh","extended thinking"]},{sectionId:"global-models",key:"openrouterModelSync",labelKey:"settings.globalModels.syncOpenRouterModelListAtStartup",labelFallback:" Sync OpenRouter model list at startup ",helpKey:"settings.globalModels.whenEnabledStartupFetchesTheLatestAvailableModels",helpFallback:" When enabled, startup fetches the latest available models from the OpenRouter API so model pickers always include the newest catalog. Default: enabled. ",keywords:["refresh","boot"]},{sectionId:"global-models",key:"openrouterAppAttribution.referer",labelKey:"settings.globalModels.openRouterHTTPReferer",labelFallback:"OpenRouter HTTP-Referer",helpKey:"settings.globalModels.leaveEmptyToOmitThisHeaderDefaultHttps",helpFallback:"Leave empty to omit this header. No default — unset (Fusion falls back to https://runfusion.ai when unset).",keywords:["attribution","app ranking"]},{sectionId:"global-models",key:"openrouterAppAttribution.title",labelKey:"settings.globalModels.openRouterXTitle",labelFallback:"OpenRouter X-Title",helpKey:"settings.globalModels.leaveEmptyToOmitThisHeaderDefaultFusion",helpFallback:'Leave empty to omit this header. No default — unset (Fusion falls back to the title "Fusion" when unset).',keywords:["attribution","app ranking"]},{sectionId:"global-models",key:"openrouterModelFilters.supported_parameters",labelKey:"settings.globalModels.openRouterSupportedParametersFilter",labelFallback:"OpenRouter supported_parameters filter",helpKey:"settings.globalModels.commaSeparatedValuesSentToOpenRouterModelSync",helpFallback:"Comma-separated values sent to OpenRouter model sync. No default — unset (unfiltered).",keywords:["tools","structured outputs","catalog filter"]},{sectionId:"global-models",key:"openrouterModelFilters.output_modalities",labelKey:"settings.globalModels.openRouterOutputModalitiesFilter",labelFallback:"OpenRouter output_modalities filter",helpKey:"settings.globalModels.commaSeparatedValuesSentToOpenRouterModelSyncOutputModalities",helpFallback:"Comma-separated values sent to OpenRouter model sync. No default — unset (unfiltered).",keywords:["text","image","catalog filter"]},{sectionId:"global-models",key:"openrouterProviderPreferences.order",labelKey:"settings.globalModels.openRouterRoutingOrder",labelFallback:"OpenRouter routing order",helpKey:"settings.globalModels.openRouterRoutingOrderHint",helpFallback:"No default — unset (OpenRouter's own default routing order applies).",keywords:["provider preference","priority"]},{sectionId:"global-models",key:"openrouterProviderPreferences.ignore",labelKey:"settings.globalModels.openRouterRoutingIgnore",labelFallback:"OpenRouter routing ignore",helpKey:"settings.globalModels.openRouterRoutingIgnoreHint",helpFallback:"No default — unset (no providers ignored).",keywords:["exclude","block","deny provider"]},{sectionId:"global-models",key:"openrouterProviderPreferences.only",labelKey:"settings.globalModels.openRouterRoutingOnly",labelFallback:"OpenRouter routing only",helpKey:"settings.globalModels.openRouterRoutingOnlyHint",helpFallback:"No default — unset (no provider restriction).",keywords:["allowlist","restrict","pin provider"]},{sectionId:"global-models",key:"openrouterProviderPreferences.allow_fallbacks",labelKey:"settings.globalModels.openRouterAllowFallbacks",labelFallback:"OpenRouter allow fallbacks",helpKey:"settings.globalModels.openRouterAllowFallbacksHint",helpFallback:"No default — unset (OpenRouter's own default fallback behavior applies).",keywords:["backup provider","failover"]},{sectionId:"global-models",key:"openrouterProviderPreferences.sort",labelKey:"settings.globalModels.openRouterRoutingSort",labelFallback:"OpenRouter routing sort",helpKey:"settings.globalModels.openRouterRoutingSortHint",helpFallback:"No default — unset (OpenRouter's own default sort applies).",keywords:["price","throughput","latency","cheapest","fastest"]},{sectionId:"global-models",key:"openrouterProviderPreferences.require_parameters",labelKey:"settings.globalModels.requireParameters",labelFallback:" Require parameters ",helpKey:"settings.globalModels.requireParametersHint",helpFallback:"Default: disabled.",keywords:["strict routing","provider support"]}],Ah=[{sectionId:"memory",key:"memoryEnabled",labelKey:"settings.memory.enableMemoryTools",labelFallback:" Enable memory tools ",helpKey:"settings.memory.agentsGetMemorySearchMemoryGetAndMemory",helpFallback:"Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback. Default: enabled.",keywords:["recall","knowledge"]},{sectionId:"memory",key:"memoryAutoSummarizeEnabled",labelKey:"settings.memory.autoSummarizeMemory",labelFallback:" Auto-Summarize Memory ",helpKey:"settings.memory.automaticallyCompactMemoryWhenItExceedsTheThreshold",helpFallback:"Automatically compact memory when it exceeds the threshold on a schedule. Default: disabled.",keywords:["condense","prune","shrink"]},{sectionId:"memory",key:"memoryAutoSummarizeThresholdChars",labelKey:"settings.memory.compactionThresholdChars",labelFallback:"Compaction Threshold (chars)",helpKey:"settings.memory.memoryWillBeCompactedWhenItExceedsThis",helpFallback:"Memory will be compacted when it exceeds this character count. Default: 50000.",keywords:["size limit","trigger"]},{sectionId:"memory",key:"memoryAutoSummarizeSchedule",labelKey:"settings.memory.scheduleCron",labelFallback:"Schedule (cron)",helpKey:"settings.memory.cronExpressionForAutoSummarizeScheduleDefaultDaily",helpFallback:"Cron expression for auto-summarize schedule. Default: 0 3 * * * (daily at 3 AM).",keywords:["auto-summarize","compaction schedule","timing"]},{sectionId:"memory",key:"insightExtractionEnabled",labelKey:"settings.memory.enableInsightExtraction",labelFallback:" Enable Insight Extraction ",helpKey:"settings.memory.periodicallyExtractDurableInsightsFromCompletedTasks",helpFallback:"Periodically extract durable insights/learnings from completed tasks into memory",keywords:["lessons","retrospective"]},{sectionId:"memory",key:"insightExtractionSchedule",labelKey:"settings.memory.scheduleCron",labelFallback:"Schedule (cron)",helpKey:"settings.memory.cronExpressionForInsightExtractionScheduleDefaultDaily",helpFallback:"Cron expression for insight extraction schedule (default: daily at 2 AM)",keywords:["insight","timing"]},{sectionId:"memory",key:"memoryDreamsEnabled",labelKey:"settings.memory.processDreamsFromDailyMemory",labelFallback:" Process dreams from daily memory ",helpKey:"settings.memory.turnsDailyNotesIntoDREAMSMdAndPromotes",helpFallback:"Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md. Default: disabled.",keywords:["synthesis","consolidation"]},{sectionId:"memory",key:"memoryDreamsSchedule",labelKey:"settings.memory.dreamSchedule",labelFallback:"Dream Schedule",helpKey:"settings.memory.cronExpressionForDreamProcessing",helpFallback:"Cron expression for dream processing. Default: 0 4 * * * (daily at 4 AM).",keywords:["timing"]}],Mh=[{sectionId:"merge",key:"requiredChecks",labelKey:"settings.merge.requiredChecks",labelFallback:"Required pull-request checks",helpKey:"settings.merge.requiredChecksHelp",helpFallback:"No default — unset. Comma-separated check names match GitHub exactly (case-sensitive). Leaving this empty uses GitHub required-status checks only; a named check that never reports blocks the merge.",keywords:["CI","status","GitHub"]},{sectionId:"merge",key:"maxAutoMergeRetries",labelKey:"settings.merge.autoMergeConflictRetries",labelFallback:"Auto-merge conflict retries",helpKey:"settings.merge.positiveIntegerRetryCapForAutoMergeConflict",helpFallback:"Positive integer retry cap for auto-merge conflict resolution before a task parks for human recovery. Default 3.",keywords:["attempts","give up","parked","merge failure"]},{sectionId:"merge",key:"merger.maxReviewPasses",labelKey:"settings.merge.maxAIReviewPasses",labelFallback:"Max AI review passes",helpKey:"settings.merge.aICorrectiveRoundsBeforeLandingTheBestResult",helpFallback:"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.",keywords:["clean room","audit","retries","attempts"]},{sectionId:"merge",key:"mergeStrategyOverlapBehavior",labelKey:"settings.merge.smartPreferMainOverlapGuard",labelFallback:"Smart Prefer Main Overlap Guard",helpKey:"settings.merge.whenUsingSmartPreferMainAutomaticallyPreferThe",helpFallback:" When using smart-prefer-main, automatically prefer the branch side for files that main has recently modified to avoid silently discarding branch work. ",keywords:["ours","theirs","lost work","clobber"]}],Rh=[{sectionId:"node-routing",key:"unavailableNodePolicy",labelKey:"settings.nodeRouting.unavailableNodePolicy",labelFallback:"Unavailable Node Policy",helpKey:"settings.nodeRouting.unavailableNodePolicyHint",helpFallback:"Default: block execution.",keywords:["offline node","fallback","unreachable","local execution"]}],Eh=[{sectionId:"node-sync",key:"settingsSyncEnabled",labelKey:"settings.nodeSync.enableAutomaticSettingsSync",labelFallback:" Enable automatic settings sync ",helpKey:"settings.nodeSync.automaticallySynchronizeSettingsBetweenThisNodeAndConnected",helpFallback:"Automatically synchronize settings between this node and connected remote nodes. Default: disabled."},{sectionId:"node-sync",key:"settingsSyncAuth",labelKey:"settings.nodeSync.syncModelAuthCredentials",labelFallback:" Sync model auth credentials ",helpKey:"settings.nodeSync.includeAPIKeysAndOAuthTokensInSync",helpFallback:"Include API keys and OAuth tokens in sync operations. Default: disabled.",keywords:["secrets","authentication"]},{sectionId:"node-sync",key:"settingsSyncInterval",labelKey:"settings.nodeSync.syncInterval",labelFallback:"Sync interval",helpKey:"settings.nodeSync.syncIntervalHint",helpFallback:"Default: every 15 minutes.",keywords:["frequency","how often","schedule"]},{sectionId:"node-sync",key:"settingsSyncConflictResolution",labelKey:"settings.nodeSync.conflictResolution",labelFallback:"Conflict resolution",helpKey:"settings.nodeSync.conflictResolutionHint",helpFallback:"Default: last write wins."}],Dh=[{sectionId:"notifications",key:"failureNotificationMode",labelKey:"settings.notifications.failureNotificationMode",labelFallback:"Failure notification mode",helpKey:"settings.notifications.stickyOnlySuppressesRecoveredFailuresTerminalOnlyWaits",helpFallback:"Sticky-only suppresses recovered failures; terminal-only waits for paused/in-review failed tasks; all restores legacy alerts.",keywords:["retry","noise","alerts"]},{sectionId:"notifications",key:"failureNotificationDelayMs",labelKey:"settings.notifications.failureNotificationDelayMs",labelFallback:"Failure notification delay (ms)",helpKey:"settings.notifications.howLongAFailureMustPersistBeforeA",helpFallback:" How long a failure must persist before a push notification is sent. 0 = notify immediately. Default: 30000 (30 seconds). ",keywords:["debounce","wait","throttle"]},{sectionId:"notifications",key:"wedgeNotificationSettleMs",labelKey:"settings.notifications.wedgeNotificationSettleMs",labelFallback:"Terminal-wedge settle window (ms)",helpKey:"settings.notifications.wedgeNotificationSettleMsHelp",helpFallback:"How long a terminal failure must persist before an operator alert. 0 = notify immediately. Default: 300000 (5 minutes).",keywords:["noise","debounce","wedge","recovered"]},{sectionId:"notifications",key:"ntfyDashboardHost",labelKey:"settings.notifications.dashboardHostname",labelFallback:"Dashboard Hostname",helpKey:"settings.notifications.baseURLForDeepLinksInNotificationsWhen",helpFallback:" Base URL for deep links in notifications. When set, clicking a notification opens the dashboard directly to the task. No default — unset. ",keywords:["ntfy","deep link","base url"]},{sectionId:"notifications",key:"webhookUrl",labelKey:"settings.notifications.webhookURL",labelFallback:"Webhook URL",helpKey:"settings.notifications.webhookUrlHint",helpFallback:"No default — unset.",keywords:["endpoint","hook","callback"]},{sectionId:"notifications",key:"webhookFormat",labelKey:"settings.notifications.format",labelFallback:"Format",helpKey:"settings.notifications.webhookFormatHint",helpFallback:"Default: generic.",keywords:["slack","discord","payload","webhook"]},{sectionId:"notifications",key:"ntfyBaseUrl",labelKey:"settings.notifications.customNtfyServerURLOptional",labelFallback:"Custom ntfy server URL (optional)",helpKey:"settings.notifications.leaveBlankToKeepTheDefaultServerHttps",helpFallback:" Leave blank to keep the default server: https://ntfy.sh. Custom servers must use http:// or https://. No default — unset. ",keywords:["self-hosted","custom server"]},{sectionId:"notifications",key:"ntfyAccessToken",labelKey:"settings.notifications.accessTokenOptional",labelFallback:"Access token (optional)",helpKey:"settings.notifications.leaveBlankToPublishWithoutAuthenticationWhenSet",helpFallback:" Leave blank to publish without authentication. When set, Fusion sends an Authorization Bearer header with ntfy requests. No default — unset. ",keywords:["auth","bearer","credential","secret"]}],Fh=[{sectionId:"project-models",key:"executorEscalationModel",labelKey:"settings.projectModels.executorEscalationModel",labelFallback:"Executor Escalation Model",helpKey:"settings.projectModels.executorEscalationModelHelp",helpFallback:"Alternate model used once tool-failure retries are exhausted. No default — unset means no alternate model; configure escalation policy and an optional node target in Scheduling.",keywords:["tool failure","alternate model","retry model","provider","executor"]},{sectionId:"project-models",key:"tokenCap",labelKey:"settings.projectModels.tokenCap",labelFallback:"Token Cap",helpKey:"settings.projectModels.automaticallyCompactContextWhenApproachingThisTokenCount",helpFallback:"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).",keywords:["context window","limit","budget"]},{sectionId:"project-models",key:"chatNewSessionMode",labelKey:"settings.projectModels.chatNewSessionMode",labelFallback:"New Chat behavior",helpKey:"settings.projectModels.chatNewSessionModeHelp",helpFallback:"Prompt mode opens New Chat with this default preselected. Always-default mode skips the dialog when the configured default is complete.",keywords:["direct chat","skip dialog"]},{sectionId:"project-models",key:"autoSelectModelPreset",labelKey:"settings.projectModels.autoSelectPresetBasedOnTaskSize",labelFallback:" Auto-select preset based on task size ",helpKey:"settings.projectModels.autoSelectModelPresetHint",helpFallback:"Default: disabled.",keywords:["small","medium","large","S M L"]},{sectionId:"project-models",key:"taskDefinitionInInputLanguage",labelKey:"settings.projectModels.taskDefinitionInInputLanguage",labelFallback:"Write task definitions in the operator's input language",helpKey:"settings.projectModels.taskDefinitionInInputLanguageHelp",helpFallback:"When enabled, generated task-definition prose uses supported detectable input languages (Spanish, French, Korean, or Chinese as zh-CN). Headings, markers, and code stay English. Unsupported or undetectable input stays English. Default: disabled.",keywords:["task definition","prompt language","localized prose","Spanish","French","Korean","Chinese"]},{sectionId:"project-models",key:"autoSummarizeTitles",labelKey:"settings.projectModels.autoSummarizeLongDescriptionsAsTitles",labelFallback:" Auto-summarize long descriptions as titles ",helpKey:"settings.projectModels.whenEnabledTasksCreatedWithoutATitleBut",helpFallback:" 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. "},{sectionId:"project-models",key:"useAiMergeCommitSummary",labelKey:"settings.projectModels.aIMergeCommitSummaries",labelFallback:" AI merge commit summaries ",helpKey:"settings.projectModels.whenEnabledMergeCommitMessagesIncludeAnAI",helpFallback:" 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. "},{sectionId:"project-models",key:"prTitlePromptInstructions",labelKey:"settings.projectModels.prTitlePromptInstructions",labelFallback:"PR title prompt guidance",helpKey:"settings.projectModels.prTitlePromptInstructionsHelp",helpFallback:"Guides the AI-generated Create PR title. Leave blank to use the default PR metadata prompt. No default — unset.",keywords:["pull request","conventional commit"]},{sectionId:"project-models",key:"prDescriptionPromptInstructions",labelKey:"settings.projectModels.prDescriptionPromptInstructions",labelFallback:"PR description prompt guidance",helpKey:"settings.projectModels.prDescriptionPromptInstructionsHelp",helpFallback:"Guides the AI-generated Create PR summary, changes, and testing sections. Leave blank to use the default PR metadata prompt. No default — unset.",keywords:["pull request","body"]}],Lh=[{sectionId:"remote",key:"remoteTailscaleAcceptRoutes",labelKey:"settings.remote.acceptRoutes",labelFallback:" Accept routes ",helpKey:"settings.remote.acceptRoutesHint",helpFallback:"Default: disabled.",keywords:["tailscale","subnet","tailnet","funnel"]},{sectionId:"remote",key:"remoteShortLivedEnabled",labelKey:"settings.remote.enableShortLivedTokens",labelFallback:" Enable short-lived tokens ",helpKey:"settings.remote.shortLivedEnabledHint",helpFallback:"Default: disabled.",keywords:["expiring token","temporary access","auth link"]},{sectionId:"remote",key:"remoteShortLivedTtlMs",labelKey:"settings.remote.shortLivedTTLMs",labelFallback:"Short-lived TTL (ms)",helpKey:"settings.remote.shortLivedTtlMsHint",helpFallback:"Default: 900000 (15 minutes).",keywords:["expiry","lifetime","time to live","token duration"]},{sectionId:"remote",key:"remoteRememberLastRunning",labelKey:"settings.remote.rememberLastRunningState",labelFallback:" Remember last running state ",helpKey:"settings.remote.automaticallyRestoreTunnelOnStartupIfItWas",helpFallback:"Automatically restore tunnel on startup if it was running when last stopped. Default: disabled.",keywords:["cloudflared","autostart","reconnect","persist tunnel"]},{sectionId:"remote",key:"remoteCloudflareTunnelName",labelKey:"settings.remote.tunnelName",labelFallback:"Tunnel name",keywords:["cloudflare","named tunnel","cloudflared"]},{sectionId:"remote",key:"remoteCloudflareTunnelToken",labelKey:"settings.remote.tunnelToken",labelFallback:"Tunnel token",keywords:["cloudflare","named tunnel","credential","secret"]},{sectionId:"remote",key:"remoteCloudflareIngressUrl",labelKey:"settings.remote.ingressURL",labelFallback:"Ingress URL",keywords:["cloudflare","named tunnel","hostname","domain"]}],Oh=[{sectionId:"research-global",key:"researchGlobalWebSearchProvider",labelKey:"settings.researchGlobal.searchProvider",labelFallback:"Search Provider",keywords:["SearXNG","Brave","Google Custom Search","Tavily","external search providers","built-in"]},{sectionId:"research-global",key:"researchGlobalSearxngUrl",labelKey:"settings.researchGlobal.searXNGURL",labelFallback:"SearXNG URL",helpKey:"settings.researchGlobal.searXNGURLHint",helpFallback:"No default — unset.",keywords:["endpoint","instance","self-hosted"]},{sectionId:"research-global",key:"researchGlobalGoogleSearchCx",labelKey:"settings.researchGlobal.googleSearchCX",labelFallback:"Google Search CX",helpKey:"settings.researchGlobal.googleSearchCXHint",helpFallback:"No default — unset.",keywords:["custom search engine id","programmable search"]}],Kh=[{sectionId:"research-project",key:"researchSettings.enabled",labelKey:"settings.researchProject.enableResearchInThisProject",labelFallback:" Enable research in this project ",helpKey:"settings.researchProject.enableResearchInThisProjectHint",helpFallback:"Default: enabled.",keywords:["research","web search","citations","sources","turn off research"]}],Bh=[{sectionId:"scheduled-evals",key:"evalSettings.enabled",labelKey:"settings.scheduledEvals.enableScheduledEvalRunsForThisProject",labelFallback:" Enable scheduled eval runs for this project ",helpKey:"settings.scheduledEvals.enabledHint",helpFallback:"Default: disabled.",keywords:["evaluation","benchmark","quality"]},{sectionId:"scheduled-evals",key:"evalSettings.intervalMs",labelKey:"settings.scheduledEvals.intervalMs",labelFallback:"Interval (ms)",helpKey:"settings.scheduledEvals.intervalMsHint",helpFallback:"Default: 86400000 (24 hours).",keywords:["frequency","how often","schedule"]},{sectionId:"scheduled-evals",key:"evalSettings.evaluatorProvider",labelKey:"settings.scheduledEvals.evaluatorProvider",labelFallback:"Evaluator Provider",helpKey:"settings.scheduledEvals.evaluatorProviderHint",helpFallback:"No default — unset (inherits the project validator lane provider)."},{sectionId:"scheduled-evals",key:"evalSettings.evaluatorModelId",labelKey:"settings.scheduledEvals.evaluatorModel",labelFallback:"Evaluator Model",helpKey:"settings.scheduledEvals.leaveProviderAndModelBlankToInheritThe",helpFallback:" Leave provider and model blank to inherit the project validator lane model settings. No default — unset. "},{sectionId:"scheduled-evals",key:"evalSettings.followUpPolicy",labelKey:"settings.scheduledEvals.followUpPolicy",labelFallback:"Follow-up Policy",helpKey:"settings.scheduledEvals.followUpPolicyHint",helpFallback:"Default: suggest only.",keywords:["auto-create tasks","suggestions"]},{sectionId:"scheduled-evals",key:"evalSettings.retentionDays",labelKey:"settings.scheduledEvals.retentionDays",labelFallback:"Retention (days)",helpKey:"settings.scheduledEvals.retentionDaysHint",helpFallback:"Default: 30.",keywords:["prune","cleanup","history"]}],Gh=[{sectionId:"scheduling",key:"maxConcurrent",labelKey:"settings.scheduling.maxConcurrentTasks",labelFallback:"Max Concurrent Tasks",helpKey:"settings.scheduling.maxConcurrentTasksHint",helpFallback:"Default: 2.",keywords:["parallelism","capacity","how many tasks at once","agents","cap"]},{sectionId:"scheduling",key:"maxConcurrentVerifications",labelKey:"settings.scheduling.maxConcurrentVerifications",labelFallback:"Max Concurrent Verifications",helpKey:"settings.scheduling.maxConcurrentVerificationsHint",helpFallback:"Caps stacked typecheck/build verification across tasks. Default: 1. Range: 1–8.",keywords:["parallelism","tests","cpu","load"]},{sectionId:"scheduling",key:"executorToolFailureRetryCount",labelKey:"settings.scheduling.executorToolFailureRetryCount",labelFallback:"Executor tool-failure retries",helpKey:"settings.scheduling.executorToolFailureRetryCountHelp",helpFallback:"Same-model retries after consecutive tool-call failures. Set 0 to disable. Default: 2.",keywords:["executor","tool error","auto retry","same model","failure"]},{sectionId:"scheduling",key:"executorToolFailureRetryBackoffMs",labelKey:"settings.scheduling.executorToolFailureRetryBackoffMs",labelFallback:"Tool-failure retry backoff (ms)",helpKey:"settings.scheduling.executorToolFailureRetryBackoffMsHelp",helpFallback:"Unref'd wait before retrying. Default: 2000.",keywords:["executor","delay","wait","auto retry","tool error"]},{sectionId:"scheduling",key:"executorToolFailureThreshold",labelKey:"settings.scheduling.executorToolFailureThreshold",labelFallback:"Consecutive tool failures",helpKey:"settings.scheduling.executorToolFailureThresholdHelp",helpFallback:"Terminal tool errors required before retrying. Default: 1.",keywords:["executor","tool error","threshold","auto retry"]},{sectionId:"scheduling",key:"executorModelEscalationEnabled",labelKey:"settings.scheduling.executorModelEscalationEnabled",labelFallback:"Escalate after tool-failure retries",helpKey:"settings.scheduling.executorModelEscalationEnabledHelp",helpFallback:"After same-model retries are exhausted, try one configured alternate model or node. Disabled by default.",keywords:["executor","model","node","escalation","tool error"]},{sectionId:"scheduling",key:"executorEscalationNodeId",labelKey:"settings.scheduling.executorEscalationNodeId",labelFallback:"Escalation node ID",helpKey:"settings.scheduling.executorEscalationNodeIdHelp",helpFallback:"Optional configured node; a node target re-enters scheduler routing.",keywords:["executor","node","routing","escalation"]},{sectionId:"scheduling",key:"pollIntervalMs",labelKey:"settings.scheduling.pollIntervalMs",labelFallback:"Poll Interval (ms)",helpKey:"settings.scheduling.pollIntervalMsHint",helpFallback:"Default: 15000 (15 seconds).",keywords:["tick","engine loop","frequency","refresh"]},{sectionId:"scheduling",key:"heartbeatScopeDiscipline",labelKey:"settings.scheduling.heartbeatScopeDiscipline",labelFallback:"Heartbeat Scope Discipline",helpKey:"settings.scheduling.strictCoordinationFocusedHigherPerTickTokensLite",helpFallback:"Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.",keywords:["agent prompt","token cost"]},{sectionId:"scheduling",key:"engineerBacklogAutoClaim",labelKey:"settings.scheduling.letEngineerAgentsAutoClaimBacklogTasks",labelFallback:" Let engineer agents auto-claim backlog tasks ",helpKey:"settings.scheduling.backlogNoTaskAutoClaimIsExecutorOnly",helpFallback:"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.",keywords:["pick up work","unassigned","todo"]},{sectionId:"scheduling",key:"taskStuckTimeoutMs",labelKey:"settings.scheduling.stuckTaskTimeoutMinutes",labelFallback:"Stuck Task Timeout (minutes)",helpKey:"settings.scheduling.timeoutInMinutesForDetectingStuckTasksWhen",helpFallback:"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).",keywords:["hung","frozen","watchdog","kill"]},{sectionId:"scheduling",key:"buildTimeoutMs",labelKey:"settings.scheduling.buildTimeoutMinutes",labelFallback:"Build/Verification Timeout (minutes)",helpKey:"settings.scheduling.maximumTimeInMinutesForBuildVerificationCommands",helpFallback:"Maximum time in minutes for build/verification commands before they are killed. Raise for large monorepo or Docker builds. Default: 5.",keywords:["test timeout","compile","slow build"]},{sectionId:"scheduling",key:"staleHighFanoutBlockerAgeThresholdMs",labelKey:"settings.scheduling.staleHighFanOutEscalationHours",labelFallback:"Stale High Fan-out Escalation (hours)",helpKey:"settings.scheduling.escalateHighFanOutBlockersOnlyAfterThey",helpFallback:"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.",keywords:["dependencies","alert","notify"]},{sectionId:"scheduling",key:"preserveProgressOnStuckRequeue",labelKey:"settings.scheduling.preserveStepProgressOnStuckTaskRequeue",labelFallback:" Preserve step progress on stuck-task requeue ",helpKey:"settings.scheduling.whenTheStuckDetectorKillsAndReQueues",helpFallback:"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.",keywords:["resume","restart","retry"]},{sectionId:"scheduling",key:"specStalenessEnabled",labelKey:"settings.scheduling.enablePlanStalenessEnforcement",labelFallback:" Enable plan staleness enforcement ",helpKey:"settings.scheduling.whenEnabledTasksWithStalePlansPROMPTMd",helpFallback:"When enabled, tasks with stale plans (PROMPT.md older than the threshold) are automatically sent back to planning for replanning. Default: disabled.",keywords:["spec","replan","outdated"]},{sectionId:"scheduling",key:"specStalenessMaxAgeMs",labelKey:"settings.scheduling.staleSpecThresholdHours",labelFallback:"Stale Spec Threshold (hours)",helpKey:"settings.scheduling.maximumAgeInHoursBeforeAPlanIs",helpFallback:"Maximum age in hours before a plan is considered stale. Default: 6 hours.",keywords:["PROMPT.md","replan","age"]},{sectionId:"scheduling",key:"autoArchiveDoneTasksEnabled",labelKey:"settings.scheduling.enableAutomaticTaskArchiving",labelFallback:" Enable automatic task archiving ",helpKey:"settings.scheduling.completedTasksOlderThanTheThresholdAreMoved",helpFallback:"Completed tasks older than the threshold are moved out of the active task database. Default: enabled.",keywords:["done column","cleanup","prune","board clutter"]},{sectionId:"scheduling",key:"autoArchiveDoneAfterMs",labelKey:"settings.scheduling.archiveCompletedTasksAfterDays",labelFallback:"Archive Completed Tasks After (days)",helpKey:"settings.scheduling.numberOfDaysATaskCanStayIn",helpFallback:"Number of days a task can stay in Done before it is archived. Default: 2 days (48 hours).",keywords:["retention","cleanup","age"]},{sectionId:"scheduling",key:"archiveAgentLogMode",labelKey:"settings.scheduling.archiveAgentLog",labelFallback:"Archive Agent Log",helpKey:"settings.scheduling.compactModeKeepsArchiveSizeLowWhilePreserving",helpFallback:"Compact mode keeps archive size low while preserving recent agent activity for context. Default: compact.",keywords:["history","transcript","disk space","retention"]},{sectionId:"scheduling",key:"autoArchiveDuplicateTasksEnabled",labelKey:"settings.scheduling.autoArchiveDuplicateTasks",labelFallback:" Automatically archive duplicate tasks ",helpKey:"settings.scheduling.autoArchiveDuplicateTasksHelp",helpFallback:"Automatically archive tasks detected as same-agent duplicates on creation (off by default). When disabled, duplicates are flagged in place with the yellow Duplicate chip and Keep/Archive actions instead of being archived automatically.",keywords:["near duplicate","dedupe","repeat"]},{sectionId:"scheduling",key:"triageDuplicateResolution",labelKey:"settings.scheduling.triageDuplicateResolution",labelFallback:"Triage duplicate resolution",helpKey:"settings.scheduling.triageDuplicateResolutionHelp",helpFallback:"Block triage-detected duplicates for a Keep/Delete decision with a link to the duplicate (default), keep automatically, or delete automatically.",keywords:["duplicate","triage","keep","delete","decision"]},{sectionId:"scheduling",key:"maxStuckKills",labelKey:"settings.scheduling.maxStuckRetries",labelFallback:"Max Stuck Retries",helpKey:"settings.scheduling.maximumStuckDetectorRetriesBeforeATaskIs",helpFallback:"Maximum stuck-detector retries before a task is marked failed. Default: 6.",keywords:["give up","attempts","hung"]},{sectionId:"scheduling",key:"groupOverlappingFiles",labelKey:"settings.scheduling.serializeTasksWithOverlappingFiles",labelFallback:" Serialize tasks with overlapping files ",helpKey:"settings.scheduling.whenEnabledTasksThatModifyTheSameFiles",helpFallback:"When enabled, tasks that modify the same files are queued serially to avoid merge conflicts. Default: enabled.",keywords:["file scope","collision","queue","lease"]},{sectionId:"scheduling",key:"ignoreHiddenOverlapPaths",labelKey:"settings.scheduling.ignoreHiddenDotPathsInOverlapChecks",labelFallback:" Ignore hidden dot paths in overlap checks ",helpKey:"settings.scheduling.ignoreHiddenDotPathsHelp",helpFallback:"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.",keywords:["dotfiles","collision","file scope"]}],Hh=[{sectionId:"source-control-global",key:"reportRoadmapDedupeEnabled",labelKey:"settings.globalGeneral.reportRoadmapDedupeEnabled",labelFallback:"Global public-roadmap deduplication",helpKey:"settings.globalGeneral.reportRoadmapDedupeEnabledHelp",helpFallback:"Fallback for projects that do not set a public-roadmap deduplication preference. No default — unset (projects default to enabled).",keywords:["roadmap","dedup","report","fallback"]},{sectionId:"source-control-global",key:"reportRoadmapLabel",labelKey:"settings.globalGeneral.reportRoadmapLabel",labelFallback:"Global public roadmap label",helpKey:"settings.globalGeneral.reportRoadmapLabelHelp",helpFallback:"Fallback label for open public-roadmap issues when a project does not set one. No default — unset (projects default to roadmap).",keywords:["roadmap","label","report","fallback"]},{sectionId:"source-control-global",key:"reportRoadmapRepo",labelKey:"settings.globalGeneral.reportRoadmapRepo",labelFallback:"Global public roadmap repository (optional)",helpKey:"settings.globalGeneral.reportRoadmapRepoHelp",helpFallback:"Fallback GitHub owner/repository for public-roadmap issues. When unset, uses the tracking repository. No default — unset.",keywords:["roadmap","repository","repo","tracking","fallback"]},{sectionId:"source-control-global",key:"gitlabInstanceUrl",labelKey:"settings.globalGeneral.gitLabInstanceUrl",labelFallback:"Global GitLab instance URL",helpKey:"settings.globalGeneral.gitLabInstanceUrlHint",helpFallback:"Blank defaults to GitLab.com. Projects inherit this self-managed GitLab URL unless they set their own project value. No default — unset.",keywords:["self managed","self-hosted","fallback","inherit"]},{sectionId:"source-control-global",key:"gitlabApiBaseUrl",labelKey:"settings.globalGeneral.gitLabApiBaseUrlOptional",labelFallback:"Global GitLab API base URL (optional / advanced)",helpKey:"settings.globalGeneral.gitLabApiBaseUrlHint",helpFallback:"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.",keywords:["api v4","gateway","fallback","self managed"]},{sectionId:"source-control-global",key:"gitlabAuthTokenType",labelKey:"settings.globalGeneral.gitLabTokenType",labelFallback:"Global GitLab token type",helpKey:"settings.globalGeneral.gitLabTokenTypeHint",helpFallback:"No default — unset (the selector falls back to personal access token until you choose otherwise).",keywords:["personal access token","project access token","group access token","pat"]},{sectionId:"source-control-global",key:"gitlabAuthToken",labelKey:"settings.globalGeneral.gitLabAccessToken",labelFallback:"Global GitLab access token",helpKey:"settings.globalGeneral.gitLabAuthTokenHint",helpFallback:"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.",keywords:["glpat","private-token","credentials","secret","fallback"]}],_h=[{sectionId:"source-control",key:"githubLinkImportedIssuesToTracking",labelKey:"settings.general.alwaysLinkImportedGitHubIssuesToTracking",labelFallback:" Always link imported GitHub issues to GitHub tracking ",helpKey:"settings.general.whenEnabledImportedGitHubIssuesUseTheirSource",helpFallback:"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.",keywords:["adopt issue","import"]},{sectionId:"source-control",key:"githubTrackingDedupEnabled",labelKey:"settings.general.searchTheTrackingRepoForLikelyDuplicatesBefore",labelFallback:" Search the tracking repo for likely duplicates before opening a new issue ",helpKey:"settings.general.whenEnabledFusionChecksOpenAndClosedIssues",helpFallback:" 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. ",keywords:["dedupe","deduplication"]},{sectionId:"source-control",key:"githubAuthMode",labelKey:"settings.merge.gitHubAuthMode",labelFallback:"GitHub auth mode",keywords:["gh cli","personal access token","pat","credentials","login"]},{sectionId:"source-control",key:"githubAuthToken",labelKey:"settings.merge.gitHubPersonalAccessToken",labelFallback:"GitHub personal access token",helpKey:"settings.merge.githubAuthTokenHint",helpFallback:"No default — unset.",keywords:["pat","credentials","secret","ghp"]},{sectionId:"source-control",key:"gitlabInstanceUrl",labelKey:"settings.general.gitLabInstanceUrl",labelFallback:"GitLab instance URL",helpKey:"settings.general.gitLabInstanceUrlHint",helpFallback:"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.",keywords:["self managed","self-hosted","on premise"]},{sectionId:"source-control",key:"gitlabApiBaseUrl",labelKey:"settings.general.gitLabApiBaseUrlOptional",labelFallback:"GitLab API base URL (optional / advanced)",helpKey:"settings.general.gitLabApiBaseUrlHint",helpFallback:"Blank derives <instance>/api/v4. Override only when a self-managed GitLab API is served from a different absolute http:// or https:// URL.",keywords:["api v4","gateway","self managed"]},{sectionId:"source-control",key:"gitlabAuthTokenType",labelKey:"settings.merge.gitLabTokenType",labelFallback:"GitLab token type",keywords:["personal access token","project access token","group access token","pat"]},{sectionId:"source-control",key:"gitlabAuthToken",labelKey:"settings.merge.gitLabAccessToken",labelFallback:"GitLab access token",helpKey:"settings.merge.gitLabAuthTokenHint",helpFallback:"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.",keywords:["glpat","private-token","credentials","secret","read_api"]}],Uh=[{sectionId:"worktrees",key:"worktreeLimitEnabled",labelKey:"settings.worktrees.worktreeLimitEnabled",labelFallback:"Limit concurrent worktrees",helpKey:"settings.worktrees.worktreeLimitEnabledHelp",helpFallback:"When on, Max Worktrees caps how many tasks may hold a worktree at once. When off, Max Concurrent Tasks is the only limit. Tasks always run in their own git worktree either way — this does not change where work executes. Default: on.",keywords:["capacity","parallelism","agents only","max worktrees","concurrency","limit"]},{sectionId:"worktrees",key:"maxWorktrees",labelKey:"settings.worktrees.maxWorktrees",labelFallback:"Max Worktrees",helpKey:"settings.worktrees.limitsTotalGitWorktreesIncludingInReviewTasks",helpFallback:"Limits total git worktrees including in-review tasks. Default: 4.",keywords:["concurrency","parallel tasks","capacity","limit"]},{sectionId:"worktrees",key:"worktreeInitCommand",labelKey:"settings.worktrees.worktreeInitCommand",labelFallback:"Worktree Init Command",helpKey:"settings.worktrees.shellCommandToRunInEachNewWorktree",helpFallback:"Shell command to run in each new worktree after creation. No default — unset.",keywords:["setup script","bootstrap","install dependencies","post-create"]},{sectionId:"worktrees",key:"recycleWorktrees",labelKey:"settings.worktrees.recycleWorktrees",labelFallback:" Recycle worktrees ",helpKey:"settings.worktrees.offByDefaultOptInWhenEnabledCompleted",helpFallback:"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",keywords:["reuse","warm pool"]},{sectionId:"worktrees",key:"showWorktreeGrouping",labelKey:"settings.worktrees.showWorktreeGrouping",labelFallback:" Show worktree grouping on the board ",helpKey:"settings.worktrees.showWorktreeGroupingHelp",helpFallback:"Off by default. When enabled, WIP and processing columns always group tasks by worktree and show worktree names, including workflow-mode processing columns.",keywords:["group by","swimlane"]},{sectionId:"worktrees",key:"worktreeNaming",labelKey:"settings.worktrees.worktreeNamingStyle",labelFallback:"Worktree Naming Style",helpKey:"settings.worktrees.howToNameFreshWorktreeDirectories",helpFallback:"How to name fresh worktree directories. Only applies when recycling is off. Default: random.",keywords:["folder name","directory name","branch naming"]},{sectionId:"worktrees",key:"worktreeRebaseBeforeMerge",labelKey:"settings.worktrees.rebaseFromRemoteBeforeMerge",labelFallback:" Rebase from remote before merge ",helpKey:"settings.worktrees.whenEnabledTheMergerFetchesFromTheConfigured",helpFallback:"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.",keywords:["pull","up to date","prerebase"]},{sectionId:"worktrees",key:"worktreeRebaseLocalBase",labelKey:"settings.worktrees.alsoRebaseOntoLocalDefaultBranchHEAD",labelFallback:" Also rebase onto local default-branch HEAD ",helpKey:"settings.worktrees.inAdditionToTheRemoteRebaseAboveAlso",helpFallback:" 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. ",keywords:["main","unpushed","prerebase"]}],Wh=[{sectionId:"voice-input",key:"voiceInput.enabled",labelKey:"settings.voiceInput.enable",labelFallback:"Enable voice input",helpKey:"settings.voiceInput.enableHelp",helpFallback:"Default: off. Voice dictation uses the operator-managed Parakeet v3 model.",keywords:["voice","dictation","microphone","speech to text","parakeet","transcription"]}],$h=[...jh,...wh,...Ch,...Sh,...Nh,...Ph,...Ih,...Th,...Ah,...Mh,...Rh,...Eh,...Dh,...Fh,...Lh,...Oh,...Kh,...Bh,...Gh,...Hh,..._h,...Uh,...Wh];function Is(t){return t.trim().toLocaleLowerCase()}const zh=0,qh=1,Vh=2,Yh=3,Qh=4,Jh=5;function Xh(t,s,a,n){const o=Is(a);return o===s?zh:o.startsWith(s)?qh:o.includes(s)?Vh:t.keywords?.some(d=>Is(d).includes(s))?Yh:Is(t.key).includes(s)?Qh:n&&Is(n).includes(s)?Jh:null}function Zh(t,s,a){const n=Is(s);if(!n)return[];const o=[];for(const d of t){const u=a(d.labelKey,d.labelFallback),c=d.helpKey&&d.helpFallback?a(d.helpKey,d.helpFallback):void 0,l=Xh(d,n,u,c);l!==null&&o.push({...d,label:u,help:c,score:l})}return o.sort((d,u)=>d.score-u.score||d.label.localeCompare(u.label))}function em(t){return new Set(t.map(s=>s.sectionId))}const tm=new Set(["node-sync","global-mcp","cli-agents","research-global","remote","experimental","hermes-runtime","openclaw-runtime","paperclip-runtime","scheduled-evals","node-routing","agent-permissions","memory","backups","research-project","secrets","mcp","prompts","plugins"]),sm=[{id:"__preferences_header",label:"Preferences",labelKey:"settings.nav.preferencesHeader",scope:void 0,isGroupHeader:!0},{id:"appearance",label:"Appearance",labelKey:"settings.nav.appearance",scope:"global",searchableText:["theme","color","sidebar","dock","task popup","task popups","board list popups","popup view attachment","open tasks as popups","quick chat"]},{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:"notifications",label:"Notifications",labelKey:"settings.nav.notifications",scope:"global",searchableText:["ntfy","webhook","events","failure notifications","sticky","toast"]},{id:"global-general",label:"General · Global",labelKey:"settings.nav.globalGeneral",scope:"global",searchableText:["global defaults","modal outside dismiss","agent logs","persist tool output","thinking logs"]},{id:"cli-binary",label:"CLI Binary",labelKey:"settings.nav.cliBinary",scope:"global",searchableText:["fn binary","cli","install","version","path","upgrade","homebrew","binary check"]},{id:"__project_header",label:"Project",labelKey:"settings.nav.projectHeader",scope:void 0,isGroupHeader:!0},{id:"general",label:"General · Project",labelKey:"settings.nav.projectGeneral",scope:"project",searchableText:["project general","Completion Documentation Automation","Quick Chat launcher","ephemeral task-worker agents","chat rooms","auto-cleanup old chats","translate","translation","auto translate","auto-translate","autotranslate","auto translate issues","translate issues","translate imported issues","githubImportAutoTranslate","importTranslateTargetLocale","target language","translation target language","translation language","language","foreign language issues","import language","localize","localization","report","report bug","send feedback","share idea","get help"],searchableKeys:["settings.general.autoTranslateImportedIssues","settings.general.autoTranslateImportedIssuesHelp","settings.general.translationTargetLanguage","settings.general.translationTargetLanguageHelp","settings.general.followDashboardLanguage"]},{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:"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:"config-versions",label:"Configuration Versions",labelKey:"settings.nav.configVersions",scope:"project",searchableText:["configuration versions","revision history","roll back settings","restore configuration","config rollback"]},{id:"__ai_header",label:"AI & Models",labelKey:"settings.nav.aiHeader",scope:void 0,isGroupHeader:!0},{id:"authentication",label:"Authentication",labelKey:"settings.nav.authentication",scope:void 0,searchableText:["login","OAuth","API key","custom providers","Anthropic","OpenAI","provider credentials"]},{id:"global-models",label:"Models · Global",labelKey:"settings.nav.globalModels",scope:"global",searchableText:["global models","model presets","favorite providers","model pricing overrides","LiteLLM pricing","token pricing","translate","translation model","import translation model","import auto-translation model"]},{id:"project-models",label:"Models · Project",labelKey:"settings.nav.projectModels",scope:"project",searchableText:["default provider","default model","workflow model lanes","executor escalation model","escalation model","alternate model","tool-failure retry model","Plan/Triage","Executor","Reviewer","summarization model","summarize","summarize titles","auto summarize","auto-summarize","auto summarize titles","auto-summarize titles","autoSummarizeTitles","task definition language","task definitions input language","taskDefinitionInInputLanguage","localized task prose","title summarization","title summarizer","AI title","AI merge commit summaries","merge commit summary","chat","new chat","new chat behavior","chat default","chat default model","chat default agent","chat model","chat agent","prompt for model","always use default","translate","translation","translation model","import translation model","import auto-translation model","auto-translate model"],searchableKeys:["settings.projectModels.chatHeading","settings.projectModels.chatDescription","settings.projectModels.chatNewSessionMode","settings.projectModels.chatNewSessionModePrompt","settings.projectModels.chatNewSessionModeAlwaysDefault","settings.projectModels.chatDefaultKind","settings.projectModels.chatDefaultModel","settings.projectModels.chatDefaultAgent","settings.projectModels.aITitleAndGitCommitMessageSummarization","settings.projectModels.executorEscalationModel","settings.projectModels.executorEscalationModelHelp","settings.projectModels.autoSummarizeLongDescriptionsAsTitles","settings.projectModels.whenEnabledTasksCreatedWithoutATitleBut","settings.projectModels.aIMergeCommitSummaries","settings.projectModels.whenEnabledMergeCommitMessagesIncludeAnAI"]},{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:"agent-permissions",label:"Agents & Permissions",labelKey:"settings.nav.agentPermissions",scope:"project",searchableText:["agent provisioning","approval","permissions","policy","agent creation"]},{id:"prompts",label:"Prompts",labelKey:"settings.nav.prompts",scope:"project",searchableText:["prompt instructions","PR title prompt","PR description prompt","custom prompts"]},{id:"memory",label:"Memory",labelKey:"settings.nav.memory",scope:"project",searchableText:["memory backend","Dreams","long-term memory","qmd","memory file","retrieval"]},{id:"research-global",label:"Research · Global",labelKey:"settings.nav.researchGlobal",scope:"global",searchableText:["research providers","external search providers","fetch limits","global research defaults","citations"]},{id:"research-project",label:"Research · Project",labelKey:"settings.nav.researchProject",scope:"project",searchableText:["project research","research runs","citations","search limits","fetch synthesis"]},{id:"voice-input",label:"Voice Input",labelKey:"settings.nav.voiceInput",scope:"project",searchableText:["voice","dictation","microphone","speech to text","parakeet","transcription"]},{id:"__automation_header",label:"Automation",labelKey:"settings.nav.automationHeader",scope:void 0,isGroupHeader:!0},{id:"scheduling",label:"Scheduling",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:"__integrations_header",label:"Integrations",labelKey:"settings.nav.integrationsHeader",scope:void 0,isGroupHeader:!0},{id:"source-control-global",label:"Source Control · Global",labelKey:"settings.nav.sourceControlGlobal",scope:"global",searchableText:["GitLab instance URL","global tracking repo","GitLab","GitHub","global GitLab token","GitLab fallback","source control","forge"]},{id:"source-control",label:"Source Control · Project",labelKey:"settings.nav.sourceControl",scope:"project",searchableText:["GitHub tracking","GitLab integration","GitHub auth mode","GitLab access token","GitHub personal access token","tracking repo","source control","forge","gh cli","issue tracking"]},{id:"global-mcp",label:"MCP Servers · Global",labelKey:"settings.nav.globalMcp",scope:"global",searchableText:["global MCP servers","shared MCP","user MCP","tool servers"]},{id:"mcp",label:"MCP Servers · Project",labelKey:"settings.nav.mcp",scope:"project",searchableText:["project MCP servers","workspace MCP","project tool servers","mcp config"]},{id:"plugins",label:"Plugins",labelKey:"settings.nav.plugins",scope:"project",searchableText:["Fusion plugins","Pi extensions","plugin manager","extension marketplace"]},{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:"secrets",label:"Secrets",labelKey:"settings.nav.secrets",scope:"project",searchableText:["secrets","secret storage","environment","credentials"]},{id:"__infrastructure_header",label:"Infrastructure",labelKey:"settings.nav.infrastructureHeader",scope:void 0,isGroupHeader:!0},{id:"node-sync",label:"Node Sync",labelKey:"settings.nav.nodeSync",scope:"global",searchableText:["sync","node","distributed","heartbeat","coordination"]},{id:"node-routing",label:"Node Routing",labelKey:"settings.nav.nodeRouting",scope:"project",searchableText:["node routing","routing rules","node selection","execution nodes"]},{id:"remote",label:"Remote Access",labelKey:"settings.nav.remote",scope:"global",searchableText:["cloudflared","tunnel","QR","persistent token","remote URL"]},{id:"backups-global",label:"Database Backups",labelKey:"settings.backups.databaseBackups",scope:"global",searchableText:["database backup","restore","shared cluster"]},{id:"backups",label:"Memory Backups",labelKey:"settings.backups.memoryBackups",scope:"project",searchableText:["memory backup","memory snapshot"]},{id:"__advanced_header",label:"Advanced",labelKey:"settings.nav.advancedHeader",scope:void 0,isGroupHeader:!0},{id:"experimental",label:"Experimental Features",labelKey:"settings.nav.experimental",scope:"global",searchableText:["feature flags","experiments","research view","evals view","sandbox","subtask breakdown"]}];let Dn;const ki=sm.map(t=>{if(t.isGroupHeader&&(Dn=t.label),!Dn)throw new Error(`Settings section ${t.id} appears before its group header`);return{...t,group:Dn,advanced:tm.has(t.id)}}),xi="fusion_github_star_count",ji=900*1e3,Yr="fusion:github-star-clicked";function pa(t){return t.startsWith("/")}function am({size:t=13}){return e.jsx("svg",{"data-testid":"discord-icon",width:t,height:t,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 nm(t){const s=new Map;for(const a of t){const n=`${a.owner}/${a.repo}`;s.has(n)||s.set(n,{value:n,label:n})}return[...s.values()].sort((a,n)=>a.value.localeCompare(n.value))}function lm(){const[t,s]=i.useState(()=>{try{return localStorage.getItem(Yr)==="true"}catch{return!1}}),a=i.useCallback(()=>{s(!0);try{localStorage.setItem(Yr,"true")}catch{}},[]);return[t,a]}function Qr(){try{const t=localStorage.getItem(xi);if(!t)return null;const s=JSON.parse(t);return Number.isFinite(s.count)&&Number.isFinite(s.fetchedAt)?s:null}catch{return null}}function rm(t){return t!==null&&Date.now()-t.fetchedAt<ji}function im(){const[t,s]=i.useState(()=>Qr()?.count??null),a=i.useRef(!1),n=i.useCallback(()=>{document.hidden||a.current||rm(Qr())||(a.current=!0,fetch("https://api.github.com/repos/Runfusion/Fusion",{cache:"no-store"}).then(async o=>{if(!o.ok)return null;const d=await o.json();return typeof d.stargazers_count=="number"&&Number.isFinite(d.stargazers_count)?d.stargazers_count:null}).then(o=>{if(o===null)return;const d={count:o,fetchedAt:Date.now()};try{localStorage.setItem(xi,JSON.stringify(d))}catch{}s(o)}).catch(()=>{}).finally(()=>{a.current=!1}))},[]);return i.useEffect(()=>{n();const o=()=>{document.hidden||n()};document.addEventListener("visibilitychange",o);const d=window.setInterval(n,ji);return()=>{document.removeEventListener("visibilitychange",o),window.clearInterval(d)}},[n]),t}const Jr="(max-width: 768px)",Fn=".fusion/memory/DREAMS.md",wi="fusion:settings:show-advanced",om=1600,Ln=8;function cm(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}const Ci="fusion:settings-nav-width",Si=248,Ni=200,Pi=420,Ii=new Map([["fusion-plugin-hermes-runtime","hermes-runtime"],["fusion-plugin-openclaw-runtime","openclaw-runtime"],["fusion-plugin-paperclip-runtime","paperclip-runtime"]]),Xr=new Set(Ii.values()),Zr=new Set(ki.filter(t=>t.advanced).map(t=>t.id));function dm(){try{return localStorage.getItem(wi)==="true"}catch{return!1}}function Ti(t){return Number.isFinite(t)?Math.min(Pi,Math.max(Ni,Math.round(t))):Si}function um(){try{const t=Number.parseFloat(localStorage.getItem(Ci)??"");return Ti(t)}catch{return Si}}function pm(t){return t.filter((s,a)=>{if(!s.isGroupHeader)return!0;for(const n of t.slice(a+1))return!n.isGroupHeader;return!1})}function Ai(t){return t.trim().toLocaleLowerCase()}function gm(t,s,a,n,o){return!s||t.isGroupHeader||o?.has(t.id)?!0:[a,...t.searchableText??[],...(t.searchableKeys??[]).map(d=>n(d))].map(Ai).some(d=>d.includes(s))}function hm(t,s,a,n,o){if(!s)return t;const d=new Set(t.filter(u=>!u.isGroupHeader&&gm(u,s,a(u),n,o)).map(u=>u.id));return t.filter((u,c)=>{if(!u.isGroupHeader)return d.has(u.id);for(const l of t.slice(c+1)){if(l.isGroupHeader)return!1;if(d.has(l.id))return!0}return!1})}function ei(t,s){return t.find(a=>!a.isGroupHeader)?.id??s}const mm=/ · (Global|Project)$/,bm=new Set(["authentication"]);function fm(t,s){return mm.test(s)?s:t.scope==="global"||bm.has(t.id)?`${s} · Global`:t.scope==="project"?`${s} · Project`:s}function ti(t){const s=Number(t?.maxAutoMergeRetries);return Number.isFinite(s)&&s>0?Math.floor(s):3}function ga(t,s){const a=Number(t);return Number.isFinite(a)&&a>=0?Math.floor(a):s}const si={authentication:ba,"source-control-global":or,"source-control":or},On=ki.map(t=>({id:t.id,label:t.label,labelKey:t.labelKey,scope:t.scope,...si[t.id]?{icon:si[t.id]}:{},...t.isGroupHeader?{isGroupHeader:!0}:{},...t.searchableText?{searchableText:[...t.searchableText]}:{},...t.searchableKeys?{searchableKeys:[...t.searchableKeys]}:{}})),ym={insights:"Insights",memoryView:"Memory Editor",skillsView:"Skills View",nodesView:"Nodes View",devServerView:"Dev Server",researchView:"Research View",evalsView:"Evals View",ideationView:"Ideation View",qualityPlugin:"Quality Plugin",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)"},vm=new Set(["chatRooms","goalsView","insights","memoryView","remoteAccess","roadmap","rightDock","skillsView","workflowColumns","workflowGraphExecutor","workflowInterpreterDualObserve"]),Mi=new Set(["leftSidebarNav"]),ja={devServer:"devServerView"};function el(t){return ja[t]??t}function $n(t,s){return t[s]===!0?!0:t[s]===!1?!1:Object.entries(ja).some(([a,n])=>n===s&&t[a]===!0)?!0:Mi.has(s)}function km(t,s){const a=el(s);return Mi.has(a)&&t[a]===void 0?!0:$n(t,a)}function xm(t){if(!t)return{};const s={};for(const[a,n]of Object.entries(t))s[el(a)]=n;for(const[a,n]of Object.entries(ja))s[n]!==void 0&&!(a in s)&&(s[a]=null);return s}function jm(t){const s=new Set,a=[];for(const n of t??[]){const o=n.trim();!o||s.has(o)||(s.add(o),a.push(o))}return a}const Kn="appearance";function wm({projectId:t,addToast:s}){const{t:a}=le("app"),{confirm:n}=Yn(),[o,d]=i.useState([]),[u,c]=i.useState({}),[l,h]=i.useState({}),[p,m]=i.useState("");i.useEffect(()=>{let N=!1;return(async()=>{try{const[S,L]=await Promise.all([fetch("/api/cli-agents"),fetch("/api/cli-agents/settings")]),F=S.ok?await S.json():{adapters:[]},K=L.ok?await L.json():{cliAgents:{}};if(N)return;const R=F.adapters??[];d(R),c(K.cliAgents??{}),R.length>0&&m(T=>T||R[0].id)}catch{}})(),()=>{N=!0}},[]),i.useEffect(()=>{if(!p)return;let N=!1;return fetch(`/api/cli-agents/${p}/autonomy`).then(S=>S.ok?S.json():null).then(S=>{N||!S||h(L=>({...L,[p]:!!S.approved}))}).catch(()=>{}),()=>{N=!0}},[p]);const x=u[p]??{},w=i.useCallback(async(N,S)=>{try{const L=await fetch("/api/cli-agents/settings",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({adapterId:N,config:S})});if(!L.ok)throw new Error(`HTTP ${L.status}`);const F=await L.json();c(F.cliAgents??{})}catch(L){s(De(L)||a("settings.cliAgents.saveFailed"),"error")}},[s,a]),f=i.useCallback(N=>{if(!p)return;const S={...x,...N};c(L=>({...L,[p]:S})),w(p,S)},[p,x,w]),E=i.useCallback(async N=>{if(p){if(N==="elevated"){if(!await n({title:a("settings.cliAgents.elevatedConfirmTitle"),message:a("settings.cliAgents.elevatedConfirmBody"),confirmLabel:a("settings.cliAgents.elevatedConfirmAction"),danger:!0}))return;try{const L=await fetch(`/api/cli-agents/${p}/approve-autonomy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:!0})});if(!L.ok)throw new Error(`HTTP ${L.status}`);h(F=>({...F,[p]:!0}))}catch(L){s(De(L)||a("settings.cliAgents.approveFailed"),"error");return}}f({autonomyMode:N})}},[p,n,a,s,f]);return e.jsxs("div",{"data-testid":"cli-agents-settings",children:[e.jsx("h4",{className:"settings-section-heading",children:a("settings.cliAgents.heading")}),e.jsx("p",{className:"settings-section-description",children:a("settings.cliAgents.description")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAdapter",children:a("settings.cliAgents.adapterLabel")}),e.jsx("select",{id:"cliAgentAdapter",value:p,onChange:N=>m(N.target.value),children:o.map(N=>e.jsxs("option",{value:N.id,children:[N.name," (",a(`settings.cliAgents.tier.${N.tier}`),")"]},N.id))})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentCommand",children:a("settings.cliAgents.commandLabel")}),e.jsx("input",{id:"cliAgentCommand",type:"text",placeholder:o.find(N=>N.id===p)?.defaultCommand??"",value:x.commandOverride??"",onChange:N=>f({commandOverride:N.target.value||void 0})}),e.jsx("p",{className:"settings-field-help",children:a("settings.cliAgents.commandHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentExtraArgs",children:a("settings.cliAgents.extraArgsLabel")}),e.jsx("input",{id:"cliAgentExtraArgs",type:"text",value:(x.extraArgs??[]).join(" "),onChange:N=>f({extraArgs:N.target.value.split(/\s+/).filter(S=>S.length>0)})}),e.jsx("p",{className:"settings-field-help",children:a("settings.cliAgents.extraArgsHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentEnv",children:a("settings.cliAgents.envLabel")}),e.jsx("input",{id:"cliAgentEnv",type:"text",value:(x.envAdditions??[]).join(", "),onChange:N=>f({envAdditions:N.target.value.split(",").map(S=>S.trim()).filter(S=>S.length>0)})}),e.jsx("p",{className:"settings-field-help",children:a("settings.cliAgents.envHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAutonomy",children:a("settings.cliAgents.autonomyLabel")}),e.jsxs("select",{id:"cliAgentAutonomy",value:x.autonomyMode??"default",onChange:N=>void E(N.target.value),children:[e.jsx("option",{value:"default",children:a("settings.cliAgents.autonomy.default")}),e.jsx("option",{value:"elevated",children:a("settings.cliAgents.autonomy.elevated")})]}),e.jsx("p",{className:"settings-field-help",children:l[p]?a("settings.cliAgents.approvedNote"):a("settings.cliAgents.autonomyHelp")})]})]})]})}function Cm({onClose:t,addToast:s,projectId:a,initialSection:n,themeMode:o="system",colorTheme:d="shadcn-ember",onThemeModeChange:u,onColorThemeChange:c,dashboardFontScalePct:l=100,shadcnCustomColors:h={},resolvedThemeMode:p,onDashboardFontScaleChange:m,onShadcnCustomColorsChange:x,onQuickChatButtonModeChange:w,onMobileNavPrimaryItemsChange:f,onReopenOnboarding:E,onOpenApprovals:N,onOpenWorkflowSettings:S,presentation:L="modal"}){const{isEmbedded:F,scrollLockEnabled:K,escapeEnabled:R,overlayDismissEnabled:T}=au(L),{t:b}=le("app"),{confirm:V}=Yn(),X=nu();lu(K);const{keyboardOverlap:k,viewportHeight:I,viewportOffsetTop:B,keyboardOpen:v}=ru({enabled:X==="mobile"}),M=v?{"--keyboard-overlap":`${k}px`,"--vv-offset-top":`${B}px`,...I!==null?{"--vv-height":`${I}px`}:{}}:{},se=i.useRef(null),ne=i.useRef(null),pe=i.useRef(0),[j,W]=i.useState(!1),ce=i.useCallback(()=>{pe.current+=1,W(!0)},[]),Ie=i.useCallback(r=>{r&&(ne.current=r)},[]),Oe=iu(),[H,Z]=i.useState({maxConcurrent:2,maxConcurrentVerifications:1,maxWorktrees:4,worktreeLimitEnabled:!0,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,ignoreHiddenOverlapPaths:!0,overlapIgnorePaths:[],allowAbsoluteFileBrowserPaths:!1,autoMerge:!0,planApprovalMode:"auto-approve-all",mergeStrategy:"direct",maxAutoMergeRetries:3,executorToolFailureRetryCount:2,executorToolFailureRetryBackoffMs:2e3,executorToolFailureThreshold:1,executorModelEscalationEnabled:!1,executorEscalationProvider:"",executorEscalationModelId:"",executorEscalationNodeId:"",mergeIntegrationWorktree:"reuse-task-worktree",mergeAdvanceAutoSync:"stash-and-ff",merger:{mode:"ai",maxReviewPasses:3,allowDirtyLocalCheckoutSync:!0},recycleWorktrees:!1,showWorktreeGrouping:!1,openTasksInRightSidebar:!1,openMobileTasksInPopup:!1,taskPopupsBoardListOnly:!0,showCostBadgeOnCards:!1,taskDetailChatFirst:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",worktreeCopyFiles:[],worktreesDir:"",worktrunk:{enabled:!1,binaryPath:"",onFailure:"fail"},includeTaskIdInCommit:!0,worktreeInitCommand:"",ntfyEnabled:!1,agentClarificationEnabled:!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:""}),[Te,_e]=i.useState(!0),[,Ke]=i.useState(!1),[D,U]=i.useState("idle"),te=i.useRef(null),[ke,Ne]=i.useState(!1),re=i.useRef(null),$=i.useRef(!1),he=i.useRef(!1),xe=i.useRef(!0),je=i.useRef(null),Me=i.useRef({dirty:!1,changed:!1}),P=i.useRef(null),[Ce,Re]=i.useState(null),[ve,we]=i.useState(null),[ie,Ee]=i.useState(null),[A,z]=i.useState(null),Y=i.useCallback(r=>({...H,mcpServers:Rt(r,ve)}),[H,ve]),de=i.useCallback(r=>g=>{we(C=>{if(!C)return C;const O={...H,mcpServers:Rt(r,C)},Q=typeof g=="function"?g(O):g;return r==="global"?{...C,global:{...C.global,mcpServers:Q.mcpServers}}:{...C,project:{...C.project,mcpServers:Q.mcpServers}}})},[H]),ue=On.find(r=>!r.isGroupHeader),[me,Se]=i.useState(()=>new Set),[oe,Fe]=i.useState(!1),Ge=i.useRef(0),Ye=i.useCallback(async()=>{const r=++Ge.current;Fe(!1),Se(new Set);try{const g=await xa(a),C=new Set;for(const O of g??[]){const Q=Ii.get(O.id);Q&&C.add(Q)}if(r!==Ge.current)return;Se(C),Fe(!0)}catch{if(r!==Ge.current)return;Se(new Set),Fe(!0)}},[a]);i.useEffect(()=>{Ye();const r=a?`?projectId=${encodeURIComponent(a)}`:"";return ci(`/api/events${r}`,{events:{"plugin:lifecycle":g=>{try{const C=JSON.parse(g.data);if(C.scope==="project"&&(C.projectId??a)!==a)return;Ye()}catch{}}},onReconnect:()=>void Ye()})},[a,Ye]);const[ee,rt]=i.useState(()=>n==="pi-extensions"?"plugins":n??Kn),Dt=xh(a,{enabled:ee==="worktrees"||H.worktrunk?.enabled===!0}),os=Dt.status==="installed",[Ms,Rs]=i.useState(()=>n==="pi-extensions"?"pi-extensions":"fusion-plugins"),[$t,Es]=i.useState(null),zt=i.useRef(!1),[y,_]=i.useState(()=>X==="mobile"||(typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(Jr)?.matches===!0:!1)),[q,fe]=i.useState(()=>um()),Be=i.useRef(null),[Xe,Ze]=i.useState(""),[qt,wa]=i.useState(()=>{const r=n==="pi-extensions"?"plugins":n;return dm()||r!==void 0&&Zr.has(r)}),Vt=i.useCallback(r=>{wa(r);try{localStorage.setItem(wi,String(r))}catch{}},[]),Ft=i.useCallback(r=>{const g=Ti(r);fe(g);try{localStorage.setItem(Ci,String(g))}catch{}return g},[]),[Lt,Ri]=i.useState(!1),[Ot,Ei]=i.useState(null),[tl,sl]=i.useState(!1),[Qe,al]=i.useState(null),[Ca,nl]=i.useState(!1),[Ds,Fs]=i.useState(null),[ll,Sa]=i.useState(),[cs,Ls]=i.useState(!1),[rl,Na]=i.useState(!1),[Pa,ds]=i.useState(null),us=im(),[Di,Fi]=lm(),[ps,Li]=i.useState(null),[Oi,gs]=i.useState(null),[it,Ia]=i.useState(null),[il,ol]=i.useState(!1),[ot,Ta]=i.useState(null),[hs,Os]=i.useState(!1),[ft,Ks]=i.useState(!1),{entries:Ki,currentPath:yt,setPath:Aa,loading:Bi,error:Gi,refresh:Hi}=bn("project",it!==null,a,{allowAbsolutePaths:!1}),{entries:_i,currentPath:vt,setPath:Ma,loading:Ui,error:Wi,refresh:$i}=bn("project",il,a,{allowAbsolutePaths:!1}),{entries:zi,currentPath:Ra,setPath:Ea,loading:qi,error:Vi,refresh:Yi}=bn("project",ot!==null,a,{allowAbsolutePaths:!1}),{nodes:Qi}=ou(),cl=H.experimentalFeatures??{},Bs=$n(cl,"researchView"),Gs=$n(cl,"evalsView"),ct=i.useMemo(()=>pm(On.filter(r=>!qt&&Zr.has(r.id)||Xr.has(r.id)&&!me.has(r.id)?!1:r.id==="research-global"||r.id==="research-project"?Bs:r.id==="scheduled-evals"?Gs:!0)),[Bs,Gs,me,qt]),ms=ct.some(r=>r.id===Kn)?Kn:ei(ct,ue?.id??"general"),Yt=Ai(Xe),Ct=i.useMemo(()=>{if(!Yt)return[];const r=new Set(ct.map(g=>g.id));return Zh($h.filter(g=>r.has(g.sectionId)),Yt,(g,C)=>b(g,C))},[Yt,b,ct]),dl=i.useMemo(()=>em(Ct),[Ct]),St=i.useMemo(()=>hm(ct,Yt,r=>b(r.labelKey,r.label),r=>b(r),dl),[Yt,b,ct,dl]),ul=St.filter(r=>!r.isGroupHeader),bs=Yt.length>0,fs=ul.length>0,pl=X==="mobile",Hs=!pl||Lt,gl=ei(St,ms),Ji=i.useCallback((r,g)=>{zt.current=!0,P.current?.(r),Es(g)},[]);i.useEffect(()=>{if(zt.current){zt.current=!1;return}se.current&&(se.current.scrollTop=0)},[ee]),i.useEffect(()=>{if(!$t)return;const r=se.current;if(!r)return;const g=r.querySelector(`[data-settings-key="${CSS.escape($t)}"]`);if(!g)return;for(let O=g.parentElement;O;O=O.parentElement)O instanceof HTMLDetailsElement&&(O.open=!0);g.scrollIntoView({block:"center",behavior:cm()});const C=window.setTimeout(()=>Es(null),om);return()=>window.clearTimeout(C)},[$t,ee]);const Da=ct.find(r=>r.id===ee)?.scope;i.useEffect(()=>{if((ee==="research-global"||ee==="research-project")&&!Bs){rt(ms);return}if(ee==="scheduled-evals"&&!Gs){rt(ms);return}if(!ct.some(r=>r.id===ee)){if(Xr.has(ee)&&!oe)return;rt(ms);return}bs&&fs&&!St.some(r=>r.id===ee)&&rt(gl)},[ee,Bs,Gs,ms,gl,bs,fs,oe,St,ct]);const[Nt,Xi]=i.useState([]),[Zi,hl]=i.useState(!1),[eo,tt]=i.useState({}),[to,Fa]=i.useState({}),[so,ml]=i.useState({}),[La,bl]=i.useState({}),[Oa,Ka]=i.useState({}),[ao,Ba]=i.useState(null),[Ga,Ha]=i.useState({}),[no,_s]=i.useState({}),[lo,ys]=i.useState({}),st=i.useRef({}),vs=i.useRef({}),[fl,yl]=i.useState([]),[vl,kl]=i.useState(!1),[Qt,_a]=i.useState([]),[Jt,Ua]=i.useState([]),[ro,xl]=i.useState({}),[io,Us]=i.useState({}),[ks,jl]=i.useState(null),[ze,wl]=i.useState(null),[oo,Wa]=i.useState(null),[co,Ws]=i.useState(!1),[dt,$s]=i.useState(null),[$a,za]=i.useState(null),[uo,Cl]=i.useState(null),[po,Sl]=i.useState(!1),[go,qa]=i.useState(null),[ho,mo]=i.useState("persistent"),[bo,fo]=i.useState(null),[yo,vo]=i.useState(null),[ko,xo]=i.useState(null),[jo,Xt]=i.useState(null),[Va,zs]=i.useState(""),[wo,Nl]=i.useState(!1),[Ya,qs]=i.useState(!1),[Pl,Vs]=i.useState([]),[Co,Il]=i.useState([]),[So,No]=i.useState(!1),[Po,Tl]=i.useState([]),[Io,Al]=i.useState(!1),[To,Ml]=i.useState(null),[Ao,Rl]=i.useState([]),[Mo,El]=i.useState(!1),[Ro,Qa]=i.useState(null),Ja=i.useRef(!1),[Eo,Dl]=i.useState([]),[ut,Xa]=i.useState(Fn),[Za,Do]=i.useState(""),[Fo,Fl]=i.useState(!1),[Lo,Ll]=i.useState(null),[Oo,Ol]=i.useState(!1),[Ko,Kl]=i.useState(!1),[Bo,Bl]=i.useState(!1),en=i.useRef(!1),[Go,xs]=i.useState(!1),[,tn]=i.useState(null),[pt,Gl]=i.useState(null),[Ys,Qs]=i.useState(!1),[sn,Ho]=i.useState("both"),[an,_o]=i.useState(!0),Hl=i.useRef(null),{status:Uo,capabilities:Wo,loading:$o,error:zo,refresh:_l}=Iu({projectId:a,enabled:ee==="memory"}),Pt=!y,qo=Pt?{"--settings-nav-width":`${q}px`}:void 0,js=i.useCallback((r,g)=>{const C=Be.current;if(C&&(document.body.style.userSelect=C.previousUserSelect,Be.current=null,typeof r=="number"&&g instanceof HTMLElement&&typeof g.releasePointerCapture=="function"))try{g.releasePointerCapture(r)}catch{}},[]),nn=i.useCallback(r=>{const g=Be.current;g&&(r.preventDefault(),Ft(g.startWidth+r.clientX-g.startX))},[Ft]),ws=i.useCallback(r=>{js(r.pointerId,r.target)},[js]),Vo=i.useCallback(r=>{Pt&&(r.preventDefault(),r.stopPropagation(),typeof r.currentTarget.setPointerCapture=="function"&&r.currentTarget.setPointerCapture(r.pointerId),Be.current={startX:r.clientX,startWidth:q,previousUserSelect:document.body.style.userSelect},document.body.style.userSelect="none")},[Pt,q]),Yo=i.useCallback(r=>{Pt&&(r.key!=="ArrowLeft"&&r.key!=="ArrowRight"||(r.preventDefault(),Ft(q+(r.key==="ArrowRight"?16:-16))))},[Ft,Pt,q]);i.useEffect(()=>{if(!Pt){js();return}return document.addEventListener("pointermove",nn),document.addEventListener("pointerup",ws),document.addEventListener("pointercancel",ws),()=>{document.removeEventListener("pointermove",nn),document.removeEventListener("pointerup",ws),document.removeEventListener("pointercancel",ws),js()}},[js,nn,ws,Pt]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(Jr);if(!r)return;const g=C=>{_(X==="mobile"||(C?C.matches:r.matches))};return g(),r.addEventListener("change",g),()=>r.removeEventListener("change",g)},[X]);const Zt=i.useCallback(r=>Promise.all([cr(a),cu(a)]).then(([g,C])=>{const O={...g,ignoreHiddenOverlapPaths:g.ignoreHiddenOverlapPaths??!0,allowAbsoluteFileBrowserPaths:g.allowAbsoluteFileBrowserPaths===!0,showCostBadgeOnCards:g.showCostBadgeOnCards===!0,taskDetailChatFirst:g.taskDetailChatFirst===!0,githubLinkImportedIssuesToTracking:g.githubLinkImportedIssuesToTracking===!0,mergeIntegrationWorktree:Ar(g.mergeIntegrationWorktree),mergeAdvanceAutoSync:Mr(g.mergeAdvanceAutoSync),maxAutoMergeRetries:ti(g),executorToolFailureRetryCount:ga(g.executorToolFailureRetryCount,2),executorToolFailureRetryBackoffMs:ga(g.executorToolFailureRetryBackoffMs,2e3),executorToolFailureThreshold:Math.max(1,Math.floor(Number(g.executorToolFailureThreshold??1)||1)),executorModelEscalationEnabled:g.executorModelEscalationEnabled===!0,executorEscalationProvider:g.executorEscalationProvider??"",executorEscalationModelId:g.executorEscalationModelId??"",executorEscalationNodeId:g.executorEscalationNodeId??"",worktreeCopyFiles:Array.isArray(g.worktreeCopyFiles)?g.worktreeCopyFiles:[]};Z(O),Re(O),we(C),Ee({gitlabEnabled:C.global.gitlabEnabled,gitlabInstanceUrl:C.global.gitlabInstanceUrl,gitlabApiBaseUrl:C.global.gitlabApiBaseUrl,gitlabAuthToken:C.global.gitlabAuthToken,gitlabAuthTokenType:C.global.gitlabAuthTokenType,reportRoadmapDedupeEnabled:C.global.reportRoadmapDedupeEnabled,reportRoadmapLabel:C.global.reportRoadmapLabel,reportRoadmapRepo:C.global.reportRoadmapRepo}),z({...C,project:{...C.project,mergeIntegrationWorktree:C.project.mergeIntegrationWorktree===void 0?void 0:Ar(C.project.mergeIntegrationWorktree),mergeAdvanceAutoSync:C.project.mergeAdvanceAutoSync===void 0?void 0:Mr(C.project.mergeAdvanceAutoSync)}}),r&&_e(!1)}).catch(g=>{s(De(g),"error"),r&&_e(!1)}),[s,a]);i.useEffect(()=>{Zt(!0)},[s,a]),i.useEffect(()=>{let r=!1;return du().then(g=>{r||typeof g.version=="string"&&g.version.trim().length>0&&Ei(g.version)}).catch(()=>{}),()=>{r=!0}},[]);const Qo=i.useCallback(async()=>{sl(!0),Fs(null),Ls(!1),Na(!1),ds(null);try{const r=await uu();al(r),r.error&&s(r.error,"error")}catch(r){const g=De(r)||b("settings.general.updateCheckFailed","Failed to check for updates");al({currentVersion:Ot??"unknown",latestVersion:null,updateAvailable:!1,error:g}),s(g,"error")}finally{sl(!1)}},[s,Ot,b]),Ul=i.useCallback(async()=>{nl(!0),Fs(null),Ls(!1),Na(!1),ds(null);try{const r=await pu(a);if(Fs(r),r.error){s(r.error,"error");return}r.updated&&(s(b("settings.general.updateSuccessToast","Update installed. Restart Fusion to apply it."),"success"),dr().then(g=>Sa(g.restartSupported)).catch(()=>{}))}catch(r){const g=De(r)||b("settings.general.updateFailed","Update failed");Fs({currentVersion:Qe?.currentVersion??Ot??"unknown",latestVersion:Qe?.latestVersion??null,updated:!1,error:g}),s(g,"error")}finally{nl(!1)}},[s,Ot,a,b,Qe]);i.useEffect(()=>{let r=!1;return dr().then(g=>{r||Sa(g.restartSupported)}).catch(()=>{r||Sa(!1)}),()=>{r=!0}},[]);const Wl=i.useCallback(async()=>{if(!cs){Ls(!0),ds(null);try{(await gu("settings-update")).scheduled?Na(!0):ds(b("settings.general.restartFailed","Restart could not be scheduled. Try restarting Fusion manually."))}catch(r){ds(De(r)||b("settings.general.restartFailed","Restart could not be scheduled. Try restarting Fusion manually."))}finally{Ls(!1)}}},[cs,b]),Jo=i.useCallback(()=>{if(!Qe)return null;if(Qe.error)return Qe.error;if(Qe.updateAvailable&&Qe.latestVersion){const r=Ds?.updated===!0,g=Ds?.error;return e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[b("settings.general.updateAvailablePrefix","v{{version}} available",{version:Qe.latestVersion})," ·"," ",e.jsx("a",{href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",className:"settings-update-result-link",children:b("settings.general.learnMore","Learn more")})]}),r?e.jsxs("span",{className:"settings-update-install-succeeded",children:[e.jsx("span",{className:"settings-update-install-status settings-update-install-status--success","aria-live":"polite",children:b("settings.general.updateSuccess","Updated to v{{version}} — restart Fusion to apply",{version:Ds.latestVersion??Qe.latestVersion})}),rl?e.jsx("span",{className:"settings-update-install-status","aria-live":"polite",children:b("settings.general.restarting","Restarting… Your connection will close shortly.")}):e.jsx("button",{type:"button",className:"btn btn-sm settings-update-now-btn",onClick:()=>{Wl()},disabled:cs,children:cs?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{size:12,className:"spinning","aria-hidden":"true"}),b("settings.general.restarting","Restarting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(hu,{size:12,"aria-hidden":"true"}),b("settings.general.restartNow","Restart Fusion")]})}),ll===!1&&e.jsx("span",{className:"settings-update-install-status","aria-live":"polite",children:b("settings.general.restartUnavailable","Needs a supervising parent — restart Fusion manually without --no-supervise.")}),Pa&&e.jsx("span",{className:"settings-update-install-status settings-update-install-status--error","aria-live":"polite",children:Pa})]}):e.jsx("button",{type:"button",className:"btn btn-sm settings-update-now-btn",onClick:()=>{Ul()},disabled:Ca,children:Ca?e.jsxs(e.Fragment,{children:[e.jsx(Ts,{size:12,className:"spinning","aria-hidden":"true"}),b("settings.general.updating","Updating…")]}):b("settings.general.updateNow","Update now")}),g&&e.jsx("span",{className:"settings-update-install-status settings-update-install-status--error","aria-live":"polite",children:b("settings.general.updateFailedWithMessage","Update failed: {{message}}",{message:g})})]})}return b("settings.general.upToDate","You're up to date ✓")},[Ul,Wl,Pa,cs,rl,ll,b,Qe,Ca,Ds]),ln=Qe?e.jsx("span",{"aria-live":"polite",className:`settings-update-result ${Qe.error?"settings-update-result--error":Qe.updateAvailable?"settings-update-result--available":"settings-update-result--up-to-date"}`,children:Jo()}):null,We=i.useCallback(async()=>{try{const{providers:r}=await ur(),g=mu(r);Xi(g),Fa(C=>{const O={};for(const[Q,J]of Object.entries(C)){const ge=g.find(ye=>ye.id===Q);ge&&!ge.authenticated&&(O[Q]=J)}return Object.keys(O).length===Object.keys(C).length?C:O})}catch{}},[]);i.useEffect(()=>{(ee==="global-models"||ee==="project-models")&&(kl(!0),bu().then(r=>{yl(r.models),_a(r.favoriteProviders),Ua(r.favoriteModels)}).catch(()=>yl([])).finally(()=>kl(!1)))},[ee]),i.useEffect(()=>{ee==="backups"&&(Ws(!0),kr(a).then(r=>Wa(r)).catch(()=>Wa(null)).finally(()=>Ws(!1)))},[ee,a]);const Js=i.useCallback(async()=>{const[r,g]=await Promise.allSettled([fp(a),jn(a)]);r.status==="fulfilled"&&Z(C=>({...C,...r.value.settings})),g.status==="fulfilled"&&($s(g.value),za(g.value.externalTunnel??null))},[a]);i.useEffect(()=>{const r=dt?.state;(r==="running"||r==="starting")&&za(null)},[dt?.state]),i.useEffect(()=>{ee==="remote"&&Js().catch(()=>{$s(null)})},[ee,Js]),i.useEffect(()=>{if(ee!=="remote")return;const r=dt?.state;if(r!=="starting"&&r!=="stopping")return;const g=setInterval(()=>{jn(a).then(C=>{$s(C),za(C.externalTunnel??null)}).catch(()=>{})},1e3);return()=>clearInterval(g)},[ee,a,dt?.state]),i.useEffect(()=>{if(ee!=="remote")return;if(dt?.state!=="running"){Xt(null);return}let r=!1;return(async()=>{try{const g=await Wn("image/svg",{projectId:a,tokenType:"persistent"});if(r)return;Xt({url:g.url,qrSvg:g.data??null})}catch{if(r)return;try{const g=await pi({projectId:a,tokenType:"persistent"});if(r)return;Xt({url:g.url,qrSvg:null})}catch{r||Xt(null)}}})(),()=>{r=!0}},[ee,a,dt?.state,dt?.url]),i.useEffect(()=>{if(ee!=="remote")return;const r=$a?.url;if(dt?.state!=="stopped"||!r)return;let g=!1;return(async()=>{try{const C=await Wn("image/svg",{projectId:a,tokenType:"persistent"});if(g)return;Xt({url:r,qrSvg:C.data??null})}catch{g||Xt({url:r,qrSvg:null})}})(),()=>{g=!0}},[ee,$a?.url,a,dt?.state]),i.useEffect(()=>{ee==="worktrees"&&pr(a).then(r=>Vs(r)).catch(()=>Vs([]))},[ee,a]),i.useEffect(()=>{ee==="merge"&&(pr(a).then(r=>Vs(r)).catch(()=>Vs([])),fu(a).then(r=>{const g=r.map(J=>J.name).filter(J=>typeof J=="string"&&J.length>0),C=new Set,O=["main","master","trunk","develop"],Q=[];for(const J of O)g.includes(J)&&!C.has(J)&&(Q.push(J),C.add(J));for(const J of[...g].sort((ge,ye)=>ge.localeCompare(ye)))C.has(J)||(C.add(J),Q.push(J));Il(Q)}).catch(()=>Il([])))},[ee,a]),i.useEffect(()=>{if(ee!=="source-control")return;let r=!1;return Al(!0),Ml(null),gr(a).then(g=>{r||Tl(nm(g))}).catch(()=>{r||(Tl([]),Ml("Could not load detected remotes. Enter a custom owner/repo value."))}).finally(()=>{r||Al(!1)}),()=>{r=!0}},[ee,a]),i.useEffect(()=>{if(ee!=="source-control-global"||Ja.current)return;let r=!1;return El(!0),Qa(null),yu().then(async g=>{const C=await Promise.allSettled(g.map(async ge=>(await gr(ge.id)).map(He=>({value:`${He.owner}/${He.repo}`,label:`${He.owner}/${He.repo}`,source:ge.name}))));if(r)return;const O=new Map;let Q=0;for(const ge of C)if(ge.status==="fulfilled"){Q+=1;for(const ye of ge.value)O.has(ye.value)||O.set(ye.value,ye)}const J=[...O.values()].sort((ge,ye)=>ge.value.localeCompare(ye.value));Rl(J),g.length>0&&Q===0&&Qa("Could not load remotes from registered projects. Enter a custom owner/repo value."),Ja.current=!0}).catch(()=>{r||(Rl([]),Qa("Could not load project list. Enter a custom owner/repo value."),Ja.current=!0)}).finally(()=>{r||El(!1)}),()=>{r=!0}},[ee,a]),i.useEffect(()=>{if(ee!=="memory"||Ya)return;if(en.current){en.current=!1;return}let r=!1;return Nl(!0),vr(a).then(async({files:g})=>{if(r)return;Dl(g);const C=g.some(Q=>Q.path===ut)?ut:g.find(Q=>Q.path===Fn)?.path??g.find(Q=>Q.layer==="dreams")?.path??g[0]?.path??Fn;Xa(C);const{content:O}=await Tu(C,a);r||(zs(O),qs(!1))}).catch(g=>{r||(s(De(g)||"Failed to load project memory","error"),zs(""))}).finally(()=>{r||Nl(!1)}),()=>{r=!0}},[ee,Ya,ut,a,s]),i.useEffect(()=>((ee==="authentication"||ee==="research-global")&&(hl(!0),We().finally(()=>hl(!1))),()=>{for(const r of Object.values(st.current))clearInterval(r);st.current={}}),[ee,We]),i.useEffect(()=>{if(ee!=="authentication"||!Nt.some(C=>C.type!=="api_key"&&C.loginInProgress))return;const g=setInterval(()=>{We()},2e3);return()=>clearInterval(g)},[ee,Nt,We]);const Xs=i.useRef({});i.useEffect(()=>{for(const r of Nt){const g=r.loginError;if(!g){r.id in Xs.current&&delete Xs.current[r.id];continue}Xs.current[r.id]!==g&&(Xs.current[r.id]=g,s(`${r.name} login failed: ${g}`,"error"))}},[Nt,s]);const Zs=i.useCallback(()=>{se.current?.scrollTo({top:0,behavior:"smooth"})},[]),Kt=i.useCallback(r=>{if(r in vs.current){const g={...vs.current};delete g[r],vs.current=g}Fa(g=>{if(!(r in g))return g;const C={...g};return delete C[r],C}),ml(g=>{if(!(r in g))return g;const C={...g};return delete C[r],C}),Ka(g=>{if(!(r in g))return g;const C={...g};return delete C[r],C}),bl(g=>{if(!(r in g))return g;const C={...g};return delete C[r],C})},[]);i.useEffect(()=>{const r=La["github-copilot"];r?.userCode&&vs.current["github-copilot"]!==r.userCode&&(vs.current["github-copilot"]=r.userCode,qn(r.userCode))},[La]);const Xo=i.useCallback(async(r,g,C)=>{const O=xt({providerId:r,instanceId:g??"default"}),Q=Nt.find(J=>J.id===r);if(!(Q?.requiresManualCode===!0&&!await V({title:b("settings.auth.manualPasteTitle","Heads up — manual paste-back required"),message:b("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:Q.name}),confirmLabel:b("settings.auth.continueToLogin","Continue to login"),cancelLabel:b("settings.actions.cancel","Cancel")}))){tt(J=>({...J,[O]:!0})),Kt(O);try{const{url:J,instructions:ge,manualCode:ye,deviceCode:He}=g===void 0?await fn(r):C===void 0?await fn(r,g):await fn(r,g,C);ge?.trim()&&!(r==="github-copilot"&&He)&&Fa(Le=>({...Le,[O]:ge})),ye&&ml(Le=>({...Le,[O]:ye})),He&&r==="github-copilot"&&bl(Le=>({...Le,[O]:He})),(r!=="github-copilot"||!He)&&ri(ii(He?.verificationUri??J)),st.current[O]=setInterval(async()=>{try{const{providers:Le}=await ur({provider:r,instance:g}),kt=Le.find(qe=>qe.id===r&&(qe.instanceId??"default")===(g??"default"));if(kt?.authenticated){st.current[O]&&(clearInterval(st.current[O]),delete st.current[O]),tt(qe=>{const nt={...qe};return delete nt[O],nt}),Kt(O),await We().catch(()=>{}),s(b("settings.auth.loginSuccessful","Login successful"),"success"),window.dispatchEvent(new CustomEvent(vu,{detail:{providerId:r}})),Zs();return}kt?.loginInProgress||(st.current[O]&&(clearInterval(st.current[O]),delete st.current[O]),tt(qe=>{const nt={...qe};return delete nt[O],nt}),Kt(O),s(b("settings.auth.loginDidNotComplete","Login did not complete. Please try again."),"error"))}catch{}},2e3)}catch(J){const ge=De(J)||"Login failed";ge.includes("already in progress")||typeof J=="object"&&J!==null&&"status"in J&&J.status===409?(s(b("settings.auth.loginAlreadyInProgress","Login already in progress. You can cancel it and retry."),"warning"),await We()):s(ge,"error"),tt(He=>{const Le={...He};return delete Le[O],Le}),Kt(O)}}},[s,Nt,Kt,V,We,Zs]),Zo=i.useCallback(async(r,g)=>{const C=xt({providerId:r,instanceId:g??"default"}),O=Oa[C]?.trim();if(!O){s(b("settings.auth.pasteRedirectUrlFirst","Paste the full redirect URL or authorization code first."),"warning");return}Ba(C);try{(g===void 0?await hr(r,O):await hr(r,O,g)).submitted?(Ka(J=>{if(!(C in J))return J;const ge={...J};return delete ge[C],ge}),s(b("settings.auth.authCodeReceived","Authorization code received. Finishing login…"),"success")):s(b("settings.auth.authCodeAlreadySubmitted","That authorization code was already submitted. Waiting for login…"),"warning")}catch(Q){s(De(Q)||"Failed to submit authorization code","error")}finally{Ba(null)}},[s,Oa]),ec=i.useCallback(async(r,g)=>{const C=xt({providerId:r,instanceId:g??"default"});tt(O=>({...O,[C]:!0}));try{g===void 0?await mr(r):await mr(r,g),Kt(C),await We().catch(()=>{}),s(b("settings.auth.loginCancelled","Login cancelled"),"success")}catch(O){s(De(O)||"Failed to cancel login","error")}finally{tt(O=>{const Q={...O};return delete Q[C],Q}),Ba(O=>O===C?null:O),st.current[C]&&(clearInterval(st.current[C]),delete st.current[C])}},[s,Kt,We]),tc=i.useCallback(async(r,g)=>{const C=xt({providerId:r,instanceId:g??"default"});tt(O=>({...O,[C]:!0}));try{g===void 0?await br(r):await br(r,g),await We(),s(b("settings.auth.loggedOut","Logged out"),"success")}catch(O){s(De(O)||"Logout failed","error")}finally{tt(O=>{const Q={...O};return delete Q[C],Q})}},[s,We]),sc=i.useCallback(async(r,g,C)=>{const O=xt({providerId:r,instanceId:g??"default"}),Q=Ga[O]?.trim();if(!Q){_s(J=>({...J,[O]:"API key is required"}));return}tt(J=>({...J,[O]:!0})),_s(J=>{const ge={...J};return delete ge[O],ge});try{const J=g===void 0?await fr(r,Q):await fr(r,Q,g,C);if(Ha(ge=>{const ye={...ge};return delete ye[O],ye}),await We(),r==="opencode"||r==="opencode-go"){const ge=J.modelsRefreshed,ye=J.refreshReason,He=J.refreshError;He?ys(Le=>({...Le,[r]:{tone:"error",message:`Saved, but model refresh failed: ${He}. Make sure the \`opencode\` CLI is installed on PATH.`}})):ye==="no-models-from-cli"?ys(Le=>({...Le,[r]:{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 ge=="number"&&ge>0?ys(Le=>({...Le,[r]:{tone:"success",message:`Refreshed ${ge} opencode-go models.`}})):ys(Le=>{const kt={...Le};return delete kt[O],kt})}s(b("settings.auth.apiKeySaved","API key saved"),"success"),Zs()}catch(J){_s(ge=>({...ge,[O]:De(J)||"Failed to save API key"})),(r==="opencode"||r==="opencode-go")&&ys(ge=>{const ye={...ge};return delete ye[O],ye})}finally{tt(J=>{const ge={...J};return delete ge[O],ge})}},[Ga,s,We,Zs]),ac=i.useCallback(async(r,g)=>{const C=xt({providerId:r,instanceId:g??"default"});tt(O=>({...O,[C]:!0}));try{g===void 0?await yr(r):await yr(r,g),Ha(O=>{const Q={...O};return delete Q[C],Q}),_s(O=>{const Q={...O};return delete Q[C],Q}),await We(),s(b("settings.auth.apiKeyCleared","API key cleared"),"success")}catch(O){s(De(O)||"Failed to clear API key","error")}finally{tt(O=>{const Q={...O};return delete Q[C],Q})}},[s,We]),nc=i.useCallback(async r=>{if(!((r==="ntfy"||r==="ntfy-message"||r==="ntfy-room")&&(!H.ntfyEnabled||!H.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(H.ntfyTopic)))){if(r==="webhook"){if(!H.webhookEnabled||!H.webhookUrl?.trim())return;try{const g=new URL(H.webhookUrl.trim());if(g.protocol!=="http:"&&g.protocol!=="https:")return}catch{return}}xl(g=>({...g,[r]:!0})),Us(g=>{const C={...g};return delete C[r],C});try{const g={ntfyEnabled:H.ntfyEnabled,ntfyTopic:H.ntfyTopic,...H.ntfyBaseUrl?.trim()?{ntfyBaseUrl:H.ntfyBaseUrl.trim()}:{},...H.ntfyAccessToken?.trim()?{ntfyAccessToken:H.ntfyAccessToken.trim()}:{}},C=r==="ntfy"?g:r==="ntfy-message"?{...g,messageEventType:"message:agent-to-user"}:r==="ntfy-room"?{...g,messageEventType:"message:room"}:{webhookUrl:H.webhookUrl,webhookFormat:H.webhookFormat||"generic"};if((await ku(r==="ntfy-message"||r==="ntfy-room"?"ntfy":r,C,a)).success){const Q=r==="ntfy"?"Test notification sent — check your ntfy app!":r==="ntfy-message"?"Message inbox test sent — check your ntfy inbox for the agent-to-user message.":r==="ntfy-room"?"Room reply test sent — check your ntfy inbox for the room reply.":"Test notification sent — check your webhook endpoint!";Us(J=>({...J,[r]:{status:"success",message:Q}})),s(Q,"success")}else{const Q=r==="ntfy-message"?"Failed to send message inbox test":r==="ntfy-room"?"Failed to send room reply test":"Failed to send test notification";Us(J=>({...J,[r]:{status:"error",message:Q}})),s(Q,"error")}}catch(g){const C=De(g)||"Failed to send test notification";Us(O=>({...O,[r]:{status:"error",message:C}})),s(C,"error")}finally{xl(g=>({...g,[r]:!1}))}}},[s,H.ntfyAccessToken,H.ntfyBaseUrl,H.ntfyEnabled,H.ntfyTopic,H.webhookEnabled,H.webhookFormat,H.webhookUrl,a]),lc=i.useCallback(async()=>{Ws(!0);try{const r=await Fu(a);if(r.success){s(b("settings.backups.backupCreated","Backup created successfully"),"success");const g=await kr(a);Wa(g)}else s(r.error||b("settings.backups.createFailed","Failed to create backup"),"error")}catch(r){s(De(r)||b("settings.backups.createFailed","Failed to create backup"),"error")}finally{Ws(!1)}},[s,a]),rc=i.useCallback(async()=>{try{const r=Da==="global"?"global":Da==="project"?"project":"both",g=await Lu(r,a),C=new Blob([JSON.stringify(g,null,2)],{type:"application/json"}),O=URL.createObjectURL(C),Q=document.createElement("a"),J=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;Q.href=O,Q.download=J,document.body.appendChild(Q),Q.click(),document.body.removeChild(Q),URL.revokeObjectURL(O);const ge=r==="global"?b("settings.importExport.scopeLabel.global","global"):r==="project"?b("settings.importExport.scopeLabel.project","project"):b("settings.importExport.scopeLabel.all","all");s(b("settings.importExport.exported","Settings exported ({{scope}} scope)",{scope:ge}),"success")}catch(r){s(De(r)||b("settings.importExport.exportFailed","Failed to export settings"),"error")}},[s,Da,a]),ic=i.useCallback(async r=>{const g=r.target.files?.[0];if(g){tn(g),Qs(!0);try{const C=await g.text(),O=JSON.parse(C);Gl(O),xs(!0)}catch(C){s(b("settings.importExport.invalidJson","Invalid JSON file: {{error}}",{error:De(C)}),"error"),tn(null)}finally{Qs(!1)}}},[s]),oc=i.useCallback(async()=>{if(pt){Qs(!0);try{const r=await Ou(pt,{scope:sn,merge:an},a);if(r.success){const g=[];r.globalCount>0&&g.push(b("settings.importExport.counts.global","{{count}} global",{count:r.globalCount})),r.projectCount>0&&g.push(b("settings.importExport.counts.project","{{count}} project",{count:r.projectCount})),r.workflowSettingsCount>0&&g.push(b("settings.importExport.counts.workflowSettings","{{count}} workflow setting value",{count:r.workflowSettingsCount})),s(b("settings.importExport.imported","Imported {{counts}} setting(s)",{counts:g.join(", ")}),"success"),xs(!1),Gl(null),tn(null);const C=await cr(a);Z({...C,ignoreHiddenOverlapPaths:C.ignoreHiddenOverlapPaths??!0,allowAbsoluteFileBrowserPaths:C.allowAbsoluteFileBrowserPaths===!0})}else s(r.error||b("settings.importExport.importFailed","Import failed"),"error")}catch(r){s(De(r)||b("settings.importExport.importFailedDetailed","Failed to import settings"),"error")}finally{Qs(!1)}}},[s,pt,sn,an,a]),$l=i.useCallback(async r=>{const g=Qt,O=g.includes(r)?g.filter(Q=>Q!==r):[r,...g];_a(O);try{await ls({favoriteProviders:O,favoriteModels:Jt})}catch{_a(g)}},[Qt,Jt]),zl=i.useCallback(async r=>{const g=Jt,O=g.includes(r)?g.filter(Q=>Q!==r):[r,...g];Ua(O);try{await ls({favoriteProviders:Qt,favoriteModels:O})}catch{Ua(g)}},[Jt,Qt]),ql=[{laneId:"default",label:"Default Model",globalProviderKey:"defaultProvider",globalModelKey:"defaultModelId",projectProviderKey:"defaultProviderOverride",projectModelKey:"defaultModelIdOverride",projectThinkingKey:"defaultThinkingLevelOverride",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",globalThinkingKey:"executionGlobalThinkingLevel",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",globalThinkingKey:"planningGlobalThinkingLevel",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",globalThinkingKey:"validatorGlobalThinkingLevel",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:"merger",label:"Merger Model",globalProviderKey:"mergerGlobalProvider",globalModelKey:"mergerGlobalModelId",globalThinkingKey:"mergerGlobalThinkingLevel",projectProviderKey:"mergerProvider",projectModelKey:"mergerModelId",projectThinkingKey:"mergerThinkingLevel",helperText:"AI model used for merge conflict resolution, clean-room merge, stash-conflict recovery, and related merger agent sessions.",fallbackOrder:"Project override → Global merger lane → Project default lane → Global default lane → Automatic resolution"},{laneId:"summarization",label:"Title and Git Commit Message Summarization Model",globalProviderKey:"titleSummarizerGlobalProvider",globalModelKey:"titleSummarizerGlobalModelId",globalThinkingKey:"titleSummarizerGlobalThinkingLevel",projectProviderKey:"titleSummarizerProvider",projectModelKey:"titleSummarizerModelId",projectThinkingKey:"titleSummarizerThinkingLevel",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"},{laneId:"import-translate",label:"Import Auto-Translation Model",globalProviderKey:"importTranslateGlobalProvider",globalModelKey:"importTranslateGlobalModelId",globalThinkingKey:"importTranslateGlobalThinkingLevel",projectProviderKey:"importTranslateProvider",projectModelKey:"importTranslateModelId",projectThinkingKey:"importTranslateThinkingLevel",helperText:"AI model used to translate foreign-language GitHub/GitLab issue titles and bodies in the Import Tasks panel.",fallbackOrder:"Project override → Global import-translate lane → Summarization lane → Project default → Global default"}];function rn(r){if(!ve?.project)return"inherited";const g=ve.project[r.projectProviderKey],C=ve.project[r.projectModelKey];return g!==void 0||C!==void 0?"overridden":"inherited"}function cc(r){const g=H[r.projectProviderKey],C=H[r.projectModelKey];return g&&C?`${g}/${C}`:""}function dc(r,g){if(g){const C=g.indexOf("/");Z(O=>({...O,[r.projectProviderKey]:g.slice(0,C),[r.projectModelKey]:g.slice(C+1)}))}else{if(rn(r)==="inherited")return;Z(O=>({...O,[r.projectProviderKey]:void 0,[r.projectModelKey]:void 0}))}}function uc(r){rn(r)!=="inherited"&&Z(C=>({...C,[r.projectProviderKey]:void 0,[r.projectModelKey]:void 0}))}function Vl(r,g="project"){const C=g==="project"?r.projectThinkingKey:r.globalThinkingKey;return C?H[C]??"":""}function on(r,g,C="project"){const O=C==="project"?r.projectThinkingKey:r.globalThinkingKey;O&&Z(Q=>({...Q,[O]:g||void 0}))}function Yl(r,g="project"){on(r,"",g)}const pc=i.useCallback(r=>{Ia(r),Aa(".")},[Aa]),It=i.useCallback(()=>{Ia(null)},[]),cn=i.useCallback(r=>{it!==null&&(pa(r)||(Z(g=>{const C=g.overlapIgnorePaths&&g.overlapIgnorePaths.length>0?[...g.overlapIgnorePaths]:[""];return C[it]=r,{...g,overlapIgnorePaths:C}}),It()))},[it,It]),gc=i.useCallback(()=>{if(yt===".")return;const r=yt.endsWith("/")?yt:`${yt}/`;cn(r)},[yt,cn]),hc=i.useCallback(r=>{r.target===r.currentTarget&&It()},[It]),mc=i.useCallback(()=>{Ma("."),ol(!0)},[Ma]),Tt=i.useCallback(()=>{ol(!1)},[]),bc=i.useCallback(r=>{if(pa(r))return;const g=r.endsWith("/")?r:`${r}/`;Z(C=>({...C,worktreesDir:g})),Tt()},[Tt]),fc=i.useCallback(()=>{if(pa(vt))return;const r=vt==="."?"./":vt.endsWith("/")?vt:`${vt}/`;Z(g=>({...g,worktreesDir:r})),Tt()},[vt,Tt]),yc=i.useCallback(r=>{r.target===r.currentTarget&&Tt()},[Tt]),vc=i.useCallback(r=>{Ta(r),Ea(".")},[Ea]),At=i.useCallback(()=>{Ta(null)},[]),kc=i.useCallback(r=>{ot!==null&&(pa(r)||(Z(g=>{const C=g.worktreeCopyFiles&&g.worktreeCopyFiles.length>0?[...g.worktreeCopyFiles]:[""];return C[ot]=r,{...g,worktreeCopyFiles:C}}),At()))},[ot,At]),xc=i.useCallback(r=>{r.target===r.currentTarget&&At()},[At]),jc=i.useCallback((r,g)=>{Z(C=>{const O=C.worktreeCopyFiles&&C.worktreeCopyFiles.length>0?[...C.worktreeCopyFiles]:[""];return O[r]=g,{...C,worktreeCopyFiles:O}})},[]),wc=i.useCallback(r=>{if(Z(g=>{const O=(g.worktreeCopyFiles&&g.worktreeCopyFiles.length>0?[...g.worktreeCopyFiles]:[""]).filter((Q,J)=>J!==r);return{...g,worktreeCopyFiles:O.length>0?O:[]}}),ot===r){At();return}ot!==null&&ot>r&&Ta(ot-1)},[ot,At]),Cc=i.useCallback(()=>{Z(r=>{const g=r.worktreeCopyFiles&&r.worktreeCopyFiles.length>0?r.worktreeCopyFiles:[""];return{...r,worktreeCopyFiles:[...g,""]}})},[]),Sc=i.useCallback((r,g)=>{Z(C=>{const O=C.overlapIgnorePaths&&C.overlapIgnorePaths.length>0?[...C.overlapIgnorePaths]:[""];return O[r]=g,{...C,overlapIgnorePaths:O}})},[]),Nc=i.useCallback(r=>{if(Z(g=>{const O=(g.overlapIgnorePaths&&g.overlapIgnorePaths.length>0?[...g.overlapIgnorePaths]:[""]).filter((Q,J)=>J!==r);return{...g,overlapIgnorePaths:O.length>0?O:[]}}),it===r){It();return}it!==null&&it>r&&Ia(it-1)},[it,It]),Pc=i.useCallback(()=>{Z(r=>{const g=r.overlapIgnorePaths&&r.overlapIgnorePaths.length>0?r.overlapIgnorePaths:[""];return{...r,overlapIgnorePaths:[...g,""]}})},[]),Ic=i.useCallback(async()=>{if($.current)return he.current=!0,!1;if(ps||ze)return xe.current=!1,!1;const r=H,g=ve,C=Ce,O=A,Q=ee,J=ie,ge=pe.current,ye=r.researchSettings?.limits;if(ye?.maxConcurrentRuns!==void 0&&(!Number.isFinite(ye.maxConcurrentRuns)||ye.maxConcurrentRuns<1))return gs("Research max concurrent runs must be at least 1."),xe.current=!1,!1;if(ye?.maxSourcesPerRun!==void 0&&(!Number.isFinite(ye.maxSourcesPerRun)||ye.maxSourcesPerRun<1))return gs("Research max sources per run must be at least 1."),xe.current=!1,!1;if(ye?.maxDurationMs!==void 0&&(!Number.isFinite(ye.maxDurationMs)||ye.maxDurationMs<1e3))return gs("Research max duration must be at least 1000 ms."),xe.current=!1,!1;if(ye?.requestTimeoutMs!==void 0&&(!Number.isFinite(ye.requestTimeoutMs)||ye.requestTimeoutMs<1e3))return gs("Research request timeout must be at least 1000 ms."),xe.current=!1,!1;gs(null);const He=ni(r.dashboardKeyboardShortcuts??{});if(He)return s(He,"error"),xe.current=!1,!1;$.current=!0,Ke(!0),U("saving");try{const Le=jm(r.worktreeCopyFiles);let kt=os;r.worktrunk?.enabled===!0&&!kt&&(kt=(await Dt.refresh()).status==="installed");const qe=Q==="source-control-global"&&J?J:r,nt={...r,worktreeInitCommand:r.worktreeInitCommand?.trim()||void 0,worktreesDir:r.worktreesDir?.trim()||void 0,worktrunk:{enabled:kt&&r.worktrunk?.enabled===!0,binaryPath:r.worktrunk?.binaryPath?.trim()||void 0,onFailure:r.worktrunk?.onFailure??"fail"},maxAutoMergeRetries:ti(r),executorToolFailureRetryCount:ga(r.executorToolFailureRetryCount,2),executorToolFailureRetryBackoffMs:ga(r.executorToolFailureRetryBackoffMs,2e3),executorToolFailureThreshold:Math.max(1,Math.floor(Number(r.executorToolFailureThreshold??1)||1)),executorModelEscalationEnabled:r.executorModelEscalationEnabled===!0,executorEscalationProvider:r.executorEscalationProvider?.trim()||void 0,executorEscalationModelId:r.executorEscalationModelId?.trim()||void 0,executorEscalationNodeId:r.executorEscalationNodeId?.trim()||void 0,taskPrefix:r.taskPrefix?.trim()||void 0,githubTrackingDefaultRepo:r.githubTrackingDefaultRepo?.trim()||void 0,dashboardKeyboardShortcuts:Object.fromEntries(Object.entries(Gn(r.dashboardKeyboardShortcuts)).map(([Ve,ta])=>[Ve,zn(ta).normalized])),gitlabEnabled:qe.gitlabEnabled,gitlabInstanceUrl:qe.gitlabInstanceUrl?.trim()||void 0,gitlabApiBaseUrl:qe.gitlabApiBaseUrl?.trim()||void 0,gitlabAuthToken:qe.gitlabAuthToken?.trim()||void 0,gitlabAuthTokenType:qe.gitlabAuthTokenType??"personal",reportRoadmapDedupeEnabled:qe.reportRoadmapDedupeEnabled,reportRoadmapLabel:qe.reportRoadmapLabel?.trim()||void 0,reportRoadmapRepo:qe.reportRoadmapRepo?.trim()||void 0,githubAuthToken:r.githubAuthToken?.trim()||void 0,prTitlePromptInstructions:r.prTitlePromptInstructions?.trim()||void 0,prDescriptionPromptInstructions:r.prDescriptionPromptInstructions?.trim()||void 0,pushRemote:r.pushAfterMerge&&r.pushRemote?.trim()||void 0,overlapIgnorePaths:(r.overlapIgnorePaths??[]).map(Ve=>Ve.trim()).filter(Ve=>Ve.length>0),worktreeCopyFiles:Le.length>0||O?.project?.worktreeCopyFiles!==void 0?Le:void 0,experimentalFeatures:xm(r.experimentalFeatures)};Q==="source-control"&&Ir({project:{gitlabInstanceUrl:nt.gitlabInstanceUrl,gitlabApiBaseUrl:nt.gitlabApiBaseUrl}}),Q==="source-control-global"&&Ir({global:{gitlabInstanceUrl:nt.gitlabInstanceUrl,gitlabApiBaseUrl:nt.gitlabApiBaseUrl}});const{globalPatch:ea,projectPatch:hn}=Rr({payload:nt,initialValues:C,initialScopedValues:O,activeSection:Q,scopedMcpValues:g?{global:Rt("global",g),project:Rt("project",g)}:void 0});return await Promise.all([Object.keys(ea).length>0?ls(ea):Promise.resolve(),Object.keys(hn).length>0?yn(hn,a):Promise.resolve()]),await ne.current?.(),pe.current===ge&&W(!1),U("saved"),Re(Ve=>Ve&&{...Ve,...ea}),z(Ve=>{if(!Ve)return Ve;const ta=(Uc,Wc)=>Object.fromEntries(Object.entries({...Uc,...Wc}).map(([$c,Ql])=>[$c,Ql===null?void 0:Ql]));return{global:ta(Ve.global,ea),project:ta(Ve.project,hn)}}),re.current=JSON.stringify({form:r,scopedSettings:g,globalGitlabSettings:J}),xe.current=!0,!0}catch(Le){return xe.current=!1,Le instanceof yi||(U("error"),s(De(Le),"error")),!1}finally{$.current=!1,Ke(!1),he.current&&(he.current=!1,je.current?.())}},[H,ie,ps,ze,Ce,A,ve,s,a,ee,b]);je.current=Ic;const Bt=i.useMemo(()=>{const r=ee==="source-control-global"&&ie?{...H,...ie}:H,{globalPatch:g,projectPatch:C}=Rr({payload:r,initialValues:Ce,initialScopedValues:A,activeSection:ee,scopedMcpValues:ve?{global:Rt("global",ve),project:Rt("project",ve)}:void 0});return Object.keys(g).length>0||Object.keys(C).length>0||j},[H,ie,A,Ce,ve,ee,j]),dn=i.useMemo(()=>JSON.stringify({form:H,scopedSettings:ve,globalGitlabSettings:ie,workflowLaneRevision:pe.current}),[H,ie,ve,j]),Gt=re.current!==null&&re.current!==dn;Me.current={dirty:Bt,changed:Gt},i.useEffect(()=>{!Te&&re.current===null&&(re.current=dn,Ne(!0))},[dn,Te]),i.useEffect(()=>{if(!(Te||!ke||!Gt||!Bt||ps||ze)){if($.current){he.current=!0;return}return te.current&&clearTimeout(te.current),te.current=setTimeout(()=>{te.current=null,je.current?.()},500),()=>{te.current&&clearTimeout(te.current)}}},[Te,ke,Gt,Bt,ps,ze,H,ve,ie,j,ee]);const es=i.useCallback(async()=>{for(te.current&&(clearTimeout(te.current),te.current=null),$.current?he.current=!0:Bt&&Gt&&await je.current?.();$.current||he.current;)await new Promise(r=>window.setTimeout(r,0));xe.current&&t()},[t,Bt,Gt]),un=i.useCallback(async r=>{if(r!==ee){if(te.current&&(clearTimeout(te.current),te.current=null),Bt&&Gt||$.current){if($.current)for(he.current=!0;$.current||he.current;)await new Promise(g=>window.setTimeout(g,0));else if(!await je.current?.())return;if(!xe.current)return}rt(r)}},[ee,Bt,Gt]);P.current=r=>{un(r)},i.useEffect(()=>()=>{te.current&&(clearTimeout(te.current),te.current=null),!$.current&&Me.current.dirty&&Me.current.changed&&je.current?.()},[]),i.useEffect(()=>{if(!R)return;const r=g=>{g.key==="Escape"&&!hs&&es()};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[R,es,hs]);const ts=i.useMemo(()=>Tp(ee),[ee]),pn=i.useMemo(()=>Ap(ee),[ee]),gn=i.useMemo(()=>{const r=On.find(g=>g.id===ee);return r?b(r.labelKey,r.label):ee},[ee,b]),Tc=i.useCallback(async()=>{if(!(ft||!ts)){Ks(!0);try{if(ts.scope==="global"){const r={};for(const g of ts.keys)r[g]=xu[g]??null;await ls(r)}else{const r={};for(const g of ts.keys)r[g]=null;await yn(r,a)}await Zt(!1),s(b("settings.reset.menuResetSuccess","{{section}} settings reset to defaults",{section:gn}),"success"),Os(!1)}catch(r){s(De(r),"error")}finally{Ks(!1)}}},[ft,ts,a,Zt,s,b,gn]),Ac=i.useCallback(async()=>{if(!ft){Ks(!0);try{const r={};for(const g of Mp)r[g]=null;await yn(r,a),await Zt(!1),s(b("settings.reset.allProjectResetSuccess","All project settings reset to defaults"),"success"),Os(!1)}catch(r){s(De(r),"error")}finally{Ks(!1)}}},[ft,a,Zt,s,b]),ss=i.useCallback(()=>{ft||Os(!1)},[ft]),Mc=i.useCallback(r=>{r.target===r.currentTarget&&ss()},[ss]);i.useEffect(()=>{if(!hs)return;const r=g=>{g.key==="Escape"&&(g.stopPropagation(),ss())};return document.addEventListener("keydown",r,!0),()=>document.removeEventListener("keydown",r,!0)},[hs,ss]);const Rc=i.useCallback(async()=>{try{await Au(ut,Va,a),qs(!1),s(b("settings.memory.memorySaved","Memory saved"),"success")}catch(r){s(De(r)||"Failed to save memory","error")}},[ut,Va,a,s]),Ec=i.useCallback(async()=>{Kl(!0);try{const{path:r,content:g}=await Mu(ut,a),C=r??ut;ut!==C&&(en.current=!0),Xa(C),zs(g),qs(!1);const{files:O}=await vr(a);Dl(O),s(b("settings.memory.memoryCompacted","Memory file compacted"),"success")}catch(r){s(De(r)||"Failed to compact memory","error")}finally{Kl(!1)}},[ut,a,s]),Dc=i.useCallback(async()=>{Fl(!0),Ll(null);try{const r=await Ru(Za,a);Ll(r),s(r.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",r.qmdAvailable?"success":"warning")}catch(r){s(De(r)||"Failed to test memory retrieval","error")}finally{Fl(!1)}},[Za,a,s]),Fc=i.useCallback(async()=>{Ol(!0);try{await Eu(a),s(b("settings.memory.dreamCompleted","Dream processing completed"),"success")}catch(r){s(r instanceof Error?r.message:"Failed to run dream processing","error")}finally{Ol(!1)}},[a,s]),Lc=i.useCallback(async()=>{Bl(!0);try{const r=await Du(a);await _l(),s(r.qmdAvailable?b("settings.memory.qmdInstalled","qmd installed successfully"):b("settings.memory.qmdInstallUnavailable","qmd install finished, but qmd is still unavailable"),r.qmdAvailable?"success":"warning")}catch(r){s(De(r)||b("settings.memory.qmdInstallFailed","Failed to install qmd"),"error")}finally{Bl(!1)}},[a,_l,s]),Oc=()=>{if(!ze)return;const r=ze.name.trim();if(!r){s(b("settings.models.presetNameRequired","Preset name is required"),"error");return}const g=H.modelPresets||[];let C;ks?C=ks:C=Pu(r,g);const O={id:C,name:r,executorProvider:ze.executorProvider,executorModelId:ze.executorModelId,...ze.executorCredentialInstanceId?{executorCredentialInstanceId:ze.executorCredentialInstanceId}:{},validatorProvider:ze.validatorProvider,validatorModelId:ze.validatorModelId,...ze.validatorCredentialInstanceId?{validatorCredentialInstanceId:ze.validatorCredentialInstanceId}:{}};Z(Q=>{const J=Q.modelPresets||[],ge=ks?J.map(ye=>ye.id===ks?O:ye):[...J,O];return{...Q,modelPresets:ge}}),jl(null),wl(null)},Kc=i.useCallback(async(r,g)=>{Cl(r);try{await g(),await Js()}catch(C){s(De(C)||`Failed to ${r}`,"error")}finally{Cl(null)}},[s,Js]),Bc=i.useCallback(()=>{if(typeof navigator<"u"&&navigator.userAgent.includes("Windows"))return"winget install Cloudflare.cloudflared";const r=typeof navigator<"u"?navigator.platform:"",g=typeof navigator<"u"?navigator.userAgent:"",C=/(Mac|iPhone|iPad|iPod)/i.test(r),O=/(arm64|aarch64)/i.test(`${r} ${g}`);return C?"brew install cloudflared":`curl -L --output /tmp/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${O?"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`},[]),Gc=i.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`,[]),Hc=i.useCallback(async()=>{Sl(!0),qa(null);try{const r=await yp(a);if(!r.success){qa(r.error??b("settings.remote.installationFailed","Installation failed"));return}const g=await jn(a);$s(g),s(b("settings.remote.cloudflaredInstalled","cloudflared installed successfully"),"success")}catch(r){qa(r instanceof Error?r.message:b("settings.remote.installationFailed","Installation failed"))}finally{Sl(!1)}},[s,a]),_c=()=>{switch(ee){case"cli-agents":return e.jsx(wm,{projectId:a,addToast:s});case"general":return e.jsx(Fg,{form:H,setForm:Z,projectId:a,addToast:s,prefixError:ps,setPrefixError:Li,onQuickChatButtonModeChange:w,onMobileNavPrimaryItemsChange:f});case"source-control":return e.jsx(sh,{form:H,setForm:Z,projectTrackingRepoOptions:Po,projectTrackingRepoLoading:Io,projectTrackingRepoError:To});case"source-control-global":return e.jsx(ah,{form:H,setForm:Z,globalSettings:ie,onGlobalSourceControlSettingsChange:r=>Ee(g=>({gitlabEnabled:g?.gitlabEnabled,gitlabInstanceUrl:g?.gitlabInstanceUrl,gitlabApiBaseUrl:g?.gitlabApiBaseUrl,gitlabAuthToken:g?.gitlabAuthToken,gitlabAuthTokenType:g?.gitlabAuthTokenType,reportRoadmapDedupeEnabled:g?.reportRoadmapDedupeEnabled,reportRoadmapLabel:g?.reportRoadmapLabel,reportRoadmapRepo:g?.reportRoadmapRepo,...r})),globalTrackingRepoOptions:Ao,globalTrackingRepoLoading:Mo,globalTrackingRepoError:Ro});case"global-general":return e.jsx(Hp,{form:H,setForm:Z});case"keyboard-shortcuts":return e.jsx(Up,{form:H,setForm:Z});case"global-models":return e.jsx(lg,{form:H,setForm:Z,availableModels:fl,modelsLoading:vl,globalModelLanes:ql.filter(r=>r.laneId!=="default"),getLaneThinkingValue:r=>Vl(r,"global"),updateLaneThinkingValue:(r,g)=>on(r,g,"global"),resetLaneThinkingValue:r=>Yl(r,"global"),favoriteProviders:Qt,favoriteModels:Jt,onToggleFavorite:$l,onToggleModelFavorite:zl,addToast:s,projectId:a});case"secrets":return e.jsx(Tg,{addToast:s,projectId:a});case"global-mcp":return e.jsx(Zp,{form:Y("global"),setForm:de("global"),projectId:a,addToast:s});case"mcp":return e.jsx(hh,{form:Y("project"),setForm:de("project"),globalSettings:ve?.global??null,projectId:a,addToast:s});case"project-models":return e.jsx(Hg,{form:H,setForm:Z,projectId:a,addToast:s,onOpenWorkflowSettings:S,registerWorkflowLaneSaver:Ie,onWorkflowLanesChange:ce,models:{modelLanes:ql,getLaneStatus:rn,getLaneValue:cc,updateLaneValue:dc,resetLaneValue:uc,getLaneThinkingValue:Vl,updateLaneThinkingValue:on,resetLaneThinkingValue:Yl,availableModels:fl,modelsLoading:vl,favoriteProviders:Qt,favoriteModels:Jt,onToggleFavorite:$l,onToggleModelFavorite:zl,editingPresetId:ks,setEditingPresetId:jl,presetDraft:ze,setPresetDraft:wl,onSavePresetDraft:Oc,confirmDelete:V}});case"appearance":return e.jsx(Op,{form:H,setForm:Z,themeMode:o,colorTheme:d,dashboardFontScalePct:l,shadcnCustomColors:h,resolvedThemeMode:p,onThemeModeChange:u,onColorThemeChange:c,onDashboardFontScaleChange:m,onShadcnCustomColorsChange:x,sessionBannersHidden:Oe,setSessionBannersHidden:Nu});case"scheduling":return e.jsx(Ug,{form:H,setForm:Z,concurrencyLoading:Te,onOverlapIgnorePathChange:Sc,onOpenOverlapPathPicker:pc,onRemoveOverlapIgnorePath:Nc,onAddOverlapIgnorePath:Pc,onOpenWorkflowSettings:S});case"scheduled-evals":return e.jsx(zg,{form:H,setForm:Z});case"node-routing":return e.jsx(Vg,{form:H,setForm:Z,nodes:Qi});case"worktrees":return e.jsx(Yg,{form:H,setForm:Z,gitRemotes:Pl,worktrunkInstall:Dt,worktrunkInstallVerified:os,onOpenWorktreesDirPicker:mc,onWorktreeCopyFileChange:jc,onRemoveWorktreeCopyFile:wc,onAddWorktreeCopyFile:Cc,onOpenWorktreeCopyFilePicker:vc,onOpenApprovals:N});case"commands":return e.jsx(Qg,{form:H,setForm:Z});case"merge":return e.jsx(eh,{form:H,setForm:Z,integrationBranchOptions:Co,integrationBranchCustomMode:So,setIntegrationBranchCustomMode:No,onOpenWorkflowSettings:S,gitRemoteOptions:Pl.map(r=>r.name),projectId:a});case"config-versions":return e.jsx(bh,{projectId:a,onSettingsRefresh:()=>Zt(!1)});case"agent-permissions":return e.jsx(lh,{form:H,setForm:Z});case"memory":return e.jsx(ch,{form:H,setForm:Z,memory:{memoryCapabilities:Wo,memoryBackendStatus:Uo,memoryBackendLoading:$o,memoryBackendError:zo,memoryFiles:Eo,selectedMemoryPath:ut,setSelectedMemoryPath:Xa,memoryContent:Va,setMemoryContent:zs,memoryLoading:wo,memoryDirty:Ya,setMemoryDirty:qs,memoryTestQuery:Za,setMemoryTestQuery:Do,memoryTestLoading:Fo,memoryTestResult:Lo,qmdInstallLoading:Bo,dreamRunning:Oo,memoryCompactLoading:Ko,onInstallQmd:Lc,onTestMemoryRetrieval:Dc,onDreamNow:Fc,onCompactMemory:Ec,onSaveMemory:Rc}});case"research-global":return e.jsx(Wp,{form:H,setForm:Z,authProviders:Nt,onNavigateToSection:rt});case"research-project":return e.jsx(dh,{form:H,setForm:Z,researchLimitError:Oi});case"voice-input":return e.jsx(gh,{form:H,setForm:Z});case"cli-binary":return e.jsx($g,{});case"experimental":return e.jsx(Kp,{form:H,setForm:Z,knownFeatures:ym,legacyAliases:ja,getCanonicalKey:el,isFeatureEnabled:km,hiddenFeatureKeys:vm});case"backups-global":return e.jsx(fh,{form:H,setForm:Z,backupInfo:oo,backupLoading:co,onBackupNow:lc});case"backups":return e.jsx(mh,{form:H,setForm:Z});case"notifications":return e.jsx(Gp,{form:H,setForm:Z,testNotificationLoading:ro,testNotificationResult:io,onTestProviderNotification:nc});case"node-sync":return e.jsx(Bp,{form:H,setForm:Z});case"remote":return e.jsx($p,{form:H,setForm:Z,remote:{projectId:a,addToast:s,remoteStatus:dt,externalTunnel:$a,tunnelShareLink:jo,remoteBusyAction:uo,cloudflaredInstalling:po,cloudflaredInstallError:go,cloudflaredManualInstallCommand:Bc,cloudflaredMacFallbackCommand:Gc,handleInstallCloudflared:Hc,runRemoteAction:Kc,remoteShortLivedToken:ko,setRemoteShortLivedToken:xo,remoteAuthLinkTokenType:ho,setRemoteAuthLinkTokenType:mo,remoteUrlPreview:bo,setRemoteUrlPreview:fo,remoteQrSvg:yo,setRemoteQrSvg:vo}});case"prompts":return e.jsx(Dg,{form:H,setForm:Z,onOpenWorkflowSettings:S});case"plugins":return e.jsx(kh,{projectId:a,addToast:s,activePluginsSubsection:Ms,setActivePluginsSubsection:Rs,onPluginsChanged:Ye});case"authentication":return e.jsx(hg,{auth:{projectId:a,addToast:s,authProviders:Nt,authLoading:Zi,authActionInProgress:eo,apiKeyInputs:Ga,setApiKeyInputs:Ha,apiKeyErrors:no,opencodeApiKeyRefreshStatus:lo,deviceCodes:La,loginInstructions:to,manualCodeConfigs:so,manualCodeInputs:Oa,setManualCodeInputs:Ka,manualCodeSubmitInProgress:ao,loadAuthStatus:We,handleLogin:Xo,handleLogout:tc,handleCancelLogin:ec,handleSaveApiKey:sc,handleClearApiKey:ac,handleSubmitManualCode:Zo,onReopenOnboarding:E},form:H,setForm:Z});case"hermes-runtime":return e.jsx(Ng,{});case"openclaw-runtime":return e.jsx(Pg,{});case"paperclip-runtime":return e.jsx(Ig,{})}};return(r=>F?e.jsx("div",{className:"settings-embedded right-dock-embedded-view","data-testid":"settings-view",role:"region","aria-label":b("settings.title","Settings"),children:r}):e.jsx(Su,{windowKey:"settings",title:b("settings.title","Settings"),ariaLabel:b("settings.title","Settings"),onClose:()=>void es(),hideHeader:!0,dragHandleSelector:".settings-modal > .modal-header",className:"floating-window--settings",defaultSize:{width:1100,height:720},minSize:{width:520,height:480},persistGeometryKey:"floating-window:settings",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:T,children:r}))(e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:F?"modal modal-lg settings-modal settings-modal--embedded":"modal modal-lg settings-modal",style:F?void 0:M,children:[e.jsxs("div",{className:F?"modal-header modal-header--embedded":"modal-header",children:[e.jsx("div",{className:"settings-modal-heading",children:e.jsxs("h3",{children:[F&&e.jsx(ju,{size:20,"aria-hidden":"true"}),e.jsx("span",{children:b("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":b("settings.header.starFusion","Star Fusion on GitHub"),title:b("settings.header.starFusion","Star Fusion on GitHub"),onClick:Fi,"data-clicked":Di?"true":"false",children:[e.jsxs("span",{className:"settings-github-star-btn__action",children:[e.jsx(jt,{provider:"github",size:"sm"}),e.jsx(wu,{size:11,"aria-hidden":"true"}),b("settings.header.star","Star")]}),us!==null&&e.jsx("span",{className:"settings-github-star-btn__count","aria-label":`${us.toLocaleString()} stars`,children:us>=1e3?`${(us/1e3).toFixed(1)}k`:us.toLocaleString()})]}),e.jsxs("a",{href:"https://discord.gg/ksrfuy7WYR",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-header-discord-btn","aria-label":b("settings.header.joinDiscord","Join our Discord"),title:b("settings.header.joinDiscord","Join our Discord"),children:[e.jsx(am,{size:13}),b("settings.header.discord","Discord")]})]}),!F&&e.jsx("button",{className:"modal-close",onClick:()=>void es(),"aria-label":b("actions.close","Close"),children:"×"}),F&&X==="mobile"&&e.jsx("button",{className:"modal-close settings-embedded-mobile-close",onClick:()=>void es(),"aria-label":b("actions.close","Close"),children:"×"})]}),Te?e.jsx("div",{className:"settings-empty-state settings-loading",children:e.jsx(Et,{label:b("settings.loading","Loading…")})}):e.jsxs("div",{className:"settings-layout",children:[e.jsxs("aside",{className:"settings-navigation","aria-label":b("settings.search.navigationLabel","Settings navigation"),style:qo,children:[y&&e.jsx("div",{className:"settings-mobile-section-picker",children:e.jsxs("div",{className:"settings-mobile-section-picker-control-row",children:[fs?e.jsx("select",{id:"settings-mobile-section","aria-label":b("settings.mobileNav.label","Settings Section"),className:"select touch-target",value:ee,onChange:r=>void un(r.target.value),children:St.map((r,g)=>{if(!r.isGroupHeader)return null;const C=St.slice(g+1).filter(J=>!J.isGroupHeader),O=St.slice(g+1).findIndex(J=>J.isGroupHeader),Q=O===-1?C:C.slice(0,O);return Q.length===0?null:e.jsx("optgroup",{label:b(r.labelKey,r.label),children:Q.map(J=>{const ge=b(J.labelKey,J.label);return e.jsx("option",{value:J.id,children:fm(J,ge)},J.id)})},r.id)})}):e.jsx("p",{className:"settings-search-empty-hint",children:b("settings.search.noMobileOptions","No sections match this search.")}),pl&&e.jsx("button",{type:"button",className:"btn btn-sm btn-icon settings-search-toggle",onClick:()=>Ri(r=>!r),"aria-expanded":Hs,"aria-controls":"settings-search-row-region","aria-label":Hs?b("settings.search.toggleHide","Hide search"):b("settings.search.toggleShow","Show search"),children:Hs?e.jsx(li,{size:16}):e.jsx(Hn,{size:16})})]})}),e.jsxs("label",{className:"settings-advanced-toggle",children:[e.jsx("input",{type:"checkbox",checked:qt,onChange:r=>Vt(r.target.checked)}),e.jsx("span",{children:b("settings.advanced.toggle","Advanced settings")})]}),Hs&&e.jsx("div",{className:"settings-search","data-testid":"settings-search",children:e.jsxs("div",{id:"settings-search-row-region",className:"settings-search-row",children:[e.jsx("label",{className:"settings-search-label",htmlFor:"settings-search-input",children:b("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:Xe,onChange:r=>Ze(r.target.value),onKeyDown:r=>{r.key==="Escape"&&bs&&(r.stopPropagation(),Ze(""))},placeholder:b("settings.search.placeholder","Search by setting or section"),"aria-describedby":"settings-search-results"}),bs&&e.jsx("button",{type:"button",className:"btn btn-sm settings-search-clear",onClick:()=>Ze(""),"aria-label":b("settings.search.clear","Clear settings search"),children:b("actions.clear","Clear")})]}),e.jsx("div",{id:"settings-search-results",className:"settings-search-results","aria-live":"polite",children:bs?Ct.length>0?b("settings.search.settingResultCount",{count:Ct.length}):b("settings.search.resultCount",{count:ul.length}):b("settings.search.allSections","Showing all settings sections")}),Ct.length>0&&e.jsxs("ul",{className:"settings-search-hits","data-testid":"settings-search-hits",children:[Ct.slice(0,Ln).map(r=>{const g=ct.find(C=>C.id===r.sectionId);return e.jsx("li",{children:e.jsxs("button",{type:"button",className:"settings-search-hit","data-testid":`settings-search-hit-${r.key}`,onClick:()=>Ji(r.sectionId,r.key),children:[e.jsx("span",{className:"settings-search-hit-label",children:r.label}),g&&e.jsx("span",{className:"settings-search-hit-section",children:b(g.labelKey,g.label)})]})},`${r.sectionId}:${r.key}`)}),Ct.length>Ln&&e.jsx("li",{className:"settings-search-hits-more",children:b("settings.search.moreResults","{{count}} more — keep typing to narrow",{count:Ct.length-Ln})})]})]})}),e.jsx("nav",{className:"settings-sidebar",children:fs?St.map(r=>r.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:b(r.labelKey,r.label)},r.id):e.jsxs("button",{className:`settings-nav-item${ee===r.id?" active":""}`,onClick:()=>void un(r.id),title:r.scope==="global"?b("settings.nav.tooltip.global","Shared across all projects"):r.scope==="project"?b("settings.nav.tooltip.project","Specific to this project"):void 0,children:[r.icon?e.jsx(r.icon,{className:"settings-scope-icon","aria-label":r.scope==="project"?b("settings.nav.aria.project","Project setting"):b("settings.nav.aria.global","Global setting"),size:16}):e.jsxs(e.Fragment,{children:[r.scope==="global"&&e.jsx(ba,{className:"settings-scope-icon","aria-label":b("settings.nav.aria.global","Global setting"),size:16}),r.scope==="project"&&e.jsx(Cu,{className:"settings-scope-icon","aria-label":b("settings.nav.aria.project","Project setting"),size:16})]}),b(r.labelKey,r.label)]},r.id)):e.jsxs("div",{className:"settings-search-empty",role:"status",children:[e.jsx("p",{children:b("settings.search.noResults",'No settings sections match "{{query}}".',{query:Xe.trim()})}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Ze(""),children:b("settings.search.clear","Clear settings search")})]})})]}),Pt&&e.jsx("div",{className:"settings-nav-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":b("settings.nav.resize","Resize settings navigation"),"aria-valuemin":Ni,"aria-valuemax":Pi,"aria-valuenow":q,tabIndex:0,onPointerDown:Vo,onKeyDown:Yo}),e.jsx("div",{className:"settings-content",ref:se,"data-show-advanced":qt?"true":"false",children:fs?e.jsx(Ku,{highlightedKey:$t,children:_c()}):e.jsxs("div",{className:"settings-empty-state settings-search-content-empty",role:"status",children:[e.jsx("p",{children:b("settings.search.noResults",'No settings sections match "{{query}}".',{query:Xe.trim()})}),e.jsx("button",{type:"button",className:"btn",onClick:()=>Ze(""),children:b("settings.search.clear","Clear settings search")})]})})]}),X==="mobile"&&ln&&e.jsx("div",{className:"settings-modal-footer-update-row",children:ln}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"settings-modal-footer-version",children:[e.jsx("a",{href:"https://github.com/Runfusion/Fusion/discussions",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-footer-help-btn","aria-label":b("settings.footer.helpDiscussions","Help and discussions"),title:b("settings.footer.helpDiscussions","Help and discussions"),children:b("settings.footer.help","Help")}),e.jsxs("div",{className:"settings-update-check",children:[Ot&&e.jsxs("button",{type:"button",className:"settings-version-check-btn",onClick:()=>{Qo()},disabled:tl,"aria-label":b("settings.footer.checkUpdates","Check for updates"),title:b("settings.footer.checkUpdates","Check for updates"),children:[e.jsx("span",{className:"settings-modal-version",children:X==="mobile"?b("settings.footer.versionShort","v{{version}}",{version:Ot}):b("settings.footer.version","Version {{version}}",{version:Ot})}),e.jsx(Ts,{size:12,className:tl?"spinning":void 0})]}),X!=="mobile"&&ln]})]}),e.jsxs("div",{className:"modal-actions-left",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:rc,title:b("settings.importExport.exportTitle","Export settings to JSON file"),children:b("settings.importExport.exportBtn","Export")}),e.jsx("input",{type:"file",ref:Hl,accept:".json,application/json",style:{display:"none"},onChange:ic}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Hl.current?.click(),disabled:Ys,title:b("settings.importExport.importTitleAttr","Import settings from JSON file"),children:Ys?b("settings.importExport.loadingFile","Loading…"):b("settings.importExport.importBtn","Import")}),e.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"settings-reset",onClick:()=>Os(!0),disabled:Te,title:b("settings.reset.buttonTitle","Reset settings to their defaults"),children:X==="mobile"?b("settings.reset.buttonShort","Reset"):b("settings.reset.button","Reset Settings")})]}),!F&&e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("span",{className:"settings-autosave-status",role:"status",children:D==="saving"?b("settings.general.saving","Saving…"):D==="saved"?b("settings.general.saved","Saved"):D==="error"?b("settings.general.saveFailed","Could not save"):null}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void es(),disabled:Te,children:b("settings.actions.close","Close")})]})]})]}),it!==null&&e.jsx("div",{className:"modal-overlay open",onClick:hc,role:"dialog","aria-modal":"true","aria-label":b("settings.scheduling.browseWorkspacePath","Browse workspace path"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:r=>r.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:b("settings.scheduling.selectIgnoredOverlapPath","Select ignored overlap path")}),e.jsx("button",{className:"modal-close",onClick:It,"aria-label":b("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:b("settings.scheduling.overlapPickerNote","Choose a file to ignore directly, or navigate into a folder and select the current directory.")}),e.jsx(vn,{entries:Ki,currentPath:yt,onSelectFile:cn,onNavigate:Aa,loading:Bi,error:Gi,onRetry:Hi,workspace:"project",projectId:a})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[b("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:yt==="."?b("settings.fileBrowser.projectRoot","(project root)"):yt})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:It,children:b("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:gc,disabled:yt===".",children:b("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),il&&e.jsx("div",{className:"modal-overlay open",onClick:yc,role:"dialog","aria-modal":"true","aria-label":b("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:r=>r.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:b("settings.worktrees.selectWorktreesDir","Select worktrees directory")}),e.jsx("button",{className:"modal-close",onClick:Tt,"aria-label":b("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:b("settings.worktrees.worktreesPickerNote","Navigate to the folder where Fusion should create task worktrees, then select the current directory.")}),e.jsx(vn,{entries:_i,currentPath:vt,onSelectFile:bc,onNavigate:Ma,loading:Ui,error:Wi,onRetry:$i,workspace:"project",projectId:a})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[b("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:vt==="."?b("settings.fileBrowser.projectRoot","(project root)"):vt})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:Tt,children:b("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:fc,children:b("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),ot!==null&&e.jsx("div",{className:"modal-overlay open",onClick:xc,role:"dialog","aria-modal":"true","aria-label":b("settings.worktrees.browseCopyFile","Browse file to copy into new worktrees"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:r=>r.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:b("settings.worktrees.selectCopyFile","Select file to copy")}),e.jsx("button",{className:"modal-close",onClick:At,"aria-label":b("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:b("settings.worktrees.copyFilePickerNote","Choose a repository file to copy into each newly assigned task worktree. Directories are not selected from this picker.")}),e.jsx(vn,{entries:zi,currentPath:Ra,onSelectFile:kc,onNavigate:Ea,loading:qi,error:Vi,onRetry:Yi,workspace:"project",projectId:a})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[b("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:Ra==="."?b("settings.fileBrowser.projectRoot","(project root)"):Ra})]})}),e.jsx("div",{className:"modal-actions-right",children:e.jsx("button",{className:"btn btn-sm",onClick:At,children:b("settings.actions.cancel","Cancel")})})]})]})}),Go&&pt&&e.jsx("div",{className:"modal-overlay open",onClick:r=>r.target===r.currentTarget&&xs(!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:b("settings.importExport.importTitle","Import Settings")}),e.jsx("button",{className:"modal-close",onClick:()=>xs(!1),"aria-label":b("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:b("settings.importExport.reviewPrompt","Review the settings to be imported:")}),pt.global&&Object.keys(pt.global).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:b("settings.importExport.globalSettings","Global Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(pt.global).filter(([,r])=>r!==void 0).map(([r])=>e.jsx("li",{children:r},r))})]}),pt.project&&Object.keys(pt.project).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:b("settings.importExport.projectSettings","Project Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(pt.project).filter(([,r])=>r!==void 0).map(([r])=>e.jsx("li",{children:r},r))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"import-scope",children:b("settings.importExport.importScope","Import Scope:")}),e.jsxs("select",{id:"import-scope",value:sn,onChange:r=>Ho(r.target.value),children:[e.jsx("option",{value:"both",children:b("settings.importExport.scopeBoth","Both global and project settings")}),e.jsx("option",{value:"global",children:b("settings.importExport.scopeGlobal","Global settings only")}),e.jsx("option",{value:"project",children:b("settings.importExport.scopeProject","Project settings only")})]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-field-label-row",children:[e.jsxs("label",{htmlFor:"import-merge",className:"checkbox-label",children:[e.jsx("input",{id:"import-merge",type:"checkbox",checked:an,onChange:r=>_o(r.target.checked)}),b("settings.importExport.mergeExisting","Merge with existing settings (recommended)")]}),e.jsx(G,{settingKey:"import-merge",children:b("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:()=>xs(!1),children:b("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:oc,disabled:Ys,children:Ys?b("settings.importExport.importing","Importing…"):b("settings.importExport.confirmImport","Confirm Import")})]})]})}),hs&&e.jsx("div",{className:"modal-overlay open",onClick:Mc,role:"dialog","aria-modal":"true","aria-label":b("settings.reset.dialogAriaLabel","Reset settings"),"data-testid":"settings-reset-dialog",children:e.jsxs("div",{className:"modal modal-md settings-reset-dialog",onClick:r=>r.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:b("settings.reset.dialogTitle","Reset Settings")}),e.jsx("button",{className:"modal-close",onClick:ss,"aria-label":b("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:b("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 Tc(),disabled:ft||!ts,title:pn,children:b("settings.reset.resetMenuAction","Reset this menu ({{section}})",{section:gn})}),pn&&e.jsx("small",{className:"settings-reset-dialog__ineligible-reason",children:pn})]}),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 Ac(),disabled:ft,children:b("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:ss,disabled:ft,children:b("settings.actions.cancel","Cancel")})})})]})})]}))}function Gm(t){return e.jsx(Cm,{presentation:"embedded",...t})}export{Zr as ADVANCED_SETTINGS_SECTION_IDS,xi as GITHUB_STAR_CACHE_KEY,ji as GITHUB_STAR_CACHE_TTL_MS,On as SETTINGS_SECTIONS,Cm as SettingsModal,Gm as SettingsView,hm as filterSettingsSectionsForSearch,Ai as normalizeSettingsSearchText,gm as sectionMatchesSettingsSearch,im as useGitHubStarCount};
|