openfox 2.0.127 → 2.0.128
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/CHANGELOG.md +11 -0
- package/dist/CHANGELOG.md +11 -0
- package/dist/{chat-handler-63VGKLM5.js → chat-handler-3O6AIOID.js} +10 -10
- package/dist/{chunk-TZJU6F6Z.js → chunk-4MXY7ELN.js} +28 -28
- package/dist/{chunk-IQYI7TWF.js → chunk-53R7QNZG.js} +14 -11
- package/dist/{chunk-GJL3QSMP.js → chunk-7ZMOP5LS.js} +16 -1
- package/dist/{chunk-T3JVYO3Z.js → chunk-B2RPFZ3U.js} +3 -3
- package/dist/{chunk-GKDJW4VP.js → chunk-BQNQJE57.js} +3 -3
- package/dist/{chunk-FGK6KPJ5.js → chunk-CQW4QASE.js} +4 -4
- package/dist/{chunk-FNXTJLCZ.js → chunk-D5QVV3LT.js} +2 -2
- package/dist/chunk-ES5635OP.js +7 -0
- package/dist/{chunk-CTHRGR4O.js → chunk-FYXZRVOL.js} +2 -2
- package/dist/{chunk-HOSFRPPI.js → chunk-JEMPUHAA.js} +2 -2
- package/dist/{chunk-TY3ONJE4.js → chunk-LWDL7HWL.js} +4 -4
- package/dist/{chunk-IE2OMJIH.js → chunk-OWCJRSOU.js} +9 -9
- package/dist/{chunk-UAAFZEIS.js → chunk-S6ATKIT2.js} +2 -2
- package/dist/{chunk-7CBVJAN5.js → chunk-VHMZBKWY.js} +5 -5
- package/dist/{chunk-LJX7KXRU.js → chunk-VJRLIKLE.js} +2 -2
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/{client-YHYIWZY7.js → client-VDXO7IIV.js} +3 -3
- package/dist/{compactor-7KPBTFZF.js → compactor-B6IVMDES.js} +4 -4
- package/dist/{dynamic-context-KXZ6VJDE.js → dynamic-context-4WVMNJTZ.js} +2 -2
- package/dist/{launch-DYWJD6L5.js → launch-AKIMGAGC.js} +10 -10
- package/dist/{orchestrator-LBQWRAXC.js → orchestrator-WLNW7TS7.js} +9 -9
- package/dist/package.json +1 -1
- package/dist/{processor-WP2LQOEV.js → processor-ZMXU5MOT.js} +9 -9
- package/dist/{profiles-3YLLEJ2B.js → profiles-HXGJIPF2.js} +2 -2
- package/dist/{provider-726LD2KU.js → provider-QIOTESLB.js} +4 -4
- package/dist/{provider-manager-OQTEXZ7X.js → provider-manager-FVI22EWM.js} +4 -4
- package/dist/{serve-OY3Y5PXK.js → serve-7M4HCERR.js} +15 -15
- package/dist/server/index.js +14 -14
- package/dist/{server-DMHNVEW4.js → server-RX5JM7IT.js} +13 -13
- package/dist/{service-BRKMLM4C.js → service-F4TWYTKE.js} +5 -5
- package/dist/{tasks-DEUZ6BNS.js → tasks-36WHYN3H.js} +5 -5
- package/dist/{tools-CZHV2FAD.js → tools-WAUWG4PE.js} +7 -7
- package/dist/{update-RCNZQCFG.js → update-AIVWCRXR.js} +2 -2
- package/dist/web/assets/{index-B63UkA7X.js → index-DtQsFnyQ.js} +1 -1
- package/dist/web/index.html +1 -1
- package/dist/web/sw.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-QDO3BEGW.js +0 -7
|
@@ -302,7 +302,7 @@ WARNING: This link could potentially be dangerous`)){const S=window.open();if(S)
|
|
|
302
302
|
`,children:n?"Reconnecting...":"Reconnect"})]})}function GG(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function qG({onClick:e}){return s.jsx("button",{type:"button",onClick:e,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:s.jsx(Kb,{})})}function bL({isOpen:e,onClose:t,initialEditId:n,projectDir:r}){const o=ln(ve=>ve.defaults),a=ln(ve=>ve.userItems),d=ln(ve=>ve.projectItems),l=ln(ve=>ve.loading),c=ln(ve=>ve.fetchCommands),h=ln(ve=>ve.fetchCommand),m=ln(ve=>ve.fetchDefaultContent),f=ln(ve=>ve.createCommand),g=ln(ve=>ve.updateCommand),x=ln(ve=>ve.deleteCommand),[w,C]=j.useState(null),[b,S]=j.useState(null),{view:_,editingId:v,formError:k,saving:E,formData:T,setView:L,setEditingId:A,setFormError:M,setFormData:I,setSaving:U}=mN(),{requestDelete:P,clearConfirm:z,isConfirming:K}=Hu(),H=j.useRef(!1),{data:F,refresh:Q}=Mi(er,r),V=(F?[...F.defaults,...F.userItems]:[]).filter(ve=>!ve.subagent),B=j.useRef(c),D=j.useRef(Q),O=j.useRef(h),$=j.useRef(m),J=j.useRef(r),X=j.useRef(n),Y=j.useRef(L),q=j.useRef(A),W=j.useRef(M),ee=j.useRef(z);j.useEffect(()=>{B.current=c,D.current=Q,O.current=h,$.current=m,J.current=r,X.current=n,Y.current=L,q.current=A,W.current=M,ee.current=z}),j.useEffect(()=>{if(e)if(B.current(J.current),D.current(),H.current||(ee.current(),H.current=!0),X.current){const ve=o.some(oe=>oe.id===X.current);Y.current("edit"),q.current(X.current),W.current(""),ve?$.current(X.current).then(oe=>{oe&&I({name:oe.metadata.name+" (copy)",id:`${X.current}-copy-${Date.now()}`,prompt:oe.prompt,agentMode:oe.metadata.agentMode??"",isDefault:!0,destination:"user"})}):O.current(X.current,J.current).then(oe=>{oe&&I({name:oe.metadata.name,id:oe.metadata.id,prompt:oe.prompt,agentMode:oe.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else Y.current("list"),q.current(null);else H.current=!1},[e]);const ie=async ve=>{C(ve);const oe=await m(ve);S((oe==null?void 0:oe.prompt)??null)},re=async ve=>{if(o.some(ae=>ae.id===ve)){const ae=await m(ve);ae&&(A(null),I({name:`${ae.metadata.name} (copy)`,id:`${ve}-copy-${Date.now()}`,prompt:ae.prompt,agentMode:ae.metadata.agentMode??"",isDefault:!0,destination:"user"}),M(""),L("edit"))}else{const ae=await h(ve,r);ae&&(A(null),I({name:`${ae.metadata.name} (copy)`,id:`${ve}-copy-${Date.now()}`,prompt:ae.prompt,agentMode:ae.metadata.agentMode??"",isDefault:!1,destination:"user"}),M(""),L("edit"))}},se=()=>{I({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),A(null),L("edit")},de=async ve=>{const oe=await h(ve,r);oe&&(A(ve),I({name:oe.metadata.name,id:oe.metadata.id,prompt:oe.prompt,agentMode:oe.metadata.agentMode??"",isDefault:!1,destination:"user"}),M(""),L("edit"))},Se=async ve=>{await x(ve,r),z()},Me=async()=>{const ve=v??T.id;if(!ve||!T.name||!T.prompt){M("Name and message are required.");return}U(!0),M("");const oe={metadata:{id:ve,name:T.name,...T.agentMode?{agentMode:T.agentMode}:{}},prompt:T.prompt},ae=v?await g(v,oe,r):await f(oe,T.destination,r);if(U(!1),!ae.success){M(ae.error??"Failed to save command.");return}n?t():L("list")},ye=()=>{n?t():(L("list"),C(null),S(null))},ue=ve=>{I(oe=>({...oe,name:ve})),(!v||T.isDefault)&&I(oe=>({...oe,id:GG(ve)}))},Ie=()=>{C(null),S(null),L("list")},We=()=>{w&&(C(null),L("edit"),A(w),m(w).then(ve=>{ve&&I({name:`${ve.metadata.name} (copy)`,id:`${w}-copy-${Date.now()}`,prompt:ve.prompt,agentMode:ve.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(w){const ve=o.find(oe=>oe.id===w);return s.jsx(vt,{isOpen:e,onClose:Ie,title:`Default: ${(ve==null?void 0:ve.name)??w}`,size:"xl",footer:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ct,{variant:"secondary",onClick:Ie,children:"Close"}),s.jsx(ct,{variant:"primary",onClick:We,children:"Duplicate & Customize"})]}),children:s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"space-y-3 mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),s.jsx("span",{className:"font-mono",children:w})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),s.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:ve==null?void 0:ve.name})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),s.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(ve==null?void 0:ve.agentMode)||"None"})]})]}),s.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),s.jsx("textarea",{value:b??"",readOnly:!0,placeholder:"...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none opacity-60"})]})]})})}if(_==="edit")return s.jsx(vt,{isOpen:e,onClose:ye,title:v?"Edit Command":"New Command",size:"xl",footer:s.jsx(cN,{onCancel:ye,onSave:Me,saving:E,saveDisabled:!T.name||!T.prompt}),children:s.jsxs("div",{className:"flex flex-col h-full",children:[k&&s.jsx(Rl,{message:k}),s.jsxs("div",{className:"space-y-3 mb-3",children:[s.jsx(fN,{name:T.name,id:T.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!T.isDefault,onNameChange:ue,onIdChange:ve=>I(oe=>({...oe,id:ve}))}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",s.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),s.jsxs("select",{value:T.agentMode,onChange:ve=>I(oe=>({...oe,agentMode:ve.target.value})),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[s.jsx("option",{value:"",children:"None (keep current mode)"}),V.map(ve=>s.jsx("option",{value:ve.id,children:ve.name},ve.id))]})]}),!v&&s.jsx(pm,{value:T.destination,onChange:ve=>I(oe=>({...oe,destination:ve}))})]}),s.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),s.jsx("textarea",{value:T.prompt,onChange:ve=>I(oe=>({...oe,prompt:ve.target.value})),placeholder:"The message that will be sent when this command is triggered...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]})});const Qe=ve=>ve.map(oe=>s.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[s.jsx("div",{className:"min-w-0 flex-1 mr-3",children:s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("span",{className:"text-text-primary text-sm font-medium",children:oe.name})})}),s.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[s.jsx(Li,{onClick:()=>de(oe.id)}),s.jsx(Lu,{onClick:()=>re(oe.id)}),K(oe.id,"delete")?s.jsx(gf,{onConfirm:()=>Se(oe.id),onCancel:z}):s.jsx(xf,{onClick:()=>P(oe.id)})]})]},oe.id));return s.jsxs(vt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[s.jsx(hN,{description:"Commands are pre-defined messages you can send with a single click.",onNew:se}),s.jsxs(Zb,{loading:l,hasItems:o.length>0||a.length>0||d.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[o.length>0&&s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),s.jsx("div",{className:"space-y-2",children:o.map(ve=>s.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[s.jsx("div",{className:"min-w-0 flex-1 mr-3",children:s.jsx("span",{className:"text-text-primary text-sm font-medium",children:ve.name})}),s.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[s.jsx(qG,{onClick:()=>ie(ve.id)}),s.jsx(Lu,{onClick:()=>re(ve.id)})]})]},ve.id))})]}),a.length>0&&s.jsx(dN,{children:Qe(a)}),d.length>0&&s.jsxs("div",{className:"mt-4",children:[s.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),s.jsx("div",{className:"space-y-2",children:Qe(d)})]})]})]})}function KG({title:e,defaultOpen:t=!1,children:n,className:r=""}){return s.jsxs("details",{className:`group ${r}`,open:t,children:[s.jsxs("summary",{className:"text-[11px] text-text-secondary uppercase tracking-wider font-medium cursor-pointer select-none hover:text-text-primary transition-colors list-none flex items-center gap-1",children:[s.jsx(mn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),e]}),s.jsx("div",{className:"mt-2 space-y-2",children:n})]})}const ea=150,_i=54,Hh=80,gs=30,pl=70,_j=100,ta=50,Uh=50,Sj=4,vL={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},_L=[{value:"step_result",label:"Step result is..."},{value:"metadata_all_match",label:"Metadata all match (key=value)"},{value:"metadata_all_in",label:"Metadata all in list"},{value:"always",label:"Always (fallback)"}],YG=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"},{value:"user",label:"User (pause)"}];function n_(e,t){if(e.type==="agent"){const n=t.find(r=>r.id===e.agentId);return{name:(n==null?void 0:n.name)??(e.agentId||"Agent"),color:(n==null?void 0:n.color)||"#3b82f6"}}if(e.type==="sub_agent"){const n=t.find(r=>r.id===e.subAgentType);return{name:(n==null?void 0:n.name)??(e.subAgentType||"Sub-Agent"),color:(n==null?void 0:n.color)||"#a855f7"}}return e.type==="user"?{name:"User",color:"#f59e0b"}:{name:"Shell",color:"#22c55e"}}function XG(e,t,n,r){const o=Uh+ta+ea+_j+ea+ta+Uh,a=o/2,d=Uh+ta+ea/2,l=Uh+ta+ea+_j+ea/2,c=[],h=[],m=new Map,f=e.filter(H=>H.type==="agent"||H.type==="shell"||H.type==="user"),g=e.filter(H=>H.type==="sub_agent"),x=g.length>0,w=x?d:a,C=f.length>0?l:a,b=ta+gs/2;c.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:b,w:Hh,h:gs}),m.set("$start",{cx:w,cy:b,w:Hh,h:gs});const S=H=>{c.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:H,w:Hh,h:gs}),m.set("$done",{cx:w,cy:H,w:Hh,h:gs})};if(e.length===0){const H=b+gs/2+pl*2+gs/2;return S(H),{nodes:c,edges:h,width:o,height:H+gs/2+ta,posMap:m}}const _=b+gs/2+pl,v=(H,F)=>{H.forEach((Q,Z)=>{const V=_+Z*(_i+pl)+_i/2,{name:B,color:D}=n_(Q,r);c.push({id:Q.id,type:"step",label:B,color:D,cx:F,cy:V,w:ea,h:_i}),m.set(Q.id,{cx:F,cy:V,w:ea,h:_i})})};v(f,w),v(g,C);const k=f.length>0?_+(f.length-1)*(_i+pl)+_i/2:b,E=x?_+(g.length-1)*(_i+pl)+_i/2:b,T=Math.max(k,E)+_i/2+pl+gs/2;S(T);const L=[];t&&m.has(t)&&L.push({from:"$start",to:t,label:n,edgeKey:"start",direction:"down",backEdgeIndex:0});let A=0;for(const H of e)H.transitions.forEach((F,Q)=>{var $;if(!F.goto||!m.has(F.goto))return;const Z=m.get(H.id),V=m.get(F.goto),B=F.when.type==="step_result"?`${F.when.result}`:F.when.type==="metadata_all_match"?`${F.when.key??"?"}=${F.when.value??"?"}`:F.when.type==="metadata_all_in"?`${F.when.key??"?"} in [${(($=F.when.values)==null?void 0:$.join(","))??"?"}]`:vL[F.when.type]??F.when.type,D=H.id===F.goto;let O;D?O="back":V.cy>Z.cy+1?O="down":V.cy<Z.cy-1?O="back":O="same",L.push({from:H.id,to:F.goto,label:B,edgeKey:`${H.id}:${Q}`,direction:O,backEdgeIndex:O==="back"?A++:0})});const M=new Map,I=new Map,U=new Map,P=new Map;for(const H of L)H.direction==="down"&&(M.set(H.from,(M.get(H.from)??0)+1),I.set(H.to,(I.get(H.to)??0)+1));const z=new Map,K=new Map;for(const H of L){if(H.direction!=="same")continue;const F=[H.from,H.to].sort().join("|");z.set(F,(z.get(F)??0)+1)}for(const H of L){if(H.direction==="back"||H.direction==="same"){let O=0;if(H.direction==="same"){const $=[H.from,H.to].sort().join("|");O=K.get($)??0,K.set($,O+1)}h.push({...H,fromPort:0,toPort:0,sameEdgeIndex:O});continue}const F=M.get(H.from)??1,Q=I.get(H.to)??1,Z=U.get(H.from)??0,V=P.get(H.to)??0;U.set(H.from,Z+1),P.set(H.to,V+1);const B=F===1?0:-.6+1.2*Z/(F-1),D=Q===1?0:-.6+1.2*V/(Q-1);h.push({...H,fromPort:B,toPort:D,sameEdgeIndex:0})}return{nodes:c,edges:h,width:o,height:T+gs/2+ta,posMap:m}}function QG({steps:e,entryStep:t,selectedNodeId:n,selectedEdgeKey:r,startConditionLabel:o,agentTypes:a,isReadOnly:d,onSelectNode:l,onSelectEdge:c,onRemoveStep:h,onCreateTransition:m,onReconnectTo:f,onReconnectFrom:g,onDeleteTransition:x}){const w=j.useRef(null),C=j.useRef(!1),[b,S]=j.useState(null),[_,v]=j.useState(null),[k,E]=j.useState(null),{nodes:T,edges:L,width:A,height:M,posMap:I}=j.useMemo(()=>XG(e,t,o,a),[e,t,o,a]),U=j.useCallback(X=>{var ie;const Y=w.current;if(!Y)return{x:0,y:0};const q=Y.createSVGPoint();q.x=X.clientX,q.y=X.clientY;const W=(ie=Y.getScreenCTM())==null?void 0:ie.inverse();if(!W)return{x:0,y:0};const ee=q.matrixTransform(W);return{x:ee.x,y:ee.y}},[]),P=j.useCallback(X=>!X||!_||X==="$start"?!1:_.type==="reconnect-from"?X!=="$done":!0,[_]),z=j.useCallback((X,Y)=>{if(d)return;X.stopPropagation(),X.preventDefault();const q=U(X);v({type:"new",fromNodeId:Y,mouseX:q.x,mouseY:q.y})},[U,d]),K=j.useCallback((X,Y)=>{if(d)return;X.stopPropagation(),X.preventDefault();const q=U(X);v({type:"reconnect-to",fromNodeId:Y.from,edgeKey:Y.edgeKey,mouseX:q.x,mouseY:q.y})},[U,d]),H=j.useCallback((X,Y)=>{if(d)return;X.stopPropagation(),X.preventDefault();const q=U(X);v({type:"reconnect-from",fromNodeId:Y.from,fixedTargetId:Y.to,edgeKey:Y.edgeKey,mouseX:q.x,mouseY:q.y})},[U,d]),F=j.useCallback(X=>{if(!_)return;const Y=U(X);v(q=>q?{...q,mouseX:Y.x,mouseY:Y.y}:null)},[_,U]),Q=j.useCallback(()=>{_&&(C.current=!0,k&&P(k)&&(_.type==="new"?m(_.fromNodeId,k):_.type==="reconnect-to"?f(_.edgeKey,k):_.type==="reconnect-from"&&g(_.edgeKey,k)),v(null),E(null))},[_,k,P,m,f,g]),Z=j.useCallback(()=>{if(C.current){C.current=!1;return}l(null),c(null)},[l,c]);j.useEffect(()=>{if(d)return;const X=Y=>{Y.target instanceof HTMLInputElement||Y.target instanceof HTMLTextAreaElement||Y.target instanceof HTMLSelectElement||(Y.key==="Delete"||Y.key==="Backspace")&&r&&r!=="start"&&(Y.preventDefault(),x(r),c(null))};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[d,r,x,c]);const V=X=>{const Y=I.get(X.from),q=I.get(X.to);if(!Y||!q)return null;let W,ee,ie,re="middle",se,de;if(X.direction==="down"){const Se=Y.cx+X.fromPort*(Y.w/2-10),Me=Y.cy+Y.h/2,ye=q.cx+X.toPort*(q.w/2-10),ue=q.cy-q.h/2,Ie=ue-Me,We=ye-Se;W=`M ${Se} ${Me} C ${Se} ${Me+Ie*.4}, ${ye-We*.2} ${ue-Ie*.1}, ${ye} ${ue}`,ee=Se+(ye-Se)*.5,ie=Me+Ie*.6,se={x:Se,y:Me},de={x:ye,y:ue}}else if(X.direction==="back"){const Se=X.from===X.to,Me=Y.cx>=A/2,ye=X.backEdgeIndex*16,ue=Me?A-20-ye:20+ye;if(Se){const Ie=Y.cx>=A/2,We=30+X.backEdgeIndex*14,Qe=Y.cy-Y.h/2,ve=Ie?Y.cx+Y.w/2:Y.cx-Y.w/2,oe=Ie?ve+We:ve-We,ae=Y.cx+(Ie?Y.w/4:-Y.w/4),we=Qe-20-X.backEdgeIndex*10;W=`M ${ve} ${Y.cy} C ${oe} ${Y.cy}, ${oe} ${we}, ${ae} ${Qe}`,ee=oe+10,ie=we+4,re="middle",se={x:ve,y:Y.cy},de={x:ae,y:Qe}}else{const Ie=Me?Y.cx+Y.w/2:Y.cx-Y.w/2,We=q.cx+(Me?q.w/4:-q.w/4),Qe=Math.min(Y.cy,q.cy)-q.h/2-18-X.backEdgeIndex*14;W=`M ${Ie} ${Y.cy} L ${ue} ${Y.cy} L ${ue} ${Qe} L ${We} ${Qe} L ${We} ${q.cy-q.h/2}`,ee=ue,ie=(Y.cy+Qe)/2,re=Me?"start":"end",se={x:Ie,y:Y.cy},de={x:We,y:q.cy-q.h/2}}}else{const Se=q.cx>Y.cx,Me=X.sameEdgeIndex===0?-12:12,ye=Se?Y.cx+Y.w/2:Y.cx-Y.w/2,ue=Se?q.cx-q.w/2:q.cx+q.w/2,Ie=Y.cy+Me,We=q.cy+Me,Qe=(ye+ue)/2;W=`M ${ye} ${Ie} C ${Qe} ${Ie}, ${Qe} ${We}, ${ue} ${We}`,ee=Qe,ie=(Ie+We)/2-6,se={x:ye,y:Ie},de={x:ue,y:We}}return{path:W,labelX:ee,labelY:ie,labelAnchor:re,fromPt:se,toPt:de}},B=(X,Y)=>{const q=V(X);if(!q)return null;const{path:W,labelX:ee,labelY:ie,labelAnchor:re}=q,se=r===X.edgeKey,de=X.label&&X.label!=="otherwise";return s.jsxs("g",{children:[s.jsx("path",{d:W,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Se=>{Se.stopPropagation(),d||c(se?null:X.edgeKey)}}),s.jsx("path",{d:W,fill:"none",stroke:se?"#58a6ff":"#484f58",strokeWidth:se?2.2:1.2,markerEnd:se?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),de&&s.jsx("text",{x:ee+(re==="start"?5:re==="end"?-5:0),y:ie+3,textAnchor:re,className:"text-[8px]",fill:se?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:X.label})]},Y)},D=()=>{if(!r||_)return null;const X=L.find(ie=>ie.edgeKey===r);if(!X)return null;const Y=V(X);if(!Y)return null;const{fromPt:q,toPt:W}=Y,ee=6;return s.jsxs(s.Fragment,{children:[X.edgeKey!=="start"&&s.jsx("circle",{cx:q.x,cy:q.y,r:ee,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>H(ie,X)}),s.jsx("circle",{cx:W.x,cy:W.y,r:ee,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>K(ie,X)})]})},O=()=>{if(!_)return null;let X,Y,q,W;if(_.type==="reconnect-from"){const re=I.get(_.fixedTargetId);if(!re)return null;X=_.mouseX,Y=_.mouseY,q=re.cx,W=re.cy-re.h/2}else{const re=I.get(_.fromNodeId);if(!re)return null;X=re.cx,Y=re.cy+re.h/2,q=_.mouseX,W=_.mouseY}const ee=W-Y,ie=Math.abs(ee)>10?`M ${X} ${Y} C ${X} ${Y+ee*.4}, ${q} ${W-ee*.4}, ${q} ${W}`:`M ${X} ${Y} L ${q} ${W}`;return s.jsx("path",{d:ie,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},$=X=>{const Y=X.cy+X.h/2,q=(_==null?void 0:_.fromNodeId)===X.id;return s.jsx("circle",{cx:X.cx,cy:Y,r:Sj,fill:q?"#58a6ff":"#1c2128",stroke:q?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:q?1:.5,className:"cursor-crosshair",onMouseDown:W=>z(W,X.id)})},J=X=>{const Y=X.cy-X.h/2,q=_&&k===X.id&&P(X.id);return s.jsx("circle",{cx:X.cx,cy:Y,r:Sj,fill:q?"#3fb950":"#1c2128",stroke:q?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:q?1:.5})};return s.jsxs("svg",{ref:w,viewBox:`0 0 ${A} ${M}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:F,onMouseUp:Q,onClick:Z,children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:s.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),s.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:s.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),L.map((X,Y)=>B(X,Y)),T.map(X=>{const Y=n===X.id,q=X.cx-X.w/2,W=X.cy-X.h/2,ee=b===X.id,ie=_&&k===X.id&&P(X.id);if(X.type==="terminal"){const se=X.id==="$start",de=se?"#58a6ff":"#3fb950",Se=se,Me=!se;return s.jsxs("g",{onClick:ye=>{ye.stopPropagation(),se&&!d&&c("start")},className:se&&!d?"cursor-pointer":void 0,children:[ie&&s.jsx("rect",{x:q-3,y:W-3,width:X.w+6,height:X.h+6,rx:X.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),se&&r==="start"&&s.jsx("rect",{x:q-3,y:W-3,width:X.w+6,height:X.h+6,rx:X.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),s.jsx("rect",{x:q,y:W,width:X.w,height:X.h,rx:X.h/2,fill:de,fillOpacity:.08,stroke:de,strokeOpacity:.4,strokeWidth:1.5}),s.jsx("text",{x:X.cx,y:X.cy+4,textAnchor:"middle",fill:de,className:"text-[10px] font-medium",pointerEvents:"none",children:X.label}),Se&&$(X),Me&&J(X)]},X.id)}const re=X.color??"#6b7280";return s.jsxs("g",{onClick:se=>{se.stopPropagation(),d||l(Y?null:X.id)},onMouseEnter:()=>S(X.id),onMouseLeave:()=>S(null),className:d?void 0:"cursor-pointer",children:[ie&&s.jsx("rect",{x:q-3,y:W-3,width:X.w+6,height:X.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),Y&&s.jsx("rect",{x:q-3,y:W-3,width:X.w+6,height:X.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),s.jsx("rect",{x:q,y:W,width:X.w,height:X.h,rx:10,fill:re,fillOpacity:.08,stroke:re,strokeOpacity:.6,strokeWidth:Y?2:1.5}),s.jsx("text",{x:X.cx,y:X.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:X.label}),!d&&$(X),!d&&J(X),ee&&!_&&!d&&s.jsxs("g",{onClick:se=>{se.stopPropagation(),h(X.id)},className:"cursor-pointer",children:[s.jsx("circle",{cx:q+X.w-2,cy:W+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),s.jsx("line",{x1:q+X.w-5,y1:W-1,x2:q+X.w+1,y2:W+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),s.jsx("line",{x1:q+X.w+1,y1:W-1,x2:q+X.w-5,y2:W+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},X.id)}),_&&T.map(X=>P(X.id)?s.jsx("rect",{x:X.cx-X.w/2-8,y:X.cy-X.h/2-8,width:X.w+16,height:X.h+16,fill:"transparent",rx:12,onMouseEnter:()=>E(X.id),onMouseLeave:()=>E(null),onMouseUp:Y=>{Y.stopPropagation(),Q()}},`drop-${X.id}`):null),O(),D()]})}const Vh="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",cu="block text-[11px] text-text-secondary mb-0.5";function JG({formName:e,formId:t,formDescription:n,formMaxIterations:r,formColor:o,isReadOnly:a,onNameChange:d,onDescriptionChange:l,onMaxIterationsChange:c,onColorChange:h}){return s.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[s.jsxs("div",{className:"min-w-[140px]",children:[s.jsx("label",{className:cu,children:"Name"}),s.jsx("input",{value:e,onChange:m=>d(m.target.value),placeholder:"Workflow name",className:`${Vh} ${a?"opacity-50":""}`,readOnly:a})]}),s.jsxs("div",{className:"min-w-[100px]",children:[s.jsx("label",{className:cu,children:"ID"}),s.jsx("input",{value:t,readOnly:!0,className:`${Vh} font-mono opacity-50`})]}),s.jsxs("div",{className:"flex-1 min-w-[140px]",children:[s.jsx("label",{className:cu,children:"Description"}),s.jsx("input",{value:n,onChange:m=>!a&&l(m.target.value),readOnly:a,placeholder:"What does this workflow do?",className:`${Vh} ${a?"opacity-50":""}`})]}),s.jsxs("div",{className:"w-20",children:[s.jsx("label",{className:cu,children:"Max Iter."}),s.jsx("input",{type:"number",value:r,onChange:m=>!a&&c(Number(m.target.value)),readOnly:a,className:`${Vh} font-mono ${a?"opacity-50":""}`})]}),s.jsxs("div",{children:[s.jsx("label",{className:cu,children:"Color"}),s.jsx("input",{type:"color",value:o,onChange:m=>!a&&h(m.target.value),disabled:a,className:`w-8 h-8 rounded border border-border bg-transparent ${a?"opacity-50":"cursor-pointer"}`})]})]})}function ZG({name:e,id:t,color:n,description:r,isBuiltIn:o,actions:a}){return s.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:n}}),s.jsx("span",{className:"text-text-primary text-sm font-medium",children:e}),s.jsx("span",{className:"text-text-muted text-xs font-mono",children:t}),o&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),r&&s.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:r})]}),s.jsx("div",{className:"flex items-center gap-1 flex-shrink-0 ml-3",children:a})]})}function hy({title:e,items:t,renderActions:n}){return t.length===0?null:s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),s.jsx("div",{className:"space-y-2",children:t.map(r=>s.jsx(ZG,{name:r.name,id:r.id,color:r.color??"#3b82f6",description:r.description,actions:n(r)},r.id))})]})}const na="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",fy="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Ps="block text-[11px] text-text-secondary mb-0.5";function my({variables:e,onInsert:t}){return e.length===0?null:s.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(n=>s.jsx("button",{type:"button",onClick:()=>t(n.name),title:n.description,className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-bg-primary border border-border text-text-secondary hover:text-accent-primary hover:border-accent-primary/40 transition-colors",children:`{{${n.name}}}`},n.name))})}function eq({step:e,isEntry:t,agentTypes:n,transitionCount:r,templateVariables:o,onUpdate:a,onRemove:d,onSetEntry:l}){const{color:c,name:h}=n_(e,n);return s.jsxs("div",{className:"space-y-3 text-sm",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:c+"20",color:c},children:h}),t&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[!t&&s.jsx("button",{onClick:l,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),s.jsx("button",{onClick:d,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Name"}),s.jsx("input",{value:e.name,onChange:m=>a({...e,name:m.target.value}),placeholder:"Step name",className:na})]}),s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Type"}),s.jsx("select",{value:e.type,onChange:m=>{const f=m.target.value,g=f==="sub_agent"?"verification":"build";if(f==="agent"){const x=n.find(w=>!w.subagent);a({...e,type:f,phase:g,agentId:(x==null?void 0:x.id)??"builder",name:(x==null?void 0:x.name)??"Agent"})}else if(f==="sub_agent"){const x=n.find(w=>w.subagent);a({...e,type:f,phase:g,subAgentType:(x==null?void 0:x.id)??"",name:(x==null?void 0:x.name)??"Sub-Agent"})}else a(f==="user"?{...e,type:f,phase:g,name:"User"}:{...e,type:f,phase:g,name:"Shell"})},className:fy,children:YG.map(m=>s.jsx("option",{value:m.value,children:m.label},m.value))})]}),e.type==="agent"&&s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Agent Type"}),s.jsx("select",{value:e.agentId??"builder",onChange:m=>{const f=n.find(g=>g.id===m.target.value);a({...e,agentId:m.target.value,name:(f==null?void 0:f.name)??m.target.value})},className:fy,children:n.filter(m=>!m.subagent).map(m=>s.jsx("option",{value:m.id,children:m.name},m.id))})]}),e.type==="sub_agent"&&s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Sub-Agent Type"}),s.jsxs("select",{value:e.subAgentType??"",onChange:m=>{const f=n.find(g=>g.id===m.target.value);a({...e,subAgentType:m.target.value,name:(f==null?void 0:f.name)??m.target.value})},className:fy,children:[s.jsx("option",{value:"",children:"— select —"}),n.filter(m=>m.subagent).map(m=>s.jsx("option",{value:m.id,children:m.name},m.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Prompt"}),s.jsx("textarea",{value:e.prompt??"",onChange:m=>a({...e,prompt:m.target.value||void 0}),rows:6,className:`${na} resize-y text-xs`,placeholder:"Injected on first entry..."}),s.jsx(my,{variables:o,onInsert:m=>a({...e,prompt:(e.prompt??"")+`{{${m}}}`})})]}),s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Nudge Prompt"}),s.jsx("textarea",{value:e.nudgePrompt??"",onChange:m=>a({...e,nudgePrompt:m.target.value||void 0}),rows:6,className:`${na} resize-y text-xs`,placeholder:"Injected on re-entry..."}),s.jsx(my,{variables:o,onInsert:m=>a({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${m}}}`})})]})]}),e.type==="shell"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Command"}),s.jsx("textarea",{value:e.command??"",onChange:m=>a({...e,command:m.target.value}),rows:3,className:`${na} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),s.jsx(my,{variables:o,onInsert:m=>a({...e,command:(e.command??"")+`{{${m}}}`})})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Timeout (ms)"}),s.jsx("input",{type:"number",value:e.timeout??6e4,onChange:m=>a({...e,timeout:Number(m.target.value)}),className:`${na} font-mono text-xs`})]}),s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Success Codes"}),s.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:m=>a({...e,successExitCodes:m.target.value.split(",").map(f=>Number(f.trim())).filter(f=>!isNaN(f))}),className:`${na} font-mono text-xs`})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:Ps,children:"Sub-group"}),s.jsx("input",{value:e.subGroup??"",onChange:m=>a({...e,subGroup:m.target.value||void 0}),placeholder:"e.g. build, verify, review",className:na})]}),s.jsx("div",{className:"pt-1 border-t border-border/50",children:s.jsxs("p",{className:"text-text-muted text-[10px]",children:[r," outgoing transition",r!==1?"s":""," — drag from the bottom port to connect."]})})]})}const gl="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",wj="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",ra="block text-[11px] text-text-secondary mb-0.5";function tq({fromLabel:e,toLabel:t,condition:n,subGroup:r,fromStep:o,agentTypes:a,transitionIndex:d,totalTransitions:l,onUpdateCondition:c,onUpdateSubGroup:h,onDelete:m,onMoveUp:f,onMoveDown:g}){var C;const x=o&&(o.type==="sub_agent"||o.type==="agent")?a.find(b=>b.id===(o.type==="sub_agent"?o.subAgentType:o.agentId)):void 0,w=(x==null?void 0:x.results)&&x.results.length>0;return s.jsxs("div",{className:"space-y-3 text-sm",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:["#",d+1]}),l>1&&s.jsxs("div",{className:"flex items-center gap-0.5",children:[s.jsx("button",{onClick:f,disabled:d===0,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move up (higher priority)",children:s.jsx(mn,{className:"w-3 h-3",rotate:180})}),s.jsx("button",{onClick:g,disabled:d===l-1,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move down (lower priority)",children:s.jsx(mn,{className:"w-3 h-3"})})]})]}),s.jsx("button",{onClick:m,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),s.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:e}),s.jsx(am,{}),s.jsx("span",{className:"font-medium text-text-primary",children:t})]}),s.jsxs("div",{children:[s.jsx("label",{className:ra,children:"Condition"}),s.jsx("select",{value:n.type,onChange:b=>{c(b.target.value==="step_result"?{type:"step_result",result:"success"}:{type:b.target.value})},className:wj,children:_L.map(b=>s.jsx("option",{value:b.value,children:b.label},b.value))})]}),n.type==="step_result"&&s.jsxs("div",{children:[s.jsx("label",{className:ra,children:"Result"}),w?s.jsx("select",{value:n.result??x.results[0],onChange:b=>{c({type:"step_result",result:b.target.value})},className:wj,children:x.results.map(b=>s.jsx("option",{value:b,children:b},b))}):s.jsx("input",{type:"text",value:n.result??"success",onChange:b=>c({type:"step_result",result:b.target.value}),placeholder:"e.g. success, passed, failed",className:gl})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:ra,children:"Metadata Key"}),s.jsx("input",{type:"text",value:n.key??"",onChange:b=>c({...n,key:b.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:gl})]}),s.jsxs("div",{children:[s.jsx("label",{className:ra,children:"Field"}),s.jsx("input",{type:"text",value:n.field??"",onChange:b=>c({...n,field:b.target.value}),placeholder:"e.g. status",className:gl})]}),n.type==="metadata_all_match"?s.jsxs("div",{children:[s.jsx("label",{className:ra,children:"Value"}),s.jsx("input",{type:"text",value:n.value??"",onChange:b=>c({...n,value:b.target.value}),placeholder:"e.g. passed, resolved",className:gl})]}):s.jsxs("div",{children:[s.jsx("label",{className:ra,children:"Values (comma-separated)"}),s.jsx("input",{type:"text",value:((C=n.values)==null?void 0:C.join(", "))??"",onChange:b=>c({...n,values:b.target.value.split(",").map(S=>S.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:gl})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:ra,children:"Sub-group"}),s.jsx("input",{type:"text",value:r??"",onChange:b=>h(b.target.value||void 0),placeholder:"e.g. build, verify",className:gl})]}),(o==null?void 0:o.type)==="user"&&s.jsxs("div",{className:"pt-1 border-t border-border/50 space-y-1",children:[s.jsx("p",{className:"text-text-muted text-[10px]",children:'On a user step, each "Step result is..." transition becomes a choice button; "Always" becomes a Continue button.'}),n.type==="step_result"&&o.transitions.filter(b=>b.when.type==="step_result"&&b.when.result===n.result).length>1&&s.jsxs("p",{className:"text-accent-warning text-[10px]",children:['Duplicate result "',n.result,'" — only the first matching transition is reachable.']}),n.type==="step_result"&&n.result==="continue"&&s.jsx("p",{className:"text-accent-warning text-[10px]",children:'"continue" is reserved for the "Always" Continue button — rename this result.'}),n.type==="always"&&o.transitions.some((b,S)=>S>d&&b.when.type==="step_result")&&s.jsx("p",{className:"text-accent-warning text-[10px]",children:'This "Always" transition comes before one or more choice transitions — those choice buttons are unreachable. Move it to the end.'}),n.type==="always"&&o.transitions.filter(b=>b.when.type==="always").length>1&&s.jsx("p",{className:"text-accent-warning text-[10px]",children:'Multiple "Always" transitions — only the first is reachable.'})]}),s.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function nq(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function rq(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const uu="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",Cj="w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary",xl="block text-[11px] text-text-secondary mb-0.5",kj=[];function SL({isOpen:e,onClose:t,initialEditId:n,projectDir:r}){var qe,Be;const o=Pt(me=>me.defaults),a=Pt(me=>me.userItems),d=Pt(me=>me.projectItems),l=Pt(me=>me.loading),c=Pt(me=>me.templateVariables),h=Pt(me=>me.fetchWorkflows),m=Pt(me=>me.fetchWorkflow),f=Pt(me=>me.fetchDefaultContent),g=Pt(me=>me.fetchTemplateVariables),x=Pt(me=>me.createWorkflow),w=Pt(me=>me.updateWorkflow),C=Pt(me=>me.deleteWorkflow),{requestDelete:b,clearConfirm:S,isConfirming:_}=Hu(),[v,k]=j.useState("list"),[E,T]=j.useState(null),[L,A]=j.useState(void 0),[M,I]=j.useState(!1),[U,P]=j.useState(null),[z,K]=j.useState(null),[H,F]=j.useState(""),[Q,Z]=j.useState(""),[V,B]=j.useState(""),[D,O]=j.useState("1.0.0"),[$,J]=j.useState("#3b82f6"),[X,Y]=j.useState(""),[q,W]=j.useState(50),[ee,ie]=j.useState(kj),[re,se]=j.useState({type:"always"}),[de,Se]=j.useState([]),[Me,ye]=j.useState("user"),[ue,Ie]=j.useState(""),[We,Qe]=j.useState(!1),{data:ve}=Mi(er,r),oe=j.useMemo(()=>ve?[...ve.defaults,...ve.userItems,...ve.projectItems]:[],[ve]),[ae]=j.useState(null);j.useEffect(()=>{e&&(h(r),g(),P(null),K(null),n?o.some(xe=>xe.id===n)?f(n,r).then(xe=>{xe&&we({...xe,metadata:{...xe.metadata,name:xe.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):m(n,r).then(xe=>{xe&&we(xe,{editingId:n,isReadOnly:!1})}):(k("list"),T(null),I(!1)))},[e,h,m,f,g,n,r]);const we=(me,xe)=>{F(me.metadata.name),Z(me.metadata.id),B(me.metadata.description),O(me.metadata.version),J(me.metadata.color??"#3b82f6"),Y(me.entryStep),W(me.settings.maxIterations),ie(me.steps),se(me.startCondition??{type:"always"}),Se(me.metadata.parameters??[]),Ie(""),(xe==null?void 0:xe.editingId)!==void 0&&T(xe.editingId),(xe==null?void 0:xe.isReadOnly)!==void 0&&I(xe.isReadOnly),(xe==null?void 0:xe.selectedNodeKey)!==void 0&&P(null),(xe==null?void 0:xe.selectedEdgeKey)!==void 0&&K(null),k("edit")},$e=async(me,xe)=>{A(xe);const He=await m(me,r,xe);He&&we(He,{editingId:me,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},fe=async()=>{var ut;const me=E??Q;if(!me||!H)return Ie("Name is required."),!1;if(ee.length===0)return Ie("Add at least one step."),!1;const xe=de.find(ht=>!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(ht.id));if(xe)return Ie(`Invalid parameter ID "${xe.id}". Use letters, digits, and underscores only.`),!1;let He=X;if(!He||!ee.some(ht=>ht.id===He)){if(He=((ut=ee.find(ht=>ht.id))==null?void 0:ut.id)??"",!He)return Ie("All steps need an ID."),!1;Y(He)}Qe(!0),Ie("");const Ue={metadata:{id:me,name:H,description:V,version:D||"1.0.0",color:$,...de.length>0?{parameters:de}:{}},entryStep:He,settings:{maxIterations:q},steps:ee,startCondition:re},et=E?await w(E,Ue,r,L):await x(Ue,Me,r);return Qe(!1),et.success?(E||T(me),!0):(Ie(et.error??"Failed to save."),!1)},Ae=async()=>{await fe()},Xe=async()=>{await fe()&&(n?t():k("list"))},tt=()=>{n?t():k("list")},pe=me=>{F(me),E||Z(nq(me))},Ge=async(me,xe)=>o.some(Ue=>Ue.id===me)?await f(me,r):await m(me,r,xe),Je=async(me,xe)=>{const He=await Ge(me,xe);He&&we({...He,metadata:{...He.metadata,name:He.metadata.name+" (copy)",id:`${me}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},ot=()=>{T(null),A(void 0),F(""),Z(""),B(""),O("1.0.0"),J("#3b82f6"),Y(""),W(50),ie(structuredClone(kj)),se({type:"always"}),Se([]),ye("user"),Ie(""),P(null),K(null),I(!1),k("edit")},Ze=async(me,xe)=>{await C(me,xe,r),S()},at=j.useCallback(me=>{P(me),K(null)},[]),ce=j.useCallback(me=>{K(me),P(null)},[]),Oe=U!==null?Number(U):-1,Ve=Oe>=0?ee[Oe]??null:null,De=j.useCallback(me=>{ie(xe=>xe.map((He,Ue)=>Ue===Oe?me:He))},[Oe]),st=re.type==="step_result"?`${re.result}`:re.type==="metadata_all_match"?`${re.key??"?"}=${re.value??"?"}`:re.type==="metadata_all_in"?`${re.key??"?"} in [${((qe=re.values)==null?void 0:qe.join(","))??"?"}]`:vL[re.type]??re.type,rt=()=>{const me=ee.length,xe=rq(ee),He=oe.find(Ue=>!Ue.subagent);ie([...ee,{id:xe,name:(He==null?void 0:He.name)??"Agent",type:"agent",phase:"build",agentId:(He==null?void 0:He.id)??"builder",transitions:[]}]),X||Y(xe),at(String(me))},yt=j.useCallback((me,xe)=>{me==="$start"?(Y(xe),ce("start")):ie(He=>{const Ue=He.find(ut=>ut.id===me),et=Ue?Ue.transitions.length:0;return ce(`${me}:${et}`),He.map(ut=>ut.id===me?{...ut,transitions:[...ut.transitions,{when:{type:"always"},goto:xe}]}:ut)})},[ce]),kt=me=>{if(me==="start")return null;const xe=me.lastIndexOf(":"),He=me.slice(0,xe),Ue=parseInt(me.slice(xe+1));return{stepId:He,transIdx:Ue}},qt=j.useCallback((me,xe)=>{const He=kt(me);He&&ie(Ue=>Ue.map(et=>et.id===He.stepId?{...et,transitions:et.transitions.map((ut,ht)=>ht===He.transIdx?xe(ut):ut)}:et))},[]),Mn=j.useCallback((me,xe)=>{if(me==="start"){Y(xe);return}qt(me,He=>({...He,goto:xe}))},[qt]),qn=j.useCallback((me,xe)=>{const He=kt(me);He&&(ie(Ue=>{const et=Ue.find(ht=>ht.id===He.stepId);if(!et)return Ue;const ut=et.transitions[He.transIdx];return ut?Ue.map(ht=>ht.id===He.stepId?{...ht,transitions:ht.transitions.filter((Xt,pn)=>pn!==He.transIdx)}:ht.id===xe?{...ht,transitions:[...ht.transitions,ut]}:ht):Ue}),K(null))},[]),In=j.useCallback(me=>{if(me==="start"){Y(""),K(null);return}const xe=kt(me);xe&&(ie(He=>He.map(Ue=>Ue.id===xe.stepId?{...Ue,transitions:Ue.transitions.filter((et,ut)=>ut!==xe.transIdx)}:Ue)),K(null))},[]),hr=j.useCallback((me,xe)=>{if(me==="start"){se(xe);return}qt(me,He=>({...He,when:xe}))},[qt]),Nr=j.useCallback((me,xe)=>{me!=="start"&&qt(me,He=>({...He,subGroup:xe||void 0}))},[qt]),Ee=me=>n_(me,oe).name,nt=()=>{if(!z)return null;if(z==="start"){const Xt=ee.find(pn=>pn.id===X);return{type:"start",fromLabel:"Start",toLabel:Xt?Ee(Xt):"(none)",condition:re}}const me=z.lastIndexOf(":"),xe=z.slice(0,me),He=parseInt(z.slice(me+1)),Ue=ee.find(Xt=>Xt.id===xe);if(!Ue)return null;const et=Ue.transitions[He];if(!et)return null;const ut=ee.find(Xt=>Xt.id===et.goto),ht=et.goto==="$done"?"Done":ut?Ee(ut):et.goto;return{type:"step",fromLabel:Ee(Ue),toLabel:ht,condition:et.when,subGroup:et.subGroup}};if(v==="edit"){const me=nt();return s.jsxs(vt,{isOpen:e,onClose:tt,title:M?H:E?"Edit Workflow":"New Workflow",size:"full",footer:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ct,{variant:"secondary",onClick:tt,children:"Close"}),M?s.jsx(ct,{variant:"primary",onClick:()=>{F(H+" (copy)"),Z(`${E}-copy-${Date.now()}`),T(null),I(!1)},children:"Duplicate & Customize"}):s.jsxs(s.Fragment,{children:[s.jsx(ct,{variant:"primary",onClick:Ae,children:"Save"}),s.jsx(ct,{variant:"primary",onClick:Xe,children:"Save & Close"})]})]}),children:[ue&&s.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:ue}),s.jsx(JG,{formName:H,formId:Q,formDescription:V,formMaxIterations:q,formColor:$,isReadOnly:M,onNameChange:pe,onDescriptionChange:B,onMaxIterationsChange:W,onColorChange:J}),!M&&s.jsx("div",{className:"mb-3 pb-3 border-b border-border",children:s.jsxs(KG,{title:`Parameters (${de.length})`,children:[de.map((xe,He)=>s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{value:xe.id,onChange:Ue=>{const et=[...de];et[He]={...xe,id:Ue.target.value},Se(et)},placeholder:"ID",className:"w-28 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"}),s.jsx("input",{value:xe.label,onChange:Ue=>{const et=[...de];et[He]={...xe,label:Ue.target.value},Se(et)},placeholder:"Label",className:"w-36 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary"}),s.jsx("input",{value:xe.description??"",onChange:Ue=>{const et=[...de];et[He]={...xe,description:Ue.target.value||void 0},Se(et)},placeholder:"Description",className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-muted whitespace-nowrap",children:[s.jsx("input",{type:"checkbox",checked:xe.required??!1,onChange:Ue=>{const et=[...de];et[He]={...xe,required:Ue.target.checked||void 0},Se(et)},className:"rounded border-border"}),"Req."]}),s.jsxs("div",{className:"flex gap-0.5",children:[s.jsx("button",{onClick:()=>{He!==0&&Se(de.map((Ue,et)=>et===He?{...de[He-1],position:et}:et===He-1?{...de[He],position:et}:{...Ue,position:et}))},disabled:He===0,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move up","aria-label":`Move ${xe.label||xe.id} up`,children:"▲"}),s.jsx("button",{onClick:()=>{He!==de.length-1&&Se(de.map((Ue,et)=>et===He?{...de[He+1],position:et}:et===He+1?{...de[He],position:et}:{...Ue,position:et}))},disabled:He===de.length-1,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move down","aria-label":`Move ${xe.label||xe.id} down`,children:"▼"})]}),s.jsx("button",{onClick:()=>Se(de.filter((Ue,et)=>et!==He)),className:"p-1 text-text-muted hover:text-accent-error transition-colors",title:"Remove parameter",children:"✕"})]},xe.id)),s.jsx("button",{onClick:()=>{const xe=`param_${de.length+1}`;Se([...de,{id:xe,label:"",description:"",required:!1}])},className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:"+ Add parameter"})]})}),!E&&!M&&s.jsx(pm,{value:Me,onChange:ye}),s.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[s.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!M&&s.jsx("button",{onClick:rt,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),s.jsxs(xt,{className:"flex-1 min-h-0 p-2",children:[s.jsx(QG,{steps:ee,entryStep:X,selectedNodeId:(Ve==null?void 0:Ve.id)??null,selectedEdgeKey:z,startConditionLabel:st,agentTypes:oe,isReadOnly:M,onSelectNode:xe=>{if(xe===null){at(null);return}const He=ee.findIndex(Ue=>Ue.id===xe);at(He>=0?String(He):null)},onSelectEdge:ce,onRemoveStep:xe=>{var Ue;const He=ee.findIndex(et=>et.id===xe);if(ie(et=>et.filter(ut=>ut.id!==xe)),Oe===He&&at(null),X===xe){const et=ee.filter(ut=>ut.id!==xe);Y(((Ue=et[0])==null?void 0:Ue.id)??"")}},onCreateTransition:yt,onReconnectTo:Mn,onReconnectFrom:qn,onDeleteTransition:In}),ee.length===0&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[s.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),s.jsx("button",{onClick:rt,className:"px-3 py-1.5 rounded bg-accent-primary/10 text-accent-primary text-xs hover:bg-accent-primary/20",children:"+ Add your first step"})]})]})]}),s.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[s.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),s.jsx(xt,{className:"p-3 flex-1 min-h-0",children:M&&(me||Ve)?s.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):me?me.type==="start"?s.jsxs("div",{className:"space-y-3 text-sm",children:[s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),X&&s.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),s.jsx(am,{}),s.jsx("span",{className:"text-text-primary font-medium",children:me.toLabel})]}),s.jsxs("div",{children:[s.jsx("label",{className:xl,children:"Activation Condition"}),s.jsx("select",{value:re.type,onChange:xe=>se(xe.target.value==="step_result"?{type:"step_result",result:"success"}:xe.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:xe.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:xe.target.value}),className:Cj,children:_L.map(xe=>s.jsx("option",{value:xe.value,children:xe.label},xe.value))})]}),re.type==="step_result"&&s.jsxs("div",{children:[s.jsx("label",{className:xl,children:"Result"}),X&&(()=>{const xe=ee.find(ut=>ut.id===X),He=xe&&(xe.type==="sub_agent"||xe.type==="agent")?oe.find(ut=>ut.id===(xe.type==="sub_agent"?xe.subAgentType:xe.agentId)):void 0,Ue=(He==null?void 0:He.results)&&He.results.length>0,et=(He==null?void 0:He.results)??[];return Ue?s.jsx("select",{value:re.result??et[0],onChange:ut=>se({type:"step_result",result:ut.target.value}),className:Cj,children:et.map(ut=>s.jsx("option",{value:ut,children:ut},ut))}):s.jsx("input",{type:"text",value:re.result??"success",onChange:ut=>se({type:"step_result",result:ut.target.value}),placeholder:"e.g. success, passed, failed",className:uu})})()]}),(re.type==="metadata_all_match"||re.type==="metadata_all_in")&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:xl,children:"Metadata Key"}),s.jsx("input",{type:"text",value:re.key??"",onChange:xe=>se({...re,key:xe.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:uu})]}),s.jsxs("div",{children:[s.jsx("label",{className:xl,children:"Field"}),s.jsx("input",{type:"text",value:re.field??"",onChange:xe=>se({...re,field:xe.target.value}),placeholder:"e.g. status",className:uu})]}),re.type==="metadata_all_match"?s.jsxs("div",{children:[s.jsx("label",{className:xl,children:"Value"}),s.jsx("input",{type:"text",value:re.value??"",onChange:xe=>se({...re,value:xe.target.value}),placeholder:"e.g. passed, resolved",className:uu})]}):s.jsxs("div",{children:[s.jsx("label",{className:xl,children:"Values (comma-separated)"}),s.jsx("input",{type:"text",value:((Be=re.values)==null?void 0:Be.join(", "))??"",onChange:xe=>se({...re,values:xe.target.value.split(",").map(He=>He.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:uu})]})]}),s.jsx("p",{className:"text-text-muted text-[10px]",children:"Workflow only proceeds when this condition is met. Drag the target handle to change entry step."})]}):(()=>{const xe=kt(z),He=xe==null?void 0:xe.stepId,Ue=(xe==null?void 0:xe.transIdx)??0,et=He?ee.find(ht=>ht.id===He):void 0,ut=(et==null?void 0:et.transitions.length)??0;return s.jsx(tq,{fromLabel:me.fromLabel,toLabel:me.toLabel,condition:me.condition,subGroup:"subGroup"in me?me.subGroup:void 0,fromStep:me.type==="step"?ee.find(ht=>ht.id===me.fromLabel):void 0,agentTypes:oe,transitionIndex:Ue,totalTransitions:ut,onUpdateCondition:ht=>hr(z,ht),onUpdateSubGroup:ht=>Nr(z,ht),onDelete:()=>In(z),onMoveUp:()=>{ie(ht=>{const Xt=ht.find(kn=>kn.id===He);if(!Xt||Ue===0)return ht;const pn=[...Xt.transitions];return[pn[Ue-1],pn[Ue]]=[pn[Ue],pn[Ue-1]],ht.map(kn=>kn.id===He?{...kn,transitions:pn}:kn)}),K(`${He}:${Ue-1}`)},onMoveDown:()=>{ie(ht=>{const Xt=ht.find(kn=>kn.id===He);if(!Xt||Ue===Xt.transitions.length-1)return ht;const pn=[...Xt.transitions];return[pn[Ue],pn[Ue+1]]=[pn[Ue+1],pn[Ue]],ht.map(kn=>kn.id===He?{...kn,transitions:pn}:kn)}),K(`${He}:${Ue+1}`)}})})():Ve?s.jsx(eq,{step:Ve,isEntry:Ve.id===X,agentTypes:oe,transitionCount:Ve.transitions.length,templateVariables:c,onUpdate:De,onRemove:()=>{var xe;if(Ve&&(ie(ee.filter((He,Ue)=>Ue!==Oe)),at(null),X===Ve.id)){const He=ee.filter((Ue,et)=>et!==Oe);Y(((xe=He[0])==null?void 0:xe.id)??"")}},onSetEntry:()=>Y(Ve.id)}):s.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",s.jsx("br",{}),"Drag from a port to connect."]})})]})]})]})}return s.jsx(vt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:s.jsx(uN,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:ot,loading:l,hasItems:o.length>0||a.length>0||d.length>0,children:s.jsxs("div",{className:"space-y-4",children:[s.jsx(hy,{title:"Built-in",items:o,renderActions:me=>s.jsx(s.Fragment,{children:s.jsx(Li,{onClick:()=>Je(me.id),children:s.jsx(Kb,{})})})}),s.jsx(hy,{title:"Custom",items:a,renderActions:me=>s.jsxs(s.Fragment,{children:[s.jsx(Li,{onClick:()=>$e(me.id,"user"),children:s.jsx("span",{className:"text-[10px]",children:"Edit"})}),s.jsx(Lu,{onClick:()=>Je(me.id,"user")}),_(`user:${me.id}`,"delete")?s.jsx(gf,{onConfirm:()=>Ze(me.id,"user"),onCancel:S}):s.jsx(xf,{onClick:()=>b(`user:${me.id}`)})]})}),d.length>0&&s.jsx(hy,{title:"Project",items:d,renderActions:me=>s.jsxs(s.Fragment,{children:[s.jsx(Li,{onClick:()=>$e(me.id,"project"),children:s.jsx("span",{className:"text-[10px]",children:"Edit"})}),s.jsx(Lu,{onClick:()=>Je(me.id,"project")}),_(`project:${me.id}`,"delete")?s.jsx(gf,{onConfirm:()=>Ze(me.id,"project"),onCancel:S}):s.jsx(xf,{onClick:()=>b(`project:${me.id}`)})]})})]})})})}function wL({searchValue:e,onSearchChange:t,onSearchKeyDown:n,placeholder:r,searchRef:o,icon:a,children:d,rows:l,emptyText:c,listRef:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-2 pb-2 shrink-0",children:[a,s.jsx("input",{ref:o,type:"text",value:e,onChange:m=>t(m.target.value),onKeyDown:n,placeholder:r,className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"})]}),d,s.jsx(xt,{ref:h,className:"flex-1 min-h-0 -mx-4 -mb-4 px-4 pb-4",children:l.length===0?s.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:c}):l})]})}const r_=j.forwardRef(({selected:e,unselectedClassName:t="text-text-secondary hover:bg-bg-tertiary hover:text-text-primary",className:n="",...r},o)=>s.jsx("button",{ref:o,type:"button",className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${e?"bg-accent-primary/20 text-text-primary":t} ${n}`,...r}));r_.displayName="SelectableListButton";function sq(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function iq({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:r,onSelectWorkflow:o,onCloseCompleteAction:a,textareaContent:d,onSearchMessages:l,onToggleAutoScroll:c,isAutoScrollActive:h}){const[,m]=Wn(),f=ln(O=>O.fetchCommands),g=Pt(O=>O.fetchWorkflows),x=ln(O=>O.defaults),w=ln(O=>O.userItems),C=ln(O=>O.projectItems),b=Pt(O=>O.defaults),S=Pt(O=>O.userItems),_=Pt(O=>O.projectItems),v=Vr(),k=Vt(v,O=>{var $;return(($=O.session)==null?void 0:$.mode)??null},O=>{var $;return(($=O.currentSession)==null?void 0:$.mode)??null},null),E=Vt(v,O=>{var $;return(($=O.session)==null?void 0:$.dangerLevel)??"normal"},O=>{var $;return(($=O.currentSession)==null?void 0:$.dangerLevel)??"normal"},"normal"),T=Re(O=>O.switchMode),L=Re(O=>O.switchDangerLevel),A=Vt(v,O=>{var $;return(($=O.session)==null?void 0:$.projectId)??null},O=>{var $;return(($=O.currentSession)==null?void 0:$.projectId)??null},null),M=Vt(v,O=>{var $;return(($=O.session)==null?void 0:$.workdir)??void 0},O=>{var $;return($=O.currentSession)==null?void 0:$.workdir},void 0),{agents:I}=Ii(M),U=j.useRef(void 0),[P,z]=j.useState(""),[K,H]=j.useState(0),F=j.useRef(null),Q=j.useRef(!1);j.useEffect(()=>{e&&(Q.current=!0)},[e]),j.useEffect(()=>{if(e){f(M),g(M),z(""),H(0);const O=setTimeout(()=>{var $;Wt()&&(($=F.current)==null||$.focus())},50);return()=>clearTimeout(O)}},[e,f,g,M]),j.useEffect(()=>{var O;!e&&Q.current&&(n==null||n(),(O=U.current)==null||O.call(U),U.current=void 0)},[e,n]);const V=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const O=A??sq(window.location.pathname);O&&m(`/p/${O}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{U.current=a,t()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{t(),l==null||l()}},{id:"toggle-autoscroll",name:h?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{t(),c==null||c(!h)}},...I.filter(O=>!O.subagent&&O.id!==k).map(O=>({id:O.id,name:O.name,prefix:"Agent > Switch to",action:()=>v&&T(v,O.id)})),...ir(ir(x,w),C).map(O=>({id:O.id,name:O.name,prefix:"Command > Launch",action:()=>r(O.id,d)})),...ir(ir(b,S),_).map(O=>({id:O.id,name:O.name,prefix:"Workflow > Run",action:()=>o(O.id,O.scope)})),...["normal","dangerous"].filter(O=>O!==E).map(O=>({id:O,name:O.charAt(0).toUpperCase()+O.slice(1),prefix:"Mode > Switch to",action:()=>v&&L(v,O)}))].filter(O=>bo(`${O.prefix} ${O.name}`,P)),B=V.length-1,D=O=>{qv(O,B,H,()=>{var $;($=V[K])==null||$.action(),t()},t)};return s.jsx(vt,{isOpen:e,onClose:t,title:"Quick Actions",size:"md",scrollable:!1,children:s.jsx(wL,{searchValue:P,onSearchChange:O=>{z(O),H(0)},onSearchKeyDown:D,placeholder:"Search...",searchRef:F,rows:V.map((O,$)=>s.jsxs(r_,{selected:$===K,onClick:()=>{O.action(),t()},children:[s.jsxs("span",{className:"text-text-muted font-normal",children:[O.prefix," "]}),s.jsx("span",{children:O.name})]},O.id)),emptyText:x.length+w.length+b.length+S.length>0?"No matches":"No agents, commands, or workflows yet"})})}const CL="openfox-message-search-filters",oq=[{key:"user",label:"User prompts"},{key:"thinking",label:"Thinking"},{key:"response",label:"Responses"}];function aq(){try{const e=localStorage.getItem(CL);if(e){const t=JSON.parse(e);return new Set(t)}}catch{}return new Set(["user","thinking","response"])}function lq(e){localStorage.setItem(CL,JSON.stringify([...e]))}function cq(e){var n,r;if(e.type!=="message")return null;const t=e.message;if(t.role==="user")return"user";if(t.role==="assistant"){if((n=t.content)!=null&&n.trim())return"response";if((r=t.thinkingContent)!=null&&r.trim())return"thinking"}return null}function uq(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear())return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const o=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),d=String(t.getDate()).padStart(2,"0"),l=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0");return`${o}/${a}/${d} ${l}:${c}`}function dq(e){var t;if(e.type==="message")return e.message.timestamp;if(e.type==="subagent")return(t=e.messages[0])==null?void 0:t.timestamp}function hq(e){var t,n;if(e.type==="message"){const r=e.message;if(r.role==="assistant"){const o=(t=r.content)==null?void 0:t.trim();return((n=r.thinkingContent)==null?void 0:n.trim())&&!o?"italic text-text-muted":""}if(r.role==="user")return"font-bold"}return""}function fq(e){var n,r;if(e.type!=="message")return s.jsx(K1,{className:"w-3.5 h-3.5"});const t=e.message;return t.role==="assistant"?(n=t.thinkingContent)!=null&&n.trim()&&!((r=t.content)!=null&&r.trim())?s.jsx(YO,{className:"w-3.5 h-3.5"}):s.jsx(K1,{className:"w-3.5 h-3.5"}):s.jsx(KO,{className:"w-3.5 h-3.5"})}function jj(e){var t;if(e.type==="message"){const n=e.message,r=n.content||"",o=r.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(n.messageKind==="workflow-started")try{return`Workflow: ${JSON.parse(r).workflowName}`}catch{return"Workflow started"}if(n.messageKind==="task-completed")return"Task completed";if(n.messageKind==="auto-prompt")return"Auto-prompt";if(n.messageKind==="correction")return"Correction";if(n.messageKind==="context-reset")return"Context reset";if(n.messageKind==="command")return"Command executed";if(n.role==="assistant")return o?o.slice(0,200):(t=n.thinkingContent)!=null&&t.trim()?n.thinkingContent.slice(0,200):"";const a=o.slice(0,200);return a.length<o.length?`${a}...`:a}return e.type==="subagent"?`Sub-agent: ${e.subAgentType}`:""}function mq({isOpen:e,onClose:t,displayItems:n,onNavigate:r}){const[o,a]=j.useState(""),[d,l]=j.useState(0),[c,h]=j.useState(aq),m=j.useRef(null),f=j.useRef(null),g=j.useRef(null),x=E=>{h(T=>{const L=new Set(T);return L.has(E)?L.delete(E):L.add(E),lq(L),L})},w=j.useMemo(()=>n.filter(E=>{var T,L;return!(E.type==="context-divider"||E.type==="message"&&(E.message.messageKind==="auto-prompt"||E.message.role==="assistant"&&!((T=E.message.content)!=null&&T.trim())&&!((L=E.message.thinkingContent)!=null&&L.trim())))}),[n]),C=j.useMemo(()=>w.filter(E=>{const T=cq(E);return!(T&&!c.has(T))}),[w,c]),b=j.useMemo(()=>o?w.filter(E=>{const T=jj(E);return bo(T,o)}):C,[C,o]),S=b.length-1;j.useEffect(()=>{if(e){a(""),l(0);const E=setTimeout(()=>{var T;Wt()&&((T=m.current)==null||T.focus())},50);return()=>clearTimeout(E)}},[e]),j.useEffect(()=>{var E;if(e&&f.current){const T=(E=f.current.osInstance())==null?void 0:E.elements().viewport;T&&(T.scrollTop=T.scrollHeight)}},[e]),j.useEffect(()=>{g.current&&g.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[d]);const _=E=>{qv(E,S,l,()=>{const T=b[d];if(T){const L=n.indexOf(T);L>=0&&r(L),t()}},t)},v=E=>{const T=n.indexOf(E);T>=0&&r(T),t()},k=E=>n.indexOf(E);return s.jsx(vt,{isOpen:e,onClose:t,title:"Search timeline",size:"md",scrollable:!1,children:s.jsx(wL,{searchValue:o,onSearchChange:E=>{a(E),l(0)},onSearchKeyDown:_,placeholder:"Search timeline...",searchRef:m,icon:s.jsx(Gs,{}),listRef:f,rows:b.map((E,T)=>{const L=k(E),A=fq(E),M=jj(E),I=hq(E),U=dq(E),P=E.type==="message"&&E.message.role==="user";return s.jsx(r_,{ref:T===d?g:null,selected:T===d,onClick:()=>v(E),...P?{unselectedClassName:"bg-accent-primary/5 text-text-secondary hover:bg-accent-primary/10 hover:text-text-primary"}:{},children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[s.jsx("span",{className:"flex-shrink-0",children:A}),s.jsx("span",{className:`truncate flex-1 ${I}`,children:M})]}),U&&s.jsx("span",{className:"text-text-muted text-xs shrink-0",children:uq(U)})]})},`${L}-${E.type}`)}),emptyText:C.length>0?"No matches":"No messages yet",children:s.jsx("div",{className:"flex gap-1.5 pb-3 shrink-0",children:oq.map(E=>{const T=c.has(E.key);return s.jsx("button",{type:"button",onClick:()=>x(E.key),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${T?"bg-accent-primary/20 text-accent-primary border border-accent-primary/40":"bg-bg-tertiary text-text-muted border border-border hover:text-text-secondary"}`,children:E.label},E.key)})})})})}function kL(e){const t=new Set,n=[],r=/\{\{(\w+)\}\}/g;let o;for(;(o=r.exec(e))!==null;){const a=o[1];t.has(a)||(t.add(a),n.push(a))}return n}function pq(e,t,n){const r=e.trim();if(!r.startsWith("/"))return null;const o=r.slice(1).split(/\s+/),a=o[0];if(!a)return null;const d=o.slice(1),l={},c=t.find(h=>h.id===a);return c?(c.parameters&&c.parameters.length>0?[...c.parameters].sort((m,f)=>(m.position??0)-(f.position??0)).forEach((m,f)=>{d[f]!==void 0&&(l[m.id]=d[f])}):d.forEach((h,m)=>{l[String(m)]=h}),{workflowId:a,params:l}):n&&n.find(m=>m.id===a)?(d.forEach((m,f)=>{l[String(f)]=m}),{commandId:a,params:l}):null}function gq({history:e,selectedIndex:t,onSelect:n,onEscape:r,onNavigate:o}){const a=j.useRef(null),d=j.useRef(null);j.useEffect(()=>{var h;d.current&&((h=a.current)!=null&&h.getElement())&&d.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[t]);const l=h=>{switch(h.key){case"Enter":h.preventDefault(),e[t]&&n(e[t].content);break;case"Escape":h.preventDefault(),r();break;case"ArrowUp":h.preventDefault(),o("up");break;case"ArrowDown":h.preventDefault(),o("down");break}},c=h=>{n(h)};return s.jsx(xt,{ref:a,role:"list",className:"mb-2 p-2 bg-bg-secondary border border-border rounded-lg max-h-64",onKeyDown:l,children:e.map((h,m)=>s.jsxs("div",{ref:m===t?d:null,role:"listitem",onClick:()=>c(h.content),className:`
|
|
303
303
|
p-2 rounded cursor-pointer transition-colors
|
|
304
304
|
${m===t?"bg-accent-primary/20 border border-accent-primary":"hover:bg-bg-tertiary"}
|
|
305
|
-
`,children:[s.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[h.formattedTimestamp,h.sessionName&&s.jsxs(s.Fragment,{children:[" | ",s.jsx("span",{className:"text-accent-primary font-medium",children:h.sessionName})]})]}),s.jsx("div",{className:"text-sm text-text-primary mt-1",children:h.trimmedContent})]},h.id))})}function xq(e){const{phase:t,isRunning:n,pendingQuestionsCount:r,pendingConfirmationsCount:o,activeWorkflow:a}=e;let d=null;t==="waiting"||r>0||o>0?d="waiting":t==="blocked"?d="blocked":t==="done"&&!n?d="completed":n&&(d="running");const l=r>0||o>0,c=(a==null?void 0:a.currentStepName)??null;return{state:d,waitingForUser:l,workflowStep:c,lastPromptAt:null}}function yq(e){if(!e||e.length===0)return null;for(let t=e.length-1;t>=0;t--){const n=e[t];if(!(!n||n.role!=="user")&&(n.messageKind==="workflow-started"||!n.isSystemGenerated&&!n.messageKind))return n.timestamp}return null}function bq(e){const{currentSession:t,messages:n=[],pendingQuestions:r,pendingPathConfirmations:o,activeWorkflowExecution:a}=e;return t?{...xq({phase:t.phase,isRunning:t.isRunning,pendingQuestionsCount:(r==null?void 0:r.length)??0,pendingConfirmationsCount:(o==null?void 0:o.length)??0,activeWorkflow:a}),lastPromptAt:yq(n)}:{state:null,waitingForUser:!1,workflowStep:null,lastPromptAt:null}}function vq(e){switch(e){case"running":return"Running";case"waiting":return"Waiting for input";case"completed":return"Completed";case"blocked":return"Blocked";case null:return""}}function _q(){const e=Re(C=>C.abortInProgress),t=Re(C=>C.currentSession),n=Re(C=>C.messages),r=Re(C=>C.pendingQuestions),o=Re(C=>C.pendingPathConfirmations),a=Re(C=>C.activeWorkflowExecution),d=bq({currentSession:t,messages:n,pendingQuestions:r,pendingPathConfirmations:o,activeWorkflowExecution:a}),l=d.state,c=d.lastPromptAt,[h,m]=j.useState(()=>Date.now());if(j.useEffect(()=>{if(!c)return;const C=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(C)},[c]),l===null)return null;const f=vq(l),g=e?"bg-amber-400":"bg-accent-primary",x=l==="running",w=c?pU(c,h):"";return s.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2","data-testid":"session-status-indicator","data-state":l,children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[x&&s.jsxs("span",{className:"flex gap-0.5",children:[s.jsx("span",{className:`w-1 h-1 rounded-full ${e?"":"animate-bounce"} ${g}`,style:{animationDelay:"0ms"}}),s.jsx("span",{className:`w-1 h-1 rounded-full ${e?"":"animate-bounce"} ${g}`,style:{animationDelay:"150ms"}}),s.jsx("span",{className:`w-1 h-1 rounded-full ${e?"":"animate-bounce"} ${g}`,style:{animationDelay:"300ms"}})]}),s.jsx("span",{className:"text-text-secondary",children:e&&l==="running"?`${f} (abort in progress)`:f})]}),!e&&l==="running"&&s.jsx("span",{className:"text-text-muted hidden sm:inline",children:"esc to interrupt"}),w&&s.jsx("span",{className:"text-text-muted hidden sm:inline","aria-label":"time since last prompt",children:w})]})}function Sq(){const e=Vr(),t=Vt(e,l=>l.activeWorkflowExecution??null,l=>l.activeWorkflowExecution,null),n=Re(l=>l.exitWorkflow),[r,o]=j.useState(!1);j.useEffect(()=>{o(!1)},[t==null?void 0:t.id]);const a=j.useCallback(()=>{r||!e||(o(!0),n(e))},[r,n,e]);if(!t||t.status!=="running"&&t.status!=="waiting")return null;const d=t.workflowColor&&/^#[0-9a-fA-F]{6}$/.test(t.workflowColor)?t.workflowColor:"#3b82f6";return s.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-xs border-b border-border",children:[s.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:d}}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:t.workflowName}),t.currentStepName&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"text-text-muted truncate",children:t.currentStepName})]}),s.jsx("div",{className:"ml-auto shrink-0",children:s.jsx("button",{onClick:a,disabled:r,className:"text-xs px-2 py-0.5 rounded text-text-tool-error hover:bg-text-tool-error/10 transition-colors disabled:opacity-50",children:r?"Exiting...":"✕ Exit"})})]})}const jL=j.createContext(null);function wq({children:e}){const[t,n]=j.useState(null),r=j.useCallback(d=>new Promise(l=>{n({info:d,resolve:l})}),[]),o=j.useCallback(d=>{n(l=>(l==null||l.resolve(d),null))},[]),a=j.useMemo(()=>({requestEffortSwitch:r}),[r]);return s.jsxs(jL.Provider,{value:a,children:[e,t&&s.jsxs(vt,{isOpen:!0,onClose:()=>o("keep"),title:"Reasoning effort change",size:"sm",children:[s.jsxs("p",{className:"text-sm text-text-secondary",children:[t.info.contextLabel?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-primary font-medium",children:t.info.contextLabel})," runs with reasoning effort ",s.jsx("code",{className:"text-accent-primary",children:t.info.toEffort}),Nj(t.info),"."]}):s.jsxs(s.Fragment,{children:["Switching the reasoning effort to ",s.jsx("code",{className:"text-accent-primary",children:t.info.toEffort}),Nj(t.info),"."]})," ","This may invalidate the LLM prefix cache — if it does, the next response will take longer while the context is reprocessed."]}),s.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[s.jsx(Ej,{onClick:()=>o("keep"),variant:"secondary",children:"Keep current reasoning effort"}),s.jsx(Ej,{onClick:()=>o("apply"),variant:"danger",children:"Apply the reasoning effort (invalidates cache)"})]})]})]})}function Ej({onClick:e,variant:t,children:n}){const r=t==="primary"?"px-3 py-1.5 text-sm rounded bg-accent-primary text-white hover:opacity-90 transition-colors":t==="danger"?"px-3 py-1.5 text-sm rounded bg-accent-error text-white hover:opacity-90 transition-colors":"px-3 py-1.5 text-sm rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors";return s.jsx("button",{type:"button",onClick:e,className:r,children:n})}function Nj(e){return!e.fromEffort||e.fromEffort===e.toEffort?null:s.jsxs(s.Fragment,{children:[" ","(currently ",s.jsx("code",{className:"text-text-primary",children:e.fromEffort}),")"]})}function EL(){const e=j.useContext(jL);if(!e)throw new Error("useEffortChangeGate must be used within EffortChangeGateProvider");return e}function NL(e){var z,K;const t=Vr(),n=e??t,r=Vt(n,H=>H.session??null,H=>H.currentSession,null),o=Vt(n,H=>H.contextState??null,H=>H.contextState,null),a=EL(),d=Gt(H=>H.providers),l=Gt(H=>H.defaultModelSelection),{data:c}=Mi(er,r==null?void 0:r.workdir),h=(c==null?void 0:c.modelOverrides)??{},m=r==null?void 0:r.mode,f=m?h[m]??void 0:void 0,g=f?Ca(f):void 0,x=g==null?void 0:g.reasoningEffort,w=!!(r!=null&&r.providerManual)&&!!(r!=null&&r.providerManualActive),C=(r==null?void 0:r.providerId)??null,b=(r==null?void 0:r.providerModel)??null,S=(l==null?void 0:l.split("/")[0])??null,_=(l==null?void 0:l.split("/").slice(1).join("/"))??null,v=w?C:(g==null?void 0:g.providerId)??C??S,k=w?b:(g==null?void 0:g.model)??b??_,E=v?(z=d.find(H=>H.id===v))==null?void 0:z.models.find(H=>H.id===k):void 0,T=(E==null?void 0:E.reasoningEffortOverride)??(E!=null&&E.thinkingEnabled?E.thinkingLevel:void 0),L=Kk({session:r,agentOverrideEffort:x,modelDefaultEffort:T}),A=w?C:C??S,M=w?b:b??_,I=A?(K=d.find(H=>H.id===A))==null?void 0:K.models.find(H=>H.id===M):void 0,U=(I==null?void 0:I.reasoningEffortOverride)??(I!=null&&I.thinkingEnabled?I.thinkingLevel:void 0),P=Kk({session:r,agentOverrideEffort:void 0,modelDefaultEffort:U});return{sessionId:n,currentEffort:L,sessionOwnEffort:P,warmCache:o==null?void 0:o.warmCache,gate:a,modelOverrides:h}}function TL(e){const{sessionId:t,currentEffort:n,sessionOwnEffort:r,warmCache:o,gate:a,modelOverrides:d}=NL(e),l=Re(m=>m.switchMode),c=Re(m=>m.pinSessionEffort),h=Re(m=>m.clearSessionEffortPin);return j.useCallback(async(m,f)=>{var w;if(!t)return;const x=((w=Ca(d[m]))==null?void 0:w.reasoningEffort)??r;x&&Uv({warmCache:o,currentEffort:n,proposedEffort:x})&&(await a.requestEffortSwitch({fromEffort:n,toEffort:x,contextLabel:f})==="keep"?n&&await c(t,n):await h(t)),await l(t,m)},[t,o,n,r,a,l,c,h,d])}function Cq(e){var n,r,o,a,d,l;const t=Re.getState();return e?((a=(o=(r=t.panes)==null?void 0:r[e])==null?void 0:o.session)==null?void 0:a.workdir)??(((d=t.currentSession)==null?void 0:d.id)===e?(l=t.currentSession)==null?void 0:l.workdir:void 0):(n=t.currentSession)==null?void 0:n.workdir}function AL(e,t){const n=Re(f=>f.sendMessage),r=Re(f=>f.launchWorkflow),o=Re(f=>f.pinSessionEffort),a=Re(f=>f.clearSessionEffortPin),{currentEffort:d,warmCache:l,gate:c}=NL(t),h=j.useCallback((f,g,x)=>{e(!0),t&&n(t,f,g,x)},[e,n,t]),m=j.useCallback(async(f,g,x,w,C,b="auto")=>{var S,_;if(e(!0),!!t){if(x&&l){const v=((S=K9(Cq(t)))==null?void 0:S.modelOverrides)??{};if(Object.values(v).some(E=>{var T;return(T=Ca(E))==null?void 0:T.reasoningEffort})){const E=ka(Pt.getState()),T=If(E,x,b);if(T){const L=await Pt.getState().fetchWorkflow(T.id,Pt.getState().workdir,T.scope),A=L?MU(L,w):void 0,M=A?(_=Ca(v[A]))==null?void 0:_.reasoningEffort:void 0;M&&Uv({warmCache:l,currentEffort:d,proposedEffort:M})&&(await c.requestEffortSwitch({fromEffort:d,toEffort:M,contextLabel:T.name})==="keep"?d&&await o(t,d):await a(t))}}}r(t,f,g,x,w,C,b)}},[e,r,t,l,d,c,o,a]);return{sendMessage:h,launchWorkflow:m}}function kq({children:e}){return Di.createPortal(e,document.body)}function jq(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function Eq({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:o,onAttach:a,textareaContent:d,attachments:l}){const[c,h]=j.useState(!1),[m,f]=j.useState("commands"),[g,x]=j.useState(""),[w,C]=j.useState(0),[b,S]=j.useState(null),[_,v]=j.useState(null),k=j.useRef(null),E=j.useRef(null),T=ln(O=>O.defaults),L=ln(O=>O.userItems),A=ln(O=>O.projectItems),M=ln(O=>O.fetchCommands),I=Pt(O=>O.fetchWorkflows),U=Re(O=>{var $;return($=O.currentSession)==null?void 0:$.workdir}),P=ir(ir(T,L),A),z=Ju();j.useEffect(()=>{c&&(m==="commands"?M(U):m==="workflows"&&I(U))},[c,m,M,I,U]),j.useEffect(()=>{c&&(x(""),C(0),requestAnimationFrame(()=>{var O;Wt()&&((O=k.current)==null||O.focus())}))},[c,m]),j.useEffect(()=>{if(!c)return;const O=$=>{var J;(J=E.current)!=null&&J.contains($.target)||h(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[c]);const K=O=>{switch(O.key){case"ArrowDown":O.preventDefault(),C($=>{const X=(m==="commands"?P:z).filter(Y=>{const q=g.toLowerCase();return!q||Y.name.toLowerCase().includes(q)});return Math.min($+1,X.length-1)});break;case"ArrowUp":O.preventDefault(),C($=>Math.max($-1,0));break;case"Enter":O.preventDefault();break;case"Escape":O.preventDefault(),h(!1);break}},H=O=>{x(O),C(0)},F=P.filter(O=>!g||O.name.toLowerCase().includes(g.toLowerCase())),Q=z.filter(O=>!g||O.name.toLowerCase().includes(g.toLowerCase())),Z=async O=>{const $=await ln.getState().fetchCommand(O,U);$&&e($.prompt,$.metadata.agentMode,d,l),h(!1)},V=(O,$)=>{t(O,$),h(!1)},B=(O,$)=>{$.stopPropagation(),h(!1),S(O)},D=(O,$)=>{$.stopPropagation(),h(!1),v(O)};return s.jsxs("div",{ref:E,className:"relative",children:[s.jsx("button",{type:"button",onClick:()=>h(!c),className:"px-1.5 py-2 rounded-r bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors border-l border-border/50",title:"More options",children:s.jsx(nN,{className:"w-4 h-4"})}),c&&s.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[s.jsxs("div",{className:"flex border-b border-border",children:[s.jsx("button",{type:"button",onClick:()=>{f("commands"),x(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${m==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),s.jsx("button",{type:"button",onClick:()=>{f("workflows"),x(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${m==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),s.jsx("button",{type:"button",onClick:()=>f("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${m==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),m!=="attach"&&s.jsx("div",{className:"p-2 border-b border-border",children:s.jsx("input",{ref:k,value:g,onChange:O=>H(O.target.value),onKeyDown:K,placeholder:m==="commands"?"Search commands...":"Search workflows...",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),s.jsx(xt,{className:"max-h-64 p-1",children:m==="commands"?F.length===0?s.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:P.length===0?"No commands yet":"No matches"}):F.map((O,$)=>s.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${$===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[s.jsx("button",{type:"button",onClick:()=>Z(O.id),className:"flex-1 text-left",children:s.jsx("div",{className:"text-sm text-text-primary font-medium",children:O.name})}),s.jsx(Li,{className:"opacity-0 group-hover:opacity-100",onClick:J=>B(O.id,J)})]},O.id)):m==="workflows"?Q.length===0?s.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:z.length===0?"No workflows yet":"No matches"}):Q.map((O,$)=>{const J=jq(O),X=O.color??"#3b82f6";return s.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${$===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[s.jsxs("button",{type:"button",onClick:()=>V(O.id,O.scope),className:"flex-1 text-left flex items-center gap-2",children:[s.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:X}}),s.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:O.name}),s.jsx("span",{className:"text-[10px] text-text-muted bg-bg-tertiary px-1.5 py-0.5 rounded whitespace-nowrap",children:Wv[O.scope]}),J!==null&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:J?"#22c55e":"#6b7280"},title:J?"Entry condition met":"Entry condition not met"})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[O.subGroups&&O.subGroups.length>0&&s.jsx(Nq,{subGroups:O.subGroups,onSelect:Y=>{h(!1),n(O.id,Y,O.scope)}}),s.jsx(Li,{className:"opacity-0 group-hover:opacity-100",onClick:Y=>D(O.id,Y)})]})]},`${O.id}-${O.scope}`)}):s.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>{a(),h(!1)},className:"flex items-center gap-2 px-4 py-2 rounded bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary transition-colors",children:[s.jsx(eN,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Attach file"})]}),s.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),m!=="attach"&&s.jsx("div",{className:"border-t border-border p-1",children:s.jsx("button",{type:"button",onClick:()=>{h(!1),m==="commands"?r():o()},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:m==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),s.jsx(bL,{isOpen:!!b,onClose:()=>S(null),initialEditId:b,projectDir:U}),s.jsx(SL,{isOpen:!!_,onClose:()=>v(null),initialEditId:_})]})}function Nq({subGroups:e,onSelect:t}){const[n,r]=j.useState(!1),[o,a]=j.useState({top:0,right:0}),d=j.useRef(null),l=j.useRef(null);zm(l,()=>r(!1),n);const c=h=>{if(h.stopPropagation(),!n&&d.current){const m=d.current.getBoundingClientRect();a({top:m.bottom+4,right:window.innerWidth-m.right})}r(!n)};return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:d,type:"button",onClick:c,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&s.jsx(kq,{children:s.jsx("div",{ref:l,onMouseDown:h=>h.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:o.top,right:o.right},children:e.map(h=>s.jsx("button",{type:"button",onClick:m=>{m.stopPropagation(),t(h)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:h},h))})})]})}function Tq({messages:e,onCancel:t}){return e.length===0?null:s.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>s.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[s.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),s.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),s.jsx(Qu,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function Aq({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:r,model:o,onView:a,onEdit:d,onDuplicate:l,onDelete:c,onCancelDelete:h}){var g;const m=e.allowedTools.filter(x=>!(r!=null&&r.has(x))),f=o?(g=o.split("/").pop())==null?void 0:g.replace(/-/g," "):void 0;return s.jsxs(xN,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:d,onDuplicate:l,onDelete:c,onCancelDelete:h,children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),s.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),s.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"}),f&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-accent-primary/10 text-accent-primary",children:f})]}),e.description&&s.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),s.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[m.slice(0,5).map(x=>s.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:x},x)),m.length>5&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",m.length-5," more"]})]})]})}function Tj({title:e,agentTitle:t="Agents",subagentTitle:n="Sub-agents",agents:r,subagents:o,isBuiltIn:a,alwaysAllowedNames:d,modelOverrides:l,onView:c,onDuplicate:h,onEdit:m,onDelete:f,onCancelDelete:g,isConfirmingDelete:x}){if(r.length===0&&o.length===0)return null;const w=C=>s.jsx(Aq,{agent:C,model:l==null?void 0:l[C.id],isBuiltIn:a,isConfirmingDelete:(x==null?void 0:x(C.id))??!1,alwaysAllowedNames:d,onView:()=>c(C.id),onEdit:m?()=>m(C.id):void 0,onDuplicate:()=>h(C.id),onDelete:a?void 0:()=>f==null?void 0:f(C.id),onCancelDelete:a?void 0:()=>g==null?void 0:g(C.id)},C.id);return s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),r.length>0&&s.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:t}),s.jsxs("div",{className:"space-y-2",children:[r.map(w),o.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:n}),s.jsx("div",{className:"space-y-2",children:o.map(w)})]})]})]})}function Lq(e){const t=new Map;for(const n of e){const r=n.indexOf(":");if(r===-1)t.set(n,new Set);else{const o=n.slice(0,r),d=n.slice(r+1).split(",").filter(Boolean);t.set(o,new Set(d))}}return t}function Wh(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function Rq({formName:e,formId:t,formDescription:n,formSubagent:r,formTools:o,formColor:a,formModel:d,formPrompt:l,formError:c,isReadOnly:h,availableTools:m,providers:f,onNameChange:g,onIdChange:x,onDescriptionChange:w,onSubagentChange:C,onToolsChange:b,onColorChange:S,onModelChange:_,onPromptChange:v}){const k=Lq(o),E=m.filter(I=>!(r&&I.topLevelOnly)&&!I.isMcp),T=m.filter(I=>I.isMcp&&!(r&&I.topLevelOnly)),L=new Map;for(const I of T){const U=I.mcpServer??I.name,P=L.get(U)??[];P.push(I),L.set(U,P)}const A=(I,U)=>{const P=new Map(k),z=P.get(I)||new Set,K=new Set(z);K.has(U)?K.delete(U):K.add(U),K.size===0?P.set(I,new Set):P.set(I,K),b(Wh(P))},M=I=>{const U=new Map(k);U.has(I)?U.delete(I):U.set(I,new Set),b(Wh(U))};return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"space-y-3",children:[c&&s.jsx(Rl,{message:c}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(as,{label:"Name",value:e,onChange:g,placeholder:"My Agent",readOnly:h}),s.jsx(as,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(as,{label:"Description",value:n,onChange:w,placeholder:"What this agent does",readOnly:h}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),s.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[s.jsx("button",{onClick:()=>!h&&C(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${h?"pointer-events-none opacity-60":""}`,children:"Agent"}),s.jsx("button",{onClick:()=>!h&&C(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),s.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),s.jsx("input",{type:"color",value:a,onChange:I=>!h&&S(I.target.value),disabled:h,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),!h&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Model override"}),s.jsx(Vv,{providers:f,value:d,onChange:_,defaultLabel:"Default (global model)"}),s.jsx("p",{className:"text-[10px] text-text-muted mt-0.5",children:"When set, this model will be used when this agent is active (overrides the session model)."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),s.jsx(xt,{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32",children:E.map(I=>{const U=k.has(I.name),P=I.actions.length>0,z=k.get(I.name)||new Set;return P?h?s.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[s.jsx("span",{children:I.name}),s.jsx("span",{className:"text-[10px]",children:"*"})]},I.name):s.jsx(Na,{trigger:s.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${U?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} cursor-pointer`,children:[s.jsx("span",{children:I.name}),z.size>0&&s.jsx("span",{className:"text-[10px]",children:"*"})]}),minWidth:"160px",items:[...I.actions.map(K=>({label:s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${I.name}-${K}`,children:[s.jsx("input",{type:"checkbox",id:`${I.name}-${K}`,checked:z.has(K),onChange:()=>A(I.name,K),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),s.jsx("span",{children:K})]}),closeOnClick:!1})),{label:U?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(U)M(I.name);else{const K=new Map(k);K.set(I.name,new Set(I.actions)),b(Wh(K))}}}]},I.name):s.jsx("button",{onClick:()=>!h&&M(I.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${U?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none":"cursor-pointer"}`,children:s.jsx("span",{children:I.name})},I.name)})})]}),L.size>0&&(()=>{const I=new Set(T.map(H=>H.name)),U=k.has("__mcp_none__"),P=[...k.keys()].some(H=>I.has(H)),z=U?"none":P?"partial":"all",K=H=>{const F=new Map(k);for(const Q of F.keys())(Q==="__mcp_none__"||I.has(Q))&&F.delete(Q);if(H==="none"&&F.set("__mcp_none__",new Set),H==="partial")for(const Q of I)F.set(Q,new Set);b(Wh(F))};return s.jsxs("div",{children:[s.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["MCP Tools ",s.jsx("span",{className:"text-text-muted font-normal",children:"— from connected MCP servers"})]}),s.jsxs("div",{className:"bg-bg-tertiary border border-border rounded overflow-hidden",children:[s.jsx("div",{className:"flex items-center gap-4 px-3 py-1.5",children:["all","none","partial"].map(H=>s.jsxs("label",{className:`flex items-center gap-1.5 text-xs cursor-pointer ${h?"pointer-events-none opacity-60":""}`,children:[s.jsx("input",{type:"radio",name:"mcp-mode",checked:z===H,onChange:()=>K(H),disabled:h,className:"w-3 h-3 accent-accent-primary"}),s.jsxs("span",{className:z===H?"text-text-primary font-medium":"text-text-muted",children:[H.charAt(0).toUpperCase()+H.slice(1),H==="partial"&&I.size>0&&s.jsxs("span",{className:"ml-1 text-text-muted font-normal",children:["(",[...k.keys()].filter(F=>I.has(F)).length,"/",I.size,")"]})]})]},H))}),z==="partial"&&(()=>{const[H,F]=j.useState(""),[Q,Z]=j.useState(0),V=j.useRef(null),B=$=>{var X;const J=(X=V.current)==null?void 0:X.querySelector(`[data-idx="${$}"]`);J==null||J.scrollIntoView({block:"nearest"})};j.useEffect(()=>{B(Q)},[Q]);const D=H?T.filter($=>$.name.toLowerCase().includes(H.toLowerCase())):T,O=$=>{$.key==="ArrowDown"?($.preventDefault(),Z(J=>Math.min(J+1,D.length-1))):$.key==="ArrowUp"?($.preventDefault(),Z(J=>Math.max(J-1,0))):$.key==="Enter"&&D[Q]&&($.preventDefault(),M(D[Q].name))};return s.jsxs("div",{children:[s.jsx("div",{className:"px-3 py-2 border-b border-border",children:s.jsx("input",{type:"text",value:H,onChange:$=>{F($.target.value),Z(0)},onKeyDown:O,placeholder:"Search MCP tools...",className:"w-full px-2 py-1 text-xs bg-bg-primary border border-border rounded font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),s.jsx(xt,{className:"max-h-60",children:s.jsxs("div",{ref:V,children:[D.map(($,J)=>{const X=k.has($.name),Y=J===Q;return s.jsxs("div",{"data-idx":J,className:`flex items-center justify-between px-3 py-1.5 transition-colors ${Y?"bg-bg-primary":"hover:bg-bg-primary/30"}`,onMouseEnter:()=>Z(J),children:[s.jsx("span",{className:`text-xs font-mono ${X?"text-text-primary":"text-text-muted"}`,children:$.name}),s.jsx(ks,{enabled:X,onClick:()=>M($.name),label:$.name})]},$.name)}),D.length===0&&s.jsx("div",{className:"px-3 py-2 text-xs text-text-muted",children:"No MCP tools match your search."})]})})]})})()]})]})})()]}),s.jsxs("div",{className:"flex-1 min-h-[150px] pt-3 flex flex-col",children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),s.jsx("textarea",{value:l,onChange:I=>!h&&v(I.target.value),readOnly:h,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${h?"opacity-60":""}`})]})]})}function Dq(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function Oq({isOpen:e,onClose:t,initialEditId:n,projectDir:r}){const{data:o,loading:a}=Mi(er,r),d=(o==null?void 0:o.defaults)??[],l=(o==null?void 0:o.userItems)??[],c=(o==null?void 0:o.projectItems)??[],h=(o==null?void 0:o.modelOverrides)??{},m=iu(ce=>ce.fetchAgent),f=iu(ce=>ce.fetchDefaultContent),g=iu(ce=>ce.createAgent),x=iu(ce=>ce.updateAgent),w=iu(ce=>ce.deleteAgent),[C,b]=j.useState("list"),[S,_]=j.useState(null),[v,k]=j.useState(!1),[E,T]=j.useState(""),[L,A]=j.useState(""),[M,I]=j.useState(""),[U,P]=j.useState(!1),[z,K]=j.useState([]),[H,F]=j.useState("#6b7280"),[Q,Z]=j.useState(void 0),[V,B]=j.useState(""),[D,O]=j.useState("user"),[$,J]=j.useState(""),[X,Y]=j.useState(!1),[q,W]=j.useState(!1),[ee,ie]=j.useState(null),[re,se]=j.useState([]),[de,Se]=j.useState(new Set),{requestDelete:Me,clearConfirm:ye,isConfirming:ue}=Hu(),Ie=ce=>{T(ce.metadata.name),A(ce.metadata.id),I(ce.metadata.description),P(ce.metadata.subagent),K(ce.metadata.allowedTools),F(ce.metadata.color??"#6b7280"),B(ce.prompt),J(""),W(!0),be(`/api/agents/${ce.metadata.id}/model`).then(Oe=>Oe.json()).then(Oe=>{if(Oe.providerId&&Oe.model){const Ve=Oe.reasoningEffort?`:${Oe.reasoningEffort}`:"";Z(`${Oe.providerId}/${Oe.model}${Ve}`)}else Z(void 0)}).catch(()=>Z(void 0)).finally(()=>W(!1))},We=(ce,Oe,Ve)=>{T(ce.metadata.name+" (copy)"),A(`${Oe}-copy-${Date.now()}`),I(ce.metadata.description),P(ce.metadata.subagent),K(ce.metadata.allowedTools),F(ce.metadata.color??"#6b7280"),B(ce.prompt),J(""),_(null),k(!1),b("edit")},Qe=(ce,Oe)=>{Ie(ce),_(Oe),k(!0),b("edit")};j.useEffect(()=>{e&&(be("/api/tools").then(ce=>ce.json()).then(ce=>{const Oe=ce.tools||[];Se(new Set(Oe.filter(Ve=>Ve.alwaysAllowed).map(Ve=>Ve.name))),se(Oe.filter(Ve=>!Ve.alwaysAllowed))}).catch(()=>{se([]),Se(new Set)}),n?d.some(Oe=>Oe.id===n)?f(n).then(Oe=>{Oe&&We(Oe,n)}):m(n,r).then(Oe=>{Oe&&(Ie(Oe),_(n),k(!1),b("edit"))}):(b("list"),_(null),k(!1)))},[e,m,f,n,r]);const ve=async ce=>{if(d.some(Ve=>Ve.id===ce)){const Ve=await f(ce);if(!Ve)return;Qe(Ve,ce)}else{const Ve=await m(ce,r);if(!Ve)return;Qe(Ve,ce)}},oe=async ce=>{let Oe=await f(ce);Oe||(Oe=await m(ce,r)),Oe&&We(Oe,ce)},ae=()=>{_(null),T(""),A(""),I(""),P(!1),K(["read_file"]),F("#6b7280"),B(""),O("user"),J(""),k(!1),b("edit")},we=async ce=>{const Oe=await m(ce,r);Oe&&(Ie(Oe),_(ce),k(!1),b("edit"))},$e=ce=>{ie(ce)},fe=async ce=>{await w(ce,r)},Ae=async()=>{const ce=S??L;if(!ce||!E||!V){J("Name and prompt are required.");return}Y(!0),J("");const Oe={metadata:{id:ce,name:E,description:M,subagent:U,allowedTools:z.filter(De=>!de.has(De)),color:H},prompt:V},Ve=S?await x(S,Oe,r):await g(Oe,D,r);if(!Ve.success){Y(!1),J(Ve.error??"Failed to save agent.");return}await LL(S??L,Q),await er.refresh(r),Y(!1),n?t():b("list")},Xe=()=>{n?t():(b("list"),k(!1))},tt=ce=>{T(ce),S||A(Dq(ce))},pe=d.filter(ce=>ce.subagent),Ge=d.filter(ce=>!ce.subagent),Je=l.filter(ce=>ce.subagent),ot=l.filter(ce=>!ce.subagent),Ze=c.filter(ce=>ce.subagent),at=c.filter(ce=>!ce.subagent);return C==="edit"?s.jsxs(s.Fragment,{children:[s.jsxs(vt,{isOpen:e,onClose:Xe,title:v?`${E}`:S?"Edit Agent":"New Agent",size:"xl",footer:v?s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{onClick:()=>{T(E+" (copy)"),A(`${S}-copy-${Date.now()}`),_(null),k(!1)},className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})}):s.jsx(cN,{onCancel:Xe,onSave:Ae,saving:X,saveDisabled:!E||!V||q}),children:[!S&&!v&&s.jsx(pm,{value:D,onChange:O}),s.jsx(Rq,{formName:E,formId:L,formDescription:M,formSubagent:U,formTools:z,formColor:H,formModel:Q,formPrompt:V,formError:$,isReadOnly:v,availableTools:re,providers:Gt.getState().providers,onNameChange:tt,onIdChange:A,onDescriptionChange:I,onSubagentChange:ce=>{P(ce),ce&&K(Oe=>Oe.filter(Ve=>{var De;return!((De=re.find(st=>st.name===Ve))!=null&&De.topLevelOnly)}))},onToolsChange:K,onColorChange:F,onModelChange:Z,onPromptChange:B})]}),s.jsx(Aj,{agentId:ee,onClose:()=>ie(null),projectDir:r,onSaved:()=>void er.refresh(r)})]}):s.jsxs(s.Fragment,{children:[s.jsx(vt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:s.jsx(uN,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ae,loading:a,hasItems:d.length>0||l.length>0||c.length>0,children:s.jsxs("div",{className:"space-y-4",children:[d.length>0&&s.jsx(Tj,{title:"Built-in",agents:Ge,subagents:pe,isBuiltIn:!0,alwaysAllowedNames:de,modelOverrides:h,onView:ve,onEdit:$e,onDuplicate:oe}),(ot.length>0||Je.length>0||at.length>0||Ze.length>0)&&s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),s.jsx("div",{className:"ml-3 space-y-3",children:[{title:"Global",agents:ot,subagents:Je},{title:"Project",agents:at,subagents:Ze}].map(ce=>(ce.agents.length>0||ce.subagents.length>0)&&s.jsx(Tj,{title:ce.title,agents:ce.agents,subagents:ce.subagents,isBuiltIn:!1,alwaysAllowedNames:de,modelOverrides:h,isConfirmingDelete:Oe=>ue(Oe,"delete"),onView:ve,onDuplicate:oe,onEdit:we,onDelete:Oe=>{ue(Oe,"delete")?(fe(Oe),ye()):Me(Oe)},onCancelDelete:ye},ce.title))})]})]})})}),s.jsx(Aj,{agentId:ee,onClose:()=>ie(null),projectDir:r,onSaved:()=>void er.refresh(r)})]})}function Mq(e){return Ca(e)??{providerId:e,model:""}}async function LL(e,t){if(t){const{providerId:n,model:r,reasoningEffort:o}=Mq(t);await be(`/api/agents/${e}/model`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:n,model:r,...o?{reasoningEffort:o}:{}})})}else await be(`/api/agents/${e}/model`,{method:"DELETE"})}function Aj({agentId:e,onClose:t,onSaved:n,projectDir:r}){const[o,a]=j.useState(void 0),[d,l]=j.useState(!1),[c,h]=j.useState(!1),[m,f]=j.useState(null),{data:g}=Mi(er,r),x=g?[...g.defaults,...g.userItems,...g.projectItems]:[],w=e?x.find(S=>S.id===e):void 0,C=Gt(S=>S.providers);j.useEffect(()=>{e&&(l(!0),be(`/api/agents/${e}/model`).then(S=>S.json()).then(S=>{const _=S.reasoningEffort?`:${S.reasoningEffort}`:"";a(S.providerId&&S.model?`${S.providerId}/${S.model}${_}`:void 0)}).catch(()=>a(void 0)).finally(()=>l(!1)))},[e]);const b=async()=>{if(e){h(!0),f(null);try{await LL(e,o),n(),t()}catch{f("Failed to save. Please try again.")}h(!1)}};return s.jsx(vt,{isOpen:!!e,onClose:t,title:`Model — ${(w==null?void 0:w.name)??e??""}`,size:"md",children:s.jsxs("div",{className:"space-y-4 p-2",children:[s.jsx("p",{className:"text-xs text-text-muted",children:"Choose which model to use when this agent is active. This overrides the session/global model."}),d?s.jsx("div",{className:"text-sm text-text-muted py-2",children:"Loading..."}):s.jsx(Vv,{providers:C,value:o,onChange:a,defaultLabel:"Default (global model)"}),m&&s.jsx("p",{className:"text-xs text-red-500",children:m}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx("button",{onClick:t,className:"px-4 py-1.5 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),s.jsx("button",{onClick:b,disabled:c,className:"px-4 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 disabled:opacity-50 transition-colors",children:c?"Saving...":"Save"})]})]})})}function Iq(){const e=Vr(),t=Vt(e,v=>{var k;return((k=v.session)==null?void 0:k.mode)??null},v=>{var k;return((k=v.currentSession)==null?void 0:k.mode)??null},null),n=Vt(e,v=>{var k;return((k=v.session)==null?void 0:k.workdir)??void 0},v=>{var k;return(k=v.currentSession)==null?void 0:k.workdir},void 0),{data:r}=Mi(er,n),o=TL(),a=r?[...r.defaults,...r.userItems,...r.projectItems]:[],[d,l]=j.useState(!1),[c,h]=j.useState(!1),[m,f]=j.useState(null),g=j.useRef(null);zm(g,()=>l(!1));const x=zu();if(!t)return null;const w=a.filter(v=>!v.subagent),C=w.find(v=>v.id===t),b=(C==null?void 0:C.name)??t,S=wa(a,t),_=async v=>{v.id===t||!e||await o(v.id,v.name)};return s.jsxs("div",{className:"relative",ref:g,children:[s.jsxs("button",{type:"button",onClick:()=>l(!d),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[s.jsx("span",{className:"text-sm font-medium",style:{color:S},children:b}),s.jsx(mn,{className:`w-3 h-3 text-text-muted transition-transform ${d?"rotate-180":""}`})]}),d&&w.length>0&&s.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((v,k)=>{const E=v.id===t,T=wa(a,v.id),L=x.agentSwitching[k],A=L?Jb(L):null;return s.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[s.jsxs("button",{type:"button",onClick:()=>{_(v),l(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[s.jsx("span",{className:"font-medium truncate",style:{color:T},children:v.name}),E&&s.jsx(Ys,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),A&&s.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:A})]},v.id)}),s.jsx("div",{className:"border-t border-border p-1",children:s.jsx("button",{type:"button",onClick:()=>{l(!1),h(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),s.jsx(Oq,{isOpen:c,onClose:()=>{h(!1),f(null)},initialEditId:m,projectDir:n})]})}function Pq(){const e=Vr(),t=Vt(e,r=>{var o;return((o=r.session)==null?void 0:o.dangerLevel)??"normal"},r=>{var o;return((o=r.currentSession)==null?void 0:o.dangerLevel)??"normal"},"normal"),n=Re(r=>r.switchDangerLevel);return e?s.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[s.jsx("button",{type:"button",onClick:()=>n(e,"normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${t==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),s.jsx("button",{type:"button",onClick:()=>n(e,"dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${t==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]}):null}function Lj({value:e,onChange:t}){return s.jsxs("div",{children:[s.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",s.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),s.jsx("input",{type:"text",value:e??"",onChange:n=>t(n.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]})}const Bq=[8080,11434,8e3,1234];function af(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function RL(e){return{name:e.name,url:e.url,backend:e.backend,apiKey:e.apiKey,isLocal:e.isLocal,thinkingField:e.thinkingField,sendReasoningInMessages:e.sendReasoningInMessages,authAdapter:e.authAdapter,transportAdapter:e.transportAdapter,models:e.models}}function $q({model:e,modelConfigs:t,autoConfigState:n,testResults:r,onUpdateConfig:o,onRunAutoConfig:a,onTestParams:d,onShowRaw:l}){var g,x,w,C,b,S,_,v,k,E,T,L,A,M,I,U,P,z,K,H,F,Q,Z,V,B,D,O,$,J,X,Y,q,W,ee,ie,re,se,de,Se,Me,ye;function c(ue,Ie){var oe;const We=((oe=t[ue])==null?void 0:oe.omitParams)??[],ve=We.includes(Ie)?We.filter(ae=>ae!==Ie):[...We,Ie];o(ue,{omitParams:ve.length>0?ve:void 0})}function h(ue){var Ie;return((Ie=t[ue])==null?void 0:Ie.reasoningEfforts)??e.reasoningEfforts??[]}function m(ue,Ie){const We=h(ue),Qe=We.includes(Ie)?We.filter(ve=>ve!==Ie):[...We,Ie];o(ue,{reasoningEfforts:Qe})}function f(ue,Ie,We){const Qe=h(ue),ve=Qe.indexOf(Ie),oe=ve+We;if(ve===-1||oe<0||oe>=Qe.length)return;const ae=[...Qe];[ae[ve],ae[oe]]=[ae[oe],ae[ve]],o(ue,{reasoningEfforts:ae})}return s.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{onClick:()=>a(e.id),disabled:n.progress[e.id]==="probing",className:"px-4 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:n.progress[e.id]==="probing"?"Probing...":"Auto-config"}),n.progress[e.id]==="done"&&s.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&s.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),s.jsxs("div",{className:"flex gap-3 items-end",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),s.jsx("input",{type:"number",value:((g=t[e.id])==null?void 0:g.contextWindow)??e.contextWindow,onChange:ue=>o(e.id,{contextWindow:parseInt(ue.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),wA(((x=t[e.id])==null?void 0:x.contextWindow)??e.contextWindow)&&s.jsx("p",{"data-small-context":!0,className:"text-[11px] text-accent-warning mt-1 w-40 leading-snug",children:"Small context — agent prompts may be truncated by the provider."})]}),s.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[s.jsx("input",{type:"checkbox",checked:((w=t[e.id])==null?void 0:w.supportsVision)??!1,onChange:ue=>o(e.id,{supportsVision:ue.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{onClick:()=>d(e.id,"thinking"),disabled:(C=r[e.id+"-thinking"])==null?void 0:C.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(b=r[e.id+"-thinking"])!=null&&b.loading?"Testing...":"Test thinking"}),((S=r[e.id+"-thinking"])==null?void 0:S.result)&&s.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((_=r[e.id+"-thinking"])==null?void 0:_.error)&&s.jsx("span",{className:"text-xs text-red-500",title:(v=r[e.id+"-thinking"])==null?void 0:v.error,children:"Fail"}),((k=r[e.id+"-thinking"])==null?void 0:k.result)&&s.jsx("button",{onClick:()=>l(r[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{onClick:()=>d(e.id,"non-thinking"),disabled:(E=r[e.id+"-non-thinking"])==null?void 0:E.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(T=r[e.id+"-non-thinking"])!=null&&T.loading?"Testing...":"Test non-thinking"}),((L=r[e.id+"-non-thinking"])==null?void 0:L.result)&&s.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((A=r[e.id+"-non-thinking"])==null?void 0:A.error)&&s.jsx("span",{className:"text-xs text-red-500",title:(M=r[e.id+"-non-thinking"])==null?void 0:M.error,children:"Fail"}),((I=r[e.id+"-non-thinking"])==null?void 0:I.result)&&s.jsx("button",{onClick:()=>l(r[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),s.jsxs("details",{className:"group",children:[s.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[s.jsx(mn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:((U=t[e.id])==null?void 0:U.thinkingEnabled)??!1,onChange:ue=>o(e.id,{thinkingEnabled:ue.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),s.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((P=t[e.id])==null?void 0:P.thinkingEnabled)&&s.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),(z=e.reasoningEfforts)!=null&&z.length?s.jsx("select",{"aria-label":"Reasoning effort",value:((K=t[e.id])==null?void 0:K.thinkingLevel)??af(e.reasoningEfforts),onChange:ue=>o(e.id,{thinkingLevel:ue.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary",children:e.reasoningEfforts.map(ue=>s.jsx("option",{value:ue,children:ue},ue))}):s.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((H=t[e.id])==null?void 0:H.thinkingLevel)??"",onChange:ue=>o(e.id,{thinkingLevel:ue.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),s.jsx(Lj,{value:(F=t[e.id])==null?void 0:F.thinkingQueryParams,onChange:ue=>o(e.id,{thinkingQueryParams:ue})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Effort presets (shown as chips in the model selector)"}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[h(e.id).map((ue,Ie)=>s.jsxs("span",{className:"flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full border border-border text-text-muted",children:[ue,s.jsx("button",{type:"button","aria-label":`Move preset ${ue} up`,onClick:()=>f(e.id,ue,-1),disabled:Ie===0,className:"text-text-muted hover:text-text-primary leading-none disabled:opacity-30",children:"↑"}),s.jsx("button",{type:"button","aria-label":`Move preset ${ue} down`,onClick:()=>f(e.id,ue,1),disabled:Ie===h(e.id).length-1,className:"text-text-muted hover:text-text-primary leading-none disabled:opacity-30",children:"↓"}),s.jsx("button",{type:"button","aria-label":`Remove preset ${ue}`,onClick:()=>m(e.id,ue),className:"text-text-muted hover:text-accent-error leading-none",children:"×"})]},ue)),s.jsxs("select",{"aria-label":"Add effort preset",value:"",onChange:ue=>{ue.target.value&&m(e.id,ue.target.value)},className:"text-[10px] px-1.5 py-0.5 rounded border border-border bg-bg-tertiary text-text-muted",children:[s.jsx("option",{value:"",children:"Add preset…"}),jA.filter(ue=>!h(e.id).includes(ue)).map(ue=>s.jsx("option",{value:ue,children:ue},ue))]})]}),((Q=t[e.id])==null?void 0:Q.reasoningEfforts)!==void 0&&s.jsx("button",{type:"button",onClick:()=>o(e.id,{reasoningEfforts:void 0}),className:"mt-1 text-[10px] text-text-muted hover:text-text-primary hover:underline",children:"Reset to defaults"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort override (raw value, sent verbatim)"}),s.jsx("input",{type:"text","aria-label":"Reasoning effort override",value:((Z=t[e.id])==null?void 0:Z.reasoningEffortOverride)??e.reasoningEffortOverride??"",onChange:ue=>o(e.id,{reasoningEffortOverride:ue.target.value||void 0}),placeholder:"e.g. deep — bypasses the preset list",className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:((V=t[e.id])==null?void 0:V.nonThinkingEnabled)??!1,onChange:ue=>o(e.id,{nonThinkingEnabled:ue.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),s.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((B=t[e.id])==null?void 0:B.nonThinkingEnabled)&&s.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:s.jsx(Lj,{value:(D=t[e.id])==null?void 0:D.nonThinkingQueryParams,onChange:ue=>o(e.id,{nonThinkingQueryParams:ue})})}),(((O=t[e.id])==null?void 0:O.omitParams)??[]).includes("reasoning_effort")&&s.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-warning cursor-pointer select-none",children:[s.jsx("input",{type:"checkbox","data-testid":"re-enable-reasoning_effort",checked:!1,onChange:()=>c(e.id,"reasoning_effort"),className:"accent-accent-primary"}),"Re-enable reasoning_effort"]})]}),s.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[s.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(Gh,{modelId:e.id,paramKey:"temperature",label:"Temperature",step:.1,value:($=t[e.id])==null?void 0:$.temperature,defaultValue:(J=t[e.id])==null?void 0:J.defaultTemperature,omitParams:(X=t[e.id])==null?void 0:X.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseFloat(ue):void 0,valueField:"temperature"}),s.jsx(Gh,{modelId:e.id,paramKey:"top_p",label:"Top P",step:.05,value:(Y=t[e.id])==null?void 0:Y.topP,defaultValue:(q=t[e.id])==null?void 0:q.defaultTopP,omitParams:(W=t[e.id])==null?void 0:W.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseFloat(ue):void 0,valueField:"topP"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[s.jsx(Gh,{modelId:e.id,paramKey:"top_k",label:"Top K",value:(ee=t[e.id])==null?void 0:ee.topK,defaultValue:(ie=t[e.id])==null?void 0:ie.defaultTopK,omitParams:(re=t[e.id])==null?void 0:re.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseInt(ue):void 0,valueField:"topK"}),s.jsx(Gh,{modelId:e.id,paramKey:"max_tokens",label:"Max tokens",value:(se=t[e.id])==null?void 0:se.maxTokens,defaultValue:(de=t[e.id])==null?void 0:de.defaultMaxTokens,omitParams:(Se=t[e.id])==null?void 0:Se.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseInt(ue):void 0,valueField:"maxTokens"})]})]}),s.jsx("div",{className:"pt-3 border-t border-border",children:s.jsx(Fq,{value:(Me=t[e.id])==null?void 0:Me.compactionThreshold,maxTokens:((ye=t[e.id])==null?void 0:ye.contextWindow)??e.contextWindow,onChange:ue=>o(e.id,{compactionThreshold:ue})})})]})]})}function Gh({modelId:e,paramKey:t,label:n,value:r,defaultValue:o,omitParams:a,onUpdateConfig:d,onToggleOmit:l,parseValue:c,valueField:h,step:m}){const f=(a==null?void 0:a.includes(t))??!1;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:n}),s.jsxs("label",{className:"flex items-center gap-1 text-xs text-text-muted cursor-pointer select-none",children:[s.jsx("input",{type:"checkbox","data-testid":`send-${t}`,checked:!f,onChange:()=>l(e,t),className:"accent-accent-primary"}),"Send"]})]}),s.jsx("input",{type:"number","data-testid":`param-${t}`,step:m,value:f?"":r??"",disabled:f,onChange:g=>d(e,{[h]:c(g.target.value)}),placeholder:f?"Not sent":(o==null?void 0:o.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary disabled:opacity-40"}),!f&&o!==void 0&&s.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",o]})]})}function Fq({value:e,maxTokens:t,onChange:n}){const a=Math.min(95,Math.floor((t-5e3)/t*100)),d=Math.min(a,Math.ceil(15e3/t*100)),l=Math.min(e??.85,a/100),[c,h]=j.useState(Math.round(l*100));j.useEffect(()=>{const f=Math.min(e??.85,a/100);h(Math.round(f*100))},[e,a]);const m=Math.floor(t*(c/100));return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-1",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:"Auto-compaction threshold"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:[c,"% · ",Ul(m)]}),s.jsx("button",{type:"button",onClick:()=>{n(void 0),h(Math.round(.85*100))},disabled:e===void 0,className:"text-xs text-accent-primary hover:underline disabled:text-text-muted disabled:no-underline",children:"Default"})]})]}),s.jsx("input",{"aria-label":"Auto-compaction threshold",type:"range",min:d,max:a,step:"1",value:c,onChange:f=>h(Number(f.target.value)),onMouseUp:()=>n(c/100),onTouchEnd:()=>n(c/100),onBlur:()=>n(c/100),onKeyUp:()=>n(c/100),className:"w-full"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Minimum ",Ul(15e3)," tokens · maximum ",a,"% · default 85%"]})]})}function DL({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:o,editModelId:a}){const[d,l]=j.useState(r),[c,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState("unknown"),[w,C]=j.useState(""),[b,S]=j.useState(!1),[_,v]=j.useState(),[k,E]=j.useState(),[T,L]=j.useState(!1),[A,M]=j.useState(null),[I,U]=j.useState([]),[P,z]=j.useState(null),[K,H]=j.useState(!1),[F,Q]=j.useState(""),[Z,V]=j.useState(!0),[B,D]=j.useState({}),[O,$]=j.useState({loading:!1,progress:{}}),[J,X]=j.useState({}),[Y,q]=j.useState(null),[W,ee]=j.useState(new Set),[ie,re]=j.useState(""),[se,de]=j.useState(null),[Se,Me]=j.useState("disconnected"),[ye,ue]=j.useState(!1),[Ie,We]=j.useState(null),[Qe,ve]=j.useState([]),[oe,ae]=j.useState(!1),[we,$e]=j.useState(!1),[fe,Ae]=j.useState(""),[Xe,tt]=j.useState(null),pe=j.useRef(null),Ge=j.useRef(!1),Je=j.useRef(null),ot=j.useRef(null);j.useEffect(()=>{d===1&&e&&requestAnimationFrame(()=>{var Ee;Wt()&&((Ee=Je.current)==null||Ee.focus())})},[d,e]),j.useEffect(()=>()=>{pe.current!==null&&window.clearTimeout(pe.current)},[]),j.useEffect(()=>{e&&be("/api/provider-presets").then(async Ee=>Ee.ok?await Ee.json():{presets:[]}).then(Ee=>ve(Ee.presets)).catch(()=>ve([]))},[e]);function Ze(Ee,nt){D(qe=>({...qe,[Ee]:{...qe[Ee],...nt}}))}function at(Ee){ee(nt=>new Set(nt).add(Ee.id)),D(nt=>({...nt,[Ee.id]:{contextWindow:Ee.contextWindow,...nt[Ee.id]}}))}function ce(Ee){if(!Ee.trim())return I;const nt=Ee.toLowerCase().split(/\s+/).filter(Boolean);return I.filter(qe=>nt.every(Be=>qe.id.toLowerCase().includes(Be)))}function Oe(){const Ee=fe.trim();if(!Ee){tt("Enter a model name");return}const nt=xe=>xe.toLowerCase().replace(/[-_\s:.]+/g,""),qe=nt(Ee),Be=I.find(xe=>nt(xe.id)===qe);if(Be){at(Be),tt(`"${Be.id}" is already in the list`),Ae(""),!_&&O.progress[Be.id]!=="probing"&&qt(Be.id);return}const me={id:Ee,contextWindow:2e5};U(xe=>[...xe,me]),ee(xe=>new Set(xe).add(me.id)),D(xe=>({...xe,[me.id]:{contextWindow:me.contextWindow,thinkingEnabled:!0}})),z(me.id),Ae(""),tt(null),M(null)}j.useEffect(()=>{var Ee,nt;if(e)if(l(r),h((o==null?void 0:o.name)??""),f((o==null?void 0:o.url)??""),x((o==null?void 0:o.backend)??"unknown"),C((o==null?void 0:o.apiKey)??""),S((o==null?void 0:o.isLocal)??!1),v(o==null?void 0:o.authAdapter),E(o==null?void 0:o.transportAdapter),M(null),Q((o==null?void 0:o.thinkingField)??""),V((o==null?void 0:o.sendReasoningInMessages)??!0),X({}),q(null),de(null),Me("disconnected"),We(null),ae(!1),$e(!1),Ae(""),tt(null),(Ee=o==null?void 0:o.models)!=null&&Ee.length){const qe={},Be=new Set;for(const me of o.models)qe[me.id]={contextWindow:me.contextWindow,supportsVision:me.supportsVision,thinkingEnabled:me.thinkingEnabled,thinkingLevel:me.thinkingLevel??af(me.reasoningEfforts),nonThinkingEnabled:me.nonThinkingEnabled,thinkingQueryParams:me.thinkingQueryParams,nonThinkingQueryParams:me.nonThinkingQueryParams,omitParams:me.omitParams,defaultTemperature:me.defaultTemperature,defaultTopP:me.defaultTopP,defaultTopK:me.defaultTopK,defaultMaxTokens:me.defaultMaxTokens,temperature:me.temperature,topP:me.topP,topK:me.topK,maxTokens:me.maxTokens,compactionThreshold:me.compactionThreshold},me.selected&&Be.add(me.id);if(Be.size===0)for(const me of o.models)Be.add(me.id);ee(Be),D(qe),U(o.models),z(a??((nt=o.models[0])==null?void 0:nt.id)??null)}else U([]),D({}),z(null),ee(new Set)},[e,r,o==null?void 0:o.id,a]),j.useEffect(()=>{const Ee=!!_;d===2&&m&&I.length===0&&!T&&!A&&(!Ee||Se==="connected")&&kt(m)},[d,Se]),j.useEffect(()=>{!e||!_||!(o!=null&&o.id)||De(o.id)},[e,k,o==null?void 0:o.id]),j.useEffect(()=>{if(!Ie)return;const Ee=(o==null?void 0:o.id)??se;if(!Ee)return;let nt=!1;const qe=async()=>{const me=await De(Ee);nt||me!=="connected"||(We(null),ae(!1),$e(!1),await kt(m))};qe();const Be=window.setInterval(()=>void qe(),2e3);return()=>{nt=!0,window.clearInterval(Be)}},[Ie,se,o==null?void 0:o.id]);async function Ve(){if(o!=null&&o.id)return o.id;if(se)return se;const Ee=await be("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:c||"Provider",url:m,backend:g,authAdapter:_,transportAdapter:k,isLocal:!1,models:[]})});if(!Ee.ok)throw new Error("Unable to create provider");const nt=await Ee.json();return de(nt.provider.id),nt.provider.id}async function De(Ee){const nt=await be(`/api/provider-auth/${Ee}/status`);if(!nt.ok)return"error";const qe=await nt.json(),Be=qe.state==="connected"?"connected":qe.state==="pending"?"pending":qe.state==="error"?"error":"disconnected";return Me(Be),Be}async function st(){ue(!0),Me("pending");try{const Ee=await Ve(),nt=await be(`/api/provider-auth/${Ee}/login`,{method:"POST"});if(!nt.ok)throw new Error("Unable to start provider sign-in");const qe=await nt.json();We(qe)}catch{Me("error")}finally{ue(!1)}}async function rt(){var Ee;Ie!=null&&Ie.userCode&&(await((Ee=navigator.clipboard)==null?void 0:Ee.writeText(Ie.userCode)),pe.current!==null&&window.clearTimeout(pe.current),$e(!1),requestAnimationFrame(()=>$e(!0)),pe.current=window.setTimeout(()=>{$e(!1),pe.current=null},1500))}function yt(){Ie&&(window.open(Ie.directUrl??Ie.verificationUrl,"_blank","noopener,noreferrer"),ae(!0))}async function kt(Ee){var nt,qe;L(!0),M(null),U([]);try{const Be=new URLSearchParams({url:Ee});w&&Be.set("apiKey",w),g&&Be.set("backend",g);const me=k?await be(`/api/providers/${await Ve()}/models`):await be(`/api/providers/models?${Be.toString()}`);if(me.ok){const xe=await me.json();if((nt=xe.models)!=null&&nt.length){U(xe.models),z(((qe=xe.models[0])==null?void 0:qe.id)??null);const He={};for(const Ue of xe.models)He[Ue.id]={contextWindow:Ue.contextWindow,thinkingEnabled:!0,thinkingLevel:af(Ue.reasoningEfforts),defaultTemperature:Ue.defaultTemperature,defaultTopP:Ue.defaultTopP,defaultTopK:Ue.defaultTopK,defaultMaxTokens:Ue.defaultMaxTokens};D(He),xe.models.length===1&&(ee(new Set([xe.models[0].id])),z(xe.models[0].id),qt(xe.models[0].id))}}else{const xe=await me.json();M(xe.error??`Failed to fetch models from ${Ee}`)}}catch(Be){M(`Failed to fetch models from ${Ee}: ${Be instanceof Error?Be.message:"Unknown error"}`)}L(!1)}async function qt(Ee){$(nt=>({loading:!0,progress:{...nt.progress,[Ee]:"probing"}}));try{const nt=await be("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:m,apiKey:w||void 0,backend:g||"unknown",models:[{id:Ee}]})});if(!nt.ok){const Be=await nt.json();throw new Error(Be.error??"Auto-config failed")}const qe=await nt.json();for(const Be of qe.models){const me={};if(Be.contextSource!=="default"&&(me.contextWindow=Be.contextWindow,me.supportsVision=Be.supportsVision),Be.thinkingConfig){me.thinkingEnabled=!0,me.thinkingQueryParams=JSON.stringify(Be.thinkingConfig);const xe=B[Be.id];me.thinkingLevel=(xe==null?void 0:xe.thinkingLevel)??Be.defaultReasoningEffort??af(Be.reasoningEfforts)}Be.nonThinkingConfig&&(me.nonThinkingEnabled=!0,me.nonThinkingQueryParams=JSON.stringify(Be.nonThinkingConfig)),Be.sendReasoningInMessages===!1&&V(!1),Be.rejectedParams&&Be.rejectedParams.length>0&&(me.omitParams=Be.rejectedParams),Be.reasoningEfforts&&Be.reasoningEfforts.length>0&&(me.reasoningEfforts=Be.reasoningEfforts),Ze(Be.id,me),$(xe=>({...xe,progress:{...xe.progress,[Be.id]:"done"}}))}}catch(nt){console.error("Auto-config error:",nt),$(qe=>({...qe,progress:{...qe.progress,[Ee]:"error"}}))}finally{$(nt=>({...nt,loading:!1}))}}async function Mn(Ee,nt){const qe=Ee+"-"+nt;X(Be=>({...Be,[qe]:{loading:!0}}));try{const Be=B[Ee],me=await be("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:m,providerId:(o==null?void 0:o.id)??se??void 0,transportAdapter:k,model:Ee,apiKey:w||void 0,backend:g||"unknown",thinkingField:F||void 0,mode:nt,modelConfig:{temperature:Be==null?void 0:Be.temperature,topP:Be==null?void 0:Be.topP,topK:Be==null?void 0:Be.topK,maxTokens:Be==null?void 0:Be.maxTokens,supportsVision:Be==null?void 0:Be.supportsVision,thinkingEnabled:Be==null?void 0:Be.thinkingEnabled,thinkingLevel:Be==null?void 0:Be.thinkingLevel,nonThinkingEnabled:Be==null?void 0:Be.nonThinkingEnabled,thinkingQueryParams:Be==null?void 0:Be.thinkingQueryParams,nonThinkingQueryParams:Be==null?void 0:Be.nonThinkingQueryParams,omitParams:Be==null?void 0:Be.omitParams}})}),xe=await me.json();me.ok?X(He=>({...He,[qe]:{loading:!1,result:JSON.stringify(xe,null,2),message:xe.message}})):X(He=>({...He,[qe]:{loading:!1,error:xe.error??"Test failed"}}))}catch(Be){X(me=>({...me,[qe]:{loading:!1,error:Be instanceof Error?Be.message:"Request failed"}}))}}function qn(){U([]),D({}),$({loading:!1,progress:{}}),X({}),q(null),ee(new Set),re(""),Ae(""),tt(null)}function In(){se&&!Ge.current&&be(`/api/providers/${se}`,{method:"DELETE"}).catch(Ee=>{console.warn("Failed to clean up draft provider",Ee)}),t()}function hr(){const Ee=c||"Provider",nt=(o==null?void 0:o.id)??se??`temp-${Date.now()}`;n({id:nt,name:Ee,url:m,backend:g||"unknown",apiKey:w||void 0,isLocal:b,thinkingField:F||void 0,sendReasoningInMessages:Z,authAdapter:_,transportAdapter:k,models:I.map(qe=>{var Be,me,xe,He,Ue,et,ut,ht,Xt,pn,kn,Ao,Js,us,Zs,Tr,ds,Ls,Wr;return{id:qe.id,name:qe.name,apiModelId:qe.apiModelId,requestBody:qe.requestBody,reasoningEfforts:((Be=B[qe.id])==null?void 0:Be.reasoningEfforts)??qe.reasoningEfforts,reasoningEffortOverride:((me=B[qe.id])==null?void 0:me.reasoningEffortOverride)??qe.reasoningEffortOverride,contextWindow:((xe=B[qe.id])==null?void 0:xe.contextWindow)??qe.contextWindow,selected:W.has(qe.id)||void 0,supportsVision:(He=B[qe.id])==null?void 0:He.supportsVision,thinkingEnabled:(Ue=B[qe.id])==null?void 0:Ue.thinkingEnabled,thinkingLevel:(et=B[qe.id])==null?void 0:et.thinkingLevel,nonThinkingEnabled:(ut=B[qe.id])==null?void 0:ut.nonThinkingEnabled,thinkingQueryParams:(ht=B[qe.id])==null?void 0:ht.thinkingQueryParams,nonThinkingQueryParams:(Xt=B[qe.id])==null?void 0:Xt.nonThinkingQueryParams,omitParams:(pn=B[qe.id])==null?void 0:pn.omitParams,temperature:(kn=B[qe.id])==null?void 0:kn.temperature,topP:(Ao=B[qe.id])==null?void 0:Ao.topP,topK:(Js=B[qe.id])==null?void 0:Js.topK,maxTokens:(us=B[qe.id])==null?void 0:us.maxTokens,defaultMaxTokens:(Zs=B[qe.id])==null?void 0:Zs.defaultMaxTokens,defaultTemperature:(Tr=B[qe.id])==null?void 0:Tr.defaultTemperature,defaultTopP:(ds=B[qe.id])==null?void 0:ds.defaultTopP,defaultTopK:(Ls=B[qe.id])==null?void 0:Ls.defaultTopK,compactionThreshold:(Wr=B[qe.id])==null?void 0:Wr.compactionThreshold}})}),Ge.current=!0,t()}if(!e)return null;const Nr=s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{children:d>1&&s.jsx("button",{onClick:()=>{d===2&&qn(),l(d-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:In,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),d===1?s.jsx("button",{onClick:()=>l(2),disabled:!m,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:"Next — Test & Configure"}):s.jsx("button",{onClick:hr,disabled:O.loading,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:O.loading?"Configuring...":"Save Provider"})]})]});return s.jsxs(s.Fragment,{children:[s.jsxs(vt,{isOpen:e,onClose:In,title:o?"Edit Provider":"Add Provider",size:"lg",footer:Nr,closeOnBackdropClick:!1,closeOnEscape:!K&&!Y,children:[s.jsx("div",{className:"flex gap-1.5 pt-2",children:[1,2].map(Ee=>s.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${Ee<d?"bg-accent-success":Ee===d?"bg-accent-primary":"bg-border"}`},Ee))}),d===1&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),s.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[Qe.map(Ee=>s.jsx("button",{type:"button",onClick:()=>{h(Ee.defaults.name??Ee.name),f(Ee.defaults.url),x(Ee.defaults.backend),S(!1),C(""),v(Ee.authAdapter),E(Ee.transportAdapter),M(null),qn()},className:`p-2 rounded border text-center text-sm transition-colors ${k&&k===Ee.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:Ee.name},Ee.id)),s.jsx("button",{type:"button",onClick:()=>{x("unknown"),S(!1),v(void 0),E(void 0),M(null),qn()},className:`p-2 rounded border text-center text-sm transition-colors ${g==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),Bq.map(Ee=>{const nt={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},qe={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return s.jsx("button",{type:"button",onClick:()=>{h(Be=>Be||(qe[Ee]??"")),f(Be=>Be||`http://localhost:${Ee}`),x(nt[Ee]??""),S(!0),v(void 0),E(void 0),M(null),qn()},className:`p-2 rounded border text-center text-sm transition-colors ${g===nt[Ee]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:qe[Ee]??`localhost:${Ee}`},Ee)})]})]}),!_&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),s.jsx("input",{ref:Je,type:"text",value:m,"data-testid":"provider-modal-url",onChange:Ee=>{f(Ee.target.value),M(null),U([]),D({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),s.jsx("input",{type:"text",autoComplete:"off",value:c,onChange:Ee=>h(Ee.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!_&&s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",s.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),s.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:Ee=>C(Ee.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!_&&s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:Ee=>S(Ee.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),s.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),d===2&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Test & Configure Models"}),s.jsx("button",{type:"button",onClick:()=>H(!0),className:"p-1.5 text-text-muted hover:text-text-primary rounded transition-colors",title:"Provider-level defaults",children:s.jsx(rN,{className:"w-4 h-4"})})]}),!!_&&s.jsxs("div",{className:"rounded-lg border border-border bg-bg-primary p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Connect provider"}),s.jsx("p",{className:"mt-1 text-xs text-text-muted",children:"Connect this provider before choosing available models."})]}),Se==="connected"?s.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):s.jsx("button",{type:"button",onClick:()=>void st(),disabled:ye||Se==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:ye||Se==="pending"?"Connecting...":Se==="error"?"Retry":"Connect"})]}),Ie&&s.jsx("div",{className:"mt-4 border-t border-border pt-4",children:Ie.mode!=="browser"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-xs text-text-muted",children:"Use this code to complete authorization:"}),s.jsx("button",{type:"button",onClick:()=>void rt(),className:"mt-3 w-full rounded-lg border border-accent-primary/40 px-4 py-4 font-mono text-2xl font-semibold tracking-[0.2em] text-accent-primary",children:Ie.userCode??"Continue"}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void rt(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:we?"Copied":"Copy code"}),s.jsx("button",{type:"button",onClick:yt,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:oe?"Reopen authorization":"Open authorization"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-xs text-text-muted mb-3",children:Ie.instructions}),s.jsx("button",{type:"button",onClick:yt,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:oe?"Reopen authorization":"Open authorization"})]})})]}),T&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[s.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),A&&s.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[s.jsx("p",{children:A}),s.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",m]}),s.jsxs("div",{className:"flex gap-2 mt-2",children:[s.jsx("button",{onClick:()=>kt(m),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),s.jsx("button",{onClick:()=>{qn(),l(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"}),!_&&s.jsx("button",{onClick:()=>{var Ee;return(Ee=ot.current)==null?void 0:Ee.focus()},className:"text-xs text-accent-primary hover:underline",children:"Add model manually"})]})]}),g&&(!_||Se==="connected")&&s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Add model manually"}),s.jsx("p",{className:"text-xs text-text-muted mb-2",children:A?"Can't discover models automatically? Enter the model name to use:":"Enter a model name manually if it does not appear in the list above:"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{ref:ot,type:"text",value:fe,onChange:Ee=>{Ae(Ee.target.value),Xe&&tt(null)},onKeyDown:Ee=>{Ee.key==="Enter"&&(Ee.preventDefault(),Oe())},placeholder:"model-name","data-testid":"provider-modal-manual-model-input",className:"flex-1 px-3 py-1.5 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),s.jsx("button",{type:"button",onClick:Oe,"data-testid":"provider-modal-manual-model-add",className:"px-3 py-1.5 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Add"})]}),Xe&&s.jsx("p",{className:"text-xs text-red-500 mt-1",children:Xe})]}),I.length>0&&g&&(!_||Se==="connected")&&s.jsxs(s.Fragment,{children:[W.size>0&&s.jsxs("div",{className:"mb-4",children:[s.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",W.size,")"]}),s.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),s.jsx("div",{className:"space-y-2",children:I.filter(Ee=>W.has(Ee.id)).map(Ee=>{var nt;return s.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[s.jsxs("div",{onClick:()=>z(P===Ee.id?null:Ee.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-sm font-medium text-text-primary",children:Ee.name??Ee.id.split("/").pop()}),s.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((nt=B[Ee.id])==null?void 0:nt.contextWindow)??Ee.contextWindow).toLocaleString()," ctx"]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[O.progress[Ee.id]==="probing"?s.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):O.progress[Ee.id]==="done"?s.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):O.progress[Ee.id]==="error"?s.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):_?null:s.jsx("button",{onClick:qe=>{qe.stopPropagation(),qt(Ee.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),I.length>1&&s.jsx("button",{onClick:qe=>{qe.stopPropagation();const Be=new Set(W);Be.delete(Ee.id),ee(Be),P===Ee.id&&z(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),s.jsx(mn,{className:`w-4 h-4 text-text-muted transition-transform ${P===Ee.id?"rotate-180":""}`})]})]}),P===Ee.id&&s.jsx($q,{model:Ee,modelConfigs:B,autoConfigState:O,testResults:J,onUpdateConfig:Ze,onRunAutoConfig:qt,onTestParams:Mn,onShowRaw:q})]},Ee.id)})})]}),I.length>1&&s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),W.size===0&&s.jsx("p",{className:"text-xs text-text-muted mb-2",children:"This provider has many models available. Select the ones you want to use below."}),s.jsxs("div",{className:"relative mb-2",children:[s.jsx("input",{type:"text",value:ie,onChange:Ee=>re(Ee.target.value),placeholder:"Search models...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),ie&&s.jsx("button",{onClick:()=>re(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",ce(ie).length," of ",I.length," models"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:()=>{const Ee=new Set(W),nt=ce(ie);for(const qe of nt)Ee.add(qe.id);if(ee(Ee),D(qe=>{const Be={...qe};for(const me of nt)Be[me.id]={contextWindow:me.contextWindow,...Be[me.id]};return Be}),!_)for(const qe of nt)O.progress[qe.id]!=="probing"&&O.progress[qe.id]!=="done"&&qt(qe.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),s.jsx("button",{onClick:()=>{const Ee=new Set(W),nt=ce(ie);for(const qe of nt)Ee.delete(qe.id);ee(Ee)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),s.jsxs(xt,{className:"space-y-1 max-h-48 border border-border rounded-lg bg-bg-primary",children:[ce(ie).map(Ee=>{var qe;const nt=W.has(Ee.id);return s.jsxs("div",{role:"checkbox","aria-checked":nt,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${nt?"bg-accent-primary/5":""}`,onClick:()=>{if(nt){const Be=new Set(W);Be.delete(Ee.id),ee(Be)}else at(Ee),_||qt(Ee.id)},onKeyDown:Be=>{(Be.key==="Enter"||Be.key===" ")&&(Be.preventDefault(),Be.currentTarget.click())},children:[s.jsx("input",{type:"checkbox",checked:nt,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),s.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:Ee.name??Ee.id.split("/").pop()}),s.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((qe=B[Ee.id])==null?void 0:qe.contextWindow)??Ee.contextWindow).toLocaleString()," ctx"]}),O.progress[Ee.id]==="probing"&&s.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),O.progress[Ee.id]==="done"&&s.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),O.progress[Ee.id]==="error"&&s.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},Ee.id)}),ce(ie).length===0&&s.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",ie,"”"]})]})]})]})]})]}),K&&s.jsx(vt,{isOpen:!0,onClose:()=>H(!1),title:"Provider-Level Defaults",size:"md",footer:s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{onClick:()=>H(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})}),children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),s.jsx("input",{type:"text",defaultValue:'{"chat_template_kwargs":{"enable_thinking":false}}',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),s.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",s.jsx("span",{className:"text-text-muted",children:"(override)"})]}),s.jsx("input",{type:"text",value:F,onChange:Ee=>Q(Ee.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),s.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:Z,onChange:Ee=>V(Ee.target.checked),className:"rounded border-border bg-bg-primary text-accent-primary focus:ring-accent-primary"}),s.jsx("span",{className:"text-sm text-text-secondary",children:"Send reasoning in messages"}),s.jsx("span",{className:"text-xs text-text-muted ml-auto",children:"When disabled, strips reasoning/thinking content from assistant messages sent to this provider"})]})]})}),Y&&s.jsx(vt,{isOpen:!0,onClose:()=>q(null),title:"Raw Response",size:"lg",children:s.jsx(xt,{horizontal:!0,children:s.jsx("pre",{className:"text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:Y})})})]})}const OL=j.forwardRef(function({onNext:t,embedded:n=!1},r){const[o,a]=j.useState([]),[d,l]=j.useState([]),[c,h]=j.useState(!1),[m,f]=j.useState(null),[g,x]=j.useState(null),[w,C]=j.useState(null),[b,S]=j.useState(null),[_,v]=j.useState(null),[k,E]=j.useState(!1),T=j.useRef(null);j.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]),j.useEffect(()=>{L()},[]);async function L(){try{const O=await be("/api/providers");if(O.ok){const J=(await O.json()).providers.map(X=>({id:X.id,name:X.name,url:X.url,backend:X.backend,model:null,apiKey:X.apiKey,isLocal:X.isLocal,thinkingField:X.thinkingField,sendReasoningInMessages:X.sendReasoningInMessages,models:X.models}));a(J),l(J)}}catch{}}async function A(O){const $=O.id.startsWith("temp-"),J=d.some(q=>q.id===O.id),X=d.length===0&&m===null,Y=RL(O);try{let q;if($){const ee=await be("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!ee.ok)throw new Error("Failed to create provider");const ie=await ee.json();q={...O,id:ie.provider.id,model:null}}else{if(!(await be(`/api/providers/${O.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})).ok)throw new Error("Failed to update provider");q={...O,model:null}}const W=ee=>ee.some(ie=>ie.id===q.id)?ee.map(ie=>ie.id===q.id?q:ie):[...ee,q];l(W),a(W),!n&&X&&!J&&t({providers:[q]})}catch{if($){const q={...O,model:null};l(W=>[...W,q])}}}function M(){f(null),h(!0)}function I(O){f(O),h(!0)}function U(){h(!1),f(null)}function P(O){x(O),o.some(J=>J.id===O)?be(`/api/providers/${O}`,{method:"DELETE"}).then(()=>{l(d.filter(J=>J.id!==O)),a(o.filter(J=>J.id!==O)),x(null)}).catch(()=>x(null)):(l(d.filter(J=>J.id!==O)),x(null))}function z(){const O=d.filter($=>!$.id.startsWith("temp-"));t({providers:O})}function K(O){l(O),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{T.current=null,be("/api/providers/order",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerIds:O.map($=>$.id)})}).then($=>{$.ok?E(!1):(E(!0),H())}).catch(()=>{E(!0),H()})},300)}async function H(){try{const O=await be("/api/providers");if(!O.ok)return;const J=(await O.json()).providers.map(X=>X.id);l(X=>{const Y=new Set(J);return X.length===J.length&&X.every(W=>Y.has(W.id))?J.map(W=>X.find(ee=>ee.id===W)).filter(W=>W!==void 0):X})}catch{}}function F(O,$){const J=O+$;if(J<0||J>=d.length)return;const X=[...d],[Y]=X.splice(O,1);X.splice(J,0,Y),K(X)}function Q(O){S(O)}function Z(O){v(O)}function V(O){if(!b||b===O)return;const $=d.findIndex(q=>q.id===b),J=d.findIndex(q=>q.id===O);if($===-1||J===-1)return;const X=[...d],[Y]=X.splice($,1);X.splice(J,0,Y),K(X)}function B(){S(null),v(null)}j.useImperativeHandle(r,()=>({addProvider:M,submit:z}),[z]);const D=d.length>0;return s.jsxs("div",{className:"max-w-xl mx-auto",children:[!n&&s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"LLM Providers"}),s.jsx("p",{className:"text-text-secondary mb-8",children:"Manage your LLM server connections"})]}),s.jsxs("div",{className:"space-y-4",children:[d.length>0?s.jsx("div",{className:"space-y-2",children:d.map((O,$)=>s.jsxs("div",{"data-testid":`provider-row-${O.id}`,onDragOver:J=>{b&&(J.preventDefault(),Z(O.id))},onDrop:J=>{b&&(J.preventDefault(),V(O.id))},className:`flex items-center justify-between bg-bg-secondary rounded-lg p-4 border ${_===O.id?"border-accent-primary":"border-border"}`,children:[n&&s.jsx("button",{type:"button",draggable:!0,onDragStart:()=>Q(O.id),onDragEnd:B,className:"p-1.5 mr-1 text-text-muted hover:text-text-secondary cursor-grab active:cursor-grabbing transition-colors",title:"Drag to reorder","aria-label":"Drag to reorder",children:s.jsx(zO,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"px-2 py-0.5 bg-accent-primary/25 text-accent-primary rounded text-xs font-medium",children:HE(O.backend)}),s.jsx("span",{className:"text-text-primary font-medium",children:O.name}),s.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${O.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:O.isLocal?"local":"api"})]}),s.jsx("p",{className:"text-text-muted text-sm mt-1 truncate",children:O.url}),O.model&&s.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",O.model]})]}),s.jsx("div",{className:"flex items-center gap-1",children:w===O.id?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("button",{onClick:()=>P(O.id),disabled:g===O.id,className:"px-2 py-1 text-xs text-red-500 hover:text-red-400 bg-red-500/10 rounded transition-colors disabled:opacity-50",children:g===O.id?"Deleting...":"Confirm"}),s.jsx("button",{onClick:()=>C(null),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>I(O),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary border border-border rounded transition-colors",children:"Edit"}),s.jsx("button",{onClick:()=>C(O.id),className:"p-2 text-text-muted hover:text-red-500 transition-colors",title:"Remove provider",children:s.jsx(Ri,{})})]})}),n&&s.jsxs("div",{className:"flex flex-col ml-1",children:[s.jsx("button",{type:"button",onClick:()=>F($,-1),disabled:$===0,className:"p-0.5 text-text-muted hover:text-text-secondary disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Move up","aria-label":"Move up",children:s.jsx(lm,{className:"w-3.5 h-3.5"})}),s.jsx("button",{type:"button",onClick:()=>F($,1),disabled:$===d.length-1,className:"p-0.5 text-text-muted hover:text-text-secondary disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Move down","aria-label":"Move down",children:s.jsx(mn,{className:"w-3.5 h-3.5"})})]})]},O.id))}):s.jsx("div",{className:"bg-bg-secondary rounded-lg p-8 text-center border border-border",children:s.jsx("p",{className:"text-text-muted",children:"No providers configured yet"})}),n&&k&&s.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Couldn't save the new provider order. Showing the last saved order."}),!n&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:M,"data-testid":"onboarding-add-provider-button",className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-bg-secondary border border-dashed border-border rounded-lg text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[s.jsx(kr,{className:"w-4 h-4"}),"Add Provider"]}),s.jsx("button",{onClick:z,disabled:!D,"data-testid":"onboarding-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:n?"Done":"Continue"})]})]}),s.jsx(DL,{isOpen:c,onClose:U,onSave:A,initialStep:1,editProvider:m??void 0})]})});function zq({isOpen:e,onClose:t}){const n=j.useRef(null);return s.jsx(vt,{isOpen:e,onClose:t,title:"Manage Providers",size:"lg",footer:s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{var r;return(r=n.current)==null?void 0:r.addProvider()},className:"flex items-center gap-2 px-4 py-2 rounded-lg border border-dashed border-border text-sm text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[s.jsx(kr,{className:"w-4 h-4"}),"Add Provider"]}),s.jsx("button",{type:"button",onClick:()=>{var r;return(r=n.current)==null?void 0:r.submit()},className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})]}),children:s.jsx(OL,{ref:n,onNext:t,embedded:!0})})}function Rj({activeProvider:e,shortModelName:t,effort:n,agentOverrideActive:r,agentColor:o,agentName:a,pinned:d}){return s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"text-sm text-accent-primary flex items-center gap-1",children:[r&&s.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 ring-1 ring-border",style:{backgroundColor:o??"#6b7280"},title:`Model set by agent "${a??"unknown"}". Change it in Settings > Agents.`}),e?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"hidden @sm:inline",children:[e.name," • "]}),t,n&&s.jsxs("span",{className:"text-text-muted",children:[":",n]})]}):s.jsxs(s.Fragment,{children:[t,n&&s.jsxs("span",{className:"text-text-muted",children:[":",n]})]}),d&&s.jsx("span",{className:"flex-shrink-0 text-text-muted",title:'Reasoning effort pinned for this session (chosen via "Keep current reasoning effort").',children:s.jsx(qO,{className:"w-3 h-3"})})]}),s.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${e!=null&&e.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:e!=null&&e.isLocal?"local":"api"})]})}function Hq(){var rc;const e=Vr(),t=Vt(e,ke=>ke.session??null,ke=>ke.currentSession,null),n=Vt(e,ke=>ke.contextState??null,ke=>ke.contextState,null),r=EL(),o=Re(ke=>ke.setSessionProvider),a=Re(ke=>ke.resetSessionProvider),d=Re(ke=>ke.clearSessionEffortPin),[l,c]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState([]),[x,w]=j.useState(null),C=j.useRef(null),[b,S]=j.useState(null),[_,v]=j.useState(!1),[k,E]=j.useState({}),[T,L]=j.useState(null),[A,M]=j.useState(null),[I,U]=j.useState(!1),P=j.useRef(null),[z,K]=j.useState(!1),H=j.useRef(new Set),F=Gt(ke=>ke.providers),Q=Gt(ke=>ke.activeProviderId),Z=Gt(ke=>ke.defaultModelSelection),V=Gt(ke=>ke.activating),B=Gt(ke=>ke.activateProvider),D=Gt(ke=>ke.refreshModel),O=Gt(ke=>ke.refreshProviderModels),$=Gt(ke=>ke.setDefaultModel),J=Gt(ke=>ke.updateModelSettings),X=Gt(ke=>ke.fetchConfig),Y=zu();Au(Y.modelSelector,()=>c(ke=>!ke));const q=(t==null?void 0:t.providerId)??null,W=(t==null?void 0:t.providerModel)??null,ee=(t==null?void 0:t.providerReasoningEffort)??null,ie=(t==null?void 0:t.providerPinnedEffort)??null,re=(Z==null?void 0:Z.split("/")[0])??null,se=(Z==null?void 0:Z.split("/").slice(1).join("/"))??null,{data:de}=Mi(er,t==null?void 0:t.workdir),Se=(de==null?void 0:de.defaults)??[],Me=(de==null?void 0:de.userItems)??[],ye=(de==null?void 0:de.modelOverrides)??{},ue=t==null?void 0:t.mode,Ie=ue?Se.find(ke=>ke.id===ue)??Me.find(ke=>ke.id===ue):void 0,We=ue?ye[ue]??void 0:void 0,Qe=We?Ca(We):void 0,ve=(Qe==null?void 0:Qe.providerId)??null,oe=(Qe==null?void 0:Qe.model)??null,ae=Qe==null?void 0:Qe.reasoningEffort,we=ue?wa([...Se,...Me],ue):void 0,$e=!!(t!=null&&t.providerManual)&&!!(t!=null&&t.providerManualActive),fe=t!=null&&t.providerId&&(t!=null&&t.providerModel)?`${t.providerId}/${t.providerModel}`:null,Ae=!!(t!=null&&t.providerManual)||fe!==null&&fe!==Z,Xe=!$e&&!!We,tt=$e?q:ve??q??re,pe=$e?W:oe??W??se,Ge=ie??($e?ee:ae??ee)??void 0,Je=!!ie,ot=pe?((rc=pe.split("/").pop())==null?void 0:rc.replace(/-/g," "))??pe:"No model",Ze=F.find(ke=>ke.id===tt),at=Ze==null?void 0:Ze.models.find(ke=>ke.id===pe),ce=gb({explicitEffort:Ge,reasoningEfforts:at==null?void 0:at.reasoningEfforts,thinkingLevel:at==null?void 0:at.thinkingLevel,thinkingEnabled:at==null?void 0:at.thinkingEnabled,override:at==null?void 0:at.reasoningEffortOverride}),Oe=(ke,it)=>{var En;if(tt===ke&&pe===it)return ce;const pt=(En=F.find(fr=>fr.id===ke))==null?void 0:En.models.find(fr=>fr.id===it);if(pt)return gb({reasoningEfforts:pt.reasoningEfforts,thinkingLevel:pt.thinkingLevel,thinkingEnabled:pt.thinkingEnabled,override:pt.reasoningEffortOverride})},[Ve,De]=j.useState(!1);j.useEffect(()=>{function ke(it){C.current&&!C.current.contains(it.target)&&(c(!1),g([]),H.current=new Set)}return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[]),j.useEffect(()=>()=>{P.current!==null&&window.clearTimeout(P.current)},[]),j.useEffect(()=>{l||(Ao(""),us(-1))},[l]),j.useEffect(()=>{var ke;l&&Wt()&&((ke=Wr.current)==null||ke.focus())},[l]),j.useEffect(()=>{if(l){const ke=F.map(it=>it.id);g(ke),F.filter(it=>!!it.authAdapter).forEach(it=>void Ee(it.id)),ke.forEach(it=>{H.current.has(it)||(H.current.add(it),kt(it))})}},[l,F]),j.useEffect(()=>{if(!A)return;let ke=!1;const it=async()=>{const En=await Ee(A.providerId);ke||En==="connected"&&(M(null),U(!1),K(!1),await X(),H.current.delete(A.providerId),await kt(A.providerId))};it();const pt=window.setInterval(()=>void it(),2e3);return()=>{ke=!0,window.clearInterval(pt)}},[A]);const st=(Ze==null?void 0:Ze.status)==="disconnected",rt=(ke,it)=>t?tt===ke&&pe===it:!1,yt=(ke,it)=>Z?Z===`${ke}/${it}`:!1,kt=async ke=>{w(ke);try{await O(ke)}catch{}finally{w(null)}},qt=ke=>{f.includes(ke.id)?g(f.filter(it=>it!==ke.id)):(g([...f,ke.id]),kt(ke.id))},Mn=async ke=>{if(ke.id===Q){qt(ke);return}t&&e?(o(e,ke.id,void 0),c(!1),g([])):await B(ke.id)&&(c(!1),g([]))},qn=ke=>{qt(ke)},In=async()=>{t&&e&&(a(e),c(!1),g([]))},hr=async()=>{t&&e&&(d(e),c(!1),g([]))},Nr=async(ke,it)=>{ke.stopPropagation(),H.current.delete(it),await kt(it)},Ee=async ke=>{const it=await be(`/api/provider-auth/${ke}/status`);if(!it.ok)return"error";const pt=await it.json();return E(En=>({...En,[ke]:pt.state})),pt.state},nt=async(ke,it)=>{ke.stopPropagation(),L(it),E(pt=>({...pt,[it]:"pending"})),U(!1),K(!1);try{const pt=await be(`/api/provider-auth/${it}/login`,{method:"POST"});if(!pt.ok)throw new Error("Unable to start provider sign-in");const En=await pt.json();M({providerId:it,...En})}catch{E(pt=>({...pt,[it]:"error"}))}finally{L(null)}},qe=async()=>{var ke;A!=null&&A.userCode&&(await((ke=navigator.clipboard)==null?void 0:ke.writeText(A.userCode)),P.current!==null&&window.clearTimeout(P.current),U(!1),requestAnimationFrame(()=>U(!0)),P.current=window.setTimeout(()=>{U(!1),P.current=null},1500))},Be=()=>{A&&(window.open(A.directUrl??A.verificationUrl,"_blank","noopener,noreferrer"),K(!0))},me=()=>{M(null),U(!1),K(!1)},xe=async(ke,it)=>{ke.stopPropagation(),L(it);try{if(!(await be(`/api/provider-auth/${it}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");E(En=>({...En,[it]:"disconnected"})),await X()}finally{L(null)}},He=(ke,it)=>{S({providerId:ke,model:it}),v(!0)},Ue=b?F.find(ke=>ke.id===b.providerId):void 0,et=()=>{S(null),v(!1)},ut=async ke=>{try{if(!(await be(`/api/providers/${ke.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(RL(ke))})).ok)throw new Error("Failed to update provider");await Gt.getState().fetchConfig()}catch{}S(null),v(!1)},ht=async(ke,it,pt,En)=>{const fr=t;if(fr){if(Re.setState(Pi=>({...Pi,currentSession:{...fr,providerId:it,providerModel:pt,providerReasoningEffort:En,providerManual:!0,providerManualActive:!0}})),!await o(ke,it,pt,En))return Re.setState(Pi=>({...Pi,currentSession:fr})),!1}else if(!await o(ke,it,pt,En))return!1;return g([]),c(!1),Ol(),!0},Xt=async(ke,it,pt)=>{if(t&&e){if(!pt&&tt===ke&&pe===it){g([]),c(!1),Ol();return}if(pt){if(Uv({warmCache:n==null?void 0:n.warmCache,currentEffort:ce,proposedEffort:pt})&&await r.requestEffortSwitch({fromEffort:ce,toEffort:pt})==="keep"){await ht(e,ke,it,ce??null);return}await ht(e,ke,it,pt)&&await J(ke,it,{thinkingLevel:pt,thinkingEnabled:!0});return}await ht(e,ke,it,null);return}await B(ke)&&(g([]),c(!1),Ol())},pn=async(ke,it,pt)=>{ke.stopPropagation(),De(!0);try{await $(it,pt)&&t&&e&&await ht(e,it,pt,null)}catch{}finally{De(!1)}},{searchQuery:kn,setSearchQuery:Ao,highlightedIndex:Js,setHighlightedIndex:us,visibleGroups:Zs,flatItems:Tr,handleSearchKeyDown:ds,highlightedRef:Ls,inputRef:Wr}=kA({providers:F,onSelect:Xt,onEscape:()=>c(!1),extraItemCount:1}),jn=Js===Tr.length,td=ke=>{if(ke.key==="Enter"&&Js===Tr.length){ke.preventDefault(),c(!1),m(!0);return}ds(ke)};return F.length===0?s.jsxs("button",{type:"button",onClick:()=>D(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:st?"LLM server is offline. Click to retry.":ot??"Click to refresh model",children:[st?s.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):s.jsx(Rj,{activeProvider:Ze,shortModelName:ot,effort:ce,agentOverrideActive:Xe,agentColor:we,agentName:Ie==null?void 0:Ie.name,pinned:Je}),s.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):s.jsxs("div",{className:"relative",ref:C,children:[s.jsxs("button",{type:"button",onClick:()=>c(!l),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[st?s.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):s.jsx(Rj,{activeProvider:Ze,shortModelName:ot,effort:ce,agentOverrideActive:Xe,agentColor:we,agentName:Ie==null?void 0:Ie.name,pinned:Je}),s.jsx(mn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:l?180:0})]}),l&&s.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[s.jsxs("div",{className:"flex items-center gap-1 px-3 py-2 border-b border-border flex-shrink-0",children:[s.jsx(Gs,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),s.jsx("input",{ref:Wr,type:"text",value:kn,onInput:ke=>{Ao(ke.currentTarget.value),us(-1)},onKeyDown:td,placeholder:"Search models...",className:"bg-transparent border-none outline-none text-sm text-text-primary w-full placeholder:text-text-muted"})]}),s.jsx(xt,{className:"flex-1 min-h-0",children:s.jsxs("div",{children:[Zs.map(ke=>{const it=kn.trim().length>0||f.includes(ke.provider.id);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${ke.provider.id===tt?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${V?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[s.jsxs("div",{onClick:()=>!V&&Mn(ke.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[s.jsx("span",{className:`text-sm font-medium truncate ${ke.provider.id===tt?"text-accent-primary":"text-text-primary"}`,children:ke.provider.name}),s.jsx("span",{className:"text-xs text-text-muted truncate",children:ke.provider.backend!=="unknown"&&HE(ke.provider.backend)})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!ke.provider.authAdapter&&(k[ke.provider.id]==="connected"||ke.provider.credentialRef?s.jsx("button",{type:"button",onClick:pt=>xe(pt,ke.provider.id),disabled:T===ke.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-success/40 text-accent-success hover:bg-accent-success/10 disabled:opacity-50",title:"Disconnect provider account",children:"Connected"}):s.jsx("button",{type:"button",onClick:pt=>nt(pt,ke.provider.id),disabled:T===ke.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-primary/40 text-accent-primary hover:bg-accent-primary/10 disabled:opacity-50",title:"Connect provider account",children:T===ke.provider.id?"Starting…":k[ke.provider.id]==="error"||k[ke.provider.id]==="expired"?"Retry":"Connect"})),ke.provider.id===tt?s.jsx("span",{className:"text-accent-success",title:"Active provider",children:s.jsx(Ys,{className:"w-4 h-4"})}):s.jsx("span",{className:"w-4"}),s.jsx("button",{type:"button",onClick:pt=>{pt.stopPropagation(),Nr(pt,ke.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:s.jsx(dm,{className:`w-4 h-4 ${x===ke.provider.id?"animate-spin":""} ${ke.provider.id===Q?"text-accent-primary":"text-text-muted"}`})}),s.jsx("button",{type:"button",onClick:pt=>{pt.stopPropagation(),qn(ke.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:s.jsx(mn,{className:`w-4 h-4 transition-transform ${it?"rotate-180":""} ${ke.provider.id===Q?"text-accent-primary":"text-text-muted"}`})})]})]}),it&&s.jsx(xt,{className:"bg-bg-primary border-t border-border max-h-40",children:x===ke.provider.id?s.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):ke.models.length>0?ke.models.map(pt=>{const fr=Tr.findIndex(Lo=>Lo.providerId===ke.provider.id&&Lo.modelConfig.id===pt.id)===Js;return s.jsx("div",{ref:fr?Ls:void 0,children:s.jsx(CA,{providerId:ke.provider.id,modelConfig:pt,isActive:rt(ke.provider.id,pt.id),isDefault:yt(ke.provider.id,pt.id),disabled:x==="activating",hasSession:!!t,settingDefault:Ve,highlighted:fr,onModelClick:Xt,onSetDefault:pn,onEditModel:He,reasoningEfforts:pt.reasoningEfforts,selectedEffort:Oe(ke.provider.id,pt.id),onSelectEffort:Xt})},`${ke.provider.id}/${pt.id}`)}):s.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},ke.provider.id)}),Zs.length===0&&kn.trim()&&s.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No models match your search"})]})}),s.jsxs("div",{className:`border-t border-border px-3 py-2 flex items-center justify-between gap-2 ${jn?"bg-bg-tertiary":""} flex-shrink-0`,children:[Je&&s.jsx("button",{type:"button",onClick:hr,className:"text-xs text-text-muted hover:text-text-primary hover:underline",title:"Stop pinning the reasoning effort so agent overrides and session picks apply again",children:"Unpin reasoning effort"}),Ae&&s.jsx("button",{type:"button",onClick:In,className:"text-xs text-text-muted hover:text-text-primary hover:underline",title:"Clear this session's manually picked model so agent overrides and the global default apply again",children:"Reset to default"}),s.jsx("button",{onClick:()=>{c(!1),m(!0)},className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})]})]}),A&&s.jsxs(vt,{isOpen:!0,onClose:me,title:"Connect provider",size:"md",children:[s.jsx("p",{className:"text-sm text-text-muted",children:"Follow the provider instructions to complete authorization."}),A.mode!=="browser"?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:qe,className:"mt-6 w-full select-all rounded-lg border border-accent-primary/40 bg-bg-primary px-4 py-5 font-mono text-3xl font-semibold tracking-[0.2em] text-accent-primary hover:bg-bg-tertiary",title:"Copy code",children:A.userCode??"Continue"}),s.jsx("div",{className:"mt-3 text-center text-xs text-text-muted",children:I?"Copied to clipboard":"Click the code to copy it"}),s.jsxs("div",{className:"mt-6 flex gap-3",children:[s.jsx("button",{type:"button",onClick:qe,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:I?"Copied":"Copy code"}),s.jsx("button",{type:"button",onClick:Be,className:"flex-1 rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:z?"Reopen authorization":"Open authorization"})]}),s.jsx("p",{className:"mt-4 text-center text-xs text-text-muted",children:z?"If the browser blocked or closed the tab, reopen authorization.":"OpenFox stays open while you complete authorization in the other tab."})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"mt-6 text-sm text-text-secondary leading-relaxed bg-bg-primary p-4 rounded-lg border border-border",children:A.instructions}),s.jsx("div",{className:"mt-6 flex gap-3",children:s.jsx("button",{type:"button",onClick:Be,className:"w-full rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:z?"Reopen authorization":"Open authorization"})})]})]}),b&&_&&s.jsx(DL,{isOpen:!0,onClose:et,onSave:ut,initialStep:2,editProvider:{id:b.providerId,name:(Ue==null?void 0:Ue.name)??"",url:(Ue==null?void 0:Ue.url)??"",backend:(Ue==null?void 0:Ue.backend)??"unknown",apiKey:Ue==null?void 0:Ue.apiKey,isLocal:Ue==null?void 0:Ue.isLocal,thinkingField:Ue==null?void 0:Ue.thinkingField,sendReasoningInMessages:Ue==null?void 0:Ue.sendReasoningInMessages,authAdapter:Ue==null?void 0:Ue.authAdapter,transportAdapter:Ue==null?void 0:Ue.transportAdapter,models:Ue==null?void 0:Ue.models},editModelId:b.model.id}),s.jsx(zq,{isOpen:h,onClose:()=>{m(!1),X()}})]})}function Uq(){const e=Eu(k=>k.servers),t=Eu(k=>k.fetchServers),n=Re(k=>k.currentSession),r=n==null?void 0:n.id,[o,a]=j.useState(!1),[d,l]=j.useState(null),[c,h]=j.useState(new Set),[m,f]=j.useState(new Set),g=j.useRef(null),x=j.useCallback(async()=>{if(r)try{const k=await be(`/api/sessions/${r}/mcp/overrides`);if(k.ok){const E=await k.json();f(new Set(E.disabledServers??[]))}}catch{}},[r]),w=j.useCallback(async()=>{await t(),await x()},[t,x]);j.useEffect(()=>{const k=()=>w();return window.addEventListener("mcp-servers-changed",k),()=>window.removeEventListener("mcp-servers-changed",k)},[w]),j.useEffect(()=>{x()},[x]),j.useEffect(()=>{o&&x()},[o,x]),zm(g,()=>a(!1));const C=k=>m.has(k.name),b=e.filter(k=>k.status==="connected"&&!C(k)),S=b.length,_=b.reduce((k,E)=>k+E.estimatedTokens,0),v=async(k,E)=>{if(r){l(null),h(T=>new Set(T).add(k));try{const T=new Set(m);E?T.add(k):T.delete(k);const L=await be(`/api/sessions/${r}/mcp/overrides`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledServers:Array.from(T)})});if(!L.ok){const A=await L.json().catch(()=>({}));throw new Error(A.error??"Toggle failed")}f(T),await t()}catch(T){l(T instanceof Error?T.message:String(T))}finally{h(T=>{const L=new Set(T);return L.delete(k),L})}}};return s.jsxs("div",{className:"relative",ref:g,children:[s.jsxs("button",{type:"button",onClick:()=>a(!o),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:S>0?`${S} MCP server(s) active`:"No MCP server active",children:[s.jsx("span",{className:"text-sm text-accent-primary whitespace-nowrap",children:S>0?`● ${S} MCP (${Df(_)})`:"MCP"}),s.jsx(mn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:o?180:0})]}),o&&s.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[s.jsx(xt,{className:"flex-1 min-h-0",children:e.length===0?s.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No MCP servers configured"}):e.map(k=>{const E=C(k),T=c.has(k.name);return s.jsx("div",{children:s.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-bg-tertiary",children:[s.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[s.jsx("span",{className:`text-sm ${$v(E?"disabled":k.status)}`,children:Fv(E?"disabled":k.status)}),s.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:k.name})]}),s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[s.jsxs("span",{children:[k.tools.length," tools"]}),k.estimatedTokens>0&&s.jsxs("span",{children:[Df(k.estimatedTokens)," tokens"]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[T&&s.jsx("span",{className:"text-xs text-text-muted animate-pulse",children:"..."}),s.jsx(ks,{enabled:!E,onClick:()=>v(k.name,!E)})]})]})},k.name)})}),s.jsx("div",{className:"border-t border-border px-3 py-2 flex-shrink-0",children:d?s.jsx("div",{className:"text-xs text-accent-error",children:d}):s.jsxs("span",{className:"text-xs text-text-muted",children:[e.length," server(s) configured"]})})]})]})}const Dj=24,Oj=200;function Vq({input:e,setInput:t,attachments:n,setAttachments:r,dragOver:o,setDragOver:a,errorMessage:d,setErrorMessage:l,scrollToBottom:c,sessionId:h,showHistory:m,history:f,selectedIndex:g,openHistory:x,closeHistory:w,navigateUp:C,navigateDown:b,selectCurrent:S,isAutoScrollActive:_,setAutoScroll:v,onOpenMessageSearch:k,onOpenCommandsModal:E,onOpenWorkflowsModal:T,onSelectWorkflow:L,onSelectWorkflowWithSubGroup:A,onSendCommand:M,clearInput:I}){const U=j.useRef(null),P=j.useRef(null),z=j.useRef(0),K=j.useRef(0),H=j.useRef(null),F=j.useRef(null),Q=om(h),Z=Re(pe=>pe.stopGeneration),V=Re(pe=>pe.cancelQueued),B=wO(h),D=Vt(h,pe=>pe.restoredInput??null,pe=>pe.restoredInput,null),O=Re(pe=>pe.clearRestoredInput),$=Vt(h,pe=>{var Ge;return((Ge=pe.session)==null?void 0:Ge.workdir)??void 0},pe=>{var Ge;return(Ge=pe.currentSession)==null?void 0:Ge.workdir},void 0),J=Vt(h,pe=>pe.session??null,pe=>pe.currentSession,null),X=j.useRef(!1),Y=j.useRef(void 0),q=j.useRef(!1),[W,ee]=j.useState([]),ie=j.useRef(null),{sendMessage:re,launchWorkflow:se}=AL(v,h);j.useEffect(()=>{Y.current!==$&&(Y.current=$,Pt.getState().fetchWorkflows($),ln.getState().fetchCommands($))},[$]),j.useEffect(()=>{e||ee([])},[e]),j.useEffect(()=>{var pe;D!==null&&(t(D),O(h),Wt()&&((pe=U.current)==null||pe.focus()))},[D,t,O]);const de=j.useCallback((pe={})=>{const Ge=U.current;if(!Ge)return;if(!e){Ge.style.height=`${Dj}px`;return}const Je=e.length>=z.current;z.current=e.length,(pe.force||!Je)&&(Ge.style.height="auto"),Ge.style.height=`${Math.min(Oj,Ge.scrollHeight)}px`},[e]),Se=j.useRef(de);j.useEffect(()=>{Se.current=de},[de]),j.useEffect(()=>{if(!h)return;const pe=`openfox:draft:${h}`,Ge=localStorage.getItem(pe);Ge!==null&&t(Ge)},[h,t]),j.useEffect(()=>{var pe;Wt()&&((pe=U.current)==null||pe.focus()),de()},[h,de]),j.useEffect(()=>{if(!h)return;const pe=`openfox:draft:${h}`,Ge=setTimeout(()=>{e?localStorage.setItem(pe,e):localStorage.removeItem(pe)},500);return()=>clearTimeout(Ge)},[h,e]),j.useEffect(()=>{de()},[e,de]),j.useEffect(()=>{var ot;const pe=(ot=U.current)==null?void 0:ot.parentElement;if(!pe||typeof ResizeObserver>"u")return;let Ge=pe.clientWidth;const Je=new ResizeObserver(()=>{const Ze=pe.clientWidth;Ze!==Ge&&(Ge=Ze,Se.current({force:!0}))});return Je.observe(pe),()=>Je.disconnect()},[]),j.useEffect(()=>{const pe=U.current;if(!pe)return;const Ge=async Je=>{var at;if(document.activeElement!==pe)return;const ot=(at=Je.clipboardData)==null?void 0:at.items;if(!ot)return;const Ze=[];for(const ce of Array.from(ot)){let Oe=ce.getAsFile();if(Oe&&AU(Oe.type)){if(Je.preventDefault(),!Oe.name){const Ve=TU(Oe.type);Oe=new File([Oe],`pasted-file.${Ve}`,{type:Oe.type})}await yb(Oe,Ve=>Ze.push(Ve),l)}}Ze.length>0&&r(ce=>[...ce,...Ze])};return pe.addEventListener("paste",Ge),()=>pe.removeEventListener("paste",Ge)},[r,l]);const Me=pe=>{pe.preventDefault(),!(!e.trim()&&n.length===0)&&we()},ye=pe=>{var Ge,Je;if(!((Ge=F.current)!=null&&Ge.handleKeyDown(pe))&&!((Je=H.current)!=null&&Je.handleKeyDown(pe))){if(m)switch(pe.key){case"Enter":{pe.preventDefault();const ot=S();ot&&(t(ot),w());return}case"Escape":pe.preventDefault(),w(),Q&&h&&Z(h);return;case"ArrowUp":pe.preventDefault(),C();return;case"ArrowDown":pe.preventDefault(),b();return}if(pe.key==="ArrowUp"&&e.trim()===""&&!m){pe.preventDefault(),x();return}pe.key==="Enter"&&!pe.shiftKey&&(pe.preventDefault(),Me(pe))}};async function ue(pe,Ge,Je){const ot=[];for(const Ze of Array.from(pe))await yb(Ze,at=>ot.push(at),Je);ot.length>0&&Ge(Ze=>[...Ze,...ot])}const Ie=j.useCallback(async pe=>{const Ge=pe.target.files;!Ge||Ge.length===0||(l(null),await ue(Ge,r,l),P.current&&(P.current.value=""))},[r,l]),We=j.useCallback(pe=>{var Ge;(Ge=pe.dataTransfer.types)!=null&&Ge.includes("Files")&&(pe.preventDefault(),pe.stopPropagation(),a(!0))},[a]),Qe=j.useCallback(pe=>{pe.preventDefault(),pe.stopPropagation(),a(!1)},[a]),ve=j.useCallback(async pe=>{pe.preventDefault(),pe.stopPropagation(),a(!1),l(null);const Ge=pe.dataTransfer.files;!Ge||Ge.length===0||await ue(Ge,r,l)},[r,a,l]),oe=j.useCallback(pe=>{r(n.filter(Ge=>Ge.id!==pe))},[n,r]),ae=j.useCallback(()=>{var pe;(pe=P.current)==null||pe.click()},[]),we=()=>{if(q.current||!e.trim()&&n.length===0)return;if(q.current=!0,c==null||c(),e.trim().startsWith("/")){const Ge=ka(Pt.getState()),Je=ln.getState(),ot=ir(ir(Je.defaults,Je.userItems),Je.projectItems),Ze=pq(e,Ge,ot);if(Ze!=null&&Ze.workflowId){const at=ie.current,ce=at&&at.id===Ze.workflowId?at.scope:"auto";ie.current=null;const Oe=If(Ge,Ze.workflowId,ce),Ve=((Oe==null?void 0:Oe.parameters)??[]).filter(De=>De.required&&!(De.id in Ze.params));if(Ve.length>0){const De=Ve.map(st=>st.label||st.id).join(", ");l(`Missing required parameter${Ve.length>1?"s":""}: ${De}`),q.current=!1;return}se(void 0,void 0,Ze.workflowId,void 0,Ze.params,ce),I(),q.current=!1;return}if(Ze!=null&&Ze.commandId){Je.fetchCommand(Ze.commandId,$).then(at=>{if(at){const ce=kL(at.prompt),Oe={};for(const[De,st]of Object.entries(Ze.params)){const rt=parseInt(De,10),yt=ce[rt];yt&&(Oe[yt]=st)}let Ve=at.prompt;for(const[De,st]of Object.entries(Oe))Ve=Ve.replaceAll(`{{${De}}}`,st);M(Ve,at.metadata.agentMode),I()}q.current=!1});return}}re(e,n),I(),q.current=!1},$e=j.useCallback((pe,Ge)=>{const ot=pe.type==="directory"?"/":" ",{newText:Ze,newCursorPos:at}=Pf(e,K.current,Ge,`@${pe.path}${ot}`);t(Ze),K.current=at,Bf(U.current,at)},[e,t]),fe=j.useCallback((pe,Ge)=>{const{newText:Je,newCursorPos:ot}=Pf(e,K.current,Ge,`/${pe.id} `);t(Je),K.current=ot,Bf(U.current,ot),pe.type==="workflow"&&(ie.current={id:pe.id,scope:pe.scope}),ee(AA(pe))},[e,t]),Ae=j.useCallback(pe=>{const Ge=pe.target.value;t(Ge),m&&w(),K.current=pe.target.selectionStart;const Je=ie.current;if(Je){const ot=Ge.match(/^\/(\S+)/),Ze=ot?ot[1]:void 0;(!Ze||Ze!==Je.id)&&(ie.current=null)}W.length>0&&(!Ge.startsWith("/")||!Ge.includes(" "))&&ee([]),!X.current&&h&&Ge&&J&&(J.messageCount??0)===0&&(X.current=!0,be(`/api/sessions/${h}/warmup`,{method:"POST"}).catch(()=>{}))},[t,m,w,h,J,W]),Xe=j.useCallback(pe=>{K.current=pe.target.selectionStart},[]),tt=j.useCallback(pe=>{K.current=pe.currentTarget.selectionStart},[]);return s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"absolute -top-8 left-2 @md:left-4 z-10",children:s.jsx(_q,{})}),s.jsxs("div",{className:`absolute -top-8 right-2 @md:right-4 z-10 flex items-center gap-2 border${_?" border-transparent":" rounded backdrop-blur-xl saturate-150 border-border"}`,children:[s.jsx(Qv,{isActive:_,onToggle:v,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),s.jsxs("button",{type:"button",onClick:k,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Browse history",children:[s.jsx(Gs,{}),"Browse history"]})]}),s.jsx(Sq,{}),s.jsxs("form",{onSubmit:Me,className:"p-2 @md:p-4 bg-secondary rounded-lg",children:[s.jsx("input",{ref:P,type:"file",accept:"image/*,text/*,.pdf,.json,.xml,.yaml,.yml,.js,.sh,.xhtml",onChange:Ie,className:"hidden",multiple:!0}),d&&s.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:d}),n.length>0&&s.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:n.map(pe=>s.jsx(Hv,{attachment:pe,onRemove:oe},pe.id))}),m&&s.jsx(gq,{history:f,selectedIndex:g,onSelect:pe=>{t(pe),w()},onEscape:w,onNavigate:pe=>{pe==="up"?C():b()}}),s.jsx(Tq,{messages:B,onCancel:pe=>h&&V(h,pe)}),s.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${o?"bg-accent-primary/10":"bg-primary"}`,onDragOver:We,onDragLeave:Qe,onDrop:ve,children:[s.jsxs("div",{className:"relative flex-1 min-w-0",children:[s.jsx("textarea",{id:dA,ref:U,value:e,onChange:Ae,onKeyDown:ye,onSelect:Xe,onKeyUp:tt,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",className:"w-full bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:`${Dj}px`,maxHeight:`${Oj}px`},spellCheck:!1}),s.jsx(TA,{ref:H,text:e,cursorPos:K.current,workdir:$,onSelect:$e}),s.jsx(NA,{ref:F,text:e,cursorPos:K.current,workflows:ka(Pt.getState()),commands:(()=>{const pe=ln.getState();return ir(ir(pe.defaults,pe.userItems),pe.projectItems)})(),onSelect:fe}),W.length>0&&(()=>{const pe=e.match(/\/(\w+)\s+(.*)$/),Je=(pe?pe[2].trim().split(/\s+/):[]).filter(Boolean).length,ot=W[Je];return ot?s.jsxs("span",{className:"absolute left-3 top-[26px] text-sm text-text-muted/40 pointer-events-none select-none","aria-hidden":!0,children:[ot,"=?"]}):null})()]}),s.jsxs("div",{className:"flex items-center self-center gap-1.5",children:[Q&&s.jsxs("button",{type:"button",onClick:()=>h&&Z(h),"data-testid":"chat-stop-button",className:"flex items-center gap-1 px-4 py-1.5 rounded bg-accent-error/20 text-sm text-accent-error font-medium hover:bg-accent-error/30 transition-colors whitespace-nowrap",children:[s.jsx(Xb,{}),"Abort"]}),s.jsxs("div",{className:"flex items-center",children:[s.jsx("button",{type:"button",onClick:we,disabled:!e.trim()&&n.length===0,"data-testid":"chat-send-button",className:"px-4 py-1.5 rounded-l bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:"Send"}),s.jsx(Eq,{onSendCommand:M,onSelectWorkflow:L,onSelectWorkflowWithSubGroup:A,onOpenCommandsManager:E,onOpenWorkflowsManager:T,onAttach:ae,textareaContent:e,attachments:n.length>0?n:void 0})]})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Iq,{}),s.jsx(Pq,{})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[It(pe=>pe.settings)[Te.FEATURES_PER_SESSION_MCP]==="true"&&s.jsx(Uq,{}),s.jsx(Hq,{})]})]})]})]})}const Wq=4;function Gq({projectId:e,sessionId:t}){const n=zt(w=>w.tasks),r=zt(w=>w.activeProjectId),o=zt(w=>w.loadBoard),a=zt(w=>w.moveTask),d=zt(w=>w.lastError),[l,c]=j.useState(!1),[h,m]=j.useState(null);j.useEffect(()=>{r!==e&&o(e)},[r,e,o]);const f=j.useMemo(()=>n.filter(w=>w.status==="todo"&&w.sessionIds.length===0).sort((w,C)=>w.position-C.position).slice(0,Wq),[n]),g=j.useMemo(()=>n.filter(w=>w.status==="in_progress"&&w.runState==="running").length,[n]);if(f.length===0)return null;const x=async w=>{var b;m(null);const C=await a(e,w.id,"in_progress",{sessionId:t});C!=null&&C.task&&C.task.status==="in_progress"&&C.task.runState==="queued"&&m({label:((b=w.prompt.split(`
|
|
305
|
+
`,children:[s.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[h.formattedTimestamp,h.sessionName&&s.jsxs(s.Fragment,{children:[" | ",s.jsx("span",{className:"text-accent-primary font-medium",children:h.sessionName})]})]}),s.jsx("div",{className:"text-sm text-text-primary mt-1",children:h.trimmedContent})]},h.id))})}function xq(e){const{phase:t,isRunning:n,pendingQuestionsCount:r,pendingConfirmationsCount:o,activeWorkflow:a}=e;let d=null;t==="waiting"||r>0||o>0?d="waiting":t==="blocked"?d="blocked":t==="done"&&!n?d="completed":n&&(d="running");const l=r>0||o>0,c=(a==null?void 0:a.currentStepName)??null;return{state:d,waitingForUser:l,workflowStep:c,lastPromptAt:null}}function yq(e){if(!e||e.length===0)return null;for(let t=e.length-1;t>=0;t--){const n=e[t];if(!(!n||n.role!=="user")&&(n.messageKind==="workflow-started"||!n.isSystemGenerated&&!n.messageKind))return n.timestamp}return null}function bq(e){const{currentSession:t,messages:n=[],pendingQuestions:r,pendingPathConfirmations:o,activeWorkflowExecution:a}=e;return t?{...xq({phase:t.phase,isRunning:t.isRunning,pendingQuestionsCount:(r==null?void 0:r.length)??0,pendingConfirmationsCount:(o==null?void 0:o.length)??0,activeWorkflow:a}),lastPromptAt:yq(n)}:{state:null,waitingForUser:!1,workflowStep:null,lastPromptAt:null}}function vq(e){switch(e){case"running":return"Running";case"waiting":return"Waiting for input";case"completed":return"Completed";case"blocked":return"Blocked";case null:return""}}function _q(){const e=Re(b=>b.abortInProgress),t=Re(b=>b.currentSession),n=Re(b=>b.messages),r=Re(b=>b.pendingQuestions),o=Re(b=>b.pendingPathConfirmations),a=Re(b=>b.activeWorkflowExecution),d=bq({currentSession:t,messages:n,pendingQuestions:r,pendingPathConfirmations:o,activeWorkflowExecution:a}),l=d.state,c=d.lastPromptAt,[h,m]=j.useState(()=>Date.now()),f=c!==null&&(l==="running"||l==="waiting");if(j.useEffect(()=>{if(!f)return;m(Date.now());const b=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(b)},[f]),l===null)return null;const g=vq(l),x=e?"bg-amber-400":"bg-accent-primary",w=l==="running",C=c?pU(c,h):"";return s.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2","data-testid":"session-status-indicator","data-state":l,children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[w&&s.jsxs("span",{className:"flex gap-0.5",children:[s.jsx("span",{className:`w-1 h-1 rounded-full ${e?"":"animate-bounce"} ${x}`,style:{animationDelay:"0ms"}}),s.jsx("span",{className:`w-1 h-1 rounded-full ${e?"":"animate-bounce"} ${x}`,style:{animationDelay:"150ms"}}),s.jsx("span",{className:`w-1 h-1 rounded-full ${e?"":"animate-bounce"} ${x}`,style:{animationDelay:"300ms"}})]}),s.jsx("span",{className:"text-text-secondary",children:e&&l==="running"?`${g} (abort in progress)`:g})]}),!e&&l==="running"&&s.jsx("span",{className:"text-text-muted hidden sm:inline",children:"esc to interrupt"}),f&&C&&s.jsx("span",{className:"text-text-muted hidden sm:inline","aria-label":"time since last prompt",children:C})]})}function Sq(){const e=Vr(),t=Vt(e,l=>l.activeWorkflowExecution??null,l=>l.activeWorkflowExecution,null),n=Re(l=>l.exitWorkflow),[r,o]=j.useState(!1);j.useEffect(()=>{o(!1)},[t==null?void 0:t.id]);const a=j.useCallback(()=>{r||!e||(o(!0),n(e))},[r,n,e]);if(!t||t.status!=="running"&&t.status!=="waiting")return null;const d=t.workflowColor&&/^#[0-9a-fA-F]{6}$/.test(t.workflowColor)?t.workflowColor:"#3b82f6";return s.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-xs border-b border-border",children:[s.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:d}}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:t.workflowName}),t.currentStepName&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"text-text-muted truncate",children:t.currentStepName})]}),s.jsx("div",{className:"ml-auto shrink-0",children:s.jsx("button",{onClick:a,disabled:r,className:"text-xs px-2 py-0.5 rounded text-text-tool-error hover:bg-text-tool-error/10 transition-colors disabled:opacity-50",children:r?"Exiting...":"✕ Exit"})})]})}const jL=j.createContext(null);function wq({children:e}){const[t,n]=j.useState(null),r=j.useCallback(d=>new Promise(l=>{n({info:d,resolve:l})}),[]),o=j.useCallback(d=>{n(l=>(l==null||l.resolve(d),null))},[]),a=j.useMemo(()=>({requestEffortSwitch:r}),[r]);return s.jsxs(jL.Provider,{value:a,children:[e,t&&s.jsxs(vt,{isOpen:!0,onClose:()=>o("keep"),title:"Reasoning effort change",size:"sm",children:[s.jsxs("p",{className:"text-sm text-text-secondary",children:[t.info.contextLabel?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-primary font-medium",children:t.info.contextLabel})," runs with reasoning effort ",s.jsx("code",{className:"text-accent-primary",children:t.info.toEffort}),Nj(t.info),"."]}):s.jsxs(s.Fragment,{children:["Switching the reasoning effort to ",s.jsx("code",{className:"text-accent-primary",children:t.info.toEffort}),Nj(t.info),"."]})," ","This may invalidate the LLM prefix cache — if it does, the next response will take longer while the context is reprocessed."]}),s.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[s.jsx(Ej,{onClick:()=>o("keep"),variant:"secondary",children:"Keep current reasoning effort"}),s.jsx(Ej,{onClick:()=>o("apply"),variant:"danger",children:"Apply the reasoning effort (invalidates cache)"})]})]})]})}function Ej({onClick:e,variant:t,children:n}){const r=t==="primary"?"px-3 py-1.5 text-sm rounded bg-accent-primary text-white hover:opacity-90 transition-colors":t==="danger"?"px-3 py-1.5 text-sm rounded bg-accent-error text-white hover:opacity-90 transition-colors":"px-3 py-1.5 text-sm rounded bg-bg-tertiary text-text-primary hover:bg-border transition-colors";return s.jsx("button",{type:"button",onClick:e,className:r,children:n})}function Nj(e){return!e.fromEffort||e.fromEffort===e.toEffort?null:s.jsxs(s.Fragment,{children:[" ","(currently ",s.jsx("code",{className:"text-text-primary",children:e.fromEffort}),")"]})}function EL(){const e=j.useContext(jL);if(!e)throw new Error("useEffortChangeGate must be used within EffortChangeGateProvider");return e}function NL(e){var z,K;const t=Vr(),n=e??t,r=Vt(n,H=>H.session??null,H=>H.currentSession,null),o=Vt(n,H=>H.contextState??null,H=>H.contextState,null),a=EL(),d=Gt(H=>H.providers),l=Gt(H=>H.defaultModelSelection),{data:c}=Mi(er,r==null?void 0:r.workdir),h=(c==null?void 0:c.modelOverrides)??{},m=r==null?void 0:r.mode,f=m?h[m]??void 0:void 0,g=f?Ca(f):void 0,x=g==null?void 0:g.reasoningEffort,w=!!(r!=null&&r.providerManual)&&!!(r!=null&&r.providerManualActive),C=(r==null?void 0:r.providerId)??null,b=(r==null?void 0:r.providerModel)??null,S=(l==null?void 0:l.split("/")[0])??null,_=(l==null?void 0:l.split("/").slice(1).join("/"))??null,v=w?C:(g==null?void 0:g.providerId)??C??S,k=w?b:(g==null?void 0:g.model)??b??_,E=v?(z=d.find(H=>H.id===v))==null?void 0:z.models.find(H=>H.id===k):void 0,T=(E==null?void 0:E.reasoningEffortOverride)??(E!=null&&E.thinkingEnabled?E.thinkingLevel:void 0),L=Kk({session:r,agentOverrideEffort:x,modelDefaultEffort:T}),A=w?C:C??S,M=w?b:b??_,I=A?(K=d.find(H=>H.id===A))==null?void 0:K.models.find(H=>H.id===M):void 0,U=(I==null?void 0:I.reasoningEffortOverride)??(I!=null&&I.thinkingEnabled?I.thinkingLevel:void 0),P=Kk({session:r,agentOverrideEffort:void 0,modelDefaultEffort:U});return{sessionId:n,currentEffort:L,sessionOwnEffort:P,warmCache:o==null?void 0:o.warmCache,gate:a,modelOverrides:h}}function TL(e){const{sessionId:t,currentEffort:n,sessionOwnEffort:r,warmCache:o,gate:a,modelOverrides:d}=NL(e),l=Re(m=>m.switchMode),c=Re(m=>m.pinSessionEffort),h=Re(m=>m.clearSessionEffortPin);return j.useCallback(async(m,f)=>{var w;if(!t)return;const x=((w=Ca(d[m]))==null?void 0:w.reasoningEffort)??r;x&&Uv({warmCache:o,currentEffort:n,proposedEffort:x})&&(await a.requestEffortSwitch({fromEffort:n,toEffort:x,contextLabel:f})==="keep"?n&&await c(t,n):await h(t)),await l(t,m)},[t,o,n,r,a,l,c,h,d])}function Cq(e){var n,r,o,a,d,l;const t=Re.getState();return e?((a=(o=(r=t.panes)==null?void 0:r[e])==null?void 0:o.session)==null?void 0:a.workdir)??(((d=t.currentSession)==null?void 0:d.id)===e?(l=t.currentSession)==null?void 0:l.workdir:void 0):(n=t.currentSession)==null?void 0:n.workdir}function AL(e,t){const n=Re(f=>f.sendMessage),r=Re(f=>f.launchWorkflow),o=Re(f=>f.pinSessionEffort),a=Re(f=>f.clearSessionEffortPin),{currentEffort:d,warmCache:l,gate:c}=NL(t),h=j.useCallback((f,g,x)=>{e(!0),t&&n(t,f,g,x)},[e,n,t]),m=j.useCallback(async(f,g,x,w,C,b="auto")=>{var S,_;if(e(!0),!!t){if(x&&l){const v=((S=K9(Cq(t)))==null?void 0:S.modelOverrides)??{};if(Object.values(v).some(E=>{var T;return(T=Ca(E))==null?void 0:T.reasoningEffort})){const E=ka(Pt.getState()),T=If(E,x,b);if(T){const L=await Pt.getState().fetchWorkflow(T.id,Pt.getState().workdir,T.scope),A=L?MU(L,w):void 0,M=A?(_=Ca(v[A]))==null?void 0:_.reasoningEffort:void 0;M&&Uv({warmCache:l,currentEffort:d,proposedEffort:M})&&(await c.requestEffortSwitch({fromEffort:d,toEffort:M,contextLabel:T.name})==="keep"?d&&await o(t,d):await a(t))}}}r(t,f,g,x,w,C,b)}},[e,r,t,l,d,c,o,a]);return{sendMessage:h,launchWorkflow:m}}function kq({children:e}){return Di.createPortal(e,document.body)}function jq(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function Eq({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:o,onAttach:a,textareaContent:d,attachments:l}){const[c,h]=j.useState(!1),[m,f]=j.useState("commands"),[g,x]=j.useState(""),[w,C]=j.useState(0),[b,S]=j.useState(null),[_,v]=j.useState(null),k=j.useRef(null),E=j.useRef(null),T=ln(O=>O.defaults),L=ln(O=>O.userItems),A=ln(O=>O.projectItems),M=ln(O=>O.fetchCommands),I=Pt(O=>O.fetchWorkflows),U=Re(O=>{var $;return($=O.currentSession)==null?void 0:$.workdir}),P=ir(ir(T,L),A),z=Ju();j.useEffect(()=>{c&&(m==="commands"?M(U):m==="workflows"&&I(U))},[c,m,M,I,U]),j.useEffect(()=>{c&&(x(""),C(0),requestAnimationFrame(()=>{var O;Wt()&&((O=k.current)==null||O.focus())}))},[c,m]),j.useEffect(()=>{if(!c)return;const O=$=>{var J;(J=E.current)!=null&&J.contains($.target)||h(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[c]);const K=O=>{switch(O.key){case"ArrowDown":O.preventDefault(),C($=>{const X=(m==="commands"?P:z).filter(Y=>{const q=g.toLowerCase();return!q||Y.name.toLowerCase().includes(q)});return Math.min($+1,X.length-1)});break;case"ArrowUp":O.preventDefault(),C($=>Math.max($-1,0));break;case"Enter":O.preventDefault();break;case"Escape":O.preventDefault(),h(!1);break}},H=O=>{x(O),C(0)},F=P.filter(O=>!g||O.name.toLowerCase().includes(g.toLowerCase())),Q=z.filter(O=>!g||O.name.toLowerCase().includes(g.toLowerCase())),Z=async O=>{const $=await ln.getState().fetchCommand(O,U);$&&e($.prompt,$.metadata.agentMode,d,l),h(!1)},V=(O,$)=>{t(O,$),h(!1)},B=(O,$)=>{$.stopPropagation(),h(!1),S(O)},D=(O,$)=>{$.stopPropagation(),h(!1),v(O)};return s.jsxs("div",{ref:E,className:"relative",children:[s.jsx("button",{type:"button",onClick:()=>h(!c),className:"px-1.5 py-2 rounded-r bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors border-l border-border/50",title:"More options",children:s.jsx(nN,{className:"w-4 h-4"})}),c&&s.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[s.jsxs("div",{className:"flex border-b border-border",children:[s.jsx("button",{type:"button",onClick:()=>{f("commands"),x(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${m==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),s.jsx("button",{type:"button",onClick:()=>{f("workflows"),x(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${m==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),s.jsx("button",{type:"button",onClick:()=>f("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${m==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),m!=="attach"&&s.jsx("div",{className:"p-2 border-b border-border",children:s.jsx("input",{ref:k,value:g,onChange:O=>H(O.target.value),onKeyDown:K,placeholder:m==="commands"?"Search commands...":"Search workflows...",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),s.jsx(xt,{className:"max-h-64 p-1",children:m==="commands"?F.length===0?s.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:P.length===0?"No commands yet":"No matches"}):F.map((O,$)=>s.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${$===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[s.jsx("button",{type:"button",onClick:()=>Z(O.id),className:"flex-1 text-left",children:s.jsx("div",{className:"text-sm text-text-primary font-medium",children:O.name})}),s.jsx(Li,{className:"opacity-0 group-hover:opacity-100",onClick:J=>B(O.id,J)})]},O.id)):m==="workflows"?Q.length===0?s.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:z.length===0?"No workflows yet":"No matches"}):Q.map((O,$)=>{const J=jq(O),X=O.color??"#3b82f6";return s.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${$===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[s.jsxs("button",{type:"button",onClick:()=>V(O.id,O.scope),className:"flex-1 text-left flex items-center gap-2",children:[s.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:X}}),s.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:O.name}),s.jsx("span",{className:"text-[10px] text-text-muted bg-bg-tertiary px-1.5 py-0.5 rounded whitespace-nowrap",children:Wv[O.scope]}),J!==null&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:J?"#22c55e":"#6b7280"},title:J?"Entry condition met":"Entry condition not met"})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[O.subGroups&&O.subGroups.length>0&&s.jsx(Nq,{subGroups:O.subGroups,onSelect:Y=>{h(!1),n(O.id,Y,O.scope)}}),s.jsx(Li,{className:"opacity-0 group-hover:opacity-100",onClick:Y=>D(O.id,Y)})]})]},`${O.id}-${O.scope}`)}):s.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>{a(),h(!1)},className:"flex items-center gap-2 px-4 py-2 rounded bg-bg-tertiary hover:bg-accent-primary/20 text-text-primary transition-colors",children:[s.jsx(eN,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Attach file"})]}),s.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),m!=="attach"&&s.jsx("div",{className:"border-t border-border p-1",children:s.jsx("button",{type:"button",onClick:()=>{h(!1),m==="commands"?r():o()},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:m==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),s.jsx(bL,{isOpen:!!b,onClose:()=>S(null),initialEditId:b,projectDir:U}),s.jsx(SL,{isOpen:!!_,onClose:()=>v(null),initialEditId:_})]})}function Nq({subGroups:e,onSelect:t}){const[n,r]=j.useState(!1),[o,a]=j.useState({top:0,right:0}),d=j.useRef(null),l=j.useRef(null);zm(l,()=>r(!1),n);const c=h=>{if(h.stopPropagation(),!n&&d.current){const m=d.current.getBoundingClientRect();a({top:m.bottom+4,right:window.innerWidth-m.right})}r(!n)};return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:d,type:"button",onClick:c,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&s.jsx(kq,{children:s.jsx("div",{ref:l,onMouseDown:h=>h.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:o.top,right:o.right},children:e.map(h=>s.jsx("button",{type:"button",onClick:m=>{m.stopPropagation(),t(h)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:h},h))})})]})}function Tq({messages:e,onCancel:t}){return e.length===0?null:s.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>s.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[s.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),s.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),s.jsx(Qu,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function Aq({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:r,model:o,onView:a,onEdit:d,onDuplicate:l,onDelete:c,onCancelDelete:h}){var g;const m=e.allowedTools.filter(x=>!(r!=null&&r.has(x))),f=o?(g=o.split("/").pop())==null?void 0:g.replace(/-/g," "):void 0;return s.jsxs(xN,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:d,onDuplicate:l,onDelete:c,onCancelDelete:h,children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),s.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),s.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"}),f&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-accent-primary/10 text-accent-primary",children:f})]}),e.description&&s.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),s.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[m.slice(0,5).map(x=>s.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:x},x)),m.length>5&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",m.length-5," more"]})]})]})}function Tj({title:e,agentTitle:t="Agents",subagentTitle:n="Sub-agents",agents:r,subagents:o,isBuiltIn:a,alwaysAllowedNames:d,modelOverrides:l,onView:c,onDuplicate:h,onEdit:m,onDelete:f,onCancelDelete:g,isConfirmingDelete:x}){if(r.length===0&&o.length===0)return null;const w=C=>s.jsx(Aq,{agent:C,model:l==null?void 0:l[C.id],isBuiltIn:a,isConfirmingDelete:(x==null?void 0:x(C.id))??!1,alwaysAllowedNames:d,onView:()=>c(C.id),onEdit:m?()=>m(C.id):void 0,onDuplicate:()=>h(C.id),onDelete:a?void 0:()=>f==null?void 0:f(C.id),onCancelDelete:a?void 0:()=>g==null?void 0:g(C.id)},C.id);return s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),r.length>0&&s.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:t}),s.jsxs("div",{className:"space-y-2",children:[r.map(w),o.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:n}),s.jsx("div",{className:"space-y-2",children:o.map(w)})]})]})]})}function Lq(e){const t=new Map;for(const n of e){const r=n.indexOf(":");if(r===-1)t.set(n,new Set);else{const o=n.slice(0,r),d=n.slice(r+1).split(",").filter(Boolean);t.set(o,new Set(d))}}return t}function Wh(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function Rq({formName:e,formId:t,formDescription:n,formSubagent:r,formTools:o,formColor:a,formModel:d,formPrompt:l,formError:c,isReadOnly:h,availableTools:m,providers:f,onNameChange:g,onIdChange:x,onDescriptionChange:w,onSubagentChange:C,onToolsChange:b,onColorChange:S,onModelChange:_,onPromptChange:v}){const k=Lq(o),E=m.filter(I=>!(r&&I.topLevelOnly)&&!I.isMcp),T=m.filter(I=>I.isMcp&&!(r&&I.topLevelOnly)),L=new Map;for(const I of T){const U=I.mcpServer??I.name,P=L.get(U)??[];P.push(I),L.set(U,P)}const A=(I,U)=>{const P=new Map(k),z=P.get(I)||new Set,K=new Set(z);K.has(U)?K.delete(U):K.add(U),K.size===0?P.set(I,new Set):P.set(I,K),b(Wh(P))},M=I=>{const U=new Map(k);U.has(I)?U.delete(I):U.set(I,new Set),b(Wh(U))};return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"space-y-3",children:[c&&s.jsx(Rl,{message:c}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(as,{label:"Name",value:e,onChange:g,placeholder:"My Agent",readOnly:h}),s.jsx(as,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(as,{label:"Description",value:n,onChange:w,placeholder:"What this agent does",readOnly:h}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),s.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[s.jsx("button",{onClick:()=>!h&&C(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${h?"pointer-events-none opacity-60":""}`,children:"Agent"}),s.jsx("button",{onClick:()=>!h&&C(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${r?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),s.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),s.jsx("input",{type:"color",value:a,onChange:I=>!h&&S(I.target.value),disabled:h,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),!h&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Model override"}),s.jsx(Vv,{providers:f,value:d,onChange:_,defaultLabel:"Default (global model)"}),s.jsx("p",{className:"text-[10px] text-text-muted mt-0.5",children:"When set, this model will be used when this agent is active (overrides the session model)."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),s.jsx(xt,{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32",children:E.map(I=>{const U=k.has(I.name),P=I.actions.length>0,z=k.get(I.name)||new Set;return P?h?s.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[s.jsx("span",{children:I.name}),s.jsx("span",{className:"text-[10px]",children:"*"})]},I.name):s.jsx(Na,{trigger:s.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${U?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} cursor-pointer`,children:[s.jsx("span",{children:I.name}),z.size>0&&s.jsx("span",{className:"text-[10px]",children:"*"})]}),minWidth:"160px",items:[...I.actions.map(K=>({label:s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${I.name}-${K}`,children:[s.jsx("input",{type:"checkbox",id:`${I.name}-${K}`,checked:z.has(K),onChange:()=>A(I.name,K),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),s.jsx("span",{children:K})]}),closeOnClick:!1})),{label:U?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(U)M(I.name);else{const K=new Map(k);K.set(I.name,new Set(I.actions)),b(Wh(K))}}}]},I.name):s.jsx("button",{onClick:()=>!h&&M(I.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${U?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none":"cursor-pointer"}`,children:s.jsx("span",{children:I.name})},I.name)})})]}),L.size>0&&(()=>{const I=new Set(T.map(H=>H.name)),U=k.has("__mcp_none__"),P=[...k.keys()].some(H=>I.has(H)),z=U?"none":P?"partial":"all",K=H=>{const F=new Map(k);for(const Q of F.keys())(Q==="__mcp_none__"||I.has(Q))&&F.delete(Q);if(H==="none"&&F.set("__mcp_none__",new Set),H==="partial")for(const Q of I)F.set(Q,new Set);b(Wh(F))};return s.jsxs("div",{children:[s.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["MCP Tools ",s.jsx("span",{className:"text-text-muted font-normal",children:"— from connected MCP servers"})]}),s.jsxs("div",{className:"bg-bg-tertiary border border-border rounded overflow-hidden",children:[s.jsx("div",{className:"flex items-center gap-4 px-3 py-1.5",children:["all","none","partial"].map(H=>s.jsxs("label",{className:`flex items-center gap-1.5 text-xs cursor-pointer ${h?"pointer-events-none opacity-60":""}`,children:[s.jsx("input",{type:"radio",name:"mcp-mode",checked:z===H,onChange:()=>K(H),disabled:h,className:"w-3 h-3 accent-accent-primary"}),s.jsxs("span",{className:z===H?"text-text-primary font-medium":"text-text-muted",children:[H.charAt(0).toUpperCase()+H.slice(1),H==="partial"&&I.size>0&&s.jsxs("span",{className:"ml-1 text-text-muted font-normal",children:["(",[...k.keys()].filter(F=>I.has(F)).length,"/",I.size,")"]})]})]},H))}),z==="partial"&&(()=>{const[H,F]=j.useState(""),[Q,Z]=j.useState(0),V=j.useRef(null),B=$=>{var X;const J=(X=V.current)==null?void 0:X.querySelector(`[data-idx="${$}"]`);J==null||J.scrollIntoView({block:"nearest"})};j.useEffect(()=>{B(Q)},[Q]);const D=H?T.filter($=>$.name.toLowerCase().includes(H.toLowerCase())):T,O=$=>{$.key==="ArrowDown"?($.preventDefault(),Z(J=>Math.min(J+1,D.length-1))):$.key==="ArrowUp"?($.preventDefault(),Z(J=>Math.max(J-1,0))):$.key==="Enter"&&D[Q]&&($.preventDefault(),M(D[Q].name))};return s.jsxs("div",{children:[s.jsx("div",{className:"px-3 py-2 border-b border-border",children:s.jsx("input",{type:"text",value:H,onChange:$=>{F($.target.value),Z(0)},onKeyDown:O,placeholder:"Search MCP tools...",className:"w-full px-2 py-1 text-xs bg-bg-primary border border-border rounded font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),s.jsx(xt,{className:"max-h-60",children:s.jsxs("div",{ref:V,children:[D.map(($,J)=>{const X=k.has($.name),Y=J===Q;return s.jsxs("div",{"data-idx":J,className:`flex items-center justify-between px-3 py-1.5 transition-colors ${Y?"bg-bg-primary":"hover:bg-bg-primary/30"}`,onMouseEnter:()=>Z(J),children:[s.jsx("span",{className:`text-xs font-mono ${X?"text-text-primary":"text-text-muted"}`,children:$.name}),s.jsx(ks,{enabled:X,onClick:()=>M($.name),label:$.name})]},$.name)}),D.length===0&&s.jsx("div",{className:"px-3 py-2 text-xs text-text-muted",children:"No MCP tools match your search."})]})})]})})()]})]})})()]}),s.jsxs("div",{className:"flex-1 min-h-[150px] pt-3 flex flex-col",children:[s.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),s.jsx("textarea",{value:l,onChange:I=>!h&&v(I.target.value),readOnly:h,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${h?"opacity-60":""}`})]})]})}function Dq(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function Oq({isOpen:e,onClose:t,initialEditId:n,projectDir:r}){const{data:o,loading:a}=Mi(er,r),d=(o==null?void 0:o.defaults)??[],l=(o==null?void 0:o.userItems)??[],c=(o==null?void 0:o.projectItems)??[],h=(o==null?void 0:o.modelOverrides)??{},m=iu(ce=>ce.fetchAgent),f=iu(ce=>ce.fetchDefaultContent),g=iu(ce=>ce.createAgent),x=iu(ce=>ce.updateAgent),w=iu(ce=>ce.deleteAgent),[C,b]=j.useState("list"),[S,_]=j.useState(null),[v,k]=j.useState(!1),[E,T]=j.useState(""),[L,A]=j.useState(""),[M,I]=j.useState(""),[U,P]=j.useState(!1),[z,K]=j.useState([]),[H,F]=j.useState("#6b7280"),[Q,Z]=j.useState(void 0),[V,B]=j.useState(""),[D,O]=j.useState("user"),[$,J]=j.useState(""),[X,Y]=j.useState(!1),[q,W]=j.useState(!1),[ee,ie]=j.useState(null),[re,se]=j.useState([]),[de,Se]=j.useState(new Set),{requestDelete:Me,clearConfirm:ye,isConfirming:ue}=Hu(),Ie=ce=>{T(ce.metadata.name),A(ce.metadata.id),I(ce.metadata.description),P(ce.metadata.subagent),K(ce.metadata.allowedTools),F(ce.metadata.color??"#6b7280"),B(ce.prompt),J(""),W(!0),be(`/api/agents/${ce.metadata.id}/model`).then(Oe=>Oe.json()).then(Oe=>{if(Oe.providerId&&Oe.model){const Ve=Oe.reasoningEffort?`:${Oe.reasoningEffort}`:"";Z(`${Oe.providerId}/${Oe.model}${Ve}`)}else Z(void 0)}).catch(()=>Z(void 0)).finally(()=>W(!1))},We=(ce,Oe,Ve)=>{T(ce.metadata.name+" (copy)"),A(`${Oe}-copy-${Date.now()}`),I(ce.metadata.description),P(ce.metadata.subagent),K(ce.metadata.allowedTools),F(ce.metadata.color??"#6b7280"),B(ce.prompt),J(""),_(null),k(!1),b("edit")},Qe=(ce,Oe)=>{Ie(ce),_(Oe),k(!0),b("edit")};j.useEffect(()=>{e&&(be("/api/tools").then(ce=>ce.json()).then(ce=>{const Oe=ce.tools||[];Se(new Set(Oe.filter(Ve=>Ve.alwaysAllowed).map(Ve=>Ve.name))),se(Oe.filter(Ve=>!Ve.alwaysAllowed))}).catch(()=>{se([]),Se(new Set)}),n?d.some(Oe=>Oe.id===n)?f(n).then(Oe=>{Oe&&We(Oe,n)}):m(n,r).then(Oe=>{Oe&&(Ie(Oe),_(n),k(!1),b("edit"))}):(b("list"),_(null),k(!1)))},[e,m,f,n,r]);const ve=async ce=>{if(d.some(Ve=>Ve.id===ce)){const Ve=await f(ce);if(!Ve)return;Qe(Ve,ce)}else{const Ve=await m(ce,r);if(!Ve)return;Qe(Ve,ce)}},oe=async ce=>{let Oe=await f(ce);Oe||(Oe=await m(ce,r)),Oe&&We(Oe,ce)},ae=()=>{_(null),T(""),A(""),I(""),P(!1),K(["read_file"]),F("#6b7280"),B(""),O("user"),J(""),k(!1),b("edit")},we=async ce=>{const Oe=await m(ce,r);Oe&&(Ie(Oe),_(ce),k(!1),b("edit"))},$e=ce=>{ie(ce)},fe=async ce=>{await w(ce,r)},Ae=async()=>{const ce=S??L;if(!ce||!E||!V){J("Name and prompt are required.");return}Y(!0),J("");const Oe={metadata:{id:ce,name:E,description:M,subagent:U,allowedTools:z.filter(De=>!de.has(De)),color:H},prompt:V},Ve=S?await x(S,Oe,r):await g(Oe,D,r);if(!Ve.success){Y(!1),J(Ve.error??"Failed to save agent.");return}await LL(S??L,Q),await er.refresh(r),Y(!1),n?t():b("list")},Xe=()=>{n?t():(b("list"),k(!1))},tt=ce=>{T(ce),S||A(Dq(ce))},pe=d.filter(ce=>ce.subagent),Ge=d.filter(ce=>!ce.subagent),Je=l.filter(ce=>ce.subagent),ot=l.filter(ce=>!ce.subagent),Ze=c.filter(ce=>ce.subagent),at=c.filter(ce=>!ce.subagent);return C==="edit"?s.jsxs(s.Fragment,{children:[s.jsxs(vt,{isOpen:e,onClose:Xe,title:v?`${E}`:S?"Edit Agent":"New Agent",size:"xl",footer:v?s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{onClick:()=>{T(E+" (copy)"),A(`${S}-copy-${Date.now()}`),_(null),k(!1)},className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})}):s.jsx(cN,{onCancel:Xe,onSave:Ae,saving:X,saveDisabled:!E||!V||q}),children:[!S&&!v&&s.jsx(pm,{value:D,onChange:O}),s.jsx(Rq,{formName:E,formId:L,formDescription:M,formSubagent:U,formTools:z,formColor:H,formModel:Q,formPrompt:V,formError:$,isReadOnly:v,availableTools:re,providers:Gt.getState().providers,onNameChange:tt,onIdChange:A,onDescriptionChange:I,onSubagentChange:ce=>{P(ce),ce&&K(Oe=>Oe.filter(Ve=>{var De;return!((De=re.find(st=>st.name===Ve))!=null&&De.topLevelOnly)}))},onToolsChange:K,onColorChange:F,onModelChange:Z,onPromptChange:B})]}),s.jsx(Aj,{agentId:ee,onClose:()=>ie(null),projectDir:r,onSaved:()=>void er.refresh(r)})]}):s.jsxs(s.Fragment,{children:[s.jsx(vt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:s.jsx(uN,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ae,loading:a,hasItems:d.length>0||l.length>0||c.length>0,children:s.jsxs("div",{className:"space-y-4",children:[d.length>0&&s.jsx(Tj,{title:"Built-in",agents:Ge,subagents:pe,isBuiltIn:!0,alwaysAllowedNames:de,modelOverrides:h,onView:ve,onEdit:$e,onDuplicate:oe}),(ot.length>0||Je.length>0||at.length>0||Ze.length>0)&&s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),s.jsx("div",{className:"ml-3 space-y-3",children:[{title:"Global",agents:ot,subagents:Je},{title:"Project",agents:at,subagents:Ze}].map(ce=>(ce.agents.length>0||ce.subagents.length>0)&&s.jsx(Tj,{title:ce.title,agents:ce.agents,subagents:ce.subagents,isBuiltIn:!1,alwaysAllowedNames:de,modelOverrides:h,isConfirmingDelete:Oe=>ue(Oe,"delete"),onView:ve,onDuplicate:oe,onEdit:we,onDelete:Oe=>{ue(Oe,"delete")?(fe(Oe),ye()):Me(Oe)},onCancelDelete:ye},ce.title))})]})]})})}),s.jsx(Aj,{agentId:ee,onClose:()=>ie(null),projectDir:r,onSaved:()=>void er.refresh(r)})]})}function Mq(e){return Ca(e)??{providerId:e,model:""}}async function LL(e,t){if(t){const{providerId:n,model:r,reasoningEffort:o}=Mq(t);await be(`/api/agents/${e}/model`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:n,model:r,...o?{reasoningEffort:o}:{}})})}else await be(`/api/agents/${e}/model`,{method:"DELETE"})}function Aj({agentId:e,onClose:t,onSaved:n,projectDir:r}){const[o,a]=j.useState(void 0),[d,l]=j.useState(!1),[c,h]=j.useState(!1),[m,f]=j.useState(null),{data:g}=Mi(er,r),x=g?[...g.defaults,...g.userItems,...g.projectItems]:[],w=e?x.find(S=>S.id===e):void 0,C=Gt(S=>S.providers);j.useEffect(()=>{e&&(l(!0),be(`/api/agents/${e}/model`).then(S=>S.json()).then(S=>{const _=S.reasoningEffort?`:${S.reasoningEffort}`:"";a(S.providerId&&S.model?`${S.providerId}/${S.model}${_}`:void 0)}).catch(()=>a(void 0)).finally(()=>l(!1)))},[e]);const b=async()=>{if(e){h(!0),f(null);try{await LL(e,o),n(),t()}catch{f("Failed to save. Please try again.")}h(!1)}};return s.jsx(vt,{isOpen:!!e,onClose:t,title:`Model — ${(w==null?void 0:w.name)??e??""}`,size:"md",children:s.jsxs("div",{className:"space-y-4 p-2",children:[s.jsx("p",{className:"text-xs text-text-muted",children:"Choose which model to use when this agent is active. This overrides the session/global model."}),d?s.jsx("div",{className:"text-sm text-text-muted py-2",children:"Loading..."}):s.jsx(Vv,{providers:C,value:o,onChange:a,defaultLabel:"Default (global model)"}),m&&s.jsx("p",{className:"text-xs text-red-500",children:m}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx("button",{onClick:t,className:"px-4 py-1.5 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),s.jsx("button",{onClick:b,disabled:c,className:"px-4 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 disabled:opacity-50 transition-colors",children:c?"Saving...":"Save"})]})]})})}function Iq(){const e=Vr(),t=Vt(e,v=>{var k;return((k=v.session)==null?void 0:k.mode)??null},v=>{var k;return((k=v.currentSession)==null?void 0:k.mode)??null},null),n=Vt(e,v=>{var k;return((k=v.session)==null?void 0:k.workdir)??void 0},v=>{var k;return(k=v.currentSession)==null?void 0:k.workdir},void 0),{data:r}=Mi(er,n),o=TL(),a=r?[...r.defaults,...r.userItems,...r.projectItems]:[],[d,l]=j.useState(!1),[c,h]=j.useState(!1),[m,f]=j.useState(null),g=j.useRef(null);zm(g,()=>l(!1));const x=zu();if(!t)return null;const w=a.filter(v=>!v.subagent),C=w.find(v=>v.id===t),b=(C==null?void 0:C.name)??t,S=wa(a,t),_=async v=>{v.id===t||!e||await o(v.id,v.name)};return s.jsxs("div",{className:"relative",ref:g,children:[s.jsxs("button",{type:"button",onClick:()=>l(!d),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[s.jsx("span",{className:"text-sm font-medium",style:{color:S},children:b}),s.jsx(mn,{className:`w-3 h-3 text-text-muted transition-transform ${d?"rotate-180":""}`})]}),d&&w.length>0&&s.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((v,k)=>{const E=v.id===t,T=wa(a,v.id),L=x.agentSwitching[k],A=L?Jb(L):null;return s.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[s.jsxs("button",{type:"button",onClick:()=>{_(v),l(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[s.jsx("span",{className:"font-medium truncate",style:{color:T},children:v.name}),E&&s.jsx(Ys,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),A&&s.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:A})]},v.id)}),s.jsx("div",{className:"border-t border-border p-1",children:s.jsx("button",{type:"button",onClick:()=>{l(!1),h(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),s.jsx(Oq,{isOpen:c,onClose:()=>{h(!1),f(null)},initialEditId:m,projectDir:n})]})}function Pq(){const e=Vr(),t=Vt(e,r=>{var o;return((o=r.session)==null?void 0:o.dangerLevel)??"normal"},r=>{var o;return((o=r.currentSession)==null?void 0:o.dangerLevel)??"normal"},"normal"),n=Re(r=>r.switchDangerLevel);return e?s.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[s.jsx("button",{type:"button",onClick:()=>n(e,"normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${t==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),s.jsx("button",{type:"button",onClick:()=>n(e,"dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${t==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]}):null}function Lj({value:e,onChange:t}){return s.jsxs("div",{children:[s.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",s.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),s.jsx("input",{type:"text",value:e??"",onChange:n=>t(n.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]})}const Bq=[8080,11434,8e3,1234];function af(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function RL(e){return{name:e.name,url:e.url,backend:e.backend,apiKey:e.apiKey,isLocal:e.isLocal,thinkingField:e.thinkingField,sendReasoningInMessages:e.sendReasoningInMessages,authAdapter:e.authAdapter,transportAdapter:e.transportAdapter,models:e.models}}function $q({model:e,modelConfigs:t,autoConfigState:n,testResults:r,onUpdateConfig:o,onRunAutoConfig:a,onTestParams:d,onShowRaw:l}){var g,x,w,C,b,S,_,v,k,E,T,L,A,M,I,U,P,z,K,H,F,Q,Z,V,B,D,O,$,J,X,Y,q,W,ee,ie,re,se,de,Se,Me,ye;function c(ue,Ie){var oe;const We=((oe=t[ue])==null?void 0:oe.omitParams)??[],ve=We.includes(Ie)?We.filter(ae=>ae!==Ie):[...We,Ie];o(ue,{omitParams:ve.length>0?ve:void 0})}function h(ue){var Ie;return((Ie=t[ue])==null?void 0:Ie.reasoningEfforts)??e.reasoningEfforts??[]}function m(ue,Ie){const We=h(ue),Qe=We.includes(Ie)?We.filter(ve=>ve!==Ie):[...We,Ie];o(ue,{reasoningEfforts:Qe})}function f(ue,Ie,We){const Qe=h(ue),ve=Qe.indexOf(Ie),oe=ve+We;if(ve===-1||oe<0||oe>=Qe.length)return;const ae=[...Qe];[ae[ve],ae[oe]]=[ae[oe],ae[ve]],o(ue,{reasoningEfforts:ae})}return s.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{onClick:()=>a(e.id),disabled:n.progress[e.id]==="probing",className:"px-4 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:n.progress[e.id]==="probing"?"Probing...":"Auto-config"}),n.progress[e.id]==="done"&&s.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&s.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),s.jsxs("div",{className:"flex gap-3 items-end",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),s.jsx("input",{type:"number",value:((g=t[e.id])==null?void 0:g.contextWindow)??e.contextWindow,onChange:ue=>o(e.id,{contextWindow:parseInt(ue.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),wA(((x=t[e.id])==null?void 0:x.contextWindow)??e.contextWindow)&&s.jsx("p",{"data-small-context":!0,className:"text-[11px] text-accent-warning mt-1 w-40 leading-snug",children:"Small context — agent prompts may be truncated by the provider."})]}),s.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[s.jsx("input",{type:"checkbox",checked:((w=t[e.id])==null?void 0:w.supportsVision)??!1,onChange:ue=>o(e.id,{supportsVision:ue.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{onClick:()=>d(e.id,"thinking"),disabled:(C=r[e.id+"-thinking"])==null?void 0:C.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(b=r[e.id+"-thinking"])!=null&&b.loading?"Testing...":"Test thinking"}),((S=r[e.id+"-thinking"])==null?void 0:S.result)&&s.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((_=r[e.id+"-thinking"])==null?void 0:_.error)&&s.jsx("span",{className:"text-xs text-red-500",title:(v=r[e.id+"-thinking"])==null?void 0:v.error,children:"Fail"}),((k=r[e.id+"-thinking"])==null?void 0:k.result)&&s.jsx("button",{onClick:()=>l(r[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{onClick:()=>d(e.id,"non-thinking"),disabled:(E=r[e.id+"-non-thinking"])==null?void 0:E.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(T=r[e.id+"-non-thinking"])!=null&&T.loading?"Testing...":"Test non-thinking"}),((L=r[e.id+"-non-thinking"])==null?void 0:L.result)&&s.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((A=r[e.id+"-non-thinking"])==null?void 0:A.error)&&s.jsx("span",{className:"text-xs text-red-500",title:(M=r[e.id+"-non-thinking"])==null?void 0:M.error,children:"Fail"}),((I=r[e.id+"-non-thinking"])==null?void 0:I.result)&&s.jsx("button",{onClick:()=>l(r[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),s.jsxs("details",{className:"group",children:[s.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[s.jsx(mn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:((U=t[e.id])==null?void 0:U.thinkingEnabled)??!1,onChange:ue=>o(e.id,{thinkingEnabled:ue.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),s.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((P=t[e.id])==null?void 0:P.thinkingEnabled)&&s.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),(z=e.reasoningEfforts)!=null&&z.length?s.jsx("select",{"aria-label":"Reasoning effort",value:((K=t[e.id])==null?void 0:K.thinkingLevel)??af(e.reasoningEfforts),onChange:ue=>o(e.id,{thinkingLevel:ue.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary",children:e.reasoningEfforts.map(ue=>s.jsx("option",{value:ue,children:ue},ue))}):s.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((H=t[e.id])==null?void 0:H.thinkingLevel)??"",onChange:ue=>o(e.id,{thinkingLevel:ue.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),s.jsx(Lj,{value:(F=t[e.id])==null?void 0:F.thinkingQueryParams,onChange:ue=>o(e.id,{thinkingQueryParams:ue})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Effort presets (shown as chips in the model selector)"}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[h(e.id).map((ue,Ie)=>s.jsxs("span",{className:"flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full border border-border text-text-muted",children:[ue,s.jsx("button",{type:"button","aria-label":`Move preset ${ue} up`,onClick:()=>f(e.id,ue,-1),disabled:Ie===0,className:"text-text-muted hover:text-text-primary leading-none disabled:opacity-30",children:"↑"}),s.jsx("button",{type:"button","aria-label":`Move preset ${ue} down`,onClick:()=>f(e.id,ue,1),disabled:Ie===h(e.id).length-1,className:"text-text-muted hover:text-text-primary leading-none disabled:opacity-30",children:"↓"}),s.jsx("button",{type:"button","aria-label":`Remove preset ${ue}`,onClick:()=>m(e.id,ue),className:"text-text-muted hover:text-accent-error leading-none",children:"×"})]},ue)),s.jsxs("select",{"aria-label":"Add effort preset",value:"",onChange:ue=>{ue.target.value&&m(e.id,ue.target.value)},className:"text-[10px] px-1.5 py-0.5 rounded border border-border bg-bg-tertiary text-text-muted",children:[s.jsx("option",{value:"",children:"Add preset…"}),jA.filter(ue=>!h(e.id).includes(ue)).map(ue=>s.jsx("option",{value:ue,children:ue},ue))]})]}),((Q=t[e.id])==null?void 0:Q.reasoningEfforts)!==void 0&&s.jsx("button",{type:"button",onClick:()=>o(e.id,{reasoningEfforts:void 0}),className:"mt-1 text-[10px] text-text-muted hover:text-text-primary hover:underline",children:"Reset to defaults"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort override (raw value, sent verbatim)"}),s.jsx("input",{type:"text","aria-label":"Reasoning effort override",value:((Z=t[e.id])==null?void 0:Z.reasoningEffortOverride)??e.reasoningEffortOverride??"",onChange:ue=>o(e.id,{reasoningEffortOverride:ue.target.value||void 0}),placeholder:"e.g. deep — bypasses the preset list",className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:((V=t[e.id])==null?void 0:V.nonThinkingEnabled)??!1,onChange:ue=>o(e.id,{nonThinkingEnabled:ue.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),s.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((B=t[e.id])==null?void 0:B.nonThinkingEnabled)&&s.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:s.jsx(Lj,{value:(D=t[e.id])==null?void 0:D.nonThinkingQueryParams,onChange:ue=>o(e.id,{nonThinkingQueryParams:ue})})}),(((O=t[e.id])==null?void 0:O.omitParams)??[]).includes("reasoning_effort")&&s.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-warning cursor-pointer select-none",children:[s.jsx("input",{type:"checkbox","data-testid":"re-enable-reasoning_effort",checked:!1,onChange:()=>c(e.id,"reasoning_effort"),className:"accent-accent-primary"}),"Re-enable reasoning_effort"]})]}),s.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[s.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(Gh,{modelId:e.id,paramKey:"temperature",label:"Temperature",step:.1,value:($=t[e.id])==null?void 0:$.temperature,defaultValue:(J=t[e.id])==null?void 0:J.defaultTemperature,omitParams:(X=t[e.id])==null?void 0:X.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseFloat(ue):void 0,valueField:"temperature"}),s.jsx(Gh,{modelId:e.id,paramKey:"top_p",label:"Top P",step:.05,value:(Y=t[e.id])==null?void 0:Y.topP,defaultValue:(q=t[e.id])==null?void 0:q.defaultTopP,omitParams:(W=t[e.id])==null?void 0:W.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseFloat(ue):void 0,valueField:"topP"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[s.jsx(Gh,{modelId:e.id,paramKey:"top_k",label:"Top K",value:(ee=t[e.id])==null?void 0:ee.topK,defaultValue:(ie=t[e.id])==null?void 0:ie.defaultTopK,omitParams:(re=t[e.id])==null?void 0:re.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseInt(ue):void 0,valueField:"topK"}),s.jsx(Gh,{modelId:e.id,paramKey:"max_tokens",label:"Max tokens",value:(se=t[e.id])==null?void 0:se.maxTokens,defaultValue:(de=t[e.id])==null?void 0:de.defaultMaxTokens,omitParams:(Se=t[e.id])==null?void 0:Se.omitParams,onUpdateConfig:o,onToggleOmit:c,parseValue:ue=>ue?parseInt(ue):void 0,valueField:"maxTokens"})]})]}),s.jsx("div",{className:"pt-3 border-t border-border",children:s.jsx(Fq,{value:(Me=t[e.id])==null?void 0:Me.compactionThreshold,maxTokens:((ye=t[e.id])==null?void 0:ye.contextWindow)??e.contextWindow,onChange:ue=>o(e.id,{compactionThreshold:ue})})})]})]})}function Gh({modelId:e,paramKey:t,label:n,value:r,defaultValue:o,omitParams:a,onUpdateConfig:d,onToggleOmit:l,parseValue:c,valueField:h,step:m}){const f=(a==null?void 0:a.includes(t))??!1;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:n}),s.jsxs("label",{className:"flex items-center gap-1 text-xs text-text-muted cursor-pointer select-none",children:[s.jsx("input",{type:"checkbox","data-testid":`send-${t}`,checked:!f,onChange:()=>l(e,t),className:"accent-accent-primary"}),"Send"]})]}),s.jsx("input",{type:"number","data-testid":`param-${t}`,step:m,value:f?"":r??"",disabled:f,onChange:g=>d(e,{[h]:c(g.target.value)}),placeholder:f?"Not sent":(o==null?void 0:o.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary disabled:opacity-40"}),!f&&o!==void 0&&s.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",o]})]})}function Fq({value:e,maxTokens:t,onChange:n}){const a=Math.min(95,Math.floor((t-5e3)/t*100)),d=Math.min(a,Math.ceil(15e3/t*100)),l=Math.min(e??.85,a/100),[c,h]=j.useState(Math.round(l*100));j.useEffect(()=>{const f=Math.min(e??.85,a/100);h(Math.round(f*100))},[e,a]);const m=Math.floor(t*(c/100));return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-1",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:"Auto-compaction threshold"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:[c,"% · ",Ul(m)]}),s.jsx("button",{type:"button",onClick:()=>{n(void 0),h(Math.round(.85*100))},disabled:e===void 0,className:"text-xs text-accent-primary hover:underline disabled:text-text-muted disabled:no-underline",children:"Default"})]})]}),s.jsx("input",{"aria-label":"Auto-compaction threshold",type:"range",min:d,max:a,step:"1",value:c,onChange:f=>h(Number(f.target.value)),onMouseUp:()=>n(c/100),onTouchEnd:()=>n(c/100),onBlur:()=>n(c/100),onKeyUp:()=>n(c/100),className:"w-full"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Minimum ",Ul(15e3)," tokens · maximum ",a,"% · default 85%"]})]})}function DL({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:o,editModelId:a}){const[d,l]=j.useState(r),[c,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState("unknown"),[w,C]=j.useState(""),[b,S]=j.useState(!1),[_,v]=j.useState(),[k,E]=j.useState(),[T,L]=j.useState(!1),[A,M]=j.useState(null),[I,U]=j.useState([]),[P,z]=j.useState(null),[K,H]=j.useState(!1),[F,Q]=j.useState(""),[Z,V]=j.useState(!0),[B,D]=j.useState({}),[O,$]=j.useState({loading:!1,progress:{}}),[J,X]=j.useState({}),[Y,q]=j.useState(null),[W,ee]=j.useState(new Set),[ie,re]=j.useState(""),[se,de]=j.useState(null),[Se,Me]=j.useState("disconnected"),[ye,ue]=j.useState(!1),[Ie,We]=j.useState(null),[Qe,ve]=j.useState([]),[oe,ae]=j.useState(!1),[we,$e]=j.useState(!1),[fe,Ae]=j.useState(""),[Xe,tt]=j.useState(null),pe=j.useRef(null),Ge=j.useRef(!1),Je=j.useRef(null),ot=j.useRef(null);j.useEffect(()=>{d===1&&e&&requestAnimationFrame(()=>{var Ee;Wt()&&((Ee=Je.current)==null||Ee.focus())})},[d,e]),j.useEffect(()=>()=>{pe.current!==null&&window.clearTimeout(pe.current)},[]),j.useEffect(()=>{e&&be("/api/provider-presets").then(async Ee=>Ee.ok?await Ee.json():{presets:[]}).then(Ee=>ve(Ee.presets)).catch(()=>ve([]))},[e]);function Ze(Ee,nt){D(qe=>({...qe,[Ee]:{...qe[Ee],...nt}}))}function at(Ee){ee(nt=>new Set(nt).add(Ee.id)),D(nt=>({...nt,[Ee.id]:{contextWindow:Ee.contextWindow,...nt[Ee.id]}}))}function ce(Ee){if(!Ee.trim())return I;const nt=Ee.toLowerCase().split(/\s+/).filter(Boolean);return I.filter(qe=>nt.every(Be=>qe.id.toLowerCase().includes(Be)))}function Oe(){const Ee=fe.trim();if(!Ee){tt("Enter a model name");return}const nt=xe=>xe.toLowerCase().replace(/[-_\s:.]+/g,""),qe=nt(Ee),Be=I.find(xe=>nt(xe.id)===qe);if(Be){at(Be),tt(`"${Be.id}" is already in the list`),Ae(""),!_&&O.progress[Be.id]!=="probing"&&qt(Be.id);return}const me={id:Ee,contextWindow:2e5};U(xe=>[...xe,me]),ee(xe=>new Set(xe).add(me.id)),D(xe=>({...xe,[me.id]:{contextWindow:me.contextWindow,thinkingEnabled:!0}})),z(me.id),Ae(""),tt(null),M(null)}j.useEffect(()=>{var Ee,nt;if(e)if(l(r),h((o==null?void 0:o.name)??""),f((o==null?void 0:o.url)??""),x((o==null?void 0:o.backend)??"unknown"),C((o==null?void 0:o.apiKey)??""),S((o==null?void 0:o.isLocal)??!1),v(o==null?void 0:o.authAdapter),E(o==null?void 0:o.transportAdapter),M(null),Q((o==null?void 0:o.thinkingField)??""),V((o==null?void 0:o.sendReasoningInMessages)??!0),X({}),q(null),de(null),Me("disconnected"),We(null),ae(!1),$e(!1),Ae(""),tt(null),(Ee=o==null?void 0:o.models)!=null&&Ee.length){const qe={},Be=new Set;for(const me of o.models)qe[me.id]={contextWindow:me.contextWindow,supportsVision:me.supportsVision,thinkingEnabled:me.thinkingEnabled,thinkingLevel:me.thinkingLevel??af(me.reasoningEfforts),nonThinkingEnabled:me.nonThinkingEnabled,thinkingQueryParams:me.thinkingQueryParams,nonThinkingQueryParams:me.nonThinkingQueryParams,omitParams:me.omitParams,defaultTemperature:me.defaultTemperature,defaultTopP:me.defaultTopP,defaultTopK:me.defaultTopK,defaultMaxTokens:me.defaultMaxTokens,temperature:me.temperature,topP:me.topP,topK:me.topK,maxTokens:me.maxTokens,compactionThreshold:me.compactionThreshold},me.selected&&Be.add(me.id);if(Be.size===0)for(const me of o.models)Be.add(me.id);ee(Be),D(qe),U(o.models),z(a??((nt=o.models[0])==null?void 0:nt.id)??null)}else U([]),D({}),z(null),ee(new Set)},[e,r,o==null?void 0:o.id,a]),j.useEffect(()=>{const Ee=!!_;d===2&&m&&I.length===0&&!T&&!A&&(!Ee||Se==="connected")&&kt(m)},[d,Se]),j.useEffect(()=>{!e||!_||!(o!=null&&o.id)||De(o.id)},[e,k,o==null?void 0:o.id]),j.useEffect(()=>{if(!Ie)return;const Ee=(o==null?void 0:o.id)??se;if(!Ee)return;let nt=!1;const qe=async()=>{const me=await De(Ee);nt||me!=="connected"||(We(null),ae(!1),$e(!1),await kt(m))};qe();const Be=window.setInterval(()=>void qe(),2e3);return()=>{nt=!0,window.clearInterval(Be)}},[Ie,se,o==null?void 0:o.id]);async function Ve(){if(o!=null&&o.id)return o.id;if(se)return se;const Ee=await be("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:c||"Provider",url:m,backend:g,authAdapter:_,transportAdapter:k,isLocal:!1,models:[]})});if(!Ee.ok)throw new Error("Unable to create provider");const nt=await Ee.json();return de(nt.provider.id),nt.provider.id}async function De(Ee){const nt=await be(`/api/provider-auth/${Ee}/status`);if(!nt.ok)return"error";const qe=await nt.json(),Be=qe.state==="connected"?"connected":qe.state==="pending"?"pending":qe.state==="error"?"error":"disconnected";return Me(Be),Be}async function st(){ue(!0),Me("pending");try{const Ee=await Ve(),nt=await be(`/api/provider-auth/${Ee}/login`,{method:"POST"});if(!nt.ok)throw new Error("Unable to start provider sign-in");const qe=await nt.json();We(qe)}catch{Me("error")}finally{ue(!1)}}async function rt(){var Ee;Ie!=null&&Ie.userCode&&(await((Ee=navigator.clipboard)==null?void 0:Ee.writeText(Ie.userCode)),pe.current!==null&&window.clearTimeout(pe.current),$e(!1),requestAnimationFrame(()=>$e(!0)),pe.current=window.setTimeout(()=>{$e(!1),pe.current=null},1500))}function yt(){Ie&&(window.open(Ie.directUrl??Ie.verificationUrl,"_blank","noopener,noreferrer"),ae(!0))}async function kt(Ee){var nt,qe;L(!0),M(null),U([]);try{const Be=new URLSearchParams({url:Ee});w&&Be.set("apiKey",w),g&&Be.set("backend",g);const me=k?await be(`/api/providers/${await Ve()}/models`):await be(`/api/providers/models?${Be.toString()}`);if(me.ok){const xe=await me.json();if((nt=xe.models)!=null&&nt.length){U(xe.models),z(((qe=xe.models[0])==null?void 0:qe.id)??null);const He={};for(const Ue of xe.models)He[Ue.id]={contextWindow:Ue.contextWindow,thinkingEnabled:!0,thinkingLevel:af(Ue.reasoningEfforts),defaultTemperature:Ue.defaultTemperature,defaultTopP:Ue.defaultTopP,defaultTopK:Ue.defaultTopK,defaultMaxTokens:Ue.defaultMaxTokens};D(He),xe.models.length===1&&(ee(new Set([xe.models[0].id])),z(xe.models[0].id),qt(xe.models[0].id))}}else{const xe=await me.json();M(xe.error??`Failed to fetch models from ${Ee}`)}}catch(Be){M(`Failed to fetch models from ${Ee}: ${Be instanceof Error?Be.message:"Unknown error"}`)}L(!1)}async function qt(Ee){$(nt=>({loading:!0,progress:{...nt.progress,[Ee]:"probing"}}));try{const nt=await be("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:m,apiKey:w||void 0,backend:g||"unknown",models:[{id:Ee}]})});if(!nt.ok){const Be=await nt.json();throw new Error(Be.error??"Auto-config failed")}const qe=await nt.json();for(const Be of qe.models){const me={};if(Be.contextSource!=="default"&&(me.contextWindow=Be.contextWindow,me.supportsVision=Be.supportsVision),Be.thinkingConfig){me.thinkingEnabled=!0,me.thinkingQueryParams=JSON.stringify(Be.thinkingConfig);const xe=B[Be.id];me.thinkingLevel=(xe==null?void 0:xe.thinkingLevel)??Be.defaultReasoningEffort??af(Be.reasoningEfforts)}Be.nonThinkingConfig&&(me.nonThinkingEnabled=!0,me.nonThinkingQueryParams=JSON.stringify(Be.nonThinkingConfig)),Be.sendReasoningInMessages===!1&&V(!1),Be.rejectedParams&&Be.rejectedParams.length>0&&(me.omitParams=Be.rejectedParams),Be.reasoningEfforts&&Be.reasoningEfforts.length>0&&(me.reasoningEfforts=Be.reasoningEfforts),Ze(Be.id,me),$(xe=>({...xe,progress:{...xe.progress,[Be.id]:"done"}}))}}catch(nt){console.error("Auto-config error:",nt),$(qe=>({...qe,progress:{...qe.progress,[Ee]:"error"}}))}finally{$(nt=>({...nt,loading:!1}))}}async function Mn(Ee,nt){const qe=Ee+"-"+nt;X(Be=>({...Be,[qe]:{loading:!0}}));try{const Be=B[Ee],me=await be("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:m,providerId:(o==null?void 0:o.id)??se??void 0,transportAdapter:k,model:Ee,apiKey:w||void 0,backend:g||"unknown",thinkingField:F||void 0,mode:nt,modelConfig:{temperature:Be==null?void 0:Be.temperature,topP:Be==null?void 0:Be.topP,topK:Be==null?void 0:Be.topK,maxTokens:Be==null?void 0:Be.maxTokens,supportsVision:Be==null?void 0:Be.supportsVision,thinkingEnabled:Be==null?void 0:Be.thinkingEnabled,thinkingLevel:Be==null?void 0:Be.thinkingLevel,nonThinkingEnabled:Be==null?void 0:Be.nonThinkingEnabled,thinkingQueryParams:Be==null?void 0:Be.thinkingQueryParams,nonThinkingQueryParams:Be==null?void 0:Be.nonThinkingQueryParams,omitParams:Be==null?void 0:Be.omitParams}})}),xe=await me.json();me.ok?X(He=>({...He,[qe]:{loading:!1,result:JSON.stringify(xe,null,2),message:xe.message}})):X(He=>({...He,[qe]:{loading:!1,error:xe.error??"Test failed"}}))}catch(Be){X(me=>({...me,[qe]:{loading:!1,error:Be instanceof Error?Be.message:"Request failed"}}))}}function qn(){U([]),D({}),$({loading:!1,progress:{}}),X({}),q(null),ee(new Set),re(""),Ae(""),tt(null)}function In(){se&&!Ge.current&&be(`/api/providers/${se}`,{method:"DELETE"}).catch(Ee=>{console.warn("Failed to clean up draft provider",Ee)}),t()}function hr(){const Ee=c||"Provider",nt=(o==null?void 0:o.id)??se??`temp-${Date.now()}`;n({id:nt,name:Ee,url:m,backend:g||"unknown",apiKey:w||void 0,isLocal:b,thinkingField:F||void 0,sendReasoningInMessages:Z,authAdapter:_,transportAdapter:k,models:I.map(qe=>{var Be,me,xe,He,Ue,et,ut,ht,Xt,pn,kn,Ao,Js,us,Zs,Tr,ds,Ls,Wr;return{id:qe.id,name:qe.name,apiModelId:qe.apiModelId,requestBody:qe.requestBody,reasoningEfforts:((Be=B[qe.id])==null?void 0:Be.reasoningEfforts)??qe.reasoningEfforts,reasoningEffortOverride:((me=B[qe.id])==null?void 0:me.reasoningEffortOverride)??qe.reasoningEffortOverride,contextWindow:((xe=B[qe.id])==null?void 0:xe.contextWindow)??qe.contextWindow,selected:W.has(qe.id)||void 0,supportsVision:(He=B[qe.id])==null?void 0:He.supportsVision,thinkingEnabled:(Ue=B[qe.id])==null?void 0:Ue.thinkingEnabled,thinkingLevel:(et=B[qe.id])==null?void 0:et.thinkingLevel,nonThinkingEnabled:(ut=B[qe.id])==null?void 0:ut.nonThinkingEnabled,thinkingQueryParams:(ht=B[qe.id])==null?void 0:ht.thinkingQueryParams,nonThinkingQueryParams:(Xt=B[qe.id])==null?void 0:Xt.nonThinkingQueryParams,omitParams:(pn=B[qe.id])==null?void 0:pn.omitParams,temperature:(kn=B[qe.id])==null?void 0:kn.temperature,topP:(Ao=B[qe.id])==null?void 0:Ao.topP,topK:(Js=B[qe.id])==null?void 0:Js.topK,maxTokens:(us=B[qe.id])==null?void 0:us.maxTokens,defaultMaxTokens:(Zs=B[qe.id])==null?void 0:Zs.defaultMaxTokens,defaultTemperature:(Tr=B[qe.id])==null?void 0:Tr.defaultTemperature,defaultTopP:(ds=B[qe.id])==null?void 0:ds.defaultTopP,defaultTopK:(Ls=B[qe.id])==null?void 0:Ls.defaultTopK,compactionThreshold:(Wr=B[qe.id])==null?void 0:Wr.compactionThreshold}})}),Ge.current=!0,t()}if(!e)return null;const Nr=s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{children:d>1&&s.jsx("button",{onClick:()=>{d===2&&qn(),l(d-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:In,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),d===1?s.jsx("button",{onClick:()=>l(2),disabled:!m,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:"Next — Test & Configure"}):s.jsx("button",{onClick:hr,disabled:O.loading,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:O.loading?"Configuring...":"Save Provider"})]})]});return s.jsxs(s.Fragment,{children:[s.jsxs(vt,{isOpen:e,onClose:In,title:o?"Edit Provider":"Add Provider",size:"lg",footer:Nr,closeOnBackdropClick:!1,closeOnEscape:!K&&!Y,children:[s.jsx("div",{className:"flex gap-1.5 pt-2",children:[1,2].map(Ee=>s.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${Ee<d?"bg-accent-success":Ee===d?"bg-accent-primary":"bg-border"}`},Ee))}),d===1&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),s.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[Qe.map(Ee=>s.jsx("button",{type:"button",onClick:()=>{h(Ee.defaults.name??Ee.name),f(Ee.defaults.url),x(Ee.defaults.backend),S(!1),C(""),v(Ee.authAdapter),E(Ee.transportAdapter),M(null),qn()},className:`p-2 rounded border text-center text-sm transition-colors ${k&&k===Ee.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:Ee.name},Ee.id)),s.jsx("button",{type:"button",onClick:()=>{x("unknown"),S(!1),v(void 0),E(void 0),M(null),qn()},className:`p-2 rounded border text-center text-sm transition-colors ${g==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),Bq.map(Ee=>{const nt={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},qe={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return s.jsx("button",{type:"button",onClick:()=>{h(Be=>Be||(qe[Ee]??"")),f(Be=>Be||`http://localhost:${Ee}`),x(nt[Ee]??""),S(!0),v(void 0),E(void 0),M(null),qn()},className:`p-2 rounded border text-center text-sm transition-colors ${g===nt[Ee]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:qe[Ee]??`localhost:${Ee}`},Ee)})]})]}),!_&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),s.jsx("input",{ref:Je,type:"text",value:m,"data-testid":"provider-modal-url",onChange:Ee=>{f(Ee.target.value),M(null),U([]),D({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),s.jsx("input",{type:"text",autoComplete:"off",value:c,onChange:Ee=>h(Ee.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!_&&s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",s.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),s.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:Ee=>C(Ee.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),!_&&s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:Ee=>S(Ee.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),s.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),d===2&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Test & Configure Models"}),s.jsx("button",{type:"button",onClick:()=>H(!0),className:"p-1.5 text-text-muted hover:text-text-primary rounded transition-colors",title:"Provider-level defaults",children:s.jsx(rN,{className:"w-4 h-4"})})]}),!!_&&s.jsxs("div",{className:"rounded-lg border border-border bg-bg-primary p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Connect provider"}),s.jsx("p",{className:"mt-1 text-xs text-text-muted",children:"Connect this provider before choosing available models."})]}),Se==="connected"?s.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):s.jsx("button",{type:"button",onClick:()=>void st(),disabled:ye||Se==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:ye||Se==="pending"?"Connecting...":Se==="error"?"Retry":"Connect"})]}),Ie&&s.jsx("div",{className:"mt-4 border-t border-border pt-4",children:Ie.mode!=="browser"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-xs text-text-muted",children:"Use this code to complete authorization:"}),s.jsx("button",{type:"button",onClick:()=>void rt(),className:"mt-3 w-full rounded-lg border border-accent-primary/40 px-4 py-4 font-mono text-2xl font-semibold tracking-[0.2em] text-accent-primary",children:Ie.userCode??"Continue"}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void rt(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:we?"Copied":"Copy code"}),s.jsx("button",{type:"button",onClick:yt,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:oe?"Reopen authorization":"Open authorization"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-xs text-text-muted mb-3",children:Ie.instructions}),s.jsx("button",{type:"button",onClick:yt,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:oe?"Reopen authorization":"Open authorization"})]})})]}),T&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[s.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),A&&s.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[s.jsx("p",{children:A}),s.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",m]}),s.jsxs("div",{className:"flex gap-2 mt-2",children:[s.jsx("button",{onClick:()=>kt(m),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),s.jsx("button",{onClick:()=>{qn(),l(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"}),!_&&s.jsx("button",{onClick:()=>{var Ee;return(Ee=ot.current)==null?void 0:Ee.focus()},className:"text-xs text-accent-primary hover:underline",children:"Add model manually"})]})]}),g&&(!_||Se==="connected")&&s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Add model manually"}),s.jsx("p",{className:"text-xs text-text-muted mb-2",children:A?"Can't discover models automatically? Enter the model name to use:":"Enter a model name manually if it does not appear in the list above:"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{ref:ot,type:"text",value:fe,onChange:Ee=>{Ae(Ee.target.value),Xe&&tt(null)},onKeyDown:Ee=>{Ee.key==="Enter"&&(Ee.preventDefault(),Oe())},placeholder:"model-name","data-testid":"provider-modal-manual-model-input",className:"flex-1 px-3 py-1.5 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),s.jsx("button",{type:"button",onClick:Oe,"data-testid":"provider-modal-manual-model-add",className:"px-3 py-1.5 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Add"})]}),Xe&&s.jsx("p",{className:"text-xs text-red-500 mt-1",children:Xe})]}),I.length>0&&g&&(!_||Se==="connected")&&s.jsxs(s.Fragment,{children:[W.size>0&&s.jsxs("div",{className:"mb-4",children:[s.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",W.size,")"]}),s.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),s.jsx("div",{className:"space-y-2",children:I.filter(Ee=>W.has(Ee.id)).map(Ee=>{var nt;return s.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[s.jsxs("div",{onClick:()=>z(P===Ee.id?null:Ee.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-sm font-medium text-text-primary",children:Ee.name??Ee.id.split("/").pop()}),s.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((nt=B[Ee.id])==null?void 0:nt.contextWindow)??Ee.contextWindow).toLocaleString()," ctx"]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[O.progress[Ee.id]==="probing"?s.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):O.progress[Ee.id]==="done"?s.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):O.progress[Ee.id]==="error"?s.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):_?null:s.jsx("button",{onClick:qe=>{qe.stopPropagation(),qt(Ee.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),I.length>1&&s.jsx("button",{onClick:qe=>{qe.stopPropagation();const Be=new Set(W);Be.delete(Ee.id),ee(Be),P===Ee.id&&z(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),s.jsx(mn,{className:`w-4 h-4 text-text-muted transition-transform ${P===Ee.id?"rotate-180":""}`})]})]}),P===Ee.id&&s.jsx($q,{model:Ee,modelConfigs:B,autoConfigState:O,testResults:J,onUpdateConfig:Ze,onRunAutoConfig:qt,onTestParams:Mn,onShowRaw:q})]},Ee.id)})})]}),I.length>1&&s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),W.size===0&&s.jsx("p",{className:"text-xs text-text-muted mb-2",children:"This provider has many models available. Select the ones you want to use below."}),s.jsxs("div",{className:"relative mb-2",children:[s.jsx("input",{type:"text",value:ie,onChange:Ee=>re(Ee.target.value),placeholder:"Search models...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),ie&&s.jsx("button",{onClick:()=>re(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",ce(ie).length," of ",I.length," models"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:()=>{const Ee=new Set(W),nt=ce(ie);for(const qe of nt)Ee.add(qe.id);if(ee(Ee),D(qe=>{const Be={...qe};for(const me of nt)Be[me.id]={contextWindow:me.contextWindow,...Be[me.id]};return Be}),!_)for(const qe of nt)O.progress[qe.id]!=="probing"&&O.progress[qe.id]!=="done"&&qt(qe.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),s.jsx("button",{onClick:()=>{const Ee=new Set(W),nt=ce(ie);for(const qe of nt)Ee.delete(qe.id);ee(Ee)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),s.jsxs(xt,{className:"space-y-1 max-h-48 border border-border rounded-lg bg-bg-primary",children:[ce(ie).map(Ee=>{var qe;const nt=W.has(Ee.id);return s.jsxs("div",{role:"checkbox","aria-checked":nt,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${nt?"bg-accent-primary/5":""}`,onClick:()=>{if(nt){const Be=new Set(W);Be.delete(Ee.id),ee(Be)}else at(Ee),_||qt(Ee.id)},onKeyDown:Be=>{(Be.key==="Enter"||Be.key===" ")&&(Be.preventDefault(),Be.currentTarget.click())},children:[s.jsx("input",{type:"checkbox",checked:nt,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),s.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:Ee.name??Ee.id.split("/").pop()}),s.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((qe=B[Ee.id])==null?void 0:qe.contextWindow)??Ee.contextWindow).toLocaleString()," ctx"]}),O.progress[Ee.id]==="probing"&&s.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),O.progress[Ee.id]==="done"&&s.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),O.progress[Ee.id]==="error"&&s.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},Ee.id)}),ce(ie).length===0&&s.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",ie,"”"]})]})]})]})]})]}),K&&s.jsx(vt,{isOpen:!0,onClose:()=>H(!1),title:"Provider-Level Defaults",size:"md",footer:s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{onClick:()=>H(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})}),children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),s.jsx("input",{type:"text",defaultValue:'{"chat_template_kwargs":{"enable_thinking":false}}',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),s.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",s.jsx("span",{className:"text-text-muted",children:"(override)"})]}),s.jsx("input",{type:"text",value:F,onChange:Ee=>Q(Ee.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),s.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:Z,onChange:Ee=>V(Ee.target.checked),className:"rounded border-border bg-bg-primary text-accent-primary focus:ring-accent-primary"}),s.jsx("span",{className:"text-sm text-text-secondary",children:"Send reasoning in messages"}),s.jsx("span",{className:"text-xs text-text-muted ml-auto",children:"When disabled, strips reasoning/thinking content from assistant messages sent to this provider"})]})]})}),Y&&s.jsx(vt,{isOpen:!0,onClose:()=>q(null),title:"Raw Response",size:"lg",children:s.jsx(xt,{horizontal:!0,children:s.jsx("pre",{className:"text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:Y})})})]})}const OL=j.forwardRef(function({onNext:t,embedded:n=!1},r){const[o,a]=j.useState([]),[d,l]=j.useState([]),[c,h]=j.useState(!1),[m,f]=j.useState(null),[g,x]=j.useState(null),[w,C]=j.useState(null),[b,S]=j.useState(null),[_,v]=j.useState(null),[k,E]=j.useState(!1),T=j.useRef(null);j.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]),j.useEffect(()=>{L()},[]);async function L(){try{const O=await be("/api/providers");if(O.ok){const J=(await O.json()).providers.map(X=>({id:X.id,name:X.name,url:X.url,backend:X.backend,model:null,apiKey:X.apiKey,isLocal:X.isLocal,thinkingField:X.thinkingField,sendReasoningInMessages:X.sendReasoningInMessages,models:X.models}));a(J),l(J)}}catch{}}async function A(O){const $=O.id.startsWith("temp-"),J=d.some(q=>q.id===O.id),X=d.length===0&&m===null,Y=RL(O);try{let q;if($){const ee=await be("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!ee.ok)throw new Error("Failed to create provider");const ie=await ee.json();q={...O,id:ie.provider.id,model:null}}else{if(!(await be(`/api/providers/${O.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})).ok)throw new Error("Failed to update provider");q={...O,model:null}}const W=ee=>ee.some(ie=>ie.id===q.id)?ee.map(ie=>ie.id===q.id?q:ie):[...ee,q];l(W),a(W),!n&&X&&!J&&t({providers:[q]})}catch{if($){const q={...O,model:null};l(W=>[...W,q])}}}function M(){f(null),h(!0)}function I(O){f(O),h(!0)}function U(){h(!1),f(null)}function P(O){x(O),o.some(J=>J.id===O)?be(`/api/providers/${O}`,{method:"DELETE"}).then(()=>{l(d.filter(J=>J.id!==O)),a(o.filter(J=>J.id!==O)),x(null)}).catch(()=>x(null)):(l(d.filter(J=>J.id!==O)),x(null))}function z(){const O=d.filter($=>!$.id.startsWith("temp-"));t({providers:O})}function K(O){l(O),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{T.current=null,be("/api/providers/order",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerIds:O.map($=>$.id)})}).then($=>{$.ok?E(!1):(E(!0),H())}).catch(()=>{E(!0),H()})},300)}async function H(){try{const O=await be("/api/providers");if(!O.ok)return;const J=(await O.json()).providers.map(X=>X.id);l(X=>{const Y=new Set(J);return X.length===J.length&&X.every(W=>Y.has(W.id))?J.map(W=>X.find(ee=>ee.id===W)).filter(W=>W!==void 0):X})}catch{}}function F(O,$){const J=O+$;if(J<0||J>=d.length)return;const X=[...d],[Y]=X.splice(O,1);X.splice(J,0,Y),K(X)}function Q(O){S(O)}function Z(O){v(O)}function V(O){if(!b||b===O)return;const $=d.findIndex(q=>q.id===b),J=d.findIndex(q=>q.id===O);if($===-1||J===-1)return;const X=[...d],[Y]=X.splice($,1);X.splice(J,0,Y),K(X)}function B(){S(null),v(null)}j.useImperativeHandle(r,()=>({addProvider:M,submit:z}),[z]);const D=d.length>0;return s.jsxs("div",{className:"max-w-xl mx-auto",children:[!n&&s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"LLM Providers"}),s.jsx("p",{className:"text-text-secondary mb-8",children:"Manage your LLM server connections"})]}),s.jsxs("div",{className:"space-y-4",children:[d.length>0?s.jsx("div",{className:"space-y-2",children:d.map((O,$)=>s.jsxs("div",{"data-testid":`provider-row-${O.id}`,onDragOver:J=>{b&&(J.preventDefault(),Z(O.id))},onDrop:J=>{b&&(J.preventDefault(),V(O.id))},className:`flex items-center justify-between bg-bg-secondary rounded-lg p-4 border ${_===O.id?"border-accent-primary":"border-border"}`,children:[n&&s.jsx("button",{type:"button",draggable:!0,onDragStart:()=>Q(O.id),onDragEnd:B,className:"p-1.5 mr-1 text-text-muted hover:text-text-secondary cursor-grab active:cursor-grabbing transition-colors",title:"Drag to reorder","aria-label":"Drag to reorder",children:s.jsx(zO,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"px-2 py-0.5 bg-accent-primary/25 text-accent-primary rounded text-xs font-medium",children:HE(O.backend)}),s.jsx("span",{className:"text-text-primary font-medium",children:O.name}),s.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${O.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:O.isLocal?"local":"api"})]}),s.jsx("p",{className:"text-text-muted text-sm mt-1 truncate",children:O.url}),O.model&&s.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",O.model]})]}),s.jsx("div",{className:"flex items-center gap-1",children:w===O.id?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("button",{onClick:()=>P(O.id),disabled:g===O.id,className:"px-2 py-1 text-xs text-red-500 hover:text-red-400 bg-red-500/10 rounded transition-colors disabled:opacity-50",children:g===O.id?"Deleting...":"Confirm"}),s.jsx("button",{onClick:()=>C(null),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>I(O),className:"px-2 py-1 text-xs text-text-muted hover:text-text-secondary border border-border rounded transition-colors",children:"Edit"}),s.jsx("button",{onClick:()=>C(O.id),className:"p-2 text-text-muted hover:text-red-500 transition-colors",title:"Remove provider",children:s.jsx(Ri,{})})]})}),n&&s.jsxs("div",{className:"flex flex-col ml-1",children:[s.jsx("button",{type:"button",onClick:()=>F($,-1),disabled:$===0,className:"p-0.5 text-text-muted hover:text-text-secondary disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Move up","aria-label":"Move up",children:s.jsx(lm,{className:"w-3.5 h-3.5"})}),s.jsx("button",{type:"button",onClick:()=>F($,1),disabled:$===d.length-1,className:"p-0.5 text-text-muted hover:text-text-secondary disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Move down","aria-label":"Move down",children:s.jsx(mn,{className:"w-3.5 h-3.5"})})]})]},O.id))}):s.jsx("div",{className:"bg-bg-secondary rounded-lg p-8 text-center border border-border",children:s.jsx("p",{className:"text-text-muted",children:"No providers configured yet"})}),n&&k&&s.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Couldn't save the new provider order. Showing the last saved order."}),!n&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:M,"data-testid":"onboarding-add-provider-button",className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-bg-secondary border border-dashed border-border rounded-lg text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[s.jsx(kr,{className:"w-4 h-4"}),"Add Provider"]}),s.jsx("button",{onClick:z,disabled:!D,"data-testid":"onboarding-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:n?"Done":"Continue"})]})]}),s.jsx(DL,{isOpen:c,onClose:U,onSave:A,initialStep:1,editProvider:m??void 0})]})});function zq({isOpen:e,onClose:t}){const n=j.useRef(null);return s.jsx(vt,{isOpen:e,onClose:t,title:"Manage Providers",size:"lg",footer:s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{var r;return(r=n.current)==null?void 0:r.addProvider()},className:"flex items-center gap-2 px-4 py-2 rounded-lg border border-dashed border-border text-sm text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[s.jsx(kr,{className:"w-4 h-4"}),"Add Provider"]}),s.jsx("button",{type:"button",onClick:()=>{var r;return(r=n.current)==null?void 0:r.submit()},className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})]}),children:s.jsx(OL,{ref:n,onNext:t,embedded:!0})})}function Rj({activeProvider:e,shortModelName:t,effort:n,agentOverrideActive:r,agentColor:o,agentName:a,pinned:d}){return s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"text-sm text-accent-primary flex items-center gap-1",children:[r&&s.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 ring-1 ring-border",style:{backgroundColor:o??"#6b7280"},title:`Model set by agent "${a??"unknown"}". Change it in Settings > Agents.`}),e?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"hidden @sm:inline",children:[e.name," • "]}),t,n&&s.jsxs("span",{className:"text-text-muted",children:[":",n]})]}):s.jsxs(s.Fragment,{children:[t,n&&s.jsxs("span",{className:"text-text-muted",children:[":",n]})]}),d&&s.jsx("span",{className:"flex-shrink-0 text-text-muted",title:'Reasoning effort pinned for this session (chosen via "Keep current reasoning effort").',children:s.jsx(qO,{className:"w-3 h-3"})})]}),s.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${e!=null&&e.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:e!=null&&e.isLocal?"local":"api"})]})}function Hq(){var rc;const e=Vr(),t=Vt(e,ke=>ke.session??null,ke=>ke.currentSession,null),n=Vt(e,ke=>ke.contextState??null,ke=>ke.contextState,null),r=EL(),o=Re(ke=>ke.setSessionProvider),a=Re(ke=>ke.resetSessionProvider),d=Re(ke=>ke.clearSessionEffortPin),[l,c]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState([]),[x,w]=j.useState(null),C=j.useRef(null),[b,S]=j.useState(null),[_,v]=j.useState(!1),[k,E]=j.useState({}),[T,L]=j.useState(null),[A,M]=j.useState(null),[I,U]=j.useState(!1),P=j.useRef(null),[z,K]=j.useState(!1),H=j.useRef(new Set),F=Gt(ke=>ke.providers),Q=Gt(ke=>ke.activeProviderId),Z=Gt(ke=>ke.defaultModelSelection),V=Gt(ke=>ke.activating),B=Gt(ke=>ke.activateProvider),D=Gt(ke=>ke.refreshModel),O=Gt(ke=>ke.refreshProviderModels),$=Gt(ke=>ke.setDefaultModel),J=Gt(ke=>ke.updateModelSettings),X=Gt(ke=>ke.fetchConfig),Y=zu();Au(Y.modelSelector,()=>c(ke=>!ke));const q=(t==null?void 0:t.providerId)??null,W=(t==null?void 0:t.providerModel)??null,ee=(t==null?void 0:t.providerReasoningEffort)??null,ie=(t==null?void 0:t.providerPinnedEffort)??null,re=(Z==null?void 0:Z.split("/")[0])??null,se=(Z==null?void 0:Z.split("/").slice(1).join("/"))??null,{data:de}=Mi(er,t==null?void 0:t.workdir),Se=(de==null?void 0:de.defaults)??[],Me=(de==null?void 0:de.userItems)??[],ye=(de==null?void 0:de.modelOverrides)??{},ue=t==null?void 0:t.mode,Ie=ue?Se.find(ke=>ke.id===ue)??Me.find(ke=>ke.id===ue):void 0,We=ue?ye[ue]??void 0:void 0,Qe=We?Ca(We):void 0,ve=(Qe==null?void 0:Qe.providerId)??null,oe=(Qe==null?void 0:Qe.model)??null,ae=Qe==null?void 0:Qe.reasoningEffort,we=ue?wa([...Se,...Me],ue):void 0,$e=!!(t!=null&&t.providerManual)&&!!(t!=null&&t.providerManualActive),fe=t!=null&&t.providerId&&(t!=null&&t.providerModel)?`${t.providerId}/${t.providerModel}`:null,Ae=!!(t!=null&&t.providerManual)||fe!==null&&fe!==Z,Xe=!$e&&!!We,tt=$e?q:ve??q??re,pe=$e?W:oe??W??se,Ge=ie??($e?ee:ae??ee)??void 0,Je=!!ie,ot=pe?((rc=pe.split("/").pop())==null?void 0:rc.replace(/-/g," "))??pe:"No model",Ze=F.find(ke=>ke.id===tt),at=Ze==null?void 0:Ze.models.find(ke=>ke.id===pe),ce=gb({explicitEffort:Ge,reasoningEfforts:at==null?void 0:at.reasoningEfforts,thinkingLevel:at==null?void 0:at.thinkingLevel,thinkingEnabled:at==null?void 0:at.thinkingEnabled,override:at==null?void 0:at.reasoningEffortOverride}),Oe=(ke,it)=>{var En;if(tt===ke&&pe===it)return ce;const pt=(En=F.find(fr=>fr.id===ke))==null?void 0:En.models.find(fr=>fr.id===it);if(pt)return gb({reasoningEfforts:pt.reasoningEfforts,thinkingLevel:pt.thinkingLevel,thinkingEnabled:pt.thinkingEnabled,override:pt.reasoningEffortOverride})},[Ve,De]=j.useState(!1);j.useEffect(()=>{function ke(it){C.current&&!C.current.contains(it.target)&&(c(!1),g([]),H.current=new Set)}return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[]),j.useEffect(()=>()=>{P.current!==null&&window.clearTimeout(P.current)},[]),j.useEffect(()=>{l||(Ao(""),us(-1))},[l]),j.useEffect(()=>{var ke;l&&Wt()&&((ke=Wr.current)==null||ke.focus())},[l]),j.useEffect(()=>{if(l){const ke=F.map(it=>it.id);g(ke),F.filter(it=>!!it.authAdapter).forEach(it=>void Ee(it.id)),ke.forEach(it=>{H.current.has(it)||(H.current.add(it),kt(it))})}},[l,F]),j.useEffect(()=>{if(!A)return;let ke=!1;const it=async()=>{const En=await Ee(A.providerId);ke||En==="connected"&&(M(null),U(!1),K(!1),await X(),H.current.delete(A.providerId),await kt(A.providerId))};it();const pt=window.setInterval(()=>void it(),2e3);return()=>{ke=!0,window.clearInterval(pt)}},[A]);const st=(Ze==null?void 0:Ze.status)==="disconnected",rt=(ke,it)=>t?tt===ke&&pe===it:!1,yt=(ke,it)=>Z?Z===`${ke}/${it}`:!1,kt=async ke=>{w(ke);try{await O(ke)}catch{}finally{w(null)}},qt=ke=>{f.includes(ke.id)?g(f.filter(it=>it!==ke.id)):(g([...f,ke.id]),kt(ke.id))},Mn=async ke=>{if(ke.id===Q){qt(ke);return}t&&e?(o(e,ke.id,void 0),c(!1),g([])):await B(ke.id)&&(c(!1),g([]))},qn=ke=>{qt(ke)},In=async()=>{t&&e&&(a(e),c(!1),g([]))},hr=async()=>{t&&e&&(d(e),c(!1),g([]))},Nr=async(ke,it)=>{ke.stopPropagation(),H.current.delete(it),await kt(it)},Ee=async ke=>{const it=await be(`/api/provider-auth/${ke}/status`);if(!it.ok)return"error";const pt=await it.json();return E(En=>({...En,[ke]:pt.state})),pt.state},nt=async(ke,it)=>{ke.stopPropagation(),L(it),E(pt=>({...pt,[it]:"pending"})),U(!1),K(!1);try{const pt=await be(`/api/provider-auth/${it}/login`,{method:"POST"});if(!pt.ok)throw new Error("Unable to start provider sign-in");const En=await pt.json();M({providerId:it,...En})}catch{E(pt=>({...pt,[it]:"error"}))}finally{L(null)}},qe=async()=>{var ke;A!=null&&A.userCode&&(await((ke=navigator.clipboard)==null?void 0:ke.writeText(A.userCode)),P.current!==null&&window.clearTimeout(P.current),U(!1),requestAnimationFrame(()=>U(!0)),P.current=window.setTimeout(()=>{U(!1),P.current=null},1500))},Be=()=>{A&&(window.open(A.directUrl??A.verificationUrl,"_blank","noopener,noreferrer"),K(!0))},me=()=>{M(null),U(!1),K(!1)},xe=async(ke,it)=>{ke.stopPropagation(),L(it);try{if(!(await be(`/api/provider-auth/${it}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");E(En=>({...En,[it]:"disconnected"})),await X()}finally{L(null)}},He=(ke,it)=>{S({providerId:ke,model:it}),v(!0)},Ue=b?F.find(ke=>ke.id===b.providerId):void 0,et=()=>{S(null),v(!1)},ut=async ke=>{try{if(!(await be(`/api/providers/${ke.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(RL(ke))})).ok)throw new Error("Failed to update provider");await Gt.getState().fetchConfig()}catch{}S(null),v(!1)},ht=async(ke,it,pt,En)=>{const fr=t;if(fr){if(Re.setState(Pi=>({...Pi,currentSession:{...fr,providerId:it,providerModel:pt,providerReasoningEffort:En,providerManual:!0,providerManualActive:!0}})),!await o(ke,it,pt,En))return Re.setState(Pi=>({...Pi,currentSession:fr})),!1}else if(!await o(ke,it,pt,En))return!1;return g([]),c(!1),Ol(),!0},Xt=async(ke,it,pt)=>{if(t&&e){if(!pt&&tt===ke&&pe===it){g([]),c(!1),Ol();return}if(pt){if(Uv({warmCache:n==null?void 0:n.warmCache,currentEffort:ce,proposedEffort:pt})&&await r.requestEffortSwitch({fromEffort:ce,toEffort:pt})==="keep"){await ht(e,ke,it,ce??null);return}await ht(e,ke,it,pt)&&await J(ke,it,{thinkingLevel:pt,thinkingEnabled:!0});return}await ht(e,ke,it,null);return}await B(ke)&&(g([]),c(!1),Ol())},pn=async(ke,it,pt)=>{ke.stopPropagation(),De(!0);try{await $(it,pt)&&t&&e&&await ht(e,it,pt,null)}catch{}finally{De(!1)}},{searchQuery:kn,setSearchQuery:Ao,highlightedIndex:Js,setHighlightedIndex:us,visibleGroups:Zs,flatItems:Tr,handleSearchKeyDown:ds,highlightedRef:Ls,inputRef:Wr}=kA({providers:F,onSelect:Xt,onEscape:()=>c(!1),extraItemCount:1}),jn=Js===Tr.length,td=ke=>{if(ke.key==="Enter"&&Js===Tr.length){ke.preventDefault(),c(!1),m(!0);return}ds(ke)};return F.length===0?s.jsxs("button",{type:"button",onClick:()=>D(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:st?"LLM server is offline. Click to retry.":ot??"Click to refresh model",children:[st?s.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):s.jsx(Rj,{activeProvider:Ze,shortModelName:ot,effort:ce,agentOverrideActive:Xe,agentColor:we,agentName:Ie==null?void 0:Ie.name,pinned:Je}),s.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):s.jsxs("div",{className:"relative",ref:C,children:[s.jsxs("button",{type:"button",onClick:()=>c(!l),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:"Click to switch provider or model",children:[st?s.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):s.jsx(Rj,{activeProvider:Ze,shortModelName:ot,effort:ce,agentOverrideActive:Xe,agentColor:we,agentName:Ie==null?void 0:Ie.name,pinned:Je}),s.jsx(mn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:l?180:0})]}),l&&s.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[s.jsxs("div",{className:"flex items-center gap-1 px-3 py-2 border-b border-border flex-shrink-0",children:[s.jsx(Gs,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),s.jsx("input",{ref:Wr,type:"text",value:kn,onInput:ke=>{Ao(ke.currentTarget.value),us(-1)},onKeyDown:td,placeholder:"Search models...",className:"bg-transparent border-none outline-none text-sm text-text-primary w-full placeholder:text-text-muted"})]}),s.jsx(xt,{className:"flex-1 min-h-0",children:s.jsxs("div",{children:[Zs.map(ke=>{const it=kn.trim().length>0||f.includes(ke.provider.id);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${ke.provider.id===tt?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${V?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[s.jsxs("div",{onClick:()=>!V&&Mn(ke.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[s.jsx("span",{className:`text-sm font-medium truncate ${ke.provider.id===tt?"text-accent-primary":"text-text-primary"}`,children:ke.provider.name}),s.jsx("span",{className:"text-xs text-text-muted truncate",children:ke.provider.backend!=="unknown"&&HE(ke.provider.backend)})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!ke.provider.authAdapter&&(k[ke.provider.id]==="connected"||ke.provider.credentialRef?s.jsx("button",{type:"button",onClick:pt=>xe(pt,ke.provider.id),disabled:T===ke.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-success/40 text-accent-success hover:bg-accent-success/10 disabled:opacity-50",title:"Disconnect provider account",children:"Connected"}):s.jsx("button",{type:"button",onClick:pt=>nt(pt,ke.provider.id),disabled:T===ke.provider.id,className:"text-[10px] px-1.5 py-0.5 rounded border border-accent-primary/40 text-accent-primary hover:bg-accent-primary/10 disabled:opacity-50",title:"Connect provider account",children:T===ke.provider.id?"Starting…":k[ke.provider.id]==="error"||k[ke.provider.id]==="expired"?"Retry":"Connect"})),ke.provider.id===tt?s.jsx("span",{className:"text-accent-success",title:"Active provider",children:s.jsx(Ys,{className:"w-4 h-4"})}):s.jsx("span",{className:"w-4"}),s.jsx("button",{type:"button",onClick:pt=>{pt.stopPropagation(),Nr(pt,ke.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:s.jsx(dm,{className:`w-4 h-4 ${x===ke.provider.id?"animate-spin":""} ${ke.provider.id===Q?"text-accent-primary":"text-text-muted"}`})}),s.jsx("button",{type:"button",onClick:pt=>{pt.stopPropagation(),qn(ke.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:s.jsx(mn,{className:`w-4 h-4 transition-transform ${it?"rotate-180":""} ${ke.provider.id===Q?"text-accent-primary":"text-text-muted"}`})})]})]}),it&&s.jsx(xt,{className:"bg-bg-primary border-t border-border max-h-40",children:x===ke.provider.id?s.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):ke.models.length>0?ke.models.map(pt=>{const fr=Tr.findIndex(Lo=>Lo.providerId===ke.provider.id&&Lo.modelConfig.id===pt.id)===Js;return s.jsx("div",{ref:fr?Ls:void 0,children:s.jsx(CA,{providerId:ke.provider.id,modelConfig:pt,isActive:rt(ke.provider.id,pt.id),isDefault:yt(ke.provider.id,pt.id),disabled:x==="activating",hasSession:!!t,settingDefault:Ve,highlighted:fr,onModelClick:Xt,onSetDefault:pn,onEditModel:He,reasoningEfforts:pt.reasoningEfforts,selectedEffort:Oe(ke.provider.id,pt.id),onSelectEffort:Xt})},`${ke.provider.id}/${pt.id}`)}):s.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},ke.provider.id)}),Zs.length===0&&kn.trim()&&s.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No models match your search"})]})}),s.jsxs("div",{className:`border-t border-border px-3 py-2 flex items-center justify-between gap-2 ${jn?"bg-bg-tertiary":""} flex-shrink-0`,children:[Je&&s.jsx("button",{type:"button",onClick:hr,className:"text-xs text-text-muted hover:text-text-primary hover:underline",title:"Stop pinning the reasoning effort so agent overrides and session picks apply again",children:"Unpin reasoning effort"}),Ae&&s.jsx("button",{type:"button",onClick:In,className:"text-xs text-text-muted hover:text-text-primary hover:underline",title:"Clear this session's manually picked model so agent overrides and the global default apply again",children:"Reset to default"}),s.jsx("button",{onClick:()=>{c(!1),m(!0)},className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})]})]}),A&&s.jsxs(vt,{isOpen:!0,onClose:me,title:"Connect provider",size:"md",children:[s.jsx("p",{className:"text-sm text-text-muted",children:"Follow the provider instructions to complete authorization."}),A.mode!=="browser"?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:qe,className:"mt-6 w-full select-all rounded-lg border border-accent-primary/40 bg-bg-primary px-4 py-5 font-mono text-3xl font-semibold tracking-[0.2em] text-accent-primary hover:bg-bg-tertiary",title:"Copy code",children:A.userCode??"Continue"}),s.jsx("div",{className:"mt-3 text-center text-xs text-text-muted",children:I?"Copied to clipboard":"Click the code to copy it"}),s.jsxs("div",{className:"mt-6 flex gap-3",children:[s.jsx("button",{type:"button",onClick:qe,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:I?"Copied":"Copy code"}),s.jsx("button",{type:"button",onClick:Be,className:"flex-1 rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:z?"Reopen authorization":"Open authorization"})]}),s.jsx("p",{className:"mt-4 text-center text-xs text-text-muted",children:z?"If the browser blocked or closed the tab, reopen authorization.":"OpenFox stays open while you complete authorization in the other tab."})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"mt-6 text-sm text-text-secondary leading-relaxed bg-bg-primary p-4 rounded-lg border border-border",children:A.instructions}),s.jsx("div",{className:"mt-6 flex gap-3",children:s.jsx("button",{type:"button",onClick:Be,className:"w-full rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary hover:bg-accent-primary/90",children:z?"Reopen authorization":"Open authorization"})})]})]}),b&&_&&s.jsx(DL,{isOpen:!0,onClose:et,onSave:ut,initialStep:2,editProvider:{id:b.providerId,name:(Ue==null?void 0:Ue.name)??"",url:(Ue==null?void 0:Ue.url)??"",backend:(Ue==null?void 0:Ue.backend)??"unknown",apiKey:Ue==null?void 0:Ue.apiKey,isLocal:Ue==null?void 0:Ue.isLocal,thinkingField:Ue==null?void 0:Ue.thinkingField,sendReasoningInMessages:Ue==null?void 0:Ue.sendReasoningInMessages,authAdapter:Ue==null?void 0:Ue.authAdapter,transportAdapter:Ue==null?void 0:Ue.transportAdapter,models:Ue==null?void 0:Ue.models},editModelId:b.model.id}),s.jsx(zq,{isOpen:h,onClose:()=>{m(!1),X()}})]})}function Uq(){const e=Eu(k=>k.servers),t=Eu(k=>k.fetchServers),n=Re(k=>k.currentSession),r=n==null?void 0:n.id,[o,a]=j.useState(!1),[d,l]=j.useState(null),[c,h]=j.useState(new Set),[m,f]=j.useState(new Set),g=j.useRef(null),x=j.useCallback(async()=>{if(r)try{const k=await be(`/api/sessions/${r}/mcp/overrides`);if(k.ok){const E=await k.json();f(new Set(E.disabledServers??[]))}}catch{}},[r]),w=j.useCallback(async()=>{await t(),await x()},[t,x]);j.useEffect(()=>{const k=()=>w();return window.addEventListener("mcp-servers-changed",k),()=>window.removeEventListener("mcp-servers-changed",k)},[w]),j.useEffect(()=>{x()},[x]),j.useEffect(()=>{o&&x()},[o,x]),zm(g,()=>a(!1));const C=k=>m.has(k.name),b=e.filter(k=>k.status==="connected"&&!C(k)),S=b.length,_=b.reduce((k,E)=>k+E.estimatedTokens,0),v=async(k,E)=>{if(r){l(null),h(T=>new Set(T).add(k));try{const T=new Set(m);E?T.add(k):T.delete(k);const L=await be(`/api/sessions/${r}/mcp/overrides`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledServers:Array.from(T)})});if(!L.ok){const A=await L.json().catch(()=>({}));throw new Error(A.error??"Toggle failed")}f(T),await t()}catch(T){l(T instanceof Error?T.message:String(T))}finally{h(T=>{const L=new Set(T);return L.delete(k),L})}}};return s.jsxs("div",{className:"relative",ref:g,children:[s.jsxs("button",{type:"button",onClick:()=>a(!o),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:S>0?`${S} MCP server(s) active`:"No MCP server active",children:[s.jsx("span",{className:"text-sm text-accent-primary whitespace-nowrap",children:S>0?`● ${S} MCP (${Df(_)})`:"MCP"}),s.jsx(mn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:o?180:0})]}),o&&s.jsxs("div",{className:"absolute bottom-full right-0 mb-1 min-w-72 max-w-[100vw] bg-bg-secondary border border-border rounded-lg shadow-lg z-50 flex flex-col max-h-[80vh]",children:[s.jsx(xt,{className:"flex-1 min-h-0",children:e.length===0?s.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No MCP servers configured"}):e.map(k=>{const E=C(k),T=c.has(k.name);return s.jsx("div",{children:s.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-bg-tertiary",children:[s.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[s.jsx("span",{className:`text-sm ${$v(E?"disabled":k.status)}`,children:Fv(E?"disabled":k.status)}),s.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:k.name})]}),s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[s.jsxs("span",{children:[k.tools.length," tools"]}),k.estimatedTokens>0&&s.jsxs("span",{children:[Df(k.estimatedTokens)," tokens"]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[T&&s.jsx("span",{className:"text-xs text-text-muted animate-pulse",children:"..."}),s.jsx(ks,{enabled:!E,onClick:()=>v(k.name,!E)})]})]})},k.name)})}),s.jsx("div",{className:"border-t border-border px-3 py-2 flex-shrink-0",children:d?s.jsx("div",{className:"text-xs text-accent-error",children:d}):s.jsxs("span",{className:"text-xs text-text-muted",children:[e.length," server(s) configured"]})})]})]})}const Dj=24,Oj=200;function Vq({input:e,setInput:t,attachments:n,setAttachments:r,dragOver:o,setDragOver:a,errorMessage:d,setErrorMessage:l,scrollToBottom:c,sessionId:h,showHistory:m,history:f,selectedIndex:g,openHistory:x,closeHistory:w,navigateUp:C,navigateDown:b,selectCurrent:S,isAutoScrollActive:_,setAutoScroll:v,onOpenMessageSearch:k,onOpenCommandsModal:E,onOpenWorkflowsModal:T,onSelectWorkflow:L,onSelectWorkflowWithSubGroup:A,onSendCommand:M,clearInput:I}){const U=j.useRef(null),P=j.useRef(null),z=j.useRef(0),K=j.useRef(0),H=j.useRef(null),F=j.useRef(null),Q=om(h),Z=Re(pe=>pe.stopGeneration),V=Re(pe=>pe.cancelQueued),B=wO(h),D=Vt(h,pe=>pe.restoredInput??null,pe=>pe.restoredInput,null),O=Re(pe=>pe.clearRestoredInput),$=Vt(h,pe=>{var Ge;return((Ge=pe.session)==null?void 0:Ge.workdir)??void 0},pe=>{var Ge;return(Ge=pe.currentSession)==null?void 0:Ge.workdir},void 0),J=Vt(h,pe=>pe.session??null,pe=>pe.currentSession,null),X=j.useRef(!1),Y=j.useRef(void 0),q=j.useRef(!1),[W,ee]=j.useState([]),ie=j.useRef(null),{sendMessage:re,launchWorkflow:se}=AL(v,h);j.useEffect(()=>{Y.current!==$&&(Y.current=$,Pt.getState().fetchWorkflows($),ln.getState().fetchCommands($))},[$]),j.useEffect(()=>{e||ee([])},[e]),j.useEffect(()=>{var pe;D!==null&&(t(D),O(h),Wt()&&((pe=U.current)==null||pe.focus()))},[D,t,O]);const de=j.useCallback((pe={})=>{const Ge=U.current;if(!Ge)return;if(!e){Ge.style.height=`${Dj}px`;return}const Je=e.length>=z.current;z.current=e.length,(pe.force||!Je)&&(Ge.style.height="auto"),Ge.style.height=`${Math.min(Oj,Ge.scrollHeight)}px`},[e]),Se=j.useRef(de);j.useEffect(()=>{Se.current=de},[de]),j.useEffect(()=>{if(!h)return;const pe=`openfox:draft:${h}`,Ge=localStorage.getItem(pe);Ge!==null&&t(Ge)},[h,t]),j.useEffect(()=>{var pe;Wt()&&((pe=U.current)==null||pe.focus()),de()},[h,de]),j.useEffect(()=>{if(!h)return;const pe=`openfox:draft:${h}`,Ge=setTimeout(()=>{e?localStorage.setItem(pe,e):localStorage.removeItem(pe)},500);return()=>clearTimeout(Ge)},[h,e]),j.useEffect(()=>{de()},[e,de]),j.useEffect(()=>{var ot;const pe=(ot=U.current)==null?void 0:ot.parentElement;if(!pe||typeof ResizeObserver>"u")return;let Ge=pe.clientWidth;const Je=new ResizeObserver(()=>{const Ze=pe.clientWidth;Ze!==Ge&&(Ge=Ze,Se.current({force:!0}))});return Je.observe(pe),()=>Je.disconnect()},[]),j.useEffect(()=>{const pe=U.current;if(!pe)return;const Ge=async Je=>{var at;if(document.activeElement!==pe)return;const ot=(at=Je.clipboardData)==null?void 0:at.items;if(!ot)return;const Ze=[];for(const ce of Array.from(ot)){let Oe=ce.getAsFile();if(Oe&&AU(Oe.type)){if(Je.preventDefault(),!Oe.name){const Ve=TU(Oe.type);Oe=new File([Oe],`pasted-file.${Ve}`,{type:Oe.type})}await yb(Oe,Ve=>Ze.push(Ve),l)}}Ze.length>0&&r(ce=>[...ce,...Ze])};return pe.addEventListener("paste",Ge),()=>pe.removeEventListener("paste",Ge)},[r,l]);const Me=pe=>{pe.preventDefault(),!(!e.trim()&&n.length===0)&&we()},ye=pe=>{var Ge,Je;if(!((Ge=F.current)!=null&&Ge.handleKeyDown(pe))&&!((Je=H.current)!=null&&Je.handleKeyDown(pe))){if(m)switch(pe.key){case"Enter":{pe.preventDefault();const ot=S();ot&&(t(ot),w());return}case"Escape":pe.preventDefault(),w(),Q&&h&&Z(h);return;case"ArrowUp":pe.preventDefault(),C();return;case"ArrowDown":pe.preventDefault(),b();return}if(pe.key==="ArrowUp"&&e.trim()===""&&!m){pe.preventDefault(),x();return}pe.key==="Enter"&&!pe.shiftKey&&(pe.preventDefault(),Me(pe))}};async function ue(pe,Ge,Je){const ot=[];for(const Ze of Array.from(pe))await yb(Ze,at=>ot.push(at),Je);ot.length>0&&Ge(Ze=>[...Ze,...ot])}const Ie=j.useCallback(async pe=>{const Ge=pe.target.files;!Ge||Ge.length===0||(l(null),await ue(Ge,r,l),P.current&&(P.current.value=""))},[r,l]),We=j.useCallback(pe=>{var Ge;(Ge=pe.dataTransfer.types)!=null&&Ge.includes("Files")&&(pe.preventDefault(),pe.stopPropagation(),a(!0))},[a]),Qe=j.useCallback(pe=>{pe.preventDefault(),pe.stopPropagation(),a(!1)},[a]),ve=j.useCallback(async pe=>{pe.preventDefault(),pe.stopPropagation(),a(!1),l(null);const Ge=pe.dataTransfer.files;!Ge||Ge.length===0||await ue(Ge,r,l)},[r,a,l]),oe=j.useCallback(pe=>{r(n.filter(Ge=>Ge.id!==pe))},[n,r]),ae=j.useCallback(()=>{var pe;(pe=P.current)==null||pe.click()},[]),we=()=>{if(q.current||!e.trim()&&n.length===0)return;if(q.current=!0,c==null||c(),e.trim().startsWith("/")){const Ge=ka(Pt.getState()),Je=ln.getState(),ot=ir(ir(Je.defaults,Je.userItems),Je.projectItems),Ze=pq(e,Ge,ot);if(Ze!=null&&Ze.workflowId){const at=ie.current,ce=at&&at.id===Ze.workflowId?at.scope:"auto";ie.current=null;const Oe=If(Ge,Ze.workflowId,ce),Ve=((Oe==null?void 0:Oe.parameters)??[]).filter(De=>De.required&&!(De.id in Ze.params));if(Ve.length>0){const De=Ve.map(st=>st.label||st.id).join(", ");l(`Missing required parameter${Ve.length>1?"s":""}: ${De}`),q.current=!1;return}se(void 0,void 0,Ze.workflowId,void 0,Ze.params,ce),I(),q.current=!1;return}if(Ze!=null&&Ze.commandId){Je.fetchCommand(Ze.commandId,$).then(at=>{if(at){const ce=kL(at.prompt),Oe={};for(const[De,st]of Object.entries(Ze.params)){const rt=parseInt(De,10),yt=ce[rt];yt&&(Oe[yt]=st)}let Ve=at.prompt;for(const[De,st]of Object.entries(Oe))Ve=Ve.replaceAll(`{{${De}}}`,st);M(Ve,at.metadata.agentMode),I()}q.current=!1});return}}re(e,n),I(),q.current=!1},$e=j.useCallback((pe,Ge)=>{const ot=pe.type==="directory"?"/":" ",{newText:Ze,newCursorPos:at}=Pf(e,K.current,Ge,`@${pe.path}${ot}`);t(Ze),K.current=at,Bf(U.current,at)},[e,t]),fe=j.useCallback((pe,Ge)=>{const{newText:Je,newCursorPos:ot}=Pf(e,K.current,Ge,`/${pe.id} `);t(Je),K.current=ot,Bf(U.current,ot),pe.type==="workflow"&&(ie.current={id:pe.id,scope:pe.scope}),ee(AA(pe))},[e,t]),Ae=j.useCallback(pe=>{const Ge=pe.target.value;t(Ge),m&&w(),K.current=pe.target.selectionStart;const Je=ie.current;if(Je){const ot=Ge.match(/^\/(\S+)/),Ze=ot?ot[1]:void 0;(!Ze||Ze!==Je.id)&&(ie.current=null)}W.length>0&&(!Ge.startsWith("/")||!Ge.includes(" "))&&ee([]),!X.current&&h&&Ge&&J&&(J.messageCount??0)===0&&(X.current=!0,be(`/api/sessions/${h}/warmup`,{method:"POST"}).catch(()=>{}))},[t,m,w,h,J,W]),Xe=j.useCallback(pe=>{K.current=pe.target.selectionStart},[]),tt=j.useCallback(pe=>{K.current=pe.currentTarget.selectionStart},[]);return s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"absolute -top-8 left-2 @md:left-4 z-10",children:s.jsx(_q,{})}),s.jsxs("div",{className:`absolute -top-8 right-2 @md:right-4 z-10 flex items-center gap-2 border${_?" border-transparent":" rounded backdrop-blur-xl saturate-150 border-border"}`,children:[s.jsx(Qv,{isActive:_,onToggle:v,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),s.jsxs("button",{type:"button",onClick:k,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Browse history",children:[s.jsx(Gs,{}),"Browse history"]})]}),s.jsx(Sq,{}),s.jsxs("form",{onSubmit:Me,className:"p-2 @md:p-4 bg-secondary rounded-lg",children:[s.jsx("input",{ref:P,type:"file",accept:"image/*,text/*,.pdf,.json,.xml,.yaml,.yml,.js,.sh,.xhtml",onChange:Ie,className:"hidden",multiple:!0}),d&&s.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:d}),n.length>0&&s.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:n.map(pe=>s.jsx(Hv,{attachment:pe,onRemove:oe},pe.id))}),m&&s.jsx(gq,{history:f,selectedIndex:g,onSelect:pe=>{t(pe),w()},onEscape:w,onNavigate:pe=>{pe==="up"?C():b()}}),s.jsx(Tq,{messages:B,onCancel:pe=>h&&V(h,pe)}),s.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${o?"bg-accent-primary/10":"bg-primary"}`,onDragOver:We,onDragLeave:Qe,onDrop:ve,children:[s.jsxs("div",{className:"relative flex-1 min-w-0",children:[s.jsx("textarea",{id:dA,ref:U,value:e,onChange:Ae,onKeyDown:ye,onSelect:Xe,onKeyUp:tt,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",className:"w-full bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:`${Dj}px`,maxHeight:`${Oj}px`},spellCheck:!1}),s.jsx(TA,{ref:H,text:e,cursorPos:K.current,workdir:$,onSelect:$e}),s.jsx(NA,{ref:F,text:e,cursorPos:K.current,workflows:ka(Pt.getState()),commands:(()=>{const pe=ln.getState();return ir(ir(pe.defaults,pe.userItems),pe.projectItems)})(),onSelect:fe}),W.length>0&&(()=>{const pe=e.match(/\/(\w+)\s+(.*)$/),Je=(pe?pe[2].trim().split(/\s+/):[]).filter(Boolean).length,ot=W[Je];return ot?s.jsxs("span",{className:"absolute left-3 top-[26px] text-sm text-text-muted/40 pointer-events-none select-none","aria-hidden":!0,children:[ot,"=?"]}):null})()]}),s.jsxs("div",{className:"flex items-center self-center gap-1.5",children:[Q&&s.jsxs("button",{type:"button",onClick:()=>h&&Z(h),"data-testid":"chat-stop-button",className:"flex items-center gap-1 px-4 py-1.5 rounded bg-accent-error/20 text-sm text-accent-error font-medium hover:bg-accent-error/30 transition-colors whitespace-nowrap",children:[s.jsx(Xb,{}),"Abort"]}),s.jsxs("div",{className:"flex items-center",children:[s.jsx("button",{type:"button",onClick:we,disabled:!e.trim()&&n.length===0,"data-testid":"chat-send-button",className:"px-4 py-1.5 rounded-l bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:"Send"}),s.jsx(Eq,{onSendCommand:M,onSelectWorkflow:L,onSelectWorkflowWithSubGroup:A,onOpenCommandsManager:E,onOpenWorkflowsManager:T,onAttach:ae,textareaContent:e,attachments:n.length>0?n:void 0})]})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Iq,{}),s.jsx(Pq,{})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[It(pe=>pe.settings)[Te.FEATURES_PER_SESSION_MCP]==="true"&&s.jsx(Uq,{}),s.jsx(Hq,{})]})]})]})]})}const Wq=4;function Gq({projectId:e,sessionId:t}){const n=zt(w=>w.tasks),r=zt(w=>w.activeProjectId),o=zt(w=>w.loadBoard),a=zt(w=>w.moveTask),d=zt(w=>w.lastError),[l,c]=j.useState(!1),[h,m]=j.useState(null);j.useEffect(()=>{r!==e&&o(e)},[r,e,o]);const f=j.useMemo(()=>n.filter(w=>w.status==="todo"&&w.sessionIds.length===0).sort((w,C)=>w.position-C.position).slice(0,Wq),[n]),g=j.useMemo(()=>n.filter(w=>w.status==="in_progress"&&w.runState==="running").length,[n]);if(f.length===0)return null;const x=async w=>{var b;m(null);const C=await a(e,w.id,"in_progress",{sessionId:t});C!=null&&C.task&&C.task.status==="in_progress"&&C.task.runState==="queued"&&m({label:((b=w.prompt.split(`
|
|
306
306
|
`)[0])==null?void 0:b.slice(0,60))||"This task"})};return s.jsxs("div",{className:"mx-auto max-w-xl w-full",children:[s.jsxs("div",{className:"rounded-lg border border-border bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-text-muted",children:[s.jsx(fm,{className:"w-3.5 h-3.5"}),"Up next",g>0&&s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-xs font-medium normal-case tracking-normal text-emerald-400",title:`${g} task${g!==1?"s":""} currently running`,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"}),g," running"]})]}),s.jsx(ct,{size:"sm",onClick:()=>c(!0),children:"Manage tasks"})]}),h&&s.jsx("div",{className:"mt-3 rounded-md border border-amber-400/40 bg-amber-400/10 p-2.5",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("p",{className:"text-xs text-text-primary",children:["“",h.label,"” is queued — it’ll start automatically when a slot frees."]}),s.jsx("button",{type:"button",onClick:()=>m(null),title:"Dismiss",className:"shrink-0 text-xs text-text-muted underline hover:text-text-primary transition-colors",children:"Dismiss"})]})}),s.jsx("ul",{className:"mt-3 space-y-2",children:f.map((w,C)=>s.jsxs("li",{className:"flex items-start justify-between gap-3 rounded-md border border-border bg-bg-secondary px-3 py-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"text-sm text-text-primary font-medium leading-snug line-clamp-2 break-words whitespace-pre-wrap",children:w.prompt}),s.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs text-text-muted",children:[w.attachments.length>0&&s.jsxs("span",{children:["📎 ",w.attachments.length]}),w.model&&s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary border border-border",children:w.model})]})]}),s.jsxs(ct,{variant:C===0?"primary":"secondary",size:"sm",onClick:()=>void x(w),className:"shrink-0 flex items-center gap-1",children:["Start ",s.jsx(am,{className:"w-3 h-3"})]})]},w.id))}),d&&s.jsx("div",{className:"mt-3 text-sm text-accent-error",children:d})]}),s.jsx(Fm,{isOpen:l,onClose:()=>c(!1),projectId:e})]})}function Mj({workflowName:e,parameters:t,onConfirm:n,onCancel:r,confirmLabel:o="Run workflow"}){const[a,d]=j.useState({}),l=[...t].sort((m,f)=>(m.position??0)-(f.position??0)),c=()=>{var f;const m={};for(const g of l){const x=(f=a[g.id])==null?void 0:f.trim();x&&(m[g.id]=x)}n(m)},h=l.every(m=>{var f;return!m.required||(((f=a[m.id])==null?void 0:f.trim())??"")!==""});return s.jsx(vt,{isOpen:!0,onClose:r,title:`Run: ${e}`,size:"sm",closeOnEscape:!0,closeOnBackdropClick:!0,footer:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:r,className:"px-3 py-1.5 text-sm text-text-muted hover:text-text-primary transition-colors",children:"Cancel"}),s.jsx("button",{onClick:c,disabled:!h,className:"px-4 py-1.5 text-sm font-medium rounded bg-accent-primary/20 text-accent-primary hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:o})]}),children:s.jsx("div",{className:"space-y-3",children:l.map(m=>s.jsxs("label",{className:"block",children:[s.jsxs("span",{className:"text-sm text-text-primary font-medium",children:[m.label||m.id,m.required&&s.jsx("span",{className:"text-accent-error ml-1",children:"*"})]}),m.description&&s.jsx("span",{className:"block text-xs text-text-muted mt-0.5",children:m.description}),s.jsx("input",{value:a[m.id]??"",onChange:f=>d(g=>({...g,[m.id]:f.target.value})),placeholder:m.label||m.id,className:"mt-1 w-full px-3 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-accent-primary",autoFocus:(m.position===0||m===l[0])&&Wt()})]},m.id))})})}const Ij=9999,qh=j.forwardRef(function({trigger:t,children:n},r){const[o,a]=j.useState(!1),d=j.useRef(null),l=j.useRef(null),c=j.useRef(null),h=j.useCallback(()=>{a(!1)},[]);j.useImperativeHandle(r,()=>({close:h}),[h]);const m=j.useCallback(f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),o?h():(c.current=document.activeElement,a(!0))),f.key==="Escape"&&o&&h()},[o,h]);return j.useEffect(()=>{var w;if(!o){Wt()&&((w=c.current)==null||w.focus()),c.current=null;return}const f=C=>{l.current&&!l.current.contains(C.target)&&d.current&&!d.current.contains(C.target)&&h()},g=C=>{C.key==="Escape"&&h()},x=()=>h();return document.addEventListener("mousedown",f),document.addEventListener("keydown",g),window.addEventListener("blur",x),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",g),window.removeEventListener("blur",x)}},[o,h]),s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:d,role:"button",tabIndex:0,"aria-expanded":o,className:"inline-flex cursor-pointer text-text-muted hover:text-text-primary transition-colors outline-none focus-visible:ring-1 focus-visible:ring-accent-primary/50 rounded",onClick:()=>{o||(c.current=document.activeElement),a(f=>!f)},onKeyDown:m,children:t}),o&&Di.createPortal(s.jsx("div",{ref:l,role:"dialog","aria-modal":"true",className:"fixed bg-bg-secondary border border-border rounded-lg shadow-xl p-3 w-[320px] max-w-[calc(100vw-16px)] max-h-[60vh]",style:(()=>{if(!d.current)return{zIndex:Ij,top:0,left:0};const f=d.current.getBoundingClientRect(),g=320,x=8;let w=f.left;return w+g>window.innerWidth-x&&(w=f.right-g),w=Math.max(x,Math.min(w,window.innerWidth-g-x)),{zIndex:Ij,top:f.bottom+4,left:w}})(),children:s.jsx(xt,{className:"max-h-full",children:n})}),document.body)]})});function qq({entries:e}){const t=new Map;for(const r of e)t.set(r.status,(t.get(r.status)??0)+1);const n=VA.filter(r=>(t.get(r)??0)>0);return n.length===0?s.jsx("span",{className:"text-text-muted text-sm",children:"None"}):s.jsx("span",{className:"flex items-center gap-1.5 text-sm",children:n.map(r=>s.jsxs("span",{className:"flex items-center gap-0.5",children:[s.jsx(nc,{status:r}),s.jsx("span",{className:"text-text-muted",children:t.get(r)})]},r))})}function Kq({visible:e}){const{contextState:t,currentSession:n}=tc(),r=Re(ee=>ee.queueUpdate),o=n?n.workspace??n.workdir:void 0,a=Vb(o),d=a.status,l=a.config,c=a.logs,h=ys(ee=>ee.start),{branch:m,diff:f}=Yv(),[g,x]=j.useState(!1),[w,C]=j.useState(!1),[b,S]=j.useState(!1),[_,v]=j.useState(null),[k,E]=j.useState(!1),[T,L]=j.useState(!1),A=j.useRef(null),M=j.useRef(null),I=j.useRef(null),U=j.useRef(null),P=It(ee=>ee.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true";if(!e||!n)return null;const z=Uu(n.workspace??"")||"original",K=n.metadataEntries??{},H=K.criteria??[],F=["review_findings","todos"],Q=F.filter(ee=>{var ie;return ee in K&&(((ie=K[ee])==null?void 0:ie.length)??0)>0}),Z=Object.keys(K).filter(ee=>ee!=="criteria"&&!F.includes(ee)).filter(ee=>{var ie;return(((ie=K[ee])==null?void 0:ie.length)??0)>0}),V=[...Q,...Z].reduce((ee,ie)=>{var re;return ee+(((re=K[ie])==null?void 0:re.length)??0)},0),B=[...Q,...Z].map(Ml),D=f.files,O=D.reduce((ee,ie)=>ee+ie.additions,0),$=D.reduce((ee,ie)=>ee+ie.deletions,0),J=(d==null?void 0:d.state)??"off",X=J==="running"||J==="warning",Y=l!==null,q=ee=>{ee.stopPropagation(),o&&h(o)},W=ee=>{ee.stopPropagation(),d!=null&&d.url&&window.open(d.url,"_blank")};return s.jsxs("div",{className:"flex-shrink-0 px-4 py-1.5 border-b border-border bg-secondary",children:[s.jsxs("div",{className:"grid grid-cols-2 @sm:flex @sm:items-center @sm:justify-between gap-x-2 gap-y-1 text-sm",children:[s.jsxs("div",{className:"flex items-center gap-1 min-w-0 @sm:shrink-0",children:[s.jsx(Cr,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),s.jsx("span",{className:"truncate text-text-secondary max-w-[120px]",children:z}),s.jsx("span",{className:"text-text-muted",children:"/"}),s.jsx(ga,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),s.jsx("span",{className:"truncate text-text-secondary max-w-[120px]",children:m??"-"}),D.length>0?s.jsxs("span",{className:"text-text-muted shrink-0 font-mono",children:["+",O," -",$]}):s.jsx("span",{className:"shrink-0"}),s.jsx(qh,{ref:U,trigger:s.jsx(mn,{className:"w-3 h-3"}),children:s.jsx(oL,{workspaceName:z,branch:m,workdir:o,showEditorLink:P,sessionId:n.id,projectId:n.projectId,onEditWorkspace:()=>{var ee;(ee=U.current)==null||ee.close(),E(!0)},onEditBranch:()=>{var ee;(ee=U.current)==null||ee.close(),L(!0)}})})]}),s.jsx("div",{className:"hidden @sm:block w-px bg-border self-stretch mx-1"}),s.jsxs("div",{className:"flex-1 flex items-center @sm:justify-center justify-self-end gap-1 min-w-0",children:[s.jsx(qq,{entries:H}),V>0&&s.jsxs("span",{className:"text-text-muted text-xs bg-bg-tertiary px-1 py-0.5 rounded leading-none",title:B.join(", "),children:["+",V]}),s.jsx(qh,{ref:I,trigger:s.jsx(mn,{className:"w-3 h-3"}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("button",{onClick:()=>{var ee;(ee=I.current)==null||ee.close(),v("criteria")},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:s.jsx(Ff,{entries:H,title:"Acceptance Criteria"})}),s.jsx(qA,{entries:H,sessionId:n.id})]}),[...Q,...Z].map(ee=>{const ie=K[ee];return s.jsxs("div",{children:[s.jsx("button",{onClick:()=>{var re;(re=I.current)==null||re.close(),v(ee)},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:s.jsx(Ff,{entries:ie,title:Ml(ee)})}),s.jsx(WA,{entries:ie})]},ee)})]})})]}),s.jsx("div",{className:"hidden @sm:block w-px bg-border self-stretch mx-1"}),s.jsx("div",{className:"col-span-2 border-t border-border @sm:hidden -mx-4"}),s.jsx("div",{className:"flex items-center gap-1.5 min-w-0 shrink-0",children:t&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted text-xs font-mono tabular-nums",children:t.currentTokens>=1e3?`${Math.round(t.currentTokens/1e3)}K`:t.currentTokens}),s.jsx(Zv,{percent:Math.round(t.currentTokens/t.maxTokens*100),dangerZone:t.dangerZone,size:"sm"}),s.jsx(qh,{ref:M,trigger:s.jsx(mn,{className:"w-3 h-3"}),children:s.jsx(lL,{onUpdateSystemPrompt:()=>{var ee;(ee=M.current)==null||ee.close(),S(!0)}})})]})}),s.jsx("div",{className:"hidden @sm:block w-px bg-border self-stretch mx-1"}),s.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 shrink-0 justify-self-end",children:[s.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${J==="running"?"bg-accent-success":J==="warning"?"bg-accent-warning":J==="error"?"bg-accent-error":"bg-text-muted"}`}),Y?X?s.jsx("button",{onClick:W,className:"flex items-center justify-center p-1 rounded text-sm font-medium bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors leading-none",title:"Open dev server",children:s.jsx(Yb,{className:"w-3.5 h-3.5"})}):s.jsx("button",{onClick:q,className:"flex items-center justify-center p-1 rounded text-sm font-medium bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors leading-none",title:"Start dev server",children:s.jsx(um,{className:"w-3.5 h-3.5"})}):s.jsx("span",{className:"text-text-muted text-xs",children:"No config"}),s.jsx(qh,{ref:A,trigger:s.jsx(mn,{className:"w-3 h-3"}),children:s.jsx(QA,{workdir:o,compact:!0,onExpand:()=>x(!0),onConfigure:()=>{var ee;(ee=A.current)==null||ee.close(),C(!0)}})})]})]}),g&&s.jsx(Jv,{title:"Dev Server Logs",logs:c,onClose:()=>x(!1)}),w&&s.jsx(KA,{isOpen:!0,onClose:()=>C(!1),workdir:o}),_&&n&&s.jsx(GA,{isOpen:!0,onClose:()=>v(null),entries:K[_]??[],sessionId:n.id,metadataKey:_,title:Ml(_)}),k&&s.jsx(sL,{isOpen:!0,onClose:()=>E(!1),projectId:n.projectId,sessionId:n.id,currentWorkspace:z,currentBranch:m}),T&&s.jsx(iL,{isOpen:!0,onClose:()=>L(!1),sessionId:n.id}),b&&t&&s.jsx(e_,{isOpen:!0,onClose:()=>S(!1),isRunning:n.isRunning,onApply:()=>{n.isRunning?r(n.id):Ft.send("context.applyDynamic",{sessionId:n.id}),S(!1)}})]})}function Yq(e){return(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="f"&&document.querySelector("[data-global-settings]")===null}function ML(e,t=[]){const n=new Map,r=new Map;for(const h of t)h.type==="message"?n.set(h.message.id,h):h.type==="subagent"&&r.set(h.subAgentId,h);const o=[];let a,d=1,l=null;const c=()=>{if(!l||l.size===0)return;const h=new Map;let m=0;for(const g of e)g.role!=="tool"&&g.contextWindowId===a&&(g.subAgentId&&!h.has(g.subAgentId)&&h.set(g.subAgentId,m),m++);const f=[...l.entries()].sort((g,x)=>(h.get(g[0])??0)-(h.get(x[0])??0));for(const[g,x]of f){const w=r.get(g);(w==null?void 0:w.type)==="subagent"&&w.messages.length===x.messages.length&&w.messages.every((b,S)=>b===x.messages[S])?o.push(w):o.push({type:"subagent",subAgentId:g,subAgentType:x.subAgentType,messages:x.messages})}l=null};for(let h=0;h<e.length;h++){const m=e[h];if(m.role!=="tool")if(m.contextWindowId&&a&&m.contextWindowId!==a&&(c(),d++,o.push({type:"context-divider",windowSequence:d})),a=m.contextWindowId,m.subAgentId&&m.subAgentType){l||(l=new Map);let f=l.get(m.subAgentId);f||(f={subAgentType:m.subAgentType,messages:[]},l.set(m.subAgentId,f)),f.messages.push(m)}else{c();const f=n.get(m.id);(f==null?void 0:f.type)==="message"&&f.message===m?o.push(f):o.push({type:"message",message:m})}}return c(),o}const Xq=10,Qq=150;function Jq(e){const t=[];if(e.recentUserPrompts)for(const n of e.recentUserPrompts)t.push({id:n.id,content:n.content,timestamp:n.timestamp,sessionId:e.id,sessionName:e.title||e.id});return t}function Zq(e){return[...e].sort((r,o)=>new Date(o.timestamp).getTime()-new Date(r.timestamp).getTime()).slice(0,Xq).reverse().map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,formattedTimestamp:xU(r.timestamp),trimmedContent:Of(r.content,Qq),sessionId:r.sessionId,sessionName:r.sessionName}))}function eK(e,t,n){const r=[],o=e.filter(a=>a.role==="user"&&!a.isSystemGenerated&&a.messageKind!=="auto-prompt");for(const a of o)r.push({id:a.id,content:a.content,timestamp:a.timestamp,sessionId:n??"",sessionName:"This session"});for(const a of t)n&&a.id===n||r.push(...Jq(a));return Zq(r)}function tK(e,t=[],n=null){const[r,o]=j.useState(0),[a,d]=j.useState(!1),l=j.useMemo(()=>eK(e,t,n),[e,t,n]),c=j.useCallback(()=>{l.length>0&&(o(l.length-1),d(!0))},[l.length]),h=j.useCallback(()=>{d(!1),o(0)},[]),m=j.useCallback(()=>{o(x=>l.length===0?x:x===0?l.length-1:x-1)},[l.length]),f=j.useCallback(()=>{o(x=>l.length===0?x:x===l.length-1?0:x+1)},[l.length]),g=j.useCallback(()=>{if(l.length===0||!a)return null;const x=l[r];return(x==null?void 0:x.content)??null},[l,r,a]);return{history:l,selectedIndex:r,showHistory:a,openHistory:c,closeHistory:h,navigateUp:m,navigateDown:f,selectCurrent:g}}j.memo(function({item:t}){const[n,r]=j.useState(!1);return t.type==="start"?s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-500/10 border border-amber-500/30 rounded text-amber-300 text-sm",children:[s.jsx("span",{className:"animate-pulse",children:"●"}),s.jsx("span",{children:"Delegating image to fallback vision model..."}),t.filename&&s.jsxs("span",{className:"text-amber-400/70",children:["(",t.filename,")"]})]}):s.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-accent-success/10 border border-accent-success/30 rounded",children:[s.jsx("span",{className:"text-accent-success",children:"✓"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-accent-success text-sm",children:"Image description done"}),s.jsx("button",{type:"button",onClick:()=>r(!n),className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:n?"Hide":"Show"})]}),n&&t.description&&s.jsx("div",{className:"mt-2 text-xs prose prose-invert prose-sm max-w-none",children:s.jsx(Jn,{content:t.description})})]})]})});function IL({criteriaSidebarOpen:e,criteriaSidebarOverlay:t,onCriteriaSidebarToggle:n,rawMessages:r,hiddenCount:o,sessionId:a}={}){const d=e??!0,[l,c]=j.useState(""),[h,m]=j.useState([]),[f,g]=j.useState(!1),[x,w]=j.useState(null),[C,b]=j.useState(!1),[S,_]=j.useState(!1),[v,k]=j.useState(!1),[E,T]=j.useState(!1),[L,A]=j.useState(null),M=j.useRef(null),I=ed(M),U=Re(ce=>{var Oe;return ce.focusedSessionId??((Oe=ce.currentSession)==null?void 0:Oe.id)??null}),P=a??U,z=a!=null,K=!z||U===a,H=Vt(z?a:null,ce=>ce.session??null,ce=>ce.currentSession,null),F=Vt(z?a:null,ce=>ce.messages,ce=>ce.messages,[]),Q=Vt(z?a:null,ce=>ce.hiddenCount??0,ce=>ce.hiddenCount,0),Z=Re(ce=>ce.sessions),V=om(z?a:null),B=Re(ce=>ce.stopGeneration),D=r??F,{maxVisibleItems:O}=Ks(),{agents:$}=Ii(H==null?void 0:H.workdir),J=$.filter(ce=>!ce.subagent),{history:X,selectedIndex:Y,showHistory:q,openHistory:W,closeHistory:ee,navigateUp:ie,navigateDown:re,selectCurrent:se}=tK(D,Z,H==null?void 0:H.id);j.useEffect(()=>{if(!K)return;const ce=Oe=>{A(Oe.detail.stats)};return window.addEventListener("open-turn-stats",ce),()=>window.removeEventListener("open-turn-stats",ce)},[K]);const de=H==null?void 0:H.workdir;j.useEffect(()=>{Pt.getState().setWorkdir(de),de&&Pt.getState().fetchWorkflows()},[de]),j.useEffect(()=>{Pt.getState().fetchWorkflows()},[]),j.useEffect(()=>{if(!K)return;const ce=Oe=>{Yq(Oe)&&(Oe.preventDefault(),T(!0))};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[K]);const Se=j.useRef([]),{displayItems:Me,hiddenCount:ye}=j.useMemo(()=>{const ce=ML(D,Se.current);return Se.current=ce,O>0&&ce.length>O?{displayItems:ce.slice(-O),hiddenCount:ce.length-O}:{displayItems:ce,hiddenCount:0}},[D,O]),ue=o??Q??ye,{isAutoScrollActive:Ie,setAutoScroll:We,handleScrollbarGesture:Qe}=Zu(M,H,I),{sendMessage:ve,launchWorkflow:oe}=AL(We,P),ae=TL(P);j.useEffect(()=>{const ce=()=>We(!0);return window.addEventListener(Vf,ce),()=>window.removeEventListener(Vf,ce)},[We]);const[we,$e]=j.useState(null),[fe,Ae]=j.useState(null),Xe=j.useCallback((ce,Oe,Ve,De="auto")=>{const st=ka(Pt.getState()),rt=If(st,ce,De);((rt==null?void 0:rt.parameters)??[]).filter(kt=>kt.position!==void 0||kt.required).length>0?$e({id:ce,name:(rt==null?void 0:rt.name)??ce,subGroup:Oe,scope:De}):oe(void 0,void 0,ce,Oe,Ve,De)},[oe]),tt=j.useCallback((ce,Oe,Ve,De)=>{Xe(ce,Oe,Ve,De)},[Xe]),pe=j.useCallback(ce=>{We(!1);const Oe=document.querySelector(`[data-item-index="${ce}"]`);Oe&&(Oe.hasAttribute("data-placeholder")?(window.dispatchEvent(new CustomEvent(vb,{detail:{index:ce}})),requestAnimationFrame(()=>requestAnimationFrame(()=>{var Ve;(Ve=document.querySelector(`[data-item-index="${ce}"]`))==null||Ve.scrollIntoView({behavior:"smooth",block:"center"})}))):Oe.scrollIntoView({behavior:"smooth",block:"center"}))},[We]);j.useEffect(()=>{if(!K)return;const ce=Oe=>{const Ve=v||C||S||E||L;Oe.key==="Escape"&&V&&!Ve&&P&&B(P),Oe.key==="ScrollLock"&&We(!Ie)};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[K,V,B,Ie,v,C,S,E,L]);const Ge=zu();Au(K?Ge.quickAction:null,()=>{k(!0)}),Au(K?Ge.criteriaSidebar:null,()=>{n==null||n()}),eM(K?Ge.agentSwitching:[],K?J:[],ce=>{P&&ae(ce)});const Je=(ce,Oe)=>{Xe(ce,void 0,void 0,Oe),Ze()},ot=(ce,Oe,Ve)=>{Xe(ce,Oe,void 0,Ve),Ze()},Ze=()=>{c(""),m([]),H!=null&&H.id&&localStorage.removeItem(`openfox:draft:${H.id}`)},at=j.useCallback(async(ce,Oe,Ve,De)=>{const st=kL(ce);if(st.length>0)Ae({prompt:ce,paramKeys:st,agentMode:Oe,textareaContent:Ve,attachments:De});else{Oe&&P&&(H==null?void 0:H.mode)!==Oe&&await Re.getState().switchMode(P,Oe);const rt=Ve&&Ve.trim()?`${Ve.trim()}
|
|
307
307
|
|
|
308
308
|
${ce}`:ce;ve(rt,De!=null&&De.length?De:void 0,{messageKind:"command",isSystemGenerated:!0}),Ze()}},[ve,Ze,H]);return s.jsxs(SV,{value:P,children:[s.jsxs(_W,{criteriaSidebarOpen:d,criteriaSidebarOverlay:t,onCriteriaSidebarToggle:n,messages:D,sessionId:P,children:[s.jsx(Kq,{visible:!d}),s.jsx(SW,{}),L&&s.jsx(wW,{stats:L,onClose:()=>A(null)}),s.jsx(WG,{}),s.jsx(UG,{displayItems:Me,scrollContainerRef:M,highlightedMessageId:null,onLaunchWorkflow:tt,onScrollToTop:()=>We(!1),hiddenCount:ue,onScrollbarGesture:Qe,emptyState:D.length===0&&(H!=null&&H.projectId)?s.jsx(Gq,{projectId:H.projectId,sessionId:H.id}):void 0}),s.jsx(Vq,{input:l,setInput:c,attachments:h,setAttachments:m,dragOver:f,setDragOver:g,errorMessage:x,setErrorMessage:w,scrollToBottom:()=>{var ce,Oe;return(Oe=I())==null?void 0:Oe.scrollTo({top:((ce=I())==null?void 0:ce.scrollHeight)??0,behavior:"smooth"})},sessionId:P,showHistory:q,history:X,selectedIndex:Y,openHistory:W,closeHistory:ee,navigateUp:ie,navigateDown:re,selectCurrent:se,isAutoScrollActive:Ie,setAutoScroll:We,onOpenMessageSearch:()=>T(!0),onOpenCommandsModal:()=>b(!0),onOpenWorkflowsModal:()=>_(!0),onSelectWorkflow:Je,onSelectWorkflowWithSubGroup:ot,onSendCommand:at,clearInput:Ze}),s.jsx(bL,{isOpen:C,onClose:()=>b(!1),projectDir:H==null?void 0:H.workdir}),s.jsx(SL,{isOpen:S,onClose:()=>_(!1),projectDir:H==null?void 0:H.workdir}),s.jsx(iq,{isOpen:v,onClose:()=>k(!1),onSearchMessages:()=>T(!0),isAutoScrollActive:Ie,onToggleAutoScroll:We,textareaContent:l,onCloseComplete:Ol,onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(ce,Oe)=>{const Ve=await ln.getState().fetchCommand(ce,H==null?void 0:H.workdir);Ve&&at(Ve.prompt,Ve.metadata.agentMode,Oe)},onSelectWorkflow:(ce,Oe)=>{Xe(ce,void 0,void 0,Oe),Ze()}}),we&&s.jsx(Mj,{workflowName:we.name,parameters:(()=>{var Oe;const ce=ka(Pt.getState());return((Oe=If(ce,we.id,we.scope))==null?void 0:Oe.parameters)??[]})(),onConfirm:ce=>{oe(void 0,void 0,we.id,we.subGroup,ce,we.scope),$e(null)},onCancel:()=>$e(null)}),fe&&s.jsx(Mj,{workflowName:"Command",confirmLabel:"Launch command",parameters:fe.paramKeys.map((ce,Oe)=>({id:ce,label:ce,position:Oe})),onConfirm:ce=>{let Oe=fe.prompt;for(const[yt,kt]of Object.entries(ce))Oe=Oe.replaceAll(`{{${yt}}}`,kt);const{agentMode:Ve,textareaContent:De,attachments:st}=fe;Ve&&P&&(H==null?void 0:H.mode)!==Ve&&Re.getState().switchMode(P,Ve);const rt=De&&De.trim()?`${De.trim()}
|