openfox 2.0.96 → 2.0.97

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.
@@ -315,7 +315,7 @@ WARNING: This link could potentially be dangerous`)){const S=window.open();if(S)
315
315
  `,children:n?"Reconnecting...":"Reconnect"})]})}const Yt=In((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchCommands:async()=>{await Tk("/api/commands",e,!0)},fetchCommand:async n=>{try{const r=await ve(`/api/commands/${n}`);return r.ok?await r.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const r=await ve(`/api/commands/defaults/${n}`);return r.ok?await r.json():null}catch{return null}},createCommand:async(n,r)=>{const a=await mi("POST","/api/commands",{...n,destination:r});return a.success&&await t().fetchCommands(),a},updateCommand:async(n,r)=>{const a=await mi("PUT",`/api/commands/${n}`,r);return a.success&&await t().fetchCommands(),a},deleteCommand:async n=>{try{const r=await ve(`/api/commands/${n}`,{method:"DELETE"}),a=await r.json();return r.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async(n,r)=>Ed(`/api/commands/${n}/duplicate`,()=>t().fetchCommands(),r)}));function D$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function R$({onClick:e}){return i.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:i.jsx(lg,{})})}function xj({isOpen:e,onClose:t,initialEditId:n}){const r=Yt(je=>je.defaults),a=Yt(je=>je.userItems),l=Yt(je=>je.projectItems),u=Yt(je=>je.loading),c=Yt(je=>je.fetchCommands),d=Yt(je=>je.fetchCommand),h=Yt(je=>je.fetchDefaultContent),p=Yt(je=>je.createCommand),m=Yt(je=>je.updateCommand),x=Yt(je=>je.deleteCommand),[y,w]=E.useState(null),[C,_]=E.useState(null),{view:S,editingId:v,formError:b,saving:j,formData:N,setView:T,setEditingId:D,setFormError:L,setFormData:O,setSaving:M}=F1(),{requestDelete:G,clearConfirm:U,isConfirming:R}=Jl(),H=E.useRef(!1),W=xt(je=>je.defaults),V=xt(je=>je.userItems),Z=xt(je=>je.fetchAgents),$=[...W,...V].filter(je=>!je.subagent),I=E.useRef(c),B=E.useRef(Z),q=E.useRef(d),z=E.useRef(h),ne=E.useRef(n),re=E.useRef(T),Q=E.useRef(D),K=E.useRef(L),P=E.useRef(U);E.useEffect(()=>{I.current=c,B.current=Z,q.current=d,z.current=h,ne.current=n,re.current=T,Q.current=D,K.current=L,P.current=U}),E.useEffect(()=>{if(e)if(I.current(),B.current(),H.current||(P.current(),H.current=!0),ne.current){const je=r.some(Me=>Me.id===ne.current);re.current("edit"),Q.current(ne.current),K.current(""),je?z.current(ne.current).then(Me=>{Me&&O({name:Me.metadata.name+" (copy)",id:`${ne.current}-copy-${Date.now()}`,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!0,destination:"user"})}):q.current(ne.current).then(Me=>{Me&&O({name:Me.metadata.name,id:Me.metadata.id,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else re.current("list"),Q.current(null);else H.current=!1},[e]);const J=async je=>{w(je);const Me=await h(je);_((Me==null?void 0:Me.prompt)??null)},ie=async je=>{if(r.some(lt=>lt.id===je)){const lt=await h(je);lt&&(D(null),O({name:`${lt.metadata.name} (copy)`,id:`${je}-copy-${Date.now()}`,prompt:lt.prompt,agentMode:lt.metadata.agentMode??"",isDefault:!0,destination:"user"}),L(""),T("edit"))}else{const lt=await d(je);lt&&(D(null),O({name:`${lt.metadata.name} (copy)`,id:`${je}-copy-${Date.now()}`,prompt:lt.prompt,agentMode:lt.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))}},he=()=>{O({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),D(null),T("edit")},ce=async je=>{const Me=await d(je);Me&&(D(je),O({name:Me.metadata.name,id:Me.metadata.id,prompt:Me.prompt,agentMode:Me.metadata.agentMode??"",isDefault:!1,destination:"user"}),L(""),T("edit"))},De=async je=>{await x(je),U()},Re=async()=>{const je=v??N.id;if(!je||!N.name||!N.prompt){L("Name and message are required.");return}M(!0),L("");const Me={metadata:{id:je,name:N.name,...N.agentMode?{agentMode:N.agentMode}:{}},prompt:N.prompt},lt=v?await m(v,Me):await p(Me,N.destination);if(M(!1),!lt.success){L(lt.error??"Failed to save command.");return}n?t():T("list")},ze=()=>{n?t():(T("list"),w(null),_(null))},Fe=je=>{O(Me=>({...Me,name:je})),(!v||N.isDefault)&&O(Me=>({...Me,id:D$(je)}))},Ee=()=>{w(null),_(null),T("list")},st=()=>{y&&(w(null),T("edit"),D(y),h(y).then(je=>{je&&O({name:`${je.metadata.name} (copy)`,id:`${y}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(y){const je=r.find(Me=>Me.id===y);return i.jsx(jt,{isOpen:e,onClose:Ee,title:`Default: ${(je==null?void 0:je.name)??y}`,size:"xl",children:i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[i.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),i.jsx("span",{className:"font-mono",children:y})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),i.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:je==null?void 0:je.name})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),i.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(je==null?void 0:je.agentMode)||"None"})]})]}),i.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),i.jsx("textarea",{value:C??"",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"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[i.jsx(rt,{variant:"secondary",onClick:Ee,children:"Close"}),i.jsx(rt,{variant:"primary",onClick:st,children:"Duplicate & Customize"})]})]})})}if(S==="edit")return i.jsx(jt,{isOpen:e,onClose:ze,title:v?"Edit Command":"New Command",size:"xl",children:i.jsxs("div",{className:"flex flex-col h-full",children:[b&&i.jsx(to,{message:b}),i.jsxs("div",{className:"space-y-3 mb-3",children:[i.jsx(U1,{name:N.name,id:N.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!v&&!N.isDefault,onNameChange:Fe,onIdChange:je=>O(Me=>({...Me,id:je}))}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsxs("select",{value:N.agentMode,onChange:je=>O(Me=>({...Me,agentMode:je.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:[i.jsx("option",{value:"",children:"None (keep current mode)"}),$.map(je=>i.jsx("option",{value:je.id,children:je.name},je.id))]})]}),!v&&i.jsx(Ld,{value:N.destination,onChange:je=>O(Me=>({...Me,destination:je}))})]}),i.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),i.jsx("textarea",{value:N.prompt,onChange:je=>O(Me=>({...Me,prompt:je.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"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[i.jsx(rt,{variant:"secondary",onClick:ze,children:"Cancel"}),i.jsx(rt,{variant:"primary",onClick:Re,disabled:j||!N.name||!N.prompt,children:j?"Saving...":"Save"})]})]})});const ot=je=>je.map(Me=>i.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[i.jsx("div",{className:"min-w-0 flex-1 mr-3",children:i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("span",{className:"text-text-primary text-sm font-medium",children:Me.name})})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(ui,{onClick:()=>ce(Me.id)}),i.jsx(Bl,{onClick:()=>ie(Me.id)}),R(Me.id,"delete")?i.jsx(ed,{onConfirm:()=>De(Me.id),onCancel:U}):i.jsx(td,{onClick:()=>G(Me.id)})]})]},Me.id));return i.jsxs(jt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[i.jsx(H1,{description:"Commands are pre-defined messages you can send with a single click.",onNew:he}),i.jsxs(fg,{loading:u,hasItems:r.length>0||a.length>0||l.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[r.length>0&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),i.jsx("div",{className:"space-y-2",children:r.map(je=>i.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[i.jsx("div",{className:"min-w-0 flex-1 mr-3",children:i.jsx("span",{className:"text-text-primary text-sm font-medium",children:je.name})}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[i.jsx(R$,{onClick:()=>J(je.id)}),i.jsx(Bl,{onClick:()=>ie(je.id)})]})]},je.id))})]}),a.length>0&&i.jsx(z1,{children:ot(a)}),l.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),i.jsx("div",{className:"space-y-2",children:ot(l)})]})]})]})}function O$({title:e,defaultOpen:t=!1,children:n,className:r=""}){return i.jsxs("details",{className:`group ${r}`,open:t,children:[i.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:[i.jsx(hn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),e]}),i.jsx("div",{className:"mt-2 space-y-2",children:n})]})}const $i=150,vs=54,Hu=80,Lr=30,Ga=70,GS=100,zi=50,Uu=50,qS=4,yj={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},bj=[{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)"}],I$=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"},{value:"user",label:"User (pause)"}];function ax(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 M$(e,t,n,r){const a=Uu+zi+$i+GS+$i+zi+Uu,l=a/2,u=Uu+zi+$i/2,c=Uu+zi+$i+GS+$i/2,d=[],h=[],p=new Map,m=e.filter(W=>W.type==="agent"||W.type==="shell"||W.type==="user"),x=e.filter(W=>W.type==="sub_agent"),y=x.length>0,w=y?u:l,C=m.length>0?c:l,_=zi+Lr/2;d.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:_,w:Hu,h:Lr}),p.set("$start",{cx:w,cy:_,w:Hu,h:Lr});const S=W=>{d.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:W,w:Hu,h:Lr}),p.set("$done",{cx:w,cy:W,w:Hu,h:Lr})};if(e.length===0){const W=_+Lr/2+Ga*2+Lr/2;return S(W),{nodes:d,edges:h,width:a,height:W+Lr/2+zi,posMap:p}}const v=_+Lr/2+Ga,b=(W,V)=>{W.forEach((Z,X)=>{const $=v+X*(vs+Ga)+vs/2,{name:I,color:B}=ax(Z,r);d.push({id:Z.id,type:"step",label:I,color:B,cx:V,cy:$,w:$i,h:vs}),p.set(Z.id,{cx:V,cy:$,w:$i,h:vs})})};b(m,w),b(x,C);const j=m.length>0?v+(m.length-1)*(vs+Ga)+vs/2:_,N=y?v+(x.length-1)*(vs+Ga)+vs/2:_,T=Math.max(j,N)+vs/2+Ga+Lr/2;S(T);const D=[];t&&p.has(t)&&D.push({from:"$start",to:t,label:n,edgeKey:"start",direction:"down",backEdgeIndex:0});let L=0;for(const W of e)W.transitions.forEach((V,Z)=>{var z;if(!V.goto||!p.has(V.goto))return;const X=p.get(W.id),$=p.get(V.goto),I=V.when.type==="step_result"?`${V.when.result}`:V.when.type==="metadata_all_match"?`${V.when.key??"?"}=${V.when.value??"?"}`:V.when.type==="metadata_all_in"?`${V.when.key??"?"} in [${((z=V.when.values)==null?void 0:z.join(","))??"?"}]`:yj[V.when.type]??V.when.type,B=W.id===V.goto;let q;B?q="back":$.cy>X.cy+1?q="down":$.cy<X.cy-1?q="back":q="same",D.push({from:W.id,to:V.goto,label:I,edgeKey:`${W.id}:${Z}`,direction:q,backEdgeIndex:q==="back"?L++:0})});const O=new Map,M=new Map,G=new Map,U=new Map;for(const W of D)W.direction==="down"&&(O.set(W.from,(O.get(W.from)??0)+1),M.set(W.to,(M.get(W.to)??0)+1));const R=new Map,H=new Map;for(const W of D){if(W.direction!=="same")continue;const V=[W.from,W.to].sort().join("|");R.set(V,(R.get(V)??0)+1)}for(const W of D){if(W.direction==="back"||W.direction==="same"){let q=0;if(W.direction==="same"){const z=[W.from,W.to].sort().join("|");q=H.get(z)??0,H.set(z,q+1)}h.push({...W,fromPort:0,toPort:0,sameEdgeIndex:q});continue}const V=O.get(W.from)??1,Z=M.get(W.to)??1,X=G.get(W.from)??0,$=U.get(W.to)??0;G.set(W.from,X+1),U.set(W.to,$+1);const I=V===1?0:-.6+1.2*X/(V-1),B=Z===1?0:-.6+1.2*$/(Z-1);h.push({...W,fromPort:I,toPort:B,sameEdgeIndex:0})}return{nodes:d,edges:h,width:a,height:T+Lr/2+zi,posMap:p}}function P$({steps:e,entryStep:t,selectedNodeId:n,selectedEdgeKey:r,startConditionLabel:a,agentTypes:l,isReadOnly:u,onSelectNode:c,onSelectEdge:d,onRemoveStep:h,onCreateTransition:p,onReconnectTo:m,onReconnectFrom:x,onDeleteTransition:y}){const w=E.useRef(null),C=E.useRef(!1),[_,S]=E.useState(null),[v,b]=E.useState(null),[j,N]=E.useState(null),{nodes:T,edges:D,width:L,height:O,posMap:M}=E.useMemo(()=>M$(e,t,a,l),[e,t,a,l]),G=E.useCallback(re=>{var ie;const Q=w.current;if(!Q)return{x:0,y:0};const K=Q.createSVGPoint();K.x=re.clientX,K.y=re.clientY;const P=(ie=Q.getScreenCTM())==null?void 0:ie.inverse();if(!P)return{x:0,y:0};const J=K.matrixTransform(P);return{x:J.x,y:J.y}},[]),U=E.useCallback(re=>!re||!v||re==="$start"?!1:v.type==="reconnect-from"?re!=="$done":!0,[v]),R=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=G(re);b({type:"new",fromNodeId:Q,mouseX:K.x,mouseY:K.y})},[G,u]),H=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=G(re);b({type:"reconnect-to",fromNodeId:Q.from,edgeKey:Q.edgeKey,mouseX:K.x,mouseY:K.y})},[G,u]),W=E.useCallback((re,Q)=>{if(u)return;re.stopPropagation(),re.preventDefault();const K=G(re);b({type:"reconnect-from",fromNodeId:Q.from,fixedTargetId:Q.to,edgeKey:Q.edgeKey,mouseX:K.x,mouseY:K.y})},[G,u]),V=E.useCallback(re=>{if(!v)return;const Q=G(re);b(K=>K?{...K,mouseX:Q.x,mouseY:Q.y}:null)},[v,G]),Z=E.useCallback(()=>{v&&(C.current=!0,j&&U(j)&&(v.type==="new"?p(v.fromNodeId,j):v.type==="reconnect-to"?m(v.edgeKey,j):v.type==="reconnect-from"&&x(v.edgeKey,j)),b(null),N(null))},[v,j,U,p,m,x]),X=E.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);E.useEffect(()=>{if(u)return;const re=Q=>{Q.target instanceof HTMLInputElement||Q.target instanceof HTMLTextAreaElement||Q.target instanceof HTMLSelectElement||(Q.key==="Delete"||Q.key==="Backspace")&&r&&r!=="start"&&(Q.preventDefault(),y(r),d(null))};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[u,r,y,d]);const $=re=>{const Q=M.get(re.from),K=M.get(re.to);if(!Q||!K)return null;let P,J,ie,he="middle",ce,De;if(re.direction==="down"){const Re=Q.cx+re.fromPort*(Q.w/2-10),ze=Q.cy+Q.h/2,Fe=K.cx+re.toPort*(K.w/2-10),Ee=K.cy-K.h/2,st=Ee-ze,ot=Fe-Re;P=`M ${Re} ${ze} C ${Re} ${ze+st*.4}, ${Fe-ot*.2} ${Ee-st*.1}, ${Fe} ${Ee}`,J=Re+(Fe-Re)*.5,ie=ze+st*.6,ce={x:Re,y:ze},De={x:Fe,y:Ee}}else if(re.direction==="back"){const Re=re.from===re.to,ze=Q.cx>=L/2,Fe=re.backEdgeIndex*16,Ee=ze?L-20-Fe:20+Fe;if(Re){const st=Q.cx>=L/2,ot=30+re.backEdgeIndex*14,je=Q.cy-Q.h/2,Me=st?Q.cx+Q.w/2:Q.cx-Q.w/2,lt=st?Me+ot:Me-ot,we=Q.cx+(st?Q.w/4:-Q.w/4),Ie=je-20-re.backEdgeIndex*10;P=`M ${Me} ${Q.cy} C ${lt} ${Q.cy}, ${lt} ${Ie}, ${we} ${je}`,J=lt+10,ie=Ie+4,he="middle",ce={x:Me,y:Q.cy},De={x:we,y:je}}else{const st=ze?Q.cx+Q.w/2:Q.cx-Q.w/2,ot=K.cx+(ze?K.w/4:-K.w/4),je=Math.min(Q.cy,K.cy)-K.h/2-18-re.backEdgeIndex*14;P=`M ${st} ${Q.cy} L ${Ee} ${Q.cy} L ${Ee} ${je} L ${ot} ${je} L ${ot} ${K.cy-K.h/2}`,J=Ee,ie=(Q.cy+je)/2,he=ze?"start":"end",ce={x:st,y:Q.cy},De={x:ot,y:K.cy-K.h/2}}}else{const Re=K.cx>Q.cx,ze=re.sameEdgeIndex===0?-12:12,Fe=Re?Q.cx+Q.w/2:Q.cx-Q.w/2,Ee=Re?K.cx-K.w/2:K.cx+K.w/2,st=Q.cy+ze,ot=K.cy+ze,je=(Fe+Ee)/2;P=`M ${Fe} ${st} C ${je} ${st}, ${je} ${ot}, ${Ee} ${ot}`,J=je,ie=(st+ot)/2-6,ce={x:Fe,y:st},De={x:Ee,y:ot}}return{path:P,labelX:J,labelY:ie,labelAnchor:he,fromPt:ce,toPt:De}},I=(re,Q)=>{const K=$(re);if(!K)return null;const{path:P,labelX:J,labelY:ie,labelAnchor:he}=K,ce=r===re.edgeKey,De=re.label&&re.label!=="otherwise";return i.jsxs("g",{children:[i.jsx("path",{d:P,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Re=>{Re.stopPropagation(),u||d(ce?null:re.edgeKey)}}),i.jsx("path",{d:P,fill:"none",stroke:ce?"#58a6ff":"#484f58",strokeWidth:ce?2.2:1.2,markerEnd:ce?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),De&&i.jsx("text",{x:J+(he==="start"?5:he==="end"?-5:0),y:ie+3,textAnchor:he,className:"text-[8px]",fill:ce?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:re.label})]},Q)},B=()=>{if(!r||v)return null;const re=D.find(ie=>ie.edgeKey===r);if(!re)return null;const Q=$(re);if(!Q)return null;const{fromPt:K,toPt:P}=Q,J=6;return i.jsxs(i.Fragment,{children:[re.edgeKey!=="start"&&i.jsx("circle",{cx:K.x,cy:K.y,r:J,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>W(ie,re)}),i.jsx("circle",{cx:P.x,cy:P.y,r:J,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:ie=>H(ie,re)})]})},q=()=>{if(!v)return null;let re,Q,K,P;if(v.type==="reconnect-from"){const he=M.get(v.fixedTargetId);if(!he)return null;re=v.mouseX,Q=v.mouseY,K=he.cx,P=he.cy-he.h/2}else{const he=M.get(v.fromNodeId);if(!he)return null;re=he.cx,Q=he.cy+he.h/2,K=v.mouseX,P=v.mouseY}const J=P-Q,ie=Math.abs(J)>10?`M ${re} ${Q} C ${re} ${Q+J*.4}, ${K} ${P-J*.4}, ${K} ${P}`:`M ${re} ${Q} L ${K} ${P}`;return i.jsx("path",{d:ie,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},z=re=>{const Q=re.cy+re.h/2,K=(v==null?void 0:v.fromNodeId)===re.id;return i.jsx("circle",{cx:re.cx,cy:Q,r:qS,fill:K?"#58a6ff":"#1c2128",stroke:K?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5,className:"cursor-crosshair",onMouseDown:P=>R(P,re.id)})},ne=re=>{const Q=re.cy-re.h/2,K=v&&j===re.id&&U(re.id);return i.jsx("circle",{cx:re.cx,cy:Q,r:qS,fill:K?"#3fb950":"#1c2128",stroke:K?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:K?1:.5})};return i.jsxs("svg",{ref:w,viewBox:`0 0 ${L} ${O}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:V,onMouseUp:Z,onClick:X,children:[i.jsxs("defs",{children:[i.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:i.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),i.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:i.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),D.map((re,Q)=>I(re,Q)),T.map(re=>{const Q=n===re.id,K=re.cx-re.w/2,P=re.cy-re.h/2,J=_===re.id,ie=v&&j===re.id&&U(re.id);if(re.type==="terminal"){const ce=re.id==="$start",De=ce?"#58a6ff":"#3fb950",Re=ce,ze=!ce;return i.jsxs("g",{onClick:Fe=>{Fe.stopPropagation(),ce&&!u&&d("start")},className:ce&&!u?"cursor-pointer":void 0,children:[ie&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:re.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ce&&r==="start"&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:re.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:P,width:re.w,height:re.h,rx:re.h/2,fill:De,fillOpacity:.08,stroke:De,strokeOpacity:.4,strokeWidth:1.5}),i.jsx("text",{x:re.cx,y:re.cy+4,textAnchor:"middle",fill:De,className:"text-[10px] font-medium",pointerEvents:"none",children:re.label}),Re&&z(re),ze&&ne(re)]},re.id)}const he=re.color??"#6b7280";return i.jsxs("g",{onClick:ce=>{ce.stopPropagation(),u||c(Q?null:re.id)},onMouseEnter:()=>S(re.id),onMouseLeave:()=>S(null),className:u?void 0:"cursor-pointer",children:[ie&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),Q&&i.jsx("rect",{x:K-3,y:P-3,width:re.w+6,height:re.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),i.jsx("rect",{x:K,y:P,width:re.w,height:re.h,rx:10,fill:he,fillOpacity:.08,stroke:he,strokeOpacity:.6,strokeWidth:Q?2:1.5}),i.jsx("text",{x:re.cx,y:re.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:re.label}),!u&&z(re),!u&&ne(re),J&&!v&&!u&&i.jsxs("g",{onClick:ce=>{ce.stopPropagation(),h(re.id)},className:"cursor-pointer",children:[i.jsx("circle",{cx:K+re.w-2,cy:P+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),i.jsx("line",{x1:K+re.w-5,y1:P-1,x2:K+re.w+1,y2:P+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),i.jsx("line",{x1:K+re.w+1,y1:P-1,x2:K+re.w-5,y2:P+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},re.id)}),v&&T.map(re=>U(re.id)?i.jsx("rect",{x:re.cx-re.w/2-8,y:re.cy-re.h/2-8,width:re.w+16,height:re.h+16,fill:"transparent",rx:12,onMouseEnter:()=>N(re.id),onMouseLeave:()=>N(null),onMouseUp:Q=>{Q.stopPropagation(),Z()}},`drop-${re.id}`):null),q(),B()]})}const Fu="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",Cl="block text-[11px] text-text-secondary mb-0.5";function B$({formName:e,formId:t,formDescription:n,formMaxIterations:r,formColor:a,isReadOnly:l,onNameChange:u,onDescriptionChange:c,onMaxIterationsChange:d,onColorChange:h}){return i.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[i.jsxs("div",{className:"min-w-[140px]",children:[i.jsx("label",{className:Cl,children:"Name"}),i.jsx("input",{value:e,onChange:p=>u(p.target.value),placeholder:"Workflow name",className:`${Fu} ${l?"opacity-50":""}`,readOnly:l})]}),i.jsxs("div",{className:"min-w-[100px]",children:[i.jsx("label",{className:Cl,children:"ID"}),i.jsx("input",{value:t,readOnly:!0,className:`${Fu} font-mono opacity-50`})]}),i.jsxs("div",{className:"flex-1 min-w-[140px]",children:[i.jsx("label",{className:Cl,children:"Description"}),i.jsx("input",{value:n,onChange:p=>!l&&c(p.target.value),readOnly:l,placeholder:"What does this workflow do?",className:`${Fu} ${l?"opacity-50":""}`})]}),i.jsxs("div",{className:"w-20",children:[i.jsx("label",{className:Cl,children:"Max Iter."}),i.jsx("input",{type:"number",value:r,onChange:p=>!l&&d(Number(p.target.value)),readOnly:l,className:`${Fu} font-mono ${l?"opacity-50":""}`})]}),i.jsxs("div",{children:[i.jsx("label",{className:Cl,children:"Color"}),i.jsx("input",{type:"color",value:a,onChange:p=>!l&&h(p.target.value),disabled:l,className:`w-8 h-8 rounded border border-border bg-transparent ${l?"opacity-50":"cursor-pointer"}`})]})]})}function $$({name:e,id:t,color:n,description:r,isBuiltIn:a,actions:l}){return i.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:n}}),i.jsx("span",{className:"text-text-primary text-sm font-medium",children:e}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:t}),a&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),r&&i.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:r})]}),i.jsx("div",{className:"flex items-center gap-1 flex-shrink-0 ml-3",children:l})]})}function fp({title:e,items:t,renderActions:n}){return t.length===0?null:i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsx("div",{className:"space-y-2",children:t.map(r=>i.jsx($$,{name:r.name,id:r.id,color:r.color??"#3b82f6",description:r.description,actions:n(r)},r.id))})]})}const qa="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",mp="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",_s="block text-[11px] text-text-secondary mb-0.5";function pp({variables:e,onInsert:t}){return e.length===0?null:i.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(n=>i.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 z$({step:e,isEntry:t,agentTypes:n,transitionCount:r,templateVariables:a,onUpdate:l,onRemove:u,onSetEntry:c}){const{color:d,name:h}=ax(e,n);return i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:d+"20",color:d},children:h}),t&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[!t&&i.jsx("button",{onClick:c,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),i.jsx("button",{onClick:u,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Type"}),i.jsx("select",{value:e.type,onChange:p=>{const m=p.target.value,x=m==="sub_agent"?"verification":"build";if(m==="agent"){const y=n.find(w=>!w.subagent);l({...e,type:m,phase:x,agentId:(y==null?void 0:y.id)??"builder",name:(y==null?void 0:y.name)??"Agent"})}else if(m==="sub_agent"){const y=n.find(w=>w.subagent);l({...e,type:m,phase:x,subAgentType:(y==null?void 0:y.id)??"",name:(y==null?void 0:y.name)??"Sub-Agent"})}else l(m==="user"?{...e,type:m,phase:x,name:"User"}:{...e,type:m,phase:x,name:"Shell"})},className:mp,children:I$.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))})]}),e.type==="agent"&&i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Agent Type"}),i.jsx("select",{value:e.agentId??"builder",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,agentId:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:mp,children:n.filter(p=>!p.subagent).map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))})]}),e.type==="sub_agent"&&i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Sub-Agent Type"}),i.jsxs("select",{value:e.subAgentType??"",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,subAgentType:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:mp,children:[i.jsx("option",{value:"",children:"— select —"}),n.filter(p=>p.subagent).map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Prompt"}),i.jsx("textarea",{value:e.prompt??"",onChange:p=>l({...e,prompt:p.target.value||void 0}),rows:6,className:`${qa} resize-y text-xs`,placeholder:"Injected on first entry..."}),i.jsx(pp,{variables:a,onInsert:p=>l({...e,prompt:(e.prompt??"")+`{{${p}}}`})})]}),i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Nudge Prompt"}),i.jsx("textarea",{value:e.nudgePrompt??"",onChange:p=>l({...e,nudgePrompt:p.target.value||void 0}),rows:6,className:`${qa} resize-y text-xs`,placeholder:"Injected on re-entry..."}),i.jsx(pp,{variables:a,onInsert:p=>l({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${p}}}`})})]})]}),e.type==="shell"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Command"}),i.jsx("textarea",{value:e.command??"",onChange:p=>l({...e,command:p.target.value}),rows:3,className:`${qa} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),i.jsx(pp,{variables:a,onInsert:p=>l({...e,command:(e.command??"")+`{{${p}}}`})})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Timeout (ms)"}),i.jsx("input",{type:"number",value:e.timeout??6e4,onChange:p=>l({...e,timeout:Number(p.target.value)}),className:`${qa} font-mono text-xs`})]}),i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Success Codes"}),i.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:p=>l({...e,successExitCodes:p.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${qa} font-mono text-xs`})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:_s,children:"Sub-group"}),i.jsx("input",{value:e.subGroup??"",onChange:p=>l({...e,subGroup:p.target.value||void 0}),placeholder:"e.g. build, verify, review",className:qa})]}),i.jsx("div",{className:"pt-1 border-t border-border/50",children:i.jsxs("p",{className:"text-text-muted text-[10px]",children:[r," outgoing transition",r!==1?"s":""," — drag from the bottom port to connect."]})})]})}const Ka="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",KS="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",Hi="block text-[11px] text-text-secondary mb-0.5";function H$({fromLabel:e,toLabel:t,condition:n,subGroup:r,fromStep:a,agentTypes:l,transitionIndex:u,totalTransitions:c,onUpdateCondition:d,onUpdateSubGroup:h,onDelete:p,onMoveUp:m,onMoveDown:x}){var C;const y=a&&(a.type==="sub_agent"||a.type==="agent")?l.find(_=>_.id===(a.type==="sub_agent"?a.subAgentType:a.agentId)):void 0,w=(y==null?void 0:y.results)&&y.results.length>0;return i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:["#",u+1]}),c>1&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:m,disabled:u===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:i.jsx(hn,{className:"w-3 h-3",rotate:180})}),i.jsx("button",{onClick:x,disabled:u===c-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:i.jsx(hn,{className:"w-3 h-3"})})]})]}),i.jsx("button",{onClick:p,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[i.jsx("span",{className:"font-medium text-text-primary",children:e}),i.jsx(N1,{}),i.jsx("span",{className:"font-medium text-text-primary",children:t})]}),i.jsxs("div",{children:[i.jsx("label",{className:Hi,children:"Condition"}),i.jsx("select",{value:n.type,onChange:_=>{d(_.target.value==="step_result"?{type:"step_result",result:"success"}:{type:_.target.value})},className:KS,children:bj.map(_=>i.jsx("option",{value:_.value,children:_.label},_.value))})]}),n.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Hi,children:"Result"}),w?i.jsx("select",{value:n.result??y.results[0],onChange:_=>{d({type:"step_result",result:_.target.value})},className:KS,children:y.results.map(_=>i.jsx("option",{value:_,children:_},_))}):i.jsx("input",{type:"text",value:n.result??"success",onChange:_=>d({type:"step_result",result:_.target.value}),placeholder:"e.g. success, passed, failed",className:Ka})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Hi,children:"Metadata Key"}),i.jsx("input",{type:"text",value:n.key??"",onChange:_=>d({...n,key:_.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:Ka})]}),i.jsxs("div",{children:[i.jsx("label",{className:Hi,children:"Field"}),i.jsx("input",{type:"text",value:n.field??"",onChange:_=>d({...n,field:_.target.value}),placeholder:"e.g. status",className:Ka})]}),n.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Hi,children:"Value"}),i.jsx("input",{type:"text",value:n.value??"",onChange:_=>d({...n,value:_.target.value}),placeholder:"e.g. passed, resolved",className:Ka})]}):i.jsxs("div",{children:[i.jsx("label",{className:Hi,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((C=n.values)==null?void 0:C.join(", "))??"",onChange:_=>d({...n,values:_.target.value.split(",").map(S=>S.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:Ka})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:Hi,children:"Sub-group"}),i.jsx("input",{type:"text",value:r??"",onChange:_=>h(_.target.value||void 0),placeholder:"e.g. build, verify",className:Ka})]}),i.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function U$(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function F$(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const kl="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",YS="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",Ya="block text-[11px] text-text-secondary mb-0.5",XS=[];function vj({isOpen:e,onClose:t,initialEditId:n}){var As,Ls;const r=vt(Se=>Se.defaults),a=vt(Se=>Se.userItems),l=vt(Se=>Se.projectItems),u=vt(Se=>Se.loading),c=vt(Se=>Se.templateVariables),d=vt(Se=>Se.fetchWorkflows),h=vt(Se=>Se.fetchWorkflow),p=vt(Se=>Se.fetchDefaultContent),m=vt(Se=>Se.fetchTemplateVariables),x=vt(Se=>Se.createWorkflow),y=vt(Se=>Se.updateWorkflow),w=vt(Se=>Se.deleteWorkflow),{requestDelete:C,clearConfirm:_,isConfirming:S}=Jl(),[v,b]=E.useState("list"),[j,N]=E.useState(null),[T,D]=E.useState(!1),[L,O]=E.useState(null),[M,G]=E.useState(null),[U,R]=E.useState(""),[H,W]=E.useState(""),[V,Z]=E.useState(""),[X,$]=E.useState("1.0.0"),[I,B]=E.useState("#3b82f6"),[q,z]=E.useState(""),[ne,re]=E.useState(50),[Q,K]=E.useState(XS),[P,J]=E.useState({type:"always"}),[ie,he]=E.useState([]),[ce,De]=E.useState("user"),[Re,ze]=E.useState(""),[Fe,Ee]=E.useState(!1),st=xt(Se=>Se.defaults),ot=xt(Se=>Se.userItems),je=xt(Se=>Se.projectItems),Me=E.useMemo(()=>[...st,...ot,...je],[st,ot,je]),lt=xt(Se=>Se.fetchAgents),[we]=E.useState(null);E.useEffect(()=>{e&&(d(),m(),lt(),O(null),G(null),n?r.some(Ce=>Ce.id===n)?p(n).then(Ce=>{Ce&&Ie({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):h(n).then(Ce=>{Ce&&Ie(Ce,{editingId:n,isReadOnly:!1})}):(b("list"),N(null),D(!1)))},[e,d,h,p,m,n]);const Ie=(Se,Ce)=>{R(Se.metadata.name),W(Se.metadata.id),Z(Se.metadata.description),$(Se.metadata.version),B(Se.metadata.color??"#3b82f6"),z(Se.entryStep),re(Se.settings.maxIterations),K(Se.steps),J(Se.startCondition??{type:"always"}),he(Se.metadata.parameters??[]),ze(""),(Ce==null?void 0:Ce.editingId)!==void 0&&N(Ce.editingId),(Ce==null?void 0:Ce.isReadOnly)!==void 0&&D(Ce.isReadOnly),(Ce==null?void 0:Ce.selectedNodeKey)!==void 0&&O(null),(Ce==null?void 0:Ce.selectedEdgeKey)!==void 0&&G(null),b("edit")},qe=async Se=>{const Ce=await h(Se);Ce&&Ie(Ce,{editingId:Se,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},te=async()=>{var Qe;const Se=j??H;if(!Se||!U)return ze("Name is required."),!1;if(Q.length===0)return ze("Add at least one step."),!1;const Ce=ie.find(at=>!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(at.id));if(Ce)return ze(`Invalid parameter ID "${Ce.id}". Use letters, digits, and underscores only.`),!1;let Oe=q;if(!Oe||!Q.some(at=>at.id===Oe)){if(Oe=((Qe=Q.find(at=>at.id))==null?void 0:Qe.id)??"",!Oe)return ze("All steps need an ID."),!1;z(Oe)}Ee(!0),ze("");const Ge={metadata:{id:Se,name:U,description:V,version:X||"1.0.0",color:I,...ie.length>0?{parameters:ie}:{}},entryStep:Oe,settings:{maxIterations:ne},steps:Q,startCondition:P},Ve=j?await y(j,Ge):await x(Ge,ce);return Ee(!1),Ve.success?(j||N(Se),!0):(ze(Ve.error??"Failed to save."),!1)},ae=async()=>{await te()},se=async()=>{await te()&&(n?t():b("list"))},me=()=>{n?t():b("list")},Ue=Se=>{R(Se),j||W(U$(Se))},He=async Se=>r.some(Oe=>Oe.id===Se)?await p(Se):await h(Se),Ye=async Se=>{const Ce=await He(Se);Ce&&Ie({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${Se}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},ct=()=>{N(null),R(""),W(""),Z(""),$("1.0.0"),B("#3b82f6"),z(""),re(50),K(structuredClone(XS)),J({type:"always"}),he([]),De("user"),ze(""),O(null),G(null),D(!1),b("edit")},Je=async Se=>{await w(Se),_()},Ze=E.useCallback(Se=>{O(Se),G(null)},[]),tt=E.useCallback(Se=>{G(Se),O(null)},[]),Nt=L!==null?Number(L):-1,dt=Nt>=0?Q[Nt]??null:null,rn=E.useCallback(Se=>{K(Ce=>Ce.map((Oe,Ge)=>Ge===Nt?Se:Oe))},[Nt]),Un=P.type==="step_result"?`${P.result}`:P.type==="metadata_all_match"?`${P.key??"?"}=${P.value??"?"}`:P.type==="metadata_all_in"?`${P.key??"?"} in [${((As=P.values)==null?void 0:As.join(","))??"?"}]`:yj[P.type]??P.type,ye=()=>{const Se=Q.length,Ce=F$(Q),Oe=Me.find(Ge=>!Ge.subagent);K([...Q,{id:Ce,name:(Oe==null?void 0:Oe.name)??"Agent",type:"agent",phase:"build",agentId:(Oe==null?void 0:Oe.id)??"builder",transitions:[]}]),q||z(Ce),Ze(String(Se))},We=E.useCallback((Se,Ce)=>{Se==="$start"?(z(Ce),tt("start")):K(Oe=>{const Ge=Oe.find(Qe=>Qe.id===Se),Ve=Ge?Ge.transitions.length:0;return tt(`${Se}:${Ve}`),Oe.map(Qe=>Qe.id===Se?{...Qe,transitions:[...Qe.transitions,{when:{type:"always"},goto:Ce}]}:Qe)})},[tt]),oe=Se=>{if(Se==="start")return null;const Ce=Se.lastIndexOf(":"),Oe=Se.slice(0,Ce),Ge=parseInt(Se.slice(Ce+1));return{stepId:Oe,transIdx:Ge}},fe=E.useCallback((Se,Ce)=>{const Oe=oe(Se);Oe&&K(Ge=>Ge.map(Ve=>Ve.id===Oe.stepId?{...Ve,transitions:Ve.transitions.map((Qe,at)=>at===Oe.transIdx?Ce(Qe):Qe)}:Ve))},[]),Pe=E.useCallback((Se,Ce)=>{if(Se==="start"){z(Ce);return}fe(Se,Oe=>({...Oe,goto:Ce}))},[fe]),St=E.useCallback((Se,Ce)=>{const Oe=oe(Se);Oe&&(K(Ge=>{const Ve=Ge.find(at=>at.id===Oe.stepId);if(!Ve)return Ge;const Qe=Ve.transitions[Oe.transIdx];return Qe?Ge.map(at=>at.id===Oe.stepId?{...at,transitions:at.transitions.filter((Zt,mn)=>mn!==Oe.transIdx)}:at.id===Ce?{...at,transitions:[...at.transitions,Qe]}:at):Ge}),G(null))},[]),bn=E.useCallback(Se=>{if(Se==="start"){z(""),G(null);return}const Ce=oe(Se);Ce&&(K(Oe=>Oe.map(Ge=>Ge.id===Ce.stepId?{...Ge,transitions:Ge.transitions.filter((Ve,Qe)=>Qe!==Ce.transIdx)}:Ge)),G(null))},[]),fn=E.useCallback((Se,Ce)=>{if(Se==="start"){J(Ce);return}fe(Se,Oe=>({...Oe,when:Ce}))},[fe]),Br=E.useCallback((Se,Ce)=>{Se!=="start"&&fe(Se,Oe=>({...Oe,subGroup:Ce||void 0}))},[fe]),Ts=Se=>ax(Se,Me).name,yi=()=>{if(!M)return null;if(M==="start"){const Zt=Q.find(mn=>mn.id===q);return{type:"start",fromLabel:"Start",toLabel:Zt?Ts(Zt):"(none)",condition:P}}const Se=M.lastIndexOf(":"),Ce=M.slice(0,Se),Oe=parseInt(M.slice(Se+1)),Ge=Q.find(Zt=>Zt.id===Ce);if(!Ge)return null;const Ve=Ge.transitions[Oe];if(!Ve)return null;const Qe=Q.find(Zt=>Zt.id===Ve.goto),at=Ve.goto==="$done"?"Done":Qe?Ts(Qe):Ve.goto;return{type:"step",fromLabel:Ts(Ge),toLabel:at,condition:Ve.when,subGroup:Ve.subGroup}};if(v==="edit"){const Se=yi();return i.jsxs(jt,{isOpen:e,onClose:me,title:T?U:j?"Edit Workflow":"New Workflow",size:"full",children:[Re&&i.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:Re}),i.jsx(B$,{formName:U,formId:H,formDescription:V,formMaxIterations:ne,formColor:I,isReadOnly:T,onNameChange:Ue,onDescriptionChange:Z,onMaxIterationsChange:re,onColorChange:B}),!T&&i.jsx("div",{className:"mb-3 pb-3 border-b border-border",children:i.jsxs(O$,{title:`Parameters (${ie.length})`,children:[ie.map((Ce,Oe)=>i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{value:Ce.id,onChange:Ge=>{const Ve=[...ie];Ve[Oe]={...Ce,id:Ge.target.value},he(Ve)},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"}),i.jsx("input",{value:Ce.label,onChange:Ge=>{const Ve=[...ie];Ve[Oe]={...Ce,label:Ge.target.value},he(Ve)},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"}),i.jsx("input",{value:Ce.description??"",onChange:Ge=>{const Ve=[...ie];Ve[Oe]={...Ce,description:Ge.target.value||void 0},he(Ve)},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"}),i.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-muted whitespace-nowrap",children:[i.jsx("input",{type:"checkbox",checked:Ce.required??!1,onChange:Ge=>{const Ve=[...ie];Ve[Oe]={...Ce,required:Ge.target.checked||void 0},he(Ve)},className:"rounded border-border"}),"Req."]}),i.jsxs("div",{className:"flex gap-0.5",children:[i.jsx("button",{onClick:()=>{Oe!==0&&he(ie.map((Ge,Ve)=>Ve===Oe?{...ie[Oe-1],position:Ve}:Ve===Oe-1?{...ie[Oe],position:Ve}:{...Ge,position:Ve}))},disabled:Oe===0,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move up","aria-label":`Move ${Ce.label||Ce.id} up`,children:"▲"}),i.jsx("button",{onClick:()=>{Oe!==ie.length-1&&he(ie.map((Ge,Ve)=>Ve===Oe?{...ie[Oe+1],position:Ve}:Ve===Oe+1?{...ie[Oe],position:Ve}:{...Ge,position:Ve}))},disabled:Oe===ie.length-1,className:"p-1 text-text-muted hover:text-text-primary disabled:opacity-30 transition-colors",title:"Move down","aria-label":`Move ${Ce.label||Ce.id} down`,children:"▼"})]}),i.jsx("button",{onClick:()=>he(ie.filter((Ge,Ve)=>Ve!==Oe)),className:"p-1 text-text-muted hover:text-accent-error transition-colors",title:"Remove parameter",children:"✕"})]},Ce.id)),i.jsx("button",{onClick:()=>{const Ce=`param_${ie.length+1}`;he([...ie,{id:Ce,label:"",description:"",required:!1}])},className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:"+ Add parameter"})]})}),!j&&!T&&i.jsx(Ld,{value:ce,onChange:De}),i.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[i.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[i.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!T&&i.jsx("button",{onClick:ye,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),i.jsxs("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:[i.jsx(P$,{steps:Q,entryStep:q,selectedNodeId:(dt==null?void 0:dt.id)??null,selectedEdgeKey:M,startConditionLabel:Un,agentTypes:Me,isReadOnly:T,onSelectNode:Ce=>{if(Ce===null){Ze(null);return}const Oe=Q.findIndex(Ge=>Ge.id===Ce);Ze(Oe>=0?String(Oe):null)},onSelectEdge:tt,onRemoveStep:Ce=>{var Ge;const Oe=Q.findIndex(Ve=>Ve.id===Ce);if(K(Ve=>Ve.filter(Qe=>Qe.id!==Ce)),Nt===Oe&&Ze(null),q===Ce){const Ve=Q.filter(Qe=>Qe.id!==Ce);z(((Ge=Ve[0])==null?void 0:Ge.id)??"")}},onCreateTransition:We,onReconnectTo:Pe,onReconnectFrom:St,onDeleteTransition:bn}),Q.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[i.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),i.jsx("button",{onClick:ye,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"})]})]})]}),i.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[i.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:i.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),i.jsx("div",{className:"p-3 overflow-y-auto flex-1 min-h-0",children:T&&(Se||dt)?i.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):Se?Se.type==="start"?i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),q&&i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[i.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),i.jsx(N1,{}),i.jsx("span",{className:"text-text-primary font-medium",children:Se.toLabel})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ya,children:"Activation Condition"}),i.jsx("select",{value:P.type,onChange:Ce=>J(Ce.target.value==="step_result"?{type:"step_result",result:"success"}:Ce.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:Ce.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:Ce.target.value}),className:YS,children:bj.map(Ce=>i.jsx("option",{value:Ce.value,children:Ce.label},Ce.value))})]}),P.type==="step_result"&&i.jsxs("div",{children:[i.jsx("label",{className:Ya,children:"Result"}),q&&(()=>{const Ce=Q.find(Qe=>Qe.id===q),Oe=Ce&&(Ce.type==="sub_agent"||Ce.type==="agent")?Me.find(Qe=>Qe.id===(Ce.type==="sub_agent"?Ce.subAgentType:Ce.agentId)):void 0,Ge=(Oe==null?void 0:Oe.results)&&Oe.results.length>0,Ve=(Oe==null?void 0:Oe.results)??[];return Ge?i.jsx("select",{value:P.result??Ve[0],onChange:Qe=>J({type:"step_result",result:Qe.target.value}),className:YS,children:Ve.map(Qe=>i.jsx("option",{value:Qe,children:Qe},Qe))}):i.jsx("input",{type:"text",value:P.result??"success",onChange:Qe=>J({type:"step_result",result:Qe.target.value}),placeholder:"e.g. success, passed, failed",className:kl})})()]}),(P.type==="metadata_all_match"||P.type==="metadata_all_in")&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:Ya,children:"Metadata Key"}),i.jsx("input",{type:"text",value:P.key??"",onChange:Ce=>J({...P,key:Ce.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:kl})]}),i.jsxs("div",{children:[i.jsx("label",{className:Ya,children:"Field"}),i.jsx("input",{type:"text",value:P.field??"",onChange:Ce=>J({...P,field:Ce.target.value}),placeholder:"e.g. status",className:kl})]}),P.type==="metadata_all_match"?i.jsxs("div",{children:[i.jsx("label",{className:Ya,children:"Value"}),i.jsx("input",{type:"text",value:P.value??"",onChange:Ce=>J({...P,value:Ce.target.value}),placeholder:"e.g. passed, resolved",className:kl})]}):i.jsxs("div",{children:[i.jsx("label",{className:Ya,children:"Values (comma-separated)"}),i.jsx("input",{type:"text",value:((Ls=P.values)==null?void 0:Ls.join(", "))??"",onChange:Ce=>J({...P,values:Ce.target.value.split(",").map(Oe=>Oe.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:kl})]})]}),i.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 Ce=oe(M),Oe=Ce==null?void 0:Ce.stepId,Ge=(Ce==null?void 0:Ce.transIdx)??0,Ve=Oe?Q.find(at=>at.id===Oe):void 0,Qe=(Ve==null?void 0:Ve.transitions.length)??0;return i.jsx(H$,{fromLabel:Se.fromLabel,toLabel:Se.toLabel,condition:Se.condition,subGroup:"subGroup"in Se?Se.subGroup:void 0,fromStep:Se.type==="step"?Q.find(at=>at.id===Se.fromLabel):void 0,agentTypes:Me,transitionIndex:Ge,totalTransitions:Qe,onUpdateCondition:at=>fn(M,at),onUpdateSubGroup:at=>Br(M,at),onDelete:()=>bn(M),onMoveUp:()=>{K(at=>{const Zt=at.find(Zn=>Zn.id===Oe);if(!Zt||Ge===0)return at;const mn=[...Zt.transitions];return[mn[Ge-1],mn[Ge]]=[mn[Ge],mn[Ge-1]],at.map(Zn=>Zn.id===Oe?{...Zn,transitions:mn}:Zn)}),G(`${Oe}:${Ge-1}`)},onMoveDown:()=>{K(at=>{const Zt=at.find(Zn=>Zn.id===Oe);if(!Zt||Ge===Zt.transitions.length-1)return at;const mn=[...Zt.transitions];return[mn[Ge],mn[Ge+1]]=[mn[Ge+1],mn[Ge]],at.map(Zn=>Zn.id===Oe?{...Zn,transitions:mn}:Zn)}),G(`${Oe}:${Ge+1}`)}})})():dt?i.jsx(z$,{step:dt,isEntry:dt.id===q,agentTypes:Me,transitionCount:dt.transitions.length,templateVariables:c,onUpdate:rn,onRemove:()=>{var Ce;if(dt&&(K(Q.filter((Oe,Ge)=>Ge!==Nt)),Ze(null),q===dt.id)){const Oe=Q.filter((Ge,Ve)=>Ve!==Nt);z(((Ce=Oe[0])==null?void 0:Ce.id)??"")}},onSetEntry:()=>z(dt.id)}):i.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",i.jsx("br",{}),"Drag from a port to connect."]})})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border",children:[i.jsx(rt,{variant:"secondary",onClick:me,children:"Close"}),T?i.jsx(rt,{variant:"primary",onClick:()=>{R(U+" (copy)"),W(`${j}-copy-${Date.now()}`),N(null),D(!1)},children:"Duplicate & Customize"}):i.jsxs(i.Fragment,{children:[i.jsx(rt,{variant:"primary",onClick:ae,children:"Save"}),i.jsx(rt,{variant:"primary",onClick:se,children:"Save & Close"})]})]})]})}return i.jsx(jt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:i.jsx($1,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:ct,loading:u,hasItems:r.length>0||a.length>0||l.length>0,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(fp,{title:"Built-in",items:r,renderActions:Se=>i.jsx(i.Fragment,{children:i.jsx(ui,{onClick:()=>Ye(Se.id),children:i.jsx(lg,{})})})}),i.jsx(fp,{title:"Custom",items:a,renderActions:Se=>i.jsxs(i.Fragment,{children:[i.jsx(ui,{onClick:()=>qe(Se.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Bl,{onClick:()=>Ye(Se.id)}),S(Se.id,"delete")?i.jsx(ed,{onConfirm:()=>Je(Se.id),onCancel:_}):i.jsx(td,{onClick:()=>C(Se.id)})]})}),l.length>0&&i.jsx(fp,{title:"Project",items:l,renderActions:Se=>i.jsxs(i.Fragment,{children:[i.jsx(ui,{onClick:()=>qe(Se.id),children:i.jsx("span",{className:"text-[10px]",children:"Edit"})}),i.jsx(Bl,{onClick:()=>Ye(Se.id)}),S(Se.id,"delete")?i.jsx(ed,{onConfirm:()=>Je(Se.id),onCancel:_}):i.jsx(td,{onClick:()=>C(Se.id)})]})})]})})})}function V$(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function W$({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:r,onSelectWorkflow:a,onCloseCompleteAction:l,textareaContent:u,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:h}){const[,p]=Tn(),m=Yt(z=>z.fetchCommands),x=vt(z=>z.fetchWorkflows),y=xt(z=>z.fetchAgents),w=Yt(z=>z.defaults),C=Yt(z=>z.userItems),_=Yt(z=>z.projectItems),S=vt(z=>z.defaults),v=vt(z=>z.userItems),b=vt(z=>z.projectItems),j=xt(z=>z.defaults),N=xt(z=>z.userItems),T=xt(z=>z.projectItems),D=Le(z=>{var ne;return(ne=z.currentSession)==null?void 0:ne.mode}),L=Le(z=>{var ne;return((ne=z.currentSession)==null?void 0:ne.dangerLevel)??"normal"}),O=Le(z=>z.switchMode),M=Le(z=>z.switchDangerLevel),G=Le(z=>{var ne;return(ne=z.currentSession)==null?void 0:ne.projectId}),U=E.useRef(void 0),[R,H]=E.useState(""),[W,V]=E.useState(0),Z=E.useRef(null),X=E.useRef(!1);E.useEffect(()=>{e&&(X.current=!0)},[e]),E.useEffect(()=>{if(e){m(),x(),y(),H(""),V(0);const z=setTimeout(()=>{var ne;return(ne=Z.current)==null?void 0:ne.focus()},50);return()=>clearTimeout(z)}},[e,m,x,y]),E.useEffect(()=>{var z;!e&&X.current&&(n==null||n(),(z=U.current)==null||z.call(U),U.current=void 0)},[e,n]);const I=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const z=G??V$(window.location.pathname);z&&p(`/p/${z}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{U.current=l,t()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{t(),c==null||c()}},{id:"toggle-autoscroll",name:h?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{t(),d==null||d(!h)}},...Kr(Kr(j,N),T).filter(z=>!z.subagent&&z.id!==D).map(z=>({id:z.id,name:z.name,prefix:"Agent > Switch to",action:()=>O(z.id)})),...Kr(Kr(w,C),_).map(z=>({id:z.id,name:z.name,prefix:"Command > Launch",action:()=>r(z.id,u)})),...Kr(Kr(S,v),b).map(z=>({id:z.id,name:z.name,prefix:"Workflow > Run",action:()=>a(z.id)})),...["normal","dangerous"].filter(z=>z!==L).map(z=>({id:z,name:z.charAt(0).toUpperCase()+z.slice(1),prefix:"Mode > Switch to",action:()=>M(z)}))].filter(z=>ci(`${z.prefix} ${z.name}`,R)),B=I.length-1,q=z=>{Hk(z,B,V,()=>{var ne;(ne=I[W])==null||ne.action(),t()},t)};return e?pi.createPortal(i.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),i.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[i.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[i.jsx("input",{ref:Z,type:"text",value:R,onChange:z=>{H(z.target.value),V(0)},onKeyDown:q,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx(hg,{onClick:t,className:"shrink-0","aria-label":"Close"})]}),i.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:I.length===0?i.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:w.length+C.length+S.length+v.length>0?"No matches":"No agents, commands, or workflows yet"}):I.map((z,ne)=>i.jsxs("button",{type:"button",onClick:()=>{z.action(),t()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${ne===W?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:[i.jsxs("span",{className:"text-text-muted font-normal",children:[z.prefix," "]}),i.jsx("span",{children:z.name})]},z.id))})]})]}),document.body):null}const _j="openfox-message-search-filters",G$=[{key:"user",label:"User prompts"},{key:"thinking",label:"Thinking"},{key:"response",label:"Responses"}];function q$(){try{const e=localStorage.getItem(_j);if(e){const t=JSON.parse(e);return new Set(t)}}catch{}return new Set(["user","thinking","response"])}function K$(e){localStorage.setItem(_j,JSON.stringify([...e]))}function Y$(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 X$(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 a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),u=String(t.getDate()).padStart(2,"0"),c=String(t.getHours()).padStart(2,"0"),d=String(t.getMinutes()).padStart(2,"0");return`${a}/${l}/${u} ${c}:${d}`}function Q$(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 J$(e){var t,n;if(e.type==="message"){const r=e.message;if(r.role==="assistant"){const a=(t=r.content)==null?void 0:t.trim();return((n=r.thinkingContent)==null?void 0:n.trim())&&!a?"italic text-text-muted":""}if(r.role==="user")return"font-bold"}return""}function Z$(e){var n,r;if(e.type!=="message")return i.jsx(O_,{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())?i.jsx(_T,{className:"w-3.5 h-3.5"}):i.jsx(O_,{className:"w-3.5 h-3.5"}):i.jsx(vT,{className:"w-3.5 h-3.5"})}function QS(e){var t;if(e.type==="message"){const n=e.message,r=n.content||"",a=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 a?a.slice(0,200):(t=n.thinkingContent)!=null&&t.trim()?n.thinkingContent.slice(0,200):"";const l=a.slice(0,200);return l.length<a.length?`${l}...`:l}return e.type==="subagent"?`Sub-agent: ${e.subAgentType}`:""}function e7({isOpen:e,onClose:t,displayItems:n,onNavigate:r}){const[a,l]=E.useState(""),[u,c]=E.useState(0),[d,h]=E.useState(q$),p=E.useRef(null),m=E.useRef(null),x=E.useRef(null),y=N=>{h(T=>{const D=new Set(T);return D.has(N)?D.delete(N):D.add(N),K$(D),D})},w=E.useMemo(()=>n.filter(N=>{var T,D;return!(N.type==="context-divider"||N.type==="message"&&(N.message.messageKind==="auto-prompt"||N.message.role==="assistant"&&!((T=N.message.content)!=null&&T.trim())&&!((D=N.message.thinkingContent)!=null&&D.trim())))}),[n]),C=E.useMemo(()=>w.filter(N=>{const T=Y$(N);return!(T&&!d.has(T))}),[w,d]),_=E.useMemo(()=>a?w.filter(N=>{const T=QS(N);return ci(T,a)}):C,[C,a]),S=_.length-1;E.useEffect(()=>{if(e){l(""),c(0);const N=setTimeout(()=>{var T;return(T=p.current)==null?void 0:T.focus()},50);return()=>clearTimeout(N)}},[e]),E.useEffect(()=>{e&&m.current&&(m.current.scrollTop=m.current.scrollHeight)},[e]),E.useEffect(()=>{x.current&&x.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[u]);const v=N=>{Hk(N,S,c,()=>{const T=_[u];if(T){const D=n.indexOf(T);D>=0&&r(D),t()}},t)},b=N=>{const T=n.indexOf(N);T>=0&&r(T),t()},j=N=>n.indexOf(N);return e?pi.createPortal(i.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),i.jsxs("div",{className:"relative w-full max-w-lg bg-bg-secondary border border-border rounded shadow-xl",children:[i.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[i.jsx(Qi,{}),i.jsx("input",{ref:p,type:"text",value:a,onChange:N=>{l(N.target.value),c(0)},onKeyDown:v,placeholder:"Search timeline...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),i.jsx("button",{type:"button",onClick:t,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:i.jsx(Es,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"flex gap-1.5 px-4 py-2 border-b border-border",children:G$.map(N=>{const T=d.has(N.key);return i.jsx("button",{type:"button",onClick:()=>y(N.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:N.label},N.key)})}),i.jsx("div",{ref:m,className:"overflow-y-auto max-h-[60vh] p-2",children:_.length===0?i.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:C.length>0?"No matches":"No messages yet"}):_.map((N,T)=>{const D=j(N),L=Z$(N),O=QS(N),M=J$(N),G=Q$(N),U=N.type==="message"&&N.message.role==="user";return i.jsx("button",{ref:T===u?x:null,type:"button",onClick:()=>b(N),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${T===u?"bg-accent-primary/20 text-text-primary":U?"bg-accent-primary/5 text-text-secondary hover:bg-accent-primary/10 hover:text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[i.jsx("span",{className:"flex-shrink-0",children:L}),i.jsx("span",{className:`truncate flex-1 ${M}`,children:O})]}),G&&i.jsx("span",{className:"text-text-muted text-xs shrink-0",children:X$(G)})]})},`${D}-${N.type}`)})})]})]}),document.body):null}function Sj(e){const t=new Set,n=[],r=/\{\{(\w+)\}\}/g;let a;for(;(a=r.exec(e))!==null;){const l=a[1];t.has(l)||(t.add(l),n.push(l))}return n}function t7(e,t,n){const r=e.trim();if(!r.startsWith("/"))return null;const a=r.slice(1).split(/\s+/),l=a[0];if(!l)return null;const u=a.slice(1),c={},d=t.find(h=>h.id===l);return d?(d.parameters&&d.parameters.length>0?[...d.parameters].sort((p,m)=>(p.position??0)-(m.position??0)).forEach((p,m)=>{u[m]!==void 0&&(c[p.id]=u[m])}):u.forEach((h,p)=>{c[String(p)]=h}),{workflowId:l,params:c}):n&&n.find(p=>p.id===l)?(u.forEach((p,m)=>{c[String(m)]=p}),{commandId:l,params:c}):null}function n7({attachment:e,onRemove:t}){const n=mj(e.filename);return i.jsxs("div",{className:"relative inline-flex flex-col items-center p-2 bg-bg-tertiary rounded-lg border border-border",children:[i.jsx(ac,{onClick:()=>t(e.id),className:"absolute -top-2 -right-2",size:"sm",variant:"overlay","aria-label":`Remove ${e.filename}`}),fj(e.mimeType)?i.jsx("img",{src:e.data,alt:e.description||e.filename,className:"w-16 h-16 object-cover rounded-md bg-bg-secondary"}):i.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-md bg-bg-secondary text-xs font-bold text-text-muted",children:n}),i.jsx("div",{className:"mt-1 text-xs text-text-muted text-center max-w-16 truncate",title:e.filename,children:e.filename}),i.jsx("div",{className:"text-[10px] text-text-muted",children:eo(e.size)})]})}function r7({history:e,selectedIndex:t,onSelect:n,onEscape:r,onNavigate:a}){const l=E.useRef(null),u=E.useRef(null);E.useEffect(()=>{u.current&&l.current&&u.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[t]);const c=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(),a("up");break;case"ArrowDown":h.preventDefault(),a("down");break}},d=h=>{n(h)};return i.jsx("div",{ref:l,role:"list",className:"mb-2 p-2 bg-bg-secondary border border-border rounded-lg overflow-y-auto max-h-64",onKeyDown:c,children:e.map((h,p)=>i.jsxs("div",{ref:p===t?u:null,role:"listitem",onClick:()=>d(h.content),className:`
316
316
  p-2 rounded cursor-pointer transition-colors
317
317
  ${p===t?"bg-accent-primary/20 border border-accent-primary":"hover:bg-bg-tertiary"}
318
- `,children:[i.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[h.formattedTimestamp,h.sessionName&&i.jsxs(i.Fragment,{children:[" | ",i.jsx("span",{className:"text-accent-primary font-medium",children:h.sessionName})]})]}),i.jsx("div",{className:"text-sm text-text-primary mt-1",children:h.trimmedContent})]},h.id))})}function s7(){const e=XN(),t=e?"bg-amber-400":"bg-accent-primary";return i.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"flex gap-0.5",children:[i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"0ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"300ms"}})]}),i.jsx("span",{className:"text-text-secondary",children:e?"Running... (abort in progress)":"Running"})]}),!e&&i.jsx("span",{className:"text-text-muted",children:"esc to interrupt"})]})}function i7(){const e=Le(u=>u.activeWorkflowExecution),t=Le(u=>u.exitWorkflow),[n,r]=E.useState(!1);E.useEffect(()=>{r(!1)},[e==null?void 0:e.id]);const a=E.useCallback(()=>{n||(r(!0),t())},[n,t]);if(!e||e.status!=="running"&&e.status!=="waiting")return null;const l=e.workflowColor&&/^#[0-9a-fA-F]{6}$/.test(e.workflowColor)?e.workflowColor:"#3b82f6";return i.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-xs border-b border-border",children:[i.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l}}),i.jsx("span",{className:"font-medium text-text-primary truncate",children:e.workflowName}),e.currentStepName&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("span",{className:"text-text-muted truncate",children:e.currentStepName})]}),i.jsx("div",{className:"ml-auto shrink-0",children:i.jsx("button",{onClick:a,disabled:n,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:n?"Exiting...":"✕ Exit"})})]})}const a7={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function o7(e,t={}){const n={...a7,...t};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=m7(a),u=`data:${e.type};base64,${l}`,c=await wj(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await l7(e,n)}async function l7(e,t){const n=await u7(e),r=await wj(n),{width:a,height:l}=c7(r.width,r.height,t.maxWidth,t.maxHeight),u=d7();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(r,0,0,a,l);let d=t.quality,h="";for(let m=0;m<10&&(h=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),!(JS(h)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=JS(h);return{dataUrl:h,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function c7(e,t,n,r){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>r?{width:Math.round(r*a),height:r}:{width:e,height:t}}function u7(e){return new Promise((t,n)=>{const r=f7(),a=new r;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function wj(e){return new Promise((t,n)=>{const r=h7(),a=new r;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function d7(){var t;const e=ox();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function h7(){const e=ox();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function f7(){const e=ox();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function ox(){return globalThis}function m7(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++){const a=t[r];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function JS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}const ZS=50*1024*1024,e1=1024*1024,p7=["image/png","image/jpeg","image/gif"];function g7(e){return e==="application/pdf"}function x7(e){return p7.includes(e.type)}async function y7(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}async function t1(e,t,n){try{if(ix(e.type)){if(e.size>e1){n(`Text file too large (${eo(e.size)}). Maximum is ${eo(e1)}.`);return}const r=await e.text(),a={id:Wu(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}else if(Ju(e.type)||g7(e.type)){if(e.size>ZS){const r=Ju(e.type)?"Image":"PDF";n(`${r} file too large (${eo(e.size)}). Maximum is ${eo(ZS)}.`);return}if(Ju(e.type)&&x7(e)){const r=await o7(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),a={id:Wu(),filename:e.name||"unnamed-file",mimeType:r.mimeType,size:r.size,data:r.dataUrl};t(a)}else{const r=await y7(e),a={id:Wu(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}}else n(`Unsupported file type: ${e.type}. Supported types: images (PNG, JPG, GIF, WebP, BMP, SVG), PDF, text files, JSON, XML, YAML, and other common text-based formats.`)}catch(r){const a=r instanceof Error?r.message??"Failed to process file":"Failed to process file";n(a)}}function Cj(e){const t=Le(l=>l.sendMessage),n=Le(l=>l.launchWorkflow),r=E.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=E.useCallback((l,u,c,d,h)=>{e(!0),n(l,u,c,d,h)},[e,n]);return{sendMessage:r,launchWorkflow:a}}function b7({children:e}){return pi.createPortal(e,document.body)}function v7(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 _7({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,h]=E.useState(!1),[p,m]=E.useState("commands"),[x,y]=E.useState(""),[w,C]=E.useState(0),[_,S]=E.useState(null),[v,b]=E.useState(null),j=E.useRef(null),N=E.useRef(null),T=Yt(ne=>ne.defaults),D=Yt(ne=>ne.userItems),L=Yt(ne=>ne.projectItems),O=Yt(ne=>ne.fetchCommands),M=vt(ne=>ne.defaults),G=vt(ne=>ne.userItems),U=vt(ne=>ne.projectItems),R=vt(ne=>ne.fetchWorkflows),H=Kr(Kr(T,D),L),W=Kr(Kr(M,G),U);E.useEffect(()=>{d&&(p==="commands"?O():p==="workflows"&&R())},[d,p,O,R]),E.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ne;return(ne=j.current)==null?void 0:ne.focus()}))},[d,p]),E.useEffect(()=>{if(!d)return;const ne=re=>{var Q;(Q=N.current)!=null&&Q.contains(re.target)||h(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[d]);const V=ne=>{switch(ne.key){case"ArrowDown":ne.preventDefault(),C(re=>{const K=(p==="commands"?H:W).filter(P=>{const J=x.toLowerCase();return!J||P.name.toLowerCase().includes(J)});return Math.min(re+1,K.length-1)});break;case"ArrowUp":ne.preventDefault(),C(re=>Math.max(re-1,0));break;case"Enter":ne.preventDefault();break;case"Escape":ne.preventDefault(),h(!1);break}},Z=ne=>{y(ne),C(0)},X=H.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),$=W.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),I=async ne=>{const re=await Yt.getState().fetchCommand(ne);re&&e(re.prompt,re.metadata.agentMode,u,c),h(!1)},B=ne=>{t(ne),h(!1)},q=(ne,re)=>{re.stopPropagation(),h(!1),S(ne)},z=(ne,re)=>{re.stopPropagation(),h(!1),b(ne)};return i.jsxs("div",{ref:N,className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>h(!d),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:i.jsx(D1,{className:"w-4 h-4"})}),d&&i.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:[i.jsxs("div",{className:"flex border-b border-border",children:[i.jsx("button",{type:"button",onClick:()=>{m("commands"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),i.jsx("button",{type:"button",onClick:()=>{m("workflows"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),i.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&i.jsx("div",{className:"p-2 border-b border-border",children:i.jsx("input",{ref:j,value:x,onChange:ne=>Z(ne.target.value),onKeyDown:V,placeholder:p==="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"})}),i.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:p==="commands"?X.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:H.length===0?"No commands yet":"No matches"}):X.map((ne,re)=>i.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsx("button",{type:"button",onClick:()=>I(ne.id),className:"flex-1 text-left",children:i.jsx("div",{className:"text-sm text-text-primary font-medium",children:ne.name})}),i.jsx(ui,{className:"opacity-0 group-hover:opacity-100",onClick:Q=>q(ne.id,Q)})]},ne.id)):p==="workflows"?$.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):$.map((ne,re)=>{const Q=v7(ne),K=ne.color??"#3b82f6";return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsxs("button",{type:"button",onClick:()=>B(ne.id),className:"flex-1 text-left flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:K}}),i.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:ne.name}),Q!==null&&i.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:Q?"#22c55e":"#6b7280"},title:Q?"Entry condition met":"Entry condition not met"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[ne.subGroups&&ne.subGroups.length>0&&i.jsx(S7,{subGroups:ne.subGroups,onSelect:P=>{h(!1),n(ne.id,P)}}),i.jsx(ui,{className:"opacity-0 group-hover:opacity-100",onClick:P=>z(ne.id,P)})]})]},ne.id)}):i.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>{l(),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:[i.jsx(aT,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm font-medium",children:"Attach file"})]}),i.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),p!=="attach"&&i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{h(!1),p==="commands"?r():a()},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:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),i.jsx(xj,{isOpen:!!_,onClose:()=>S(null),initialEditId:_}),i.jsx(vj,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function S7({subGroups:e,onSelect:t}){const[n,r]=E.useState(!1),[a,l]=E.useState({top:0,right:0}),u=E.useRef(null),c=E.useRef(null);th(c,()=>r(!1),n);const d=h=>{if(h.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}r(!n)};return i.jsxs(i.Fragment,{children:[i.jsx("button",{ref:u,type:"button",onClick:d,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&i.jsx(b7,{children:i.jsx("div",{ref:c,onMouseDown:h=>h.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(h=>i.jsx("button",{type:"button",onClick:p=>{p.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 w7({messages:e,onCancel:t}){return e.length===0?null:i.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>i.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:[i.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),i.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),i.jsx(ac,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function C7({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:r,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d}){const h=e.allowedTools.filter(p=>!(r!=null&&r.has(p)));return i.jsxs(K1,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),i.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&i.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[h.slice(0,5).map(p=>i.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:p},p)),h.length>5&&i.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",h.length-5," more"]})]})]})}function n1({title:e,agents:t,subagents:n,isBuiltIn:r,alwaysAllowedNames:a,onView:l,onDuplicate:u,onEdit:c,onDelete:d,onCancelDelete:h,isConfirmingDelete:p}){if(t.length===0&&n.length===0)return null;const m=x=>i.jsx(C7,{agent:x,isBuiltIn:r,isConfirmingDelete:(p==null?void 0:p(x.id))??!1,alwaysAllowedNames:a,onView:()=>l(x.id),onEdit:r?void 0:()=>c==null?void 0:c(x.id),onDuplicate:()=>u(x.id),onDelete:r?void 0:()=>d==null?void 0:d(x.id),onCancelDelete:r?void 0:()=>h==null?void 0:h(x.id)},x.id);return i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsxs("div",{className:"space-y-2",children:[t.map(m),n.length>0&&i.jsxs("div",{className:"mt-3",children:[i.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),i.jsx("div",{className:"space-y-2",children:n.map(m)})]})]})]})}function k7(e){const t=new Map;for(const n of e){const r=n.indexOf(":");if(r===-1)t.set(n,new Set);else{const a=n.slice(0,r),u=n.slice(r+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function gp(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function j7({formName:e,formId:t,formDescription:n,formSubagent:r,formTools:a,formColor:l,formPrompt:u,formError:c,saving:d,isReadOnly:h,availableTools:p,onNameChange:m,onIdChange:x,onDescriptionChange:y,onSubagentChange:w,onToolsChange:C,onColorChange:_,onPromptChange:S,onSave:v,onCancel:b,onDuplicate:j}){const N=k7(a),T=p.filter(O=>!(r&&O.topLevelOnly)),D=(O,M)=>{const G=new Map(N),U=G.get(O)||new Set,R=new Set(U);R.has(M)?R.delete(M):R.add(M),R.size===0?G.set(O,new Set):G.set(O,R),C(gp(G))},L=O=>{const M=new Map(N);M.has(O)?M.delete(O):M.set(O,new Set),C(gp(M))};return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3",children:[c&&i.jsx(to,{message:c}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:h}),i.jsx(Cr,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Description",value:n,onChange:y,placeholder:"What this agent does",readOnly:h}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),i.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[i.jsx("button",{onClick:()=>!h&&w(!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"}),i.jsx("button",{onClick:()=>!h&&w(!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"}),i.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),i.jsx("input",{type:"color",value:l,onChange:O=>!h&&_(O.target.value),disabled:h,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),i.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:T.map(O=>{const M=N.has(O.name),G=O.actions.length>0,U=N.get(O.name)||new Set;return G?h?i.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:[i.jsx("span",{children:O.name}),i.jsx("span",{className:"text-[10px]",children:"*"})]},O.name):i.jsx(ic,{trigger:i.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[i.jsx("span",{children:O.name}),G&&i.jsx("span",{className:`text-[10px] ${M&&U.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...O.actions.map(R=>({label:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${O.name}-${R}`,children:[i.jsx("input",{type:"checkbox",id:`${O.name}-${R}`,checked:U.has(R),onChange:()=>D(O.name,R),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),i.jsx("span",{children:R})]}),closeOnClick:!1})),{label:M?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(M)L(O.name);else{const R=new Map(N);R.set(O.name,new Set(O.actions)),C(gp(R))}}}]},O.name):i.jsx("button",{onClick:()=>!h&&L(O.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none":"cursor-pointer"}`,children:i.jsx("span",{children:O.name})},O.name)})})]})]}),i.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),i.jsx("textarea",{value:u,onChange:O=>!h&&S(O.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":""}`})]}),i.jsx(DT,{onCancel:b,onSave:v,saving:d,saveDisabled:!e||!u||h}),h&&i.jsx("div",{className:"flex justify-end mt-2",children:i.jsx("button",{onClick:j,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"})})]})}function E7(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function N7({isOpen:e,onClose:t,initialEditId:n}){const r=xt(ae=>ae.defaults),a=xt(ae=>ae.userItems),l=xt(ae=>ae.projectItems),u=xt(ae=>ae.loading),c=xt(ae=>ae.fetchAgents),d=xt(ae=>ae.fetchAgent),h=xt(ae=>ae.fetchDefaultContent),p=xt(ae=>ae.createAgent),m=xt(ae=>ae.updateAgent),x=xt(ae=>ae.deleteAgent),[y,w]=E.useState("list"),[C,_]=E.useState(null),[S,v]=E.useState(!1),[b,j]=E.useState(""),[N,T]=E.useState(""),[D,L]=E.useState(""),[O,M]=E.useState(!0),[G,U]=E.useState([]),[R,H]=E.useState("#6b7280"),[W,V]=E.useState(""),[Z,X]=E.useState("user"),[$,I]=E.useState(""),[B,q]=E.useState(!1),[z,ne]=E.useState([]),[re,Q]=E.useState(new Set),{requestDelete:K,clearConfirm:P,isConfirming:J}=Jl(),ie=ae=>{j(ae.metadata.name),T(ae.metadata.id),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I("")},he=(ae,se,me)=>{j(ae.metadata.name+" (copy)"),T(`${se}-copy-${Date.now()}`),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I(""),_(null),v(!1),w("edit")},ce=(ae,se)=>{ie(ae),_(se),v(!0),w("edit")};E.useEffect(()=>{e&&(c(),ve("/api/tools").then(ae=>ae.json()).then(ae=>{const se=ae.tools||[];Q(new Set(se.filter(me=>me.alwaysAllowed).map(me=>me.name))),ne(se.filter(me=>!me.alwaysAllowed))}).catch(()=>{ne([]),Q(new Set)}),n?r.some(se=>se.id===n)?h(n).then(se=>{se&&he(se,n)}):d(n).then(se=>{se&&(ie(se),_(n),v(!1),w("edit"))}):(w("list"),_(null),v(!1)))},[e,c,d,h,n]);const De=async ae=>{if(r.some(me=>me.id===ae)){const me=await h(ae);if(!me)return;ce(me,ae)}else{const me=await d(ae);if(!me)return;ce(me,ae)}},Re=async ae=>{let se=await h(ae);se||(se=await d(ae)),se&&he(se,ae)},ze=()=>{_(null),j(""),T(""),L(""),M(!0),U(["read_file"]),H("#6b7280"),V(""),X("user"),I(""),v(!1),w("edit")},Fe=async ae=>{const se=await d(ae);se&&(ie(se),_(ae),v(!1),w("edit"))},Ee=async ae=>{await x(ae)},st=async()=>{const ae=C??N;if(!ae||!b||!W){I("Name and prompt are required.");return}q(!0),I("");const se={metadata:{id:ae,name:b,description:D,subagent:O,allowedTools:G.filter(Ue=>!re.has(Ue)),color:R},prompt:W},me=C?await m(C,se):await p(se,Z);if(q(!1),!me.success){I(me.error??"Failed to save agent.");return}n?t():w("list")},ot=()=>{n?t():(w("list"),v(!1))},je=ae=>{j(ae),C||T(E7(ae))},Me=r.filter(ae=>ae.subagent),lt=r.filter(ae=>!ae.subagent),we=a.filter(ae=>ae.subagent),Ie=a.filter(ae=>!ae.subagent),qe=l.filter(ae=>ae.subagent),te=l.filter(ae=>!ae.subagent);return y==="edit"?i.jsxs(jt,{isOpen:e,onClose:ot,title:S?`${b}`:C?"Edit Agent":"New Agent",size:"xl",children:[!C&&!S&&i.jsx(Ld,{value:Z,onChange:X}),i.jsx(j7,{formName:b,formId:N,formDescription:D,formSubagent:O,formTools:G,formColor:R,formPrompt:W,formError:$,saving:B,isReadOnly:S,availableTools:z,onNameChange:je,onIdChange:T,onDescriptionChange:L,onSubagentChange:ae=>{M(ae),ae&&U(se=>se.filter(me=>{var Ue;return!((Ue=z.find(He=>He.name===me))!=null&&Ue.topLevelOnly)}))},onToolsChange:U,onColorChange:H,onPromptChange:V,onSave:st,onCancel:ot,onDuplicate:()=>{j(b+" (copy)"),T(`${C}-copy-${Date.now()}`),_(null),v(!1)}})]}):i.jsx(jt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:i.jsx($1,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ze,loading:u,hasItems:r.length>0||a.length>0||l.length>0,children:i.jsxs("div",{className:"space-y-4",children:[r.length>0&&i.jsx(n1,{title:"Built-in",agents:lt,subagents:Me,isBuiltIn:!0,alwaysAllowedNames:re,onView:De,onDuplicate:Re}),[{title:"Custom",agents:Ie,subagents:we},{title:"Project",agents:te,subagents:qe}].map(ae=>ae.agents.length>0&&i.jsx(n1,{title:ae.title,agents:ae.agents,subagents:ae.subagents,isBuiltIn:!1,alwaysAllowedNames:re,isConfirmingDelete:se=>J(se,"delete"),onView:De,onDuplicate:Re,onEdit:Fe,onDelete:se=>{J(se,"delete")?(Ee(se),P()):K(se)},onCancelDelete:P},ae.title))]})})})}function T7(){const e=Le(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=Le(v=>v.switchMode),n=xt(v=>v.defaults),r=xt(v=>v.userItems),a=xt(v=>v.fetchAgents),l=[...n,...r],[u,c]=E.useState(!1),[d,h]=E.useState(!1),[p,m]=E.useState(null),x=E.useRef(null);E.useEffect(()=>{a()},[a]),th(x,()=>c(!1));const y=Ql();if(!e)return null;const w=l.filter(v=>!v.subagent),C=w.find(v=>v.id===e),_=(C==null?void 0:C.name)??e,S=ql(l,e);return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[i.jsx("span",{className:"text-sm font-medium",style:{color:S},children:_}),i.jsx(hn,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&i.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,b)=>{const j=v.id===e,N=ql(l,v.id),T=y.agentSwitching[b],D=T?Zu(T):null;return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${j?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[i.jsxs("button",{type:"button",onClick:()=>{j||t(v.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"font-medium truncate",style:{color:N},children:v.name}),j&&i.jsx(Pr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),D&&i.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:D})]},v.id)}),i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{c(!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..."})})]}),i.jsx(N7,{isOpen:d,onClose:()=>{h(!1),m(null)},initialEditId:p})]})}function A7(){const e=Le(r=>r.currentSession),t=Le(r=>r.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return i.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[i.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="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"}),i.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="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"})]})}function r1({value:e,onChange:t}){return i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",i.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),i.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 L7=[8080,11434,8e3,1234];function rg(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function kj(e){return{name:e.name,url:e.url,backend:e.backend,apiKey:e.apiKey,isLocal:e.isLocal,thinkingField:e.thinkingField,authAdapter:e.authAdapter,transportAdapter:e.transportAdapter,models:e.models}}function D7({model:e,modelConfigs:t,autoConfigState:n,testResults:r,onUpdateConfig:a,onRunAutoConfig:l,onTestParams:u,onShowRaw:c}){var d,h,p,m,x,y,w,C,_,S,v,b,j,N,T,D,L,O,M,G,U,R,H,W,V,Z,X,$,I,B,q,z,ne,re,Q,K,P,J,ie,he,ce,De,Re,ze,Fe;return i.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>l(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"&&i.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&i.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),i.jsxs("div",{className:"flex gap-3 items-end",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),i.jsx("input",{type:"number",value:((d=t[e.id])==null?void 0:d.contextWindow)??e.contextWindow,onChange:Ee=>a(e.id,{contextWindow:parseInt(Ee.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[i.jsx("input",{type:"checkbox",checked:((h=t[e.id])==null?void 0:h.supportsVision)??!1,onChange:Ee=>a(e.id,{supportsVision:Ee.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"thinking"),disabled:(p=r[e.id+"-thinking"])==null?void 0:p.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:(m=r[e.id+"-thinking"])!=null&&m.loading?"Testing...":"Test thinking"}),((x=r[e.id+"-thinking"])==null?void 0:x.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((y=r[e.id+"-thinking"])==null?void 0:y.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(w=r[e.id+"-thinking"])==null?void 0:w.error,children:"Fail"}),((C=r[e.id+"-thinking"])==null?void 0:C.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"non-thinking"),disabled:(_=r[e.id+"-non-thinking"])==null?void 0:_.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:(S=r[e.id+"-non-thinking"])!=null&&S.loading?"Testing...":"Test non-thinking"}),((v=r[e.id+"-non-thinking"])==null?void 0:v.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((b=r[e.id+"-non-thinking"])==null?void 0:b.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(j=r[e.id+"-non-thinking"])==null?void 0:j.error,children:"Fail"}),((N=r[e.id+"-non-thinking"])==null?void 0:N.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),i.jsxs("details",{className:"group",children:[i.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[i.jsx(hn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),i.jsxs("div",{className:"mt-3 space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((T=t[e.id])==null?void 0:T.thinkingEnabled)??!1,onChange:Ee=>a(e.id,{thinkingEnabled:Ee.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((D=t[e.id])==null?void 0:D.thinkingEnabled)&&i.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),(L=e.reasoningEfforts)!=null&&L.length?i.jsx("select",{"aria-label":"Reasoning effort",value:((O=t[e.id])==null?void 0:O.thinkingLevel)??rg(e.reasoningEfforts),onChange:Ee=>a(e.id,{thinkingLevel:Ee.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(Ee=>i.jsx("option",{value:Ee,children:Ee},Ee))}):i.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((M=t[e.id])==null?void 0:M.thinkingLevel)??"",onChange:Ee=>a(e.id,{thinkingLevel:Ee.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsx(r1,{value:(G=t[e.id])==null?void 0:G.thinkingQueryParams,onChange:Ee=>a(e.id,{thinkingQueryParams:Ee})})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((U=t[e.id])==null?void 0:U.nonThinkingEnabled)??!1,onChange:Ee=>a(e.id,{nonThinkingEnabled:Ee.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((R=t[e.id])==null?void 0:R.nonThinkingEnabled)&&i.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:i.jsx(r1,{value:(H=t[e.id])==null?void 0:H.nonThinkingQueryParams,onChange:Ee=>a(e.id,{nonThinkingQueryParams:Ee})})})]}),i.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),i.jsx("input",{type:"number",step:"0.1",value:((W=t[e.id])==null?void 0:W.temperature)??"",onChange:Ee=>a(e.id,{temperature:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((Z=(V=t[e.id])==null?void 0:V.defaultTemperature)==null?void 0:Z.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((X=t[e.id])==null?void 0:X.defaultTemperature)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",($=t[e.id])==null?void 0:$.defaultTemperature]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),i.jsx("input",{type:"number",step:"0.05",value:((I=t[e.id])==null?void 0:I.topP)??"",onChange:Ee=>a(e.id,{topP:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((q=(B=t[e.id])==null?void 0:B.defaultTopP)==null?void 0:q.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((z=t[e.id])==null?void 0:z.defaultTopP)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(ne=t[e.id])==null?void 0:ne.defaultTopP]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),i.jsx("input",{type:"number",value:((re=t[e.id])==null?void 0:re.topK)??"",onChange:Ee=>a(e.id,{topK:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((K=(Q=t[e.id])==null?void 0:Q.defaultTopK)==null?void 0:K.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((P=t[e.id])==null?void 0:P.defaultTopK)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(J=t[e.id])==null?void 0:J.defaultTopK]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),i.jsx("input",{type:"number",value:((ie=t[e.id])==null?void 0:ie.maxTokens)??"",onChange:Ee=>a(e.id,{maxTokens:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((ce=(he=t[e.id])==null?void 0:he.defaultMaxTokens)==null?void 0:ce.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((De=t[e.id])==null?void 0:De.defaultMaxTokens)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Re=t[e.id])==null?void 0:Re.defaultMaxTokens]})]})]})]}),i.jsx("div",{className:"pt-3 border-t border-border",children:i.jsx(R7,{value:(ze=t[e.id])==null?void 0:ze.compactionThreshold,maxTokens:((Fe=t[e.id])==null?void 0:Fe.contextWindow)??e.contextWindow,onChange:Ee=>a(e.id,{compactionThreshold:Ee})})})]})]})}function R7({value:e,maxTokens:t,onChange:n}){const l=Math.min(95,Math.floor((t-5e3)/t*100)),u=Math.min(l,Math.ceil(15e3/t*100)),c=Math.min(e??.85,l/100),[d,h]=E.useState(Math.round(c*100));E.useEffect(()=>{const m=Math.min(e??.85,l/100);h(Math.round(m*100))},[e,l]);const p=Math.floor(t*(d/100));return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-3 mb-1",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Auto-compaction threshold"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"font-mono text-xs text-text-primary",children:[d,"% · ",co(p)]}),i.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"})]})]}),i.jsx("input",{"aria-label":"Auto-compaction threshold",type:"range",min:u,max:l,step:"1",value:d,onChange:m=>h(Number(m.target.value)),onMouseUp:()=>n(d/100),onTouchEnd:()=>n(d/100),onBlur:()=>n(d/100),onKeyUp:()=>n(d/100),className:"w-full"}),i.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Minimum ",co(15e3)," tokens · maximum ",l,"% · default 85%"]})]})}function jj({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:a,editModelId:l}){const[u,c]=E.useState(r),[d,h]=E.useState(""),[p,m]=E.useState(""),[x,y]=E.useState("unknown"),[w,C]=E.useState(""),[_,S]=E.useState(!1),[v,b]=E.useState(),[j,N]=E.useState(),[T,D]=E.useState(!1),[L,O]=E.useState(null),[M,G]=E.useState([]),[U,R]=E.useState(null),[H,W]=E.useState(!1),[V,Z]=E.useState(""),[X,$]=E.useState({}),[I,B]=E.useState({loading:!1,progress:{}}),[q,z]=E.useState({}),[ne,re]=E.useState(null),[Q,K]=E.useState(new Set),[P,J]=E.useState(""),[ie,he]=E.useState(null),[ce,De]=E.useState("disconnected"),[Re,ze]=E.useState(!1),[Fe,Ee]=E.useState(null),[st,ot]=E.useState([]),[je,Me]=E.useState(!1),[lt,we]=E.useState(!1),Ie=E.useRef(null),qe=E.useRef(!1),te=E.useRef(null);E.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var ye;return(ye=te.current)==null?void 0:ye.focus()})},[u,e]),E.useEffect(()=>()=>{Ie.current!==null&&window.clearTimeout(Ie.current)},[]),E.useEffect(()=>{e&&ve("/api/provider-presets").then(async ye=>ye.ok?await ye.json():{presets:[]}).then(ye=>ot(ye.presets)).catch(()=>ot([]))},[e]);function ae(ye,We){$(oe=>({...oe,[ye]:{...oe[ye],...We}}))}function se(ye){K(We=>new Set(We).add(ye.id)),$(We=>({...We,[ye.id]:{contextWindow:ye.contextWindow,...We[ye.id]}}))}function me(ye){if(!ye.trim())return M;const We=ye.toLowerCase().split(/\s+/).filter(Boolean);return M.filter(oe=>We.every(fe=>oe.id.toLowerCase().includes(fe)))}E.useEffect(()=>{var ye,We;if(e)if(c(r),h((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),y((a==null?void 0:a.backend)??"unknown"),C((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),b(a==null?void 0:a.authAdapter),N(a==null?void 0:a.transportAdapter),O(null),Z((a==null?void 0:a.thinkingField)??""),z({}),re(null),he(null),De("disconnected"),Ee(null),Me(!1),we(!1),(ye=a==null?void 0:a.models)!=null&&ye.length){const oe={},fe=new Set;for(const Pe of a.models)oe[Pe.id]={contextWindow:Pe.contextWindow,supportsVision:Pe.supportsVision,thinkingEnabled:Pe.thinkingEnabled,thinkingLevel:Pe.thinkingLevel??rg(Pe.reasoningEfforts),nonThinkingEnabled:Pe.nonThinkingEnabled,thinkingQueryParams:Pe.thinkingQueryParams,nonThinkingQueryParams:Pe.nonThinkingQueryParams,defaultTemperature:Pe.defaultTemperature,defaultTopP:Pe.defaultTopP,defaultTopK:Pe.defaultTopK,defaultMaxTokens:Pe.defaultMaxTokens,temperature:Pe.temperature,topP:Pe.topP,topK:Pe.topK,maxTokens:Pe.maxTokens,compactionThreshold:Pe.compactionThreshold},Pe.selected&&fe.add(Pe.id);if(fe.size===0)for(const Pe of a.models)fe.add(Pe.id);K(fe),$(oe),G(a.models),R(l??((We=a.models[0])==null?void 0:We.id)??null)}else G([]),$({}),R(null),K(new Set)},[e,r,a==null?void 0:a.id,l]),E.useEffect(()=>{const ye=!!v;u===2&&p&&M.length===0&&!T&&!L&&(!ye||ce==="connected")&&Ze(p)},[u,ce]),E.useEffect(()=>{!e||!v||!(a!=null&&a.id)||He(a.id)},[e,j,a==null?void 0:a.id]),E.useEffect(()=>{if(!Fe)return;const ye=(a==null?void 0:a.id)??ie;if(!ye)return;let We=!1;const oe=async()=>{const Pe=await He(ye);We||Pe!=="connected"||(Ee(null),Me(!1),we(!1),await Ze(p))};oe();const fe=window.setInterval(()=>void oe(),2e3);return()=>{We=!0,window.clearInterval(fe)}},[Fe,ie,a==null?void 0:a.id]);async function Ue(){if(a!=null&&a.id)return a.id;if(ie)return ie;const ye=await ve("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d||"Provider",url:p,backend:x,authAdapter:v,transportAdapter:j,isLocal:!1,models:[]})});if(!ye.ok)throw new Error("Unable to create provider");const We=await ye.json();return he(We.provider.id),We.provider.id}async function He(ye){const We=await ve(`/api/provider-auth/${ye}/status`);if(!We.ok)return"error";const oe=await We.json(),fe=oe.state==="connected"?"connected":oe.state==="pending"?"pending":oe.state==="error"?"error":"disconnected";return De(fe),fe}async function Ye(){ze(!0),De("pending");try{const ye=await Ue(),We=await ve(`/api/provider-auth/${ye}/login`,{method:"POST"});if(!We.ok)throw new Error("Unable to start provider sign-in");const oe=await We.json();Ee(oe)}catch{De("error")}finally{ze(!1)}}async function ct(){var ye;Fe!=null&&Fe.userCode&&(await((ye=navigator.clipboard)==null?void 0:ye.writeText(Fe.userCode)),Ie.current!==null&&window.clearTimeout(Ie.current),we(!1),requestAnimationFrame(()=>we(!0)),Ie.current=window.setTimeout(()=>{we(!1),Ie.current=null},1500))}function Je(){Fe&&(window.open(Fe.directUrl??Fe.verificationUrl,"_blank","noopener,noreferrer"),Me(!0))}async function Ze(ye){var We,oe;D(!0),O(null),G([]);try{const fe=new URLSearchParams({url:ye});w&&fe.set("apiKey",w),x&&fe.set("backend",x);const Pe=j?await ve(`/api/providers/${await Ue()}/models`):await ve(`/api/providers/models?${fe.toString()}`);if(Pe.ok){const St=await Pe.json();if((We=St.models)!=null&&We.length){G(St.models),R(((oe=St.models[0])==null?void 0:oe.id)??null);const bn={};for(const fn of St.models)bn[fn.id]={contextWindow:fn.contextWindow,thinkingEnabled:!0,thinkingLevel:rg(fn.reasoningEfforts),defaultTemperature:fn.defaultTemperature,defaultTopP:fn.defaultTopP,defaultTopK:fn.defaultTopK,defaultMaxTokens:fn.defaultMaxTokens};$(bn),St.models.length===1&&(K(new Set([St.models[0].id])),R(St.models[0].id),tt(St.models[0].id))}}else{const St=await Pe.json();O(St.error??`Failed to fetch models from ${ye}`)}}catch(fe){O(`Failed to fetch models from ${ye}: ${fe instanceof Error?fe.message:"Unknown error"}`)}D(!1)}async function tt(ye){B(We=>({loading:!0,progress:{...We.progress,[ye]:"probing"}}));try{const We=await ve("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,apiKey:w||void 0,backend:x||"unknown",models:[{id:ye}]})});if(!We.ok){const fe=await We.json();throw new Error(fe.error??"Auto-config failed")}const oe=await We.json();for(const fe of oe.models){const Pe={};fe.contextSource!=="default"&&(Pe.contextWindow=fe.contextWindow,Pe.supportsVision=fe.supportsVision),fe.thinkingConfig&&(Pe.thinkingEnabled=!0,Pe.thinkingQueryParams=JSON.stringify(fe.thinkingConfig)),fe.nonThinkingConfig&&(Pe.nonThinkingEnabled=!0,Pe.nonThinkingQueryParams=JSON.stringify(fe.nonThinkingConfig)),ae(fe.id,Pe),B(St=>({...St,progress:{...St.progress,[fe.id]:"done"}}))}}catch(We){console.error("Auto-config error:",We),B(oe=>({...oe,progress:{...oe.progress,[ye]:"error"}}))}finally{B(We=>({...We,loading:!1}))}}async function Nt(ye,We){const oe=ye+"-"+We;z(fe=>({...fe,[oe]:{loading:!0}}));try{const fe=X[ye],Pe=await ve("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,providerId:(a==null?void 0:a.id)??ie??void 0,transportAdapter:j,model:ye,apiKey:w||void 0,backend:x||"unknown",thinkingField:V||void 0,mode:We,modelConfig:{temperature:fe==null?void 0:fe.temperature,topP:fe==null?void 0:fe.topP,topK:fe==null?void 0:fe.topK,maxTokens:fe==null?void 0:fe.maxTokens,supportsVision:fe==null?void 0:fe.supportsVision,thinkingEnabled:fe==null?void 0:fe.thinkingEnabled,thinkingLevel:fe==null?void 0:fe.thinkingLevel,nonThinkingEnabled:fe==null?void 0:fe.nonThinkingEnabled,thinkingQueryParams:fe==null?void 0:fe.thinkingQueryParams,nonThinkingQueryParams:fe==null?void 0:fe.nonThinkingQueryParams}})}),St=await Pe.json();Pe.ok?z(bn=>({...bn,[oe]:{loading:!1,result:JSON.stringify(St,null,2),message:St.message}})):z(bn=>({...bn,[oe]:{loading:!1,error:St.error??"Test failed"}}))}catch(fe){z(Pe=>({...Pe,[oe]:{loading:!1,error:fe instanceof Error?fe.message:"Request failed"}}))}}function dt(){G([]),$({}),B({loading:!1,progress:{}}),z({}),re(null),K(new Set),J("")}function rn(){ie&&!qe.current&&ve(`/api/providers/${ie}`,{method:"DELETE"}).catch(ye=>{console.warn("Failed to clean up draft provider",ye)}),t()}function Un(){const ye=d||"Provider",We=(a==null?void 0:a.id)??ie??`temp-${Date.now()}`;n({id:We,name:ye,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:_,thinkingField:V||void 0,authAdapter:v,transportAdapter:j,models:M.map(oe=>{var fe,Pe,St,bn,fn,Br,Ts,yi,As,Ls,Se,Ce,Oe,Ge,Ve,Qe;return{id:oe.id,name:oe.name,apiModelId:oe.apiModelId,requestBody:oe.requestBody,reasoningEfforts:oe.reasoningEfforts,contextWindow:((fe=X[oe.id])==null?void 0:fe.contextWindow)??oe.contextWindow,selected:Q.has(oe.id)||void 0,supportsVision:(Pe=X[oe.id])==null?void 0:Pe.supportsVision,thinkingEnabled:(St=X[oe.id])==null?void 0:St.thinkingEnabled,thinkingLevel:(bn=X[oe.id])==null?void 0:bn.thinkingLevel,nonThinkingEnabled:(fn=X[oe.id])==null?void 0:fn.nonThinkingEnabled,thinkingQueryParams:(Br=X[oe.id])==null?void 0:Br.thinkingQueryParams,nonThinkingQueryParams:(Ts=X[oe.id])==null?void 0:Ts.nonThinkingQueryParams,temperature:(yi=X[oe.id])==null?void 0:yi.temperature,topP:(As=X[oe.id])==null?void 0:As.topP,topK:(Ls=X[oe.id])==null?void 0:Ls.topK,maxTokens:(Se=X[oe.id])==null?void 0:Se.maxTokens,defaultMaxTokens:(Ce=X[oe.id])==null?void 0:Ce.defaultMaxTokens,defaultTemperature:(Oe=X[oe.id])==null?void 0:Oe.defaultTemperature,defaultTopP:(Ge=X[oe.id])==null?void 0:Ge.defaultTopP,defaultTopK:(Ve=X[oe.id])==null?void 0:Ve.defaultTopK,compactionThreshold:(Qe=X[oe.id])==null?void 0:Qe.compactionThreshold}})}),qe.current=!0,t()}return e?i.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",children:[i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),i.jsx("button",{onClick:rn,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2].map(ye=>i.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${ye<u?"bg-accent-success":ye===u?"bg-accent-primary":"bg-border"}`},ye))}),u===1&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),i.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[st.map(ye=>i.jsx("button",{type:"button",onClick:()=>{h(ye.defaults.name??ye.name),m(ye.defaults.url),y(ye.defaults.backend),S(!1),C(""),b(ye.authAdapter),N(ye.transportAdapter),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${j&&j===ye.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ye.name},ye.id)),i.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),b(void 0),N(void 0),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${x==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),L7.map(ye=>{const We={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},oe={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return i.jsx("button",{type:"button",onClick:()=>{h(fe=>fe||(oe[ye]??"")),m(fe=>fe||`http://localhost:${ye}`),y(We[ye]??""),S(!0),b(void 0),N(void 0),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${x===We[ye]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:oe[ye]??`localhost:${ye}`},ye)})]})]}),!v&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),i.jsx("input",{ref:te,type:"text",value:p,"data-testid":"provider-modal-url",onChange:ye=>{m(ye.target.value),O(null),G([]),$({})},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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),i.jsx("input",{type:"text",autoComplete:"off",value:d,onChange:ye=>h(ye.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"})]}),!v&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:ye=>C(ye.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"})]}),!v&&i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:_,onChange:ye=>S(ye.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),i.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[!!v&&i.jsxs("div",{className:"rounded-lg border border-border bg-bg-primary p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-xs text-text-muted",children:"Connect this provider before choosing available models."})]}),ce==="connected"?i.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):i.jsx("button",{type:"button",onClick:()=>void Ye(),disabled:Re||ce==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:Re||ce==="pending"?"Connecting...":ce==="error"?"Retry":"Connect"})]}),Fe&&i.jsx("div",{className:"mt-4 border-t border-border pt-4",children:Fe.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted",children:"Use this code to complete authorization:"}),i.jsx("button",{type:"button",onClick:()=>void ct(),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:Fe.userCode??"Continue"}),i.jsxs("div",{className:"mt-3 flex gap-2",children:[i.jsx("button",{type:"button",onClick:()=>void ct(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:lt?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:Je,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"Reopen authorization":"Open authorization"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted mb-3",children:Fe.instructions}),i.jsx("button",{type:"button",onClick:Je,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"Reopen authorization":"Open authorization"})]})})]}),T&&i.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[i.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),L&&i.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[i.jsx("p",{children:L}),i.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),i.jsxs("div",{className:"flex gap-2 mt-2",children:[i.jsx("button",{onClick:()=>Ze(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),i.jsx("button",{onClick:()=>{dt(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),M.length>0&&x&&(!v||ce==="connected")&&i.jsxs(i.Fragment,{children:[Q.size>0&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",Q.size,")"]}),i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),i.jsx("div",{className:"space-y-2",children:M.filter(ye=>Q.has(ye.id)).map(ye=>{var We;return i.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[i.jsxs("div",{onClick:()=>R(U===ye.id?null:ye.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((We=X[ye.id])==null?void 0:We.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[I.progress[ye.id]==="probing"?i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):I.progress[ye.id]==="done"?i.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):I.progress[ye.id]==="error"?i.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):v?null:i.jsx("button",{onClick:oe=>{oe.stopPropagation(),tt(ye.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),M.length>1&&i.jsx("button",{onClick:oe=>{oe.stopPropagation();const fe=new Set(Q);fe.delete(ye.id),K(fe),U===ye.id&&R(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),i.jsx(hn,{className:`w-4 h-4 text-text-muted transition-transform ${U===ye.id?"rotate-180":""}`})]})]}),U===ye.id&&i.jsx(D7,{model:ye,modelConfigs:X,autoConfigState:I,testResults:q,onUpdateConfig:ae,onRunAutoConfig:tt,onTestParams:Nt,onShowRaw:re})]},ye.id)})})]}),M.length>1&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),Q.size===0&&i.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."}),i.jsxs("div",{className:"relative mb-2",children:[i.jsx("input",{type:"text",value:P,onChange:ye=>J(ye.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"}),P&&i.jsx("button",{onClick:()=>J(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",me(P).length," of ",M.length," models"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{const ye=new Set(Q),We=me(P);for(const oe of We)ye.add(oe.id);if(K(ye),$(oe=>{const fe={...oe};for(const Pe of We)fe[Pe.id]={contextWindow:Pe.contextWindow,...fe[Pe.id]};return fe}),!v)for(const oe of We)I.progress[oe.id]!=="probing"&&I.progress[oe.id]!=="done"&&tt(oe.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),i.jsx("button",{onClick:()=>{const ye=new Set(Q),We=me(P);for(const oe of We)ye.delete(oe.id);K(ye)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),i.jsxs("div",{className:"space-y-1 max-h-48 overflow-y-auto border border-border rounded-lg bg-bg-primary",children:[me(P).map(ye=>{var oe;const We=Q.has(ye.id);return i.jsxs("div",{role:"checkbox","aria-checked":We,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${We?"bg-accent-primary/5":""}`,onClick:()=>{if(We){const fe=new Set(Q);fe.delete(ye.id),K(fe)}else se(ye),v||tt(ye.id)},onKeyDown:fe=>{(fe.key==="Enter"||fe.key===" ")&&(fe.preventDefault(),fe.currentTarget.click())},children:[i.jsx("input",{type:"checkbox",checked:We,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),i.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((oe=X[ye.id])==null?void 0:oe.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]}),I.progress[ye.id]==="probing"&&i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),I.progress[ye.id]==="done"&&i.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),I.progress[ye.id]==="error"&&i.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},ye.id)}),me(P).length===0&&i.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",P,"”"]})]})]})]})]}),i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[i.jsx("div",{children:u>1&&i.jsx("button",{onClick:()=>{u===2&&dt(),c(u-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:rn,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u===1?i.jsx("button",{onClick:()=>c(2),disabled:!p,"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"}):i.jsx("button",{onClick:Un,disabled:I.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:I.loading?"Configuring...":"Save Provider"})]})]})]}),H&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&W(!1)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),i.jsx("button",{onClick:()=>W(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),i.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),i.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"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",i.jsx("span",{className:"text-text-muted",children:"(override)"})]}),i.jsx("input",{type:"text",value:V,onChange:ye=>Z(ye.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"}),i.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)."})]})]}),i.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:i.jsx("button",{onClick:()=>W(!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"})})]})}),ne&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&re(null)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[80vh] shadow-2xl flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border shrink-0",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),i.jsx("button",{onClick:()=>re(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:ne})]})})]}):null}function O7(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function I7(e,t){const n=t.toLowerCase(),r=(e.name??"").toLowerCase(),a=e.id.toLowerCase(),l=a.replace(/-/g," ");return r.includes(n)||a.includes(n)||l.includes(n)}function s1({activeProvider:e,shortModelName:t}){return i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-accent-primary",children:e?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"hidden sm:inline",children:[e.name," • "]}),t]}):t}),i.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 M7({providerId:e,modelConfig:t,isActive:n,isDefault:r,disabled:a,hasSession:l,settingDefault:u,highlighted:c,onModelClick:d,onSetDefault:h,onEditModel:p}){var m;return i.jsxs("div",{className:`flex items-center px-4 py-1.5 text-sm transition-colors group ${c?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${a?"opacity-50 cursor-wait":""} ${n?"text-accent-primary":"text-text-secondary"}`,children:[i.jsx("button",{type:"button",onClick:()=>d(e,t.id),disabled:a,className:"flex-1 truncate text-left",children:t.name??((m=t.id.split("/").pop())==null?void 0:m.replace(/-/g," "))??t.id}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0 ml-2",children:[i.jsx("span",{className:"text-xs text-text-muted",children:O7(t.contextWindow)}),l&&i.jsx("button",{type:"button",onClick:x=>h(x,e,t.id),disabled:u,className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors disabled:opacity-40",title:r?"Default model":"Set as default model",children:r?i.jsx(I1,{className:"w-3.5 h-3.5 text-accent-warning"}):i.jsx(M1,{className:"w-3.5 h-3.5 text-text-muted hover:text-accent-warning"})}),i.jsx("button",{type:"button",onClick:x=>{x.stopPropagation(),p(e,t)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:i.jsx(A1,{className:"w-3 h-3 text-text-muted"})}),n&&i.jsx("span",{className:"text-accent-success flex-shrink-0",title:"Session model",children:i.jsx(Pr,{className:"w-3.5 h-3.5"})})]})]})}function P7(){var We;const[,e]=Tn(),t=Le(oe=>oe.currentSession),n=Le(oe=>oe.setSessionProvider),[r,a]=E.useState(!1),[l,u]=E.useState([]),[c,d]=E.useState(null),h=E.useRef(null),[p,m]=E.useState(null),[x,y]=E.useState(!1),[w,C]=E.useState({}),[_,S]=E.useState(null),[v,b]=E.useState(null),[j,N]=E.useState(!1),T=E.useRef(null),[D,L]=E.useState(!1),O=E.useRef(new Set),[M,G]=E.useState(-1),U=E.useRef(null),R=Xt(oe=>oe.providers),H=Xt(oe=>oe.activeProviderId),W=Xt(oe=>oe.defaultModelSelection),V=Xt(oe=>oe.activating),Z=Xt(oe=>oe.activateProvider),X=Xt(oe=>oe.refreshModel),$=Xt(oe=>oe.refreshProviderModels),I=Xt(oe=>oe.setDefaultModel),B=Xt(oe=>oe.fetchConfig),q=Ql();Pl(q.modelSelector,()=>a(oe=>!oe));const z=(t==null?void 0:t.providerId)??null,ne=(t==null?void 0:t.providerModel)??null,re=(W==null?void 0:W.split("/")[0])??null,Q=(W==null?void 0:W.split("/").slice(1).join("/"))??null,K=z??re,P=ne??Q,J=P?((We=P.split("/").pop())==null?void 0:We.replace(/-/g," "))??P:"No model",[ie,he]=E.useState(!1),[ce,De]=E.useState(""),Re=E.useRef(null);E.useEffect(()=>{function oe(fe){h.current&&!h.current.contains(fe.target)&&(a(!1),u([]),O.current=new Set)}return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]),E.useEffect(()=>()=>{T.current!==null&&window.clearTimeout(T.current)},[]),E.useEffect(()=>{r||(De(""),G(-1))},[r]),E.useEffect(()=>{var oe;r&&((oe=Re.current)==null||oe.focus())},[r]),E.useEffect(()=>{M>=0&&U.current&&U.current.scrollIntoView({block:"nearest"})},[M]),E.useEffect(()=>{if(r){const oe=R.map(fe=>fe.id);u(oe),R.filter(fe=>!!fe.authAdapter).forEach(fe=>void Ie(fe.id)),oe.forEach(fe=>{O.current.has(fe)||(O.current.add(fe),ot(fe))})}},[r,R]),E.useEffect(()=>{if(!v)return;let oe=!1;const fe=async()=>{const St=await Ie(v.providerId);oe||St==="connected"&&(b(null),N(!1),L(!1),await B(),O.current.delete(v.providerId),await ot(v.providerId))};fe();const Pe=window.setInterval(()=>void fe(),2e3);return()=>{oe=!0,window.clearInterval(Pe)}},[v]);const ze=R.find(oe=>oe.id===K),Fe=(ze==null?void 0:ze.status)==="disconnected",Ee=(oe,fe)=>t?t.providerId===oe&&t.providerModel===fe:!1,st=(oe,fe)=>W?W===`${oe}/${fe}`:!1,ot=async oe=>{d(oe);try{await $(oe)}catch{}finally{d(null)}},je=oe=>{l.includes(oe.id)?u(l.filter(fe=>fe!==oe.id)):(u([...l,oe.id]),ot(oe.id))},Me=async oe=>{if(oe.id===H){je(oe);return}t?(n(oe.id,void 0),a(!1),u([])):await Z(oe.id)&&(a(!1),u([]))},lt=oe=>{je(oe)},we=async(oe,fe)=>{oe.stopPropagation(),O.current.delete(fe),await ot(fe)},Ie=async oe=>{const fe=await ve(`/api/provider-auth/${oe}/status`);if(!fe.ok)return"error";const Pe=await fe.json();return C(St=>({...St,[oe]:Pe.state})),Pe.state},qe=async(oe,fe)=>{oe.stopPropagation(),S(fe),C(Pe=>({...Pe,[fe]:"pending"})),N(!1),L(!1);try{const Pe=await ve(`/api/provider-auth/${fe}/login`,{method:"POST"});if(!Pe.ok)throw new Error("Unable to start provider sign-in");const St=await Pe.json();b({providerId:fe,...St})}catch{C(Pe=>({...Pe,[fe]:"error"}))}finally{S(null)}},te=async()=>{var oe;v!=null&&v.userCode&&(await((oe=navigator.clipboard)==null?void 0:oe.writeText(v.userCode)),T.current!==null&&window.clearTimeout(T.current),N(!1),requestAnimationFrame(()=>N(!0)),T.current=window.setTimeout(()=>{N(!1),T.current=null},1500))},ae=()=>{v&&(window.open(v.directUrl??v.verificationUrl,"_blank","noopener,noreferrer"),L(!0))},se=()=>{b(null),N(!1),L(!1)},me=async(oe,fe)=>{oe.stopPropagation(),S(fe);try{if(!(await ve(`/api/provider-auth/${fe}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");C(St=>({...St,[fe]:"disconnected"})),await B()}finally{S(null)}},Ue=(oe,fe)=>{m({providerId:oe,model:fe}),y(!0)},He=p?R.find(oe=>oe.id===p.providerId):void 0,Ye=()=>{m(null),y(!1)},ct=async oe=>{try{if(!(await ve(`/api/providers/${oe.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(kj(oe))})).ok)throw new Error("Failed to update provider");await Xt.getState().fetchConfig()}catch{}m(null),y(!1)},Je=async(oe,fe)=>{if(t){Le.setState(St=>({currentSession:St.currentSession?{...St.currentSession,providerId:oe,providerModel:fe}:null})),n(oe,fe),u([]),a(!1),Kl();return}await Z(oe)&&(u([]),a(!1),Kl())},Ze=async(oe,fe,Pe)=>{oe.stopPropagation(),he(!0);try{await I(fe,Pe)}catch{}finally{he(!1)}};function tt(oe){return oe.models.some(Pe=>Pe.selected)?oe.models.filter(Pe=>Pe.selected):oe.models}const Nt=E.useMemo(()=>ce.trim()?R.map(oe=>({provider:oe,models:tt(oe).filter(fe=>I7(fe,ce))})).filter(oe=>oe.models.length>0):R.map(oe=>({provider:oe,models:tt(oe)})),[R,ce]),dt=E.useMemo(()=>Nt.flatMap(oe=>oe.models.map(fe=>({providerId:oe.provider.id,modelConfig:fe}))),[Nt]),rn=dt.length+1,Un=M===dt.length;E.useEffect(()=>{rn===1?G(-1):M>=rn?G(rn-1):M<0&&ce.trim()&&G(0)},[rn,M,ce]);const ye=oe=>{switch(oe.key){case"Escape":a(!1);break;case"ArrowDown":oe.preventDefault(),rn>0&&G(fe=>fe<rn-1?fe+1:0);break;case"ArrowUp":oe.preventDefault(),rn>0&&G(fe=>fe>0?fe-1:rn-1);break;case"Home":oe.preventDefault(),G(0);break;case"End":oe.preventDefault(),G(rn-1);break;case"Enter":if(oe.preventDefault(),M===dt.length)e("/onboarding"),a(!1);else if(M>=0&&M<dt.length){const fe=dt[M];fe&&Je(fe.providerId,fe.modelConfig.id)}break}};return R.length===0?i.jsxs("button",{type:"button",onClick:()=>X(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:Fe?"LLM server is offline. Click to retry.":J??"Click to refresh model",children:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):i.jsx(s1,{activeProvider:ze,shortModelName:J}),i.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):i.jsxs("div",{className:"relative",ref:h,children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),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:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):i.jsx(s1,{activeProvider:ze,shortModelName:J}),i.jsx(hn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:r?180:0})]}),r&&i.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:[i.jsxs("div",{className:"flex items-center gap-1 px-3 py-2 border-b border-border flex-shrink-0",children:[i.jsx(Qi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("input",{ref:Re,type:"text",value:ce,onInput:oe=>{De(oe.currentTarget.value),G(-1)},onKeyDown:ye,placeholder:"Search models...",className:"bg-transparent border-none outline-none text-sm text-text-primary w-full placeholder:text-text-muted"})]}),i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:i.jsxs("div",{children:[Nt.map(oe=>{const fe=ce.trim().length>0||l.includes(oe.provider.id);return i.jsxs("div",{children:[i.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${oe.provider.id===K?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${V?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[i.jsxs("div",{onClick:()=>!V&&Me(oe.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[i.jsx("span",{className:`text-sm font-medium truncate ${oe.provider.id===K?"text-accent-primary":"text-text-primary"}`,children:oe.provider.name}),i.jsx("span",{className:"text-xs text-text-muted truncate",children:oe.provider.backend!=="unknown"&&v1(oe.provider.backend)})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!oe.provider.authAdapter&&(w[oe.provider.id]==="connected"||oe.provider.credentialRef?i.jsx("button",{type:"button",onClick:Pe=>me(Pe,oe.provider.id),disabled:_===oe.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"}):i.jsx("button",{type:"button",onClick:Pe=>qe(Pe,oe.provider.id),disabled:_===oe.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:_===oe.provider.id?"Starting…":w[oe.provider.id]==="error"||w[oe.provider.id]==="expired"?"Retry":"Connect"})),oe.provider.id===K?i.jsx("span",{className:"text-accent-success",title:"Active provider",children:i.jsx(Pr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-4"}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),we(Pe,oe.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:i.jsx(Td,{className:`w-4 h-4 ${c===oe.provider.id?"animate-spin":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),lt(oe.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:i.jsx(hn,{className:`w-4 h-4 transition-transform ${fe?"rotate-180":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})})]})]}),fe&&i.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===oe.provider.id?i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):oe.models.length>0?oe.models.map(Pe=>{const bn=dt.findIndex(fn=>fn.providerId===oe.provider.id&&fn.modelConfig.id===Pe.id)===M;return i.jsx("div",{ref:bn?U:void 0,children:i.jsx(M7,{providerId:oe.provider.id,modelConfig:Pe,isActive:Ee(oe.provider.id,Pe.id),isDefault:st(oe.provider.id,Pe.id),disabled:c==="activating",hasSession:!!t,settingDefault:ie,highlighted:bn,onModelClick:Je,onSetDefault:Ze,onEditModel:Ue})},`${oe.provider.id}/${Pe.id}`)}):i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},oe.provider.id)}),Nt.length===0&&ce.trim()&&i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No models match your search"})]})}),i.jsx("div",{className:`border-t border-border px-3 py-2 ${Un?"bg-bg-tertiary":""} flex-shrink-0`,children:i.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),v&&i.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/70 px-4",role:"dialog","aria-modal":"true","aria-labelledby":"provider-device-title",onMouseDown:oe=>{oe.target===oe.currentTarget&&se()},children:i.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border bg-bg-secondary p-6 shadow-2xl",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h2",{id:"provider-device-title",className:"text-lg font-semibold text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-sm text-text-muted",children:"Follow the provider instructions to complete authorization."})]}),i.jsx("button",{type:"button",onClick:se,className:"rounded px-2 py-1 text-xl leading-none text-text-muted hover:bg-bg-tertiary hover:text-text-primary","aria-label":"Close",children:"×"})]}),v.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:te,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:v.userCode??"Continue"}),i.jsx("div",{className:"mt-3 text-center text-xs text-text-muted",children:j?"Copied to clipboard":"Click the code to copy it"}),i.jsxs("div",{className:"mt-6 flex gap-3",children:[i.jsx("button",{type:"button",onClick:te,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:j?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:ae,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:D?"Reopen authorization":"Open authorization"})]}),i.jsx("p",{className:"mt-4 text-center text-xs text-text-muted",children:D?"If the browser blocked or closed the tab, reopen authorization.":"OpenFox stays open while you complete authorization in the other tab."})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"mt-6 text-sm text-text-secondary leading-relaxed bg-bg-primary p-4 rounded-lg border border-border",children:v.instructions}),i.jsx("div",{className:"mt-6 flex gap-3",children:i.jsx("button",{type:"button",onClick:ae,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:D?"Reopen authorization":"Open authorization"})})]})]})}),p&&x&&i.jsx(jj,{isOpen:!0,onClose:Ye,onSave:ct,initialStep:2,editProvider:{id:p.providerId,name:(He==null?void 0:He.name)??"",url:(He==null?void 0:He.url)??"",backend:(He==null?void 0:He.backend)??"unknown",apiKey:He==null?void 0:He.apiKey,isLocal:He==null?void 0:He.isLocal,thinkingField:He==null?void 0:He.thinkingField,authAdapter:He==null?void 0:He.authAdapter,transportAdapter:He==null?void 0:He.transportAdapter,models:He==null?void 0:He.models},editModelId:p.model.id})]})}function B7(){const e=Il(j=>j.servers),t=Il(j=>j.fetchServers),n=Le(j=>j.currentSession),r=n==null?void 0:n.id,[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(new Set),[p,m]=E.useState(new Set),x=E.useRef(null),y=E.useCallback(async()=>{if(r)try{const j=await ve(`/api/sessions/${r}/mcp/overrides`);if(j.ok){const N=await j.json();m(new Set(N.disabledServers??[]))}}catch{}},[r]),w=E.useCallback(async()=>{await t(),await y()},[t,y]);E.useEffect(()=>{const j=()=>w();return window.addEventListener("mcp-servers-changed",j),()=>window.removeEventListener("mcp-servers-changed",j)},[w]),E.useEffect(()=>{y()},[y]),E.useEffect(()=>{a&&y()},[a,y]),th(x,()=>l(!1));const C=j=>p.has(j.name),_=e.filter(j=>j.status==="connected"&&!C(j)),S=_.length,v=_.reduce((j,N)=>j+N.estimatedTokens,0),b=async(j,N)=>{if(r){c(null),h(T=>new Set(T).add(j));try{const T=new Set(p);N?T.add(j):T.delete(j);const D=await ve(`/api/sessions/${r}/mcp/overrides`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledServers:Array.from(T)})});if(!D.ok){const L=await D.json().catch(()=>({}));throw new Error(L.error??"Toggle failed")}m(T),await t()}catch(T){c(T instanceof Error?T.message:String(T))}finally{h(T=>{const D=new Set(T);return D.delete(j),D})}}};return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>l(!a),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:[i.jsx("span",{className:"text-sm text-accent-primary whitespace-nowrap",children:S>0?`● ${S} MCP (${xd(v)})`:"MCP"}),i.jsx(hn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:a?180:0})]}),a&&i.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:[i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:e.length===0?i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No MCP servers configured"}):e.map(j=>{const N=C(j),T=d.has(j.name);return i.jsx("div",{children:i.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-bg-tertiary",children:[i.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[i.jsx("span",{className:`text-sm ${Xg(N?"disabled":j.status)}`,children:Qg(N?"disabled":j.status)}),i.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:j.name})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[i.jsxs("span",{children:[j.tools.length," tools"]}),j.estimatedTokens>0&&i.jsxs("span",{children:[xd(j.estimatedTokens)," tokens"]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[T&&i.jsx("span",{className:"text-xs text-text-muted animate-pulse",children:"..."}),i.jsx(Yr,{enabled:!N,onClick:()=>b(j.name,!N)})]})]})},j.name)})}),i.jsx("div",{className:"border-t border-border px-3 py-2 flex-shrink-0",children:u?i.jsx("div",{className:"text-xs text-accent-error",children:u}):i.jsxs("span",{className:"text-xs text-text-muted",children:[e.length," server(s) configured"]})})]})]})}function $7(e,t){const n=e.slice(0,t),r=n.lastIndexOf("@");if(r===-1)return null;const a=n.slice(r+1);return a.includes(" ")||a.includes(`
318
+ `,children:[i.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[h.formattedTimestamp,h.sessionName&&i.jsxs(i.Fragment,{children:[" | ",i.jsx("span",{className:"text-accent-primary font-medium",children:h.sessionName})]})]}),i.jsx("div",{className:"text-sm text-text-primary mt-1",children:h.trimmedContent})]},h.id))})}function s7(){const e=XN(),t=e?"bg-amber-400":"bg-accent-primary";return i.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"flex gap-0.5",children:[i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"0ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),i.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"300ms"}})]}),i.jsx("span",{className:"text-text-secondary",children:e?"Running... (abort in progress)":"Running"})]}),!e&&i.jsx("span",{className:"text-text-muted hidden sm:inline",children:"esc to interrupt"})]})}function i7(){const e=Le(u=>u.activeWorkflowExecution),t=Le(u=>u.exitWorkflow),[n,r]=E.useState(!1);E.useEffect(()=>{r(!1)},[e==null?void 0:e.id]);const a=E.useCallback(()=>{n||(r(!0),t())},[n,t]);if(!e||e.status!=="running"&&e.status!=="waiting")return null;const l=e.workflowColor&&/^#[0-9a-fA-F]{6}$/.test(e.workflowColor)?e.workflowColor:"#3b82f6";return i.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-xs border-b border-border",children:[i.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l}}),i.jsx("span",{className:"font-medium text-text-primary truncate",children:e.workflowName}),e.currentStepName&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-muted",children:"·"}),i.jsx("span",{className:"text-text-muted truncate",children:e.currentStepName})]}),i.jsx("div",{className:"ml-auto shrink-0",children:i.jsx("button",{onClick:a,disabled:n,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:n?"Exiting...":"✕ Exit"})})]})}const a7={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function o7(e,t={}){const n={...a7,...t};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=m7(a),u=`data:${e.type};base64,${l}`,c=await wj(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await l7(e,n)}async function l7(e,t){const n=await u7(e),r=await wj(n),{width:a,height:l}=c7(r.width,r.height,t.maxWidth,t.maxHeight),u=d7();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(r,0,0,a,l);let d=t.quality,h="";for(let m=0;m<10&&(h=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),!(JS(h)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=JS(h);return{dataUrl:h,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function c7(e,t,n,r){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>r?{width:Math.round(r*a),height:r}:{width:e,height:t}}function u7(e){return new Promise((t,n)=>{const r=f7(),a=new r;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function wj(e){return new Promise((t,n)=>{const r=h7(),a=new r;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function d7(){var t;const e=ox();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function h7(){const e=ox();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function f7(){const e=ox();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function ox(){return globalThis}function m7(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++){const a=t[r];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function JS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}const ZS=50*1024*1024,e1=1024*1024,p7=["image/png","image/jpeg","image/gif"];function g7(e){return e==="application/pdf"}function x7(e){return p7.includes(e.type)}async function y7(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}async function t1(e,t,n){try{if(ix(e.type)){if(e.size>e1){n(`Text file too large (${eo(e.size)}). Maximum is ${eo(e1)}.`);return}const r=await e.text(),a={id:Wu(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}else if(Ju(e.type)||g7(e.type)){if(e.size>ZS){const r=Ju(e.type)?"Image":"PDF";n(`${r} file too large (${eo(e.size)}). Maximum is ${eo(ZS)}.`);return}if(Ju(e.type)&&x7(e)){const r=await o7(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),a={id:Wu(),filename:e.name||"unnamed-file",mimeType:r.mimeType,size:r.size,data:r.dataUrl};t(a)}else{const r=await y7(e),a={id:Wu(),filename:e.name||"unnamed-file",mimeType:e.type,size:e.size,data:r};t(a)}}else n(`Unsupported file type: ${e.type}. Supported types: images (PNG, JPG, GIF, WebP, BMP, SVG), PDF, text files, JSON, XML, YAML, and other common text-based formats.`)}catch(r){const a=r instanceof Error?r.message??"Failed to process file":"Failed to process file";n(a)}}function Cj(e){const t=Le(l=>l.sendMessage),n=Le(l=>l.launchWorkflow),r=E.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=E.useCallback((l,u,c,d,h)=>{e(!0),n(l,u,c,d,h)},[e,n]);return{sendMessage:r,launchWorkflow:a}}function b7({children:e}){return pi.createPortal(e,document.body)}function v7(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 _7({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:r,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,h]=E.useState(!1),[p,m]=E.useState("commands"),[x,y]=E.useState(""),[w,C]=E.useState(0),[_,S]=E.useState(null),[v,b]=E.useState(null),j=E.useRef(null),N=E.useRef(null),T=Yt(ne=>ne.defaults),D=Yt(ne=>ne.userItems),L=Yt(ne=>ne.projectItems),O=Yt(ne=>ne.fetchCommands),M=vt(ne=>ne.defaults),G=vt(ne=>ne.userItems),U=vt(ne=>ne.projectItems),R=vt(ne=>ne.fetchWorkflows),H=Kr(Kr(T,D),L),W=Kr(Kr(M,G),U);E.useEffect(()=>{d&&(p==="commands"?O():p==="workflows"&&R())},[d,p,O,R]),E.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ne;return(ne=j.current)==null?void 0:ne.focus()}))},[d,p]),E.useEffect(()=>{if(!d)return;const ne=re=>{var Q;(Q=N.current)!=null&&Q.contains(re.target)||h(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[d]);const V=ne=>{switch(ne.key){case"ArrowDown":ne.preventDefault(),C(re=>{const K=(p==="commands"?H:W).filter(P=>{const J=x.toLowerCase();return!J||P.name.toLowerCase().includes(J)});return Math.min(re+1,K.length-1)});break;case"ArrowUp":ne.preventDefault(),C(re=>Math.max(re-1,0));break;case"Enter":ne.preventDefault();break;case"Escape":ne.preventDefault(),h(!1);break}},Z=ne=>{y(ne),C(0)},X=H.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),$=W.filter(ne=>!x||ne.name.toLowerCase().includes(x.toLowerCase())),I=async ne=>{const re=await Yt.getState().fetchCommand(ne);re&&e(re.prompt,re.metadata.agentMode,u,c),h(!1)},B=ne=>{t(ne),h(!1)},q=(ne,re)=>{re.stopPropagation(),h(!1),S(ne)},z=(ne,re)=>{re.stopPropagation(),h(!1),b(ne)};return i.jsxs("div",{ref:N,className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>h(!d),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:i.jsx(D1,{className:"w-4 h-4"})}),d&&i.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:[i.jsxs("div",{className:"flex border-b border-border",children:[i.jsx("button",{type:"button",onClick:()=>{m("commands"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),i.jsx("button",{type:"button",onClick:()=>{m("workflows"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),i.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&i.jsx("div",{className:"p-2 border-b border-border",children:i.jsx("input",{ref:j,value:x,onChange:ne=>Z(ne.target.value),onKeyDown:V,placeholder:p==="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"})}),i.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:p==="commands"?X.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:H.length===0?"No commands yet":"No matches"}):X.map((ne,re)=>i.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsx("button",{type:"button",onClick:()=>I(ne.id),className:"flex-1 text-left",children:i.jsx("div",{className:"text-sm text-text-primary font-medium",children:ne.name})}),i.jsx(ui,{className:"opacity-0 group-hover:opacity-100",onClick:Q=>q(ne.id,Q)})]},ne.id)):p==="workflows"?$.length===0?i.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):$.map((ne,re)=>{const Q=v7(ne),K=ne.color??"#3b82f6";return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${re===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[i.jsxs("button",{type:"button",onClick:()=>B(ne.id),className:"flex-1 text-left flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:K}}),i.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:ne.name}),Q!==null&&i.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:Q?"#22c55e":"#6b7280"},title:Q?"Entry condition met":"Entry condition not met"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[ne.subGroups&&ne.subGroups.length>0&&i.jsx(S7,{subGroups:ne.subGroups,onSelect:P=>{h(!1),n(ne.id,P)}}),i.jsx(ui,{className:"opacity-0 group-hover:opacity-100",onClick:P=>z(ne.id,P)})]})]},ne.id)}):i.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>{l(),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:[i.jsx(aT,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm font-medium",children:"Attach file"})]}),i.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),p!=="attach"&&i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{h(!1),p==="commands"?r():a()},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:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),i.jsx(xj,{isOpen:!!_,onClose:()=>S(null),initialEditId:_}),i.jsx(vj,{isOpen:!!v,onClose:()=>b(null),initialEditId:v})]})}function S7({subGroups:e,onSelect:t}){const[n,r]=E.useState(!1),[a,l]=E.useState({top:0,right:0}),u=E.useRef(null),c=E.useRef(null);th(c,()=>r(!1),n);const d=h=>{if(h.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}r(!n)};return i.jsxs(i.Fragment,{children:[i.jsx("button",{ref:u,type:"button",onClick:d,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&i.jsx(b7,{children:i.jsx("div",{ref:c,onMouseDown:h=>h.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(h=>i.jsx("button",{type:"button",onClick:p=>{p.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 w7({messages:e,onCancel:t}){return e.length===0?null:i.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>i.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:[i.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),i.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),i.jsx(ac,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function C7({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:r,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d}){const h=e.allowedTools.filter(p=>!(r!=null&&r.has(p)));return i.jsxs(K1,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:l,onDuplicate:u,onDelete:c,onCancelDelete:d,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),i.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),i.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&i.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[h.slice(0,5).map(p=>i.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:p},p)),h.length>5&&i.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",h.length-5," more"]})]})]})}function n1({title:e,agents:t,subagents:n,isBuiltIn:r,alwaysAllowedNames:a,onView:l,onDuplicate:u,onEdit:c,onDelete:d,onCancelDelete:h,isConfirmingDelete:p}){if(t.length===0&&n.length===0)return null;const m=x=>i.jsx(C7,{agent:x,isBuiltIn:r,isConfirmingDelete:(p==null?void 0:p(x.id))??!1,alwaysAllowedNames:a,onView:()=>l(x.id),onEdit:r?void 0:()=>c==null?void 0:c(x.id),onDuplicate:()=>u(x.id),onDelete:r?void 0:()=>d==null?void 0:d(x.id),onCancelDelete:r?void 0:()=>h==null?void 0:h(x.id)},x.id);return i.jsxs("div",{children:[i.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),i.jsxs("div",{className:"space-y-2",children:[t.map(m),n.length>0&&i.jsxs("div",{className:"mt-3",children:[i.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),i.jsx("div",{className:"space-y-2",children:n.map(m)})]})]})]})}function k7(e){const t=new Map;for(const n of e){const r=n.indexOf(":");if(r===-1)t.set(n,new Set);else{const a=n.slice(0,r),u=n.slice(r+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function gp(e){const t=[];for(const[n,r]of e)r.size===0?t.push(n):t.push(`${n}:${[...r].join(",")}`);return t}function j7({formName:e,formId:t,formDescription:n,formSubagent:r,formTools:a,formColor:l,formPrompt:u,formError:c,saving:d,isReadOnly:h,availableTools:p,onNameChange:m,onIdChange:x,onDescriptionChange:y,onSubagentChange:w,onToolsChange:C,onColorChange:_,onPromptChange:S,onSave:v,onCancel:b,onDuplicate:j}){const N=k7(a),T=p.filter(O=>!(r&&O.topLevelOnly)),D=(O,M)=>{const G=new Map(N),U=G.get(O)||new Set,R=new Set(U);R.has(M)?R.delete(M):R.add(M),R.size===0?G.set(O,new Set):G.set(O,R),C(gp(G))},L=O=>{const M=new Map(N);M.has(O)?M.delete(O):M.set(O,new Set),C(gp(M))};return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"space-y-3",children:[c&&i.jsx(to,{message:c}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:h}),i.jsx(Cr,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(Cr,{label:"Description",value:n,onChange:y,placeholder:"What this agent does",readOnly:h}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),i.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[i.jsx("button",{onClick:()=>!h&&w(!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"}),i.jsx("button",{onClick:()=>!h&&w(!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"}),i.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),i.jsx("input",{type:"color",value:l,onChange:O=>!h&&_(O.target.value),disabled:h,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),i.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:T.map(O=>{const M=N.has(O.name),G=O.actions.length>0,U=N.get(O.name)||new Set;return G?h?i.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:[i.jsx("span",{children:O.name}),i.jsx("span",{className:"text-[10px]",children:"*"})]},O.name):i.jsx(ic,{trigger:i.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[i.jsx("span",{children:O.name}),G&&i.jsx("span",{className:`text-[10px] ${M&&U.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...O.actions.map(R=>({label:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${O.name}-${R}`,children:[i.jsx("input",{type:"checkbox",id:`${O.name}-${R}`,checked:U.has(R),onChange:()=>D(O.name,R),disabled:h,className:"w-3 h-3 rounded accent-accent-primary"}),i.jsx("span",{children:R})]}),closeOnClick:!1})),{label:M?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(M)L(O.name);else{const R=new Map(N);R.set(O.name,new Set(O.actions)),C(gp(R))}}}]},O.name):i.jsx("button",{onClick:()=>!h&&L(O.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${h?"pointer-events-none":"cursor-pointer"}`,children:i.jsx("span",{children:O.name})},O.name)})})]})]}),i.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[i.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),i.jsx("textarea",{value:u,onChange:O=>!h&&S(O.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":""}`})]}),i.jsx(DT,{onCancel:b,onSave:v,saving:d,saveDisabled:!e||!u||h}),h&&i.jsx("div",{className:"flex justify-end mt-2",children:i.jsx("button",{onClick:j,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"})})]})}function E7(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return t?`custom-${t}`:""}function N7({isOpen:e,onClose:t,initialEditId:n}){const r=xt(ae=>ae.defaults),a=xt(ae=>ae.userItems),l=xt(ae=>ae.projectItems),u=xt(ae=>ae.loading),c=xt(ae=>ae.fetchAgents),d=xt(ae=>ae.fetchAgent),h=xt(ae=>ae.fetchDefaultContent),p=xt(ae=>ae.createAgent),m=xt(ae=>ae.updateAgent),x=xt(ae=>ae.deleteAgent),[y,w]=E.useState("list"),[C,_]=E.useState(null),[S,v]=E.useState(!1),[b,j]=E.useState(""),[N,T]=E.useState(""),[D,L]=E.useState(""),[O,M]=E.useState(!0),[G,U]=E.useState([]),[R,H]=E.useState("#6b7280"),[W,V]=E.useState(""),[Z,X]=E.useState("user"),[$,I]=E.useState(""),[B,q]=E.useState(!1),[z,ne]=E.useState([]),[re,Q]=E.useState(new Set),{requestDelete:K,clearConfirm:P,isConfirming:J}=Jl(),ie=ae=>{j(ae.metadata.name),T(ae.metadata.id),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I("")},he=(ae,se,me)=>{j(ae.metadata.name+" (copy)"),T(`${se}-copy-${Date.now()}`),L(ae.metadata.description),M(ae.metadata.subagent),U(ae.metadata.allowedTools),H(ae.metadata.color??"#6b7280"),V(ae.prompt),I(""),_(null),v(!1),w("edit")},ce=(ae,se)=>{ie(ae),_(se),v(!0),w("edit")};E.useEffect(()=>{e&&(c(),ve("/api/tools").then(ae=>ae.json()).then(ae=>{const se=ae.tools||[];Q(new Set(se.filter(me=>me.alwaysAllowed).map(me=>me.name))),ne(se.filter(me=>!me.alwaysAllowed))}).catch(()=>{ne([]),Q(new Set)}),n?r.some(se=>se.id===n)?h(n).then(se=>{se&&he(se,n)}):d(n).then(se=>{se&&(ie(se),_(n),v(!1),w("edit"))}):(w("list"),_(null),v(!1)))},[e,c,d,h,n]);const De=async ae=>{if(r.some(me=>me.id===ae)){const me=await h(ae);if(!me)return;ce(me,ae)}else{const me=await d(ae);if(!me)return;ce(me,ae)}},Re=async ae=>{let se=await h(ae);se||(se=await d(ae)),se&&he(se,ae)},ze=()=>{_(null),j(""),T(""),L(""),M(!0),U(["read_file"]),H("#6b7280"),V(""),X("user"),I(""),v(!1),w("edit")},Fe=async ae=>{const se=await d(ae);se&&(ie(se),_(ae),v(!1),w("edit"))},Ee=async ae=>{await x(ae)},st=async()=>{const ae=C??N;if(!ae||!b||!W){I("Name and prompt are required.");return}q(!0),I("");const se={metadata:{id:ae,name:b,description:D,subagent:O,allowedTools:G.filter(Ue=>!re.has(Ue)),color:R},prompt:W},me=C?await m(C,se):await p(se,Z);if(q(!1),!me.success){I(me.error??"Failed to save agent.");return}n?t():w("list")},ot=()=>{n?t():(w("list"),v(!1))},je=ae=>{j(ae),C||T(E7(ae))},Me=r.filter(ae=>ae.subagent),lt=r.filter(ae=>!ae.subagent),we=a.filter(ae=>ae.subagent),Ie=a.filter(ae=>!ae.subagent),qe=l.filter(ae=>ae.subagent),te=l.filter(ae=>!ae.subagent);return y==="edit"?i.jsxs(jt,{isOpen:e,onClose:ot,title:S?`${b}`:C?"Edit Agent":"New Agent",size:"xl",children:[!C&&!S&&i.jsx(Ld,{value:Z,onChange:X}),i.jsx(j7,{formName:b,formId:N,formDescription:D,formSubagent:O,formTools:G,formColor:R,formPrompt:W,formError:$,saving:B,isReadOnly:S,availableTools:z,onNameChange:je,onIdChange:T,onDescriptionChange:L,onSubagentChange:ae=>{M(ae),ae&&U(se=>se.filter(me=>{var Ue;return!((Ue=z.find(He=>He.name===me))!=null&&Ue.topLevelOnly)}))},onToolsChange:U,onColorChange:H,onPromptChange:V,onSave:st,onCancel:ot,onDuplicate:()=>{j(b+" (copy)"),T(`${C}-copy-${Date.now()}`),_(null),v(!1)}})]}):i.jsx(jt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:i.jsx($1,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ze,loading:u,hasItems:r.length>0||a.length>0||l.length>0,children:i.jsxs("div",{className:"space-y-4",children:[r.length>0&&i.jsx(n1,{title:"Built-in",agents:lt,subagents:Me,isBuiltIn:!0,alwaysAllowedNames:re,onView:De,onDuplicate:Re}),[{title:"Custom",agents:Ie,subagents:we},{title:"Project",agents:te,subagents:qe}].map(ae=>ae.agents.length>0&&i.jsx(n1,{title:ae.title,agents:ae.agents,subagents:ae.subagents,isBuiltIn:!1,alwaysAllowedNames:re,isConfirmingDelete:se=>J(se,"delete"),onView:De,onDuplicate:Re,onEdit:Fe,onDelete:se=>{J(se,"delete")?(Ee(se),P()):K(se)},onCancelDelete:P},ae.title))]})})})}function T7(){const e=Le(v=>{var b;return(b=v.currentSession)==null?void 0:b.mode}),t=Le(v=>v.switchMode),n=xt(v=>v.defaults),r=xt(v=>v.userItems),a=xt(v=>v.fetchAgents),l=[...n,...r],[u,c]=E.useState(!1),[d,h]=E.useState(!1),[p,m]=E.useState(null),x=E.useRef(null);E.useEffect(()=>{a()},[a]),th(x,()=>c(!1));const y=Ql();if(!e)return null;const w=l.filter(v=>!v.subagent),C=w.find(v=>v.id===e),_=(C==null?void 0:C.name)??e,S=ql(l,e);return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[i.jsx("span",{className:"text-sm font-medium",style:{color:S},children:_}),i.jsx(hn,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&i.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,b)=>{const j=v.id===e,N=ql(l,v.id),T=y.agentSwitching[b],D=T?Zu(T):null;return i.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${j?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[i.jsxs("button",{type:"button",onClick:()=>{j||t(v.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"font-medium truncate",style:{color:N},children:v.name}),j&&i.jsx(Pr,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),D&&i.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:D})]},v.id)}),i.jsx("div",{className:"border-t border-border p-1",children:i.jsx("button",{type:"button",onClick:()=>{c(!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..."})})]}),i.jsx(N7,{isOpen:d,onClose:()=>{h(!1),m(null)},initialEditId:p})]})}function A7(){const e=Le(r=>r.currentSession),t=Le(r=>r.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return i.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[i.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="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"}),i.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="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"})]})}function r1({value:e,onChange:t}){return i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",i.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),i.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 L7=[8080,11434,8e3,1234];function rg(e){if(e!=null&&e.length)return e.includes("medium")?"medium":e[0]}function kj(e){return{name:e.name,url:e.url,backend:e.backend,apiKey:e.apiKey,isLocal:e.isLocal,thinkingField:e.thinkingField,authAdapter:e.authAdapter,transportAdapter:e.transportAdapter,models:e.models}}function D7({model:e,modelConfigs:t,autoConfigState:n,testResults:r,onUpdateConfig:a,onRunAutoConfig:l,onTestParams:u,onShowRaw:c}){var d,h,p,m,x,y,w,C,_,S,v,b,j,N,T,D,L,O,M,G,U,R,H,W,V,Z,X,$,I,B,q,z,ne,re,Q,K,P,J,ie,he,ce,De,Re,ze,Fe;return i.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>l(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"&&i.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&i.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),i.jsxs("div",{className:"flex gap-3 items-end",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),i.jsx("input",{type:"number",value:((d=t[e.id])==null?void 0:d.contextWindow)??e.contextWindow,onChange:Ee=>a(e.id,{contextWindow:parseInt(Ee.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[i.jsx("input",{type:"checkbox",checked:((h=t[e.id])==null?void 0:h.supportsVision)??!1,onChange:Ee=>a(e.id,{supportsVision:Ee.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"thinking"),disabled:(p=r[e.id+"-thinking"])==null?void 0:p.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:(m=r[e.id+"-thinking"])!=null&&m.loading?"Testing...":"Test thinking"}),((x=r[e.id+"-thinking"])==null?void 0:x.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((y=r[e.id+"-thinking"])==null?void 0:y.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(w=r[e.id+"-thinking"])==null?void 0:w.error,children:"Fail"}),((C=r[e.id+"-thinking"])==null?void 0:C.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(e.id,"non-thinking"),disabled:(_=r[e.id+"-non-thinking"])==null?void 0:_.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:(S=r[e.id+"-non-thinking"])!=null&&S.loading?"Testing...":"Test non-thinking"}),((v=r[e.id+"-non-thinking"])==null?void 0:v.result)&&i.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((b=r[e.id+"-non-thinking"])==null?void 0:b.error)&&i.jsx("span",{className:"text-xs text-red-500",title:(j=r[e.id+"-non-thinking"])==null?void 0:j.error,children:"Fail"}),((N=r[e.id+"-non-thinking"])==null?void 0:N.result)&&i.jsx("button",{onClick:()=>c(r[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),i.jsxs("details",{className:"group",children:[i.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[i.jsx(hn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),i.jsxs("div",{className:"mt-3 space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((T=t[e.id])==null?void 0:T.thinkingEnabled)??!1,onChange:Ee=>a(e.id,{thinkingEnabled:Ee.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((D=t[e.id])==null?void 0:D.thinkingEnabled)&&i.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),(L=e.reasoningEfforts)!=null&&L.length?i.jsx("select",{"aria-label":"Reasoning effort",value:((O=t[e.id])==null?void 0:O.thinkingLevel)??rg(e.reasoningEfforts),onChange:Ee=>a(e.id,{thinkingLevel:Ee.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(Ee=>i.jsx("option",{value:Ee,children:Ee},Ee))}):i.jsx("input",{type:"text","aria-label":"Reasoning effort",value:((M=t[e.id])==null?void 0:M.thinkingLevel)??"",onChange:Ee=>a(e.id,{thinkingLevel:Ee.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),i.jsx(r1,{value:(G=t[e.id])==null?void 0:G.thinkingQueryParams,onChange:Ee=>a(e.id,{thinkingQueryParams:Ee})})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:((U=t[e.id])==null?void 0:U.nonThinkingEnabled)??!1,onChange:Ee=>a(e.id,{nonThinkingEnabled:Ee.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),i.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((R=t[e.id])==null?void 0:R.nonThinkingEnabled)&&i.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:i.jsx(r1,{value:(H=t[e.id])==null?void 0:H.nonThinkingQueryParams,onChange:Ee=>a(e.id,{nonThinkingQueryParams:Ee})})})]}),i.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),i.jsx("input",{type:"number",step:"0.1",value:((W=t[e.id])==null?void 0:W.temperature)??"",onChange:Ee=>a(e.id,{temperature:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((Z=(V=t[e.id])==null?void 0:V.defaultTemperature)==null?void 0:Z.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((X=t[e.id])==null?void 0:X.defaultTemperature)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",($=t[e.id])==null?void 0:$.defaultTemperature]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),i.jsx("input",{type:"number",step:"0.05",value:((I=t[e.id])==null?void 0:I.topP)??"",onChange:Ee=>a(e.id,{topP:Ee.target.value?parseFloat(Ee.target.value):void 0}),placeholder:((q=(B=t[e.id])==null?void 0:B.defaultTopP)==null?void 0:q.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((z=t[e.id])==null?void 0:z.defaultTopP)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(ne=t[e.id])==null?void 0:ne.defaultTopP]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),i.jsx("input",{type:"number",value:((re=t[e.id])==null?void 0:re.topK)??"",onChange:Ee=>a(e.id,{topK:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((K=(Q=t[e.id])==null?void 0:Q.defaultTopK)==null?void 0:K.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((P=t[e.id])==null?void 0:P.defaultTopK)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(J=t[e.id])==null?void 0:J.defaultTopK]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),i.jsx("input",{type:"number",value:((ie=t[e.id])==null?void 0:ie.maxTokens)??"",onChange:Ee=>a(e.id,{maxTokens:Ee.target.value?parseInt(Ee.target.value):void 0}),placeholder:((ce=(he=t[e.id])==null?void 0:he.defaultMaxTokens)==null?void 0:ce.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((De=t[e.id])==null?void 0:De.defaultMaxTokens)!==void 0&&i.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Re=t[e.id])==null?void 0:Re.defaultMaxTokens]})]})]})]}),i.jsx("div",{className:"pt-3 border-t border-border",children:i.jsx(R7,{value:(ze=t[e.id])==null?void 0:ze.compactionThreshold,maxTokens:((Fe=t[e.id])==null?void 0:Fe.contextWindow)??e.contextWindow,onChange:Ee=>a(e.id,{compactionThreshold:Ee})})})]})]})}function R7({value:e,maxTokens:t,onChange:n}){const l=Math.min(95,Math.floor((t-5e3)/t*100)),u=Math.min(l,Math.ceil(15e3/t*100)),c=Math.min(e??.85,l/100),[d,h]=E.useState(Math.round(c*100));E.useEffect(()=>{const m=Math.min(e??.85,l/100);h(Math.round(m*100))},[e,l]);const p=Math.floor(t*(d/100));return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-3 mb-1",children:[i.jsx("label",{className:"text-xs text-text-secondary",children:"Auto-compaction threshold"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"font-mono text-xs text-text-primary",children:[d,"% · ",co(p)]}),i.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"})]})]}),i.jsx("input",{"aria-label":"Auto-compaction threshold",type:"range",min:u,max:l,step:"1",value:d,onChange:m=>h(Number(m.target.value)),onMouseUp:()=>n(d/100),onTouchEnd:()=>n(d/100),onBlur:()=>n(d/100),onKeyUp:()=>n(d/100),className:"w-full"}),i.jsxs("p",{className:"text-[10px] text-text-muted mt-0.5",children:["Minimum ",co(15e3)," tokens · maximum ",l,"% · default 85%"]})]})}function jj({isOpen:e,onClose:t,onSave:n,initialStep:r=1,editProvider:a,editModelId:l}){const[u,c]=E.useState(r),[d,h]=E.useState(""),[p,m]=E.useState(""),[x,y]=E.useState("unknown"),[w,C]=E.useState(""),[_,S]=E.useState(!1),[v,b]=E.useState(),[j,N]=E.useState(),[T,D]=E.useState(!1),[L,O]=E.useState(null),[M,G]=E.useState([]),[U,R]=E.useState(null),[H,W]=E.useState(!1),[V,Z]=E.useState(""),[X,$]=E.useState({}),[I,B]=E.useState({loading:!1,progress:{}}),[q,z]=E.useState({}),[ne,re]=E.useState(null),[Q,K]=E.useState(new Set),[P,J]=E.useState(""),[ie,he]=E.useState(null),[ce,De]=E.useState("disconnected"),[Re,ze]=E.useState(!1),[Fe,Ee]=E.useState(null),[st,ot]=E.useState([]),[je,Me]=E.useState(!1),[lt,we]=E.useState(!1),Ie=E.useRef(null),qe=E.useRef(!1),te=E.useRef(null);E.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var ye;return(ye=te.current)==null?void 0:ye.focus()})},[u,e]),E.useEffect(()=>()=>{Ie.current!==null&&window.clearTimeout(Ie.current)},[]),E.useEffect(()=>{e&&ve("/api/provider-presets").then(async ye=>ye.ok?await ye.json():{presets:[]}).then(ye=>ot(ye.presets)).catch(()=>ot([]))},[e]);function ae(ye,We){$(oe=>({...oe,[ye]:{...oe[ye],...We}}))}function se(ye){K(We=>new Set(We).add(ye.id)),$(We=>({...We,[ye.id]:{contextWindow:ye.contextWindow,...We[ye.id]}}))}function me(ye){if(!ye.trim())return M;const We=ye.toLowerCase().split(/\s+/).filter(Boolean);return M.filter(oe=>We.every(fe=>oe.id.toLowerCase().includes(fe)))}E.useEffect(()=>{var ye,We;if(e)if(c(r),h((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),y((a==null?void 0:a.backend)??"unknown"),C((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),b(a==null?void 0:a.authAdapter),N(a==null?void 0:a.transportAdapter),O(null),Z((a==null?void 0:a.thinkingField)??""),z({}),re(null),he(null),De("disconnected"),Ee(null),Me(!1),we(!1),(ye=a==null?void 0:a.models)!=null&&ye.length){const oe={},fe=new Set;for(const Pe of a.models)oe[Pe.id]={contextWindow:Pe.contextWindow,supportsVision:Pe.supportsVision,thinkingEnabled:Pe.thinkingEnabled,thinkingLevel:Pe.thinkingLevel??rg(Pe.reasoningEfforts),nonThinkingEnabled:Pe.nonThinkingEnabled,thinkingQueryParams:Pe.thinkingQueryParams,nonThinkingQueryParams:Pe.nonThinkingQueryParams,defaultTemperature:Pe.defaultTemperature,defaultTopP:Pe.defaultTopP,defaultTopK:Pe.defaultTopK,defaultMaxTokens:Pe.defaultMaxTokens,temperature:Pe.temperature,topP:Pe.topP,topK:Pe.topK,maxTokens:Pe.maxTokens,compactionThreshold:Pe.compactionThreshold},Pe.selected&&fe.add(Pe.id);if(fe.size===0)for(const Pe of a.models)fe.add(Pe.id);K(fe),$(oe),G(a.models),R(l??((We=a.models[0])==null?void 0:We.id)??null)}else G([]),$({}),R(null),K(new Set)},[e,r,a==null?void 0:a.id,l]),E.useEffect(()=>{const ye=!!v;u===2&&p&&M.length===0&&!T&&!L&&(!ye||ce==="connected")&&Ze(p)},[u,ce]),E.useEffect(()=>{!e||!v||!(a!=null&&a.id)||He(a.id)},[e,j,a==null?void 0:a.id]),E.useEffect(()=>{if(!Fe)return;const ye=(a==null?void 0:a.id)??ie;if(!ye)return;let We=!1;const oe=async()=>{const Pe=await He(ye);We||Pe!=="connected"||(Ee(null),Me(!1),we(!1),await Ze(p))};oe();const fe=window.setInterval(()=>void oe(),2e3);return()=>{We=!0,window.clearInterval(fe)}},[Fe,ie,a==null?void 0:a.id]);async function Ue(){if(a!=null&&a.id)return a.id;if(ie)return ie;const ye=await ve("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d||"Provider",url:p,backend:x,authAdapter:v,transportAdapter:j,isLocal:!1,models:[]})});if(!ye.ok)throw new Error("Unable to create provider");const We=await ye.json();return he(We.provider.id),We.provider.id}async function He(ye){const We=await ve(`/api/provider-auth/${ye}/status`);if(!We.ok)return"error";const oe=await We.json(),fe=oe.state==="connected"?"connected":oe.state==="pending"?"pending":oe.state==="error"?"error":"disconnected";return De(fe),fe}async function Ye(){ze(!0),De("pending");try{const ye=await Ue(),We=await ve(`/api/provider-auth/${ye}/login`,{method:"POST"});if(!We.ok)throw new Error("Unable to start provider sign-in");const oe=await We.json();Ee(oe)}catch{De("error")}finally{ze(!1)}}async function ct(){var ye;Fe!=null&&Fe.userCode&&(await((ye=navigator.clipboard)==null?void 0:ye.writeText(Fe.userCode)),Ie.current!==null&&window.clearTimeout(Ie.current),we(!1),requestAnimationFrame(()=>we(!0)),Ie.current=window.setTimeout(()=>{we(!1),Ie.current=null},1500))}function Je(){Fe&&(window.open(Fe.directUrl??Fe.verificationUrl,"_blank","noopener,noreferrer"),Me(!0))}async function Ze(ye){var We,oe;D(!0),O(null),G([]);try{const fe=new URLSearchParams({url:ye});w&&fe.set("apiKey",w),x&&fe.set("backend",x);const Pe=j?await ve(`/api/providers/${await Ue()}/models`):await ve(`/api/providers/models?${fe.toString()}`);if(Pe.ok){const St=await Pe.json();if((We=St.models)!=null&&We.length){G(St.models),R(((oe=St.models[0])==null?void 0:oe.id)??null);const bn={};for(const fn of St.models)bn[fn.id]={contextWindow:fn.contextWindow,thinkingEnabled:!0,thinkingLevel:rg(fn.reasoningEfforts),defaultTemperature:fn.defaultTemperature,defaultTopP:fn.defaultTopP,defaultTopK:fn.defaultTopK,defaultMaxTokens:fn.defaultMaxTokens};$(bn),St.models.length===1&&(K(new Set([St.models[0].id])),R(St.models[0].id),tt(St.models[0].id))}}else{const St=await Pe.json();O(St.error??`Failed to fetch models from ${ye}`)}}catch(fe){O(`Failed to fetch models from ${ye}: ${fe instanceof Error?fe.message:"Unknown error"}`)}D(!1)}async function tt(ye){B(We=>({loading:!0,progress:{...We.progress,[ye]:"probing"}}));try{const We=await ve("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,apiKey:w||void 0,backend:x||"unknown",models:[{id:ye}]})});if(!We.ok){const fe=await We.json();throw new Error(fe.error??"Auto-config failed")}const oe=await We.json();for(const fe of oe.models){const Pe={};fe.contextSource!=="default"&&(Pe.contextWindow=fe.contextWindow,Pe.supportsVision=fe.supportsVision),fe.thinkingConfig&&(Pe.thinkingEnabled=!0,Pe.thinkingQueryParams=JSON.stringify(fe.thinkingConfig)),fe.nonThinkingConfig&&(Pe.nonThinkingEnabled=!0,Pe.nonThinkingQueryParams=JSON.stringify(fe.nonThinkingConfig)),ae(fe.id,Pe),B(St=>({...St,progress:{...St.progress,[fe.id]:"done"}}))}}catch(We){console.error("Auto-config error:",We),B(oe=>({...oe,progress:{...oe.progress,[ye]:"error"}}))}finally{B(We=>({...We,loading:!1}))}}async function Nt(ye,We){const oe=ye+"-"+We;z(fe=>({...fe,[oe]:{loading:!0}}));try{const fe=X[ye],Pe=await ve("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,providerId:(a==null?void 0:a.id)??ie??void 0,transportAdapter:j,model:ye,apiKey:w||void 0,backend:x||"unknown",thinkingField:V||void 0,mode:We,modelConfig:{temperature:fe==null?void 0:fe.temperature,topP:fe==null?void 0:fe.topP,topK:fe==null?void 0:fe.topK,maxTokens:fe==null?void 0:fe.maxTokens,supportsVision:fe==null?void 0:fe.supportsVision,thinkingEnabled:fe==null?void 0:fe.thinkingEnabled,thinkingLevel:fe==null?void 0:fe.thinkingLevel,nonThinkingEnabled:fe==null?void 0:fe.nonThinkingEnabled,thinkingQueryParams:fe==null?void 0:fe.thinkingQueryParams,nonThinkingQueryParams:fe==null?void 0:fe.nonThinkingQueryParams}})}),St=await Pe.json();Pe.ok?z(bn=>({...bn,[oe]:{loading:!1,result:JSON.stringify(St,null,2),message:St.message}})):z(bn=>({...bn,[oe]:{loading:!1,error:St.error??"Test failed"}}))}catch(fe){z(Pe=>({...Pe,[oe]:{loading:!1,error:fe instanceof Error?fe.message:"Request failed"}}))}}function dt(){G([]),$({}),B({loading:!1,progress:{}}),z({}),re(null),K(new Set),J("")}function rn(){ie&&!qe.current&&ve(`/api/providers/${ie}`,{method:"DELETE"}).catch(ye=>{console.warn("Failed to clean up draft provider",ye)}),t()}function Un(){const ye=d||"Provider",We=(a==null?void 0:a.id)??ie??`temp-${Date.now()}`;n({id:We,name:ye,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:_,thinkingField:V||void 0,authAdapter:v,transportAdapter:j,models:M.map(oe=>{var fe,Pe,St,bn,fn,Br,Ts,yi,As,Ls,Se,Ce,Oe,Ge,Ve,Qe;return{id:oe.id,name:oe.name,apiModelId:oe.apiModelId,requestBody:oe.requestBody,reasoningEfforts:oe.reasoningEfforts,contextWindow:((fe=X[oe.id])==null?void 0:fe.contextWindow)??oe.contextWindow,selected:Q.has(oe.id)||void 0,supportsVision:(Pe=X[oe.id])==null?void 0:Pe.supportsVision,thinkingEnabled:(St=X[oe.id])==null?void 0:St.thinkingEnabled,thinkingLevel:(bn=X[oe.id])==null?void 0:bn.thinkingLevel,nonThinkingEnabled:(fn=X[oe.id])==null?void 0:fn.nonThinkingEnabled,thinkingQueryParams:(Br=X[oe.id])==null?void 0:Br.thinkingQueryParams,nonThinkingQueryParams:(Ts=X[oe.id])==null?void 0:Ts.nonThinkingQueryParams,temperature:(yi=X[oe.id])==null?void 0:yi.temperature,topP:(As=X[oe.id])==null?void 0:As.topP,topK:(Ls=X[oe.id])==null?void 0:Ls.topK,maxTokens:(Se=X[oe.id])==null?void 0:Se.maxTokens,defaultMaxTokens:(Ce=X[oe.id])==null?void 0:Ce.defaultMaxTokens,defaultTemperature:(Oe=X[oe.id])==null?void 0:Oe.defaultTemperature,defaultTopP:(Ge=X[oe.id])==null?void 0:Ge.defaultTopP,defaultTopK:(Ve=X[oe.id])==null?void 0:Ve.defaultTopK,compactionThreshold:(Qe=X[oe.id])==null?void 0:Qe.compactionThreshold}})}),qe.current=!0,t()}return e?i.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",children:[i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),i.jsx("button",{onClick:rn,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2].map(ye=>i.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${ye<u?"bg-accent-success":ye===u?"bg-accent-primary":"bg-border"}`},ye))}),u===1&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),i.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[st.map(ye=>i.jsx("button",{type:"button",onClick:()=>{h(ye.defaults.name??ye.name),m(ye.defaults.url),y(ye.defaults.backend),S(!1),C(""),b(ye.authAdapter),N(ye.transportAdapter),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${j&&j===ye.transportAdapter?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ye.name},ye.id)),i.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),b(void 0),N(void 0),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${x==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),L7.map(ye=>{const We={8e3:"vllm",11434:"ollama",8080:"llamacpp",1234:"lmstudio"},oe={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp",1234:"LM Studio"};return i.jsx("button",{type:"button",onClick:()=>{h(fe=>fe||(oe[ye]??"")),m(fe=>fe||`http://localhost:${ye}`),y(We[ye]??""),S(!0),b(void 0),N(void 0),O(null),dt()},className:`p-2 rounded border text-center text-sm transition-colors ${x===We[ye]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:oe[ye]??`localhost:${ye}`},ye)})]})]}),!v&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),i.jsx("input",{ref:te,type:"text",value:p,"data-testid":"provider-modal-url",onChange:ye=>{m(ye.target.value),O(null),G([]),$({})},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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),i.jsx("input",{type:"text",autoComplete:"off",value:d,onChange:ye=>h(ye.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"})]}),!v&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",i.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),i.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:ye=>C(ye.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"})]}),!v&&i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:_,onChange:ye=>S(ye.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),i.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[!!v&&i.jsxs("div",{className:"rounded-lg border border-border bg-bg-primary p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-xs text-text-muted",children:"Connect this provider before choosing available models."})]}),ce==="connected"?i.jsx("span",{className:"text-sm font-medium text-accent-success",children:"Connected ✓"}):i.jsx("button",{type:"button",onClick:()=>void Ye(),disabled:Re||ce==="pending",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-medium text-text-primary disabled:opacity-50",children:Re||ce==="pending"?"Connecting...":ce==="error"?"Retry":"Connect"})]}),Fe&&i.jsx("div",{className:"mt-4 border-t border-border pt-4",children:Fe.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted",children:"Use this code to complete authorization:"}),i.jsx("button",{type:"button",onClick:()=>void ct(),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:Fe.userCode??"Continue"}),i.jsxs("div",{className:"mt-3 flex gap-2",children:[i.jsx("button",{type:"button",onClick:()=>void ct(),className:"flex-1 rounded-lg border border-border px-3 py-2 text-sm text-text-primary",children:lt?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:Je,className:"flex-1 rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"Reopen authorization":"Open authorization"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-xs text-text-muted mb-3",children:Fe.instructions}),i.jsx("button",{type:"button",onClick:Je,className:"w-full rounded-lg bg-accent-primary px-3 py-2 text-sm font-medium text-text-primary",children:je?"Reopen authorization":"Open authorization"})]})})]}),T&&i.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[i.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),L&&i.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[i.jsx("p",{children:L}),i.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),i.jsxs("div",{className:"flex gap-2 mt-2",children:[i.jsx("button",{onClick:()=>Ze(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),i.jsx("button",{onClick:()=>{dt(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),M.length>0&&x&&(!v||ce==="connected")&&i.jsxs(i.Fragment,{children:[Q.size>0&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",Q.size,")"]}),i.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),i.jsx("div",{className:"space-y-2",children:M.filter(ye=>Q.has(ye.id)).map(ye=>{var We;return i.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[i.jsxs("div",{onClick:()=>R(U===ye.id?null:ye.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm font-medium text-text-primary",children:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((We=X[ye.id])==null?void 0:We.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[I.progress[ye.id]==="probing"?i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):I.progress[ye.id]==="done"?i.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):I.progress[ye.id]==="error"?i.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):v?null:i.jsx("button",{onClick:oe=>{oe.stopPropagation(),tt(ye.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),M.length>1&&i.jsx("button",{onClick:oe=>{oe.stopPropagation();const fe=new Set(Q);fe.delete(ye.id),K(fe),U===ye.id&&R(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),i.jsx(hn,{className:`w-4 h-4 text-text-muted transition-transform ${U===ye.id?"rotate-180":""}`})]})]}),U===ye.id&&i.jsx(D7,{model:ye,modelConfigs:X,autoConfigState:I,testResults:q,onUpdateConfig:ae,onRunAutoConfig:tt,onTestParams:Nt,onShowRaw:re})]},ye.id)})})]}),M.length>1&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),Q.size===0&&i.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."}),i.jsxs("div",{className:"relative mb-2",children:[i.jsx("input",{type:"text",value:P,onChange:ye=>J(ye.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"}),P&&i.jsx("button",{onClick:()=>J(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",me(P).length," of ",M.length," models"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{const ye=new Set(Q),We=me(P);for(const oe of We)ye.add(oe.id);if(K(ye),$(oe=>{const fe={...oe};for(const Pe of We)fe[Pe.id]={contextWindow:Pe.contextWindow,...fe[Pe.id]};return fe}),!v)for(const oe of We)I.progress[oe.id]!=="probing"&&I.progress[oe.id]!=="done"&&tt(oe.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),i.jsx("button",{onClick:()=>{const ye=new Set(Q),We=me(P);for(const oe of We)ye.delete(oe.id);K(ye)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),i.jsxs("div",{className:"space-y-1 max-h-48 overflow-y-auto border border-border rounded-lg bg-bg-primary",children:[me(P).map(ye=>{var oe;const We=Q.has(ye.id);return i.jsxs("div",{role:"checkbox","aria-checked":We,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${We?"bg-accent-primary/5":""}`,onClick:()=>{if(We){const fe=new Set(Q);fe.delete(ye.id),K(fe)}else se(ye),v||tt(ye.id)},onKeyDown:fe=>{(fe.key==="Enter"||fe.key===" ")&&(fe.preventDefault(),fe.currentTarget.click())},children:[i.jsx("input",{type:"checkbox",checked:We,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),i.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:ye.name??ye.id.split("/").pop()}),i.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((oe=X[ye.id])==null?void 0:oe.contextWindow)??ye.contextWindow).toLocaleString()," ctx"]}),I.progress[ye.id]==="probing"&&i.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),I.progress[ye.id]==="done"&&i.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),I.progress[ye.id]==="error"&&i.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},ye.id)}),me(P).length===0&&i.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",P,"”"]})]})]})]})]}),i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[i.jsx("div",{children:u>1&&i.jsx("button",{onClick:()=>{u===2&&dt(),c(u-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:rn,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u===1?i.jsx("button",{onClick:()=>c(2),disabled:!p,"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"}):i.jsx("button",{onClick:Un,disabled:I.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:I.loading?"Configuring...":"Save Provider"})]})]})]}),H&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&W(!1)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),i.jsx("button",{onClick:()=>W(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsxs("div",{className:"px-6 py-4 space-y-4",children:[i.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),i.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),i.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"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",i.jsx("span",{className:"text-text-muted",children:"(override)"})]}),i.jsx("input",{type:"text",value:V,onChange:ye=>Z(ye.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"}),i.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)."})]})]}),i.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:i.jsx("button",{onClick:()=>W(!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"})})]})}),ne&&i.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:ye=>{ye.target===ye.currentTarget&&re(null)},children:i.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[80vh] shadow-2xl flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border shrink-0",children:[i.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),i.jsx("button",{onClick:()=>re(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),i.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:ne})]})})]}):null}function O7(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function I7(e,t){const n=t.toLowerCase(),r=(e.name??"").toLowerCase(),a=e.id.toLowerCase(),l=a.replace(/-/g," ");return r.includes(n)||a.includes(n)||l.includes(n)}function s1({activeProvider:e,shortModelName:t}){return i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-accent-primary",children:e?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"hidden sm:inline",children:[e.name," • "]}),t]}):t}),i.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 M7({providerId:e,modelConfig:t,isActive:n,isDefault:r,disabled:a,hasSession:l,settingDefault:u,highlighted:c,onModelClick:d,onSetDefault:h,onEditModel:p}){var m;return i.jsxs("div",{className:`flex items-center px-4 py-1.5 text-sm transition-colors group ${c?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${a?"opacity-50 cursor-wait":""} ${n?"text-accent-primary":"text-text-secondary"}`,children:[i.jsx("button",{type:"button",onClick:()=>d(e,t.id),disabled:a,className:"flex-1 truncate text-left",children:t.name??((m=t.id.split("/").pop())==null?void 0:m.replace(/-/g," "))??t.id}),i.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0 ml-2",children:[i.jsx("span",{className:"text-xs text-text-muted",children:O7(t.contextWindow)}),l&&i.jsx("button",{type:"button",onClick:x=>h(x,e,t.id),disabled:u,className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors disabled:opacity-40",title:r?"Default model":"Set as default model",children:r?i.jsx(I1,{className:"w-3.5 h-3.5 text-accent-warning"}):i.jsx(M1,{className:"w-3.5 h-3.5 text-text-muted hover:text-accent-warning"})}),i.jsx("button",{type:"button",onClick:x=>{x.stopPropagation(),p(e,t)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:i.jsx(A1,{className:"w-3 h-3 text-text-muted"})}),n&&i.jsx("span",{className:"text-accent-success flex-shrink-0",title:"Session model",children:i.jsx(Pr,{className:"w-3.5 h-3.5"})})]})]})}function P7(){var We;const[,e]=Tn(),t=Le(oe=>oe.currentSession),n=Le(oe=>oe.setSessionProvider),[r,a]=E.useState(!1),[l,u]=E.useState([]),[c,d]=E.useState(null),h=E.useRef(null),[p,m]=E.useState(null),[x,y]=E.useState(!1),[w,C]=E.useState({}),[_,S]=E.useState(null),[v,b]=E.useState(null),[j,N]=E.useState(!1),T=E.useRef(null),[D,L]=E.useState(!1),O=E.useRef(new Set),[M,G]=E.useState(-1),U=E.useRef(null),R=Xt(oe=>oe.providers),H=Xt(oe=>oe.activeProviderId),W=Xt(oe=>oe.defaultModelSelection),V=Xt(oe=>oe.activating),Z=Xt(oe=>oe.activateProvider),X=Xt(oe=>oe.refreshModel),$=Xt(oe=>oe.refreshProviderModels),I=Xt(oe=>oe.setDefaultModel),B=Xt(oe=>oe.fetchConfig),q=Ql();Pl(q.modelSelector,()=>a(oe=>!oe));const z=(t==null?void 0:t.providerId)??null,ne=(t==null?void 0:t.providerModel)??null,re=(W==null?void 0:W.split("/")[0])??null,Q=(W==null?void 0:W.split("/").slice(1).join("/"))??null,K=z??re,P=ne??Q,J=P?((We=P.split("/").pop())==null?void 0:We.replace(/-/g," "))??P:"No model",[ie,he]=E.useState(!1),[ce,De]=E.useState(""),Re=E.useRef(null);E.useEffect(()=>{function oe(fe){h.current&&!h.current.contains(fe.target)&&(a(!1),u([]),O.current=new Set)}return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]),E.useEffect(()=>()=>{T.current!==null&&window.clearTimeout(T.current)},[]),E.useEffect(()=>{r||(De(""),G(-1))},[r]),E.useEffect(()=>{var oe;r&&((oe=Re.current)==null||oe.focus())},[r]),E.useEffect(()=>{M>=0&&U.current&&U.current.scrollIntoView({block:"nearest"})},[M]),E.useEffect(()=>{if(r){const oe=R.map(fe=>fe.id);u(oe),R.filter(fe=>!!fe.authAdapter).forEach(fe=>void Ie(fe.id)),oe.forEach(fe=>{O.current.has(fe)||(O.current.add(fe),ot(fe))})}},[r,R]),E.useEffect(()=>{if(!v)return;let oe=!1;const fe=async()=>{const St=await Ie(v.providerId);oe||St==="connected"&&(b(null),N(!1),L(!1),await B(),O.current.delete(v.providerId),await ot(v.providerId))};fe();const Pe=window.setInterval(()=>void fe(),2e3);return()=>{oe=!0,window.clearInterval(Pe)}},[v]);const ze=R.find(oe=>oe.id===K),Fe=(ze==null?void 0:ze.status)==="disconnected",Ee=(oe,fe)=>t?t.providerId===oe&&t.providerModel===fe:!1,st=(oe,fe)=>W?W===`${oe}/${fe}`:!1,ot=async oe=>{d(oe);try{await $(oe)}catch{}finally{d(null)}},je=oe=>{l.includes(oe.id)?u(l.filter(fe=>fe!==oe.id)):(u([...l,oe.id]),ot(oe.id))},Me=async oe=>{if(oe.id===H){je(oe);return}t?(n(oe.id,void 0),a(!1),u([])):await Z(oe.id)&&(a(!1),u([]))},lt=oe=>{je(oe)},we=async(oe,fe)=>{oe.stopPropagation(),O.current.delete(fe),await ot(fe)},Ie=async oe=>{const fe=await ve(`/api/provider-auth/${oe}/status`);if(!fe.ok)return"error";const Pe=await fe.json();return C(St=>({...St,[oe]:Pe.state})),Pe.state},qe=async(oe,fe)=>{oe.stopPropagation(),S(fe),C(Pe=>({...Pe,[fe]:"pending"})),N(!1),L(!1);try{const Pe=await ve(`/api/provider-auth/${fe}/login`,{method:"POST"});if(!Pe.ok)throw new Error("Unable to start provider sign-in");const St=await Pe.json();b({providerId:fe,...St})}catch{C(Pe=>({...Pe,[fe]:"error"}))}finally{S(null)}},te=async()=>{var oe;v!=null&&v.userCode&&(await((oe=navigator.clipboard)==null?void 0:oe.writeText(v.userCode)),T.current!==null&&window.clearTimeout(T.current),N(!1),requestAnimationFrame(()=>N(!0)),T.current=window.setTimeout(()=>{N(!1),T.current=null},1500))},ae=()=>{v&&(window.open(v.directUrl??v.verificationUrl,"_blank","noopener,noreferrer"),L(!0))},se=()=>{b(null),N(!1),L(!1)},me=async(oe,fe)=>{oe.stopPropagation(),S(fe);try{if(!(await ve(`/api/provider-auth/${fe}/logout`,{method:"POST"})).ok)throw new Error("Unable to disconnect provider account");C(St=>({...St,[fe]:"disconnected"})),await B()}finally{S(null)}},Ue=(oe,fe)=>{m({providerId:oe,model:fe}),y(!0)},He=p?R.find(oe=>oe.id===p.providerId):void 0,Ye=()=>{m(null),y(!1)},ct=async oe=>{try{if(!(await ve(`/api/providers/${oe.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(kj(oe))})).ok)throw new Error("Failed to update provider");await Xt.getState().fetchConfig()}catch{}m(null),y(!1)},Je=async(oe,fe)=>{if(t){Le.setState(St=>({currentSession:St.currentSession?{...St.currentSession,providerId:oe,providerModel:fe}:null})),n(oe,fe),u([]),a(!1),Kl();return}await Z(oe)&&(u([]),a(!1),Kl())},Ze=async(oe,fe,Pe)=>{oe.stopPropagation(),he(!0);try{await I(fe,Pe)}catch{}finally{he(!1)}};function tt(oe){return oe.models.some(Pe=>Pe.selected)?oe.models.filter(Pe=>Pe.selected):oe.models}const Nt=E.useMemo(()=>ce.trim()?R.map(oe=>({provider:oe,models:tt(oe).filter(fe=>I7(fe,ce))})).filter(oe=>oe.models.length>0):R.map(oe=>({provider:oe,models:tt(oe)})),[R,ce]),dt=E.useMemo(()=>Nt.flatMap(oe=>oe.models.map(fe=>({providerId:oe.provider.id,modelConfig:fe}))),[Nt]),rn=dt.length+1,Un=M===dt.length;E.useEffect(()=>{rn===1?G(-1):M>=rn?G(rn-1):M<0&&ce.trim()&&G(0)},[rn,M,ce]);const ye=oe=>{switch(oe.key){case"Escape":a(!1);break;case"ArrowDown":oe.preventDefault(),rn>0&&G(fe=>fe<rn-1?fe+1:0);break;case"ArrowUp":oe.preventDefault(),rn>0&&G(fe=>fe>0?fe-1:rn-1);break;case"Home":oe.preventDefault(),G(0);break;case"End":oe.preventDefault(),G(rn-1);break;case"Enter":if(oe.preventDefault(),M===dt.length)e("/onboarding"),a(!1);else if(M>=0&&M<dt.length){const fe=dt[M];fe&&Je(fe.providerId,fe.modelConfig.id)}break}};return R.length===0?i.jsxs("button",{type:"button",onClick:()=>X(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:Fe?"LLM server is offline. Click to retry.":J??"Click to refresh model",children:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):i.jsx(s1,{activeProvider:ze,shortModelName:J}),i.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):i.jsxs("div",{className:"relative",ref:h,children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),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:[Fe?i.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):i.jsx(s1,{activeProvider:ze,shortModelName:J}),i.jsx(hn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:r?180:0})]}),r&&i.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:[i.jsxs("div",{className:"flex items-center gap-1 px-3 py-2 border-b border-border flex-shrink-0",children:[i.jsx(Qi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("input",{ref:Re,type:"text",value:ce,onInput:oe=>{De(oe.currentTarget.value),G(-1)},onKeyDown:ye,placeholder:"Search models...",className:"bg-transparent border-none outline-none text-sm text-text-primary w-full placeholder:text-text-muted"})]}),i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:i.jsxs("div",{children:[Nt.map(oe=>{const fe=ce.trim().length>0||l.includes(oe.provider.id);return i.jsxs("div",{children:[i.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${oe.provider.id===K?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${V?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[i.jsxs("div",{onClick:()=>!V&&Me(oe.provider),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[i.jsx("span",{className:`text-sm font-medium truncate ${oe.provider.id===K?"text-accent-primary":"text-text-primary"}`,children:oe.provider.name}),i.jsx("span",{className:"text-xs text-text-muted truncate",children:oe.provider.backend!=="unknown"&&v1(oe.provider.backend)})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!!oe.provider.authAdapter&&(w[oe.provider.id]==="connected"||oe.provider.credentialRef?i.jsx("button",{type:"button",onClick:Pe=>me(Pe,oe.provider.id),disabled:_===oe.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"}):i.jsx("button",{type:"button",onClick:Pe=>qe(Pe,oe.provider.id),disabled:_===oe.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:_===oe.provider.id?"Starting…":w[oe.provider.id]==="error"||w[oe.provider.id]==="expired"?"Retry":"Connect"})),oe.provider.id===K?i.jsx("span",{className:"text-accent-success",title:"Active provider",children:i.jsx(Pr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-4"}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),we(Pe,oe.provider.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:i.jsx(Td,{className:`w-4 h-4 ${c===oe.provider.id?"animate-spin":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})}),i.jsx("button",{type:"button",onClick:Pe=>{Pe.stopPropagation(),lt(oe.provider)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:i.jsx(hn,{className:`w-4 h-4 transition-transform ${fe?"rotate-180":""} ${oe.provider.id===H?"text-accent-primary":"text-text-muted"}`})})]})]}),fe&&i.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===oe.provider.id?i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):oe.models.length>0?oe.models.map(Pe=>{const bn=dt.findIndex(fn=>fn.providerId===oe.provider.id&&fn.modelConfig.id===Pe.id)===M;return i.jsx("div",{ref:bn?U:void 0,children:i.jsx(M7,{providerId:oe.provider.id,modelConfig:Pe,isActive:Ee(oe.provider.id,Pe.id),isDefault:st(oe.provider.id,Pe.id),disabled:c==="activating",hasSession:!!t,settingDefault:ie,highlighted:bn,onModelClick:Je,onSetDefault:Ze,onEditModel:Ue})},`${oe.provider.id}/${Pe.id}`)}):i.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},oe.provider.id)}),Nt.length===0&&ce.trim()&&i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No models match your search"})]})}),i.jsx("div",{className:`border-t border-border px-3 py-2 ${Un?"bg-bg-tertiary":""} flex-shrink-0`,children:i.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),v&&i.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/70 px-4",role:"dialog","aria-modal":"true","aria-labelledby":"provider-device-title",onMouseDown:oe=>{oe.target===oe.currentTarget&&se()},children:i.jsxs("div",{className:"w-full max-w-md rounded-xl border border-border bg-bg-secondary p-6 shadow-2xl",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{children:[i.jsx("h2",{id:"provider-device-title",className:"text-lg font-semibold text-text-primary",children:"Connect provider"}),i.jsx("p",{className:"mt-1 text-sm text-text-muted",children:"Follow the provider instructions to complete authorization."})]}),i.jsx("button",{type:"button",onClick:se,className:"rounded px-2 py-1 text-xl leading-none text-text-muted hover:bg-bg-tertiary hover:text-text-primary","aria-label":"Close",children:"×"})]}),v.mode!=="browser"?i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:te,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:v.userCode??"Continue"}),i.jsx("div",{className:"mt-3 text-center text-xs text-text-muted",children:j?"Copied to clipboard":"Click the code to copy it"}),i.jsxs("div",{className:"mt-6 flex gap-3",children:[i.jsx("button",{type:"button",onClick:te,className:"flex-1 rounded-lg border border-border px-4 py-2 text-sm text-text-primary hover:bg-bg-tertiary",children:j?"Copied":"Copy code"}),i.jsx("button",{type:"button",onClick:ae,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:D?"Reopen authorization":"Open authorization"})]}),i.jsx("p",{className:"mt-4 text-center text-xs text-text-muted",children:D?"If the browser blocked or closed the tab, reopen authorization.":"OpenFox stays open while you complete authorization in the other tab."})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"mt-6 text-sm text-text-secondary leading-relaxed bg-bg-primary p-4 rounded-lg border border-border",children:v.instructions}),i.jsx("div",{className:"mt-6 flex gap-3",children:i.jsx("button",{type:"button",onClick:ae,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:D?"Reopen authorization":"Open authorization"})})]})]})}),p&&x&&i.jsx(jj,{isOpen:!0,onClose:Ye,onSave:ct,initialStep:2,editProvider:{id:p.providerId,name:(He==null?void 0:He.name)??"",url:(He==null?void 0:He.url)??"",backend:(He==null?void 0:He.backend)??"unknown",apiKey:He==null?void 0:He.apiKey,isLocal:He==null?void 0:He.isLocal,thinkingField:He==null?void 0:He.thinkingField,authAdapter:He==null?void 0:He.authAdapter,transportAdapter:He==null?void 0:He.transportAdapter,models:He==null?void 0:He.models},editModelId:p.model.id})]})}function B7(){const e=Il(j=>j.servers),t=Il(j=>j.fetchServers),n=Le(j=>j.currentSession),r=n==null?void 0:n.id,[a,l]=E.useState(!1),[u,c]=E.useState(null),[d,h]=E.useState(new Set),[p,m]=E.useState(new Set),x=E.useRef(null),y=E.useCallback(async()=>{if(r)try{const j=await ve(`/api/sessions/${r}/mcp/overrides`);if(j.ok){const N=await j.json();m(new Set(N.disabledServers??[]))}}catch{}},[r]),w=E.useCallback(async()=>{await t(),await y()},[t,y]);E.useEffect(()=>{const j=()=>w();return window.addEventListener("mcp-servers-changed",j),()=>window.removeEventListener("mcp-servers-changed",j)},[w]),E.useEffect(()=>{y()},[y]),E.useEffect(()=>{a&&y()},[a,y]),th(x,()=>l(!1));const C=j=>p.has(j.name),_=e.filter(j=>j.status==="connected"&&!C(j)),S=_.length,v=_.reduce((j,N)=>j+N.estimatedTokens,0),b=async(j,N)=>{if(r){c(null),h(T=>new Set(T).add(j));try{const T=new Set(p);N?T.add(j):T.delete(j);const D=await ve(`/api/sessions/${r}/mcp/overrides`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({disabledServers:Array.from(T)})});if(!D.ok){const L=await D.json().catch(()=>({}));throw new Error(L.error??"Toggle failed")}m(T),await t()}catch(T){c(T instanceof Error?T.message:String(T))}finally{h(T=>{const D=new Set(T);return D.delete(j),D})}}};return i.jsxs("div",{className:"relative",ref:x,children:[i.jsxs("button",{type:"button",onClick:()=>l(!a),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:[i.jsx("span",{className:"text-sm text-accent-primary whitespace-nowrap",children:S>0?`● ${S} MCP (${xd(v)})`:"MCP"}),i.jsx(hn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:a?180:0})]}),a&&i.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:[i.jsx("div",{className:"overflow-y-auto flex-1 min-h-0",children:e.length===0?i.jsx("div",{className:"px-4 py-3 text-sm text-text-muted text-center",children:"No MCP servers configured"}):e.map(j=>{const N=C(j),T=d.has(j.name);return i.jsx("div",{children:i.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-bg-tertiary",children:[i.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[i.jsx("span",{className:`text-sm ${Xg(N?"disabled":j.status)}`,children:Qg(N?"disabled":j.status)}),i.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:j.name})]}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted ml-3.5",children:[i.jsxs("span",{children:[j.tools.length," tools"]}),j.estimatedTokens>0&&i.jsxs("span",{children:[xd(j.estimatedTokens)," tokens"]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[T&&i.jsx("span",{className:"text-xs text-text-muted animate-pulse",children:"..."}),i.jsx(Yr,{enabled:!N,onClick:()=>b(j.name,!N)})]})]})},j.name)})}),i.jsx("div",{className:"border-t border-border px-3 py-2 flex-shrink-0",children:u?i.jsx("div",{className:"text-xs text-accent-error",children:u}):i.jsxs("span",{className:"text-xs text-text-muted",children:[e.length," server(s) configured"]})})]})]})}function $7(e,t){const n=e.slice(0,t),r=n.lastIndexOf("@");if(r===-1)return null;const a=n.slice(r+1);return a.includes(" ")||a.includes(`
319
319
  `)||a.includes(" ")?null:{query:a,startIndex:r}}const z7=E.forwardRef(function({text:t,cursorPos:n,workdir:r,onSelect:a},l){const u=$7(t,n),[c,d]=E.useState([]),[h,p]=E.useState(!1),[m,x]=E.useState(0),y=E.useRef(null),w=E.useRef([]),C=E.useRef(0),_=E.useRef([]);E.useEffect(()=>{C.current=m},[m]),E.useEffect(()=>{_.current=c},[c]),E.useEffect(()=>{if(!u){d([]);return}const b=setTimeout(()=>{S(u.query)},150);return()=>clearTimeout(b)},[u==null?void 0:u.query,r]);const S=async b=>{p(!0);try{const j=new URLSearchParams({q:b});r&&j.set("workdir",r);const T=await(await ve(`/api/files?${j.toString()}`)).json();d(T),x(0),C.current=0}catch(j){console.error("File search failed:",j),d([])}finally{p(!1)}},v=E.useCallback(b=>{if(!u)return!1;switch(b.key){case"ArrowDown":return b.preventDefault(),x(j=>{var T;const N=Math.min(j+1,_.current.length-1);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.min(C.current+1,_.current.length-1),!0;case"ArrowUp":return b.preventDefault(),x(j=>{var T;const N=Math.max(j-1,0);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.max(C.current-1,0),!0;case"Enter":case"Tab":{const j=_.current;return j[C.current]?(b.preventDefault(),a(j[C.current],u.startIndex),!0):!1}case"Escape":return b.preventDefault(),d([]),!0}return!1},[u,a]);return E.useImperativeHandle(l,()=>({handleKeyDown:v}),[v]),E.useEffect(()=>{if(!u)return;const b=j=>{y.current&&!y.current.contains(j.target)&&d([])};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[u]),u?h?i.jsx("div",{className:"absolute bottom-full left-0 right-0 mb-2 z-50",children:i.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg",children:i.jsx("div",{className:"p-4 text-center",children:i.jsx(gi,{size:"sm"})})})}):c.length===0?null:i.jsx("div",{ref:y,className:"absolute bottom-full left-0 right-0 mb-2 z-50",children:i.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg max-h-64 overflow-y-auto",children:i.jsx("ul",{children:c.map((b,j)=>i.jsxs("li",{ref:N=>{w.current[j]=N},className:`px-3 py-2 cursor-pointer flex items-center gap-2 text-sm ${j===m?"bg-accent-primary/20 text-text-primary":"text-text-muted hover:bg-bg-tertiary"}`,onClick:()=>{u&&a(b,u.startIndex)},children:[b.type==="directory"?i.jsx(jr,{className:"w-4 h-4 shrink-0"}):i.jsx("span",{className:"w-4 h-4 shrink-0"}),i.jsx("span",{className:"truncate",children:b.path})]},b.path))})})}):null});function H7(e,t){const n=e.slice(0,t);if(n.length===0||n[0]!=="/")return null;const r=n.slice(1);return r.includes(" ")||r.includes(`
320
320
  `)||r.includes(" ")?null:{query:r,startIndex:0}}const U7=E.forwardRef(function({text:t,cursorPos:n,workflows:r,commands:a,onSelect:l},u){const c=H7(t,n),[d,h]=E.useState(0),p=E.useRef(null),m=E.useRef([]),x=E.useRef(0),y=E.useRef([]);E.useEffect(()=>{x.current=d},[d]),E.useEffect(()=>{y.current=C});const w=(c==null?void 0:c.query)??"",C=(()=>{if(!c)return[];const S=w.toLowerCase(),v=r.filter(j=>j.id.toLowerCase().includes(S)||j.name.toLowerCase().includes(S)).map(j=>({type:"workflow",id:j.id,name:j.name,paramCount:(j.parameters??[]).length})),b=a.filter(j=>j.id.toLowerCase().includes(S)||j.name.toLowerCase().includes(S)).map(j=>({type:"command",id:j.id,name:j.name,paramCount:0}));return[...v,...b]})();E.useEffect(()=>{h(0),x.current=0},[C.length]);const _=E.useCallback(S=>{if(!c||C.length===0)return!1;switch(S.key){case"ArrowDown":return S.preventDefault(),h(v=>{var j;const b=Math.min(v+1,C.length-1);return(j=m.current[b])==null||j.scrollIntoView({block:"nearest"}),b}),!0;case"ArrowUp":return S.preventDefault(),h(v=>{var j;const b=Math.max(v-1,0);return(j=m.current[b])==null||j.scrollIntoView({block:"nearest"}),b}),!0;case"Enter":case"Tab":{const v=C[x.current];return v?(S.preventDefault(),l(v,c.startIndex),!0):!1}case"Escape":return S.preventDefault(),!0}return!1},[c,C,l]);return E.useImperativeHandle(u,()=>({handleKeyDown:_}),[_]),!c||C.length===0?null:i.jsx("div",{ref:p,className:"absolute bottom-full left-0 right-0 mb-2 z-50",role:"listbox",children:i.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg max-h-64 overflow-y-auto",children:i.jsx("div",{children:C.map((S,v)=>i.jsxs("button",{ref:b=>{m.current[v]=b},role:"option","aria-selected":v===d,className:`w-full text-left px-3 py-2 flex items-center gap-2 text-sm ${v===d?"bg-accent-primary/20 text-text-primary":"text-text-muted hover:bg-bg-tertiary"}`,onClick:()=>{c&&l(S,c.startIndex)},children:[i.jsxs("span",{className:`font-medium ${S.type==="workflow"?"text-accent-primary":"text-accent-warning"}`,children:["/",S.id]}),i.jsx("span",{className:"truncate flex-1",children:S.name}),S.paramCount>0&&i.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary px-1.5 py-0.5 rounded",children:[S.paramCount," param",S.paramCount>1?"s":""]})]},`${S.type}-${S.id}`))})})})});function F7({input:e,setInput:t,attachments:n,setAttachments:r,dragOver:a,setDragOver:l,errorMessage:u,setErrorMessage:c,scrollContainerRef:d,sessionId:h,showHistory:p,history:m,selectedIndex:x,openHistory:y,closeHistory:w,navigateUp:C,navigateDown:_,selectCurrent:S,isAutoScrollActive:v,setAutoScroll:b,onOpenMessageSearch:j,onOpenCommandsModal:N,onOpenWorkflowsModal:T,onSelectWorkflow:D,onSelectWorkflowWithSubGroup:L,onSendCommand:O,clearInput:M}){const G=E.useRef(null),U=E.useRef(null),R=E.useRef(0),H=E.useRef(0),W=E.useRef(null),V=E.useRef(null),Z=Nd(),X=Le(se=>se.stopGeneration),$=Le(se=>se.cancelQueued),I=Le(se=>se.queuedMessages),B=Le(se=>se.restoredInput),q=Le(se=>se.clearRestoredInput),z=Le(se=>{var me;return(me=se.currentSession)==null?void 0:me.workdir}),ne=Le(se=>se.currentSession),re=E.useRef(!1),Q=E.useRef(!1),K=E.useRef(!1),[P,J]=E.useState([]),{sendMessage:ie,launchWorkflow:he}=Cj(b);E.useEffect(()=>{if(Q.current)return;Q.current=!0;const se=vt.getState();se.defaults.length===0&&se.userItems.length===0&&se.projectItems.length===0&&se.fetchWorkflows();const me=Yt.getState();me.defaults.length===0&&me.userItems.length===0&&me.projectItems.length===0&&me.fetchCommands()},[]),E.useEffect(()=>{e||J([])},[e]),E.useEffect(()=>{var se;B!==null&&(t(B),q(),(se=G.current)==null||se.focus())},[B,t,q]);const ce=E.useCallback(()=>{const se=G.current;if(!se)return;const me=e.length>=R.current;R.current=e.length,me||(se.style.height="auto"),se.style.height=`${Math.min(200,se.scrollHeight)}px`},[e]);E.useEffect(()=>{if(!h)return;const se=`openfox:draft:${h}`,me=localStorage.getItem(se);me!==null&&t(me)},[h,t]),E.useEffect(()=>{var se;(se=G.current)==null||se.focus(),ce()},[h,ce]),E.useEffect(()=>{if(!h)return;const se=`openfox:draft:${h}`,me=setTimeout(()=>{e?localStorage.setItem(se,e):localStorage.removeItem(se)},500);return()=>clearTimeout(me)},[h,e]),E.useEffect(()=>{ce()},[e,ce]),E.useEffect(()=>{const se=G.current;if(!se)return;const me=async Ue=>{var ct;if(document.activeElement!==se)return;const He=(ct=Ue.clipboardData)==null?void 0:ct.items;if(!He)return;const Ye=[];for(const Je of Array.from(He)){let Ze=Je.getAsFile();if(Ze&&v$(Ze.type)){if(Ue.preventDefault(),!Ze.name){const tt=b$(Ze.type);Ze=new File([Ze],`pasted-file.${tt}`,{type:Ze.type})}await t1(Ze,tt=>Ye.push(tt),c)}}Ye.length>0&&r(Je=>[...Je,...Ye])};return se.addEventListener("paste",me),()=>se.removeEventListener("paste",me)},[r,c]);const De=se=>{se.preventDefault(),!(!e.trim()&&n.length===0)&&lt()},Re=se=>{var me,Ue;if(!((me=V.current)!=null&&me.handleKeyDown(se))&&!((Ue=W.current)!=null&&Ue.handleKeyDown(se))){if(p)switch(se.key){case"Enter":{se.preventDefault();const He=S();He&&(t(He),w());return}case"Escape":se.preventDefault(),w(),Z&&X();return;case"ArrowUp":se.preventDefault(),C();return;case"ArrowDown":se.preventDefault(),_();return}if(se.key==="ArrowUp"&&e.trim()===""&&!p){se.preventDefault(),y();return}se.key==="Enter"&&!se.shiftKey&&(se.preventDefault(),De(se))}};async function ze(se,me,Ue){const He=[];for(const Ye of Array.from(se))await t1(Ye,ct=>He.push(ct),Ue);He.length>0&&me(Ye=>[...Ye,...He])}const Fe=E.useCallback(async se=>{const me=se.target.files;!me||me.length===0||(c(null),await ze(me,r,c),U.current&&(U.current.value=""))},[r,c]),Ee=E.useCallback(se=>{var me;(me=se.dataTransfer.types)!=null&&me.includes("Files")&&(se.preventDefault(),se.stopPropagation(),l(!0))},[l]),st=E.useCallback(se=>{se.preventDefault(),se.stopPropagation(),l(!1)},[l]),ot=E.useCallback(async se=>{se.preventDefault(),se.stopPropagation(),l(!1),c(null);const me=se.dataTransfer.files;!me||me.length===0||await ze(me,r,c)},[r,l,c]),je=E.useCallback(se=>{r(n.filter(me=>me.id!==se))},[n,r]),Me=E.useCallback(()=>{var se;(se=U.current)==null||se.click()},[]),lt=()=>{var me;if(K.current||!e.trim()&&n.length===0)return;if(K.current=!0,(me=d.current)==null||me.scrollTo({top:d.current.scrollHeight,behavior:"smooth"}),e.trim().startsWith("/")){const Ue=vt.getState(),He=[...Ue.defaults,...Ue.userItems,...Ue.projectItems],Ye=Yt.getState(),ct=[...Ye.defaults,...Ye.userItems,...Ye.projectItems],Je=t7(e,He,ct);if(Je!=null&&Je.workflowId){const Ze=He.find(Nt=>Nt.id===Je.workflowId),tt=((Ze==null?void 0:Ze.parameters)??[]).filter(Nt=>Nt.required&&!(Nt.id in Je.params));if(tt.length>0){const Nt=tt.map(dt=>dt.label||dt.id).join(", ");c(`Missing required parameter${tt.length>1?"s":""}: ${Nt}`),K.current=!1;return}he(void 0,void 0,Je.workflowId,void 0,Je.params),M(),K.current=!1;return}if(Je!=null&&Je.commandId){Ye.fetchCommand(Je.commandId).then(Ze=>{if(Ze){const tt=Sj(Ze.prompt),Nt={};for(const[rn,Un]of Object.entries(Je.params)){const ye=parseInt(rn,10),We=tt[ye];We&&(Nt[We]=Un)}let dt=Ze.prompt;for(const[rn,Un]of Object.entries(Nt))dt=dt.replaceAll(`{{${rn}}}`,Un);ie(dt,void 0),M()}K.current=!1});return}M(),K.current=!1;return}ie(e,n),M(),K.current=!1},we=E.useCallback((se,me)=>{const He=se.type==="directory"?"/":" ",Ye=e.slice(0,me),ct=e.slice(H.current),Je=`${Ye}@${se.path}${He}${ct}`;t(Je);const Ze=me+se.path.length+2;H.current=Ze,G.current&&(G.current.selectionStart=Ze,G.current.selectionEnd=Ze,G.current.focus())},[e,t]),Ie=E.useCallback((se,me)=>{const Ue=e.slice(0,me),He=e.slice(H.current),Ye=`${Ue}/${se.id} ${He}`;t(Ye);const ct=me+se.id.length+2;if(H.current=ct,G.current&&(G.current.selectionStart=ct,G.current.selectionEnd=ct,G.current.focus()),se.type==="workflow"){const Je=[...vt.getState().defaults,...vt.getState().userItems,...vt.getState().projectItems].find(Ze=>Ze.id===se.id);J(((Je==null?void 0:Je.parameters)??[]).map(Ze=>Ze.id))}else{const Je=Yt.getState(),Ze=[...Je.defaults,...Je.userItems,...Je.projectItems].find(tt=>tt.id===se.id);J((Ze==null?void 0:Ze.paramNames)??[])}},[e,t]),qe=E.useCallback(se=>{const me=se.target.value;t(me),p&&w(),H.current=se.target.selectionStart,P.length>0&&(!me.startsWith("/")||!me.includes(" "))&&J([]),!re.current&&h&&me&&ne&&ne.messages.length===0&&(re.current=!0,ve(`/api/sessions/${h}/warmup`,{method:"POST"}).catch(()=>{}))},[t,p,w,h,ne,P]),te=E.useCallback(se=>{H.current=se.target.selectionStart},[]),ae=E.useCallback(se=>{H.current=se.currentTarget.selectionStart},[]);return i.jsxs("div",{className:"relative",children:[Z&&i.jsx("div",{className:"absolute -top-8 left-2 md:left-4 z-10",children:i.jsx(s7,{})}),i.jsxs("div",{className:`absolute -top-8 right-2 md:right-4 z-10 flex items-center gap-2 border${v?" border-transparent":" rounded backdrop-blur-xl saturate-150 border-border"}`,children:[i.jsx(ex,{isActive:v,onToggle:b,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"}),i.jsxs("button",{type:"button",onClick:j,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:[i.jsx(Qi,{}),"Browse history"]})]}),i.jsx(i7,{}),i.jsxs("form",{onSubmit:De,className:"p-2 md:p-4 bg-secondary rounded-lg",children:[i.jsx("input",{ref:U,type:"file",accept:"image/*,text/*,.pdf,.json,.xml,.yaml,.yml,.js,.sh,.xhtml",onChange:Fe,className:"hidden",multiple:!0}),u&&i.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:u}),n.length>0&&i.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:n.map(se=>i.jsx(n7,{attachment:se,onRemove:je},se.id))}),p&&i.jsx(r7,{history:m,selectedIndex:x,onSelect:se=>{t(se),w()},onEscape:w,onNavigate:se=>{se==="up"?C():_()}}),i.jsx(w7,{messages:I,onCancel:$}),i.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${a?"bg-accent-primary/10":"bg-primary"}`,onDragOver:Ee,onDragLeave:st,onDrop:ot,children:[i.jsxs("div",{className:"relative flex-1 min-w-0",children:[i.jsx("textarea",{id:Rk,ref:G,value:e,onChange:qe,onKeyDown:Re,onSelect:te,onKeyUp:ae,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:"24px",maxHeight:"200px"},spellCheck:!1}),i.jsx(z7,{ref:W,text:e,cursorPos:H.current,workdir:z,onSelect:we}),i.jsx(U7,{ref:V,text:e,cursorPos:H.current,workflows:(()=>{const se=vt.getState();return[...se.defaults,...se.userItems,...se.projectItems]})(),commands:(()=>{const se=Yt.getState();return[...se.defaults,...se.userItems,...se.projectItems]})(),onSelect:Ie}),P.length>0&&(()=>{const se=e.match(/\/(\w+)\s+(.*)$/),Ue=(se?se[2].trim().split(/\s+/):[]).filter(Boolean).length,He=P[Ue];return He?i.jsxs("span",{className:"absolute left-3 top-[26px] text-sm text-text-muted/40 pointer-events-none select-none","aria-hidden":!0,children:[He,"=?"]}):null})()]}),i.jsxs("div",{className:"flex items-center self-center gap-1.5",children:[Z&&i.jsxs("button",{type:"button",onClick:()=>X(),"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:[i.jsx(ug,{}),"Abort"]}),i.jsxs("div",{className:"flex items-center",children:[i.jsx("button",{type:"button",onClick:lt,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"}),i.jsx(_7,{onSendCommand:O,onSelectWorkflow:D,onSelectWorkflowWithSubGroup:L,onOpenCommandsManager:N,onOpenWorkflowsManager:T,onAttach:Me,textareaContent:e,attachments:n.length>0?n:void 0})]})]})]}),i.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(T7,{}),i.jsx(A7,{})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[Ft(se=>se.settings)[Te.FEATURES_PER_SESSION_MCP]==="true"&&i.jsx(B7,{}),i.jsx(P7,{})]})]})]})]})}function i1({workflowName:e,parameters:t,onConfirm:n,onCancel:r,confirmLabel:a="Run workflow"}){const[l,u]=E.useState({}),c=[...t].sort((p,m)=>(p.position??0)-(m.position??0)),d=()=>{var m;const p={};for(const x of c){const y=(m=l[x.id])==null?void 0:m.trim();y&&(p[x.id]=y)}n(p)},h=c.every(p=>{var m;return!p.required||(((m=l[p.id])==null?void 0:m.trim())??"")!==""});return i.jsxs(jt,{isOpen:!0,onClose:r,title:`Run: ${e}`,size:"sm",closeOnEscape:!0,closeOnBackdropClick:!0,children:[i.jsx("div",{className:"space-y-3 py-2",children:c.map(p=>i.jsxs("label",{className:"block",children:[i.jsxs("span",{className:"text-sm text-text-primary font-medium",children:[p.label||p.id,p.required&&i.jsx("span",{className:"text-accent-error ml-1",children:"*"})]}),p.description&&i.jsx("span",{className:"block text-xs text-text-muted mt-0.5",children:p.description}),i.jsx("input",{value:l[p.id]??"",onChange:m=>u(x=>({...x,[p.id]:m.target.value})),placeholder:p.label||p.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:p.position===0||p===c[0]})]},p.id))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border",children:[i.jsx("button",{onClick:r,className:"px-3 py-1.5 text-sm text-text-muted hover:text-text-primary transition-colors",children:"Cancel"}),i.jsx("button",{onClick:d,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:a})]})]})}const a1=9999,Vu=E.forwardRef(function({trigger:t,children:n},r){const[a,l]=E.useState(!1),u=E.useRef(null),c=E.useRef(null),d=E.useRef(null),h=E.useCallback(()=>{l(!1)},[]);E.useImperativeHandle(r,()=>({close:h}),[h]);const p=E.useCallback(m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),a?h():(d.current=document.activeElement,l(!0))),m.key==="Escape"&&a&&h()},[a,h]);return E.useEffect(()=>{var w;if(!a){(w=d.current)==null||w.focus(),d.current=null;return}const m=C=>{c.current&&!c.current.contains(C.target)&&u.current&&!u.current.contains(C.target)&&h()},x=C=>{C.key==="Escape"&&h()},y=()=>h();return document.addEventListener("mousedown",m),document.addEventListener("keydown",x),window.addEventListener("blur",y),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",x),window.removeEventListener("blur",y)}},[a,h]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:u,role:"button",tabIndex:0,"aria-expanded":a,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:()=>{a||(d.current=document.activeElement),l(m=>!m)},onKeyDown:p,children:t}),a&&pi.createPortal(i.jsx("div",{ref:c,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] overflow-y-auto",style:(()=>{if(!u.current)return{zIndex:a1,top:0,left:0};const m=u.current.getBoundingClientRect(),x=320,y=8;let w=m.left;return w+x>window.innerWidth-y&&(w=m.right-x),w=Math.max(y,Math.min(w,window.innerWidth-x-y)),{zIndex:a1,top:m.bottom+4,left:w}})(),children:n}),document.body)]})});function V7({entries:e}){const t=new Map;for(const r of e)t.set(r.status,(t.get(r.status)??0)+1);const n=Wk.filter(r=>(t.get(r)??0)>0);return n.length===0?i.jsx("span",{className:"text-text-muted text-sm",children:"None"}):i.jsx("span",{className:"flex items-center gap-1.5 text-sm",children:n.map(r=>i.jsxs("span",{className:"flex items-center gap-0.5",children:[i.jsx(bo,{status:r}),i.jsx("span",{className:"text-text-muted",children:t.get(r)})]},r))})}function W7({visible:e}){const t=Le(P=>P.currentSession),n=Dn(P=>P.status),r=Dn(P=>P.config),a=Dn(P=>P.start),l=Le(P=>P.contextState),u=Le(P=>P.queueUpdate),c=Dn(P=>P.logs),{branch:d,diff:h}=Jg(),[p,m]=E.useState(!1),[x,y]=E.useState(!1),[w,C]=E.useState(!1),[_,S]=E.useState(null),[v,b]=E.useState(!1),[j,N]=E.useState(!1),T=E.useRef(null),D=E.useRef(null),L=E.useRef(null),O=E.useRef(null),M=Ft(P=>P.settings[Te.DISPLAY_SHOW_OPEN_IN_EDITOR])==="true";if(!e||!t)return null;const G=t.workspace?t.workspace.split("/").pop()??"original":"original",U=t.workspace??t.workdir,R=t.metadataEntries??{},H=R.criteria??[],W=["review_findings","todos"],V=W.filter(P=>{var J;return P in R&&(((J=R[P])==null?void 0:J.length)??0)>0}),Z=Object.keys(R).filter(P=>P!=="criteria"&&!W.includes(P)).filter(P=>{var J;return(((J=R[P])==null?void 0:J.length)??0)>0}),X=[...V,...Z].reduce((P,J)=>{var ie;return P+(((ie=R[J])==null?void 0:ie.length)??0)},0),$=[...V,...Z].map(io),I=h.files,B=I.reduce((P,J)=>P+J.additions,0),q=I.reduce((P,J)=>P+J.deletions,0),z=(n==null?void 0:n.state)??"off",ne=z==="running"||z==="warning",re=r!==null,Q=P=>{P.stopPropagation(),a()},K=P=>{P.stopPropagation(),n!=null&&n.url&&window.open(n.url,"_blank")};return i.jsxs("div",{className:"flex-shrink-0 px-4 py-1.5 border-b border-border bg-secondary",children:[i.jsxs("div",{className:"grid grid-cols-2 sm:flex sm:items-center sm:justify-between gap-x-2 gap-y-1 text-sm",children:[i.jsxs("div",{className:"flex items-center gap-1 min-w-0 sm:shrink-0",children:[i.jsx(jr,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary max-w-[120px]",children:G}),i.jsx("span",{className:"text-text-muted",children:"/"}),i.jsx(Yi,{className:"w-3.5 h-3.5 text-text-muted flex-shrink-0"}),i.jsx("span",{className:"truncate text-text-secondary max-w-[120px]",children:d??"-"}),I.length>0?i.jsxs("span",{className:"text-text-muted shrink-0 font-mono",children:["+",B," -",q]}):i.jsx("span",{className:"shrink-0"}),i.jsx(Vu,{ref:O,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(aj,{workspaceName:G,branch:d,workdir:U,showEditorLink:M,sessionId:t.id,projectId:t.projectId,onEditWorkspace:()=>{var P;(P=O.current)==null||P.close(),b(!0)},onEditBranch:()=>{var P;(P=O.current)==null||P.close(),N(!0)}})})]}),i.jsx("div",{className:"hidden sm:block w-px bg-border self-stretch mx-1"}),i.jsxs("div",{className:"flex-1 flex items-center sm:justify-center justify-self-end gap-1 min-w-0",children:[i.jsx(V7,{entries:H}),X>0&&i.jsxs("span",{className:"text-text-muted text-xs bg-bg-tertiary px-1 py-0.5 rounded leading-none",title:$.join(", "),children:["+",X]}),i.jsx(Vu,{ref:L,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var P;(P=L.current)==null||P.close(),S("criteria")},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(vd,{entries:H,title:"Acceptance Criteria"})}),i.jsx(Kk,{entries:H,sessionId:t.id})]}),[...V,...Z].map(P=>{const J=R[P];return i.jsxs("div",{children:[i.jsx("button",{onClick:()=>{var ie;(ie=L.current)==null||ie.close(),S(P)},className:"w-full text-left cursor-pointer hover:[&_h3]:text-accent-primary transition-colors",children:i.jsx(vd,{entries:J,title:io(P)})}),i.jsx(Gk,{entries:J})]},P)})]})})]}),i.jsx("div",{className:"hidden sm:block w-px bg-border self-stretch mx-1"}),i.jsx("div",{className:"col-span-2 border-t border-border sm:hidden -mx-4"}),i.jsx("div",{className:"flex items-center gap-1.5 min-w-0 shrink-0",children:l&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-muted text-xs font-mono tabular-nums",children:l.currentTokens>=1e3?`${Math.round(l.currentTokens/1e3)}K`:l.currentTokens}),i.jsx(nx,{percent:Math.round(l.currentTokens/l.maxTokens*100),dangerZone:l.dangerZone,size:"sm"}),i.jsx(Vu,{ref:D,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(lj,{onUpdateSystemPrompt:()=>{var P;(P=D.current)==null||P.close(),C(!0)}})})]})}),i.jsx("div",{className:"hidden sm:block w-px bg-border self-stretch mx-1"}),i.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 shrink-0 justify-self-end",children:[i.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${z==="running"?"bg-accent-success":z==="warning"?"bg-accent-warning":z==="error"?"bg-accent-error":"bg-text-muted"}`}),re?ne?i.jsx("button",{onClick:K,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:i.jsx(R1,{className:"w-3.5 h-3.5"})}):i.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:i.jsx(O1,{className:"w-3.5 h-3.5"})}):i.jsx("span",{className:"text-text-muted text-xs",children:"No config"}),i.jsx(Vu,{ref:T,trigger:i.jsx(hn,{className:"w-3 h-3"}),children:i.jsx(Qk,{workdir:U,compact:!0,onExpand:()=>m(!0),onConfigure:()=>{var P;(P=T.current)==null||P.close(),y(!0)}})})]})]}),p&&i.jsx(tx,{title:"Dev Server Logs",logs:c,onClose:()=>m(!1)}),x&&i.jsx(Yk,{isOpen:!0,onClose:()=>y(!1)}),_&&t&&i.jsx(qk,{isOpen:!0,onClose:()=>S(null),entries:R[_]??[],sessionId:t.id,metadataKey:_,title:io(_)}),v&&i.jsx(sj,{isOpen:!0,onClose:()=>b(!1),projectId:t.projectId,sessionId:t.id,currentWorkspace:G,currentBranch:d}),j&&i.jsx(ij,{isOpen:!0,onClose:()=>N(!1),sessionId:t.id}),w&&l&&i.jsx(rx,{isOpen:!0,onClose:()=>C(!1),isRunning:t.isRunning,onApply:()=>{t.isRunning?u():Dt.send("context.applyDynamic",{}),C(!1)}})]})}function G7(e){return(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="f"&&document.querySelector("[data-global-settings]")===null}function Ej(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 a=[];let l,u=1,c=null;const d=()=>{if(!c||c.size===0)return;const h=new Map;let p=0;for(const x of e)x.role!=="tool"&&x.contextWindowId===l&&(x.subAgentId&&!h.has(x.subAgentId)&&h.set(x.subAgentId,p),p++);const m=[...c.entries()].sort((x,y)=>(h.get(x[0])??0)-(h.get(y[0])??0));for(const[x,y]of m){const w=r.get(x);(w==null?void 0:w.type)==="subagent"&&w.messages.length===y.messages.length&&w.messages.every((_,S)=>_===y.messages[S])?a.push(w):a.push({type:"subagent",subAgentId:x,subAgentType:y.subAgentType,messages:y.messages})}c=null};for(let h=0;h<e.length;h++){const p=e[h];if(p.role!=="tool")if(p.contextWindowId&&l&&p.contextWindowId!==l&&(d(),u++,a.push({type:"context-divider",windowSequence:u})),l=p.contextWindowId,p.subAgentId&&p.subAgentType){c||(c=new Map);let m=c.get(p.subAgentId);m||(m={subAgentType:p.subAgentType,messages:[]},c.set(p.subAgentId,m)),m.messages.push(p)}else{d();const m=n.get(p.id);(m==null?void 0:m.type)==="message"&&m.message===p?a.push(m):a.push({type:"message",message:p})}}return d(),a}const q7=10,K7=150;function Y7(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 X7(e){return[...e].sort((r,a)=>new Date(a.timestamp).getTime()-new Date(r.timestamp).getTime()).slice(0,q7).reverse().map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,formattedTimestamp:cB(r.timestamp),trimmedContent:yd(r.content,K7),sessionId:r.sessionId,sessionName:r.sessionName}))}function Q7(e,t,n){const r=[],a=e.filter(l=>l.role==="user"&&!l.isSystemGenerated&&l.messageKind!=="auto-prompt");for(const l of a)r.push({id:l.id,content:l.content,timestamp:l.timestamp,sessionId:n??"",sessionName:"This session"});for(const l of t)n&&l.id===n||r.push(...Y7(l));return X7(r)}function J7(e,t=[],n=null){const[r,a]=E.useState(0),[l,u]=E.useState(!1),c=E.useMemo(()=>Q7(e,t,n),[e,t,n]),d=E.useCallback(()=>{c.length>0&&(a(c.length-1),u(!0))},[c.length]),h=E.useCallback(()=>{u(!1),a(0)},[]),p=E.useCallback(()=>{a(y=>c.length===0?y:y===0?c.length-1:y-1)},[c.length]),m=E.useCallback(()=>{a(y=>c.length===0?y:y===c.length-1?0:y+1)},[c.length]),x=E.useCallback(()=>{if(c.length===0||!l)return null;const y=c[r];return(y==null?void 0:y.content)??null},[c,r,l]);return{history:c,selectedIndex:r,showHistory:l,openHistory:d,closeHistory:h,navigateUp:p,navigateDown:m,selectCurrent:x}}E.memo(function({item:t}){const[n,r]=E.useState(!1);return t.type==="start"?i.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:[i.jsx("span",{className:"animate-pulse",children:"●"}),i.jsx("span",{children:"Delegating image to fallback vision model..."}),t.filename&&i.jsxs("span",{className:"text-amber-400/70",children:["(",t.filename,")"]})]}):i.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-accent-success/10 border border-accent-success/30 rounded",children:[i.jsx("span",{className:"text-accent-success",children:"✓"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"text-accent-success text-sm",children:"Image description done"}),i.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&&i.jsx("div",{className:"mt-2 text-xs prose prose-invert prose-sm max-w-none",children:i.jsx(zn,{content:t.description})})]})]})});function Z7({criteriaSidebarOpen:e,onCriteriaSidebarToggle:t,rawMessages:n,hiddenCount:r}={}){const a=e??!0,[l,u]=E.useState(""),[c,d]=E.useState([]),[h,p]=E.useState(!1),[m,x]=E.useState(null),[y,w]=E.useState(!1),[C,_]=E.useState(!1),[S,v]=E.useState(!1),[b,j]=E.useState(!1),[N,T]=E.useState(null),D=E.useRef(null),L=Le(te=>te.currentSession),O=Le(te=>te.messages),M=Le(te=>te.sessions),G=Nd(),U=Le(te=>te.stopGeneration),R=n??O,{maxVisibleItems:H}=ea(),W=xt(te=>te.defaults),V=xt(te=>te.userItems),Z=[...W,...V].filter(te=>!te.subagent),{history:X,selectedIndex:$,showHistory:I,openHistory:B,closeHistory:q,navigateUp:z,navigateDown:ne,selectCurrent:re}=J7(R,M,L==null?void 0:L.id);E.useEffect(()=>{const te=ae=>{T(ae.detail.stats)};return window.addEventListener("open-turn-stats",te),()=>window.removeEventListener("open-turn-stats",te)},[]),E.useEffect(()=>{vt.getState().fetchWorkflows()},[]),E.useEffect(()=>{const te=ae=>{G7(ae)&&(ae.preventDefault(),j(!0))};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[]);const Q=E.useRef([]),{displayItems:K,hiddenCount:P}=E.useMemo(()=>{const te=Ej(R,Q.current);return Q.current=te,H>0&&te.length>H?{displayItems:te.slice(-H),hiddenCount:te.length-H}:{displayItems:te,hiddenCount:0}},[R,H]),J=r??P,{isAutoScrollActive:ie,setAutoScroll:he}=eh(D,L),{sendMessage:ce,launchWorkflow:De}=Cj(he),[Re,ze]=E.useState(null),[Fe,Ee]=E.useState(null),st=E.useCallback((te,ae,se)=>{const me=vt.getState(),He=[...me.defaults,...me.userItems,...me.projectItems].find(ct=>ct.id===te);((He==null?void 0:He.parameters)??[]).filter(ct=>ct.position!==void 0||ct.required).length>0?ze({id:te,name:(He==null?void 0:He.name)??te,subGroup:ae}):De(void 0,void 0,te,ae,se)},[De]),ot=E.useCallback((te,ae,se)=>{st(te,ae,se)},[st]),je=E.useCallback(te=>{he(!1);const ae=document.querySelector(`[data-item-index="${te}"]`);ae&&ae.scrollIntoView({behavior:"smooth",block:"center"})},[he]);E.useEffect(()=>{const te=ae=>{const se=S||y||C||b||N;ae.key==="Escape"&&G&&!se&&U(),ae.key==="ScrollLock"&&he(!ie)};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[G,U,ie,S,y,C,b,N]);const Me=Ql();Pl(Me.quickAction,()=>{v(!0)}),Pl(Me.criteriaSidebar,()=>{t==null||t()}),jT(Me.agentSwitching,Z,te=>{Le.getState().switchMode(te)});const lt=te=>{st(te),Ie()},we=(te,ae)=>{st(te,ae),Ie()},Ie=()=>{u(""),d([]),L!=null&&L.id&&localStorage.removeItem(`openfox:draft:${L.id}`)},qe=E.useCallback(async(te,ae,se,me)=>{const Ue=Sj(te);if(Ue.length>0)Ee({prompt:te,paramKeys:Ue,agentMode:ae,textareaContent:se,attachments:me});else{ae&&(L==null?void 0:L.mode)!==ae&&await Le.getState().switchMode(ae);const He=se&&se.trim()?`${se.trim()}
321
321