openfox 2.0.53 → 2.0.55
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/{chat-handler-FGRCJX76.js → chat-handler-C3NO5RY3.js} +5 -5
- package/dist/{chunk-QOHRXWK4.js → chunk-5UHSEVAP.js} +2 -2
- package/dist/{chunk-KUE7ASKH.js → chunk-7V3JBKYK.js} +20 -20
- package/dist/{chunk-VRGRAQDG.js → chunk-CYJEQF7U.js} +79 -9
- package/dist/{chunk-N3Z4SMEH.js → chunk-JQ4FVPIM.js} +2 -2
- package/dist/{chunk-PBGOZMVY.js → chunk-OCILP3SJ.js} +11 -39
- package/dist/{chunk-HVLNOTRE.js → chunk-PRYVRROH.js} +4 -4
- package/dist/{chunk-3KVWOPRN.js → chunk-ZIW47U5D.js} +22 -92
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/{manager-R3EMNOPR.js → manager-FV4BDEVU.js} +3 -3
- package/dist/{orchestrator-5LSO63RB.js → orchestrator-2OPDGKLZ.js} +5 -5
- package/dist/package.json +3 -1
- package/dist/{processor-F5FMOPOQ.js → processor-VUAIB4Z6.js} +5 -5
- package/dist/{serve-DMHI2CWZ.js → serve-UX6YYIMR.js} +7 -7
- package/dist/server/index.js +6 -6
- package/dist/{server-ZQ5NGHPD.js → server-ILO7GYZE.js} +6 -6
- package/dist/{store-SF7CDOQT.js → store-TTU4UQQ7.js} +2 -2
- package/dist/{tools-2QMJFAXE.js → tools-32PBXC2S.js} +4 -4
- package/dist/web/assets/{index-Bc9jabDX.js → index-ByGymMJ1.js} +2 -2
- package/dist/web/index.html +1 -1
- package/dist/web/sw.js +1 -1
- package/package.json +3 -1
|
@@ -86,7 +86,7 @@ WARNING: This link could potentially be dangerous`)){const S=window.open();if(S)
|
|
|
86
86
|
w-[300px] bg-secondary border-r border-border flex flex-col
|
|
87
87
|
transition-all duration-300 ease-in-out
|
|
88
88
|
${t?"translate-x-0":"-translate-x-full"}
|
|
89
|
-
`,children:[o.jsxs("div",{className:"p-4 border-b border-border flex gap-2",children:[o.jsx(Gn,{href:`/p/${e}/new`,className:"flex-1 block text-center rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-1.5 text-sm","data-testid":"sidebar-new-session-button",children:"+ New Session"}),o.jsx(wl,{items:[{label:"Edit project settings",onClick:()=>l(!0)},{label:"Delete all sessions",onClick:E,danger:!0}],trigger:o.jsx("button",{className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Options",children:o.jsx(_p,{})})}),n&&o.jsx(Cl,{onClick:n,className:"md:hidden",variant:"sidebar",size:"md"})]}),w&&o.jsx(PN,{isOpen:a,onClose:()=>l(!1),project:w}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:S.length===0?o.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"No sessions"}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"divide-y divide-border",children:$N(S,c,d,b,_,e)}),y&&o.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"Loading more..."}),o.jsx("div",{ref:C,className:"h-px"})]})})]})]})}function $N(e,t,n,s,a,l){const u=WS(e);return Array.from(u).map(([c,d])=>{const f=d[0];return f?o.jsxs("div",{children:[o.jsx("div",{className:"px-4 py-2 bg-bg-tertiary/30 text-text-muted text-xs font-medium",children:VS(f.updatedAt)}),d.map(p=>{const m=(t==null?void 0:t.id)===p.id,x=n.includes(p.id),y=p.isRunning;return o.jsx("div",{className:`w-full px-4 py-3 text-left hover:bg-bg-tertiary/50 transition-colors group ${m?"bg-bg-tertiary":""}`,children:o.jsxs(Gn,{href:`/p/${l}/s/${p.id}`,className:`block ${m?"text-accent-primary":"text-text-primary"} hover:text-accent-primary`,children:[o.jsxs("div",{className:"flex justify-between items-center mb-1",children:[o.jsx("span",{className:`font-medium truncate text-sm ${m?"text-accent-primary":"text-text-primary"}`,children:p.title??p.id.slice(0,6)}),o.jsx(wl,{items:[{label:"Rename session",onClick:w=>a(p.id,w)},{label:"Delete session",onClick:w=>s(p.id,w),danger:!0}],trigger:o.jsx("button",{onClick:w=>w.preventDefault(),className:"p-1.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-all",title:"Options",children:o.jsx(_p,{})})})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[y?o.jsx(Hj,{}):x&&!m?o.jsx("span",{"aria-label":"Unread activity",title:"Unread activity",className:"w-2 h-2 rounded-full bg-amber-400 flex-shrink-0"}):null,o.jsx("span",{className:"text-text-muted text-xs flex-shrink-0",children:Yu(p.updatedAt)}),o.jsxs("span",{className:"text-text-muted text-xs flex-shrink-0",children:[p.messageCount," messages"]})]})]})},p.id)})]},c):null})}const Jv=["⠋","⠙","⠹","⠸","⠼","⠴"];function HN(){var c;const e=Lt(d=>d.currentProject),t=Re(d=>d.currentSession),n=Fu(),s=!1,a=L.useRef(0),l=L.useRef(null);L.useEffect(()=>(n?(l.current=window.setInterval(()=>{a.current=(a.current+1)%Jv.length,u()},150),u()):(l.current&&(clearInterval(l.current),l.current=null),u()),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[n,e,t,s]);const u=()=>{var m;const f=(m=t==null?void 0:t.metadata)==null?void 0:m.title,p=n?`${Jv[a.current]} `:"";e&&f?document.title=`${p}${e.name} - ${f} | OpenFox`:e?document.title=`${p}${e.name} | OpenFox`:document.title=`${p}OpenFox`};return typeof window<"u"&&((c=t==null?void 0:t.metadata)!=null&&c.title)&&window.document.documentElement.setAttribute("data-session-title",t.metadata.title),null}function KS(e,t=28){if(e.length<=t)return e;const n=e.split("/").filter(Boolean);if(n.length<=2)return e;const s=n[0],a=n[n.length-1],l=n.slice(1,-1).join("/"),u=t-s.length-a.length-3;if(u<0)return e;const c=l.slice(0,Math.floor(u/2)),d=l.slice(-Math.ceil(u/2));return`/${s}/${c}...${d}/${a}`}function YS({isOpen:e,onClose:t,projectName:n,onConfirm:s}){const a=()=>{s(),t()};return o.jsx(Dt,{isOpen:e,onClose:t,title:"Delete Project",size:"sm",children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("p",{className:"text-text-secondary",children:["This will permanently delete the project"," ",o.jsx("span",{className:"font-semibold text-text-primary",children:n})," and all its sessions from OpenFox. The project files on disk will remain untouched."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{variant:"secondary",onClick:t,children:"Cancel"}),o.jsx(nt,{variant:"danger",onClick:a,children:"Delete"})]})]})})}function UN({isOpen:e,onClose:t}){const[,n]=qn(),[s,a]=L.useState(!1),l=FS(),[u,c]=L.useState(!1),d=Lt(A=>A.projects),f=Lt(A=>A.createProject),p=Lt(A=>A.listProjects),m=Lt(A=>A.deleteProject),[x,y]=L.useState(null),[w,C]=L.useState(null);L.useEffect(()=>{e&&p()},[e,p]);const v=A=>{n(`/p/${A}`),t()},S=(A,O)=>{O.stopPropagation(),y(A)},b=()=>{x&&(m(x.id),y(null))},_=async A=>N(A);function E(A){return A!=null&&typeof A=="object"&&"error"in A&&A.error!=null&&typeof A.error=="object"&&"code"in A.error&&A.error.code==="EACCES"}async function N(A){const O=A.split("/").filter(Boolean).pop()??"",M=await f(O,A);return p(),E(M)?(C(M.error.path||A),!1):M&&"id"in M?(n(`/p/${M.id}`),t(),!0):!1}const T=L.useCallback(()=>{C(null)},[]),D=L.useCallback(async()=>{const A=w;C(null),A&&await N(A)},[w]);return e?o.jsxs(Dt,{isOpen:e,onClose:t,title:"Open Project",size:"xl",footer:o.jsx("div",{className:"flex justify-end gap-2",children:o.jsx(nt,{variant:"secondary",onClick:t,children:"Close"})}),children:[o.jsxs("div",{className:"flex flex-col sm:flex-row flex-1 -m-4",children:[o.jsxs("div",{className:"w-full sm:w-1/2 border-b sm:border-b-0 sm:border-r border-border flex flex-col max-h-[40vh] sm:max-h-[50vh]",children:[o.jsx("div",{className:"p-3 border-b border-border bg-bg-tertiary/30 shrink-0",children:o.jsx("h3",{className:"font-medium text-sm text-text-secondary",children:"Recent Projects"})}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:d.length===0?o.jsxs("div",{className:"p-6 text-center text-text-muted text-sm",children:[o.jsx("p",{className:"mb-2",children:"No recent projects"}),o.jsx("p",{className:"text-xs",children:'Click "Create new project" to add one'})]}):o.jsx("div",{className:"divide-y divide-border",children:d.map(A=>o.jsxs("div",{className:"group flex items-center gap-3 p-3 hover:bg-bg-tertiary/50 transition-colors",children:[o.jsxs("button",{onClick:()=>v(A.id),className:"flex-1 flex items-center gap-3 text-left",children:[o.jsx(bl,{className:"w-5 h-5 text-accent-primary"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"font-medium truncate",children:A.name}),o.jsx("div",{className:"text-xs text-text-muted truncate",children:KS(A.workdir,32)})]})]}),o.jsx("button",{onClick:O=>S(A,O),className:"text-accent-error/70 hover:text-accent-error p-1",title:"Delete project",children:o.jsx(Va,{className:"w-4 h-4"})})]},A.id))})})]}),o.jsx("div",{className:"w-full sm:w-1/2 flex flex-col items-center justify-center p-6 sm:p-8 text-center",children:o.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-sm",children:[o.jsx(nt,{variant:"primary",onClick:()=>c(!0),children:"Select existing project"}),o.jsx(nt,{variant:"secondary",onClick:()=>a(!0),"data-testid":"open-project-create-button",children:"Create new project"})]})})]}),s&&o.jsx(US,{isOpen:s,onClose:()=>a(!1)}),x&&o.jsx(YS,{isOpen:!0,onClose:()=>y(null),projectName:x.name,onConfirm:b}),u&&o.jsx(Tp,{initialPath:l??void 0,onSelect:A=>{_(A)},onClose:()=>c(!1)}),w&&o.jsx(HS,{isOpen:!0,onClose:T,path:w,onRetry:D})]}):null}function FN(){const[e,t]=L.useState(!1),[n,s]=L.useState(null),a=Re(w=>w.sessions),l=Lt(w=>w.projects),u=Lt(w=>w.loading),c=Lt(w=>w.listProjects),d=Re(w=>w.listSessions),f=Lt(w=>w.deleteProject),p=Re(w=>w.connectionStatus);L.useEffect(()=>{p==="connected"&&(c(),d())},[p,c,d]);const m=[...l].sort((w,C)=>{const v=a.filter(E=>E.workdir.startsWith(w.workdir)),S=a.filter(E=>E.workdir.startsWith(C.workdir)),b=v.length>0?new Date(v.reduce((E,N)=>new Date(N.updatedAt)>new Date(E.updatedAt)?N:E).updatedAt).getTime():new Date(w.updatedAt).getTime();return(S.length>0?new Date(S.reduce((E,N)=>new Date(N.updatedAt)>new Date(E.updatedAt)?N:E).updatedAt).getTime():new Date(C.updatedAt).getTime())-b}),x=w=>{const C=l.find(v=>v.id===w);return C?a.filter(v=>v.workdir.startsWith(C.workdir)).sort((v,S)=>new Date(S.updatedAt).getTime()-new Date(v.updatedAt).getTime()).slice(0,5):[]},y=()=>{t(!0)};return o.jsxs("div",{className:"flex-1 flex flex-col overflow-y-auto bg-primary",children:[o.jsxs("div",{className:"max-w-5xl mx-auto w-full p-4 md:p-8",children:[o.jsxs("div",{className:"mb-6 md:mb-8 flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-3xl font-bold text-accent-primary",children:"OpenFox"}),o.jsx("p",{className:"text-text-secondary",children:"Local LLM-powered coding assistant with contract-driven execution"})]}),o.jsx(nt,{variant:"primary",onClick:y,children:"Open Project"})]}),m.map(w=>{const C=x(w.id);return o.jsx("div",{className:"mb-6 md:mb-8",children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-lg overflow-hidden",children:[o.jsxs("div",{className:"p-3 md:p-4 border-b border-border flex items-center justify-between gap-2",children:[o.jsxs(Gn,{href:`/p/${w.id}`,className:"flex items-center gap-2 cursor-pointer hover:opacity-80 transition-opacity flex-1",children:[o.jsx(bl,{className:"w-5 h-5 text-accent-primary flex-shrink-0"}),o.jsx("span",{className:"text-text-primary font-semibold",children:w.name})]}),o.jsx(Gn,{href:`/p/${w.id}/new`,className:"rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-1.5 py-1 text-xs",children:"+ New Session"}),o.jsx("button",{type:"button",onClick:()=>s({id:w.id,name:w.name}),className:"p-1.5 rounded text-text-muted hover:text-accent-error hover:bg-accent-error/10 transition-colors",title:"Delete project",children:o.jsx(Va,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"divide-y divide-border",children:C.length>0?C.map(v=>{const S=l.find(_=>v.workdir.startsWith(_.workdir)),b=S?`/p/${S.id}/s/${v.id}`:"#";return o.jsx(Gn,{href:b,className:"block p-3 md:p-4 hover:bg-bg-tertiary/50 cursor-pointer transition-colors",children:o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("div",{className:"text-sm text-text-muted truncate",children:v.title??v.id.slice(0,8)})})}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-text-muted text-xs",children:AN(v.updatedAt)}),o.jsxs("span",{className:"text-text-muted text-xs",children:[v.messageCount," msgs"]})]})]})},v.id)}):o.jsx("div",{className:"p-3 md:p-4 text-text-muted text-sm",children:"No sessions yet"})})]})},w.id)}),m.length===0&&!u&&o.jsx("div",{className:"text-center py-12 text-text-muted",children:"No projects yet. Open a project to get started."}),u&&o.jsx("div",{className:"flex justify-center py-12",children:o.jsx(Di,{})})]}),e&&o.jsx(UN,{isOpen:e,onClose:()=>t(!1)}),n&&o.jsx(YS,{isOpen:!0,onClose:()=>s(null),projectName:n.name,onConfirm:()=>f(n.id)})]})}function VN(){const[,e]=Fa("/p/:projectId/new"),[,t]=qn(),n=e==null?void 0:e.projectId,s=Re(u=>u.createSession),a=Re(u=>u.resetPendingSessionCreate),l=L.useCallback(async()=>{if(!n)return;const u=await s(n);u?(t(`/p/${n}/s/${u.id}`),a()):(t(`/p/${n}`),a())},[n,s,t,a]);return L.useEffect(()=>{l()},[l]),o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Di,{})})}function GN(){const e=Lt(t=>t.currentProject);return o.jsx("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center",children:o.jsxs("div",{className:"max-w-md",children:[o.jsx("h2",{className:"text-xl font-semibold text-text-primary mb-2",children:(e==null?void 0:e.name)??"Project"}),o.jsx("p",{className:"text-text-secondary mb-6",children:"No session selected"}),o.jsxs("div",{className:"flex flex-col gap-3",children:[e&&o.jsx(Gn,{href:`/p/${e.id}/new`,"data-testid":"create-new-session-button",className:"block w-full rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-2 text-center",children:"Create New Session"}),o.jsx("p",{className:"text-sm text-text-muted",children:"Or select an existing session from the sidebar"})]})]})})}const Wo=e=>Math.round(e*10)/10;function WN(e){return typeof e.totalTime=="number"&&!Number.isNaN(e.totalTime)}function Im(e){return{providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model}}function qN(e){return`${e.providerId}::${e.model}`}function KN(e){return`${e.providerName} > ${e.model}`}function Zv(e){let t=0,n=0,s=0,a=0,l=0,u=0;const c=[],d=[];let f=0;for(const[x,y]of e.entries()){const w=y.stats,C=Im(w);t+=w.totalTime,n+=w.toolTime,s+=w.prefillTokens,a+=w.generationTokens;const v=w.prefillSpeed>0?w.prefillTokens/w.prefillSpeed:0,S=w.generationSpeed>0?w.generationTokens/w.generationSpeed:0;l+=v,u+=S,c.push({messageId:y.id,timestamp:y.timestamp,...C,mode:w.mode,responseIndex:x+1,prefillTokens:w.prefillTokens,generationTokens:w.generationTokens,prefillSpeed:w.prefillSpeed,generationSpeed:w.generationSpeed,totalTime:w.totalTime,aiTime:w.totalTime-w.toolTime,toolTime:w.toolTime});const b=w.llmCalls??[];for(const _ of b)f+=1,d.push({messageId:y.id,timestamp:_.timestamp??y.timestamp,providerId:_.providerId,providerName:_.providerName,backend:_.backend,model:_.model,mode:w.mode,responseIndex:x+1,sessionCallIndex:f,callIndex:_.callIndex,promptTokens:_.promptTokens,completionTokens:_.completionTokens,ttft:_.ttft,completionTime:_.completionTime,prefillSpeed:_.prefillSpeed,generationSpeed:_.generationSpeed,totalTime:_.totalTime,..._.temperature!==void 0&&{temperature:_.temperature},..._.topP!==void 0&&{topP:_.topP},..._.topK!==void 0&&{topK:_.topK},..._.maxTokens!==void 0&&{maxTokens:_.maxTokens}})}const p=l>0?Wo(s/l):0,m=u>0?Wo(a/u):0;return{totalTime:Wo(t),aiTime:Wo(t-n),toolTime:Wo(n),prefillTokens:s,generationTokens:a,avgPrefillSpeed:p,avgGenerationSpeed:m,responseCount:e.length,llmCallCount:d.length,dataPoints:c,callDataPoints:d}}function YN(e){const t=e.filter(a=>a.stats!==void 0&&a.stats!==null&&WN(a.stats)).sort((a,l)=>new Date(a.timestamp).getTime()-new Date(l.timestamp).getTime());if(t.length===0)return null;const n=new Map;for(const a of t){const l=qN(Im(a.stats)),u=n.get(l)??[];n.set(l,[...u,a])}const s=Array.from(n.entries()).map(([a,l])=>{const u=Im(l[0].stats),c=Zv(l);return{...u,key:a,label:KN(u),...c}});return{...Zv(t),modelGroups:s}}function XN(e){return L.useMemo(()=>YN(e),[e])}function XS(){var a;const e=Re(l=>l.gitStatus),t=Re(l=>l.currentSession),[n,s]=L.useState(!0);return L.useEffect(()=>{t!=null&&t.workdir&&s(!1)},[t==null?void 0:t.workdir]),{branch:(e==null?void 0:e.branch)??null,diff:{files:((a=e==null?void 0:e.diff)==null?void 0:a.files)??[],loading:n,error:null}}}function _u(e){return e.toLocaleString("en-US").replace(/,/g," ")}function eb(e){return Number.isFinite(e)?e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1):"0"}function QN(e){if(!Number.isFinite(e))return"0s";if(e<60)return`${e.toFixed(1)}s`;const t=Math.floor(e/60),n=Math.round(e%60);return`${t}m${n}s`}const tb=["▁","▂","▃","▄","▅","▆","▇","█"];function JN(e,t,n){if(n===t)return 4;const s=(e-t)/(n-t);return Math.min(7,Math.max(0,Math.round(s*7)))}function ZN(e,t){if(e===t){const a=Math.max(Math.abs(e)*.05,1);return{minY:e-a,maxY:t+a}}const n=t-e,s=Math.max(n*.1,.1);return{minY:e-s,maxY:t+s}}function eT(e,t){if(e.length===0||t<=0)return{blocks:"",minX:0,maxX:0,minY:0,maxY:0};const n=[...e].sort((x,y)=>x.x-y.x),s=n[0].x,a=n[n.length-1].x,l=Math.min(...n.map(x=>x.y)),u=Math.max(...n.map(x=>x.y)),{minY:c,maxY:d}=ZN(l,u),f=Math.max(0,c),p=Array.from({length:t},()=>" "),m=new Map;for(const x of n){const y=a===s?0:Math.round((x.x-s)/(a-s)*(t-1)),w=m.get(y)??[];m.set(y,[...w,x.y])}for(const[x,y]of m){const w=Math.max(...y);p[x]=tb[JN(w,c,d)]??tb[0]}return{blocks:p.join(""),minX:s,maxX:a,minY:f,maxY:d}}function nb(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function rb({data:e,width:t=60,height:n=78,label:s,xLabel:a,yLabel:l,showAxes:u=!0,formatY:c=nb,formatX:d=nb}){const f=L.useMemo(()=>{const p=eT(e,t),m=Math.max(t*6,240),x=10,y=8,C=[...e].sort((_,E)=>_.x-E.x).map(_=>{const E=p.maxX===p.minX?m/2:x+(_.x-p.minX)/(p.maxX-p.minX)*(m-x*2),N=p.maxY===p.minY?n/2:y+(p.maxY-_.y)/(p.maxY-p.minY)*(n-y*2);return{..._,cx:E,cy:N,leftPercent:E/m*100,topPercent:N/n*100}}),v=C.map((_,E)=>`${E===0?"M":"L"} ${_.cx.toFixed(1)} ${_.cy.toFixed(1)}`).join(" "),b=[p.maxY,(p.maxY+p.minY)/2,p.minY].map(_=>({value:_,y:p.maxY===p.minY?n/2:y+(p.maxY-_)/(p.maxY-p.minY)*(n-y*2)}));return{...p,chartWidth:m,points:C,path:v,gridLines:b}},[e,n,t]);return e.length===0?o.jsxs("div",{className:"font-mono text-text-muted text-xs",children:[s&&o.jsx("div",{className:"mb-1",children:s}),o.jsx("div",{children:"No data"})]}):o.jsxs("div",{className:"font-mono text-xs",children:[s&&o.jsx("div",{className:"text-text-secondary mb-2",children:s}),o.jsxs("div",{className:"flex gap-3",children:[u&&o.jsx("div",{className:"w-12 h-[78px] flex flex-col justify-between text-right text-text-muted",children:f.gridLines.map(p=>o.jsx("span",{children:c(p.value)},`${p.value}-${p.y}`))}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsxs("div",{className:"relative h-[78px]",children:[o.jsxs("svg",{viewBox:`0 0 ${f.chartWidth} ${n}`,className:"w-full h-[78px] overflow-visible",preserveAspectRatio:"none","aria-hidden":"true",children:[f.gridLines.map(p=>o.jsx("line",{x1:"0",x2:f.chartWidth,y1:p.y,y2:p.y,stroke:"currentColor",strokeDasharray:"3 4",className:"text-border/60"},`grid-${p.y}`)),f.points.map(p=>o.jsx("line",{x1:p.cx,x2:p.cx,y1:n-4,y2:p.cy,stroke:"currentColor",className:"text-border/40"},`guide-${p.cx}-${p.cy}`)),f.points.length>1&&o.jsx("path",{d:f.path,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-accent-primary/45"})]}),f.points.map(p=>o.jsx("div",{className:"absolute -translate-x-1/2 -translate-y-1/2",style:{left:`${p.leftPercent}%`,top:`${p.topPercent}%`},title:`${d(p.x)} -> ${c(p.y)}`,children:o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-accent-primary/20 flex items-center justify-center",children:o.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary"})})},`point-${p.x}-${p.y}`))]})})]}),u&&o.jsxs("div",{className:"flex items-start gap-3 text-text-muted mt-1",children:[o.jsx("span",{className:"w-12"}),o.jsxs("span",{className:"flex-1 flex justify-between",children:[o.jsx("span",{children:d(f.minX)}),o.jsx("span",{children:a}),o.jsx("span",{children:d(f.maxX)})]})]}),l&&u&&o.jsx("div",{className:"text-text-muted mt-1 text-center",children:l})]})}function tT({data:e,prefillLabel:t="Prefill Speed (tok/s) by Response",generationLabel:n="Generation Speed (tok/s) by Response",xLabel:s="response",width:a=60}){const l=e.map(c=>({x:c.x,y:c.ppSpeed})),u=e.map(c=>({x:c.x,y:c.tgSpeed}));return o.jsxs("div",{className:"space-y-5",children:[o.jsx(rb,{data:l,width:a,label:t,xLabel:s}),o.jsx(rb,{data:u,width:a,label:n,xLabel:s})]})}function nT(e){const t=new Map;for(const n of e.callDataPoints){const s=t.get(n.messageId)??[];t.set(n.messageId,[...s,n])}return e.dataPoints.map(n=>{const s=[...t.get(n.messageId)??[]].sort((a,l)=>a.callIndex-l.callIndex);return{...n,callCount:s.length,calls:s,isExpandable:s.length>1}})}function rT(e){return{mode:"responses",xLabel:"response",prefillLabel:"Prefill Speed (tok/s) by Response",generationLabel:"Generation Speed (tok/s) by Response",points:e.dataPoints.map(t=>({x:t.responseIndex,ppSpeed:t.prefillSpeed,tgSpeed:t.generationSpeed}))}}function sT(e){return{mode:"calls",xLabel:"context",prefillLabel:"Prefill Speed (tok/s) vs Context",generationLabel:"Generation Speed (tok/s) vs Context",points:e.callDataPoints.map(t=>({x:t.promptTokens,ppSpeed:t.prefillSpeed,tgSpeed:t.generationSpeed}))}}function iT(e){return e.callDataPoints.length>0?sT(e):rT(e)}function Vf(e){if(e<60)return`${e.toFixed(1)}s`;const t=Math.floor(e/60),n=e%60;return`${t}m ${n.toFixed(0)}s`}function Ni(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function rl(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function aT(e){if(e.length===0)return"0 ctx";const t=Math.min(...e),n=Math.max(...e);return t===n?`${Ni(t)} ctx`:`${Ni(t)}-${Ni(n)} ctx`}function vu(e){return`${rl(e)} t/s`}function QS(e){try{return new Date(e).toLocaleTimeString("en-US",{hour12:!1})}catch{return e}}function oT(e){return{exportedAt:new Date().toISOString(),providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model,label:e.label,summary:{totalTime:e.totalTime,aiTime:e.aiTime,toolTime:e.toolTime,prefillTokens:e.prefillTokens,generationTokens:e.generationTokens,avgPrefillSpeed:e.avgPrefillSpeed,avgGenerationSpeed:e.avgGenerationSpeed,responseCount:e.responseCount,llmCallCount:e.llmCallCount},responses:e.dataPoints.map(t=>({responseIndex:t.responseIndex,timestamp:t.timestamp,mode:t.mode,prefillTokens:t.prefillTokens,generationTokens:t.generationTokens,prefillSpeed:t.prefillSpeed,generationSpeed:t.generationSpeed,totalTime:t.totalTime,aiTime:t.aiTime,toolTime:t.toolTime})),llmCalls:e.callDataPoints.map(t=>({sessionCallIndex:t.sessionCallIndex,responseIndex:t.responseIndex,callIndex:t.callIndex,timestamp:t.timestamp,mode:t.mode,promptTokens:t.promptTokens,completionTokens:t.completionTokens,ttft:t.ttft,completionTime:t.completionTime,prefillSpeed:t.prefillSpeed,generationSpeed:t.generationSpeed,totalTime:t.totalTime}))}}function lT({isOpen:e,onClose:t,stats:n}){const s=L.useRef(null),[a,l]=L.useState({}),[u,c]=L.useState(()=>{var w;return((w=n.modelGroups[0])==null?void 0:w.key)??""});L.useEffect(()=>{var w;n.modelGroups.some(C=>C.key===u)||c(((w=n.modelGroups[0])==null?void 0:w.key)??"")},[u,n.modelGroups]);const d=L.useMemo(()=>n.modelGroups.find(w=>w.key===u)??n.modelGroups[0],[u,n.modelGroups]),f=L.useMemo(()=>d?nT(d):[],[d]),p=L.useMemo(()=>d?iT(d):{mode:"responses",xLabel:"response",prefillLabel:"",generationLabel:"",points:[]},[d]),m=L.useCallback(w=>{l(C=>({...C,[w]:!C[w]}))},[]),x=L.useCallback(()=>{if(!d)return;const w=oT(d);navigator.clipboard.writeText(JSON.stringify(w,null,2)).catch(C=>console.error("Failed to copy:",C))},[d]),y=L.useCallback(async()=>{if(s.current)try{const w=(await X(async()=>{const{default:S}=await import("./html2canvas.esm-QH1iLAAe.js");return{default:S}},[])).default,C=await w(s.current,{backgroundColor:"#1a1a1a",scale:2}),v=document.createElement("a");v.download=`openfox-stats-${new Date().toISOString().slice(0,10)}.png`,v.href=C.toDataURL("image/png"),v.click()}catch(w){console.error("Failed to export PNG:",w),x()}},[x]);return o.jsx(Dt,{isOpen:e,onClose:t,title:"Session Stats",size:"lg",children:o.jsxs("div",{ref:s,className:"space-y-6",children:[o.jsx("section",{children:o.jsx("div",{className:"flex flex-wrap gap-2",children:n.modelGroups.map(w=>o.jsx("button",{onClick:()=>c(w.key),className:`px-3 py-1.5 rounded border text-xs transition-colors ${w.key===(d==null?void 0:d.key)?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-primary hover:bg-bg-tertiary/40"}`,title:w.label,children:w.label},w.key))})}),d&&o.jsxs("section",{children:[o.jsx("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:"Summary"}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[o.jsx(ns,{label:"AI Time",value:Vf(d.aiTime)}),o.jsx(ns,{label:"Total Time",value:Vf(d.totalTime)}),o.jsx(ns,{label:"Tool Time",value:Vf(d.toolTime)}),o.jsx(ns,{label:"Responses",value:d.responseCount.toString()}),o.jsx(ns,{label:"LLM Calls",value:d.llmCallCount.toString()})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-3",children:[o.jsx(ns,{label:"Prefill Tokens",value:Ni(d.prefillTokens),subValue:`@ ${rl(d.avgPrefillSpeed)} tok/s`}),o.jsx(ns,{label:"Gen Tokens",value:Ni(d.generationTokens),subValue:`@ ${rl(d.avgGenerationSpeed)} tok/s`}),o.jsx(ns,{label:"Avg PP Speed",value:`${rl(d.avgPrefillSpeed)}`,subValue:"tok/s"}),o.jsx(ns,{label:"Avg TG Speed",value:`${rl(d.avgGenerationSpeed)}`,subValue:"tok/s"})]})]}),d&&p.points.length>1&&o.jsxs("section",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("h3",{className:"text-sm font-semibold text-text-secondary uppercase tracking-wide",children:"Performance Progression"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:x,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Copy JSON"}),o.jsx("button",{onClick:y,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Save PNG"})]})]}),o.jsx("div",{className:"bg-bg-tertiary/50 rounded p-4",children:o.jsx(tT,{data:p.points,width:50,prefillLabel:p.prefillLabel,generationLabel:p.generationLabel,xLabel:p.xLabel})})]}),d&&o.jsxs("section",{children:[o.jsxs("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:["Response Log (",d.responseCount," responses)"]}),o.jsx("div",{className:"overflow-y-auto bg-bg-tertiary/30 rounded",children:o.jsxs("table",{className:"w-full table-fixed border-separate border-spacing-0 text-xs",children:[o.jsxs("colgroup",{children:[o.jsx("col",{className:"w-[7%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[10%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[11%]"}),o.jsx("col",{className:"w-[2%]"})]}),o.jsx("thead",{children:o.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-text-muted/80",children:[o.jsx("th",{className:"px-3 py-2 text-center font-medium",children:"#"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"At"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Time"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Context"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"PP t/s"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"TG t/s"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Calls"}),o.jsx("th",{className:"px-2 py-2"})]})}),o.jsx("tbody",{children:f.map((w,C)=>o.jsxs(L.Fragment,{children:[o.jsx(cT,{row:w,index:C,isExpanded:a[w.messageId]??!1,onToggle:w.isExpandable?()=>m(w.messageId):void 0}),(a[w.messageId]??!1)&&w.calls.map((v,S)=>o.jsx(uT,{dataPoint:v,index:S},`${v.messageId}-${v.callIndex}`))]},w.messageId))})]})})]})]})})}function ns({label:e,value:t,subValue:n}){return o.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[o.jsx("div",{className:"text-text-muted text-xs mb-1",children:e}),o.jsx("div",{className:"text-text-primary text-lg font-semibold",children:t}),n&&o.jsx("div",{className:"text-text-muted text-xs",children:n})]})}function cT({row:e,index:t,isExpanded:n,onToggle:s}){const a=e.calls.length>0?aT(e.calls.map(l=>l.promptTokens)):`${Ni(e.prefillTokens)} ctx`;return o.jsxs("tr",{onClick:s,className:`${t%2===0?"bg-bg-tertiary/20":""} ${s?"cursor-pointer hover:bg-bg-tertiary/35 transition-colors":""}`,children:[o.jsx("td",{className:"px-3 py-2 text-center text-text-muted align-middle",children:e.responseIndex}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:QS(e.timestamp)}),o.jsxs("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:[e.totalTime.toFixed(1),"s"]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:a.replace(/ ctx$/,"")}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.prefillSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.generationSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callCount}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:e.isExpandable?n?"v":">":""})]})}function uT({dataPoint:e,index:t}){const n=e.temperature!==void 0||e.topP!==void 0||e.topK!==void 0||e.maxTokens!==void 0;return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{className:`${t%2===0?"bg-bg-tertiary/10":"bg-bg-tertiary/5"}`,children:[o.jsxs("td",{className:"px-3 py-2 pl-6 text-center text-text-muted align-middle border-l border-border/60",children:["c",e.callIndex]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:QS(e.timestamp)}),o.jsxs("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:[e.totalTime.toFixed(1),"s"]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Ni(e.promptTokens)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.prefillSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.generationSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callIndex}),o.jsx("td",{className:"px-2 py-2"})]}),n&&o.jsx("tr",{className:`${t%2===0?"bg-bg-tertiary/5":"bg-bg-tertiary/[2.5%]"}`,children:o.jsx("td",{colSpan:8,className:"px-6 py-1.5 border-l border-border/60",children:o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-text-muted",children:[e.temperature!==void 0&&o.jsxs("span",{children:["temp: ",e.temperature.toFixed(2)]}),e.topP!==void 0&&o.jsxs("span",{children:["topP: ",e.topP.toFixed(2)]}),e.topK!==void 0&&o.jsxs("span",{children:["topK: ",e.topK]}),e.maxTokens!==void 0&&o.jsxs("span",{children:["maxTok: ",e.maxTokens]})]})})})]})}const dT={passed:{icon:"✓",color:"text-accent-success"},completed:{icon:"◉",color:"text-purple-400"},failed:{icon:"✗",color:"text-accent-error"},resolved:{icon:"✓",color:"text-accent-success"},dismissed:{icon:"–",color:"text-text-muted"},open:{icon:"○",color:"text-accent-warning"},pending:{icon:"○",color:"text-text-muted"},in_progress:{icon:"◌",color:"text-accent-warning"}},hT=["open","in_progress","pending","completed","resolved","dismissed","passed","failed"];function fT(e){return dT[e]??{icon:"○",color:"text-text-muted"}}function JS(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}const Xu=L.memo(function({status:t,className:n="text-xs leading-tight flex-shrink-0"}){const{icon:s,color:a}=fT(t);return o.jsx("span",{className:`${a} ${n}`,children:s})});function sb({entries:e,title:t}){const n=L.useMemo(()=>e.reduce((s,a)=>(s[a.status]=(s[a.status]??0)+1,s),{}),[e]);return o.jsxs("h3",{className:"text-sm font-semibold text-text-primary mb-2 flex items-center justify-between",children:[o.jsx("span",{children:t}),Object.keys(n).length>0&&o.jsx("span",{className:"font-normal text-xs flex items-center gap-1.5",children:hT.map(s=>{const a=n[s];return a?o.jsxs("span",{className:"flex items-center gap-0.5",children:[o.jsx(Xu,{status:s}),o.jsx("span",{children:a})]},s):null})})]})}const mT=L.memo(function({entries:t,title:n,onClearAll:s}){const[a,l]=L.useState(!1),u=L.useCallback(()=>{l(!1),s==null||s()},[s]);return t.length===0?null:o.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[n&&o.jsx("div",{className:"px-1.5 py-1 border-b border-border bg-secondary",children:o.jsx("span",{className:"text-xs font-medium text-text-muted",children:n})}),o.jsx("div",{className:"bg-primary",children:t.map((c,d)=>o.jsxs("div",{className:`flex items-start gap-1 px-1.5 py-1 ${d>0?"border-t border-border":""}`,children:[o.jsx(Xu,{status:c.status}),o.jsxs("div",{className:"flex-1 min-w-0 text-xs truncate",children:[o.jsxs("span",{className:"text-text-muted",children:["[",c.id,"]"]})," ",JS(c.description)]})]},c.id??d))}),s&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary flex items-center gap-2",children:o.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-error transition-colors ml-auto cursor-pointer",title:"Clear all",children:[o.jsx(Va,{className:"w-3 h-3"}),"Clear all"]})}),a&&o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[o.jsx("span",{className:"text-xs text-accent-error",children:"Clear all?"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:u,className:"text-xs text-accent-error hover:text-accent-error/70 transition-colors cursor-pointer",children:"Yes"}),o.jsx("button",{onClick:()=>l(!1),className:"text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:"No"})]})]})})]})]})}),pT="#6b7280";function dl(e,t){var n;return((n=e.find(s=>s.id===t))==null?void 0:n.color)??pT}const mt=Yn(e=>{const t=async()=>{await Cp("/api/agents",e,!0)};return{defaults:[],userItems:[],projectItems:[],loading:!1,fetchAgents:t,fetchAgent:async n=>{try{const s=await Ae(`/api/agents/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ae(`/api/agents/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createAgent:async(n,s)=>{const a=await Ws("POST","/api/agents",{...n,destination:s});return a.success&&await t(),a},updateAgent:async(n,s)=>{const a=await Ws("PUT",`/api/agents/${n}`,s);return a.success&&await t(),a},deleteAgent:async n=>{try{const s=await Ae(`/api/agents/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateAgent:async(n,s)=>Uu(`/api/agents/${n}/duplicate`,t,s)}}),Ct=Yn((e,t)=>({defaults:[],userItems:[],projectItems:[],activeWorkflowId:"default",loading:!1,templateVariables:[],fetchTemplateVariables:async()=>{try{const s=await(await Ae("/api/workflows/template-variables")).json();e({templateVariables:s.variables??[]})}catch{}},fetchWorkflows:async()=>{e({loading:!0});try{const s=await(await Ae("/api/workflows")).json();e({defaults:s.defaults??[],userItems:s.userItems??[],projectItems:s.projectItems??[],activeWorkflowId:s.activeWorkflowId??"default",loading:!1})}catch{e({loading:!1})}},fetchWorkflow:async n=>{try{const s=await Ae(`/api/workflows/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ae(`/api/workflows/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createWorkflow:async(n,s)=>{const a=await Ws("POST","/api/workflows",{...n,destination:s});return a.success&&await t().fetchWorkflows(),a},updateWorkflow:async(n,s)=>{const a=await Ws("PUT",`/api/workflows/${n}`,s);return a.success&&await t().fetchWorkflows(),a},deleteWorkflow:async n=>{try{const s=await Ae(`/api/workflows/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateWorkflow:async(n,s)=>Uu(`/api/workflows/${n}/duplicate`,()=>t().fetchWorkflows(),s)})),gT={pending:"completed",completed:"passed",passed:"failed",failed:"pending"};async function xT(e,t){await Ae(`/api/sessions/${e}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:t})})}function Kc({id:e,agents:t}){const n=dl(t,e),s=t.find(a=>a.id===e);return o.jsx("span",{className:"font-medium rounded px-1",style:{backgroundColor:`${n}20`,color:n},children:(s==null?void 0:s.name)??e})}function yT({id:e}){const t=Ct(u=>u.defaults),n=Ct(u=>u.userItems),a=L.useMemo(()=>[...t,...n],[t,n]).find(u=>u.id===e),l=(a==null?void 0:a.color)??"#3b82f6";return o.jsx("span",{className:"font-medium rounded px-1",style:{backgroundColor:`${l}20`,color:l},children:(a==null?void 0:a.name)??e})}function _T({entries:e,sessionId:t}){const[n,s]=L.useState(e),[a,l]=L.useState(!1),[u,c]=L.useState(null),[d,f]=L.useState(""),[p,m]=L.useState(""),[x,y]=L.useState(!1),[w,C]=L.useState(!1),v=mt(z=>z.defaults),S=mt(z=>z.userItems),b=mt(z=>z.projectItems),_=L.useMemo(()=>[...v,...S,...b],[v,S,b]),E=L.useRef(null),N=L.useRef(null);L.useEffect(()=>{s(e)},[e]),L.useEffect(()=>{var z;a&&((z=E.current)==null||z.focus())},[a]),L.useEffect(()=>{var z;u&&((z=N.current)==null||z.focus())},[u]);const T=L.useCallback(z=>{s(z),xT(t,z)},[t]),D=L.useCallback(()=>{var H;const z=d.trim();if(!z)return;const J=String(n.length),Z=[...n,{id:J,description:z,status:"pending"}];T(Z),f(""),(H=E.current)==null||H.focus()},[n,d,T]),A=L.useCallback(()=>{l(!1),f("")},[]),O=L.useCallback((z,J)=>{c(z),m(J)},[]),M=L.useCallback(()=>{if(!u)return;const z=p.trim(),J=n.map(Z=>Z.id===u?{...Z,description:z||Z.description}:Z);T(J),c(null)},[u,p,n,T]),G=L.useCallback(z=>{const J=n.map(Z=>Z.id===z?{...Z,status:gT[Z.status]??"pending"}:Z);T(J)},[n,T]),V=L.useCallback(z=>{T(n.filter(J=>J.id!==z))},[n,T]),R=L.useCallback(()=>{T([]),y(!1)},[T]),U=L.useCallback(z=>{z.key==="Enter"&&(z.preventDefault(),D()),z.key==="Escape"&&A()},[D,A]),W=L.useCallback(z=>{z.key==="Enter"&&M(),z.key==="Escape"&&c(null)},[M]);return o.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[o.jsxs("div",{className:"bg-primary",children:[n.length===0&&!a&&o.jsxs("div",{className:"px-1.5 py-2 text-xs text-text-muted italic text-center",children:["No criteria yet."," ",o.jsx("button",{onClick:()=>C(!0),className:"text-accent-primary hover:underline not-italic cursor-pointer",children:"Learn more"})]}),n.map((z,J)=>{const Z=z.status,H=u===z.id;return o.jsxs("div",{className:`flex items-start gap-1 px-1.5 py-1 group ${J>0?"border-t border-border":""}`,children:[o.jsx("button",{onClick:()=>G(z.id),className:"text-xs leading-tight flex-shrink-0 cursor-pointer hover:opacity-70 transition-opacity",title:`Status: ${z.status} (click to cycle)`,children:o.jsx(Xu,{status:Z})}),o.jsx("div",{className:"flex-1 min-w-0",children:H?o.jsx("input",{ref:N,value:p,onChange:I=>m(I.target.value),onBlur:M,onKeyDown:W,className:"w-full bg-bg-tertiary text-text-primary text-xs px-1.5 py-0.5 rounded border border-border focus:outline-none focus:border-accent-primary"}):o.jsxs("button",{onClick:()=>O(z.id,z.description),className:"text-xs text-text-primary text-left hover:text-accent-primary transition-colors w-full truncate cursor-pointer",title:"Click to edit",children:["[",z.id,"] ",JS(z.description)]})}),o.jsx("button",{onClick:()=>V(z.id),className:"flex-shrink-0 opacity-0 group-hover:opacity-100 text-text-muted hover:text-accent-error transition-all ml-0.5 cursor-pointer flex items-center self-center",title:"Delete criterion",children:o.jsx(Sl,{className:"w-4 h-4"})})]},z.id)})]}),a&&o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"text-text-muted text-xs leading-tight flex-shrink-0",children:"○"}),o.jsx("input",{ref:E,value:d,onChange:z=>f(z.target.value),onKeyDown:U,placeholder:"New criterion...",className:"flex-1 bg-bg-tertiary text-text-primary text-xs px-1.5 py-0.5 rounded border border-border focus:outline-none focus:border-accent-primary placeholder-text-muted"})]})}),o.jsxs("div",{className:"px-1.5 py-1 border-t border-border bg-secondary flex items-center gap-2",children:[a?o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:D,className:"flex items-center gap-1 text-xs text-accent-primary hover:text-accent-primary/70 transition-colors cursor-pointer",title:"Add criterion",children:[o.jsx(qs,{className:"w-3 h-3"}),"Add"]}),o.jsx("button",{onClick:A,className:"flex items-center gap-1 text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",title:"Cancel",children:"Cancel"})]}):o.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-primary transition-colors cursor-pointer",title:"Add criterion",children:[o.jsx(qs,{className:"w-3 h-3"}),"Add"]}),n.length>0&&o.jsxs("button",{onClick:()=>y(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-error transition-colors ml-auto cursor-pointer",title:"Clear all criteria",children:[o.jsx(Va,{className:"w-3 h-3"}),"Clear all"]}),o.jsx("button",{onClick:()=>C(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-primary transition-colors cursor-pointer",title:"About criteria",children:o.jsx(wS,{className:"w-3 h-3"})})]}),x&&o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[o.jsx("span",{className:"text-xs text-accent-error",children:"Clear all criteria?"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:R,className:"text-xs text-accent-error hover:text-accent-error/70 transition-colors cursor-pointer",children:"Yes"}),o.jsx("button",{onClick:()=>y(!1),className:"text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:"No"})]})]})}),o.jsx(Dt,{isOpen:w,onClose:()=>C(!1),title:"About Acceptance Criteria",size:"md",children:o.jsxs("div",{className:"space-y-3 text-sm text-text-secondary",children:[o.jsx("p",{children:"Each criterion defines a specific requirement that needs to be met."}),o.jsxs("p",{children:["To use this feature, start in ",o.jsx(Kc,{id:"planner",agents:_})," mode and",o.jsxs("strong",{className:"text-text-primary",children:[" ","ask the agent to define acceptance criteria that matches your goal"]}),". Then launch the ",o.jsx(yT,{id:"default"})," builtin workflow to launch the automation part."]}),o.jsx("p",{children:"This workflow will automatically:"}),o.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[o.jsxs("li",{children:["Launch the ",o.jsx(Kc,{id:"builder",agents:_}),' agent, that will be forced to continue until it marks all criteria as "completed"']}),o.jsxs("li",{children:["Then launch the ",o.jsx(Kc,{id:"verifier",agents:_})," subagent, that will verify each criterion. If every criterion is fulfilled, then it goes to the next step, otherwise, it gives feedback to the main agent until 100% of the criteria are met."]}),o.jsxs("li",{children:["Launch a ",o.jsx(Kc,{id:"code_reviewer",agents:_})," subagent, that will analyze the code to provide actionable feedback to the main agent."]})]}),o.jsx("div",{className:"bg-bg-tertiary rounded p-3 space-y-1.5",children:o.jsx("p",{children:"This lets smaller models follow complex plans to completion and improves the chances that nothing from your plan is missed."})})]})})]})}function vT({isOpen:e,onClose:t}){const n=Rr(C=>C.config),s=Rr(C=>C.saveConfig),[a,l]=L.useState(""),[u,c]=L.useState(""),[d,f]=L.useState(!1),[p,m]=L.useState(!1),[x,y]=L.useState(!1);L.useEffect(()=>{e&&(l((n==null?void 0:n.command)??""),c((n==null?void 0:n.url)??""),f((n==null?void 0:n.hotReload)??!1),m((n==null?void 0:n.disableInspect)??!1))},[e,n]);const w=async()=>{!a.trim()||!u.trim()||(y(!0),await s({command:a.trim(),url:u.trim(),hotReload:d,disableInspect:p}),y(!1),t())};return o.jsx(Dt,{isOpen:e,onClose:t,title:"Dev Server Config",size:"sm",children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Command"}),o.jsx("input",{className:"input w-full",type:"text",value:a,onChange:C=>l(C.target.value),placeholder:"npm run dev"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Dev URL"}),o.jsx("input",{className:"input w-full",type:"text",value:u,onChange:C=>c(C.target.value),placeholder:"http://localhost:3000"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",id:"hotReload",checked:d,onChange:C=>f(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),o.jsx("label",{htmlFor:"hotReload",className:"text-xs text-text-secondary",children:"Hot Reload"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",id:"disableInspect",checked:p,onChange:C=>m(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),o.jsx("label",{htmlFor:"disableInspect",className:"text-xs text-text-secondary",children:"Disable inspect feedback"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o.jsx("button",{className:"btn btn-secondary",onClick:t,children:"Cancel"}),o.jsx("button",{className:"btn btn-primary",onClick:w,disabled:x||!a.trim()||!u.trim(),children:x?"Saving...":"Save"})]})]})})}const ib={30:"text-black",31:"text-red-400",32:"text-accent-success",33:"text-accent-warning",34:"text-blue-400",35:"text-purple-400",36:"text-cyan-400",37:"text-gray-300",90:"text-gray-500",91:"text-red-500",92:"text-green-500",93:"text-yellow-400",94:"text-blue-500",95:"text-pink-400",96:"text-cyan-500",97:"text-white"},bT={40:"bg-black",41:"bg-red-900",42:"bg-green-900",43:"bg-yellow-900",44:"bg-blue-900",45:"bg-purple-900",46:"bg-cyan-900",47:"bg-gray-700"},ab={1:"font-bold",2:"opacity-75",4:"underline",7:"bg-bg-secondary"},ST="text-text-primary";function wT(e){const t=[],n=new RegExp("\x1B\\[([0-9;]+)m","g");let s=0,a="text-text-primary",l;try{for(;(l=n.exec(e))!==null;){if(l.index>s){const f=e.slice(s,l.index);f&&t.push({text:f,className:a})}const u=l[1];if(!u)continue;const c=u.split(";").map(Number);if(c.length===0||c[0]===0){a="text-text-primary";continue}const d=[];for(const f of c)if(f>=30&&f<=37){const p=ib[f];p&&d.push(p)}else if(f>=40&&f<=47){const p=bT[f];p&&d.push(p)}else if(f>=90&&f<=97){const p=ib[f];p&&d.push(p)}else if(f in ab){const p=ab[f];p&&d.push(p)}else f===39?d.push(ST):f===49&&(a=a.split(" ").filter(p=>!p.startsWith("bg-")).join(" "));d.length>0&&(a=d.join(" ")),s=n.lastIndex}if(s<e.length){const u=e.slice(s);u&&t.push({text:u,className:a})}return t}catch(u){return console.warn("ANSI parsing failed, stripping codes:",u),[{text:CT(e),className:"text-text-primary"}]}}function CT(e){return e.replace(new RegExp("\x1B\\[([0-9;]+)m","g"),"")}function bu(e){const t=wT(e),n=[];return t.forEach((s,a)=>{const l=s.text.split(`
|
|
89
|
+
`,children:[o.jsxs("div",{className:"p-4 border-b border-border flex gap-2",children:[o.jsx(Gn,{href:`/p/${e}/new`,className:"flex-1 block text-center rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-1.5 text-sm","data-testid":"sidebar-new-session-button",children:"+ New Session"}),o.jsx(wl,{items:[{label:"Edit project settings",onClick:()=>l(!0)},{label:"Delete all sessions",onClick:E,danger:!0}],trigger:o.jsx("button",{className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Options",children:o.jsx(_p,{})})}),n&&o.jsx(Cl,{onClick:n,className:"md:hidden",variant:"sidebar",size:"md"})]}),w&&o.jsx(PN,{isOpen:a,onClose:()=>l(!1),project:w}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:S.length===0?o.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"No sessions"}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"divide-y divide-border",children:$N(S,c,d,b,_,e)}),y&&o.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"Loading more..."}),o.jsx("div",{ref:C,className:"h-px"})]})})]})]})}function $N(e,t,n,s,a,l){const u=WS(e);return Array.from(u).map(([c,d])=>{const f=d[0];return f?o.jsxs("div",{children:[o.jsx("div",{className:"px-4 py-2 bg-bg-tertiary/30 text-text-muted text-xs font-medium",children:VS(f.updatedAt)}),d.map(p=>{const m=(t==null?void 0:t.id)===p.id,x=n.includes(p.id),y=p.isRunning;return o.jsx("div",{className:`w-full px-4 py-3 text-left hover:bg-bg-tertiary/50 transition-colors group ${m?"bg-bg-tertiary":""}`,children:o.jsxs(Gn,{href:`/p/${l}/s/${p.id}`,className:`block ${m?"text-accent-primary":"text-text-primary"} hover:text-accent-primary`,children:[o.jsxs("div",{className:"flex justify-between items-center mb-1",children:[o.jsx("span",{className:`font-medium truncate text-sm ${m?"text-accent-primary":"text-text-primary"}`,children:p.title??p.id.slice(0,6)}),o.jsx(wl,{items:[{label:"Rename session",onClick:w=>a(p.id,w)},{label:"Delete session",onClick:w=>s(p.id,w),danger:!0}],trigger:o.jsx("button",{onClick:w=>w.preventDefault(),className:"p-1.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-all",title:"Options",children:o.jsx(_p,{})})})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[y?o.jsx(Hj,{}):x&&!m?o.jsx("span",{"aria-label":"Unread activity",title:"Unread activity",className:"w-2 h-2 rounded-full bg-amber-400 flex-shrink-0"}):null,o.jsx("span",{className:"text-text-muted text-xs flex-shrink-0",children:Yu(p.updatedAt)}),o.jsxs("span",{className:"text-text-muted text-xs flex-shrink-0",children:[p.messageCount," messages"]})]})]})},p.id)})]},c):null})}const Jv=["⠋","⠙","⠹","⠸","⠼","⠴"];function HN(){var c;const e=Lt(d=>d.currentProject),t=Re(d=>d.currentSession),n=Fu(),s=!1,a=L.useRef(0),l=L.useRef(null);L.useEffect(()=>(n?(l.current=window.setInterval(()=>{a.current=(a.current+1)%Jv.length,u()},150),u()):(l.current&&(clearInterval(l.current),l.current=null),u()),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[n,e,t,s]);const u=()=>{var m;const f=(m=t==null?void 0:t.metadata)==null?void 0:m.title,p=n?`${Jv[a.current]} `:"";e&&f?document.title=`${p}${e.name} - ${f} | OpenFox`:e?document.title=`${p}${e.name} | OpenFox`:document.title=`${p}OpenFox`};return typeof window<"u"&&((c=t==null?void 0:t.metadata)!=null&&c.title)&&window.document.documentElement.setAttribute("data-session-title",t.metadata.title),null}function KS(e,t=28){if(e.length<=t)return e;const n=e.split("/").filter(Boolean);if(n.length<=2)return e;const s=n[0],a=n[n.length-1],l=n.slice(1,-1).join("/"),u=t-s.length-a.length-3;if(u<0)return e;const c=l.slice(0,Math.floor(u/2)),d=l.slice(-Math.ceil(u/2));return`/${s}/${c}...${d}/${a}`}function YS({isOpen:e,onClose:t,projectName:n,onConfirm:s}){const a=()=>{s(),t()};return o.jsx(Dt,{isOpen:e,onClose:t,title:"Delete Project",size:"sm",children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("p",{className:"text-text-secondary",children:["This will permanently delete the project"," ",o.jsx("span",{className:"font-semibold text-text-primary",children:n})," and all its sessions from OpenFox. The project files on disk will remain untouched."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{variant:"secondary",onClick:t,children:"Cancel"}),o.jsx(nt,{variant:"danger",onClick:a,children:"Delete"})]})]})})}function UN({isOpen:e,onClose:t}){const[,n]=qn(),[s,a]=L.useState(!1),l=FS(),[u,c]=L.useState(!1),d=Lt(A=>A.projects),f=Lt(A=>A.createProject),p=Lt(A=>A.listProjects),m=Lt(A=>A.deleteProject),[x,y]=L.useState(null),[w,C]=L.useState(null);L.useEffect(()=>{e&&p()},[e,p]);const v=A=>{n(`/p/${A}`),t()},S=(A,O)=>{O.stopPropagation(),y(A)},b=()=>{x&&(m(x.id),y(null))},_=async A=>N(A);function E(A){return A!=null&&typeof A=="object"&&"error"in A&&A.error!=null&&typeof A.error=="object"&&"code"in A.error&&A.error.code==="EACCES"}async function N(A){const O=A.split("/").filter(Boolean).pop()??"",M=await f(O,A);return p(),E(M)?(C(M.error.path||A),!1):M&&"id"in M?(n(`/p/${M.id}`),t(),!0):!1}const T=L.useCallback(()=>{C(null)},[]),D=L.useCallback(async()=>{const A=w;C(null),A&&await N(A)},[w]);return e?o.jsxs(Dt,{isOpen:e,onClose:t,title:"Open Project",size:"xl",footer:o.jsx("div",{className:"flex justify-end gap-2",children:o.jsx(nt,{variant:"secondary",onClick:t,children:"Close"})}),children:[o.jsxs("div",{className:"flex flex-col sm:flex-row flex-1 -m-4",children:[o.jsxs("div",{className:"w-full sm:w-1/2 border-b sm:border-b-0 sm:border-r border-border flex flex-col max-h-[40vh] sm:max-h-[50vh]",children:[o.jsx("div",{className:"p-3 border-b border-border bg-bg-tertiary/30 shrink-0",children:o.jsx("h3",{className:"font-medium text-sm text-text-secondary",children:"Recent Projects"})}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:d.length===0?o.jsxs("div",{className:"p-6 text-center text-text-muted text-sm",children:[o.jsx("p",{className:"mb-2",children:"No recent projects"}),o.jsx("p",{className:"text-xs",children:'Click "Create new project" to add one'})]}):o.jsx("div",{className:"divide-y divide-border",children:d.map(A=>o.jsxs("div",{className:"group flex items-center gap-3 p-3 hover:bg-bg-tertiary/50 transition-colors",children:[o.jsxs("button",{onClick:()=>v(A.id),className:"flex-1 flex items-center gap-3 text-left",children:[o.jsx(bl,{className:"w-5 h-5 text-accent-primary"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"font-medium truncate",children:A.name}),o.jsx("div",{className:"text-xs text-text-muted truncate",children:KS(A.workdir,32)})]})]}),o.jsx("button",{onClick:O=>S(A,O),className:"text-accent-error/70 hover:text-accent-error p-1",title:"Delete project",children:o.jsx(Va,{className:"w-4 h-4"})})]},A.id))})})]}),o.jsx("div",{className:"w-full sm:w-1/2 flex flex-col items-center justify-center p-6 sm:p-8 text-center",children:o.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-sm",children:[o.jsx(nt,{variant:"primary",onClick:()=>c(!0),children:"Select existing project"}),o.jsx(nt,{variant:"secondary",onClick:()=>a(!0),"data-testid":"open-project-create-button",children:"Create new project"})]})})]}),s&&o.jsx(US,{isOpen:s,onClose:()=>a(!1)}),x&&o.jsx(YS,{isOpen:!0,onClose:()=>y(null),projectName:x.name,onConfirm:b}),u&&o.jsx(Tp,{initialPath:l??void 0,onSelect:A=>{_(A)},onClose:()=>c(!1)}),w&&o.jsx(HS,{isOpen:!0,onClose:T,path:w,onRetry:D})]}):null}function FN(){const[e,t]=L.useState(!1),[n,s]=L.useState(null),a=Re(w=>w.sessions),l=Lt(w=>w.projects),u=Lt(w=>w.loading),c=Lt(w=>w.listProjects),d=Re(w=>w.listSessions),f=Lt(w=>w.deleteProject),p=Re(w=>w.connectionStatus);L.useEffect(()=>{p==="connected"&&(c(),d())},[p,c,d]);const m=[...l].sort((w,C)=>{const v=a.filter(E=>E.projectId===w.id),S=a.filter(E=>E.projectId===C.id),b=v.length>0?new Date(v.reduce((E,N)=>new Date(N.updatedAt)>new Date(E.updatedAt)?N:E).updatedAt).getTime():new Date(w.updatedAt).getTime();return(S.length>0?new Date(S.reduce((E,N)=>new Date(N.updatedAt)>new Date(E.updatedAt)?N:E).updatedAt).getTime():new Date(C.updatedAt).getTime())-b}),x=w=>l.find(v=>v.id===w)?a.filter(v=>v.projectId===w).sort((v,S)=>new Date(S.updatedAt).getTime()-new Date(v.updatedAt).getTime()).slice(0,5):[],y=()=>{t(!0)};return o.jsxs("div",{className:"flex-1 flex flex-col overflow-y-auto bg-primary",children:[o.jsxs("div",{className:"max-w-5xl mx-auto w-full p-4 md:p-8",children:[o.jsxs("div",{className:"mb-6 md:mb-8 flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-3xl font-bold text-accent-primary",children:"OpenFox"}),o.jsx("p",{className:"text-text-secondary",children:"Local LLM-powered coding assistant with contract-driven execution"})]}),o.jsx(nt,{variant:"primary",onClick:y,children:"Open Project"})]}),m.map(w=>{const C=x(w.id);return o.jsx("div",{className:"mb-6 md:mb-8",children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-lg overflow-hidden",children:[o.jsxs("div",{className:"p-3 md:p-4 border-b border-border flex items-center justify-between gap-2",children:[o.jsxs(Gn,{href:`/p/${w.id}`,className:"flex items-center gap-2 cursor-pointer hover:opacity-80 transition-opacity flex-1",children:[o.jsx(bl,{className:"w-5 h-5 text-accent-primary flex-shrink-0"}),o.jsx("span",{className:"text-text-primary font-semibold",children:w.name})]}),o.jsx(Gn,{href:`/p/${w.id}/new`,className:"rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-1.5 py-1 text-xs",children:"+ New Session"}),o.jsx("button",{type:"button",onClick:()=>s({id:w.id,name:w.name}),className:"p-1.5 rounded text-text-muted hover:text-accent-error hover:bg-accent-error/10 transition-colors",title:"Delete project",children:o.jsx(Va,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"divide-y divide-border",children:C.length>0?C.map(v=>{const S=l.find(_=>v.projectId===_.id),b=S?`/p/${S.id}/s/${v.id}`:"#";return o.jsx(Gn,{href:b,className:"block p-3 md:p-4 hover:bg-bg-tertiary/50 cursor-pointer transition-colors",children:o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("div",{className:"text-sm text-text-muted truncate",children:v.title??v.id.slice(0,8)})})}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-text-muted text-xs",children:AN(v.updatedAt)}),o.jsxs("span",{className:"text-text-muted text-xs",children:[v.messageCount," msgs"]})]})]})},v.id)}):o.jsx("div",{className:"p-3 md:p-4 text-text-muted text-sm",children:"No sessions yet"})})]})},w.id)}),m.length===0&&!u&&o.jsx("div",{className:"text-center py-12 text-text-muted",children:"No projects yet. Open a project to get started."}),u&&o.jsx("div",{className:"flex justify-center py-12",children:o.jsx(Di,{})})]}),e&&o.jsx(UN,{isOpen:e,onClose:()=>t(!1)}),n&&o.jsx(YS,{isOpen:!0,onClose:()=>s(null),projectName:n.name,onConfirm:()=>f(n.id)})]})}function VN(){const[,e]=Fa("/p/:projectId/new"),[,t]=qn(),n=e==null?void 0:e.projectId,s=Re(u=>u.createSession),a=Re(u=>u.resetPendingSessionCreate),l=L.useCallback(async()=>{if(!n)return;const u=await s(n);u?(t(`/p/${n}/s/${u.id}`),a()):(t(`/p/${n}`),a())},[n,s,t,a]);return L.useEffect(()=>{l()},[l]),o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Di,{})})}function GN(){const e=Lt(t=>t.currentProject);return o.jsx("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center",children:o.jsxs("div",{className:"max-w-md",children:[o.jsx("h2",{className:"text-xl font-semibold text-text-primary mb-2",children:(e==null?void 0:e.name)??"Project"}),o.jsx("p",{className:"text-text-secondary mb-6",children:"No session selected"}),o.jsxs("div",{className:"flex flex-col gap-3",children:[e&&o.jsx(Gn,{href:`/p/${e.id}/new`,"data-testid":"create-new-session-button",className:"block w-full rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-2 text-center",children:"Create New Session"}),o.jsx("p",{className:"text-sm text-text-muted",children:"Or select an existing session from the sidebar"})]})]})})}const Wo=e=>Math.round(e*10)/10;function WN(e){return typeof e.totalTime=="number"&&!Number.isNaN(e.totalTime)}function Im(e){return{providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model}}function qN(e){return`${e.providerId}::${e.model}`}function KN(e){return`${e.providerName} > ${e.model}`}function Zv(e){let t=0,n=0,s=0,a=0,l=0,u=0;const c=[],d=[];let f=0;for(const[x,y]of e.entries()){const w=y.stats,C=Im(w);t+=w.totalTime,n+=w.toolTime,s+=w.prefillTokens,a+=w.generationTokens;const v=w.prefillSpeed>0?w.prefillTokens/w.prefillSpeed:0,S=w.generationSpeed>0?w.generationTokens/w.generationSpeed:0;l+=v,u+=S,c.push({messageId:y.id,timestamp:y.timestamp,...C,mode:w.mode,responseIndex:x+1,prefillTokens:w.prefillTokens,generationTokens:w.generationTokens,prefillSpeed:w.prefillSpeed,generationSpeed:w.generationSpeed,totalTime:w.totalTime,aiTime:w.totalTime-w.toolTime,toolTime:w.toolTime});const b=w.llmCalls??[];for(const _ of b)f+=1,d.push({messageId:y.id,timestamp:_.timestamp??y.timestamp,providerId:_.providerId,providerName:_.providerName,backend:_.backend,model:_.model,mode:w.mode,responseIndex:x+1,sessionCallIndex:f,callIndex:_.callIndex,promptTokens:_.promptTokens,completionTokens:_.completionTokens,ttft:_.ttft,completionTime:_.completionTime,prefillSpeed:_.prefillSpeed,generationSpeed:_.generationSpeed,totalTime:_.totalTime,..._.temperature!==void 0&&{temperature:_.temperature},..._.topP!==void 0&&{topP:_.topP},..._.topK!==void 0&&{topK:_.topK},..._.maxTokens!==void 0&&{maxTokens:_.maxTokens}})}const p=l>0?Wo(s/l):0,m=u>0?Wo(a/u):0;return{totalTime:Wo(t),aiTime:Wo(t-n),toolTime:Wo(n),prefillTokens:s,generationTokens:a,avgPrefillSpeed:p,avgGenerationSpeed:m,responseCount:e.length,llmCallCount:d.length,dataPoints:c,callDataPoints:d}}function YN(e){const t=e.filter(a=>a.stats!==void 0&&a.stats!==null&&WN(a.stats)).sort((a,l)=>new Date(a.timestamp).getTime()-new Date(l.timestamp).getTime());if(t.length===0)return null;const n=new Map;for(const a of t){const l=qN(Im(a.stats)),u=n.get(l)??[];n.set(l,[...u,a])}const s=Array.from(n.entries()).map(([a,l])=>{const u=Im(l[0].stats),c=Zv(l);return{...u,key:a,label:KN(u),...c}});return{...Zv(t),modelGroups:s}}function XN(e){return L.useMemo(()=>YN(e),[e])}function XS(){var a;const e=Re(l=>l.gitStatus),t=Re(l=>l.currentSession),[n,s]=L.useState(!0);return L.useEffect(()=>{t!=null&&t.workdir&&s(!1)},[t==null?void 0:t.workdir]),{branch:(e==null?void 0:e.branch)??null,diff:{files:((a=e==null?void 0:e.diff)==null?void 0:a.files)??[],loading:n,error:null}}}function _u(e){return e.toLocaleString("en-US").replace(/,/g," ")}function eb(e){return Number.isFinite(e)?e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1):"0"}function QN(e){if(!Number.isFinite(e))return"0s";if(e<60)return`${e.toFixed(1)}s`;const t=Math.floor(e/60),n=Math.round(e%60);return`${t}m${n}s`}const tb=["▁","▂","▃","▄","▅","▆","▇","█"];function JN(e,t,n){if(n===t)return 4;const s=(e-t)/(n-t);return Math.min(7,Math.max(0,Math.round(s*7)))}function ZN(e,t){if(e===t){const a=Math.max(Math.abs(e)*.05,1);return{minY:e-a,maxY:t+a}}const n=t-e,s=Math.max(n*.1,.1);return{minY:e-s,maxY:t+s}}function eT(e,t){if(e.length===0||t<=0)return{blocks:"",minX:0,maxX:0,minY:0,maxY:0};const n=[...e].sort((x,y)=>x.x-y.x),s=n[0].x,a=n[n.length-1].x,l=Math.min(...n.map(x=>x.y)),u=Math.max(...n.map(x=>x.y)),{minY:c,maxY:d}=ZN(l,u),f=Math.max(0,c),p=Array.from({length:t},()=>" "),m=new Map;for(const x of n){const y=a===s?0:Math.round((x.x-s)/(a-s)*(t-1)),w=m.get(y)??[];m.set(y,[...w,x.y])}for(const[x,y]of m){const w=Math.max(...y);p[x]=tb[JN(w,c,d)]??tb[0]}return{blocks:p.join(""),minX:s,maxX:a,minY:f,maxY:d}}function nb(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function rb({data:e,width:t=60,height:n=78,label:s,xLabel:a,yLabel:l,showAxes:u=!0,formatY:c=nb,formatX:d=nb}){const f=L.useMemo(()=>{const p=eT(e,t),m=Math.max(t*6,240),x=10,y=8,C=[...e].sort((_,E)=>_.x-E.x).map(_=>{const E=p.maxX===p.minX?m/2:x+(_.x-p.minX)/(p.maxX-p.minX)*(m-x*2),N=p.maxY===p.minY?n/2:y+(p.maxY-_.y)/(p.maxY-p.minY)*(n-y*2);return{..._,cx:E,cy:N,leftPercent:E/m*100,topPercent:N/n*100}}),v=C.map((_,E)=>`${E===0?"M":"L"} ${_.cx.toFixed(1)} ${_.cy.toFixed(1)}`).join(" "),b=[p.maxY,(p.maxY+p.minY)/2,p.minY].map(_=>({value:_,y:p.maxY===p.minY?n/2:y+(p.maxY-_)/(p.maxY-p.minY)*(n-y*2)}));return{...p,chartWidth:m,points:C,path:v,gridLines:b}},[e,n,t]);return e.length===0?o.jsxs("div",{className:"font-mono text-text-muted text-xs",children:[s&&o.jsx("div",{className:"mb-1",children:s}),o.jsx("div",{children:"No data"})]}):o.jsxs("div",{className:"font-mono text-xs",children:[s&&o.jsx("div",{className:"text-text-secondary mb-2",children:s}),o.jsxs("div",{className:"flex gap-3",children:[u&&o.jsx("div",{className:"w-12 h-[78px] flex flex-col justify-between text-right text-text-muted",children:f.gridLines.map(p=>o.jsx("span",{children:c(p.value)},`${p.value}-${p.y}`))}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsxs("div",{className:"relative h-[78px]",children:[o.jsxs("svg",{viewBox:`0 0 ${f.chartWidth} ${n}`,className:"w-full h-[78px] overflow-visible",preserveAspectRatio:"none","aria-hidden":"true",children:[f.gridLines.map(p=>o.jsx("line",{x1:"0",x2:f.chartWidth,y1:p.y,y2:p.y,stroke:"currentColor",strokeDasharray:"3 4",className:"text-border/60"},`grid-${p.y}`)),f.points.map(p=>o.jsx("line",{x1:p.cx,x2:p.cx,y1:n-4,y2:p.cy,stroke:"currentColor",className:"text-border/40"},`guide-${p.cx}-${p.cy}`)),f.points.length>1&&o.jsx("path",{d:f.path,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-accent-primary/45"})]}),f.points.map(p=>o.jsx("div",{className:"absolute -translate-x-1/2 -translate-y-1/2",style:{left:`${p.leftPercent}%`,top:`${p.topPercent}%`},title:`${d(p.x)} -> ${c(p.y)}`,children:o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-accent-primary/20 flex items-center justify-center",children:o.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary"})})},`point-${p.x}-${p.y}`))]})})]}),u&&o.jsxs("div",{className:"flex items-start gap-3 text-text-muted mt-1",children:[o.jsx("span",{className:"w-12"}),o.jsxs("span",{className:"flex-1 flex justify-between",children:[o.jsx("span",{children:d(f.minX)}),o.jsx("span",{children:a}),o.jsx("span",{children:d(f.maxX)})]})]}),l&&u&&o.jsx("div",{className:"text-text-muted mt-1 text-center",children:l})]})}function tT({data:e,prefillLabel:t="Prefill Speed (tok/s) by Response",generationLabel:n="Generation Speed (tok/s) by Response",xLabel:s="response",width:a=60}){const l=e.map(c=>({x:c.x,y:c.ppSpeed})),u=e.map(c=>({x:c.x,y:c.tgSpeed}));return o.jsxs("div",{className:"space-y-5",children:[o.jsx(rb,{data:l,width:a,label:t,xLabel:s}),o.jsx(rb,{data:u,width:a,label:n,xLabel:s})]})}function nT(e){const t=new Map;for(const n of e.callDataPoints){const s=t.get(n.messageId)??[];t.set(n.messageId,[...s,n])}return e.dataPoints.map(n=>{const s=[...t.get(n.messageId)??[]].sort((a,l)=>a.callIndex-l.callIndex);return{...n,callCount:s.length,calls:s,isExpandable:s.length>1}})}function rT(e){return{mode:"responses",xLabel:"response",prefillLabel:"Prefill Speed (tok/s) by Response",generationLabel:"Generation Speed (tok/s) by Response",points:e.dataPoints.map(t=>({x:t.responseIndex,ppSpeed:t.prefillSpeed,tgSpeed:t.generationSpeed}))}}function sT(e){return{mode:"calls",xLabel:"context",prefillLabel:"Prefill Speed (tok/s) vs Context",generationLabel:"Generation Speed (tok/s) vs Context",points:e.callDataPoints.map(t=>({x:t.promptTokens,ppSpeed:t.prefillSpeed,tgSpeed:t.generationSpeed}))}}function iT(e){return e.callDataPoints.length>0?sT(e):rT(e)}function Vf(e){if(e<60)return`${e.toFixed(1)}s`;const t=Math.floor(e/60),n=e%60;return`${t}m ${n.toFixed(0)}s`}function Ni(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function rl(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function aT(e){if(e.length===0)return"0 ctx";const t=Math.min(...e),n=Math.max(...e);return t===n?`${Ni(t)} ctx`:`${Ni(t)}-${Ni(n)} ctx`}function vu(e){return`${rl(e)} t/s`}function QS(e){try{return new Date(e).toLocaleTimeString("en-US",{hour12:!1})}catch{return e}}function oT(e){return{exportedAt:new Date().toISOString(),providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model,label:e.label,summary:{totalTime:e.totalTime,aiTime:e.aiTime,toolTime:e.toolTime,prefillTokens:e.prefillTokens,generationTokens:e.generationTokens,avgPrefillSpeed:e.avgPrefillSpeed,avgGenerationSpeed:e.avgGenerationSpeed,responseCount:e.responseCount,llmCallCount:e.llmCallCount},responses:e.dataPoints.map(t=>({responseIndex:t.responseIndex,timestamp:t.timestamp,mode:t.mode,prefillTokens:t.prefillTokens,generationTokens:t.generationTokens,prefillSpeed:t.prefillSpeed,generationSpeed:t.generationSpeed,totalTime:t.totalTime,aiTime:t.aiTime,toolTime:t.toolTime})),llmCalls:e.callDataPoints.map(t=>({sessionCallIndex:t.sessionCallIndex,responseIndex:t.responseIndex,callIndex:t.callIndex,timestamp:t.timestamp,mode:t.mode,promptTokens:t.promptTokens,completionTokens:t.completionTokens,ttft:t.ttft,completionTime:t.completionTime,prefillSpeed:t.prefillSpeed,generationSpeed:t.generationSpeed,totalTime:t.totalTime}))}}function lT({isOpen:e,onClose:t,stats:n}){const s=L.useRef(null),[a,l]=L.useState({}),[u,c]=L.useState(()=>{var w;return((w=n.modelGroups[0])==null?void 0:w.key)??""});L.useEffect(()=>{var w;n.modelGroups.some(C=>C.key===u)||c(((w=n.modelGroups[0])==null?void 0:w.key)??"")},[u,n.modelGroups]);const d=L.useMemo(()=>n.modelGroups.find(w=>w.key===u)??n.modelGroups[0],[u,n.modelGroups]),f=L.useMemo(()=>d?nT(d):[],[d]),p=L.useMemo(()=>d?iT(d):{mode:"responses",xLabel:"response",prefillLabel:"",generationLabel:"",points:[]},[d]),m=L.useCallback(w=>{l(C=>({...C,[w]:!C[w]}))},[]),x=L.useCallback(()=>{if(!d)return;const w=oT(d);navigator.clipboard.writeText(JSON.stringify(w,null,2)).catch(C=>console.error("Failed to copy:",C))},[d]),y=L.useCallback(async()=>{if(s.current)try{const w=(await X(async()=>{const{default:S}=await import("./html2canvas.esm-QH1iLAAe.js");return{default:S}},[])).default,C=await w(s.current,{backgroundColor:"#1a1a1a",scale:2}),v=document.createElement("a");v.download=`openfox-stats-${new Date().toISOString().slice(0,10)}.png`,v.href=C.toDataURL("image/png"),v.click()}catch(w){console.error("Failed to export PNG:",w),x()}},[x]);return o.jsx(Dt,{isOpen:e,onClose:t,title:"Session Stats",size:"lg",children:o.jsxs("div",{ref:s,className:"space-y-6",children:[o.jsx("section",{children:o.jsx("div",{className:"flex flex-wrap gap-2",children:n.modelGroups.map(w=>o.jsx("button",{onClick:()=>c(w.key),className:`px-3 py-1.5 rounded border text-xs transition-colors ${w.key===(d==null?void 0:d.key)?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-primary hover:bg-bg-tertiary/40"}`,title:w.label,children:w.label},w.key))})}),d&&o.jsxs("section",{children:[o.jsx("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:"Summary"}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[o.jsx(ns,{label:"AI Time",value:Vf(d.aiTime)}),o.jsx(ns,{label:"Total Time",value:Vf(d.totalTime)}),o.jsx(ns,{label:"Tool Time",value:Vf(d.toolTime)}),o.jsx(ns,{label:"Responses",value:d.responseCount.toString()}),o.jsx(ns,{label:"LLM Calls",value:d.llmCallCount.toString()})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-3",children:[o.jsx(ns,{label:"Prefill Tokens",value:Ni(d.prefillTokens),subValue:`@ ${rl(d.avgPrefillSpeed)} tok/s`}),o.jsx(ns,{label:"Gen Tokens",value:Ni(d.generationTokens),subValue:`@ ${rl(d.avgGenerationSpeed)} tok/s`}),o.jsx(ns,{label:"Avg PP Speed",value:`${rl(d.avgPrefillSpeed)}`,subValue:"tok/s"}),o.jsx(ns,{label:"Avg TG Speed",value:`${rl(d.avgGenerationSpeed)}`,subValue:"tok/s"})]})]}),d&&p.points.length>1&&o.jsxs("section",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("h3",{className:"text-sm font-semibold text-text-secondary uppercase tracking-wide",children:"Performance Progression"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:x,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Copy JSON"}),o.jsx("button",{onClick:y,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Save PNG"})]})]}),o.jsx("div",{className:"bg-bg-tertiary/50 rounded p-4",children:o.jsx(tT,{data:p.points,width:50,prefillLabel:p.prefillLabel,generationLabel:p.generationLabel,xLabel:p.xLabel})})]}),d&&o.jsxs("section",{children:[o.jsxs("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:["Response Log (",d.responseCount," responses)"]}),o.jsx("div",{className:"overflow-y-auto bg-bg-tertiary/30 rounded",children:o.jsxs("table",{className:"w-full table-fixed border-separate border-spacing-0 text-xs",children:[o.jsxs("colgroup",{children:[o.jsx("col",{className:"w-[7%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[10%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[11%]"}),o.jsx("col",{className:"w-[2%]"})]}),o.jsx("thead",{children:o.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-text-muted/80",children:[o.jsx("th",{className:"px-3 py-2 text-center font-medium",children:"#"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"At"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Time"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Context"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"PP t/s"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"TG t/s"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Calls"}),o.jsx("th",{className:"px-2 py-2"})]})}),o.jsx("tbody",{children:f.map((w,C)=>o.jsxs(L.Fragment,{children:[o.jsx(cT,{row:w,index:C,isExpanded:a[w.messageId]??!1,onToggle:w.isExpandable?()=>m(w.messageId):void 0}),(a[w.messageId]??!1)&&w.calls.map((v,S)=>o.jsx(uT,{dataPoint:v,index:S},`${v.messageId}-${v.callIndex}`))]},w.messageId))})]})})]})]})})}function ns({label:e,value:t,subValue:n}){return o.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[o.jsx("div",{className:"text-text-muted text-xs mb-1",children:e}),o.jsx("div",{className:"text-text-primary text-lg font-semibold",children:t}),n&&o.jsx("div",{className:"text-text-muted text-xs",children:n})]})}function cT({row:e,index:t,isExpanded:n,onToggle:s}){const a=e.calls.length>0?aT(e.calls.map(l=>l.promptTokens)):`${Ni(e.prefillTokens)} ctx`;return o.jsxs("tr",{onClick:s,className:`${t%2===0?"bg-bg-tertiary/20":""} ${s?"cursor-pointer hover:bg-bg-tertiary/35 transition-colors":""}`,children:[o.jsx("td",{className:"px-3 py-2 text-center text-text-muted align-middle",children:e.responseIndex}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:QS(e.timestamp)}),o.jsxs("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:[e.totalTime.toFixed(1),"s"]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:a.replace(/ ctx$/,"")}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.prefillSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.generationSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callCount}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:e.isExpandable?n?"v":">":""})]})}function uT({dataPoint:e,index:t}){const n=e.temperature!==void 0||e.topP!==void 0||e.topK!==void 0||e.maxTokens!==void 0;return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{className:`${t%2===0?"bg-bg-tertiary/10":"bg-bg-tertiary/5"}`,children:[o.jsxs("td",{className:"px-3 py-2 pl-6 text-center text-text-muted align-middle border-l border-border/60",children:["c",e.callIndex]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:QS(e.timestamp)}),o.jsxs("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:[e.totalTime.toFixed(1),"s"]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Ni(e.promptTokens)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.prefillSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:vu(e.generationSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callIndex}),o.jsx("td",{className:"px-2 py-2"})]}),n&&o.jsx("tr",{className:`${t%2===0?"bg-bg-tertiary/5":"bg-bg-tertiary/[2.5%]"}`,children:o.jsx("td",{colSpan:8,className:"px-6 py-1.5 border-l border-border/60",children:o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-text-muted",children:[e.temperature!==void 0&&o.jsxs("span",{children:["temp: ",e.temperature.toFixed(2)]}),e.topP!==void 0&&o.jsxs("span",{children:["topP: ",e.topP.toFixed(2)]}),e.topK!==void 0&&o.jsxs("span",{children:["topK: ",e.topK]}),e.maxTokens!==void 0&&o.jsxs("span",{children:["maxTok: ",e.maxTokens]})]})})})]})}const dT={passed:{icon:"✓",color:"text-accent-success"},completed:{icon:"◉",color:"text-purple-400"},failed:{icon:"✗",color:"text-accent-error"},resolved:{icon:"✓",color:"text-accent-success"},dismissed:{icon:"–",color:"text-text-muted"},open:{icon:"○",color:"text-accent-warning"},pending:{icon:"○",color:"text-text-muted"},in_progress:{icon:"◌",color:"text-accent-warning"}},hT=["open","in_progress","pending","completed","resolved","dismissed","passed","failed"];function fT(e){return dT[e]??{icon:"○",color:"text-text-muted"}}function JS(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}const Xu=L.memo(function({status:t,className:n="text-xs leading-tight flex-shrink-0"}){const{icon:s,color:a}=fT(t);return o.jsx("span",{className:`${a} ${n}`,children:s})});function sb({entries:e,title:t}){const n=L.useMemo(()=>e.reduce((s,a)=>(s[a.status]=(s[a.status]??0)+1,s),{}),[e]);return o.jsxs("h3",{className:"text-sm font-semibold text-text-primary mb-2 flex items-center justify-between",children:[o.jsx("span",{children:t}),Object.keys(n).length>0&&o.jsx("span",{className:"font-normal text-xs flex items-center gap-1.5",children:hT.map(s=>{const a=n[s];return a?o.jsxs("span",{className:"flex items-center gap-0.5",children:[o.jsx(Xu,{status:s}),o.jsx("span",{children:a})]},s):null})})]})}const mT=L.memo(function({entries:t,title:n,onClearAll:s}){const[a,l]=L.useState(!1),u=L.useCallback(()=>{l(!1),s==null||s()},[s]);return t.length===0?null:o.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[n&&o.jsx("div",{className:"px-1.5 py-1 border-b border-border bg-secondary",children:o.jsx("span",{className:"text-xs font-medium text-text-muted",children:n})}),o.jsx("div",{className:"bg-primary",children:t.map((c,d)=>o.jsxs("div",{className:`flex items-start gap-1 px-1.5 py-1 ${d>0?"border-t border-border":""}`,children:[o.jsx(Xu,{status:c.status}),o.jsxs("div",{className:"flex-1 min-w-0 text-xs truncate",children:[o.jsxs("span",{className:"text-text-muted",children:["[",c.id,"]"]})," ",JS(c.description)]})]},c.id??d))}),s&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary flex items-center gap-2",children:o.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-error transition-colors ml-auto cursor-pointer",title:"Clear all",children:[o.jsx(Va,{className:"w-3 h-3"}),"Clear all"]})}),a&&o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[o.jsx("span",{className:"text-xs text-accent-error",children:"Clear all?"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:u,className:"text-xs text-accent-error hover:text-accent-error/70 transition-colors cursor-pointer",children:"Yes"}),o.jsx("button",{onClick:()=>l(!1),className:"text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:"No"})]})]})})]})]})}),pT="#6b7280";function dl(e,t){var n;return((n=e.find(s=>s.id===t))==null?void 0:n.color)??pT}const mt=Yn(e=>{const t=async()=>{await Cp("/api/agents",e,!0)};return{defaults:[],userItems:[],projectItems:[],loading:!1,fetchAgents:t,fetchAgent:async n=>{try{const s=await Ae(`/api/agents/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ae(`/api/agents/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createAgent:async(n,s)=>{const a=await Ws("POST","/api/agents",{...n,destination:s});return a.success&&await t(),a},updateAgent:async(n,s)=>{const a=await Ws("PUT",`/api/agents/${n}`,s);return a.success&&await t(),a},deleteAgent:async n=>{try{const s=await Ae(`/api/agents/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateAgent:async(n,s)=>Uu(`/api/agents/${n}/duplicate`,t,s)}}),Ct=Yn((e,t)=>({defaults:[],userItems:[],projectItems:[],activeWorkflowId:"default",loading:!1,templateVariables:[],fetchTemplateVariables:async()=>{try{const s=await(await Ae("/api/workflows/template-variables")).json();e({templateVariables:s.variables??[]})}catch{}},fetchWorkflows:async()=>{e({loading:!0});try{const s=await(await Ae("/api/workflows")).json();e({defaults:s.defaults??[],userItems:s.userItems??[],projectItems:s.projectItems??[],activeWorkflowId:s.activeWorkflowId??"default",loading:!1})}catch{e({loading:!1})}},fetchWorkflow:async n=>{try{const s=await Ae(`/api/workflows/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ae(`/api/workflows/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createWorkflow:async(n,s)=>{const a=await Ws("POST","/api/workflows",{...n,destination:s});return a.success&&await t().fetchWorkflows(),a},updateWorkflow:async(n,s)=>{const a=await Ws("PUT",`/api/workflows/${n}`,s);return a.success&&await t().fetchWorkflows(),a},deleteWorkflow:async n=>{try{const s=await Ae(`/api/workflows/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateWorkflow:async(n,s)=>Uu(`/api/workflows/${n}/duplicate`,()=>t().fetchWorkflows(),s)})),gT={pending:"completed",completed:"passed",passed:"failed",failed:"pending"};async function xT(e,t){await Ae(`/api/sessions/${e}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:t})})}function Kc({id:e,agents:t}){const n=dl(t,e),s=t.find(a=>a.id===e);return o.jsx("span",{className:"font-medium rounded px-1",style:{backgroundColor:`${n}20`,color:n},children:(s==null?void 0:s.name)??e})}function yT({id:e}){const t=Ct(u=>u.defaults),n=Ct(u=>u.userItems),a=L.useMemo(()=>[...t,...n],[t,n]).find(u=>u.id===e),l=(a==null?void 0:a.color)??"#3b82f6";return o.jsx("span",{className:"font-medium rounded px-1",style:{backgroundColor:`${l}20`,color:l},children:(a==null?void 0:a.name)??e})}function _T({entries:e,sessionId:t}){const[n,s]=L.useState(e),[a,l]=L.useState(!1),[u,c]=L.useState(null),[d,f]=L.useState(""),[p,m]=L.useState(""),[x,y]=L.useState(!1),[w,C]=L.useState(!1),v=mt(z=>z.defaults),S=mt(z=>z.userItems),b=mt(z=>z.projectItems),_=L.useMemo(()=>[...v,...S,...b],[v,S,b]),E=L.useRef(null),N=L.useRef(null);L.useEffect(()=>{s(e)},[e]),L.useEffect(()=>{var z;a&&((z=E.current)==null||z.focus())},[a]),L.useEffect(()=>{var z;u&&((z=N.current)==null||z.focus())},[u]);const T=L.useCallback(z=>{s(z),xT(t,z)},[t]),D=L.useCallback(()=>{var H;const z=d.trim();if(!z)return;const J=String(n.length),Z=[...n,{id:J,description:z,status:"pending"}];T(Z),f(""),(H=E.current)==null||H.focus()},[n,d,T]),A=L.useCallback(()=>{l(!1),f("")},[]),O=L.useCallback((z,J)=>{c(z),m(J)},[]),M=L.useCallback(()=>{if(!u)return;const z=p.trim(),J=n.map(Z=>Z.id===u?{...Z,description:z||Z.description}:Z);T(J),c(null)},[u,p,n,T]),G=L.useCallback(z=>{const J=n.map(Z=>Z.id===z?{...Z,status:gT[Z.status]??"pending"}:Z);T(J)},[n,T]),V=L.useCallback(z=>{T(n.filter(J=>J.id!==z))},[n,T]),R=L.useCallback(()=>{T([]),y(!1)},[T]),U=L.useCallback(z=>{z.key==="Enter"&&(z.preventDefault(),D()),z.key==="Escape"&&A()},[D,A]),W=L.useCallback(z=>{z.key==="Enter"&&M(),z.key==="Escape"&&c(null)},[M]);return o.jsxs("div",{className:"my-1 rounded border border-border bg-secondary overflow-hidden",children:[o.jsxs("div",{className:"bg-primary",children:[n.length===0&&!a&&o.jsxs("div",{className:"px-1.5 py-2 text-xs text-text-muted italic text-center",children:["No criteria yet."," ",o.jsx("button",{onClick:()=>C(!0),className:"text-accent-primary hover:underline not-italic cursor-pointer",children:"Learn more"})]}),n.map((z,J)=>{const Z=z.status,H=u===z.id;return o.jsxs("div",{className:`flex items-start gap-1 px-1.5 py-1 group ${J>0?"border-t border-border":""}`,children:[o.jsx("button",{onClick:()=>G(z.id),className:"text-xs leading-tight flex-shrink-0 cursor-pointer hover:opacity-70 transition-opacity",title:`Status: ${z.status} (click to cycle)`,children:o.jsx(Xu,{status:Z})}),o.jsx("div",{className:"flex-1 min-w-0",children:H?o.jsx("input",{ref:N,value:p,onChange:I=>m(I.target.value),onBlur:M,onKeyDown:W,className:"w-full bg-bg-tertiary text-text-primary text-xs px-1.5 py-0.5 rounded border border-border focus:outline-none focus:border-accent-primary"}):o.jsxs("button",{onClick:()=>O(z.id,z.description),className:"text-xs text-text-primary text-left hover:text-accent-primary transition-colors w-full truncate cursor-pointer",title:"Click to edit",children:["[",z.id,"] ",JS(z.description)]})}),o.jsx("button",{onClick:()=>V(z.id),className:"flex-shrink-0 opacity-0 group-hover:opacity-100 text-text-muted hover:text-accent-error transition-all ml-0.5 cursor-pointer flex items-center self-center",title:"Delete criterion",children:o.jsx(Sl,{className:"w-4 h-4"})})]},z.id)})]}),a&&o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"text-text-muted text-xs leading-tight flex-shrink-0",children:"○"}),o.jsx("input",{ref:E,value:d,onChange:z=>f(z.target.value),onKeyDown:U,placeholder:"New criterion...",className:"flex-1 bg-bg-tertiary text-text-primary text-xs px-1.5 py-0.5 rounded border border-border focus:outline-none focus:border-accent-primary placeholder-text-muted"})]})}),o.jsxs("div",{className:"px-1.5 py-1 border-t border-border bg-secondary flex items-center gap-2",children:[a?o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:D,className:"flex items-center gap-1 text-xs text-accent-primary hover:text-accent-primary/70 transition-colors cursor-pointer",title:"Add criterion",children:[o.jsx(qs,{className:"w-3 h-3"}),"Add"]}),o.jsx("button",{onClick:A,className:"flex items-center gap-1 text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",title:"Cancel",children:"Cancel"})]}):o.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-primary transition-colors cursor-pointer",title:"Add criterion",children:[o.jsx(qs,{className:"w-3 h-3"}),"Add"]}),n.length>0&&o.jsxs("button",{onClick:()=>y(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-error transition-colors ml-auto cursor-pointer",title:"Clear all criteria",children:[o.jsx(Va,{className:"w-3 h-3"}),"Clear all"]}),o.jsx("button",{onClick:()=>C(!0),className:"flex items-center gap-1 text-xs text-text-muted hover:text-accent-primary transition-colors cursor-pointer",title:"About criteria",children:o.jsx(wS,{className:"w-3 h-3"})})]}),x&&o.jsx("div",{className:"px-1.5 py-1 border-t border-border bg-secondary",children:o.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[o.jsx("span",{className:"text-xs text-accent-error",children:"Clear all criteria?"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:R,className:"text-xs text-accent-error hover:text-accent-error/70 transition-colors cursor-pointer",children:"Yes"}),o.jsx("button",{onClick:()=>y(!1),className:"text-xs text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:"No"})]})]})}),o.jsx(Dt,{isOpen:w,onClose:()=>C(!1),title:"About Acceptance Criteria",size:"md",children:o.jsxs("div",{className:"space-y-3 text-sm text-text-secondary",children:[o.jsx("p",{children:"Each criterion defines a specific requirement that needs to be met."}),o.jsxs("p",{children:["To use this feature, start in ",o.jsx(Kc,{id:"planner",agents:_})," mode and",o.jsxs("strong",{className:"text-text-primary",children:[" ","ask the agent to define acceptance criteria that matches your goal"]}),". Then launch the ",o.jsx(yT,{id:"default"})," builtin workflow to launch the automation part."]}),o.jsx("p",{children:"This workflow will automatically:"}),o.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[o.jsxs("li",{children:["Launch the ",o.jsx(Kc,{id:"builder",agents:_}),' agent, that will be forced to continue until it marks all criteria as "completed"']}),o.jsxs("li",{children:["Then launch the ",o.jsx(Kc,{id:"verifier",agents:_})," subagent, that will verify each criterion. If every criterion is fulfilled, then it goes to the next step, otherwise, it gives feedback to the main agent until 100% of the criteria are met."]}),o.jsxs("li",{children:["Launch a ",o.jsx(Kc,{id:"code_reviewer",agents:_})," subagent, that will analyze the code to provide actionable feedback to the main agent."]})]}),o.jsx("div",{className:"bg-bg-tertiary rounded p-3 space-y-1.5",children:o.jsx("p",{children:"This lets smaller models follow complex plans to completion and improves the chances that nothing from your plan is missed."})})]})})]})}function vT({isOpen:e,onClose:t}){const n=Rr(C=>C.config),s=Rr(C=>C.saveConfig),[a,l]=L.useState(""),[u,c]=L.useState(""),[d,f]=L.useState(!1),[p,m]=L.useState(!1),[x,y]=L.useState(!1);L.useEffect(()=>{e&&(l((n==null?void 0:n.command)??""),c((n==null?void 0:n.url)??""),f((n==null?void 0:n.hotReload)??!1),m((n==null?void 0:n.disableInspect)??!1))},[e,n]);const w=async()=>{!a.trim()||!u.trim()||(y(!0),await s({command:a.trim(),url:u.trim(),hotReload:d,disableInspect:p}),y(!1),t())};return o.jsx(Dt,{isOpen:e,onClose:t,title:"Dev Server Config",size:"sm",children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Command"}),o.jsx("input",{className:"input w-full",type:"text",value:a,onChange:C=>l(C.target.value),placeholder:"npm run dev"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Dev URL"}),o.jsx("input",{className:"input w-full",type:"text",value:u,onChange:C=>c(C.target.value),placeholder:"http://localhost:3000"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",id:"hotReload",checked:d,onChange:C=>f(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),o.jsx("label",{htmlFor:"hotReload",className:"text-xs text-text-secondary",children:"Hot Reload"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",id:"disableInspect",checked:p,onChange:C=>m(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),o.jsx("label",{htmlFor:"disableInspect",className:"text-xs text-text-secondary",children:"Disable inspect feedback"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o.jsx("button",{className:"btn btn-secondary",onClick:t,children:"Cancel"}),o.jsx("button",{className:"btn btn-primary",onClick:w,disabled:x||!a.trim()||!u.trim(),children:x?"Saving...":"Save"})]})]})})}const ib={30:"text-black",31:"text-red-400",32:"text-accent-success",33:"text-accent-warning",34:"text-blue-400",35:"text-purple-400",36:"text-cyan-400",37:"text-gray-300",90:"text-gray-500",91:"text-red-500",92:"text-green-500",93:"text-yellow-400",94:"text-blue-500",95:"text-pink-400",96:"text-cyan-500",97:"text-white"},bT={40:"bg-black",41:"bg-red-900",42:"bg-green-900",43:"bg-yellow-900",44:"bg-blue-900",45:"bg-purple-900",46:"bg-cyan-900",47:"bg-gray-700"},ab={1:"font-bold",2:"opacity-75",4:"underline",7:"bg-bg-secondary"},ST="text-text-primary";function wT(e){const t=[],n=new RegExp("\x1B\\[([0-9;]+)m","g");let s=0,a="text-text-primary",l;try{for(;(l=n.exec(e))!==null;){if(l.index>s){const f=e.slice(s,l.index);f&&t.push({text:f,className:a})}const u=l[1];if(!u)continue;const c=u.split(";").map(Number);if(c.length===0||c[0]===0){a="text-text-primary";continue}const d=[];for(const f of c)if(f>=30&&f<=37){const p=ib[f];p&&d.push(p)}else if(f>=40&&f<=47){const p=bT[f];p&&d.push(p)}else if(f>=90&&f<=97){const p=ib[f];p&&d.push(p)}else if(f in ab){const p=ab[f];p&&d.push(p)}else f===39?d.push(ST):f===49&&(a=a.split(" ").filter(p=>!p.startsWith("bg-")).join(" "));d.length>0&&(a=d.join(" ")),s=n.lastIndex}if(s<e.length){const u=e.slice(s);u&&t.push({text:u,className:a})}return t}catch(u){return console.warn("ANSI parsing failed, stripping codes:",u),[{text:CT(e),className:"text-text-primary"}]}}function CT(e){return e.replace(new RegExp("\x1B\\[([0-9;]+)m","g"),"")}function bu(e){const t=wT(e),n=[];return t.forEach((s,a)=>{const l=s.text.split(`
|
|
90
90
|
`);l.forEach((u,c)=>{n.push(Hs.createElement("span",{key:`${a}-${c}`,className:s.className,style:{display:"inline-block",whiteSpace:"pre-wrap"}},u)),c<l.length-1&&n.push(Hs.createElement("br",{key:`${a}-${c}-br`}))})}),n.length===1?n[0]:n}function ZS({logs:e,preRef:t,preClassName:n="text-sm font-mono"}){return o.jsx("pre",{ref:t,className:n,children:e.length===0?o.jsx("span",{className:"text-text-muted",children:"No output yet"}):e.map((s,a)=>o.jsx("span",{className:s.stream==="stderr"?"text-accent-warning":"",children:bu(s.content)},a))})}function Ap({isActive:e,onToggle:t,className:n,style:s}){return o.jsxs("button",{type:"button",onClick:()=>t(!e),className:n,style:s,children:[e?o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-success"}):o.jsx(Kn,{className:"w-3 h-3"}),e?"live":"scroll to bottom"]})}const Qu=(e,t)=>{const n=L.useRef(!0),s=L.useRef(null),[a,l]=L.useState(!0),u=()=>{const c=e.current;c&&(c.scrollTop=c.scrollHeight)};return L.useEffect(()=>{const c=e.current;if(!c)return;const d=y=>{if(y.deltaY>0){requestAnimationFrame(()=>requestAnimationFrame(()=>{c.scrollHeight-c.scrollTop-c.offsetHeight<100&&(n.current=!0,l(!0))}));return}n.current=!1,l(!1)},f=y=>{y.touches[0]&&(s.current=y.touches[0].clientY)},p=y=>{if(s.current===null)return;const w=y.touches[0];if(!w)return;if(w.clientY-s.current>0){n.current=!1,l(!1);return}requestAnimationFrame(()=>requestAnimationFrame(()=>{c.scrollHeight-c.scrollTop-c.offsetHeight<100&&(n.current=!0,l(!0))}))},m=new MutationObserver(()=>{n.current&&requestAnimationFrame(u)}),x=setInterval(()=>{n.current&&u()},1e3);return c.addEventListener("wheel",d,{passive:!0}),c.addEventListener("touchstart",f,{passive:!0}),c.addEventListener("touchmove",p,{passive:!0}),m.observe(c,{childList:!0,subtree:!0,characterData:!0}),()=>{c.removeEventListener("wheel",d),c.removeEventListener("touchstart",f),c.removeEventListener("touchmove",p),m.disconnect(),clearInterval(x)}},[t==null?void 0:t.id]),{force_scroll_to_bottom:()=>{n.current=!0,l(!0),u()},isAutoScrollActive:a,setAutoScroll:c=>{n.current=c,l(c),c&&u()}}},e1=L.memo(function({title:t,logs:n,onClose:s,preClassName:a}){const l=L.useRef(null),{isAutoScrollActive:u,setAutoScroll:c}=Qu(l,null);return o.jsx(Dt,{isOpen:!0,onClose:s,title:t,size:"full",headerRight:o.jsx(Ap,{isActive:u,onToggle:c,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),children:o.jsx("div",{ref:l,className:"h-full overflow-y-auto",children:o.jsx(ZS,{logs:n,preClassName:a})})})}),kT=L.memo(function({logs:t,anchorRef:n,isHiding:s,isAutoScrollActive:a,onSetAutoScroll:l}){const[u,c]=L.useState(null),d=L.useRef(null),f=L.useRef(l);return f.current=l,L.useEffect(()=>{var m;const p=(m=n.current)==null?void 0:m.getBoundingClientRect();p&&c({bottom:window.innerHeight-p.bottom,right:window.innerWidth-p.right,width:p.width,height:p.height})},[n]),L.useEffect(()=>{const p=d.current;if(!p)return;const m=x=>{if(x.deltaY<0){f.current(!1);return}x.deltaY>0&&requestAnimationFrame(()=>requestAnimationFrame(()=>{p.scrollHeight-p.scrollTop-p.offsetHeight<100&&f.current(!0)}))};return p.addEventListener("wheel",m,{passive:!0}),()=>p.removeEventListener("wheel",m)},[]),L.useEffect(()=>{d.current&&a&&(d.current.scrollTop=d.current.scrollHeight)},[t,a,u]),o.jsx("div",{className:`relative ${u?"":"hidden"}`,children:o.jsx("pre",{ref:d,className:"fixed z-40 text-sm font-mono text-text-primary bg-bg-primary p-2 rounded border border-border overflow-auto transition-all duration-150 ease-out select-text",style:u?{bottom:u.bottom,right:u.right,width:u.width*2,maxHeight:u.height*3,transformOrigin:"bottom right",transform:s?"scale(0.01)":"scale(1)",opacity:s?0:1}:void 0,children:t.map((p,m)=>o.jsx("span",{className:p.stream==="stderr"?"text-accent-warning":"",children:bu(p.content)},m))})})}),ET=L.memo(function({workdir:t}){const n=Rr(V=>V.setWorkdir),s=Rr(V=>V.status),a=Rr(V=>V.config),l=Rr(V=>V.logs),u=Rr(V=>V.start),c=Rr(V=>V.stop),d=Rr(V=>V.fetchLogs),[f,p]=L.useState(!1),[m,x]=L.useState(!1),[y,w]=L.useState(!1),[C,v]=L.useState(!1),S=L.useRef(null),{isAutoScrollActive:b,setAutoScroll:_}=Qu(S,null),E=L.useRef(null),N=L.useRef(null),T=L.useRef(null),D=()=>{const V=s==null?void 0:s.inspectProxyPort;if(!V){s!=null&&s.url&&window.open(s.url,"_blank");return}const R=`${window.location.protocol}//${window.location.hostname}:${V}`;window.open(R,"_blank")},A=(s==null?void 0:s.state)??"off",O=a!==null,M=A==="running"||A==="warning";L.useEffect(()=>{n(t??null)},[t,n]),L.useEffect(()=>{M&&d()},[M,d]);const G=()=>{M?c():u()};return o.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",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:`inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 ${A==="running"?"bg-accent-success":A==="warning"?"bg-accent-warning":A==="error"?"bg-accent-error":"bg-text-muted"}`}),o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Dev Server"})]}),o.jsx("button",{onClick:()=>p(!0),className:"p-1.5 rounded hover:bg-bg-tertiary transition-colors text-text-muted",title:"Configure dev server",children:o.jsx(Mj,{})})]}),O?o.jsx(o.Fragment,{children:A==="running"||A==="warning"?o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("button",{onClick:G,className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:[o.jsx(jS,{}),"Stop"]}),(s==null?void 0:s.url)&&o.jsxs("button",{onClick:()=>D(),className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",title:s.url,children:[o.jsx(Pj,{}),"Open"]})]}):o.jsx("button",{onClick:G,className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",children:"Start"})}):o.jsx("button",{onClick:()=>p(!0),className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-muted hover:bg-border transition-colors",children:"Configure"}),o.jsxs("div",{ref:T,className:`relative ${O&&M?"":"hidden"}`,onMouseEnter:()=>{!O||!M||(N.current&&clearTimeout(N.current),E.current=setTimeout(()=>{w(!0),v(!1)},500))},onMouseLeave:()=>{E.current&&clearTimeout(E.current),v(!0),N.current=setTimeout(()=>w(!1),150)},children:[o.jsx(ZS,{logs:l,preRef:S,preClassName:"text-sm bg-bg-primary p-2 rounded overflow-auto max-h-[200px] border border-border"}),O&&M&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"absolute bottom-1 right-1 z-50 flex items-center gap-1",children:[(y||C)&&o.jsx(Ap,{isActive:b,onToggle:_,className:"text-xs text-text-muted hover:text-text-primary flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),o.jsx("button",{onClick:()=>x(!0),className:"px-2 py-0.5 rounded text-xs font-medium bg-accent-primary/30 text-text-primary hover:bg-accent-primary/50 transition-colors",children:"Expand"})]}),(y||C)&&T.current&&Ga.createPortal(o.jsx(kT,{logs:l,anchorRef:T,isHiding:C,isAutoScrollActive:b,onSetAutoScroll:_}),document.body)]})]}),o.jsx(vT,{isOpen:f,onClose:()=>p(!1)}),m&&o.jsx(e1,{title:"Dev Server Logs",logs:l,onClose:()=>x(!1)})]})}),jT=L.memo(function({sessionId:t}){var y;const n=il(w=>w.processes),s=il(w=>w.stopProcess),[a,l]=L.useState(null),[u,c]=L.useState([]),d=n.filter(w=>w.status!=="exited"),f=d.filter(w=>w.status==="running").length;if(n.length===0)return null;const p=w=>{switch(w){case"running":return"bg-accent-success";case"starting":return"bg-accent-warning";case"stopping":return"bg-accent-warning";case"exited":return"bg-text-muted";default:return"bg-text-muted"}},m=w=>{const C=il.getState().logs[w]??[];c(C.map(v=>({content:v.content,stream:v.stream}))),l(w)},x=w=>{t&&s(w,t)};return o.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 bg-accent-primary"}),o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Background"}),o.jsxs("span",{className:"text-xs text-text-muted",children:["(",f," running)"]})]})}),o.jsx("div",{className:"space-y-2",children:d.map(w=>o.jsx("div",{className:"border border-border rounded p-2",children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${p(w.status)}`}),o.jsx("span",{className:"text-sm text-text-primary truncate",title:w.name,children:w.name}),o.jsxs("span",{className:"text-xs text-text-muted",children:["[",w.status,"]"]})]}),o.jsxs("div",{className:"flex gap-1 ml-2",children:[o.jsx("button",{onClick:()=>m(w.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-border text-text-secondary transition-colors",title:"View logs",children:"Logs"}),o.jsx("button",{onClick:()=>x(w.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-accent-error/20 text-text-secondary hover:text-accent-error transition-colors",title:"Stop process",children:"Stop"})]})]})},w.id))}),a&&o.jsx(e1,{title:((y=d.find(w=>w.id===a))==null?void 0:y.name)??"",logs:u,onClose:()=>{l(null),c([])}})]})});function NT({isOpen:e,onClose:t,versionInfo:n}){const[s,a]=L.useState("ready"),[l,u]=L.useState(""),[c,d]=L.useState(n),[f,p]=L.useState(null),[m,x]=L.useState(null);L.useEffect(()=>{if(e){if(n){d(n);return}fetch("/api/auto-update/check").then(v=>v.json()).then(v=>{d({current:v.current,latest:v.latest})}).catch(()=>{})}},[e]),L.useEffect(()=>{if(!e||s!=="updating"&&s!=="restarting")return;const v=setInterval(()=>{u(S=>S.length>=3?"":S+".")},400);return()=>clearInterval(v)},[e,s]);const y=L.useCallback(async()=>{a("updating"),x(null);try{const S=await(await Ae("/api/auto-update",{method:"POST"})).json();if(S.success){const b=S.version??"unknown";p(b),localStorage.setItem("openfox_updated_to",b),localStorage.setItem("update_pending","true"),S.isService?(a("restarting"),await Ae("/api/auto-update/restart",{method:"POST"}).catch(()=>{}),setTimeout(()=>window.location.reload(),5e3)):a("complete")}else x(S.error??"Update failed"),a("failed")}catch(v){x(v instanceof Error?v.message:"Update request failed"),a("failed")}},[]);L.useEffect(()=>{e&&(a("ready"),u(""),p(null),x(null))},[e]);const w=s!=="updating"&&s!=="restarting",C=s==="failed"?"Update Failed":s==="complete"||s==="restarting"?"Update Complete":"New OpenFox Version Available";return o.jsxs(Dt,{isOpen:e,onClose:w?t:void 0,title:C,size:"sm",closeOnBackdropClick:w,showCloseButton:w,children:[o.jsxs("div",{className:"flex flex-col gap-4",children:[c&&o.jsxs("div",{className:"flex justify-between text-sm",children:[o.jsx("span",{className:"text-text-muted",children:"Current version"}),o.jsx("span",{className:"text-text-primary font-mono",children:c.current})]}),c&&o.jsxs("div",{className:"flex justify-between text-sm pb-2",children:[o.jsx("span",{className:"text-text-muted",children:"Latest version"}),o.jsx("span",{className:"text-accent-primary font-mono font-semibold",children:c.latest})]}),(s==="updating"||s==="restarting")&&o.jsxs("div",{className:"flex flex-col gap-2 mt-2",children:[o.jsx("div",{className:"h-1.5 bg-bg-tertiary rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent-primary animate-pulse w-full"})}),o.jsxs("p",{className:"text-xs text-text-muted text-center",children:[s==="restarting"?"Restarting":"Updating",l]})]}),s==="complete"&&o.jsx("div",{className:"flex flex-col gap-3 mt-2",children:o.jsxs("div",{className:"bg-bg-tertiary rounded px-3 py-2 text-xs text-text-secondary",children:["OpenFox has been updated to v",f??(c==null?void 0:c.latest),"."," Please restart OpenFox to use the new version."]})}),s==="failed"&&o.jsxs("div",{className:"flex flex-col gap-3 mt-2",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-accent-danger/10 border border-accent-danger/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:m})]}),o.jsx("div",{className:"bg-bg-tertiary rounded px-3 py-2 text-xs font-mono text-text-secondary",children:"openfox update"}),o.jsx("p",{className:"text-xs text-text-muted",children:"Run this command in your terminal to complete the update."})]})]}),s==="ready"&&o.jsx("button",{onClick:y,className:"w-full px-3 py-2 text-sm rounded bg-accent-primary hover:brightness-110 transition-all text-white font-medium",children:"Update OpenFox"}),(s==="complete"||s==="failed")&&o.jsx("button",{onClick:t,className:"w-full px-3 py-2 text-sm rounded bg-bg-tertiary hover:bg-bg-secondary transition-colors text-text-primary font-medium mt-2",children:"Close"})]})}function TT({file:e}){const t=KS(e.path,28),n=e.status==="added"?"text-accent-success":e.status==="deleted"?"text-accent-error":"text-accent-primary",s=e.status==="added"?`+${e.additions}`:e.status==="deleted"?`-${e.deletions}`:e.additions>0||e.deletions>0?`+${e.additions}, -${e.deletions}`:"";return o.jsxs("div",{className:"flex items-center justify-between gap-1 py-0.5 text-xs min-w-0",children:[o.jsx("span",{className:`truncate ${n}`,title:e.path,children:t}),s&&o.jsx("span",{className:`shrink-0 font-mono${e.status==="added"?" text-accent-success":e.status==="deleted"?" text-accent-error":" text-text-muted"}`,children:s})]})}function AT(){const{diff:e}=XS();return e.loading?o.jsx("div",{className:"mt-3",children:o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-muted",children:[o.jsx("span",{className:"w-3 h-3 border border-border border-t-accent-primary rounded-full animate-spin"}),o.jsx("span",{children:"Checking changes..."})]})}):e.files.length===0?o.jsx("div",{className:"mt-3",children:o.jsx("p",{className:"text-xs text-text-muted text-center",children:"No changes"})}):o.jsx("div",{className:"mt-3 max-h-[150px] overflow-y-auto",children:o.jsx("div",{className:"pr-1",children:e.files.map((t,n)=>o.jsx(TT,{file:t},n))})})}function ob({messages:e,workdir:t}){var C,v,S,b;const[n,s]=L.useState(!1),[a,l]=L.useState(!1),[u,c]=L.useState(!1),[d,f]=L.useState(!1),p=XN(e),{branch:m}=XS(),x=nn(_=>_.version),y=Re(_=>_.currentSession),w=L.useCallback(async()=>{l(!0);try{const _=await fetch("/api/auto-update/check");if(_.ok){const E=await _.json();c(E.isUpdateAvailable)}}catch{}finally{l(!1)}},[]);return L.useEffect(()=>{w()},[w]),o.jsxs("div",{className:"flex flex-col h-full",children:[p&&o.jsxs("div",{className:"mb-4",children:[o.jsx("button",{onClick:()=>s(!0),className:"w-full flex items-center justify-center px-3 py-2 rounded bg-bg-tertiary hover:bg-bg-secondary transition-colors",title:"View detailed response and call-level stats",children:o.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[o.jsx("span",{className:"text-text-secondary",children:QN(p.aiTime)}),o.jsx("span",{className:"w-px h-3 bg-border"}),o.jsx("span",{className:"text-text-secondary",children:eb(p.avgPrefillSpeed)}),o.jsx("span",{children:"pp"}),o.jsx("span",{className:"w-px h-3 bg-border"}),o.jsx("span",{className:"text-text-secondary",children:eb(p.avgGenerationSpeed)}),o.jsx("span",{children:"tg"})]})}),o.jsx(lT,{isOpen:n,onClose:()=>s(!1),stats:p})]}),o.jsx("div",{className:"flex flex-col flex-1 overflow-y-auto",children:o.jsxs("div",{className:"mt-4",children:[o.jsx(sb,{entries:((C=y==null?void 0:y.metadataEntries)==null?void 0:C.criteria)??[],title:"Acceptance Criteria"}),y&&o.jsx(_T,{entries:((v=y==null?void 0:y.metadataEntries)==null?void 0:v.criteria)??[],sessionId:y.id}),y&&(((b=(S=y.metadataEntries)==null?void 0:S.review_findings)==null?void 0:b.length)??0)>0&&o.jsxs("div",{className:"mt-6",children:[o.jsx(sb,{entries:y.metadataEntries.review_findings,title:"Review Findings"}),o.jsx(mT,{entries:y.metadataEntries.review_findings,onClearAll:async()=>{try{await Ae(`/api/sessions/${y.id}/review-findings`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({review_findings:[]})})}catch(_){console.error("Failed to clear review findings:",_)}}})]})]})}),m&&o.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm",children:[o.jsx(Aj,{}),o.jsx("span",{className:"truncate text-text-secondary",title:m,children:m})]}),o.jsx(AT,{}),o.jsx(ET,{workdir:t}),o.jsx(jT,{sessionId:y==null?void 0:y.id}),x&&o.jsxs("div",{className:"mt-4 pt-4 border-t border-border text-center text-xs text-text-muted",children:[o.jsxs("div",{className:"flex items-center justify-center gap-1",children:[o.jsx("a",{href:"https://github.com/co-l/openfox",target:"_blank",rel:"noopener noreferrer",className:"hover:text-accent-primary transition-colors",children:"OpenFox"})," - ",o.jsxs("span",{className:"font-mono",children:["v",x]}),o.jsx("button",{onClick:()=>w(),disabled:a,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors disabled:opacity-50",title:"Check for updates",children:o.jsx(vp,{className:`w-3 h-3 ${a?"animate-spin":""}`})})]}),u&&o.jsx("button",{onClick:()=>f(!0),className:"text-accent-primary hover:underline mt-1",children:"Update OpenFox →"})]}),o.jsx(NT,{isOpen:d,onClose:()=>f(!1),versionInfo:null})]})}function LT({children:e,criteriaSidebarOpen:t=!0,onCriteriaSidebarToggle:n,messages:s}){const a=Re(l=>l.currentSession);return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[t&&o.jsx("div",{className:"fixed md:hidden inset-0 bg-secondary/50 z-40",onClick:n}),o.jsxs("div",{className:"flex h-full",children:[o.jsx("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden bg-secondary",children:e}),t?o.jsx("aside",{className:"hidden md:block w-[320px] shrink-0 border-l border-border p-4 overflow-y-auto bg-secondary",children:o.jsx(ob,{messages:s,workdir:a==null?void 0:a.workdir})}):o.jsx("aside",{className:"hidden md:block w-0 shrink-0 overflow-hidden border-l-0"}),o.jsx("aside",{className:`
|
|
91
91
|
md:hidden
|
|
92
92
|
p-4 overflow-y-auto bg-secondary
|
|
@@ -294,7 +294,7 @@ XID_Start XIDS`.split(/\s/).map(e=>[fd(e),e])),OP=new Map([["s",sn(383)],[sn(383
|
|
|
294
294
|
`,children:n?"Reconnecting...":"Reconnect"})]})}const en=Yn((e,t)=>({defaults:[],userItems:[],projectItems:[],loading:!1,fetchCommands:async()=>{await Cp("/api/commands",e,!0)},fetchCommand:async n=>{try{const s=await Ae(`/api/commands/${n}`);return s.ok?await s.json():null}catch{return null}},fetchDefaultContent:async n=>{try{const s=await Ae(`/api/commands/defaults/${n}`);return s.ok?await s.json():null}catch{return null}},createCommand:async(n,s)=>{const a=await Ws("POST","/api/commands",{...n,destination:s});return a.success&&await t().fetchCommands(),a},updateCommand:async(n,s)=>{const a=await Ws("PUT",`/api/commands/${n}`,s);return a.success&&await t().fetchCommands(),a},deleteCommand:async n=>{try{const s=await Ae(`/api/commands/${n}`,{method:"DELETE"}),a=await s.json();return s.ok?(e(l=>({userItems:l.userItems.filter(u=>u.id!==n)})),{success:!0}):{success:!1,error:a.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateCommand:async(n,s)=>Uu(`/api/commands/${n}/duplicate`,()=>t().fetchCommands(),s)}));function yB(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function _B({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(xu,{})})}function BC({isOpen:e,onClose:t,initialEditId:n}){const s=en(ne=>ne.defaults),a=en(ne=>ne.userItems),l=en(ne=>ne.projectItems),u=en(ne=>ne.loading),c=en(ne=>ne.fetchCommands),d=en(ne=>ne.fetchCommand),f=en(ne=>ne.fetchDefaultContent),p=en(ne=>ne.createCommand),m=en(ne=>ne.updateCommand),x=en(ne=>ne.deleteCommand),[y,w]=L.useState(null),[C,v]=L.useState(null),{view:S,editingId:b,formError:_,saving:E,formData:N,setView:T,setEditingId:D,setFormError:A,setFormData:O,setSaving:M}=PS(),{requestDelete:G,clearConfirm:V,isConfirming:R}=Gu(),U=L.useRef(!1),W=mt(ne=>ne.defaults),z=mt(ne=>ne.userItems),J=mt(ne=>ne.fetchAgents),H=[...W,...z].filter(ne=>!ne.subagent),I=L.useRef(c),$=L.useRef(J),q=L.useRef(d),B=L.useRef(f),ee=L.useRef(n),Q=L.useRef(T),te=L.useRef(D),Y=L.useRef(A),F=L.useRef(V);L.useEffect(()=>{I.current=c,$.current=J,q.current=d,B.current=f,ee.current=n,Q.current=T,te.current=D,Y.current=A,F.current=V}),L.useEffect(()=>{if(e)if(I.current(),$.current(),U.current||(F.current(),U.current=!0),ee.current){const ne=s.some(xe=>xe.id===ee.current);Q.current("edit"),te.current(ee.current),Y.current(""),ne?B.current(ee.current).then(xe=>{xe&&O({name:xe.metadata.name+" (copy)",id:`${ee.current}-copy-${Date.now()}`,prompt:xe.prompt,agentMode:xe.metadata.agentMode??"",isDefault:!0,destination:"user"})}):q.current(ee.current).then(xe=>{xe&&O({name:xe.metadata.name,id:xe.metadata.id,prompt:xe.prompt,agentMode:xe.metadata.agentMode??"",isDefault:!1,destination:"user"})})}else Q.current("list"),te.current(null);else U.current=!1},[e]);const ue=async ne=>{w(ne);const xe=await f(ne);v((xe==null?void 0:xe.prompt)??null)},oe=async ne=>{if(s.some(He=>He.id===ne)){const He=await f(ne);He&&(D(null),O({name:`${He.metadata.name} (copy)`,id:`${ne}-copy-${Date.now()}`,prompt:He.prompt,agentMode:He.metadata.agentMode??"",isDefault:!0,destination:"user"}),A(""),T("edit"))}else{const He=await d(ne);He&&(D(null),O({name:`${He.metadata.name} (copy)`,id:`${ne}-copy-${Date.now()}`,prompt:He.prompt,agentMode:He.metadata.agentMode??"",isDefault:!1,destination:"user"}),A(""),T("edit"))}},ke=()=>{O({name:"",id:"",prompt:"",agentMode:"",isDefault:!1,destination:"user"}),D(null),T("edit")},Se=async ne=>{const xe=await d(ne);xe&&(D(ne),O({name:xe.metadata.name,id:xe.metadata.id,prompt:xe.prompt,agentMode:xe.metadata.agentMode??"",isDefault:!1,destination:"user"}),A(""),T("edit"))},Te=async ne=>{await x(ne),V()},fe=async()=>{const ne=b??N.id;if(!ne||!N.name||!N.prompt){A("Name and message are required.");return}M(!0),A("");const xe={metadata:{id:ne,name:N.name,...N.agentMode?{agentMode:N.agentMode}:{}},prompt:N.prompt},He=b?await m(b,xe):await p(xe,N.destination);if(M(!1),!He.success){A(He.error??"Failed to save command.");return}n?t():T("list")},ae=()=>{n?t():(T("list"),w(null),v(null))},ce=ne=>{O(xe=>({...xe,name:ne})),(!b||N.isDefault)&&O(xe=>({...xe,id:yB(ne)}))},se=()=>{w(null),v(null),T("list")},je=()=>{y&&(w(null),T("edit"),D(y),f(y).then(ne=>{ne&&O({name:`${ne.metadata.name} (copy)`,id:`${y}-copy-${Date.now()}`,prompt:ne.prompt,agentMode:ne.metadata.agentMode??"",isDefault:!0,destination:"user"})}))};if(y){const ne=s.find(xe=>xe.id===y);return o.jsx(Dt,{isOpen:e,onClose:se,title:`Default: ${(ne==null?void 0:ne.name)??y}`,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:y})]}),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:ne==null?void 0:ne.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:(ne==null?void 0:ne.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:C??"",readOnly:!0,placeholder:"...",className:"flex-1 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none opacity-60"})]}),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:se,children:"Close"}),o.jsx(nt,{variant:"primary",onClick:je,children:"Duplicate & Customize"})]})]})})}if(S==="edit")return o.jsx(Dt,{isOpen:e,onClose:ae,title:b?"Edit Command":"New Command",size:"xl",children:o.jsxs("div",{className:"flex flex-col h-full",children:[_&&o.jsx(Wu,{message:_}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(IS,{name:N.name,id:N.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Command",idPlaceholder:"my-command",readOnlyId:!!b&&!N.isDefault,onNameChange:ce,onIdChange:ne=>O(xe=>({...xe,id:ne}))}),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:N.agentMode,onChange:ne=>O(xe=>({...xe,agentMode:ne.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)"}),H.map(ne=>o.jsx("option",{value:ne.id,children:ne.name},ne.id))]})]}),!b&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Save to:"}),o.jsxs("select",{value:N.destination,onChange:ne=>O(xe=>({...xe,destination:ne.target.value})),className:"px-2 py-1 bg-bg-tertiary border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary",children:[o.jsx("option",{value:"user",children:"Global config"}),o.jsx("option",{value:"project",children:"Project (.openfox/)"})]})]})]}),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:N.prompt,onChange:ne=>O(xe=>({...xe,prompt:ne.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:ae,children:"Cancel"}),o.jsx(nt,{variant:"primary",onClick:fe,disabled:E||!N.name||!N.prompt,children:E?"Saving...":"Save"})]})]})});const _e=ne=>ne.map(xe=>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:xe.name})})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(Fs,{onClick:()=>Se(xe.id)}),o.jsx(yu,{onClick:()=>oe(xe.id)}),R(xe.id,"delete")?o.jsx(kp,{onConfirm:()=>Te(xe.id),onCancel:V}):o.jsx(Ep,{onClick:()=>G(xe.id)})]})]},xe.id));return o.jsxs(Dt,{isOpen:e,onClose:t,title:"Commands",size:"lg",children:[o.jsx(jp,{description:"Commands are pre-defined messages you can send with a single click.",onNew:ke}),o.jsxs(Np,{loading:u,hasItems:s.length>0||a.length>0||l.length>0,loadingLabel:"Loading commands...",emptyLabel:"No commands created yet.",children:[s.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:s.map(ne=>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:ne.name})}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[o.jsx(_B,{onClick:()=>ue(ne.id)}),o.jsx(yu,{onClick:()=>oe(ne.id)})]})]},ne.id))})]}),a.length>0&&o.jsx(OS,{children:_e(a)}),l.length>0&&o.jsxs("div",{className:"mt-4",children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Project"}),o.jsx("div",{className:"space-y-2",children:_e(l)})]})]})]})}const xi=150,is=54,cu=80,xr=30,Na=70,q0=100,yi=50,uu=50,K0=4,zC={step_result:"Result",metadata_all_match:"Metadata match",metadata_all_in:"Metadata in",always:"otherwise"},$C=[{value:"step_result",label:"Step result is..."},{value:"metadata_all_match",label:"Metadata all match (key=value)"},{value:"metadata_all_in",label:"Metadata all in list"},{value:"always",label:"Always (fallback)"}],vB=[{value:"agent",label:"Agent"},{value:"sub_agent",label:"Sub-Agent"},{value:"shell",label:"Shell"}];function pg(e,t){if(e.type==="agent"){const n=t.find(s=>s.id===e.agentId);return{name:(n==null?void 0:n.name)??(e.agentId||"Agent"),color:(n==null?void 0:n.color)||"#3b82f6"}}if(e.type==="sub_agent"){const n=t.find(s=>s.id===e.subAgentType);return{name:(n==null?void 0:n.name)??(e.subAgentType||"Sub-Agent"),color:(n==null?void 0:n.color)||"#a855f7"}}return{name:"Shell",color:"#22c55e"}}function bB(e,t,n,s){const a=uu+yi+xi+q0+xi+yi+uu,l=a/2,u=uu+yi+xi/2,c=uu+yi+xi+q0+xi/2,d=[],f=[],p=new Map,m=e.filter(W=>W.type==="agent"||W.type==="shell"),x=e.filter(W=>W.type==="sub_agent"),y=x.length>0,w=y?u:l,C=m.length>0?c:l,v=yi+xr/2;d.push({id:"$start",type:"terminal",label:"Start",cx:w,cy:v,w:cu,h:xr}),p.set("$start",{cx:w,cy:v,w:cu,h:xr});const S=W=>{d.push({id:"$done",type:"terminal",label:"Done",cx:w,cy:W,w:cu,h:xr}),p.set("$done",{cx:w,cy:W,w:cu,h:xr})};if(e.length===0){const W=v+xr/2+Na*2+xr/2;return S(W),{nodes:d,edges:f,width:a,height:W+xr/2+yi,posMap:p}}const b=v+xr/2+Na,_=(W,z)=>{W.forEach((J,Z)=>{const H=b+Z*(is+Na)+is/2,{name:I,color:$}=pg(J,s);d.push({id:J.id,type:"step",label:I,color:$,cx:z,cy:H,w:xi,h:is}),p.set(J.id,{cx:z,cy:H,w:xi,h:is})})};_(m,w),_(x,C);const E=m.length>0?b+(m.length-1)*(is+Na)+is/2:v,N=y?b+(x.length-1)*(is+Na)+is/2:v,T=Math.max(E,N)+is/2+Na+xr/2;S(T);const D=[];t&&p.has(t)&&D.push({from:"$start",to:t,label:n,edgeKey:"start",direction:"down",backEdgeIndex:0});let A=0;for(const W of e)W.transitions.forEach((z,J)=>{var B;if(!z.goto||!p.has(z.goto))return;const Z=p.get(W.id),H=p.get(z.goto),I=z.when.type==="step_result"?`${z.when.result}`:z.when.type==="metadata_all_match"?`${z.when.key??"?"}=${z.when.value??"?"}`:z.when.type==="metadata_all_in"?`${z.when.key??"?"} in [${((B=z.when.values)==null?void 0:B.join(","))??"?"}]`:zC[z.when.type]??z.when.type,$=W.id===z.goto;let q;$?q="back":H.cy>Z.cy+1?q="down":H.cy<Z.cy-1?q="back":q="same",D.push({from:W.id,to:z.goto,label:I,edgeKey:`${W.id}:${J}`,direction:q,backEdgeIndex:q==="back"?A++:0})});const O=new Map,M=new Map,G=new Map,V=new Map;for(const W of D)W.direction==="down"&&(O.set(W.from,(O.get(W.from)??0)+1),M.set(W.to,(M.get(W.to)??0)+1));const R=new Map,U=new Map;for(const W of D){if(W.direction!=="same")continue;const z=[W.from,W.to].sort().join("|");R.set(z,(R.get(z)??0)+1)}for(const W of D){if(W.direction==="back"||W.direction==="same"){let q=0;if(W.direction==="same"){const B=[W.from,W.to].sort().join("|");q=U.get(B)??0,U.set(B,q+1)}f.push({...W,fromPort:0,toPort:0,sameEdgeIndex:q});continue}const z=O.get(W.from)??1,J=M.get(W.to)??1,Z=G.get(W.from)??0,H=V.get(W.to)??0;G.set(W.from,Z+1),V.set(W.to,H+1);const I=z===1?0:-.6+1.2*Z/(z-1),$=J===1?0:-.6+1.2*H/(J-1);f.push({...W,fromPort:I,toPort:$,sameEdgeIndex:0})}return{nodes:d,edges:f,width:a,height:T+xr/2+yi,posMap:p}}function SB({steps:e,entryStep:t,selectedNodeId:n,selectedEdgeKey:s,startConditionLabel:a,agentTypes:l,isReadOnly:u,onSelectNode:c,onSelectEdge:d,onRemoveStep:f,onCreateTransition:p,onReconnectTo:m,onReconnectFrom:x,onDeleteTransition:y}){const w=L.useRef(null),C=L.useRef(!1),[v,S]=L.useState(null),[b,_]=L.useState(null),[E,N]=L.useState(null),{nodes:T,edges:D,width:A,height:O,posMap:M}=L.useMemo(()=>bB(e,t,a,l),[e,t,a,l]),G=L.useCallback(Q=>{var oe;const te=w.current;if(!te)return{x:0,y:0};const Y=te.createSVGPoint();Y.x=Q.clientX,Y.y=Q.clientY;const F=(oe=te.getScreenCTM())==null?void 0:oe.inverse();if(!F)return{x:0,y:0};const ue=Y.matrixTransform(F);return{x:ue.x,y:ue.y}},[]),V=L.useCallback(Q=>!Q||!b||Q==="$start"?!1:b.type==="reconnect-from"?Q!=="$done":!0,[b]),R=L.useCallback((Q,te)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const Y=G(Q);_({type:"new",fromNodeId:te,mouseX:Y.x,mouseY:Y.y})},[G,u]),U=L.useCallback((Q,te)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const Y=G(Q);_({type:"reconnect-to",fromNodeId:te.from,edgeKey:te.edgeKey,mouseX:Y.x,mouseY:Y.y})},[G,u]),W=L.useCallback((Q,te)=>{if(u)return;Q.stopPropagation(),Q.preventDefault();const Y=G(Q);_({type:"reconnect-from",fromNodeId:te.from,fixedTargetId:te.to,edgeKey:te.edgeKey,mouseX:Y.x,mouseY:Y.y})},[G,u]),z=L.useCallback(Q=>{if(!b)return;const te=G(Q);_(Y=>Y?{...Y,mouseX:te.x,mouseY:te.y}:null)},[b,G]),J=L.useCallback(()=>{b&&(C.current=!0,E&&V(E)&&(b.type==="new"?p(b.fromNodeId,E):b.type==="reconnect-to"?m(b.edgeKey,E):b.type==="reconnect-from"&&x(b.edgeKey,E)),_(null),N(null))},[b,E,V,p,m,x]),Z=L.useCallback(()=>{if(C.current){C.current=!1;return}c(null),d(null)},[c,d]);L.useEffect(()=>{if(u)return;const Q=te=>{te.target instanceof HTMLInputElement||te.target instanceof HTMLTextAreaElement||te.target instanceof HTMLSelectElement||(te.key==="Delete"||te.key==="Backspace")&&s&&s!=="start"&&(te.preventDefault(),y(s),d(null))};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[u,s,y,d]);const H=Q=>{const te=M.get(Q.from),Y=M.get(Q.to);if(!te||!Y)return null;let F,ue,oe,ke="middle",Se,Te;if(Q.direction==="down"){const fe=te.cx+Q.fromPort*(te.w/2-10),ae=te.cy+te.h/2,ce=Y.cx+Q.toPort*(Y.w/2-10),se=Y.cy-Y.h/2,je=se-ae,_e=ce-fe;F=`M ${fe} ${ae} C ${fe} ${ae+je*.4}, ${ce-_e*.2} ${se-je*.1}, ${ce} ${se}`,ue=fe+(ce-fe)*.5,oe=ae+je*.6,Se={x:fe,y:ae},Te={x:ce,y:se}}else if(Q.direction==="back"){const fe=Q.from===Q.to,ae=te.cx>=A/2,ce=Q.backEdgeIndex*16,se=ae?A-20-ce:20+ce;if(fe){const je=te.cx>=A/2,_e=30+Q.backEdgeIndex*14,ne=te.cy-te.h/2,xe=je?te.cx+te.w/2:te.cx-te.w/2,He=je?xe+_e:xe-_e,Ze=te.cx+(je?te.w/4:-te.w/4),rt=ne-20-Q.backEdgeIndex*10;F=`M ${xe} ${te.cy} C ${He} ${te.cy}, ${He} ${rt}, ${Ze} ${ne}`,ue=He+10,oe=rt+4,ke="middle",Se={x:xe,y:te.cy},Te={x:Ze,y:ne}}else{const je=ae?te.cx+te.w/2:te.cx-te.w/2,_e=Y.cx+(ae?Y.w/4:-Y.w/4),ne=Math.min(te.cy,Y.cy)-Y.h/2-18-Q.backEdgeIndex*14;F=`M ${je} ${te.cy} L ${se} ${te.cy} L ${se} ${ne} L ${_e} ${ne} L ${_e} ${Y.cy-Y.h/2}`,ue=se,oe=(te.cy+ne)/2,ke=ae?"start":"end",Se={x:je,y:te.cy},Te={x:_e,y:Y.cy-Y.h/2}}}else{const fe=Y.cx>te.cx,ae=Q.sameEdgeIndex===0?-12:12,ce=fe?te.cx+te.w/2:te.cx-te.w/2,se=fe?Y.cx-Y.w/2:Y.cx+Y.w/2,je=te.cy+ae,_e=Y.cy+ae,ne=(ce+se)/2;F=`M ${ce} ${je} C ${ne} ${je}, ${ne} ${_e}, ${se} ${_e}`,ue=ne,oe=(je+_e)/2-6,Se={x:ce,y:je},Te={x:se,y:_e}}return{path:F,labelX:ue,labelY:oe,labelAnchor:ke,fromPt:Se,toPt:Te}},I=(Q,te)=>{const Y=H(Q);if(!Y)return null;const{path:F,labelX:ue,labelY:oe,labelAnchor:ke}=Y,Se=s===Q.edgeKey,Te=Q.label&&Q.label!=="otherwise";return o.jsxs("g",{children:[o.jsx("path",{d:F,fill:"none",stroke:"transparent",strokeWidth:14,className:"cursor-pointer",onClick:fe=>{fe.stopPropagation(),u||d(Se?null:Q.edgeKey)}}),o.jsx("path",{d:F,fill:"none",stroke:Se?"#58a6ff":"#484f58",strokeWidth:Se?2.2:1.2,markerEnd:Se?"url(#arrow-selected)":"url(#arrow)",pointerEvents:"none"}),Te&&o.jsx("text",{x:ue+(ke==="start"?5:ke==="end"?-5:0),y:oe+3,textAnchor:ke,className:"text-[8px]",fill:Se?"#79c0ff":"#8b949e",style:{paintOrder:"stroke",stroke:"#0d1117",strokeWidth:3,strokeLinejoin:"round"},pointerEvents:"none",children:Q.label})]},te)},$=()=>{if(!s||b)return null;const Q=D.find(oe=>oe.edgeKey===s);if(!Q)return null;const te=H(Q);if(!te)return null;const{fromPt:Y,toPt:F}=te,ue=6;return o.jsxs(o.Fragment,{children:[Q.edgeKey!=="start"&&o.jsx("circle",{cx:Y.x,cy:Y.y,r:ue,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:oe=>W(oe,Q)}),o.jsx("circle",{cx:F.x,cy:F.y,r:ue,fill:"#58a6ff",fillOpacity:.25,stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.8,className:"cursor-grab",onMouseDown:oe=>U(oe,Q)})]})},q=()=>{if(!b)return null;let Q,te,Y,F;if(b.type==="reconnect-from"){const ke=M.get(b.fixedTargetId);if(!ke)return null;Q=b.mouseX,te=b.mouseY,Y=ke.cx,F=ke.cy-ke.h/2}else{const ke=M.get(b.fromNodeId);if(!ke)return null;Q=ke.cx,te=ke.cy+ke.h/2,Y=b.mouseX,F=b.mouseY}const ue=F-te,oe=Math.abs(ue)>10?`M ${Q} ${te} C ${Q} ${te+ue*.4}, ${Y} ${F-ue*.4}, ${Y} ${F}`:`M ${Q} ${te} L ${Y} ${F}`;return o.jsx("path",{d:oe,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeDasharray:"6 3",strokeOpacity:.7,pointerEvents:"none"})},B=Q=>{const te=Q.cy+Q.h/2,Y=(b==null?void 0:b.fromNodeId)===Q.id;return o.jsx("circle",{cx:Q.cx,cy:te,r:K0,fill:Y?"#58a6ff":"#1c2128",stroke:Y?"#58a6ff":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5,className:"cursor-crosshair",onMouseDown:F=>R(F,Q.id)})},ee=Q=>{const te=Q.cy-Q.h/2,Y=b&&E===Q.id&&V(Q.id);return o.jsx("circle",{cx:Q.cx,cy:te,r:K0,fill:Y?"#3fb950":"#1c2128",stroke:Y?"#3fb950":"#484f58",strokeWidth:1.5,strokeOpacity:Y?1:.5})};return o.jsxs("svg",{ref:w,viewBox:`0 0 ${A} ${O}`,className:"block w-full",preserveAspectRatio:"xMidYMin meet",onMouseMove:z,onMouseUp:J,onClick:Z,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((Q,te)=>I(Q,te)),T.map(Q=>{const te=n===Q.id,Y=Q.cx-Q.w/2,F=Q.cy-Q.h/2,ue=v===Q.id,oe=b&&E===Q.id&&V(Q.id);if(Q.type==="terminal"){const Se=Q.id==="$start",Te=Se?"#58a6ff":"#3fb950",fe=Se,ae=!Se;return o.jsxs("g",{onClick:ce=>{ce.stopPropagation(),Se&&!u&&d("start")},className:Se&&!u?"cursor-pointer":void 0,children:[oe&&o.jsx("rect",{x:Y-3,y:F-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),Se&&s==="start"&&o.jsx("rect",{x:Y-3,y:F-3,width:Q.w+6,height:Q.h+6,rx:Q.h/2+3,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:F,width:Q.w,height:Q.h,rx:Q.h/2,fill:Te,fillOpacity:.08,stroke:Te,strokeOpacity:.4,strokeWidth:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:Te,className:"text-[10px] font-medium",pointerEvents:"none",children:Q.label}),fe&&B(Q),ae&&ee(Q)]},Q.id)}const ke=Q.color??"#6b7280";return o.jsxs("g",{onClick:Se=>{Se.stopPropagation(),u||c(te?null:Q.id)},onMouseEnter:()=>S(Q.id),onMouseLeave:()=>S(null),className:u?void 0:"cursor-pointer",children:[oe&&o.jsx("rect",{x:Y-3,y:F-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#3fb950",strokeOpacity:.6,strokeWidth:2}),te&&o.jsx("rect",{x:Y-3,y:F-3,width:Q.w+6,height:Q.h+6,rx:12,fill:"none",stroke:"#58a6ff",strokeOpacity:.5,strokeWidth:2}),o.jsx("rect",{x:Y,y:F,width:Q.w,height:Q.h,rx:10,fill:ke,fillOpacity:.08,stroke:ke,strokeOpacity:.6,strokeWidth:te?2:1.5}),o.jsx("text",{x:Q.cx,y:Q.cy+4,textAnchor:"middle",fill:"#c9d1d9",className:"text-[11px] font-medium",pointerEvents:"none",children:Q.label}),!u&&B(Q),!u&&ee(Q),ue&&!b&&!u&&o.jsxs("g",{onClick:Se=>{Se.stopPropagation(),f(Q.id)},className:"cursor-pointer",children:[o.jsx("circle",{cx:Y+Q.w-2,cy:F+2,r:8,fill:"#0d1117",fillOpacity:.9,stroke:"#f85149",strokeOpacity:.5,strokeWidth:1}),o.jsx("line",{x1:Y+Q.w-5,y1:F-1,x2:Y+Q.w+1,y2:F+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"}),o.jsx("line",{x1:Y+Q.w+1,y1:F-1,x2:Y+Q.w-5,y2:F+5,stroke:"#f85149",strokeWidth:1.5,strokeLinecap:"round"})]})]},Q.id)}),b&&T.map(Q=>V(Q.id)?o.jsx("rect",{x:Q.cx-Q.w/2-8,y:Q.cy-Q.h/2-8,width:Q.w+16,height:Q.h+16,fill:"transparent",rx:12,onMouseEnter:()=>N(Q.id),onMouseLeave:()=>N(null),onMouseUp:te=>{te.stopPropagation(),J()}},`drop-${Q.id}`):null),q(),$()]})}const du="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",el="block text-[11px] text-text-secondary mb-0.5";function wB({formName:e,formId:t,formDescription:n,formMaxIterations:s,formColor:a,isReadOnly:l,onNameChange:u,onDescriptionChange:c,onMaxIterationsChange:d,onColorChange:f}){return 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:el,children:"Name"}),o.jsx("input",{value:e,onChange:p=>u(p.target.value),placeholder:"Workflow name",className:`${du} ${l?"opacity-50":""}`,readOnly:l})]}),o.jsxs("div",{className:"min-w-[100px]",children:[o.jsx("label",{className:el,children:"ID"}),o.jsx("input",{value:t,readOnly:!0,className:`${du} font-mono opacity-50`})]}),o.jsxs("div",{className:"flex-1 min-w-[140px]",children:[o.jsx("label",{className:el,children:"Description"}),o.jsx("input",{value:n,onChange:p=>!l&&c(p.target.value),readOnly:l,placeholder:"What does this workflow do?",className:`${du} ${l?"opacity-50":""}`})]}),o.jsxs("div",{className:"w-20",children:[o.jsx("label",{className:el,children:"Max Iter."}),o.jsx("input",{type:"number",value:s,onChange:p=>!l&&d(Number(p.target.value)),readOnly:l,className:`${du} font-mono ${l?"opacity-50":""}`})]}),o.jsxs("div",{children:[o.jsx("label",{className:el,children:"Color"}),o.jsx("input",{type:"color",value:a,onChange:p=>!l&&f(p.target.value),disabled:l,className:`w-8 h-8 rounded border border-border bg-transparent ${l?"opacity-50":"cursor-pointer"}`})]})]})}function CB({name:e,id:t,color:n,description:s,isBuiltIn:a,actions:l}){return 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 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:n}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:t}),a&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),s&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:s})]}),o.jsx("div",{className:"flex items-center gap-1 flex-shrink-0 ml-3",children:l})]})}function Y0({title:e,items:t,renderActions:n}){return t.length===0?null:o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsx("div",{className:"space-y-2",children:t.map(s=>o.jsx(CB,{name:s.name,id:s.id,color:s.color??"#3b82f6",description:s.description,actions:n(s)},s.id))})]})}const Ta="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",Cm="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",as="block text-[11px] text-text-secondary mb-0.5";function km({variables:e,onInsert:t}){return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:e.map(n=>o.jsx("button",{type:"button",onClick:()=>t(n.name),title:n.description,className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-bg-primary border border-border text-text-secondary hover:text-accent-primary hover:border-accent-primary/40 transition-colors",children:`{{${n.name}}}`},n.name))})}function kB({step:e,isEntry:t,agentTypes:n,transitionCount:s,templateVariables:a,onUpdate:l,onRemove:u,onSetEntry:c}){const{color:d,name:f}=pg(e,n);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}),t&&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:[!t&&o.jsx("button",{onClick:c,className:"p-1 rounded text-text-muted hover:text-accent-primary text-xs",children:"Set entry"}),o.jsx("button",{onClick:u,className:"p-1 rounded text-text-muted hover:text-accent-error text-xs",children:"Delete"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Type"}),o.jsx("select",{value:e.type,onChange:p=>{const m=p.target.value,x=m==="sub_agent"?"verification":"build";if(m==="agent"){const y=n.find(w=>!w.subagent);l({...e,type:m,phase:x,agentId:(y==null?void 0:y.id)??"builder",name:(y==null?void 0:y.name)??"Agent"})}else if(m==="sub_agent"){const y=n.find(w=>w.subagent);l({...e,type:m,phase:x,subAgentType:(y==null?void 0:y.id)??"",name:(y==null?void 0:y.name)??"Sub-Agent"})}else l({...e,type:m,phase:x,name:"Shell"})},className:Cm,children:vB.map(p=>o.jsx("option",{value:p.value,children:p.label},p.value))})]}),e.type==="agent"&&o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Agent Type"}),o.jsx("select",{value:e.agentId??"builder",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,agentId:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:Cm,children:n.filter(p=>!p.subagent).map(p=>o.jsx("option",{value:p.id,children:p.name},p.id))})]}),e.type==="sub_agent"&&o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Sub-Agent Type"}),o.jsxs("select",{value:e.subAgentType??"",onChange:p=>{const m=n.find(x=>x.id===p.target.value);l({...e,subAgentType:p.target.value,name:(m==null?void 0:m.name)??p.target.value})},className:Cm,children:[o.jsx("option",{value:"",children:"— select —"}),n.filter(p=>p.subagent).map(p=>o.jsx("option",{value:p.id,children:p.name},p.id))]})]}),(e.type==="agent"||e.type==="sub_agent")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Prompt"}),o.jsx("textarea",{value:e.prompt??"",onChange:p=>l({...e,prompt:p.target.value||void 0}),rows:6,className:`${Ta} resize-y text-xs`,placeholder:"Injected on first entry..."}),o.jsx(km,{variables:a,onInsert:p=>l({...e,prompt:(e.prompt??"")+`{{${p}}}`})})]}),o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Nudge Prompt"}),o.jsx("textarea",{value:e.nudgePrompt??"",onChange:p=>l({...e,nudgePrompt:p.target.value||void 0}),rows:6,className:`${Ta} resize-y text-xs`,placeholder:"Injected on re-entry..."}),o.jsx(km,{variables:a,onInsert:p=>l({...e,nudgePrompt:(e.nudgePrompt??"")+`{{${p}}}`})})]})]}),e.type==="shell"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Command"}),o.jsx("textarea",{value:e.command??"",onChange:p=>l({...e,command:p.target.value}),rows:3,className:`${Ta} font-mono text-xs resize-y`,placeholder:"cd {{workdir}} && npm run lint"}),o.jsx(km,{variables:a,onInsert:p=>l({...e,command:(e.command??"")+`{{${p}}}`})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Timeout (ms)"}),o.jsx("input",{type:"number",value:e.timeout??6e4,onChange:p=>l({...e,timeout:Number(p.target.value)}),className:`${Ta} font-mono text-xs`})]}),o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Success Codes"}),o.jsx("input",{value:(e.successExitCodes??[0]).join(", "),onChange:p=>l({...e,successExitCodes:p.target.value.split(",").map(m=>Number(m.trim())).filter(m=>!isNaN(m))}),className:`${Ta} font-mono text-xs`})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:as,children:"Sub-group"}),o.jsx("input",{value:e.subGroup??"",onChange:p=>l({...e,subGroup:p.target.value||void 0}),placeholder:"e.g. build, verify, review",className:Ta})]}),o.jsx("div",{className:"pt-1 border-t border-border/50",children:o.jsxs("p",{className:"text-text-muted text-[10px]",children:[s," outgoing transition",s!==1?"s":""," — drag from the bottom port to connect."]})})]})}const Aa="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",X0="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",_i="block text-[11px] text-text-secondary mb-0.5";function EB({fromLabel:e,toLabel:t,condition:n,subGroup:s,fromStep:a,agentTypes:l,transitionIndex:u,totalTransitions:c,onUpdateCondition:d,onUpdateSubGroup:f,onDelete:p,onMoveUp:m,onMoveDown:x}){var C;const y=a&&(a.type==="sub_agent"||a.type==="agent")?l.find(v=>v.id===(a.type==="sub_agent"?a.subAgentType:a.agentId)):void 0,w=(y==null?void 0:y.results)&&y.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.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-500/15 text-blue-300",children:["#",u+1]}),c>1&&o.jsxs("div",{className:"flex items-center gap-0.5",children:[o.jsx("button",{onClick:m,disabled:u===0,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move up (higher priority)",children:o.jsx(Kn,{className:"w-3 h-3",rotate:180})}),o.jsx("button",{onClick:x,disabled:u===c-1,className:"p-0.5 rounded text-text-muted hover:text-text-primary disabled:opacity-20 disabled:cursor-not-allowed",title:"Move down (lower priority)",children:o.jsx(Kn,{className:"w-3 h-3"})})]})]}),o.jsx("button",{onClick:p,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(xp,{}),o.jsx("span",{className:"font-medium text-text-primary",children:t})]}),o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Condition"}),o.jsx("select",{value:n.type,onChange:v=>{d(v.target.value==="step_result"?{type:"step_result",result:"success"}:{type:v.target.value})},className:X0,children:$C.map(v=>o.jsx("option",{value:v.value,children:v.label},v.value))})]}),n.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Result"}),w?o.jsx("select",{value:n.result??y.results[0],onChange:v=>{d({type:"step_result",result:v.target.value})},className:X0,children:y.results.map(v=>o.jsx("option",{value:v,children:v},v))}):o.jsx("input",{type:"text",value:n.result??"success",onChange:v=>d({type:"step_result",result:v.target.value}),placeholder:"e.g. success, passed, failed",className:Aa})]}),(n.type==="metadata_all_match"||n.type==="metadata_all_in")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Metadata Key"}),o.jsx("input",{type:"text",value:n.key??"",onChange:v=>d({...n,key:v.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:Aa})]}),o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Field"}),o.jsx("input",{type:"text",value:n.field??"",onChange:v=>d({...n,field:v.target.value}),placeholder:"e.g. status",className:Aa})]}),n.type==="metadata_all_match"?o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Value"}),o.jsx("input",{type:"text",value:n.value??"",onChange:v=>d({...n,value:v.target.value}),placeholder:"e.g. passed, resolved",className:Aa})]}):o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Values (comma-separated)"}),o.jsx("input",{type:"text",value:((C=n.values)==null?void 0:C.join(", "))??"",onChange:v=>d({...n,values:v.target.value.split(",").map(S=>S.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:Aa})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:_i,children:"Sub-group"}),o.jsx("input",{type:"text",value:s??"",onChange:v=>f(v.target.value||void 0),placeholder:"e.g. build, verify",className:Aa})]}),o.jsx("p",{className:"text-text-muted text-[10px]",children:"Drag handles to reconnect. Order determines evaluation priority. Press Delete to remove."})]})}function jB(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function NB(e){let t=1;for(;e.some(n=>n.id===`s${t}`);)t++;return`s${t}`}const tl="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",Q0="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",La="block text-[11px] text-text-secondary mb-0.5",J0=[];function HC({isOpen:e,onClose:t,initialEditId:n}){var zi,hs;const s=Ct(be=>be.defaults),a=Ct(be=>be.userItems),l=Ct(be=>be.loading),u=Ct(be=>be.templateVariables),c=Ct(be=>be.fetchWorkflows),d=Ct(be=>be.fetchWorkflow),f=Ct(be=>be.fetchDefaultContent),p=Ct(be=>be.fetchTemplateVariables),m=Ct(be=>be.createWorkflow),x=Ct(be=>be.updateWorkflow),y=Ct(be=>be.deleteWorkflow),{requestDelete:w,clearConfirm:C,isConfirming:v}=Gu(),[S,b]=L.useState("list"),[_,E]=L.useState(null),[N,T]=L.useState(!1),[D,A]=L.useState(null),[O,M]=L.useState(null),[G,V]=L.useState(""),[R,U]=L.useState(""),[W,z]=L.useState(""),[J,Z]=L.useState("1.0.0"),[H,I]=L.useState("#3b82f6"),[$,q]=L.useState(""),[B,ee]=L.useState(50),[Q,te]=L.useState(J0),[Y,F]=L.useState({type:"always"}),[ue,oe]=L.useState(""),[ke,Se]=L.useState(!1),Te=mt(be=>be.defaults),fe=mt(be=>be.userItems),ae=mt(be=>be.projectItems),ce=L.useMemo(()=>[...Te,...fe,...ae],[Te,fe,ae]),se=mt(be=>be.fetchAgents),[je]=L.useState(null);L.useEffect(()=>{e&&(c(),p(),se(),A(null),M(null),n?s.some(Ce=>Ce.id===n)?f(n).then(Ce=>{Ce&&_e({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${n}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})}):d(n).then(Ce=>{Ce&&_e(Ce,{editingId:n,isReadOnly:!1})}):(b("list"),E(null),T(!1)))},[e,c,d,f,p,n]);const _e=(be,Ce)=>{V(be.metadata.name),U(be.metadata.id),z(be.metadata.description),Z(be.metadata.version),I(be.metadata.color??"#3b82f6"),q(be.entryStep),ee(be.settings.maxIterations),te(be.steps),F(be.startCondition??{type:"always"}),oe(""),(Ce==null?void 0:Ce.editingId)!==void 0&&E(Ce.editingId),(Ce==null?void 0:Ce.isReadOnly)!==void 0&&T(Ce.isReadOnly),(Ce==null?void 0:Ce.selectedNodeKey)!==void 0&&A(null),(Ce==null?void 0:Ce.selectedEdgeKey)!==void 0&&M(null),b("edit")},ne=async be=>{const Ce=await d(be);Ce&&_e(Ce,{editingId:be,isReadOnly:!1,selectedNodeKey:null,selectedEdgeKey:null})},xe=async()=>{var et;const be=_??R;if(!be||!G)return oe("Name is required."),!1;if(Q.length===0)return oe("Add at least one step."),!1;let Ce=$;if(!Ce||!Q.some(We=>We.id===Ce)){if(Ce=((et=Q.find(We=>We.id))==null?void 0:et.id)??"",!Ce)return oe("All steps need an ID."),!1;q(Ce)}Se(!0),oe("");const Oe={metadata:{id:be,name:G,description:W,version:J||"1.0.0",color:H},entryStep:Ce,settings:{maxIterations:B},steps:Q,startCondition:Y},$e=_?await x(_,Oe):await m(Oe);return Se(!1),$e.success?(_||E(be),!0):(oe($e.error??"Failed to save."),!1)},He=async()=>{await xe()},Ze=async()=>{await xe()&&(n?t():b("list"))},rt=()=>{n?t():b("list")},kt=be=>{V(be),_||U(jB(be))},ge=async be=>s.some(Oe=>Oe.id===be)?await f(be):await d(be),Ne=async be=>{const Ce=await ge(be);Ce&&_e(Ce,{editingId:be,isReadOnly:!0})},Be=async be=>{const Ce=await ge(be);Ce&&_e({...Ce,metadata:{...Ce.metadata,name:Ce.metadata.name+" (copy)",id:`${be}-copy-${Date.now()}`}},{editingId:null,isReadOnly:!1})},Ve=()=>{E(null),V(""),U(""),z(""),Z("1.0.0"),I("#3b82f6"),q(""),ee(50),te(structuredClone(J0)),F({type:"always"}),oe(""),A(null),M(null),T(!1),b("edit")},Ye=async be=>{await y(be),C()},Rt=L.useCallback(be=>{A(be),M(null)},[]),tt=L.useCallback(be=>{M(be),A(null)},[]),Ot=D!==null?Number(D):-1,pt=Ot>=0?Q[Ot]??null:null,gn=L.useCallback(be=>{te(Ce=>Ce.map((Oe,$e)=>$e===Ot?be:Oe))},[Ot]),xt=Y.type==="step_result"?`${Y.result}`:Y.type==="metadata_all_match"?`${Y.key??"?"}=${Y.value??"?"}`:Y.type==="metadata_all_in"?`${Y.key??"?"} in [${((zi=Y.values)==null?void 0:zi.join(","))??"?"}]`:zC[Y.type]??Y.type,dr=()=>{const be=Q.length,Ce=NB(Q),Oe=ce.find($e=>!$e.subagent);te([...Q,{id:Ce,name:(Oe==null?void 0:Oe.name)??"Agent",type:"agent",phase:"build",agentId:(Oe==null?void 0:Oe.id)??"builder",transitions:[]}]),$||q(Ce),Rt(String(be))},Mn=L.useCallback((be,Ce)=>{be==="$start"?(q(Ce),tt("start")):te(Oe=>{const $e=Oe.find(We=>We.id===be),et=$e?$e.transitions.length:0;return tt(`${be}:${et}`),Oe.map(We=>We.id===be?{...We,transitions:[...We.transitions,{when:{type:"always"},goto:Ce}]}:We)})},[tt]),Mi=be=>{if(be==="start")return null;const Ce=be.lastIndexOf(":"),Oe=be.slice(0,Ce),$e=parseInt(be.slice(Ce+1));return{stepId:Oe,transIdx:$e}},hr=L.useCallback((be,Ce)=>{const Oe=Mi(be);Oe&&te($e=>$e.map(et=>et.id===Oe.stepId?{...et,transitions:et.transitions.map((We,dt)=>dt===Oe.transIdx?Ce(We):We)}:et))},[]),Ii=L.useCallback((be,Ce)=>{if(be==="start"){q(Ce);return}hr(be,Oe=>({...Oe,goto:Ce}))},[hr]),Pi=L.useCallback((be,Ce)=>{const Oe=Mi(be);Oe&&(te($e=>{const et=$e.find(dt=>dt.id===Oe.stepId);if(!et)return $e;const We=et.transitions[Oe.transIdx];return We?$e.map(dt=>dt.id===Oe.stepId?{...dt,transitions:dt.transitions.filter((dn,Pt)=>Pt!==Oe.transIdx)}:dt.id===Ce?{...dt,transitions:[...dt.transitions,We]}:dt):$e}),M(null))},[]),wr=L.useCallback(be=>{if(be==="start"){q(""),M(null);return}const Ce=Mi(be);Ce&&(te(Oe=>Oe.map($e=>$e.id===Ce.stepId?{...$e,transitions:$e.transitions.filter((et,We)=>We!==Ce.transIdx)}:$e)),M(null))},[]),Bi=L.useCallback((be,Ce)=>{if(be==="start"){F(Ce);return}hr(be,Oe=>({...Oe,when:Ce}))},[hr]),Ys=L.useCallback((be,Ce)=>{be!=="start"&&hr(be,Oe=>({...Oe,subGroup:Ce||void 0}))},[hr]),Qa=be=>pg(be,ce).name,Ll=()=>{if(!O)return null;if(O==="start"){const dn=Q.find(Pt=>Pt.id===$);return{type:"start",fromLabel:"Start",toLabel:dn?Qa(dn):"(none)",condition:Y}}const be=O.lastIndexOf(":"),Ce=O.slice(0,be),Oe=parseInt(O.slice(be+1)),$e=Q.find(dn=>dn.id===Ce);if(!$e)return null;const et=$e.transitions[Oe];if(!et)return null;const We=Q.find(dn=>dn.id===et.goto),dt=et.goto==="$done"?"Done":We?Qa(We):et.goto;return{type:"step",fromLabel:Qa($e),toLabel:dt,condition:et.when,subGroup:et.subGroup}};if(S==="edit"){const be=Ll();return o.jsxs(Dt,{isOpen:e,onClose:rt,title:N?G:_?"Edit Workflow":"New Workflow",size:"full",children:[ue&&o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded mb-3",children:ue}),o.jsx(wB,{formName:G,formId:R,formDescription:W,formMaxIterations:B,formColor:H,isReadOnly:N,onNameChange:kt,onDescriptionChange:z,onMaxIterationsChange:ee,onColorChange:I}),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"}),!N&&o.jsx("button",{onClick:dr,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(SB,{steps:Q,entryStep:$,selectedNodeId:(pt==null?void 0:pt.id)??null,selectedEdgeKey:O,startConditionLabel:xt,agentTypes:ce,isReadOnly:N,onSelectNode:Ce=>{if(Ce===null){Rt(null);return}const Oe=Q.findIndex($e=>$e.id===Ce);Rt(Oe>=0?String(Oe):null)},onSelectEdge:tt,onRemoveStep:Ce=>{var $e;const Oe=Q.findIndex(et=>et.id===Ce);if(te(et=>et.filter(We=>We.id!==Ce)),Ot===Oe&&Rt(null),$===Ce){const et=Q.filter(We=>We.id!==Ce);q((($e=et[0])==null?void 0:$e.id)??"")}},onCreateTransition:Mn,onReconnectTo:Ii,onReconnectFrom:Pi,onDeleteTransition:wr}),Q.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:dr,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:N&&(be||pt)?o.jsx("p",{className:"text-text-muted text-xs text-center py-8",children:'View only — click "Duplicate & Customize" to edit.'}):be?be.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"})}),$&&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(xp,{}),o.jsx("span",{className:"text-text-primary font-medium",children:be.toLabel})]}),o.jsxs("div",{children:[o.jsx("label",{className:La,children:"Activation Condition"}),o.jsx("select",{value:Y.type,onChange:Ce=>F(Ce.target.value==="step_result"?{type:"step_result",result:"success"}:Ce.target.value==="metadata_all_match"?{type:"metadata_all_match",key:"",field:"",value:""}:Ce.target.value==="metadata_all_in"?{type:"metadata_all_in",key:"",field:"",values:[]}:{type:Ce.target.value}),className:Q0,children:$C.map(Ce=>o.jsx("option",{value:Ce.value,children:Ce.label},Ce.value))})]}),Y.type==="step_result"&&o.jsxs("div",{children:[o.jsx("label",{className:La,children:"Result"}),$&&(()=>{const Ce=Q.find(We=>We.id===$),Oe=Ce&&(Ce.type==="sub_agent"||Ce.type==="agent")?ce.find(We=>We.id===(Ce.type==="sub_agent"?Ce.subAgentType:Ce.agentId)):void 0,$e=(Oe==null?void 0:Oe.results)&&Oe.results.length>0,et=(Oe==null?void 0:Oe.results)??[];return $e?o.jsx("select",{value:Y.result??et[0],onChange:We=>F({type:"step_result",result:We.target.value}),className:Q0,children:et.map(We=>o.jsx("option",{value:We,children:We},We))}):o.jsx("input",{type:"text",value:Y.result??"success",onChange:We=>F({type:"step_result",result:We.target.value}),placeholder:"e.g. success, passed, failed",className:tl})})()]}),(Y.type==="metadata_all_match"||Y.type==="metadata_all_in")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:La,children:"Metadata Key"}),o.jsx("input",{type:"text",value:Y.key??"",onChange:Ce=>F({...Y,key:Ce.target.value}),placeholder:"e.g. criteria, todos, review_findings",className:tl})]}),o.jsxs("div",{children:[o.jsx("label",{className:La,children:"Field"}),o.jsx("input",{type:"text",value:Y.field??"",onChange:Ce=>F({...Y,field:Ce.target.value}),placeholder:"e.g. status",className:tl})]}),Y.type==="metadata_all_match"?o.jsxs("div",{children:[o.jsx("label",{className:La,children:"Value"}),o.jsx("input",{type:"text",value:Y.value??"",onChange:Ce=>F({...Y,value:Ce.target.value}),placeholder:"e.g. passed, resolved",className:tl})]}):o.jsxs("div",{children:[o.jsx("label",{className:La,children:"Values (comma-separated)"}),o.jsx("input",{type:"text",value:((hs=Y.values)==null?void 0:hs.join(", "))??"",onChange:Ce=>F({...Y,values:Ce.target.value.split(",").map(Oe=>Oe.trim()).filter(Boolean)}),placeholder:"e.g. resolved, dismissed",className:tl})]})]}),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."})]}):(()=>{const Ce=Mi(O),Oe=Ce==null?void 0:Ce.stepId,$e=(Ce==null?void 0:Ce.transIdx)??0,et=Oe?Q.find(dt=>dt.id===Oe):void 0,We=(et==null?void 0:et.transitions.length)??0;return o.jsx(EB,{fromLabel:be.fromLabel,toLabel:be.toLabel,condition:be.condition,subGroup:"subGroup"in be?be.subGroup:void 0,fromStep:be.type==="step"?Q.find(dt=>dt.id===be.fromLabel):void 0,agentTypes:ce,transitionIndex:$e,totalTransitions:We,onUpdateCondition:dt=>Bi(O,dt),onUpdateSubGroup:dt=>Ys(O,dt),onDelete:()=>wr(O),onMoveUp:()=>{te(dt=>{const dn=dt.find(yt=>yt.id===Oe);if(!dn||$e===0)return dt;const Pt=[...dn.transitions];return[Pt[$e-1],Pt[$e]]=[Pt[$e],Pt[$e-1]],dt.map(yt=>yt.id===Oe?{...yt,transitions:Pt}:yt)}),M(`${Oe}:${$e-1}`)},onMoveDown:()=>{te(dt=>{const dn=dt.find(yt=>yt.id===Oe);if(!dn||$e===dn.transitions.length-1)return dt;const Pt=[...dn.transitions];return[Pt[$e],Pt[$e+1]]=[Pt[$e+1],Pt[$e]],dt.map(yt=>yt.id===Oe?{...yt,transitions:Pt}:yt)}),M(`${Oe}:${$e+1}`)}})})():pt?o.jsx(kB,{step:pt,isEntry:pt.id===$,agentTypes:ce,transitionCount:pt.transitions.length,templateVariables:u,onUpdate:gn,onRemove:()=>{var Ce;if(pt&&(te(Q.filter((Oe,$e)=>$e!==Ot)),Rt(null),$===pt.id)){const Oe=Q.filter(($e,et)=>et!==Ot);q(((Ce=Oe[0])==null?void 0:Ce.id)??"")}},onSetEntry:()=>q(pt.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:rt,children:"Close"}),N?o.jsx(nt,{variant:"primary",onClick:()=>{V(G+" (copy)"),U(`${_}-copy-${Date.now()}`),E(null),T(!1)},children:"Duplicate & Customize"}):o.jsxs(o.Fragment,{children:[o.jsx(nt,{variant:"primary",onClick:He,children:"Save"}),o.jsx(nt,{variant:"primary",onClick:Ze,children:"Save & Close"})]})]})]})}return o.jsx(Dt,{isOpen:e,onClose:t,title:"Workflows",size:"lg",children:o.jsx(RS,{description:"Workflows define multi-step agentic processes with branching transitions.",onNew:Ve,loading:l,hasItems:s.length>0||a.length>0,children:o.jsxs("div",{className:"space-y-4",children:[o.jsx(Y0,{title:"Built-in",items:s,renderActions:be=>o.jsx(o.Fragment,{children:o.jsx(Fs,{onClick:()=>Be(be.id),children:o.jsx(xu,{})})})}),o.jsx(Y0,{title:"Custom",items:a,renderActions:be=>o.jsxs(o.Fragment,{children:[o.jsx(Fs,{onClick:()=>Ne(be.id),children:o.jsx(xu,{})}),o.jsx(Fs,{onClick:()=>ne(be.id),children:o.jsx("span",{className:"text-[10px]",children:"Edit"})}),o.jsx(yu,{onClick:()=>Be(be.id)}),v(be.id,"delete")?o.jsx(kp,{onConfirm:()=>Ye(be.id),onCancel:C}):o.jsx(Ep,{onClick:()=>w(be.id)})]})})]})})})}function Or(e,t){const n=new Set(t.map(s=>s.id));return[...e.filter(s=>!n.has(s.id)),...t]}function UC(e,t){if(!t)return!0;const n=t.toLowerCase().split(/\s+/),s=e.toLowerCase().split(/\s+/);return n.every(a=>{for(const l of s){let u=0;for(let c=0;c<l.length&&u<a.length;c++)l[c]===a[u]&&u++;if(u===a.length)return!0}return!1})}function FC(e,t,n,s,a){switch(e.key){case"ArrowDown":e.preventDefault(),n(l=>Math.min(l+1,t));break;case"ArrowUp":e.preventDefault(),n(l=>Math.max(l-1,0));break;case"Enter":e.preventDefault(),s();break;case"Escape":e.preventDefault(),a();break}}function TB(e){const t=e.match(/^\/p\/([^/]+)/);return t==null?void 0:t[1]}function AB({isOpen:e,onClose:t,onCloseComplete:n,onSelectCommand:s,onSelectWorkflow:a,onCloseCompleteAction:l,textareaContent:u,onSearchMessages:c,onToggleAutoScroll:d,isAutoScrollActive:f}){const[,p]=qn(),m=en(B=>B.fetchCommands),x=Ct(B=>B.fetchWorkflows),y=mt(B=>B.fetchAgents),w=en(B=>B.defaults),C=en(B=>B.userItems),v=en(B=>B.projectItems),S=Ct(B=>B.defaults),b=Ct(B=>B.userItems),_=Ct(B=>B.projectItems),E=mt(B=>B.defaults),N=mt(B=>B.userItems),T=mt(B=>B.projectItems),D=Re(B=>{var ee;return(ee=B.currentSession)==null?void 0:ee.mode}),A=Re(B=>{var ee;return((ee=B.currentSession)==null?void 0:ee.dangerLevel)??"normal"}),O=Re(B=>B.switchMode),M=Re(B=>B.switchDangerLevel),G=Re(B=>{var ee;return(ee=B.currentSession)==null?void 0:ee.projectId}),V=L.useRef(void 0),[R,U]=L.useState(""),[W,z]=L.useState(0),J=L.useRef(null),Z=L.useRef(!1);L.useEffect(()=>{e&&(Z.current=!0)},[e]),L.useEffect(()=>{if(e){m(),x(),y(),U(""),z(0);const B=setTimeout(()=>{var ee;return(ee=J.current)==null?void 0:ee.focus()},50);return()=>clearTimeout(B)}},[e,m,x,y]),L.useEffect(()=>{var B;!e&&Z.current&&(n==null||n(),(B=V.current)==null||B.call(V),V.current=void 0)},[e,n]);const I=[{id:"create-session",name:"New Session",prefix:"Action > Create",action:()=>{const B=G??TB(window.location.pathname);B&&p(`/p/${B}/new`)}},{id:"navigate-session",name:"Another Session",prefix:"Action > Navigate to",action:()=>{V.current=l,t()}},{id:"search-messages",name:"Messages",prefix:"Action > Search",action:()=>{t(),c==null||c()}},{id:"toggle-autoscroll",name:f?"Auto-scroll Off":"Auto-scroll On",prefix:"Action > Toggle",action:()=>{t(),d==null||d(!f)}},...Or(Or(E,N),T).filter(B=>!B.subagent&&B.id!==D).map(B=>({id:B.id,name:B.name,prefix:"Agent > Switch to",action:()=>O(B.id)})),...Or(Or(w,C),v).map(B=>({id:B.id,name:B.name,prefix:"Command > Launch",action:()=>s(B.id,u)})),...Or(Or(S,b),_).map(B=>({id:B.id,name:B.name,prefix:"Workflow > Run",action:()=>a(B.id)})),...["normal","dangerous"].filter(B=>B!==A).map(B=>({id:B,name:B.charAt(0).toUpperCase()+B.slice(1),prefix:"Mode > Switch to",action:()=>M(B)}))].filter(B=>UC(`${B.prefix} ${B.name}`,R)),$=I.length-1,q=B=>{FC(B,$,z,()=>{var ee;(ee=I[W])==null||ee.action(),t()},t)};return e?Ga.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:t}),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:J,type:"text",value:R,onChange:B=>{U(B.target.value),z(0)},onKeyDown:q,placeholder:"Search...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx(wp,{onClick:t,className:"shrink-0","aria-label":"Close"})]}),o.jsx("div",{className:"overflow-y-auto max-h-[60vh] p-2",children:I.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:w.length+C.length+S.length+b.length>0?"No matches":"No agents, commands, or workflows yet"}):I.map((B,ee)=>o.jsxs("button",{type:"button",onClick:()=>{B.action(),t()},className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${ee===W?"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:[B.prefix," "]}),o.jsx("span",{children:B.name})]},B.id))})]})]}),document.body):null}const VC="openfox-message-search-filters",LB=[{key:"user",label:"User prompts"},{key:"thinking",label:"Thinking"},{key:"response",label:"Responses"}];function DB(){try{const e=localStorage.getItem(VC);if(e){const t=JSON.parse(e);return new Set(t)}}catch{}return new Set(["user","thinking","response"])}function RB(e){localStorage.setItem(VC,JSON.stringify([...e]))}function OB(e){var n,s;if(e.type!=="message")return null;const t=e.message;if(t.role==="user")return"user";if(t.role==="assistant"){if((n=t.content)!=null&&n.trim())return"response";if((s=t.thinkingContent)!=null&&s.trim())return"thinking"}return null}function MB(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear())return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});const a=t.getFullYear(),l=String(t.getMonth()+1).padStart(2,"0"),u=String(t.getDate()).padStart(2,"0"),c=String(t.getHours()).padStart(2,"0"),d=String(t.getMinutes()).padStart(2,"0");return`${a}/${l}/${u} ${c}:${d}`}function IB(e){var t;if(e.type==="message")return e.message.timestamp;if(e.type==="subagent")return(t=e.messages[0])==null?void 0:t.timestamp}function PB(e){var t,n;if(e.type==="message"){const s=e.message;if(s.role==="assistant"){const a=(t=s.content)==null?void 0:t.trim();return((n=s.thinkingContent)==null?void 0:n.trim())&&!a?"italic text-text-muted":""}if(s.role==="user")return"font-bold"}return""}function BB(e){var n,s;if(e.type!=="message")return o.jsx(Fv,{className:"w-3.5 h-3.5"});const t=e.message;return t.role==="assistant"?(n=t.thinkingContent)!=null&&n.trim()&&!((s=t.content)!=null&&s.trim())?o.jsx(Wj,{className:"w-3.5 h-3.5"}):o.jsx(Fv,{className:"w-3.5 h-3.5"}):o.jsx(Gj,{className:"w-3.5 h-3.5"})}function Z0(e){var t;if(e.type==="message"){const n=e.message,s=n.content||"",a=s.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(n.messageKind==="workflow-started")try{return`Workflow: ${JSON.parse(s).workflowName}`}catch{return"Workflow started"}if(n.messageKind==="task-completed")return"Task completed";if(n.messageKind==="auto-prompt")return"Auto-prompt";if(n.messageKind==="correction")return"Correction";if(n.messageKind==="context-reset")return"Context reset";if(n.messageKind==="command")return"Command executed";if(n.role==="assistant")return a?a.slice(0,200):(t=n.thinkingContent)!=null&&t.trim()?n.thinkingContent.slice(0,200):"";const l=a.slice(0,200);return l.length<a.length?`${l}...`:l}return e.type==="subagent"?`Sub-agent: ${e.subAgentType}`:""}function zB({isOpen:e,onClose:t,displayItems:n,onNavigate:s}){const[a,l]=L.useState(""),[u,c]=L.useState(0),[d,f]=L.useState(DB),p=L.useRef(null),m=L.useRef(null),x=L.useRef(null),y=N=>{f(T=>{const D=new Set(T);return D.has(N)?D.delete(N):D.add(N),RB(D),D})},w=L.useMemo(()=>n.filter(N=>{var T,D;return!(N.type==="context-divider"||N.type==="message"&&(N.message.messageKind==="auto-prompt"||N.message.role==="assistant"&&!((T=N.message.content)!=null&&T.trim())&&!((D=N.message.thinkingContent)!=null&&D.trim())))}),[n]),C=L.useMemo(()=>w.filter(N=>{const T=OB(N);return!(T&&!d.has(T))}),[w,d]),v=L.useMemo(()=>a?w.filter(N=>{const T=Z0(N);return UC(T,a)}):C,[C,a]),S=v.length-1;L.useEffect(()=>{if(e){l(""),c(0);const N=setTimeout(()=>{var T;return(T=p.current)==null?void 0:T.focus()},50);return()=>clearTimeout(N)}},[e]),L.useEffect(()=>{e&&m.current&&(m.current.scrollTop=m.current.scrollHeight)},[e]),L.useEffect(()=>{x.current&&x.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[u]);const b=N=>{FC(N,S,c,()=>{const T=v[u];if(T){const D=n.indexOf(T);D>=0&&s(D),t()}},t)},_=N=>{const T=n.indexOf(N);T>=0&&s(T),t()},E=N=>n.indexOf(N);return e?Ga.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:t}),o.jsxs("div",{className:"relative w-full max-w-lg 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(bp,{}),o.jsx("input",{ref:p,type:"text",value:a,onChange:N=>{l(N.target.value),c(0)},onKeyDown:b,placeholder:"Search timeline...",className:"flex-1 bg-transparent text-sm focus:outline-none placeholder:text-text-muted"}),o.jsx("button",{type:"button",onClick:t,className:"p-0.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:o.jsx(Sl,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"flex gap-1.5 px-4 py-2 border-b border-border",children:LB.map(N=>{const T=d.has(N.key);return o.jsx("button",{type:"button",onClick:()=>y(N.key),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${T?"bg-accent-primary/20 text-accent-primary border border-accent-primary/40":"bg-bg-tertiary text-text-muted border border-border hover:text-text-secondary"}`,children:N.label},N.key)})}),o.jsx("div",{ref:m,className:"overflow-y-auto max-h-[60vh] p-2",children:v.length===0?o.jsx("div",{className:"px-3 py-4 text-center text-text-muted text-sm",children:C.length>0?"No matches":"No messages yet"}):v.map((N,T)=>{const D=E(N),A=BB(N),O=Z0(N),M=PB(N),G=IB(N),V=N.type==="message"&&N.message.role==="user";return o.jsx("button",{ref:T===u?x:null,type:"button",onClick:()=>_(N),className:`w-full text-left px-3 py-2 rounded text-sm transition-colors ${T===u?"bg-accent-primary/20 text-text-primary":V?"bg-accent-primary/5 text-text-secondary hover:bg-accent-primary/10 hover:text-text-primary":"text-text-secondary hover:bg-bg-tertiary hover:text-text-primary"}`,children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[o.jsx("span",{className:"flex-shrink-0",children:A}),o.jsx("span",{className:`truncate flex-1 ${M}`,children:O})]}),G&&o.jsx("span",{className:"text-text-muted text-xs shrink-0",children:MB(G)})]})},`${D}-${N.type}`)})})]})]}),document.body):null}function $B({attachment:e,onRemove:t}){const n=s=>s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(1)} KB`:`${(s/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(Cl,{onClick:()=>t(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.description||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:n(e.size)})]})}function HB({history:e,selectedIndex:t,onSelect:n,onEscape:s,onNavigate:a}){const l=L.useRef(null),u=L.useRef(null);L.useEffect(()=>{u.current&&l.current&&u.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[t]);const c=f=>{switch(f.key){case"Enter":f.preventDefault(),e[t]&&n(e[t].content);break;case"Escape":f.preventDefault(),s();break;case"ArrowUp":f.preventDefault(),a("up");break;case"ArrowDown":f.preventDefault(),a("down");break}},d=f=>{n(f)};return o.jsx("div",{ref:l,role:"list",className:"mb-2 p-2 bg-bg-secondary border border-border rounded-lg overflow-y-auto max-h-64",onKeyDown:c,children:e.map((f,p)=>o.jsxs("div",{ref:p===t?u:null,role:"listitem",onClick:()=>d(f.content),className:`
|
|
295
295
|
p-2 rounded cursor-pointer transition-colors
|
|
296
296
|
${p===t?"bg-accent-primary/20 border border-accent-primary":"hover:bg-bg-tertiary"}
|
|
297
|
-
`,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))})}function UB(){const e=_j(),t=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 ${t}`,style:{animationDelay:"0ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,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"})]})}const FB={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function VB(e,t={}){const n={...FB,...t};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=QB(a),u=`data:${e.type};base64,${l}`,c=await GC(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await GB(e,n)}async function GB(e,t){const n=await qB(e),s=await GC(n),{width:a,height:l}=WB(s.width,s.height,t.maxWidth,t.maxHeight),u=KB();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(s,0,0,a,l);let d=t.quality,f="";for(let m=0;m<10&&(f=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),!(eS(f)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=eS(f);return{dataUrl:f,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function WB(e,t,n,s){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>s?{width:Math.round(s*a),height:s}:{width:e,height:t}}function qB(e){return new Promise((t,n)=>{const s=XB(),a=new s;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function GC(e){return new Promise((t,n)=>{const s=YB(),a=new s;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function KB(){var t;const e=gg();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function YB(){const e=gg();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function XB(){const e=gg();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function gg(){return globalThis}function QB(e){const t=new Uint8Array(e);let n="";for(let s=0;s<t.byteLength;s++){const a=t[s];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function eS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}function JB(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function ZB(e,t=50*1024*1024){return e.size>t?{valid:!1,error:`Image file is too large (${tS(e.size)}). Maximum size is ${tS(t)}.`}:{valid:!0}}function tS(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function Em(e,t,n,s={}){const{maxSizeBytes:a=50*1024*1024,filename:l}=s;if(!JB(e)){n(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const u=ZB(e,a);if(!u.valid){n(u.error??"Image file is too large");return}try{const c=await VB(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:mS(),filename:l??e.name,mimeType:c.mimeType,size:c.size,data:c.dataUrl};t(d)}catch(c){const d=c instanceof Error?c.message??"Failed to process image":"Failed to process image";n(d)}}function WC(e){const t=Re(l=>l.sendMessage),n=Re(l=>l.launchWorkflow),s=L.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=L.useCallback((l,u,c,d)=>{e(!0),n(l,u,c,d)},[e,n]);return{sendMessage:s,launchWorkflow:a}}function e8({children:e}){return Ga.createPortal(e,document.body)}function t8(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function n8({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:s,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,f]=L.useState(!1),[p,m]=L.useState("commands"),[x,y]=L.useState(""),[w,C]=L.useState(0),[v,S]=L.useState(null),[b,_]=L.useState(null),E=L.useRef(null),N=L.useRef(null),T=en(ee=>ee.defaults),D=en(ee=>ee.userItems),A=en(ee=>ee.projectItems),O=en(ee=>ee.fetchCommands),M=Ct(ee=>ee.defaults),G=Ct(ee=>ee.userItems),V=Ct(ee=>ee.projectItems),R=Ct(ee=>ee.fetchWorkflows),U=Or(Or(T,D),A),W=Or(Or(M,G),V);L.useEffect(()=>{d&&(p==="commands"?O():p==="workflows"&&R())},[d,p,O,R]),L.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ee;return(ee=E.current)==null?void 0:ee.focus()}))},[d,p]),L.useEffect(()=>{if(!d)return;const ee=Q=>{var te;(te=N.current)!=null&&te.contains(Q.target)||f(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[d]);const z=ee=>{switch(ee.key){case"ArrowDown":ee.preventDefault(),C(Q=>{const Y=(p==="commands"?U:W).filter(F=>{const ue=x.toLowerCase();return!ue||F.name.toLowerCase().includes(ue)});return Math.min(Q+1,Y.length-1)});break;case"ArrowUp":ee.preventDefault(),C(Q=>Math.max(Q-1,0));break;case"Enter":ee.preventDefault();break;case"Escape":ee.preventDefault(),f(!1);break}},J=ee=>{y(ee),C(0)},Z=U.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),H=W.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),I=async ee=>{const Q=await en.getState().fetchCommand(ee);Q&&e(Q.prompt,Q.metadata.agentMode,u,c),f(!1)},$=ee=>{t(ee),f(!1)},q=(ee,Q)=>{Q.stopPropagation(),f(!1),S(ee)},B=(ee,Q)=>{Q.stopPropagation(),f(!1),_(ee)};return o.jsxs("div",{ref:N,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(CS,{className:"w-4 h-4"})}),d&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[o.jsxs("div",{className:"flex border-b border-border",children:[o.jsx("button",{type:"button",onClick:()=>{m("commands"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),o.jsx("button",{type:"button",onClick:()=>{m("workflows"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),o.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:E,value:x,onChange:ee=>J(ee.target.value),onKeyDown:z,placeholder:p==="commands"?"Search commands...":"Search workflows...",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),o.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:p==="commands"?Z.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:U.length===0?"No commands yet":"No matches"}):Z.map((ee,Q)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>I(ee.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:ee.name})}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:te=>q(ee.id,te)})]},ee.id)):p==="workflows"?H.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):H.map((ee,Q)=>{const te=t8(ee),Y=ee.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>$(ee.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:Y}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:ee.name}),te!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:te?"#22c55e":"#6b7280"},title:te?"Entry condition met":"Entry condition not met"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[ee.subGroups&&ee.subGroups.length>0&&o.jsx(r8,{subGroups:ee.subGroups,onSelect:F=>{f(!1),n(ee.id,F)}}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:F=>B(ee.id,F)})]})]},ee.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{l(),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(Nj,{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"})]})}),p!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{f(!1),p==="commands"?s():a()},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(BC,{isOpen:!!v,onClose:()=>S(null),initialEditId:v}),o.jsx(HC,{isOpen:!!b,onClose:()=>_(null),initialEditId:b})]})}function r8({subGroups:e,onSelect:t}){const[n,s]=L.useState(!1),[a,l]=L.useState({top:0,right:0}),u=L.useRef(null),c=L.useRef(null);PC(c,()=>s(!1),n);const d=f=>{if(f.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}s(!n)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{ref:u,type:"button",onClick:d,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&o.jsx(e8,{children:o.jsx("div",{ref:c,onMouseDown:f=>f.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(f=>o.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),t(f)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:f},f))})})]})}function s8({messages:e,onCancel:t}){return e.length===0?null:o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[o.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),o.jsx(Cl,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function i8({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:s,onView:a,onEdit:l,onDuplicate:u,onDelete:c}){const d=e.allowedTools.filter(f=>!(s!=null&&s.has(f)));return o.jsxs(MS,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:l,onDuplicate:u,onDelete:c,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[d.slice(0,5).map(f=>o.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:f},f)),d.length>5&&o.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",d.length-5," more"]})]})]})}function nS({title:e,agents:t,subagents:n,isBuiltIn:s,alwaysAllowedNames:a,onView:l,onDuplicate:u,onEdit:c,onDelete:d}){if(t.length===0&&n.length===0)return null;const f=p=>o.jsx(i8,{agent:p,isBuiltIn:s,isConfirmingDelete:!1,alwaysAllowedNames:a,onView:()=>l(p.id),onEdit:s?void 0:()=>c==null?void 0:c(p.id),onDuplicate:()=>u(p.id),onDelete:s?void 0:()=>d==null?void 0:d(p.id)},p.id);return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsxs("div",{className:"space-y-2",children:[t.map(f),n.length>0&&o.jsxs("div",{className:"mt-3",children:[o.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),o.jsx("div",{className:"space-y-2",children:n.map(f)})]})]})]})}function a8(e){const t=new Map;for(const n of e){const s=n.indexOf(":");if(s===-1)t.set(n,new Set);else{const a=n.slice(0,s),u=n.slice(s+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function jm(e){const t=[];for(const[n,s]of e)s.size===0?t.push(n):t.push(`${n}:${[...s].join(",")}`);return t}function o8({formName:e,formId:t,formDescription:n,formSubagent:s,formTools:a,formColor:l,formPrompt:u,formError:c,saving:d,isReadOnly:f,availableTools:p,onNameChange:m,onIdChange:x,onDescriptionChange:y,onSubagentChange:w,onToolsChange:C,onColorChange:v,onPromptChange:S,onSave:b,onCancel:_,onDuplicate:E}){const N=a8(a),T=p.filter(O=>!(s&&O.topLevelOnly)),D=(O,M)=>{const G=new Map(N),V=G.get(O)||new Set,R=new Set(V);R.has(M)?R.delete(M):R.add(M),R.size===0?G.set(O,new Set):G.set(O,R),C(jm(G))},A=O=>{const M=new Map(N);M.has(O)?M.delete(O):M.set(O,new Set),C(jm(M))};return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3",children:[c&&o.jsx(Wu,{message:c}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(vr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:f}),o.jsx(vr,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(vr,{label:"Description",value:n,onChange:y,placeholder:"What this agent does",readOnly:f}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),o.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[o.jsx("button",{onClick:()=>!f&&w(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${f?"pointer-events-none opacity-60":""}`,children:"Agent"}),o.jsx("button",{onClick:()=>!f&&w(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),o.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),o.jsx("input",{type:"color",value:l,onChange:O=>!f&&v(O.target.value),disabled:f,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),o.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:T.map(O=>{const M=N.has(O.name),G=O.actions.length>0,V=N.get(O.name)||new Set;return G?f?o.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[o.jsx("span",{children:O.name}),o.jsx("span",{className:"text-[10px]",children:"*"})]},O.name):o.jsx(wl,{trigger:o.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[o.jsx("span",{children:O.name}),G&&o.jsx("span",{className:`text-[10px] ${M&&V.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...O.actions.map(R=>({label:o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${O.name}-${R}`,children:[o.jsx("input",{type:"checkbox",id:`${O.name}-${R}`,checked:V.has(R),onChange:()=>D(O.name,R),disabled:f,className:"w-3 h-3 rounded accent-accent-primary"}),o.jsx("span",{children:R})]}),closeOnClick:!1})),{label:M?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(M)A(O.name);else{const R=new Map(N);R.set(O.name,new Set(O.actions)),C(jm(R))}}}]},O.name):o.jsx("button",{onClick:()=>!f&&A(O.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none":"cursor-pointer"}`,children:o.jsx("span",{children:O.name})},O.name)})})]})]}),o.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:u,onChange:O=>!f&&S(O.target.value),readOnly:f,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"opacity-60":""}`})]}),o.jsx(rN,{onCancel:_,onSave:b,saving:d,saveDisabled:!e||!u||f}),f&&o.jsx("div",{className:"flex justify-end mt-2",children:o.jsx("button",{onClick:E,className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})})]})}function l8(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function c8({isOpen:e,onClose:t,initialEditId:n}){const s=mt(_e=>_e.defaults),a=mt(_e=>_e.userItems),l=mt(_e=>_e.loading),u=mt(_e=>_e.fetchAgents),c=mt(_e=>_e.fetchAgent),d=mt(_e=>_e.fetchDefaultContent),f=mt(_e=>_e.createAgent),p=mt(_e=>_e.updateAgent),m=mt(_e=>_e.deleteAgent),[x,y]=L.useState("list"),[w,C]=L.useState(null),[v,S]=L.useState(!1),[b,_]=L.useState(""),[E,N]=L.useState(""),[T,D]=L.useState(""),[A,O]=L.useState(!0),[M,G]=L.useState([]),[V,R]=L.useState("#6b7280"),[U,W]=L.useState(""),[z,J]=L.useState(""),[Z,H]=L.useState(!1),[I,$]=L.useState([]),[q,B]=L.useState(new Set),ee=_e=>{_(_e.metadata.name),N(_e.metadata.id),D(_e.metadata.description),O(_e.metadata.subagent),G(_e.metadata.allowedTools),R(_e.metadata.color??"#6b7280"),W(_e.prompt),J("")},Q=(_e,ne,xe)=>{_(_e.metadata.name+" (copy)"),N(`${ne}-copy-${Date.now()}`),D(_e.metadata.description),O(_e.metadata.subagent),G(_e.metadata.allowedTools),R(_e.metadata.color??"#6b7280"),W(_e.prompt),J(""),C(null),S(!1),y("edit")},te=(_e,ne)=>{ee(_e),C(ne),S(!0),y("edit")};L.useEffect(()=>{e&&(u(),Ae("/api/tools").then(_e=>_e.json()).then(_e=>{const ne=_e.tools||[];B(new Set(ne.filter(xe=>xe.alwaysAllowed).map(xe=>xe.name))),$(ne.filter(xe=>!xe.alwaysAllowed))}).catch(()=>{$([]),B(new Set)}),n?s.some(ne=>ne.id===n)?d(n).then(ne=>{ne&&Q(ne,n)}):c(n).then(ne=>{ne&&(ee(ne),C(n),S(!1),y("edit"))}):(y("list"),C(null),S(!1)))},[e,u,c,d,n]);const Y=async _e=>{if(s.some(xe=>xe.id===_e)){const xe=await d(_e);if(!xe)return;te(xe,_e)}else{const xe=await c(_e);if(!xe)return;te(xe,_e)}},F=async _e=>{const ne=await d(_e);ne&&Q(ne,_e)},ue=()=>{C(null),_(""),N(""),D(""),O(!0),G(["read_file"]),R("#6b7280"),W(""),J(""),S(!1),y("edit")},oe=async _e=>{const ne=await c(_e);ne&&(ee(ne),C(_e),S(!1),y("edit"))},ke=async _e=>{await m(_e)},Se=async()=>{const _e=w??E;if(!_e||!b||!U){J("Name and prompt are required.");return}H(!0),J("");const ne={metadata:{id:_e,name:b,description:T,subagent:A,allowedTools:M.filter(He=>!q.has(He)),color:V},prompt:U},xe=w?await p(w,ne):await f(ne);if(H(!1),!xe.success){J(xe.error??"Failed to save agent.");return}n?t():y("list")},Te=()=>{n?t():(y("list"),S(!1))},fe=_e=>{_(_e),w||N(l8(_e))},ae=s.filter(_e=>_e.subagent),ce=s.filter(_e=>!_e.subagent),se=a.filter(_e=>_e.subagent),je=a.filter(_e=>!_e.subagent);return x==="edit"?o.jsx(Dt,{isOpen:e,onClose:Te,title:v?`${b}`:w?"Edit Agent":"New Agent",size:"xl",children:o.jsx(o8,{formName:b,formId:E,formDescription:T,formSubagent:A,formTools:M,formColor:V,formPrompt:U,formError:z,saving:Z,isReadOnly:v,availableTools:I,onNameChange:fe,onIdChange:N,onDescriptionChange:D,onSubagentChange:_e=>{O(_e),_e&&G(ne=>ne.filter(xe=>{var He;return!((He=I.find(Ze=>Ze.name===xe))!=null&&He.topLevelOnly)}))},onToolsChange:G,onColorChange:R,onPromptChange:W,onSave:Se,onCancel:Te,onDuplicate:()=>{_(b+" (copy)"),N(`${w}-copy-${Date.now()}`),C(null),S(!1)}})}):o.jsx(Dt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:o.jsx(RS,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ue,loading:l,hasItems:s.length>0||a.length>0,children:o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsx(nS,{title:"Built-in",agents:ce,subagents:ae,isBuiltIn:!0,alwaysAllowedNames:q,onView:Y,onDuplicate:F}),a.length>0&&o.jsx(nS,{title:"Custom",agents:je,subagents:se,isBuiltIn:!1,alwaysAllowedNames:q,onView:Y,onDuplicate:F,onEdit:oe,onDelete:ke})]})})})}function u8(){const e=Re(b=>{var _;return(_=b.currentSession)==null?void 0:_.mode}),t=Re(b=>b.switchMode),n=mt(b=>b.defaults),s=mt(b=>b.userItems),a=mt(b=>b.fetchAgents),l=[...n,...s],[u,c]=L.useState(!1),[d,f]=L.useState(!1),[p,m]=L.useState(null),x=L.useRef(null);L.useEffect(()=>{a()},[a]),L.useEffect(()=>{function b(_){x.current&&!x.current.contains(_.target)&&c(!1)}return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const y=Sp();if(!e)return null;const w=l.filter(b=>!b.subagent),C=w.find(b=>b.id===e),v=(C==null?void 0:C.name)??e,S=dl(l,e);return o.jsxs("div",{className:"relative",ref:x,children:[o.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[o.jsx("span",{className:"text-sm font-medium",style:{color:S},children:v}),o.jsx(Kn,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&o.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((b,_)=>{const E=b.id===e,N=dl(l,b.id),T=y.agentSwitching[_],D=T?TS(T):null;return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[o.jsxs("button",{type:"button",onClick:()=>{E||t(b.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"font-medium truncate",style:{color:N},children:b.name}),E&&o.jsx(Ir,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),D&&o.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:D})]},b.id)}),o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{c(!1),f(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),o.jsx(c8,{isOpen:d,onClose:()=>{f(!1),m(null)},initialEditId:p})]})}function d8(){const e=Re(s=>s.currentSession),t=Re(s=>s.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return o.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[o.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),o.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function rS({value:e,onChange:t}){return o.jsxs("div",{children:[o.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",o.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),o.jsx("input",{type:"text",value:e??"",onChange:n=>t(n.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]})}const h8=[8080,11434,8e3];function f8({model:e,modelConfigs:t,autoConfigState:n,testResults:s,onUpdateConfig:a,onRunAutoConfig:l,onTestParams:u,onShowRaw:c}){var d,f,p,m,x,y,w,C,v,S,b,_,E,N,T,D,A,O,M,G,V,R,U,W,z,J,Z,H,I,$,q,B,ee,Q,te,Y,F,ue,oe,ke,Se;return o.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:()=>l(e.id),disabled:n.progress[e.id]==="probing",className:"px-4 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:n.progress[e.id]==="probing"?"Probing...":"Auto-config"}),n.progress[e.id]==="done"&&o.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&o.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),o.jsxs("div",{className:"flex gap-3 items-end",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),o.jsx("input",{type:"number",value:((d=t[e.id])==null?void 0:d.contextWindow)??e.contextWindow,onChange:Te=>a(e.id,{contextWindow:parseInt(Te.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[o.jsx("input",{type:"checkbox",checked:((f=t[e.id])==null?void 0:f.supportsVision)??!1,onChange:Te=>a(e.id,{supportsVision:Te.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:()=>u(e.id,"thinking"),disabled:(p=s[e.id+"-thinking"])==null?void 0:p.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(m=s[e.id+"-thinking"])!=null&&m.loading?"Testing...":"Test thinking"}),((x=s[e.id+"-thinking"])==null?void 0:x.result)&&o.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((y=s[e.id+"-thinking"])==null?void 0:y.error)&&o.jsx("span",{className:"text-xs text-red-500",title:(w=s[e.id+"-thinking"])==null?void 0:w.error,children:"Fail"}),((C=s[e.id+"-thinking"])==null?void 0:C.result)&&o.jsx("button",{onClick:()=>c(s[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:()=>u(e.id,"non-thinking"),disabled:(v=s[e.id+"-non-thinking"])==null?void 0:v.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(S=s[e.id+"-non-thinking"])!=null&&S.loading?"Testing...":"Test non-thinking"}),((b=s[e.id+"-non-thinking"])==null?void 0:b.result)&&o.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((_=s[e.id+"-non-thinking"])==null?void 0:_.error)&&o.jsx("span",{className:"text-xs text-red-500",title:(E=s[e.id+"-non-thinking"])==null?void 0:E.error,children:"Fail"}),((N=s[e.id+"-non-thinking"])==null?void 0:N.result)&&o.jsx("button",{onClick:()=>c(s[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),o.jsxs("details",{className:"group",children:[o.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[o.jsx(Kn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((T=t[e.id])==null?void 0:T.thinkingEnabled)??!1,onChange:Te=>a(e.id,{thinkingEnabled:Te.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((D=t[e.id])==null?void 0:D.thinkingEnabled)&&o.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),o.jsx("input",{type:"text",value:((A=t[e.id])==null?void 0:A.thinkingLevel)??"",onChange:Te=>a(e.id,{thinkingLevel:Te.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsx(rS,{value:(O=t[e.id])==null?void 0:O.thinkingQueryParams,onChange:Te=>a(e.id,{thinkingQueryParams:Te})})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((M=t[e.id])==null?void 0:M.nonThinkingEnabled)??!1,onChange:Te=>a(e.id,{nonThinkingEnabled:Te.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((G=t[e.id])==null?void 0:G.nonThinkingEnabled)&&o.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:o.jsx(rS,{value:(V=t[e.id])==null?void 0:V.nonThinkingQueryParams,onChange:Te=>a(e.id,{nonThinkingQueryParams:Te})})})]}),o.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[o.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),o.jsx("input",{type:"number",step:"0.1",value:((R=t[e.id])==null?void 0:R.temperature)??"",onChange:Te=>a(e.id,{temperature:Te.target.value?parseFloat(Te.target.value):void 0}),placeholder:((W=(U=t[e.id])==null?void 0:U.defaultTemperature)==null?void 0:W.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((z=t[e.id])==null?void 0:z.defaultTemperature)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(J=t[e.id])==null?void 0:J.defaultTemperature]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),o.jsx("input",{type:"number",step:"0.05",value:((Z=t[e.id])==null?void 0:Z.topP)??"",onChange:Te=>a(e.id,{topP:Te.target.value?parseFloat(Te.target.value):void 0}),placeholder:((I=(H=t[e.id])==null?void 0:H.defaultTopP)==null?void 0:I.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),(($=t[e.id])==null?void 0:$.defaultTopP)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(q=t[e.id])==null?void 0:q.defaultTopP]})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),o.jsx("input",{type:"number",value:((B=t[e.id])==null?void 0:B.topK)??"",onChange:Te=>a(e.id,{topK:Te.target.value?parseInt(Te.target.value):void 0}),placeholder:((Q=(ee=t[e.id])==null?void 0:ee.defaultTopK)==null?void 0:Q.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((te=t[e.id])==null?void 0:te.defaultTopK)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Y=t[e.id])==null?void 0:Y.defaultTopK]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),o.jsx("input",{type:"number",value:((F=t[e.id])==null?void 0:F.maxTokens)??"",onChange:Te=>a(e.id,{maxTokens:Te.target.value?parseInt(Te.target.value):void 0}),placeholder:((oe=(ue=t[e.id])==null?void 0:ue.defaultMaxTokens)==null?void 0:oe.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((ke=t[e.id])==null?void 0:ke.defaultMaxTokens)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Se=t[e.id])==null?void 0:Se.defaultMaxTokens]})]})]})]})]})]})}function qC({isOpen:e,onClose:t,onSave:n,initialStep:s=1,editProvider:a,editModelId:l}){const[u,c]=L.useState(s),[d,f]=L.useState(""),[p,m]=L.useState(""),[x,y]=L.useState("unknown"),[w,C]=L.useState(""),[v,S]=L.useState(!1),[b,_]=L.useState(!1),[E,N]=L.useState(null),[T,D]=L.useState([]),[A,O]=L.useState(null),[M,G]=L.useState(!1),[V,R]=L.useState(""),[U,W]=L.useState({}),[z,J]=L.useState({loading:!1,progress:{}}),[Z,H]=L.useState({}),[I,$]=L.useState(null),[q,B]=L.useState(new Set),[ee,Q]=L.useState(""),te=L.useRef(null);L.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var fe;return(fe=te.current)==null?void 0:fe.focus()})},[u,e]);function Y(fe,ae){W(ce=>({...ce,[fe]:{...ce[fe],...ae}}))}function F(fe){if(!fe.trim())return T;const ae=fe.toLowerCase().split(/\s+/).filter(Boolean);return T.filter(ce=>ae.every(se=>ce.id.toLowerCase().includes(se)))}L.useEffect(()=>{var fe,ae;if(e)if(c(s),f((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),y((a==null?void 0:a.backend)??"unknown"),C((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),N(null),R((a==null?void 0:a.thinkingField)??""),H({}),$(null),(fe=a==null?void 0:a.models)!=null&&fe.length){const ce={},se=new Set;for(const je of a.models)ce[je.id]={contextWindow:je.contextWindow,supportsVision:je.supportsVision,thinkingEnabled:je.thinkingEnabled,thinkingLevel:je.thinkingLevel,nonThinkingEnabled:je.nonThinkingEnabled,thinkingQueryParams:je.thinkingQueryParams,nonThinkingQueryParams:je.nonThinkingQueryParams,defaultTemperature:je.defaultTemperature,defaultTopP:je.defaultTopP,defaultTopK:je.defaultTopK,defaultMaxTokens:je.defaultMaxTokens},je.selected&&se.add(je.id);if(se.size===0)for(const je of a.models)se.add(je.id);B(se),W(ce),D(a.models.map(je=>({id:je.id,contextWindow:je.contextWindow}))),O(l??((ae=a.models[0])==null?void 0:ae.id)??null)}else D([]),W({}),O(null),B(new Set)},[e,s,a==null?void 0:a.id,l]),L.useEffect(()=>{u===2&&p&&T.length===0&&!b&&!E&&ue(p)},[u]);async function ue(fe){var ae,ce;_(!0),N(null),D([]);try{const se=new URLSearchParams({url:fe});w&&se.set("apiKey",w);const je=await Ae(`/api/providers/models?${se.toString()}`);if(je.ok){const _e=await je.json();if((ae=_e.models)!=null&&ae.length){D(_e.models),O(((ce=_e.models[0])==null?void 0:ce.id)??null);const ne={};for(const xe of _e.models)ne[xe.id]={contextWindow:xe.contextWindow,thinkingEnabled:!0,thinkingLevel:void 0,defaultTemperature:xe.defaultTemperature,defaultTopP:xe.defaultTopP,defaultTopK:xe.defaultTopK,defaultMaxTokens:xe.defaultMaxTokens};W(ne),_e.models.length===1&&(B(new Set([_e.models[0].id])),O(_e.models[0].id),oe(_e.models[0].id))}}else{const _e=await je.json();N(_e.error??`Failed to fetch models from ${fe}`)}}catch(se){N(`Failed to fetch models from ${fe}: ${se instanceof Error?se.message:"Unknown error"}`)}_(!1)}async function oe(fe){J(ae=>({loading:!0,progress:{...ae.progress,[fe]:"probing"}}));try{const ae=await Ae("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,apiKey:w||void 0,backend:x||"unknown",models:[{id:fe}]})});if(!ae.ok){const se=await ae.json();throw new Error(se.error??"Auto-config failed")}const ce=await ae.json();for(const se of ce.models){const je={};se.contextSource!=="default"&&(je.contextWindow=se.contextWindow,je.supportsVision=se.supportsVision),se.thinkingConfig&&(je.thinkingEnabled=!0,je.thinkingQueryParams=JSON.stringify(se.thinkingConfig)),se.nonThinkingConfig&&(je.nonThinkingEnabled=!0,je.nonThinkingQueryParams=JSON.stringify(se.nonThinkingConfig)),Y(se.id,je),J(_e=>({..._e,progress:{..._e.progress,[se.id]:"done"}}))}}catch(ae){console.error("Auto-config error:",ae),J(ce=>({...ce,progress:{...ce.progress,[fe]:"error"}}))}finally{J(ae=>({...ae,loading:!1}))}}async function ke(fe,ae){const ce=fe+"-"+ae;H(se=>({...se,[ce]:{loading:!0}}));try{const se=U[fe],je=await Ae("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,model:fe,apiKey:w||void 0,backend:x||"unknown",thinkingField:V||void 0,mode:ae,modelConfig:{temperature:se==null?void 0:se.temperature,topP:se==null?void 0:se.topP,topK:se==null?void 0:se.topK,maxTokens:se==null?void 0:se.maxTokens,supportsVision:se==null?void 0:se.supportsVision,thinkingEnabled:se==null?void 0:se.thinkingEnabled,thinkingLevel:se==null?void 0:se.thinkingLevel,nonThinkingEnabled:se==null?void 0:se.nonThinkingEnabled,thinkingQueryParams:se==null?void 0:se.thinkingQueryParams,nonThinkingQueryParams:se==null?void 0:se.nonThinkingQueryParams}})}),_e=await je.json();je.ok?H(ne=>({...ne,[ce]:{loading:!1,result:JSON.stringify(_e,null,2),message:_e.message}})):H(ne=>({...ne,[ce]:{loading:!1,error:_e.error??"Test failed"}}))}catch(se){H(je=>({...je,[ce]:{loading:!1,error:se instanceof Error?se.message:"Request failed"}}))}}function Se(){D([]),W({}),J({loading:!1,progress:{}}),H({}),$(null),B(new Set),Q("")}function Te(){const fe=d||"Provider",ae=(a==null?void 0:a.id)??`temp-${Date.now()}`;n({id:ae,name:fe,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:v||void 0,thinkingField:V||void 0,models:T.map(ce=>{var se,je,_e,ne,xe,He,Ze,rt,kt,ge,Ne;return{id:ce.id,contextWindow:((se=U[ce.id])==null?void 0:se.contextWindow)??ce.contextWindow,selected:q.has(ce.id)||void 0,supportsVision:(je=U[ce.id])==null?void 0:je.supportsVision,thinkingEnabled:(_e=U[ce.id])==null?void 0:_e.thinkingEnabled,thinkingLevel:(ne=U[ce.id])==null?void 0:ne.thinkingLevel,nonThinkingEnabled:(xe=U[ce.id])==null?void 0:xe.nonThinkingEnabled,thinkingQueryParams:(He=U[ce.id])==null?void 0:He.thinkingQueryParams,nonThinkingQueryParams:(Ze=U[ce.id])==null?void 0:Ze.nonThinkingQueryParams,temperature:(rt=U[ce.id])==null?void 0:rt.temperature,topP:(kt=U[ce.id])==null?void 0:kt.topP,topK:(ge=U[ce.id])==null?void 0:ge.topK,maxTokens:(Ne=U[ce.id])==null?void 0:Ne.maxTokens}})}),t()}return e?o.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:fe=>{fe.target===fe.currentTarget&&t()},children:[o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),o.jsx("button",{onClick:t,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2].map(fe=>o.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${fe<u?"bg-accent-success":fe===u?"bg-accent-primary":"bg-border"}`},fe))}),u===1&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),o.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[o.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),N(null)},className:`p-2 rounded border text-center text-sm transition-colors ${x==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),h8.map(fe=>{const ae={8e3:"vllm",11434:"ollama",8080:"llamacpp"},ce={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp"};return o.jsx("button",{type:"button",onClick:()=>{f(se=>se||(ce[fe]??"")),m(se=>se||`http://localhost:${fe}`),y(ae[fe]??""),S(!0),N(null)},className:`p-2 rounded border text-center text-sm transition-colors ${x===ae[fe]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ce[fe]??`localhost:${fe}`},fe)})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),o.jsx("input",{ref:te,type:"text",value:p,"data-testid":"provider-modal-url",onChange:fe=>{m(fe.target.value),N(null),D([]),W({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),o.jsx("input",{type:"text",autoComplete:"off",value:d,onChange:fe=>f(fe.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:fe=>C(fe.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:v,onChange:fe=>S(fe.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),o.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[b&&o.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[o.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),E&&o.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[o.jsx("p",{children:E}),o.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),o.jsxs("div",{className:"flex gap-2 mt-2",children:[o.jsx("button",{onClick:()=>ue(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),o.jsx("button",{onClick:()=>{Se(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),T.length>0&&x&&o.jsxs(o.Fragment,{children:[q.size>0&&o.jsxs("div",{className:"mb-4",children:[o.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",q.size,")"]}),o.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),o.jsx("div",{className:"space-y-2",children:T.filter(fe=>q.has(fe.id)).map(fe=>{var ae;return o.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[o.jsxs("div",{onClick:()=>O(A===fe.id?null:fe.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-sm font-medium text-text-primary",children:fe.id.split("/").pop()}),o.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((ae=U[fe.id])==null?void 0:ae.contextWindow)??fe.contextWindow).toLocaleString()," ctx"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[z.progress[fe.id]==="probing"?o.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):z.progress[fe.id]==="done"?o.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):z.progress[fe.id]==="error"?o.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):o.jsx("button",{onClick:ce=>{ce.stopPropagation(),oe(fe.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),T.length>1&&o.jsx("button",{onClick:ce=>{ce.stopPropagation();const se=new Set(q);se.delete(fe.id),B(se),A===fe.id&&O(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),o.jsx(Kn,{className:`w-4 h-4 text-text-muted transition-transform ${A===fe.id?"rotate-180":""}`})]})]}),A===fe.id&&o.jsx(f8,{model:fe,modelConfigs:U,autoConfigState:z,testResults:Z,onUpdateConfig:Y,onRunAutoConfig:oe,onTestParams:ke,onShowRaw:$})]},fe.id)})})]}),T.length>1&&o.jsxs("div",{children:[o.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),q.size===0&&o.jsx("p",{className:"text-xs text-text-muted mb-2",children:"This provider has many models available. Select the ones you want to use below."}),o.jsxs("div",{className:"relative mb-2",children:[o.jsx("input",{type:"text",value:ee,onChange:fe=>Q(fe.target.value),placeholder:"Search models...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),ee&&o.jsx("button",{onClick:()=>Q(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",F(ee).length," of ",T.length," models"]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:()=>{const fe=new Set(q),ae=F(ee);for(const ce of ae)fe.add(ce.id);B(fe);for(const ce of ae)z.progress[ce.id]!=="probing"&&z.progress[ce.id]!=="done"&&oe(ce.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),o.jsx("button",{onClick:()=>{const fe=new Set(q),ae=F(ee);for(const ce of ae)fe.delete(ce.id);B(fe)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),o.jsxs("div",{className:"space-y-1 max-h-48 overflow-y-auto border border-border rounded-lg bg-bg-primary",children:[F(ee).map(fe=>{var ce;const ae=q.has(fe.id);return o.jsxs("div",{role:"checkbox","aria-checked":ae,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${ae?"bg-accent-primary/5":""}`,onClick:()=>{if(ae){const se=new Set(q);se.delete(fe.id),B(se)}else{const se=new Set(q);se.add(fe.id),B(se),oe(fe.id)}},onKeyDown:se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),se.currentTarget.click())},children:[o.jsx("input",{type:"checkbox",checked:ae,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),o.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:fe.id.split("/").pop()}),o.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((ce=U[fe.id])==null?void 0:ce.contextWindow)??fe.contextWindow).toLocaleString()," ctx"]}),z.progress[fe.id]==="probing"&&o.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),z.progress[fe.id]==="done"&&o.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),z.progress[fe.id]==="error"&&o.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},fe.id)}),F(ee).length===0&&o.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",ee,"”"]})]})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[o.jsx("div",{children:u>1&&o.jsx("button",{onClick:()=>{u===2&&Se(),c(u-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u===1?o.jsx("button",{onClick:()=>c(2),disabled:!p,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:"Next — Test & Configure"}):o.jsx("button",{onClick:Te,disabled:z.loading,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:z.loading?"Configuring...":"Save Provider"})]})]})]}),M&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:fe=>{fe.target===fe.currentTarget&&G(!1)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),o.jsx("button",{onClick:()=>G(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'{"chat_template_kwargs":{"enable_thinking":false}}',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",o.jsx("span",{className:"text-text-muted",children:"(override)"})]}),o.jsx("input",{type:"text",value:V,onChange:fe=>R(fe.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),o.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]})]}),o.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:o.jsx("button",{onClick:()=>G(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})})]})}),I&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:fe=>{fe.target===fe.currentTarget&&$(null)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[80vh] shadow-2xl flex flex-col",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border shrink-0",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),o.jsx("button",{onClick:()=>$(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:I})]})})]}):null}function m8(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function p8(){var fe;const[,e]=qn(),t=Re(ae=>ae.currentSession),n=Re(ae=>ae.setSessionProvider),[s,a]=L.useState(!1),[l,u]=L.useState([]),[c,d]=L.useState(null),f=L.useRef(null),[p,m]=L.useState(null),[x,y]=L.useState(!1),w=L.useRef(new Set),C=nn(ae=>ae.providers),v=nn(ae=>ae.activeProviderId),S=nn(ae=>ae.defaultModelSelection),b=nn(ae=>ae.activating),_=nn(ae=>ae.activateProvider),E=nn(ae=>ae.refreshModel),N=nn(ae=>ae.refreshProviderModels),T=nn(ae=>ae.setDefaultModel),D=(t==null?void 0:t.providerId)??null,A=(t==null?void 0:t.providerModel)??null,O=(S==null?void 0:S.split("/")[0])??null,M=(S==null?void 0:S.split("/").slice(1).join("/"))??null,G=D??O,V=A??M,R=V?((fe=V.split("/").pop())==null?void 0:fe.replace(/-/g," "))??V:"No model",W=!!(t&&A)&&A!==M,[z,J]=L.useState(!1);L.useEffect(()=>{function ae(ce){f.current&&!f.current.contains(ce.target)&&(a(!1),u([]),w.current=new Set)}return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[]),L.useEffect(()=>{if(s){const ae=C.map(ce=>ce.id);u(ae),ae.forEach(ce=>{w.current.has(ce)||(w.current.add(ce),q(ce))})}},[s,C]);const Z=C.find(ae=>ae.id===G),H=(Z==null?void 0:Z.status)==="disconnected",I=(ae,ce)=>t?t.providerId===ae&&t.providerModel===ce:!1,$=(ae,ce)=>S?S===`${ae}/${ce}`:!1,q=async ae=>{d(ae);try{await N(ae)}catch{}finally{d(null)}},B=ae=>{l.includes(ae.id)?u(l.filter(ce=>ce!==ae.id)):(u([...l,ae.id]),q(ae.id))},ee=async ae=>{if(ae.id===v){B(ae);return}t?(n(ae.id,void 0),a(!1),u([])):await _(ae.id)&&(a(!1),u([]))},Q=ae=>{B(ae)},te=async(ae,ce)=>{ae.stopPropagation(),w.current.delete(ce),await q(ce)},Y=(ae,ce)=>{m({providerId:ae,model:ce}),y(!0)},F=p?C.find(ae=>ae.id===p.providerId):void 0,ue=()=>{m(null),y(!1)},oe=async ae=>{try{if(!(await Ae(`/api/providers/${ae.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ae.name,url:ae.url,backend:ae.backend,apiKey:ae.apiKey,isLocal:ae.isLocal,thinkingField:ae.thinkingField,models:ae.models})})).ok)throw new Error("Failed to update provider");await nn.getState().fetchConfig()}catch{}m(null),y(!1)},ke=async(ae,ce)=>{if(t){Re.setState(je=>({currentSession:je.currentSession?{...je.currentSession,providerId:ae,providerModel:ce}:null})),n(ae,ce),u([]),a(!1);return}await _(ae)&&(u([]),a(!1))},Se=async(ae,ce,se)=>{ae.stopPropagation(),J(!0);try{await T(ce,se)}catch{}finally{J(!1)}};function Te(ae){return ae.models.some(se=>se.selected)?ae.models.filter(se=>se.selected):ae.models}return C.length===0?o.jsxs("button",{type:"button",onClick:()=>E(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:H?"LLM server is offline. Click to retry.":R??"Click to refresh model",children:[H?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-accent-primary",children:R}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${Z!=null&&Z.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:Z!=null&&Z.isLocal?"local":"api"})]}),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:()=>a(!s),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:[H?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:`text-sm ${W?"text-accent-primary italic":"text-accent-primary"}`,children:R}),W&&o.jsx("span",{className:"text-xs text-text-muted ml-0.5",title:"Session-scoped model (different from default)",children:"•"}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${Z!=null&&Z.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:Z!=null&&Z.isLocal?"local":"api"})]}),o.jsx(Kn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:s?180:0})]}),s&&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:C.map(ae=>{var ce;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${ae.id===G?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${b?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!b&&ee(ae),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${ae.id===G?"text-accent-primary":"text-text-primary"}`,children:ae.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:ae.backend!=="unknown"&&pS(ae.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ae.id===G?o.jsx("span",{className:"text-accent-success",title:"Active provider",children:o.jsx(Ir,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),te(se,ae.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(vp,{className:`w-4 h-4 ${c===ae.id?"animate-spin":""} ${ae.id===v?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),Q(ae)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(Kn,{className:`w-4 h-4 transition-transform ${l.includes(ae.id)?"rotate-180":""} ${ae.id===v?"text-accent-primary":"text-text-muted"}`})})]})]}),l.includes(ae.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===ae.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(ce=ae.models)!=null&&ce.length?Te(ae).map(se=>{var ne;const je=I(ae.id,se.id),_e=$(ae.id,se.id);return o.jsxs("div",{className:`flex items-center px-4 py-1.5 text-sm hover:bg-bg-tertiary transition-colors group ${c==="activating"?"opacity-50 cursor-wait":""} ${je?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("button",{type:"button",onClick:()=>ke(ae.id,se.id),disabled:c==="activating",className:"flex-1 truncate text-left",children:((ne=se.id.split("/").pop())==null?void 0:ne.replace(/-/g," "))??se.id}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0 ml-2",children:[o.jsx("span",{className:"text-xs text-text-muted",children:m8(se.contextWindow)}),t&&o.jsx("button",{type:"button",onClick:xe=>Se(xe,ae.id,se.id),disabled:z,className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors disabled:opacity-40",title:_e?"Default model":"Set as default model",children:_e?o.jsx(kS,{className:"w-3.5 h-3.5 text-accent-warning"}):o.jsx(ES,{className:"w-3.5 h-3.5 text-text-muted hover:text-accent-warning"})}),o.jsx("button",{type:"button",onClick:xe=>{xe.stopPropagation(),Y(ae.id,se)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(Dj,{className:"w-3 h-3 text-text-muted"})}),je&&o.jsx("span",{className:"text-accent-success flex-shrink-0",title:"Session model",children:o.jsx(Ir,{className:"w-3.5 h-3.5"})})]})]},se.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},ae.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"})})]}),p&&x&&o.jsx(qC,{isOpen:!0,onClose:ue,onSave:oe,initialStep:2,editProvider:{id:p.providerId,name:(F==null?void 0:F.name)??"",url:(F==null?void 0:F.url)??"",backend:(F==null?void 0:F.backend)??"unknown",apiKey:F==null?void 0:F.apiKey,isLocal:F==null?void 0:F.isLocal,thinkingField:F==null?void 0:F.thinkingField,models:F==null?void 0:F.models},editModelId:p.model.id})]})}function g8(e,t){const n=e.slice(0,t),s=n.lastIndexOf("@");if(s===-1)return null;const a=n.slice(s+1);return a.includes(" ")||a.includes(`
|
|
297
|
+
`,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))})}function UB(){const e=_j(),t=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 ${t}`,style:{animationDelay:"0ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,style:{animationDelay:"150ms"}}),o.jsx("span",{className:`w-1 h-1 rounded-full animate-bounce ${t}`,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"})]})}const FB={maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576};async function VB(e,t={}){const n={...FB,...t};if(!e.type.startsWith("image/"))throw new Error("File is not an image");if(!["image/png","image/jpeg","image/gif"].includes(e.type))throw new Error(`Unsupported image format: ${e.type}. Only PNG, JPG, and GIF are supported.`);if(e.size<=n.maxSizeBytes){const a=await e.arrayBuffer(),l=QB(a),u=`data:${e.type};base64,${l}`,c=await GC(u);return{dataUrl:u,mimeType:e.type,size:e.size,width:c.width,height:c.height}}return await GB(e,n)}async function GB(e,t){const n=await qB(e),s=await GC(n),{width:a,height:l}=WB(s.width,s.height,t.maxWidth,t.maxHeight),u=KB();u.width=a,u.height=l;const c=u.getContext("2d");if(!c)throw new Error("Failed to get canvas context");c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(s,0,0,a,l);let d=t.quality,f="";for(let m=0;m<10&&(f=u.toDataURL(e.type.startsWith("image/gif")?"image/png":e.type,d),!(eS(f)<=t.maxSizeBytes||d<=.3));m++)d-=.1;const p=eS(f);return{dataUrl:f,mimeType:e.type.startsWith("image/gif")?"image/png":e.type,size:p,width:a,height:l}}function WB(e,t,n,s){const a=e/t;return e>t&&e>n?{width:n,height:Math.round(n/a)}:t>e&&t>s?{width:Math.round(s*a),height:s}:{width:e,height:t}}function qB(e){return new Promise((t,n)=>{const s=XB(),a=new s;a.onload=()=>t(a.result),a.onerror=()=>n(new Error("Failed to read file")),a.readAsDataURL(e)})}function GC(e){return new Promise((t,n)=>{const s=YB(),a=new s;a.onload=()=>t(a),a.onerror=()=>n(new Error("Failed to load image")),a.src=e})}function KB(){var t;const e=gg();if(!((t=e.document)!=null&&t.createElement))throw new Error("Image compression requires browser canvas APIs");return e.document.createElement("canvas")}function YB(){const e=gg();if(!e.Image)throw new Error("Image compression requires browser image APIs");return e.Image}function XB(){const e=gg();if(!e.FileReader)throw new Error("Image compression requires browser file APIs");return e.FileReader}function gg(){return globalThis}function QB(e){const t=new Uint8Array(e);let n="";for(let s=0;s<t.byteLength;s++){const a=t[s];a!==void 0&&(n+=String.fromCharCode(a))}return btoa(n)}function eS(e){const n=e.split(",")[1];return n?Math.round(n.length*3/4):0}function JB(e){return["image/png","image/jpeg","image/gif"].includes(e.type)}function ZB(e,t=50*1024*1024){return e.size>t?{valid:!1,error:`Image file is too large (${tS(e.size)}). Maximum size is ${tS(t)}.`}:{valid:!0}}function tS(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function Em(e,t,n,s={}){const{maxSizeBytes:a=50*1024*1024,filename:l}=s;if(!JB(e)){n(`Unsupported file type: ${e.type}. Only PNG, JPG, and GIF are supported.`);return}const u=ZB(e,a);if(!u.valid){n(u.error??"Image file is too large");return}try{const c=await VB(e,{maxWidth:1920,maxHeight:1920,quality:.85,maxSizeBytes:1048576}),d={id:mS(),filename:l??e.name,mimeType:c.mimeType,size:c.size,data:c.dataUrl};t(d)}catch(c){const d=c instanceof Error?c.message??"Failed to process image":"Failed to process image";n(d)}}function WC(e){const t=Re(l=>l.sendMessage),n=Re(l=>l.launchWorkflow),s=L.useCallback((l,u,c)=>{e(!0),t(l,u,c)},[e,t]),a=L.useCallback((l,u,c,d)=>{e(!0),n(l,u,c,d)},[e,n]);return{sendMessage:s,launchWorkflow:a}}function e8({children:e}){return Ga.createPortal(e,document.body)}function t8(e){const t=e.startCondition;if(!t||t.type==="always")return!0;switch(t.type){case"step_result":case"metadata_all_match":case"metadata_all_in":return null;default:return null}}function n8({onSendCommand:e,onSelectWorkflow:t,onSelectWorkflowWithSubGroup:n,onOpenCommandsManager:s,onOpenWorkflowsManager:a,onAttach:l,textareaContent:u,attachments:c}){const[d,f]=L.useState(!1),[p,m]=L.useState("commands"),[x,y]=L.useState(""),[w,C]=L.useState(0),[v,S]=L.useState(null),[b,_]=L.useState(null),E=L.useRef(null),N=L.useRef(null),T=en(ee=>ee.defaults),D=en(ee=>ee.userItems),A=en(ee=>ee.projectItems),O=en(ee=>ee.fetchCommands),M=Ct(ee=>ee.defaults),G=Ct(ee=>ee.userItems),V=Ct(ee=>ee.projectItems),R=Ct(ee=>ee.fetchWorkflows),U=Or(Or(T,D),A),W=Or(Or(M,G),V);L.useEffect(()=>{d&&(p==="commands"?O():p==="workflows"&&R())},[d,p,O,R]),L.useEffect(()=>{d&&(y(""),C(0),requestAnimationFrame(()=>{var ee;return(ee=E.current)==null?void 0:ee.focus()}))},[d,p]),L.useEffect(()=>{if(!d)return;const ee=Q=>{var te;(te=N.current)!=null&&te.contains(Q.target)||f(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[d]);const z=ee=>{switch(ee.key){case"ArrowDown":ee.preventDefault(),C(Q=>{const Y=(p==="commands"?U:W).filter(F=>{const ue=x.toLowerCase();return!ue||F.name.toLowerCase().includes(ue)});return Math.min(Q+1,Y.length-1)});break;case"ArrowUp":ee.preventDefault(),C(Q=>Math.max(Q-1,0));break;case"Enter":ee.preventDefault();break;case"Escape":ee.preventDefault(),f(!1);break}},J=ee=>{y(ee),C(0)},Z=U.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),H=W.filter(ee=>!x||ee.name.toLowerCase().includes(x.toLowerCase())),I=async ee=>{const Q=await en.getState().fetchCommand(ee);Q&&e(Q.prompt,Q.metadata.agentMode,u,c),f(!1)},$=ee=>{t(ee),f(!1)},q=(ee,Q)=>{Q.stopPropagation(),f(!1),S(ee)},B=(ee,Q)=>{Q.stopPropagation(),f(!1),_(ee)};return o.jsxs("div",{ref:N,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(CS,{className:"w-4 h-4"})}),d&&o.jsxs("div",{className:"absolute bottom-full right-0 mb-1 w-80 max-w-[calc(100vw-2rem)] bg-bg-secondary border border-border rounded-lg shadow-xl z-50 overflow-hidden",children:[o.jsxs("div",{className:"flex border-b border-border",children:[o.jsx("button",{type:"button",onClick:()=>{m("commands"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="commands"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Commands"}),o.jsx("button",{type:"button",onClick:()=>{m("workflows"),y(""),C(0)},className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="workflows"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Workflows"}),o.jsx("button",{type:"button",onClick:()=>m("attach"),className:`flex-1 px-4 py-2 text-sm font-medium transition-colors ${p==="attach"?"text-accent-primary border-b-2 border-accent-primary":"text-text-muted hover:text-text-primary"}`,children:"Attach"})]}),p!=="attach"&&o.jsx("div",{className:"p-2 border-b border-border",children:o.jsx("input",{ref:E,value:x,onChange:ee=>J(ee.target.value),onKeyDown:z,placeholder:p==="commands"?"Search commands...":"Search workflows...",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary"})}),o.jsx("div",{className:"overflow-y-auto max-h-64 p-1",children:p==="commands"?Z.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:U.length===0?"No commands yet":"No matches"}):Z.map((ee,Q)=>o.jsxs("div",{className:`flex items-center gap-1 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsx("button",{type:"button",onClick:()=>I(ee.id),className:"flex-1 text-left",children:o.jsx("div",{className:"text-sm text-text-primary font-medium",children:ee.name})}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:te=>q(ee.id,te)})]},ee.id)):p==="workflows"?H.length===0?o.jsx("div",{className:"px-3 py-2 text-text-muted text-sm",children:W.length===0?"No workflows yet":"No matches"}):H.map((ee,Q)=>{const te=t8(ee),Y=ee.color??"#3b82f6";return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 rounded transition-colors group ${Q===w?"bg-accent-primary/20":"hover:bg-bg-tertiary"}`,children:[o.jsxs("button",{type:"button",onClick:()=>$(ee.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:Y}}),o.jsx("span",{className:"text-sm text-text-primary font-medium flex-1",children:ee.name}),te!==null&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:te?"#22c55e":"#6b7280"},title:te?"Entry condition met":"Entry condition not met"})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[ee.subGroups&&ee.subGroups.length>0&&o.jsx(r8,{subGroups:ee.subGroups,onSelect:F=>{f(!1),n(ee.id,F)}}),o.jsx(Fs,{className:"opacity-0 group-hover:opacity-100",onClick:F=>B(ee.id,F)})]})]},ee.id)}):o.jsxs("div",{className:"p-4 flex flex-col items-center gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>{l(),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(Nj,{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"})]})}),p!=="attach"&&o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{f(!1),p==="commands"?s():a()},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:p==="commands"?"Manage Commands...":"Manage Workflows..."})})]}),o.jsx(BC,{isOpen:!!v,onClose:()=>S(null),initialEditId:v}),o.jsx(HC,{isOpen:!!b,onClose:()=>_(null),initialEditId:b})]})}function r8({subGroups:e,onSelect:t}){const[n,s]=L.useState(!1),[a,l]=L.useState({top:0,right:0}),u=L.useRef(null),c=L.useRef(null);PC(c,()=>s(!1),n);const d=f=>{if(f.stopPropagation(),!n&&u.current){const p=u.current.getBoundingClientRect();l({top:p.bottom+4,right:window.innerWidth-p.right})}s(!n)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{ref:u,type:"button",onClick:d,className:"p-1 rounded text-text-muted hover:text-text-primary transition-colors",title:"Sub-groups",children:"⋮"}),n&&o.jsx(e8,{children:o.jsx("div",{ref:c,onMouseDown:f=>f.stopPropagation(),className:"fixed w-40 bg-bg-secondary border border-border rounded-lg shadow-xl z-[100] overflow-hidden",style:{top:a.top,right:a.right},children:e.map(f=>o.jsx("button",{type:"button",onClick:p=>{p.stopPropagation(),t(f)},className:"w-full text-left px-3 py-2 text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:f},f))})})]})}function s8({messages:e,onCancel:t}){return e.length===0?null:o.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:e.map(n=>o.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-xs ${n.mode==="asap"?"bg-amber-500/15 text-amber-300 border border-amber-500/30":"bg-blue-500/15 text-blue-300 border border-blue-500/30"}`,children:[o.jsxs("span",{className:"font-medium",children:[n.mode==="asap"?"ASAP":"Queue",":"]}),o.jsx("span",{className:"truncate max-w-[200px]",children:n.content}),o.jsx(Cl,{onClick:()=>t(n.queueId),size:"sm"})]},n.queueId))})}function i8({agent:e,isBuiltIn:t,isConfirmingDelete:n,alwaysAllowedNames:s,onView:a,onEdit:l,onDuplicate:u,onDelete:c}){const d=e.allowedTools.filter(f=>!(s!=null&&s.has(f)));return o.jsxs(MS,{isBuiltIn:t,isConfirmingDelete:n,onView:a,onEdit:l,onDuplicate:u,onDelete:c,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0",style:{backgroundColor:e.color??"#6b7280"}}),o.jsx("span",{className:"text-text-primary text-sm font-medium",children:e.name}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e.id}),t&&o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-bg-primary text-text-muted",children:"Built-in"})]}),e.description&&o.jsx("p",{className:"text-text-secondary text-xs mt-0.5 truncate",children:e.description}),o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[d.slice(0,5).map(f=>o.jsx("span",{className:"text-[10px] font-mono text-text-muted bg-bg-primary px-1 py-0.5 rounded",children:f},f)),d.length>5&&o.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",d.length-5," more"]})]})]})}function nS({title:e,agents:t,subagents:n,isBuiltIn:s,alwaysAllowedNames:a,onView:l,onDuplicate:u,onEdit:c,onDelete:d}){if(t.length===0&&n.length===0)return null;const f=p=>o.jsx(i8,{agent:p,isBuiltIn:s,isConfirmingDelete:!1,alwaysAllowedNames:a,onView:()=>l(p.id),onEdit:s?void 0:()=>c==null?void 0:c(p.id),onDuplicate:()=>u(p.id),onDelete:s?void 0:()=>d==null?void 0:d(p.id)},p.id);return o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:e}),o.jsxs("div",{className:"space-y-2",children:[t.map(f),n.length>0&&o.jsxs("div",{className:"mt-3",children:[o.jsx("div",{className:"text-xs text-text-muted uppercase tracking-wider mb-1.5",children:"Sub-agents"}),o.jsx("div",{className:"space-y-2",children:n.map(f)})]})]})]})}function a8(e){const t=new Map;for(const n of e){const s=n.indexOf(":");if(s===-1)t.set(n,new Set);else{const a=n.slice(0,s),u=n.slice(s+1).split(",").filter(Boolean);t.set(a,new Set(u))}}return t}function jm(e){const t=[];for(const[n,s]of e)s.size===0?t.push(n):t.push(`${n}:${[...s].join(",")}`);return t}function o8({formName:e,formId:t,formDescription:n,formSubagent:s,formTools:a,formColor:l,formPrompt:u,formError:c,saving:d,isReadOnly:f,availableTools:p,onNameChange:m,onIdChange:x,onDescriptionChange:y,onSubagentChange:w,onToolsChange:C,onColorChange:v,onPromptChange:S,onSave:b,onCancel:_,onDuplicate:E}){const N=a8(a),T=p.filter(O=>!(s&&O.topLevelOnly)),D=(O,M)=>{const G=new Map(N),V=G.get(O)||new Set,R=new Set(V);R.has(M)?R.delete(M):R.add(M),R.size===0?G.set(O,new Set):G.set(O,R),C(jm(G))},A=O=>{const M=new Map(N);M.has(O)?M.delete(O):M.set(O,new Set),C(jm(M))};return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"space-y-3",children:[c&&o.jsx(Wu,{message:c}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(vr,{label:"Name",value:e,onChange:m,placeholder:"My Agent",readOnly:f}),o.jsx(vr,{label:"ID",value:t,onChange:x,readOnly:!0,placeholder:"my_agent",hint:"(read-only)",mono:!0})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(vr,{label:"Description",value:n,onChange:y,placeholder:"What this agent does",readOnly:f}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Type"}),o.jsxs("div",{className:"flex items-center gap-3 h-[34px]",children:[o.jsx("button",{onClick:()=>!f&&w(!1),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-bg-tertiary text-text-muted hover:text-text-secondary":"bg-accent-primary/25 text-accent-primary"} ${f?"pointer-events-none opacity-60":""}`,children:"Agent"}),o.jsx("button",{onClick:()=>!f&&w(!0),className:`px-2.5 py-1 rounded text-xs font-medium transition-colors ${s?"bg-accent-primary/25 text-accent-primary":"bg-bg-tertiary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none opacity-60":""}`,children:"Sub-agent"}),o.jsxs("div",{className:"flex items-center gap-1.5 ml-auto",children:[o.jsx("label",{className:"text-xs text-text-secondary",children:"Color"}),o.jsx("input",{type:"color",value:l,onChange:O=>!f&&v(O.target.value),disabled:f,className:"w-6 h-6 rounded cursor-pointer border border-border bg-transparent"})]})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Tools"}),o.jsx("div",{className:"flex flex-wrap gap-1.5 p-2 bg-bg-tertiary border border-border rounded max-h-32 overflow-y-auto",children:T.map(O=>{const M=N.has(O.name),G=O.actions.length>0,V=N.get(O.name)||new Set;return G?f?o.jsxs("button",{className:"px-1.5 py-0.5 rounded text-xs font-mono flex items-center gap-1 bg-bg-primary text-text-muted pointer-events-none opacity-60",children:[o.jsx("span",{children:O.name}),o.jsx("span",{className:"text-[10px]",children:"*"})]},O.name):o.jsx(wl,{trigger:o.jsxs("button",{className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted"}`,children:[o.jsx("span",{children:O.name}),G&&o.jsx("span",{className:`text-[10px] ${M&&V.size>0?"text-accent-primary":"text-text-muted"}`,children:"*"})]}),minWidth:"160px",items:[...O.actions.map(R=>({label:o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",htmlFor:`${O.name}-${R}`,children:[o.jsx("input",{type:"checkbox",id:`${O.name}-${R}`,checked:V.has(R),onChange:()=>D(O.name,R),disabled:f,className:"w-3 h-3 rounded accent-accent-primary"}),o.jsx("span",{children:R})]}),closeOnClick:!1})),{label:M?"Deselect all":"Select all",closeOnClick:!1,onClick:()=>{if(M)A(O.name);else{const R=new Map(N);R.set(O.name,new Set(O.actions)),C(jm(R))}}}]},O.name):o.jsx("button",{onClick:()=>!f&&A(O.name),className:`px-1.5 py-0.5 rounded text-xs font-mono transition-colors flex items-center gap-1 ${M?"bg-accent-primary/25 text-accent-primary":"bg-bg-primary text-text-muted hover:text-text-secondary"} ${f?"pointer-events-none":"cursor-pointer"}`,children:o.jsx("span",{children:O.name})},O.name)})})]})]}),o.jsxs("div",{className:"flex-1 min-h-[150px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:u,onChange:O=>!f&&S(O.target.value),readOnly:f,placeholder:"Instructions for this agent...",className:`h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary ${f?"opacity-60":""}`})]}),o.jsx(rN,{onCancel:_,onSave:b,saving:d,saveDisabled:!e||!u||f}),f&&o.jsx("div",{className:"flex justify-end mt-2",children:o.jsx("button",{onClick:E,className:"px-3 py-1.5 rounded bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 transition-colors",children:"Duplicate & Customize"})})]})}function l8(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function c8({isOpen:e,onClose:t,initialEditId:n}){const s=mt(_e=>_e.defaults),a=mt(_e=>_e.userItems),l=mt(_e=>_e.loading),u=mt(_e=>_e.fetchAgents),c=mt(_e=>_e.fetchAgent),d=mt(_e=>_e.fetchDefaultContent),f=mt(_e=>_e.createAgent),p=mt(_e=>_e.updateAgent),m=mt(_e=>_e.deleteAgent),[x,y]=L.useState("list"),[w,C]=L.useState(null),[v,S]=L.useState(!1),[b,_]=L.useState(""),[E,N]=L.useState(""),[T,D]=L.useState(""),[A,O]=L.useState(!0),[M,G]=L.useState([]),[V,R]=L.useState("#6b7280"),[U,W]=L.useState(""),[z,J]=L.useState(""),[Z,H]=L.useState(!1),[I,$]=L.useState([]),[q,B]=L.useState(new Set),ee=_e=>{_(_e.metadata.name),N(_e.metadata.id),D(_e.metadata.description),O(_e.metadata.subagent),G(_e.metadata.allowedTools),R(_e.metadata.color??"#6b7280"),W(_e.prompt),J("")},Q=(_e,ne,xe)=>{_(_e.metadata.name+" (copy)"),N(`${ne}-copy-${Date.now()}`),D(_e.metadata.description),O(_e.metadata.subagent),G(_e.metadata.allowedTools),R(_e.metadata.color??"#6b7280"),W(_e.prompt),J(""),C(null),S(!1),y("edit")},te=(_e,ne)=>{ee(_e),C(ne),S(!0),y("edit")};L.useEffect(()=>{e&&(u(),Ae("/api/tools").then(_e=>_e.json()).then(_e=>{const ne=_e.tools||[];B(new Set(ne.filter(xe=>xe.alwaysAllowed).map(xe=>xe.name))),$(ne.filter(xe=>!xe.alwaysAllowed))}).catch(()=>{$([]),B(new Set)}),n?s.some(ne=>ne.id===n)?d(n).then(ne=>{ne&&Q(ne,n)}):c(n).then(ne=>{ne&&(ee(ne),C(n),S(!1),y("edit"))}):(y("list"),C(null),S(!1)))},[e,u,c,d,n]);const Y=async _e=>{if(s.some(xe=>xe.id===_e)){const xe=await d(_e);if(!xe)return;te(xe,_e)}else{const xe=await c(_e);if(!xe)return;te(xe,_e)}},F=async _e=>{const ne=await d(_e);ne&&Q(ne,_e)},ue=()=>{C(null),_(""),N(""),D(""),O(!0),G(["read_file"]),R("#6b7280"),W(""),J(""),S(!1),y("edit")},oe=async _e=>{const ne=await c(_e);ne&&(ee(ne),C(_e),S(!1),y("edit"))},ke=async _e=>{await m(_e)},Se=async()=>{const _e=w??E;if(!_e||!b||!U){J("Name and prompt are required.");return}H(!0),J("");const ne={metadata:{id:_e,name:b,description:T,subagent:A,allowedTools:M.filter(He=>!q.has(He)),color:V},prompt:U},xe=w?await p(w,ne):await f(ne);if(H(!1),!xe.success){J(xe.error??"Failed to save agent.");return}n?t():y("list")},Te=()=>{n?t():(y("list"),S(!1))},fe=_e=>{_(_e),w||N(l8(_e))},ae=s.filter(_e=>_e.subagent),ce=s.filter(_e=>!_e.subagent),se=a.filter(_e=>_e.subagent),je=a.filter(_e=>!_e.subagent);return x==="edit"?o.jsx(Dt,{isOpen:e,onClose:Te,title:v?`${b}`:w?"Edit Agent":"New Agent",size:"xl",children:o.jsx(o8,{formName:b,formId:E,formDescription:T,formSubagent:A,formTools:M,formColor:V,formPrompt:U,formError:z,saving:Z,isReadOnly:v,availableTools:I,onNameChange:fe,onIdChange:N,onDescriptionChange:D,onSubagentChange:_e=>{O(_e),_e&&G(ne=>ne.filter(xe=>{var He;return!((He=I.find(Ze=>Ze.name===xe))!=null&&He.topLevelOnly)}))},onToolsChange:G,onColorChange:R,onPromptChange:W,onSave:Se,onCancel:Te,onDuplicate:()=>{_(b+" (copy)"),N(`${w}-copy-${Date.now()}`),C(null),S(!1)}})}):o.jsx(Dt,{isOpen:e,onClose:t,title:"Agents",size:"lg",children:o.jsx(RS,{description:"Agents define behavior, tools, and prompts for top-level modes and sub-agents.",onNew:ue,loading:l,hasItems:s.length>0||a.length>0,children:o.jsxs("div",{className:"space-y-4",children:[s.length>0&&o.jsx(nS,{title:"Built-in",agents:ce,subagents:ae,isBuiltIn:!0,alwaysAllowedNames:q,onView:Y,onDuplicate:F}),a.length>0&&o.jsx(nS,{title:"Custom",agents:je,subagents:se,isBuiltIn:!1,alwaysAllowedNames:q,onView:Y,onDuplicate:F,onEdit:oe,onDelete:ke})]})})})}function u8(){const e=Re(b=>{var _;return(_=b.currentSession)==null?void 0:_.mode}),t=Re(b=>b.switchMode),n=mt(b=>b.defaults),s=mt(b=>b.userItems),a=mt(b=>b.fetchAgents),l=[...n,...s],[u,c]=L.useState(!1),[d,f]=L.useState(!1),[p,m]=L.useState(null),x=L.useRef(null);L.useEffect(()=>{a()},[a]),L.useEffect(()=>{function b(_){x.current&&!x.current.contains(_.target)&&c(!1)}return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const y=Sp();if(!e)return null;const w=l.filter(b=>!b.subagent),C=w.find(b=>b.id===e),v=(C==null?void 0:C.name)??e,S=dl(l,e);return o.jsxs("div",{className:"relative",ref:x,children:[o.jsxs("button",{type:"button",onClick:()=>c(!u),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors",title:"Switch agent",children:[o.jsx("span",{className:"text-sm font-medium",style:{color:S},children:v}),o.jsx(Kn,{className:`w-3 h-3 text-text-muted transition-transform ${u?"rotate-180":""}`})]}),u&&w.length>0&&o.jsxs("div",{className:"absolute bottom-full left-0 mb-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:[w.map((b,_)=>{const E=b.id===e,N=dl(l,b.id),T=y.agentSwitching[_],D=T?TS(T):null;return o.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-sm transition-colors group ${E?"bg-bg-tertiary":"hover:bg-bg-tertiary cursor-pointer"}`,children:[o.jsxs("button",{type:"button",onClick:()=>{E||t(b.id),c(!1)},className:"flex-1 text-left flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"font-medium truncate",style:{color:N},children:b.name}),E&&o.jsx(Ir,{className:"w-3.5 h-3.5 text-text-muted shrink-0"})]}),D&&o.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] bg-bg-tertiary text-text-muted rounded",children:D})]},b.id)}),o.jsx("div",{className:"border-t border-border p-1",children:o.jsx("button",{type:"button",onClick:()=>{c(!1),f(!0)},className:"w-full text-left px-3 py-1.5 rounded text-sm text-text-muted hover:text-text-primary hover:bg-bg-tertiary transition-colors",children:"Manage Agents..."})})]}),o.jsx(c8,{isOpen:d,onClose:()=>{f(!1),m(null)},initialEditId:p})]})}function d8(){const e=Re(s=>s.currentSession),t=Re(s=>s.switchDangerLevel);if(!e)return null;const n=e.dangerLevel??"normal";return o.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-bg-tertiary/50",children:[o.jsx("button",{type:"button",onClick:()=>t("normal"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="normal"?"bg-accent-success/20 text-accent-success":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Normal mode - requires path confirmation",children:"Normal"}),o.jsx("button",{type:"button",onClick:()=>t("dangerous"),className:`px-2 py-0.5 text-xs font-medium rounded transition-colors ${n==="dangerous"?"bg-red-500/20 text-red-400":"text-text-muted hover:text-text-primary hover:bg-bg-tertiary"}`,title:"Dangerous mode - bypasses all confirmations",children:"Dangerous"})]})}function rS({value:e,onChange:t}){return o.jsxs("div",{children:[o.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Query params ",o.jsx("span",{className:"text-text-muted",children:"(optional JSON)"})]}),o.jsx("input",{type:"text",value:e??"",onChange:n=>t(n.target.value),className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono"})]})}const h8=[8080,11434,8e3];function f8({model:e,modelConfigs:t,autoConfigState:n,testResults:s,onUpdateConfig:a,onRunAutoConfig:l,onTestParams:u,onShowRaw:c}){var d,f,p,m,x,y,w,C,v,S,b,_,E,N,T,D,A,O,M,G,V,R,U,W,z,J,Z,H,I,$,q,B,ee,Q,te,Y,F,ue,oe,ke,Se;return o.jsxs("div",{className:"px-4 pb-4 border-t border-border pt-3 space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("button",{onClick:()=>l(e.id),disabled:n.progress[e.id]==="probing",className:"px-4 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:n.progress[e.id]==="probing"?"Probing...":"Auto-config"}),n.progress[e.id]==="done"&&o.jsx("span",{className:"text-sm text-accent-success font-medium",children:"Configured ✓"}),n.progress[e.id]==="error"&&o.jsx("span",{className:"text-sm text-red-500 font-medium",children:"Failed ✗"})]}),o.jsxs("div",{className:"flex gap-3 items-end",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Context window (tokens)"}),o.jsx("input",{type:"number",value:((d=t[e.id])==null?void 0:d.contextWindow)??e.contextWindow,onChange:Te=>a(e.id,{contextWindow:parseInt(Te.target.value)||e.contextWindow}),className:"w-32 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-text-secondary pb-1",children:[o.jsx("input",{type:"checkbox",checked:((f=t[e.id])==null?void 0:f.supportsVision)??!1,onChange:Te=>a(e.id,{supportsVision:Te.target.checked}),className:"accent-accent-primary"})," ","Supports vision"]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:()=>u(e.id,"thinking"),disabled:(p=s[e.id+"-thinking"])==null?void 0:p.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(m=s[e.id+"-thinking"])!=null&&m.loading?"Testing...":"Test thinking"}),((x=s[e.id+"-thinking"])==null?void 0:x.result)&&o.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((y=s[e.id+"-thinking"])==null?void 0:y.error)&&o.jsx("span",{className:"text-xs text-red-500",title:(w=s[e.id+"-thinking"])==null?void 0:w.error,children:"Fail"}),((C=s[e.id+"-thinking"])==null?void 0:C.result)&&o.jsx("button",{onClick:()=>c(s[e.id+"-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:()=>u(e.id,"non-thinking"),disabled:(v=s[e.id+"-non-thinking"])==null?void 0:v.loading,className:"px-3 py-1.5 bg-bg-tertiary border border-border rounded text-xs font-medium hover:bg-bg-secondary disabled:opacity-50 transition-colors",children:(S=s[e.id+"-non-thinking"])!=null&&S.loading?"Testing...":"Test non-thinking"}),((b=s[e.id+"-non-thinking"])==null?void 0:b.result)&&o.jsx("span",{className:"text-xs text-accent-success",children:"OK"}),((_=s[e.id+"-non-thinking"])==null?void 0:_.error)&&o.jsx("span",{className:"text-xs text-red-500",title:(E=s[e.id+"-non-thinking"])==null?void 0:E.error,children:"Fail"}),((N=s[e.id+"-non-thinking"])==null?void 0:N.result)&&o.jsx("button",{onClick:()=>c(s[e.id+"-non-thinking"].result),className:"text-xs text-accent-primary hover:underline",children:"raw"})]})]}),o.jsxs("details",{className:"group",children:[o.jsxs("summary",{className:"text-xs text-text-muted cursor-pointer hover:text-text-secondary list-none flex items-center gap-1 select-none",children:[o.jsx(Kn,{className:"w-3 h-3 transition-transform group-open:rotate-180"}),"Advanced: thinking & non-thinking params"]}),o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((T=t[e.id])==null?void 0:T.thinkingEnabled)??!1,onChange:Te=>a(e.id,{thinkingEnabled:Te.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Thinking"})]}),((D=t[e.id])==null?void 0:D.thinkingEnabled)&&o.jsxs("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-primary/30",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Reasoning effort"}),o.jsx("input",{type:"text",value:((A=t[e.id])==null?void 0:A.thinkingLevel)??"",onChange:Te=>a(e.id,{thinkingLevel:Te.target.value}),className:"w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-xs text-text-primary"})]}),o.jsx(rS,{value:(O=t[e.id])==null?void 0:O.thinkingQueryParams,onChange:Te=>a(e.id,{thinkingQueryParams:Te})})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:((M=t[e.id])==null?void 0:M.nonThinkingEnabled)??!1,onChange:Te=>a(e.id,{nonThinkingEnabled:Te.target.checked}),className:"w-4 h-4 rounded border-border bg-bg-tertiary accent-accent-primary"}),o.jsx("span",{className:"text-xs font-medium text-text-primary",children:"Non-thinking"})]}),((G=t[e.id])==null?void 0:G.nonThinkingEnabled)&&o.jsx("div",{className:"ml-6 space-y-2 pl-3 border-l-2 border-accent-warning/30",children:o.jsx(rS,{value:(V=t[e.id])==null?void 0:V.nonThinkingQueryParams,onChange:Te=>a(e.id,{nonThinkingQueryParams:Te})})})]}),o.jsxs("div",{className:"border-t border-border pt-3 mt-3",children:[o.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Sampling parameters"}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Temperature"}),o.jsx("input",{type:"number",step:"0.1",value:((R=t[e.id])==null?void 0:R.temperature)??"",onChange:Te=>a(e.id,{temperature:Te.target.value?parseFloat(Te.target.value):void 0}),placeholder:((W=(U=t[e.id])==null?void 0:U.defaultTemperature)==null?void 0:W.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((z=t[e.id])==null?void 0:z.defaultTemperature)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(J=t[e.id])==null?void 0:J.defaultTemperature]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top P"}),o.jsx("input",{type:"number",step:"0.05",value:((Z=t[e.id])==null?void 0:Z.topP)??"",onChange:Te=>a(e.id,{topP:Te.target.value?parseFloat(Te.target.value):void 0}),placeholder:((I=(H=t[e.id])==null?void 0:H.defaultTopP)==null?void 0:I.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),(($=t[e.id])==null?void 0:$.defaultTopP)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(q=t[e.id])==null?void 0:q.defaultTopP]})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Top K"}),o.jsx("input",{type:"number",value:((B=t[e.id])==null?void 0:B.topK)??"",onChange:Te=>a(e.id,{topK:Te.target.value?parseInt(Te.target.value):void 0}),placeholder:((Q=(ee=t[e.id])==null?void 0:ee.defaultTopK)==null?void 0:Q.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((te=t[e.id])==null?void 0:te.defaultTopK)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Y=t[e.id])==null?void 0:Y.defaultTopK]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-0.5",children:"Max tokens"}),o.jsx("input",{type:"number",value:((F=t[e.id])==null?void 0:F.maxTokens)??"",onChange:Te=>a(e.id,{maxTokens:Te.target.value?parseInt(Te.target.value):void 0}),placeholder:((oe=(ue=t[e.id])==null?void 0:ue.defaultMaxTokens)==null?void 0:oe.toString())??"Using default",className:"w-full px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary"}),((ke=t[e.id])==null?void 0:ke.defaultMaxTokens)!==void 0&&o.jsxs("p",{className:"text-xs text-text-muted mt-0.5",children:["default: ",(Se=t[e.id])==null?void 0:Se.defaultMaxTokens]})]})]})]})]})]})}function qC({isOpen:e,onClose:t,onSave:n,initialStep:s=1,editProvider:a,editModelId:l}){const[u,c]=L.useState(s),[d,f]=L.useState(""),[p,m]=L.useState(""),[x,y]=L.useState("unknown"),[w,C]=L.useState(""),[v,S]=L.useState(!1),[b,_]=L.useState(!1),[E,N]=L.useState(null),[T,D]=L.useState([]),[A,O]=L.useState(null),[M,G]=L.useState(!1),[V,R]=L.useState(""),[U,W]=L.useState({}),[z,J]=L.useState({loading:!1,progress:{}}),[Z,H]=L.useState({}),[I,$]=L.useState(null),[q,B]=L.useState(new Set),[ee,Q]=L.useState(""),te=L.useRef(null);L.useEffect(()=>{u===1&&e&&requestAnimationFrame(()=>{var fe;return(fe=te.current)==null?void 0:fe.focus()})},[u,e]);function Y(fe,ae){W(ce=>({...ce,[fe]:{...ce[fe],...ae}}))}function F(fe){if(!fe.trim())return T;const ae=fe.toLowerCase().split(/\s+/).filter(Boolean);return T.filter(ce=>ae.every(se=>ce.id.toLowerCase().includes(se)))}L.useEffect(()=>{var fe,ae;if(e)if(c(s),f((a==null?void 0:a.name)??""),m((a==null?void 0:a.url)??""),y((a==null?void 0:a.backend)??"unknown"),C((a==null?void 0:a.apiKey)??""),S((a==null?void 0:a.isLocal)??!1),N(null),R((a==null?void 0:a.thinkingField)??""),H({}),$(null),(fe=a==null?void 0:a.models)!=null&&fe.length){const ce={},se=new Set;for(const je of a.models)ce[je.id]={contextWindow:je.contextWindow,supportsVision:je.supportsVision,thinkingEnabled:je.thinkingEnabled,thinkingLevel:je.thinkingLevel,nonThinkingEnabled:je.nonThinkingEnabled,thinkingQueryParams:je.thinkingQueryParams,nonThinkingQueryParams:je.nonThinkingQueryParams,defaultTemperature:je.defaultTemperature,defaultTopP:je.defaultTopP,defaultTopK:je.defaultTopK,defaultMaxTokens:je.defaultMaxTokens},je.selected&&se.add(je.id);if(se.size===0)for(const je of a.models)se.add(je.id);B(se),W(ce),D(a.models.map(je=>({id:je.id,contextWindow:je.contextWindow}))),O(l??((ae=a.models[0])==null?void 0:ae.id)??null)}else D([]),W({}),O(null),B(new Set)},[e,s,a==null?void 0:a.id,l]),L.useEffect(()=>{u===2&&p&&T.length===0&&!b&&!E&&ue(p)},[u]);async function ue(fe){var ae,ce;_(!0),N(null),D([]);try{const se=new URLSearchParams({url:fe});w&&se.set("apiKey",w);const je=await Ae(`/api/providers/models?${se.toString()}`);if(je.ok){const _e=await je.json();if((ae=_e.models)!=null&&ae.length){D(_e.models),O(((ce=_e.models[0])==null?void 0:ce.id)??null);const ne={};for(const xe of _e.models)ne[xe.id]={contextWindow:xe.contextWindow,thinkingEnabled:!0,thinkingLevel:void 0,defaultTemperature:xe.defaultTemperature,defaultTopP:xe.defaultTopP,defaultTopK:xe.defaultTopK,defaultMaxTokens:xe.defaultMaxTokens};W(ne),_e.models.length===1&&(B(new Set([_e.models[0].id])),O(_e.models[0].id),oe(_e.models[0].id))}}else{const _e=await je.json();N(_e.error??`Failed to fetch models from ${fe}`)}}catch(se){N(`Failed to fetch models from ${fe}: ${se instanceof Error?se.message:"Unknown error"}`)}_(!1)}async function oe(fe){J(ae=>({loading:!0,progress:{...ae.progress,[fe]:"probing"}}));try{const ae=await Ae("/api/providers/auto-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,apiKey:w||void 0,backend:x||"unknown",models:[{id:fe}]})});if(!ae.ok){const se=await ae.json();throw new Error(se.error??"Auto-config failed")}const ce=await ae.json();for(const se of ce.models){const je={};se.contextSource!=="default"&&(je.contextWindow=se.contextWindow,je.supportsVision=se.supportsVision),se.thinkingConfig&&(je.thinkingEnabled=!0,je.thinkingQueryParams=JSON.stringify(se.thinkingConfig)),se.nonThinkingConfig&&(je.nonThinkingEnabled=!0,je.nonThinkingQueryParams=JSON.stringify(se.nonThinkingConfig)),Y(se.id,je),J(_e=>({..._e,progress:{..._e.progress,[se.id]:"done"}}))}}catch(ae){console.error("Auto-config error:",ae),J(ce=>({...ce,progress:{...ce.progress,[fe]:"error"}}))}finally{J(ae=>({...ae,loading:!1}))}}async function ke(fe,ae){const ce=fe+"-"+ae;H(se=>({...se,[ce]:{loading:!0}}));try{const se=U[fe],je=await Ae("/api/providers/test-params",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p,model:fe,apiKey:w||void 0,backend:x||"unknown",thinkingField:V||void 0,mode:ae,modelConfig:{temperature:se==null?void 0:se.temperature,topP:se==null?void 0:se.topP,topK:se==null?void 0:se.topK,maxTokens:se==null?void 0:se.maxTokens,supportsVision:se==null?void 0:se.supportsVision,thinkingEnabled:se==null?void 0:se.thinkingEnabled,thinkingLevel:se==null?void 0:se.thinkingLevel,nonThinkingEnabled:se==null?void 0:se.nonThinkingEnabled,thinkingQueryParams:se==null?void 0:se.thinkingQueryParams,nonThinkingQueryParams:se==null?void 0:se.nonThinkingQueryParams}})}),_e=await je.json();je.ok?H(ne=>({...ne,[ce]:{loading:!1,result:JSON.stringify(_e,null,2),message:_e.message}})):H(ne=>({...ne,[ce]:{loading:!1,error:_e.error??"Test failed"}}))}catch(se){H(je=>({...je,[ce]:{loading:!1,error:se instanceof Error?se.message:"Request failed"}}))}}function Se(){D([]),W({}),J({loading:!1,progress:{}}),H({}),$(null),B(new Set),Q("")}function Te(){const fe=d||"Provider",ae=(a==null?void 0:a.id)??`temp-${Date.now()}`;n({id:ae,name:fe,url:p,backend:x||"unknown",apiKey:w||void 0,isLocal:v||void 0,thinkingField:V||void 0,models:T.map(ce=>{var se,je,_e,ne,xe,He,Ze,rt,kt,ge,Ne;return{id:ce.id,contextWindow:((se=U[ce.id])==null?void 0:se.contextWindow)??ce.contextWindow,selected:q.has(ce.id)||void 0,supportsVision:(je=U[ce.id])==null?void 0:je.supportsVision,thinkingEnabled:(_e=U[ce.id])==null?void 0:_e.thinkingEnabled,thinkingLevel:(ne=U[ce.id])==null?void 0:ne.thinkingLevel,nonThinkingEnabled:(xe=U[ce.id])==null?void 0:xe.nonThinkingEnabled,thinkingQueryParams:(He=U[ce.id])==null?void 0:He.thinkingQueryParams,nonThinkingQueryParams:(Ze=U[ce.id])==null?void 0:Ze.nonThinkingQueryParams,temperature:(rt=U[ce.id])==null?void 0:rt.temperature,topP:(kt=U[ce.id])==null?void 0:kt.topP,topK:(ge=U[ce.id])==null?void 0:ge.topK,maxTokens:(Ne=U[ce.id])==null?void 0:Ne.maxTokens}})}),t()}return e?o.jsxs("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",children:[o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[85vh] overflow-y-auto shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-lg font-semibold text-text-primary",children:a?"Edit Provider":"Add Provider"}),o.jsx("button",{onClick:t,className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("div",{className:"flex gap-1.5 px-6 pt-4",children:[1,2].map(fe=>o.jsx("div",{className:`h-1 flex-1 rounded-full transition-colors ${fe<u?"bg-accent-success":fe===u?"bg-accent-primary":"bg-border"}`},fe))}),u===1&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-2",children:"Inference engine"}),o.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[o.jsx("button",{type:"button",onClick:()=>{y("unknown"),S(!1),N(null)},className:`p-2 rounded border text-center text-sm transition-colors ${x==="unknown"?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:"Other"},"other"),h8.map(fe=>{const ae={8e3:"vllm",11434:"ollama",8080:"llamacpp"},ce={8e3:"vLLM",11434:"Ollama",8080:"llama.cpp"};return o.jsx("button",{type:"button",onClick:()=>{f(se=>se||(ce[fe]??"")),m(se=>se||`http://localhost:${fe}`),y(ae[fe]??""),S(!0),N(null)},className:`p-2 rounded border text-center text-sm transition-colors ${x===ae[fe]?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border hover:border-text-muted text-text-secondary"}`,children:ce[fe]??`localhost:${fe}`},fe)})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider URL"}),o.jsx("input",{ref:te,type:"text",value:p,"data-testid":"provider-modal-url",onChange:fe=>{m(fe.target.value),N(null),D([]),W({})},placeholder:"http://localhost:8000",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-text-secondary mb-1",children:"Provider name"}),o.jsx("input",{type:"text",autoComplete:"off",value:d,onChange:fe=>f(fe.target.value),placeholder:"My LLM Server",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-sm text-text-secondary mb-1",children:["API key ",o.jsx("span",{className:"text-text-muted",children:"(optional)"})]}),o.jsx("input",{type:"text",autoComplete:"off",value:w,onChange:fe=>C(fe.target.value),placeholder:"sk-...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:v,onChange:fe=>S(fe.target.checked),className:"w-4 h-4 rounded border-border bg-bg-primary accent-accent-primary"}),o.jsx("span",{className:"text-sm text-text-secondary",children:"This is a local provider"})]})]}),u===2&&o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[b&&o.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[o.jsx("span",{className:"w-4 h-4 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}),"Fetching models..."]}),E&&o.jsxs("div",{className:"p-3 rounded-lg text-sm bg-red-500/10 text-red-500 border border-red-500/20",children:[o.jsx("p",{children:E}),o.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["URL: ",p]}),o.jsxs("div",{className:"flex gap-2 mt-2",children:[o.jsx("button",{onClick:()=>ue(p),className:"text-xs text-accent-primary hover:underline",children:"Retry"}),o.jsx("button",{onClick:()=>{Se(),c(1)},className:"text-xs text-accent-primary hover:underline",children:"Edit URL"})]})]}),T.length>0&&x&&o.jsxs(o.Fragment,{children:[q.size>0&&o.jsxs("div",{className:"mb-4",children:[o.jsxs("h4",{className:"text-sm font-medium text-text-primary mb-1",children:["Selected Models (",q.size,")"]}),o.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Only selected models will appear in the model selector."}),o.jsx("div",{className:"space-y-2",children:T.filter(fe=>q.has(fe.id)).map(fe=>{var ae;return o.jsxs("div",{className:"bg-bg-primary border border-border rounded-lg overflow-hidden",children:[o.jsxs("div",{onClick:()=>O(A===fe.id?null:fe.id),className:"w-full flex items-center justify-between px-4 py-3 hover:bg-bg-tertiary transition-colors cursor-pointer",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-sm font-medium text-text-primary",children:fe.id.split("/").pop()}),o.jsxs("span",{className:"text-xs text-text-muted bg-bg-tertiary px-2 py-0.5 rounded",children:[(((ae=U[fe.id])==null?void 0:ae.contextWindow)??fe.contextWindow).toLocaleString()," ctx"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[z.progress[fe.id]==="probing"?o.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin"}):z.progress[fe.id]==="done"?o.jsx("span",{className:"text-xs text-accent-success font-medium",children:"Configured ✓"}):z.progress[fe.id]==="error"?o.jsx("span",{className:"text-xs text-red-500 font-medium",children:"Failed ✗"}):o.jsx("button",{onClick:ce=>{ce.stopPropagation(),oe(fe.id)},className:"text-xs text-accent-primary hover:underline",children:"Auto-config"}),T.length>1&&o.jsx("button",{onClick:ce=>{ce.stopPropagation();const se=new Set(q);se.delete(fe.id),B(se),A===fe.id&&O(null)},className:"text-xs text-red-500 hover:text-red-400 px-2 py-1 rounded hover:bg-red-500/10",children:"Remove"}),o.jsx(Kn,{className:`w-4 h-4 text-text-muted transition-transform ${A===fe.id?"rotate-180":""}`})]})]}),A===fe.id&&o.jsx(f8,{model:fe,modelConfigs:U,autoConfigState:z,testResults:Z,onUpdateConfig:Y,onRunAutoConfig:oe,onTestParams:ke,onShowRaw:$})]},fe.id)})})]}),T.length>1&&o.jsxs("div",{children:[o.jsx("h4",{className:"text-sm font-medium text-text-primary mb-1",children:"Available Models"}),q.size===0&&o.jsx("p",{className:"text-xs text-text-muted mb-2",children:"This provider has many models available. Select the ones you want to use below."}),o.jsxs("div",{className:"relative mb-2",children:[o.jsx("input",{type:"text",value:ee,onChange:fe=>Q(fe.target.value),placeholder:"Search models...",className:"w-full px-4 py-2 bg-bg-primary border border-border rounded-lg text-sm text-text-primary placeholder-text-muted focus:outline-none focus:border-accent-primary"}),ee&&o.jsx("button",{onClick:()=>Q(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-text-muted hover:text-text-primary text-sm",children:"×"})]}),o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("p",{className:"text-xs text-text-muted",children:["Showing ",F(ee).length," of ",T.length," models"]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:()=>{const fe=new Set(q),ae=F(ee);for(const ce of ae)fe.add(ce.id);B(fe);for(const ce of ae)z.progress[ce.id]!=="probing"&&z.progress[ce.id]!=="done"&&oe(ce.id)},className:"text-xs text-accent-primary hover:underline",children:"Select all"}),o.jsx("button",{onClick:()=>{const fe=new Set(q),ae=F(ee);for(const ce of ae)fe.delete(ce.id);B(fe)},className:"text-xs text-text-muted hover:text-text-secondary",children:"Deselect all"})]})]}),o.jsxs("div",{className:"space-y-1 max-h-48 overflow-y-auto border border-border rounded-lg bg-bg-primary",children:[F(ee).map(fe=>{var ce;const ae=q.has(fe.id);return o.jsxs("div",{role:"checkbox","aria-checked":ae,tabIndex:0,className:`flex items-center gap-3 px-4 py-2 hover:bg-bg-tertiary transition-colors cursor-pointer ${ae?"bg-accent-primary/5":""}`,onClick:()=>{if(ae){const se=new Set(q);se.delete(fe.id),B(se)}else{const se=new Set(q);se.add(fe.id),B(se),oe(fe.id)}},onKeyDown:se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),se.currentTarget.click())},children:[o.jsx("input",{type:"checkbox",checked:ae,onChange:()=>{},className:"w-4 h-4 rounded border-border accent-accent-primary pointer-events-none"}),o.jsx("span",{className:"text-sm text-text-primary flex-1 truncate",children:fe.id.split("/").pop()}),o.jsxs("span",{className:"text-xs text-text-muted flex-shrink-0",children:[(((ce=U[fe.id])==null?void 0:ce.contextWindow)??fe.contextWindow).toLocaleString()," ctx"]}),z.progress[fe.id]==="probing"&&o.jsx("span",{className:"w-3 h-3 border-2 border-accent-primary border-t-transparent rounded-full animate-spin flex-shrink-0"}),z.progress[fe.id]==="done"&&o.jsx("span",{className:"text-xs text-accent-success flex-shrink-0",children:"✓"}),z.progress[fe.id]==="error"&&o.jsx("span",{className:"text-xs text-red-500 flex-shrink-0",children:"✗"})]},fe.id)}),F(ee).length===0&&o.jsxs("div",{className:"px-4 py-6 text-center text-sm text-text-muted",children:["No models match “",ee,"”"]})]})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border",children:[o.jsx("div",{children:u>1&&o.jsx("button",{onClick:()=>{u===2&&Se(),c(u-1)},className:"text-sm text-text-muted hover:text-text-secondary transition-colors",children:"← Back"})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-text-muted hover:text-text-secondary transition-colors",children:"Cancel"}),u===1?o.jsx("button",{onClick:()=>c(2),disabled:!p,"data-testid":"provider-modal-next",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:"Next — Test & Configure"}):o.jsx("button",{onClick:Te,disabled:z.loading,"data-testid":"provider-modal-save",className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition-colors",children:z.loading?"Configuring...":"Save Provider"})]})]})]}),M&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:fe=>{fe.target===fe.currentTarget&&G(!1)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[480px] shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Provider-Level Defaults"}),o.jsx("button",{onClick:()=>G(!1),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsxs("div",{className:"px-6 py-4 space-y-4",children:[o.jsx("p",{className:"text-xs text-text-muted",children:"These apply to all models unless overridden per-model."}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Non-thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'{"chat_template_kwargs":{"enable_thinking":false}}',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-secondary block mb-1",children:"Thinking mode params"}),o.jsx("input",{type:"text",defaultValue:'reasoning_effort: "low"',readOnly:!0,className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-secondary font-mono"})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"text-xs text-text-secondary block mb-1",children:["Thinking response field ",o.jsx("span",{className:"text-text-muted",children:"(override)"})]}),o.jsx("input",{type:"text",value:V,onChange:fe=>R(fe.target.value),placeholder:"Leave blank for auto-detect",className:"w-full px-3 py-2 bg-bg-primary border border-border rounded text-sm text-text-primary font-mono"}),o.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Field name the backend uses for reasoning/thinking content (e.g. reasoning, reasoning_content, thinking)."})]})]}),o.jsx("div",{className:"flex justify-end px-6 py-4 border-t border-border",children:o.jsx("button",{onClick:()=>G(!1),className:"px-5 py-2 bg-accent-primary text-text-primary rounded-lg text-sm font-medium hover:bg-accent-primary/90 transition-colors",children:"Done"})})]})}),I&&o.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-[60]",onClick:fe=>{fe.target===fe.currentTarget&&$(null)},children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-xl w-[640px] max-h-[80vh] shadow-2xl flex flex-col",children:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border shrink-0",children:[o.jsx("h3",{className:"text-base font-semibold text-text-primary",children:"Raw Response"}),o.jsx("button",{onClick:()=>$(null),className:"text-text-muted hover:text-text-primary text-xl leading-none p-1",children:"×"})]}),o.jsx("pre",{className:"px-6 py-4 overflow-y-auto text-xs text-text-secondary font-mono whitespace-pre-wrap break-all",children:I})]})})]}):null}function m8(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function p8(){var fe;const[,e]=qn(),t=Re(ae=>ae.currentSession),n=Re(ae=>ae.setSessionProvider),[s,a]=L.useState(!1),[l,u]=L.useState([]),[c,d]=L.useState(null),f=L.useRef(null),[p,m]=L.useState(null),[x,y]=L.useState(!1),w=L.useRef(new Set),C=nn(ae=>ae.providers),v=nn(ae=>ae.activeProviderId),S=nn(ae=>ae.defaultModelSelection),b=nn(ae=>ae.activating),_=nn(ae=>ae.activateProvider),E=nn(ae=>ae.refreshModel),N=nn(ae=>ae.refreshProviderModels),T=nn(ae=>ae.setDefaultModel),D=(t==null?void 0:t.providerId)??null,A=(t==null?void 0:t.providerModel)??null,O=(S==null?void 0:S.split("/")[0])??null,M=(S==null?void 0:S.split("/").slice(1).join("/"))??null,G=D??O,V=A??M,R=V?((fe=V.split("/").pop())==null?void 0:fe.replace(/-/g," "))??V:"No model",W=!!(t&&A)&&A!==M,[z,J]=L.useState(!1);L.useEffect(()=>{function ae(ce){f.current&&!f.current.contains(ce.target)&&(a(!1),u([]),w.current=new Set)}return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[]),L.useEffect(()=>{if(s){const ae=C.map(ce=>ce.id);u(ae),ae.forEach(ce=>{w.current.has(ce)||(w.current.add(ce),q(ce))})}},[s,C]);const Z=C.find(ae=>ae.id===G),H=(Z==null?void 0:Z.status)==="disconnected",I=(ae,ce)=>t?t.providerId===ae&&t.providerModel===ce:!1,$=(ae,ce)=>S?S===`${ae}/${ce}`:!1,q=async ae=>{d(ae);try{await N(ae)}catch{}finally{d(null)}},B=ae=>{l.includes(ae.id)?u(l.filter(ce=>ce!==ae.id)):(u([...l,ae.id]),q(ae.id))},ee=async ae=>{if(ae.id===v){B(ae);return}t?(n(ae.id,void 0),a(!1),u([])):await _(ae.id)&&(a(!1),u([]))},Q=ae=>{B(ae)},te=async(ae,ce)=>{ae.stopPropagation(),w.current.delete(ce),await q(ce)},Y=(ae,ce)=>{m({providerId:ae,model:ce}),y(!0)},F=p?C.find(ae=>ae.id===p.providerId):void 0,ue=()=>{m(null),y(!1)},oe=async ae=>{try{if(!(await Ae(`/api/providers/${ae.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:ae.name,url:ae.url,backend:ae.backend,apiKey:ae.apiKey,isLocal:ae.isLocal,thinkingField:ae.thinkingField,models:ae.models})})).ok)throw new Error("Failed to update provider");await nn.getState().fetchConfig()}catch{}m(null),y(!1)},ke=async(ae,ce)=>{if(t){Re.setState(je=>({currentSession:je.currentSession?{...je.currentSession,providerId:ae,providerModel:ce}:null})),n(ae,ce),u([]),a(!1);return}await _(ae)&&(u([]),a(!1))},Se=async(ae,ce,se)=>{ae.stopPropagation(),J(!0);try{await T(ce,se)}catch{}finally{J(!1)}};function Te(ae){return ae.models.some(se=>se.selected)?ae.models.filter(se=>se.selected):ae.models}return C.length===0?o.jsxs("button",{type:"button",onClick:()=>E(),className:"flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-bg-tertiary transition-colors group",title:H?"LLM server is offline. Click to retry.":R??"Click to refresh model",children:[H?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"LLM offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-sm text-accent-primary",children:R}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${Z!=null&&Z.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:Z!=null&&Z.isLocal?"local":"api"})]}),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:()=>a(!s),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:[H?o.jsx("span",{className:"text-sm text-accent-error animate-pulse",children:"offline"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:`text-sm ${W?"text-accent-primary italic":"text-accent-primary"}`,children:R}),W&&o.jsx("span",{className:"text-xs text-text-muted ml-0.5",title:"Session-scoped model (different from default)",children:"•"}),o.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${Z!=null&&Z.isLocal?"text-accent-success bg-accent-success/10":"text-accent-warning bg-accent-warning/10"}`,children:Z!=null&&Z.isLocal?"local":"api"})]}),o.jsx(Kn,{className:"w-3 h-3 text-text-muted transition-transform",rotate:s?180:0})]}),s&&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:C.map(ae=>{var ce;return o.jsxs("div",{children:[o.jsxs("div",{className:`px-3 py-2 flex items-center justify-between ${ae.id===G?"bg-bg-tertiary":"hover:bg-bg-tertiary"} ${b?"opacity-50 cursor-wait":"cursor-pointer"}`,children:[o.jsxs("div",{onClick:()=>!b&&ee(ae),className:"flex flex-col min-w-0 flex-1 cursor-pointer",children:[o.jsx("span",{className:`text-sm font-medium truncate ${ae.id===G?"text-accent-primary":"text-text-primary"}`,children:ae.name}),o.jsx("span",{className:"text-xs text-text-muted truncate",children:ae.backend!=="unknown"&&pS(ae.backend)})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ae.id===G?o.jsx("span",{className:"text-accent-success",title:"Active provider",children:o.jsx(Ir,{className:"w-4 h-4"})}):o.jsx("span",{className:"w-4"}),o.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),te(se,ae.id)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Refresh models",children:o.jsx(vp,{className:`w-4 h-4 ${c===ae.id?"animate-spin":""} ${ae.id===v?"text-accent-primary":"text-text-muted"}`})}),o.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),Q(ae)},className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors",title:"Show models",children:o.jsx(Kn,{className:`w-4 h-4 transition-transform ${l.includes(ae.id)?"rotate-180":""} ${ae.id===v?"text-accent-primary":"text-text-muted"}`})})]})]}),l.includes(ae.id)&&o.jsx("div",{className:"bg-bg-primary border-t border-border max-h-40 overflow-y-auto",children:c===ae.id?o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"Loading models..."}):(ce=ae.models)!=null&&ce.length?Te(ae).map(se=>{var ne;const je=I(ae.id,se.id),_e=$(ae.id,se.id);return o.jsxs("div",{className:`flex items-center px-4 py-1.5 text-sm hover:bg-bg-tertiary transition-colors group ${c==="activating"?"opacity-50 cursor-wait":""} ${je?"text-accent-primary":"text-text-secondary"}`,children:[o.jsx("button",{type:"button",onClick:()=>ke(ae.id,se.id),disabled:c==="activating",className:"flex-1 truncate text-left",children:((ne=se.id.split("/").pop())==null?void 0:ne.replace(/-/g," "))??se.id}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0 ml-2",children:[o.jsx("span",{className:"text-xs text-text-muted",children:m8(se.contextWindow)}),t&&o.jsx("button",{type:"button",onClick:xe=>Se(xe,ae.id,se.id),disabled:z,className:"p-0.5 hover:bg-bg-tertiary rounded transition-colors disabled:opacity-40",title:_e?"Default model":"Set as default model",children:_e?o.jsx(kS,{className:"w-3.5 h-3.5 text-accent-warning"}):o.jsx(ES,{className:"w-3.5 h-3.5 text-text-muted hover:text-accent-warning"})}),o.jsx("button",{type:"button",onClick:xe=>{xe.stopPropagation(),Y(ae.id,se)},className:"opacity-0 group-hover:opacity-100 p-0.5 hover:bg-bg-tertiary rounded transition-opacity",title:"Edit model context",children:o.jsx(Dj,{className:"w-3 h-3 text-text-muted"})}),je&&o.jsx("span",{className:"text-accent-success flex-shrink-0",title:"Session model",children:o.jsx(Ir,{className:"w-3.5 h-3.5"})})]})]},se.id)}):o.jsx("div",{className:"px-4 py-2 text-xs text-text-muted",children:"No models available"})})]},ae.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"})})]}),p&&x&&o.jsx(qC,{isOpen:!0,onClose:ue,onSave:oe,initialStep:2,editProvider:{id:p.providerId,name:(F==null?void 0:F.name)??"",url:(F==null?void 0:F.url)??"",backend:(F==null?void 0:F.backend)??"unknown",apiKey:F==null?void 0:F.apiKey,isLocal:F==null?void 0:F.isLocal,thinkingField:F==null?void 0:F.thinkingField,models:F==null?void 0:F.models},editModelId:p.model.id})]})}function g8(e,t){const n=e.slice(0,t),s=n.lastIndexOf("@");if(s===-1)return null;const a=n.slice(s+1);return a.includes(" ")||a.includes(`
|
|
298
298
|
`)||a.includes(" ")?null:{query:a,startIndex:s}}const x8=L.forwardRef(function({text:t,cursorPos:n,workdir:s,onSelect:a},l){const u=g8(t,n),[c,d]=L.useState([]),[f,p]=L.useState(!1),[m,x]=L.useState(0),y=L.useRef(null),w=L.useRef([]),C=L.useRef(0),v=L.useRef([]);L.useEffect(()=>{C.current=m},[m]),L.useEffect(()=>{v.current=c},[c]),L.useEffect(()=>{if(!u){d([]);return}const _=setTimeout(()=>{S(u.query)},150);return()=>clearTimeout(_)},[u==null?void 0:u.query,s]);const S=async _=>{p(!0);try{const E=new URLSearchParams({q:_});s&&E.set("workdir",s);const T=await(await Ae(`/api/files?${E.toString()}`)).json();d(T),x(0),C.current=0}catch(E){console.error("File search failed:",E),d([])}finally{p(!1)}},b=L.useCallback(_=>{if(!u)return!1;switch(_.key){case"ArrowDown":return _.preventDefault(),x(E=>{var T;const N=Math.min(E+1,v.current.length-1);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.min(C.current+1,v.current.length-1),!0;case"ArrowUp":return _.preventDefault(),x(E=>{var T;const N=Math.max(E-1,0);return w.current[N]&&((T=w.current[N])==null||T.scrollIntoView({block:"nearest"})),N}),C.current=Math.max(C.current-1,0),!0;case"Enter":case"Tab":{const E=v.current;return E[C.current]?(_.preventDefault(),a(E[C.current],u.startIndex),!0):!1}case"Escape":return _.preventDefault(),d([]),!0}return!1},[u,a]);return L.useImperativeHandle(l,()=>({handleKeyDown:b}),[b]),L.useEffect(()=>{if(!u)return;const _=E=>{y.current&&!y.current.contains(E.target)&&d([])};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[u]),u?f?o.jsx("div",{className:"absolute bottom-full left-0 right-0 mb-2 z-50",children:o.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg",children:o.jsx("div",{className:"p-4 text-center",children:o.jsx(Di,{size:"sm"})})})}):c.length===0?null:o.jsx("div",{ref:y,className:"absolute bottom-full left-0 right-0 mb-2 z-50",children:o.jsx("div",{className:"bg-bg-secondary border border-border rounded-lg shadow-lg max-h-64 overflow-y-auto",children:o.jsx("ul",{className:"py-1",children:c.map((_,E)=>o.jsxs("li",{ref:N=>{w.current[E]=N},className:`px-3 py-2 cursor-pointer flex items-center gap-2 text-sm ${E===m?"bg-accent-primary/20 text-text-primary":"text-text-muted hover:bg-bg-tertiary"}`,onClick:()=>{u&&a(_,u.startIndex)},children:[_.type==="directory"?o.jsx(bl,{className:"w-4 h-4 shrink-0"}):o.jsx("span",{className:"w-4 h-4 shrink-0"}),o.jsx("span",{className:"truncate",children:_.path})]},_.path))})})}):null});function y8({input:e,setInput:t,attachments:n,setAttachments:s,dragOver:a,setDragOver:l,errorMessage:u,setErrorMessage:c,scrollContainerRef:d,sessionId:f,sessionMode:p,showHistory:m,history:x,selectedIndex:y,openHistory:w,closeHistory:C,navigateUp:v,navigateDown:S,selectCurrent:b,isAutoScrollActive:_,setAutoScroll:E,onOpenMessageSearch:N,onOpenCommandsModal:T,onOpenWorkflowsModal:D,onSelectWorkflow:A,onSelectWorkflowWithSubGroup:O,clearInput:M}){const G=L.useRef(null),V=L.useRef(null),R=L.useRef(0),U=L.useRef(0),W=L.useRef(null),z=Fu(),J=Re(ne=>ne.stopGeneration),Z=Re(ne=>ne.cancelQueued),H=Re(ne=>ne.queuedMessages),I=Re(ne=>ne.restoredInput),$=Re(ne=>ne.clearRestoredInput),q=Re(ne=>{var xe;return(xe=ne.currentSession)==null?void 0:xe.workdir}),B=Re(ne=>ne.currentSession),ee=L.useRef(!1),{sendMessage:Q}=WC(E);L.useEffect(()=>{var ne;I!==null&&(t(I),$(),(ne=G.current)==null||ne.focus())},[I,t,$]);const te=L.useCallback(()=>{const ne=G.current;if(!ne)return;const xe=e.length>=R.current;R.current=e.length,xe||(ne.style.height="auto"),ne.style.height=`${Math.min(200,ne.scrollHeight)}px`},[e]);L.useEffect(()=>{if(!f)return;const ne=`openfox:draft:${f}`,xe=localStorage.getItem(ne);xe!==null&&t(xe)},[f,t]),L.useEffect(()=>{var ne;(ne=G.current)==null||ne.focus(),te()},[f,te]),L.useEffect(()=>{if(!f)return;const ne=`openfox:draft:${f}`,xe=setTimeout(()=>{e?localStorage.setItem(ne,e):localStorage.removeItem(ne)},500);return()=>clearTimeout(xe)},[f,e]),L.useEffect(()=>{te()},[e,te]),L.useEffect(()=>{const ne=G.current;if(!ne)return;const xe=async He=>{var rt;if(document.activeElement!==ne)return;const Ze=(rt=He.clipboardData)==null?void 0:rt.items;if(Ze){for(const kt of Array.from(Ze))if(kt.type.startsWith("image/")){He.preventDefault();const ge=kt.getAsFile();if(!ge)continue;await Em(ge,Ne=>s([...n,Ne]),c,{filename:"pasted-image"})}}};return ne.addEventListener("paste",xe),()=>ne.removeEventListener("paste",xe)},[n,s,c]);const Y=ne=>{ne.preventDefault(),!(!e.trim()&&n.length===0)&&(Q(e,n.length>0?n:void 0),M())},F=ne=>{var xe;if(!((xe=W.current)!=null&&xe.handleKeyDown(ne))){if(m)switch(ne.key){case"Enter":{ne.preventDefault();const He=b();He&&(t(He),C());return}case"Escape":ne.preventDefault(),C(),z&&J();return;case"ArrowUp":ne.preventDefault(),v();return;case"ArrowDown":ne.preventDefault(),S();return}if(ne.key==="ArrowUp"&&e.trim()===""&&!m){ne.preventDefault(),w();return}ne.key==="Enter"&&!ne.shiftKey&&(ne.preventDefault(),Y(ne))}},ue=L.useCallback(async ne=>{const xe=ne.target.files;if(!(!xe||xe.length===0)){c(null);for(const He of Array.from(xe))await Em(He,Ze=>s([...n,Ze]),c);V.current&&(V.current.value="")}},[n,s,c]),oe=L.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),l(!0)},[l]),ke=L.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),l(!1)},[l]),Se=L.useCallback(async ne=>{ne.preventDefault(),ne.stopPropagation(),l(!1),c(null);const xe=ne.dataTransfer.files;if(!(!xe||xe.length===0))for(const He of Array.from(xe))await Em(He,Ze=>s([...n,Ze]),c)},[n,s,l,c]),Te=L.useCallback(ne=>{s(n.filter(xe=>xe.id!==ne))},[n,s]),fe=L.useCallback(()=>{var ne;(ne=V.current)==null||ne.click()},[]),ae=()=>{var ne;!e.trim()&&n.length===0||((ne=d.current)==null||ne.scrollTo({top:d.current.scrollHeight,behavior:"smooth"}),Q(e,n),M())},ce=L.useCallback((ne,xe)=>{const Ze=ne.type==="directory"?"/":" ",rt=e.slice(0,xe),kt=e.slice(U.current),ge=`${rt}@${ne.path}${Ze}${kt}`;t(ge);const Ne=xe+ne.path.length+2;U.current=Ne,G.current&&(G.current.selectionStart=Ne,G.current.selectionEnd=Ne,G.current.focus())},[e,t]),se=L.useCallback(ne=>{const xe=ne.target.value;t(xe),m&&C(),U.current=ne.target.selectionStart,!ee.current&&f&&xe&&B&&B.messages.length===0&&(ee.current=!0,Ae(`/api/sessions/${f}/warmup`,{method:"POST"}).catch(()=>{}))},[t,m,C,f,B]),je=L.useCallback(ne=>{U.current=ne.target.selectionStart},[]),_e=L.useCallback(ne=>{U.current=ne.currentTarget.selectionStart},[]);return o.jsxs("form",{onSubmit:Y,className:"relative p-2 md:p-4 bg-secondary",children:[z&&o.jsx("div",{className:"absolute -top-8 left-2 md:left-4 z-10",children:o.jsx(UB,{})}),o.jsxs("div",{className:`absolute -top-8 right-2 md:right-4 z-10 flex items-center gap-2 border${_?" border-transparent":" rounded backdrop-blur-xl saturate-150 border-border"}`,children:[o.jsx(Ap,{isActive:_,onToggle:E,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors"}),o.jsxs("button",{type:"button",onClick:N,className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1.5 px-2 py-0.5 rounded hover:bg-bg-tertiary transition-colors","aria-label":"Browse history",children:[o.jsx(bp,{}),"Browse history"]})]}),o.jsx("input",{ref:V,type:"file",accept:".png,.jpg,.jpeg,.gif",onChange:ue,className:"hidden",multiple:!0}),u&&o.jsx("div",{className:"mb-2 p-2 bg-red-500/10 border border-red-500/50 rounded text-red-300 text-sm",children:u}),n.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:n.map(ne=>o.jsx($B,{attachment:ne,onRemove:Te},ne.id))}),m&&o.jsx(HB,{history:x,selectedIndex:y,onSelect:ne=>{t(ne),C()},onEscape:C,onNavigate:ne=>{ne==="up"?v():S()}}),o.jsx(s8,{messages:H,onCancel:Z}),o.jsxs("div",{className:`flex items-end gap-3 p-3 rounded transition-colors ${a?"bg-accent-primary/10":"bg-primary"}`,onDragOver:oe,onDragLeave:ke,onDrop:Se,children:[o.jsxs("div",{className:"relative flex-1 min-w-0",children:[o.jsx("textarea",{id:$S,ref:G,value:e,onChange:se,onKeyDown:F,onSelect:je,onKeyUp:_e,placeholder:"What would you like to build?","data-testid":"chat-input-textarea",className:"w-full bg-transparent text-sm placeholder:text-text-muted resize-none overflow-y-auto focus:outline-none",style:{minHeight:"24px",maxHeight:"200px"},spellCheck:!1}),o.jsx(x8,{ref:W,text:e,cursorPos:U.current,workdir:q,onSelect:ce})]}),o.jsxs("div",{className:"flex items-center self-center gap-1.5",children:[z&&o.jsxs("button",{type:"button",onClick:()=>J(),"data-testid":"chat-stop-button",className:"flex items-center gap-1 px-4 py-1.5 rounded bg-accent-error/20 text-sm text-accent-error font-medium hover:bg-accent-error/30 transition-colors whitespace-nowrap",children:[o.jsx(jS,{}),"Abort"]}),o.jsxs("div",{className:"flex items-center",children:[o.jsx("button",{type:"button",onClick:ae,disabled:!e.trim()&&n.length===0,"data-testid":"chat-send-button",className:"px-4 py-1.5 rounded-l bg-accent-primary/20 text-sm text-accent-primary font-medium hover:bg-accent-primary/30 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:"Send"}),o.jsx(n8,{onSendCommand:(ne,xe,He,Ze)=>{var kt;xe&&p!==xe&&Re.getState().switchMode(xe);const rt=He&&He.trim()?`${He.trim()}
|
|
299
299
|
|
|
300
300
|
${ne}`:ne;(kt=d.current)==null||kt.scrollTo({top:d.current.scrollHeight,behavior:"smooth"}),Q(rt,Ze!=null&&Ze.length?Ze:void 0,{messageKind:"command",isSystemGenerated:!0}),M()},onSelectWorkflow:A,onSelectWorkflowWithSubGroup:O,onOpenCommandsManager:T,onOpenWorkflowsManager:D,onAttach:fe,textareaContent:e,attachments:n.length>0?n:void 0})]})]})]}),o.jsxs("div",{className:"mt-3 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(u8,{}),o.jsx(d8,{})]}),o.jsx(p8,{})]})]})}function KC(e,t=[]){const n=[];let s=null,a,l=1;const u=new Map,c=new Map;for(const f of t)f.type==="message"?u.set(f.message.id,f):f.type==="subagent"&&c.set(f.subAgentId,f);const d=()=>{if(!s)return;const f=s,p=c.get(f.subAgentId);p&&p.type==="subagent"&&p.messages.length===f.messages.length&&p.messages.every((x,y)=>x===f.messages[y])?n.push(p):n.push({type:"subagent",subAgentId:f.subAgentId,subAgentType:f.subAgentType,messages:f.messages}),s=null};for(const f of e)if(f.role!=="tool")if(f.contextWindowId&&a&&f.contextWindowId!==a&&(d(),l++,n.push({type:"context-divider",windowSequence:l})),a=f.contextWindowId,f.subAgentId&&f.subAgentType)s&&s.subAgentId===f.subAgentId?s.messages.push(f):(d(),s={subAgentId:f.subAgentId,subAgentType:f.subAgentType,messages:[f]});else{d();const p=u.get(f.id);p&&p.type==="message"&&p.message===f?n.push(p):n.push({type:"message",message:f})}return d(),n}function _8(e){const{year:t,month:n,day:s}=GS(e);return`${t}/${n}/${s} ${Yu(e)}`}function v8(e,t){return e.length<=t?e:e.substring(0,t)+"..."}const b8=10,S8=150;function w8(e){const t=[];if(e.recentUserPrompts)for(const n of e.recentUserPrompts)t.push({id:n.id,content:n.content,timestamp:n.timestamp,sessionId:e.id,sessionName:e.title||e.id});return t}function C8(e){return[...e].sort((s,a)=>new Date(a.timestamp).getTime()-new Date(s.timestamp).getTime()).slice(0,b8).reverse().map(s=>({id:s.id,content:s.content,timestamp:s.timestamp,formattedTimestamp:_8(s.timestamp),trimmedContent:v8(s.content,S8),sessionId:s.sessionId,sessionName:s.sessionName}))}function k8(e,t,n){const s=[],a=e.filter(l=>l.role==="user"&&!l.isSystemGenerated&&l.messageKind!=="auto-prompt");for(const l of a)s.push({id:l.id,content:l.content,timestamp:l.timestamp,sessionId:n??"",sessionName:"This session"});for(const l of t)n&&l.id===n||s.push(...w8(l));return C8(s)}function E8(e,t=[],n=null){const[s,a]=L.useState(0),[l,u]=L.useState(!1),c=L.useMemo(()=>k8(e,t,n),[e,t,n]),d=L.useCallback(()=>{c.length>0&&(a(c.length-1),u(!0))},[c.length]),f=L.useCallback(()=>{u(!1),a(0)},[]),p=L.useCallback(()=>{a(y=>c.length===0?y:y===0?c.length-1:y-1)},[c.length]),m=L.useCallback(()=>{a(y=>c.length===0?y:y===c.length-1?0:y+1)},[c.length]),x=L.useCallback(()=>{if(c.length===0||!l)return null;const y=c[s];return(y==null?void 0:y.content)??null},[c,s,l]);return{history:c,selectedIndex:s,showHistory:l,openHistory:d,closeHistory:f,navigateUp:p,navigateDown:m,selectCurrent:x}}L.memo(function({item:t}){const[n,s]=L.useState(!1);return t.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..."}),t.filename&&o.jsxs("span",{className:"text-amber-400/70",children:["(",t.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:()=>s(!n),className:"text-xs text-accent-primary hover:text-accent-primary/80 transition-colors",children:n?"Hide":"Show"})]}),n&&t.description&&o.jsx("div",{className:"mt-2 text-xs prose prose-invert prose-sm max-w-none",children:o.jsx(us,{content:t.description})})]})]})});function j8({criteriaSidebarOpen:e,onCriteriaSidebarToggle:t}={}){const n=e??!0,[s,a]=L.useState(""),[l,u]=L.useState([]),[c,d]=L.useState(!1),[f,p]=L.useState(null),[m,x]=L.useState(!1),[y,w]=L.useState(!1),[C,v]=L.useState(!1),[S,b]=L.useState(!1),[_,E]=L.useState(null),N=L.useRef(null),T=Re(ce=>ce.currentSession),D=Re(ce=>ce.messages),A=Re(ce=>ce.sessions),O=Fu(),M=Re(ce=>ce.stopGeneration),G=mt(ce=>ce.defaults),V=mt(ce=>ce.userItems),R=[...G,...V].filter(ce=>!ce.subagent),{history:U,selectedIndex:W,showHistory:z,openHistory:J,closeHistory:Z,navigateUp:H,navigateDown:I,selectCurrent:$}=E8(D,A,T==null?void 0:T.id);L.useEffect(()=>{const ce=se=>{E(se.detail.stats)};return window.addEventListener("open-turn-stats",ce),()=>window.removeEventListener("open-turn-stats",ce)},[]),L.useEffect(()=>{Ct.getState().fetchWorkflows()},[]),L.useEffect(()=>{const ce=se=>{(se.ctrlKey||se.metaKey)&&se.key==="f"&&(se.preventDefault(),b(!0))};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[]);const{maxVisibleItems:q}=Li(),B=L.useRef([]),{displayItems:ee,hiddenCount:Q}=L.useMemo(()=>{const ce=KC(D,B.current);return B.current=ce,q>0&&ce.length>q?{displayItems:ce.slice(-q),hiddenCount:ce.length-q}:{displayItems:ce,hiddenCount:0}},[D,q]),{isAutoScrollActive:te,setAutoScroll:Y}=Qu(N,T),{sendMessage:F,launchWorkflow:ue}=WC(Y),oe=L.useCallback((ce,se)=>{ue(void 0,void 0,ce,se)},[ue]),ke=L.useCallback(ce=>{var je;Y(!1);const se=document.querySelector(`[data-item-index="${ce}"]`);se&&(se.scrollIntoView({behavior:"smooth",block:"start"}),(je=se.closest('[data-testid="chat-scroll-container"]'))==null||je.scrollBy(0,-80))},[Y]);L.useEffect(()=>{const ce=se=>{const je=C||m||y||S||_;se.key==="Escape"&&O&&!je&&M(),se.key==="ScrollLock"&&Y(!te)};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[O,M,te,C,m,y,S,_]);const Se=Sp();DS(Se.quickAction,()=>{v(!0)}),Qj(Se.agentSwitching,R,ce=>{Re.getState().switchMode(ce)});const Te=ce=>{const se=s.trim()?s:void 0,je=l.length>0?l:void 0;ue(se,je,ce),ae()},fe=(ce,se)=>{const je=s.trim()?s:void 0,_e=l.length>0?l:void 0;ue(je,_e,ce,se),ae()},ae=()=>{a(""),u([]),T!=null&&T.id&&localStorage.removeItem(`openfox:draft:${T.id}`)};return o.jsxs(o.Fragment,{children:[o.jsxs(LT,{criteriaSidebarOpen:n,onCriteriaSidebarToggle:t,messages:D,children:[o.jsx(OT,{}),_&&o.jsx(MT,{stats:_,onClose:()=>E(null)}),o.jsx(xB,{}),o.jsx(pB,{displayItems:ee,scrollContainerRef:N,highlightedMessageId:null,onLaunchWorkflow:oe,hiddenCount:Q}),o.jsx(y8,{input:s,setInput:a,attachments:l,setAttachments:u,dragOver:c,setDragOver:d,errorMessage:f,setErrorMessage:p,scrollContainerRef:N,sessionId:T==null?void 0:T.id,sessionMode:T==null?void 0:T.mode,showHistory:z,history:U,selectedIndex:W,openHistory:J,closeHistory:Z,navigateUp:H,navigateDown:I,selectCurrent:$,isAutoScrollActive:te,setAutoScroll:Y,onOpenMessageSearch:()=>b(!0),onOpenCommandsModal:()=>x(!0),onOpenWorkflowsModal:()=>w(!0),onSelectWorkflow:Te,onSelectWorkflowWithSubGroup:fe,clearInput:ae}),o.jsx(BC,{isOpen:m,onClose:()=>x(!1)}),o.jsx(HC,{isOpen:y,onClose:()=>w(!1)}),o.jsx(AB,{isOpen:C,onClose:()=>v(!1),onSearchMessages:()=>b(!0),isAutoScrollActive:te,onToggleAutoScroll:Y,textareaContent:s,onCloseComplete:Mm,onCloseCompleteAction:()=>window.dispatchEvent(new CustomEvent("open-session-dropdown")),onSelectCommand:async(ce,se)=>{const je=await en.getState().fetchCommand(ce);if(je){const _e=se!=null&&se.trim()?`${se.trim()}
|