@runfusion/fusion 0.47.0 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +153 -85
- package/dist/client/.vite/manifest.json +242 -242
- package/dist/client/assets/{AgentDetailView-D9lYcdOS.js → AgentDetailView-CF6isJ51.js} +1 -1
- package/dist/client/assets/{AgentPermissionPolicyEditor-Bn_PEeQW.js → AgentPermissionPolicyEditor-DFldf6aS.js} +1 -1
- package/dist/client/assets/{AgentsView-BRbnFmv3.js → AgentsView-DiGseTuo.js} +3 -3
- package/dist/client/assets/{ChatView-Batci7-w.js → ChatView-BjQBbDyo.js} +1 -1
- package/dist/client/assets/{CommandCenter-DAUgvVMX.js → CommandCenter-DwpiADSX.js} +1 -1
- package/dist/client/assets/{DevServerView-HdEXR5UB.js → DevServerView-D6RFaGPU.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-DrCiUJlF.js → DirectoryPicker-DNBB-viz.js} +1 -1
- package/dist/client/assets/{DocumentsView-C0KxPWex.js → DocumentsView-DXG-sctG.js} +1 -1
- package/dist/client/assets/{EvalsView-wCfi9Rkj.js → EvalsView-Ol6ECKz5.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-Crck6eJe.js → ExperimentalAgentOnboardingModal-BQc3GaE_.js} +1 -1
- package/dist/client/assets/{GoalsView-sFGHX3Wt.js → GoalsView-C_m90anC.js} +1 -1
- package/dist/client/assets/{InsightsView-jl0cX1um.js → InsightsView-BbFgPsDH.js} +1 -1
- package/dist/client/assets/{MemoryView-Bwv99M_s.js → MemoryView-CRS7AjWK.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-BsA3tCZh.js → PiExtensionsManager-BEj5xu45.js} +1 -1
- package/dist/client/assets/{PluginManager-Bgd8Hj0a.js → PluginManager-CzCM3XUY.js} +1 -1
- package/dist/client/assets/{PullRequestView-CqO16SNt.js → PullRequestView-9yNYCunb.js} +1 -1
- package/dist/client/assets/{ResearchView-CfRsbJWS.js → ResearchView-BKdirpiw.js} +1 -1
- package/dist/client/assets/{SecretsView-CHomYGnm.js → SecretsView-qGjo-0Cp.js} +1 -1
- package/dist/client/assets/{SessionTerminal-DcYUuwbV.js → SessionTerminal-C7YlkdGJ.js} +1 -1
- package/dist/client/assets/{SettingsModal-CX5GLed_.js → SettingsModal-DihNd7g8.js} +1 -1
- package/dist/client/assets/{SettingsModal-ybSf6HDn.js → SettingsModal-DpaptT6t.js} +3 -3
- package/dist/client/assets/{SetupWizardModal-D2BQL0df.js → SetupWizardModal-MovTj5pY.js} +2 -2
- package/dist/client/assets/{ShadcnColorPicker-B-8x0Gci.js → ShadcnColorPicker-Bnf5n5R4.js} +1 -1
- package/dist/client/assets/{SkillsView-4iqYHf9N.js → SkillsView-Br2LkA3x.js} +1 -1
- package/dist/client/assets/{TodoView-BJsknVS6.js → TodoView-BEdk6FTU.js} +1 -1
- package/dist/client/assets/{WorkflowNodeEditor-QdwW4bY5.js → WorkflowNodeEditor-e-eR6yzw.js} +1 -1
- package/dist/client/assets/{agentSkills-CwR8s-gl.js → agentSkills-D5nDZPRY.js} +1 -1
- package/dist/client/assets/{app-BJGkp7Tt.js → app-BM6bAO0b.js} +1 -1
- package/dist/client/assets/{app-CZQ_fFNf.js → app-BglOELbc.js} +1 -1
- package/dist/client/assets/{app-BaoNC9zg.js → app-ChkCVQpq.js} +1 -1
- package/dist/client/assets/{app-DgezOJub.js → app-DMn7Jt9g.js} +1 -1
- package/dist/client/assets/{app-DAu3AzsS.js → app-D_IT9Buz.js} +1 -1
- package/dist/client/assets/{app-BKLUvvm8.js → app-S8fehQv8.js} +1 -1
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-rav0thhm.js → architectureDiagram-3BPJPVTR-BbkXWBni.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-x9Opikul.js → blockDiagram-GPEHLZMM-DhaqpHqZ.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-BGrWtNPI.js → c4Diagram-AAUBKEIU-qC0WSHMZ.js} +1 -1
- package/dist/client/assets/channel-CCKvUami.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-BMFvL-OW.js → chunk-2J33WTMH-Dah9zMeT.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-CWTOrH7n.js → chunk-4BX2VUAB-epHwnUb_.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-l48k3a4l.js → chunk-55IACEB6-DpYBy44g.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-DeynG6ym.js → chunk-727SXJPM-B9b8698e.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-B9ndyq3h.js → chunk-AQP2D5EJ-DrM8nnhR.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-DV2d1-q1.js → chunk-FMBD7UC4-jyT6Scwe.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-D0Dl37Mc.js → chunk-ND2GUHAM-EoPfF-PK.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-NGiOWxhM.js → chunk-QZHKN3VN-qMwLVfgJ.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-C_HqY7AI.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-C_HqY7AI.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-2ojNpRS8.js → cose-bilkent-S5V4N54A-DmPFKoVD.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-BaIP71Bo.js → dagre-BM42HDAG-DeHxd-ej.js} +1 -1
- package/dist/client/assets/{dashboard-view-hB7ta6sK.js → dashboard-view-Cw5mMJay.js} +1 -1
- package/dist/client/assets/{dashboard-view-CC2QtNhx.js → dashboard-view-DXjNQ5IF.js} +1 -1
- package/dist/client/assets/{diagram-2AECGRRQ-DQfEScya.js → diagram-2AECGRRQ-C04A2mhr.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-B5iw3WNT.js → diagram-5GNKFQAL-DqtOwADI.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-C5mMn4JH.js → diagram-KO2AKTUF-CH0har-Z.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-CaMhdmPl.js → diagram-LMA3HP47-CxN-U-0W.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-D2ed8-Fx.js → diagram-OG6HWLK6-42A7wpwF.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-CZl07SyK.js → erDiagram-TEJ5UH35-CnZI5YlN.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-Dz7RLhaG.js → flowDiagram-I6XJVG4X-BKfQhMVF.js} +1 -1
- package/dist/client/assets/{folder-open-DCNfEqr1.js → folder-open-STXgbemw.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-C3ny-S6Q.js → ganttDiagram-6RSMTGT7-BfA0pME8.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII-BjHF5C7t.js → gitGraphDiagram-PVQCEYII-BgDFB7PS.js} +1 -1
- package/dist/client/assets/index-BnfnLXyO.css +1 -0
- package/dist/client/assets/index-CHy0WNjH.js +1301 -0
- package/dist/client/assets/{infoDiagram-5YYISTIA-BTYecWEx.js → infoDiagram-5YYISTIA-Bb5F155s.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-BBNOAxJa.js → ishikawaDiagram-YF4QCWOH-8Oati7l_.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-DrjdbyT5.js → journeyDiagram-JHISSGLW-DhHTHXTM.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-CgTNTfT7.js → kanban-definition-UN3LZRKU-BWB9EtUX.js} +1 -1
- package/dist/client/assets/{mermaid.core-CyFmJxTj.js → mermaid.core-BD-L2gUQ.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-C95r0KZv.js → mindmap-definition-RKZ34NQL-BSKGd7LE.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-CmYuIsZ-.js → pieDiagram-4H26LBE5-BtBFPvSW.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-BFLFwHMa.js → quadrantDiagram-W4KKPZXB-aWQWYPto.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-G0s0AfQq.js → requirementDiagram-4Y6WPE33-CprlEpIa.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-D8OLAFhm.js → sankeyDiagram-5OEKKPKP-Cw-AcRAV.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-6fDSosvV.js → sequenceDiagram-3UESZ5HK-BMW5slyv.js} +1 -1
- package/dist/client/assets/{shield-alert-CBAzSycj.js → shield-alert-Bzf8yNOc.js} +1 -1
- package/dist/client/assets/{stateDiagram-AJRCARHV-BfNs5lJU.js → stateDiagram-AJRCARHV-CcxvIVwM.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-Bt0-CBqz.js → stateDiagram-v2-BHNVJYJU-awOfoFOB.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-DmKYLILn.js → timeline-definition-PNZ67QCA-DIEAc2YP.js} +1 -1
- package/dist/client/assets/{upload--9MWYfcA.js → upload-DuwyPTKe.js} +1 -1
- package/dist/client/assets/{users-vOsWas_i.js → users-D1Qhfyro.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-D3jx9PAk.js → vennDiagram-CIIHVFJN-DOkqg5Wi.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-BGRnyThw.js → wardley-L42UT6IY-DoPK1Q6d.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-pwLVIgII.js → wardleyDiagram-YWT4CUSO-l1vun-m2.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-ltxtDdDp.js → xychartDiagram-2RQKCTM6-DcUOUKvl.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 +104 -77
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/package.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/dist/client/assets/channel-BFVfY8Ks.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-pfX_P8V9.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-pfX_P8V9.js +0 -1
- package/dist/client/assets/index-CUY6xXXv.js +0 -1292
- package/dist/client/assets/index-CXlzJfKU.css +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-
|
|
2
|
-
import{r as i,j as e}from"./vendor-react-SZ_qB27O.js";import{c as hl,fk as gl,fl as pl,c2 as bl,fm as Cs,fn as fl,fo as tt,fp as kt,bM as st,fq as vl,fr as xl,fs as yl,ft as jl,fu as ka,dx as nt,h as kl,b7 as wl,fv as Nl,fw as cs,fx as Cl,fy as ds,fz as Sl,fA as Pl,fB as sn,fC as Ss,a6 as wa,al as De,bP as Fe,fD as Al,fE as Ml,fF as Tl,fG as Rl,fH as Il,fI as El,L as Le,q as Fl,I as an,J as nn,aK as Na,P as rn,fJ as Ll,fK as Dl,fL as Ol,fM as Bl,fN as Ps,dv as rt,fO as ln,a8 as on,fP as Gl,fQ as Wl,aw as Ts,fR as _l,fS as Ul,aq as He,fT as Hl,fU as $l,fV as Kl,fW as zl,fX as ql,fY as Vl,fZ as Ca,f_ as Sa,f$ as Yl,dh as xt,dg as us,ad as Ql,o as Xl,ey as Jl,g0 as Zl,g1 as ei,ek as ti,bF as Pa,el as si,g2 as ai,g3 as ni,g4 as ri,bd as li,b6 as ii,_ as cn,ai as oi,ae as dn,dy as ci,b$ as di,W as ui,ce as mi,g5 as hi,g6 as Aa,u as gi,aR as Ma,cM as pi,g7 as Ta,g8 as Ra,bp as ie,g9 as bi,ga as fi,gb as vi,gc as xi,R as Ia,c1 as Ea,gd as Fa,bL as yi,ge as La,gf as ji,gg as ms,gh as ki,gi as wi,gj as Da,gk as Ni,aT as Oa,aS as Ci,gl as Si,gm as Pi,gn as Ai,go as Mi,gp as Ti,gq as Ri,gr as Ii,gs as Ei,gt as Fi,gu as Li,gv as Di,dj as Oi,aV as Bi,gw as Gi,aW as Wi,b2 as _i,aY as Ui,b1 as Hi,aX as $i,gx as Ki,a2 as zi,ca as qi,ac as Ba,f4 as Vi,gy as Ga,es as Yi,gz as Qi,gA as Xi}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-CzCM3XUY.js","assets/vendor-react-SZ_qB27O.js","assets/index-CHy0WNjH.js","assets/vendor-i18n-GF3RlKbq.js","assets/vendor-reactflow-Bg-Qjzh8.js","assets/vendor-reactflow-C5ap-Sga.css","assets/vendor-xterm-BNq00GSj.js","assets/vendor-xterm-LZoznX6r.css","assets/vendor-codemirror-jBKmHyH0.js","assets/index-BnfnLXyO.css","assets/DirectoryPicker-DNBB-viz.js","assets/folder-open-STXgbemw.js","assets/DirectoryPicker-0rspvcMz.css","assets/PluginManager-DSiHizRD.css","assets/PiExtensionsManager-BEj5xu45.js","assets/AgentPermissionPolicyEditor-DFldf6aS.js","assets/AgentPermissionPolicyEditor-CGxjOr6G.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 hl,fk as gl,fl as pl,c2 as bl,fm as Cs,fn as fl,fo as tt,fp as kt,bM as st,fq as vl,fr as xl,fs as yl,ft as jl,fu as ka,dx as nt,h as kl,b7 as wl,fv as Nl,fw as cs,fx as Cl,fy as ds,fz as Sl,fA as Pl,fB as sn,fC as Ss,a6 as wa,al as De,bP as Fe,fD as Al,fE as Ml,fF as Tl,fG as Rl,fH as Il,fI as El,L as Le,q as Fl,I as an,J as nn,aK as Na,P as rn,fJ as Ll,fK as Dl,fL as Ol,fM as Bl,fN as Ps,dv as rt,fO as ln,a8 as on,fP as Gl,fQ as Wl,aw as Ts,fR as _l,fS as Ul,aq as He,fT as Hl,fU as $l,fV as Kl,fW as zl,fX as ql,fY as Vl,fZ as Ca,f_ as Sa,f$ as Yl,dh as xt,dg as us,ad as Ql,o as Xl,ey as Jl,g0 as Zl,g1 as ei,ek as ti,bF as Pa,el as si,g2 as ai,g3 as ni,g4 as ri,bd as li,b6 as ii,_ as cn,ai as oi,ae as dn,dy as ci,b$ as di,W as ui,ce as mi,g5 as hi,g6 as Aa,u as gi,aR as Ma,cM as pi,g7 as Ta,g8 as Ra,bp as ie,g9 as bi,ga as fi,gb as vi,gc as xi,R as Ia,c1 as Ea,gd as Fa,bL as yi,ge as La,gf as ji,gg as ms,gh as ki,gi as wi,gj as Da,gk as Ni,aT as Oa,aS as Ci,gl as Si,gm as Pi,gn as Ai,go as Mi,gp as Ti,gq as Ri,gr as Ii,gs as Ei,gt as Fi,gu as Li,gv as Di,dj as Oi,aV as Bi,gw as Gi,aW as Wi,b2 as _i,aY as Ui,b1 as Hi,aX as $i,gx as Ki,a2 as zi,ca as qi,ac as Ba,f4 as Vi,gy as Ga,es as Yi,gz as Qi,gA as Xi}from"./index-CHy0WNjH.js";import{T as Ji,S as Zi,M as eo,C as Wa,a as to}from"./ShadcnColorPicker-Bnf5n5R4.js";import{u as q,T as As}from"./vendor-i18n-GF3RlKbq.js";import{SecretsView as so}from"./SecretsView-qGjo-0Cp.js";import{B as ao,A as no}from"./AgentPermissionPolicyEditor-DFldf6aS.js";import{U as ro}from"./users-D1Qhfyro.js";import{u as lo}from"./SettingsModal-DihNd7g8.js";import"./vendor-reactflow-Bg-Qjzh8.js";import"./vendor-xterm-BNq00GSj.js";import"./vendor-codemirror-jBKmHyH0.js";/**
|
|
3
3
|
* @license lucide-react v1.7.0 - ISC
|
|
4
4
|
*
|
|
5
5
|
* This source code is licensed under the ISC license.
|
|
@@ -18,4 +18,4 @@ You operate with a high degree of autonomy, making architectural decisions and b
|
|
|
18
18
|
|
|
19
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
20
|
|
|
21
|
-
Be brief and precise — avoid verbosity.`,builtIn:!0}],ec={"executor-welcome":{key:"executor-welcome",name:"Executor Welcome",roles:["executor"],description:"Introductory section for the executor agent",defaultContent:"You are a task execution agent..."},"executor-guardrails":{key:"executor-guardrails",name:"Executor Guardrails",roles:["executor"],description:"Behavioral guardrails and constraints for the executor",defaultContent:"Treat the File Scope in PROMPT.md..."},"executor-spawning":{key:"executor-spawning",name:"Executor Spawning",roles:["executor"],description:"Instructions for spawning child agents",defaultContent:"You can spawn child agents..."},"executor-completion":{key:"executor-completion",name:"Executor Completion",roles:["executor"],description:"Completion criteria and signaling for executor",defaultContent:"After all steps are done..."},"triage-welcome":{key:"triage-welcome",name:"Triage Welcome",roles:["triage"],description:"Introductory section for the triage/specification agent",defaultContent:"You are a task specification agent..."},"triage-context":{key:"triage-context",name:"Triage Context",roles:["triage"],description:"Context-gathering instructions for triage",defaultContent:"What you receive: A raw task title..."},"reviewer-verdict":{key:"reviewer-verdict",name:"Reviewer Verdict",roles:["reviewer"],description:"Verdict criteria and format for code/review agent",defaultContent:"APPROVE — Step will achieve its stated outcomes..."},"merger-conflicts":{key:"merger-conflicts",name:"Merger Conflicts",roles:["merger"],description:"Merge conflict resolution instructions for merger",defaultContent:"If there are merge conflicts..."},"agent-generation-system":{key:"agent-generation-system",name:"Agent Generation System",roles:["executor"],description:"System prompt for generating agent specifications",defaultContent:"You are an agent specification generator..."},"workflow-step-refine":{key:"workflow-step-refine",name:"Workflow Step Refine",roles:["executor"],description:"System prompt for refining workflow step descriptions",defaultContent:"You are an expert at creating detailed agent prompts..."},"planning-system":{key:"planning-system",name:"Planning System",roles:["triage"],description:"System prompt for the AI planning assistant",defaultContent:"You are a planning assistant for the fn task board system..."},"subtask-breakdown-system":{key:"subtask-breakdown-system",name:"Subtask Breakdown System",roles:["executor"],description:"System prompt for AI subtask decomposition",defaultContent:"You are a task decomposition assistant..."},"mission-interview-system":{key:"mission-interview-system",name:"Mission Interview System",roles:["triage"],description:"System prompt for AI-assisted mission planning",defaultContent:"You are a mission planning assistant..."},"ai-refine-system":{key:"ai-refine-system",name:"AI Refine System",roles:["executor"],description:"System prompt for AI-powered text refinement",defaultContent:"You are a text refinement assistant..."},"agent-onboarding-system":{key:"agent-onboarding-system",name:"Agent Onboarding System",roles:["executor"],description:"System prompt for AI-guided agent onboarding interview",defaultContent:"You are an agent onboarding assistant for the fn task board system..."}},qa=["executor","triage","reviewer","merger"],tc={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"}},et=a=>`prompt-role-tone--${a}`,vs={name:"",description:"",role:"executor",prompt:""};function sc(a,t){const s=a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),u=new Set(Ue.map(o=>o.id)),r=new Set(t.map(o=>o.id));if(!u.has(s)&&!r.has(s))return s;let m=2;for(;u.has(`${s}-${m}`)||r.has(`${s}-${m}`);)m++;return`${s}-${m}`}function ac({value:a,onChange:t,promptOverrides:s,onPromptOverridesChange:u}){const{t:r}=q("app"),m=C=>{const I=tc[C];return r(I.key,I.defaultValue)},[o,n]=i.useState("templates"),[d,w]=i.useState(null),[b,c]=i.useState(!1),[h,P]=i.useState(vs),[g,x]=i.useState(null),[f,j]=i.useState(null),[k,R]=i.useState(new Set),[v,M]=i.useState(null),[V,N]=i.useState(!1),[Z,O]=i.useState(null),K=i.useRef(null),$=a?.templates??[],ee=a?.roleAssignments??{},Q=Z===null?null:Z.source==="builtin"?Ue.find(C=>C.id===Z.id):$.find(C=>C.id===Z.id),B=i.useCallback(C=>{const I=Ue.filter(ne=>ne.role===C),z=$.filter(ne=>ne.role===C);return[...I,...z]},[$]);i.useEffect(()=>{Z!==null&&K.current?.focus()},[Z]);const L=i.useCallback(()=>{c(!0),w(null),P(vs),x(null),O(null)},[]),S=i.useCallback(C=>{w(C.id),c(!1),P({name:C.name,description:C.description,role:C.role,prompt:C.prompt}),x(null),O(null)},[]),F=i.useCallback(()=>{w(null),c(!1),P(vs),x(null),O(null),N(!1)},[]),te=i.useCallback(()=>{const C=h.name.trim();if(!C){x(r("agentPrompts.errors.nameRequired","Template name is required"));return}let I;if(b){if(I=sc(C,$),new Set(Ue.map(T=>T.id)).has(I)){x(r("agentPrompts.errors.idConflict",'Template ID "{{templateId}}" conflicts with a built-in template. Please use a different name.',{templateId:I}));return}}else I=d;const z={id:I,name:C,description:h.description.trim(),role:h.role,prompt:h.prompt,builtIn:!1};let ne;b?ne=[...$,z]:ne=$.map(Y=>Y.id===I?z:Y);const le={...ee};for(const[Y,T]of Object.entries(le))T===I&&h.role!==Y&&delete le[Y];t({...a,templates:ne,roleAssignments:Object.keys(le).length>0?le:void 0}),F()},[h,b,d,$,ee,a,t,F]),G=i.useCallback(C=>{const I=$.filter(le=>le.id!==C),z={...ee};let ne=!1;for(const[le,Y]of Object.entries(z))Y===C&&(delete z[le],ne=!0);t({...a,templates:I.length>0?I:void 0,roleAssignments:Object.keys(z).length>0||ne?Object.keys(z).length>0?z:void 0:ee}),j(null),d===C&&F()},[$,ee,a,t,d,F]),J=i.useCallback((C,I)=>{const z={...ee};I===""?delete z[C]:z[C]=I,t({...a,roleAssignments:Object.keys(z).length>0?z:void 0})},[ee,a,t]),me=i.useCallback((C,I)=>{const z={...s};z[C]=I||null,u(z)},[s,u]),y=i.useCallback(C=>{const I={...s};I[C]=null,u(I)},[s,u]),U=i.useCallback(C=>{R(I=>{const z=new Set(I);return z.has(C)?z.delete(C):z.add(C),z})},[]),ce=i.useCallback(C=>{M(I=>I===C?null:C)},[]),pe=i.useCallback((C,I)=>{N(!1),O({source:C,id:I})},[]),fe=i.useCallback(()=>{O(null),N(C=>!C)},[]),_=C=>Ue.some(I=>I.id===C);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 ${o==="templates"?"active":""}`,onClick:()=>n("templates"),"data-testid":"tab-templates",children:[e.jsx(ao,{size:14}),r("agentPrompts.tabs.templates","Templates")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${o==="assignments"?"active":""}`,onClick:()=>n("assignments"),"data-testid":"tab-assignments",children:[e.jsx(ro,{size:14}),r("agentPrompts.tabs.assignments","Assignments")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${o==="overrides"?"active":""}`,onClick:()=>n("overrides"),"data-testid":"tab-overrides",children:[e.jsx(oo,{size:14}),r("agentPrompts.tabs.overrides","Overrides")]})]}),e.jsxs("div",{className:"prompt-manager-content",children:[o==="templates"&&e.jsxs("div",{className:"prompt-manager-templates-tab","data-testid":"templates-tab",children:[(b||d!==null)&&e.jsxs("div",{className:"prompt-template-editor","data-testid":"template-editor",children:[e.jsx("h4",{className:"prompt-template-editor-title",children:b?r("agentPrompts.editor.newTemplate","New Custom Template"):r("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:r("agentPrompts.labels.name","Name")}),e.jsx("input",{id:"template-name",type:"text",value:h.name,onChange:C=>P(I=>({...I,name:C.target.value})),placeholder:r("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:r("agentPrompts.labels.description","Description")}),e.jsx("input",{id:"template-description",type:"text",value:h.description,onChange:C=>P(I=>({...I,description:C.target.value})),placeholder:r("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:r("agentPrompts.labels.role","Role")}),e.jsx("select",{id:"template-role",value:h.role,onChange:C=>P(I=>({...I,role:C.target.value})),"data-testid":"template-role-select",children:qa.map(C=>e.jsx("option",{value:C,children:m(C)},C))})]}),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:r("agentPrompts.labels.prompt","Prompt")}),e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:fe,"aria-label":r("agentPrompts.ariaLabels.expandPrompt","Expand prompt to fullscreen"),"data-testid":"template-prompt-fullscreen",children:e.jsx(xt,{size:14})})]}),V?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),N(!1))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsx("div",{className:"prompt-override-fullscreen-title",children:r("agentPrompts.titles.editPrompt","Edit Prompt")}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>N(!1),"data-testid":"template-prompt-collapse",children:[e.jsx(us,{size:14}),r("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:"template-prompt-fullscreen","aria-label":r("agentPrompts.ariaLabels.templatePromptFullscreen","Template prompt - fullscreen"),className:"prompt-template-prompt-textarea",value:h.prompt,onChange:C=>P(I=>({...I,prompt:C.target.value})),placeholder:r("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:r("agents.charactersCount","{{count}} characters",{count:h.prompt.length})})})]}):e.jsx("textarea",{id:"template-prompt",value:h.prompt,onChange:C=>P(I=>({...I,prompt:C.target.value})),placeholder:r("agentPrompts.placeholders.prompt","Enter the system prompt for this template..."),rows:8,className:"prompt-template-prompt-textarea","data-testid":"template-prompt-input"})]}),g&&e.jsx("div",{className:"prompt-template-error","data-testid":"template-error",children:g}),e.jsxs("div",{className:"prompt-template-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:F,"data-testid":"cancel-template-btn",children:r("agentPrompts.actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:te,"data-testid":"save-template-btn",children:b?r("agentPrompts.actions.create","Create"):r("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:r("agentPrompts.sections.builtinTemplates","Built-in Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:r("agentPrompts.descriptions.builtinTemplates","These templates are provided by Fusion and cannot be modified.")}),e.jsx("div",{className:"prompt-template-list",children:Ue.map(C=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${C.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:C.name}),e.jsx("span",{className:`prompt-template-badge-built-in ${et(C.role)}`,children:r("agentPrompts.badges.builtin","Built-in")}),e.jsx("span",{className:`prompt-template-badge-role ${et(C.role)}`,children:m(C.role)})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>pe("builtin",C.id),title:r("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":r("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:C.name}),"data-testid":`expand-view-${C.id}`,children:e.jsx(xt,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:C.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:C.prompt})})]},C.id))})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"custom-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:r("agentPrompts.sections.customTemplates","Custom Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:r("agentPrompts.descriptions.customTemplates","Create custom templates to override built-in prompts for specific roles.")}),$.length===0&&!b&&e.jsx("div",{className:"prompt-template-empty",children:r("agentPrompts.emptyStates.noCustomTemplates","No custom templates yet. Create one to get started.")}),$.length>0&&e.jsx("div",{className:"prompt-template-list",children:$.map(C=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${C.id}`,children:f===C.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsx("p",{children:r("agentPrompts.confirmations.deleteTemplate",'Delete "{{name}}"?',{name:C.name})}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>G(C.id),"data-testid":`confirm-delete-${C.id}`,children:r("agentPrompts.actions.delete","Delete")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>j(null),"data-testid":`cancel-delete-${C.id}`,children:r("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:C.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:r("agentPrompts.badges.custom","Custom")}),e.jsx("span",{className:`prompt-template-badge-role ${et(C.role)}`,children:m(C.role)}),_(C.id)&&e.jsx("span",{className:"prompt-template-badge-override",children:r("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:()=>pe("custom",C.id),title:r("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":r("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:C.name}),"data-testid":`expand-view-${C.id}`,children:e.jsx(xt,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>S(C),title:r("agentPrompts.titles.edit","Edit"),"aria-label":r("agentPrompts.ariaLabels.editTemplate","Edit {{name}}",{name:C.name}),"data-testid":`edit-${C.id}`,children:e.jsx(an,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>j(C.id),title:r("agentPrompts.titles.delete","Delete"),"aria-label":r("agentPrompts.ariaLabels.deleteTemplate","Delete {{name}}",{name:C.name}),"data-testid":`delete-${C.id}`,children:e.jsx(nn,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:C.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:C.prompt})})]})},C.id))}),!b&&d===null&&e.jsxs("button",{type:"button",className:"btn btn-primary prompt-template-add-btn",onClick:L,"data-testid":"add-template-btn",children:[e.jsx(rn,{size:14}),r("agentPrompts.actions.addCustomTemplate","Add Custom Template")]})]}),Q&&e.jsxs("div",{ref:K,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),O(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[Q.name,e.jsx("span",{className:`prompt-template-badge-role ${et(Q.role)}`,children:m(Q.role)})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>O(null),"data-testid":`collapse-view-${Q.id}`,children:[e.jsx(us,{size:14}),r("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:Q.prompt})]})]}),o==="assignments"&&e.jsxs("div",{className:"prompt-manager-assignments-tab","data-testid":"assignments-tab",children:[e.jsx("p",{className:"prompt-assignments-desc",children:r("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:qa.map(C=>{const I=B(C),z=ee[C]??"",ne=I.find(Y=>Y.id===z),le=!!z;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${C}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:`prompt-role-badge ${et(C)}`,children:m(C)}),le&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[ne?.name??r("agentPrompts.labels.custom","Custom")," (",r("agentPrompts.labels.overridesDefault","overrides default"),")"]})]}),e.jsxs("select",{className:"prompt-role-select",value:z,onChange:Y=>J(C,Y.target.value),"data-testid":`select-${C}`,children:[e.jsx("option",{value:"",children:r("agentPrompts.options.useDefault","Use default")}),I.map(Y=>e.jsxs("option",{value:Y.id,children:[Y.name,_(Y.id)?` (${r("agentPrompts.labels.builtIn","built-in")})`:` (${r("agentPrompts.labels.custom","custom")})`]},Y.id))]})]},C)})}),Object.keys(ee).length>0&&e.jsxs("div",{className:"prompt-assignments-note",children:[e.jsxs("strong",{children:[r("agentPrompts.labels.note","Note"),":"]})," ",r("agentPrompts.descriptions.assignmentNote","Role assignments are stored in the agentPrompts configuration. Custom templates override built-ins by ID.")]})]}),o==="overrides"&&e.jsxs("div",{className:"prompt-manager-overrides-tab","data-testid":"overrides-tab",children:[e.jsx("p",{className:"prompt-overrides-desc",children:r("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(ec).map(C=>{const I=C.key,z=s?.[I]??"",ne=z!=="",le=k.has(I);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${I}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("button",{type:"button",className:"prompt-override-info",onClick:()=>U(I),children:[e.jsx("span",{className:"prompt-override-name",children:C.name}),e.jsx("code",{className:"prompt-override-key",children:I}),ne&&e.jsx("span",{className:"prompt-override-badge",children:r("agentPrompts.badges.customized","customized")})]}),e.jsxs("div",{className:"prompt-override-header-actions",children:[le&&e.jsx("button",{type:"button",className:"prompt-override-fullscreen-btn",onClick:Y=>{Y.stopPropagation(),ce(I)},"aria-label":r("agentPrompts.ariaLabels.expandToFullscreen","Expand to fullscreen"),"data-testid":`fullscreen-${I}`,children:e.jsx(xt,{size:14})}),e.jsx("button",{type:"button",className:"prompt-override-expand-btn","aria-label":le?r("agentPrompts.ariaLabels.collapse","Collapse"):r("agentPrompts.ariaLabels.expand","Expand"),"data-testid":`expand-${I}`,onClick:Y=>{Y.stopPropagation(),U(I)},children:le?e.jsx(Ql,{size:16}):e.jsx(Xl,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:C.description}),le&&(v===I?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:Y=>{Y.key==="Escape"&&(Y.preventDefault(),M(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[C.name,e.jsx("code",{className:"prompt-override-key",children:I})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>M(null),"data-testid":`collapse-fullscreen-${I}`,children:[e.jsx(us,{size:14}),r("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:`prompt-${I}-fullscreen`,"aria-label":r("agentPrompts.ariaLabels.promptOverrideFullscreen","{{name}} prompt override ({{key}}) - fullscreen",{name:C.name,key:I}),className:"prompt-override-textarea",value:z,onChange:Y=>{me(I,Y.target.value)},placeholder:`Default: ${C.defaultContent.slice(0,100)}${C.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${I}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ne&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>y(I),"data-testid":`reset-fullscreen-${I}`,children:r("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ne?r("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):r("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:C.defaultContent.length})})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${I}`,"aria-label":r("agentPrompts.ariaLabels.promptOverride","{{name}} prompt override ({{key}})",{name:C.name,key:I}),className:"prompt-override-textarea",value:z,onChange:Y=>{me(I,Y.target.value)},placeholder:r("agentPrompts.placeholders.promptDefault","Default: {{preview}}",{preview:C.defaultContent.slice(0,100)+(C.defaultContent.length>100?"...":"")}),rows:4,"data-testid":`override-input-${I}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ne&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:Y=>{Y.stopPropagation(),y(I)},"data-testid":`reset-${I}`,children:r("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ne?r("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):r("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:C.defaultContent.length})})]})]}))]},I)})})]})]})]})}function nc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.nav.prompts","Prompts")}),e.jsx(ac,{value:t.agentPrompts,onChange:r=>{s(m=>({...m,agentPrompts:r}))},promptOverrides:t.promptOverrides,onPromptOverridesChange:r=>{s(m=>({...m,promptOverrides:r}))}})]})}function rc({scopeBanner:a,form:t,setForm:s,projectId:u,addToast:r,prefixError:m,setPrefixError:o,projectTrackingRepoOptions:n,projectTrackingRepoLoading:d,projectTrackingRepoError:w,onQuickChatButtonModeChange:b}){const{t:c}=q("app"),[h,P]=i.useState([]);i.useEffect(()=>{let f=!1;return Jl(u,{includeDisabledBuiltins:!0}).then(j=>{f||P(j.filter(k=>k.id.startsWith("builtin:")&&k.kind!=="fragment"))}).catch(()=>{f||P([])}),()=>{f=!0}},[u]);const g=i.useMemo(()=>{const f=Array.isArray(t.enabledBuiltinWorkflowIds)?t.enabledBuiltinWorkflowIds:void 0;return new Set(f??h.map(j=>j.id))},[h,t.enabledBuiltinWorkflowIds]),x=(f,j)=>{s(k=>{const R=h.map(V=>V.id),v=new Set(Array.isArray(k.enabledBuiltinWorkflowIds)?k.enabledBuiltinWorkflowIds:R);j?v.add(f):v.delete(f);const M=R.filter(V=>v.has(V));return{...k,enabledBuiltinWorkflowIds:M.length===R.length?void 0:M}})};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.general.general","General")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskPrefix",children:c("settings.general.taskPrefix","Task Prefix")}),e.jsx("input",{id:"taskPrefix",type:"text",placeholder:c("settings.general.fN","FN"),value:t.taskPrefix||"",onChange:f=>{const j=f.target.value;s(k=>({...k,taskPrefix:j||void 0})),j&&!/^[A-Z]{1,5}$/.test(j)?o(c("settings.general.prefixMustBe15UppercaseLetters","Prefix must be 1–5 uppercase letters")):o(null)}}),m&&e.jsx("small",{className:"field-error",children:m}),!m&&e.jsx("small",{children:c("settings.general.prefixForNewTaskIDsEGKB","Prefix for new task IDs (e.g. KB, PROJ)")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx(Zl,{projectId:u,addToast:r}),e.jsx("small",{children:c("settings.general.newTasksInheritThisCustomWorkflowsStepsOverridable","New tasks inherit this custom workflow's steps (overridable per task)")})]}),h.length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:c("settings.general.builtInWorkflows","Built-in workflows")}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:h.map(f=>e.jsxs("label",{htmlFor:`builtin-workflow-${f.id}`,className:"checkbox-label",children:[e.jsx("input",{id:`builtin-workflow-${f.id}`,type:"checkbox",checked:g.has(f.id),onChange:j=>x(f.id,j.target.checked)}),e.jsx("span",{children:f.name})]},f.id))}),e.jsx("small",{children:c("settings.general.disabledBuiltInWorkflowsAreHiddenFromWorkflow","Disabled built-in workflows are hidden from workflow pickers. Existing tasks that already use one continue to resolve.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"ephemeralAgentsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"ephemeralAgentsEnabled",type:"checkbox",checked:t.ephemeralAgentsEnabled!==!1,onChange:f=>s(j=>({...j,ephemeralAgentsEnabled:f.target.checked}))}),c("settings.general.useEphemeralTaskWorkerAgents"," Use ephemeral task-worker agents ")]}),e.jsxs("small",{children:[c("settings.general.whenEnabledDefaultFusionSpawnsShortLived"," When enabled (default), Fusion spawns short-lived "),e.jsx("code",{children:"executor-FN-XXXX"}),c("settings.general.agentsToRunEachTaskWhenDisabledOnly"," agents to run each task. When disabled, only permanent agents execute tasks and the scheduler auto-assigns work using the agent reporting chain. Tasks with no eligible permanent agent stay queued. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"workspaceMode",className:"checkbox-label",children:[e.jsx("input",{id:"workspaceMode",type:"checkbox",checked:t.workspaceMode===!0,onChange:f=>s(j=>({...j,workspaceMode:f.target.checked}))}),c("settings.general.workspaceMode"," Workspace mode (multi-repo) ")]}),e.jsx("small",{children:c("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.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"completionDocumentationMode",children:c("settings.general.completionDocumentationAutomation","Completion Documentation Automation")}),e.jsxs("select",{id:"completionDocumentationMode",value:t.completionDocumentationMode||"off",onChange:f=>s(j=>({...j,completionDocumentationMode:f.target.value})),children:[e.jsx("option",{value:"off",children:c("settings.general.off","Off")}),e.jsx("option",{value:"changeset",children:c("settings.general.requireChangesetChangesetMd","Require changeset (.changeset/*.md)")}),e.jsx("option",{value:"changelog",children:c("settings.general.requireChangelogUpdateExistingChangelog","Require changelog update (existing changelog)")})]}),e.jsxs("small",{children:[c("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"}),c("settings.general.workflowsOrChangelogModeWhenContributorsShouldUpdate"," workflows, or changelog mode when contributors should update an existing changelog file. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"quickChatButtonMode",children:c("settings.general.quickChatLauncher","Quick Chat launcher")}),e.jsxs("select",{id:"quickChatButtonMode",className:"select",value:t.quickChatButtonMode??(t.showQuickChatFAB?"floating":"off"),onChange:f=>s(j=>{const k=f.target.value;return b?.(k),{...j,quickChatButtonMode:k,showQuickChatFAB:k==="floating"}}),children:[e.jsx("option",{value:"floating",children:c("settings.general.quickChatLauncherFloating","Floating button")}),e.jsx("option",{value:"footer",children:c("settings.general.quickChatLauncherFooter","Footer button")}),e.jsx("option",{value:"off",children:c("settings.general.off","Off")})]}),e.jsx("small",{children:c("settings.general.quickChatLauncherHint","Choose whether Quick Chat opens from the draggable floating button, a footer button beside Terminal, or stays hidden.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.chatHistory","Chat history")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatAutoCleanupDays",children:c("settings.general.autoCleanupOldChats","Auto-cleanup old chats")}),e.jsxs("select",{id:"chatAutoCleanupDays",className:"select",value:t.chatAutoCleanupDays??0,onChange:f=>s(j=>({...j,chatAutoCleanupDays:Number(f.target.value)||0})),children:[e.jsx("option",{value:0,children:c("settings.general.off","Off")}),e.jsx("option",{value:7,children:c("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:c("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:c("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:c("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:c("settings.general.90Days","90 days")})]}),e.jsx("small",{children:c("settings.general.deleteChatSessionsAndRoomsThatHaveBeen","Delete chat sessions and rooms that have been idle for this many days. Default: Off.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mailAutoCleanupDays",children:c("settings.general.autoPruneOldMail","Auto-prune old mail")}),e.jsxs("select",{id:"mailAutoCleanupDays",className:"select",value:t.mailAutoCleanupDays??0,onChange:f=>s(j=>({...j,mailAutoCleanupDays:Number(f.target.value)||0})),children:[e.jsx("option",{value:0,children:c("settings.general.off","Off")}),e.jsx("option",{value:7,children:c("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:c("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:c("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:c("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:c("settings.general.90Days","90 days")})]}),e.jsx("small",{children:c("settings.general.deleteInboxOutboxMessagesOlderThanThisMany","Delete inbox/outbox messages older than this many days. Default: Off. 7 days is the suggested setting.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"operationalLogRetentionDays",children:c("settings.general.operationalLogRetention","Operational log retention")}),e.jsxs("select",{id:"operationalLogRetentionDays",className:"select",value:t.operationalLogRetentionDays??30,onChange:f=>s(j=>({...j,operationalLogRetentionDays:Number(f.target.value)||0})),children:[e.jsx("option",{value:0,children:c("settings.general.off","Off")}),e.jsx("option",{value:7,children:c("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:c("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:c("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:c("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:c("settings.general.90Days","90 days")})]}),e.jsx("small",{children:c("settings.general.loweringThisWindowMeansReliabilityMetricsChartsAnd"," Lowering this window means Reliability metrics/charts and the Activity feed will not show history older than the selected range. Per-task task detail history is unaffected. Default: 30 days. ")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.chatRooms","Chat Rooms")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomRecentVerbatimMessages",children:c("settings.general.recentVerbatimRoomMessages","Recent verbatim room messages")}),e.jsx("input",{id:"chatRoomRecentVerbatimMessages",type:"number",min:"1",className:"input",placeholder:c("settings.general.25","25"),value:t.chatRoomRecentVerbatimMessages??"",onChange:f=>s(j=>({...j,chatRoomRecentVerbatimMessages:Number(f.target.value)||void 0}))}),e.jsx("small",{children:c("settings.general.numberOfMostRecentChatRoomMessagesKept","Number of most-recent chat-room messages kept verbatim in the responder transcript. Older messages are compacted into a summary block. Default: 25.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomCompactionFetchLimit",children:c("settings.general.roomCompactionFetchLimit","Room compaction fetch limit")}),e.jsx("input",{id:"chatRoomCompactionFetchLimit",type:"number",min:"1",className:"input",placeholder:c("settings.general.200","200"),value:t.chatRoomCompactionFetchLimit??"",onChange:f=>s(j=>({...j,chatRoomCompactionFetchLimit:Number(f.target.value)||void 0}))}),e.jsx("small",{children:c("settings.general.upperBoundOnMessagesFetchedFromTheRoom","Upper bound on messages fetched from the room store for compaction consideration. Default: 200.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomSummaryMaxChars",children:c("settings.general.roomSummaryMaxCharacters","Room summary max characters")}),e.jsx("input",{id:"chatRoomSummaryMaxChars",type:"number",min:"200",className:"input",placeholder:c("settings.general.3000","3000"),value:t.chatRoomSummaryMaxChars??"",onChange:f=>s(j=>({...j,chatRoomSummaryMaxChars:Number(f.target.value)||void 0}))}),e.jsx("small",{children:c("settings.general.hardCapOnTheSynthesizedEarlierRoomContext",'Hard cap on the synthesized "Earlier room context" summary block. Default: 3000.')})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.capacityRiskBanner","Capacity Risk Banner")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"capacityRiskBannerEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"capacityRiskBannerEnabled",type:"checkbox",checked:t.capacityRiskBannerEnabled===!0,onChange:f=>s(j=>({...j,capacityRiskBannerEnabled:f.target.checked}))}),c("settings.general.showCapacityRiskBanner"," Show capacity risk banner ")]}),e.jsx("small",{children:c("settings.general.warnOnTheBoardWhenTodoWorkExceeds","Warn on the board when todo work exceeds the threshold and no idle agents are available.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"capacityRiskTodoThresholdGeneral",children:c("settings.general.todoThreshold","Todo threshold")}),e.jsx("input",{id:"capacityRiskTodoThresholdGeneral",type:"number",min:0,className:"input",value:t.capacityRiskTodoThreshold??20,onChange:f=>s(j=>({...j,capacityRiskTodoThreshold:f.target.value===""?0:Math.max(0,Number.parseInt(f.target.value,10)||0)}))}),e.jsx("small",{children:c("settings.general.bannerFiresWhenTodoCountIsStrictlyGreater","Banner fires when todo count is strictly greater than this value (default 20). Applies when the banner is enabled.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.gitHubTracking","GitHub Tracking")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubTrackingMode",children:c("settings.general.defaultTrackingModeForNewTasks","Default tracking mode for new tasks")}),e.jsxs("select",{id:"githubTrackingMode",className:"select",value:t.githubTrackingEnabledByDefault?"new-tasks":"off",onChange:f=>s(j=>({...j,githubTrackingEnabledByDefault:f.target.value==="new-tasks"})),children:[e.jsx("option",{value:"off",children:c("settings.general.offDefault","Off (default)")}),e.jsx("option",{value:"new-tasks",children:c("settings.general.onForNewTasks","On for new tasks")})]}),e.jsx("small",{children:c("settings.general.controlsWhetherNewlyCreatedTasksHaveGitHubIssue"," Controls whether newly created tasks have GitHub issue tracking enabled by default. Individual tasks can still override this from the task detail modal. ")}),e.jsxs("small",{children:[c("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?c("settings.general.enableSummarizationInProjectModelsToConfigureThatModel"," Enable summarization in Project Models to configure that model."):""]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"projectGithubTrackingDefaultRepoGeneral",children:c("settings.general.projectDefaultTrackingRepo","Project default tracking repo")}),e.jsx(un,{id:"projectGithubTrackingDefaultRepoGeneral",ariaLabel:"Project default tracking repo",value:t.githubTrackingDefaultRepo??"",options:n,loading:d,error:w??void 0,placeholder:c("settings.general.ownerRepo","owner/repo"),onChange:f=>s(j=>({...j,githubTrackingDefaultRepo:f||void 0}))}),e.jsx("small",{children:c("settings.general.defaultRepoUsedWhenCreatingGitHubIssuesFor","Default repo used when creating GitHub issues for tracked tasks. Falls back to the global default if blank.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"githubTrackingDedupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"githubTrackingDedupEnabled",type:"checkbox",checked:t.githubTrackingDedupEnabled!==!1,onChange:f=>s(j=>({...j,githubTrackingDedupEnabled:f.target.checked}))}),c("settings.general.searchTheTrackingRepoForLikelyDuplicatesBefore"," Search the tracking repo for likely duplicates before opening a new issue ")]}),e.jsx("small",{children:c("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. ")})]})]})}const xs="builtin:coding",lc=[{id:"planning",providerId:"planningProvider",modelId:"planningModelId",label:"Plan/Triage Model",help:"Provider and model used when planning or triaging tasks. Leave unset to inherit from the workflow default."},{id:"execution",providerId:"executionProvider",modelId:"executionModelId",label:"Executor Model",help:"Provider and model used while executing workflow steps. Leave unset to inherit from the workflow default."},{id:"validator",providerId:"validatorProvider",modelId:"validatorModelId",label:"Reviewer Model",help:"Provider and model used for workflow review or validation lanes. Leave unset to inherit from the workflow default."},{id:"planning-fallback",providerId:"planningFallbackProvider",modelId:"planningFallbackModelId",label:"Planning Fallback Model",help:"Fallback provider and model used when the primary Plan/Triage model cannot be used."},{id:"validator-fallback",providerId:"validatorFallbackProvider",modelId:"validatorFallbackModelId",label:"Reviewer Fallback Model",help:"Fallback provider and model used when the primary Reviewer model cannot be used."},{id:"title-summarizer-fallback",providerId:"titleSummarizerFallbackProvider",modelId:"titleSummarizerFallbackModelId",label:"Title Summarizer Fallback Model",help:"Fallback provider and model used when the primary Title Summarizer model cannot be used."}];function ic(a){const t=new Map((a??[]).map(s=>[s.id,s]));return lc.filter(s=>{const u=t.get(s.providerId),r=t.get(s.modelId);return u?.type==="string"&&r?.type==="string"})}function oc(a,t){const s=a[t.providerId],u=a[t.modelId];return typeof s=="string"&&typeof u=="string"&&s&&u?`${s}/${u}`:""}class hn extends Error{rejections;constructor(t){super("Workflow model lane settings were rejected"),this.name="WorkflowLaneFlushRejection",this.rejections=t}}function cc({scopeBanner:a,form:t,setForm:s,models:u,projectId:r,onOpenWorkflowSettings:m,registerWorkflowLaneSaver:o}){const{t:n}=q("app"),{modelLanes:d,getLaneStatus:w,getLaneValue:b,updateLaneValue:c,resetLaneValue:h,availableModels:P,modelsLoading:g,favoriteProviders:x,favoriteModels:f,onToggleFavorite:j,onToggleModelFavorite:k,editingPresetId:R,setEditingPresetId:v,presetDraft:M,setPresetDraft:V,onSavePresetDraft:N,confirmDelete:Z}=u,O=t.modelPresets||[],K=O.map(T=>({id:T.id,name:T.name})),$=new Set(Object.values(t.defaultPresetBySize||{}).filter(Boolean)),ee=typeof t.defaultWorkflowId=="string"&&t.defaultWorkflowId.trim()?t.defaultWorkflowId:xs,[Q,B]=i.useState(ee),[L,S]=i.useState(null),[F,te]=i.useState(!1),[G,J]=i.useState({}),[me,y]=i.useState({}),[U,ce]=i.useState([]),pe=i.useRef(0),fe=Object.keys(G).length>0;i.useEffect(()=>{B(ee)},[ee]),i.useEffect(()=>{if(!r){S(null),J({}),y({}),ce([]);return}const T=++pe.current;te(!0),Promise.all([ei(Q,r),ti(Q,r)]).then(([E,H])=>{if(pe.current!==T)return;S(H),J({}),y({});const ae="settings"in E.ir?E.ir.settings:void 0;ce(ic(ae))}).catch(E=>{if(pe.current===T){if(E instanceof Pa&&E.status===404&&Q!==xs){B(xs);return}S({stored:{},effective:{},orphaned:[]}),ce([])}}).finally(()=>{pe.current===T&&te(!1)})},[r,Q]);const _=i.useMemo(()=>({...L?.effective??{},...Object.fromEntries(Object.entries(G).filter(([,T])=>T!==null))}),[L,G]),C=i.useCallback((T,E)=>{y(H=>{const ae={...H};return delete ae[T.providerId],delete ae[T.modelId],ae}),J(H=>{if(!E)return{...H,[T.providerId]:null,[T.modelId]:null};const ae=E.indexOf("/");return ae<=0?H:{...H,[T.providerId]:E.slice(0,ae),[T.modelId]:E.slice(ae+1)}})},[]),I=i.useCallback(T=>{C(T,"")},[C]),z=i.useCallback(async()=>{if(!(!r||!fe))try{const T=await si(Q,G,r);S(T),J({}),y({})}catch(T){if(T instanceof Pa&&T.status===400&&T.details){const E=T.details.rejections??[];if(E.length>0)throw y(Object.fromEntries(E.map(H=>[H.settingId,H]))),new hn(E)}throw T}},[r,fe,Q,G]);i.useEffect(()=>(o?.(z),()=>o?.(null)),[o,z]);const ne=d.filter(T=>["default","summarization"].includes(T.laneId)),le=T=>T.laneId==="default"?"Project Default Model":T.laneId==="summarization"?"Project Summarization Model":T.label,Y=T=>T.laneId==="default"?"Project-wide default AI model used when no more specific task or project lane override is set.":T.laneId==="summarization"?"Model used for title auto-summarization, merge commit summaries, GitHub tracking issue titles, and PR title/body generation.":T.helperText;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.projectModels.tokenCap","Token Cap")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"tokenCap",children:n("settings.projectModels.tokenCap","Token Cap")}),e.jsxs("div",{className:"settings-token-cap-row",children:[e.jsx("input",{id:"tokenCap",type:"number",placeholder:n("settings.projectModels.noCap","No cap"),value:t.tokenCap??"",onChange:T=>{const E=T.target.value;s(H=>({...H,tokenCap:E?parseInt(E,10):null}))}}),t.tokenCap!=null&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:n("settings.projectModels.resetToDefaultNoCap","Reset to default (no cap)"),onClick:()=>s(T=>({...T,tokenCap:null})),style:{whiteSpace:"nowrap"},children:n("settings.projectModels.reset"," Reset ")})]}),e.jsx("small",{children:n("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.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.modelLanes","Model Lanes")}),e.jsx("p",{className:"settings-description",children:n("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. ")}),g?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:n("settings.projectModels.loadingAvailableModels","Loading available models…")})}):P.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.noModelsAvailableConfigureAuthenticationFirst"," No models available. Configure authentication first. ")}):e.jsx(e.Fragment,{children:ne.map(T=>{const E=w(T),H=b(T),ae=E==="overridden",ve=le(T);return e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`${T.laneId}Model`,children:ve}),e.jsx("span",{className:`settings-lane-badge ${ae?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:ae?"Explicitly set for this project":"Inherited from global settings",children:ae?"Override (Project)":"Inherited (Global)"})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(Fe,{id:`${T.laneId}Model`,label:ve,models:P,value:H,onChange:St=>c(T,St),placeholder:T.laneId==="default"?"Use global default":"Use global",favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})}),ae&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:n("settings.projectModels.resetToInheritFromGlobal","Reset to inherit from global"),onClick:()=>h(T),style:{whiteSpace:"nowrap"},children:n("settings.projectModels.reset"," Reset ")})]}),e.jsxs("small",{children:[Y(T),n("settings.projectModels.fallsBackTo"," Falls back to: "),T.fallbackOrder,"."]})]},T.laneId)})}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.defaultWorkflowModelLanes","Default workflow model lanes")}),e.jsxs("p",{className:"settings-description",children:[n("settings.movedStub.modelLanes","Per-phase model lanes (execution, planning, reviewer, and their fallbacks) now live on the workflow."),n("settings.projectModels.theseProjectOverridesApplyToTheActiveDefault"," These project overrides apply to the active default workflow. ")]}),r?F?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:n("settings.projectModels.loadingWorkflowModelLanes","Loading workflow model lanes…")})}):P.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.noModelsAvailableConfigureAuthenticationBeforeSelectingWorkflow"," No models available. Configure authentication before selecting workflow model lanes. ")}):e.jsxs(e.Fragment,{children:[U.map(T=>{const E=oc(_,T),H=Object.prototype.hasOwnProperty.call(G,T.providerId)?G[T.providerId]!==null:!!(L?.stored&&(Object.prototype.hasOwnProperty.call(L.stored,T.providerId)||Object.prototype.hasOwnProperty.call(L.stored,T.modelId))),ae=me[T.providerId]?.message??me[T.modelId]?.message;return e.jsxs("div",{className:"form-group","data-testid":`workflow-model-lane-${T.id}`,children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`workflow-${T.id}-model`,children:T.label}),e.jsx("span",{className:`settings-lane-badge ${H?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:H?"Explicitly set for this project workflow":"Inherited from workflow defaults",children:H?"Override (Project)":"Inherited (Workflow)"})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(Fe,{id:`workflow-${T.id}-model`,label:T.label,models:P,value:E,onChange:ve=>C(T,ve),placeholder:n("settings.projectModels.useWorkflowDefault","Use workflow default"),defaultOptionLabel:"Use workflow default",favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})}),H&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:n("settings.projectModels.resetToInheritFromWorkflow","Reset to inherit from workflow"),onClick:()=>I(T),style:{whiteSpace:"nowrap"},children:n("settings.projectModels.reset"," Reset ")})]}),e.jsx("small",{children:T.help}),ae?e.jsx("small",{className:"settings-error","data-testid":`workflow-model-lane-error-${T.id}`,children:ae}):null]},T.id)}),m?e.jsx("div",{className:"settings-model-lane-actions","aria-label":n("settings.projectModels.defaultWorkflowModelLaneActions","Default workflow model lane actions"),children:e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:m,children:n("settings.projectModels.advancedWorkflowPolicy"," Advanced workflow policy ")})}):null]}):e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.openAProjectToEditWorkflowModelLanes","Open a project to edit workflow model lanes.")}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.modelPresets","Model Presets")}),e.jsxs("div",{className:"form-group settings-model-presets",children:[e.jsx("label",{children:n("settings.projectModels.configuredPresets","Configured presets")}),O.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.noPresetsConfiguredYet","No presets configured yet.")}):e.jsx("div",{className:"settings-preset-list",children:O.map(T=>{const E=ai(T),H=`${E.executorValue||"default"} / ${E.validatorValue||"default"}`;return e.jsxs("div",{className:"settings-preset-item",children:[e.jsxs("div",{className:"settings-preset-item-meta",children:[e.jsx("strong",{children:T.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:H})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{v(T.id),V({...T})},children:n("settings.projectModels.edit"," Edit ")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:async()=>{$.has(T.id)&&!await Z({title:n("settings.models.deletePresetTitle","Delete Preset"),message:n("settings.models.deletePresetMessage",'Preset "{{name}}" is used in auto-selection. Delete it anyway?',{name:T.name}),danger:!0})||(s(ae=>({...ae,modelPresets:(ae.modelPresets||[]).filter(ve=>ve.id!==T.id),defaultPresetBySize:Object.fromEntries(Object.entries(ae.defaultPresetBySize||{}).filter(([,ve])=>ve!==T.id))})),R===T.id&&(v(null),V(null)))},children:n("settings.projectModels.delete"," Delete ")})]})]},T.id)})}),M?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{v(null),V({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:n("settings.projectModels.addPreset"," Add Preset ")})})]}),M?e.jsxs("div",{className:"form-group settings-preset-editor",children:[e.jsx("label",{children:n("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:n("settings.projectModels.name","Name")}),e.jsx("input",{id:"preset-name",type:"text",value:M.name,onChange:T=>{const E=T.target.value;V(H=>H&&{...H,name:E})}})]}),P.length===0?e.jsx("small",{children:n("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:n("settings.projectModels.executorModel","Executor model")}),e.jsx(Fe,{id:"preset-executor-model",label:"Preset executor model",models:P,value:M.executorProvider&&M.executorModelId?`${M.executorProvider}/${M.executorModelId}`:"",onChange:T=>{if(!T){V(H=>H&&{...H,executorProvider:void 0,executorModelId:void 0});return}const E=T.indexOf("/");V(H=>H&&{...H,executorProvider:T.slice(0,E),executorModelId:T.slice(E+1)})},placeholder:n("settings.projectModels.useDefault","Use default"),favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:n("settings.projectModels.reviewerModel","Reviewer model")}),e.jsx(Fe,{id:"preset-validator-model",label:"Preset reviewer model",models:P,value:M.validatorProvider&&M.validatorModelId?`${M.validatorProvider}/${M.validatorModelId}`:"",onChange:T=>{if(!T){V(H=>H&&{...H,validatorProvider:void 0,validatorModelId:void 0});return}const E=T.indexOf("/");V(H=>H&&{...H,validatorProvider:T.slice(0,E),validatorModelId:T.slice(E+1)})},placeholder:n("settings.projectModels.useDefault","Use default"),favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,children:n("settings.models.savePreset","Save preset")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{v(null),V(null)},children:n("settings.actions.cancel","Cancel")})]})]}):null,e.jsx("div",{className:"form-group settings-preset-auto-select",children:e.jsxs("label",{htmlFor:"autoSelectModelPreset",className:"checkbox-label",children:[e.jsx("input",{id:"autoSelectModelPreset",type:"checkbox",checked:t.autoSelectModelPreset||!1,onChange:T=>s(E=>({...E,autoSelectModelPreset:T.target.checked}))}),n("settings.projectModels.autoSelectPresetBasedOnTaskSize"," Auto-select preset based on task size ")]})}),t.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(T=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${T}`,children:T==="S"?"Small tasks (S):":T==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${T}`,value:t.defaultPresetBySize?.[T]||"",onChange:E=>{const H=E.target.value||void 0;s(ae=>({...ae,defaultPresetBySize:{...ae.defaultPresetBySize||{},[T]:H}}))},children:[e.jsx("option",{value:"",children:n("settings.projectModels.noPreset","No preset")}),K.map(E=>e.jsx("option",{value:E.id,children:E.name},E.id))]})]},T))}):null,e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.aITitleAndGitCommitMessageSummarization"," AI Title and Git Commit Message Summarization ")}),e.jsx("p",{className:"settings-description",children:n("settings.projectModels.configuresTheModelUsedForTwoShortSummary"," Configures the model used for two short-summary jobs: auto-generating task titles from long descriptions, and generating merge commit summaries from step commits and diff stats. ")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoSummarizeTitles",className:"checkbox-label",children:[e.jsx("input",{id:"autoSummarizeTitles",type:"checkbox",checked:t.autoSummarizeTitles||!1,onChange:T=>s(E=>({...E,autoSummarizeTitles:T.target.checked}))}),n("settings.projectModels.autoSummarizeLongDescriptionsAsTitles"," Auto-summarize long descriptions as titles ")]}),e.jsx("small",{children:n("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. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"useAiMergeCommitSummary",className:"checkbox-label",children:[e.jsx("input",{id:"useAiMergeCommitSummary",type:"checkbox",checked:t.useAiMergeCommitSummary||!1,onChange:T=>s(E=>({...E,useAiMergeCommitSummary:T.target.checked}))}),n("settings.projectModels.aIMergeCommitSummaries"," AI merge commit summaries ")]}),e.jsx("small",{children:n("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. ")})]}),(t.autoSummarizeTitles||t.useAiMergeCommitSummary||t.githubTrackingEnabledByDefault||!1)&&e.jsx("p",{className:"settings-description",children:n("settings.movedStub.summarizerModelInline","The summarization model lane above controls title auto-summarization, merge commit summaries, GitHub tracking titles, and PR metadata generation.")})]})}function gn({message:a,onOpenWorkflowSettings:t}){const{t:s}=q("app");return e.jsxs("div",{className:"settings-moved-stub",role:"note",children:[e.jsx("p",{className:"settings-moved-stub__message",children:a}),e.jsx("button",{type:"button",className:"settings-moved-stub__action",onClick:t,disabled:!t,children:s("settings.movedStub.openWorkflowSettings","Open workflow settings")})]})}const Va=1440*60*1e3,dc=2;function uc({scopeBanner:a,form:t,setForm:s,globalMaxConcurrent:u,concurrencyLoading:r=!1,onGlobalMaxConcurrentChange:m,onOverlapIgnorePathChange:o,onOpenOverlapPathPicker:n,onRemoveOverlapIgnorePath:d,onAddOverlapIgnorePath:w,onOpenWorkflowSettings:b}){const{t:c}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.scheduling.scheduling","Scheduling")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalMaxConcurrent",children:c("settings.scheduling.globalMaxConcurrent","Global Max Concurrent")}),e.jsx("input",{id:"globalMaxConcurrent",type:"number",min:0,max:1e4,disabled:r,value:u??"",onChange:h=>{const P=h.target.value;m(P===""?void 0:Number(P))}}),e.jsx("small",{className:"form-text text-muted",children:c("settings.scheduling.maximumConcurrentAgentsAcrossAllProjects","Maximum concurrent agents across all projects")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxConcurrent",children:c("settings.scheduling.maxConcurrentTasks","Max Concurrent Tasks")}),e.jsx("input",{id:"maxConcurrent",type:"number",min:1,max:10,disabled:r,value:t.maxConcurrent??"",onChange:h=>{const P=h.target.value;s(g=>({...g,maxConcurrent:P===""?void 0:Number(P)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxTriageConcurrent",children:c("settings.scheduling.maxTriageConcurrent","Max Triage Concurrent")}),e.jsx("input",{id:"maxTriageConcurrent",type:"number",min:1,max:10,disabled:r,value:t.maxTriageConcurrent??"",onChange:h=>{const P=h.target.value;s(g=>({...g,maxTriageConcurrent:P===""?void 0:Number(P)}))}}),e.jsx("small",{children:c("settings.scheduling.maximumConcurrentPlanningAgents","Maximum concurrent planning agents")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pollIntervalMs",children:c("settings.scheduling.pollIntervalMs","Poll Interval (ms)")}),e.jsx("input",{id:"pollIntervalMs",type:"number",min:5e3,step:1e3,value:t.pollIntervalMs??"",onChange:h=>{const P=h.target.value;s(g=>({...g,pollIntervalMs:P===""?void 0:Number(P)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"heartbeatScopeDiscipline",children:c("settings.scheduling.heartbeatScopeDiscipline","Heartbeat Scope Discipline")}),e.jsxs("select",{id:"heartbeatScopeDiscipline",className:"select",value:t.heartbeatScopeDiscipline??"strict",onChange:h=>{s(P=>({...P,heartbeatScopeDiscipline:h.target.value}))},children:[e.jsx("option",{value:"strict",children:c("settings.scheduling.strictDefault","Strict (default)")}),e.jsx("option",{value:"lite",children:c("settings.scheduling.lite","Lite")}),e.jsx("option",{value:"off",children:c("settings.scheduling.off","Off")})]}),e.jsx("small",{children:c("settings.scheduling.strictCoordinationFocusedHigherPerTickTokensLite","Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"engineerBacklogAutoClaim",className:"checkbox-label",children:[e.jsx("input",{id:"engineerBacklogAutoClaim",type:"checkbox",checked:t.engineerBacklogAutoClaim===!0,onChange:h=>s(P=>({...P,engineerBacklogAutoClaim:h.target.checked}))}),c("settings.scheduling.letEngineerAgentsAutoClaimBacklogTasks"," Let engineer agents auto-claim backlog tasks ")]}),e.jsx("small",{children:c("settings.scheduling.backlogNoTaskAutoClaimIsExecutorOnly","Backlog/no-task auto-claim is executor-only by default. Enable to let engineer-role agents auto-claim unowned backlog tasks; explicit routing and delegation are unchanged. Default: off.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskStuckTimeoutMs",children:c("settings.scheduling.stuckTaskTimeoutMinutes","Stuck Task Timeout (minutes)")}),e.jsx("input",{id:"taskStuckTimeoutMs",type:"number",min:1,step:1,value:t.taskStuckTimeoutMs?Math.round(t.taskStuckTimeoutMs/6e4):"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,taskStuckTimeoutMs:P&&g>0?g*6e4:void 0}))}}),e.jsx("small",{children:c("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.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"staleHighFanoutBlockerAgeThresholdMs",children:c("settings.scheduling.staleHighFanOutEscalationHours","Stale High Fan-out Escalation (hours)")}),e.jsx("input",{id:"staleHighFanoutBlockerAgeThresholdMs",type:"number",min:1,step:1,value:t.staleHighFanoutBlockerAgeThresholdMs?Math.round(t.staleHighFanoutBlockerAgeThresholdMs/36e5):"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,staleHighFanoutBlockerAgeThresholdMs:P&&g>0?g*36e5:void 0}))}}),e.jsx("small",{children:c("settings.scheduling.escalateHighFanOutBlockersOnlyAfterThey","Escalate high fan-out blockers only after they remain in in-progress or in-review for this many hours (age source: columnMovedAt, fallback updatedAt). Default: 2 hours.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"preserveProgressOnStuckRequeue",className:"checkbox-label",children:[e.jsx("input",{id:"preserveProgressOnStuckRequeue",type:"checkbox",checked:t.preserveProgressOnStuckRequeue!==!1,onChange:h=>s(P=>({...P,preserveProgressOnStuckRequeue:h.target.checked}))}),c("settings.scheduling.preserveStepProgressOnStuckTaskRequeue"," Preserve step progress on stuck-task requeue ")]}),e.jsx("small",{children:c("settings.scheduling.whenTheStuckDetectorKillsAndReQueues","When the stuck detector kills and re-queues a task, keep completed step statuses so the agent can resume from where it left off. Disable to reset every step to pending on each stuck retry. Default: enabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"specStalenessEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"specStalenessEnabled",type:"checkbox",checked:t.specStalenessEnabled||!1,onChange:h=>s(P=>({...P,specStalenessEnabled:h.target.checked}))}),c("settings.scheduling.enablePlanStalenessEnforcement"," Enable plan staleness enforcement ")]}),e.jsx("small",{children:c("settings.scheduling.whenEnabledTasksWithStalePlansPROMPTMd","When enabled, tasks with stale plans (PROMPT.md older than the threshold) are automatically sent back to planning for replanning")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"specStalenessMaxAgeMs",children:c("settings.scheduling.staleSpecThresholdHours","Stale Spec Threshold (hours)")}),e.jsx("input",{id:"specStalenessMaxAgeMs",type:"number",min:0,step:1,value:t.specStalenessMaxAgeMs!==void 0?Math.round(t.specStalenessMaxAgeMs/36e5):"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,specStalenessMaxAgeMs:P!==""?g*36e5:void 0}))},disabled:!t.specStalenessEnabled}),e.jsx("small",{children:c("settings.scheduling.maximumAgeInHoursBeforeAPlanIs","Maximum age in hours before a plan is considered stale. Default: 6 hours.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoArchiveDoneTasksEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoArchiveDoneTasksEnabled",type:"checkbox",checked:t.autoArchiveDoneTasksEnabled??!0,onChange:h=>s(P=>({...P,autoArchiveDoneTasksEnabled:h.target.checked}))}),c("settings.scheduling.enableAutomaticTaskArchiving"," Enable automatic task archiving ")]}),e.jsx("small",{children:c("settings.scheduling.completedTasksOlderThanTheThresholdAreMoved","Completed tasks older than the threshold are moved out of the active task database.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoArchiveDoneAfterMs",children:c("settings.scheduling.archiveCompletedTasksAfterDays","Archive Completed Tasks After (days)")}),e.jsx("input",{id:"autoArchiveDoneAfterMs",type:"number",min:1,step:1,value:t.autoArchiveDoneAfterMs!==void 0?Math.round(t.autoArchiveDoneAfterMs/Va):dc,onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,autoArchiveDoneAfterMs:P===""?void 0:g*Va}))},disabled:t.autoArchiveDoneTasksEnabled===!1}),e.jsx("small",{children:c("settings.scheduling.numberOfDaysATaskCanStayIn","Number of days a task can stay in Done before it is archived. Default: 2 days (48 hours).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"archiveAgentLogMode",children:c("settings.scheduling.archiveAgentLog","Archive Agent Log")}),e.jsxs("select",{id:"archiveAgentLogMode",value:t.archiveAgentLogMode??"compact",onChange:h=>s(P=>({...P,archiveAgentLogMode:h.target.value})),disabled:t.autoArchiveDoneTasksEnabled===!1,children:[e.jsx("option",{value:"compact",children:c("settings.scheduling.compactSummaryAndRecentEntries","Compact summary and recent entries")}),e.jsx("option",{value:"none",children:c("settings.scheduling.doNotArchiveAgentLogs","Do not archive agent logs")}),e.jsx("option",{value:"full",children:c("settings.scheduling.fullAgentLog","Full agent log")})]}),e.jsx("small",{children:c("settings.scheduling.compactModeKeepsArchiveSizeLowWhilePreserving","Compact mode keeps archive size low while preserving recent agent activity for context.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxStuckKills",children:c("settings.scheduling.maxStuckRetries","Max Stuck Retries")}),e.jsx("input",{id:"maxStuckKills",type:"number",min:1,step:1,value:t.maxStuckKills??"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,maxStuckKills:P&&g>0?g:void 0}))}}),e.jsx("small",{children:c("settings.scheduling.maximumStuckDetectorRetriesBeforeATaskIs","Maximum stuck-detector retries before a task is marked failed. Default: 6.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"groupOverlappingFiles",className:"checkbox-label",children:[e.jsx("input",{id:"groupOverlappingFiles",type:"checkbox",checked:t.groupOverlappingFiles,onChange:h=>s(P=>({...P,groupOverlappingFiles:h.target.checked}))}),c("settings.scheduling.serializeTasksWithOverlappingFiles"," Serialize tasks with overlapping files ")]}),e.jsx("small",{children:c("settings.scheduling.whenEnabledTasksThatModifyTheSameFiles","When enabled, tasks that modify the same files are queued serially to avoid merge conflicts")})]}),e.jsxs("div",{className:"form-group settings-overlap-ignore-group",children:[e.jsx("label",{children:c("settings.scheduling.ignoredOverlapPaths","Ignored overlap paths")}),e.jsxs("small",{children:[c("settings.scheduling.optionalFileOrDirectoryPathsToIgnoreWhen"," Optional file or directory paths to ignore when overlap serialization is enabled. Paths are project-relative (for example "),e.jsx("code",{children:"docs/"}),c("settings.scheduling.or"," or "),e.jsx("code",{children:"generated/*"}),c("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",{type:"text",value:h,placeholder:c("settings.scheduling.docs","docs/"),onChange:g=>o(P,g.target.value)}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>n(P),"aria-label":`Browse path for ignored overlap entry ${P+1}`,children:c("settings.scheduling.browse"," Browse ")})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>d(P),disabled:(t.overlapIgnorePaths??[]).length===0&&P===0,children:c("settings.scheduling.remove"," Remove ")})]},`overlap-ignore-${P}`))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:c("settings.scheduling.addIgnoredPath"," Add ignored path ")})]}),e.jsx("div",{className:"settings-section-divider"}),e.jsx("h5",{className:"settings-section-heading",children:c("settings.scheduling.stepExecution","Step Execution")}),e.jsx(gn,{message:c("settings.movedStub.stepExecution","Step execution settings (run steps in new sessions, max parallel steps) now live on the workflow."),onOpenWorkflowSettings:b})]})}function mc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app"),r=t.evalSettings??{},m=r.enabled??!1;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.scheduledEvals.scheduledEvals","Scheduled Evals")}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{htmlFor:"scheduled-evals-enabled",className:"checkbox-label",children:[e.jsx("input",{id:"scheduled-evals-enabled",type:"checkbox",checked:m,onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},enabled:o.target.checked}}))}),u("settings.scheduledEvals.enableScheduledEvalRunsForThisProject"," Enable scheduled eval runs for this project ")]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-interval",children:u("settings.scheduledEvals.intervalMs","Interval (ms)")}),e.jsx("input",{id:"scheduled-evals-interval",className:"input",type:"number",min:6e4,max:6048e5,step:1e3,disabled:!m,value:r.intervalMs??864e5,onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},intervalMs:o.target.value===""?void 0:Number(o.target.value)}}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-provider",children:u("settings.scheduledEvals.evaluatorProvider","Evaluator Provider")}),e.jsx("input",{id:"scheduled-evals-provider",className:"input",value:r.evaluatorProvider??"",onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},evaluatorProvider:o.target.value.trim()===""?void 0:o.target.value}})),placeholder:u("settings.scheduledEvals.openai","openai")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-model",children:u("settings.scheduledEvals.evaluatorModel","Evaluator Model")}),e.jsx("input",{id:"scheduled-evals-model",className:"input",value:r.evaluatorModelId??"",onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},evaluatorModelId:o.target.value.trim()===""?void 0:o.target.value}})),placeholder:u("settings.scheduledEvals.gpt5","gpt-5")}),e.jsx("small",{className:"form-text text-muted",children:u("settings.scheduledEvals.leaveProviderAndModelBlankToInheritThe"," Leave provider and model blank to inherit the project validator lane model settings. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-follow-up-policy",children:u("settings.scheduledEvals.followUpPolicy","Follow-up Policy")}),e.jsxs("select",{id:"scheduled-evals-follow-up-policy",className:"select",disabled:!m,value:r.followUpPolicy??"suggest-only",onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},followUpPolicy:o.target.value}})),children:[e.jsx("option",{value:"disabled",children:u("settings.scheduledEvals.disabled","Disabled")}),e.jsx("option",{value:"suggest-only",children:u("settings.scheduledEvals.suggestOnly","Suggest only")}),e.jsx("option",{value:"auto-create",children:u("settings.scheduledEvals.autoCreateTasks","Auto-create tasks")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-retention-days",children:u("settings.scheduledEvals.retentionDays","Retention (days)")}),e.jsx("input",{id:"scheduled-evals-retention-days",className:"input",type:"number",min:1,max:365,step:1,disabled:!m,value:r.retentionDays??30,onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},retentionDays:o.target.value===""?void 0:Number(o.target.value)}}))})]})]})}function hc(a,t){return a==="online"?t("settings.nodeRouting.statusOnline","Online"):a==="connecting"?t("settings.nodeRouting.statusConnecting","Connecting"):a==="error"?t("settings.nodeRouting.statusError","Error"):t("settings.nodeRouting.statusOffline","Offline")}function gc({scopeBanner:a,form:t,setForm:s,nodes:u}){const{t:r}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.nodeRouting.nodeRouting","Node Routing")}),e.jsx("p",{className:"settings-section-description",children:r("settings.nodeRouting.configureHowTasksAreRoutedToExecutionNodes","Configure how tasks are routed to execution nodes.")}),e.jsx("p",{className:"settings-node-routing-note",children:r("settings.nodeRouting.theseSettingsApplyAtTheProjectLevel","These settings apply at the project level.")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultNodeId",children:r("settings.nodeRouting.defaultExecutionNode","Default Execution Node")}),e.jsxs("select",{id:"defaultNodeId",className:"select",value:typeof t.defaultNodeId=="string"?t.defaultNodeId:"",onChange:m=>{const o=m.target.value;s(n=>({...n,defaultNodeId:o||void 0}))},children:[e.jsx("option",{value:"",children:r("settings.nodeRouting.localExecutionNoDefaultNode","Local execution (no default node)")}),u.map(m=>e.jsxs("option",{value:m.id,children:[m.name," (",hc(m.status,r),")"]},m.id))]}),(()=>{const m=u.find(o=>o.id===t.defaultNodeId);return m?e.jsxs("div",{className:"settings-node-status",children:[e.jsx("span",{children:r("settings.nodeRouting.selectedNode","Selected node:")}),e.jsx(ni,{status:m.status,showLabel:!0})]}):null})(),e.jsx("small",{children:r("settings.nodeRouting.usedWhenATaskHasNoNodeOverride","Used when a task has no node override. Node status is shown for safer routing selection.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"unavailableNodePolicy",children:r("settings.nodeRouting.unavailableNodePolicy","Unavailable Node Policy")}),e.jsxs("select",{id:"unavailableNodePolicy",className:"select",value:t.unavailableNodePolicy==="fallback-local"?"fallback-local":"block",onChange:m=>s(o=>({...o,unavailableNodePolicy:m.target.value})),children:[e.jsx("option",{value:"block",children:r("settings.nodeRouting.blockExecution","Block execution")}),e.jsx("option",{value:"fallback-local",children:r("settings.nodeRouting.fallBackToLocal","Fall back to local")})]})]})]})}function pc({scopeBanner:a,form:t,setForm:s,gitRemotes:u,worktrunkInstall:r,worktrunkInstallVerified:m,onOpenWorktreesDirPicker:o,onOpenApprovals:n}){const{t:d}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:d("settings.worktrees.worktrees","Worktrees")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxWorktrees",children:d("settings.worktrees.maxWorktrees","Max Worktrees")}),e.jsx("input",{id:"maxWorktrees",type:"number",min:1,max:20,value:t.maxWorktrees??"",onChange:w=>{const b=w.target.value;s(c=>({...c,maxWorktrees:b===""?void 0:Number(b)}))}}),e.jsx("small",{children:d("settings.worktrees.limitsTotalGitWorktreesIncludingInReviewTasks","Limits total git worktrees including in-review tasks")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeInitCommand",children:d("settings.worktrees.worktreeInitCommand","Worktree Init Command")}),e.jsx("input",{id:"worktreeInitCommand",type:"text",placeholder:d("settings.worktrees.pnpmInstallFrozenLockfile","pnpm install --frozen-lockfile"),value:t.worktreeInitCommand||"",onChange:w=>s(b=>({...b,worktreeInitCommand:w.target.value}))}),e.jsx("small",{children:d("settings.worktrees.shellCommandToRunInEachNewWorktree","Shell command to run in each new worktree after creation")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"recycleWorktrees",className:"checkbox-label",children:[e.jsx("input",{id:"recycleWorktrees",type:"checkbox",checked:t.recycleWorktrees,onChange:w=>s(b=>({...b,recycleWorktrees:w.target.checked}))}),d("settings.worktrees.recycleWorktrees"," Recycle worktrees ")]}),e.jsx("small",{children:d("settings.worktrees.offByDefaultOptInWhenEnabledCompleted","Off by default (opt-in). When enabled, completed task worktrees are returned to an idle pool instead of being deleted, preserving build caches for faster startup")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"executorAllowSiblingBranchRename",className:"checkbox-label",children:[e.jsx("input",{id:"executorAllowSiblingBranchRename",type:"checkbox",checked:t.executorAllowSiblingBranchRename===!0,onChange:w=>s(b=>({...b,executorAllowSiblingBranchRename:w.target.checked}))}),d("settings.worktrees.allowSilentSiblingBranchRenameDuringExecutorConflicts"," Allow silent sibling branch rename during executor conflicts ")]}),e.jsxs("small",{children:[d("settings.worktrees.discouragedThisRestoresTheLegacyBehaviorWhereA"," Discouraged. This restores the legacy behavior where a live "),e.jsx("code",{children:"fusion/<task-id>"}),d("settings.worktrees.branchCollisionSilentlyForksWorkOntoSiblingBranches"," branch collision silently forks work onto sibling branches like "),e.jsx("code",{children:"-2"}),d("settings.worktrees.andCanHidePriorCommitsFromTheDefault"," and can hide prior commits from the default recovery flow. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeNaming",children:d("settings.worktrees.worktreeNamingStyle","Worktree Naming Style")}),e.jsxs("select",{id:"worktreeNaming",value:t.worktreeNaming||"random",onChange:w=>s(b=>({...b,worktreeNaming:w.target.value})),disabled:t.recycleWorktrees,children:[e.jsx("option",{value:"random",children:d("settings.worktrees.randomNamesEGSwiftFalcon","Random names (e.g., swift-falcon)")}),e.jsx("option",{value:"task-id",children:d("settings.worktrees.taskIDEGFN042","Task ID (e.g., FN-042)")}),e.jsx("option",{value:"task-title",children:d("settings.worktrees.taskTitleEGFixLoginBug","Task title (e.g., fix-login-bug)")})]}),e.jsx("small",{children:t.recycleWorktrees?"Naming style is not applicable when recycling worktrees — pooled worktrees retain their existing names":"How to name fresh worktree directories. Only applies when recycling is off."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreesDir",children:d("settings.worktrees.worktreesDirectory","Worktrees Directory")}),e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{id:"worktreesDir",type:"text",placeholder:d("settings.worktrees.defaultsToWorktreesLeaveEmptyUnlessOverriding","Defaults to .worktrees — leave empty unless overriding"),value:t.worktreesDir||"",disabled:t.worktrunk?.enabled===!0,onChange:w=>s(b=>({...b,worktreesDir:w.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:o,"aria-label":d("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),disabled:t.worktrunk?.enabled===!0,children:d("settings.worktrees.browse"," Browse ")})]}),e.jsx("small",{children:t.worktrunk?.enabled===!0?"Disabled because Worktrunk integration is enabled — worktrunk manages the worktree directory layout. Disable worktrunk integration to use a custom directory.":e.jsxs(e.Fragment,{children:[d("settings.worktrees.optionalSupports"," Optional. Supports "),e.jsx("code",{children:"~"}),d("settings.worktrees.and"," and "),e.jsx("code",{children:"{repo}"}),d("settings.worktrees.defaultsTo",". Defaults to "),e.jsx("code",{children:"<projectRoot>/.worktrees"}),d("settings.worktrees.whenUnsetOnlyAffectsNewlyCreatedWorktrees"," when unset. Only affects newly-created worktrees. ")]})})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktreeRebaseBeforeMerge",className:"checkbox-label",children:[e.jsx("input",{id:"worktreeRebaseBeforeMerge",type:"checkbox",checked:t.worktreeRebaseBeforeMerge!==!1,onChange:w=>s(b=>({...b,worktreeRebaseBeforeMerge:w.target.checked}))}),d("settings.worktrees.rebaseFromRemoteBeforeMerge"," Rebase from remote before merge ")]}),e.jsx("small",{children:d("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.")})]}),t.worktreeRebaseBeforeMerge!==!1&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeRebaseRemote",children:d("settings.worktrees.rebaseRemote","Rebase Remote")}),e.jsxs("select",{id:"worktreeRebaseRemote",value:t.worktreeRebaseRemote??"",onChange:w=>s(b=>({...b,worktreeRebaseRemote:w.target.value||void 0})),children:[e.jsx("option",{value:"",children:d("settings.worktrees.useGitDefault","Use git default")}),u.map(w=>e.jsxs("option",{value:w.name,children:[w.name," (",w.fetchUrl,")"]},w.name))]}),e.jsxs("small",{children:[d("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"}),d("settings.worktrees.closeParenPeriod",").")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktreeRebaseLocalBase",className:"checkbox-label",children:[e.jsx("input",{id:"worktreeRebaseLocalBase",type:"checkbox",checked:t.worktreeRebaseLocalBase!==!1,onChange:w=>s(b=>({...b,worktreeRebaseLocalBase:w.target.checked}))}),d("settings.worktrees.alsoRebaseOntoLocalDefaultBranchHEAD"," Also rebase onto local default-branch HEAD ")]}),e.jsx("small",{children:d("settings.worktrees.inAdditionToTheRemoteRebaseAboveAlso"," In addition to the remote rebase above, also rebase the task branch onto the local default-branch HEAD (rootDir). This catches sibling tasks that merged locally but haven't been pushed yet — without it, two concurrent tasks where one deletes code can have the other silently re-introduce it via the fallback strategy. Enabled by default; only disable if it causes issues with your workflow. ")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.worktrees.worktrunkIntegration","Worktrunk integration")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktrunkEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"worktrunkEnabled",type:"checkbox",checked:t.worktrunk?.enabled===!0,disabled:!m&&t.worktrunk?.enabled!==!0,onChange:w=>s(b=>({...b,worktrunk:{enabled:w.target.checked,binaryPath:b.worktrunk?.binaryPath??"",onFailure:b.worktrunk?.onFailure??"fail"}}))}),d("settings.worktrees.enableWorktrunkIntegration"," Enable worktrunk integration ")]}),e.jsxs("small",{children:[d("settings.worktrees.disabledByDefaultOptInWhenEnabledFusion"," Disabled by default (opt-in). When enabled, Fusion shells out to "),e.jsx("code",{children:"worktrunk"}),d("settings.worktrees.forWorktreeCreateSyncPruneAndRemoveOperations"," for worktree create, sync, prune, and remove operations and follows worktrunk's directory layout. ")]}),!m&&t.worktrunk?.enabled!==!0&&e.jsx("small",{className:"settings-muted",children:d("settings.worktrees.installTheWorktrunkBinaryBelowToEnableThis","Install the worktrunk binary below to enable this integration.")})]}),e.jsxs("div",{className:"form-group","data-testid":"worktrunk-install-affordance",children:[r.status==="installed"&&e.jsxs("small",{className:"settings-muted",children:[d("settings.worktrees.worktrunk"," worktrunk "),r.version??"",d("settings.worktrees.installedAt"," installed at "),r.installPath??"~/.fusion/bin/worktrunk"]}),(r.status==="missing"||r.status==="installing")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void r.requestInstall(),disabled:r.requesting||r.status==="installing",children:d("settings.worktrees.installWorktrunk","Install worktrunk binary")}),e.jsx("small",{className:"settings-muted",children:d("settings.worktrees.enableWorktrunkAndRequestApprovalToInstallThe","Enable worktrunk and request approval to install the pinned release.")})]}),r.status==="pending-approval"&&e.jsxs(e.Fragment,{children:[e.jsx("small",{className:"settings-muted",children:d("settings.worktrees.awaitingApproval","Awaiting approval — open Approvals to continue.")}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>n?.(r.pendingApprovalId),children:d("settings.worktrees.openApprovals","Open Approvals")})]}),(r.status==="denied"||r.status==="failed")&&e.jsxs(e.Fragment,{children:[e.jsx("small",{style:{color:"var(--color-error)"},children:r.error??"Worktrunk install failed."}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void r.requestInstall(),children:d("settings.worktrees.tryAgain","Try again")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktrunkBinaryPath",children:d("settings.worktrees.worktrunkBinaryPath","Worktrunk binary path")}),e.jsx("input",{id:"worktrunkBinaryPath",type:"text",className:"input",placeholder:d("settings.worktrees.autoDetectFusionBinWorktrunkOrPATH","auto-detect (~/.fusion/bin/worktrunk or $PATH)"),value:t.worktrunk?.binaryPath??"",disabled:t.worktrunk?.enabled!==!0,onChange:w=>s(b=>({...b,worktrunk:{enabled:b.worktrunk?.enabled===!0,binaryPath:w.target.value,onFailure:b.worktrunk?.onFailure??"fail"}}))}),e.jsx("small",{children:d("settings.worktrees.optionalLeaveBlankToAutoResolveFusionWill","Optional. Leave blank to auto-resolve; Fusion will offer to install on first use.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktrunkOnFailure",children:d("settings.worktrees.worktrunkFailureBehavior","Worktrunk failure behavior")}),e.jsxs("select",{id:"worktrunkOnFailure",className:"select",value:t.worktrunk?.onFailure??"fail",disabled:t.worktrunk?.enabled!==!0,onChange:w=>s(b=>({...b,worktrunk:{enabled:b.worktrunk?.enabled===!0,binaryPath:b.worktrunk?.binaryPath??"",onFailure:w.target.value}})),children:[e.jsx("option",{value:"fail",children:d("settings.worktrees.failAndPauseTheTaskDefault","Fail and pause the task (default)")}),e.jsx("option",{value:"fallback-native",children:d("settings.worktrees.fallBackToFusionsNativeWorktreeBackend","Fall back to Fusion's native worktree backend")})]}),e.jsxs("small",{children:[e.jsx("code",{children:"fail"}),d("settings.worktrees.stopsOnWorktrunkErrorsForExplicitOperatorRecovery"," stops on worktrunk errors for explicit operator recovery; "),e.jsx("code",{children:"fallback-native"}),d("settings.worktrees.keepsProgressMovingBySwitchingToFusionApos"," keeps progress moving by switching to Fusion's built-in worktree backend. ")]})]})]})}function bc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.commands.commands","Commands")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"testCommand",children:u("settings.commands.testCommand","Test Command")}),e.jsx("input",{id:"testCommand",type:"text",placeholder:u("settings.commands.eGPnpmTest","e.g. pnpm test"),value:t.testCommand||"",onChange:r=>s(m=>({...m,testCommand:r.target.value||void 0}))}),e.jsx("small",{children:u("settings.commands.commandUsedToRunTestsInjectedIntoGenerated","Command used to run tests — injected into generated task specs")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"buildCommand",children:u("settings.commands.buildCommand","Build Command")}),e.jsx("input",{id:"buildCommand",type:"text",placeholder:u("settings.commands.eGPnpmBuild","e.g. pnpm build"),value:t.buildCommand||"",onChange:r=>s(m=>({...m,buildCommand:r.target.value||void 0}))}),e.jsx("small",{children:u("settings.commands.commandUsedToBuildTheProjectInjectedInto","Command used to build the project — injected into generated task specs")})]})]})}function fc(a){const t=Number(a);return Number.isFinite(t)&&t>0?Math.floor(t):3}async function vc(a){if(!a.ok)throw new Error(await a.text()||"Failed to load legacy auto-merge stamps");return a.json()}function xc({scopeBanner:a,form:t,setForm:s,integrationBranchOptions:u,integrationBranchCustomMode:r,setIntegrationBranchCustomMode:m,onOpenWorkflowSettings:o}){const{t:n}=q("app"),[d,w]=i.useState([]),[b,c]=i.useState(!0),[h,P]=i.useState(!1),[g,x]=i.useState(null),[f,j]=i.useState(null),k=i.useCallback(async()=>{c(!0),x(null);try{const v=await vc(await fetch("/api/maintenance/legacy-automerge-stamps"));w(Array.isArray(v.candidates)?v.candidates:[])}catch(v){x(v instanceof Error?v.message:"Failed to load legacy auto-merge stamps")}finally{c(!1)}},[]);i.useEffect(()=>{k()},[k]);const R=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.")){P(!0),x(null),j(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 V=await M.json();j(`Cleared ${V.count} legacy auto-merge stamp${V.count===1?"":"s"}.`),await k()}catch(M){x(M instanceof Error?M.message:"Failed to apply legacy auto-merge stamp cleanup")}finally{P(!1)}}};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.merge.merge","Merge")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoMerge",className:"checkbox-label",children:[e.jsx("input",{id:"autoMerge",type:"checkbox",checked:t.autoMerge,onChange:v=>s(M=>({...M,autoMerge:v.target.checked}))}),n("settings.merge.autoMergeCompletedTasks"," Auto-merge completed tasks ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.whenEnabledTasksThatPassReviewAreAutomatically","When enabled, tasks that pass review are automatically merged into the main branch")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxAutoMergeRetries",children:n("settings.merge.autoMergeConflictRetries","Auto-merge conflict retries")}),e.jsx("input",{id:"maxAutoMergeRetries",type:"number",min:1,step:1,value:t.maxAutoMergeRetries??3,onChange:v=>s(M=>({...M,maxAutoMergeRetries:v.target.value===""?void 0:fc(v.target.value)}))}),e.jsx("small",{children:n("settings.merge.positiveIntegerRetryCapForAutoMergeConflict","Positive integer retry cap for auto-merge conflict resolution before a task parks for human recovery. Default 3.")})]}),e.jsxs("div",{className:"form-group","data-testid":"legacy-automerge-stamp-cleanup-panel",children:[e.jsx("h5",{className:"settings-section-heading",children:n("settings.merge.legacyAutoMergeStampCleanup","Legacy auto-merge stamp cleanup")}),e.jsx("small",{children:n("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. ")}),b?e.jsx("small",{"aria-live":"polite",children:n("settings.merge.checkingForLegacyAutoMergeStamps","Checking for legacy auto-merge stamps…")}):d.length===0?e.jsx("small",{"data-testid":"legacy-automerge-stamp-empty-state",children:n("settings.merge.noLegacyAutoMergeStampsToCleanUp"," No legacy auto-merge stamps to clean up. ")}):e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:[d.length,n("settings.merge.legacyAutoMergeStamp"," legacy auto-merge stamp"),d.length===1?"":"s",n("settings.merge.readyToCleanUp"," ready to clean up.")]}),e.jsx("ul",{children:d.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:R,disabled:h,"data-testid":"legacy-automerge-stamp-apply-button",children:h?"Applying cleanup…":"Apply cleanup"})]}),f?e.jsx("small",{className:"settings-success","aria-live":"polite",children:f}):null,g?e.jsx("small",{className:"settings-error",role:"alert",children:g}):null]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergerMode",children:n("settings.merge.aIMerge","AI merge")}),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:n("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:n("settings.merge.deterministicLegacyRebaseConflictStrategyAuditPipeline","Deterministic (legacy) — rebase / conflict-strategy / audit pipeline")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("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:n("settings.merge.theLegacyMergeSettingsBelowDoNotApply","The legacy merge settings below do not apply while AI merge is on.")})]})]})]}),(t.merger?.mode??"ai")==="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergerMaxReviewPasses",children:n("settings.merge.maxAIReviewPasses","Max AI review passes")}),e.jsx("input",{id:"mergerMaxReviewPasses",type:"number",min:0,max:10,value:t.merger?.maxReviewPasses??3,onChange:v=>s(M=>({...M,merger:{...M.merger??{},maxReviewPasses:v.target.value===""?void 0:Number(v.target.value)}}))}),e.jsx("small",{children:n("settings.merge.aICorrectiveRoundsBeforeLandingTheBestResult","AI corrective rounds before landing the best result (advisory concern) or hard-failing (unfixable correctness concern). Default 3. The reviewer uses your project's reviewer/validator model.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"mergerAllowDirtyLocalCheckoutSync",className:"checkbox-label",children:[e.jsx("input",{id:"mergerAllowDirtyLocalCheckoutSync",type:"checkbox",checked:t.merger?.allowDirtyLocalCheckoutSync===!0,onChange:v=>s(M=>({...M,merger:{...M.merger??{},allowDirtyLocalCheckoutSync:v.target.checked}}))}),n("settings.merge.allowAIMergeToSyncADirtyChecked"," Allow AI merge to sync a dirty checked-out integration branch ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.dangerousCompatibilityEscapeHatchLeaveOffUnlessYou"," Dangerous compatibility escape hatch. Leave off unless you explicitly want 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. ")})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"testMode",className:"checkbox-label",children:[e.jsx("input",{id:"testMode",type:"checkbox",checked:t.testMode===!0,onChange:v=>s(M=>({...M,testMode:v.target.checked}))}),n("settings.merge.enableTestMode"," Enable test mode ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.forcesAllAILanesToUseTheDeterministic","Forces all AI lanes to use the deterministic mock provider. No network calls, zero token cost.")})]})]}),e.jsx(gn,{message:n("settings.movedStub.reviewVerification","Review, verification auto-fix, and scope-enforcement settings now live on the workflow."),onOpenWorkflowSettings:o}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeStrategy",children:n("settings.merge.autoCompletionMode","Auto-completion mode")}),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:n("settings.merge.directMergeIntoTheCurrentBranch","Direct merge into the current branch")}),e.jsx("option",{value:"pull-request",children:n("settings.merge.createMonitorAndMergeAGitHubPullRequest","Create, monitor, and merge a GitHub pull request")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.controlsWhatHappensAfterATaskReachesIn"," Controls what happens after a task reaches In Review. Direct mode merges into the current branch locally. Pull request mode keeps the task in In Review while Fusion waits for GitHub reviews and required checks before merging the PR. ")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"integrationBranch",children:n("settings.merge.integrationBranch","Integration branch")}),(()=>{const v=t.integrationBranch??"",M=v.length>0&&u.includes(v);if(r||v.length>0&&!M)return e.jsxs("div",{className:"form-inline-group",children:[e.jsx("input",{id:"integrationBranch",type:"text",className:"input",placeholder:n("settings.merge.branchName","branch name"),value:v,onChange:O=>{const K=O.target.value.trim();s($=>({...$,integrationBranch:K.length===0?void 0:K}))},"data-testid":"integration-branch-custom-input"}),e.jsx("button",{type:"button",className:"btn-link",onClick:()=>{m(!1),s(O=>({...O,integrationBranch:void 0}))},"data-testid":"integration-branch-use-dropdown",children:n("settings.merge.useDropdown"," Use dropdown ")})]});const N="__fusion-custom__",Z="";return e.jsxs("select",{id:"integrationBranch",className:"select",value:v,onChange:O=>{const K=O.target.value;if(K===N){m(!0);return}s($=>({...$,integrationBranch:K===Z?void 0:K}))},"data-testid":"integration-branch-select",children:[e.jsx("option",{value:Z,children:n("settings.merge.autoDetectOriginHEADMain","(auto-detect — origin/HEAD → main)")}),u.map(O=>e.jsx("option",{value:O,children:O},O)),e.jsx("option",{value:N,children:n("settings.merge.custom","Custom…")})]})})(),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.theCanonicalBranchFusionMergesTasksIntoAnd"," 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:n("settings.merge.autoDetect","auto-detect")}),n("settings.merge.toResolveViaTheStandardCascade"," to resolve via the standard cascade ("),e.jsx("code",{children:"integrationBranch"}),n("settings.merge.legacy"," → legacy "),e.jsx("code",{children:"baseBranch"})," →",e.jsx("code",{children:"origin/HEAD"}),n("settings.merge.symbolicRefFallback"," symbolic ref → fallback "),e.jsx("code",{children:"main"}),n("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"}),n("settings.merge.and",", and "),e.jsx("code",{children:"develop"}),n("settings.merge.areListedFirstOrChoose"," are listed first — or choose "),e.jsx("em",{children:n("settings.merge.custom","Custom…")}),n("settings.merge.toTypeABranchThatDoesnAposT"," to type a branch that doesn't exist locally yet. Applies to both direct merges and pull-request mode; individual tasks can still override via task metadata. ")]})]})]}),t.mergeStrategy!=="pull-request"&&(t.merger?.mode??"ai")!=="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"directMergeCommitStrategy",children:n("settings.merge.directMergeCommitRouting","Direct merge commit routing")}),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:n("settings.merge.autoSquashSingleSubstantiveBranchesPreserveMultiSubstantive","Auto — squash single-substantive branches, preserve multi-substantive history")}),e.jsx("option",{value:"always-squash",children:n("settings.merge.alwaysSquashDirectMerges","Always squash direct merges")}),e.jsx("option",{value:"always-rebase",children:n("settings.merge.alwaysPreserveDirectMergeCommitHistory","Always preserve direct-merge commit history")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.autoKeepsTodayAposSSquashBehaviorFor"," Auto keeps today's squash behavior for branches with zero or one substantive commit, but switches multi-substantive branches to a history-preserving rebase-and-merge path. Individual tasks can override this in PROMPT.md with "),e.jsx("code",{children:"**Direct Merge Commit Strategy:** auto|always-squash|always-rebase"}),"."]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeIntegrationWorktree",children:n("settings.merge.integrationWorktree","Integration worktree")}),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:n("settings.merge.reuseTaskWorktreeDefault","Reuse task worktree (default)")}),e.jsx("option",{value:"cwd-main",children:n("settings.merge.useProjectRootLegacy","Use project root (legacy)")})]}),e.jsx("small",{children:n("settings.merge.autoMergeRunsInTheTaskWorktreeBy"," Auto-merge runs in the task worktree by default. Switch to the legacy project-root path only if you need the pre-FN-5279 fallback; worktrunk-managed projects still defer to worktrunk. ")}),(t.mergeIntegrationWorktree??"reuse-task-worktree")!=="reuse-task-worktree"&&e.jsxs("div",{className:"settings-warning-banner",role:"alert","aria-live":"polite","data-testid":"merge-integration-worktree-warning",children:[e.jsx("strong",{children:n("settings.merge.legacyIntegrationBranchMode","Legacy integration-branch mode.")})," ",n("settings.merge.autoMergeWillRunRebaseConflictResolutionAnd"," Auto-merge will run rebase, conflict resolution, and squash commits inside the project root (the user's checked-out integration-branch worktree) instead of the task worktree. Fusion assumes that directory is already on the integration branch and clean; if it isn't, merges may fail or touch the user's working tree. Reuse-task-worktree is the recommended default (FN-5279). Switch back unless you have a specific reason to opt in (FN-5348). ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeAdvanceAutoSync",children:n("settings.merge.autoSyncProjectCheckoutAfterMerge","Auto-sync project checkout after merge")}),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:n("settings.merge.stashFastForwardDefaultPreserveLocalEdits","Stash + fast-forward (default) — preserve local edits")}),e.jsx("option",{value:"ff-only",children:n("settings.merge.fastForwardOnlySkipDirtyWorktrees","Fast-forward only — skip dirty worktrees")}),e.jsx("option",{value:"off",children:n("settings.merge.offLeaveTheProjectRootStaleLegacyBehavior","Off — leave the project root stale (legacy behavior)")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("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"}),n("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"}),n("settings.merge.snapsCleanlyWhenTheWorktreeHasNoEdits"," snaps cleanly when the worktree has no edits and skips otherwise. "),e.jsx("code",{children:"Off"}),n("settings.merge.isTheLegacyBehavior"," is the legacy behavior: "),e.jsx("code",{children:"git status"}),n("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.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.merge.gitHubAuthentication","GitHub Authentication")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubAuthMode",children:n("settings.merge.gitHubAuthMode","GitHub auth mode")}),e.jsxs("select",{id:"githubAuthMode",className:"select",value:t.githubAuthMode??"gh-cli",onChange:v=>s(M=>({...M,githubAuthMode:v.target.value})),children:[e.jsx("option",{value:"gh-cli",children:n("settings.merge.gitHubCLIGhAuth","GitHub CLI (gh auth)")}),e.jsx("option",{value:"token",children:n("settings.merge.personalAccessToken","Personal access token")})]})]}),(t.githubAuthMode??"gh-cli")==="token"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubAuthToken",children:n("settings.merge.gitHubPersonalAccessToken","GitHub personal access token")}),e.jsx("input",{id:"githubAuthToken",type:"password",className:"input",value:t.githubAuthToken??"",onChange:v=>s(M=>({...M,githubAuthToken:v.target.value||void 0}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"includeTaskIdInCommit",className:"checkbox-label",children:[e.jsx("input",{id:"includeTaskIdInCommit",type:"checkbox",checked:t.includeTaskIdInCommit!==!1,onChange:v=>s(M=>({...M,includeTaskIdInCommit:v.target.checked}))}),n("settings.merge.includeTaskIDInCommitScope"," Include task ID in commit scope ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.whenDisabledMergeCommitMessagesOmitTheTask","When disabled, merge commit messages omit the task ID from the scope (e.g. "),e.jsx("code",{children:"feat: ..."}),n("settings.merge.insteadOf"," instead of "),e.jsx("code",{children:"feat(KB-001): ..."}),")"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"commitAuthorEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"commitAuthorEnabled",type:"checkbox",checked:t.commitAuthorEnabled!==!1,onChange:v=>s(M=>({...M,commitAuthorEnabled:v.target.checked}))}),n("settings.merge.addFusionAsCoAuthorOnCommits"," Add Fusion as co-author on commits ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("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"}),n("settings.merge.trailerCreditingFusionRecognizedByGitHubForShared"," trailer crediting Fusion (recognized by GitHub for shared attribution). ")]})]})]}),t.commitAuthorEnabled!==!1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorName",children:n("settings.merge.coAuthorName","Co-author Name")}),e.jsx("input",{id:"commitAuthorName",type:"text",value:t.commitAuthorName??"",placeholder:n("settings.merge.fusion","Fusion"),onChange:v=>s(M=>({...M,commitAuthorName:v.target.value||void 0}))}),e.jsxs("small",{children:[n("settings.merge.nameUsedInThe","Name used in the "),e.jsx("code",{children:"Co-authored-by"}),n("settings.merge.trailer"," trailer")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorEmail",children:n("settings.merge.coAuthorEmail","Co-author Email")}),e.jsx("input",{id:"commitAuthorEmail",type:"email",value:t.commitAuthorEmail??"",placeholder:n("settings.merge.noreplyRunfusionAi","noreply@runfusion.ai"),onChange:v=>s(M=>({...M,commitAuthorEmail:v.target.value||void 0}))}),e.jsxs("small",{children:[n("settings.merge.emailUsedInThe","Email used in the "),e.jsx("code",{children:"Co-authored-by"}),n("settings.merge.trailer"," trailer")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoResolveConflicts",className:"checkbox-label",children:[e.jsx("input",{id:"autoResolveConflicts",type:"checkbox",checked:t.autoResolveConflicts!==!1,onChange:v=>s(M=>({...M,autoResolveConflicts:v.target.checked}))}),n("settings.merge.autoResolveConflictsInLockFilesAndGenerated"," Auto-resolve conflicts in lock files and generated files ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("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.")})]})]}),(t.merger?.mode??"ai")!=="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"smartConflictResolution",className:"checkbox-label",children:[e.jsx("input",{id:"smartConflictResolution",type:"checkbox",checked:t.smartConflictResolution!==!1,onChange:v=>s(M=>({...M,smartConflictResolution:v.target.checked}))}),n("settings.merge.smartConflictResolution"," Smart conflict resolution ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("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.")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeConflictStrategy",children:n("settings.merge.conflictFallbackStrategy","Conflict Fallback Strategy")}),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:n("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:n("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:n("settings.merge.aIOnlyAIAutoResolveAIRetryNever","AI only — AI → auto-resolve → AI retry; never silently pick a side")}),e.jsx("option",{value:"abort",children:n("settings.merge.abortOneAIAttemptRequireManualResolutionIf","Abort — one AI attempt; require manual resolution if it fails")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.both"," Both "),e.jsx("strong",{children:n("settings.merge.smart","Smart")}),n("settings.merge.optionsStartWithABestEffort"," options start with a best-effort "),e.jsx("code",{children:"git fetch"}),n("settings.merge.fastForwardOfLocalMainFrom"," + fast-forward of local main from "),e.jsx("code",{children:"origin"}),n("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:n("settings.merge.finalFallback","final fallback")}),":"," ",e.jsx("strong",{children:n("settings.merge.smartPreferMain","Smart, prefer main")}),n("settings.merge.uses"," uses "),e.jsx("code",{children:"-X ours"}),n("settings.merge.soMainWinsProtectsJustMergedSiblingWork"," so main wins — protects just-merged sibling work and is the new default. ")," ",e.jsx("strong",{children:n("settings.merge.smartPreferTask","Smart, prefer task")}),n("settings.merge.uses"," uses "),e.jsx("code",{children:"-X theirs"}),n("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:n("settings.merge.aIOnly","AI only")}),n("settings.merge.retriesTheAIAgentRatherThanAutoPicking"," retries the AI agent rather than auto-picking a side. ")," ",e.jsx("strong",{children:n("settings.merge.abort","Abort")}),n("settings.merge.stopsAfterTheFirstAIAttemptAndWaits"," stops after the first AI attempt and waits for a human. ")," ",e.jsxs("em",{children:[n("settings.merge.legacy2","Legacy "),e.jsx("code",{children:'"smart"'}),n("settings.merge.and2"," and "),e.jsx("code",{children:'"prefer-main"'}),n("settings.merge.valuesFromOlderSettingsAreMigratedAutomatically"," values from older settings are migrated automatically.")]})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeStrategyOverlapBehavior",children:n("settings.merge.smartPreferMainOverlapGuard","Smart Prefer Main Overlap Guard")}),e.jsxs("select",{id:"mergeStrategyOverlapBehavior",value:t.mergeStrategyOverlapBehavior??"flip-to-prefer-branch",onChange:v=>s(M=>({...M,mergeStrategyOverlapBehavior:v.target.value})),children:[e.jsx("option",{value:"flip-to-prefer-branch",children:n("settings.merge.flipOverlappingFilesToPreferTheTaskBranch","Flip overlapping files to prefer the task branch (default)")}),e.jsx("option",{value:"warn-only",children:n("settings.merge.warnOnlyKeepLegacyMainWinsFallback","Warn only — keep legacy main-wins fallback")}),e.jsx("option",{value:"ignore",children:n("settings.merge.ignoreOverlapDetectionPreserveLegacyBehavior","Ignore overlap detection — preserve legacy behavior")})]}),e.jsx("small",{children:n("settings.merge.whenUsingSmartPreferMainAutomaticallyPreferThe"," When using smart-prefer-main, automatically prefer the branch side for files that main has recently modified to avoid silently discarding branch work. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"postMergeAuditMode",children:n("settings.merge.postMergeAuditMode","Post-merge audit mode")}),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:n("settings.merge.blockStrict","Block (strict)")}),e.jsx("option",{value:"warn",children:n("settings.merge.warnDefaultLogFindingsContinue","Warn (default; log findings, continue)")}),e.jsx("option",{value:"off",children:n("settings.merge.offSkipAudit","Off (skip audit)")})]}),e.jsxs("small",{children:[n("settings.merge.controlsThePostMergeAuditGate"," Controls the post-merge audit gate. "),e.jsx("strong",{children:n("settings.merge.warn","Warn")}),n("settings.merge.defaultLogsFindingsButAutoCompletesTheMerge"," (default) logs findings but auto-completes the merge. "),e.jsx("strong",{children:n("settings.merge.block","Block")}),n("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:n("settings.merge.off","Off")}),n("settings.merge.skipsTheAuditEntirelySwitchingToOffIs"," skips the audit entirely. Switching to Off is recommended only if you trust your branches don't silently drop edits. ")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"pushAfterMerge",className:"checkbox-label",children:[e.jsx("input",{id:"pushAfterMerge",type:"checkbox",checked:t.pushAfterMerge===!0,onChange:v=>s(M=>({...M,pushAfterMerge:v.target.checked}))}),n("settings.merge.pushToRemoteAfterMerge"," Push to remote after merge ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("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.")})]})]}),t.pushAfterMerge&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pushRemote",children:n("settings.merge.pushRemote","Push Remote")}),e.jsx("input",{id:"pushRemote",type:"text",placeholder:n("settings.merge.origin","origin"),value:t.pushRemote||"",onChange:v=>s(M=>({...M,pushRemote:v.target.value||void 0}))}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.gitRemoteToPushToEGOrigin",'Git remote to push to (e.g. "origin"). Can include branch name (e.g. "origin main"). Default: "origin".')})]})]})]})}function Ya(a){return Array.from(new Set(a.split(/[\n,]+/).map(t=>t.trim()).filter(t=>t.length>0)))}function yc({value:a,onChange:t,disabled:s=!1}){const{t:u}=q("app"),r=a?.approvalMode??"trusted-only",m=a?.alwaysApproveDelete??!0,o={always:{label:u("agentProvisioning.always","Always require approval"),description:u("agentProvisioning.alwaysDesc","All fn_agent_create/fn_agent_delete requests require approval unless caller is trusted.")},"trusted-only":{label:u("agentProvisioning.trustedOnly","Trusted-only"),description:u("agentProvisioning.trustedOnlyDesc","Trusted roles/agent IDs bypass approval; other callers require approval.")},never:{label:u("agentProvisioning.never","Never require approval"),description:u("agentProvisioning.neverDesc","Allow provisioning without approval for non-privileged callers.")}},n=d=>{t({...a??{},...d})};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:u("agentProvisioning.approvalMode","Approval mode")}),e.jsx("select",{id:"agent-provisioning-approval-mode",className:"select",value:r,onChange:d=>n({approvalMode:d.target.value}),disabled:s,children:ri.map(d=>e.jsx("option",{value:d,children:o[d].label},d))}),e.jsx("small",{className:"agent-provisioning-policy-help",children:o[r].description})]}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{className:"checkbox-label",htmlFor:"agent-provisioning-always-approve-delete",children:[e.jsx("input",{id:"agent-provisioning-always-approve-delete",type:"checkbox",checked:m,onChange:d=>n({alwaysApproveDelete:d.target.checked}),disabled:s}),u("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:u("agentProvisioning.trustedRoles","Trusted roles")}),e.jsx("textarea",{id:"agent-provisioning-trusted-roles",className:"input agent-provisioning-policy-textarea",value:(a?.trustedRoles??[]).join(", "),onChange:d=>n({trustedRoles:Ya(d.target.value)}),disabled:s,placeholder:u("agentProvisioning.trustedRolesPlaceholder","reviewer, ceo"),rows:2})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-provisioning-trusted-agent-ids",children:u("agentProvisioning.trustedAgentIds","Trusted agent IDs")}),e.jsx("textarea",{id:"agent-provisioning-trusted-agent-ids",className:"input agent-provisioning-policy-textarea",value:(a?.trustedAgentIds??[]).join(", "),onChange:d=>n({trustedAgentIds:Ya(d.target.value)}),disabled:s,placeholder:u("agentProvisioning.trustedAgentIdsPlaceholder","agent-abc123"),rows:2})]}),e.jsx("p",{className:"agent-provisioning-policy-help",children:e.jsx(As,{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 ys(a){return li.reduce((t,s)=>(t[s]=a?.[s]??"allow",t),{})}function jc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.agentPermissions.agentPermissions","Agent Permissions")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:u("settings.agentPermissions.perAgentSettingsOverrideProjectDefaultsEachCategory","Per-agent settings override project defaults. Each category controls a separate approval gate.")})}),e.jsx(no,{mode:"project-default",value:t.defaultAgentPermissionPolicy?{presetId:"custom",rules:ys(t.defaultAgentPermissionPolicy.rules)}:{presetId:"custom",rules:ys()},onChange:r=>s(m=>({...m,defaultAgentPermissionPolicy:{rules:ys(r?.rules)}}))}),e.jsx("h4",{className:"settings-section-heading",children:u("settings.agentPermissions.agentProvisioningApprovals","Agent Provisioning Approvals")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:u("settings.agentPermissions.configureProjectLevelApprovalBehaviorForDurableProvisioning"," Configure project-level approval behavior for durable provisioning tools (fn_agent_create/fn_agent_delete). ")})}),e.jsx(yc,{value:t.agentProvisioning,onChange:r=>s(m=>({...m,agentProvisioning:r}))})]})}const kc=72;function wc(a,t){if(a.length<=t)return a;const s=Math.max(1,t-1),u=Math.ceil(s/2),r=Math.floor(s/2);return`${a.slice(0,u)}…${a.slice(a.length-r)}`}function Nc(a){const t=`${a.label} — ${a.path}`;return wc(t,kc)}function Cc({scopeBanner:a,form:t,setForm:s,memory:u}){const{t:r}=q("app"),{memoryCapabilities:m,memoryBackendStatus:o,memoryBackendLoading:n,memoryBackendError:d,memoryFiles:w,selectedMemoryPath:b,setSelectedMemoryPath:c,memoryContent:h,setMemoryContent:P,memoryLoading:g,memoryDirty:x,setMemoryDirty:f,memoryTestQuery:j,setMemoryTestQuery:k,memoryTestLoading:R,memoryTestResult:v,qmdInstallLoading:M,dreamRunning:V,memoryCompactLoading:N,onInstallQmd:Z,onTestMemoryRetrieval:O,onDreamNow:K,onCompactMemory:$,onSaveMemory:ee}=u,Q=t.memoryEnabled!==!1,B=!n&&o!==null,L=B?m?.writable??!0:!0,S=Q&&L,F=w.find(G=>G.path===b),te={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.memory.memory","Memory")}),e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"settings-muted",children:[r("settings.memory.memoryLivesIn"," Memory lives in "),e.jsx("code",{children:".fusion/memory/"}),r("settings.memory.agentsSearchWithQmdFirstFallBackTo",". Agents search with qmd first, fall back to local files when qmd is missing, and open exact line windows only when needed. ")]})}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryEnabled",type:"checkbox",checked:t.memoryEnabled!==!1,onChange:G=>s(J=>({...J,memoryEnabled:G.target.checked}))}),r("settings.memory.enableMemoryTools"," Enable memory tools ")]}),e.jsx("small",{children:r("settings.memory.agentsGetMemorySearchMemoryGetAndMemory","Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback.")})]}),n?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:r("settings.memory.checkingMemoryWriteAccess","Checking memory write access...")})}):d?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[r("settings.memory.failedToLoadBackendStatus","Failed to load backend status: "),d]})}):null,B&&o.qmdAvailable===!1&&e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:[r("settings.memory.qmdIsNotInstalledSearchWillUseLocal"," qmd is not installed. Search will use local files. Install indexed retrieval: "),e.jsx("code",{children:o.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Z,disabled:M,children:M?r("settings.memory.installing","Installing…"):r("settings.memory.installQmd","Install qmd")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryAutoSummarizeEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryAutoSummarizeEnabled",type:"checkbox",checked:t.memoryAutoSummarizeEnabled||!1,onChange:G=>s(J=>({...J,memoryAutoSummarizeEnabled:G.target.checked}))}),r("settings.memory.autoSummarizeMemory"," Auto-Summarize Memory ")]}),e.jsx("small",{children:r("settings.memory.automaticallyCompactMemoryWhenItExceedsTheThreshold","Automatically compact memory when it exceeds the threshold on a schedule")})]}),(t.memoryAutoSummarizeEnabled||!1)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeThresholdChars",children:r("settings.memory.compactionThresholdChars","Compaction Threshold (chars)")}),e.jsx("input",{id:"memoryAutoSummarizeThresholdChars",type:"number",className:"input",value:t.memoryAutoSummarizeThresholdChars??5e4,onChange:G=>s(J=>({...J,memoryAutoSummarizeThresholdChars:parseInt(G.target.value,10)||5e4})),min:1e3}),e.jsx("small",{children:r("settings.memory.memoryWillBeCompactedWhenItExceedsThis","Memory will be compacted when it exceeds this character count")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeSchedule",children:r("settings.memory.scheduleCron","Schedule (cron)")}),e.jsx("input",{id:"memoryAutoSummarizeSchedule",type:"text",className:"input",value:t.memoryAutoSummarizeSchedule??"0 3 * * *",onChange:G=>s(J=>({...J,memoryAutoSummarizeSchedule:G.target.value})),placeholder:r("settings.memory.03","0 3 * * *")}),e.jsx("small",{children:r("settings.memory.cronExpressionForAutoSummarizeScheduleDefaultDaily","Cron expression for auto-summarize schedule (default: daily at 3 AM)")})]})]}),e.jsx("div",{style:{borderTop:"1px solid var(--border)",margin:"var(--space-lg) 0"}}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryDreamsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryDreamsEnabled",type:"checkbox",checked:t.memoryDreamsEnabled===!0,onChange:G=>s(J=>({...J,memoryDreamsEnabled:G.target.checked})),disabled:!Q}),r("settings.memory.processDreamsFromDailyMemory"," Process dreams from daily memory ")]}),e.jsx("small",{children:r("settings.memory.turnsDailyNotesIntoDREAMSMdAndPromotes","Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md.")})]}),Q&&t.memoryDreamsEnabled===!0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryDreamsSchedule",children:r("settings.memory.dreamSchedule","Dream Schedule")}),e.jsx("input",{id:"memoryDreamsSchedule",type:"text",value:t.memoryDreamsSchedule??"0 4 * * *",onChange:G=>s(J=>({...J,memoryDreamsSchedule:G.target.value}))}),e.jsx("small",{children:r("settings.memory.cronExpressionForDreamProcessing","Cron expression for dream processing.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:K,disabled:V||t.memoryDreamsEnabled!==!0,children:V?e.jsxs(e.Fragment,{children:[e.jsx(Le,{size:14,className:"animate-spin"}),r("settings.memory.dreaming"," Dreaming… ")]}):r("settings.memory.dreamNow","Dream Now")}),e.jsx("small",{children:r("settings.memory.manuallyTriggerDreamProcessingNow","Manually trigger dream processing now.")})]})]}),e.jsxs("div",{className:"memory-retrieval-test",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryRetrievalQuery",children:r("settings.memory.testRetrieval","Test Retrieval")}),e.jsx("input",{id:"memoryRetrievalQuery",type:"text",value:j,onChange:G=>k(G.target.value),placeholder:r("settings.memory.searchMemoryWithQmd","Search memory with qmd")}),e.jsx("small",{children:r("settings.memory.runsTheSameQmdBackedMemorySearchPath","Runs the same qmd-backed memory_search path agents use.")})]}),e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:O,disabled:R,children:R?r("settings.memory.testing","Testing…"):r("settings.memory.testRetrieval","Test Retrieval")})}),v&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[v.results.length,r("settings.memory.result"," result"),v.results.length===1?"":"s"," ",r("settings.memory.for",'for "'),v.query,'"']}),e.jsxs("small",{children:[r("settings.memory.qmd"," qmd "),v.qmdAvailable?"available":"missing"," · ",v.usedFallback?"local fallback used":"qmd path used"]}),v.results.length>0?e.jsx("ul",{children:v.results.map((G,J)=>e.jsxs("li",{children:[e.jsxs("span",{children:[G.path,":",G.lineStart]}),e.jsx("p",{children:G.snippet})]},`${G.path}-${G.lineStart}-${J}`))}):e.jsx("small",{children:r("settings.memory.noMatchingMemoryFound","No matching memory found.")})]})]}),!Q&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:r("settings.memory.memoryIsCurrentlyDisabledYouCanViewThe"," Memory is currently disabled. You can view the file, but editing is read-only until memory is re-enabled. ")}),Q&&B&&!L&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:r("settings.memory.memoryIsConfiguredWithAReadOnlyBackend"," Memory is configured with a read-only backend. You can view the file, but saving is disabled. ")}),g?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:r("settings.memory.loadingMemory","Loading memory…")})}):e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryFilePath",children:r("settings.memory.memoryFile","Memory File")}),e.jsx("select",{id:"memoryFilePath",value:b,onChange:G=>{c(G.target.value),f(!1)},disabled:x,children:w.map(G=>e.jsx("option",{value:G.path,title:`${G.label} — ${G.path}`,children:Nc(G)},G.path))}),e.jsx("small",{children:x?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit. Dreams is selected by default."})]}),F&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:te[F.layer]}),e.jsx("strong",{children:F.path}),e.jsxs("small",{children:[F.size.toLocaleString(),r("settings.memory.bytesUpdated"," bytes · updated "),new Date(F.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group memory-editor-form-group",children:[e.jsx("label",{children:F?.label||"Memory Editor"}),e.jsxs("small",{children:[F?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",F?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",F?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!F&&"Edits the selected memory file."]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(ii,{content:h,onChange:G=>{P(G),f(!0)},readOnly:!S,filePath:b})})]})]}),!g&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:$,disabled:!S||x||N,children:N?r("settings.memory.compacting","Compacting…"):r("settings.memory.compactSelectedFile","Compact Selected File")}),e.jsx("small",{children:x?"Save or discard edits before compacting this file.":`Compacts ${b} and writes the result back to the same file.`})]}),x&&S&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:ee,children:r("settings.memory.saveMemory","Save Memory")})}),x&&!S&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[r("settings.memory.cannotSave","Cannot save: "),Q?"Backend is read-only":"Memory is disabled"]})})]})}function Sc({scopeBanner:a,form:t,setForm:s,researchLimitError:u}){const{t:r}=q("app"),m=t.researchSettings?.limits,o=t.researchSettings?.enabledSources;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.researchProject.projectResearchSettings","Project Research Settings")}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{htmlFor:"research-project-enabled",className:"checkbox-label",children:[e.jsx("input",{id:"research-project-enabled",type:"checkbox",checked:t.researchSettings?.enabled??!0,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},enabled:n.target.checked}}))}),r("settings.researchProject.enableResearchInThisProject"," Enable research in this project ")]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:r("settings.researchProject.enabledSources","Enabled Sources")}),e.jsxs("label",{htmlFor:"research-project-source-webSearch",className:"checkbox-label settings-research-source-locked",children:[e.jsx("input",{id:"research-project-source-webSearch",type:"checkbox",checked:!0,disabled:!0,readOnly:!0}),r("settings.researchProject.webSearch"," Web Search "),e.jsx("span",{className:"settings-muted",children:r("settings.researchProject.alwaysOn","Always on")})]}),e.jsx("small",{className:"settings-muted",children:r("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",r("settings.researchProject.pageFetch","Page Fetch")],["github",r("settings.researchProject.github","GitHub")],["localDocs",r("settings.researchProject.localDocs","Local Docs")],["llmSynthesis",r("settings.researchProject.llmSynthesis","LLM Synthesis")]].map(([n,d])=>e.jsxs("label",{htmlFor:`research-project-source-${n}`,className:"checkbox-label",children:[e.jsx("input",{id:`research-project-source-${n}`,type:"checkbox",checked:o?.[n]??!1,onChange:w=>s(b=>({...b,researchSettings:{...b.researchSettings??{},enabledSources:{...b.researchSettings?.enabledSources??{},[n]:w.target.checked}}}))}),d]},n))})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-research-limits-grid",children:[e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-concurrent",children:r("settings.researchProject.maxConcurrentRuns","Max Concurrent Runs")}),e.jsx("input",{id:"research-project-max-concurrent",className:"input",type:"number",min:1,value:m?.maxConcurrentRuns??3,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},maxConcurrentRuns:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-sources",children:r("settings.researchProject.maxSourcesPerRun","Max Sources Per Run")}),e.jsx("input",{id:"research-project-max-sources",className:"input",type:"number",min:1,value:m?.maxSourcesPerRun??20,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},maxSourcesPerRun:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-duration",children:r("settings.researchProject.maxDurationMs","Max Duration (ms)")}),e.jsx("input",{id:"research-project-max-duration",className:"input",type:"number",min:1e3,value:m?.maxDurationMs??3e5,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},maxDurationMs:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-request-timeout",children:r("settings.researchProject.requestTimeoutMs","Request Timeout (ms)")}),e.jsx("input",{id:"research-project-request-timeout",className:"input",type:"number",min:1e3,value:m?.requestTimeoutMs??3e4,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},requestTimeoutMs:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),u&&e.jsx("small",{className:"field-error settings-research-limits-error",children:u})]})})]})}function Pc({scopeBanner:a,form:t,setForm:s,backupInfo:u,backupLoading:r,onBackupNow:m}){const{t:o}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:o("settings.backups.databaseBackups","Database Backups")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoBackupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoBackupEnabled",type:"checkbox",checked:t.autoBackupEnabled||!1,onChange:n=>s(d=>({...d,autoBackupEnabled:n.target.checked}))}),o("settings.backups.enableAutomaticDatabaseBackups"," Enable automatic database backups ")]}),e.jsx("small",{children:o("settings.backups.whenEnabledTheDatabaseIsBackedUpAutomatically","When enabled, the database is backed up automatically on a schedule")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupSchedule",children:o("settings.backups.backupScheduleCron","Backup Schedule (Cron)")}),e.jsx("input",{id:"autoBackupSchedule",type:"text",placeholder:o("settings.backups.02","0 2 * * *"),value:t.autoBackupSchedule||"0 2 * * *",onChange:n=>s(d=>({...d,autoBackupSchedule:n.target.value})),disabled:!t.autoBackupEnabled}),e.jsx("small",{children:o("settings.backups.cronExpressionForBackupTimingDefault02"," Cron expression for backup timing. Default: 0 2 * * * (daily at 2 AM). Examples: 0 * * * * (hourly), 0 0 * * 0 (weekly), */15 * * * * (every 15 min) ")}),t.autoBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.autoBackupSchedule)&&e.jsx("small",{className:"field-error",children:o("settings.backups.invalidCronExpressionFormat","Invalid cron expression format")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupRetention",children:o("settings.backups.retentionCount","Retention Count")}),e.jsx("input",{id:"autoBackupRetention",type:"number",min:1,max:100,value:t.autoBackupRetention??"",onChange:n=>{const d=n.target.value;s(w=>({...w,autoBackupRetention:d===""?void 0:Number(d)}))},disabled:!t.autoBackupEnabled}),e.jsx("small",{children:o("settings.backups.numberOfBackupFilesToKeepOldestAre","Number of backup files to keep (oldest are deleted first). Range: 1-100.")}),t.autoBackupRetention!==void 0&&(t.autoBackupRetention<1||t.autoBackupRetention>100)&&e.jsx("small",{className:"field-error",children:o("settings.backups.mustBeBetween1And100","Must be between 1 and 100")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupDir",children:o("settings.backups.backupDirectory","Backup Directory")}),e.jsx("input",{id:"autoBackupDir",type:"text",placeholder:o("settings.backups.fusionBackups",".fusion/backups"),value:t.autoBackupDir||".fusion/backups",onChange:n=>s(d=>({...d,autoBackupDir:n.target.value})),disabled:!t.autoBackupEnabled}),e.jsx("small",{children:o("settings.backups.directoryForBackupFilesRelativeToProjectRoot","Directory for backup files, relative to project root")}),t.autoBackupDir&&t.autoBackupDir.includes("..")&&e.jsx("small",{className:"field-error",children:o("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)")})]}),e.jsx("h4",{className:"settings-section-heading",children:o("settings.backups.memoryBackups","Memory Backups")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryBackupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryBackupEnabled",type:"checkbox",checked:t.memoryBackupEnabled||!1,onChange:n=>s(d=>({...d,memoryBackupEnabled:n.target.checked}))}),o("settings.backups.enableAutomaticMemoryBackups"," Enable automatic memory backups ")]}),e.jsx("small",{children:o("settings.backups.whenEnabledProjectAndAgentMemoryFilesAre","When enabled, project and agent memory files are backed up automatically on a schedule.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupSchedule",children:o("settings.backups.memoryBackupScheduleCron","Memory Backup Schedule (Cron)")}),e.jsx("input",{id:"memoryBackupSchedule",type:"text",placeholder:o("settings.backups.03","0 3 * * *"),value:t.memoryBackupSchedule||"0 3 * * *",onChange:n=>s(d=>({...d,memoryBackupSchedule:n.target.value})),disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:o("settings.backups.cronExpressionForMemoryBackupTimingDefault0","Cron expression for memory backup timing. Default: 0 3 * * * (daily at 3 AM).")}),t.memoryBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.memoryBackupSchedule)&&e.jsx("small",{className:"field-error",children:o("settings.backups.invalidCronExpressionFormat","Invalid cron expression format")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupRetention",children:o("settings.backups.memoryRetentionCount","Memory Retention Count")}),e.jsx("input",{id:"memoryBackupRetention",type:"number",min:1,max:100,value:t.memoryBackupRetention??"",onChange:n=>{const d=n.target.value;s(w=>({...w,memoryBackupRetention:d===""?void 0:Number(d)}))},disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:o("settings.backups.numberOfMemoryBackupsToKeepOldestAre","Number of memory backups to keep (oldest are deleted first). Range: 1-100.")}),t.memoryBackupRetention!==void 0&&(t.memoryBackupRetention<1||t.memoryBackupRetention>100)&&e.jsx("small",{className:"field-error",children:o("settings.backups.mustBeBetween1And100","Must be between 1 and 100")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupDir",children:o("settings.backups.memoryBackupDirectory","Memory Backup Directory")}),e.jsx("input",{id:"memoryBackupDir",type:"text",placeholder:o("settings.backups.fusionBackupsMemory",".fusion/backups/memory"),value:t.memoryBackupDir||".fusion/backups/memory",onChange:n=>s(d=>({...d,memoryBackupDir:n.target.value})),disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:o("settings.backups.directoryForMemoryBackupsRelativeToProjectRoot","Directory for memory backups, relative to project root.")}),t.memoryBackupDir&&t.memoryBackupDir.includes("..")&&e.jsx("small",{className:"field-error",children:o("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupScope",children:o("settings.backups.memoryBackupScope","Memory Backup Scope")}),e.jsxs("select",{id:"memoryBackupScope",value:t.memoryBackupScope||"all",onChange:n=>s(d=>({...d,memoryBackupScope:n.target.value})),disabled:!t.memoryBackupEnabled,children:[e.jsx("option",{value:"all",children:o("settings.backups.allProjectAgents","All (project + agents)")}),e.jsx("option",{value:"project",children:o("settings.backups.projectOnlyFusionMemory","Project only (.fusion/memory)")}),e.jsx("option",{value:"agents",children:o("settings.backups.agentsOnlyFusionAgentMemory","Agents only (.fusion/agent-memory)")})]})]}),r?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:o("settings.backups.loadingBackupInfo","Loading backup info…")})}):u?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:o("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:u.count}),e.jsx("span",{className:"backup-stat-label",children:o("settings.backups.backups","backups")})]}),e.jsxs("div",{className:"backup-stat",children:[e.jsx("span",{className:"backup-stat-value",children:u.totalSize>1024*1024?`${(u.totalSize/(1024*1024)).toFixed(1)} MB`:`${(u.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:o("settings.backups.totalSize","total size")})]})]}),u.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:[o("settings.backups.view","View "),u.backups.length,o("settings.backups.backupS"," backup(s)")]}),e.jsxs("ul",{children:[u.backups.slice(0,10).map(n=>e.jsxs("li",{children:[e.jsx("code",{children:n.filename}),e.jsx("span",{className:"backup-size",children:n.size>1024*1024?`${(n.size/(1024*1024)).toFixed(1)} MB`:`${(n.size/1024).toFixed(1)} KB`})]},n.filename)),u.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:[o("settings.backups.and","...and "),u.backups.length-10,o("settings.backups.more"," more")]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:m,disabled:r,children:r?o("settings.backups.creating","Creating…"):o("settings.backups.backupNow","Backup Now")})})]})}const Ac=i.lazy(()=>cn(()=>import("./PluginManager-Bgd8Hj0a.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(a=>({default:a.PluginManager}))),Mc=i.lazy(()=>cn(()=>import("./PiExtensionsManager-BsA3tCZh.js"),__vite__mapDeps([14,1,2,3,4,5,6,7,8,9,15,16,17])).then(a=>({default:a.PiExtensionsManager})));function Tc({scopeBanner:a,projectId:t,addToast:s,activePluginsSubsection:u,setActivePluginsSubsection:r}){const{t:m}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:m("settings.plugins.plugins","Plugins")}),e.jsxs("div",{className:"settings-plugins-subsection-toggle",role:"tablist","aria-label":m("settings.plugins.pluginManagerType","Plugin manager type"),children:[e.jsx("button",{type:"button",id:"plugins-tab-fusion-plugins",role:"tab","aria-controls":"plugins-panel-fusion-plugins","aria-selected":u==="fusion-plugins",tabIndex:u==="fusion-plugins"?0:-1,className:`settings-plugins-subsection-btn${u==="fusion-plugins"?" active":""}`,onClick:()=>r("fusion-plugins"),children:m("settings.plugins.fusionPlugins"," Fusion Plugins ")}),e.jsx("button",{type:"button",id:"plugins-tab-pi-extensions",role:"tab","aria-controls":"plugins-panel-pi-extensions","aria-selected":u==="pi-extensions",tabIndex:u==="pi-extensions"?0:-1,className:`settings-plugins-subsection-btn${u==="pi-extensions"?" active":""}`,onClick:()=>r("pi-extensions"),children:m("settings.plugins.piExtensions"," Pi Extensions ")})]}),e.jsx("div",{id:"plugins-panel-fusion-plugins",role:"tabpanel","aria-labelledby":"plugins-tab-fusion-plugins",className:"settings-plugins-subsection-panel",hidden:u!=="fusion-plugins",children:u==="fusion-plugins"&&e.jsxs(e.Fragment,{children:[e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ac,{addToast:s,projectId:t})}),e.jsx(Ps,{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:u!=="pi-extensions",children:u==="pi-extensions"&&e.jsx(i.Suspense,{fallback:null,children:e.jsx(Mc,{addToast:s,projectId:t})})})]})}function js(a,t){if(!t)return a;const s=a.includes("?")?"&":"?";return`${a}${s}projectId=${encodeURIComponent(t)}`}async function Qa(a,t){const s=await fetch(a,{credentials:"same-origin",...t,headers:{"Content-Type":"application/json",...t?.headers??{}}}),u=await s.json();if(!s.ok)throw new Error(u.error??`Request failed (${s.status})`);return u}function Rc(a){const[t,s]=i.useState({status:"missing"}),[u,r]=i.useState(!1),m=i.useCallback(async()=>{try{const n=await Qa(js("/api/worktrunk/status",a));s(n)}catch(n){s({status:"failed",error:n instanceof Error?n.message:"Failed to load worktrunk status"})}},[a]);i.useEffect(()=>{m()},[m]),i.useEffect(()=>oi(js("/api/events",a),{events:{"approval:updated":()=>{t.pendingApprovalId&&m()},"approval:decided":()=>{t.pendingApprovalId&&m()}}}),[a,m,t.pendingApprovalId]);const o=i.useCallback(async()=>{r(!0),s(n=>({...n,status:"installing",error:void 0}));try{const n=await Qa(js("/api/worktrunk/install-request",a),{method:"POST",body:JSON.stringify({})});s({status:n.status,version:n.version,installPath:n.installPath,pendingApprovalId:n.pendingApprovalId??n.approvalRequestId,error:n.error})}catch(n){s({status:"failed",error:n instanceof Error?n.message:"Failed to request install"})}finally{r(!1)}},[a]);return{...t,requestInstall:o,requesting:u}}const ks="fusion_github_star_count",Xa=3600*1e3,Ja="fusion:github-star-clicked";function Ic({size:a=13}){return e.jsx("svg",{"data-testid":"discord-icon",width:a,height:a,viewBox:"0 0 24 24",role:"img","aria-hidden":"true",fill:"currentColor",children:e.jsx("path",{d:"M20.317 4.369A19.791 19.791 0 0 0 15.885 3a13.66 13.66 0 0 0-.696 1.412 18.27 18.27 0 0 0-6.378 0A13.627 13.627 0 0 0 8.115 3a19.736 19.736 0 0 0-4.432 1.369C.878 8.604.111 12.734.494 16.803a19.916 19.916 0 0 0 5.993 3.048 14.43 14.43 0 0 0 1.286-2.106 12.94 12.94 0 0 1-2.024-.977c.17-.122.337-.249.499-.381 3.908 1.838 8.149 1.838 12.01 0 .163.132.329.259.5.381a12.936 12.936 0 0 1-2.028.978 14.344 14.344 0 0 0 1.287 2.105 19.85 19.85 0 0 0 5.996-3.049c.449-4.713-.766-8.806-3.696-12.433zM8.02 14.335c-1.184 0-2.157-1.085-2.157-2.419 0-1.334.95-2.418 2.157-2.418 1.217 0 2.167 1.095 2.157 2.418 0 1.334-.95 2.419-2.157 2.419zm7.975 0c-1.184 0-2.157-1.085-2.157-2.419 0-1.334.95-2.418 2.157-2.418 1.217 0 2.167 1.095 2.157 2.418 0 1.334-.94 2.419-2.157 2.419z"})})}function Ec(a){const t=new Map;for(const s of a){const u=`${s.owner}/${s.repo}`;t.has(u)||t.set(u,{value:u,label:u})}return[...t.values()].sort((s,u)=>s.value.localeCompare(u.value))}function Fc(){const[a,t]=i.useState(()=>{try{return localStorage.getItem(Ja)==="true"}catch{return!1}}),s=i.useCallback(()=>{t(!0);try{localStorage.setItem(Ja,"true")}catch{}},[]);return[a,s]}function Lc(){const[a,t]=i.useState(()=>{try{const s=localStorage.getItem(ks);if(s){const u=JSON.parse(s);if(Date.now()-u.fetchedAt<Xa)return u.count}}catch{}return null});return i.useEffect(()=>{try{const s=localStorage.getItem(ks);if(s){const u=JSON.parse(s);if(Date.now()-u.fetchedAt<Xa)return}}catch{}fetch("https://api.github.com/repos/Runfusion/Fusion").then(s=>{if(s.ok)return s.json()}).then(s=>{if(s&&typeof s.stargazers_count=="number"){const u={count:s.stargazers_count,fetchedAt:Date.now()};try{localStorage.setItem(ks,JSON.stringify(u))}catch{}t(s.stargazers_count)}}).catch(()=>{})},[]),a}const Za="(max-width: 768px)",ws=".fusion/memory/DREAMS.md";function en(a){const t=Number(a?.maxAutoMergeRetries);return Number.isFinite(t)&&t>0?Math.floor(t):3}const tn=[{id:"__global_header",label:"Global",labelKey:"settings.nav.globalHeader",scope:void 0,isGroupHeader:!0},{id:"global-general",label:"General",labelKey:"settings.nav.globalGeneral",scope:"global"},{id:"authentication",label:"Authentication",labelKey:"settings.nav.authentication",scope:void 0,icon:nt},{id:"appearance",label:"Appearance",labelKey:"settings.nav.appearance",scope:"global"},{id:"notifications",label:"Notifications",labelKey:"settings.nav.notifications",scope:"global"},{id:"node-sync",label:"Node Sync",labelKey:"settings.nav.nodeSync",scope:"global"},{id:"global-models",label:"Models",labelKey:"settings.nav.globalModels",scope:"global"},{id:"cli-agents",label:"CLI Agents",labelKey:"settings.nav.cliAgents",scope:"global"},{id:"research-global",label:"Research Defaults",labelKey:"settings.nav.researchGlobal",scope:"global"},{id:"remote",label:"Remote Access & Node Sync",labelKey:"settings.nav.remote",scope:"global"},{id:"experimental",label:"Experimental Features",labelKey:"settings.nav.experimental",scope:"global"},{id:"__runtimes_header",label:"Runtimes",labelKey:"settings.nav.runtimesHeader",scope:void 0,isGroupHeader:!0},{id:"hermes-runtime",label:"Hermes",labelKey:"settings.nav.hermesRuntime",scope:"global"},{id:"openclaw-runtime",label:"OpenClaw",labelKey:"settings.nav.openclawRuntime",scope:"global"},{id:"paperclip-runtime",label:"Paperclip",labelKey:"settings.nav.paperclipRuntime",scope:"global"},{id:"__project_header",label:"Project",labelKey:"settings.nav.projectHeader",scope:void 0,isGroupHeader:!0},{id:"general",label:"Project General",labelKey:"settings.nav.projectGeneral",scope:"project"},{id:"commands",label:"Commands & Scripts",labelKey:"settings.nav.commands",scope:"project"},{id:"worktrees",label:"Worktrees",labelKey:"settings.nav.worktrees",scope:"project"},{id:"scheduling",label:"Scheduling & Capacity",labelKey:"settings.nav.scheduling",scope:"project"},{id:"scheduled-evals",label:"Scheduled Evals",labelKey:"settings.nav.scheduledEvals",scope:"project"},{id:"node-routing",label:"Node Routing",labelKey:"settings.nav.nodeRouting",scope:"project"},{id:"merge",label:"Merge",labelKey:"settings.nav.merge",scope:"project"},{id:"agent-permissions",label:"Agents & Permissions",labelKey:"settings.nav.agentPermissions",scope:"project"},{id:"memory",label:"Memory",labelKey:"settings.nav.memory",scope:"project"},{id:"backups",label:"Backups",labelKey:"settings.nav.backups",scope:"project"},{id:"research-project",label:"Research",labelKey:"settings.nav.researchProject",scope:"project"},{id:"project-models",label:"Project Models",labelKey:"settings.nav.projectModels",scope:"project"},{id:"secrets",label:"Secrets",labelKey:"settings.nav.secrets",scope:"project"},{id:"prompts",label:"Prompts",labelKey:"settings.nav.prompts",scope:"project"},{id:"plugins",label:"Plugins",labelKey:"settings.nav.plugins",scope:"project"}],Dc={insights:"Insights",memoryView:"Memory Editor",remoteAccess:"Remote Access",skillsView:"Skills View",nodesView:"Nodes View",devServerView:"Dev Server",todoView:"Todo List",researchView:"Research View",evalsView:"Evals View",goalsView:"Goals View",subtaskBreakdown:"Subtask Breakdown",leftSidebarNav:"Left Sidebar Navigation",sandbox:"Sandbox (command isolation)",chatRooms:"Chat Rooms",agentOnboarding:"Planning-style Agent Onboarding",workflowInterpreterDualObserve:"Workflow Graph Engine — dual-observe parity (diagnostic)"},Oc=new Set(["chatRooms","goalsView","insights","memoryView","roadmap","rightDock","skillsView","todoView","workflowColumns","workflowGraphExecutor","workflowInterpreterDualObserve"]),pn=new Set(["leftSidebarNav"]),Ct={devServer:"devServerView"};function Is(a){return Ct[a]??a}function wt(a,t){return a[t]===!0?!0:a[t]===!1?!1:Object.entries(Ct).some(([s,u])=>u===t&&a[s]===!0)?!0:pn.has(t)}function Bc(a,t){const s=Is(t);return pn.has(s)&&a[s]===void 0?!0:wt(a,s)}function Gc(a){if(!a)return{};const t={};for(const[s,u]of Object.entries(a))t[Is(s)]=u;for(const[s,u]of Object.entries(Ct))t[u]!==void 0&&!(s in t)&&(t[s]=null);return t}const Ns="global-general";function Wc({projectId:a,addToast:t}){const{t:s}=q("app"),{confirm:u}=dn(),[r,m]=i.useState([]),[o,n]=i.useState({}),[d,w]=i.useState({}),[b,c]=i.useState("");i.useEffect(()=>{let f=!1;return(async()=>{try{const[j,k]=await Promise.all([fetch("/api/cli-agents"),fetch("/api/cli-agents/settings")]),R=j.ok?await j.json():{adapters:[]},v=k.ok?await k.json():{cliAgents:{}};if(f)return;const M=R.adapters??[];m(M),n(v.cliAgents??{}),M.length>0&&c(V=>V||M[0].id)}catch{}})(),()=>{f=!0}},[]),i.useEffect(()=>{if(!b)return;let f=!1;return fetch(`/api/cli-agents/${b}/autonomy`).then(j=>j.ok?j.json():null).then(j=>{f||!j||w(k=>({...k,[b]:!!j.approved}))}).catch(()=>{}),()=>{f=!0}},[b]);const h=o[b]??{},P=i.useCallback(async(f,j)=>{try{const k=await fetch("/api/cli-agents/settings",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({adapterId:f,config:j})});if(!k.ok)throw new Error(`HTTP ${k.status}`);const R=await k.json();n(R.cliAgents??{})}catch(k){t(ie(k)||s("settings.cliAgents.saveFailed"),"error")}},[t,s]),g=i.useCallback(f=>{if(!b)return;const j={...h,...f};n(k=>({...k,[b]:j})),P(b,j)},[b,h,P]),x=i.useCallback(async f=>{if(b){if(f==="elevated"){if(!await u({title:s("settings.cliAgents.elevatedConfirmTitle"),message:s("settings.cliAgents.elevatedConfirmBody"),confirmLabel:s("settings.cliAgents.elevatedConfirmAction"),danger:!0}))return;try{const k=await fetch(`/api/cli-agents/${b}/approve-autonomy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:!0})});if(!k.ok)throw new Error(`HTTP ${k.status}`);w(R=>({...R,[b]:!0}))}catch(k){t(ie(k)||s("settings.cliAgents.approveFailed"),"error");return}}g({autonomyMode:f})}},[b,u,s,t,g]);return e.jsxs("div",{"data-testid":"cli-agents-settings",children:[e.jsx("h4",{className:"settings-section-heading",children:s("settings.cliAgents.heading")}),e.jsx("p",{className:"settings-section-description",children:s("settings.cliAgents.description")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAdapter",children:s("settings.cliAgents.adapterLabel")}),e.jsx("select",{id:"cliAgentAdapter",value:b,onChange:f=>c(f.target.value),children:r.map(f=>e.jsxs("option",{value:f.id,children:[f.name," (",s(`settings.cliAgents.tier.${f.tier}`),")"]},f.id))})]}),b&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentCommand",children:s("settings.cliAgents.commandLabel")}),e.jsx("input",{id:"cliAgentCommand",type:"text",placeholder:r.find(f=>f.id===b)?.defaultCommand??"",value:h.commandOverride??"",onChange:f=>g({commandOverride:f.target.value||void 0})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.commandHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentExtraArgs",children:s("settings.cliAgents.extraArgsLabel")}),e.jsx("input",{id:"cliAgentExtraArgs",type:"text",value:(h.extraArgs??[]).join(" "),onChange:f=>g({extraArgs:f.target.value.split(/\s+/).filter(j=>j.length>0)})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.extraArgsHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentEnv",children:s("settings.cliAgents.envLabel")}),e.jsx("input",{id:"cliAgentEnv",type:"text",value:(h.envAdditions??[]).join(", "),onChange:f=>g({envAdditions:f.target.value.split(",").map(j=>j.trim()).filter(j=>j.length>0)})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.envHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAutonomy",children:s("settings.cliAgents.autonomyLabel")}),e.jsxs("select",{id:"cliAgentAutonomy",value:h.autonomyMode??"default",onChange:f=>void x(f.target.value),children:[e.jsx("option",{value:"default",children:s("settings.cliAgents.autonomy.default")}),e.jsx("option",{value:"elevated",children:s("settings.cliAgents.autonomy.elevated")})]}),e.jsx("p",{className:"settings-field-help",children:d[b]?s("settings.cliAgents.approvedNote"):s("settings.cliAgents.autonomyHelp")})]})]})]})}function _c({onClose:a,addToast:t,projectId:s,initialSection:u,themeMode:r="dark",colorTheme:m="ocean",onThemeModeChange:o,onColorThemeChange:n,dashboardFontScalePct:d=100,shadcnCustomColors:w={},resolvedThemeMode:b,onDashboardFontScaleChange:c,onShadcnCustomColorsChange:h,onQuickChatButtonModeChange:P,onReopenOnboarding:g,onOpenApprovals:x,onOpenWorkflowSettings:f,presentation:j="modal"}){const{isEmbedded:k,scrollLockEnabled:R,resizePersistEnabled:v,escapeEnabled:M,overlayDismissEnabled:V}=Yi(j),{t:N}=q("app"),{confirm:Z}=dn(),O=Rc(s),K=O.status==="installed",$=ci();di(R);const{keyboardOverlap:ee,viewportHeight:Q,viewportOffsetTop:B,keyboardOpen:L}=ui({enabled:$==="mobile"}),S=L?{"--keyboard-overlap":`${ee}px`,"--vv-offset-top":`${B}px`,...Q!==null?{"--vv-height":`${Q}px`}:{}}:{},F=i.useRef(null),te=i.useRef(null),G=i.useRef(null),J=i.useCallback(l=>{G.current=l},[]);mi(F,v,"fusion:settings-modal-size");const me=hi(),[y,U]=i.useState({maxConcurrent:2,maxTriageConcurrent:2,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",maxAutoMergeRetries:3,mergeIntegrationWorktree:"reuse-task-worktree",mergeAdvanceAutoSync:"stash-and-ff",merger:{mode:"ai",maxReviewPasses:3,allowDirtyLocalCheckoutSync:!1},recycleWorktrees:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",worktreesDir:"",worktrunk:{enabled:!1,binaryPath:"",onFailure:"fail"},includeTaskIdInCommit:!0,worktreeInitCommand:"",ntfyEnabled:!1,ntfyTopic:void 0,ntfyAccessToken:void 0,failureNotificationMode:"sticky-only",failureNotificationDelayMs:3e4,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:void 0}),[ce,pe]=i.useState(!0),[fe,_]=i.useState(!1),[C,I]=i.useState(null),[z,ne]=i.useState(null),[le,Y]=i.useState(null),T=tn.find(l=>!l.isGroupHeader),[E,H]=i.useState(()=>u==="pi-extensions"?"plugins":u??Ns),[ae,ve]=i.useState(()=>u==="pi-extensions"?"pi-extensions":"fusion-plugins"),[St,bn]=i.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(Za)?.matches===!0:!1),[Oe,fn]=i.useState(null),[Es,Fs]=i.useState(!1),[ue,Ls]=i.useState(null),[Pt,Ds]=i.useState(!1),[lt,it]=i.useState(null),$e=Lc(),[vn,xn]=Fc(),[At,yn]=i.useState(null),[jn,Ke]=i.useState(null),[xe,Mt]=i.useState(null),[Os,Bs]=i.useState(!1),{entries:kn,currentPath:Ce,setPath:Tt,loading:wn,error:Nn,refresh:Cn}=Aa("project",xe!==null,s),{entries:Sn,currentPath:Pe,setPath:Rt,loading:Pn,error:An,refresh:Mn}=Aa("project",Os,s),{nodes:Tn}=gi(),It=y.experimentalFeatures??{},Et=wt(It,"remoteAccess"),Ft=wt(It,"researchView"),Lt=wt(It,"evalsView"),Re=tn.filter(l=>l.id==="remote"?Et:l.id==="research-global"||l.id==="research-project"?Ft:l.id==="scheduled-evals"?Lt:!0),ze=Re.some(l=>l.id===Ns)?Ns:Re.find(l=>!l.isGroupHeader)?.id??T?.id??"general",qe=Re.find(l=>l.id===E)?.scope;i.useEffect(()=>{if(E==="remote"&&!Et){H(ze);return}if((E==="research-global"||E==="research-project")&&!Ft){H(ze);return}if(E==="scheduled-evals"&&!Lt){H(ze);return}Re.some(l=>l.id===E)||H(ze)},[E,Et,Ft,Lt,ze,Re]);const[Be,Dt]=i.useState([]),[Rn,Gs]=i.useState(!1),[In,be]=i.useState(null),[En,Ot]=i.useState({}),[Fn,Ws]=i.useState({}),[Bt,_s]=i.useState({}),[Gt,Wt]=i.useState({}),[Ln,_t]=i.useState(null),[Ut,Ht]=i.useState({}),[Dn,ot]=i.useState({}),[On,Ve]=i.useState({}),he=i.useRef(null),Ye=i.useRef({}),[Us,Hs]=i.useState([]),[$s,Ks]=i.useState(!1),[Ge,$t]=i.useState([]),[We,Kt]=i.useState([]),[Bn,zs]=i.useState({}),[Gn,ct]=i.useState({}),[Qe,qs]=i.useState(null),[Se,Vs]=i.useState(null),[Wn,zt]=i.useState(null),[_n,dt]=i.useState(!1),[ye,ut]=i.useState(null),[qt,Vt]=i.useState(null),[Un,Ys]=i.useState(null),[Hn,Qs]=i.useState(!1),[$n,Yt]=i.useState(null),[Kn,zn]=i.useState("persistent"),[qn,Vn]=i.useState(null),[Yn,Qn]=i.useState(null),[Xn,Jn]=i.useState(null),[Zn,_e]=i.useState(null),[Qt,mt]=i.useState(""),[er,Xs]=i.useState(!1),[Xt,ht]=i.useState(!1),[tr,Js]=i.useState([]),[sr,Zs]=i.useState([]),[ar,nr]=i.useState(!1),[rr,ea]=i.useState([]),[lr,ta]=i.useState(!1),[ir,sa]=i.useState(null),[or,aa]=i.useState([]),[cr,na]=i.useState(!1),[dr,Jt]=i.useState(null),Zt=i.useRef(!1),[ur,ra]=i.useState([]),[je,es]=i.useState(ws),[ts,mr]=i.useState(""),[hr,la]=i.useState(!1),[gr,ia]=i.useState(null),[pr,oa]=i.useState(!1),[br,ca]=i.useState(!1),[fr,da]=i.useState(!1),ss=i.useRef(!1),[gt,ua]=i.useState(4),ma=i.useRef(4),ha=i.useRef(!1),as=i.useRef(!1),[vr,ga]=i.useState(!1),[xr,Xe]=i.useState(!1),[,ns]=i.useState(null),[ke,pa]=i.useState(null),[pt,bt]=i.useState(!1),[rs,yr]=i.useState("both"),[ls,jr]=i.useState(!0),ba=i.useRef(null),{status:kr,capabilities:wr,loading:Nr,error:Cr,refresh:fa}=lo({projectId:s,enabled:E==="memory"});i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia(Za);if(!l)return;const p=A=>{bn(A?A.matches:l.matches)};return p(),l.addEventListener("change",p),()=>l.removeEventListener("change",p)},[]),i.useEffect(()=>{Promise.all([Ma(s),pi(s)]).then(([l,p])=>{const A={...l,mergeIntegrationWorktree:Ra(l.mergeIntegrationWorktree),mergeAdvanceAutoSync:Ta(l.mergeAdvanceAutoSync),maxAutoMergeRetries:en(l)};U(A),I(A),ne(p),Y({...p,project:{...p.project,mergeIntegrationWorktree:p.project.mergeIntegrationWorktree===void 0?void 0:Ra(p.project.mergeIntegrationWorktree),mergeAdvanceAutoSync:p.project.mergeAdvanceAutoSync===void 0?void 0:Ta(p.project.mergeAdvanceAutoSync)}}),pe(!1)}).catch(l=>{t(ie(l),"error"),pe(!1)})},[t,s]),i.useEffect(()=>{if(E!=="scheduling"||ha.current)return;let l=!1;return bi().then(p=>{l||(as.current||ua(p.globalMaxConcurrent),ma.current=p.globalMaxConcurrent,ha.current=!0,ga(!0))}).catch(()=>{ga(!0)}),()=>{l=!0}},[E]),i.useEffect(()=>{let l=!1;return fi().then(p=>{l||typeof p.version=="string"&&p.version.trim().length>0&&fn(p.version)}).catch(()=>{}),()=>{l=!0}},[]);const Sr=i.useCallback(async()=>{Fs(!0),it(null);try{const l=await vi();Ls(l),l.error&&t(l.error,"error")}catch(l){const p=ie(l)||N("settings.general.updateCheckFailed","Failed to check for updates");Ls({currentVersion:Oe??"unknown",latestVersion:null,updateAvailable:!1,error:p}),t(p,"error")}finally{Fs(!1)}},[t,Oe,N]),va=i.useCallback(async()=>{Ds(!0),it(null);try{const l=await xi(s);if(it(l),l.error){t(l.error,"error");return}l.updated&&t(N("settings.general.updateSuccessToast","Update installed. Restart Fusion to apply it."),"success")}catch(l){const p=ie(l)||N("settings.general.updateFailed","Update failed");it({currentVersion:ue?.currentVersion??Oe??"unknown",latestVersion:ue?.latestVersion??null,updated:!1,error:p}),t(p,"error")}finally{Ds(!1)}},[t,Oe,s,N,ue]),Pr=i.useCallback(()=>{if(!ue)return null;if(ue.error)return ue.error;if(ue.updateAvailable&&ue.latestVersion){const l=lt?.updated===!0,p=lt?.error;return e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[N("settings.general.updateAvailablePrefix","v{{version}} available",{version:ue.latestVersion})," ·"," ",e.jsx("a",{href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",className:"settings-update-result-link",children:N("settings.general.learnMore","Learn more")})]}),l?e.jsx("span",{className:"settings-update-install-status settings-update-install-status--success","aria-live":"polite",children:N("settings.general.updateSuccess","Updated to v{{version}} — restart Fusion to apply",{version:lt.latestVersion??ue.latestVersion})}):e.jsx("button",{type:"button",className:"btn btn-sm settings-update-now-btn",onClick:()=>{va()},disabled:Pt,children:Pt?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{size:12,className:"spinning","aria-hidden":"true"}),N("settings.general.updating","Updating…")]}):N("settings.general.updateNow","Update now")}),p&&e.jsx("span",{className:"settings-update-install-status settings-update-install-status--error","aria-live":"polite",children:N("settings.general.updateFailedWithMessage","Update failed: {{message}}",{message:p})})]})}return N("settings.general.upToDate","You're up to date ✓")},[va,N,ue,Pt,lt]),de=i.useCallback(async()=>{try{const{providers:l}=await Ea(),p=Fa(l);Dt(p),Ot(A=>{const D={};for(const[W,X]of Object.entries(A)){const se=p.find(oe=>oe.id===W);se&&!se.authenticated&&(D[W]=X)}return Object.keys(D).length===Object.keys(A).length?A:D})}catch{}},[]);i.useEffect(()=>{(E==="global-models"||E==="project-models")&&(Ks(!0),yi().then(l=>{Hs(l.models),$t(l.favoriteProviders),Kt(l.favoriteModels)}).catch(()=>Hs([])).finally(()=>Ks(!1)))},[E]),i.useEffect(()=>{E==="backups"&&(dt(!0),La(s).then(l=>zt(l)).catch(()=>zt(null)).finally(()=>dt(!1)))},[E,s]);const ft=i.useCallback(async()=>{const[l,p]=await Promise.allSettled([ji(s),ms(s)]);l.status==="fulfilled"&&U(A=>({...A,...l.value.settings})),p.status==="fulfilled"&&(ut(p.value),Vt(p.value.externalTunnel??null))},[s]);i.useEffect(()=>{const l=ye?.state;(l==="running"||l==="starting")&&Vt(null)},[ye?.state]),i.useEffect(()=>{E==="remote"&&ft().catch(()=>{ut(null)})},[E,ft]),i.useEffect(()=>{if(E!=="remote")return;const l=ye?.state;if(l!=="starting"&&l!=="stopping")return;const p=setInterval(()=>{ms(s).then(A=>{ut(A),Vt(A.externalTunnel??null)}).catch(()=>{})},1e3);return()=>clearInterval(p)},[E,s,ye?.state]),i.useEffect(()=>{if(E!=="remote")return;if(ye?.state!=="running"){_e(null);return}let l=!1;return(async()=>{try{const p=await Ss("image/svg",{projectId:s,tokenType:"persistent"});if(l)return;_e({url:p.url,qrSvg:p.data??null})}catch{if(l)return;try{const p=await sn({projectId:s,tokenType:"persistent"});if(l)return;_e({url:p.url,qrSvg:null})}catch{l||_e(null)}}})(),()=>{l=!0}},[E,s,ye?.state,ye?.url]),i.useEffect(()=>{if(E!=="remote")return;const l=qt?.url;if(ye?.state!=="stopped"||!l)return;let p=!1;return(async()=>{try{const A=await Ss("image/svg",{projectId:s,tokenType:"persistent"});if(p)return;_e({url:l,qrSvg:A.data??null})}catch{p||_e({url:l,qrSvg:null})}})(),()=>{p=!0}},[E,qt?.url,s,ye?.state]),i.useEffect(()=>{E==="worktrees"&&ki(s).then(l=>Js(l)).catch(()=>Js([]))},[E,s]),i.useEffect(()=>{E==="merge"&&wi(s).then(l=>{const p=l.map(X=>X.name).filter(X=>typeof X=="string"&&X.length>0),A=new Set,D=["main","master","trunk","develop"],W=[];for(const X of D)p.includes(X)&&!A.has(X)&&(W.push(X),A.add(X));for(const X of[...p].sort((se,oe)=>se.localeCompare(oe)))A.has(X)||(A.add(X),W.push(X));Zs(W)}).catch(()=>Zs([]))},[E,s]),i.useEffect(()=>{if(E!=="general")return;let l=!1;return ta(!0),sa(null),Da(s).then(p=>{l||ea(Ec(p))}).catch(()=>{l||(ea([]),sa("Could not load detected remotes. Enter a custom owner/repo value."))}).finally(()=>{l||ta(!1)}),()=>{l=!0}},[E,s]),i.useEffect(()=>{if(E!=="global-general"||Zt.current)return;let l=!1;return na(!0),Jt(null),Ni().then(async p=>{const A=await Promise.allSettled(p.map(async se=>(await Da(se.id)).map(Ee=>({value:`${Ee.owner}/${Ee.repo}`,label:`${Ee.owner}/${Ee.repo}`,source:se.name}))));if(l)return;const D=new Map;let W=0;for(const se of A)if(se.status==="fulfilled"){W+=1;for(const oe of se.value)D.has(oe.value)||D.set(oe.value,oe)}const X=[...D.values()].sort((se,oe)=>se.value.localeCompare(oe.value));aa(X),p.length>0&&W===0&&Jt("Could not load remotes from registered projects. Enter a custom owner/repo value."),Zt.current=!0}).catch(()=>{l||(aa([]),Jt("Could not load project list. Enter a custom owner/repo value."),Zt.current=!0)}).finally(()=>{l||na(!1)}),()=>{l=!0}},[E,s]),i.useEffect(()=>{if(E!=="memory"||Xt)return;if(ss.current){ss.current=!1;return}let l=!1;return Xs(!0),Oa(s).then(async({files:p})=>{if(l)return;ra(p);const A=p.some(W=>W.path===je)?je:p.find(W=>W.path===ws)?.path??p.find(W=>W.layer==="dreams")?.path??p[0]?.path??ws;es(A);const{content:D}=await Ci(A,s);l||(mt(D),ht(!1))}).catch(p=>{l||(t(ie(p)||"Failed to load project memory","error"),mt(""))}).finally(()=>{l||Xs(!1)}),()=>{l=!0}},[E,Xt,je,s,t]),i.useEffect(()=>((E==="authentication"||E==="research-global")&&(Gs(!0),de().finally(()=>Gs(!1))),()=>{he.current&&(clearInterval(he.current),he.current=null)}),[E,de]),i.useEffect(()=>{if(E!=="authentication"||!Be.some(A=>A.type!=="api_key"&&A.loginInProgress))return;const p=setInterval(()=>{de()},2e3);return()=>clearInterval(p)},[E,Be,de]);const vt=i.useCallback(()=>{te.current?.scrollTo({top:0,behavior:"smooth"})},[]),Ie=i.useCallback(l=>{if(l in Ye.current){const p={...Ye.current};delete p[l],Ye.current=p}Ot(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A}),Ws(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A}),Wt(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A}),_s(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A})},[]);i.useEffect(()=>{const l=Bt["github-copilot"];l?.userCode&&Ye.current["github-copilot"]!==l.userCode&&(Ye.current["github-copilot"]=l.userCode,ln(l.userCode))},[Bt]);const Ar=i.useCallback(async l=>{const p=Be.find(A=>A.id===l);if(!(p?.requiresManualCode===!0&&!await Z({title:N("settings.auth.manualPasteTitle","Heads up — manual paste-back required"),message:N("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:p.name}),confirmLabel:N("settings.auth.continueToLogin","Continue to login"),cancelLabel:N("settings.actions.cancel","Cancel")}))){be(l),Ie(l);try{const{url:A,instructions:D,manualCode:W,deviceCode:X}=await Si(l);D?.trim()&&!(l==="github-copilot"&&X)&&Ot(se=>({...se,[l]:D})),W&&Ws(se=>({...se,[l]:W})),X&&l==="github-copilot"&&_s(se=>({...se,[l]:X})),(l!=="github-copilot"||!X)&&window.open(on(X?.verificationUri??A),"_blank"),he.current=setInterval(async()=>{try{const{providers:se}=await Ea(),oe=Fa(se);Dt(oe);const Ee=oe.find(ml=>ml.id===l);if(Ee?.authenticated){he.current&&(clearInterval(he.current),he.current=null),be(null),Ie(l),t(N("settings.auth.loginSuccessful","Login successful"),"success"),window.dispatchEvent(new CustomEvent(Pi,{detail:{providerId:l}})),vt();return}Ee?.loginInProgress||(he.current&&(clearInterval(he.current),he.current=null),be(null),Ie(l),t(N("settings.auth.loginDidNotComplete","Login did not complete. Please try again."),"error"))}catch{}},2e3)}catch(A){const D=ie(A)||"Login failed";D.includes("already in progress")||typeof A=="object"&&A!==null&&"status"in A&&A.status===409?(t(N("settings.auth.loginAlreadyInProgress","Login already in progress. You can cancel it and retry."),"warning"),await de()):t(D,"error"),be(null),Ie(l)}}},[t,Be,Ie,Z,de,vt]),Mr=i.useCallback(async l=>{const p=Gt[l]?.trim();if(!p){t(N("settings.auth.pasteRedirectUrlFirst","Paste the full redirect URL or authorization code first."),"warning");return}_t(l);try{(await Ai(l,p)).submitted?(Wt(D=>{if(!(l in D))return D;const W={...D};return delete W[l],W}),t(N("settings.auth.authCodeReceived","Authorization code received. Finishing login…"),"success")):t(N("settings.auth.authCodeAlreadySubmitted","That authorization code was already submitted. Waiting for login…"),"warning")}catch(A){t(ie(A)||"Failed to submit authorization code","error")}finally{_t(null)}},[t,Gt]),Tr=i.useCallback(async l=>{be(l),Dt(p=>p.map(A=>A.id===l?{...A,loginInProgress:!1}:A));try{await Mi(l),Ie(l),await de().catch(()=>{}),t(N("settings.auth.loginCancelled","Login cancelled"),"success")}catch(p){t(ie(p)||"Failed to cancel login","error")}finally{be(null),_t(p=>p===l?null:p),he.current&&(clearInterval(he.current),he.current=null)}},[t,Ie,de]),Rr=i.useCallback(async l=>{be(l);try{await Ti(l),await de(),t(N("settings.auth.loggedOut","Logged out"),"success")}catch(p){t(ie(p)||"Logout failed","error")}finally{be(null)}},[t,de]),Ir=i.useCallback(async l=>{const p=Ut[l]?.trim();if(!p){ot(A=>({...A,[l]:"API key is required"}));return}be(l),ot(A=>{const D={...A};return delete D[l],D});try{const A=await Ri(l,p);if(Ht(D=>{const W={...D};return delete W[l],W}),await de(),l==="opencode"||l==="opencode-go"){const D=A.modelsRefreshed,W=A.refreshReason,X=A.refreshError;X?Ve(se=>({...se,[l]:{tone:"error",message:`Saved, but model refresh failed: ${X}. Make sure the \`opencode\` CLI is installed on PATH.`}})):W==="no-models-from-cli"?Ve(se=>({...se,[l]:{tone:"error",message:"Saved. The local `opencode` CLI returned no models — run `opencode auth login` and `opencode models opencode --refresh`, then click Save again."}})):typeof D=="number"&&D>0?Ve(se=>({...se,[l]:{tone:"success",message:`Refreshed ${D} opencode-go models.`}})):Ve(se=>{const oe={...se};return delete oe[l],oe})}t(N("settings.auth.apiKeySaved","API key saved"),"success"),vt()}catch(A){ot(D=>({...D,[l]:ie(A)||"Failed to save API key"})),(l==="opencode"||l==="opencode-go")&&Ve(D=>{const W={...D};return delete W[l],W})}finally{be(null)}},[Ut,t,de,vt]),Er=i.useCallback(async l=>{be(l);try{await Ii(l),Ht(p=>{const A={...p};return delete A[l],A}),ot(p=>{const A={...p};return delete A[l],A}),await de(),t(N("settings.auth.apiKeyCleared","API key cleared"),"success")}catch(p){t(ie(p)||"Failed to clear API key","error")}finally{be(null)}},[t,de]),Fr=i.useCallback(async l=>{if(!((l==="ntfy"||l==="ntfy-message"||l==="ntfy-room")&&(!y.ntfyEnabled||!y.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(y.ntfyTopic)))){if(l==="webhook"){if(!y.webhookEnabled||!y.webhookUrl?.trim())return;try{const p=new URL(y.webhookUrl.trim());if(p.protocol!=="http:"&&p.protocol!=="https:")return}catch{return}}zs(p=>({...p,[l]:!0})),ct(p=>{const A={...p};return delete A[l],A});try{const p={ntfyEnabled:y.ntfyEnabled,ntfyTopic:y.ntfyTopic,...y.ntfyBaseUrl?.trim()?{ntfyBaseUrl:y.ntfyBaseUrl.trim()}:{},...y.ntfyAccessToken?.trim()?{ntfyAccessToken:y.ntfyAccessToken.trim()}:{}},A=l==="ntfy"?p:l==="ntfy-message"?{...p,messageEventType:"message:agent-to-user"}:l==="ntfy-room"?{...p,messageEventType:"message:room"}:{webhookUrl:y.webhookUrl,webhookFormat:y.webhookFormat||"generic"};if((await Ei(l==="ntfy-message"||l==="ntfy-room"?"ntfy":l,A,s)).success){const W=l==="ntfy"?"Test notification sent — check your ntfy app!":l==="ntfy-message"?"Message inbox test sent — check your ntfy inbox for the agent-to-user message.":l==="ntfy-room"?"Room reply test sent — check your ntfy inbox for the room reply.":"Test notification sent — check your webhook endpoint!";ct(X=>({...X,[l]:{status:"success",message:W}})),t(W,"success")}else{const W=l==="ntfy-message"?"Failed to send message inbox test":l==="ntfy-room"?"Failed to send room reply test":"Failed to send test notification";ct(X=>({...X,[l]:{status:"error",message:W}})),t(W,"error")}}catch(p){const A=ie(p)||"Failed to send test notification";ct(D=>({...D,[l]:{status:"error",message:A}})),t(A,"error")}finally{zs(p=>({...p,[l]:!1}))}}},[t,y.ntfyAccessToken,y.ntfyBaseUrl,y.ntfyEnabled,y.ntfyTopic,y.webhookEnabled,y.webhookFormat,y.webhookUrl,s]),Lr=i.useCallback(async()=>{dt(!0);try{const l=await Fi(s);if(l.success){t(N("settings.backups.backupCreated","Backup created successfully"),"success");const p=await La(s);zt(p)}else t(l.error||N("settings.backups.createFailed","Failed to create backup"),"error")}catch(l){t(ie(l)||N("settings.backups.createFailed","Failed to create backup"),"error")}finally{dt(!1)}},[t,s]),Dr=i.useCallback(async()=>{try{const l=qe==="global"?"global":qe==="project"?"project":"both",p=await Li(l,s),A=new Blob([JSON.stringify(p,null,2)],{type:"application/json"}),D=URL.createObjectURL(A),W=document.createElement("a"),X=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;W.href=D,W.download=X,document.body.appendChild(W),W.click(),document.body.removeChild(W),URL.revokeObjectURL(D);const se=l==="global"?N("settings.importExport.scopeLabel.global","global"):l==="project"?N("settings.importExport.scopeLabel.project","project"):N("settings.importExport.scopeLabel.all","all");t(N("settings.importExport.exported","Settings exported ({{scope}} scope)",{scope:se}),"success")}catch(l){t(ie(l)||N("settings.importExport.exportFailed","Failed to export settings"),"error")}},[t,qe,s]),Or=i.useCallback(async l=>{const p=l.target.files?.[0];if(p){ns(p),bt(!0);try{const A=await p.text(),D=JSON.parse(A);pa(D),Xe(!0)}catch(A){t(N("settings.importExport.invalidJson","Invalid JSON file: {{error}}",{error:ie(A)}),"error"),ns(null)}finally{bt(!1)}}},[t]),Br=i.useCallback(async()=>{if(ke){bt(!0);try{const l=await Di(ke,{scope:rs,merge:ls},s);if(l.success){const p=[];l.globalCount>0&&p.push(N("settings.importExport.counts.global","{{count}} global",{count:l.globalCount})),l.projectCount>0&&p.push(N("settings.importExport.counts.project","{{count}} project",{count:l.projectCount})),l.workflowSettingsCount>0&&p.push(N("settings.importExport.counts.workflowSettings","{{count}} workflow setting value",{count:l.workflowSettingsCount})),t(N("settings.importExport.imported","Imported {{counts}} setting(s)",{counts:p.join(", ")}),"success"),Xe(!1),pa(null),ns(null);const A=await Ma(s);U(A)}else t(l.error||N("settings.importExport.importFailed","Import failed"),"error")}catch(l){t(ie(l)||N("settings.importExport.importFailedDetailed","Failed to import settings"),"error")}finally{bt(!1)}}},[t,ke,rs,ls,s]),xa=i.useCallback(async l=>{const p=Ge,D=p.includes(l)?p.filter(W=>W!==l):[l,...p];$t(D);try{await st({favoriteProviders:D,favoriteModels:We})}catch{$t(p)}},[Ge,We]),ya=i.useCallback(async l=>{const p=We,D=p.includes(l)?p.filter(W=>W!==l):[l,...p];Kt(D);try{await st({favoriteProviders:Ge,favoriteModels:D})}catch{Kt(p)}},[We,Ge]);i.useEffect(()=>{if(!M)return;const l=p=>{p.key==="Escape"&&a()};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[a,M]);const Gr=Oi(a),Wr=V?Gr:{},ja=[{laneId:"default",label:"Default Model",globalProviderKey:"defaultProvider",globalModelKey:"defaultModelId",projectProviderKey:"defaultProviderOverride",projectModelKey:"defaultModelIdOverride",helperText:"Default AI model used for task execution when no per-task override is set.",fallbackOrder:"Project override → Global default lane → Automatic resolution"},{laneId:"execution",label:"Execution Model",globalProviderKey:"executionGlobalProvider",globalModelKey:"executionGlobalModelId",projectProviderKey:"executionProvider",projectModelKey:"executionModelId",helperText:"AI model used for task implementation (executor agent).",fallbackOrder:"Project override → Global execution lane → Global default lane → Automatic resolution"},{laneId:"planning",label:"Planning Model",globalProviderKey:"planningGlobalProvider",globalModelKey:"planningGlobalModelId",projectProviderKey:"planningProvider",projectModelKey:"planningModelId",helperText:"AI model used for task planning.",fallbackOrder:"Project override → Global planning lane → Global default lane → Automatic resolution"},{laneId:"validator",label:"Reviewer Model",globalProviderKey:"validatorGlobalProvider",globalModelKey:"validatorGlobalModelId",projectProviderKey:"validatorProvider",projectModelKey:"validatorModelId",helperText:"AI model used for code and specification review.",fallbackOrder:"Project override → Global reviewer lane → Global default lane → Automatic resolution"},{laneId:"summarization",label:"Title and Git Commit Message Summarization Model",globalProviderKey:"titleSummarizerGlobalProvider",globalModelKey:"titleSummarizerGlobalModelId",projectProviderKey:"titleSummarizerProvider",projectModelKey:"titleSummarizerModelId",helperText:"AI model used for auto-generating task titles and merge commit summaries.",fallbackOrder:"Project override → Global summarization lane → Project planning lane → Project default lane → Global default lane → Automatic resolution"}];function is(l){if(!z?.project)return"inherited";const p=z.project[l.projectProviderKey],A=z.project[l.projectModelKey];return p!==void 0||A!==void 0?"overridden":"inherited"}function _r(l){const p=y[l.projectProviderKey],A=y[l.projectModelKey];return p&&A?`${p}/${A}`:""}function Ur(l,p){if(p){const A=p.indexOf("/");U(D=>({...D,[l.projectProviderKey]:p.slice(0,A),[l.projectModelKey]:p.slice(A+1)}))}else{if(is(l)==="inherited")return;U(D=>({...D,[l.projectProviderKey]:void 0,[l.projectModelKey]:void 0}))}}function Hr(l){is(l)!=="inherited"&&U(A=>({...A,[l.projectProviderKey]:void 0,[l.projectModelKey]:void 0}))}const $r=i.useCallback(l=>{Mt(l),Tt(".")},[Tt]),Ae=i.useCallback(()=>{Mt(null)},[]),os=i.useCallback(l=>{xe!==null&&(U(p=>{const A=p.overlapIgnorePaths&&p.overlapIgnorePaths.length>0?[...p.overlapIgnorePaths]:[""];return A[xe]=l,{...p,overlapIgnorePaths:A}}),Ae())},[xe,Ae]),Kr=i.useCallback(()=>{if(Ce===".")return;const l=Ce.endsWith("/")?Ce:`${Ce}/`;os(l)},[Ce,os]),zr=i.useCallback(l=>{l.target===l.currentTarget&&Ae()},[Ae]),qr=i.useCallback(()=>{Rt("."),Bs(!0)},[Rt]),Me=i.useCallback(()=>{Bs(!1)},[]),Vr=i.useCallback(l=>{const p=l.endsWith("/")?l:`${l}/`;U(A=>({...A,worktreesDir:p})),Me()},[Me]),Yr=i.useCallback(()=>{const l=Pe==="."?"./":Pe.endsWith("/")?Pe:`${Pe}/`;U(p=>({...p,worktreesDir:l})),Me()},[Pe,Me]),Qr=i.useCallback(l=>{l.target===l.currentTarget&&Me()},[Me]),Xr=i.useCallback((l,p)=>{U(A=>{const D=A.overlapIgnorePaths&&A.overlapIgnorePaths.length>0?[...A.overlapIgnorePaths]:[""];return D[l]=p,{...A,overlapIgnorePaths:D}})},[]),Jr=i.useCallback(l=>{if(U(p=>{const D=(p.overlapIgnorePaths&&p.overlapIgnorePaths.length>0?[...p.overlapIgnorePaths]:[""]).filter((W,X)=>X!==l);return{...p,overlapIgnorePaths:D.length>0?D:[]}}),xe===l){Ae();return}xe!==null&&xe>l&&Mt(xe-1)},[xe,Ae]),Zr=i.useCallback(()=>{U(l=>{const p=l.overlapIgnorePaths&&l.overlapIgnorePaths.length>0?l.overlapIgnorePaths:[""];return{...l,overlapIgnorePaths:[...p,""]}})},[]),el=i.useCallback(async()=>{if(fe||At||Se)return;const l=y.researchSettings?.limits;if(l?.maxConcurrentRuns!==void 0&&(!Number.isFinite(l.maxConcurrentRuns)||l.maxConcurrentRuns<1)){Ke("Research max concurrent runs must be at least 1.");return}if(l?.maxSourcesPerRun!==void 0&&(!Number.isFinite(l.maxSourcesPerRun)||l.maxSourcesPerRun<1)){Ke("Research max sources per run must be at least 1.");return}if(l?.maxDurationMs!==void 0&&(!Number.isFinite(l.maxDurationMs)||l.maxDurationMs<1e3)){Ke("Research max duration must be at least 1000 ms.");return}if(l?.requestTimeoutMs!==void 0&&(!Number.isFinite(l.requestTimeoutMs)||l.requestTimeoutMs<1e3)){Ke("Research request timeout must be at least 1000 ms.");return}Ke(null),_(!0);try{const p={...y,worktreeInitCommand:y.worktreeInitCommand?.trim()||void 0,worktreesDir:y.worktreesDir?.trim()||void 0,worktrunk:{enabled:K&&y.worktrunk?.enabled===!0,binaryPath:y.worktrunk?.binaryPath?.trim()||void 0,onFailure:y.worktrunk?.onFailure??"fail"},maxAutoMergeRetries:en(y),taskPrefix:y.taskPrefix?.trim()||void 0,githubTrackingDefaultRepo:y.githubTrackingDefaultRepo?.trim()||void 0,githubAuthToken:y.githubAuthToken?.trim()||void 0,overlapIgnorePaths:(y.overlapIgnorePaths??[]).map(W=>W.trim()).filter(W=>W.length>0),experimentalFeatures:Gc(y.experimentalFeatures)},{globalPatch:A,projectPatch:D}=go({payload:p,initialValues:C,initialScopedValues:le,activeSection:E});await Promise.all([Object.keys(A).length>0?st(A):Promise.resolve(),Object.keys(D).length>0?Bi(D,s):Promise.resolve(),gt!==ma.current?Gi({globalMaxConcurrent:gt??4}):Promise.resolve()]),await G.current?.(),t(N("settings.general.settingsSaved","Settings saved"),"success"),a()}catch(p){if(p instanceof hn)return;t(ie(p),"error")}finally{_(!1)}},[y,gt,At,Se,C,le,a,t,s,E,fe,N]),tl=i.useCallback(async()=>{try{await Wi(je,Qt,s),ht(!1),t(N("settings.memory.memorySaved","Memory saved"),"success")}catch(l){t(ie(l)||"Failed to save memory","error")}},[je,Qt,s,t]),sl=i.useCallback(async()=>{ca(!0);try{const{path:l,content:p}=await _i(je,s),A=l??je;je!==A&&(ss.current=!0),es(A),mt(p),ht(!1);const{files:D}=await Oa(s);ra(D),t(N("settings.memory.memoryCompacted","Memory file compacted"),"success")}catch(l){t(ie(l)||"Failed to compact memory","error")}finally{ca(!1)}},[je,s,t]),al=i.useCallback(async()=>{la(!0),ia(null);try{const l=await Ui(ts,s);ia(l),t(l.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",l.qmdAvailable?"success":"warning")}catch(l){t(ie(l)||"Failed to test memory retrieval","error")}finally{la(!1)}},[ts,s,t]),nl=i.useCallback(async()=>{oa(!0);try{await Hi(s),t(N("settings.memory.dreamCompleted","Dream processing completed"),"success")}catch(l){t(l instanceof Error?l.message:"Failed to run dream processing","error")}finally{oa(!1)}},[s,t]),rl=i.useCallback(async()=>{da(!0);try{const l=await $i(s);await fa(),t(l.qmdAvailable?N("settings.memory.qmdInstalled","qmd installed successfully"):N("settings.memory.qmdInstallUnavailable","qmd install finished, but qmd is still unavailable"),l.qmdAvailable?"success":"warning")}catch(l){t(ie(l)||N("settings.memory.qmdInstallFailed","Failed to install qmd"),"error")}finally{da(!1)}},[s,fa,t]),ll=()=>{if(!Se)return;const l=Se.name.trim();if(!l){t(N("settings.models.presetNameRequired","Preset name is required"),"error");return}const p=y.modelPresets||[];let A;Qe?A=Qe:A=Xi(l,p);const D={id:A,name:l,executorProvider:Se.executorProvider,executorModelId:Se.executorModelId,validatorProvider:Se.validatorProvider,validatorModelId:Se.validatorModelId};U(W=>{const X=W.modelPresets||[],se=Qe?X.map(oe=>oe.id===Qe?D:oe):[...X,D];return{...W,modelPresets:se}}),qs(null),Vs(null)},il=i.useCallback(async(l,p)=>{Ys(l);try{await p(),await ft()}catch(A){t(ie(A)||`Failed to ${l}`,"error")}finally{Ys(null)}},[t,ft]),ol=i.useCallback(()=>{if(typeof navigator<"u"&&navigator.userAgent.includes("Windows"))return"winget install Cloudflare.cloudflared";const l=typeof navigator<"u"?navigator.platform:"",p=typeof navigator<"u"?navigator.userAgent:"",A=/(Mac|iPhone|iPad|iPod)/i.test(l),D=/(arm64|aarch64)/i.test(`${l} ${p}`);return A?"brew install cloudflared":`curl -L --output /tmp/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${D?"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`},[]),cl=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`,[]),dl=i.useCallback(async()=>{Qs(!0),Yt(null);try{const l=await Ki(s);if(!l.success){Yt(l.error??N("settings.remote.installationFailed","Installation failed"));return}const p=await ms(s);ut(p),t(N("settings.remote.cloudflaredInstalled","cloudflared installed successfully"),"success")}catch(l){Yt(l instanceof Error?l.message:N("settings.remote.installationFailed","Installation failed"))}finally{Qs(!1)}},[t,s]),re=()=>qe==="global"?e.jsxs("div",{className:"settings-scope-banner settings-scope-global",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(nt,{size:14})}),e.jsx("span",{children:N("settings.scope.globalBanner","These settings are shared across all your Fusion projects.")})]}):qe==="project"?e.jsxs("div",{className:"settings-scope-banner settings-scope-project",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(Ba,{size:14})}),e.jsx("span",{children:N("settings.scope.projectBanner","These settings only affect this project.")})]}):null,ul=()=>{switch(E){case"cli-agents":return e.jsxs(e.Fragment,{children:[re(),e.jsx(Wc,{projectId:s,addToast:t})]});case"general":return e.jsx(rc,{scopeBanner:re(),form:y,setForm:U,projectId:s,addToast:t,prefixError:At,setPrefixError:yn,projectTrackingRepoOptions:rr,projectTrackingRepoLoading:lr,projectTrackingRepoError:ir,onQuickChatButtonModeChange:P});case"global-general":return e.jsx(So,{scopeBanner:re(),form:y,setForm:U,globalTrackingRepoOptions:or,globalTrackingRepoLoading:cr,globalTrackingRepoError:dr});case"global-models":return e.jsx(Eo,{scopeBanner:re(),form:y,setForm:U,availableModels:Us,modelsLoading:$s,globalModelLanes:ja.filter(l=>l.laneId!=="default"),favoriteProviders:Ge,favoriteModels:We,onToggleFavorite:xa,onToggleModelFavorite:ya,addToast:t,projectId:s});case"secrets":return e.jsx(Zo,{scopeBanner:re(),addToast:t});case"project-models":return e.jsx(cc,{scopeBanner:re(),form:y,setForm:U,projectId:s,addToast:t,onOpenWorkflowSettings:f,registerWorkflowLaneSaver:J,models:{modelLanes:ja,getLaneStatus:is,getLaneValue:_r,updateLaneValue:Ur,resetLaneValue:Hr,availableModels:Us,modelsLoading:$s,favoriteProviders:Ge,favoriteModels:We,onToggleFavorite:xa,onToggleModelFavorite:ya,editingPresetId:Qe,setEditingPresetId:qs,presetDraft:Se,setPresetDraft:Vs,onSavePresetDraft:ll,confirmDelete:Z}});case"appearance":return e.jsx(yo,{scopeBanner:re(),form:y,setForm:U,themeMode:r,colorTheme:m,dashboardFontScalePct:d,shadcnCustomColors:w,resolvedThemeMode:b,onThemeModeChange:o,onColorThemeChange:n,onDashboardFontScaleChange:c,onShadcnCustomColorsChange:h,sessionBannersHidden:me,setSessionBannersHidden:Qi});case"scheduling":return e.jsx(uc,{scopeBanner:re(),form:y,setForm:U,globalMaxConcurrent:gt,concurrencyLoading:E==="scheduling"&&!vr&&!as.current,onGlobalMaxConcurrentChange:l=>{as.current=!0,ua(l)},onOverlapIgnorePathChange:Xr,onOpenOverlapPathPicker:$r,onRemoveOverlapIgnorePath:Jr,onAddOverlapIgnorePath:Zr,onOpenWorkflowSettings:f});case"scheduled-evals":return e.jsx(mc,{scopeBanner:re(),form:y,setForm:U});case"node-routing":return e.jsx(gc,{scopeBanner:re(),form:y,setForm:U,nodes:Tn});case"worktrees":return e.jsx(pc,{scopeBanner:re(),form:y,setForm:U,gitRemotes:tr,worktrunkInstall:O,worktrunkInstallVerified:K,onOpenWorktreesDirPicker:qr,onOpenApprovals:x});case"commands":return e.jsx(bc,{scopeBanner:re(),form:y,setForm:U});case"merge":return e.jsx(xc,{scopeBanner:re(),form:y,setForm:U,integrationBranchOptions:sr,integrationBranchCustomMode:ar,setIntegrationBranchCustomMode:nr,onOpenWorkflowSettings:f});case"agent-permissions":return e.jsx(jc,{scopeBanner:re(),form:y,setForm:U});case"memory":return e.jsx(Cc,{scopeBanner:re(),form:y,setForm:U,memory:{memoryCapabilities:wr,memoryBackendStatus:kr,memoryBackendLoading:Nr,memoryBackendError:Cr,memoryFiles:ur,selectedMemoryPath:je,setSelectedMemoryPath:es,memoryContent:Qt,setMemoryContent:mt,memoryLoading:er,memoryDirty:Xt,setMemoryDirty:ht,memoryTestQuery:ts,setMemoryTestQuery:mr,memoryTestLoading:hr,memoryTestResult:gr,qmdInstallLoading:fr,dreamRunning:pr,memoryCompactLoading:br,onInstallQmd:rl,onTestMemoryRetrieval:al,onDreamNow:nl,onCompactMemory:sl,onSaveMemory:tl}});case"research-global":return e.jsx(Po,{scopeBanner:re(),form:y,setForm:U,authProviders:Be,onNavigateToSection:H});case"research-project":return e.jsx(Sc,{scopeBanner:re(),form:y,setForm:U,researchLimitError:jn});case"experimental":return e.jsx(jo,{scopeBanner:re(),form:y,setForm:U,knownFeatures:Dc,legacyAliases:Ct,getCanonicalKey:Is,isFeatureEnabled:Bc,hiddenFeatureKeys:Oc});case"backups":return e.jsx(Pc,{scopeBanner:re(),form:y,setForm:U,backupInfo:Wn,backupLoading:_n,onBackupNow:Lr});case"notifications":return e.jsx(wo,{scopeBanner:re(),form:y,setForm:U,testNotificationLoading:Bn,testNotificationResult:Gn,onTestProviderNotification:Fr});case"node-sync":return e.jsx(ko,{scopeBanner:re(),form:y,setForm:U});case"remote":return e.jsx(Ao,{scopeBanner:re(),form:y,setForm:U,remote:{projectId:s,addToast:t,remoteStatus:ye,externalTunnel:qt,tunnelShareLink:Zn,remoteBusyAction:Un,cloudflaredInstalling:Hn,cloudflaredInstallError:$n,cloudflaredManualInstallCommand:ol,cloudflaredMacFallbackCommand:cl,handleInstallCloudflared:dl,runRemoteAction:il,remoteShortLivedToken:Xn,setRemoteShortLivedToken:Jn,remoteAuthLinkTokenType:Kn,setRemoteAuthLinkTokenType:zn,remoteUrlPreview:qn,setRemoteUrlPreview:Vn,remoteQrSvg:Yn,setRemoteQrSvg:Qn}});case"prompts":return e.jsx(nc,{scopeBanner:re(),form:y,setForm:U});case"plugins":return e.jsx(Tc,{scopeBanner:re(),projectId:s,addToast:t,activePluginsSubsection:ae,setActivePluginsSubsection:ve});case"authentication":return e.jsx(Bo,{auth:{projectId:s,addToast:t,authProviders:Be,authLoading:Rn,authActionInProgress:In,apiKeyInputs:Ut,setApiKeyInputs:Ht,apiKeyErrors:Dn,opencodeApiKeyRefreshStatus:On,deviceCodes:Bt,loginInstructions:En,manualCodeConfigs:Fn,manualCodeInputs:Gt,setManualCodeInputs:Wt,manualCodeSubmitInProgress:Ln,loadAuthStatus:de,handleLogin:Ar,handleLogout:Rr,handleCancelLogin:Tr,handleSaveApiKey:Ir,handleClearApiKey:Er,handleSubmitManualCode:Mr,onReopenOnboarding:g}});case"hermes-runtime":return e.jsx(Qo,{});case"openclaw-runtime":return e.jsx(Xo,{});case"paperclip-runtime":return e.jsx(Jo,{})}};return e.jsxs("div",{className:k?"settings-embedded right-dock-embedded-view":"modal-overlay open settings-modal-overlay",...Wr,"data-testid":k?"settings-view":void 0,role:k?"region":"dialog","aria-label":k?N("settings.title","Settings"):void 0,"aria-modal":k?void 0:"true",children:[e.jsxs("div",{className:k?"modal modal-lg settings-modal settings-modal--embedded":"modal modal-lg settings-modal",ref:F,style:k?void 0:S,children:[e.jsxs("div",{className:k?"modal-header modal-header--embedded":"modal-header",children:[e.jsx("div",{className:"settings-modal-heading",children:e.jsxs("h3",{children:[k&&e.jsx(zi,{size:20,"aria-hidden":"true"}),e.jsx("span",{children:N("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":N("settings.header.starFusion","Star Fusion on GitHub"),title:N("settings.header.starFusion","Star Fusion on GitHub"),onClick:xn,"data-clicked":vn?"true":"false",children:[e.jsxs("span",{className:"settings-github-star-btn__action",children:[e.jsx(rt,{provider:"github",size:"sm"}),e.jsx(qi,{size:11,"aria-hidden":"true"}),N("settings.header.star","Star")]}),$e!==null&&e.jsx("span",{className:"settings-github-star-btn__count","aria-label":`${$e.toLocaleString()} stars`,children:$e>=1e3?`${($e/1e3).toFixed(1)}k`:$e.toLocaleString()})]}),e.jsxs("a",{href:"https://discord.gg/ksrfuy7WYR",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-header-discord-btn","aria-label":N("settings.header.joinDiscord","Join our Discord"),title:N("settings.header.joinDiscord","Join our Discord"),children:[e.jsx(Ic,{size:13}),N("settings.header.discord","Discord")]})]}),!k&&e.jsx("button",{className:"modal-close",onClick:a,"aria-label":N("actions.close","Close"),children:"×"})]}),ce?e.jsx("div",{className:"settings-empty-state settings-loading",children:e.jsx(De,{label:N("settings.loading","Loading…")})}):e.jsxs("div",{className:"settings-layout",children:[St&&e.jsxs("div",{className:"settings-mobile-section-picker",children:[e.jsx("label",{htmlFor:"settings-mobile-section",children:N("settings.mobileNav.label","Settings Section")}),e.jsx("select",{id:"settings-mobile-section",className:"select touch-target",value:E,onChange:l=>H(l.target.value),children:Re.filter(l=>!l.isGroupHeader).map(l=>e.jsx("option",{value:l.id,children:N(l.labelKey,l.label)},l.id))})]}),e.jsx("nav",{className:"settings-sidebar",children:Re.map(l=>l.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:N(l.labelKey,l.label)},l.id):e.jsxs("button",{className:`settings-nav-item${E===l.id?" active":""}`,onClick:()=>H(l.id),title:l.scope==="global"?N("settings.nav.tooltip.global","Shared across all projects"):l.scope==="project"?N("settings.nav.tooltip.project","Specific to this project"):void 0,children:[l.scope==="global"&&e.jsx(nt,{className:"settings-scope-icon","aria-label":N("settings.nav.aria.global","Global setting"),size:16}),l.scope==="project"&&e.jsx(Ba,{className:"settings-scope-icon","aria-label":N("settings.nav.aria.project","Project setting"),size:16}),l.icon&&!l.scope&&e.jsx(l.icon,{className:"settings-scope-icon","aria-label":N("settings.nav.aria.global","Global setting"),size:16}),N(l.labelKey,l.label)]},l.id))}),e.jsx("div",{className:"settings-content",ref:te,children:ul()})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"settings-modal-footer-version",children:[e.jsxs("a",{href:"https://github.com/Runfusion/Fusion/discussions",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-footer-help-btn","aria-label":N("settings.footer.helpDiscussions","Help and discussions"),title:N("settings.footer.helpDiscussions","Help and discussions"),children:[e.jsx(Vi,{size:13,"aria-hidden":"true"}),N("settings.footer.help","Help")]}),e.jsxs("div",{className:"settings-update-check",children:[Oe&&e.jsxs("button",{type:"button",className:"settings-version-check-btn",onClick:()=>{Sr()},disabled:Es,"aria-label":N("settings.footer.checkUpdates","Check for updates"),title:N("settings.footer.checkUpdates","Check for updates"),children:[e.jsx("span",{className:"settings-modal-version",children:N("settings.footer.version","Version {{version}}",{version:Oe})}),e.jsx(Ia,{size:12,className:Es?"spinning":void 0})]}),ue&&e.jsx("span",{"aria-live":"polite",className:`settings-update-result ${ue.error?"settings-update-result--error":ue.updateAvailable?"settings-update-result--available":"settings-update-result--up-to-date"}`,children:Pr()})]})]}),e.jsxs("div",{className:"modal-actions-left",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Dr,title:N("settings.importExport.exportTitle","Export settings to JSON file"),children:N("settings.importExport.exportBtn","Export")}),e.jsx("input",{type:"file",ref:ba,accept:".json,application/json",style:{display:"none"},onChange:Or}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ba.current?.click(),disabled:pt,title:N("settings.importExport.importTitleAttr","Import settings from JSON file"),children:pt?N("settings.importExport.loadingFile","Loading…"):N("settings.importExport.importBtn","Import")})]}),e.jsxs("div",{className:"modal-actions-right",children:[!k&&e.jsx("button",{className:"btn btn-sm",onClick:a,children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:el,disabled:ce||fe,children:N("settings.actions.save","Save")})]})]})]}),xe!==null&&e.jsx("div",{className:"modal-overlay open",onClick:zr,role:"dialog","aria-modal":"true","aria-label":N("settings.scheduling.browseWorkspacePath","Browse workspace path"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:N("settings.scheduling.selectIgnoredOverlapPath","Select ignored overlap path")}),e.jsx("button",{className:"modal-close",onClick:Ae,"aria-label":N("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:N("settings.scheduling.overlapPickerNote","Choose a file to ignore directly, or navigate into a folder and select the current directory.")}),e.jsx(Ga,{entries:kn,currentPath:Ce,onSelectFile:os,onNavigate:Tt,loading:wn,error:Nn,onRetry:Cn,workspace:"project",projectId:s})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[N("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:Ce==="."?N("settings.fileBrowser.projectRoot","(project root)"):Ce})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:Ae,children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Kr,disabled:Ce===".",children:N("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),Os&&e.jsx("div",{className:"modal-overlay open",onClick:Qr,role:"dialog","aria-modal":"true","aria-label":N("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:N("settings.worktrees.selectWorktreesDir","Select worktrees directory")}),e.jsx("button",{className:"modal-close",onClick:Me,"aria-label":N("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:N("settings.worktrees.worktreesPickerNote","Navigate to the folder where Fusion should create task worktrees, then select the current directory.")}),e.jsx(Ga,{entries:Sn,currentPath:Pe,onSelectFile:Vr,onNavigate:Rt,loading:Pn,error:An,onRetry:Mn,workspace:"project",projectId:s})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[N("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:Pe==="."?N("settings.fileBrowser.projectRoot","(project root)"):Pe})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:Me,children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Yr,children:N("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),xr&&ke&&e.jsx("div",{className:"modal-overlay open",onClick:l=>l.target===l.currentTarget&&Xe(!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:N("settings.importExport.importTitle","Import Settings")}),e.jsx("button",{className:"modal-close",onClick:()=>Xe(!1),"aria-label":N("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:N("settings.importExport.reviewPrompt","Review the settings to be imported:")}),ke.global&&Object.keys(ke.global).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:N("settings.importExport.globalSettings","Global Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(ke.global).filter(([,l])=>l!==void 0).map(([l])=>e.jsx("li",{children:l},l))})]}),ke.project&&Object.keys(ke.project).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:N("settings.importExport.projectSettings","Project Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(ke.project).filter(([,l])=>l!==void 0).map(([l])=>e.jsx("li",{children:l},l))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"import-scope",children:N("settings.importExport.importScope","Import Scope:")}),e.jsxs("select",{id:"import-scope",value:rs,onChange:l=>yr(l.target.value),children:[e.jsx("option",{value:"both",children:N("settings.importExport.scopeBoth","Both global and project settings")}),e.jsx("option",{value:"global",children:N("settings.importExport.scopeGlobal","Global settings only")}),e.jsx("option",{value:"project",children:N("settings.importExport.scopeProject","Project settings only")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"import-merge",className:"checkbox-label",children:[e.jsx("input",{id:"import-merge",type:"checkbox",checked:ls,onChange:l=>jr(l.target.checked)}),N("settings.importExport.mergeExisting","Merge with existing settings (recommended)")]}),e.jsx("small",{children:N("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:()=>Xe(!1),children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Br,disabled:pt,children:pt?N("settings.importExport.importing","Importing…"):N("settings.importExport.confirmImport","Confirm Import")})]})]})})]})}function Zc(a){return e.jsx(_c,{presentation:"embedded",...a})}export{_c as SettingsModal,Zc as SettingsView};
|
|
21
|
+
Be brief and precise — avoid verbosity.`,builtIn:!0}],ec={"executor-welcome":{key:"executor-welcome",name:"Executor Welcome",roles:["executor"],description:"Introductory section for the executor agent",defaultContent:"You are a task execution agent..."},"executor-guardrails":{key:"executor-guardrails",name:"Executor Guardrails",roles:["executor"],description:"Behavioral guardrails and constraints for the executor",defaultContent:"Treat the File Scope in PROMPT.md..."},"executor-spawning":{key:"executor-spawning",name:"Executor Spawning",roles:["executor"],description:"Instructions for spawning child agents",defaultContent:"You can spawn child agents..."},"executor-completion":{key:"executor-completion",name:"Executor Completion",roles:["executor"],description:"Completion criteria and signaling for executor",defaultContent:"After all steps are done..."},"triage-welcome":{key:"triage-welcome",name:"Triage Welcome",roles:["triage"],description:"Introductory section for the triage/specification agent",defaultContent:"You are a task specification agent..."},"triage-context":{key:"triage-context",name:"Triage Context",roles:["triage"],description:"Context-gathering instructions for triage",defaultContent:"What you receive: A raw task title..."},"reviewer-verdict":{key:"reviewer-verdict",name:"Reviewer Verdict",roles:["reviewer"],description:"Verdict criteria and format for code/review agent",defaultContent:"APPROVE — Step will achieve its stated outcomes..."},"merger-conflicts":{key:"merger-conflicts",name:"Merger Conflicts",roles:["merger"],description:"Merge conflict resolution instructions for merger",defaultContent:"If there are merge conflicts..."},"agent-generation-system":{key:"agent-generation-system",name:"Agent Generation System",roles:["executor"],description:"System prompt for generating agent specifications",defaultContent:"You are an agent specification generator..."},"workflow-step-refine":{key:"workflow-step-refine",name:"Workflow Step Refine",roles:["executor"],description:"System prompt for refining workflow step descriptions",defaultContent:"You are an expert at creating detailed agent prompts..."},"planning-system":{key:"planning-system",name:"Planning System",roles:["triage"],description:"System prompt for the AI planning assistant",defaultContent:"You are a planning assistant for the fn task board system..."},"subtask-breakdown-system":{key:"subtask-breakdown-system",name:"Subtask Breakdown System",roles:["executor"],description:"System prompt for AI subtask decomposition",defaultContent:"You are a task decomposition assistant..."},"mission-interview-system":{key:"mission-interview-system",name:"Mission Interview System",roles:["triage"],description:"System prompt for AI-assisted mission planning",defaultContent:"You are a mission planning assistant..."},"ai-refine-system":{key:"ai-refine-system",name:"AI Refine System",roles:["executor"],description:"System prompt for AI-powered text refinement",defaultContent:"You are a text refinement assistant..."},"agent-onboarding-system":{key:"agent-onboarding-system",name:"Agent Onboarding System",roles:["executor"],description:"System prompt for AI-guided agent onboarding interview",defaultContent:"You are an agent onboarding assistant for the fn task board system..."}},qa=["executor","triage","reviewer","merger"],tc={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"}},et=a=>`prompt-role-tone--${a}`,vs={name:"",description:"",role:"executor",prompt:""};function sc(a,t){const s=a.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),u=new Set(Ue.map(o=>o.id)),r=new Set(t.map(o=>o.id));if(!u.has(s)&&!r.has(s))return s;let m=2;for(;u.has(`${s}-${m}`)||r.has(`${s}-${m}`);)m++;return`${s}-${m}`}function ac({value:a,onChange:t,promptOverrides:s,onPromptOverridesChange:u}){const{t:r}=q("app"),m=C=>{const I=tc[C];return r(I.key,I.defaultValue)},[o,n]=i.useState("templates"),[d,w]=i.useState(null),[b,c]=i.useState(!1),[h,P]=i.useState(vs),[g,x]=i.useState(null),[f,j]=i.useState(null),[k,R]=i.useState(new Set),[v,M]=i.useState(null),[V,N]=i.useState(!1),[Z,O]=i.useState(null),K=i.useRef(null),$=a?.templates??[],ee=a?.roleAssignments??{},Q=Z===null?null:Z.source==="builtin"?Ue.find(C=>C.id===Z.id):$.find(C=>C.id===Z.id),B=i.useCallback(C=>{const I=Ue.filter(ne=>ne.role===C),z=$.filter(ne=>ne.role===C);return[...I,...z]},[$]);i.useEffect(()=>{Z!==null&&K.current?.focus()},[Z]);const L=i.useCallback(()=>{c(!0),w(null),P(vs),x(null),O(null)},[]),S=i.useCallback(C=>{w(C.id),c(!1),P({name:C.name,description:C.description,role:C.role,prompt:C.prompt}),x(null),O(null)},[]),F=i.useCallback(()=>{w(null),c(!1),P(vs),x(null),O(null),N(!1)},[]),te=i.useCallback(()=>{const C=h.name.trim();if(!C){x(r("agentPrompts.errors.nameRequired","Template name is required"));return}let I;if(b){if(I=sc(C,$),new Set(Ue.map(T=>T.id)).has(I)){x(r("agentPrompts.errors.idConflict",'Template ID "{{templateId}}" conflicts with a built-in template. Please use a different name.',{templateId:I}));return}}else I=d;const z={id:I,name:C,description:h.description.trim(),role:h.role,prompt:h.prompt,builtIn:!1};let ne;b?ne=[...$,z]:ne=$.map(Y=>Y.id===I?z:Y);const le={...ee};for(const[Y,T]of Object.entries(le))T===I&&h.role!==Y&&delete le[Y];t({...a,templates:ne,roleAssignments:Object.keys(le).length>0?le:void 0}),F()},[h,b,d,$,ee,a,t,F]),G=i.useCallback(C=>{const I=$.filter(le=>le.id!==C),z={...ee};let ne=!1;for(const[le,Y]of Object.entries(z))Y===C&&(delete z[le],ne=!0);t({...a,templates:I.length>0?I:void 0,roleAssignments:Object.keys(z).length>0||ne?Object.keys(z).length>0?z:void 0:ee}),j(null),d===C&&F()},[$,ee,a,t,d,F]),J=i.useCallback((C,I)=>{const z={...ee};I===""?delete z[C]:z[C]=I,t({...a,roleAssignments:Object.keys(z).length>0?z:void 0})},[ee,a,t]),me=i.useCallback((C,I)=>{const z={...s};z[C]=I||null,u(z)},[s,u]),y=i.useCallback(C=>{const I={...s};I[C]=null,u(I)},[s,u]),U=i.useCallback(C=>{R(I=>{const z=new Set(I);return z.has(C)?z.delete(C):z.add(C),z})},[]),ce=i.useCallback(C=>{M(I=>I===C?null:C)},[]),pe=i.useCallback((C,I)=>{N(!1),O({source:C,id:I})},[]),fe=i.useCallback(()=>{O(null),N(C=>!C)},[]),_=C=>Ue.some(I=>I.id===C);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 ${o==="templates"?"active":""}`,onClick:()=>n("templates"),"data-testid":"tab-templates",children:[e.jsx(ao,{size:14}),r("agentPrompts.tabs.templates","Templates")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${o==="assignments"?"active":""}`,onClick:()=>n("assignments"),"data-testid":"tab-assignments",children:[e.jsx(ro,{size:14}),r("agentPrompts.tabs.assignments","Assignments")]}),e.jsxs("button",{type:"button",className:`prompt-manager-tab ${o==="overrides"?"active":""}`,onClick:()=>n("overrides"),"data-testid":"tab-overrides",children:[e.jsx(oo,{size:14}),r("agentPrompts.tabs.overrides","Overrides")]})]}),e.jsxs("div",{className:"prompt-manager-content",children:[o==="templates"&&e.jsxs("div",{className:"prompt-manager-templates-tab","data-testid":"templates-tab",children:[(b||d!==null)&&e.jsxs("div",{className:"prompt-template-editor","data-testid":"template-editor",children:[e.jsx("h4",{className:"prompt-template-editor-title",children:b?r("agentPrompts.editor.newTemplate","New Custom Template"):r("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:r("agentPrompts.labels.name","Name")}),e.jsx("input",{id:"template-name",type:"text",value:h.name,onChange:C=>P(I=>({...I,name:C.target.value})),placeholder:r("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:r("agentPrompts.labels.description","Description")}),e.jsx("input",{id:"template-description",type:"text",value:h.description,onChange:C=>P(I=>({...I,description:C.target.value})),placeholder:r("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:r("agentPrompts.labels.role","Role")}),e.jsx("select",{id:"template-role",value:h.role,onChange:C=>P(I=>({...I,role:C.target.value})),"data-testid":"template-role-select",children:qa.map(C=>e.jsx("option",{value:C,children:m(C)},C))})]}),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:r("agentPrompts.labels.prompt","Prompt")}),e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:fe,"aria-label":r("agentPrompts.ariaLabels.expandPrompt","Expand prompt to fullscreen"),"data-testid":"template-prompt-fullscreen",children:e.jsx(xt,{size:14})})]}),V?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),N(!1))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsx("div",{className:"prompt-override-fullscreen-title",children:r("agentPrompts.titles.editPrompt","Edit Prompt")}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>N(!1),"data-testid":"template-prompt-collapse",children:[e.jsx(us,{size:14}),r("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:"template-prompt-fullscreen","aria-label":r("agentPrompts.ariaLabels.templatePromptFullscreen","Template prompt - fullscreen"),className:"prompt-template-prompt-textarea",value:h.prompt,onChange:C=>P(I=>({...I,prompt:C.target.value})),placeholder:r("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:r("agents.charactersCount","{{count}} characters",{count:h.prompt.length})})})]}):e.jsx("textarea",{id:"template-prompt",value:h.prompt,onChange:C=>P(I=>({...I,prompt:C.target.value})),placeholder:r("agentPrompts.placeholders.prompt","Enter the system prompt for this template..."),rows:8,className:"prompt-template-prompt-textarea","data-testid":"template-prompt-input"})]}),g&&e.jsx("div",{className:"prompt-template-error","data-testid":"template-error",children:g}),e.jsxs("div",{className:"prompt-template-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:F,"data-testid":"cancel-template-btn",children:r("agentPrompts.actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:te,"data-testid":"save-template-btn",children:b?r("agentPrompts.actions.create","Create"):r("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:r("agentPrompts.sections.builtinTemplates","Built-in Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:r("agentPrompts.descriptions.builtinTemplates","These templates are provided by Fusion and cannot be modified.")}),e.jsx("div",{className:"prompt-template-list",children:Ue.map(C=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${C.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:C.name}),e.jsx("span",{className:`prompt-template-badge-built-in ${et(C.role)}`,children:r("agentPrompts.badges.builtin","Built-in")}),e.jsx("span",{className:`prompt-template-badge-role ${et(C.role)}`,children:m(C.role)})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>pe("builtin",C.id),title:r("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":r("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:C.name}),"data-testid":`expand-view-${C.id}`,children:e.jsx(xt,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:C.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:C.prompt})})]},C.id))})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"custom-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:r("agentPrompts.sections.customTemplates","Custom Templates")}),e.jsx("p",{className:"prompt-template-section-desc",children:r("agentPrompts.descriptions.customTemplates","Create custom templates to override built-in prompts for specific roles.")}),$.length===0&&!b&&e.jsx("div",{className:"prompt-template-empty",children:r("agentPrompts.emptyStates.noCustomTemplates","No custom templates yet. Create one to get started.")}),$.length>0&&e.jsx("div",{className:"prompt-template-list",children:$.map(C=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${C.id}`,children:f===C.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsx("p",{children:r("agentPrompts.confirmations.deleteTemplate",'Delete "{{name}}"?',{name:C.name})}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>G(C.id),"data-testid":`confirm-delete-${C.id}`,children:r("agentPrompts.actions.delete","Delete")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>j(null),"data-testid":`cancel-delete-${C.id}`,children:r("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:C.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:r("agentPrompts.badges.custom","Custom")}),e.jsx("span",{className:`prompt-template-badge-role ${et(C.role)}`,children:m(C.role)}),_(C.id)&&e.jsx("span",{className:"prompt-template-badge-override",children:r("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:()=>pe("custom",C.id),title:r("agentPrompts.titles.viewFullPrompt","View full prompt"),"aria-label":r("agentPrompts.ariaLabels.viewFullPromptFor","View full prompt for {{name}}",{name:C.name}),"data-testid":`expand-view-${C.id}`,children:e.jsx(xt,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>S(C),title:r("agentPrompts.titles.edit","Edit"),"aria-label":r("agentPrompts.ariaLabels.editTemplate","Edit {{name}}",{name:C.name}),"data-testid":`edit-${C.id}`,children:e.jsx(an,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>j(C.id),title:r("agentPrompts.titles.delete","Delete"),"aria-label":r("agentPrompts.ariaLabels.deleteTemplate","Delete {{name}}",{name:C.name}),"data-testid":`delete-${C.id}`,children:e.jsx(nn,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:C.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:C.prompt})})]})},C.id))}),!b&&d===null&&e.jsxs("button",{type:"button",className:"btn btn-primary prompt-template-add-btn",onClick:L,"data-testid":"add-template-btn",children:[e.jsx(rn,{size:14}),r("agentPrompts.actions.addCustomTemplate","Add Custom Template")]})]}),Q&&e.jsxs("div",{ref:K,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),O(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[Q.name,e.jsx("span",{className:`prompt-template-badge-role ${et(Q.role)}`,children:m(Q.role)})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>O(null),"data-testid":`collapse-view-${Q.id}`,children:[e.jsx(us,{size:14}),r("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:Q.prompt})]})]}),o==="assignments"&&e.jsxs("div",{className:"prompt-manager-assignments-tab","data-testid":"assignments-tab",children:[e.jsx("p",{className:"prompt-assignments-desc",children:r("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:qa.map(C=>{const I=B(C),z=ee[C]??"",ne=I.find(Y=>Y.id===z),le=!!z;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${C}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:`prompt-role-badge ${et(C)}`,children:m(C)}),le&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[ne?.name??r("agentPrompts.labels.custom","Custom")," (",r("agentPrompts.labels.overridesDefault","overrides default"),")"]})]}),e.jsxs("select",{className:"prompt-role-select",value:z,onChange:Y=>J(C,Y.target.value),"data-testid":`select-${C}`,children:[e.jsx("option",{value:"",children:r("agentPrompts.options.useDefault","Use default")}),I.map(Y=>e.jsxs("option",{value:Y.id,children:[Y.name,_(Y.id)?` (${r("agentPrompts.labels.builtIn","built-in")})`:` (${r("agentPrompts.labels.custom","custom")})`]},Y.id))]})]},C)})}),Object.keys(ee).length>0&&e.jsxs("div",{className:"prompt-assignments-note",children:[e.jsxs("strong",{children:[r("agentPrompts.labels.note","Note"),":"]})," ",r("agentPrompts.descriptions.assignmentNote","Role assignments are stored in the agentPrompts configuration. Custom templates override built-ins by ID.")]})]}),o==="overrides"&&e.jsxs("div",{className:"prompt-manager-overrides-tab","data-testid":"overrides-tab",children:[e.jsx("p",{className:"prompt-overrides-desc",children:r("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(ec).map(C=>{const I=C.key,z=s?.[I]??"",ne=z!=="",le=k.has(I);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${I}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("button",{type:"button",className:"prompt-override-info",onClick:()=>U(I),children:[e.jsx("span",{className:"prompt-override-name",children:C.name}),e.jsx("code",{className:"prompt-override-key",children:I}),ne&&e.jsx("span",{className:"prompt-override-badge",children:r("agentPrompts.badges.customized","customized")})]}),e.jsxs("div",{className:"prompt-override-header-actions",children:[le&&e.jsx("button",{type:"button",className:"prompt-override-fullscreen-btn",onClick:Y=>{Y.stopPropagation(),ce(I)},"aria-label":r("agentPrompts.ariaLabels.expandToFullscreen","Expand to fullscreen"),"data-testid":`fullscreen-${I}`,children:e.jsx(xt,{size:14})}),e.jsx("button",{type:"button",className:"prompt-override-expand-btn","aria-label":le?r("agentPrompts.ariaLabels.collapse","Collapse"):r("agentPrompts.ariaLabels.expand","Expand"),"data-testid":`expand-${I}`,onClick:Y=>{Y.stopPropagation(),U(I)},children:le?e.jsx(Ql,{size:16}):e.jsx(Xl,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:C.description}),le&&(v===I?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:Y=>{Y.key==="Escape"&&(Y.preventDefault(),M(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[C.name,e.jsx("code",{className:"prompt-override-key",children:I})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>M(null),"data-testid":`collapse-fullscreen-${I}`,children:[e.jsx(us,{size:14}),r("agentPrompts.actions.collapse","Collapse")]})]}),e.jsx("textarea",{id:`prompt-${I}-fullscreen`,"aria-label":r("agentPrompts.ariaLabels.promptOverrideFullscreen","{{name}} prompt override ({{key}}) - fullscreen",{name:C.name,key:I}),className:"prompt-override-textarea",value:z,onChange:Y=>{me(I,Y.target.value)},placeholder:`Default: ${C.defaultContent.slice(0,100)}${C.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${I}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ne&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>y(I),"data-testid":`reset-fullscreen-${I}`,children:r("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ne?r("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):r("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:C.defaultContent.length})})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${I}`,"aria-label":r("agentPrompts.ariaLabels.promptOverride","{{name}} prompt override ({{key}})",{name:C.name,key:I}),className:"prompt-override-textarea",value:z,onChange:Y=>{me(I,Y.target.value)},placeholder:r("agentPrompts.placeholders.promptDefault","Default: {{preview}}",{preview:C.defaultContent.slice(0,100)+(C.defaultContent.length>100?"...":"")}),rows:4,"data-testid":`override-input-${I}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ne&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:Y=>{Y.stopPropagation(),y(I)},"data-testid":`reset-${I}`,children:r("agentPrompts.actions.reset","Reset")}),e.jsx("small",{className:"prompt-override-hint",children:ne?r("agentPrompts.hints.customOverrideActive","Custom override active. Click Reset to restore default."):r("agentPrompts.hints.noOverrideSet","No override set. Using built-in default ({{chars}} chars).",{chars:C.defaultContent.length})})]})]}))]},I)})})]})]})]})}function nc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.nav.prompts","Prompts")}),e.jsx(ac,{value:t.agentPrompts,onChange:r=>{s(m=>({...m,agentPrompts:r}))},promptOverrides:t.promptOverrides,onPromptOverridesChange:r=>{s(m=>({...m,promptOverrides:r}))}})]})}function rc({scopeBanner:a,form:t,setForm:s,projectId:u,addToast:r,prefixError:m,setPrefixError:o,projectTrackingRepoOptions:n,projectTrackingRepoLoading:d,projectTrackingRepoError:w,onQuickChatButtonModeChange:b}){const{t:c}=q("app"),[h,P]=i.useState([]);i.useEffect(()=>{let f=!1;return Jl(u,{includeDisabledBuiltins:!0}).then(j=>{f||P(j.filter(k=>k.id.startsWith("builtin:")&&k.kind!=="fragment"))}).catch(()=>{f||P([])}),()=>{f=!0}},[u]);const g=i.useMemo(()=>{const f=Array.isArray(t.enabledBuiltinWorkflowIds)?t.enabledBuiltinWorkflowIds:void 0;return new Set(f??h.map(j=>j.id))},[h,t.enabledBuiltinWorkflowIds]),x=(f,j)=>{s(k=>{const R=h.map(V=>V.id),v=new Set(Array.isArray(k.enabledBuiltinWorkflowIds)?k.enabledBuiltinWorkflowIds:R);j?v.add(f):v.delete(f);const M=R.filter(V=>v.has(V));return{...k,enabledBuiltinWorkflowIds:M.length===R.length?void 0:M}})};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.general.general","General")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskPrefix",children:c("settings.general.taskPrefix","Task Prefix")}),e.jsx("input",{id:"taskPrefix",type:"text",placeholder:c("settings.general.fN","FN"),value:t.taskPrefix||"",onChange:f=>{const j=f.target.value;s(k=>({...k,taskPrefix:j||void 0})),j&&!/^[A-Z]{1,5}$/.test(j)?o(c("settings.general.prefixMustBe15UppercaseLetters","Prefix must be 1–5 uppercase letters")):o(null)}}),m&&e.jsx("small",{className:"field-error",children:m}),!m&&e.jsx("small",{children:c("settings.general.prefixForNewTaskIDsEGKB","Prefix for new task IDs (e.g. KB, PROJ)")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx(Zl,{projectId:u,addToast:r}),e.jsx("small",{children:c("settings.general.newTasksInheritThisCustomWorkflowsStepsOverridable","New tasks inherit this custom workflow's steps (overridable per task)")})]}),h.length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:c("settings.general.builtInWorkflows","Built-in workflows")}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:h.map(f=>e.jsxs("label",{htmlFor:`builtin-workflow-${f.id}`,className:"checkbox-label",children:[e.jsx("input",{id:`builtin-workflow-${f.id}`,type:"checkbox",checked:g.has(f.id),onChange:j=>x(f.id,j.target.checked)}),e.jsx("span",{children:f.name})]},f.id))}),e.jsx("small",{children:c("settings.general.disabledBuiltInWorkflowsAreHiddenFromWorkflow","Disabled built-in workflows are hidden from workflow pickers. Existing tasks that already use one continue to resolve.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"ephemeralAgentsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"ephemeralAgentsEnabled",type:"checkbox",checked:t.ephemeralAgentsEnabled!==!1,onChange:f=>s(j=>({...j,ephemeralAgentsEnabled:f.target.checked}))}),c("settings.general.useEphemeralTaskWorkerAgents"," Use ephemeral task-worker agents ")]}),e.jsxs("small",{children:[c("settings.general.whenEnabledDefaultFusionSpawnsShortLived"," When enabled (default), Fusion spawns short-lived "),e.jsx("code",{children:"executor-FN-XXXX"}),c("settings.general.agentsToRunEachTaskWhenDisabledOnly"," agents to run each task. When disabled, only permanent agents execute tasks and the scheduler auto-assigns work using the agent reporting chain. Tasks with no eligible permanent agent stay queued. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"workspaceMode",className:"checkbox-label",children:[e.jsx("input",{id:"workspaceMode",type:"checkbox",checked:t.workspaceMode===!0,onChange:f=>s(j=>({...j,workspaceMode:f.target.checked}))}),c("settings.general.workspaceMode"," Workspace mode (multi-repo) ")]}),e.jsx("small",{children:c("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.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"completionDocumentationMode",children:c("settings.general.completionDocumentationAutomation","Completion Documentation Automation")}),e.jsxs("select",{id:"completionDocumentationMode",value:t.completionDocumentationMode||"off",onChange:f=>s(j=>({...j,completionDocumentationMode:f.target.value})),children:[e.jsx("option",{value:"off",children:c("settings.general.off","Off")}),e.jsx("option",{value:"changeset",children:c("settings.general.requireChangesetChangesetMd","Require changeset (.changeset/*.md)")}),e.jsx("option",{value:"changelog",children:c("settings.general.requireChangelogUpdateExistingChangelog","Require changelog update (existing changelog)")})]}),e.jsxs("small",{children:[c("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"}),c("settings.general.workflowsOrChangelogModeWhenContributorsShouldUpdate"," workflows, or changelog mode when contributors should update an existing changelog file. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"quickChatButtonMode",children:c("settings.general.quickChatLauncher","Quick Chat launcher")}),e.jsxs("select",{id:"quickChatButtonMode",className:"select",value:t.quickChatButtonMode??(t.showQuickChatFAB?"floating":"off"),onChange:f=>s(j=>{const k=f.target.value;return b?.(k),{...j,quickChatButtonMode:k,showQuickChatFAB:k==="floating"}}),children:[e.jsx("option",{value:"floating",children:c("settings.general.quickChatLauncherFloating","Floating button")}),e.jsx("option",{value:"footer",children:c("settings.general.quickChatLauncherFooter","Footer button")}),e.jsx("option",{value:"off",children:c("settings.general.off","Off")})]}),e.jsx("small",{children:c("settings.general.quickChatLauncherHint","Choose whether Quick Chat opens from the draggable floating button, a footer button beside Terminal, or stays hidden.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.chatHistory","Chat history")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatAutoCleanupDays",children:c("settings.general.autoCleanupOldChats","Auto-cleanup old chats")}),e.jsxs("select",{id:"chatAutoCleanupDays",className:"select",value:t.chatAutoCleanupDays??0,onChange:f=>s(j=>({...j,chatAutoCleanupDays:Number(f.target.value)||0})),children:[e.jsx("option",{value:0,children:c("settings.general.off","Off")}),e.jsx("option",{value:7,children:c("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:c("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:c("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:c("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:c("settings.general.90Days","90 days")})]}),e.jsx("small",{children:c("settings.general.deleteChatSessionsAndRoomsThatHaveBeen","Delete chat sessions and rooms that have been idle for this many days. Default: Off.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mailAutoCleanupDays",children:c("settings.general.autoPruneOldMail","Auto-prune old mail")}),e.jsxs("select",{id:"mailAutoCleanupDays",className:"select",value:t.mailAutoCleanupDays??0,onChange:f=>s(j=>({...j,mailAutoCleanupDays:Number(f.target.value)||0})),children:[e.jsx("option",{value:0,children:c("settings.general.off","Off")}),e.jsx("option",{value:7,children:c("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:c("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:c("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:c("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:c("settings.general.90Days","90 days")})]}),e.jsx("small",{children:c("settings.general.deleteInboxOutboxMessagesOlderThanThisMany","Delete inbox/outbox messages older than this many days. Default: Off. 7 days is the suggested setting.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"operationalLogRetentionDays",children:c("settings.general.operationalLogRetention","Operational log retention")}),e.jsxs("select",{id:"operationalLogRetentionDays",className:"select",value:t.operationalLogRetentionDays??30,onChange:f=>s(j=>({...j,operationalLogRetentionDays:Number(f.target.value)||0})),children:[e.jsx("option",{value:0,children:c("settings.general.off","Off")}),e.jsx("option",{value:7,children:c("settings.general.7Days","7 days")}),e.jsx("option",{value:14,children:c("settings.general.14Days","14 days")}),e.jsx("option",{value:30,children:c("settings.general.30Days","30 days")}),e.jsx("option",{value:60,children:c("settings.general.60Days","60 days")}),e.jsx("option",{value:90,children:c("settings.general.90Days","90 days")})]}),e.jsx("small",{children:c("settings.general.loweringThisWindowMeansReliabilityMetricsChartsAnd"," Lowering this window means Reliability metrics/charts and the Activity feed will not show history older than the selected range. Per-task task detail history is unaffected. Default: 30 days. ")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.chatRooms","Chat Rooms")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomRecentVerbatimMessages",children:c("settings.general.recentVerbatimRoomMessages","Recent verbatim room messages")}),e.jsx("input",{id:"chatRoomRecentVerbatimMessages",type:"number",min:"1",className:"input",placeholder:c("settings.general.25","25"),value:t.chatRoomRecentVerbatimMessages??"",onChange:f=>s(j=>({...j,chatRoomRecentVerbatimMessages:Number(f.target.value)||void 0}))}),e.jsx("small",{children:c("settings.general.numberOfMostRecentChatRoomMessagesKept","Number of most-recent chat-room messages kept verbatim in the responder transcript. Older messages are compacted into a summary block. Default: 25.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomCompactionFetchLimit",children:c("settings.general.roomCompactionFetchLimit","Room compaction fetch limit")}),e.jsx("input",{id:"chatRoomCompactionFetchLimit",type:"number",min:"1",className:"input",placeholder:c("settings.general.200","200"),value:t.chatRoomCompactionFetchLimit??"",onChange:f=>s(j=>({...j,chatRoomCompactionFetchLimit:Number(f.target.value)||void 0}))}),e.jsx("small",{children:c("settings.general.upperBoundOnMessagesFetchedFromTheRoom","Upper bound on messages fetched from the room store for compaction consideration. Default: 200.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"chatRoomSummaryMaxChars",children:c("settings.general.roomSummaryMaxCharacters","Room summary max characters")}),e.jsx("input",{id:"chatRoomSummaryMaxChars",type:"number",min:"200",className:"input",placeholder:c("settings.general.3000","3000"),value:t.chatRoomSummaryMaxChars??"",onChange:f=>s(j=>({...j,chatRoomSummaryMaxChars:Number(f.target.value)||void 0}))}),e.jsx("small",{children:c("settings.general.hardCapOnTheSynthesizedEarlierRoomContext",'Hard cap on the synthesized "Earlier room context" summary block. Default: 3000.')})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.capacityRiskBanner","Capacity Risk Banner")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"capacityRiskBannerEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"capacityRiskBannerEnabled",type:"checkbox",checked:t.capacityRiskBannerEnabled===!0,onChange:f=>s(j=>({...j,capacityRiskBannerEnabled:f.target.checked}))}),c("settings.general.showCapacityRiskBanner"," Show capacity risk banner ")]}),e.jsx("small",{children:c("settings.general.warnOnTheBoardWhenTodoWorkExceeds","Warn on the board when todo work exceeds the threshold and no idle agents are available.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"capacityRiskTodoThresholdGeneral",children:c("settings.general.todoThreshold","Todo threshold")}),e.jsx("input",{id:"capacityRiskTodoThresholdGeneral",type:"number",min:0,className:"input",value:t.capacityRiskTodoThreshold??20,onChange:f=>s(j=>({...j,capacityRiskTodoThreshold:f.target.value===""?0:Math.max(0,Number.parseInt(f.target.value,10)||0)}))}),e.jsx("small",{children:c("settings.general.bannerFiresWhenTodoCountIsStrictlyGreater","Banner fires when todo count is strictly greater than this value (default 20). Applies when the banner is enabled.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:c("settings.general.gitHubTracking","GitHub Tracking")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubTrackingMode",children:c("settings.general.defaultTrackingModeForNewTasks","Default tracking mode for new tasks")}),e.jsxs("select",{id:"githubTrackingMode",className:"select",value:t.githubTrackingEnabledByDefault?"new-tasks":"off",onChange:f=>s(j=>({...j,githubTrackingEnabledByDefault:f.target.value==="new-tasks"})),children:[e.jsx("option",{value:"off",children:c("settings.general.offDefault","Off (default)")}),e.jsx("option",{value:"new-tasks",children:c("settings.general.onForNewTasks","On for new tasks")})]}),e.jsx("small",{children:c("settings.general.controlsWhetherNewlyCreatedTasksHaveGitHubIssue"," Controls whether newly created tasks have GitHub issue tracking enabled by default. Individual tasks can still override this from the task detail modal. ")}),e.jsxs("small",{children:[c("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?c("settings.general.enableSummarizationInProjectModelsToConfigureThatModel"," Enable summarization in Project Models to configure that model."):""]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"projectGithubTrackingDefaultRepoGeneral",children:c("settings.general.projectDefaultTrackingRepo","Project default tracking repo")}),e.jsx(un,{id:"projectGithubTrackingDefaultRepoGeneral",ariaLabel:"Project default tracking repo",value:t.githubTrackingDefaultRepo??"",options:n,loading:d,error:w??void 0,placeholder:c("settings.general.ownerRepo","owner/repo"),onChange:f=>s(j=>({...j,githubTrackingDefaultRepo:f||void 0}))}),e.jsx("small",{children:c("settings.general.defaultRepoUsedWhenCreatingGitHubIssuesFor","Default repo used when creating GitHub issues for tracked tasks. Falls back to the global default if blank.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"githubTrackingDedupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"githubTrackingDedupEnabled",type:"checkbox",checked:t.githubTrackingDedupEnabled!==!1,onChange:f=>s(j=>({...j,githubTrackingDedupEnabled:f.target.checked}))}),c("settings.general.searchTheTrackingRepoForLikelyDuplicatesBefore"," Search the tracking repo for likely duplicates before opening a new issue ")]}),e.jsx("small",{children:c("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. ")})]})]})}const xs="builtin:coding",lc=[{id:"planning",providerId:"planningProvider",modelId:"planningModelId",label:"Plan/Triage Model",help:"Provider and model used when planning or triaging tasks. Leave unset to inherit from the workflow default."},{id:"execution",providerId:"executionProvider",modelId:"executionModelId",label:"Executor Model",help:"Provider and model used while executing workflow steps. Leave unset to inherit from the workflow default."},{id:"validator",providerId:"validatorProvider",modelId:"validatorModelId",label:"Reviewer Model",help:"Provider and model used for workflow review or validation lanes. Leave unset to inherit from the workflow default."},{id:"planning-fallback",providerId:"planningFallbackProvider",modelId:"planningFallbackModelId",label:"Planning Fallback Model",help:"Fallback provider and model used when the primary Plan/Triage model cannot be used."},{id:"validator-fallback",providerId:"validatorFallbackProvider",modelId:"validatorFallbackModelId",label:"Reviewer Fallback Model",help:"Fallback provider and model used when the primary Reviewer model cannot be used."},{id:"title-summarizer-fallback",providerId:"titleSummarizerFallbackProvider",modelId:"titleSummarizerFallbackModelId",label:"Title Summarizer Fallback Model",help:"Fallback provider and model used when the primary Title Summarizer model cannot be used."}];function ic(a){const t=new Map((a??[]).map(s=>[s.id,s]));return lc.filter(s=>{const u=t.get(s.providerId),r=t.get(s.modelId);return u?.type==="string"&&r?.type==="string"})}function oc(a,t){const s=a[t.providerId],u=a[t.modelId];return typeof s=="string"&&typeof u=="string"&&s&&u?`${s}/${u}`:""}class hn extends Error{rejections;constructor(t){super("Workflow model lane settings were rejected"),this.name="WorkflowLaneFlushRejection",this.rejections=t}}function cc({scopeBanner:a,form:t,setForm:s,models:u,projectId:r,onOpenWorkflowSettings:m,registerWorkflowLaneSaver:o}){const{t:n}=q("app"),{modelLanes:d,getLaneStatus:w,getLaneValue:b,updateLaneValue:c,resetLaneValue:h,availableModels:P,modelsLoading:g,favoriteProviders:x,favoriteModels:f,onToggleFavorite:j,onToggleModelFavorite:k,editingPresetId:R,setEditingPresetId:v,presetDraft:M,setPresetDraft:V,onSavePresetDraft:N,confirmDelete:Z}=u,O=t.modelPresets||[],K=O.map(T=>({id:T.id,name:T.name})),$=new Set(Object.values(t.defaultPresetBySize||{}).filter(Boolean)),ee=typeof t.defaultWorkflowId=="string"&&t.defaultWorkflowId.trim()?t.defaultWorkflowId:xs,[Q,B]=i.useState(ee),[L,S]=i.useState(null),[F,te]=i.useState(!1),[G,J]=i.useState({}),[me,y]=i.useState({}),[U,ce]=i.useState([]),pe=i.useRef(0),fe=Object.keys(G).length>0;i.useEffect(()=>{B(ee)},[ee]),i.useEffect(()=>{if(!r){S(null),J({}),y({}),ce([]);return}const T=++pe.current;te(!0),Promise.all([ei(Q,r),ti(Q,r)]).then(([E,H])=>{if(pe.current!==T)return;S(H),J({}),y({});const ae="settings"in E.ir?E.ir.settings:void 0;ce(ic(ae))}).catch(E=>{if(pe.current===T){if(E instanceof Pa&&E.status===404&&Q!==xs){B(xs);return}S({stored:{},effective:{},orphaned:[]}),ce([])}}).finally(()=>{pe.current===T&&te(!1)})},[r,Q]);const _=i.useMemo(()=>({...L?.effective??{},...Object.fromEntries(Object.entries(G).filter(([,T])=>T!==null))}),[L,G]),C=i.useCallback((T,E)=>{y(H=>{const ae={...H};return delete ae[T.providerId],delete ae[T.modelId],ae}),J(H=>{if(!E)return{...H,[T.providerId]:null,[T.modelId]:null};const ae=E.indexOf("/");return ae<=0?H:{...H,[T.providerId]:E.slice(0,ae),[T.modelId]:E.slice(ae+1)}})},[]),I=i.useCallback(T=>{C(T,"")},[C]),z=i.useCallback(async()=>{if(!(!r||!fe))try{const T=await si(Q,G,r);S(T),J({}),y({})}catch(T){if(T instanceof Pa&&T.status===400&&T.details){const E=T.details.rejections??[];if(E.length>0)throw y(Object.fromEntries(E.map(H=>[H.settingId,H]))),new hn(E)}throw T}},[r,fe,Q,G]);i.useEffect(()=>(o?.(z),()=>o?.(null)),[o,z]);const ne=d.filter(T=>["default","summarization"].includes(T.laneId)),le=T=>T.laneId==="default"?"Project Default Model":T.laneId==="summarization"?"Project Summarization Model":T.label,Y=T=>T.laneId==="default"?"Project-wide default AI model used when no more specific task or project lane override is set.":T.laneId==="summarization"?"Model used for title auto-summarization, merge commit summaries, GitHub tracking issue titles, and PR title/body generation.":T.helperText;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.projectModels.tokenCap","Token Cap")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"tokenCap",children:n("settings.projectModels.tokenCap","Token Cap")}),e.jsxs("div",{className:"settings-token-cap-row",children:[e.jsx("input",{id:"tokenCap",type:"number",placeholder:n("settings.projectModels.noCap","No cap"),value:t.tokenCap??"",onChange:T=>{const E=T.target.value;s(H=>({...H,tokenCap:E?parseInt(E,10):null}))}}),t.tokenCap!=null&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:n("settings.projectModels.resetToDefaultNoCap","Reset to default (no cap)"),onClick:()=>s(T=>({...T,tokenCap:null})),style:{whiteSpace:"nowrap"},children:n("settings.projectModels.reset"," Reset ")})]}),e.jsx("small",{children:n("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.")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.modelLanes","Model Lanes")}),e.jsx("p",{className:"settings-description",children:n("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. ")}),g?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:n("settings.projectModels.loadingAvailableModels","Loading available models…")})}):P.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.noModelsAvailableConfigureAuthenticationFirst"," No models available. Configure authentication first. ")}):e.jsx(e.Fragment,{children:ne.map(T=>{const E=w(T),H=b(T),ae=E==="overridden",ve=le(T);return e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`${T.laneId}Model`,children:ve}),e.jsx("span",{className:`settings-lane-badge ${ae?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:ae?"Explicitly set for this project":"Inherited from global settings",children:ae?"Override (Project)":"Inherited (Global)"})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(Fe,{id:`${T.laneId}Model`,label:ve,models:P,value:H,onChange:St=>c(T,St),placeholder:T.laneId==="default"?"Use global default":"Use global",favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})}),ae&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:n("settings.projectModels.resetToInheritFromGlobal","Reset to inherit from global"),onClick:()=>h(T),style:{whiteSpace:"nowrap"},children:n("settings.projectModels.reset"," Reset ")})]}),e.jsxs("small",{children:[Y(T),n("settings.projectModels.fallsBackTo"," Falls back to: "),T.fallbackOrder,"."]})]},T.laneId)})}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.defaultWorkflowModelLanes","Default workflow model lanes")}),e.jsxs("p",{className:"settings-description",children:[n("settings.movedStub.modelLanes","Per-phase model lanes (execution, planning, reviewer, and their fallbacks) now live on the workflow."),n("settings.projectModels.theseProjectOverridesApplyToTheActiveDefault"," These project overrides apply to the active default workflow. ")]}),r?F?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:n("settings.projectModels.loadingWorkflowModelLanes","Loading workflow model lanes…")})}):P.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.noModelsAvailableConfigureAuthenticationBeforeSelectingWorkflow"," No models available. Configure authentication before selecting workflow model lanes. ")}):e.jsxs(e.Fragment,{children:[U.map(T=>{const E=oc(_,T),H=Object.prototype.hasOwnProperty.call(G,T.providerId)?G[T.providerId]!==null:!!(L?.stored&&(Object.prototype.hasOwnProperty.call(L.stored,T.providerId)||Object.prototype.hasOwnProperty.call(L.stored,T.modelId))),ae=me[T.providerId]?.message??me[T.modelId]?.message;return e.jsxs("div",{className:"form-group","data-testid":`workflow-model-lane-${T.id}`,children:[e.jsxs("div",{className:"settings-model-lane-label-row",children:[e.jsx("label",{htmlFor:`workflow-${T.id}-model`,children:T.label}),e.jsx("span",{className:`settings-lane-badge ${H?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:H?"Explicitly set for this project workflow":"Inherited from workflow defaults",children:H?"Override (Project)":"Inherited (Workflow)"})]}),e.jsxs("div",{className:"settings-model-lane-control-row",children:[e.jsx("div",{className:"settings-model-lane-control-main",children:e.jsx(Fe,{id:`workflow-${T.id}-model`,label:T.label,models:P,value:E,onChange:ve=>C(T,ve),placeholder:n("settings.projectModels.useWorkflowDefault","Use workflow default"),defaultOptionLabel:"Use workflow default",favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})}),H&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:n("settings.projectModels.resetToInheritFromWorkflow","Reset to inherit from workflow"),onClick:()=>I(T),style:{whiteSpace:"nowrap"},children:n("settings.projectModels.reset"," Reset ")})]}),e.jsx("small",{children:T.help}),ae?e.jsx("small",{className:"settings-error","data-testid":`workflow-model-lane-error-${T.id}`,children:ae}):null]},T.id)}),m?e.jsx("div",{className:"settings-model-lane-actions","aria-label":n("settings.projectModels.defaultWorkflowModelLaneActions","Default workflow model lane actions"),children:e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:m,children:n("settings.projectModels.advancedWorkflowPolicy"," Advanced workflow policy ")})}):null]}):e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.openAProjectToEditWorkflowModelLanes","Open a project to edit workflow model lanes.")}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.modelPresets","Model Presets")}),e.jsxs("div",{className:"form-group settings-model-presets",children:[e.jsx("label",{children:n("settings.projectModels.configuredPresets","Configured presets")}),O.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:n("settings.projectModels.noPresetsConfiguredYet","No presets configured yet.")}):e.jsx("div",{className:"settings-preset-list",children:O.map(T=>{const E=ai(T),H=`${E.executorValue||"default"} / ${E.validatorValue||"default"}`;return e.jsxs("div",{className:"settings-preset-item",children:[e.jsxs("div",{className:"settings-preset-item-meta",children:[e.jsx("strong",{children:T.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:H})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{v(T.id),V({...T})},children:n("settings.projectModels.edit"," Edit ")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:async()=>{$.has(T.id)&&!await Z({title:n("settings.models.deletePresetTitle","Delete Preset"),message:n("settings.models.deletePresetMessage",'Preset "{{name}}" is used in auto-selection. Delete it anyway?',{name:T.name}),danger:!0})||(s(ae=>({...ae,modelPresets:(ae.modelPresets||[]).filter(ve=>ve.id!==T.id),defaultPresetBySize:Object.fromEntries(Object.entries(ae.defaultPresetBySize||{}).filter(([,ve])=>ve!==T.id))})),R===T.id&&(v(null),V(null)))},children:n("settings.projectModels.delete"," Delete ")})]})]},T.id)})}),M?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{v(null),V({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:n("settings.projectModels.addPreset"," Add Preset ")})})]}),M?e.jsxs("div",{className:"form-group settings-preset-editor",children:[e.jsx("label",{children:n("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:n("settings.projectModels.name","Name")}),e.jsx("input",{id:"preset-name",type:"text",value:M.name,onChange:T=>{const E=T.target.value;V(H=>H&&{...H,name:E})}})]}),P.length===0?e.jsx("small",{children:n("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:n("settings.projectModels.executorModel","Executor model")}),e.jsx(Fe,{id:"preset-executor-model",label:"Preset executor model",models:P,value:M.executorProvider&&M.executorModelId?`${M.executorProvider}/${M.executorModelId}`:"",onChange:T=>{if(!T){V(H=>H&&{...H,executorProvider:void 0,executorModelId:void 0});return}const E=T.indexOf("/");V(H=>H&&{...H,executorProvider:T.slice(0,E),executorModelId:T.slice(E+1)})},placeholder:n("settings.projectModels.useDefault","Use default"),favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:n("settings.projectModels.reviewerModel","Reviewer model")}),e.jsx(Fe,{id:"preset-validator-model",label:"Preset reviewer model",models:P,value:M.validatorProvider&&M.validatorModelId?`${M.validatorProvider}/${M.validatorModelId}`:"",onChange:T=>{if(!T){V(H=>H&&{...H,validatorProvider:void 0,validatorModelId:void 0});return}const E=T.indexOf("/");V(H=>H&&{...H,validatorProvider:T.slice(0,E),validatorModelId:T.slice(E+1)})},placeholder:n("settings.projectModels.useDefault","Use default"),favoriteProviders:x,onToggleFavorite:j,favoriteModels:f,onToggleModelFavorite:k})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,children:n("settings.models.savePreset","Save preset")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{v(null),V(null)},children:n("settings.actions.cancel","Cancel")})]})]}):null,e.jsx("div",{className:"form-group settings-preset-auto-select",children:e.jsxs("label",{htmlFor:"autoSelectModelPreset",className:"checkbox-label",children:[e.jsx("input",{id:"autoSelectModelPreset",type:"checkbox",checked:t.autoSelectModelPreset||!1,onChange:T=>s(E=>({...E,autoSelectModelPreset:T.target.checked}))}),n("settings.projectModels.autoSelectPresetBasedOnTaskSize"," Auto-select preset based on task size ")]})}),t.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(T=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${T}`,children:T==="S"?"Small tasks (S):":T==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${T}`,value:t.defaultPresetBySize?.[T]||"",onChange:E=>{const H=E.target.value||void 0;s(ae=>({...ae,defaultPresetBySize:{...ae.defaultPresetBySize||{},[T]:H}}))},children:[e.jsx("option",{value:"",children:n("settings.projectModels.noPreset","No preset")}),K.map(E=>e.jsx("option",{value:E.id,children:E.name},E.id))]})]},T))}):null,e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.projectModels.aITitleAndGitCommitMessageSummarization"," AI Title and Git Commit Message Summarization ")}),e.jsx("p",{className:"settings-description",children:n("settings.projectModels.configuresTheModelUsedForTwoShortSummary"," Configures the model used for two short-summary jobs: auto-generating task titles from long descriptions, and generating merge commit summaries from step commits and diff stats. ")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoSummarizeTitles",className:"checkbox-label",children:[e.jsx("input",{id:"autoSummarizeTitles",type:"checkbox",checked:t.autoSummarizeTitles||!1,onChange:T=>s(E=>({...E,autoSummarizeTitles:T.target.checked}))}),n("settings.projectModels.autoSummarizeLongDescriptionsAsTitles"," Auto-summarize long descriptions as titles ")]}),e.jsx("small",{children:n("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. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"useAiMergeCommitSummary",className:"checkbox-label",children:[e.jsx("input",{id:"useAiMergeCommitSummary",type:"checkbox",checked:t.useAiMergeCommitSummary||!1,onChange:T=>s(E=>({...E,useAiMergeCommitSummary:T.target.checked}))}),n("settings.projectModels.aIMergeCommitSummaries"," AI merge commit summaries ")]}),e.jsx("small",{children:n("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. ")})]}),(t.autoSummarizeTitles||t.useAiMergeCommitSummary||t.githubTrackingEnabledByDefault||!1)&&e.jsx("p",{className:"settings-description",children:n("settings.movedStub.summarizerModelInline","The summarization model lane above controls title auto-summarization, merge commit summaries, GitHub tracking titles, and PR metadata generation.")})]})}function gn({message:a,onOpenWorkflowSettings:t}){const{t:s}=q("app");return e.jsxs("div",{className:"settings-moved-stub",role:"note",children:[e.jsx("p",{className:"settings-moved-stub__message",children:a}),e.jsx("button",{type:"button",className:"settings-moved-stub__action",onClick:t,disabled:!t,children:s("settings.movedStub.openWorkflowSettings","Open workflow settings")})]})}const Va=1440*60*1e3,dc=2;function uc({scopeBanner:a,form:t,setForm:s,globalMaxConcurrent:u,concurrencyLoading:r=!1,onGlobalMaxConcurrentChange:m,onOverlapIgnorePathChange:o,onOpenOverlapPathPicker:n,onRemoveOverlapIgnorePath:d,onAddOverlapIgnorePath:w,onOpenWorkflowSettings:b}){const{t:c}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:c("settings.scheduling.scheduling","Scheduling")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalMaxConcurrent",children:c("settings.scheduling.globalMaxConcurrent","Global Max Concurrent")}),e.jsx("input",{id:"globalMaxConcurrent",type:"number",min:0,max:1e4,disabled:r,value:u??"",onChange:h=>{const P=h.target.value;m(P===""?void 0:Number(P))}}),e.jsx("small",{className:"form-text text-muted",children:c("settings.scheduling.maximumConcurrentAgentsAcrossAllProjects","Maximum concurrent agents across all projects")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxConcurrent",children:c("settings.scheduling.maxConcurrentTasks","Max Concurrent Tasks")}),e.jsx("input",{id:"maxConcurrent",type:"number",min:1,max:10,disabled:r,value:t.maxConcurrent??"",onChange:h=>{const P=h.target.value;s(g=>({...g,maxConcurrent:P===""?void 0:Number(P)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxTriageConcurrent",children:c("settings.scheduling.maxTriageConcurrent","Max Triage Concurrent")}),e.jsx("input",{id:"maxTriageConcurrent",type:"number",min:1,max:10,disabled:r,value:t.maxTriageConcurrent??"",onChange:h=>{const P=h.target.value;s(g=>({...g,maxTriageConcurrent:P===""?void 0:Number(P)}))}}),e.jsx("small",{children:c("settings.scheduling.maximumConcurrentPlanningAgents","Maximum concurrent planning agents")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pollIntervalMs",children:c("settings.scheduling.pollIntervalMs","Poll Interval (ms)")}),e.jsx("input",{id:"pollIntervalMs",type:"number",min:5e3,step:1e3,value:t.pollIntervalMs??"",onChange:h=>{const P=h.target.value;s(g=>({...g,pollIntervalMs:P===""?void 0:Number(P)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"heartbeatScopeDiscipline",children:c("settings.scheduling.heartbeatScopeDiscipline","Heartbeat Scope Discipline")}),e.jsxs("select",{id:"heartbeatScopeDiscipline",className:"select",value:t.heartbeatScopeDiscipline??"strict",onChange:h=>{s(P=>({...P,heartbeatScopeDiscipline:h.target.value}))},children:[e.jsx("option",{value:"strict",children:c("settings.scheduling.strictDefault","Strict (default)")}),e.jsx("option",{value:"lite",children:c("settings.scheduling.lite","Lite")}),e.jsx("option",{value:"off",children:c("settings.scheduling.off","Off")})]}),e.jsx("small",{children:c("settings.scheduling.strictCoordinationFocusedHigherPerTickTokensLite","Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"engineerBacklogAutoClaim",className:"checkbox-label",children:[e.jsx("input",{id:"engineerBacklogAutoClaim",type:"checkbox",checked:t.engineerBacklogAutoClaim===!0,onChange:h=>s(P=>({...P,engineerBacklogAutoClaim:h.target.checked}))}),c("settings.scheduling.letEngineerAgentsAutoClaimBacklogTasks"," Let engineer agents auto-claim backlog tasks ")]}),e.jsx("small",{children:c("settings.scheduling.backlogNoTaskAutoClaimIsExecutorOnly","Backlog/no-task auto-claim is executor-only by default. Enable to let engineer-role agents auto-claim unowned backlog tasks; explicit routing and delegation are unchanged. Default: off.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskStuckTimeoutMs",children:c("settings.scheduling.stuckTaskTimeoutMinutes","Stuck Task Timeout (minutes)")}),e.jsx("input",{id:"taskStuckTimeoutMs",type:"number",min:1,step:1,value:t.taskStuckTimeoutMs?Math.round(t.taskStuckTimeoutMs/6e4):"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,taskStuckTimeoutMs:P&&g>0?g*6e4:void 0}))}}),e.jsx("small",{children:c("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.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"staleHighFanoutBlockerAgeThresholdMs",children:c("settings.scheduling.staleHighFanOutEscalationHours","Stale High Fan-out Escalation (hours)")}),e.jsx("input",{id:"staleHighFanoutBlockerAgeThresholdMs",type:"number",min:1,step:1,value:t.staleHighFanoutBlockerAgeThresholdMs?Math.round(t.staleHighFanoutBlockerAgeThresholdMs/36e5):"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,staleHighFanoutBlockerAgeThresholdMs:P&&g>0?g*36e5:void 0}))}}),e.jsx("small",{children:c("settings.scheduling.escalateHighFanOutBlockersOnlyAfterThey","Escalate high fan-out blockers only after they remain in in-progress or in-review for this many hours (age source: columnMovedAt, fallback updatedAt). Default: 2 hours.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"preserveProgressOnStuckRequeue",className:"checkbox-label",children:[e.jsx("input",{id:"preserveProgressOnStuckRequeue",type:"checkbox",checked:t.preserveProgressOnStuckRequeue!==!1,onChange:h=>s(P=>({...P,preserveProgressOnStuckRequeue:h.target.checked}))}),c("settings.scheduling.preserveStepProgressOnStuckTaskRequeue"," Preserve step progress on stuck-task requeue ")]}),e.jsx("small",{children:c("settings.scheduling.whenTheStuckDetectorKillsAndReQueues","When the stuck detector kills and re-queues a task, keep completed step statuses so the agent can resume from where it left off. Disable to reset every step to pending on each stuck retry. Default: enabled.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"specStalenessEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"specStalenessEnabled",type:"checkbox",checked:t.specStalenessEnabled||!1,onChange:h=>s(P=>({...P,specStalenessEnabled:h.target.checked}))}),c("settings.scheduling.enablePlanStalenessEnforcement"," Enable plan staleness enforcement ")]}),e.jsx("small",{children:c("settings.scheduling.whenEnabledTasksWithStalePlansPROMPTMd","When enabled, tasks with stale plans (PROMPT.md older than the threshold) are automatically sent back to planning for replanning")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"specStalenessMaxAgeMs",children:c("settings.scheduling.staleSpecThresholdHours","Stale Spec Threshold (hours)")}),e.jsx("input",{id:"specStalenessMaxAgeMs",type:"number",min:0,step:1,value:t.specStalenessMaxAgeMs!==void 0?Math.round(t.specStalenessMaxAgeMs/36e5):"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,specStalenessMaxAgeMs:P!==""?g*36e5:void 0}))},disabled:!t.specStalenessEnabled}),e.jsx("small",{children:c("settings.scheduling.maximumAgeInHoursBeforeAPlanIs","Maximum age in hours before a plan is considered stale. Default: 6 hours.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoArchiveDoneTasksEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoArchiveDoneTasksEnabled",type:"checkbox",checked:t.autoArchiveDoneTasksEnabled??!0,onChange:h=>s(P=>({...P,autoArchiveDoneTasksEnabled:h.target.checked}))}),c("settings.scheduling.enableAutomaticTaskArchiving"," Enable automatic task archiving ")]}),e.jsx("small",{children:c("settings.scheduling.completedTasksOlderThanTheThresholdAreMoved","Completed tasks older than the threshold are moved out of the active task database.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoArchiveDoneAfterMs",children:c("settings.scheduling.archiveCompletedTasksAfterDays","Archive Completed Tasks After (days)")}),e.jsx("input",{id:"autoArchiveDoneAfterMs",type:"number",min:1,step:1,value:t.autoArchiveDoneAfterMs!==void 0?Math.round(t.autoArchiveDoneAfterMs/Va):dc,onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,autoArchiveDoneAfterMs:P===""?void 0:g*Va}))},disabled:t.autoArchiveDoneTasksEnabled===!1}),e.jsx("small",{children:c("settings.scheduling.numberOfDaysATaskCanStayIn","Number of days a task can stay in Done before it is archived. Default: 2 days (48 hours).")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"archiveAgentLogMode",children:c("settings.scheduling.archiveAgentLog","Archive Agent Log")}),e.jsxs("select",{id:"archiveAgentLogMode",value:t.archiveAgentLogMode??"compact",onChange:h=>s(P=>({...P,archiveAgentLogMode:h.target.value})),disabled:t.autoArchiveDoneTasksEnabled===!1,children:[e.jsx("option",{value:"compact",children:c("settings.scheduling.compactSummaryAndRecentEntries","Compact summary and recent entries")}),e.jsx("option",{value:"none",children:c("settings.scheduling.doNotArchiveAgentLogs","Do not archive agent logs")}),e.jsx("option",{value:"full",children:c("settings.scheduling.fullAgentLog","Full agent log")})]}),e.jsx("small",{children:c("settings.scheduling.compactModeKeepsArchiveSizeLowWhilePreserving","Compact mode keeps archive size low while preserving recent agent activity for context.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxStuckKills",children:c("settings.scheduling.maxStuckRetries","Max Stuck Retries")}),e.jsx("input",{id:"maxStuckKills",type:"number",min:1,step:1,value:t.maxStuckKills??"",onChange:h=>{const P=h.target.value,g=Number(P);s(x=>({...x,maxStuckKills:P&&g>0?g:void 0}))}}),e.jsx("small",{children:c("settings.scheduling.maximumStuckDetectorRetriesBeforeATaskIs","Maximum stuck-detector retries before a task is marked failed. Default: 6.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"groupOverlappingFiles",className:"checkbox-label",children:[e.jsx("input",{id:"groupOverlappingFiles",type:"checkbox",checked:t.groupOverlappingFiles,onChange:h=>s(P=>({...P,groupOverlappingFiles:h.target.checked}))}),c("settings.scheduling.serializeTasksWithOverlappingFiles"," Serialize tasks with overlapping files ")]}),e.jsx("small",{children:c("settings.scheduling.whenEnabledTasksThatModifyTheSameFiles","When enabled, tasks that modify the same files are queued serially to avoid merge conflicts")})]}),e.jsxs("div",{className:"form-group settings-overlap-ignore-group",children:[e.jsx("label",{children:c("settings.scheduling.ignoredOverlapPaths","Ignored overlap paths")}),e.jsxs("small",{children:[c("settings.scheduling.optionalFileOrDirectoryPathsToIgnoreWhen"," Optional file or directory paths to ignore when overlap serialization is enabled. Paths are project-relative (for example "),e.jsx("code",{children:"docs/"}),c("settings.scheduling.or"," or "),e.jsx("code",{children:"generated/*"}),c("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",{type:"text",value:h,placeholder:c("settings.scheduling.docs","docs/"),onChange:g=>o(P,g.target.value)}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>n(P),"aria-label":`Browse path for ignored overlap entry ${P+1}`,children:c("settings.scheduling.browse"," Browse ")})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>d(P),disabled:(t.overlapIgnorePaths??[]).length===0&&P===0,children:c("settings.scheduling.remove"," Remove ")})]},`overlap-ignore-${P}`))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:c("settings.scheduling.addIgnoredPath"," Add ignored path ")})]}),e.jsx("div",{className:"settings-section-divider"}),e.jsx("h5",{className:"settings-section-heading",children:c("settings.scheduling.stepExecution","Step Execution")}),e.jsx(gn,{message:c("settings.movedStub.stepExecution","Step execution settings (run steps in new sessions, max parallel steps) now live on the workflow."),onOpenWorkflowSettings:b})]})}function mc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app"),r=t.evalSettings??{},m=r.enabled??!1;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.scheduledEvals.scheduledEvals","Scheduled Evals")}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{htmlFor:"scheduled-evals-enabled",className:"checkbox-label",children:[e.jsx("input",{id:"scheduled-evals-enabled",type:"checkbox",checked:m,onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},enabled:o.target.checked}}))}),u("settings.scheduledEvals.enableScheduledEvalRunsForThisProject"," Enable scheduled eval runs for this project ")]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-interval",children:u("settings.scheduledEvals.intervalMs","Interval (ms)")}),e.jsx("input",{id:"scheduled-evals-interval",className:"input",type:"number",min:6e4,max:6048e5,step:1e3,disabled:!m,value:r.intervalMs??864e5,onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},intervalMs:o.target.value===""?void 0:Number(o.target.value)}}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-provider",children:u("settings.scheduledEvals.evaluatorProvider","Evaluator Provider")}),e.jsx("input",{id:"scheduled-evals-provider",className:"input",value:r.evaluatorProvider??"",onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},evaluatorProvider:o.target.value.trim()===""?void 0:o.target.value}})),placeholder:u("settings.scheduledEvals.openai","openai")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-model",children:u("settings.scheduledEvals.evaluatorModel","Evaluator Model")}),e.jsx("input",{id:"scheduled-evals-model",className:"input",value:r.evaluatorModelId??"",onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},evaluatorModelId:o.target.value.trim()===""?void 0:o.target.value}})),placeholder:u("settings.scheduledEvals.gpt5","gpt-5")}),e.jsx("small",{className:"form-text text-muted",children:u("settings.scheduledEvals.leaveProviderAndModelBlankToInheritThe"," Leave provider and model blank to inherit the project validator lane model settings. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-follow-up-policy",children:u("settings.scheduledEvals.followUpPolicy","Follow-up Policy")}),e.jsxs("select",{id:"scheduled-evals-follow-up-policy",className:"select",disabled:!m,value:r.followUpPolicy??"suggest-only",onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},followUpPolicy:o.target.value}})),children:[e.jsx("option",{value:"disabled",children:u("settings.scheduledEvals.disabled","Disabled")}),e.jsx("option",{value:"suggest-only",children:u("settings.scheduledEvals.suggestOnly","Suggest only")}),e.jsx("option",{value:"auto-create",children:u("settings.scheduledEvals.autoCreateTasks","Auto-create tasks")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"scheduled-evals-retention-days",children:u("settings.scheduledEvals.retentionDays","Retention (days)")}),e.jsx("input",{id:"scheduled-evals-retention-days",className:"input",type:"number",min:1,max:365,step:1,disabled:!m,value:r.retentionDays??30,onChange:o=>s(n=>({...n,evalSettings:{...n.evalSettings??{},retentionDays:o.target.value===""?void 0:Number(o.target.value)}}))})]})]})}function hc(a,t){return a==="online"?t("settings.nodeRouting.statusOnline","Online"):a==="connecting"?t("settings.nodeRouting.statusConnecting","Connecting"):a==="error"?t("settings.nodeRouting.statusError","Error"):t("settings.nodeRouting.statusOffline","Offline")}function gc({scopeBanner:a,form:t,setForm:s,nodes:u}){const{t:r}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.nodeRouting.nodeRouting","Node Routing")}),e.jsx("p",{className:"settings-section-description",children:r("settings.nodeRouting.configureHowTasksAreRoutedToExecutionNodes","Configure how tasks are routed to execution nodes.")}),e.jsx("p",{className:"settings-node-routing-note",children:r("settings.nodeRouting.theseSettingsApplyAtTheProjectLevel","These settings apply at the project level.")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultNodeId",children:r("settings.nodeRouting.defaultExecutionNode","Default Execution Node")}),e.jsxs("select",{id:"defaultNodeId",className:"select",value:typeof t.defaultNodeId=="string"?t.defaultNodeId:"",onChange:m=>{const o=m.target.value;s(n=>({...n,defaultNodeId:o||void 0}))},children:[e.jsx("option",{value:"",children:r("settings.nodeRouting.localExecutionNoDefaultNode","Local execution (no default node)")}),u.map(m=>e.jsxs("option",{value:m.id,children:[m.name," (",hc(m.status,r),")"]},m.id))]}),(()=>{const m=u.find(o=>o.id===t.defaultNodeId);return m?e.jsxs("div",{className:"settings-node-status",children:[e.jsx("span",{children:r("settings.nodeRouting.selectedNode","Selected node:")}),e.jsx(ni,{status:m.status,showLabel:!0})]}):null})(),e.jsx("small",{children:r("settings.nodeRouting.usedWhenATaskHasNoNodeOverride","Used when a task has no node override. Node status is shown for safer routing selection.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"unavailableNodePolicy",children:r("settings.nodeRouting.unavailableNodePolicy","Unavailable Node Policy")}),e.jsxs("select",{id:"unavailableNodePolicy",className:"select",value:t.unavailableNodePolicy==="fallback-local"?"fallback-local":"block",onChange:m=>s(o=>({...o,unavailableNodePolicy:m.target.value})),children:[e.jsx("option",{value:"block",children:r("settings.nodeRouting.blockExecution","Block execution")}),e.jsx("option",{value:"fallback-local",children:r("settings.nodeRouting.fallBackToLocal","Fall back to local")})]})]})]})}function pc({scopeBanner:a,form:t,setForm:s,gitRemotes:u,worktrunkInstall:r,worktrunkInstallVerified:m,onOpenWorktreesDirPicker:o,onOpenApprovals:n}){const{t:d}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:d("settings.worktrees.worktrees","Worktrees")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxWorktrees",children:d("settings.worktrees.maxWorktrees","Max Worktrees")}),e.jsx("input",{id:"maxWorktrees",type:"number",min:1,max:20,value:t.maxWorktrees??"",onChange:w=>{const b=w.target.value;s(c=>({...c,maxWorktrees:b===""?void 0:Number(b)}))}}),e.jsx("small",{children:d("settings.worktrees.limitsTotalGitWorktreesIncludingInReviewTasks","Limits total git worktrees including in-review tasks")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeInitCommand",children:d("settings.worktrees.worktreeInitCommand","Worktree Init Command")}),e.jsx("input",{id:"worktreeInitCommand",type:"text",placeholder:d("settings.worktrees.pnpmInstallFrozenLockfile","pnpm install --frozen-lockfile"),value:t.worktreeInitCommand||"",onChange:w=>s(b=>({...b,worktreeInitCommand:w.target.value}))}),e.jsx("small",{children:d("settings.worktrees.shellCommandToRunInEachNewWorktree","Shell command to run in each new worktree after creation")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"recycleWorktrees",className:"checkbox-label",children:[e.jsx("input",{id:"recycleWorktrees",type:"checkbox",checked:t.recycleWorktrees,onChange:w=>s(b=>({...b,recycleWorktrees:w.target.checked}))}),d("settings.worktrees.recycleWorktrees"," Recycle worktrees ")]}),e.jsx("small",{children:d("settings.worktrees.offByDefaultOptInWhenEnabledCompleted","Off by default (opt-in). When enabled, completed task worktrees are returned to an idle pool instead of being deleted, preserving build caches for faster startup")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"executorAllowSiblingBranchRename",className:"checkbox-label",children:[e.jsx("input",{id:"executorAllowSiblingBranchRename",type:"checkbox",checked:t.executorAllowSiblingBranchRename===!0,onChange:w=>s(b=>({...b,executorAllowSiblingBranchRename:w.target.checked}))}),d("settings.worktrees.allowSilentSiblingBranchRenameDuringExecutorConflicts"," Allow silent sibling branch rename during executor conflicts ")]}),e.jsxs("small",{children:[d("settings.worktrees.discouragedThisRestoresTheLegacyBehaviorWhereA"," Discouraged. This restores the legacy behavior where a live "),e.jsx("code",{children:"fusion/<task-id>"}),d("settings.worktrees.branchCollisionSilentlyForksWorkOntoSiblingBranches"," branch collision silently forks work onto sibling branches like "),e.jsx("code",{children:"-2"}),d("settings.worktrees.andCanHidePriorCommitsFromTheDefault"," and can hide prior commits from the default recovery flow. ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeNaming",children:d("settings.worktrees.worktreeNamingStyle","Worktree Naming Style")}),e.jsxs("select",{id:"worktreeNaming",value:t.worktreeNaming||"random",onChange:w=>s(b=>({...b,worktreeNaming:w.target.value})),disabled:t.recycleWorktrees,children:[e.jsx("option",{value:"random",children:d("settings.worktrees.randomNamesEGSwiftFalcon","Random names (e.g., swift-falcon)")}),e.jsx("option",{value:"task-id",children:d("settings.worktrees.taskIDEGFN042","Task ID (e.g., FN-042)")}),e.jsx("option",{value:"task-title",children:d("settings.worktrees.taskTitleEGFixLoginBug","Task title (e.g., fix-login-bug)")})]}),e.jsx("small",{children:t.recycleWorktrees?"Naming style is not applicable when recycling worktrees — pooled worktrees retain their existing names":"How to name fresh worktree directories. Only applies when recycling is off."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreesDir",children:d("settings.worktrees.worktreesDirectory","Worktrees Directory")}),e.jsxs("div",{className:"settings-overlap-ignore-path-controls",children:[e.jsx("input",{id:"worktreesDir",type:"text",placeholder:d("settings.worktrees.defaultsToWorktreesLeaveEmptyUnlessOverriding","Defaults to .worktrees — leave empty unless overriding"),value:t.worktreesDir||"",disabled:t.worktrunk?.enabled===!0,onChange:w=>s(b=>({...b,worktreesDir:w.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:o,"aria-label":d("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),disabled:t.worktrunk?.enabled===!0,children:d("settings.worktrees.browse"," Browse ")})]}),e.jsx("small",{children:t.worktrunk?.enabled===!0?"Disabled because Worktrunk integration is enabled — worktrunk manages the worktree directory layout. Disable worktrunk integration to use a custom directory.":e.jsxs(e.Fragment,{children:[d("settings.worktrees.optionalSupports"," Optional. Supports "),e.jsx("code",{children:"~"}),d("settings.worktrees.and"," and "),e.jsx("code",{children:"{repo}"}),d("settings.worktrees.defaultsTo",". Defaults to "),e.jsx("code",{children:"<projectRoot>/.worktrees"}),d("settings.worktrees.whenUnsetOnlyAffectsNewlyCreatedWorktrees"," when unset. Only affects newly-created worktrees. ")]})})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktreeRebaseBeforeMerge",className:"checkbox-label",children:[e.jsx("input",{id:"worktreeRebaseBeforeMerge",type:"checkbox",checked:t.worktreeRebaseBeforeMerge!==!1,onChange:w=>s(b=>({...b,worktreeRebaseBeforeMerge:w.target.checked}))}),d("settings.worktrees.rebaseFromRemoteBeforeMerge"," Rebase from remote before merge ")]}),e.jsx("small",{children:d("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.")})]}),t.worktreeRebaseBeforeMerge!==!1&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeRebaseRemote",children:d("settings.worktrees.rebaseRemote","Rebase Remote")}),e.jsxs("select",{id:"worktreeRebaseRemote",value:t.worktreeRebaseRemote??"",onChange:w=>s(b=>({...b,worktreeRebaseRemote:w.target.value||void 0})),children:[e.jsx("option",{value:"",children:d("settings.worktrees.useGitDefault","Use git default")}),u.map(w=>e.jsxs("option",{value:w.name,children:[w.name," (",w.fetchUrl,")"]},w.name))]}),e.jsxs("small",{children:[d("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"}),d("settings.worktrees.closeParenPeriod",").")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktreeRebaseLocalBase",className:"checkbox-label",children:[e.jsx("input",{id:"worktreeRebaseLocalBase",type:"checkbox",checked:t.worktreeRebaseLocalBase!==!1,onChange:w=>s(b=>({...b,worktreeRebaseLocalBase:w.target.checked}))}),d("settings.worktrees.alsoRebaseOntoLocalDefaultBranchHEAD"," Also rebase onto local default-branch HEAD ")]}),e.jsx("small",{children:d("settings.worktrees.inAdditionToTheRemoteRebaseAboveAlso"," In addition to the remote rebase above, also rebase the task branch onto the local default-branch HEAD (rootDir). This catches sibling tasks that merged locally but haven't been pushed yet — without it, two concurrent tasks where one deletes code can have the other silently re-introduce it via the fallback strategy. Enabled by default; only disable if it causes issues with your workflow. ")})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:d("settings.worktrees.worktrunkIntegration","Worktrunk integration")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktrunkEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"worktrunkEnabled",type:"checkbox",checked:t.worktrunk?.enabled===!0,disabled:!m&&t.worktrunk?.enabled!==!0,onChange:w=>s(b=>({...b,worktrunk:{enabled:w.target.checked,binaryPath:b.worktrunk?.binaryPath??"",onFailure:b.worktrunk?.onFailure??"fail"}}))}),d("settings.worktrees.enableWorktrunkIntegration"," Enable worktrunk integration ")]}),e.jsxs("small",{children:[d("settings.worktrees.disabledByDefaultOptInWhenEnabledFusion"," Disabled by default (opt-in). When enabled, Fusion shells out to "),e.jsx("code",{children:"worktrunk"}),d("settings.worktrees.forWorktreeCreateSyncPruneAndRemoveOperations"," for worktree create, sync, prune, and remove operations and follows worktrunk's directory layout. ")]}),!m&&t.worktrunk?.enabled!==!0&&e.jsx("small",{className:"settings-muted",children:d("settings.worktrees.installTheWorktrunkBinaryBelowToEnableThis","Install the worktrunk binary below to enable this integration.")})]}),e.jsxs("div",{className:"form-group","data-testid":"worktrunk-install-affordance",children:[r.status==="installed"&&e.jsxs("small",{className:"settings-muted",children:[d("settings.worktrees.worktrunk"," worktrunk "),r.version??"",d("settings.worktrees.installedAt"," installed at "),r.installPath??"~/.fusion/bin/worktrunk"]}),(r.status==="missing"||r.status==="installing")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void r.requestInstall(),disabled:r.requesting||r.status==="installing",children:d("settings.worktrees.installWorktrunk","Install worktrunk binary")}),e.jsx("small",{className:"settings-muted",children:d("settings.worktrees.enableWorktrunkAndRequestApprovalToInstallThe","Enable worktrunk and request approval to install the pinned release.")})]}),r.status==="pending-approval"&&e.jsxs(e.Fragment,{children:[e.jsx("small",{className:"settings-muted",children:d("settings.worktrees.awaitingApproval","Awaiting approval — open Approvals to continue.")}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>n?.(r.pendingApprovalId),children:d("settings.worktrees.openApprovals","Open Approvals")})]}),(r.status==="denied"||r.status==="failed")&&e.jsxs(e.Fragment,{children:[e.jsx("small",{style:{color:"var(--color-error)"},children:r.error??"Worktrunk install failed."}),e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void r.requestInstall(),children:d("settings.worktrees.tryAgain","Try again")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktrunkBinaryPath",children:d("settings.worktrees.worktrunkBinaryPath","Worktrunk binary path")}),e.jsx("input",{id:"worktrunkBinaryPath",type:"text",className:"input",placeholder:d("settings.worktrees.autoDetectFusionBinWorktrunkOrPATH","auto-detect (~/.fusion/bin/worktrunk or $PATH)"),value:t.worktrunk?.binaryPath??"",disabled:t.worktrunk?.enabled!==!0,onChange:w=>s(b=>({...b,worktrunk:{enabled:b.worktrunk?.enabled===!0,binaryPath:w.target.value,onFailure:b.worktrunk?.onFailure??"fail"}}))}),e.jsx("small",{children:d("settings.worktrees.optionalLeaveBlankToAutoResolveFusionWill","Optional. Leave blank to auto-resolve; Fusion will offer to install on first use.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktrunkOnFailure",children:d("settings.worktrees.worktrunkFailureBehavior","Worktrunk failure behavior")}),e.jsxs("select",{id:"worktrunkOnFailure",className:"select",value:t.worktrunk?.onFailure??"fail",disabled:t.worktrunk?.enabled!==!0,onChange:w=>s(b=>({...b,worktrunk:{enabled:b.worktrunk?.enabled===!0,binaryPath:b.worktrunk?.binaryPath??"",onFailure:w.target.value}})),children:[e.jsx("option",{value:"fail",children:d("settings.worktrees.failAndPauseTheTaskDefault","Fail and pause the task (default)")}),e.jsx("option",{value:"fallback-native",children:d("settings.worktrees.fallBackToFusionsNativeWorktreeBackend","Fall back to Fusion's native worktree backend")})]}),e.jsxs("small",{children:[e.jsx("code",{children:"fail"}),d("settings.worktrees.stopsOnWorktrunkErrorsForExplicitOperatorRecovery"," stops on worktrunk errors for explicit operator recovery; "),e.jsx("code",{children:"fallback-native"}),d("settings.worktrees.keepsProgressMovingBySwitchingToFusionApos"," keeps progress moving by switching to Fusion's built-in worktree backend. ")]})]})]})}function bc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.commands.commands","Commands")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"testCommand",children:u("settings.commands.testCommand","Test Command")}),e.jsx("input",{id:"testCommand",type:"text",placeholder:u("settings.commands.eGPnpmTest","e.g. pnpm test"),value:t.testCommand||"",onChange:r=>s(m=>({...m,testCommand:r.target.value||void 0}))}),e.jsx("small",{children:u("settings.commands.commandUsedToRunTestsInjectedIntoGenerated","Command used to run tests — injected into generated task specs")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"buildCommand",children:u("settings.commands.buildCommand","Build Command")}),e.jsx("input",{id:"buildCommand",type:"text",placeholder:u("settings.commands.eGPnpmBuild","e.g. pnpm build"),value:t.buildCommand||"",onChange:r=>s(m=>({...m,buildCommand:r.target.value||void 0}))}),e.jsx("small",{children:u("settings.commands.commandUsedToBuildTheProjectInjectedInto","Command used to build the project — injected into generated task specs")})]})]})}function fc(a){const t=Number(a);return Number.isFinite(t)&&t>0?Math.floor(t):3}async function vc(a){if(!a.ok)throw new Error(await a.text()||"Failed to load legacy auto-merge stamps");return a.json()}function xc({scopeBanner:a,form:t,setForm:s,integrationBranchOptions:u,integrationBranchCustomMode:r,setIntegrationBranchCustomMode:m,onOpenWorkflowSettings:o}){const{t:n}=q("app"),[d,w]=i.useState([]),[b,c]=i.useState(!0),[h,P]=i.useState(!1),[g,x]=i.useState(null),[f,j]=i.useState(null),k=i.useCallback(async()=>{c(!0),x(null);try{const v=await vc(await fetch("/api/maintenance/legacy-automerge-stamps"));w(Array.isArray(v.candidates)?v.candidates:[])}catch(v){x(v instanceof Error?v.message:"Failed to load legacy auto-merge stamps")}finally{c(!1)}},[]);i.useEffect(()=>{k()},[k]);const R=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.")){P(!0),x(null),j(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 V=await M.json();j(`Cleared ${V.count} legacy auto-merge stamp${V.count===1?"":"s"}.`),await k()}catch(M){x(M instanceof Error?M.message:"Failed to apply legacy auto-merge stamp cleanup")}finally{P(!1)}}};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:n("settings.merge.merge","Merge")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoMerge",className:"checkbox-label",children:[e.jsx("input",{id:"autoMerge",type:"checkbox",checked:t.autoMerge,onChange:v=>s(M=>({...M,autoMerge:v.target.checked}))}),n("settings.merge.autoMergeCompletedTasks"," Auto-merge completed tasks ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.whenEnabledTasksThatPassReviewAreAutomatically","When enabled, tasks that pass review are automatically merged into the main branch")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxAutoMergeRetries",children:n("settings.merge.autoMergeConflictRetries","Auto-merge conflict retries")}),e.jsx("input",{id:"maxAutoMergeRetries",type:"number",min:1,step:1,value:t.maxAutoMergeRetries??3,onChange:v=>s(M=>({...M,maxAutoMergeRetries:v.target.value===""?void 0:fc(v.target.value)}))}),e.jsx("small",{children:n("settings.merge.positiveIntegerRetryCapForAutoMergeConflict","Positive integer retry cap for auto-merge conflict resolution before a task parks for human recovery. Default 3.")})]}),e.jsxs("div",{className:"form-group","data-testid":"legacy-automerge-stamp-cleanup-panel",children:[e.jsx("h5",{className:"settings-section-heading",children:n("settings.merge.legacyAutoMergeStampCleanup","Legacy auto-merge stamp cleanup")}),e.jsx("small",{children:n("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. ")}),b?e.jsx("small",{"aria-live":"polite",children:n("settings.merge.checkingForLegacyAutoMergeStamps","Checking for legacy auto-merge stamps…")}):d.length===0?e.jsx("small",{"data-testid":"legacy-automerge-stamp-empty-state",children:n("settings.merge.noLegacyAutoMergeStampsToCleanUp"," No legacy auto-merge stamps to clean up. ")}):e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:[d.length,n("settings.merge.legacyAutoMergeStamp"," legacy auto-merge stamp"),d.length===1?"":"s",n("settings.merge.readyToCleanUp"," ready to clean up.")]}),e.jsx("ul",{children:d.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:R,disabled:h,"data-testid":"legacy-automerge-stamp-apply-button",children:h?"Applying cleanup…":"Apply cleanup"})]}),f?e.jsx("small",{className:"settings-success","aria-live":"polite",children:f}):null,g?e.jsx("small",{className:"settings-error",role:"alert",children:g}):null]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergerMode",children:n("settings.merge.aIMerge","AI merge")}),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:n("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:n("settings.merge.deterministicLegacyRebaseConflictStrategyAuditPipeline","Deterministic (legacy) — rebase / conflict-strategy / audit pipeline")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("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:n("settings.merge.theLegacyMergeSettingsBelowDoNotApply","The legacy merge settings below do not apply while AI merge is on.")})]})]})]}),(t.merger?.mode??"ai")==="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergerMaxReviewPasses",children:n("settings.merge.maxAIReviewPasses","Max AI review passes")}),e.jsx("input",{id:"mergerMaxReviewPasses",type:"number",min:0,max:10,value:t.merger?.maxReviewPasses??3,onChange:v=>s(M=>({...M,merger:{...M.merger??{},maxReviewPasses:v.target.value===""?void 0:Number(v.target.value)}}))}),e.jsx("small",{children:n("settings.merge.aICorrectiveRoundsBeforeLandingTheBestResult","AI corrective rounds before landing the best result (advisory concern) or hard-failing (unfixable correctness concern). Default 3. The reviewer uses your project's reviewer/validator model.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"mergerAllowDirtyLocalCheckoutSync",className:"checkbox-label",children:[e.jsx("input",{id:"mergerAllowDirtyLocalCheckoutSync",type:"checkbox",checked:t.merger?.allowDirtyLocalCheckoutSync===!0,onChange:v=>s(M=>({...M,merger:{...M.merger??{},allowDirtyLocalCheckoutSync:v.target.checked}}))}),n("settings.merge.allowAIMergeToSyncADirtyChecked"," Allow AI merge to sync a dirty checked-out integration branch ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.dangerousCompatibilityEscapeHatchLeaveOffUnlessYou"," Dangerous compatibility escape hatch. Leave off unless you explicitly want 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. ")})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"testMode",className:"checkbox-label",children:[e.jsx("input",{id:"testMode",type:"checkbox",checked:t.testMode===!0,onChange:v=>s(M=>({...M,testMode:v.target.checked}))}),n("settings.merge.enableTestMode"," Enable test mode ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.forcesAllAILanesToUseTheDeterministic","Forces all AI lanes to use the deterministic mock provider. No network calls, zero token cost.")})]})]}),e.jsx(gn,{message:n("settings.movedStub.reviewVerification","Review, verification auto-fix, and scope-enforcement settings now live on the workflow."),onOpenWorkflowSettings:o}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeStrategy",children:n("settings.merge.autoCompletionMode","Auto-completion mode")}),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:n("settings.merge.directMergeIntoTheCurrentBranch","Direct merge into the current branch")}),e.jsx("option",{value:"pull-request",children:n("settings.merge.createMonitorAndMergeAGitHubPullRequest","Create, monitor, and merge a GitHub pull request")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.controlsWhatHappensAfterATaskReachesIn"," Controls what happens after a task reaches In Review. Direct mode merges into the current branch locally. Pull request mode keeps the task in In Review while Fusion waits for GitHub reviews and required checks before merging the PR. ")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"integrationBranch",children:n("settings.merge.integrationBranch","Integration branch")}),(()=>{const v=t.integrationBranch??"",M=v.length>0&&u.includes(v);if(r||v.length>0&&!M)return e.jsxs("div",{className:"form-inline-group",children:[e.jsx("input",{id:"integrationBranch",type:"text",className:"input",placeholder:n("settings.merge.branchName","branch name"),value:v,onChange:O=>{const K=O.target.value.trim();s($=>({...$,integrationBranch:K.length===0?void 0:K}))},"data-testid":"integration-branch-custom-input"}),e.jsx("button",{type:"button",className:"btn-link",onClick:()=>{m(!1),s(O=>({...O,integrationBranch:void 0}))},"data-testid":"integration-branch-use-dropdown",children:n("settings.merge.useDropdown"," Use dropdown ")})]});const N="__fusion-custom__",Z="";return e.jsxs("select",{id:"integrationBranch",className:"select",value:v,onChange:O=>{const K=O.target.value;if(K===N){m(!0);return}s($=>({...$,integrationBranch:K===Z?void 0:K}))},"data-testid":"integration-branch-select",children:[e.jsx("option",{value:Z,children:n("settings.merge.autoDetectOriginHEADMain","(auto-detect — origin/HEAD → main)")}),u.map(O=>e.jsx("option",{value:O,children:O},O)),e.jsx("option",{value:N,children:n("settings.merge.custom","Custom…")})]})})(),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.theCanonicalBranchFusionMergesTasksIntoAnd"," 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:n("settings.merge.autoDetect","auto-detect")}),n("settings.merge.toResolveViaTheStandardCascade"," to resolve via the standard cascade ("),e.jsx("code",{children:"integrationBranch"}),n("settings.merge.legacy"," → legacy "),e.jsx("code",{children:"baseBranch"})," →",e.jsx("code",{children:"origin/HEAD"}),n("settings.merge.symbolicRefFallback"," symbolic ref → fallback "),e.jsx("code",{children:"main"}),n("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"}),n("settings.merge.and",", and "),e.jsx("code",{children:"develop"}),n("settings.merge.areListedFirstOrChoose"," are listed first — or choose "),e.jsx("em",{children:n("settings.merge.custom","Custom…")}),n("settings.merge.toTypeABranchThatDoesnAposT"," to type a branch that doesn't exist locally yet. Applies to both direct merges and pull-request mode; individual tasks can still override via task metadata. ")]})]})]}),t.mergeStrategy!=="pull-request"&&(t.merger?.mode??"ai")!=="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"directMergeCommitStrategy",children:n("settings.merge.directMergeCommitRouting","Direct merge commit routing")}),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:n("settings.merge.autoSquashSingleSubstantiveBranchesPreserveMultiSubstantive","Auto — squash single-substantive branches, preserve multi-substantive history")}),e.jsx("option",{value:"always-squash",children:n("settings.merge.alwaysSquashDirectMerges","Always squash direct merges")}),e.jsx("option",{value:"always-rebase",children:n("settings.merge.alwaysPreserveDirectMergeCommitHistory","Always preserve direct-merge commit history")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.autoKeepsTodayAposSSquashBehaviorFor"," Auto keeps today's squash behavior for branches with zero or one substantive commit, but switches multi-substantive branches to a history-preserving rebase-and-merge path. Individual tasks can override this in PROMPT.md with "),e.jsx("code",{children:"**Direct Merge Commit Strategy:** auto|always-squash|always-rebase"}),"."]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeIntegrationWorktree",children:n("settings.merge.integrationWorktree","Integration worktree")}),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:n("settings.merge.reuseTaskWorktreeDefault","Reuse task worktree (default)")}),e.jsx("option",{value:"cwd-main",children:n("settings.merge.useProjectRootLegacy","Use project root (legacy)")})]}),e.jsx("small",{children:n("settings.merge.autoMergeRunsInTheTaskWorktreeBy"," Auto-merge runs in the task worktree by default. Switch to the legacy project-root path only if you need the pre-FN-5279 fallback; worktrunk-managed projects still defer to worktrunk. ")}),(t.mergeIntegrationWorktree??"reuse-task-worktree")!=="reuse-task-worktree"&&e.jsxs("div",{className:"settings-warning-banner",role:"alert","aria-live":"polite","data-testid":"merge-integration-worktree-warning",children:[e.jsx("strong",{children:n("settings.merge.legacyIntegrationBranchMode","Legacy integration-branch mode.")})," ",n("settings.merge.autoMergeWillRunRebaseConflictResolutionAnd"," Auto-merge will run rebase, conflict resolution, and squash commits inside the project root (the user's checked-out integration-branch worktree) instead of the task worktree. Fusion assumes that directory is already on the integration branch and clean; if it isn't, merges may fail or touch the user's working tree. Reuse-task-worktree is the recommended default (FN-5279). Switch back unless you have a specific reason to opt in (FN-5348). ")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeAdvanceAutoSync",children:n("settings.merge.autoSyncProjectCheckoutAfterMerge","Auto-sync project checkout after merge")}),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:n("settings.merge.stashFastForwardDefaultPreserveLocalEdits","Stash + fast-forward (default) — preserve local edits")}),e.jsx("option",{value:"ff-only",children:n("settings.merge.fastForwardOnlySkipDirtyWorktrees","Fast-forward only — skip dirty worktrees")}),e.jsx("option",{value:"off",children:n("settings.merge.offLeaveTheProjectRootStaleLegacyBehavior","Off — leave the project root stale (legacy behavior)")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("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"}),n("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"}),n("settings.merge.snapsCleanlyWhenTheWorktreeHasNoEdits"," snaps cleanly when the worktree has no edits and skips otherwise. "),e.jsx("code",{children:"Off"}),n("settings.merge.isTheLegacyBehavior"," is the legacy behavior: "),e.jsx("code",{children:"git status"}),n("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.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:n("settings.merge.gitHubAuthentication","GitHub Authentication")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubAuthMode",children:n("settings.merge.gitHubAuthMode","GitHub auth mode")}),e.jsxs("select",{id:"githubAuthMode",className:"select",value:t.githubAuthMode??"gh-cli",onChange:v=>s(M=>({...M,githubAuthMode:v.target.value})),children:[e.jsx("option",{value:"gh-cli",children:n("settings.merge.gitHubCLIGhAuth","GitHub CLI (gh auth)")}),e.jsx("option",{value:"token",children:n("settings.merge.personalAccessToken","Personal access token")})]})]}),(t.githubAuthMode??"gh-cli")==="token"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"githubAuthToken",children:n("settings.merge.gitHubPersonalAccessToken","GitHub personal access token")}),e.jsx("input",{id:"githubAuthToken",type:"password",className:"input",value:t.githubAuthToken??"",onChange:v=>s(M=>({...M,githubAuthToken:v.target.value||void 0}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"includeTaskIdInCommit",className:"checkbox-label",children:[e.jsx("input",{id:"includeTaskIdInCommit",type:"checkbox",checked:t.includeTaskIdInCommit!==!1,onChange:v=>s(M=>({...M,includeTaskIdInCommit:v.target.checked}))}),n("settings.merge.includeTaskIDInCommitScope"," Include task ID in commit scope ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.whenDisabledMergeCommitMessagesOmitTheTask","When disabled, merge commit messages omit the task ID from the scope (e.g. "),e.jsx("code",{children:"feat: ..."}),n("settings.merge.insteadOf"," instead of "),e.jsx("code",{children:"feat(KB-001): ..."}),")"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"commitAuthorEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"commitAuthorEnabled",type:"checkbox",checked:t.commitAuthorEnabled!==!1,onChange:v=>s(M=>({...M,commitAuthorEnabled:v.target.checked}))}),n("settings.merge.addFusionAsCoAuthorOnCommits"," Add Fusion as co-author on commits ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("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"}),n("settings.merge.trailerCreditingFusionRecognizedByGitHubForShared"," trailer crediting Fusion (recognized by GitHub for shared attribution). ")]})]})]}),t.commitAuthorEnabled!==!1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorName",children:n("settings.merge.coAuthorName","Co-author Name")}),e.jsx("input",{id:"commitAuthorName",type:"text",value:t.commitAuthorName??"",placeholder:n("settings.merge.fusion","Fusion"),onChange:v=>s(M=>({...M,commitAuthorName:v.target.value||void 0}))}),e.jsxs("small",{children:[n("settings.merge.nameUsedInThe","Name used in the "),e.jsx("code",{children:"Co-authored-by"}),n("settings.merge.trailer"," trailer")]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorEmail",children:n("settings.merge.coAuthorEmail","Co-author Email")}),e.jsx("input",{id:"commitAuthorEmail",type:"email",value:t.commitAuthorEmail??"",placeholder:n("settings.merge.noreplyRunfusionAi","noreply@runfusion.ai"),onChange:v=>s(M=>({...M,commitAuthorEmail:v.target.value||void 0}))}),e.jsxs("small",{children:[n("settings.merge.emailUsedInThe","Email used in the "),e.jsx("code",{children:"Co-authored-by"}),n("settings.merge.trailer"," trailer")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoResolveConflicts",className:"checkbox-label",children:[e.jsx("input",{id:"autoResolveConflicts",type:"checkbox",checked:t.autoResolveConflicts!==!1,onChange:v=>s(M=>({...M,autoResolveConflicts:v.target.checked}))}),n("settings.merge.autoResolveConflictsInLockFilesAndGenerated"," Auto-resolve conflicts in lock files and generated files ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("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.")})]})]}),(t.merger?.mode??"ai")!=="ai"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"smartConflictResolution",className:"checkbox-label",children:[e.jsx("input",{id:"smartConflictResolution",type:"checkbox",checked:t.smartConflictResolution!==!1,onChange:v=>s(M=>({...M,smartConflictResolution:v.target.checked}))}),n("settings.merge.smartConflictResolution"," Smart conflict resolution ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("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.")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeConflictStrategy",children:n("settings.merge.conflictFallbackStrategy","Conflict Fallback Strategy")}),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:n("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:n("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:n("settings.merge.aIOnlyAIAutoResolveAIRetryNever","AI only — AI → auto-resolve → AI retry; never silently pick a side")}),e.jsx("option",{value:"abort",children:n("settings.merge.abortOneAIAttemptRequireManualResolutionIf","Abort — one AI attempt; require manual resolution if it fails")})]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsxs("small",{children:[n("settings.merge.both"," Both "),e.jsx("strong",{children:n("settings.merge.smart","Smart")}),n("settings.merge.optionsStartWithABestEffort"," options start with a best-effort "),e.jsx("code",{children:"git fetch"}),n("settings.merge.fastForwardOfLocalMainFrom"," + fast-forward of local main from "),e.jsx("code",{children:"origin"}),n("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:n("settings.merge.finalFallback","final fallback")}),":"," ",e.jsx("strong",{children:n("settings.merge.smartPreferMain","Smart, prefer main")}),n("settings.merge.uses"," uses "),e.jsx("code",{children:"-X ours"}),n("settings.merge.soMainWinsProtectsJustMergedSiblingWork"," so main wins — protects just-merged sibling work and is the new default. ")," ",e.jsx("strong",{children:n("settings.merge.smartPreferTask","Smart, prefer task")}),n("settings.merge.uses"," uses "),e.jsx("code",{children:"-X theirs"}),n("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:n("settings.merge.aIOnly","AI only")}),n("settings.merge.retriesTheAIAgentRatherThanAutoPicking"," retries the AI agent rather than auto-picking a side. ")," ",e.jsx("strong",{children:n("settings.merge.abort","Abort")}),n("settings.merge.stopsAfterTheFirstAIAttemptAndWaits"," stops after the first AI attempt and waits for a human. ")," ",e.jsxs("em",{children:[n("settings.merge.legacy2","Legacy "),e.jsx("code",{children:'"smart"'}),n("settings.merge.and2"," and "),e.jsx("code",{children:'"prefer-main"'}),n("settings.merge.valuesFromOlderSettingsAreMigratedAutomatically"," values from older settings are migrated automatically.")]})]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeStrategyOverlapBehavior",children:n("settings.merge.smartPreferMainOverlapGuard","Smart Prefer Main Overlap Guard")}),e.jsxs("select",{id:"mergeStrategyOverlapBehavior",value:t.mergeStrategyOverlapBehavior??"flip-to-prefer-branch",onChange:v=>s(M=>({...M,mergeStrategyOverlapBehavior:v.target.value})),children:[e.jsx("option",{value:"flip-to-prefer-branch",children:n("settings.merge.flipOverlappingFilesToPreferTheTaskBranch","Flip overlapping files to prefer the task branch (default)")}),e.jsx("option",{value:"warn-only",children:n("settings.merge.warnOnlyKeepLegacyMainWinsFallback","Warn only — keep legacy main-wins fallback")}),e.jsx("option",{value:"ignore",children:n("settings.merge.ignoreOverlapDetectionPreserveLegacyBehavior","Ignore overlap detection — preserve legacy behavior")})]}),e.jsx("small",{children:n("settings.merge.whenUsingSmartPreferMainAutomaticallyPreferThe"," When using smart-prefer-main, automatically prefer the branch side for files that main has recently modified to avoid silently discarding branch work. ")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"postMergeAuditMode",children:n("settings.merge.postMergeAuditMode","Post-merge audit mode")}),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:n("settings.merge.blockStrict","Block (strict)")}),e.jsx("option",{value:"warn",children:n("settings.merge.warnDefaultLogFindingsContinue","Warn (default; log findings, continue)")}),e.jsx("option",{value:"off",children:n("settings.merge.offSkipAudit","Off (skip audit)")})]}),e.jsxs("small",{children:[n("settings.merge.controlsThePostMergeAuditGate"," Controls the post-merge audit gate. "),e.jsx("strong",{children:n("settings.merge.warn","Warn")}),n("settings.merge.defaultLogsFindingsButAutoCompletesTheMerge"," (default) logs findings but auto-completes the merge. "),e.jsx("strong",{children:n("settings.merge.block","Block")}),n("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:n("settings.merge.off","Off")}),n("settings.merge.skipsTheAuditEntirelySwitchingToOffIs"," skips the audit entirely. Switching to Off is recommended only if you trust your branches don't silently drop edits. ")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"pushAfterMerge",className:"checkbox-label",children:[e.jsx("input",{id:"pushAfterMerge",type:"checkbox",checked:t.pushAfterMerge===!0,onChange:v=>s(M=>({...M,pushAfterMerge:v.target.checked}))}),n("settings.merge.pushToRemoteAfterMerge"," Push to remote after merge ")]}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("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.")})]})]}),t.pushAfterMerge&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pushRemote",children:n("settings.merge.pushRemote","Push Remote")}),e.jsx("input",{id:"pushRemote",type:"text",placeholder:n("settings.merge.origin","origin"),value:t.pushRemote||"",onChange:v=>s(M=>({...M,pushRemote:v.target.value||void 0}))}),e.jsxs("details",{className:"settings-option-details",children:[e.jsx("summary",{children:n("settings.merge.moreDetails","More details")}),e.jsx("small",{children:n("settings.merge.gitRemoteToPushToEGOrigin",'Git remote to push to (e.g. "origin"). Can include branch name (e.g. "origin main"). Default: "origin".')})]})]})]})}function Ya(a){return Array.from(new Set(a.split(/[\n,]+/).map(t=>t.trim()).filter(t=>t.length>0)))}function yc({value:a,onChange:t,disabled:s=!1}){const{t:u}=q("app"),r=a?.approvalMode??"trusted-only",m=a?.alwaysApproveDelete??!0,o={always:{label:u("agentProvisioning.always","Always require approval"),description:u("agentProvisioning.alwaysDesc","All fn_agent_create/fn_agent_delete requests require approval unless caller is trusted.")},"trusted-only":{label:u("agentProvisioning.trustedOnly","Trusted-only"),description:u("agentProvisioning.trustedOnlyDesc","Trusted roles/agent IDs bypass approval; other callers require approval.")},never:{label:u("agentProvisioning.never","Never require approval"),description:u("agentProvisioning.neverDesc","Allow provisioning without approval for non-privileged callers.")}},n=d=>{t({...a??{},...d})};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:u("agentProvisioning.approvalMode","Approval mode")}),e.jsx("select",{id:"agent-provisioning-approval-mode",className:"select",value:r,onChange:d=>n({approvalMode:d.target.value}),disabled:s,children:ri.map(d=>e.jsx("option",{value:d,children:o[d].label},d))}),e.jsx("small",{className:"agent-provisioning-policy-help",children:o[r].description})]}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{className:"checkbox-label",htmlFor:"agent-provisioning-always-approve-delete",children:[e.jsx("input",{id:"agent-provisioning-always-approve-delete",type:"checkbox",checked:m,onChange:d=>n({alwaysApproveDelete:d.target.checked}),disabled:s}),u("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:u("agentProvisioning.trustedRoles","Trusted roles")}),e.jsx("textarea",{id:"agent-provisioning-trusted-roles",className:"input agent-provisioning-policy-textarea",value:(a?.trustedRoles??[]).join(", "),onChange:d=>n({trustedRoles:Ya(d.target.value)}),disabled:s,placeholder:u("agentProvisioning.trustedRolesPlaceholder","reviewer, ceo"),rows:2})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-provisioning-trusted-agent-ids",children:u("agentProvisioning.trustedAgentIds","Trusted agent IDs")}),e.jsx("textarea",{id:"agent-provisioning-trusted-agent-ids",className:"input agent-provisioning-policy-textarea",value:(a?.trustedAgentIds??[]).join(", "),onChange:d=>n({trustedAgentIds:Ya(d.target.value)}),disabled:s,placeholder:u("agentProvisioning.trustedAgentIdsPlaceholder","agent-abc123"),rows:2})]}),e.jsx("p",{className:"agent-provisioning-policy-help",children:e.jsx(As,{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 ys(a){return li.reduce((t,s)=>(t[s]=a?.[s]??"allow",t),{})}function jc({scopeBanner:a,form:t,setForm:s}){const{t:u}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:u("settings.agentPermissions.agentPermissions","Agent Permissions")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:u("settings.agentPermissions.perAgentSettingsOverrideProjectDefaultsEachCategory","Per-agent settings override project defaults. Each category controls a separate approval gate.")})}),e.jsx(no,{mode:"project-default",value:t.defaultAgentPermissionPolicy?{presetId:"custom",rules:ys(t.defaultAgentPermissionPolicy.rules)}:{presetId:"custom",rules:ys()},onChange:r=>s(m=>({...m,defaultAgentPermissionPolicy:{rules:ys(r?.rules)}}))}),e.jsx("h4",{className:"settings-section-heading",children:u("settings.agentPermissions.agentProvisioningApprovals","Agent Provisioning Approvals")}),e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:u("settings.agentPermissions.configureProjectLevelApprovalBehaviorForDurableProvisioning"," Configure project-level approval behavior for durable provisioning tools (fn_agent_create/fn_agent_delete). ")})}),e.jsx(yc,{value:t.agentProvisioning,onChange:r=>s(m=>({...m,agentProvisioning:r}))})]})}const kc=72;function wc(a,t){if(a.length<=t)return a;const s=Math.max(1,t-1),u=Math.ceil(s/2),r=Math.floor(s/2);return`${a.slice(0,u)}…${a.slice(a.length-r)}`}function Nc(a){const t=`${a.label} — ${a.path}`;return wc(t,kc)}function Cc({scopeBanner:a,form:t,setForm:s,memory:u}){const{t:r}=q("app"),{memoryCapabilities:m,memoryBackendStatus:o,memoryBackendLoading:n,memoryBackendError:d,memoryFiles:w,selectedMemoryPath:b,setSelectedMemoryPath:c,memoryContent:h,setMemoryContent:P,memoryLoading:g,memoryDirty:x,setMemoryDirty:f,memoryTestQuery:j,setMemoryTestQuery:k,memoryTestLoading:R,memoryTestResult:v,qmdInstallLoading:M,dreamRunning:V,memoryCompactLoading:N,onInstallQmd:Z,onTestMemoryRetrieval:O,onDreamNow:K,onCompactMemory:$,onSaveMemory:ee}=u,Q=t.memoryEnabled!==!1,B=!n&&o!==null,L=B?m?.writable??!0:!0,S=Q&&L,F=w.find(G=>G.path===b),te={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.memory.memory","Memory")}),e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"settings-muted",children:[r("settings.memory.memoryLivesIn"," Memory lives in "),e.jsx("code",{children:".fusion/memory/"}),r("settings.memory.agentsSearchWithQmdFirstFallBackTo",". Agents search with qmd first, fall back to local files when qmd is missing, and open exact line windows only when needed. ")]})}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryEnabled",type:"checkbox",checked:t.memoryEnabled!==!1,onChange:G=>s(J=>({...J,memoryEnabled:G.target.checked}))}),r("settings.memory.enableMemoryTools"," Enable memory tools ")]}),e.jsx("small",{children:r("settings.memory.agentsGetMemorySearchMemoryGetAndMemory","Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback.")})]}),n?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:r("settings.memory.checkingMemoryWriteAccess","Checking memory write access...")})}):d?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[r("settings.memory.failedToLoadBackendStatus","Failed to load backend status: "),d]})}):null,B&&o.qmdAvailable===!1&&e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:[r("settings.memory.qmdIsNotInstalledSearchWillUseLocal"," qmd is not installed. Search will use local files. Install indexed retrieval: "),e.jsx("code",{children:o.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Z,disabled:M,children:M?r("settings.memory.installing","Installing…"):r("settings.memory.installQmd","Install qmd")})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryAutoSummarizeEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryAutoSummarizeEnabled",type:"checkbox",checked:t.memoryAutoSummarizeEnabled||!1,onChange:G=>s(J=>({...J,memoryAutoSummarizeEnabled:G.target.checked}))}),r("settings.memory.autoSummarizeMemory"," Auto-Summarize Memory ")]}),e.jsx("small",{children:r("settings.memory.automaticallyCompactMemoryWhenItExceedsTheThreshold","Automatically compact memory when it exceeds the threshold on a schedule")})]}),(t.memoryAutoSummarizeEnabled||!1)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeThresholdChars",children:r("settings.memory.compactionThresholdChars","Compaction Threshold (chars)")}),e.jsx("input",{id:"memoryAutoSummarizeThresholdChars",type:"number",className:"input",value:t.memoryAutoSummarizeThresholdChars??5e4,onChange:G=>s(J=>({...J,memoryAutoSummarizeThresholdChars:parseInt(G.target.value,10)||5e4})),min:1e3}),e.jsx("small",{children:r("settings.memory.memoryWillBeCompactedWhenItExceedsThis","Memory will be compacted when it exceeds this character count")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeSchedule",children:r("settings.memory.scheduleCron","Schedule (cron)")}),e.jsx("input",{id:"memoryAutoSummarizeSchedule",type:"text",className:"input",value:t.memoryAutoSummarizeSchedule??"0 3 * * *",onChange:G=>s(J=>({...J,memoryAutoSummarizeSchedule:G.target.value})),placeholder:r("settings.memory.03","0 3 * * *")}),e.jsx("small",{children:r("settings.memory.cronExpressionForAutoSummarizeScheduleDefaultDaily","Cron expression for auto-summarize schedule (default: daily at 3 AM)")})]})]}),e.jsx("div",{style:{borderTop:"1px solid var(--border)",margin:"var(--space-lg) 0"}}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryDreamsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryDreamsEnabled",type:"checkbox",checked:t.memoryDreamsEnabled===!0,onChange:G=>s(J=>({...J,memoryDreamsEnabled:G.target.checked})),disabled:!Q}),r("settings.memory.processDreamsFromDailyMemory"," Process dreams from daily memory ")]}),e.jsx("small",{children:r("settings.memory.turnsDailyNotesIntoDREAMSMdAndPromotes","Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md.")})]}),Q&&t.memoryDreamsEnabled===!0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryDreamsSchedule",children:r("settings.memory.dreamSchedule","Dream Schedule")}),e.jsx("input",{id:"memoryDreamsSchedule",type:"text",value:t.memoryDreamsSchedule??"0 4 * * *",onChange:G=>s(J=>({...J,memoryDreamsSchedule:G.target.value}))}),e.jsx("small",{children:r("settings.memory.cronExpressionForDreamProcessing","Cron expression for dream processing.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:K,disabled:V||t.memoryDreamsEnabled!==!0,children:V?e.jsxs(e.Fragment,{children:[e.jsx(Le,{size:14,className:"animate-spin"}),r("settings.memory.dreaming"," Dreaming… ")]}):r("settings.memory.dreamNow","Dream Now")}),e.jsx("small",{children:r("settings.memory.manuallyTriggerDreamProcessingNow","Manually trigger dream processing now.")})]})]}),e.jsxs("div",{className:"memory-retrieval-test",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryRetrievalQuery",children:r("settings.memory.testRetrieval","Test Retrieval")}),e.jsx("input",{id:"memoryRetrievalQuery",type:"text",value:j,onChange:G=>k(G.target.value),placeholder:r("settings.memory.searchMemoryWithQmd","Search memory with qmd")}),e.jsx("small",{children:r("settings.memory.runsTheSameQmdBackedMemorySearchPath","Runs the same qmd-backed memory_search path agents use.")})]}),e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:O,disabled:R,children:R?r("settings.memory.testing","Testing…"):r("settings.memory.testRetrieval","Test Retrieval")})}),v&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[v.results.length,r("settings.memory.result"," result"),v.results.length===1?"":"s"," ",r("settings.memory.for",'for "'),v.query,'"']}),e.jsxs("small",{children:[r("settings.memory.qmd"," qmd "),v.qmdAvailable?"available":"missing"," · ",v.usedFallback?"local fallback used":"qmd path used"]}),v.results.length>0?e.jsx("ul",{children:v.results.map((G,J)=>e.jsxs("li",{children:[e.jsxs("span",{children:[G.path,":",G.lineStart]}),e.jsx("p",{children:G.snippet})]},`${G.path}-${G.lineStart}-${J}`))}):e.jsx("small",{children:r("settings.memory.noMatchingMemoryFound","No matching memory found.")})]})]}),!Q&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:r("settings.memory.memoryIsCurrentlyDisabledYouCanViewThe"," Memory is currently disabled. You can view the file, but editing is read-only until memory is re-enabled. ")}),Q&&B&&!L&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:r("settings.memory.memoryIsConfiguredWithAReadOnlyBackend"," Memory is configured with a read-only backend. You can view the file, but saving is disabled. ")}),g?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:r("settings.memory.loadingMemory","Loading memory…")})}):e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryFilePath",children:r("settings.memory.memoryFile","Memory File")}),e.jsx("select",{id:"memoryFilePath",value:b,onChange:G=>{c(G.target.value),f(!1)},disabled:x,children:w.map(G=>e.jsx("option",{value:G.path,title:`${G.label} — ${G.path}`,children:Nc(G)},G.path))}),e.jsx("small",{children:x?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit. Dreams is selected by default."})]}),F&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:te[F.layer]}),e.jsx("strong",{children:F.path}),e.jsxs("small",{children:[F.size.toLocaleString(),r("settings.memory.bytesUpdated"," bytes · updated "),new Date(F.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group memory-editor-form-group",children:[e.jsx("label",{children:F?.label||"Memory Editor"}),e.jsxs("small",{children:[F?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",F?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",F?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!F&&"Edits the selected memory file."]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(ii,{content:h,onChange:G=>{P(G),f(!0)},readOnly:!S,filePath:b})})]})]}),!g&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:$,disabled:!S||x||N,children:N?r("settings.memory.compacting","Compacting…"):r("settings.memory.compactSelectedFile","Compact Selected File")}),e.jsx("small",{children:x?"Save or discard edits before compacting this file.":`Compacts ${b} and writes the result back to the same file.`})]}),x&&S&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:ee,children:r("settings.memory.saveMemory","Save Memory")})}),x&&!S&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:[r("settings.memory.cannotSave","Cannot save: "),Q?"Backend is read-only":"Memory is disabled"]})})]})}function Sc({scopeBanner:a,form:t,setForm:s,researchLimitError:u}){const{t:r}=q("app"),m=t.researchSettings?.limits,o=t.researchSettings?.enabledSources;return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:r("settings.researchProject.projectResearchSettings","Project Research Settings")}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{htmlFor:"research-project-enabled",className:"checkbox-label",children:[e.jsx("input",{id:"research-project-enabled",type:"checkbox",checked:t.researchSettings?.enabled??!0,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},enabled:n.target.checked}}))}),r("settings.researchProject.enableResearchInThisProject"," Enable research in this project ")]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:r("settings.researchProject.enabledSources","Enabled Sources")}),e.jsxs("label",{htmlFor:"research-project-source-webSearch",className:"checkbox-label settings-research-source-locked",children:[e.jsx("input",{id:"research-project-source-webSearch",type:"checkbox",checked:!0,disabled:!0,readOnly:!0}),r("settings.researchProject.webSearch"," Web Search "),e.jsx("span",{className:"settings-muted",children:r("settings.researchProject.alwaysOn","Always on")})]}),e.jsx("small",{className:"settings-muted",children:r("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",r("settings.researchProject.pageFetch","Page Fetch")],["github",r("settings.researchProject.github","GitHub")],["localDocs",r("settings.researchProject.localDocs","Local Docs")],["llmSynthesis",r("settings.researchProject.llmSynthesis","LLM Synthesis")]].map(([n,d])=>e.jsxs("label",{htmlFor:`research-project-source-${n}`,className:"checkbox-label",children:[e.jsx("input",{id:`research-project-source-${n}`,type:"checkbox",checked:o?.[n]??!1,onChange:w=>s(b=>({...b,researchSettings:{...b.researchSettings??{},enabledSources:{...b.researchSettings?.enabledSources??{},[n]:w.target.checked}}}))}),d]},n))})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"settings-research-limits-grid",children:[e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-concurrent",children:r("settings.researchProject.maxConcurrentRuns","Max Concurrent Runs")}),e.jsx("input",{id:"research-project-max-concurrent",className:"input",type:"number",min:1,value:m?.maxConcurrentRuns??3,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},maxConcurrentRuns:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-sources",children:r("settings.researchProject.maxSourcesPerRun","Max Sources Per Run")}),e.jsx("input",{id:"research-project-max-sources",className:"input",type:"number",min:1,value:m?.maxSourcesPerRun??20,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},maxSourcesPerRun:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-max-duration",children:r("settings.researchProject.maxDurationMs","Max Duration (ms)")}),e.jsx("input",{id:"research-project-max-duration",className:"input",type:"number",min:1e3,value:m?.maxDurationMs??3e5,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},maxDurationMs:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),e.jsxs("div",{className:"settings-research-limit-field",children:[e.jsx("label",{htmlFor:"research-project-request-timeout",children:r("settings.researchProject.requestTimeoutMs","Request Timeout (ms)")}),e.jsx("input",{id:"research-project-request-timeout",className:"input",type:"number",min:1e3,value:m?.requestTimeoutMs??3e4,onChange:n=>s(d=>({...d,researchSettings:{...d.researchSettings??{},limits:{...d.researchSettings?.limits??{},requestTimeoutMs:n.target.value===""?void 0:Number(n.target.value)}}}))})]}),u&&e.jsx("small",{className:"field-error settings-research-limits-error",children:u})]})})]})}function Pc({scopeBanner:a,form:t,setForm:s,backupInfo:u,backupLoading:r,onBackupNow:m}){const{t:o}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:o("settings.backups.databaseBackups","Database Backups")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoBackupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoBackupEnabled",type:"checkbox",checked:t.autoBackupEnabled||!1,onChange:n=>s(d=>({...d,autoBackupEnabled:n.target.checked}))}),o("settings.backups.enableAutomaticDatabaseBackups"," Enable automatic database backups ")]}),e.jsx("small",{children:o("settings.backups.whenEnabledTheDatabaseIsBackedUpAutomatically","When enabled, the database is backed up automatically on a schedule")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupSchedule",children:o("settings.backups.backupScheduleCron","Backup Schedule (Cron)")}),e.jsx("input",{id:"autoBackupSchedule",type:"text",placeholder:o("settings.backups.02","0 2 * * *"),value:t.autoBackupSchedule||"0 2 * * *",onChange:n=>s(d=>({...d,autoBackupSchedule:n.target.value})),disabled:!t.autoBackupEnabled}),e.jsx("small",{children:o("settings.backups.cronExpressionForBackupTimingDefault02"," Cron expression for backup timing. Default: 0 2 * * * (daily at 2 AM). Examples: 0 * * * * (hourly), 0 0 * * 0 (weekly), */15 * * * * (every 15 min) ")}),t.autoBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.autoBackupSchedule)&&e.jsx("small",{className:"field-error",children:o("settings.backups.invalidCronExpressionFormat","Invalid cron expression format")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupRetention",children:o("settings.backups.retentionCount","Retention Count")}),e.jsx("input",{id:"autoBackupRetention",type:"number",min:1,max:100,value:t.autoBackupRetention??"",onChange:n=>{const d=n.target.value;s(w=>({...w,autoBackupRetention:d===""?void 0:Number(d)}))},disabled:!t.autoBackupEnabled}),e.jsx("small",{children:o("settings.backups.numberOfBackupFilesToKeepOldestAre","Number of backup files to keep (oldest are deleted first). Range: 1-100.")}),t.autoBackupRetention!==void 0&&(t.autoBackupRetention<1||t.autoBackupRetention>100)&&e.jsx("small",{className:"field-error",children:o("settings.backups.mustBeBetween1And100","Must be between 1 and 100")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupDir",children:o("settings.backups.backupDirectory","Backup Directory")}),e.jsx("input",{id:"autoBackupDir",type:"text",placeholder:o("settings.backups.fusionBackups",".fusion/backups"),value:t.autoBackupDir||".fusion/backups",onChange:n=>s(d=>({...d,autoBackupDir:n.target.value})),disabled:!t.autoBackupEnabled}),e.jsx("small",{children:o("settings.backups.directoryForBackupFilesRelativeToProjectRoot","Directory for backup files, relative to project root")}),t.autoBackupDir&&t.autoBackupDir.includes("..")&&e.jsx("small",{className:"field-error",children:o("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)")})]}),e.jsx("h4",{className:"settings-section-heading",children:o("settings.backups.memoryBackups","Memory Backups")}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryBackupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryBackupEnabled",type:"checkbox",checked:t.memoryBackupEnabled||!1,onChange:n=>s(d=>({...d,memoryBackupEnabled:n.target.checked}))}),o("settings.backups.enableAutomaticMemoryBackups"," Enable automatic memory backups ")]}),e.jsx("small",{children:o("settings.backups.whenEnabledProjectAndAgentMemoryFilesAre","When enabled, project and agent memory files are backed up automatically on a schedule.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupSchedule",children:o("settings.backups.memoryBackupScheduleCron","Memory Backup Schedule (Cron)")}),e.jsx("input",{id:"memoryBackupSchedule",type:"text",placeholder:o("settings.backups.03","0 3 * * *"),value:t.memoryBackupSchedule||"0 3 * * *",onChange:n=>s(d=>({...d,memoryBackupSchedule:n.target.value})),disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:o("settings.backups.cronExpressionForMemoryBackupTimingDefault0","Cron expression for memory backup timing. Default: 0 3 * * * (daily at 3 AM).")}),t.memoryBackupSchedule&&!/^[\s\d*,/-]+$/.test(t.memoryBackupSchedule)&&e.jsx("small",{className:"field-error",children:o("settings.backups.invalidCronExpressionFormat","Invalid cron expression format")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupRetention",children:o("settings.backups.memoryRetentionCount","Memory Retention Count")}),e.jsx("input",{id:"memoryBackupRetention",type:"number",min:1,max:100,value:t.memoryBackupRetention??"",onChange:n=>{const d=n.target.value;s(w=>({...w,memoryBackupRetention:d===""?void 0:Number(d)}))},disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:o("settings.backups.numberOfMemoryBackupsToKeepOldestAre","Number of memory backups to keep (oldest are deleted first). Range: 1-100.")}),t.memoryBackupRetention!==void 0&&(t.memoryBackupRetention<1||t.memoryBackupRetention>100)&&e.jsx("small",{className:"field-error",children:o("settings.backups.mustBeBetween1And100","Must be between 1 and 100")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupDir",children:o("settings.backups.memoryBackupDirectory","Memory Backup Directory")}),e.jsx("input",{id:"memoryBackupDir",type:"text",placeholder:o("settings.backups.fusionBackupsMemory",".fusion/backups/memory"),value:t.memoryBackupDir||".fusion/backups/memory",onChange:n=>s(d=>({...d,memoryBackupDir:n.target.value})),disabled:!t.memoryBackupEnabled}),e.jsx("small",{children:o("settings.backups.directoryForMemoryBackupsRelativeToProjectRoot","Directory for memory backups, relative to project root.")}),t.memoryBackupDir&&t.memoryBackupDir.includes("..")&&e.jsx("small",{className:"field-error",children:o("settings.backups.pathCannotContainParentDirectoryTraversal","Path cannot contain parent directory traversal (..)")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryBackupScope",children:o("settings.backups.memoryBackupScope","Memory Backup Scope")}),e.jsxs("select",{id:"memoryBackupScope",value:t.memoryBackupScope||"all",onChange:n=>s(d=>({...d,memoryBackupScope:n.target.value})),disabled:!t.memoryBackupEnabled,children:[e.jsx("option",{value:"all",children:o("settings.backups.allProjectAgents","All (project + agents)")}),e.jsx("option",{value:"project",children:o("settings.backups.projectOnlyFusionMemory","Project only (.fusion/memory)")}),e.jsx("option",{value:"agents",children:o("settings.backups.agentsOnlyFusionAgentMemory","Agents only (.fusion/agent-memory)")})]})]}),r?e.jsx("div",{className:"settings-empty-state",children:e.jsx(De,{label:o("settings.backups.loadingBackupInfo","Loading backup info…")})}):u?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:o("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:u.count}),e.jsx("span",{className:"backup-stat-label",children:o("settings.backups.backups","backups")})]}),e.jsxs("div",{className:"backup-stat",children:[e.jsx("span",{className:"backup-stat-value",children:u.totalSize>1024*1024?`${(u.totalSize/(1024*1024)).toFixed(1)} MB`:`${(u.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:o("settings.backups.totalSize","total size")})]})]}),u.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:[o("settings.backups.view","View "),u.backups.length,o("settings.backups.backupS"," backup(s)")]}),e.jsxs("ul",{children:[u.backups.slice(0,10).map(n=>e.jsxs("li",{children:[e.jsx("code",{children:n.filename}),e.jsx("span",{className:"backup-size",children:n.size>1024*1024?`${(n.size/(1024*1024)).toFixed(1)} MB`:`${(n.size/1024).toFixed(1)} KB`})]},n.filename)),u.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:[o("settings.backups.and","...and "),u.backups.length-10,o("settings.backups.more"," more")]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:m,disabled:r,children:r?o("settings.backups.creating","Creating…"):o("settings.backups.backupNow","Backup Now")})})]})}const Ac=i.lazy(()=>cn(()=>import("./PluginManager-CzCM3XUY.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(a=>({default:a.PluginManager}))),Mc=i.lazy(()=>cn(()=>import("./PiExtensionsManager-BEj5xu45.js"),__vite__mapDeps([14,1,2,3,4,5,6,7,8,9,15,16,17])).then(a=>({default:a.PiExtensionsManager})));function Tc({scopeBanner:a,projectId:t,addToast:s,activePluginsSubsection:u,setActivePluginsSubsection:r}){const{t:m}=q("app");return e.jsxs(e.Fragment,{children:[a,e.jsx("h4",{className:"settings-section-heading",children:m("settings.plugins.plugins","Plugins")}),e.jsxs("div",{className:"settings-plugins-subsection-toggle",role:"tablist","aria-label":m("settings.plugins.pluginManagerType","Plugin manager type"),children:[e.jsx("button",{type:"button",id:"plugins-tab-fusion-plugins",role:"tab","aria-controls":"plugins-panel-fusion-plugins","aria-selected":u==="fusion-plugins",tabIndex:u==="fusion-plugins"?0:-1,className:`settings-plugins-subsection-btn${u==="fusion-plugins"?" active":""}`,onClick:()=>r("fusion-plugins"),children:m("settings.plugins.fusionPlugins"," Fusion Plugins ")}),e.jsx("button",{type:"button",id:"plugins-tab-pi-extensions",role:"tab","aria-controls":"plugins-panel-pi-extensions","aria-selected":u==="pi-extensions",tabIndex:u==="pi-extensions"?0:-1,className:`settings-plugins-subsection-btn${u==="pi-extensions"?" active":""}`,onClick:()=>r("pi-extensions"),children:m("settings.plugins.piExtensions"," Pi Extensions ")})]}),e.jsx("div",{id:"plugins-panel-fusion-plugins",role:"tabpanel","aria-labelledby":"plugins-tab-fusion-plugins",className:"settings-plugins-subsection-panel",hidden:u!=="fusion-plugins",children:u==="fusion-plugins"&&e.jsxs(e.Fragment,{children:[e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ac,{addToast:s,projectId:t})}),e.jsx(Ps,{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:u!=="pi-extensions",children:u==="pi-extensions"&&e.jsx(i.Suspense,{fallback:null,children:e.jsx(Mc,{addToast:s,projectId:t})})})]})}function js(a,t){if(!t)return a;const s=a.includes("?")?"&":"?";return`${a}${s}projectId=${encodeURIComponent(t)}`}async function Qa(a,t){const s=await fetch(a,{credentials:"same-origin",...t,headers:{"Content-Type":"application/json",...t?.headers??{}}}),u=await s.json();if(!s.ok)throw new Error(u.error??`Request failed (${s.status})`);return u}function Rc(a){const[t,s]=i.useState({status:"missing"}),[u,r]=i.useState(!1),m=i.useCallback(async()=>{try{const n=await Qa(js("/api/worktrunk/status",a));s(n)}catch(n){s({status:"failed",error:n instanceof Error?n.message:"Failed to load worktrunk status"})}},[a]);i.useEffect(()=>{m()},[m]),i.useEffect(()=>oi(js("/api/events",a),{events:{"approval:updated":()=>{t.pendingApprovalId&&m()},"approval:decided":()=>{t.pendingApprovalId&&m()}}}),[a,m,t.pendingApprovalId]);const o=i.useCallback(async()=>{r(!0),s(n=>({...n,status:"installing",error:void 0}));try{const n=await Qa(js("/api/worktrunk/install-request",a),{method:"POST",body:JSON.stringify({})});s({status:n.status,version:n.version,installPath:n.installPath,pendingApprovalId:n.pendingApprovalId??n.approvalRequestId,error:n.error})}catch(n){s({status:"failed",error:n instanceof Error?n.message:"Failed to request install"})}finally{r(!1)}},[a]);return{...t,requestInstall:o,requesting:u}}const ks="fusion_github_star_count",Xa=3600*1e3,Ja="fusion:github-star-clicked";function Ic({size:a=13}){return e.jsx("svg",{"data-testid":"discord-icon",width:a,height:a,viewBox:"0 0 24 24",role:"img","aria-hidden":"true",fill:"currentColor",children:e.jsx("path",{d:"M20.317 4.369A19.791 19.791 0 0 0 15.885 3a13.66 13.66 0 0 0-.696 1.412 18.27 18.27 0 0 0-6.378 0A13.627 13.627 0 0 0 8.115 3a19.736 19.736 0 0 0-4.432 1.369C.878 8.604.111 12.734.494 16.803a19.916 19.916 0 0 0 5.993 3.048 14.43 14.43 0 0 0 1.286-2.106 12.94 12.94 0 0 1-2.024-.977c.17-.122.337-.249.499-.381 3.908 1.838 8.149 1.838 12.01 0 .163.132.329.259.5.381a12.936 12.936 0 0 1-2.028.978 14.344 14.344 0 0 0 1.287 2.105 19.85 19.85 0 0 0 5.996-3.049c.449-4.713-.766-8.806-3.696-12.433zM8.02 14.335c-1.184 0-2.157-1.085-2.157-2.419 0-1.334.95-2.418 2.157-2.418 1.217 0 2.167 1.095 2.157 2.418 0 1.334-.95 2.419-2.157 2.419zm7.975 0c-1.184 0-2.157-1.085-2.157-2.419 0-1.334.95-2.418 2.157-2.418 1.217 0 2.167 1.095 2.157 2.418 0 1.334-.94 2.419-2.157 2.419z"})})}function Ec(a){const t=new Map;for(const s of a){const u=`${s.owner}/${s.repo}`;t.has(u)||t.set(u,{value:u,label:u})}return[...t.values()].sort((s,u)=>s.value.localeCompare(u.value))}function Fc(){const[a,t]=i.useState(()=>{try{return localStorage.getItem(Ja)==="true"}catch{return!1}}),s=i.useCallback(()=>{t(!0);try{localStorage.setItem(Ja,"true")}catch{}},[]);return[a,s]}function Lc(){const[a,t]=i.useState(()=>{try{const s=localStorage.getItem(ks);if(s){const u=JSON.parse(s);if(Date.now()-u.fetchedAt<Xa)return u.count}}catch{}return null});return i.useEffect(()=>{try{const s=localStorage.getItem(ks);if(s){const u=JSON.parse(s);if(Date.now()-u.fetchedAt<Xa)return}}catch{}fetch("https://api.github.com/repos/Runfusion/Fusion").then(s=>{if(s.ok)return s.json()}).then(s=>{if(s&&typeof s.stargazers_count=="number"){const u={count:s.stargazers_count,fetchedAt:Date.now()};try{localStorage.setItem(ks,JSON.stringify(u))}catch{}t(s.stargazers_count)}}).catch(()=>{})},[]),a}const Za="(max-width: 768px)",ws=".fusion/memory/DREAMS.md";function en(a){const t=Number(a?.maxAutoMergeRetries);return Number.isFinite(t)&&t>0?Math.floor(t):3}const tn=[{id:"__global_header",label:"Global",labelKey:"settings.nav.globalHeader",scope:void 0,isGroupHeader:!0},{id:"global-general",label:"General",labelKey:"settings.nav.globalGeneral",scope:"global"},{id:"authentication",label:"Authentication",labelKey:"settings.nav.authentication",scope:void 0,icon:nt},{id:"appearance",label:"Appearance",labelKey:"settings.nav.appearance",scope:"global"},{id:"notifications",label:"Notifications",labelKey:"settings.nav.notifications",scope:"global"},{id:"node-sync",label:"Node Sync",labelKey:"settings.nav.nodeSync",scope:"global"},{id:"global-models",label:"Models",labelKey:"settings.nav.globalModels",scope:"global"},{id:"cli-agents",label:"CLI Agents",labelKey:"settings.nav.cliAgents",scope:"global"},{id:"research-global",label:"Research Defaults",labelKey:"settings.nav.researchGlobal",scope:"global"},{id:"remote",label:"Remote Access & Node Sync",labelKey:"settings.nav.remote",scope:"global"},{id:"experimental",label:"Experimental Features",labelKey:"settings.nav.experimental",scope:"global"},{id:"__runtimes_header",label:"Runtimes",labelKey:"settings.nav.runtimesHeader",scope:void 0,isGroupHeader:!0},{id:"hermes-runtime",label:"Hermes",labelKey:"settings.nav.hermesRuntime",scope:"global"},{id:"openclaw-runtime",label:"OpenClaw",labelKey:"settings.nav.openclawRuntime",scope:"global"},{id:"paperclip-runtime",label:"Paperclip",labelKey:"settings.nav.paperclipRuntime",scope:"global"},{id:"__project_header",label:"Project",labelKey:"settings.nav.projectHeader",scope:void 0,isGroupHeader:!0},{id:"general",label:"Project General",labelKey:"settings.nav.projectGeneral",scope:"project"},{id:"commands",label:"Commands & Scripts",labelKey:"settings.nav.commands",scope:"project"},{id:"worktrees",label:"Worktrees",labelKey:"settings.nav.worktrees",scope:"project"},{id:"scheduling",label:"Scheduling & Capacity",labelKey:"settings.nav.scheduling",scope:"project"},{id:"scheduled-evals",label:"Scheduled Evals",labelKey:"settings.nav.scheduledEvals",scope:"project"},{id:"node-routing",label:"Node Routing",labelKey:"settings.nav.nodeRouting",scope:"project"},{id:"merge",label:"Merge",labelKey:"settings.nav.merge",scope:"project"},{id:"agent-permissions",label:"Agents & Permissions",labelKey:"settings.nav.agentPermissions",scope:"project"},{id:"memory",label:"Memory",labelKey:"settings.nav.memory",scope:"project"},{id:"backups",label:"Backups",labelKey:"settings.nav.backups",scope:"project"},{id:"research-project",label:"Research",labelKey:"settings.nav.researchProject",scope:"project"},{id:"project-models",label:"Project Models",labelKey:"settings.nav.projectModels",scope:"project"},{id:"secrets",label:"Secrets",labelKey:"settings.nav.secrets",scope:"project"},{id:"prompts",label:"Prompts",labelKey:"settings.nav.prompts",scope:"project"},{id:"plugins",label:"Plugins",labelKey:"settings.nav.plugins",scope:"project"}],Dc={insights:"Insights",memoryView:"Memory Editor",remoteAccess:"Remote Access",skillsView:"Skills View",nodesView:"Nodes View",devServerView:"Dev Server",todoView:"Todo List",researchView:"Research View",evalsView:"Evals View",goalsView:"Goals View",subtaskBreakdown:"Subtask Breakdown",leftSidebarNav:"Left Sidebar Navigation",sandbox:"Sandbox (command isolation)",chatRooms:"Chat Rooms",agentOnboarding:"Planning-style Agent Onboarding",workflowInterpreterDualObserve:"Workflow Graph Engine — dual-observe parity (diagnostic)"},Oc=new Set(["chatRooms","goalsView","insights","memoryView","roadmap","rightDock","skillsView","todoView","workflowColumns","workflowGraphExecutor","workflowInterpreterDualObserve"]),pn=new Set(["leftSidebarNav"]),Ct={devServer:"devServerView"};function Is(a){return Ct[a]??a}function wt(a,t){return a[t]===!0?!0:a[t]===!1?!1:Object.entries(Ct).some(([s,u])=>u===t&&a[s]===!0)?!0:pn.has(t)}function Bc(a,t){const s=Is(t);return pn.has(s)&&a[s]===void 0?!0:wt(a,s)}function Gc(a){if(!a)return{};const t={};for(const[s,u]of Object.entries(a))t[Is(s)]=u;for(const[s,u]of Object.entries(Ct))t[u]!==void 0&&!(s in t)&&(t[s]=null);return t}const Ns="global-general";function Wc({projectId:a,addToast:t}){const{t:s}=q("app"),{confirm:u}=dn(),[r,m]=i.useState([]),[o,n]=i.useState({}),[d,w]=i.useState({}),[b,c]=i.useState("");i.useEffect(()=>{let f=!1;return(async()=>{try{const[j,k]=await Promise.all([fetch("/api/cli-agents"),fetch("/api/cli-agents/settings")]),R=j.ok?await j.json():{adapters:[]},v=k.ok?await k.json():{cliAgents:{}};if(f)return;const M=R.adapters??[];m(M),n(v.cliAgents??{}),M.length>0&&c(V=>V||M[0].id)}catch{}})(),()=>{f=!0}},[]),i.useEffect(()=>{if(!b)return;let f=!1;return fetch(`/api/cli-agents/${b}/autonomy`).then(j=>j.ok?j.json():null).then(j=>{f||!j||w(k=>({...k,[b]:!!j.approved}))}).catch(()=>{}),()=>{f=!0}},[b]);const h=o[b]??{},P=i.useCallback(async(f,j)=>{try{const k=await fetch("/api/cli-agents/settings",{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({adapterId:f,config:j})});if(!k.ok)throw new Error(`HTTP ${k.status}`);const R=await k.json();n(R.cliAgents??{})}catch(k){t(ie(k)||s("settings.cliAgents.saveFailed"),"error")}},[t,s]),g=i.useCallback(f=>{if(!b)return;const j={...h,...f};n(k=>({...k,[b]:j})),P(b,j)},[b,h,P]),x=i.useCallback(async f=>{if(b){if(f==="elevated"){if(!await u({title:s("settings.cliAgents.elevatedConfirmTitle"),message:s("settings.cliAgents.elevatedConfirmBody"),confirmLabel:s("settings.cliAgents.elevatedConfirmAction"),danger:!0}))return;try{const k=await fetch(`/api/cli-agents/${b}/approve-autonomy`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:!0})});if(!k.ok)throw new Error(`HTTP ${k.status}`);w(R=>({...R,[b]:!0}))}catch(k){t(ie(k)||s("settings.cliAgents.approveFailed"),"error");return}}g({autonomyMode:f})}},[b,u,s,t,g]);return e.jsxs("div",{"data-testid":"cli-agents-settings",children:[e.jsx("h4",{className:"settings-section-heading",children:s("settings.cliAgents.heading")}),e.jsx("p",{className:"settings-section-description",children:s("settings.cliAgents.description")}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAdapter",children:s("settings.cliAgents.adapterLabel")}),e.jsx("select",{id:"cliAgentAdapter",value:b,onChange:f=>c(f.target.value),children:r.map(f=>e.jsxs("option",{value:f.id,children:[f.name," (",s(`settings.cliAgents.tier.${f.tier}`),")"]},f.id))})]}),b&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentCommand",children:s("settings.cliAgents.commandLabel")}),e.jsx("input",{id:"cliAgentCommand",type:"text",placeholder:r.find(f=>f.id===b)?.defaultCommand??"",value:h.commandOverride??"",onChange:f=>g({commandOverride:f.target.value||void 0})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.commandHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentExtraArgs",children:s("settings.cliAgents.extraArgsLabel")}),e.jsx("input",{id:"cliAgentExtraArgs",type:"text",value:(h.extraArgs??[]).join(" "),onChange:f=>g({extraArgs:f.target.value.split(/\s+/).filter(j=>j.length>0)})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.extraArgsHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentEnv",children:s("settings.cliAgents.envLabel")}),e.jsx("input",{id:"cliAgentEnv",type:"text",value:(h.envAdditions??[]).join(", "),onChange:f=>g({envAdditions:f.target.value.split(",").map(j=>j.trim()).filter(j=>j.length>0)})}),e.jsx("p",{className:"settings-field-help",children:s("settings.cliAgents.envHelp")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"cliAgentAutonomy",children:s("settings.cliAgents.autonomyLabel")}),e.jsxs("select",{id:"cliAgentAutonomy",value:h.autonomyMode??"default",onChange:f=>void x(f.target.value),children:[e.jsx("option",{value:"default",children:s("settings.cliAgents.autonomy.default")}),e.jsx("option",{value:"elevated",children:s("settings.cliAgents.autonomy.elevated")})]}),e.jsx("p",{className:"settings-field-help",children:d[b]?s("settings.cliAgents.approvedNote"):s("settings.cliAgents.autonomyHelp")})]})]})]})}function _c({onClose:a,addToast:t,projectId:s,initialSection:u,themeMode:r="dark",colorTheme:m="ocean",onThemeModeChange:o,onColorThemeChange:n,dashboardFontScalePct:d=100,shadcnCustomColors:w={},resolvedThemeMode:b,onDashboardFontScaleChange:c,onShadcnCustomColorsChange:h,onQuickChatButtonModeChange:P,onReopenOnboarding:g,onOpenApprovals:x,onOpenWorkflowSettings:f,presentation:j="modal"}){const{isEmbedded:k,scrollLockEnabled:R,resizePersistEnabled:v,escapeEnabled:M,overlayDismissEnabled:V}=Yi(j),{t:N}=q("app"),{confirm:Z}=dn(),O=Rc(s),K=O.status==="installed",$=ci();di(R);const{keyboardOverlap:ee,viewportHeight:Q,viewportOffsetTop:B,keyboardOpen:L}=ui({enabled:$==="mobile"}),S=L?{"--keyboard-overlap":`${ee}px`,"--vv-offset-top":`${B}px`,...Q!==null?{"--vv-height":`${Q}px`}:{}}:{},F=i.useRef(null),te=i.useRef(null),G=i.useRef(null),J=i.useCallback(l=>{G.current=l},[]);mi(F,v,"fusion:settings-modal-size");const me=hi(),[y,U]=i.useState({maxConcurrent:2,maxTriageConcurrent:2,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",maxAutoMergeRetries:3,mergeIntegrationWorktree:"reuse-task-worktree",mergeAdvanceAutoSync:"stash-and-ff",merger:{mode:"ai",maxReviewPasses:3,allowDirtyLocalCheckoutSync:!1},recycleWorktrees:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",worktreesDir:"",worktrunk:{enabled:!1,binaryPath:"",onFailure:"fail"},includeTaskIdInCommit:!0,worktreeInitCommand:"",ntfyEnabled:!1,ntfyTopic:void 0,ntfyAccessToken:void 0,failureNotificationMode:"sticky-only",failureNotificationDelayMs:3e4,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:void 0}),[ce,pe]=i.useState(!0),[fe,_]=i.useState(!1),[C,I]=i.useState(null),[z,ne]=i.useState(null),[le,Y]=i.useState(null),T=tn.find(l=>!l.isGroupHeader),[E,H]=i.useState(()=>u==="pi-extensions"?"plugins":u??Ns),[ae,ve]=i.useState(()=>u==="pi-extensions"?"pi-extensions":"fusion-plugins"),[St,bn]=i.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(Za)?.matches===!0:!1),[Oe,fn]=i.useState(null),[Es,Fs]=i.useState(!1),[ue,Ls]=i.useState(null),[Pt,Ds]=i.useState(!1),[lt,it]=i.useState(null),$e=Lc(),[vn,xn]=Fc(),[At,yn]=i.useState(null),[jn,Ke]=i.useState(null),[xe,Mt]=i.useState(null),[Os,Bs]=i.useState(!1),{entries:kn,currentPath:Ce,setPath:Tt,loading:wn,error:Nn,refresh:Cn}=Aa("project",xe!==null,s),{entries:Sn,currentPath:Pe,setPath:Rt,loading:Pn,error:An,refresh:Mn}=Aa("project",Os,s),{nodes:Tn}=gi(),It=y.experimentalFeatures??{},Et=wt(It,"remoteAccess"),Ft=wt(It,"researchView"),Lt=wt(It,"evalsView"),Re=tn.filter(l=>l.id==="remote"?Et:l.id==="research-global"||l.id==="research-project"?Ft:l.id==="scheduled-evals"?Lt:!0),ze=Re.some(l=>l.id===Ns)?Ns:Re.find(l=>!l.isGroupHeader)?.id??T?.id??"general",qe=Re.find(l=>l.id===E)?.scope;i.useEffect(()=>{if(E==="remote"&&!Et){H(ze);return}if((E==="research-global"||E==="research-project")&&!Ft){H(ze);return}if(E==="scheduled-evals"&&!Lt){H(ze);return}Re.some(l=>l.id===E)||H(ze)},[E,Et,Ft,Lt,ze,Re]);const[Be,Dt]=i.useState([]),[Rn,Gs]=i.useState(!1),[In,be]=i.useState(null),[En,Ot]=i.useState({}),[Fn,Ws]=i.useState({}),[Bt,_s]=i.useState({}),[Gt,Wt]=i.useState({}),[Ln,_t]=i.useState(null),[Ut,Ht]=i.useState({}),[Dn,ot]=i.useState({}),[On,Ve]=i.useState({}),he=i.useRef(null),Ye=i.useRef({}),[Us,Hs]=i.useState([]),[$s,Ks]=i.useState(!1),[Ge,$t]=i.useState([]),[We,Kt]=i.useState([]),[Bn,zs]=i.useState({}),[Gn,ct]=i.useState({}),[Qe,qs]=i.useState(null),[Se,Vs]=i.useState(null),[Wn,zt]=i.useState(null),[_n,dt]=i.useState(!1),[ye,ut]=i.useState(null),[qt,Vt]=i.useState(null),[Un,Ys]=i.useState(null),[Hn,Qs]=i.useState(!1),[$n,Yt]=i.useState(null),[Kn,zn]=i.useState("persistent"),[qn,Vn]=i.useState(null),[Yn,Qn]=i.useState(null),[Xn,Jn]=i.useState(null),[Zn,_e]=i.useState(null),[Qt,mt]=i.useState(""),[er,Xs]=i.useState(!1),[Xt,ht]=i.useState(!1),[tr,Js]=i.useState([]),[sr,Zs]=i.useState([]),[ar,nr]=i.useState(!1),[rr,ea]=i.useState([]),[lr,ta]=i.useState(!1),[ir,sa]=i.useState(null),[or,aa]=i.useState([]),[cr,na]=i.useState(!1),[dr,Jt]=i.useState(null),Zt=i.useRef(!1),[ur,ra]=i.useState([]),[je,es]=i.useState(ws),[ts,mr]=i.useState(""),[hr,la]=i.useState(!1),[gr,ia]=i.useState(null),[pr,oa]=i.useState(!1),[br,ca]=i.useState(!1),[fr,da]=i.useState(!1),ss=i.useRef(!1),[gt,ua]=i.useState(4),ma=i.useRef(4),ha=i.useRef(!1),as=i.useRef(!1),[vr,ga]=i.useState(!1),[xr,Xe]=i.useState(!1),[,ns]=i.useState(null),[ke,pa]=i.useState(null),[pt,bt]=i.useState(!1),[rs,yr]=i.useState("both"),[ls,jr]=i.useState(!0),ba=i.useRef(null),{status:kr,capabilities:wr,loading:Nr,error:Cr,refresh:fa}=lo({projectId:s,enabled:E==="memory"});i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia(Za);if(!l)return;const p=A=>{bn(A?A.matches:l.matches)};return p(),l.addEventListener("change",p),()=>l.removeEventListener("change",p)},[]),i.useEffect(()=>{Promise.all([Ma(s),pi(s)]).then(([l,p])=>{const A={...l,mergeIntegrationWorktree:Ra(l.mergeIntegrationWorktree),mergeAdvanceAutoSync:Ta(l.mergeAdvanceAutoSync),maxAutoMergeRetries:en(l)};U(A),I(A),ne(p),Y({...p,project:{...p.project,mergeIntegrationWorktree:p.project.mergeIntegrationWorktree===void 0?void 0:Ra(p.project.mergeIntegrationWorktree),mergeAdvanceAutoSync:p.project.mergeAdvanceAutoSync===void 0?void 0:Ta(p.project.mergeAdvanceAutoSync)}}),pe(!1)}).catch(l=>{t(ie(l),"error"),pe(!1)})},[t,s]),i.useEffect(()=>{if(E!=="scheduling"||ha.current)return;let l=!1;return bi().then(p=>{l||(as.current||ua(p.globalMaxConcurrent),ma.current=p.globalMaxConcurrent,ha.current=!0,ga(!0))}).catch(()=>{ga(!0)}),()=>{l=!0}},[E]),i.useEffect(()=>{let l=!1;return fi().then(p=>{l||typeof p.version=="string"&&p.version.trim().length>0&&fn(p.version)}).catch(()=>{}),()=>{l=!0}},[]);const Sr=i.useCallback(async()=>{Fs(!0),it(null);try{const l=await vi();Ls(l),l.error&&t(l.error,"error")}catch(l){const p=ie(l)||N("settings.general.updateCheckFailed","Failed to check for updates");Ls({currentVersion:Oe??"unknown",latestVersion:null,updateAvailable:!1,error:p}),t(p,"error")}finally{Fs(!1)}},[t,Oe,N]),va=i.useCallback(async()=>{Ds(!0),it(null);try{const l=await xi(s);if(it(l),l.error){t(l.error,"error");return}l.updated&&t(N("settings.general.updateSuccessToast","Update installed. Restart Fusion to apply it."),"success")}catch(l){const p=ie(l)||N("settings.general.updateFailed","Update failed");it({currentVersion:ue?.currentVersion??Oe??"unknown",latestVersion:ue?.latestVersion??null,updated:!1,error:p}),t(p,"error")}finally{Ds(!1)}},[t,Oe,s,N,ue]),Pr=i.useCallback(()=>{if(!ue)return null;if(ue.error)return ue.error;if(ue.updateAvailable&&ue.latestVersion){const l=lt?.updated===!0,p=lt?.error;return e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[N("settings.general.updateAvailablePrefix","v{{version}} available",{version:ue.latestVersion})," ·"," ",e.jsx("a",{href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",className:"settings-update-result-link",children:N("settings.general.learnMore","Learn more")})]}),l?e.jsx("span",{className:"settings-update-install-status settings-update-install-status--success","aria-live":"polite",children:N("settings.general.updateSuccess","Updated to v{{version}} — restart Fusion to apply",{version:lt.latestVersion??ue.latestVersion})}):e.jsx("button",{type:"button",className:"btn btn-sm settings-update-now-btn",onClick:()=>{va()},disabled:Pt,children:Pt?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{size:12,className:"spinning","aria-hidden":"true"}),N("settings.general.updating","Updating…")]}):N("settings.general.updateNow","Update now")}),p&&e.jsx("span",{className:"settings-update-install-status settings-update-install-status--error","aria-live":"polite",children:N("settings.general.updateFailedWithMessage","Update failed: {{message}}",{message:p})})]})}return N("settings.general.upToDate","You're up to date ✓")},[va,N,ue,Pt,lt]),de=i.useCallback(async()=>{try{const{providers:l}=await Ea(),p=Fa(l);Dt(p),Ot(A=>{const D={};for(const[W,X]of Object.entries(A)){const se=p.find(oe=>oe.id===W);se&&!se.authenticated&&(D[W]=X)}return Object.keys(D).length===Object.keys(A).length?A:D})}catch{}},[]);i.useEffect(()=>{(E==="global-models"||E==="project-models")&&(Ks(!0),yi().then(l=>{Hs(l.models),$t(l.favoriteProviders),Kt(l.favoriteModels)}).catch(()=>Hs([])).finally(()=>Ks(!1)))},[E]),i.useEffect(()=>{E==="backups"&&(dt(!0),La(s).then(l=>zt(l)).catch(()=>zt(null)).finally(()=>dt(!1)))},[E,s]);const ft=i.useCallback(async()=>{const[l,p]=await Promise.allSettled([ji(s),ms(s)]);l.status==="fulfilled"&&U(A=>({...A,...l.value.settings})),p.status==="fulfilled"&&(ut(p.value),Vt(p.value.externalTunnel??null))},[s]);i.useEffect(()=>{const l=ye?.state;(l==="running"||l==="starting")&&Vt(null)},[ye?.state]),i.useEffect(()=>{E==="remote"&&ft().catch(()=>{ut(null)})},[E,ft]),i.useEffect(()=>{if(E!=="remote")return;const l=ye?.state;if(l!=="starting"&&l!=="stopping")return;const p=setInterval(()=>{ms(s).then(A=>{ut(A),Vt(A.externalTunnel??null)}).catch(()=>{})},1e3);return()=>clearInterval(p)},[E,s,ye?.state]),i.useEffect(()=>{if(E!=="remote")return;if(ye?.state!=="running"){_e(null);return}let l=!1;return(async()=>{try{const p=await Ss("image/svg",{projectId:s,tokenType:"persistent"});if(l)return;_e({url:p.url,qrSvg:p.data??null})}catch{if(l)return;try{const p=await sn({projectId:s,tokenType:"persistent"});if(l)return;_e({url:p.url,qrSvg:null})}catch{l||_e(null)}}})(),()=>{l=!0}},[E,s,ye?.state,ye?.url]),i.useEffect(()=>{if(E!=="remote")return;const l=qt?.url;if(ye?.state!=="stopped"||!l)return;let p=!1;return(async()=>{try{const A=await Ss("image/svg",{projectId:s,tokenType:"persistent"});if(p)return;_e({url:l,qrSvg:A.data??null})}catch{p||_e({url:l,qrSvg:null})}})(),()=>{p=!0}},[E,qt?.url,s,ye?.state]),i.useEffect(()=>{E==="worktrees"&&ki(s).then(l=>Js(l)).catch(()=>Js([]))},[E,s]),i.useEffect(()=>{E==="merge"&&wi(s).then(l=>{const p=l.map(X=>X.name).filter(X=>typeof X=="string"&&X.length>0),A=new Set,D=["main","master","trunk","develop"],W=[];for(const X of D)p.includes(X)&&!A.has(X)&&(W.push(X),A.add(X));for(const X of[...p].sort((se,oe)=>se.localeCompare(oe)))A.has(X)||(A.add(X),W.push(X));Zs(W)}).catch(()=>Zs([]))},[E,s]),i.useEffect(()=>{if(E!=="general")return;let l=!1;return ta(!0),sa(null),Da(s).then(p=>{l||ea(Ec(p))}).catch(()=>{l||(ea([]),sa("Could not load detected remotes. Enter a custom owner/repo value."))}).finally(()=>{l||ta(!1)}),()=>{l=!0}},[E,s]),i.useEffect(()=>{if(E!=="global-general"||Zt.current)return;let l=!1;return na(!0),Jt(null),Ni().then(async p=>{const A=await Promise.allSettled(p.map(async se=>(await Da(se.id)).map(Ee=>({value:`${Ee.owner}/${Ee.repo}`,label:`${Ee.owner}/${Ee.repo}`,source:se.name}))));if(l)return;const D=new Map;let W=0;for(const se of A)if(se.status==="fulfilled"){W+=1;for(const oe of se.value)D.has(oe.value)||D.set(oe.value,oe)}const X=[...D.values()].sort((se,oe)=>se.value.localeCompare(oe.value));aa(X),p.length>0&&W===0&&Jt("Could not load remotes from registered projects. Enter a custom owner/repo value."),Zt.current=!0}).catch(()=>{l||(aa([]),Jt("Could not load project list. Enter a custom owner/repo value."),Zt.current=!0)}).finally(()=>{l||na(!1)}),()=>{l=!0}},[E,s]),i.useEffect(()=>{if(E!=="memory"||Xt)return;if(ss.current){ss.current=!1;return}let l=!1;return Xs(!0),Oa(s).then(async({files:p})=>{if(l)return;ra(p);const A=p.some(W=>W.path===je)?je:p.find(W=>W.path===ws)?.path??p.find(W=>W.layer==="dreams")?.path??p[0]?.path??ws;es(A);const{content:D}=await Ci(A,s);l||(mt(D),ht(!1))}).catch(p=>{l||(t(ie(p)||"Failed to load project memory","error"),mt(""))}).finally(()=>{l||Xs(!1)}),()=>{l=!0}},[E,Xt,je,s,t]),i.useEffect(()=>((E==="authentication"||E==="research-global")&&(Gs(!0),de().finally(()=>Gs(!1))),()=>{he.current&&(clearInterval(he.current),he.current=null)}),[E,de]),i.useEffect(()=>{if(E!=="authentication"||!Be.some(A=>A.type!=="api_key"&&A.loginInProgress))return;const p=setInterval(()=>{de()},2e3);return()=>clearInterval(p)},[E,Be,de]);const vt=i.useCallback(()=>{te.current?.scrollTo({top:0,behavior:"smooth"})},[]),Ie=i.useCallback(l=>{if(l in Ye.current){const p={...Ye.current};delete p[l],Ye.current=p}Ot(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A}),Ws(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A}),Wt(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A}),_s(p=>{if(!(l in p))return p;const A={...p};return delete A[l],A})},[]);i.useEffect(()=>{const l=Bt["github-copilot"];l?.userCode&&Ye.current["github-copilot"]!==l.userCode&&(Ye.current["github-copilot"]=l.userCode,ln(l.userCode))},[Bt]);const Ar=i.useCallback(async l=>{const p=Be.find(A=>A.id===l);if(!(p?.requiresManualCode===!0&&!await Z({title:N("settings.auth.manualPasteTitle","Heads up — manual paste-back required"),message:N("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:p.name}),confirmLabel:N("settings.auth.continueToLogin","Continue to login"),cancelLabel:N("settings.actions.cancel","Cancel")}))){be(l),Ie(l);try{const{url:A,instructions:D,manualCode:W,deviceCode:X}=await Si(l);D?.trim()&&!(l==="github-copilot"&&X)&&Ot(se=>({...se,[l]:D})),W&&Ws(se=>({...se,[l]:W})),X&&l==="github-copilot"&&_s(se=>({...se,[l]:X})),(l!=="github-copilot"||!X)&&window.open(on(X?.verificationUri??A),"_blank"),he.current=setInterval(async()=>{try{const{providers:se}=await Ea(),oe=Fa(se);Dt(oe);const Ee=oe.find(ml=>ml.id===l);if(Ee?.authenticated){he.current&&(clearInterval(he.current),he.current=null),be(null),Ie(l),t(N("settings.auth.loginSuccessful","Login successful"),"success"),window.dispatchEvent(new CustomEvent(Pi,{detail:{providerId:l}})),vt();return}Ee?.loginInProgress||(he.current&&(clearInterval(he.current),he.current=null),be(null),Ie(l),t(N("settings.auth.loginDidNotComplete","Login did not complete. Please try again."),"error"))}catch{}},2e3)}catch(A){const D=ie(A)||"Login failed";D.includes("already in progress")||typeof A=="object"&&A!==null&&"status"in A&&A.status===409?(t(N("settings.auth.loginAlreadyInProgress","Login already in progress. You can cancel it and retry."),"warning"),await de()):t(D,"error"),be(null),Ie(l)}}},[t,Be,Ie,Z,de,vt]),Mr=i.useCallback(async l=>{const p=Gt[l]?.trim();if(!p){t(N("settings.auth.pasteRedirectUrlFirst","Paste the full redirect URL or authorization code first."),"warning");return}_t(l);try{(await Ai(l,p)).submitted?(Wt(D=>{if(!(l in D))return D;const W={...D};return delete W[l],W}),t(N("settings.auth.authCodeReceived","Authorization code received. Finishing login…"),"success")):t(N("settings.auth.authCodeAlreadySubmitted","That authorization code was already submitted. Waiting for login…"),"warning")}catch(A){t(ie(A)||"Failed to submit authorization code","error")}finally{_t(null)}},[t,Gt]),Tr=i.useCallback(async l=>{be(l),Dt(p=>p.map(A=>A.id===l?{...A,loginInProgress:!1}:A));try{await Mi(l),Ie(l),await de().catch(()=>{}),t(N("settings.auth.loginCancelled","Login cancelled"),"success")}catch(p){t(ie(p)||"Failed to cancel login","error")}finally{be(null),_t(p=>p===l?null:p),he.current&&(clearInterval(he.current),he.current=null)}},[t,Ie,de]),Rr=i.useCallback(async l=>{be(l);try{await Ti(l),await de(),t(N("settings.auth.loggedOut","Logged out"),"success")}catch(p){t(ie(p)||"Logout failed","error")}finally{be(null)}},[t,de]),Ir=i.useCallback(async l=>{const p=Ut[l]?.trim();if(!p){ot(A=>({...A,[l]:"API key is required"}));return}be(l),ot(A=>{const D={...A};return delete D[l],D});try{const A=await Ri(l,p);if(Ht(D=>{const W={...D};return delete W[l],W}),await de(),l==="opencode"||l==="opencode-go"){const D=A.modelsRefreshed,W=A.refreshReason,X=A.refreshError;X?Ve(se=>({...se,[l]:{tone:"error",message:`Saved, but model refresh failed: ${X}. Make sure the \`opencode\` CLI is installed on PATH.`}})):W==="no-models-from-cli"?Ve(se=>({...se,[l]:{tone:"error",message:"Saved. The local `opencode` CLI returned no models — run `opencode auth login` and `opencode models opencode --refresh`, then click Save again."}})):typeof D=="number"&&D>0?Ve(se=>({...se,[l]:{tone:"success",message:`Refreshed ${D} opencode-go models.`}})):Ve(se=>{const oe={...se};return delete oe[l],oe})}t(N("settings.auth.apiKeySaved","API key saved"),"success"),vt()}catch(A){ot(D=>({...D,[l]:ie(A)||"Failed to save API key"})),(l==="opencode"||l==="opencode-go")&&Ve(D=>{const W={...D};return delete W[l],W})}finally{be(null)}},[Ut,t,de,vt]),Er=i.useCallback(async l=>{be(l);try{await Ii(l),Ht(p=>{const A={...p};return delete A[l],A}),ot(p=>{const A={...p};return delete A[l],A}),await de(),t(N("settings.auth.apiKeyCleared","API key cleared"),"success")}catch(p){t(ie(p)||"Failed to clear API key","error")}finally{be(null)}},[t,de]),Fr=i.useCallback(async l=>{if(!((l==="ntfy"||l==="ntfy-message"||l==="ntfy-room")&&(!y.ntfyEnabled||!y.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(y.ntfyTopic)))){if(l==="webhook"){if(!y.webhookEnabled||!y.webhookUrl?.trim())return;try{const p=new URL(y.webhookUrl.trim());if(p.protocol!=="http:"&&p.protocol!=="https:")return}catch{return}}zs(p=>({...p,[l]:!0})),ct(p=>{const A={...p};return delete A[l],A});try{const p={ntfyEnabled:y.ntfyEnabled,ntfyTopic:y.ntfyTopic,...y.ntfyBaseUrl?.trim()?{ntfyBaseUrl:y.ntfyBaseUrl.trim()}:{},...y.ntfyAccessToken?.trim()?{ntfyAccessToken:y.ntfyAccessToken.trim()}:{}},A=l==="ntfy"?p:l==="ntfy-message"?{...p,messageEventType:"message:agent-to-user"}:l==="ntfy-room"?{...p,messageEventType:"message:room"}:{webhookUrl:y.webhookUrl,webhookFormat:y.webhookFormat||"generic"};if((await Ei(l==="ntfy-message"||l==="ntfy-room"?"ntfy":l,A,s)).success){const W=l==="ntfy"?"Test notification sent — check your ntfy app!":l==="ntfy-message"?"Message inbox test sent — check your ntfy inbox for the agent-to-user message.":l==="ntfy-room"?"Room reply test sent — check your ntfy inbox for the room reply.":"Test notification sent — check your webhook endpoint!";ct(X=>({...X,[l]:{status:"success",message:W}})),t(W,"success")}else{const W=l==="ntfy-message"?"Failed to send message inbox test":l==="ntfy-room"?"Failed to send room reply test":"Failed to send test notification";ct(X=>({...X,[l]:{status:"error",message:W}})),t(W,"error")}}catch(p){const A=ie(p)||"Failed to send test notification";ct(D=>({...D,[l]:{status:"error",message:A}})),t(A,"error")}finally{zs(p=>({...p,[l]:!1}))}}},[t,y.ntfyAccessToken,y.ntfyBaseUrl,y.ntfyEnabled,y.ntfyTopic,y.webhookEnabled,y.webhookFormat,y.webhookUrl,s]),Lr=i.useCallback(async()=>{dt(!0);try{const l=await Fi(s);if(l.success){t(N("settings.backups.backupCreated","Backup created successfully"),"success");const p=await La(s);zt(p)}else t(l.error||N("settings.backups.createFailed","Failed to create backup"),"error")}catch(l){t(ie(l)||N("settings.backups.createFailed","Failed to create backup"),"error")}finally{dt(!1)}},[t,s]),Dr=i.useCallback(async()=>{try{const l=qe==="global"?"global":qe==="project"?"project":"both",p=await Li(l,s),A=new Blob([JSON.stringify(p,null,2)],{type:"application/json"}),D=URL.createObjectURL(A),W=document.createElement("a"),X=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;W.href=D,W.download=X,document.body.appendChild(W),W.click(),document.body.removeChild(W),URL.revokeObjectURL(D);const se=l==="global"?N("settings.importExport.scopeLabel.global","global"):l==="project"?N("settings.importExport.scopeLabel.project","project"):N("settings.importExport.scopeLabel.all","all");t(N("settings.importExport.exported","Settings exported ({{scope}} scope)",{scope:se}),"success")}catch(l){t(ie(l)||N("settings.importExport.exportFailed","Failed to export settings"),"error")}},[t,qe,s]),Or=i.useCallback(async l=>{const p=l.target.files?.[0];if(p){ns(p),bt(!0);try{const A=await p.text(),D=JSON.parse(A);pa(D),Xe(!0)}catch(A){t(N("settings.importExport.invalidJson","Invalid JSON file: {{error}}",{error:ie(A)}),"error"),ns(null)}finally{bt(!1)}}},[t]),Br=i.useCallback(async()=>{if(ke){bt(!0);try{const l=await Di(ke,{scope:rs,merge:ls},s);if(l.success){const p=[];l.globalCount>0&&p.push(N("settings.importExport.counts.global","{{count}} global",{count:l.globalCount})),l.projectCount>0&&p.push(N("settings.importExport.counts.project","{{count}} project",{count:l.projectCount})),l.workflowSettingsCount>0&&p.push(N("settings.importExport.counts.workflowSettings","{{count}} workflow setting value",{count:l.workflowSettingsCount})),t(N("settings.importExport.imported","Imported {{counts}} setting(s)",{counts:p.join(", ")}),"success"),Xe(!1),pa(null),ns(null);const A=await Ma(s);U(A)}else t(l.error||N("settings.importExport.importFailed","Import failed"),"error")}catch(l){t(ie(l)||N("settings.importExport.importFailedDetailed","Failed to import settings"),"error")}finally{bt(!1)}}},[t,ke,rs,ls,s]),xa=i.useCallback(async l=>{const p=Ge,D=p.includes(l)?p.filter(W=>W!==l):[l,...p];$t(D);try{await st({favoriteProviders:D,favoriteModels:We})}catch{$t(p)}},[Ge,We]),ya=i.useCallback(async l=>{const p=We,D=p.includes(l)?p.filter(W=>W!==l):[l,...p];Kt(D);try{await st({favoriteProviders:Ge,favoriteModels:D})}catch{Kt(p)}},[We,Ge]);i.useEffect(()=>{if(!M)return;const l=p=>{p.key==="Escape"&&a()};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[a,M]);const Gr=Oi(a),Wr=V?Gr:{},ja=[{laneId:"default",label:"Default Model",globalProviderKey:"defaultProvider",globalModelKey:"defaultModelId",projectProviderKey:"defaultProviderOverride",projectModelKey:"defaultModelIdOverride",helperText:"Default AI model used for task execution when no per-task override is set.",fallbackOrder:"Project override → Global default lane → Automatic resolution"},{laneId:"execution",label:"Execution Model",globalProviderKey:"executionGlobalProvider",globalModelKey:"executionGlobalModelId",projectProviderKey:"executionProvider",projectModelKey:"executionModelId",helperText:"AI model used for task implementation (executor agent).",fallbackOrder:"Project override → Global execution lane → Global default lane → Automatic resolution"},{laneId:"planning",label:"Planning Model",globalProviderKey:"planningGlobalProvider",globalModelKey:"planningGlobalModelId",projectProviderKey:"planningProvider",projectModelKey:"planningModelId",helperText:"AI model used for task planning.",fallbackOrder:"Project override → Global planning lane → Global default lane → Automatic resolution"},{laneId:"validator",label:"Reviewer Model",globalProviderKey:"validatorGlobalProvider",globalModelKey:"validatorGlobalModelId",projectProviderKey:"validatorProvider",projectModelKey:"validatorModelId",helperText:"AI model used for code and specification review.",fallbackOrder:"Project override → Global reviewer lane → Global default lane → Automatic resolution"},{laneId:"summarization",label:"Title and Git Commit Message Summarization Model",globalProviderKey:"titleSummarizerGlobalProvider",globalModelKey:"titleSummarizerGlobalModelId",projectProviderKey:"titleSummarizerProvider",projectModelKey:"titleSummarizerModelId",helperText:"AI model used for auto-generating task titles and merge commit summaries.",fallbackOrder:"Project override → Global summarization lane → Project planning lane → Project default lane → Global default lane → Automatic resolution"}];function is(l){if(!z?.project)return"inherited";const p=z.project[l.projectProviderKey],A=z.project[l.projectModelKey];return p!==void 0||A!==void 0?"overridden":"inherited"}function _r(l){const p=y[l.projectProviderKey],A=y[l.projectModelKey];return p&&A?`${p}/${A}`:""}function Ur(l,p){if(p){const A=p.indexOf("/");U(D=>({...D,[l.projectProviderKey]:p.slice(0,A),[l.projectModelKey]:p.slice(A+1)}))}else{if(is(l)==="inherited")return;U(D=>({...D,[l.projectProviderKey]:void 0,[l.projectModelKey]:void 0}))}}function Hr(l){is(l)!=="inherited"&&U(A=>({...A,[l.projectProviderKey]:void 0,[l.projectModelKey]:void 0}))}const $r=i.useCallback(l=>{Mt(l),Tt(".")},[Tt]),Ae=i.useCallback(()=>{Mt(null)},[]),os=i.useCallback(l=>{xe!==null&&(U(p=>{const A=p.overlapIgnorePaths&&p.overlapIgnorePaths.length>0?[...p.overlapIgnorePaths]:[""];return A[xe]=l,{...p,overlapIgnorePaths:A}}),Ae())},[xe,Ae]),Kr=i.useCallback(()=>{if(Ce===".")return;const l=Ce.endsWith("/")?Ce:`${Ce}/`;os(l)},[Ce,os]),zr=i.useCallback(l=>{l.target===l.currentTarget&&Ae()},[Ae]),qr=i.useCallback(()=>{Rt("."),Bs(!0)},[Rt]),Me=i.useCallback(()=>{Bs(!1)},[]),Vr=i.useCallback(l=>{const p=l.endsWith("/")?l:`${l}/`;U(A=>({...A,worktreesDir:p})),Me()},[Me]),Yr=i.useCallback(()=>{const l=Pe==="."?"./":Pe.endsWith("/")?Pe:`${Pe}/`;U(p=>({...p,worktreesDir:l})),Me()},[Pe,Me]),Qr=i.useCallback(l=>{l.target===l.currentTarget&&Me()},[Me]),Xr=i.useCallback((l,p)=>{U(A=>{const D=A.overlapIgnorePaths&&A.overlapIgnorePaths.length>0?[...A.overlapIgnorePaths]:[""];return D[l]=p,{...A,overlapIgnorePaths:D}})},[]),Jr=i.useCallback(l=>{if(U(p=>{const D=(p.overlapIgnorePaths&&p.overlapIgnorePaths.length>0?[...p.overlapIgnorePaths]:[""]).filter((W,X)=>X!==l);return{...p,overlapIgnorePaths:D.length>0?D:[]}}),xe===l){Ae();return}xe!==null&&xe>l&&Mt(xe-1)},[xe,Ae]),Zr=i.useCallback(()=>{U(l=>{const p=l.overlapIgnorePaths&&l.overlapIgnorePaths.length>0?l.overlapIgnorePaths:[""];return{...l,overlapIgnorePaths:[...p,""]}})},[]),el=i.useCallback(async()=>{if(fe||At||Se)return;const l=y.researchSettings?.limits;if(l?.maxConcurrentRuns!==void 0&&(!Number.isFinite(l.maxConcurrentRuns)||l.maxConcurrentRuns<1)){Ke("Research max concurrent runs must be at least 1.");return}if(l?.maxSourcesPerRun!==void 0&&(!Number.isFinite(l.maxSourcesPerRun)||l.maxSourcesPerRun<1)){Ke("Research max sources per run must be at least 1.");return}if(l?.maxDurationMs!==void 0&&(!Number.isFinite(l.maxDurationMs)||l.maxDurationMs<1e3)){Ke("Research max duration must be at least 1000 ms.");return}if(l?.requestTimeoutMs!==void 0&&(!Number.isFinite(l.requestTimeoutMs)||l.requestTimeoutMs<1e3)){Ke("Research request timeout must be at least 1000 ms.");return}Ke(null),_(!0);try{const p={...y,worktreeInitCommand:y.worktreeInitCommand?.trim()||void 0,worktreesDir:y.worktreesDir?.trim()||void 0,worktrunk:{enabled:K&&y.worktrunk?.enabled===!0,binaryPath:y.worktrunk?.binaryPath?.trim()||void 0,onFailure:y.worktrunk?.onFailure??"fail"},maxAutoMergeRetries:en(y),taskPrefix:y.taskPrefix?.trim()||void 0,githubTrackingDefaultRepo:y.githubTrackingDefaultRepo?.trim()||void 0,githubAuthToken:y.githubAuthToken?.trim()||void 0,overlapIgnorePaths:(y.overlapIgnorePaths??[]).map(W=>W.trim()).filter(W=>W.length>0),experimentalFeatures:Gc(y.experimentalFeatures)},{globalPatch:A,projectPatch:D}=go({payload:p,initialValues:C,initialScopedValues:le,activeSection:E});await Promise.all([Object.keys(A).length>0?st(A):Promise.resolve(),Object.keys(D).length>0?Bi(D,s):Promise.resolve(),gt!==ma.current?Gi({globalMaxConcurrent:gt??4}):Promise.resolve()]),await G.current?.(),t(N("settings.general.settingsSaved","Settings saved"),"success"),a()}catch(p){if(p instanceof hn)return;t(ie(p),"error")}finally{_(!1)}},[y,gt,At,Se,C,le,a,t,s,E,fe,N]),tl=i.useCallback(async()=>{try{await Wi(je,Qt,s),ht(!1),t(N("settings.memory.memorySaved","Memory saved"),"success")}catch(l){t(ie(l)||"Failed to save memory","error")}},[je,Qt,s,t]),sl=i.useCallback(async()=>{ca(!0);try{const{path:l,content:p}=await _i(je,s),A=l??je;je!==A&&(ss.current=!0),es(A),mt(p),ht(!1);const{files:D}=await Oa(s);ra(D),t(N("settings.memory.memoryCompacted","Memory file compacted"),"success")}catch(l){t(ie(l)||"Failed to compact memory","error")}finally{ca(!1)}},[je,s,t]),al=i.useCallback(async()=>{la(!0),ia(null);try{const l=await Ui(ts,s);ia(l),t(l.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",l.qmdAvailable?"success":"warning")}catch(l){t(ie(l)||"Failed to test memory retrieval","error")}finally{la(!1)}},[ts,s,t]),nl=i.useCallback(async()=>{oa(!0);try{await Hi(s),t(N("settings.memory.dreamCompleted","Dream processing completed"),"success")}catch(l){t(l instanceof Error?l.message:"Failed to run dream processing","error")}finally{oa(!1)}},[s,t]),rl=i.useCallback(async()=>{da(!0);try{const l=await $i(s);await fa(),t(l.qmdAvailable?N("settings.memory.qmdInstalled","qmd installed successfully"):N("settings.memory.qmdInstallUnavailable","qmd install finished, but qmd is still unavailable"),l.qmdAvailable?"success":"warning")}catch(l){t(ie(l)||N("settings.memory.qmdInstallFailed","Failed to install qmd"),"error")}finally{da(!1)}},[s,fa,t]),ll=()=>{if(!Se)return;const l=Se.name.trim();if(!l){t(N("settings.models.presetNameRequired","Preset name is required"),"error");return}const p=y.modelPresets||[];let A;Qe?A=Qe:A=Xi(l,p);const D={id:A,name:l,executorProvider:Se.executorProvider,executorModelId:Se.executorModelId,validatorProvider:Se.validatorProvider,validatorModelId:Se.validatorModelId};U(W=>{const X=W.modelPresets||[],se=Qe?X.map(oe=>oe.id===Qe?D:oe):[...X,D];return{...W,modelPresets:se}}),qs(null),Vs(null)},il=i.useCallback(async(l,p)=>{Ys(l);try{await p(),await ft()}catch(A){t(ie(A)||`Failed to ${l}`,"error")}finally{Ys(null)}},[t,ft]),ol=i.useCallback(()=>{if(typeof navigator<"u"&&navigator.userAgent.includes("Windows"))return"winget install Cloudflare.cloudflared";const l=typeof navigator<"u"?navigator.platform:"",p=typeof navigator<"u"?navigator.userAgent:"",A=/(Mac|iPhone|iPad|iPod)/i.test(l),D=/(arm64|aarch64)/i.test(`${l} ${p}`);return A?"brew install cloudflared":`curl -L --output /tmp/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${D?"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`},[]),cl=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`,[]),dl=i.useCallback(async()=>{Qs(!0),Yt(null);try{const l=await Ki(s);if(!l.success){Yt(l.error??N("settings.remote.installationFailed","Installation failed"));return}const p=await ms(s);ut(p),t(N("settings.remote.cloudflaredInstalled","cloudflared installed successfully"),"success")}catch(l){Yt(l instanceof Error?l.message:N("settings.remote.installationFailed","Installation failed"))}finally{Qs(!1)}},[t,s]),re=()=>qe==="global"?e.jsxs("div",{className:"settings-scope-banner settings-scope-global",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(nt,{size:14})}),e.jsx("span",{children:N("settings.scope.globalBanner","These settings are shared across all your Fusion projects.")})]}):qe==="project"?e.jsxs("div",{className:"settings-scope-banner settings-scope-project",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(Ba,{size:14})}),e.jsx("span",{children:N("settings.scope.projectBanner","These settings only affect this project.")})]}):null,ul=()=>{switch(E){case"cli-agents":return e.jsxs(e.Fragment,{children:[re(),e.jsx(Wc,{projectId:s,addToast:t})]});case"general":return e.jsx(rc,{scopeBanner:re(),form:y,setForm:U,projectId:s,addToast:t,prefixError:At,setPrefixError:yn,projectTrackingRepoOptions:rr,projectTrackingRepoLoading:lr,projectTrackingRepoError:ir,onQuickChatButtonModeChange:P});case"global-general":return e.jsx(So,{scopeBanner:re(),form:y,setForm:U,globalTrackingRepoOptions:or,globalTrackingRepoLoading:cr,globalTrackingRepoError:dr});case"global-models":return e.jsx(Eo,{scopeBanner:re(),form:y,setForm:U,availableModels:Us,modelsLoading:$s,globalModelLanes:ja.filter(l=>l.laneId!=="default"),favoriteProviders:Ge,favoriteModels:We,onToggleFavorite:xa,onToggleModelFavorite:ya,addToast:t,projectId:s});case"secrets":return e.jsx(Zo,{scopeBanner:re(),addToast:t});case"project-models":return e.jsx(cc,{scopeBanner:re(),form:y,setForm:U,projectId:s,addToast:t,onOpenWorkflowSettings:f,registerWorkflowLaneSaver:J,models:{modelLanes:ja,getLaneStatus:is,getLaneValue:_r,updateLaneValue:Ur,resetLaneValue:Hr,availableModels:Us,modelsLoading:$s,favoriteProviders:Ge,favoriteModels:We,onToggleFavorite:xa,onToggleModelFavorite:ya,editingPresetId:Qe,setEditingPresetId:qs,presetDraft:Se,setPresetDraft:Vs,onSavePresetDraft:ll,confirmDelete:Z}});case"appearance":return e.jsx(yo,{scopeBanner:re(),form:y,setForm:U,themeMode:r,colorTheme:m,dashboardFontScalePct:d,shadcnCustomColors:w,resolvedThemeMode:b,onThemeModeChange:o,onColorThemeChange:n,onDashboardFontScaleChange:c,onShadcnCustomColorsChange:h,sessionBannersHidden:me,setSessionBannersHidden:Qi});case"scheduling":return e.jsx(uc,{scopeBanner:re(),form:y,setForm:U,globalMaxConcurrent:gt,concurrencyLoading:E==="scheduling"&&!vr&&!as.current,onGlobalMaxConcurrentChange:l=>{as.current=!0,ua(l)},onOverlapIgnorePathChange:Xr,onOpenOverlapPathPicker:$r,onRemoveOverlapIgnorePath:Jr,onAddOverlapIgnorePath:Zr,onOpenWorkflowSettings:f});case"scheduled-evals":return e.jsx(mc,{scopeBanner:re(),form:y,setForm:U});case"node-routing":return e.jsx(gc,{scopeBanner:re(),form:y,setForm:U,nodes:Tn});case"worktrees":return e.jsx(pc,{scopeBanner:re(),form:y,setForm:U,gitRemotes:tr,worktrunkInstall:O,worktrunkInstallVerified:K,onOpenWorktreesDirPicker:qr,onOpenApprovals:x});case"commands":return e.jsx(bc,{scopeBanner:re(),form:y,setForm:U});case"merge":return e.jsx(xc,{scopeBanner:re(),form:y,setForm:U,integrationBranchOptions:sr,integrationBranchCustomMode:ar,setIntegrationBranchCustomMode:nr,onOpenWorkflowSettings:f});case"agent-permissions":return e.jsx(jc,{scopeBanner:re(),form:y,setForm:U});case"memory":return e.jsx(Cc,{scopeBanner:re(),form:y,setForm:U,memory:{memoryCapabilities:wr,memoryBackendStatus:kr,memoryBackendLoading:Nr,memoryBackendError:Cr,memoryFiles:ur,selectedMemoryPath:je,setSelectedMemoryPath:es,memoryContent:Qt,setMemoryContent:mt,memoryLoading:er,memoryDirty:Xt,setMemoryDirty:ht,memoryTestQuery:ts,setMemoryTestQuery:mr,memoryTestLoading:hr,memoryTestResult:gr,qmdInstallLoading:fr,dreamRunning:pr,memoryCompactLoading:br,onInstallQmd:rl,onTestMemoryRetrieval:al,onDreamNow:nl,onCompactMemory:sl,onSaveMemory:tl}});case"research-global":return e.jsx(Po,{scopeBanner:re(),form:y,setForm:U,authProviders:Be,onNavigateToSection:H});case"research-project":return e.jsx(Sc,{scopeBanner:re(),form:y,setForm:U,researchLimitError:jn});case"experimental":return e.jsx(jo,{scopeBanner:re(),form:y,setForm:U,knownFeatures:Dc,legacyAliases:Ct,getCanonicalKey:Is,isFeatureEnabled:Bc,hiddenFeatureKeys:Oc});case"backups":return e.jsx(Pc,{scopeBanner:re(),form:y,setForm:U,backupInfo:Wn,backupLoading:_n,onBackupNow:Lr});case"notifications":return e.jsx(wo,{scopeBanner:re(),form:y,setForm:U,testNotificationLoading:Bn,testNotificationResult:Gn,onTestProviderNotification:Fr});case"node-sync":return e.jsx(ko,{scopeBanner:re(),form:y,setForm:U});case"remote":return e.jsx(Ao,{scopeBanner:re(),form:y,setForm:U,remote:{projectId:s,addToast:t,remoteStatus:ye,externalTunnel:qt,tunnelShareLink:Zn,remoteBusyAction:Un,cloudflaredInstalling:Hn,cloudflaredInstallError:$n,cloudflaredManualInstallCommand:ol,cloudflaredMacFallbackCommand:cl,handleInstallCloudflared:dl,runRemoteAction:il,remoteShortLivedToken:Xn,setRemoteShortLivedToken:Jn,remoteAuthLinkTokenType:Kn,setRemoteAuthLinkTokenType:zn,remoteUrlPreview:qn,setRemoteUrlPreview:Vn,remoteQrSvg:Yn,setRemoteQrSvg:Qn}});case"prompts":return e.jsx(nc,{scopeBanner:re(),form:y,setForm:U});case"plugins":return e.jsx(Tc,{scopeBanner:re(),projectId:s,addToast:t,activePluginsSubsection:ae,setActivePluginsSubsection:ve});case"authentication":return e.jsx(Bo,{auth:{projectId:s,addToast:t,authProviders:Be,authLoading:Rn,authActionInProgress:In,apiKeyInputs:Ut,setApiKeyInputs:Ht,apiKeyErrors:Dn,opencodeApiKeyRefreshStatus:On,deviceCodes:Bt,loginInstructions:En,manualCodeConfigs:Fn,manualCodeInputs:Gt,setManualCodeInputs:Wt,manualCodeSubmitInProgress:Ln,loadAuthStatus:de,handleLogin:Ar,handleLogout:Rr,handleCancelLogin:Tr,handleSaveApiKey:Ir,handleClearApiKey:Er,handleSubmitManualCode:Mr,onReopenOnboarding:g}});case"hermes-runtime":return e.jsx(Qo,{});case"openclaw-runtime":return e.jsx(Xo,{});case"paperclip-runtime":return e.jsx(Jo,{})}};return e.jsxs("div",{className:k?"settings-embedded right-dock-embedded-view":"modal-overlay open settings-modal-overlay",...Wr,"data-testid":k?"settings-view":void 0,role:k?"region":"dialog","aria-label":k?N("settings.title","Settings"):void 0,"aria-modal":k?void 0:"true",children:[e.jsxs("div",{className:k?"modal modal-lg settings-modal settings-modal--embedded":"modal modal-lg settings-modal",ref:F,style:k?void 0:S,children:[e.jsxs("div",{className:k?"modal-header modal-header--embedded":"modal-header",children:[e.jsx("div",{className:"settings-modal-heading",children:e.jsxs("h3",{children:[k&&e.jsx(zi,{size:20,"aria-hidden":"true"}),e.jsx("span",{children:N("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":N("settings.header.starFusion","Star Fusion on GitHub"),title:N("settings.header.starFusion","Star Fusion on GitHub"),onClick:xn,"data-clicked":vn?"true":"false",children:[e.jsxs("span",{className:"settings-github-star-btn__action",children:[e.jsx(rt,{provider:"github",size:"sm"}),e.jsx(qi,{size:11,"aria-hidden":"true"}),N("settings.header.star","Star")]}),$e!==null&&e.jsx("span",{className:"settings-github-star-btn__count","aria-label":`${$e.toLocaleString()} stars`,children:$e>=1e3?`${($e/1e3).toFixed(1)}k`:$e.toLocaleString()})]}),e.jsxs("a",{href:"https://discord.gg/ksrfuy7WYR",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-header-discord-btn","aria-label":N("settings.header.joinDiscord","Join our Discord"),title:N("settings.header.joinDiscord","Join our Discord"),children:[e.jsx(Ic,{size:13}),N("settings.header.discord","Discord")]})]}),!k&&e.jsx("button",{className:"modal-close",onClick:a,"aria-label":N("actions.close","Close"),children:"×"})]}),ce?e.jsx("div",{className:"settings-empty-state settings-loading",children:e.jsx(De,{label:N("settings.loading","Loading…")})}):e.jsxs("div",{className:"settings-layout",children:[St&&e.jsxs("div",{className:"settings-mobile-section-picker",children:[e.jsx("label",{htmlFor:"settings-mobile-section",children:N("settings.mobileNav.label","Settings Section")}),e.jsx("select",{id:"settings-mobile-section",className:"select touch-target",value:E,onChange:l=>H(l.target.value),children:Re.filter(l=>!l.isGroupHeader).map(l=>e.jsx("option",{value:l.id,children:N(l.labelKey,l.label)},l.id))})]}),e.jsx("nav",{className:"settings-sidebar",children:Re.map(l=>l.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:N(l.labelKey,l.label)},l.id):e.jsxs("button",{className:`settings-nav-item${E===l.id?" active":""}`,onClick:()=>H(l.id),title:l.scope==="global"?N("settings.nav.tooltip.global","Shared across all projects"):l.scope==="project"?N("settings.nav.tooltip.project","Specific to this project"):void 0,children:[l.scope==="global"&&e.jsx(nt,{className:"settings-scope-icon","aria-label":N("settings.nav.aria.global","Global setting"),size:16}),l.scope==="project"&&e.jsx(Ba,{className:"settings-scope-icon","aria-label":N("settings.nav.aria.project","Project setting"),size:16}),l.icon&&!l.scope&&e.jsx(l.icon,{className:"settings-scope-icon","aria-label":N("settings.nav.aria.global","Global setting"),size:16}),N(l.labelKey,l.label)]},l.id))}),e.jsx("div",{className:"settings-content",ref:te,children:ul()})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"settings-modal-footer-version",children:[e.jsxs("a",{href:"https://github.com/Runfusion/Fusion/discussions",target:"_blank",rel:"noopener noreferrer",className:"btn btn-sm settings-footer-help-btn","aria-label":N("settings.footer.helpDiscussions","Help and discussions"),title:N("settings.footer.helpDiscussions","Help and discussions"),children:[e.jsx(Vi,{size:13,"aria-hidden":"true"}),N("settings.footer.help","Help")]}),e.jsxs("div",{className:"settings-update-check",children:[Oe&&e.jsxs("button",{type:"button",className:"settings-version-check-btn",onClick:()=>{Sr()},disabled:Es,"aria-label":N("settings.footer.checkUpdates","Check for updates"),title:N("settings.footer.checkUpdates","Check for updates"),children:[e.jsx("span",{className:"settings-modal-version",children:N("settings.footer.version","Version {{version}}",{version:Oe})}),e.jsx(Ia,{size:12,className:Es?"spinning":void 0})]}),ue&&e.jsx("span",{"aria-live":"polite",className:`settings-update-result ${ue.error?"settings-update-result--error":ue.updateAvailable?"settings-update-result--available":"settings-update-result--up-to-date"}`,children:Pr()})]})]}),e.jsxs("div",{className:"modal-actions-left",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Dr,title:N("settings.importExport.exportTitle","Export settings to JSON file"),children:N("settings.importExport.exportBtn","Export")}),e.jsx("input",{type:"file",ref:ba,accept:".json,application/json",style:{display:"none"},onChange:Or}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ba.current?.click(),disabled:pt,title:N("settings.importExport.importTitleAttr","Import settings from JSON file"),children:pt?N("settings.importExport.loadingFile","Loading…"):N("settings.importExport.importBtn","Import")})]}),e.jsxs("div",{className:"modal-actions-right",children:[!k&&e.jsx("button",{className:"btn btn-sm",onClick:a,children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:el,disabled:ce||fe,children:N("settings.actions.save","Save")})]})]})]}),xe!==null&&e.jsx("div",{className:"modal-overlay open",onClick:zr,role:"dialog","aria-modal":"true","aria-label":N("settings.scheduling.browseWorkspacePath","Browse workspace path"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:N("settings.scheduling.selectIgnoredOverlapPath","Select ignored overlap path")}),e.jsx("button",{className:"modal-close",onClick:Ae,"aria-label":N("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:N("settings.scheduling.overlapPickerNote","Choose a file to ignore directly, or navigate into a folder and select the current directory.")}),e.jsx(Ga,{entries:kn,currentPath:Ce,onSelectFile:os,onNavigate:Tt,loading:wn,error:Nn,onRetry:Cn,workspace:"project",projectId:s})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[N("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:Ce==="."?N("settings.fileBrowser.projectRoot","(project root)"):Ce})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:Ae,children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Kr,disabled:Ce===".",children:N("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),Os&&e.jsx("div",{className:"modal-overlay open",onClick:Qr,role:"dialog","aria-modal":"true","aria-label":N("settings.worktrees.browseWorktreesDirectory","Browse worktrees directory"),children:e.jsxs("div",{className:"modal modal-lg settings-overlap-path-picker-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:N("settings.worktrees.selectWorktreesDir","Select worktrees directory")}),e.jsx("button",{className:"modal-close",onClick:Me,"aria-label":N("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:N("settings.worktrees.worktreesPickerNote","Navigate to the folder where Fusion should create task worktrees, then select the current directory.")}),e.jsx(Ga,{entries:Sn,currentPath:Pe,onSelectFile:Vr,onNavigate:Rt,loading:Pn,error:An,onRetry:Mn,workspace:"project",projectId:s})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("div",{className:"modal-actions-left",children:e.jsxs("small",{children:[N("settings.fileBrowser.currentDirectory","Current directory:")," ",e.jsx("code",{children:Pe==="."?N("settings.fileBrowser.projectRoot","(project root)"):Pe})]})}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:Me,children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Yr,children:N("settings.scheduling.selectCurrentDir","Select current directory")})]})]})]})}),xr&&ke&&e.jsx("div",{className:"modal-overlay open",onClick:l=>l.target===l.currentTarget&&Xe(!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:N("settings.importExport.importTitle","Import Settings")}),e.jsx("button",{className:"modal-close",onClick:()=>Xe(!1),"aria-label":N("actions.close","Close"),children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:N("settings.importExport.reviewPrompt","Review the settings to be imported:")}),ke.global&&Object.keys(ke.global).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:N("settings.importExport.globalSettings","Global Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(ke.global).filter(([,l])=>l!==void 0).map(([l])=>e.jsx("li",{children:l},l))})]}),ke.project&&Object.keys(ke.project).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:N("settings.importExport.projectSettings","Project Settings:")}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(ke.project).filter(([,l])=>l!==void 0).map(([l])=>e.jsx("li",{children:l},l))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"import-scope",children:N("settings.importExport.importScope","Import Scope:")}),e.jsxs("select",{id:"import-scope",value:rs,onChange:l=>yr(l.target.value),children:[e.jsx("option",{value:"both",children:N("settings.importExport.scopeBoth","Both global and project settings")}),e.jsx("option",{value:"global",children:N("settings.importExport.scopeGlobal","Global settings only")}),e.jsx("option",{value:"project",children:N("settings.importExport.scopeProject","Project settings only")})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"import-merge",className:"checkbox-label",children:[e.jsx("input",{id:"import-merge",type:"checkbox",checked:ls,onChange:l=>jr(l.target.checked)}),N("settings.importExport.mergeExisting","Merge with existing settings (recommended)")]}),e.jsx("small",{children:N("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:()=>Xe(!1),children:N("settings.actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Br,disabled:pt,children:pt?N("settings.importExport.importing","Importing…"):N("settings.importExport.confirmImport","Confirm Import")})]})]})})]})}function Zc(a){return e.jsx(_c,{presentation:"embedded",...a})}export{_c as SettingsModal,Zc as SettingsView};
|