openfox 1.6.72 → 1.6.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{auth-JF2HDJ6P.js → auth-LZZX63KI.js} +1 -1
- package/dist/{auto-compaction-B6BOL7ZI.js → auto-compaction-HQHEK75L.js} +6 -6
- package/dist/{chat-handler-HPWLJF5O.js → chat-handler-NNDQSDFI.js} +9 -9
- package/dist/{chunk-TGR7VMJQ.js → chunk-4CQ7CUQ6.js} +2 -2
- package/dist/{chunk-F2VWCCMC.js → chunk-55Z3DJ7G.js} +5 -5
- package/dist/{chunk-SW7HAQNV.js → chunk-5UTTLO4D.js} +2 -2
- package/dist/{chunk-TVQOONDR.js → chunk-AFATQ5LJ.js} +1 -6
- package/dist/{chunk-VCALN543.js → chunk-DLINTLB7.js} +3 -3
- package/dist/{chunk-TLVDGEKQ.js → chunk-EGIJKK4U.js} +7 -5
- package/dist/{chunk-WNZIUQ2L.js → chunk-J5DV33SS.js} +2 -2
- package/dist/{chunk-JF2QDLS3.js → chunk-JQBTYHUR.js} +4 -4
- package/dist/{chunk-K332VV3B.js → chunk-ODUSHSK2.js} +11 -13
- package/dist/{chunk-SPEGIMYZ.js → chunk-PPSXSDMY.js} +7 -7
- package/dist/{chunk-WAKARZDD.js → chunk-RTOWT3GF.js} +36 -81
- package/dist/{chunk-4DNPYFL4.js → chunk-TYUNDOX2.js} +4 -4
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/{config-3TU54V4X.js → config-6T4EHAP2.js} +5 -5
- package/dist/{events-2IHZ662M.js → events-LKEZ3YCW.js} +3 -3
- package/dist/{orchestrator-IPTSMNWX.js → orchestrator-T2EQZJS5.js} +7 -7
- package/dist/package.json +3 -1
- package/dist/{processor-SZMPOBLC.js → processor-HF5SS6CR.js} +5 -5
- package/dist/{provider-A37TI24X.js → provider-AKN355YH.js} +8 -9
- package/dist/{runtime-config-2XJJIMSC.js → runtime-config-ZCK74XKM.js} +2 -2
- package/dist/{serve-BQ5OQ2EY.js → serve-YCFUOOGT.js} +11 -11
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +9 -9
- package/dist/{tools-24YVLSCD.js → tools-5MCH72FH.js} +6 -6
- package/dist/{vision-fallback-HXPTLQHN.js → vision-fallback-AXH3BGJC.js} +2 -2
- package/dist/web/assets/{index-C4APUIWx.js → index-9GgVgB7B.js} +3 -3
- package/dist/web/index.html +1 -1
- package/dist/web/sw.js +1 -1
- package/package.json +3 -1
|
@@ -146,8 +146,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
146
146
|
`,children:s?"Reconnecting...":"Reconnect"})]})}function SA(){const e=lw(),r=e?"bg-amber-400":"bg-accent-primary";return o.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-muted py-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs("span",{className:"flex gap-0.5",children:[o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${r}`,style:{animationDelay:"0ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${r}`,style:{animationDelay:"150ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${r}`,style:{animationDelay:"300ms"}})]}),o.jsx("span",{className:"text-text-secondary",children:e?"Running... (abort in progress)":"Running"})]}),!e&&o.jsx("span",{className:"text-text-muted",children:"esc to interrupt"})]})}function wA({attachment:e,onRemove:r}){const s=i=>i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(1)} KB`:`${(i/1048576).toFixed(1)} MB`;return o.jsxs("div",{className:"relative inline-flex flex-col items-center p-2 bg-bg-tertiary rounded-lg border border-border",children:[o.jsx(lo,{onClick:()=>r(e.id),className:"absolute -top-2 -right-2",size:"sm",variant:"overlay","aria-label":`Remove ${e.filename}`}),o.jsx("img",{src:e.data,alt:e.filename,className:"w-16 h-16 object-cover rounded-md bg-bg-secondary"}),o.jsx("div",{className:"mt-1 text-xs text-text-muted text-center max-w-16 truncate",title:e.filename,children:e.filename}),o.jsx("div",{className:"text-[10px] text-text-muted",children:s(e.size)})]})}function CA({history:e,selectedIndex:r,onSelect:s,onEscape:i,onNavigate:c}){const u=P.useRef(null),h=P.useRef(null);P.useEffect(()=>{h.current&&u.current&&h.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[r]);const l=f=>{switch(f.key){case"Enter":f.preventDefault(),e[r]&&s(e[r].content);break;case"Escape":f.preventDefault(),i();break;case"ArrowUp":f.preventDefault(),c("up");break;case"ArrowDown":f.preventDefault(),c("down");break}},d=f=>{s(f)};return o.jsx("div",{ref:u,role:"list",className:"mb-2 p-2 bg-bg-secondary border border-border rounded-lg overflow-y-auto max-h-64",onKeyDown:l,children:e.map((f,g)=>o.jsxs("div",{ref:g===r?h:null,role:"listitem",onClick:()=>d(f.content),className:`
|
|
147
147
|
p-2 rounded cursor-pointer transition-colors
|
|
148
148
|
${g===r?"bg-accent-primary/20 border border-accent-primary":"hover:bg-bg-tertiary"}
|
|
149
|
-
`,children:[o.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[f.formattedTimestamp,f.sessionName&&o.jsxs(o.Fragment,{children:[" | ",o.jsx("span",{className:"text-accent-primary font-medium",children:f.sessionName})]})]}),o.jsx("div",{className:"text-sm text-text-primary mt-1",children:f.trimmedContent})]},f.id))})}const hn=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchCommands:async()=>{await $h("/api/commands",e)},fetchCommand:async s=>{try{const i=await ke(`/api/commands/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/commands/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createCommand:async s=>{const i=await xs("POST","/api/commands",s);return i.success&&await r().fetchCommands(),i},updateCommand:async(s,i)=>{const c=await xs("PUT",`/api/commands/${s}`,i);return c.success&&await r().fetchCommands(),c},deleteCommand:async s=>{try{const i=await ke(`/api/commands/${s}`,{method:"DELETE"}),c=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async s=>{try{const i=await ke(`/api/commands/${s}/duplicate`,{method:"POST"}),c=await i.json();return i.ok?(await r().fetchCommands(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}})),kA={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function EA(e,r={}){const s={...kA,...r};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<=s.maxSizeBytes){const c=await e.arrayBuffer(),u=LA(c),h=`data:${e.type};base64,${u}`,l=await M0(h);return{dataUrl:h,mimeType:e.type,size:e.size,width:l.width,height:l.height}}return await jA(e,s)}async function jA(e,r){const s=await TA(e),i=await M0(s),{width:c,height:u}=NA(i.width,i.height,r.maxWidth,r.maxHeight),h=AA();h.width=c,h.height=u;const l=h.getContext("2d");if(!l)throw new Error("Failed to get canvas context");l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(i,0,0,c,u);let d=r.quality,f;do{if(f=h.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),_v(f)<=r.maxSizeBytes||d<=.3)break;d-=.1}while(!0);const g=_v(f);return{dataUrl:f,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:g,width:c,height:u}}function NA(e,r,s,i){const c=e/r;return e>r&&e>s?{width:s,height:Math.round(s/c)}:r>e&&r>i?{width:Math.round(i*c),height:i}:{width:e,height:r}}function TA(e){return new Promise((r,s)=>{const i=RA(),c=new i;c.onload=()=>r(c.result),c.onerror=()=>s(new Error("Failed to read file")),c.readAsDataURL(e)})}function M0(e){return new Promise((r,s)=>{const i=DA(),c=new i;c.onload=()=>r(c),c.onerror=()=>s(new Error("Failed to load image")),c.src=e})}function AA(){var r;const e=Af();if(!((r=e.document)!=null&&r.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function DA(){const e=Af();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function RA(){const e=Af();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function Af(){return globalThis}function LA(e){const r=new Uint8Array(e);let s="";for(let i=0;i<r.byteLength;i++){const c=r[i];c!==void 0&&(s+=String.fromCharCode(c))}return btoa(s)}function _v(e){const s=e.split(",")[1];return s?Math.round(s.length*3/4):0}function OA(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function MA(e,r=50*1024*1024){return e.size>r?{valid:!1,error:`Image file is too large (${Sv(e.size)}). Maximum size is ${Sv(r)}.`}:{valid:!0}}function Sv(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function ch(e,r,s,i={}){const{maxSizeBytes:c=50*1024*1024,filename:u}=i;if(!OA(e)){s(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const h=MA(e,c);if(!h.valid){s(h.error??"Image file is too large");return}try{const l=await EA(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:zv(),filename:u??e.name,mimeType:l.mimeType,size:l.size,data:l.dataUrl};r(d)}catch(l){const d=l instanceof Error?l.message??"Failed to process image":"Failed to process image";s(d)}}function IA(e){const r={};let s=null;for(const i of e){if(i.role==="user"&&!i.isSystemGenerated){s=i.id;continue}i.role==="assistant"&&i.promptContext&&s&&r[s]===void 0&&(r[s]=i.promptContext)}return r}function BA({content:e,children:r,position:s="top",delay:i=200}){const[c,u]=P.useState(!1),[h,l]=P.useState({top:0,left:0}),d=P.useRef(void 0),f=P.useRef(null);P.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=()=>{d.current=setTimeout(()=>{if(f.current){const S=f.current.getBoundingClientRect();l({top:S.top,left:S.left+S.width/2})}u(!0)},i)},m=()=>{d.current&&clearTimeout(d.current),u(!1)},v=(()=>{switch(s){case"top":return{top:h.top-8,left:h.left,tx:"-50%",ty:"-100%"};case"bottom":return{top:h.top+8,left:h.left,tx:"-50%",ty:"0%"};case"left":return{top:h.top,left:h.left-8,tx:"-100%",ty:"-50%"};case"right":return{top:h.top,left:h.left+8,tx:"0%",ty:"-50%"}}})();return o.jsxs(o.Fragment,{children:[o.jsx("span",{ref:f,className:"inline-flex",onMouseEnter:g,onMouseLeave:m,onFocus:g,onBlur:m,children:r}),c&&Ki.createPortal(o.jsx("div",{className:"fixed z-[9999] px-4 py-3 text-sm text-text-primary bg-bg-secondary border border-border rounded-lg shadow-xl max-w-sm break-words pointer-events-none",style:{top:v.top,left:v.left,transform:`translate(${v.tx}, ${v.ty})`},children:e}),document.body)]})}function uh(e){return{contextWindow:e.contextWindow,temperature:e.temperature??null,topP:e.topP??null,topK:e.topK??null,maxTokens:e.maxTokens??null,supportsVision:e.supportsVision??null}}function zA({label:e,children:r}){return o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-sm font-medium text-text-secondary border-b border-border/50 pb-1",children:e}),r]})}function Ja({label:e,value:r,onChange:s,min:i,max:c,step:u=1,helpText:h,defaultValue:l,profileDefault:d,tooltip:f}){const[g,m]=P.useState((r==null?void 0:r.toString())??""),[v,S]=P.useState(r===null);P.useEffect(()=>{m((r==null?void 0:r.toString())??""),S(r===null)},[r]);const k=b=>{if(m(b),b==="")s(null);else{const x=parseFloat(b);isNaN(x)||s(x)}},C=()=>{v?(S(!1),l!==void 0&&(m(l.toString()),s(l))):(S(!0),s(null))},y=o.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-secondary mb-1",children:[f&&o.jsx(BA,{content:f,children:o.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-xs text-text-muted hover:text-text-secondary cursor-help rounded-full border border-border/50",children:"?"})}),e,o.jsx("button",{type:"button",onClick:C,className:`text-xs px-1.5 py-0.5 rounded border ${v?"border-accent-primary/50 bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-secondary"}`,title:v?"Click to set a custom value":"Click to use default",children:v?"default":"custom"})]});return o.jsxs("div",{children:[y,o.jsx("input",{type:"number",min:i,max:c,step:u,value:g,readOnly:v,onChange:b=>k(b.target.value),onClick:()=>v&&C(),placeholder:v?`${d!==void 0?d:"Using default"} (click to edit)`:"",className:`w-full bg-bg-tertiary border border-border rounded px-3 py-2 text-text-primary focus:outline-none focus:border-accent-primary ${v?"opacity-50 cursor-pointer":""}`}),h&&o.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[o.jsx("p",{className:"text-xs text-text-muted",children:h}),d!==void 0&&o.jsxs("span",{className:"text-xs text-text-muted/60",children:["(default: ",d,")"]})]}),!h&&d!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["Profile default: ",d]})]})}function PA({isOpen:e,onClose:r,providerId:s,model:i}){const[c,u]=P.useState(()=>uh(i)),[h,l]=P.useState(!1),d=Rt(m=>m.updateModelSettings);P.useEffect(()=>{u(uh(i))},[i]);const f=async()=>{if(c.contextWindow<1024||c.contextWindow>1e7)return;l(!0);const m=c.temperature!==(i.temperature??null)||c.topP!==(i.topP??null)||c.topK!==(i.topK??null)||c.maxTokens!==(i.maxTokens??null)||c.supportsVision!==(i.supportsVision??null);await d(s,i.id,{contextWindow:c.contextWindow,...m&&{temperature:c.temperature,topP:c.topP,topK:c.topK,maxTokens:c.maxTokens,supportsVision:c.supportsVision??void 0}}),l(!1),r()},g=()=>{u(uh(i)),r()};return e?o.jsx(At,{isOpen:e,onClose:r,title:"Model Properties",size:"lg",footer:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{variant:"secondary",onClick:g,disabled:h,children:"Cancel"}),o.jsx(nt,{variant:"primary",onClick:f,disabled:h||c.contextWindow<1024||c.contextWindow>1e7,children:h?"Saving...":"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Model Name"}),o.jsx("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded font-mono text-sm break-all",children:i.id})]}),o.jsx(Ja,{label:"Context Window",value:c.contextWindow,onChange:m=>m!==null&&u(v=>({...v,contextWindow:m})),min:1024,max:1e7,helpText:"Range: 1,024 - 10,000,000 tokens"}),o.jsxs(zA,{label:"Sampling Parameters",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Ja,{label:"Temperature",value:c.temperature,onChange:m=>u(v=>({...v,temperature:m})),min:0,max:2,step:.1,helpText:"0.0 - 2.0",defaultValue:1,profileDefault:i.defaultTemperature,tooltip:"How random the response is. Low (0.1-0.3) = precise and predictable. High (0.7-1.5) = creative and varied."}),o.jsx(Ja,{label:"Top P",value:c.topP,onChange:m=>u(v=>({...v,topP:m})),min:0,max:1,step:.05,helpText:"0.0 - 1.0",defaultValue:1,profileDefault:i.defaultTopP,tooltip:"How to pick the next word. Low (0.5-0.8) = stick to obvious choices. High (0.95-1.0) = allow surprising words."})]}),o.jsx(Ja,{label:"Top K",value:c.topK,onChange:m=>u(v=>({...v,topK:m})),min:1,max:200,helpText:"1 - 200 (leave as default if not supported)",profileDefault:i.defaultTopK,tooltip:"Restricts word choices to the top K most likely ones. Low (10-20) = focused. High (50-200) = diverse. Not all backends support this."})]}),o.jsx(Ja,{label:"Max Tokens",value:c.maxTokens,onChange:m=>u(v=>({...v,maxTokens:m})),min:256,max:32e3,helpText:"Maximum tokens to generate per response",profileDefault:i.defaultMaxTokens,tooltip:"Longest response length. Higher values let the model write more, but use up your context window faster."}),o.jsxs("div",{children:[o.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-secondary mb-1",children:[o.jsx("input",{type:"checkbox",checked:c.supportsVision??!1,onChange:m=>u(v=>({...v,supportsVision:m.target.checked})),className:"rounded border-border bg-bg-tertiary text-accent-primary focus:ring-accent-primary focus:ring-offset-0"}),"Vision Enabled"]}),o.jsx("p",{className:"text-xs text-text-muted",children:"Allow sending images directly to this model. Disable if the model doesn't support vision."})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Source"}),o.jsxs("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded text-sm",children:[i.source==="backend"&&"Auto-detected from backend",i.source==="user"&&"Manually set",i.source==="default"&&"Default value"]})]})]})}):null}function HA(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function FA(){var $;const[,e]=lr(),r=Ce(B=>B.currentSession),s=Ce(B=>B.setSessionProvider),[i,c]=P.useState(!1),[u,h]=P.useState([]),[l,d]=P.useState(null),f=P.useRef(null),[g,m]=P.useState(null),v=P.useRef(new Set),S=Rt(B=>B.providers),k=Rt(B=>B.activeProviderId),C=Rt(B=>B.model);Rt(B=>B.backend);const y=Rt(B=>B.llmStatus),b=Rt(B=>B.activating),x=Rt(B=>B.activateProvider),_=Rt(B=>B.refreshModel),j=Rt(B=>B.refreshProviderModels);P.useEffect(()=>{function B(X){f.current&&!f.current.contains(X.target)&&(c(!1),h([]),v.current=new Set)}return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]),P.useEffect(()=>{if(i){const B=S.map(X=>X.id);h(B),B.forEach(X=>{v.current.has(X)||(v.current.add(X),D(X))})}},[i,S]),S.find(B=>B.id===k);const A=y==="disconnected",N=C?(($=C.split("/").pop())==null?void 0:$.replace(/-/g," "))??C:"detecting...",D=async B=>{d(B);try{await j(B)}catch{}finally{d(null)}},T=B=>{u.includes(B.id)?h(u.filter(X=>X!==B.id)):(h([...u,B.id]),D(B.id))},z=async B=>{if(B.id===k){T(B);return}r?(s(B.id,void 0),Rt.getState().syncFromSession(B.id,""),c(!1),h([])):await x(B.id)&&(c(!1),h([]))},O=B=>{T(B)},q=async(B,X)=>{B.stopPropagation(),v.current.delete(X),await j(X),await D(X)},V=(B,X)=>{m({providerId:B,model:X})},W=()=>{m(null)},I=async(B,X)=>{if(console.log("[ProviderSelector.handleModelClick] providerId:",B,"model:",X),r){console.log("[ProviderSelector.handleModelClick] Calling setSessionProvider"),s(B,X),Rt.getState().syncFromSession(B,X),h([]),c(!1);return}d("activating");try{(await ke(`/api/providers/${B}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:X})})).ok&&(await Rt.getState().fetchConfig(),h([]),c(!1))}catch{}finally{d(null)}};return S.length===0?o.jsxs("button",{type:"button",onClick:()=>_(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:A?"LLM server is offline. Click to retry.":C??"Click to refresh model",children:[A?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):o.jsxs("div",{className:"relative",ref:f,children:[o.jsxs("button",{type:"button",onClick:()=>c(!i),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:[A?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx(br,{className:"w-3 h-3 text-text-muted transition-transform",rotate:i?180:0})]}),i&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-lg z-50 overflow-hidden max-h-[80vh] overflow-y-auto",children:[o.jsx("div",{className:"py-1",children:S.map(B=>{var X;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${B.id===k?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${b?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!b&&z(B),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${B.id===k?"text-accent-primary":"text-text-primary"}`,children:B.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:B.backend!=="auto"&&W1(B.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[B.id===k?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Ur,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:Q=>{Q.stopPropagation(),q(Q,B.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(Ew,{className:`w-4 h-4 ${l===B.id?"animate-spin":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:Q=>{Q.stopPropagation(),O(B)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(br,{className:`w-4 h-4 transition-transform ${u.includes(B.id)?"rotate-180":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})})]})]}),u.includes(B.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:l===B.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(X=B.models)!=null&&X.length?B.models.map(Q=>{var H;return o.jsxs("button",{type:"button",onClick:()=>I(B.id,Q.id),disabled:l==="activating",className:`w-full px-4 py-1.5 text-left hover:bg-bg-tertiary transition-colors text-sm flex items-center justify-between group ${l==="activating"?"opacity-50 cursor-wait":""} ${C===Q.id?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((H=Q.id.split("/").pop())==null?void 0:H.replace(/-/g," "))??Q.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:HA(Q.contextWindow)}),o.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),V(B.id,Q)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(xw,{className:"w-3 h-3 text-text-muted"})})]}),C===Q.id&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Ur,{className:"w-3.5 h-3.5"})})]},Q.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},B.id)})}),o.jsx("div",{className:"border-t border-border px-3 py-2",children:o.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),g&&o.jsx(PA,{isOpen:!0,onClose:W,providerId:g.providerId,model:g.model})]})}function UA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function $A({onClick:e}){return o.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:o.jsx(lc,{})})}function I0({isOpen:e,onClose:r,initialEditId:s}){const i=hn(fe=>fe.defaults),c=hn(fe=>fe.userItems),u=hn(fe=>fe.loading),h=hn(fe=>fe.fetchCommands),l=hn(fe=>fe.fetchCommand),d=hn(fe=>fe.fetchDefaultContent),f=hn(fe=>fe.createCommand),g=hn(fe=>fe.updateCommand),m=hn(fe=>fe.deleteCommand),[v,S]=P.useState(null),[k,C]=P.useState(null),{view:y,editingId:b,formError:x,saving:_,formData:j,setView:A,setEditingId:N,setFormError:D,setFormData:T,setSaving:z}=Jv(),{requestDelete:O,clearConfirm:q,isConfirming:V}=qh(),W=P.useRef(!1),I=Tt(fe=>fe.defaults),$=Tt(fe=>fe.userItems),B=Tt(fe=>fe.fetchAgents),Q=[...I,...$].filter(fe=>!fe.subagent),H=P.useRef(h),L=P.useRef(B),R=P.useRef(l),U=P.useRef(d),F=P.useRef(s),ne=P.useRef(A),Z=P.useRef(N),ee=P.useRef(D),Y=P.useRef(q);P.useEffect(()=>{H.current=h,L.current=B,R.current=l,U.current=d,F.current=s,ne.current=A,Z.current=N,ee.current=D,Y.current=q}),P.useEffect(()=>{if(e)if(H.current(),L.current(),W.current||(Y.current(),W.current=!0),F.current){const fe=i.some(je=>je.id===F.current);ne.current("edit"),Z.current(F.current),ee.current(""),fe?U.current(F.current).then(je=>{je&&T({name:je.metadata.name+" (copy)",id:`${F.current}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0})}):R.current(F.current).then(je=>{je&&T({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1})})}else ne.current("list"),Z.current(null);else W.current=!1},[e]);const G=async fe=>{S(fe);const je=await d(fe);C((je==null?void 0:je.prompt)??null)},ae=async fe=>{if(i.some(Ue=>Ue.id===fe)){const Ue=await d(fe);Ue&&(N(null),T({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!0}),D(""),A("edit"))}else{const Ue=await l(fe);Ue&&(N(null),T({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!1}),D(""),A("edit"))}},re=()=>{T({name:"",id:"",prompt:"",agentMode:"",isDefault:!1}),N(null),A("edit")},be=async fe=>{const je=await l(fe);je&&(N(fe),T({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1}),D(""),A("edit"))},ve=async fe=>{await m(fe),q()},Re=async()=>{const fe=b??j.id;if(!fe||!j.name||!j.prompt){D("Name and message are required.");return}z(!0),D("");const je={metadata:{id:fe,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},Ue=b?await g(b,je):await f(je);if(z(!1),!Ue.success){D(Ue.error??"Failed to save command.");return}s?r():A("list")},Oe=()=>{s?r():(A("list"),S(null),C(null))},ze=fe=>{T(je=>({...je,name:fe})),(!b||j.isDefault)&&T(je=>({...je,id:UA(fe)}))},We=()=>{S(null),C(null),A("list")},Ee=()=>{v&&(S(null),A("edit"),N(v),d(v).then(fe=>{fe&&T({name:`${fe.metadata.name} (copy)`,id:`${v}-copy-${Date.now()}`,prompt:fe.prompt,agentMode:fe.metadata.agentMode??"",isDefault:!0})}))};if(v){const fe=i.find(je=>je.id===v);return o.jsx(At,{isOpen:e,onClose:We,title:`Default: ${(fe==null?void 0:fe.name)??v}`,size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),o.jsx("span",{className:"font-mono",children:v})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:fe==null?void 0:fe.name})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(fe==null?void 0:fe.agentMode)||"None"})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:k??"",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"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(nt,{variant:"secondary",onClick:We,children:"Close"}),o.jsx(nt,{variant:"primary",onClick:Ee,children:"Duplicate & Customize"})]})]})})}return y==="edit"?o.jsx(At,{isOpen:e,onClose:Oe,title:b?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[x&&o.jsx(Gh,{message:x}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(Qv,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!b&&!j.isDefault,onNameChange:ze,onIdChange:fe=>T(je=>({...je,id:fe}))}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsxs("select",{value:j.agentMode,onChange:fe=>T(je=>({...je,agentMode:fe.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:[o.jsx("option",{value:"",children:"None (keep current mode)"}),Q.map(fe=>o.jsx("option",{value:fe.id,children:fe.name},fe.id))]})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:j.prompt,onChange:fe=>T(je=>({...je,prompt:fe.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"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(nt,{variant:"secondary",onClick:Oe,children:"Cancel"}),o.jsx(nt,{variant:"primary",onClick:Re,disabled:_||!j.name||!j.prompt,children:_?"Saving...":"Save"})]})]})}):o.jsxs(At,{isOpen:e,onClose:r,title:"Commands",size:"lg",children:[o.jsx(Yv,{description:"Commands are pre-defined messages you can send with a single click.",onNew:re}),o.jsxs(Zv,{loading:u,hasItems:i.length>0||c.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:i.map(fe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:fe.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx($A,{onClick:()=>G(fe.id)}),o.jsx(oo,{onClick:()=>ae(fe.id)})]})]},fe.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(fe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:fe.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Wi,{onClick:()=>be(fe.id)}),o.jsx(oo,{onClick:()=>ae(fe.id)}),V(fe.id,"delete")?o.jsx(Wh,{onConfirm:()=>ve(fe.id),onCancel:q}):o.jsx(Vh,{onClick:()=>O(fe.id)})]})]},fe.id))})]})]})]})}function qA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function WA(e){let r=1;for(;e.some(s=>s.id===`s${r}`);)r++;return`s${r}`}const VA=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}],B0={all_criteria_passed:"All passed",all_criteria_completed_or_passed:"All completed",any_criteria_blocked:"Blocked",has_pending_criteria:"Pending/Failed",step_result:"Result",always:"Always"},z0=[{value:"all_criteria_passed",label:"All criteria passed"},{value:"all_criteria_completed_or_passed",label:"All criteria completed or passed"},{value:"any_criteria_blocked",label:"Any criteria blocked (retry limit)"},{value:"has_pending_criteria",label:"Has pending or failed criteria"},{value:"step_result",label:"Step result is..."},{value:"always",label:"Always (fallback)"}],zs=150,Fr=54,zi=80,Pn=30,Pi=70,wv=100,Ps=50,Vl=50,Cv=4;function Df(e,r){if(e.type==="agent"){const s=r.find(i=>i.id===e.toolMode);return{name:(s==null?void 0:s.name)??(e.toolMode||"Agent"),color:(s==null?void 0:s.color)||"#3b82f6"}}if(e.type==="sub_agent"){const s=r.find(i=>i.id===e.subAgentType);return{name:(s==null?void 0:s.name)??(e.subAgentType||"Sub-Agent"),color:(s==null?void 0:s.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function GA(e,r,s,i){const c=Vl+Ps+zs+wv+zs+Ps+Vl,u=c/2,h=Vl+Ps+zs/2,l=Vl+Ps+zs+wv+zs/2,d=[],f=[],g=new Map,m=e.filter(I=>I.type==="agent"||I.type==="shell"),v=e.filter(I=>I.type==="sub_agent"),S=v.length>0,k=S?h:u,C=m.length>0?l:u,y=Ps+Pn/2;if(d.push({id:"$start",type:"terminal",label:"Start",cx:k,cy:y,w:zi,h:Pn}),g.set("$start",{cx:k,cy:y,w:zi,h:Pn}),e.length===0){const I=y+Pn/2+Pi*2+Pn/2;return d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:I,w:zi,h:Pn}),g.set("$done",{cx:k,cy:I,w:zi,h:Pn}),{nodes:d,edges:f,width:c,height:I+Pn/2+Ps,posMap:g}}const b=y+Pn/2+Pi,x=(I,$)=>{I.forEach((B,X)=>{const Q=b+X*(Fr+Pi)+Fr/2,{name:H,color:L}=Df(B,i);d.push({id:B.id,type:"step",label:H,color:L,cx:$,cy:Q,w:zs,h:Fr}),g.set(B.id,{cx:$,cy:Q,w:zs,h:Fr})})};x(m,k),x(v,C);const _=m.length>0?b+(m.length-1)*(Fr+Pi)+Fr/2:y,j=S?b+(v.length-1)*(Fr+Pi)+Fr/2:y,A=Math.max(_,j)+Fr/2+Pi+Pn/2;d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:A,w:zi,h:Pn}),g.set("$done",{cx:k,cy:A,w:zi,h:Pn});const N=[];r&&g.has(r)&&N.push({from:"$start",to:r,label:s,edgeKey:"start",direction:"down",backEdgeIndex:0});let D=0;for(const I of e)I.transitions.forEach(($,B)=>{if(!$.goto||!g.has($.goto))return;const X=g.get(I.id),Q=g.get($.goto),H=$.when.type==="step_result"?`${$.when.result}`:B0[$.when.type]??$.when.type,L=I.id===$.goto;let R;L?R="back":Q.cy>X.cy+1?R="down":Q.cy<X.cy-1?R="back":R="same",N.push({from:I.id,to:$.goto,label:H,edgeKey:`${I.id}:${B}`,direction:R,backEdgeIndex:R==="back"?D++:0})});const T=new Map,z=new Map,O=new Map,q=new Map;for(const I of N)I.direction==="down"&&(T.set(I.from,(T.get(I.from)??0)+1),z.set(I.to,(z.get(I.to)??0)+1));const V=new Map,W=new Map;for(const I of N){if(I.direction!=="same")continue;const $=[I.from,I.to].sort().join("|");V.set($,(V.get($)??0)+1)}for(const I of N){if(I.direction==="back"||I.direction==="same"){let R=0;if(I.direction==="same"){const U=[I.from,I.to].sort().join("|");R=W.get(U)??0,W.set(U,R+1)}f.push({...I,fromPort:0,toPort:0,sameEdgeIndex:R});continue}const $=T.get(I.from)??1,B=z.get(I.to)??1,X=O.get(I.from)??0,Q=q.get(I.to)??0;O.set(I.from,X+1),q.set(I.to,Q+1);const H=$===1?0:-.6+1.2*X/($-1),L=B===1?0:-.6+1.2*Q/(B-1);f.push({...I,fromPort:H,toPort:L,sameEdgeIndex:0})}return{nodes:d,edges:f,width:c,height:A+Pn/2+Ps,posMap:g}}function KA({steps:e,entryStep:r,selectedNodeId:s,selectedEdgeKey:i,startConditionLabel:c,agentTypes:u,isReadOnly:h,onSelectNode:l,onSelectEdge:d,onRemoveStep:f,onCreateTransition:g,onReconnectTo:m,onReconnectFrom:v,onDeleteTransition:S}){const k=P.useRef(null),C=P.useRef(!1),[y,b]=P.useState(null),[x,_]=P.useState(null),[j,A]=P.useState(null),{nodes:N,edges:D,width:T,height:z,posMap:O}=P.useMemo(()=>GA(e,r,c,u),[e,r,c,u]),q=P.useCallback(Z=>{var re;const ee=k.current;if(!ee)return{x:0,y:0};const Y=ee.createSVGPoint();Y.x=Z.clientX,Y.y=Z.clientY;const G=(re=ee.getScreenCTM())==null?void 0:re.inverse();if(!G)return{x:0,y:0};const ae=Y.matrixTransform(G);return{x:ae.x,y:ae.y}},[]),V=P.useCallback(Z=>!Z||!x||Z==="$start"?!1:x.type==="reconnect-from"?Z!=="$done":!0,[x]),W=P.useCallback((Z,ee)=>{if(h)return;Z.stopPropagation(),Z.preventDefault();const Y=q(Z);_({type:"new",fromNodeId:ee,mouseX:Y.x,mouseY:Y.y})},[q,h]),I=P.useCallback((Z,ee)=>{if(h)return;Z.stopPropagation(),Z.preventDefault();const Y=q(Z);_({type:"reconnect-to",fromNodeId:ee.from,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),$=P.useCallback((Z,ee)=>{if(h)return;Z.stopPropagation(),Z.preventDefault();const Y=q(Z);_({type:"reconnect-from",fromNodeId:ee.from,fixedTargetId:ee.to,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),B=P.useCallback(Z=>{if(!x)return;const ee=q(Z);_(Y=>Y?{...Y,mouseX:ee.x,mouseY:ee.y}:null)},[x,q]),X=P.useCallback(()=>{x&&(C.current=!0,j&&V(j)&&(x.type==="new"?g(x.fromNodeId,j):x.type==="reconnect-to"?m(x.edgeKey,j):x.type==="reconnect-from"&&v(x.edgeKey,j)),_(null),A(null))},[x,j,V,g,m,v]),Q=P.useCallback(()=>{if(C.current){C.current=!1;return}l(null),d(null)},[l,d]);P.useEffect(()=>{if(h)return;const Z=ee=>{ee.target instanceof HTMLInputElement||ee.target instanceof HTMLTextAreaElement||ee.target instanceof HTMLSelectElement||(ee.key==="Delete"||ee.key==="Backspace")&&i&&i!=="start"&&(ee.preventDefault(),S(i),d(null))};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[h,i,S,d]);const H=Z=>{const ee=O.get(Z.from),Y=O.get(Z.to);if(!ee||!Y)return null;let G,ae,re,be="middle",ve,Re;if(Z.direction==="down"){const Oe=ee.cx+Z.fromPort*(ee.w/2-10),ze=ee.cy+ee.h/2,We=Y.cx+Z.toPort*(Y.w/2-10),Ee=Y.cy-Y.h/2,fe=Ee-ze,je=We-Oe;G=`M ${Oe} ${ze} C ${Oe} ${ze+fe*.4}, ${We-je*.2} ${Ee-fe*.1}, ${We} ${Ee}`,ae=Oe+(We-Oe)*.5,re=ze+fe*.6,ve={x:Oe,y:ze},Re={x:We,y:Ee}}else if(Z.direction==="back"){const Oe=Z.from===Z.to,ze=ee.cx>=T/2,We=Z.backEdgeIndex*16,Ee=ze?T-20-We:20+We;if(Oe){const fe=ee.cx>=T/2,je=30+Z.backEdgeIndex*14,Ue=ee.cy-ee.h/2,It=fe?ee.cx+ee.w/2:ee.cx-ee.w/2,pe=fe?It+je:It-je,Ne=ee.cx+(fe?ee.w/4:-ee.w/4),Me=Ue-20-Z.backEdgeIndex*10;G=`M ${It} ${ee.cy} C ${pe} ${ee.cy}, ${pe} ${Me}, ${Ne} ${Ue}`,ae=pe+10,re=Me+4,be="middle",ve={x:It,y:ee.cy},Re={x:Ne,y:Ue}}else{const fe=ze?ee.cx+ee.w/2:ee.cx-ee.w/2,je=Y.cx+(ze?Y.w/4:-Y.w/4),Ue=Math.min(ee.cy,Y.cy)-Y.h/2-18-Z.backEdgeIndex*14;G=`M ${fe} ${ee.cy} L ${Ee} ${ee.cy} L ${Ee} ${Ue} L ${je} ${Ue} L ${je} ${Y.cy-Y.h/2}`,ae=Ee,re=(ee.cy+Ue)/2,be=ze?"start":"end",ve={x:fe,y:ee.cy},Re={x:je,y:Y.cy-Y.h/2}}}else{const Oe=Y.cx>ee.cx,ze=Z.sameEdgeIndex===0?-12:12,We=Oe?ee.cx+ee.w/2:ee.cx-ee.w/2,Ee=Oe?Y.cx-Y.w/2:Y.cx+Y.w/2,fe=ee.cy+ze,je=Y.cy+ze,Ue=(We+Ee)/2;G=`M ${We} ${fe} C ${Ue} ${fe}, ${Ue} ${je}, ${Ee} ${je}`,ae=Ue,re=(fe+je)/2-6,ve={x:We,y:fe},Re={x:Ee,y:je}}return{path:G,labelX:ae,labelY:re,labelAnchor:be,fromPt:ve,toPt:Re}},L=(Z,ee)=>{const Y=H(Z);if(!Y)return null;const{path:G,labelX:ae,labelY:re,labelAnchor:be}=Y,ve=i===Z.edgeKey,Re=Z.label&&!(Z.from==="$start"&&Z.label==="Always");return o.jsxs("g",{children:[o.jsx("path",{d:G,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Oe=>{Oe.stopPropagation(),d(ve?null:Z.edgeKey)}}),o.jsx("path",{d:G,fill:"none",stroke:ve?"#58a6ff":"#484f58",strokeWidth:ve?2.2:1.2,markerEnd:ve?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Re&&o.jsx("text",{x:ae+(be==="start"?5:be==="end"?-5:0),y:re+3,textAnchor:be,className:"text-[8px]",fill:ve?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Z.label})]},ee)},R=()=>{if(!i||x)return null;const Z=D.find(re=>re.edgeKey===i);if(!Z)return null;const ee=H(Z);if(!ee)return null;const{fromPt:Y,toPt:G}=ee,ae=6;return o.jsxs(o.Fragment,{children:[Z.edgeKey!=="start"&&o.jsx("circle",{cx:Y.x,cy:Y.y,r:ae,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>$(re,Z)}),o.jsx("circle",{cx:G.x,cy:G.y,r:ae,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>I(re,Z)})]})},U=()=>{if(!x)return null;let Z,ee,Y,G;if(x.type==="reconnect-from"){const be=O.get(x.fixedTargetId);if(!be)return null;Z=x.mouseX,ee=x.mouseY,Y=be.cx,G=be.cy-be.h/2}else{const be=O.get(x.fromNodeId);if(!be)return null;Z=be.cx,ee=be.cy+be.h/2,Y=x.mouseX,G=x.mouseY}const ae=G-ee,re=Math.abs(ae)>10?`M ${Z} ${ee} C ${Z} ${ee+ae*.4}, ${Y} ${G-ae*.4}, ${Y} ${G}`:`M ${Z} ${ee} L ${Y} ${G}`;return o.jsx("path",{d:re,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},F=Z=>{const ee=Z.cy+Z.h/2,Y=(x==null?void 0:x.fromNodeId)===Z.id;return o.jsx("circle",{cx:Z.cx,cy:ee,r:Cv,fill:Y?"#58a6ff":"#1c2128",stroke:Y?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5,className:"cursor-crosshair",onMouseDown:G=>W(G,Z.id)})},ne=Z=>{const ee=Z.cy-Z.h/2,Y=x&&j===Z.id&&V(Z.id);return o.jsx("circle",{cx:Z.cx,cy:ee,r:Cv,fill:Y?"#3fb950":"#1c2128",stroke:Y?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5})};return o.jsxs("svg",{ref:k,viewBox:`0 0 ${T} ${z}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:B,onMouseUp:X,onClick:Q,children:[o.jsxs("defs",{children:[o.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),o.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),D.map((Z,ee)=>L(Z,ee)),N.map(Z=>{const ee=s===Z.id,Y=Z.cx-Z.w/2,G=Z.cy-Z.h/2,ae=y===Z.id,re=x&&j===Z.id&&V(Z.id);if(Z.type==="terminal"){const ve=Z.id==="$start",Re=ve?"#58a6ff":"#3fb950",Oe=ve,ze=!ve;return o.jsxs("g",{onClick:We=>{We.stopPropagation(),ve&&!h&&d("start")},className:ve&&!h?"cursor-pointer":void 0,children:[re&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:Z.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ve&&i==="start"&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:Z.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:G,width:Z.w,height:Z.h,rx:Z.h/2,fill:Re,fillOpacity:.08,stroke:Re,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Z.cx,y:Z.cy+4,textAnchor:"middle",fill:Re,className:"text-[10px] font-medium",pointerEvents:"none",children:Z.label}),Oe&&F(Z),ze&&ne(Z)]},Z.id)}const be=Z.color??"#6b7280";return o.jsxs("g",{onClick:ve=>{ve.stopPropagation(),h||l(ee?null:Z.id)},onMouseEnter:()=>b(Z.id),onMouseLeave:()=>b(null),className:h?void 0:"cursor-pointer",children:[re&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ee&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:G,width:Z.w,height:Z.h,rx:10,fill:be,fillOpacity:.08,stroke:be,strokeOpacity:.6,strokeWidth:ee?2:1.5}),o.jsx("text",{x:Z.cx,y:Z.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:Z.label}),!h&&F(Z),!h&&ne(Z),ae&&!x&&!h&&o.jsxs("g",{onClick:ve=>{ve.stopPropagation(),f(Z.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:Y+Z.w-2,cy:G+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:Y+Z.w-5,y1:G-1,x2:Y+Z.w+1,y2:G+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:Y+Z.w+1,y1:G-1,x2:Y+Z.w-5,y2:G+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Z.id)}),x&&N.map(Z=>V(Z.id)?o.jsx("rect",{x:Z.cx-Z.w/2-8,y:Z.cy-Z.h/2-8,width:Z.w+16,height:Z.h+16,fill:"transparent",rx:12,onMouseEnter:()=>A(Z.id),onMouseLeave:()=>A(null),onMouseUp:ee=>{ee.stopPropagation(),X()}},`drop-${Z.id}`):null),U(),R()]})}const ar="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",qs="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",fn="block text-[11px] text-text-secondary mb-0.5";function YA({fromLabel:e,toLabel:r,condition:s,fromStep:i,agentTypes:c,onUpdateCondition:u,onDelete:h}){const l=i&&(i.type==="sub_agent"||i.type==="agent")?c.find(f=>f.id===(i.type==="sub_agent"?i.subAgentType:i.toolMode)):void 0,d=(l==null?void 0:l.results)&&l.results.length>0;return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:"Transition"}),o.jsx("button",{onClick:h,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"font-medium text-text-primary",children:e}),o.jsx(Vv,{}),o.jsx("span",{className:"font-medium text-text-primary",children:r})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Condition"}),o.jsx("select",{value:s.type,onChange:f=>{u(f.target.value==="step_result"?{type:"step_result",result:"success"}:{type:f.target.value})},className:qs,children:z0.map(f=>o.jsx("option",{value:f.value,children:f.label},f.value))})]}),s.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),d?o.jsx("select",{value:s.result??l.results[0],onChange:f=>{u({type:"step_result",result:f.target.value})},className:qs,children:l.results.map(f=>o.jsx("option",{value:f,children:f},f))}):o.jsx("input",{type:"text",value:s.result??"success",onChange:f=>u({type:"step_result",result:f.target.value}),placeholder:"e.g. success, passed, failed",className:ar})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Press Delete to remove."})]})}function dh({variables:e,onInsert:r}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(s=>o.jsx("button",{type:"button",onClick:()=>r(s.name),title:s.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:`{{${s.name}}}`},s.name))})}function XA({step:e,isEntry:r,agentTypes:s,transitionCount:i,templateVariables:c,onUpdate:u,onRemove:h,onSetEntry:l}){const{color:d,name:f}=Df(e,s);return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:d+"20",color:d},children:f}),r&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[!r&&o.jsx("button",{onClick:l,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),o.jsx("button",{onClick:h,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Type"}),o.jsx("select",{value:e.type,onChange:g=>{const m=g.target.value,v=m==="sub_agent"?"verification":"build";if(m==="agent"){const S=s.find(k=>!k.subagent);u({...e,type:m,phase:v,toolMode:(S==null?void 0:S.id)??"builder",name:(S==null?void 0:S.name)??"Agent"})}else if(m==="sub_agent"){const S=s.find(k=>k.subagent);u({...e,type:m,phase:v,subAgentType:(S==null?void 0:S.id)??"",name:(S==null?void 0:S.name)??"Sub-Agent"})}else u({...e,type:m,phase:v,name:"Shell"})},className:qs,children:VA.map(g=>o.jsx("option",{value:g.value,children:g.label},g.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Agent Type"}),o.jsx("select",{value:e.toolMode??"builder",onChange:g=>{const m=s.find(v=>v.id===g.target.value);u({...e,toolMode:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:s.filter(g=>!g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))})]}),e.type==="sub_agent"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:g=>{const m=s.find(v=>v.id===g.target.value);u({...e,subAgentType:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:[o.jsx("option",{value:"",children:"— select —"}),s.filter(g=>g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:g=>u({...e,prompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(dh,{variables:c,onInsert:g=>u({...e,prompt:(e.prompt??"")+`{{${g}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:g=>u({...e,nudgePrompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(dh,{variables:c,onInsert:g=>u({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${g}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:g=>u({...e,command:g.target.value}),rows:3,className:`${ar} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(dh,{variables:c,onInsert:g=>u({...e,command:(e.command??"")+`{{${g}}}`})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:g=>u({...e,timeout:Number(g.target.value)}),className:`${ar} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Success Codes"}),o.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:g=>u({...e,successExitCodes:g.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${ar} font-mono text-xs`})]})]})]}),o.jsx("div",{className:"pt-1 border-t border-border/50",children:o.jsxs("p",{className:"text-text-muted text-[10px]",children:[i," outgoing transition",i!==1?"s":""," — drag from the bottom port to connect."]})})]})}const kv=[];function P0({isOpen:e,onClose:r,initialEditId:s}){const i=Nt(me=>me.defaults),c=Nt(me=>me.userItems),u=Nt(me=>me.loading),h=Nt(me=>me.templateVariables),l=Nt(me=>me.fetchWorkflows),d=Nt(me=>me.fetchWorkflow),f=Nt(me=>me.fetchDefaultContent),g=Nt(me=>me.fetchTemplateVariables),m=Nt(me=>me.createWorkflow),v=Nt(me=>me.updateWorkflow),S=Nt(me=>me.deleteWorkflow),{requestDelete:k,clearConfirm:C,isConfirming:y}=qh(),[b,x]=P.useState("list"),[_,j]=P.useState(null),[A,N]=P.useState(!1),[D,T]=P.useState(null),[z,O]=P.useState(null),[q,V]=P.useState(""),[W,I]=P.useState(""),[$,B]=P.useState(""),[X,Q]=P.useState("1.0.0"),[H,L]=P.useState("#3b82f6"),[R,U]=P.useState(""),[F,ne]=P.useState(50),[Z,ee]=P.useState(kv),[Y,G]=P.useState({type:"always"}),[ae,re]=P.useState(""),[be,ve]=P.useState(!1),[Re,Oe]=P.useState([]),[ze]=P.useState(null);P.useEffect(()=>{e&&(l(),g(),ke("/api/agents").then(me=>me.json()).then(me=>Oe(me.agents??[])).catch(()=>{}),T(null),O(null),s?i.some(ye=>ye.id===s)?f(s).then(ye=>{ye&&(V(ye.metadata.name+" (copy)"),I(`${s}-copy-${Date.now()}`),B(ye.metadata.description),Q(ye.metadata.version),L(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),G(ye.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))}):d(s).then(ye=>{ye&&(V(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Q(ye.metadata.version),L(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),G(ye.startCondition??{type:"always"}),re(""),j(s),N(!1),x("edit"))}):(x("list"),j(null),N(!1)))},[e,l,d,f,g,s]);const We=async me=>{const ye=await d(me);ye&&(j(me),V(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Q(ye.metadata.version),L(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),G(ye.startCondition??{type:"always"}),re(""),T(null),O(null),x("edit"))},Ee=async()=>{var Qe;const me=_??W;if(!me||!q)return re("Name is required."),!1;if(Z.length===0)return re("Add at least one step."),!1;let ye=R;if(!ye||!Z.some(He=>He.id===ye)){if(ye=((Qe=Z.find(He=>He.id))==null?void 0:Qe.id)??"",!ye)return re("All steps need an ID."),!1;U(ye)}ve(!0),re("");const we={metadata:{id:me,name:q,description:$,version:X||"1.0.0",color:H},entryStep:ye,settings:{maxIterations:F},steps:Z,startCondition:Y},Ve=_?await v(_,we):await m(we);return ve(!1),Ve.success?(_||j(me),!0):(re(Ve.error??"Failed to save."),!1)},fe=async()=>{await Ee()},je=async()=>{await Ee()&&(s?r():x("list"))},Ue=()=>{s?r():x("list")},It=me=>{V(me),_||I(qA(me))},pe=async me=>{if(i.some(we=>we.id===me)){const we=await f(me);if(!we)return;V(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Q(we.metadata.version),L(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),G(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}else{const we=await d(me);if(!we)return;V(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Q(we.metadata.version),L(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),G(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}x("edit")},Ne=async me=>{const we=i.some(Ve=>Ve.id===me)?await f(me):await d(me);we&&(V(we.metadata.name+" (copy)"),I(`${me}-copy-${Date.now()}`),B(we.metadata.description),Q(we.metadata.version),L(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),G(we.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))},Me=()=>{j(null),V(""),I(""),B(""),Q("1.0.0"),L("#3b82f6"),U(""),ne(50),ee(structuredClone(kv)),G({type:"always"}),re(""),T(null),O(null),N(!1),x("edit")},lt=async me=>{await S(me),C()},ue=P.useCallback(me=>{T(me),O(null)},[]),_e=P.useCallback(me=>{O(me),T(null)},[]),Te=D!==null?Number(D):-1,Ie=Te>=0?Z[Te]??null:null,$e=P.useCallback(me=>{ee(ye=>ye.map((we,Ve)=>Ve===Te?me:we))},[Te]),St=Y.type==="step_result"?`${Y.result}`:B0[Y.type]??Y.type,Ye=()=>{const me=Z.length,ye=WA(Z),we=Re.find(Ve=>!Ve.subagent);ee([...Z,{id:ye,name:(we==null?void 0:we.name)??"Agent",type:"agent",phase:"build",toolMode:(we==null?void 0:we.id)??"builder",transitions:[]}]),R||U(ye),ue(String(me))},Dt=P.useCallback((me,ye)=>{me==="$start"?(U(ye),_e("start")):ee(we=>{const Ve=we.find(He=>He.id===me),Qe=Ve?Ve.transitions.length:0;return _e(`${me}:${Qe}`),we.map(He=>He.id===me?{...He,transitions:[...He.transitions,{when:{type:"always"},goto:ye}]}:He)})},[_e]),gt=P.useCallback((me,ye)=>{if(me==="start")U(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Zt=>Zt.id===Ve?{...Zt,transitions:Zt.transitions.map((Lt,Bt)=>Bt===Qe?{...Lt,goto:ye}:Lt)}:Zt))}},[]),Xt=P.useCallback((me,ye)=>{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>{const Zt=He.find(Bt=>Bt.id===Ve);if(!Zt)return He;const Lt=Zt.transitions[Qe];return Lt?He.map(Bt=>Bt.id===Ve?{...Bt,transitions:Bt.transitions.filter((qr,oe)=>oe!==Qe)}:Bt.id===ye?{...Bt,transitions:[...Bt.transitions,Lt]}:Bt):He}),O(null)},[]),ct=P.useCallback(me=>{if(me==="start")U("");else{const ye=me.lastIndexOf(":"),we=me.slice(0,ye),Ve=parseInt(me.slice(ye+1));ee(Qe=>Qe.map(He=>He.id===we?{...He,transitions:He.transitions.filter((Zt,Lt)=>Lt!==Ve)}:He))}O(null)},[]),qn=P.useCallback((me,ye)=>{if(me==="start")G(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Zt=>Zt.id===Ve?{...Zt,transitions:Zt.transitions.map((Lt,Bt)=>Bt===Qe?{...Lt,when:ye}:Lt)}:Zt))}},[]),sn=me=>Df(me,Re).name,Zi=()=>{if(!z)return null;if(z==="start"){const Lt=Z.find(Bt=>Bt.id===R);return{type:"start",fromLabel:"Start",toLabel:Lt?sn(Lt):"(none)",condition:Y}}const me=z.lastIndexOf(":"),ye=z.slice(0,me),we=parseInt(z.slice(me+1)),Ve=Z.find(Lt=>Lt.id===ye);if(!Ve)return null;const Qe=Ve.transitions[we];if(!Qe)return null;const He=Z.find(Lt=>Lt.id===Qe.goto),Zt=Qe.goto==="$done"?"Done":He?sn(He):Qe.goto;return{type:"step",fromLabel:sn(Ve),toLabel:Zt,condition:Qe.when}};if(b==="edit"){const me=Zi();return o.jsxs(At,{isOpen:e,onClose:Ue,title:A?q:_?"Edit Workflow":"New Workflow",size:"full",children:[ae&&o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:ae}),o.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[o.jsxs("div",{className:"min-w-[140px]",children:[o.jsx("label",{className:fn,children:"Name"}),o.jsx("input",{value:q,onChange:ye=>It(ye.target.value),placeholder:"Workflow name",className:`${ar} ${A?"opacity-50":""}`,readOnly:A})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:fn,children:"ID"}),o.jsx("input",{value:W,readOnly:!0,className:`${ar} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:fn,children:"Description"}),o.jsx("input",{value:$,onChange:ye=>!A&&B(ye.target.value),readOnly:A,placeholder:"What does this workflow do?",className:`${ar} ${A?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:fn,children:"Max Iter."}),o.jsx("input",{type:"number",value:F,onChange:ye=>!A&&ne(Number(ye.target.value)),readOnly:A,className:`${ar} font-mono ${A?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Color"}),o.jsx("input",{type:"color",value:H,onChange:ye=>!A&&L(ye.target.value),disabled:A,className:`w-8 h-8 rounded border border-border bg-transparent ${A?"opacity-50":"cursor-pointer"}`})]})]}),o.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[o.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!A&&o.jsx("button",{onClick:Ye,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),o.jsxs("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:[o.jsx(KA,{steps:Z,entryStep:R,selectedNodeId:(Ie==null?void 0:Ie.id)??null,selectedEdgeKey:z,startConditionLabel:St,agentTypes:Re,isReadOnly:A,onSelectNode:ye=>{if(ye===null){ue(null);return}const we=Z.findIndex(Ve=>Ve.id===ye);ue(we>=0?String(we):null)},onSelectEdge:_e,onRemoveStep:ye=>{var Ve;const we=Z.findIndex(Qe=>Qe.id===ye);if(ee(Qe=>Qe.filter(He=>He.id!==ye)),Te===we&&ue(null),R===ye){const Qe=Z.filter(He=>He.id!==ye);U(((Ve=Qe[0])==null?void 0:Ve.id)??"")}},onCreateTransition:Dt,onReconnectTo:gt,onReconnectFrom:Xt,onDeleteTransition:ct}),Z.length===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[o.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),o.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"})]})]})]}),o.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[o.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),o.jsx("div",{className:"p-3 overflow-y-auto flex-1 min-h-0",children:A&&(me||Ie)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):me?me.type==="start"?o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),R&&o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),o.jsx(Vv,{}),o.jsx("span",{className:"text-text-primary font-medium",children:me.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Activation Condition"}),o.jsx("select",{value:Y.type,onChange:ye=>G(ye.target.value==="step_result"?{type:"step_result",result:"success"}:{type:ye.target.value}),className:qs,children:z0.map(ye=>o.jsx("option",{value:ye.value,children:ye.label},ye.value))})]}),Y.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),R&&(()=>{const ye=Z.find(He=>He.id===R),we=ye&&(ye.type==="sub_agent"||ye.type==="agent")?Re.find(He=>He.id===(ye.type==="sub_agent"?ye.subAgentType:ye.toolMode)):void 0,Ve=(we==null?void 0:we.results)&&we.results.length>0,Qe=(we==null?void 0:we.results)??[];return Ve?o.jsx("select",{value:Y.result??Qe[0],onChange:He=>G({type:"step_result",result:He.target.value}),className:qs,children:Qe.map(He=>o.jsx("option",{value:He,children:He},He))}):o.jsx("input",{type:"text",value:Y.result??"success",onChange:He=>G({type:"step_result",result:He.target.value}),placeholder:"e.g. success, passed, failed",className:ar})})()]}),o.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."})]}):o.jsx(YA,{fromLabel:me.fromLabel,toLabel:me.toLabel,condition:me.condition,fromStep:me.type==="step"?Z.find(ye=>ye.id===me.fromLabel):void 0,agentTypes:Re,onUpdateCondition:ye=>qn(z,ye),onDelete:()=>ct(z)}):Ie?o.jsx(XA,{step:Ie,isEntry:Ie.id===R,agentTypes:Re,transitionCount:Ie.transitions.length,templateVariables:h,onUpdate:$e,onRemove:()=>{var ye;if(Ie&&(ee(Z.filter((we,Ve)=>Ve!==Te)),ue(null),R===Ie.id)){const we=Z.filter((Ve,Qe)=>Qe!==Te);U(((ye=we[0])==null?void 0:ye.id)??"")}},onSetEntry:()=>U(Ie.id)}):o.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",o.jsx("br",{}),"Drag from a port to connect."]})})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border",children:[o.jsx(nt,{variant:"secondary",onClick:Ue,children:"Close"}),A?o.jsx(nt,{variant:"primary",onClick:()=>{V(q+" (copy)"),I(`${_}-copy-${Date.now()}`),j(null),N(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(nt,{variant:"secondary",onClick:fe,disabled:be||!q,children:be?"Saving...":"Save"}),o.jsx(nt,{variant:"primary",onClick:je,disabled:be||!q,children:"Save & Close"})]})]})]})}return o.jsxs(At,{isOpen:e,onClose:r,title:"Workflows",size:"lg",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:"Workflows define the orchestrator's step sequence when running tasks."}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(nt,{variant:"primary",size:"sm",onClick:Me,children:"+ New"})})]}),u&&i.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading workflows..."}):i.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No workflows installed."}):o.jsxs("div",{className:"space-y-4",children:[i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:i.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx("button",{onClick:()=>pe(me.id),className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(oo,{onClick:()=>Ne(me.id)})]})]},me.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(oo,{onClick:()=>Ne(me.id)}),o.jsx(Wi,{onClick:()=>We(me.id)}),y(me.id,"delete")?o.jsx(Wh,{onConfirm:()=>lt(me.id),onCancel:()=>{}}):o.jsx(Vh,{onClick:()=>k(me.id)})]})]},me.id))})]})]})]})}function ZA(e,r){const s=e.startCondition;if(!s||s.type==="always")return!0;switch(s.type){case"has_pending_criteria":return r.some(i=>i.status.type!=="passed");case"all_criteria_passed":return r.length===0||r.every(i=>i.status.type==="passed");case"all_criteria_completed_or_passed":return r.every(i=>i.status.type==="completed"||i.status.type==="passed");case"any_criteria_blocked":return r.some(i=>i.status.type==="failed"&&i.attempts.filter(c=>c.status==="failed").length>=4);case"step_result":return null;default:return null}}function QA({onSendCommand:e,onSelectWorkflow:r,onOpenCommandsManager:s,onOpenWorkflowsManager:i,onAttach:c,textareaContent:u,attachments:h,criteria:l}){const[d,f]=P.useState(!1),[g,m]=P.useState("commands"),[v,S]=P.useState(""),[k,C]=P.useState(0),[y,b]=P.useState(null),[x,_]=P.useState(null),j=P.useRef(null),A=P.useRef(null),N=hn(U=>U.defaults),D=hn(U=>U.userItems),T=hn(U=>U.fetchCommands),z=Nt(U=>U.defaults),O=Nt(U=>U.userItems),q=Nt(U=>U.fetchWorkflows),V=[...N,...D],W=[...z,...O];P.useEffect(()=>{d&&(g==="commands"?T():g==="workflows"&&q())},[d,g,T,q]),P.useEffect(()=>{d&&(S(""),C(0),requestAnimationFrame(()=>{var U;return(U=j.current)==null?void 0:U.focus()}))},[d,g]),P.useEffect(()=>{if(!d)return;const U=F=>{var ne;(ne=A.current)!=null&&ne.contains(F.target)||f(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[d]);const I=U=>{switch(U.key){case"ArrowDown":U.preventDefault(),C(F=>{const Z=(g==="commands"?V:W).filter(ee=>{const Y=v.toLowerCase();return!Y||ee.name.toLowerCase().includes(Y)});return Math.min(F+1,Z.length-1)});break;case"ArrowUp":U.preventDefault(),C(F=>Math.max(F-1,0));break;case"Enter":U.preventDefault();break;case"Escape":U.preventDefault(),f(!1);break}},$=U=>{S(U),C(0)},B=V.filter(U=>!v||U.name.toLowerCase().includes(v.toLowerCase())),X=W.filter(U=>!v||U.name.toLowerCase().includes(v.toLowerCase())),Q=async U=>{const F=await hn.getState().fetchCommand(U);F&&e(F.prompt,F.metadata.agentMode,u,h),f(!1)},H=U=>{r(U),f(!1)},L=(U,F)=>{F.stopPropagation(),f(!1),b(U)},R=(U,F)=>{F.stopPropagation(),f(!1),_(U)};return o.jsxs("div",{ref:A,className:"relative",children:[o.jsx("button",{type:"button",onClick:()=>f(!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:o.jsx(Gv,{className:"w-4 h-4"})}),d&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[o.jsxs("div",{className:"flex border-b border-border",children:[o.jsx("button",{type:"button",onClick:()=>{m("commands"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),o.jsx("button",{type:"button",onClick:()=>{m("workflows"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),o.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),g!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:j,value:v,onChange:U=>$(U.target.value),onKeyDown:I,placeholder:g==="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"})}),o.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:g==="commands"?B.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:V.length===0?"No commands yet":"No matches"}):B.map((U,F)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>Q(U.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:U.name})}),o.jsx(Wi,{className:"opacity-0 group-hover:opacity-100",onClick:ne=>L(U.id,ne)})]},U.id)):g==="workflows"?X.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):X.map((U,F)=>{const ne=ZA(U,l),Z=U.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>H(U.id),className:"flex-1 text-left flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:Z}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:U.name}),ne!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:ne?"#22c55e":"#6b7280"},title:ne?"Entry condition met":"Entry condition not met"})]}),o.jsx(Wi,{className:"opacity-0 group-hover:opacity-100",onClick:ee=>R(U.id,ee)})]},U.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{c(),f(!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:[o.jsx(fw,{className:"w-4 h-4"}),o.jsx("span",{className:"text-sm font-medium",children:"Attach image"})]}),o.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),g!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{f(!1),g==="commands"?s():i()},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:g==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(I0,{isOpen:!!y,onClose:()=>b(null),initialEditId:y}),o.jsx(P0,{isOpen:!!x,onClose:()=>_(null),initialEditId:x})]})}function H0(e,r){if(!r)return!0;const s=r.toLowerCase().split(/\s+/),i=e.toLowerCase().split(/\s+/);return s.every(c=>{for(const u of i){let h=0;for(let l=0;l<u.length&&h<c.length;l++)u[l]===c[h]&&h++;if(h===c.length)return!0}return!1})}function F0(e,r,s,i,c){switch(e.key){case"ArrowDown":e.preventDefault(),s(u=>Math.min(u+1,r));break;case"ArrowUp":e.preventDefault(),s(u=>Math.max(u-1,0));break;case"Enter":e.preventDefault(),i();break;case"Escape":e.preventDefault(),c();break}}function JA({isOpen:e,onClose:r,onCloseComplete:s,onSelectCommand:i,onSelectWorkflow:c,onCloseCompleteAction:u,textareaContent:h,onSearchMessages:l,onToggleAutoScroll:d,isAutoScrollActive:f}){const[,g]=lr(),m=hn(R=>R.fetchCommands),v=Nt(R=>R.fetchWorkflows),S=Tt(R=>R.fetchAgents),k=hn(R=>R.defaults),C=hn(R=>R.userItems),y=Nt(R=>R.defaults),b=Nt(R=>R.userItems),x=Tt(R=>R.defaults),_=Tt(R=>R.userItems),j=Ce(R=>{var U;return(U=R.currentSession)==null?void 0:U.mode}),A=Ce(R=>{var U;return((U=R.currentSession)==null?void 0:U.dangerLevel)??"normal"}),N=Ce(R=>R.switchMode),D=Ce(R=>R.switchDangerLevel),T=Ce(R=>{var U;return(U=R.currentSession)==null?void 0:U.projectId}),z=P.useRef(void 0),[O,q]=P.useState(""),[V,W]=P.useState(0),I=P.useRef(null),$=P.useRef(!1);P.useEffect(()=>{e&&($.current=!0)},[e]),P.useEffect(()=>{if(e){m(),v(),S(),q(""),W(0);const R=setTimeout(()=>{var U;return(U=I.current)==null?void 0:U.focus()},50);return()=>clearTimeout(R)}},[e,m,v,S]),P.useEffect(()=>{var R;!e&&$.current&&(s==null||s(),(R=z.current)==null||R.call(z),z.current=void 0)},[e,s]);const B=(R,U)=>{const F=new Set(U.map(ne=>ne.id));return[...R.filter(ne=>!F.has(ne.id)),...U]},Q=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>T&&g(`/p/${T}/new`)},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{z.current=u,r()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{r(),l==null||l()}},{id:"toggle-autoscroll",name:f?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{r(),d==null||d(!f)}},...B(x,_).filter(R=>!R.subagent&&R.id!==j).map(R=>({id:R.id,name:R.name,prefix:"Agent > Switch to",action:()=>N(R.id)})),...B(k,C).map(R=>({id:R.id,name:R.name,prefix:"Command > Launch",action:()=>i(R.id,h)})),...B(y,b).map(R=>({id:R.id,name:R.name,prefix:"Workflow > Run",action:()=>c(R.id)})),...["normal","dangerous"].filter(R=>R!==A).map(R=>({id:R,name:R.charAt(0).toUpperCase()+R.slice(1),prefix:"Mode > Switch to",action:()=>D(R)}))].filter(R=>H0(`${R.prefix} ${R.name}`,O)),H=Q.length-1,L=R=>{F0(R,H,W,()=>{var U;(U=Q[V])==null||U.action(),r()},r)};return e?Ki.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:r}),o.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[o.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[o.jsx("input",{ref:I,type:"text",value:O,onChange:R=>{q(R.target.value),W(0)},onKeyDown:L,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(Uh,{onClick:r,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:Q.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:k.length+C.length+y.length+b.length>0?"No matches":"No agents, commands, or workflows yet"}):Q.map((R,U)=>o.jsxs("button",{type:"button",onClick:()=>{R.action(),r()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${U===V?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:[o.jsxs("span",{className:"text-text-muted font-normal",children:[R.prefix," "]}),o.jsx("span",{children:R.name})]},R.id))})]})]}),document.body):null}function e4(e){const r=new Date(e),s=new Date;if(r.getDate()===s.getDate()&&r.getMonth()===s.getMonth()&&r.getFullYear()===s.getFullYear())return r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const c=r.getFullYear(),u=String(r.getMonth()+1).padStart(2,"0"),h=String(r.getDate()).padStart(2,"0"),l=String(r.getHours()).padStart(2,"0"),d=String(r.getMinutes()).padStart(2,"0");return`${c}/${u}/${h} ${l}:${d}`}function t4({isOpen:e,onClose:r,messages:s,onSelectMessage:i}){const[c,u]=P.useState(""),[h,l]=P.useState(0),d=P.useRef(null),f=P.useRef(!1),g=s.filter(C=>C.role==="user"&&!C.isSystemGenerated&&C.messageKind!=="auto-prompt"&&C.messageKind!=="command");P.useEffect(()=>{e&&(f.current=!0)},[e]),P.useEffect(()=>{if(e){u(""),l(0);const C=setTimeout(()=>{var y;return(y=d.current)==null?void 0:y.focus()},50);return()=>clearTimeout(C)}},[e]);const m=g.filter(C=>H0(C.content,c)),v=m.length-1,S=C=>{F0(C,v,l,()=>{m[h]&&(i(m[h].id),r())},r)},k=C=>{i(C),r()};return e?Ki.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:r}),o.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[o.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[o.jsx(Hh,{}),o.jsx("input",{ref:d,type:"text",value:c,onChange:C=>{u(C.target.value),l(0)},onKeyDown:S,placeholder:"Search messages...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx("button",{type:"button",onClick:r,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:o.jsx(Fh,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:m.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:g.length>0?"No matches":"No messages yet"}):m.map((C,y)=>o.jsx("button",{type:"button",onClick:()=>k(C.id),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${y===h?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("span",{className:"truncate flex-1",children:C.content}),o.jsx("span",{className:"text-text-muted text-xs shrink-0",children:e4(C.timestamp)})]})},C.id))})]})]}),document.body):null}function n4(e){return e==="criterion"}function r4(e){var r,s;return e.role!=="assistant"||e.subAgentId||(r=e.content)!=null&&r.trim()||(s=e.thinkingContent)!=null&&s.trim()||!e.toolCalls||e.toolCalls.length===0?!1:e.toolCalls.every(i=>n4(i.name))}function s4(e,r=[]){const s=[];let i=null,c=[],u,h=1;const l=new Map,d=new Map,f=[];for(const S of r)S.type==="message"?l.set(S.message.id,S):S.type==="subagent"?d.set(S.subAgentId,S):S.type==="criteria-batch"&&f.push(S);let g=0;const m=()=>{if(c.length>0){const S=f[g];S&&S.type==="criteria-batch"&&S.toolCalls.length===c.length&&S.toolCalls.every((C,y)=>{var b;return C.id===((b=c[y])==null?void 0:b.id)})?s.push(S):s.push({type:"criteria-batch",toolCalls:[...c]}),g++,c=[]}},v=()=>{if(!i)return;const S=i,k=d.get(S.subAgentId);k&&k.type==="subagent"&&k.messages.length===S.messages.length&&k.messages.every((y,b)=>y===S.messages[b])?s.push(k):s.push({type:"subagent",subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:S.messages}),i=null};for(const S of e)if(S.role!=="tool"){if(S.contextWindowId&&u&&S.contextWindowId!==u&&(m(),v(),h++,s.push({type:"context-divider",windowSequence:h})),u=S.contextWindowId,r4(S)){v();for(const k of S.toolCalls)c.push(k);continue}if(m(),S.subAgentId&&S.subAgentType)i&&i.subAgentId===S.subAgentId?i.messages.push(S):(v(),i={subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:[S]});else{v();const k=l.get(S.id);k&&k.type==="message"&&k.message===S?s.push(k):s.push({type:"message",message:S})}}return m(),v(),s}function i4(e){const{year:r,month:s,day:i}=sy(e);return`${r}/${s}/${i} ${uc(e)}`}function a4(e,r){return e.length<=r?e:e.substring(0,r)+"..."}const o4=10,l4=150;function c4(e){const r=[];if(e.recentUserPrompts)for(const s of e.recentUserPrompts)r.push({id:s.id,content:s.content,timestamp:s.timestamp,sessionId:e.id,sessionName:e.title||e.id});return r}function u4(e){return[...e].sort((i,c)=>new Date(c.timestamp).getTime()-new Date(i.timestamp).getTime()).slice(0,o4).reverse().map(i=>({id:i.id,content:i.content,timestamp:i.timestamp,formattedTimestamp:i4(i.timestamp),trimmedContent:a4(i.content,l4),sessionId:i.sessionId,sessionName:i.sessionName}))}function d4(e,r,s){const i=[],c=e.filter(u=>u.role==="user"&&!u.isSystemGenerated&&u.messageKind!=="auto-prompt");for(const u of c)i.push({id:u.id,content:u.content,timestamp:u.timestamp,sessionId:s??"",sessionName:"This session"});for(const u of r)s&&u.id===s||i.push(...c4(u));return u4(i)}function h4(e,r=[],s=null){const[i,c]=P.useState(0),[u,h]=P.useState(!1),l=P.useMemo(()=>d4(e,r,s),[e,r,s]),d=P.useCallback(()=>{l.length>0&&(c(l.length-1),h(!0))},[l.length]),f=P.useCallback(()=>{h(!1),c(0)},[]),g=P.useCallback(()=>{c(S=>l.length===0?S:S===0?l.length-1:S-1)},[l.length]),m=P.useCallback(()=>{c(S=>l.length===0?S:S===l.length-1?0:S+1)},[l.length]),v=P.useCallback(()=>{if(l.length===0||!u)return null;const S=l[i];return(S==null?void 0:S.content)??null},[l,i,u]);return{history:l,selectedIndex:i,showHistory:u,openHistory:d,closeHistory:f,navigateUp:g,navigateDown:m,selectCurrent:v}}function f4({criteriaSidebarOpen:e,onCriteriaSidebarToggle:r}={}){const s=e??!0,[i,c]=P.useState(""),[u,h]=P.useState([]),[l,d]=P.useState(!1),[f,g]=P.useState(null),[m,v]=P.useState(!1),[S,k]=P.useState(!1),[C,y]=P.useState(!1),[b,x]=P.useState(!1),[_,j]=P.useState(null),[A,N]=P.useState(null),D=P.useRef(null),T=P.useRef(null),z=P.useRef(null),O=Ce(oe=>oe.currentSession),q=Ce(oe=>oe.messages),V=Ce(oe=>oe.streamingMessage),W=Ce(oe=>oe.sessions),I=Ce(oe=>oe.error),$=Ce(oe=>oe.pendingQuestion),B=qv(),X=Ce(oe=>oe.sendMessage),Q=Ce(oe=>oe.clearError),H=Ce(oe=>oe.acceptAndBuild),L=Ce(oe=>oe.stopGeneration),R=Ce(oe=>oe.launchRunner),U=Ce(oe=>oe.cancelQueued),F=ow(),{showThinking:ne,showVerboseToolOutput:Z,showStats:ee,showAgentDefinitions:Y,showWorkflowBars:G}=Dh(),ae=Nt(oe=>oe.defaults),re=Nt(oe=>oe.userItems),be=[...ae,...re],ve=Nt(oe=>oe.fetchWorkflows),Re=Tt(oe=>oe.defaults),Oe=Tt(oe=>oe.userItems),ze=[...Re,...Oe].filter(oe=>!oe.subagent);P.useEffect(()=>{ve()},[ve]);const{history:We,selectedIndex:Ee,showHistory:fe,openHistory:je,closeHistory:Ue,navigateUp:It,navigateDown:pe,selectCurrent:Ne}=h4(q,W,O==null?void 0:O.id),Me=P.useCallback(oe=>{j(oe),St(!1);const Ae=document.querySelector(`[data-message-id="${oe}"]`);Ae&&Ae.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>j(null),3e3)},[]);P.useEffect(()=>{const oe=Ae=>{N(Ae.detail.stats)};return window.addEventListener("open-turn-stats",oe),()=>window.removeEventListener("open-turn-stats",oe)},[]);const lt=P.useMemo(()=>V?q.map(oe=>oe.id===V.id?V:oe):q,[q,V]),ue=P.useRef([]),_e=P.useMemo(()=>{const oe=s4(lt,ue.current);return ue.current=oe,oe},[lt]),Te=P.useMemo(()=>IA(q),[q]),{force_scroll_to_bottom:Ie,isAutoScrollActive:$e,setAutoScroll:St}=O0(D,O),Ye=P.useCallback(()=>{const oe=T.current;if(!oe)return;oe.style.height="auto";const Ae=Math.min(200,oe.scrollHeight);oe.style.height=`${Ae}px`},[]);P.useEffect(()=>{if(!(O!=null&&O.id))return;const oe=`openfox:draft:${O.id}`,Ae=localStorage.getItem(oe);Ae!==null&&c(Ae)},[O==null?void 0:O.id]),P.useEffect(()=>{var oe;(oe=T.current)==null||oe.focus(),Ye()},[O==null?void 0:O.id,Ye]),P.useEffect(()=>{if(!(O!=null&&O.id))return;const oe=`openfox:draft:${O.id}`,Ae=setTimeout(()=>{i?localStorage.setItem(oe,i):localStorage.removeItem(oe)},500);return()=>clearTimeout(Ae)},[O==null?void 0:O.id,i]),P.useEffect(()=>{Ye()},[i,Ye]),P.useEffect(()=>{const oe=Ae=>{Ae.key==="Escape"&&B&&L(),Ae.key==="ScrollLock"&&St(!$e)};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[B,L,$e]);const Dt=P.useRef(0);P.useEffect(()=>{const oe=Ae=>{if(Ae.key==="Shift"&&!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey){const qe=Date.now();qe-Dt.current<300?(Ae.preventDefault(),y(!0),Dt.current=0):Dt.current=qe}};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[]),P.useEffect(()=>{const oe=T.current;if(!oe)return;const Ae=async qe=>{var en;if(document.activeElement!==oe)return;const Ct=(en=qe.clipboardData)==null?void 0:en.items;if(Ct){for(const _n of Array.from(Ct))if(_n.type.startsWith("image/")){qe.preventDefault();const yr=_n.getAsFile();if(!yr)continue;await ch(yr,Xs=>h(Sn=>[...Sn,Xs]),g,{filename:"pasted-image"})}}};return oe.addEventListener("paste",Ae),()=>oe.removeEventListener("paste",Ae)},[]);const gt=()=>{c(""),h([]),O!=null&&O.id&&localStorage.removeItem(`openfox:draft:${O.id}`)},Xt=async oe=>{oe.preventDefault(),!(!i.trim()&&u.length===0)&&(Ie(),X(i,u.length>0?u:void 0),gt())},ct=oe=>{if((oe.ctrlKey||oe.metaKey)&&oe.code.startsWith("Digit")){const qe=parseInt(oe.code.slice(-1),10)-1,Ct=ze[qe];Ct&&(oe.preventDefault(),Ce.getState().switchMode(Ct.id));return}if(fe)switch(oe.key){case"Enter":oe.preventDefault();const Ae=Ne();Ae&&(c(Ae),Ue());return;case"Escape":oe.preventDefault(),Ue(),B&&L();return;case"ArrowUp":oe.preventDefault(),It();return;case"ArrowDown":oe.preventDefault(),pe();return}if(oe.key==="ArrowUp"&&i.trim()===""&&!fe){oe.preventDefault(),je();return}oe.key==="Enter"&&!oe.shiftKey&&(oe.preventDefault(),Xt(oe))},qn=P.useCallback(async oe=>{const Ae=oe.target.files;if(!(!Ae||Ae.length===0)){g(null);for(const qe of Array.from(Ae))await ch(qe,Ct=>h(en=>[...en,Ct]),g);z.current&&(z.current.value="")}},[]),sn=P.useCallback(oe=>{oe.preventDefault(),oe.stopPropagation(),d(!0)},[]),Zi=P.useCallback(oe=>{oe.preventDefault(),oe.stopPropagation(),d(!1)},[]),me=P.useCallback(async oe=>{oe.preventDefault(),oe.stopPropagation(),d(!1),g(null);const Ae=oe.dataTransfer.files;if(!(!Ae||Ae.length===0))for(const qe of Array.from(Ae))await ch(qe,Ct=>h(en=>[...en,Ct]),g)},[]),ye=P.useCallback(oe=>{h(Ae=>Ae.filter(qe=>qe.id!==oe))},[]),we=P.useCallback(()=>{var oe;(oe=z.current)==null||oe.click()},[]),Ve=(O==null?void 0:O.mode)==="planner",Qe=(O==null?void 0:O.mode)==="builder",He=((O==null?void 0:O.criteria.length)??0)>0,Zt=(O==null?void 0:O.phase)==="done",Lt=_e.some(oe=>oe.type==="message"&&oe.message.role==="assistant"),Bt=Ve&&He&&!B&&Lt&&!Zt,qr=oe=>{const Ae=i.trim()?i:void 0,qe=u.length>0?u:void 0;Ve?H(oe,Ae,qe):Qe&&R(Ae,qe,oe),gt()};return o.jsxs(o.Fragment,{children:[o.jsxs(t2,{criteriaSidebarOpen:s,onCriteriaSidebarToggle:r,messages:lt,children:[$&&o.jsx(yA,{question:$}),o.jsx(s2,{}),A&&o.jsx(uA,{stats:A,onClose:()=>N(null)}),o.jsx(_A,{}),o.jsxs("div",{ref:D,"data-testid":"chat-scroll-container",className:"flex-1 min-w-0 overflow-y-auto relative bg-primary",children:[o.jsx("div",{className:"pt-4",children:_e.map((oe,Ae)=>{if(oe.type==="context-divider")return o.jsxs("div",{className:"flex items-center gap-2 feed-item px-2 md:px-4",children:[o.jsx("div",{className:"flex-1 border-t border-border"}),o.jsx("span",{className:"text-[10px] text-text-muted font-medium px-2",children:"Earlier context summarized"}),o.jsx("div",{className:"flex-1 border-t border-border"})]},Ae);if(oe.type==="subagent"){const _n=oe.messages.some(yr=>yr.isStreaming);return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(pA,{messages:oe.messages,subAgentType:oe.subAgentType,subAgentId:oe.subAgentId,isStreaming:_n})},Ae)}if(oe.type==="criteria-batch")return o.jsx("div",{className:"feed-item px-2 md:px-4",children:o.jsx(R0,{toolCalls:oe.toolCalls,criteria:O==null?void 0:O.criteria})},Ae);const qe=oe.message;if(qe.role==="assistant")return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(Tf,{message:qe,showStats:ee,showThinking:ne,showVerboseToolOutput:Z})},Ae);const Ct=!Y&&qe.messageKind==="auto-prompt",en=!G&&(qe.messageKind==="workflow-started"||qe.messageKind==="task-completed");return Ct||en?null:o.jsx("div",{className:"px-2 md:px-4",children:o.jsx("div",{"data-message-id":qe.id,className:_===qe.id?"rounded animate-highlight-fade":void 0,children:o.jsx(L0,{message:qe,isLastAssistantMessage:!1,promptContext:qe.role==="user"?Te[qe.id]:void 0})})},Ae)})}),o.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[I&&o.jsx("div",{className:"feed-item bg-red-500/10 border border-red-500/50 rounded p-2",children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-red-400 text-sm font-medium",children:I.code}),o.jsx("div",{className:"text-red-300 text-xs mt-0.5",children:I.message})]}),o.jsx(lo,{onClick:Q,className:"text-red-400 hover:text-red-300 p-0.5",size:"sm"})]})}),Bt&&o.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:be.map(oe=>{const Ae=oe.color??"#3b82f6",qe=parseInt(Ae.slice(1,3),16),Ct=parseInt(Ae.slice(3,5),16),en=parseInt(Ae.slice(5,7),16),_n=`rgba(${qe},${Ct},${en},0.12)`,yr=`rgba(${qe},${Ct},${en},0.22)`,Xs=`rgba(${qe},${Ct},${en},0.25)`;return o.jsxs("button",{onClick:()=>H(oe.id),"data-testid":"workflow-run-button",className:"px-4 py-1.5 rounded text-sm font-medium transition-colors",style:{backgroundColor:_n,color:Ae,border:`1px solid ${Xs}`},onMouseEnter:Sn=>{Sn.currentTarget.style.backgroundColor=yr},onMouseLeave:Sn=>{Sn.currentTarget.style.backgroundColor=_n},children:["▶ ",oe.name]},oe.id)})}),B&&o.jsx(SA,{})]})]}),o.jsxs("form",{onSubmit:Xt,className:"relative p-2 md:p-4 bg-secondary",children:[o.jsxs("button",{type:"button",className:"absolute -top-8 right-12 md:right-16 text-sm text-text-muted hover:text-text-primary z-10 flex items-center gap-1.5",onClick:()=>St(!$e),children:[$e?o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):o.jsx(br,{className:"w-3 h-3 text-text-muted"}),$e?"live":"scroll to bottom"]}),o.jsx("button",{type:"button",onClick:()=>x(!0),className:"absolute -top-8 right-2 md:right-4 text-sm text-text-muted hover:text-text-primary z-10 flex items-center p-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Search messages",children:o.jsx(Hh,{})}),o.jsx("input",{ref:z,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:qn,className:"hidden",multiple:!0}),f&&o.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:f}),u.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:u.map(oe=>o.jsx(wA,{attachment:oe,onRemove:ye},oe.id))}),fe&&o.jsx(CA,{history:We,selectedIndex:Ee,onSelect:oe=>{c(oe),Ue()},onEscape:Ue,onNavigate:oe=>{oe==="up"?It():pe()}}),F.length>0&&o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:F.map(oe=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${oe.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:[o.jsxs("span",{className:"font-medium",children:[oe.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:oe.content}),o.jsx(lo,{onClick:()=>U(oe.queueId),size:"sm"})]},oe.queueId))}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${l?"bg-accent-primary/10":"bg-primary"}`,onDragOver:sn,onDragLeave:Zi,onDrop:me,children:[o.jsx("textarea",{id:ty,ref:T,value:i,onChange:oe=>{c(oe.target.value),fe&&Ue()},onKeyDown:ct,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",className:"flex-1 bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:"24px",maxHeight:"200px"},spellCheck:!1}),o.jsxs("div",{className:"flex items-center self-center",children:[o.jsx("button",{type:"button",onClick:()=>{var oe;!i.trim()&&u.length===0||((oe=D.current)==null||oe.scrollTo({top:D.current.scrollHeight,behavior:"smooth"}),X(i,u),gt())},disabled:!i.trim()&&u.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"}),o.jsx(QA,{onSendCommand:(oe,Ae,qe,Ct)=>{var _n;Ae&&(O==null?void 0:O.mode)!==Ae&&Ce.getState().switchMode(Ae);const en=qe&&qe.trim()?`${qe.trim()}
|
|
149
|
+
`,children:[o.jsxs("div",{className:"text-xs text-text-muted font-mono",children:[f.formattedTimestamp,f.sessionName&&o.jsxs(o.Fragment,{children:[" | ",o.jsx("span",{className:"text-accent-primary font-medium",children:f.sessionName})]})]}),o.jsx("div",{className:"text-sm text-text-primary mt-1",children:f.trimmedContent})]},f.id))})}const hn=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchCommands:async()=>{await $h("/api/commands",e)},fetchCommand:async s=>{try{const i=await ke(`/api/commands/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/commands/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createCommand:async s=>{const i=await xs("POST","/api/commands",s);return i.success&&await r().fetchCommands(),i},updateCommand:async(s,i)=>{const c=await xs("PUT",`/api/commands/${s}`,i);return c.success&&await r().fetchCommands(),c},deleteCommand:async s=>{try{const i=await ke(`/api/commands/${s}`,{method:"DELETE"}),c=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:c.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async s=>{try{const i=await ke(`/api/commands/${s}/duplicate`,{method:"POST"}),c=await i.json();return i.ok?(await r().fetchCommands(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}})),kA={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function EA(e,r={}){const s={...kA,...r};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<=s.maxSizeBytes){const c=await e.arrayBuffer(),u=LA(c),h=`data:${e.type};base64,${u}`,l=await M0(h);return{dataUrl:h,mimeType:e.type,size:e.size,width:l.width,height:l.height}}return await jA(e,s)}async function jA(e,r){const s=await TA(e),i=await M0(s),{width:c,height:u}=NA(i.width,i.height,r.maxWidth,r.maxHeight),h=AA();h.width=c,h.height=u;const l=h.getContext("2d");if(!l)throw new Error("Failed to get canvas context");l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(i,0,0,c,u);let d=r.quality,f;do{if(f=h.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),_v(f)<=r.maxSizeBytes||d<=.3)break;d-=.1}while(!0);const g=_v(f);return{dataUrl:f,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:g,width:c,height:u}}function NA(e,r,s,i){const c=e/r;return e>r&&e>s?{width:s,height:Math.round(s/c)}:r>e&&r>i?{width:Math.round(i*c),height:i}:{width:e,height:r}}function TA(e){return new Promise((r,s)=>{const i=RA(),c=new i;c.onload=()=>r(c.result),c.onerror=()=>s(new Error("Failed to read file")),c.readAsDataURL(e)})}function M0(e){return new Promise((r,s)=>{const i=DA(),c=new i;c.onload=()=>r(c),c.onerror=()=>s(new Error("Failed to load image")),c.src=e})}function AA(){var r;const e=Af();if(!((r=e.document)!=null&&r.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function DA(){const e=Af();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function RA(){const e=Af();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function Af(){return globalThis}function LA(e){const r=new Uint8Array(e);let s="";for(let i=0;i<r.byteLength;i++){const c=r[i];c!==void 0&&(s+=String.fromCharCode(c))}return btoa(s)}function _v(e){const s=e.split(",")[1];return s?Math.round(s.length*3/4):0}function OA(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function MA(e,r=50*1024*1024){return e.size>r?{valid:!1,error:`Image file is too large (${Sv(e.size)}). Maximum size is ${Sv(r)}.`}:{valid:!0}}function Sv(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function ch(e,r,s,i={}){const{maxSizeBytes:c=50*1024*1024,filename:u}=i;if(!OA(e)){s(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const h=MA(e,c);if(!h.valid){s(h.error??"Image file is too large");return}try{const l=await EA(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:zv(),filename:u??e.name,mimeType:l.mimeType,size:l.size,data:l.dataUrl};r(d)}catch(l){const d=l instanceof Error?l.message??"Failed to process image":"Failed to process image";s(d)}}function IA(e){const r={};let s=null;for(const i of e){if(i.role==="user"&&!i.isSystemGenerated){s=i.id;continue}i.role==="assistant"&&i.promptContext&&s&&r[s]===void 0&&(r[s]=i.promptContext)}return r}function BA({content:e,children:r,position:s="top",delay:i=200}){const[c,u]=P.useState(!1),[h,l]=P.useState({top:0,left:0}),d=P.useRef(void 0),f=P.useRef(null);P.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=()=>{d.current=setTimeout(()=>{if(f.current){const S=f.current.getBoundingClientRect();l({top:S.top,left:S.left+S.width/2})}u(!0)},i)},m=()=>{d.current&&clearTimeout(d.current),u(!1)},v=(()=>{switch(s){case"top":return{top:h.top-8,left:h.left,tx:"-50%",ty:"-100%"};case"bottom":return{top:h.top+8,left:h.left,tx:"-50%",ty:"0%"};case"left":return{top:h.top,left:h.left-8,tx:"-100%",ty:"-50%"};case"right":return{top:h.top,left:h.left+8,tx:"0%",ty:"-50%"}}})();return o.jsxs(o.Fragment,{children:[o.jsx("span",{ref:f,className:"inline-flex",onMouseEnter:g,onMouseLeave:m,onFocus:g,onBlur:m,children:r}),c&&Ki.createPortal(o.jsx("div",{className:"fixed z-[9999] px-4 py-3 text-sm text-text-primary bg-bg-secondary border border-border rounded-lg shadow-xl max-w-sm break-words pointer-events-none",style:{top:v.top,left:v.left,transform:`translate(${v.tx}, ${v.ty})`},children:e}),document.body)]})}function uh(e){return{contextWindow:e.contextWindow,temperature:e.temperature??null,topP:e.topP??null,topK:e.topK??null,maxTokens:e.maxTokens??null,supportsVision:e.supportsVision??null}}function zA({label:e,children:r}){return o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-sm font-medium text-text-secondary border-b border-border/50 pb-1",children:e}),r]})}function Ja({label:e,value:r,onChange:s,min:i,max:c,step:u=1,helpText:h,defaultValue:l,profileDefault:d,tooltip:f}){const[g,m]=P.useState((r==null?void 0:r.toString())??""),[v,S]=P.useState(r===null);P.useEffect(()=>{m((r==null?void 0:r.toString())??""),S(r===null)},[r]);const k=b=>{if(m(b),b==="")s(null);else{const x=parseFloat(b);isNaN(x)||s(x)}},C=()=>{v?(S(!1),l!==void 0&&(m(l.toString()),s(l))):(S(!0),s(null))},y=o.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-secondary mb-1",children:[f&&o.jsx(BA,{content:f,children:o.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-xs text-text-muted hover:text-text-secondary cursor-help rounded-full border border-border/50",children:"?"})}),e,o.jsx("button",{type:"button",onClick:C,className:`text-xs px-1.5 py-0.5 rounded border ${v?"border-accent-primary/50 bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-secondary"}`,title:v?"Click to set a custom value":"Click to use default",children:v?"default":"custom"})]});return o.jsxs("div",{children:[y,o.jsx("input",{type:"number",min:i,max:c,step:u,value:g,readOnly:v,onChange:b=>k(b.target.value),onClick:()=>v&&C(),placeholder:v?`${d!==void 0?d:"Using default"} (click to edit)`:"",className:`w-full bg-bg-tertiary border border-border rounded px-3 py-2 text-text-primary focus:outline-none focus:border-accent-primary ${v?"opacity-50 cursor-pointer":""}`}),h&&o.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[o.jsx("p",{className:"text-xs text-text-muted",children:h}),d!==void 0&&o.jsxs("span",{className:"text-xs text-text-muted/60",children:["(default: ",d,")"]})]}),!h&&d!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["Profile default: ",d]})]})}function PA({isOpen:e,onClose:r,providerId:s,model:i}){const[c,u]=P.useState(()=>uh(i)),[h,l]=P.useState(!1),d=Rt(m=>m.updateModelSettings);P.useEffect(()=>{u(uh(i))},[i]);const f=async()=>{if(c.contextWindow<1024||c.contextWindow>1e7)return;l(!0);const m=c.temperature!==(i.temperature??null)||c.topP!==(i.topP??null)||c.topK!==(i.topK??null)||c.maxTokens!==(i.maxTokens??null)||c.supportsVision!==(i.supportsVision??null);await d(s,i.id,{contextWindow:c.contextWindow,...m&&{temperature:c.temperature,topP:c.topP,topK:c.topK,maxTokens:c.maxTokens,supportsVision:c.supportsVision??void 0}}),l(!1),r()},g=()=>{u(uh(i)),r()};return e?o.jsx(At,{isOpen:e,onClose:r,title:"Model Properties",size:"lg",footer:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{variant:"secondary",onClick:g,disabled:h,children:"Cancel"}),o.jsx(nt,{variant:"primary",onClick:f,disabled:h||c.contextWindow<1024||c.contextWindow>1e7,children:h?"Saving...":"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Model Name"}),o.jsx("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded font-mono text-sm break-all",children:i.id})]}),o.jsx(Ja,{label:"Context Window",value:c.contextWindow,onChange:m=>m!==null&&u(v=>({...v,contextWindow:m})),min:1024,max:1e7,helpText:"Range: 1,024 - 10,000,000 tokens"}),o.jsxs(zA,{label:"Sampling Parameters",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Ja,{label:"Temperature",value:c.temperature,onChange:m=>u(v=>({...v,temperature:m})),min:0,max:2,step:.1,helpText:"0.0 - 2.0",defaultValue:1,profileDefault:i.defaultTemperature,tooltip:"How random the response is. Low (0.1-0.3) = precise and predictable. High (0.7-1.5) = creative and varied."}),o.jsx(Ja,{label:"Top P",value:c.topP,onChange:m=>u(v=>({...v,topP:m})),min:0,max:1,step:.05,helpText:"0.0 - 1.0",defaultValue:1,profileDefault:i.defaultTopP,tooltip:"How to pick the next word. Low (0.5-0.8) = stick to obvious choices. High (0.95-1.0) = allow surprising words."})]}),o.jsx(Ja,{label:"Top K",value:c.topK,onChange:m=>u(v=>({...v,topK:m})),min:1,max:200,helpText:"1 - 200 (leave as default if not supported)",profileDefault:i.defaultTopK,tooltip:"Restricts word choices to the top K most likely ones. Low (10-20) = focused. High (50-200) = diverse. Not all backends support this."})]}),o.jsx(Ja,{label:"Max Tokens",value:c.maxTokens,onChange:m=>u(v=>({...v,maxTokens:m})),min:256,max:32e3,helpText:"Maximum tokens to generate per response",profileDefault:i.defaultMaxTokens,tooltip:"Longest response length. Higher values let the model write more, but use up your context window faster."}),o.jsxs("div",{children:[o.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-secondary mb-1",children:[o.jsx("input",{type:"checkbox",checked:c.supportsVision??!1,onChange:m=>u(v=>({...v,supportsVision:m.target.checked})),className:"rounded border-border bg-bg-tertiary text-accent-primary focus:ring-accent-primary focus:ring-offset-0"}),"Vision Enabled"]}),o.jsx("p",{className:"text-xs text-text-muted",children:"Allow sending images directly to this model. Disable if the model doesn't support vision."})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Source"}),o.jsxs("p",{className:"text-text-primary bg-bg-tertiary px-3 py-2 rounded text-sm",children:[i.source==="backend"&&"Auto-detected from backend",i.source==="user"&&"Manually set",i.source==="default"&&"Default value"]})]})]})}):null}function HA(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function FA(){var $;const[,e]=lr(),r=Ce(B=>B.currentSession),s=Ce(B=>B.setSessionProvider),[i,c]=P.useState(!1),[u,h]=P.useState([]),[l,d]=P.useState(null),f=P.useRef(null),[g,m]=P.useState(null),v=P.useRef(new Set),S=Rt(B=>B.providers),k=Rt(B=>B.activeProviderId),C=Rt(B=>B.model);Rt(B=>B.backend);const y=Rt(B=>B.llmStatus),b=Rt(B=>B.activating),x=Rt(B=>B.activateProvider),_=Rt(B=>B.refreshModel),j=Rt(B=>B.refreshProviderModels);P.useEffect(()=>{function B(X){f.current&&!f.current.contains(X.target)&&(c(!1),h([]),v.current=new Set)}return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]),P.useEffect(()=>{if(i){const B=S.map(X=>X.id);h(B),B.forEach(X=>{v.current.has(X)||(v.current.add(X),D(X))})}},[i,S]),S.find(B=>B.id===k);const A=y==="disconnected",N=C?(($=C.split("/").pop())==null?void 0:$.replace(/-/g," "))??C:"detecting...",D=async B=>{d(B);try{await j(B)}catch{}finally{d(null)}},T=B=>{u.includes(B.id)?h(u.filter(X=>X!==B.id)):(h([...u,B.id]),D(B.id))},z=async B=>{if(B.id===k){T(B);return}r?(s(B.id,void 0),Rt.getState().syncFromSession(B.id,""),c(!1),h([])):await x(B.id)&&(c(!1),h([]))},O=B=>{T(B)},q=async(B,X)=>{B.stopPropagation(),v.current.delete(X),await j(X),await D(X)},V=(B,X)=>{m({providerId:B,model:X})},W=()=>{m(null)},I=async(B,X)=>{if(console.log("[ProviderSelector.handleModelClick] providerId:",B,"model:",X),r){console.log("[ProviderSelector.handleModelClick] Calling setSessionProvider"),s(B,X),Rt.getState().syncFromSession(B,X),h([]),c(!1);return}d("activating");try{(await ke(`/api/providers/${B}/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:X})})).ok&&(await Rt.getState().fetchConfig(),h([]),c(!1))}catch{}finally{d(null)}};return S.length===0?o.jsxs("button",{type:"button",onClick:()=>_(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:A?"LLM server is offline. Click to retry.":C??"Click to refresh model",children:[A?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx("span",{className:"text-text-muted opacity-0 group-hover:opacity-100 transition-opacity",children:"↻"})]}):o.jsxs("div",{className:"relative",ref:f,children:[o.jsxs("button",{type:"button",onClick:()=>c(!i),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:[A?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsx("span",{className:"text-sm text-accent-primary",children:N}),o.jsx(br,{className:"w-3 h-3 text-text-muted transition-transform",rotate:i?180:0})]}),i&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-72 bg-bg-secondary border border-border rounded-lg shadow-lg z-50 overflow-hidden max-h-[80vh] overflow-y-auto",children:[o.jsx("div",{className:"py-1",children:S.map(B=>{var X;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${B.id===k?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${b?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!b&&z(B),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${B.id===k?"text-accent-primary":"text-text-primary"}`,children:B.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:B.backend!=="auto"&&W1(B.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[B.id===k?o.jsx("span",{className:"text-accent-success",title:"Active",children:o.jsx(Ur,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:Q=>{Q.stopPropagation(),q(Q,B.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(Ew,{className:`w-4 h-4 ${l===B.id?"animate-spin":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:Q=>{Q.stopPropagation(),O(B)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(br,{className:`w-4 h-4 transition-transform ${u.includes(B.id)?"rotate-180":""} ${B.id===k?"text-accent-primary":"text-text-muted"}`})})]})]}),u.includes(B.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:l===B.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(X=B.models)!=null&&X.length?B.models.map(Q=>{var H;return o.jsxs("button",{type:"button",onClick:()=>I(B.id,Q.id),disabled:l==="activating",className:`w-full px-4 py-1.5 text-left hover:bg-bg-tertiary transition-colors text-sm flex items-center justify-between group ${l==="activating"?"opacity-50 cursor-wait":""} ${C===Q.id?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("span",{className:"truncate flex-1",children:((H=Q.id.split("/").pop())==null?void 0:H.replace(/-/g," "))??Q.id}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-xs text-text-muted",children:HA(Q.contextWindow)}),o.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),V(B.id,Q)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(xw,{className:"w-3 h-3 text-text-muted"})})]}),C===Q.id&&o.jsx("span",{className:"text-accent-success flex-shrink-0 ml-1",children:o.jsx(Ur,{className:"w-3.5 h-3.5"})})]},Q.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},B.id)})}),o.jsx("div",{className:"border-t border-border px-3 py-2",children:o.jsx("button",{onClick:()=>e("/onboarding"),className:"text-xs text-accent-primary hover:underline",children:"Manage providers"})})]}),g&&o.jsx(PA,{isOpen:!0,onClose:W,providerId:g.providerId,model:g.model})]})}function UA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function $A({onClick:e}){return o.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:o.jsx(lc,{})})}function I0({isOpen:e,onClose:r,initialEditId:s}){const i=hn(fe=>fe.defaults),c=hn(fe=>fe.userItems),u=hn(fe=>fe.loading),h=hn(fe=>fe.fetchCommands),l=hn(fe=>fe.fetchCommand),d=hn(fe=>fe.fetchDefaultContent),f=hn(fe=>fe.createCommand),g=hn(fe=>fe.updateCommand),m=hn(fe=>fe.deleteCommand),[v,S]=P.useState(null),[k,C]=P.useState(null),{view:y,editingId:b,formError:x,saving:_,formData:j,setView:A,setEditingId:N,setFormError:D,setFormData:T,setSaving:z}=Jv(),{requestDelete:O,clearConfirm:q,isConfirming:V}=qh(),W=P.useRef(!1),I=Tt(fe=>fe.defaults),$=Tt(fe=>fe.userItems),B=Tt(fe=>fe.fetchAgents),Q=[...I,...$].filter(fe=>!fe.subagent),H=P.useRef(h),L=P.useRef(B),R=P.useRef(l),U=P.useRef(d),F=P.useRef(s),ne=P.useRef(A),Z=P.useRef(N),ee=P.useRef(D),Y=P.useRef(q);P.useEffect(()=>{H.current=h,L.current=B,R.current=l,U.current=d,F.current=s,ne.current=A,Z.current=N,ee.current=D,Y.current=q}),P.useEffect(()=>{if(e)if(H.current(),L.current(),W.current||(Y.current(),W.current=!0),F.current){const fe=i.some(je=>je.id===F.current);ne.current("edit"),Z.current(F.current),ee.current(""),fe?U.current(F.current).then(je=>{je&&T({name:je.metadata.name+" (copy)",id:`${F.current}-copy-${Date.now()}`,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!0})}):R.current(F.current).then(je=>{je&&T({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1})})}else ne.current("list"),Z.current(null);else W.current=!1},[e]);const G=async fe=>{S(fe);const je=await d(fe);C((je==null?void 0:je.prompt)??null)},ae=async fe=>{if(i.some(Ue=>Ue.id===fe)){const Ue=await d(fe);Ue&&(N(null),T({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!0}),D(""),A("edit"))}else{const Ue=await l(fe);Ue&&(N(null),T({name:`${Ue.metadata.name} (copy)`,id:`${fe}-copy-${Date.now()}`,prompt:Ue.prompt,agentMode:Ue.metadata.agentMode??"",isDefault:!1}),D(""),A("edit"))}},re=()=>{T({name:"",id:"",prompt:"",agentMode:"",isDefault:!1}),N(null),A("edit")},be=async fe=>{const je=await l(fe);je&&(N(fe),T({name:je.metadata.name,id:je.metadata.id,prompt:je.prompt,agentMode:je.metadata.agentMode??"",isDefault:!1}),D(""),A("edit"))},ve=async fe=>{await m(fe),q()},Re=async()=>{const fe=b??j.id;if(!fe||!j.name||!j.prompt){D("Name and message are required.");return}z(!0),D("");const je={metadata:{id:fe,name:j.name,...j.agentMode?{agentMode:j.agentMode}:{}},prompt:j.prompt},Ue=b?await g(b,je):await f(je);if(z(!1),!Ue.success){D(Ue.error??"Failed to save command.");return}s?r():A("list")},Oe=()=>{s?r():(A("list"),S(null),C(null))},ze=fe=>{T(je=>({...je,name:fe})),(!b||j.isDefault)&&T(je=>({...je,id:UA(fe)}))},We=()=>{S(null),C(null),A("list")},Ee=()=>{v&&(S(null),A("edit"),N(v),d(v).then(fe=>{fe&&T({name:`${fe.metadata.name} (copy)`,id:`${v}-copy-${Date.now()}`,prompt:fe.prompt,agentMode:fe.metadata.agentMode??"",isDefault:!0})}))};if(v){const fe=i.find(je=>je.id===v);return o.jsx(At,{isOpen:e,onClose:We,title:`Default: ${(fe==null?void 0:fe.name)??v}`,size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-tertiary text-text-secondary",children:"Built-in"}),o.jsx("span",{className:"font-mono",children:v})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Name"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm",children:fe==null?void 0:fe.name})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Agent Mode"}),o.jsx("div",{className:"px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm text-text-muted",children:(fe==null?void 0:fe.agentMode)||"None"})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:k??"",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"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(nt,{variant:"secondary",onClick:We,children:"Close"}),o.jsx(nt,{variant:"primary",onClick:Ee,children:"Duplicate & Customize"})]})]})})}return y==="edit"?o.jsx(At,{isOpen:e,onClose:Oe,title:b?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[x&&o.jsx(Gh,{message:x}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(Qv,{name:j.name,id:j.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!b&&!j.isDefault,onNameChange:ze,onIdChange:fe=>T(je=>({...je,id:fe}))}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:["Agent Mode ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsxs("select",{value:j.agentMode,onChange:fe=>T(je=>({...je,agentMode:fe.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:[o.jsx("option",{value:"",children:"None (keep current mode)"}),Q.map(fe=>o.jsx("option",{value:fe.id,children:fe.name},fe.id))]})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Message"}),o.jsx("textarea",{value:j.prompt,onChange:fe=>T(je=>({...je,prompt:fe.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"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border flex-shrink-0",children:[o.jsx(nt,{variant:"secondary",onClick:Oe,children:"Cancel"}),o.jsx(nt,{variant:"primary",onClick:Re,disabled:_||!j.name||!j.prompt,children:_?"Saving...":"Save"})]})]})}):o.jsxs(At,{isOpen:e,onClose:r,title:"Commands",size:"lg",children:[o.jsx(Yv,{description:"Commands are pre-defined messages you can send with a single click.",onNew:re}),o.jsxs(Zv,{loading:u,hasItems:i.length>0||c.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:i.map(fe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:fe.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx($A,{onClick:()=>G(fe.id)}),o.jsx(oo,{onClick:()=>ae(fe.id)})]})]},fe.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(fe=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"text-text-primary text-sm font-medium",children:fe.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Wi,{onClick:()=>be(fe.id)}),o.jsx(oo,{onClick:()=>ae(fe.id)}),V(fe.id,"delete")?o.jsx(Wh,{onConfirm:()=>ve(fe.id),onCancel:q}):o.jsx(Vh,{onClick:()=>O(fe.id)})]})]},fe.id))})]})]})]})}function qA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function WA(e){let r=1;for(;e.some(s=>s.id===`s${r}`);)r++;return`s${r}`}const VA=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}],B0={all_criteria_passed:"All passed",all_criteria_completed_or_passed:"All completed",any_criteria_blocked:"Blocked",has_pending_criteria:"Pending/Failed",step_result:"Result",always:"Always"},z0=[{value:"all_criteria_passed",label:"All criteria passed"},{value:"all_criteria_completed_or_passed",label:"All criteria completed or passed"},{value:"any_criteria_blocked",label:"Any criteria blocked (retry limit)"},{value:"has_pending_criteria",label:"Has pending or failed criteria"},{value:"step_result",label:"Step result is..."},{value:"always",label:"Always (fallback)"}],zs=150,Fr=54,zi=80,Pn=30,Pi=70,wv=100,Ps=50,Vl=50,Cv=4;function Df(e,r){if(e.type==="agent"){const s=r.find(i=>i.id===e.toolMode);return{name:(s==null?void 0:s.name)??(e.toolMode||"Agent"),color:(s==null?void 0:s.color)||"#3b82f6"}}if(e.type==="sub_agent"){const s=r.find(i=>i.id===e.subAgentType);return{name:(s==null?void 0:s.name)??(e.subAgentType||"Sub-Agent"),color:(s==null?void 0:s.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function GA(e,r,s,i){const c=Vl+Ps+zs+wv+zs+Ps+Vl,u=c/2,h=Vl+Ps+zs/2,l=Vl+Ps+zs+wv+zs/2,d=[],f=[],g=new Map,m=e.filter(I=>I.type==="agent"||I.type==="shell"),v=e.filter(I=>I.type==="sub_agent"),S=v.length>0,k=S?h:u,C=m.length>0?l:u,y=Ps+Pn/2;if(d.push({id:"$start",type:"terminal",label:"Start",cx:k,cy:y,w:zi,h:Pn}),g.set("$start",{cx:k,cy:y,w:zi,h:Pn}),e.length===0){const I=y+Pn/2+Pi*2+Pn/2;return d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:I,w:zi,h:Pn}),g.set("$done",{cx:k,cy:I,w:zi,h:Pn}),{nodes:d,edges:f,width:c,height:I+Pn/2+Ps,posMap:g}}const b=y+Pn/2+Pi,x=(I,$)=>{I.forEach((B,X)=>{const Q=b+X*(Fr+Pi)+Fr/2,{name:H,color:L}=Df(B,i);d.push({id:B.id,type:"step",label:H,color:L,cx:$,cy:Q,w:zs,h:Fr}),g.set(B.id,{cx:$,cy:Q,w:zs,h:Fr})})};x(m,k),x(v,C);const _=m.length>0?b+(m.length-1)*(Fr+Pi)+Fr/2:y,j=S?b+(v.length-1)*(Fr+Pi)+Fr/2:y,A=Math.max(_,j)+Fr/2+Pi+Pn/2;d.push({id:"$done",type:"terminal",label:"Done",cx:k,cy:A,w:zi,h:Pn}),g.set("$done",{cx:k,cy:A,w:zi,h:Pn});const N=[];r&&g.has(r)&&N.push({from:"$start",to:r,label:s,edgeKey:"start",direction:"down",backEdgeIndex:0});let D=0;for(const I of e)I.transitions.forEach(($,B)=>{if(!$.goto||!g.has($.goto))return;const X=g.get(I.id),Q=g.get($.goto),H=$.when.type==="step_result"?`${$.when.result}`:B0[$.when.type]??$.when.type,L=I.id===$.goto;let R;L?R="back":Q.cy>X.cy+1?R="down":Q.cy<X.cy-1?R="back":R="same",N.push({from:I.id,to:$.goto,label:H,edgeKey:`${I.id}:${B}`,direction:R,backEdgeIndex:R==="back"?D++:0})});const T=new Map,z=new Map,O=new Map,q=new Map;for(const I of N)I.direction==="down"&&(T.set(I.from,(T.get(I.from)??0)+1),z.set(I.to,(z.get(I.to)??0)+1));const V=new Map,W=new Map;for(const I of N){if(I.direction!=="same")continue;const $=[I.from,I.to].sort().join("|");V.set($,(V.get($)??0)+1)}for(const I of N){if(I.direction==="back"||I.direction==="same"){let R=0;if(I.direction==="same"){const U=[I.from,I.to].sort().join("|");R=W.get(U)??0,W.set(U,R+1)}f.push({...I,fromPort:0,toPort:0,sameEdgeIndex:R});continue}const $=T.get(I.from)??1,B=z.get(I.to)??1,X=O.get(I.from)??0,Q=q.get(I.to)??0;O.set(I.from,X+1),q.set(I.to,Q+1);const H=$===1?0:-.6+1.2*X/($-1),L=B===1?0:-.6+1.2*Q/(B-1);f.push({...I,fromPort:H,toPort:L,sameEdgeIndex:0})}return{nodes:d,edges:f,width:c,height:A+Pn/2+Ps,posMap:g}}function KA({steps:e,entryStep:r,selectedNodeId:s,selectedEdgeKey:i,startConditionLabel:c,agentTypes:u,isReadOnly:h,onSelectNode:l,onSelectEdge:d,onRemoveStep:f,onCreateTransition:g,onReconnectTo:m,onReconnectFrom:v,onDeleteTransition:S}){const k=P.useRef(null),C=P.useRef(!1),[y,b]=P.useState(null),[x,_]=P.useState(null),[j,A]=P.useState(null),{nodes:N,edges:D,width:T,height:z,posMap:O}=P.useMemo(()=>GA(e,r,c,u),[e,r,c,u]),q=P.useCallback(Z=>{var re;const ee=k.current;if(!ee)return{x:0,y:0};const Y=ee.createSVGPoint();Y.x=Z.clientX,Y.y=Z.clientY;const G=(re=ee.getScreenCTM())==null?void 0:re.inverse();if(!G)return{x:0,y:0};const ae=Y.matrixTransform(G);return{x:ae.x,y:ae.y}},[]),V=P.useCallback(Z=>!Z||!x||Z==="$start"?!1:x.type==="reconnect-from"?Z!=="$done":!0,[x]),W=P.useCallback((Z,ee)=>{if(h)return;Z.stopPropagation(),Z.preventDefault();const Y=q(Z);_({type:"new",fromNodeId:ee,mouseX:Y.x,mouseY:Y.y})},[q,h]),I=P.useCallback((Z,ee)=>{if(h)return;Z.stopPropagation(),Z.preventDefault();const Y=q(Z);_({type:"reconnect-to",fromNodeId:ee.from,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),$=P.useCallback((Z,ee)=>{if(h)return;Z.stopPropagation(),Z.preventDefault();const Y=q(Z);_({type:"reconnect-from",fromNodeId:ee.from,fixedTargetId:ee.to,edgeKey:ee.edgeKey,mouseX:Y.x,mouseY:Y.y})},[q,h]),B=P.useCallback(Z=>{if(!x)return;const ee=q(Z);_(Y=>Y?{...Y,mouseX:ee.x,mouseY:ee.y}:null)},[x,q]),X=P.useCallback(()=>{x&&(C.current=!0,j&&V(j)&&(x.type==="new"?g(x.fromNodeId,j):x.type==="reconnect-to"?m(x.edgeKey,j):x.type==="reconnect-from"&&v(x.edgeKey,j)),_(null),A(null))},[x,j,V,g,m,v]),Q=P.useCallback(()=>{if(C.current){C.current=!1;return}l(null),d(null)},[l,d]);P.useEffect(()=>{if(h)return;const Z=ee=>{ee.target instanceof HTMLInputElement||ee.target instanceof HTMLTextAreaElement||ee.target instanceof HTMLSelectElement||(ee.key==="Delete"||ee.key==="Backspace")&&i&&i!=="start"&&(ee.preventDefault(),S(i),d(null))};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[h,i,S,d]);const H=Z=>{const ee=O.get(Z.from),Y=O.get(Z.to);if(!ee||!Y)return null;let G,ae,re,be="middle",ve,Re;if(Z.direction==="down"){const Oe=ee.cx+Z.fromPort*(ee.w/2-10),ze=ee.cy+ee.h/2,We=Y.cx+Z.toPort*(Y.w/2-10),Ee=Y.cy-Y.h/2,fe=Ee-ze,je=We-Oe;G=`M ${Oe} ${ze} C ${Oe} ${ze+fe*.4}, ${We-je*.2} ${Ee-fe*.1}, ${We} ${Ee}`,ae=Oe+(We-Oe)*.5,re=ze+fe*.6,ve={x:Oe,y:ze},Re={x:We,y:Ee}}else if(Z.direction==="back"){const Oe=Z.from===Z.to,ze=ee.cx>=T/2,We=Z.backEdgeIndex*16,Ee=ze?T-20-We:20+We;if(Oe){const fe=ee.cx>=T/2,je=30+Z.backEdgeIndex*14,Ue=ee.cy-ee.h/2,It=fe?ee.cx+ee.w/2:ee.cx-ee.w/2,pe=fe?It+je:It-je,Ne=ee.cx+(fe?ee.w/4:-ee.w/4),Me=Ue-20-Z.backEdgeIndex*10;G=`M ${It} ${ee.cy} C ${pe} ${ee.cy}, ${pe} ${Me}, ${Ne} ${Ue}`,ae=pe+10,re=Me+4,be="middle",ve={x:It,y:ee.cy},Re={x:Ne,y:Ue}}else{const fe=ze?ee.cx+ee.w/2:ee.cx-ee.w/2,je=Y.cx+(ze?Y.w/4:-Y.w/4),Ue=Math.min(ee.cy,Y.cy)-Y.h/2-18-Z.backEdgeIndex*14;G=`M ${fe} ${ee.cy} L ${Ee} ${ee.cy} L ${Ee} ${Ue} L ${je} ${Ue} L ${je} ${Y.cy-Y.h/2}`,ae=Ee,re=(ee.cy+Ue)/2,be=ze?"start":"end",ve={x:fe,y:ee.cy},Re={x:je,y:Y.cy-Y.h/2}}}else{const Oe=Y.cx>ee.cx,ze=Z.sameEdgeIndex===0?-12:12,We=Oe?ee.cx+ee.w/2:ee.cx-ee.w/2,Ee=Oe?Y.cx-Y.w/2:Y.cx+Y.w/2,fe=ee.cy+ze,je=Y.cy+ze,Ue=(We+Ee)/2;G=`M ${We} ${fe} C ${Ue} ${fe}, ${Ue} ${je}, ${Ee} ${je}`,ae=Ue,re=(fe+je)/2-6,ve={x:We,y:fe},Re={x:Ee,y:je}}return{path:G,labelX:ae,labelY:re,labelAnchor:be,fromPt:ve,toPt:Re}},L=(Z,ee)=>{const Y=H(Z);if(!Y)return null;const{path:G,labelX:ae,labelY:re,labelAnchor:be}=Y,ve=i===Z.edgeKey,Re=Z.label&&!(Z.from==="$start"&&Z.label==="Always");return o.jsxs("g",{children:[o.jsx("path",{d:G,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:Oe=>{Oe.stopPropagation(),d(ve?null:Z.edgeKey)}}),o.jsx("path",{d:G,fill:"none",stroke:ve?"#58a6ff":"#484f58",strokeWidth:ve?2.2:1.2,markerEnd:ve?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Re&&o.jsx("text",{x:ae+(be==="start"?5:be==="end"?-5:0),y:re+3,textAnchor:be,className:"text-[8px]",fill:ve?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Z.label})]},ee)},R=()=>{if(!i||x)return null;const Z=D.find(re=>re.edgeKey===i);if(!Z)return null;const ee=H(Z);if(!ee)return null;const{fromPt:Y,toPt:G}=ee,ae=6;return o.jsxs(o.Fragment,{children:[Z.edgeKey!=="start"&&o.jsx("circle",{cx:Y.x,cy:Y.y,r:ae,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>$(re,Z)}),o.jsx("circle",{cx:G.x,cy:G.y,r:ae,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:re=>I(re,Z)})]})},U=()=>{if(!x)return null;let Z,ee,Y,G;if(x.type==="reconnect-from"){const be=O.get(x.fixedTargetId);if(!be)return null;Z=x.mouseX,ee=x.mouseY,Y=be.cx,G=be.cy-be.h/2}else{const be=O.get(x.fromNodeId);if(!be)return null;Z=be.cx,ee=be.cy+be.h/2,Y=x.mouseX,G=x.mouseY}const ae=G-ee,re=Math.abs(ae)>10?`M ${Z} ${ee} C ${Z} ${ee+ae*.4}, ${Y} ${G-ae*.4}, ${Y} ${G}`:`M ${Z} ${ee} L ${Y} ${G}`;return o.jsx("path",{d:re,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},F=Z=>{const ee=Z.cy+Z.h/2,Y=(x==null?void 0:x.fromNodeId)===Z.id;return o.jsx("circle",{cx:Z.cx,cy:ee,r:Cv,fill:Y?"#58a6ff":"#1c2128",stroke:Y?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5,className:"cursor-crosshair",onMouseDown:G=>W(G,Z.id)})},ne=Z=>{const ee=Z.cy-Z.h/2,Y=x&&j===Z.id&&V(Z.id);return o.jsx("circle",{cx:Z.cx,cy:ee,r:Cv,fill:Y?"#3fb950":"#1c2128",stroke:Y?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5})};return o.jsxs("svg",{ref:k,viewBox:`0 0 ${T} ${z}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:B,onMouseUp:X,onClick:Q,children:[o.jsxs("defs",{children:[o.jsx("marker",{id:"arrow",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#484f58"})}),o.jsx("marker",{id:"arrow-selected",viewBox:"0 0 10 7",refX:"10",refY:"3.5",markerWidth:"7",markerHeight:"5",orient:"auto",children:o.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#58a6ff"})})]}),D.map((Z,ee)=>L(Z,ee)),N.map(Z=>{const ee=s===Z.id,Y=Z.cx-Z.w/2,G=Z.cy-Z.h/2,ae=y===Z.id,re=x&&j===Z.id&&V(Z.id);if(Z.type==="terminal"){const ve=Z.id==="$start",Re=ve?"#58a6ff":"#3fb950",Oe=ve,ze=!ve;return o.jsxs("g",{onClick:We=>{We.stopPropagation(),ve&&!h&&d("start")},className:ve&&!h?"cursor-pointer":void 0,children:[re&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:Z.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ve&&i==="start"&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:Z.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:G,width:Z.w,height:Z.h,rx:Z.h/2,fill:Re,fillOpacity:.08,stroke:Re,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Z.cx,y:Z.cy+4,textAnchor:"middle",fill:Re,className:"text-[10px] font-medium",pointerEvents:"none",children:Z.label}),Oe&&F(Z),ze&&ne(Z)]},Z.id)}const be=Z.color??"#6b7280";return o.jsxs("g",{onClick:ve=>{ve.stopPropagation(),h||l(ee?null:Z.id)},onMouseEnter:()=>b(Z.id),onMouseLeave:()=>b(null),className:h?void 0:"cursor-pointer",children:[re&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),ee&&o.jsx("rect",{x:Y-3,y:G-3,width:Z.w+6,height:Z.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:G,width:Z.w,height:Z.h,rx:10,fill:be,fillOpacity:.08,stroke:be,strokeOpacity:.6,strokeWidth:ee?2:1.5}),o.jsx("text",{x:Z.cx,y:Z.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:Z.label}),!h&&F(Z),!h&&ne(Z),ae&&!x&&!h&&o.jsxs("g",{onClick:ve=>{ve.stopPropagation(),f(Z.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:Y+Z.w-2,cy:G+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:Y+Z.w-5,y1:G-1,x2:Y+Z.w+1,y2:G+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:Y+Z.w+1,y1:G-1,x2:Y+Z.w-5,y2:G+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Z.id)}),x&&N.map(Z=>V(Z.id)?o.jsx("rect",{x:Z.cx-Z.w/2-8,y:Z.cy-Z.h/2-8,width:Z.w+16,height:Z.h+16,fill:"transparent",rx:12,onMouseEnter:()=>A(Z.id),onMouseLeave:()=>A(null),onMouseUp:ee=>{ee.stopPropagation(),X()}},`drop-${Z.id}`):null),U(),R()]})}const ar="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",qs="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",fn="block text-[11px] text-text-secondary mb-0.5";function YA({fromLabel:e,toLabel:r,condition:s,fromStep:i,agentTypes:c,onUpdateCondition:u,onDelete:h}){const l=i&&(i.type==="sub_agent"||i.type==="agent")?c.find(f=>f.id===(i.type==="sub_agent"?i.subAgentType:i.toolMode)):void 0,d=(l==null?void 0:l.results)&&l.results.length>0;return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:"Transition"}),o.jsx("button",{onClick:h,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"font-medium text-text-primary",children:e}),o.jsx(Vv,{}),o.jsx("span",{className:"font-medium text-text-primary",children:r})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Condition"}),o.jsx("select",{value:s.type,onChange:f=>{u(f.target.value==="step_result"?{type:"step_result",result:"success"}:{type:f.target.value})},className:qs,children:z0.map(f=>o.jsx("option",{value:f.value,children:f.label},f.value))})]}),s.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),d?o.jsx("select",{value:s.result??l.results[0],onChange:f=>{u({type:"step_result",result:f.target.value})},className:qs,children:l.results.map(f=>o.jsx("option",{value:f,children:f},f))}):o.jsx("input",{type:"text",value:s.result??"success",onChange:f=>u({type:"step_result",result:f.target.value}),placeholder:"e.g. success, passed, failed",className:ar})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Press Delete to remove."})]})}function dh({variables:e,onInsert:r}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(s=>o.jsx("button",{type:"button",onClick:()=>r(s.name),title:s.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:`{{${s.name}}}`},s.name))})}function XA({step:e,isEntry:r,agentTypes:s,transitionCount:i,templateVariables:c,onUpdate:u,onRemove:h,onSetEntry:l}){const{color:d,name:f}=Df(e,s);return o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold",style:{backgroundColor:d+"20",color:d},children:f}),r&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-accent-primary/15 text-accent-primary",children:"Entry"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[!r&&o.jsx("button",{onClick:l,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),o.jsx("button",{onClick:h,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Type"}),o.jsx("select",{value:e.type,onChange:g=>{const m=g.target.value,v=m==="sub_agent"?"verification":"build";if(m==="agent"){const S=s.find(k=>!k.subagent);u({...e,type:m,phase:v,toolMode:(S==null?void 0:S.id)??"builder",name:(S==null?void 0:S.name)??"Agent"})}else if(m==="sub_agent"){const S=s.find(k=>k.subagent);u({...e,type:m,phase:v,subAgentType:(S==null?void 0:S.id)??"",name:(S==null?void 0:S.name)??"Sub-Agent"})}else u({...e,type:m,phase:v,name:"Shell"})},className:qs,children:VA.map(g=>o.jsx("option",{value:g.value,children:g.label},g.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Agent Type"}),o.jsx("select",{value:e.toolMode??"builder",onChange:g=>{const m=s.find(v=>v.id===g.target.value);u({...e,toolMode:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:s.filter(g=>!g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))})]}),e.type==="sub_agent"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:g=>{const m=s.find(v=>v.id===g.target.value);u({...e,subAgentType:g.target.value,name:(m==null?void 0:m.name)??g.target.value})},className:qs,children:[o.jsx("option",{value:"",children:"— select —"}),s.filter(g=>g.subagent).map(g=>o.jsx("option",{value:g.id,children:g.name},g.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:g=>u({...e,prompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(dh,{variables:c,onInsert:g=>u({...e,prompt:(e.prompt??"")+`{{${g}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:g=>u({...e,nudgePrompt:g.target.value||void 0}),rows:6,className:`${ar} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(dh,{variables:c,onInsert:g=>u({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${g}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:g=>u({...e,command:g.target.value}),rows:3,className:`${ar} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(dh,{variables:c,onInsert:g=>u({...e,command:(e.command??"")+`{{${g}}}`})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:g=>u({...e,timeout:Number(g.target.value)}),className:`${ar} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Success Codes"}),o.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:g=>u({...e,successExitCodes:g.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${ar} font-mono text-xs`})]})]})]}),o.jsx("div",{className:"pt-1 border-t border-border/50",children:o.jsxs("p",{className:"text-text-muted text-[10px]",children:[i," outgoing transition",i!==1?"s":""," — drag from the bottom port to connect."]})})]})}const kv=[];function P0({isOpen:e,onClose:r,initialEditId:s}){const i=Nt(me=>me.defaults),c=Nt(me=>me.userItems),u=Nt(me=>me.loading),h=Nt(me=>me.templateVariables),l=Nt(me=>me.fetchWorkflows),d=Nt(me=>me.fetchWorkflow),f=Nt(me=>me.fetchDefaultContent),g=Nt(me=>me.fetchTemplateVariables),m=Nt(me=>me.createWorkflow),v=Nt(me=>me.updateWorkflow),S=Nt(me=>me.deleteWorkflow),{requestDelete:k,clearConfirm:C,isConfirming:y}=qh(),[b,x]=P.useState("list"),[_,j]=P.useState(null),[A,N]=P.useState(!1),[D,T]=P.useState(null),[z,O]=P.useState(null),[q,V]=P.useState(""),[W,I]=P.useState(""),[$,B]=P.useState(""),[X,Q]=P.useState("1.0.0"),[H,L]=P.useState("#3b82f6"),[R,U]=P.useState(""),[F,ne]=P.useState(50),[Z,ee]=P.useState(kv),[Y,G]=P.useState({type:"always"}),[ae,re]=P.useState(""),[be,ve]=P.useState(!1),[Re,Oe]=P.useState([]),[ze]=P.useState(null);P.useEffect(()=>{e&&(l(),g(),ke("/api/agents").then(me=>me.json()).then(me=>Oe(me.agents??[])).catch(()=>{}),T(null),O(null),s?i.some(ye=>ye.id===s)?f(s).then(ye=>{ye&&(V(ye.metadata.name+" (copy)"),I(`${s}-copy-${Date.now()}`),B(ye.metadata.description),Q(ye.metadata.version),L(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),G(ye.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))}):d(s).then(ye=>{ye&&(V(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Q(ye.metadata.version),L(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),G(ye.startCondition??{type:"always"}),re(""),j(s),N(!1),x("edit"))}):(x("list"),j(null),N(!1)))},[e,l,d,f,g,s]);const We=async me=>{const ye=await d(me);ye&&(j(me),V(ye.metadata.name),I(ye.metadata.id),B(ye.metadata.description),Q(ye.metadata.version),L(ye.metadata.color??"#3b82f6"),U(ye.entryStep),ne(ye.settings.maxIterations),ee(ye.steps),G(ye.startCondition??{type:"always"}),re(""),T(null),O(null),x("edit"))},Ee=async()=>{var Qe;const me=_??W;if(!me||!q)return re("Name is required."),!1;if(Z.length===0)return re("Add at least one step."),!1;let ye=R;if(!ye||!Z.some(He=>He.id===ye)){if(ye=((Qe=Z.find(He=>He.id))==null?void 0:Qe.id)??"",!ye)return re("All steps need an ID."),!1;U(ye)}ve(!0),re("");const we={metadata:{id:me,name:q,description:$,version:X||"1.0.0",color:H},entryStep:ye,settings:{maxIterations:F},steps:Z,startCondition:Y},Ve=_?await v(_,we):await m(we);return ve(!1),Ve.success?(_||j(me),!0):(re(Ve.error??"Failed to save."),!1)},fe=async()=>{await Ee()},je=async()=>{await Ee()&&(s?r():x("list"))},Ue=()=>{s?r():x("list")},It=me=>{V(me),_||I(qA(me))},pe=async me=>{if(i.some(we=>we.id===me)){const we=await f(me);if(!we)return;V(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Q(we.metadata.version),L(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),G(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}else{const we=await d(me);if(!we)return;V(we.metadata.name),I(we.metadata.id),B(we.metadata.description),Q(we.metadata.version),L(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),G(we.startCondition??{type:"always"}),re(""),j(me),N(!0)}x("edit")},Ne=async me=>{const we=i.some(Ve=>Ve.id===me)?await f(me):await d(me);we&&(V(we.metadata.name+" (copy)"),I(`${me}-copy-${Date.now()}`),B(we.metadata.description),Q(we.metadata.version),L(we.metadata.color??"#3b82f6"),U(we.entryStep),ne(we.settings.maxIterations),ee(we.steps),G(we.startCondition??{type:"always"}),re(""),j(null),N(!1),x("edit"))},Me=()=>{j(null),V(""),I(""),B(""),Q("1.0.0"),L("#3b82f6"),U(""),ne(50),ee(structuredClone(kv)),G({type:"always"}),re(""),T(null),O(null),N(!1),x("edit")},lt=async me=>{await S(me),C()},ue=P.useCallback(me=>{T(me),O(null)},[]),_e=P.useCallback(me=>{O(me),T(null)},[]),Te=D!==null?Number(D):-1,Ie=Te>=0?Z[Te]??null:null,$e=P.useCallback(me=>{ee(ye=>ye.map((we,Ve)=>Ve===Te?me:we))},[Te]),St=Y.type==="step_result"?`${Y.result}`:B0[Y.type]??Y.type,Ye=()=>{const me=Z.length,ye=WA(Z),we=Re.find(Ve=>!Ve.subagent);ee([...Z,{id:ye,name:(we==null?void 0:we.name)??"Agent",type:"agent",phase:"build",toolMode:(we==null?void 0:we.id)??"builder",transitions:[]}]),R||U(ye),ue(String(me))},Dt=P.useCallback((me,ye)=>{me==="$start"?(U(ye),_e("start")):ee(we=>{const Ve=we.find(He=>He.id===me),Qe=Ve?Ve.transitions.length:0;return _e(`${me}:${Qe}`),we.map(He=>He.id===me?{...He,transitions:[...He.transitions,{when:{type:"always"},goto:ye}]}:He)})},[_e]),gt=P.useCallback((me,ye)=>{if(me==="start")U(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Zt=>Zt.id===Ve?{...Zt,transitions:Zt.transitions.map((Lt,Bt)=>Bt===Qe?{...Lt,goto:ye}:Lt)}:Zt))}},[]),Xt=P.useCallback((me,ye)=>{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>{const Zt=He.find(Bt=>Bt.id===Ve);if(!Zt)return He;const Lt=Zt.transitions[Qe];return Lt?He.map(Bt=>Bt.id===Ve?{...Bt,transitions:Bt.transitions.filter((qr,oe)=>oe!==Qe)}:Bt.id===ye?{...Bt,transitions:[...Bt.transitions,Lt]}:Bt):He}),O(null)},[]),ct=P.useCallback(me=>{if(me==="start")U("");else{const ye=me.lastIndexOf(":"),we=me.slice(0,ye),Ve=parseInt(me.slice(ye+1));ee(Qe=>Qe.map(He=>He.id===we?{...He,transitions:He.transitions.filter((Zt,Lt)=>Lt!==Ve)}:He))}O(null)},[]),qn=P.useCallback((me,ye)=>{if(me==="start")G(ye);else{const we=me.lastIndexOf(":"),Ve=me.slice(0,we),Qe=parseInt(me.slice(we+1));ee(He=>He.map(Zt=>Zt.id===Ve?{...Zt,transitions:Zt.transitions.map((Lt,Bt)=>Bt===Qe?{...Lt,when:ye}:Lt)}:Zt))}},[]),sn=me=>Df(me,Re).name,Zi=()=>{if(!z)return null;if(z==="start"){const Lt=Z.find(Bt=>Bt.id===R);return{type:"start",fromLabel:"Start",toLabel:Lt?sn(Lt):"(none)",condition:Y}}const me=z.lastIndexOf(":"),ye=z.slice(0,me),we=parseInt(z.slice(me+1)),Ve=Z.find(Lt=>Lt.id===ye);if(!Ve)return null;const Qe=Ve.transitions[we];if(!Qe)return null;const He=Z.find(Lt=>Lt.id===Qe.goto),Zt=Qe.goto==="$done"?"Done":He?sn(He):Qe.goto;return{type:"step",fromLabel:sn(Ve),toLabel:Zt,condition:Qe.when}};if(b==="edit"){const me=Zi();return o.jsxs(At,{isOpen:e,onClose:Ue,title:A?q:_?"Edit Workflow":"New Workflow",size:"full",children:[ae&&o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:ae}),o.jsxs("div",{className:"flex items-end gap-3 mb-3 pb-3 border-b border-border flex-wrap",children:[o.jsxs("div",{className:"min-w-[140px]",children:[o.jsx("label",{className:fn,children:"Name"}),o.jsx("input",{value:q,onChange:ye=>It(ye.target.value),placeholder:"Workflow name",className:`${ar} ${A?"opacity-50":""}`,readOnly:A})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:fn,children:"ID"}),o.jsx("input",{value:W,readOnly:!0,className:`${ar} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:fn,children:"Description"}),o.jsx("input",{value:$,onChange:ye=>!A&&B(ye.target.value),readOnly:A,placeholder:"What does this workflow do?",className:`${ar} ${A?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:fn,children:"Max Iter."}),o.jsx("input",{type:"number",value:F,onChange:ye=>!A&&ne(Number(ye.target.value)),readOnly:A,className:`${ar} font-mono ${A?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Color"}),o.jsx("input",{type:"color",value:H,onChange:ye=>!A&&L(ye.target.value),disabled:A,className:`w-8 h-8 rounded border border-border bg-transparent ${A?"opacity-50":"cursor-pointer"}`})]})]}),o.jsxs("div",{className:"flex gap-3",style:{height:"calc(90vh - 220px)",minHeight:300},children:[o.jsxs("div",{className:"flex-1 min-w-0 bg-bg-primary/50 border border-border rounded-lg flex flex-col overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/50 shrink-0",children:[o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Flow"}),!A&&o.jsx("button",{onClick:Ye,className:"text-[11px] text-accent-primary hover:text-accent-primary/80",children:"+ Add Step"})]}),o.jsxs("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:[o.jsx(KA,{steps:Z,entryStep:R,selectedNodeId:(Ie==null?void 0:Ie.id)??null,selectedEdgeKey:z,startConditionLabel:St,agentTypes:Re,isReadOnly:A,onSelectNode:ye=>{if(ye===null){ue(null);return}const we=Z.findIndex(Ve=>Ve.id===ye);ue(we>=0?String(we):null)},onSelectEdge:_e,onRemoveStep:ye=>{var Ve;const we=Z.findIndex(Qe=>Qe.id===ye);if(ee(Qe=>Qe.filter(He=>He.id!==ye)),Te===we&&ue(null),R===ye){const Qe=Z.filter(He=>He.id!==ye);U(((Ve=Qe[0])==null?void 0:Ve.id)??"")}},onCreateTransition:Dt,onReconnectTo:gt,onReconnectFrom:Xt,onDeleteTransition:ct}),Z.length===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-text-muted",children:[o.jsx("p",{className:"text-xs mb-2",children:"No steps yet"}),o.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"})]})]})]}),o.jsxs("div",{className:"w-[300px] shrink-0 border border-border rounded-lg bg-bg-secondary flex flex-col overflow-hidden",children:[o.jsx("div",{className:"px-3 py-1.5 border-b border-border shrink-0",children:o.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wider font-medium",children:"Properties"})}),o.jsx("div",{className:"p-3 overflow-y-auto flex-1 min-h-0",children:A&&(me||Ie)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):me?me.type==="start"?o.jsxs("div",{className:"space-y-3 text-sm",children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/20 text-blue-300",children:"Start"})}),R&&o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[o.jsx("span",{className:"text-text-primary font-medium",children:"Start"}),o.jsx(Vv,{}),o.jsx("span",{className:"text-text-primary font-medium",children:me.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Activation Condition"}),o.jsx("select",{value:Y.type,onChange:ye=>G(ye.target.value==="step_result"?{type:"step_result",result:"success"}:{type:ye.target.value}),className:qs,children:z0.map(ye=>o.jsx("option",{value:ye.value,children:ye.label},ye.value))})]}),Y.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:fn,children:"Result"}),R&&(()=>{const ye=Z.find(He=>He.id===R),we=ye&&(ye.type==="sub_agent"||ye.type==="agent")?Re.find(He=>He.id===(ye.type==="sub_agent"?ye.subAgentType:ye.toolMode)):void 0,Ve=(we==null?void 0:we.results)&&we.results.length>0,Qe=(we==null?void 0:we.results)??[];return Ve?o.jsx("select",{value:Y.result??Qe[0],onChange:He=>G({type:"step_result",result:He.target.value}),className:qs,children:Qe.map(He=>o.jsx("option",{value:He,children:He},He))}):o.jsx("input",{type:"text",value:Y.result??"success",onChange:He=>G({type:"step_result",result:He.target.value}),placeholder:"e.g. success, passed, failed",className:ar})})()]}),o.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."})]}):o.jsx(YA,{fromLabel:me.fromLabel,toLabel:me.toLabel,condition:me.condition,fromStep:me.type==="step"?Z.find(ye=>ye.id===me.fromLabel):void 0,agentTypes:Re,onUpdateCondition:ye=>qn(z,ye),onDelete:()=>ct(z)}):Ie?o.jsx(XA,{step:Ie,isEntry:Ie.id===R,agentTypes:Re,transitionCount:Ie.transitions.length,templateVariables:h,onUpdate:$e,onRemove:()=>{var ye;if(Ie&&(ee(Z.filter((we,Ve)=>Ve!==Te)),ue(null),R===Ie.id)){const we=Z.filter((Ve,Qe)=>Qe!==Te);U(((ye=we[0])==null?void 0:ye.id)??"")}},onSetEntry:()=>U(Ie.id)}):o.jsxs("p",{className:"text-text-muted text-xs text-center py-8",children:["Click a node or edge to edit.",o.jsx("br",{}),"Drag from a port to connect."]})})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 mt-3 border-t border-border",children:[o.jsx(nt,{variant:"secondary",onClick:Ue,children:"Close"}),A?o.jsx(nt,{variant:"primary",onClick:()=>{V(q+" (copy)"),I(`${_}-copy-${Date.now()}`),j(null),N(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(nt,{variant:"secondary",onClick:fe,disabled:be||!q,children:be?"Saving...":"Save"}),o.jsx(nt,{variant:"primary",onClick:je,disabled:be||!q,children:"Save & Close"})]})]})]})}return o.jsxs(At,{isOpen:e,onClose:r,title:"Workflows",size:"lg",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:"Workflows define the orchestrator's step sequence when running tasks."}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(nt,{variant:"primary",size:"sm",onClick:Me,children:"+ New"})})]}),u&&i.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"Loading workflows..."}):i.length===0&&c.length===0?o.jsx("div",{className:"text-text-muted text-sm",children:"No workflows installed."}):o.jsxs("div",{className:"space-y-4",children:[i.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:i.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx("button",{onClick:()=>pe(me.id),className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(oo,{onClick:()=>Ne(me.id)})]})]},me.id))})]}),c.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:c.map(me=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsxs("div",{className:"min-w-0 flex-1 mr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:me.name}),o.jsxs("span",{className:"text-text-muted text-xs",children:["v",me.version]})]}),o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:me.description})]}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(oo,{onClick:()=>Ne(me.id)}),o.jsx(Wi,{onClick:()=>We(me.id)}),y(me.id,"delete")?o.jsx(Wh,{onConfirm:()=>lt(me.id),onCancel:()=>{}}):o.jsx(Vh,{onClick:()=>k(me.id)})]})]},me.id))})]})]})]})}function ZA(e,r){const s=e.startCondition;if(!s||s.type==="always")return!0;switch(s.type){case"has_pending_criteria":return r.some(i=>i.status.type!=="passed");case"all_criteria_passed":return r.length===0||r.every(i=>i.status.type==="passed");case"all_criteria_completed_or_passed":return r.every(i=>i.status.type==="completed"||i.status.type==="passed");case"any_criteria_blocked":return r.some(i=>i.status.type==="failed"&&i.attempts.filter(c=>c.status==="failed").length>=4);case"step_result":return null;default:return null}}function QA({onSendCommand:e,onSelectWorkflow:r,onOpenCommandsManager:s,onOpenWorkflowsManager:i,onAttach:c,textareaContent:u,attachments:h,criteria:l}){const[d,f]=P.useState(!1),[g,m]=P.useState("commands"),[v,S]=P.useState(""),[k,C]=P.useState(0),[y,b]=P.useState(null),[x,_]=P.useState(null),j=P.useRef(null),A=P.useRef(null),N=hn(U=>U.defaults),D=hn(U=>U.userItems),T=hn(U=>U.fetchCommands),z=Nt(U=>U.defaults),O=Nt(U=>U.userItems),q=Nt(U=>U.fetchWorkflows),V=[...N,...D],W=[...z,...O];P.useEffect(()=>{d&&(g==="commands"?T():g==="workflows"&&q())},[d,g,T,q]),P.useEffect(()=>{d&&(S(""),C(0),requestAnimationFrame(()=>{var U;return(U=j.current)==null?void 0:U.focus()}))},[d,g]),P.useEffect(()=>{if(!d)return;const U=F=>{var ne;(ne=A.current)!=null&&ne.contains(F.target)||f(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[d]);const I=U=>{switch(U.key){case"ArrowDown":U.preventDefault(),C(F=>{const Z=(g==="commands"?V:W).filter(ee=>{const Y=v.toLowerCase();return!Y||ee.name.toLowerCase().includes(Y)});return Math.min(F+1,Z.length-1)});break;case"ArrowUp":U.preventDefault(),C(F=>Math.max(F-1,0));break;case"Enter":U.preventDefault();break;case"Escape":U.preventDefault(),f(!1);break}},$=U=>{S(U),C(0)},B=V.filter(U=>!v||U.name.toLowerCase().includes(v.toLowerCase())),X=W.filter(U=>!v||U.name.toLowerCase().includes(v.toLowerCase())),Q=async U=>{const F=await hn.getState().fetchCommand(U);F&&e(F.prompt,F.metadata.agentMode,u,h),f(!1)},H=U=>{r(U),f(!1)},L=(U,F)=>{F.stopPropagation(),f(!1),b(U)},R=(U,F)=>{F.stopPropagation(),f(!1),_(U)};return o.jsxs("div",{ref:A,className:"relative",children:[o.jsx("button",{type:"button",onClick:()=>f(!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:o.jsx(Gv,{className:"w-4 h-4"})}),d&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[o.jsxs("div",{className:"flex border-b border-border",children:[o.jsx("button",{type:"button",onClick:()=>{m("commands"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),o.jsx("button",{type:"button",onClick:()=>{m("workflows"),S(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),o.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${g==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),g!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:j,value:v,onChange:U=>$(U.target.value),onKeyDown:I,placeholder:g==="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"})}),o.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:g==="commands"?B.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:V.length===0?"No commands yet":"No matches"}):B.map((U,F)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>Q(U.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:U.name})}),o.jsx(Wi,{className:"opacity-0 group-hover:opacity-100",onClick:ne=>L(U.id,ne)})]},U.id)):g==="workflows"?X.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):X.map((U,F)=>{const ne=ZA(U,l),Z=U.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${F===k?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>H(U.id),className:"flex-1 text-left flex items-center gap-2",children:[o.jsx("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:Z}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:U.name}),ne!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:ne?"#22c55e":"#6b7280"},title:ne?"Entry condition met":"Entry condition not met"})]}),o.jsx(Wi,{className:"opacity-0 group-hover:opacity-100",onClick:ee=>R(U.id,ee)})]},U.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{c(),f(!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:[o.jsx(fw,{className:"w-4 h-4"}),o.jsx("span",{className:"text-sm font-medium",children:"Attach image"})]}),o.jsx("span",{className:"text-xs text-text-muted",children:"or drag & drop into chat"})]})}),g!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{f(!1),g==="commands"?s():i()},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:g==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(I0,{isOpen:!!y,onClose:()=>b(null),initialEditId:y}),o.jsx(P0,{isOpen:!!x,onClose:()=>_(null),initialEditId:x})]})}function H0(e,r){if(!r)return!0;const s=r.toLowerCase().split(/\s+/),i=e.toLowerCase().split(/\s+/);return s.every(c=>{for(const u of i){let h=0;for(let l=0;l<u.length&&h<c.length;l++)u[l]===c[h]&&h++;if(h===c.length)return!0}return!1})}function F0(e,r,s,i,c){switch(e.key){case"ArrowDown":e.preventDefault(),s(u=>Math.min(u+1,r));break;case"ArrowUp":e.preventDefault(),s(u=>Math.max(u-1,0));break;case"Enter":e.preventDefault(),i();break;case"Escape":e.preventDefault(),c();break}}function JA(e){const r=e.match(/^\/p\/([^/]+)/);return r==null?void 0:r[1]}function e4({isOpen:e,onClose:r,onCloseComplete:s,onSelectCommand:i,onSelectWorkflow:c,onCloseCompleteAction:u,textareaContent:h,onSearchMessages:l,onToggleAutoScroll:d,isAutoScrollActive:f}){const[,g]=lr(),m=hn(R=>R.fetchCommands),v=Nt(R=>R.fetchWorkflows),S=Tt(R=>R.fetchAgents),k=hn(R=>R.defaults),C=hn(R=>R.userItems),y=Nt(R=>R.defaults),b=Nt(R=>R.userItems),x=Tt(R=>R.defaults),_=Tt(R=>R.userItems),j=Ce(R=>{var U;return(U=R.currentSession)==null?void 0:U.mode}),A=Ce(R=>{var U;return((U=R.currentSession)==null?void 0:U.dangerLevel)??"normal"}),N=Ce(R=>R.switchMode),D=Ce(R=>R.switchDangerLevel),T=Ce(R=>{var U;return(U=R.currentSession)==null?void 0:U.projectId}),z=P.useRef(void 0),[O,q]=P.useState(""),[V,W]=P.useState(0),I=P.useRef(null),$=P.useRef(!1);P.useEffect(()=>{e&&($.current=!0)},[e]),P.useEffect(()=>{if(e){m(),v(),S(),q(""),W(0);const R=setTimeout(()=>{var U;return(U=I.current)==null?void 0:U.focus()},50);return()=>clearTimeout(R)}},[e,m,v,S]),P.useEffect(()=>{var R;!e&&$.current&&(s==null||s(),(R=z.current)==null||R.call(z),z.current=void 0)},[e,s]);const B=(R,U)=>{const F=new Set(U.map(ne=>ne.id));return[...R.filter(ne=>!F.has(ne.id)),...U]},Q=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const R=T??JA(window.location.pathname);R&&g(`/p/${R}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{z.current=u,r()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{r(),l==null||l()}},{id:"toggle-autoscroll",name:f?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{r(),d==null||d(!f)}},...B(x,_).filter(R=>!R.subagent&&R.id!==j).map(R=>({id:R.id,name:R.name,prefix:"Agent > Switch to",action:()=>N(R.id)})),...B(k,C).map(R=>({id:R.id,name:R.name,prefix:"Command > Launch",action:()=>i(R.id,h)})),...B(y,b).map(R=>({id:R.id,name:R.name,prefix:"Workflow > Run",action:()=>c(R.id)})),...["normal","dangerous"].filter(R=>R!==A).map(R=>({id:R,name:R.charAt(0).toUpperCase()+R.slice(1),prefix:"Mode > Switch to",action:()=>D(R)}))].filter(R=>H0(`${R.prefix} ${R.name}`,O)),H=Q.length-1,L=R=>{F0(R,H,W,()=>{var U;(U=Q[V])==null||U.action(),r()},r)};return e?Ki.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:r}),o.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[o.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[o.jsx("input",{ref:I,type:"text",value:O,onChange:R=>{q(R.target.value),W(0)},onKeyDown:L,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(Uh,{onClick:r,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:Q.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:k.length+C.length+y.length+b.length>0?"No matches":"No agents, commands, or workflows yet"}):Q.map((R,U)=>o.jsxs("button",{type:"button",onClick:()=>{R.action(),r()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${U===V?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:[o.jsxs("span",{className:"text-text-muted font-normal",children:[R.prefix," "]}),o.jsx("span",{children:R.name})]},R.id))})]})]}),document.body):null}function t4(e){const r=new Date(e),s=new Date;if(r.getDate()===s.getDate()&&r.getMonth()===s.getMonth()&&r.getFullYear()===s.getFullYear())return r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const c=r.getFullYear(),u=String(r.getMonth()+1).padStart(2,"0"),h=String(r.getDate()).padStart(2,"0"),l=String(r.getHours()).padStart(2,"0"),d=String(r.getMinutes()).padStart(2,"0");return`${c}/${u}/${h} ${l}:${d}`}function n4({isOpen:e,onClose:r,messages:s,onSelectMessage:i}){const[c,u]=P.useState(""),[h,l]=P.useState(0),d=P.useRef(null),f=P.useRef(!1),g=s.filter(C=>C.role==="user"&&!C.isSystemGenerated&&C.messageKind!=="auto-prompt"&&C.messageKind!=="command");P.useEffect(()=>{e&&(f.current=!0)},[e]),P.useEffect(()=>{if(e){u(""),l(0);const C=setTimeout(()=>{var y;return(y=d.current)==null?void 0:y.focus()},50);return()=>clearTimeout(C)}},[e]);const m=g.filter(C=>H0(C.content,c)),v=m.length-1,S=C=>{F0(C,v,l,()=>{m[h]&&(i(m[h].id),r())},r)},k=C=>{i(C),r()};return e?Ki.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[15vh] p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:r}),o.jsxs("div",{className:"relative w-full max-w-md bg-bg-secondary border border-border rounded shadow-xl",children:[o.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-border",children:[o.jsx(Hh,{}),o.jsx("input",{ref:d,type:"text",value:c,onChange:C=>{u(C.target.value),l(0)},onKeyDown:S,placeholder:"Search messages...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx("button",{type:"button",onClick:r,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:o.jsx(Fh,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:m.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:g.length>0?"No matches":"No messages yet"}):m.map((C,y)=>o.jsx("button",{type:"button",onClick:()=>k(C.id),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${y===h?"bg-accent-primary/20 text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("span",{className:"truncate flex-1",children:C.content}),o.jsx("span",{className:"text-text-muted text-xs shrink-0",children:t4(C.timestamp)})]})},C.id))})]})]}),document.body):null}function r4(e){return e==="criterion"}function s4(e){var r,s;return e.role!=="assistant"||e.subAgentId||(r=e.content)!=null&&r.trim()||(s=e.thinkingContent)!=null&&s.trim()||!e.toolCalls||e.toolCalls.length===0?!1:e.toolCalls.every(i=>r4(i.name))}function i4(e,r=[]){const s=[];let i=null,c=[],u,h=1;const l=new Map,d=new Map,f=[];for(const S of r)S.type==="message"?l.set(S.message.id,S):S.type==="subagent"?d.set(S.subAgentId,S):S.type==="criteria-batch"&&f.push(S);let g=0;const m=()=>{if(c.length>0){const S=f[g];S&&S.type==="criteria-batch"&&S.toolCalls.length===c.length&&S.toolCalls.every((C,y)=>{var b;return C.id===((b=c[y])==null?void 0:b.id)})?s.push(S):s.push({type:"criteria-batch",toolCalls:[...c]}),g++,c=[]}},v=()=>{if(!i)return;const S=i,k=d.get(S.subAgentId);k&&k.type==="subagent"&&k.messages.length===S.messages.length&&k.messages.every((y,b)=>y===S.messages[b])?s.push(k):s.push({type:"subagent",subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:S.messages}),i=null};for(const S of e)if(S.role!=="tool"){if(S.contextWindowId&&u&&S.contextWindowId!==u&&(m(),v(),h++,s.push({type:"context-divider",windowSequence:h})),u=S.contextWindowId,s4(S)){v();for(const k of S.toolCalls)c.push(k);continue}if(m(),S.subAgentId&&S.subAgentType)i&&i.subAgentId===S.subAgentId?i.messages.push(S):(v(),i={subAgentId:S.subAgentId,subAgentType:S.subAgentType,messages:[S]});else{v();const k=l.get(S.id);k&&k.type==="message"&&k.message===S?s.push(k):s.push({type:"message",message:S})}}return m(),v(),s}function a4(e){const{year:r,month:s,day:i}=sy(e);return`${r}/${s}/${i} ${uc(e)}`}function o4(e,r){return e.length<=r?e:e.substring(0,r)+"..."}const l4=10,c4=150;function u4(e){const r=[];if(e.recentUserPrompts)for(const s of e.recentUserPrompts)r.push({id:s.id,content:s.content,timestamp:s.timestamp,sessionId:e.id,sessionName:e.title||e.id});return r}function d4(e){return[...e].sort((i,c)=>new Date(c.timestamp).getTime()-new Date(i.timestamp).getTime()).slice(0,l4).reverse().map(i=>({id:i.id,content:i.content,timestamp:i.timestamp,formattedTimestamp:a4(i.timestamp),trimmedContent:o4(i.content,c4),sessionId:i.sessionId,sessionName:i.sessionName}))}function h4(e,r,s){const i=[],c=e.filter(u=>u.role==="user"&&!u.isSystemGenerated&&u.messageKind!=="auto-prompt");for(const u of c)i.push({id:u.id,content:u.content,timestamp:u.timestamp,sessionId:s??"",sessionName:"This session"});for(const u of r)s&&u.id===s||i.push(...u4(u));return d4(i)}function f4(e,r=[],s=null){const[i,c]=P.useState(0),[u,h]=P.useState(!1),l=P.useMemo(()=>h4(e,r,s),[e,r,s]),d=P.useCallback(()=>{l.length>0&&(c(l.length-1),h(!0))},[l.length]),f=P.useCallback(()=>{h(!1),c(0)},[]),g=P.useCallback(()=>{c(S=>l.length===0?S:S===0?l.length-1:S-1)},[l.length]),m=P.useCallback(()=>{c(S=>l.length===0?S:S===l.length-1?0:S+1)},[l.length]),v=P.useCallback(()=>{if(l.length===0||!u)return null;const S=l[i];return(S==null?void 0:S.content)??null},[l,i,u]);return{history:l,selectedIndex:i,showHistory:u,openHistory:d,closeHistory:f,navigateUp:g,navigateDown:m,selectCurrent:v}}function p4({criteriaSidebarOpen:e,onCriteriaSidebarToggle:r}={}){const s=e??!0,[i,c]=P.useState(""),[u,h]=P.useState([]),[l,d]=P.useState(!1),[f,g]=P.useState(null),[m,v]=P.useState(!1),[S,k]=P.useState(!1),[C,y]=P.useState(!1),[b,x]=P.useState(!1),[_,j]=P.useState(null),[A,N]=P.useState(null),D=P.useRef(null),T=P.useRef(null),z=P.useRef(null),O=Ce(oe=>oe.currentSession),q=Ce(oe=>oe.messages),V=Ce(oe=>oe.streamingMessage),W=Ce(oe=>oe.sessions),I=Ce(oe=>oe.error),$=Ce(oe=>oe.pendingQuestion),B=qv(),X=Ce(oe=>oe.sendMessage),Q=Ce(oe=>oe.clearError),H=Ce(oe=>oe.acceptAndBuild),L=Ce(oe=>oe.stopGeneration),R=Ce(oe=>oe.launchRunner),U=Ce(oe=>oe.cancelQueued),F=ow(),{showThinking:ne,showVerboseToolOutput:Z,showStats:ee,showAgentDefinitions:Y,showWorkflowBars:G}=Dh(),ae=Nt(oe=>oe.defaults),re=Nt(oe=>oe.userItems),be=[...ae,...re],ve=Nt(oe=>oe.fetchWorkflows),Re=Tt(oe=>oe.defaults),Oe=Tt(oe=>oe.userItems),ze=[...Re,...Oe].filter(oe=>!oe.subagent);P.useEffect(()=>{ve()},[ve]);const{history:We,selectedIndex:Ee,showHistory:fe,openHistory:je,closeHistory:Ue,navigateUp:It,navigateDown:pe,selectCurrent:Ne}=f4(q,W,O==null?void 0:O.id),Me=P.useCallback(oe=>{j(oe),St(!1);const Ae=document.querySelector(`[data-message-id="${oe}"]`);Ae&&Ae.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>j(null),3e3)},[]);P.useEffect(()=>{const oe=Ae=>{N(Ae.detail.stats)};return window.addEventListener("open-turn-stats",oe),()=>window.removeEventListener("open-turn-stats",oe)},[]);const lt=P.useMemo(()=>V?q.map(oe=>oe.id===V.id?V:oe):q,[q,V]),ue=P.useRef([]),_e=P.useMemo(()=>{const oe=i4(lt,ue.current);return ue.current=oe,oe},[lt]),Te=P.useMemo(()=>IA(q),[q]),{force_scroll_to_bottom:Ie,isAutoScrollActive:$e,setAutoScroll:St}=O0(D,O),Ye=P.useCallback(()=>{const oe=T.current;if(!oe)return;oe.style.height="auto";const Ae=Math.min(200,oe.scrollHeight);oe.style.height=`${Ae}px`},[]);P.useEffect(()=>{if(!(O!=null&&O.id))return;const oe=`openfox:draft:${O.id}`,Ae=localStorage.getItem(oe);Ae!==null&&c(Ae)},[O==null?void 0:O.id]),P.useEffect(()=>{var oe;(oe=T.current)==null||oe.focus(),Ye()},[O==null?void 0:O.id,Ye]),P.useEffect(()=>{if(!(O!=null&&O.id))return;const oe=`openfox:draft:${O.id}`,Ae=setTimeout(()=>{i?localStorage.setItem(oe,i):localStorage.removeItem(oe)},500);return()=>clearTimeout(Ae)},[O==null?void 0:O.id,i]),P.useEffect(()=>{Ye()},[i,Ye]),P.useEffect(()=>{const oe=Ae=>{Ae.key==="Escape"&&B&&L(),Ae.key==="ScrollLock"&&St(!$e)};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[B,L,$e]);const Dt=P.useRef(0);P.useEffect(()=>{const oe=Ae=>{if(Ae.key==="Shift"&&!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey){const qe=Date.now();qe-Dt.current<300?(Ae.preventDefault(),y(!0),Dt.current=0):Dt.current=qe}};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[]),P.useEffect(()=>{const oe=T.current;if(!oe)return;const Ae=async qe=>{var en;if(document.activeElement!==oe)return;const Ct=(en=qe.clipboardData)==null?void 0:en.items;if(Ct){for(const _n of Array.from(Ct))if(_n.type.startsWith("image/")){qe.preventDefault();const yr=_n.getAsFile();if(!yr)continue;await ch(yr,Xs=>h(Sn=>[...Sn,Xs]),g,{filename:"pasted-image"})}}};return oe.addEventListener("paste",Ae),()=>oe.removeEventListener("paste",Ae)},[]);const gt=()=>{c(""),h([]),O!=null&&O.id&&localStorage.removeItem(`openfox:draft:${O.id}`)},Xt=async oe=>{oe.preventDefault(),!(!i.trim()&&u.length===0)&&(Ie(),X(i,u.length>0?u:void 0),gt())},ct=oe=>{if((oe.ctrlKey||oe.metaKey)&&oe.code.startsWith("Digit")){const qe=parseInt(oe.code.slice(-1),10)-1,Ct=ze[qe];Ct&&(oe.preventDefault(),Ce.getState().switchMode(Ct.id));return}if(fe)switch(oe.key){case"Enter":oe.preventDefault();const Ae=Ne();Ae&&(c(Ae),Ue());return;case"Escape":oe.preventDefault(),Ue(),B&&L();return;case"ArrowUp":oe.preventDefault(),It();return;case"ArrowDown":oe.preventDefault(),pe();return}if(oe.key==="ArrowUp"&&i.trim()===""&&!fe){oe.preventDefault(),je();return}oe.key==="Enter"&&!oe.shiftKey&&(oe.preventDefault(),Xt(oe))},qn=P.useCallback(async oe=>{const Ae=oe.target.files;if(!(!Ae||Ae.length===0)){g(null);for(const qe of Array.from(Ae))await ch(qe,Ct=>h(en=>[...en,Ct]),g);z.current&&(z.current.value="")}},[]),sn=P.useCallback(oe=>{oe.preventDefault(),oe.stopPropagation(),d(!0)},[]),Zi=P.useCallback(oe=>{oe.preventDefault(),oe.stopPropagation(),d(!1)},[]),me=P.useCallback(async oe=>{oe.preventDefault(),oe.stopPropagation(),d(!1),g(null);const Ae=oe.dataTransfer.files;if(!(!Ae||Ae.length===0))for(const qe of Array.from(Ae))await ch(qe,Ct=>h(en=>[...en,Ct]),g)},[]),ye=P.useCallback(oe=>{h(Ae=>Ae.filter(qe=>qe.id!==oe))},[]),we=P.useCallback(()=>{var oe;(oe=z.current)==null||oe.click()},[]),Ve=(O==null?void 0:O.mode)==="planner",Qe=(O==null?void 0:O.mode)==="builder",He=((O==null?void 0:O.criteria.length)??0)>0,Zt=(O==null?void 0:O.phase)==="done",Lt=_e.some(oe=>oe.type==="message"&&oe.message.role==="assistant"),Bt=Ve&&He&&!B&&Lt&&!Zt,qr=oe=>{const Ae=i.trim()?i:void 0,qe=u.length>0?u:void 0;Ve?H(oe,Ae,qe):Qe&&R(Ae,qe,oe),gt()};return o.jsxs(o.Fragment,{children:[o.jsxs(t2,{criteriaSidebarOpen:s,onCriteriaSidebarToggle:r,messages:lt,children:[$&&o.jsx(yA,{question:$}),o.jsx(s2,{}),A&&o.jsx(uA,{stats:A,onClose:()=>N(null)}),o.jsx(_A,{}),o.jsxs("div",{ref:D,"data-testid":"chat-scroll-container",className:"flex-1 min-w-0 overflow-y-auto relative bg-primary",children:[o.jsx("div",{className:"pt-4",children:_e.map((oe,Ae)=>{if(oe.type==="context-divider")return o.jsxs("div",{className:"flex items-center gap-2 feed-item px-2 md:px-4",children:[o.jsx("div",{className:"flex-1 border-t border-border"}),o.jsx("span",{className:"text-[10px] text-text-muted font-medium px-2",children:"Earlier context summarized"}),o.jsx("div",{className:"flex-1 border-t border-border"})]},Ae);if(oe.type==="subagent"){const _n=oe.messages.some(yr=>yr.isStreaming);return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(pA,{messages:oe.messages,subAgentType:oe.subAgentType,subAgentId:oe.subAgentId,isStreaming:_n})},Ae)}if(oe.type==="criteria-batch")return o.jsx("div",{className:"feed-item px-2 md:px-4",children:o.jsx(R0,{toolCalls:oe.toolCalls,criteria:O==null?void 0:O.criteria})},Ae);const qe=oe.message;if(qe.role==="assistant")return o.jsx("div",{className:"px-2 md:px-4",children:o.jsx(Tf,{message:qe,showStats:ee,showThinking:ne,showVerboseToolOutput:Z})},Ae);const Ct=!Y&&qe.messageKind==="auto-prompt",en=!G&&(qe.messageKind==="workflow-started"||qe.messageKind==="task-completed");return Ct||en?null:o.jsx("div",{className:"px-2 md:px-4",children:o.jsx("div",{"data-message-id":qe.id,className:_===qe.id?"rounded animate-highlight-fade":void 0,children:o.jsx(L0,{message:qe,isLastAssistantMessage:!1,promptContext:qe.role==="user"?Te[qe.id]:void 0})})},Ae)})}),o.jsxs("div",{className:"px-2 md:px-4 pb-4",children:[I&&o.jsx("div",{className:"feed-item bg-red-500/10 border border-red-500/50 rounded p-2",children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-red-400 text-sm font-medium",children:I.code}),o.jsx("div",{className:"text-red-300 text-xs mt-0.5",children:I.message})]}),o.jsx(lo,{onClick:Q,className:"text-red-400 hover:text-red-300 p-0.5",size:"sm"})]})}),Bt&&o.jsx("div",{className:"flex justify-center gap-2 feed-item flex-wrap",children:be.map(oe=>{const Ae=oe.color??"#3b82f6",qe=parseInt(Ae.slice(1,3),16),Ct=parseInt(Ae.slice(3,5),16),en=parseInt(Ae.slice(5,7),16),_n=`rgba(${qe},${Ct},${en},0.12)`,yr=`rgba(${qe},${Ct},${en},0.22)`,Xs=`rgba(${qe},${Ct},${en},0.25)`;return o.jsxs("button",{onClick:()=>H(oe.id),"data-testid":"workflow-run-button",className:"px-4 py-1.5 rounded text-sm font-medium transition-colors",style:{backgroundColor:_n,color:Ae,border:`1px solid ${Xs}`},onMouseEnter:Sn=>{Sn.currentTarget.style.backgroundColor=yr},onMouseLeave:Sn=>{Sn.currentTarget.style.backgroundColor=_n},children:["▶ ",oe.name]},oe.id)})}),B&&o.jsx(SA,{})]})]}),o.jsxs("form",{onSubmit:Xt,className:"relative p-2 md:p-4 bg-secondary",children:[o.jsxs("button",{type:"button",className:"absolute -top-8 right-12 md:right-16 text-sm text-text-muted hover:text-text-primary z-10 flex items-center gap-1.5",onClick:()=>St(!$e),children:[$e?o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):o.jsx(br,{className:"w-3 h-3 text-text-muted"}),$e?"live":"scroll to bottom"]}),o.jsx("button",{type:"button",onClick:()=>x(!0),className:"absolute -top-8 right-2 md:right-4 text-sm text-text-muted hover:text-text-primary z-10 flex items-center p-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Search messages",children:o.jsx(Hh,{})}),o.jsx("input",{ref:z,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:qn,className:"hidden",multiple:!0}),f&&o.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:f}),u.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:u.map(oe=>o.jsx(wA,{attachment:oe,onRemove:ye},oe.id))}),fe&&o.jsx(CA,{history:We,selectedIndex:Ee,onSelect:oe=>{c(oe),Ue()},onEscape:Ue,onNavigate:oe=>{oe==="up"?It():pe()}}),F.length>0&&o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:F.map(oe=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${oe.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:[o.jsxs("span",{className:"font-medium",children:[oe.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:oe.content}),o.jsx(lo,{onClick:()=>U(oe.queueId),size:"sm"})]},oe.queueId))}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${l?"bg-accent-primary/10":"bg-primary"}`,onDragOver:sn,onDragLeave:Zi,onDrop:me,children:[o.jsx("textarea",{id:ty,ref:T,value:i,onChange:oe=>{c(oe.target.value),fe&&Ue()},onKeyDown:ct,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",className:"flex-1 bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:"24px",maxHeight:"200px"},spellCheck:!1}),o.jsxs("div",{className:"flex items-center self-center",children:[o.jsx("button",{type:"button",onClick:()=>{var oe;!i.trim()&&u.length===0||((oe=D.current)==null||oe.scrollTo({top:D.current.scrollHeight,behavior:"smooth"}),X(i,u),gt())},disabled:!i.trim()&&u.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"}),o.jsx(QA,{onSendCommand:(oe,Ae,qe,Ct)=>{var _n;Ae&&(O==null?void 0:O.mode)!==Ae&&Ce.getState().switchMode(Ae);const en=qe&&qe.trim()?`${qe.trim()}
|
|
150
150
|
|
|
151
|
-
${oe}`:oe;(_n=D.current)==null||_n.scrollTo({top:D.current.scrollHeight,behavior:"smooth"}),X(en,Ct!=null&&Ct.length?Ct:void 0,{messageKind:"command",isSystemGenerated:!0}),gt()},onSelectWorkflow:qr,onOpenCommandsManager:()=>v(!0),onOpenWorkflowsManager:()=>k(!0),onAttach:we,textareaContent:i,attachments:u.length>0?u:void 0,criteria:(O==null?void 0:O.criteria)??[]})]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(bA,{}),o.jsx(vA,{})]}),o.jsx(FA,{})]})]}),o.jsx(I0,{isOpen:m,onClose:()=>v(!1)}),o.jsx(P0,{isOpen:S,onClose:()=>k(!1)}),o.jsx(
|
|
151
|
+
${oe}`:oe;(_n=D.current)==null||_n.scrollTo({top:D.current.scrollHeight,behavior:"smooth"}),X(en,Ct!=null&&Ct.length?Ct:void 0,{messageKind:"command",isSystemGenerated:!0}),gt()},onSelectWorkflow:qr,onOpenCommandsManager:()=>v(!0),onOpenWorkflowsManager:()=>k(!0),onAttach:we,textareaContent:i,attachments:u.length>0?u:void 0,criteria:(O==null?void 0:O.criteria)??[]})]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(bA,{}),o.jsx(vA,{})]}),o.jsx(FA,{})]})]}),o.jsx(I0,{isOpen:m,onClose:()=>v(!1)}),o.jsx(P0,{isOpen:S,onClose:()=>k(!1)}),o.jsx(e4,{isOpen:C,onClose:()=>y(!1),onSearchMessages:()=>x(!0),isAutoScrollActive:$e,onToggleAutoScroll:St,textareaContent:i,onCloseComplete:ny,onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(oe,Ae)=>{const qe=await hn.getState().fetchCommand(oe);if(qe){const Ct=Ae!=null&&Ae.trim()?`${Ae.trim()}
|
|
152
152
|
|
|
153
|
-
${qe.prompt}`:qe.prompt;qe.metadata.agentMode&&Ce.getState().switchMode(qe.metadata.agentMode),X(Ct,u!=null&&u.length?u:void 0,{messageKind:"command",isSystemGenerated:!0}),gt()}},onSelectWorkflow:oe=>{const Ae=i.trim()||void 0,qe=u.length>0?u:void 0;(O==null?void 0:O.mode)==="planner"?Ce.getState().acceptAndBuild(oe,Ae,qe):Ce.getState().launchRunner(Ae,qe,oe),gt()}})]}),b&&o.jsx(t4,{isOpen:b,onClose:()=>x(!1),messages:q,onSelectMessage:Me})]})}P.memo(function({item:r}){const[s,i]=P.useState(!1);return r.type==="start"?o.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:[o.jsx("span",{className:"animate-pulse",children:"●"}),o.jsx("span",{children:"Delegating image to fallback vision model..."}),r.filename&&o.jsxs("span",{className:"text-amber-400/70",children:["(",r.filename,")"]})]}):o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-accent-success/10 border border-accent-success/30 rounded",children:[o.jsx("span",{className:"text-accent-success",children:"✓"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-accent-success text-sm",children:"Image description done"}),o.jsx("button",{type:"button",onClick:()=>i(!s),className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:s?"Hide":"Show"})]}),s&&r.description&&o.jsx("div",{className:"mt-2 text-xs prose prose-invert prose-sm max-w-none",children:o.jsx(Ys,{content:r.description})})]})]})});function Ev({isOpen:e,isRetry:r,onSubmit:s,onCancel:i}){const[c,u]=P.useState(""),h=P.useRef(null);P.useEffect(()=>{e&&(u(""),setTimeout(()=>{var d;return(d=h.current)==null?void 0:d.focus()},100))},[e]);const l=d=>{d.preventDefault(),c.trim()&&s(c)};return o.jsx(At,{isOpen:e,onClose:i,title:r?"Invalid Password":"Password Required",size:"sm",children:o.jsxs("form",{onSubmit:l,className:"space-y-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:r?"The password you entered was incorrect. Please try again.":"This server requires a password to connect."}),o.jsx(dc,{ref:h,type:"password",value:c,onChange:d=>u(d.target.value),placeholder:"Enter password",autoFocus:!0}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{type:"button",variant:"secondary",onClick:i,children:"Cancel"}),o.jsx(nt,{type:"submit",disabled:!c.trim(),children:r?"Try Again":"Connect"})]})]})})}const p4=[8e3,11434,8080],m4=[{name:"OpenCode Go",url:"https://opencode.ai/zen/go/v1",backend:"opencode-go"}];function jv(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return"Unknown";default:return e}}function g4({currentStep:e,totalSteps:r,labels:s,onStepClick:i}){return o.jsx("div",{className:"flex justify-center py-6",children:o.jsx("div",{className:"flex items-center",children:Array.from({length:r},(c,u)=>{const h=u+1,l=h<e,d=h===e;return o.jsxs("div",{className:"flex items-center",children:[o.jsx("button",{onClick:()=>i==null?void 0:i(h),className:`size-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors shrink-0 ${l?"bg-accent-primary text-text-primary hover:opacity-80":d?"bg-accent-primary text-text-primary":"bg-bg-tertiary text-text-muted"}`,children:l?"✓":h}),o.jsx("button",{onClick:()=>i==null?void 0:i(h),className:`ml-2 mr-4 text-sm whitespace-nowrap hidden sm:block ${d?"text-text-primary font-medium":"text-text-muted hover:text-text-secondary"}`,children:s[u]}),u<r-1&&o.jsx("div",{className:`w-12 sm:w-20 h-0.5 mr-4 ${l?"bg-accent-primary":"bg-border"}`})]},u)})})})}function x4({onNext:e}){const[r,s]=P.useState([]),[i,c]=P.useState([]),[u,h]=P.useState(!1),[l,d]=P.useState(""),[f,g]=P.useState(""),[m,v]=P.useState(""),[S,k]=P.useState("auto"),[C,y]=P.useState(!1),[b,x]=P.useState(null),[_,j]=P.useState(null),[A,N]=P.useState(null),[D,T]=P.useState("");P.useEffect(()=>{z()},[]);async function z(){try{const $=await ke("/api/providers");if($.ok){const X=(await $.json()).providers.map(Q=>({id:Q.id,name:Q.name,url:Q.url,backend:Q.backend,model:null,apiKey:Q.apiKey}));s(X),c(X)}}catch{}}async function O($){y(!0),x(null);const B=S!=="auto";try{const Q=await(await ke("/api/providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:$,skipBackendDetection:B})})).json();Q.success?(B||k(Q.backend??"auto"),x({success:!0,model:Q.model??void 0})):x({success:!1,error:Q.error??"Connection failed"})}catch(X){x({success:!1,error:X instanceof Error?X.message:"Connection failed"})}y(!1)}function q(){if(!f)return;const $=l||`Provider ${i.length+1}`,B={id:`temp-${Date.now()}`,name:$,url:f,backend:b!=null&&b.success?S:"auto",model:b!=null&&b.success?b.model??null:null,apiKey:m||void 0};c([...i,B]),d(""),g(""),v(""),x(null)}function V($){j($),r.some(X=>X.id===$)?ke(`/api/providers/${$}`,{method:"DELETE"}).then(()=>{c(i.filter(X=>X.id!==$)),s(r.filter(X=>X.id!==$)),j(null)}).catch(()=>{j(null)}):(c(i.filter(X=>X.id!==$)),j(null))}async function W(){for(const B of i)(B.id.startsWith("temp-")||!r.some(X=>X.id===B.id))&&((await ke("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B.name,url:B.url,backend:B.backend,model:B.model,apiKey:B.apiKey})})).ok||console.error("Failed to add provider",B));const $=i.filter(B=>!B.id.startsWith("temp-"));e({providers:$})}const I=i.length>0;return o.jsxs("div",{className:"max-w-xl mx-auto",children:[o.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"LLM Providers"}),o.jsx("p",{className:"text-text-secondary mb-8",children:"Manage your LLM server connections"}),o.jsxs("div",{className:"space-y-4",children:[i.length>0?o.jsx("div",{className:"space-y-2",children:i.map($=>o.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"px-2 py-0.5 bg-accent-primary/25 text-accent-primary rounded text-xs font-medium",children:jv($.backend)}),A===$.id?o.jsx("input",{type:"text",value:D,onChange:B=>T(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(c(i.map(X=>X.id===$.id?{...X,name:D}:X)),N(null)),B.key==="Escape"&&N(null)},onBlur:()=>{c(i.map(B=>B.id===$.id?{...B,name:D}:B)),N(null)},className:"px-2 py-0.5 bg-bg-primary border border-accent-primary rounded text-text-primary text-sm focus:outline-none",autoFocus:!0}):o.jsx("span",{className:"text-text-primary font-medium cursor-pointer hover:text-accent-primary",onClick:()=>{N($.id),T($.name)},title:"Click to edit",children:$.name})]}),o.jsx("p",{className:"text-text-muted text-sm mt-1",children:$.url}),$.model&&o.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",$.model]})]}),o.jsx("button",{onClick:()=>V($.id),disabled:_===$.id,className:"p-2 text-text-muted hover:text-red-500 transition-colors disabled:opacity-50",title:"Remove provider",children:o.jsx(Ph,{})})]},$.id))}):o.jsx("div",{className:"bg-bg-secondary rounded-lg p-8 text-center border border-border",children:o.jsx("p",{className:"text-text-muted",children:"No providers configured yet"})}),u?o.jsxs("form",{onSubmit:$=>{$.preventDefault(),f&&q()},className:"space-y-4 p-4 bg-bg-tertiary rounded-lg",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Service Presets"}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:m4.map($=>o.jsx("button",{type:"button",onClick:()=>{d($.name),g($.url),k($.backend),x(null)},className:`p-2 rounded border text-center text-sm transition-colors ${f===$.url?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:$.name},$.name))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Local Presets"}),o.jsx("div",{className:"grid grid-cols-3 gap-2",children:p4.map($=>o.jsxs("button",{type:"button",onClick:()=>{d(""),g(`http://localhost:${$}`),k("auto"),x(null)},className:`p-2 rounded border text-center text-sm transition-colors ${f===`http://localhost:${$}`?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:["localhost:",$]},$))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Or enter address manually"}),o.jsx("input",{type:"text",name:"url",value:f,onChange:$=>{g($.target.value),x(null)},onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),O(f))},placeholder:"http://localhost:8000","data-testid":"onboarding-provider-url-input",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name (optional)"}),o.jsx("input",{type:"text",name:"name",value:l,onChange:$=>d($.target.value),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),q())},placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"API key (optional)"}),o.jsx("input",{type:"password",name:"apiKey",value:m,onChange:$=>v($.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),b&&o.jsx("div",{className:`p-3 rounded-lg ${b.success?"bg-accent-primary/10":"bg-red-500/10"}`,children:b.success?o.jsxs("p",{className:"text-accent-primary font-medium",children:["✓ Connected to ",jv(S),b.model&&` (${b.model})`]}):o.jsx("p",{className:"text-red-500",children:b.error})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{type:"button",onClick:()=>O(f),disabled:!f||C,"data-testid":"onboarding-test-connection-button",className:"flex-1 px-4 py-2 bg-bg-secondary border border-border rounded-lg hover:border-text-muted disabled:opacity-50",children:C?o.jsx(qi,{className:"w-4 h-4"}):"Test Connection"}),o.jsx("button",{type:"submit",disabled:!f,"data-testid":"onboarding-add-provider-submit-button",className:"flex-1 px-4 py-2 bg-accent-primary text-text-primary rounded-lg hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium",children:b!=null&&b.success?"Add Provider ✓":"Add Provider"})]}),o.jsx("button",{type:"button",onClick:()=>{h(!1),d(""),g(""),x(null)},className:"w-full text-center text-text-muted hover:text-text-secondary text-sm",children:"Cancel"})]}):o.jsxs("button",{onClick:()=>h(!0),"data-testid":"onboarding-add-provider-button",className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-bg-secondary border border-dashed border-border rounded-lg text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[o.jsx(qi,{className:"w-4 h-4"}),"Add Provider"]}),o.jsx("button",{onClick:W,disabled:!I,"data-testid":"onboarding-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]})]})}function b4({onNext:e}){const[r,s]=P.useState(""),[i,c]=P.useState(!1);return P.useEffect(()=>{ke("/api/config").then(u=>u.json()).then(u=>{u.workdir?s(u.workdir):fetch("/api/directories?path="+encodeURIComponent("/home")).then(h=>h.json()).then(h=>{h.current&&s(h.current)}).catch(()=>{})}).catch(()=>{fetch("/api/directories?path="+encodeURIComponent("/home")).then(u=>u.json()).then(u=>{u.current&&s(u.current)}).catch(()=>{})})},[]),o.jsxs("div",{className:"max-w-xl mx-auto",children:[o.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Your Projects Folder"}),o.jsx("p",{className:"text-text-secondary mb-8",children:"Where should OpenFox create project folders?"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Workspace directory"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("input",{type:"text",value:r,onChange:u=>s(u.target.value),placeholder:"/home/user/projects","data-testid":"onboarding-workdir-input",className:"flex-1 px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),o.jsx("button",{onClick:()=>c(!0),className:"px-4 py-2 bg-bg-secondary border border-border rounded-lg hover:border-text-muted",children:"Browse"})]})]}),i&&o.jsx(oy,{initialPath:r||void 0,onSelect:u=>{s(u),c(!1)},onClose:()=>c(!1)}),o.jsx("button",{onClick:()=>e({workdir:r}),disabled:!r,"data-testid":"onboarding-workdir-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]})]})}function v4({onNext:e}){const[r,s]=P.useState(!1),[i,c]=P.useState("http://localhost:11434"),[u,h]=P.useState("qwen3-vl:2b"),{copied:l,copy:d}=N0();P.useEffect(()=>{ke("/api/config").then(g=>g.json()).then(g=>{g.visionFallback&&(s(g.visionFallback.enabled),c(g.visionFallback.url),h(g.visionFallback.model))}).catch(()=>{})},[]);function f(g){if(g){e({});return}e({visionFallback:{enabled:r,url:i,model:u,timeout:120}})}return o.jsxs("div",{className:"max-w-xl mx-auto",children:[o.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Vision (Optional)"}),o.jsx("p",{className:"text-text-secondary mb-8",children:"Configure a vision model for non-vision models"}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"bg-bg-secondary rounded-lg p-4 border border-border",children:[o.jsx("p",{className:"text-text-secondary text-sm mb-2",children:"To enable vision support, you need an Ollama server with a vision model:"}),o.jsx("a",{href:"https://ollama.com/download",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline text-sm",children:"Download Ollama"}),o.jsxs("div",{className:"mt-3 p-2 bg-bg-primary rounded border border-border flex items-center justify-between gap-2",children:[o.jsx("code",{className:"text-text-secondary text-xs",children:"ollama pull qwen3-vl:2b"}),o.jsx("button",{onClick:()=>d("ollama pull qwen3-vl:2b"),className:"text-text-muted hover:text-text-primary transition-colors",title:"Copy",children:l?o.jsx(Ur,{className:"w-4 h-4 text-accent-primary"}):o.jsx(gw,{className:"w-4 h-4"})})]})]}),o.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:r,onChange:g=>s(g.target.checked),className:"w-5 h-5 rounded border-border bg-bg-secondary text-accent-primary focus:ring-accent-primary"}),o.jsx("span",{className:"text-text-primary",children:"Enable vision fallback for non-vision models"})]}),r&&o.jsxs("div",{className:"space-y-4 pl-8",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision server URL"}),o.jsx("input",{type:"text",value:i,onChange:g=>c(g.target.value),placeholder:"http://localhost:11434",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision model name"}),o.jsx("input",{type:"text",value:u,onChange:g=>h(g.target.value),placeholder:"qwen3-vl:2b",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]})]}),o.jsxs("div",{className:"flex items-center justify-between pt-4",children:[o.jsx("button",{onClick:()=>f(!0),"data-testid":"onboarding-skip-button",className:"text-text-muted hover:text-text-secondary text-sm underline",children:"Skip for now"}),o.jsx("button",{onClick:()=>f(!1),className:"px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 transition-colors",children:"Finish Setup"})]})]})]})}function y4({onComplete:e}){const[r,s]=P.useState(1),[i,c]=P.useState(!1),[u,h]=P.useState({});async function l(m){h(v=>({...v,providers:m.providers})),s(2)}async function d(m){h(v=>({...v,...m})),s(3)}async function f(m){c(!0);try{if(!(await ke("/api/init/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:u.workdir,visionFallback:m.visionFallback})})).ok)throw new Error("Failed to save config");e()}catch(v){console.error("Failed to save onboarding data:",v),c(!1)}}const g=m=>{s(m)};return o.jsxs("div",{className:"w-full max-w-xl mx-auto px-6 py-16 relative",children:[o.jsx(lo,{onClick:e,className:"absolute top-4 right-4 p-2",variant:"modal",size:"xl"}),o.jsx(g4,{currentStep:r,totalSteps:3,labels:["LLM Server","Projects Folder","Vision"],onStepClick:g}),o.jsx("div",{className:"max-w-xl mx-auto",children:i?o.jsxs("div",{className:"text-center",children:[o.jsx(qi,{className:"w-6 h-6"}),o.jsx("p",{className:"mt-4 text-text-secondary",children:"Saving your settings..."})]}):o.jsxs(o.Fragment,{children:[r===1&&o.jsx(x4,{onNext:l}),r===2&&o.jsx(b4,{onNext:d}),r===3&&o.jsx(v4,{onNext:f})]})})]})}typeof window<"u"&&(dn.getState().loadUserPresets(),dn.getState().applySavedTheme());function Rf(){return typeof window>"u"?!1:localStorage.getItem("openfox_token")!==null}function U0(){return o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(vo,{})})}function _4({sidebarOpen:e,onSidebarToggle:r}){const[,s]=Mh("/p/:projectId"),i=s==null?void 0:s.projectId,c=Ce(m=>m.connectionStatus),u=Ce(m=>m.listSessions),h=Ce(m=>m.clearSession),l=Ft(m=>m.currentProject),d=Ft(m=>m.loadProject),f=Rf(),g=c==="connected"||f;return P.useEffect(()=>{g&&i&&((l==null?void 0:l.id)!==i&&d(i),u(i),h())},[g,i,l==null?void 0:l.id,d,u,h]),!l||l.id!==i?o.jsx(U0,{}):o.jsxs(o.Fragment,{children:[o.jsx(ay,{projectId:i,isOpen:e,onClose:r}),o.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:o.jsx(kC,{})})]})}function S4({sidebarOpen:e,onSidebarToggle:r,rightSidebarOpen:s,onRightSidebarToggle:i}){const[,c]=Mh("/p/:projectId/s/:sessionId"),u=c==null?void 0:c.projectId,h=c==null?void 0:c.sessionId,[,l]=lr(),d=Ce(_=>_.connectionStatus),f=Ce(_=>_.currentSession),g=Ce(_=>_.loadSession),m=Ce(_=>_.listSessions),v=Ce(_=>_.pendingSessionCreate),S=Ce(_=>_.error),k=Ce(_=>_.clearError),C=Ft(_=>_.currentProject),y=Ft(_=>_.loadProject),b=Rf(),x=d==="connected"||b;return P.useEffect(()=>{x&&u&&(C==null?void 0:C.id)!==u&&y(u)},[x,u,C==null?void 0:C.id,y]),P.useEffect(()=>{x&&h&&(f==null?void 0:f.id)!==h&&g(h),x&&u&&m(u)},[x,h,f==null?void 0:f.id,g,m,v,u]),P.useEffect(()=>{(S==null?void 0:S.code)==="NOT_FOUND"&&u&&(k(),l(`/p/${u}`))},[S,u,k,l]),!C||C.id!==u?o.jsx(U0,{}):o.jsxs(o.Fragment,{children:[o.jsx(ay,{projectId:u,isOpen:e,onClose:r}),o.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:o.jsx(f4,{criteriaSidebarOpen:s,onCriteriaSidebarToggle:i})})]})}function w4(){const e=Rt(s=>s.fetchConfig);function r(){e(),window.history.back()}return o.jsx("div",{className:"flex-1 overflow-y-auto",children:o.jsx(y4,{onComplete:r})})}function C4(){const{connectionStatus:e}=cw(),r=Rt(B=>B.fetchConfig),s=Rt(B=>B.refreshProviderModels),i=Yt(B=>B.getSetting),c=Rt(B=>B.providers),u=Rt(B=>B.activeProviderId),[,h]=lr(),l=Rf(),[d,f]=P.useState(!1);P.useEffect(()=>{(e==="connected"||l)&&r().then(()=>{f(!0);for(const B of Tv)i(B);i(ot.DISPLAY_THEME),i(ot.DISPLAY_USER_PRESETS)})},[e,l,r,i]),P.useEffect(()=>{d&&u&&s(u).then(()=>{r()})},[d,u,s,r]);const g=Yt(B=>B.settings);P.useEffect(()=>{d&&c.length===0&&h("/onboarding")},[d,c.length]),P.useEffect(()=>{const{applySavedTheme:B,saveTheme:X}=dn.getState(),Q=g[ot.DISPLAY_THEME],H=g[ot.DISPLAY_USER_PRESETS];Q&&localStorage.setItem("openfox:theme",Q),H&&localStorage.setItem("openfox:userPresets",H),Q?B():X(JSON.stringify({preset:"dark"}))},[g[ot.DISPLAY_THEME],g[ot.DISPLAY_USER_PRESETS]]);const m=()=>{const B=localStorage.getItem("openfox:leftSidebar");return B!==null?B==="true":!0},v=()=>{const B=localStorage.getItem("openfox:rightSidebar");return B!==null?B==="true":!0},[S,k]=P.useState(m),[C,y]=P.useState(v),[b,x]=P.useState(!1),[_,j]=P.useState(!1),[A,N]=P.useState(!1),D=x1();P.useEffect(()=>{const B=()=>{N(window.innerWidth<768)};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]);const T=A?b:S,z=A?_:C,O=()=>{A?x(!b):k(!S)},q=()=>{A?j(!_):y(!C)};P.useEffect(()=>{A||localStorage.setItem("openfox:leftSidebar",String(S))},[S,A]),P.useEffect(()=>{A||localStorage.setItem("openfox:rightSidebar",String(C))},[C,A]),P.useEffect(()=>{(e==="connected"||l)&&r()},[e,r,l]);const V=Ce(B=>B.showPasswordModal),W=Ce(B=>B.passwordModalRetry),I=Ce(B=>B.submitPassword),$=Ce(B=>B.cancelPassword);return e!=="connected"&&!V&&!l?o.jsxs(o.Fragment,{children:[o.jsx(Ev,{isOpen:!0,isRetry:W,onSubmit:I,onCancel:$}),o.jsx("div",{className:"h-screen flex items-center justify-center",children:o.jsx(_C,{text:"Connecting to server..."})})]}):o.jsxs(o.Fragment,{children:[o.jsx(Ev,{isOpen:V,isRetry:W,onSubmit:I,onCancel:$}),o.jsxs("div",{className:"flex flex-col",style:{height:A?`calc(${D.offsetTop}px + ${D.height}px)`:"100vh"},children:[o.jsx(gC,{}),o.jsx(uC,{onMenuClick:O,onCriteriaToggle:q}),o.jsx("div",{className:"flex-1 flex overflow-hidden",children:o.jsxs(P1,{children:[o.jsx($a,{path:"/onboarding",children:o.jsx(w4,{})}),o.jsx($a,{path:"/p/:projectId/s/:sessionId",children:o.jsx(S4,{sidebarOpen:T,onSidebarToggle:O,rightSidebarOpen:z,onRightSidebarToggle:q})}),o.jsx($a,{path:"/p/:projectId/new",children:o.jsx(CC,{})}),o.jsx($a,{path:"/p/:projectId",children:o.jsx(_4,{sidebarOpen:T,onSidebarToggle:O})}),o.jsx($a,{path:"/",children:o.jsx(wC,{})})]})})]})]})}f1.createRoot(document.getElementById("root")).render(o.jsx(gn.StrictMode,{children:o.jsx(C4,{})}));
|
|
153
|
+
${qe.prompt}`:qe.prompt;qe.metadata.agentMode&&Ce.getState().switchMode(qe.metadata.agentMode),X(Ct,u!=null&&u.length?u:void 0,{messageKind:"command",isSystemGenerated:!0}),gt()}},onSelectWorkflow:oe=>{const Ae=i.trim()||void 0,qe=u.length>0?u:void 0;(O==null?void 0:O.mode)==="planner"?Ce.getState().acceptAndBuild(oe,Ae,qe):Ce.getState().launchRunner(Ae,qe,oe),gt()}})]}),b&&o.jsx(n4,{isOpen:b,onClose:()=>x(!1),messages:q,onSelectMessage:Me})]})}P.memo(function({item:r}){const[s,i]=P.useState(!1);return r.type==="start"?o.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:[o.jsx("span",{className:"animate-pulse",children:"●"}),o.jsx("span",{children:"Delegating image to fallback vision model..."}),r.filename&&o.jsxs("span",{className:"text-amber-400/70",children:["(",r.filename,")"]})]}):o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-accent-success/10 border border-accent-success/30 rounded",children:[o.jsx("span",{className:"text-accent-success",children:"✓"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-accent-success text-sm",children:"Image description done"}),o.jsx("button",{type:"button",onClick:()=>i(!s),className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:s?"Hide":"Show"})]}),s&&r.description&&o.jsx("div",{className:"mt-2 text-xs prose prose-invert prose-sm max-w-none",children:o.jsx(Ys,{content:r.description})})]})]})});function Ev({isOpen:e,isRetry:r,onSubmit:s,onCancel:i}){const[c,u]=P.useState(""),h=P.useRef(null);P.useEffect(()=>{e&&(u(""),setTimeout(()=>{var d;return(d=h.current)==null?void 0:d.focus()},100))},[e]);const l=d=>{d.preventDefault(),c.trim()&&s(c)};return o.jsx(At,{isOpen:e,onClose:i,title:r?"Invalid Password":"Password Required",size:"sm",children:o.jsxs("form",{onSubmit:l,className:"space-y-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:r?"The password you entered was incorrect. Please try again.":"This server requires a password to connect."}),o.jsx(dc,{ref:h,type:"password",value:c,onChange:d=>u(d.target.value),placeholder:"Enter password",autoFocus:!0}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{type:"button",variant:"secondary",onClick:i,children:"Cancel"}),o.jsx(nt,{type:"submit",disabled:!c.trim(),children:r?"Try Again":"Connect"})]})]})})}const m4=[8e3,11434,8080],g4=[{name:"OpenCode Go",url:"https://opencode.ai/zen/go/v1",backend:"opencode-go"}];function jv(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return"Unknown";default:return e}}function x4({currentStep:e,totalSteps:r,labels:s,onStepClick:i}){return o.jsx("div",{className:"flex justify-center py-6",children:o.jsx("div",{className:"flex items-center",children:Array.from({length:r},(c,u)=>{const h=u+1,l=h<e,d=h===e;return o.jsxs("div",{className:"flex items-center",children:[o.jsx("button",{onClick:()=>i==null?void 0:i(h),className:`size-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors shrink-0 ${l?"bg-accent-primary text-text-primary hover:opacity-80":d?"bg-accent-primary text-text-primary":"bg-bg-tertiary text-text-muted"}`,children:l?"✓":h}),o.jsx("button",{onClick:()=>i==null?void 0:i(h),className:`ml-2 mr-4 text-sm whitespace-nowrap hidden sm:block ${d?"text-text-primary font-medium":"text-text-muted hover:text-text-secondary"}`,children:s[u]}),u<r-1&&o.jsx("div",{className:`w-12 sm:w-20 h-0.5 mr-4 ${l?"bg-accent-primary":"bg-border"}`})]},u)})})})}function b4({onNext:e}){const[r,s]=P.useState([]),[i,c]=P.useState([]),[u,h]=P.useState(!1),[l,d]=P.useState(""),[f,g]=P.useState(""),[m,v]=P.useState(""),[S,k]=P.useState("auto"),[C,y]=P.useState(!1),[b,x]=P.useState(null),[_,j]=P.useState(null),[A,N]=P.useState(null),[D,T]=P.useState("");P.useEffect(()=>{z()},[]);async function z(){try{const $=await ke("/api/providers");if($.ok){const X=(await $.json()).providers.map(Q=>({id:Q.id,name:Q.name,url:Q.url,backend:Q.backend,model:null,apiKey:Q.apiKey}));s(X),c(X)}}catch{}}async function O($){y(!0),x(null);const B=S!=="auto";try{const Q=await(await ke("/api/providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:$,skipBackendDetection:B})})).json();Q.success?(B||k(Q.backend??"auto"),x({success:!0,model:Q.model??void 0})):x({success:!1,error:Q.error??"Connection failed"})}catch(X){x({success:!1,error:X instanceof Error?X.message:"Connection failed"})}y(!1)}function q(){if(!f)return;const $=l||`Provider ${i.length+1}`,B={id:`temp-${Date.now()}`,name:$,url:f,backend:b!=null&&b.success?S:"auto",model:b!=null&&b.success?b.model??null:null,apiKey:m||void 0};c([...i,B]),d(""),g(""),v(""),x(null)}function V($){j($),r.some(X=>X.id===$)?ke(`/api/providers/${$}`,{method:"DELETE"}).then(()=>{c(i.filter(X=>X.id!==$)),s(r.filter(X=>X.id!==$)),j(null)}).catch(()=>{j(null)}):(c(i.filter(X=>X.id!==$)),j(null))}async function W(){for(const B of i)(B.id.startsWith("temp-")||!r.some(X=>X.id===B.id))&&((await ke("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B.name,url:B.url,backend:B.backend,model:B.model,apiKey:B.apiKey})})).ok||console.error("Failed to add provider",B));const $=i.filter(B=>!B.id.startsWith("temp-"));e({providers:$})}const I=i.length>0;return o.jsxs("div",{className:"max-w-xl mx-auto",children:[o.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"LLM Providers"}),o.jsx("p",{className:"text-text-secondary mb-8",children:"Manage your LLM server connections"}),o.jsxs("div",{className:"space-y-4",children:[i.length>0?o.jsx("div",{className:"space-y-2",children:i.map($=>o.jsxs("div",{className:"flex items-center justify-between bg-bg-secondary rounded-lg p-4 border border-border",children:[o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"px-2 py-0.5 bg-accent-primary/25 text-accent-primary rounded text-xs font-medium",children:jv($.backend)}),A===$.id?o.jsx("input",{type:"text",value:D,onChange:B=>T(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(c(i.map(X=>X.id===$.id?{...X,name:D}:X)),N(null)),B.key==="Escape"&&N(null)},onBlur:()=>{c(i.map(B=>B.id===$.id?{...B,name:D}:B)),N(null)},className:"px-2 py-0.5 bg-bg-primary border border-accent-primary rounded text-text-primary text-sm focus:outline-none",autoFocus:!0}):o.jsx("span",{className:"text-text-primary font-medium cursor-pointer hover:text-accent-primary",onClick:()=>{N($.id),T($.name)},title:"Click to edit",children:$.name})]}),o.jsx("p",{className:"text-text-muted text-sm mt-1",children:$.url}),$.model&&o.jsxs("p",{className:"text-text-secondary text-xs mt-0.5",children:["Model: ",$.model]})]}),o.jsx("button",{onClick:()=>V($.id),disabled:_===$.id,className:"p-2 text-text-muted hover:text-red-500 transition-colors disabled:opacity-50",title:"Remove provider",children:o.jsx(Ph,{})})]},$.id))}):o.jsx("div",{className:"bg-bg-secondary rounded-lg p-8 text-center border border-border",children:o.jsx("p",{className:"text-text-muted",children:"No providers configured yet"})}),u?o.jsxs("form",{onSubmit:$=>{$.preventDefault(),f&&q()},className:"space-y-4 p-4 bg-bg-tertiary rounded-lg",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Service Presets"}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:g4.map($=>o.jsx("button",{type:"button",onClick:()=>{d($.name),g($.url),k($.backend),x(null)},className:`p-2 rounded border text-center text-sm transition-colors ${f===$.url?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:$.name},$.name))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Local Presets"}),o.jsx("div",{className:"grid grid-cols-3 gap-2",children:m4.map($=>o.jsxs("button",{type:"button",onClick:()=>{d(""),g(`http://localhost:${$}`),k("auto"),x(null)},className:`p-2 rounded border text-center text-sm transition-colors ${f===`http://localhost:${$}`?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:["localhost:",$]},$))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Or enter address manually"}),o.jsx("input",{type:"text",name:"url",value:f,onChange:$=>{g($.target.value),x(null)},onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),O(f))},placeholder:"http://localhost:8000","data-testid":"onboarding-provider-url-input",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name (optional)"}),o.jsx("input",{type:"text",name:"name",value:l,onChange:$=>d($.target.value),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),q())},placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"API key (optional)"}),o.jsx("input",{type:"password",name:"apiKey",value:m,onChange:$=>v($.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),b&&o.jsx("div",{className:`p-3 rounded-lg ${b.success?"bg-accent-primary/10":"bg-red-500/10"}`,children:b.success?o.jsxs("p",{className:"text-accent-primary font-medium",children:["✓ Connected to ",jv(S),b.model&&` (${b.model})`]}):o.jsx("p",{className:"text-red-500",children:b.error})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{type:"button",onClick:()=>O(f),disabled:!f||C,"data-testid":"onboarding-test-connection-button",className:"flex-1 px-4 py-2 bg-bg-secondary border border-border rounded-lg hover:border-text-muted disabled:opacity-50",children:C?o.jsx(qi,{className:"w-4 h-4"}):"Test Connection"}),o.jsx("button",{type:"submit",disabled:!f,"data-testid":"onboarding-add-provider-submit-button",className:"flex-1 px-4 py-2 bg-accent-primary text-text-primary rounded-lg hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium",children:b!=null&&b.success?"Add Provider ✓":"Add Provider"})]}),o.jsx("button",{type:"button",onClick:()=>{h(!1),d(""),g(""),x(null)},className:"w-full text-center text-text-muted hover:text-text-secondary text-sm",children:"Cancel"})]}):o.jsxs("button",{onClick:()=>h(!0),"data-testid":"onboarding-add-provider-button",className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-bg-secondary border border-dashed border-border rounded-lg text-text-secondary hover:text-text-primary hover:border-text-muted transition-colors",children:[o.jsx(qi,{className:"w-4 h-4"}),"Add Provider"]}),o.jsx("button",{onClick:W,disabled:!I,"data-testid":"onboarding-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]})]})}function v4({onNext:e}){const[r,s]=P.useState(""),[i,c]=P.useState(!1);return P.useEffect(()=>{ke("/api/config").then(u=>u.json()).then(u=>{u.workdir?s(u.workdir):fetch("/api/directories?path="+encodeURIComponent("/home")).then(h=>h.json()).then(h=>{h.current&&s(h.current)}).catch(()=>{})}).catch(()=>{fetch("/api/directories?path="+encodeURIComponent("/home")).then(u=>u.json()).then(u=>{u.current&&s(u.current)}).catch(()=>{})})},[]),o.jsxs("div",{className:"max-w-xl mx-auto",children:[o.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Your Projects Folder"}),o.jsx("p",{className:"text-text-secondary mb-8",children:"Where should OpenFox create project folders?"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Workspace directory"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("input",{type:"text",value:r,onChange:u=>s(u.target.value),placeholder:"/home/user/projects","data-testid":"onboarding-workdir-input",className:"flex-1 px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),o.jsx("button",{onClick:()=>c(!0),className:"px-4 py-2 bg-bg-secondary border border-border rounded-lg hover:border-text-muted",children:"Browse"})]})]}),i&&o.jsx(oy,{initialPath:r||void 0,onSelect:u=>{s(u),c(!1)},onClose:()=>c(!1)}),o.jsx("button",{onClick:()=>e({workdir:r}),disabled:!r,"data-testid":"onboarding-workdir-continue-button",className:"w-full mt-6 px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Continue"})]})]})}function y4({onNext:e}){const[r,s]=P.useState(!1),[i,c]=P.useState("http://localhost:11434"),[u,h]=P.useState("qwen3-vl:2b"),{copied:l,copy:d}=N0();P.useEffect(()=>{ke("/api/config").then(g=>g.json()).then(g=>{g.visionFallback&&(s(g.visionFallback.enabled),c(g.visionFallback.url),h(g.visionFallback.model))}).catch(()=>{})},[]);function f(g){if(g){e({});return}e({visionFallback:{enabled:r,url:i,model:u,timeout:120}})}return o.jsxs("div",{className:"max-w-xl mx-auto",children:[o.jsx("h2",{className:"text-2xl font-bold text-text-primary mb-2",children:"Vision (Optional)"}),o.jsx("p",{className:"text-text-secondary mb-8",children:"Configure a vision model for non-vision models"}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"bg-bg-secondary rounded-lg p-4 border border-border",children:[o.jsx("p",{className:"text-text-secondary text-sm mb-2",children:"To enable vision support, you need an Ollama server with a vision model:"}),o.jsx("a",{href:"https://ollama.com/download",target:"_blank",rel:"noopener noreferrer",className:"text-accent-primary hover:underline text-sm",children:"Download Ollama"}),o.jsxs("div",{className:"mt-3 p-2 bg-bg-primary rounded border border-border flex items-center justify-between gap-2",children:[o.jsx("code",{className:"text-text-secondary text-xs",children:"ollama pull qwen3-vl:2b"}),o.jsx("button",{onClick:()=>d("ollama pull qwen3-vl:2b"),className:"text-text-muted hover:text-text-primary transition-colors",title:"Copy",children:l?o.jsx(Ur,{className:"w-4 h-4 text-accent-primary"}):o.jsx(gw,{className:"w-4 h-4"})})]})]}),o.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:r,onChange:g=>s(g.target.checked),className:"w-5 h-5 rounded border-border bg-bg-secondary text-accent-primary focus:ring-accent-primary"}),o.jsx("span",{className:"text-text-primary",children:"Enable vision fallback for non-vision models"})]}),r&&o.jsxs("div",{className:"space-y-4 pl-8",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision server URL"}),o.jsx("input",{type:"text",value:i,onChange:g=>c(g.target.value),placeholder:"http://localhost:11434",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Vision model name"}),o.jsx("input",{type:"text",value:u,onChange:g=>h(g.target.value),placeholder:"qwen3-vl:2b",className:"w-full px-4 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]})]}),o.jsxs("div",{className:"flex items-center justify-between pt-4",children:[o.jsx("button",{onClick:()=>f(!0),"data-testid":"onboarding-skip-button",className:"text-text-muted hover:text-text-secondary text-sm underline",children:"Skip for now"}),o.jsx("button",{onClick:()=>f(!1),className:"px-6 py-3 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 transition-colors",children:"Finish Setup"})]})]})]})}function _4({onComplete:e}){const[r,s]=P.useState(1),[i,c]=P.useState(!1),[u,h]=P.useState({});async function l(m){h(v=>({...v,providers:m.providers})),s(2)}async function d(m){h(v=>({...v,...m})),s(3)}async function f(m){c(!0);try{if(!(await ke("/api/init/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:u.workdir,visionFallback:m.visionFallback})})).ok)throw new Error("Failed to save config");e()}catch(v){console.error("Failed to save onboarding data:",v),c(!1)}}const g=m=>{s(m)};return o.jsxs("div",{className:"w-full max-w-xl mx-auto px-6 py-16 relative",children:[o.jsx(lo,{onClick:e,className:"absolute top-4 right-4 p-2",variant:"modal",size:"xl"}),o.jsx(x4,{currentStep:r,totalSteps:3,labels:["LLM Server","Projects Folder","Vision"],onStepClick:g}),o.jsx("div",{className:"max-w-xl mx-auto",children:i?o.jsxs("div",{className:"text-center",children:[o.jsx(qi,{className:"w-6 h-6"}),o.jsx("p",{className:"mt-4 text-text-secondary",children:"Saving your settings..."})]}):o.jsxs(o.Fragment,{children:[r===1&&o.jsx(b4,{onNext:l}),r===2&&o.jsx(v4,{onNext:d}),r===3&&o.jsx(y4,{onNext:f})]})})]})}typeof window<"u"&&(dn.getState().loadUserPresets(),dn.getState().applySavedTheme());function Rf(){return typeof window>"u"?!1:localStorage.getItem("openfox_token")!==null}function U0(){return o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(vo,{})})}function S4({sidebarOpen:e,onSidebarToggle:r}){const[,s]=Mh("/p/:projectId"),i=s==null?void 0:s.projectId,c=Ce(m=>m.connectionStatus),u=Ce(m=>m.listSessions),h=Ce(m=>m.clearSession),l=Ft(m=>m.currentProject),d=Ft(m=>m.loadProject),f=Rf(),g=c==="connected"||f;return P.useEffect(()=>{g&&i&&((l==null?void 0:l.id)!==i&&d(i),u(i),h())},[g,i,l==null?void 0:l.id,d,u,h]),!l||l.id!==i?o.jsx(U0,{}):o.jsxs(o.Fragment,{children:[o.jsx(ay,{projectId:i,isOpen:e,onClose:r}),o.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:o.jsx(kC,{})})]})}function w4({sidebarOpen:e,onSidebarToggle:r,rightSidebarOpen:s,onRightSidebarToggle:i}){const[,c]=Mh("/p/:projectId/s/:sessionId"),u=c==null?void 0:c.projectId,h=c==null?void 0:c.sessionId,[,l]=lr(),d=Ce(_=>_.connectionStatus),f=Ce(_=>_.currentSession),g=Ce(_=>_.loadSession),m=Ce(_=>_.listSessions),v=Ce(_=>_.pendingSessionCreate),S=Ce(_=>_.error),k=Ce(_=>_.clearError),C=Ft(_=>_.currentProject),y=Ft(_=>_.loadProject),b=Rf(),x=d==="connected"||b;return P.useEffect(()=>{x&&u&&(C==null?void 0:C.id)!==u&&y(u)},[x,u,C==null?void 0:C.id,y]),P.useEffect(()=>{x&&h&&(f==null?void 0:f.id)!==h&&g(h),x&&u&&m(u)},[x,h,f==null?void 0:f.id,g,m,v,u]),P.useEffect(()=>{(S==null?void 0:S.code)==="NOT_FOUND"&&u&&(k(),l(`/p/${u}`))},[S,u,k,l]),!C||C.id!==u?o.jsx(U0,{}):o.jsxs(o.Fragment,{children:[o.jsx(ay,{projectId:u,isOpen:e,onClose:r}),o.jsx("div",{className:"flex-1 min-w-0 bg-primary",children:o.jsx(p4,{criteriaSidebarOpen:s,onCriteriaSidebarToggle:i})})]})}function C4(){const e=Rt(s=>s.fetchConfig);function r(){e(),window.history.back()}return o.jsx("div",{className:"flex-1 overflow-y-auto",children:o.jsx(_4,{onComplete:r})})}function k4(){const{connectionStatus:e}=cw(),r=Rt(B=>B.fetchConfig),s=Rt(B=>B.refreshProviderModels),i=Yt(B=>B.getSetting),c=Rt(B=>B.providers),u=Rt(B=>B.activeProviderId),[,h]=lr(),l=Rf(),[d,f]=P.useState(!1);P.useEffect(()=>{(e==="connected"||l)&&r().then(()=>{f(!0);for(const B of Tv)i(B);i(ot.DISPLAY_THEME),i(ot.DISPLAY_USER_PRESETS)})},[e,l,r,i]),P.useEffect(()=>{d&&u&&s(u).then(()=>{r()})},[d,u,s,r]);const g=Yt(B=>B.settings);P.useEffect(()=>{d&&c.length===0&&h("/onboarding")},[d,c.length]),P.useEffect(()=>{const{applySavedTheme:B,saveTheme:X}=dn.getState(),Q=g[ot.DISPLAY_THEME],H=g[ot.DISPLAY_USER_PRESETS];Q&&localStorage.setItem("openfox:theme",Q),H&&localStorage.setItem("openfox:userPresets",H),Q?B():X(JSON.stringify({preset:"dark"}))},[g[ot.DISPLAY_THEME],g[ot.DISPLAY_USER_PRESETS]]);const m=()=>{const B=localStorage.getItem("openfox:leftSidebar");return B!==null?B==="true":!0},v=()=>{const B=localStorage.getItem("openfox:rightSidebar");return B!==null?B==="true":!0},[S,k]=P.useState(m),[C,y]=P.useState(v),[b,x]=P.useState(!1),[_,j]=P.useState(!1),[A,N]=P.useState(!1),D=x1();P.useEffect(()=>{const B=()=>{N(window.innerWidth<768)};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]);const T=A?b:S,z=A?_:C,O=()=>{A?x(!b):k(!S)},q=()=>{A?j(!_):y(!C)};P.useEffect(()=>{A||localStorage.setItem("openfox:leftSidebar",String(S))},[S,A]),P.useEffect(()=>{A||localStorage.setItem("openfox:rightSidebar",String(C))},[C,A]),P.useEffect(()=>{(e==="connected"||l)&&r()},[e,r,l]);const V=Ce(B=>B.showPasswordModal),W=Ce(B=>B.passwordModalRetry),I=Ce(B=>B.submitPassword),$=Ce(B=>B.cancelPassword);return e!=="connected"&&!V&&!l?o.jsxs(o.Fragment,{children:[o.jsx(Ev,{isOpen:!0,isRetry:W,onSubmit:I,onCancel:$}),o.jsx("div",{className:"h-screen flex items-center justify-center",children:o.jsx(_C,{text:"Connecting to server..."})})]}):o.jsxs(o.Fragment,{children:[o.jsx(Ev,{isOpen:V,isRetry:W,onSubmit:I,onCancel:$}),o.jsxs("div",{className:"flex flex-col",style:{height:A?`calc(${D.offsetTop}px + ${D.height}px)`:"100vh"},children:[o.jsx(gC,{}),o.jsx(uC,{onMenuClick:O,onCriteriaToggle:q}),o.jsx("div",{className:"flex-1 flex overflow-hidden",children:o.jsxs(P1,{children:[o.jsx($a,{path:"/onboarding",children:o.jsx(C4,{})}),o.jsx($a,{path:"/p/:projectId/s/:sessionId",children:o.jsx(w4,{sidebarOpen:T,onSidebarToggle:O,rightSidebarOpen:z,onRightSidebarToggle:q})}),o.jsx($a,{path:"/p/:projectId/new",children:o.jsx(CC,{})}),o.jsx($a,{path:"/p/:projectId",children:o.jsx(S4,{sidebarOpen:T,onSidebarToggle:O})}),o.jsx($a,{path:"/",children:o.jsx(wC,{})})]})})]})]})}f1.createRoot(document.getElementById("root")).render(o.jsx(gn.StrictMode,{children:o.jsx(k4,{})}));
|