@exellix/jobs-ui 2.0.1 → 2.0.2
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/README.md
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
> A **JobRun** is one graph run on one input. See [`temp/jobs/`](../temp/jobs/README.md) for the design.
|
|
13
13
|
|
|
14
|
+
> **Migration from 1.x:** `@exellix/jobs-ui@1.x` bundled the HTTP API and dashboard in one package. **2.x is dashboard-only** — use [`@exellix/jobs-api`](../jobs-api/README.md) for the REST server and programmatic queries.
|
|
15
|
+
|
|
14
16
|
## Install
|
|
15
17
|
|
|
16
18
|
```bash
|
|
@@ -58,4 +58,4 @@ Error generating stack: `+n.message+`
|
|
|
58
58
|
*/var Sd=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,Vy=/^[\\/]{2}/;function Wb(l,s){return s+l.replace(/\\/g,"/")}var sy="popstate";function ry(l){return typeof l=="object"&&l!=null&&"pathname"in l&&"search"in l&&"hash"in l&&"state"in l&&"key"in l}function Pb(l={}){function s(u,d){var g;let f=(g=d.state)==null?void 0:g.masked,{pathname:p,search:m,hash:y}=f||u.location;return ud("",{pathname:p,search:m,hash:y},d.state&&d.state.usr||null,d.state&&d.state.key||"default",f?{pathname:u.location.pathname,search:u.location.search,hash:u.location.hash}:void 0)}function c(u,d){return typeof d=="string"?d:Ns(d)}return tj(s,c,null,l)}function Ve(l,s){if(l===!1||l===null||typeof l>"u")throw new Error(s)}function sa(l,s){if(!l){typeof console<"u"&&console.warn(s);try{throw new Error(s)}catch{}}}function ej(){return Math.random().toString(36).substring(2,10)}function uy(l,s){return{usr:l.state,key:l.key,idx:s,masked:l.mask?{pathname:l.pathname,search:l.search,hash:l.hash}:void 0}}function ud(l,s,c=null,u,d){return{pathname:typeof l=="string"?l:l.pathname,search:"",hash:"",...typeof s=="string"?Si(s):s,state:c,key:s&&s.key||u||ej(),mask:d}}function Ns({pathname:l="/",search:s="",hash:c=""}){return s&&s!=="?"&&(l+=s.charAt(0)==="?"?s:"?"+s),c&&c!=="#"&&(l+=c.charAt(0)==="#"?c:"#"+c),l}function Si(l){let s={};if(l){let c=l.indexOf("#");c>=0&&(s.hash=l.substring(c),l=l.substring(0,c));let u=l.indexOf("?");u>=0&&(s.search=l.substring(u),l=l.substring(0,u)),l&&(s.pathname=l)}return s}function tj(l,s,c,u={}){let{window:d=document.defaultView,v5Compat:f=!1}=u,p=d.history,m="POP",y=null,g=b();g==null&&(g=0,p.replaceState({...p.state,idx:g},""));function b(){return(p.state||{idx:null}).idx}function x(){m="POP";let H=b(),U=H==null?null:H-g;g=H,y&&y({action:m,location:q.location,delta:U})}function T(H,U){m="PUSH";let X=ry(H)?H:ud(q.location,H,U);g=b()+1;let G=uy(X,g),V=q.createHref(X.mask||X);try{p.pushState(G,"",V)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;d.location.assign(V)}f&&y&&y({action:m,location:q.location,delta:1})}function R(H,U){m="REPLACE";let X=ry(H)?H:ud(q.location,H,U);g=b();let G=uy(X,g),V=q.createHref(X.mask||X);p.replaceState(G,"",V),f&&y&&y({action:m,location:q.location,delta:0})}function w(H){return aj(d,H)}let q={get action(){return m},get location(){return l(d,p)},listen(H){if(y)throw new Error("A history only accepts one active listener");return d.addEventListener(sy,x),y=H,()=>{d.removeEventListener(sy,x),y=null}},createHref(H){return s(d,H)},createURL:w,encodeLocation(H){let U=w(H);return{pathname:U.pathname,search:U.search,hash:U.hash}},push:T,replace:R,go(H){return p.go(H)}};return q}function aj(l,s,c=!1){let u="http://localhost";l&&(u=l.location.origin!=="null"?l.location.origin:l.location.href),Ve(u,"No window.location.(origin|href) available to create URL");let d=typeof s=="string"?s:Ns(s);return d=d.replace(/ $/,"%20"),!c&&Vy.test(d)&&(d=u+d),new URL(d,u)}function $y(l,s,c="/"){return nj(l,s,c,!1)}function nj(l,s,c,u,d){let f=typeof s=="string"?Si(s):s,p=Fa(f.pathname||"/",c);if(p==null)return null;let m=lj(l),y=null,g=pj(p);for(let b=0;y==null&&b<m.length;++b)y=mj(m[b],g,u);return y}function lj(l){let s=Jy(l);return ij(s),s}function Jy(l,s=[],c=[],u="",d=!1){let f=(p,m,y=d,g)=>{let b={relativePath:g===void 0?p.path||"":g,caseSensitive:p.caseSensitive===!0,childrenIndex:m,route:p};if(b.relativePath.startsWith("/")){if(!b.relativePath.startsWith(u)&&y)return;Ve(b.relativePath.startsWith(u),`Absolute route path "${b.relativePath}" nested under path "${u}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),b.relativePath=b.relativePath.slice(u.length)}let x=ma([u,b.relativePath]),T=c.concat(b);p.children&&p.children.length>0&&(Ve(p.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${x}".`),Jy(p.children,s,T,x,y)),!(p.path==null&&!p.index)&&s.push({path:x,score:fj(x,p.index),routesMeta:T.map((R,w)=>{let[q,H]=Wy(R.relativePath,R.caseSensitive,w===T.length-1);return{...R,matcher:q,compiledParams:H}})})};return l.forEach((p,m)=>{var y;if(p.path===""||!((y=p.path)!=null&&y.includes("?")))f(p,m);else for(let g of Fy(p.path))f(p,m,!0,g)}),s}function Fy(l){let s=l.split("/");if(s.length===0)return[];let[c,...u]=s,d=c.endsWith("?"),f=c.replace(/\?$/,"");if(u.length===0)return d?[f,""]:[f];let p=Fy(u.join("/")),m=[];return m.push(...p.map(y=>y===""?f:[f,y].join("/"))),d&&m.push(...p),m.map(y=>l.startsWith("/")&&y===""?"/":y)}function ij(l){l.sort((s,c)=>s.score!==c.score?c.score-s.score:hj(s.routesMeta.map(u=>u.childrenIndex),c.routesMeta.map(u=>u.childrenIndex)))}var sj=/^:[\w-]+$/,rj=3,uj=2,cj=1,oj=10,dj=-2,cy=l=>l==="*";function fj(l,s){let c=l.split("/"),u=c.length;return c.some(cy)&&(u+=dj),s&&(u+=uj),c.filter(d=>!cy(d)).reduce((d,f)=>d+(sj.test(f)?rj:f===""?cj:oj),u)}function hj(l,s){return l.length===s.length&&l.slice(0,-1).every((u,d)=>u===s[d])?l[l.length-1]-s[s.length-1]:0}function mj(l,s,c=!1){let{routesMeta:u}=l,d={},f="/",p=[];for(let m=0;m<u.length;++m){let y=u[m],g=m===u.length-1,b=f==="/"?s:s.slice(f.length)||"/",x={path:y.relativePath,caseSensitive:y.caseSensitive,end:g},T=y.matcher&&y.compiledParams?Iy(x,b,y.matcher,y.compiledParams):su(x,b),R=y.route;if(!T&&g&&c&&!u[u.length-1].route.index&&(T=su({path:y.relativePath,caseSensitive:y.caseSensitive,end:!1},b)),!T)return null;Object.assign(d,T.params),p.push({params:d,pathname:ma([f,T.pathname]),pathnameBase:gj(ma([f,T.pathnameBase])),route:R}),T.pathnameBase!=="/"&&(f=ma([f,T.pathnameBase]))}return p}function su(l,s){typeof l=="string"&&(l={path:l,caseSensitive:!1,end:!0});let[c,u]=Wy(l.path,l.caseSensitive,l.end);return Iy(l,s,c,u)}function Iy(l,s,c,u){let d=s.match(c);if(!d)return null;let f=d[0],p=f.replace(/(.)\/+$/,"$1"),m=d.slice(1);return{params:u.reduce((g,{paramName:b,isOptional:x},T)=>{if(b==="*"){let w=m[T]||"";p=f.slice(0,f.length-w.length).replace(/(.)\/+$/,"$1")}const R=m[T];return x&&!R?g[b]=void 0:g[b]=(R||"").replace(/%2F/g,"/"),g},{}),pathname:f,pathnameBase:p,pattern:l}}function Wy(l,s=!1,c=!0){sa(l==="*"||!l.endsWith("*")||l.endsWith("/*"),`Route path "${l}" will be treated as if it were "${l.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${l.replace(/\*$/,"/*")}".`);let u=[],d="^"+l.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(p,m,y,g,b)=>{if(u.push({paramName:m,isOptional:y!=null}),y){let x=b.charAt(g+p.length);return x&&x!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return l.endsWith("*")?(u.push({paramName:"*"}),d+=l==="*"||l==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):c?d+="\\/*$":l!==""&&l!=="/"&&(d+="(?:(?=\\/|$))"),[new RegExp(d,s?void 0:"i"),u]}function pj(l){try{return l.split("/").map(s=>decodeURIComponent(s).replace(/\//g,"%2F")).join("/")}catch(s){return sa(!1,`The URL path "${l}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${s}).`),l}}function Fa(l,s){if(s==="/")return l;if(!l.toLowerCase().startsWith(s.toLowerCase()))return null;let c=s.endsWith("/")?s.length-1:s.length,u=l.charAt(c);return u&&u!=="/"?null:l.slice(c)||"/"}function yj(l,s="/"){let{pathname:c,search:u="",hash:d=""}=typeof l=="string"?Si(l):l,f;return c?(c=Py(c),c.startsWith("/")?f=oy(c.substring(1),"/"):f=oy(c,s)):f=s,{pathname:f,search:xj(u),hash:bj(d)}}function oy(l,s){let c=ru(s).split("/");return l.split("/").forEach(d=>{d===".."?c.length>1&&c.pop():d!=="."&&c.push(d)}),c.length>1?c.join("/"):"/"}function Yo(l,s,c,u){return`Cannot include a '${l}' character in a manually specified \`to.${s}\` field [${JSON.stringify(u)}]. Please separate it out to the \`to.${c}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function vj(l){return l.filter((s,c)=>c===0||s.route.path&&s.route.path.length>0)}function Nd(l){let s=vj(l);return s.map((c,u)=>u===s.length-1?c.pathname:c.pathnameBase)}function cu(l,s,c,u=!1){let d;typeof l=="string"?d=Si(l):(d={...l},Ve(!d.pathname||!d.pathname.includes("?"),Yo("?","pathname","search",d)),Ve(!d.pathname||!d.pathname.includes("#"),Yo("#","pathname","hash",d)),Ve(!d.search||!d.search.includes("#"),Yo("#","search","hash",d)));let f=l===""||d.pathname==="",p=f?"/":d.pathname,m;if(p==null)m=c;else{let x=s.length-1;if(!u&&p.startsWith("..")){let T=p.split("/");for(;T[0]==="..";)T.shift(),x-=1;d.pathname=T.join("/")}m=x>=0?s[x]:"/"}let y=yj(d,m),g=p&&p!=="/"&&p.endsWith("/"),b=(f||p===".")&&c.endsWith("/");return!y.pathname.endsWith("/")&&(g||b)&&(y.pathname+="/"),y}var Py=l=>l.replace(/[\\/]{2,}/g,"/"),ma=l=>Py(l.join("/")),ru=l=>l.replace(/\/+$/,""),gj=l=>ru(l).replace(/^\/*/,"/"),xj=l=>!l||l==="?"?"":l.startsWith("?")?l:"?"+l,bj=l=>!l||l==="#"?"":l.startsWith("#")?l:"#"+l,jj=class{constructor(l,s,c,u=!1){this.status=l,this.statusText=s||"",this.internal=u,c instanceof Error?(this.data=c.toString(),this.error=c):this.data=c}};function Sj(l){return l!=null&&typeof l.status=="number"&&typeof l.statusText=="string"&&typeof l.internal=="boolean"&&"data"in l}function Nj(l){let s=l.map(c=>c.route.path).filter(Boolean);return ma(s)||"/"}var ev=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function tv(l,s){let c=l;if(typeof c!="string"||!Sd.test(c))return{absoluteURL:void 0,isExternal:!1,to:c};let u=c,d=!1;if(ev)try{let f=new URL(window.location.href),p=Vy.test(c)?new URL(Wb(c,f.protocol)):new URL(c),m=Fa(p.pathname,s);p.origin===f.origin&&m!=null?c=m+p.search+p.hash:d=!0}catch{sa(!1,`<Link to="${c}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:u,isExternal:d,to:c}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var av=["POST","PUT","PATCH","DELETE"];new Set(av);var Ej=["GET",...av];new Set(Ej);var Cj=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function Tj(l){try{return Cj.includes(new URL(l).protocol)}catch{return!1}}var Ni=j.createContext(null);Ni.displayName="DataRouter";var ou=j.createContext(null);ou.displayName="DataRouterState";var nv=j.createContext(!1);function Rj(){return j.useContext(nv)}var lv=j.createContext({isTransitioning:!1});lv.displayName="ViewTransition";var Aj=j.createContext(new Map);Aj.displayName="Fetchers";var Oj=j.createContext(null);Oj.displayName="Await";var Vt=j.createContext(null);Vt.displayName="Navigation";var Ms=j.createContext(null);Ms.displayName="Location";var pa=j.createContext({outlet:null,matches:[],isDataRoute:!1});pa.displayName="Route";var Ed=j.createContext(null);Ed.displayName="RouteError";var iv="REACT_ROUTER_ERROR",zj="REDIRECT",Mj="ROUTE_ERROR_RESPONSE";function Dj(l){if(l.startsWith(`${iv}:${zj}:{`))try{let s=JSON.parse(l.slice(28));if(typeof s=="object"&&s&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.location=="string"&&typeof s.reloadDocument=="boolean"&&typeof s.replace=="boolean")return s}catch{}}function wj(l){if(l.startsWith(`${iv}:${Mj}:{`))try{let s=JSON.parse(l.slice(40));if(typeof s=="object"&&s&&typeof s.status=="number"&&typeof s.statusText=="string")return new jj(s.status,s.statusText,s.data)}catch{}}function _j(l,{relative:s}={}){Ve(Ei(),"useHref() may be used only in the context of a <Router> component.");let{basename:c,navigator:u}=j.useContext(Vt),{hash:d,pathname:f,search:p}=ws(l,{relative:s}),m=f;return c!=="/"&&(m=f==="/"?c:ma([c,f])),u.createHref({pathname:m,search:p,hash:d})}function Ei(){return j.useContext(Ms)!=null}function ra(){return Ve(Ei(),"useLocation() may be used only in the context of a <Router> component."),j.useContext(Ms).location}var sv="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function rv(l){j.useContext(Vt).static||j.useLayoutEffect(l)}function Bn(){let{isDataRoute:l}=j.useContext(pa);return l?Vj():qj()}function qj(){Ve(Ei(),"useNavigate() may be used only in the context of a <Router> component.");let l=j.useContext(Ni),{basename:s,navigator:c}=j.useContext(Vt),{matches:u}=j.useContext(pa),{pathname:d}=ra(),f=JSON.stringify(Nd(u)),p=j.useRef(!1);return rv(()=>{p.current=!0}),j.useCallback((y,g={})=>{if(sa(p.current,sv),!p.current)return;if(typeof y=="number"){c.go(y);return}let b=cu(y,JSON.parse(f),d,g.relative==="path");l==null&&s!=="/"&&(b.pathname=b.pathname==="/"?s:ma([s,b.pathname])),(g.replace?c.replace:c.push)(b,g.state,g)},[s,c,f,d,l])}j.createContext(null);function Ds(){let{matches:l}=j.useContext(pa),s=l[l.length-1];return(s==null?void 0:s.params)??{}}function ws(l,{relative:s}={}){let{matches:c}=j.useContext(pa),{pathname:u}=ra(),d=JSON.stringify(Nd(c));return j.useMemo(()=>cu(l,JSON.parse(d),u,s==="path"),[l,d,u,s])}function Uj(l,s){return uv(l,s)}function uv(l,s,c){var H;Ve(Ei(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:u}=j.useContext(Vt),{matches:d}=j.useContext(pa),f=d[d.length-1],p=f?f.params:{},m=f?f.pathname:"/",y=f?f.pathnameBase:"/",g=f&&f.route;{let U=g&&g.path||"";ov(m,!g||U.endsWith("*")||U.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${m}" (under <Route path="${U}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
59
59
|
|
|
60
60
|
Please change the parent <Route path="${U}"> to <Route path="${U==="/"?"*":`${U}/*`}">.`)}let b=ra(),x;if(s){let U=typeof s=="string"?Si(s):s;Ve(y==="/"||((H=U.pathname)==null?void 0:H.startsWith(y)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${y}" but pathname "${U.pathname}" was given in the \`location\` prop.`),x=U}else x=b;let T=x.pathname||"/",R=T;if(y!=="/"){let U=y.replace(/^\//,"").split("/");R="/"+T.replace(/^\//,"").split("/").slice(U.length).join("/")}let w=c&&c.state.matches.length?c.state.matches.map(U=>Object.assign(U,{route:c.manifest[U.route.id]||U.route})):$y(l,{pathname:R});sa(g||w!=null,`No routes matched location "${x.pathname}${x.search}${x.hash}" `),sa(w==null||w[w.length-1].route.element!==void 0||w[w.length-1].route.Component!==void 0||w[w.length-1].route.lazy!==void 0,`Matched leaf route at location "${x.pathname}${x.search}${x.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let q=Gj(w&&w.map(U=>Object.assign({},U,{params:Object.assign({},p,U.params),pathname:ma([y,u.encodeLocation?u.encodeLocation(U.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:U.pathname]),pathnameBase:U.pathnameBase==="/"?y:ma([y,u.encodeLocation?u.encodeLocation(U.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:U.pathnameBase])})),d,c);return s&&q?j.createElement(Ms.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...x},navigationType:"POP"}},q):q}function Lj(){let l=Zj(),s=Sj(l)?`${l.status} ${l.statusText}`:l instanceof Error?l.message:JSON.stringify(l),c=l instanceof Error?l.stack:null,u="rgba(200,200,200, 0.5)",d={padding:"0.5rem",backgroundColor:u},f={padding:"2px 4px",backgroundColor:u},p=null;return console.error("Error handled by React Router default ErrorBoundary:",l),p=j.createElement(j.Fragment,null,j.createElement("p",null,"💿 Hey developer 👋"),j.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",j.createElement("code",{style:f},"ErrorBoundary")," or"," ",j.createElement("code",{style:f},"errorElement")," prop on your route.")),j.createElement(j.Fragment,null,j.createElement("h2",null,"Unexpected Application Error!"),j.createElement("h3",{style:{fontStyle:"italic"}},s),c?j.createElement("pre",{style:d},c):null,p)}var Bj=j.createElement(Lj,null),cv=class extends j.Component{constructor(l){super(l),this.state={location:l.location,revalidation:l.revalidation,error:l.error}}static getDerivedStateFromError(l){return{error:l}}static getDerivedStateFromProps(l,s){return s.location!==l.location||s.revalidation!=="idle"&&l.revalidation==="idle"?{error:l.error,location:l.location,revalidation:l.revalidation}:{error:l.error!==void 0?l.error:s.error,location:s.location,revalidation:l.revalidation||s.revalidation}}componentDidCatch(l,s){this.props.onError?this.props.onError(l,s):console.error("React Router caught the following error during render",l)}render(){let l=this.state.error;if(this.context&&typeof l=="object"&&l&&"digest"in l&&typeof l.digest=="string"){const c=wj(l.digest);c&&(l=c)}let s=l!==void 0?j.createElement(pa.Provider,{value:this.props.routeContext},j.createElement(Ed.Provider,{value:l,children:this.props.component})):this.props.children;return this.context?j.createElement(Hj,{error:l},s):s}};cv.contextType=nv;var Ko=new WeakMap;function Hj({children:l,error:s}){let{basename:c}=j.useContext(Vt);if(typeof s=="object"&&s&&"digest"in s&&typeof s.digest=="string"){let u=Dj(s.digest);if(u){let d=Ko.get(s);if(d)throw d;let f=tv(u.location,c),p=f.absoluteURL||f.to;if(Tj(p))throw new Error("Invalid redirect location");if(ev&&!Ko.get(s))if(f.isExternal||u.reloadDocument)window.location.href=p;else{const m=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(f.to,{replace:u.replace}));throw Ko.set(s,m),m}return j.createElement("meta",{httpEquiv:"refresh",content:`0;url=${p}`})}}return l}function Qj({routeContext:l,match:s,children:c}){let u=j.useContext(Ni);return u&&u.static&&u.staticContext&&(s.route.errorElement||s.route.ErrorBoundary)&&(u.staticContext._deepestRenderedBoundaryId=s.route.id),j.createElement(pa.Provider,{value:l},c)}function Gj(l,s=[],c){let u=c==null?void 0:c.state;if(l==null){if(!u)return null;if(u.errors)l=u.matches;else if(s.length===0&&!u.initialized&&u.matches.length>0)l=u.matches;else return null}let d=l,f=u==null?void 0:u.errors;if(f!=null){let b=d.findIndex(x=>x.route.id&&(f==null?void 0:f[x.route.id])!==void 0);Ve(b>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(f).join(",")}`),d=d.slice(0,Math.min(d.length,b+1))}let p=!1,m=-1;if(c&&u){p=u.renderFallback;for(let b=0;b<d.length;b++){let x=d[b];if((x.route.HydrateFallback||x.route.hydrateFallbackElement)&&(m=b),x.route.id){let{loaderData:T,errors:R}=u,w=x.route.loader&&!T.hasOwnProperty(x.route.id)&&(!R||R[x.route.id]===void 0);if(x.route.lazy||w){c.isStatic&&(p=!0),m>=0?d=d.slice(0,m+1):d=[d[0]];break}}}}let y=c==null?void 0:c.onError,g=u&&y?(b,x)=>{var T,R;y(b,{location:u.location,params:((R=(T=u.matches)==null?void 0:T[0])==null?void 0:R.params)??{},pattern:Nj(u.matches),errorInfo:x})}:void 0;return d.reduceRight((b,x,T)=>{let R,w=!1,q=null,H=null;u&&(R=f&&x.route.id?f[x.route.id]:void 0,q=x.route.errorElement||Bj,p&&(m<0&&T===0?(ov("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),w=!0,H=null):m===T&&(w=!0,H=x.route.hydrateFallbackElement||null)));let U=s.concat(d.slice(0,T+1)),X=()=>{let G;return R?G=q:w?G=H:x.route.Component?G=j.createElement(x.route.Component,null):x.route.element?G=x.route.element:G=b,j.createElement(Qj,{match:x,routeContext:{outlet:b,matches:U,isDataRoute:u!=null},children:G})};return u&&(x.route.ErrorBoundary||x.route.errorElement||T===0)?j.createElement(cv,{location:u.location,revalidation:u.revalidation,component:q,error:R,children:X(),routeContext:{outlet:null,matches:U,isDataRoute:!0},onError:g}):X()},null)}function Cd(l){return`${l} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function kj(l){let s=j.useContext(Ni);return Ve(s,Cd(l)),s}function Yj(l){let s=j.useContext(ou);return Ve(s,Cd(l)),s}function Kj(l){let s=j.useContext(pa);return Ve(s,Cd(l)),s}function Td(l){let s=Kj(l),c=s.matches[s.matches.length-1];return Ve(c.route.id,`${l} can only be used on routes that contain a unique "id"`),c.route.id}function Xj(){return Td("useRouteId")}function Zj(){var u;let l=j.useContext(Ed),s=Yj("useRouteError"),c=Td("useRouteError");return l!==void 0?l:(u=s.errors)==null?void 0:u[c]}function Vj(){let{router:l}=kj("useNavigate"),s=Td("useNavigate"),c=j.useRef(!1);return rv(()=>{c.current=!0}),j.useCallback(async(d,f={})=>{sa(c.current,sv),c.current&&(typeof d=="number"?await l.navigate(d):await l.navigate(d,{fromRouteId:s,...f}))},[l,s])}var dy={};function ov(l,s,c){!s&&!dy[l]&&(dy[l]=!0,sa(!1,c))}j.memo($j);function $j({routes:l,manifest:s,future:c,state:u,isStatic:d,onError:f}){return uv(l,void 0,{manifest:s,state:u,isStatic:d,onError:f})}function ka({to:l,replace:s,state:c,relative:u}){Ve(Ei(),"<Navigate> may be used only in the context of a <Router> component.");let{static:d}=j.useContext(Vt);sa(!d,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:f}=j.useContext(pa),{pathname:p}=ra(),m=Bn(),y=cu(l,Nd(f),p,u==="path"),g=JSON.stringify(y);return j.useEffect(()=>{m(JSON.parse(g),{replace:s,state:c,relative:u})},[m,g,u,s,c]),null}function Ze(l){Ve(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function Jj({basename:l="/",children:s=null,location:c,navigationType:u="POP",navigator:d,static:f=!1,useTransitions:p}){Ve(!Ei(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let m=l.replace(/^\/*/,"/"),y=j.useMemo(()=>({basename:m,navigator:d,static:f,useTransitions:p,future:{}}),[m,d,f,p]);typeof c=="string"&&(c=Si(c));let{pathname:g="/",search:b="",hash:x="",state:T=null,key:R="default",mask:w}=c,q=j.useMemo(()=>{let H=Fa(g,m);return H==null?null:{location:{pathname:H,search:b,hash:x,state:T,key:R,mask:w},navigationType:u}},[m,g,b,x,T,R,u,w]);return sa(q!=null,`<Router basename="${m}"> is not able to match the URL "${g}${b}${x}" because it does not start with the basename, so the <Router> won't render anything.`),q==null?null:j.createElement(Vt.Provider,{value:y},j.createElement(Ms.Provider,{children:s,value:q}))}function Fj({children:l,location:s}){return Uj(cd(l),s)}function cd(l,s=[]){let c=[];return j.Children.forEach(l,(u,d)=>{if(!j.isValidElement(u))return;let f=[...s,d];if(u.type===j.Fragment){c.push.apply(c,cd(u.props.children,f));return}Ve(u.type===Ze,`[${typeof u.type=="string"?u.type:u.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Ve(!u.props.index||!u.props.children,"An index route cannot have child routes.");let p={id:u.props.id||f.join("-"),caseSensitive:u.props.caseSensitive,element:u.props.element,Component:u.props.Component,index:u.props.index,path:u.props.path,middleware:u.props.middleware,loader:u.props.loader,action:u.props.action,hydrateFallbackElement:u.props.hydrateFallbackElement,HydrateFallback:u.props.HydrateFallback,errorElement:u.props.errorElement,ErrorBoundary:u.props.ErrorBoundary,hasErrorBoundary:u.props.hasErrorBoundary===!0||u.props.ErrorBoundary!=null||u.props.errorElement!=null,shouldRevalidate:u.props.shouldRevalidate,handle:u.props.handle,lazy:u.props.lazy};u.props.children&&(p.children=cd(u.props.children,f)),c.push(p)}),c}var tu="get",au="application/x-www-form-urlencoded";function du(l){return typeof HTMLElement<"u"&&l instanceof HTMLElement}function Ij(l){return du(l)&&l.tagName.toLowerCase()==="button"}function Wj(l){return du(l)&&l.tagName.toLowerCase()==="form"}function Pj(l){return du(l)&&l.tagName.toLowerCase()==="input"}function e0(l){return!!(l.metaKey||l.altKey||l.ctrlKey||l.shiftKey)}function t0(l,s){return l.button===0&&(!s||s==="_self")&&!e0(l)}function od(l=""){return new URLSearchParams(typeof l=="string"||Array.isArray(l)||l instanceof URLSearchParams?l:Object.keys(l).reduce((s,c)=>{let u=l[c];return s.concat(Array.isArray(u)?u.map(d=>[c,d]):[[c,u]])},[]))}function a0(l,s){let c=od(l);return s&&s.forEach((u,d)=>{c.has(d)||s.getAll(d).forEach(f=>{c.append(d,f)})}),c}var Pr=null;function n0(){if(Pr===null)try{new FormData(document.createElement("form"),0),Pr=!1}catch{Pr=!0}return Pr}var l0=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Xo(l){return l!=null&&!l0.has(l)?(sa(!1,`"${l}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${au}"`),null):l}function i0(l,s){let c,u,d,f,p;if(Wj(l)){let m=l.getAttribute("action");u=m?Fa(m,s):null,c=l.getAttribute("method")||tu,d=Xo(l.getAttribute("enctype"))||au,f=new FormData(l)}else if(Ij(l)||Pj(l)&&(l.type==="submit"||l.type==="image")){let m=l.form;if(m==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let y=l.getAttribute("formaction")||m.getAttribute("action");if(u=y?Fa(y,s):null,c=l.getAttribute("formmethod")||m.getAttribute("method")||tu,d=Xo(l.getAttribute("formenctype"))||Xo(m.getAttribute("enctype"))||au,f=new FormData(m,l),!n0()){let{name:g,type:b,value:x}=l;if(b==="image"){let T=g?`${g}.`:"";f.append(`${T}x`,"0"),f.append(`${T}y`,"0")}else g&&f.append(g,x)}}else{if(du(l))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');c=tu,u=null,d=au,p=l}return f&&d==="text/plain"&&(p=f,f=void 0),{action:u,method:c.toLowerCase(),encType:d,formData:f,body:p}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Rd(l,s){if(l===!1||l===null||typeof l>"u")throw new Error(s)}function dv(l,s,c,u){let d=typeof l=="string"?new URL(l,typeof window>"u"?"server://singlefetch/":window.location.origin):l;return c?d.pathname.endsWith("/")?d.pathname=`${d.pathname}_.${u}`:d.pathname=`${d.pathname}.${u}`:d.pathname==="/"?d.pathname=`_root.${u}`:s&&Fa(d.pathname,s)==="/"?d.pathname=`${ru(s)}/_root.${u}`:d.pathname=`${ru(d.pathname)}.${u}`,d}async function s0(l,s){if(l.id in s)return s[l.id];try{let c=await import(l.module);return s[l.id]=c,c}catch(c){return console.error(`Error loading route module \`${l.module}\`, reloading page...`),console.error(c),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function r0(l){return l==null?!1:l.href==null?l.rel==="preload"&&typeof l.imageSrcSet=="string"&&typeof l.imageSizes=="string":typeof l.rel=="string"&&typeof l.href=="string"}async function u0(l,s,c){let u=await Promise.all(l.map(async d=>{let f=s.routes[d.route.id];if(f){let p=await s0(f,c);return p.links?p.links():[]}return[]}));return f0(u.flat(1).filter(r0).filter(d=>d.rel==="stylesheet"||d.rel==="preload").map(d=>d.rel==="stylesheet"?{...d,rel:"prefetch",as:"style"}:{...d,rel:"prefetch"}))}function fy(l,s,c,u,d,f){let p=(y,g)=>c[g]?y.route.id!==c[g].route.id:!0,m=(y,g)=>{var b;return c[g].pathname!==y.pathname||((b=c[g].route.path)==null?void 0:b.endsWith("*"))&&c[g].params["*"]!==y.params["*"]};return f==="assets"?s.filter((y,g)=>p(y,g)||m(y,g)):f==="data"?s.filter((y,g)=>{var x;let b=u.routes[y.route.id];if(!b||!b.hasLoader)return!1;if(p(y,g)||m(y,g))return!0;if(y.route.shouldRevalidate){let T=y.route.shouldRevalidate({currentUrl:new URL(d.pathname+d.search+d.hash,window.origin),currentParams:((x=c[0])==null?void 0:x.params)||{},nextUrl:new URL(l,window.origin),nextParams:y.params,defaultShouldRevalidate:!0});if(typeof T=="boolean")return T}return!0}):[]}function c0(l,s,{includeHydrateFallback:c}={}){return o0(l.map(u=>{let d=s.routes[u.route.id];if(!d)return[];let f=[d.module];return d.clientActionModule&&(f=f.concat(d.clientActionModule)),d.clientLoaderModule&&(f=f.concat(d.clientLoaderModule)),c&&d.hydrateFallbackModule&&(f=f.concat(d.hydrateFallbackModule)),d.imports&&(f=f.concat(d.imports)),f}).flat(1))}function o0(l){return[...new Set(l)]}function d0(l){let s={},c=Object.keys(l).sort();for(let u of c)s[u]=l[u];return s}function f0(l,s){let c=new Set;return new Set(s),l.reduce((u,d)=>{let f=JSON.stringify(d0(d));return c.has(f)||(c.add(f),u.push({key:f,link:d})),u},[])}function Ad(){let l=j.useContext(Ni);return Rd(l,"You must render this element inside a <DataRouterContext.Provider> element"),l}function h0(){let l=j.useContext(ou);return Rd(l,"You must render this element inside a <DataRouterStateContext.Provider> element"),l}var Od=j.createContext(void 0);Od.displayName="FrameworkContext";function fu(){let l=j.useContext(Od);return Rd(l,"You must render this element inside a <HydratedRouter> element"),l}function m0(l,s){let c=j.useContext(Od),[u,d]=j.useState(!1),[f,p]=j.useState(!1),{onFocus:m,onBlur:y,onMouseEnter:g,onMouseLeave:b,onTouchStart:x}=s,T=j.useRef(null);j.useEffect(()=>{if(l==="render"&&p(!0),l==="viewport"){let q=U=>{U.forEach(X=>{p(X.isIntersecting)})},H=new IntersectionObserver(q,{threshold:.5});return T.current&&H.observe(T.current),()=>{H.disconnect()}}},[l]),j.useEffect(()=>{if(u){let q=setTimeout(()=>{p(!0)},100);return()=>{clearTimeout(q)}}},[u]);let R=()=>{d(!0)},w=()=>{d(!1),p(!1)};return c?l!=="intent"?[f,T,{}]:[f,T,{onFocus:xs(m,R),onBlur:xs(y,w),onMouseEnter:xs(g,R),onMouseLeave:xs(b,w),onTouchStart:xs(x,R)}]:[!1,T,{}]}function xs(l,s){return c=>{l&&l(c),c.defaultPrevented||s(c)}}function p0({page:l,...s}){let c=Rj(),{nonce:u}=fu(),{router:d}=Ad(),f=j.useMemo(()=>$y(d.routes,l,d.basename),[d.routes,l,d.basename]);return f?(s.nonce==null&&u&&(s={...s,nonce:u}),c?j.createElement(v0,{page:l,matches:f,...s}):j.createElement(g0,{page:l,matches:f,...s})):null}function y0(l){let{manifest:s,routeModules:c}=fu(),[u,d]=j.useState([]);return j.useEffect(()=>{let f=!1;return u0(l,s,c).then(p=>{f||d(p)}),()=>{f=!0}},[l,s,c]),u}function v0({page:l,matches:s,...c}){let u=ra(),{future:d}=fu(),{basename:f}=Ad(),p=j.useMemo(()=>{if(l===u.pathname+u.search+u.hash)return[];let m=dv(l,f,d.v8_trailingSlashAwareDataRequests,"rsc"),y=!1,g=[];for(let b of s)typeof b.route.shouldRevalidate=="function"?y=!0:g.push(b.route.id);return y&&g.length>0&&m.searchParams.set("_routes",g.join(",")),[m.pathname+m.search]},[f,d.v8_trailingSlashAwareDataRequests,l,u,s]);return j.createElement(j.Fragment,null,p.map(m=>j.createElement("link",{key:m,rel:"prefetch",as:"fetch",href:m,...c})))}function g0({page:l,matches:s,...c}){let u=ra(),{future:d,manifest:f,routeModules:p}=fu(),{basename:m}=Ad(),{loaderData:y,matches:g}=h0(),b=j.useMemo(()=>fy(l,s,g,f,u,"data"),[l,s,g,f,u]),x=j.useMemo(()=>fy(l,s,g,f,u,"assets"),[l,s,g,f,u]),T=j.useMemo(()=>{if(l===u.pathname+u.search+u.hash)return[];let q=new Set,H=!1;if(s.forEach(X=>{var V;let G=f.routes[X.route.id];!G||!G.hasLoader||(!b.some(P=>P.route.id===X.route.id)&&X.route.id in y&&((V=p[X.route.id])!=null&&V.shouldRevalidate)||G.hasClientLoader?H=!0:q.add(X.route.id))}),q.size===0)return[];let U=dv(l,m,d.v8_trailingSlashAwareDataRequests,"data");return H&&q.size>0&&U.searchParams.set("_routes",s.filter(X=>q.has(X.route.id)).map(X=>X.route.id).join(",")),[U.pathname+U.search]},[m,d.v8_trailingSlashAwareDataRequests,y,u,f,b,s,l,p]),R=j.useMemo(()=>c0(x,f),[x,f]),w=y0(x);return j.createElement(j.Fragment,null,T.map(q=>j.createElement("link",{key:q,rel:"prefetch",as:"fetch",href:q,...c})),R.map(q=>j.createElement("link",{key:q,rel:"modulepreload",href:q,...c})),w.map(({key:q,link:H})=>j.createElement("link",{key:q,nonce:c.nonce,...H,crossOrigin:H.crossOrigin??c.crossOrigin})))}function x0(...l){return s=>{l.forEach(c=>{typeof c=="function"?c(s):c!=null&&(c.current=s)})}}var b0=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{b0&&(window.__reactRouterVersion="7.18.0")}catch{}function j0({basename:l,children:s,useTransitions:c,window:u}){let d=j.useRef();d.current==null&&(d.current=Pb({window:u,v5Compat:!0}));let f=d.current,[p,m]=j.useState({action:f.action,location:f.location}),y=j.useCallback(g=>{c===!1?m(g):j.startTransition(()=>m(g))},[c]);return j.useLayoutEffect(()=>f.listen(y),[f,y]),j.createElement(Jj,{basename:l,children:s,location:p.location,navigationType:p.action,navigator:f,useTransitions:c})}var Ke=j.forwardRef(function({onClick:s,discover:c="render",prefetch:u="none",relative:d,reloadDocument:f,replace:p,mask:m,state:y,target:g,to:b,preventScrollReset:x,viewTransition:T,defaultShouldRevalidate:R,...w},q){let{basename:H,navigator:U,useTransitions:X}=j.useContext(Vt),G=typeof b=="string"&&Sd.test(b),V=tv(b,H);b=V.to;let P=_j(b,{relative:d}),J=ra(),Z=null;if(m){let pe=cu(m,[],J.mask?J.mask.pathname:"/",!0);H!=="/"&&(pe.pathname=pe.pathname==="/"?H:ma([H,pe.pathname])),Z=U.createHref(pe)}let[I,O,le]=m0(u,w),ue=E0(b,{replace:p,mask:m,state:y,target:g,preventScrollReset:x,relative:d,viewTransition:T,defaultShouldRevalidate:R,useTransitions:X});function de(pe){s&&s(pe),pe.defaultPrevented||ue(pe)}let se=!(V.isExternal||f),Ne=j.createElement("a",{...w,...le,href:(se?Z:void 0)||V.absoluteURL||P,onClick:se?de:s,ref:x0(q,O),target:g,"data-discover":!G&&c==="render"?"true":void 0});return I&&!G?j.createElement(j.Fragment,null,Ne,j.createElement(p0,{page:P})):Ne});Ke.displayName="Link";var ll=j.forwardRef(function({"aria-current":s="page",caseSensitive:c=!1,className:u="",end:d=!1,style:f,to:p,viewTransition:m,children:y,...g},b){let x=ws(p,{relative:g.relative}),T=ra(),R=j.useContext(ou),{navigator:w,basename:q}=j.useContext(Vt),H=R!=null&&O0(x)&&m===!0,U=w.encodeLocation?w.encodeLocation(x).pathname:x.pathname,X=T.pathname,G=R&&R.navigation&&R.navigation.location?R.navigation.location.pathname:null;c||(X=X.toLowerCase(),G=G?G.toLowerCase():null,U=U.toLowerCase()),G&&q&&(G=Fa(G,q)||G);const V=U!=="/"&&U.endsWith("/")?U.length-1:U.length;let P=X===U||!d&&X.startsWith(U)&&X.charAt(V)==="/",J=G!=null&&(G===U||!d&&G.startsWith(U)&&G.charAt(U.length)==="/"),Z={isActive:P,isPending:J,isTransitioning:H},I=P?s:void 0,O;typeof u=="function"?O=u(Z):O=[u,P?"active":null,J?"pending":null,H?"transitioning":null].filter(Boolean).join(" ");let le=typeof f=="function"?f(Z):f;return j.createElement(Ke,{...g,"aria-current":I,className:O,ref:b,style:le,to:p,viewTransition:m},typeof y=="function"?y(Z):y)});ll.displayName="NavLink";var S0=j.forwardRef(({discover:l="render",fetcherKey:s,navigate:c,reloadDocument:u,replace:d,state:f,method:p=tu,action:m,onSubmit:y,relative:g,preventScrollReset:b,viewTransition:x,defaultShouldRevalidate:T,...R},w)=>{let{useTransitions:q}=j.useContext(Vt),H=R0(),U=A0(m,{relative:g}),X=p.toLowerCase()==="get"?"get":"post",G=typeof m=="string"&&Sd.test(m),V=P=>{if(y&&y(P),P.defaultPrevented)return;P.preventDefault();let J=P.nativeEvent.submitter,Z=(J==null?void 0:J.getAttribute("formmethod"))||p,I=()=>H(J||P.currentTarget,{fetcherKey:s,method:Z,navigate:c,replace:d,state:f,relative:g,preventScrollReset:b,viewTransition:x,defaultShouldRevalidate:T});q&&c!==!1?j.startTransition(()=>I()):I()};return j.createElement("form",{ref:w,method:X,action:U,onSubmit:u?y:V,...R,"data-discover":!G&&l==="render"?"true":void 0})});S0.displayName="Form";function N0(l){return`${l} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function fv(l){let s=j.useContext(Ni);return Ve(s,N0(l)),s}function E0(l,{target:s,replace:c,mask:u,state:d,preventScrollReset:f,relative:p,viewTransition:m,defaultShouldRevalidate:y,useTransitions:g}={}){let b=Bn(),x=ra(),T=ws(l,{relative:p});return j.useCallback(R=>{if(t0(R,s)){R.preventDefault();let w=c!==void 0?c:Ns(x)===Ns(T),q=()=>b(l,{replace:w,mask:u,state:d,preventScrollReset:f,relative:p,viewTransition:m,defaultShouldRevalidate:y});g?j.startTransition(()=>q()):q()}},[x,b,T,c,u,d,s,l,f,p,m,y,g])}function hu(l){sa(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let s=j.useRef(od(l)),c=j.useRef(!1),u=ra(),d=j.useMemo(()=>a0(u.search,c.current?null:s.current),[u.search]),f=Bn(),p=j.useCallback((m,y)=>{const g=od(typeof m=="function"?m(new URLSearchParams(d)):m);c.current=!0,f("?"+g,y)},[f,d]);return[d,p]}var C0=0,T0=()=>`__${String(++C0)}__`;function R0(){let{router:l}=fv("useSubmit"),{basename:s}=j.useContext(Vt),c=Xj(),u=l.fetch,d=l.navigate;return j.useCallback(async(f,p={})=>{let{action:m,method:y,encType:g,formData:b,body:x}=i0(f,s);if(p.navigate===!1){let T=p.fetcherKey||T0();await u(T,c,p.action||m,{defaultShouldRevalidate:p.defaultShouldRevalidate,preventScrollReset:p.preventScrollReset,formData:b,body:x,formMethod:p.method||y,formEncType:p.encType||g,flushSync:p.flushSync})}else await d(p.action||m,{defaultShouldRevalidate:p.defaultShouldRevalidate,preventScrollReset:p.preventScrollReset,formData:b,body:x,formMethod:p.method||y,formEncType:p.encType||g,replace:p.replace,state:p.state,fromRouteId:c,flushSync:p.flushSync,viewTransition:p.viewTransition})},[u,d,s,c])}function A0(l,{relative:s}={}){let{basename:c}=j.useContext(Vt),u=j.useContext(pa);Ve(u,"useFormAction must be used inside a RouteContext");let[d]=u.matches.slice(-1),f={...ws(l||".",{relative:s})},p=ra();if(l==null){f.search=p.search;let m=new URLSearchParams(f.search),y=m.getAll("index");if(y.some(b=>b==="")){m.delete("index"),y.filter(x=>x).forEach(x=>m.append("index",x));let b=m.toString();f.search=b?`?${b}`:""}}return(!l||l===".")&&d.route.index&&(f.search=f.search?f.search.replace(/^\?/,"?index&"):"?index"),c!=="/"&&(f.pathname=f.pathname==="/"?c:ma([c,f.pathname])),Ns(f)}function O0(l,{relative:s}={}){let c=j.useContext(lv);Ve(c!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:u}=fv("useViewTransitionState"),d=ws(l,{relative:s});if(!c.isTransitioning)return!1;let f=Fa(c.currentLocation.pathname,u)||c.currentLocation.pathname,p=Fa(c.nextLocation.pathname,u)||c.nextLocation.pathname;return su(d.pathname,p)!=null||su(d.pathname,f)!=null}const z0="/api";async function gi(l,s,c){var p;const u=typeof window<"u"&&((p=window.location)!=null&&p.origin)&&window.location.origin!=="null"?window.location.origin:"http://localhost",d=new URL(z0+l,u);if(c)for(const[m,y]of Object.entries(c))y!==void 0&&y!==""&&d.searchParams.set(m,String(y));const f=await fetch(d.toString(),s);if(!f.ok){const m=await f.json().catch(()=>({}));throw new Error(String(m.error??`${f.status} ${f.statusText}`))}return f.json()}const Se=(l,s)=>gi(l,void 0,s),gt=(l,s)=>gi(l,{method:"POST",headers:s?{"Content-Type":"application/json"}:void 0,body:s?JSON.stringify(s):void 0}),hy=(l,s)=>gi(l,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),M0=l=>gi(l,{method:"DELETE"}),D0={health:()=>Se("/health"),ready:()=>Se("/ready"),config:()=>Se("/config"),queueSettings:()=>Se("/settings"),saveQueueSettings:l=>hy("/settings",l),pushQueue:l=>gt("/queue/push",l),executeRun:(l,s)=>gt(`/factory-runs/${encodeURIComponent(l)}/execute`,s===void 0?{}:{force:s}),queueRunNext:l=>gt(`/factory-runs/${encodeURIComponent(l)}/queue-next`),statsByStatus:l=>Se("/stats/by-status",{jobDefId:l}),throughput:l=>Se("/stats/throughput",l),stuck:l=>Se("/stats/stuck",l),runs:l=>Se("/runs",l),recentFailures:l=>Se("/runs/recent-failures",l),run:l=>Se(`/runs/${l}`),runEvents:l=>Se(`/runs/${l}/events`),runActivities:(l,s)=>Se(`/factory-runs/${encodeURIComponent(l)}/activities`,s?{limit:s}:void 0),retryRun:l=>gt(`/factory-runs/${l}/retry`),cancelRun:l=>gt(`/factory-runs/${l}/cancel`),itemRuns:l=>Se(`/items/${l}/runs`),itemGraph:l=>Se(`/items/${l}/graph`),filters:()=>Se("/meta/filters"),compatibleGraphs:l=>Se("/meta/graphs",l),descriptors:()=>Se("/descriptors"),entitySources:l=>Se(`/entities/${encodeURIComponent(l)}/sources`),entityRelations:l=>Se(`/entities/${encodeURIComponent(l)}/relations`),entityRecordSamples:(l,s)=>Se(`/entities/${encodeURIComponent(l)}/record-samples`,{...s,random:s.random?"1":void 0}),jobDefs:()=>Se("/job-defs"),jobDef:l=>Se(`/job-defs/${l}`),saveJobDef:l=>gt("/job-defs",l),updateJobDef:(l,s)=>hy(`/job-defs/${l}`,s),deleteJobDef:l=>M0(`/job-defs/${l}`),enqueue:l=>gt("/jobs/enqueue",l),previewContext:l=>gt("/context/preview",l),executeGraph:l=>gt("/graphs/execute",l),records:l=>Se("/records",l),recordStats:l=>Se("/records/stats",l),recordGraphRuns:(l,s)=>Se(`/records/${encodeURIComponent(l)}/graph-runs`,s),listEntities:l=>Se("/entities/summary",l?{agent:l}:void 0),entitySummary:l=>Se(`/entities/${encodeURIComponent(l)}/summary`),listNarratives:l=>Se("/narratives",l?{entity:l}:void 0),graphsForEntity:l=>Se("/graphs",{entity:l}),coreRecords:l=>{var s;return Se("/core-records",{entity:l.entity,collection:l.collection,narratives:(s=l.narratives)==null?void 0:s.join(","),processingGraphId:l.processingGraphId,processingCondition:l.processingCondition,search:l.search,page:l.page,pageSize:l.pageSize})},coreRecord:(l,s)=>Se(`/core-records/${encodeURIComponent(l)}/${encodeURIComponent(s)}`),previewMatching:l=>gt("/selection/preview",l),listWork:l=>Se("/work",l?{agent:l}:void 0),work:l=>Se(`/work/${l}`),createWork:l=>gt("/work",l),setWorkStatus:(l,s)=>gi(`/work/${l}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:s})}),updateWork:(l,s)=>gi(`/work/${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),runEvaluation:l=>gt(`/work/${l}/evaluate`),workEvaluations:l=>Se(`/work/${l}/evaluations`),listBatches:()=>Se("/batches"),batch:l=>Se(`/batches/${l}`),queueBatch:l=>gt("/batches",l),queueSingle:l=>gt("/on-demand/single",l),assemblerProperties:l=>Se("/assembler/properties",l),assemblerPreview:l=>gt("/assembler/preview",l),factoryRuns:l=>Se("/factory-runs",l),factoryRun:l=>Se(`/factory-runs/${l}`),runStatusCounts:(l,s)=>Se("/factory-runs/status-counts",{scope:l,agent:s})},re=D0,hv={configured:{label:"Configured",tone:"pending"},evaluating:{label:"Evaluating",tone:"running"},matched:{label:"Matched",tone:"pending"},queued:{label:"Queued",tone:"pending"},pending:{label:"Pending",tone:"pending"},running:{label:"Running",tone:"running"},succeeded:{label:"Succeeded",tone:"done"},done:{label:"Done",tone:"done"},failed:{label:"Failed",tone:"failed"},cancelled:{label:"Cancelled",tone:"cancelled"},skipped:{label:"Skipped",tone:"cancelled"},excluded:{label:"Excluded",tone:"blocked"},blocked:{label:"Blocked",tone:"blocked"},active:{label:"Active",tone:"running"},inactive:{label:"Inactive",tone:"cancelled"},completed:{label:"Completed",tone:"done"},partial:{label:"Partial",tone:"blocked"},"not-processed":{label:"Not processed",tone:"pending"},in_progress:{label:"In progress",tone:"running"},never:{label:"Never",tone:"pending"},unknown:{label:"Unknown",tone:"cancelled"}};function w0(l){var s;return((s=hv[l])==null?void 0:s.label)??l.replace(/[-_]/g," ")}function _0(l){var s;return((s=hv[l])==null?void 0:s.tone)??"pending"}function jt({status:l}){return i.jsx("span",{className:`badge badge-${_0(l)}`,children:w0(l)})}const q0=[{label:"5s",ms:5e3},{label:"15s",ms:15e3},{label:"30s",ms:3e4},{label:"Off",ms:0}];function mv({onRefresh:l,intervalMs:s=5e3,lastRefreshed:c}){const[u,d]=j.useState(s),[f,p]=j.useState(!1),m=j.useRef(null);return j.useEffect(()=>{if(!(f||u===0))return m.current=setTimeout(()=>l(),u),()=>{m.current&&clearTimeout(m.current)}},[l,u,f,c]),i.jsxs("div",{className:"refresh-control",children:[i.jsx("span",{className:`refresh-dot${f||u===0?" paused":""}`}),c&&i.jsx("span",{children:c.toLocaleTimeString()}),i.jsx("select",{value:u,onChange:y=>{const g=Number(y.target.value);d(g),p(g===0)},style:{minWidth:"unset",width:60},children:q0.map(({label:y,ms:g})=>i.jsx("option",{value:g,children:y},g))}),i.jsx("button",{onClick:()=>{p(y=>!y)},title:f?"Resume auto-refresh":"Pause auto-refresh",style:{padding:"3px 8px"},children:f?"▶":"⏸"}),i.jsx("button",{onClick:l,title:"Refresh now",style:{padding:"3px 8px"},children:"↻"})]})}function U0({buckets:l}){if(!l.length)return i.jsx("div",{className:"text-dim",style:{fontSize:12,padding:"8px 0"},children:"No throughput data"});const s=new Map;for(const d of l)s.set(d.bucket,(s.get(d.bucket)??0)+d.count);const c=[...s.entries()].sort((d,f)=>d[0].localeCompare(f[0])),u=Math.max(...c.map(([,d])=>d),1);return i.jsx("div",{style:{display:"flex",alignItems:"flex-end",gap:3,height:48,marginTop:8},children:c.map(([d,f])=>i.jsx("div",{title:`${new Date(d).toLocaleString()}: ${f}`,style:{flex:1,minWidth:4,height:`${Math.max(8,f/u*100)}%`,background:"var(--color-accent)",borderRadius:2,opacity:.85}},d))})}function Ln(l){if(!l)return"—";const s=Date.now()-new Date(l).getTime(),c=Math.abs(s),u=s<0,d=Math.round(c/6e4);if(d<1)return u?"in <1m":"just now";if(d<60)return u?`in ${d}m`:`${d}m ago`;const f=Math.round(d/60);if(f<24)return u?`in ${f}h`:`${f}h ago`;const p=Math.round(f/24);return u?`in ${p}d`:`${p}d ago`}function ia(l){return l?new Date(l).toLocaleString():"—"}function Es(l){return l%1440===0?`every ${l/1440} day${l===1440?"":"s"}`:l%60===0?`every ${l/60} hour${l===60?"":"s"}`:`every ${l} min`}const dd="inferences",Cs={continuous:"Ongoing Work","on-demand-single":"On-Demand Single","on-demand-batch":"On-Demand Batch"},L0={entity:"Entities",event:"Events",knowledge:"Knowledge"},B0={"already-processed":"Already processed by this graph","already-queued":"Already queued for this graph","already-running":"Currently running for this graph","missing-narrative":"Missing a required narrative","incompatible-graph":"Graph not compatible with this item","missing-data":"Item is missing required data","metadata-unavailable":"Metadata unavailable","changed-since-eligible":"Changed or became ineligible since preview","prerequisite-graph-not-met":"Required prior processing not completed","cross-entity-prerequisite-not-met":"Linked entity information not yet processed"},pv={ttl:"Re-run if older than… (default)",skip:"Skip — never re-run already-processed information","failed-only":"Failed only — re-run information where last attempt failed",all:"All — force re-run of every already-processed item","before-date":"Before date — re-run information processed before…","after-date":"After date — re-run information processed after…",condition:"Condition — re-run only if item matches a filter"},H0=["blocked","pending","running","done","failed","cancelled"],my={blocked:"var(--status-blocked)",pending:"var(--status-pending)",running:"var(--status-running)",done:"var(--status-done)",failed:"var(--status-failed)",cancelled:"var(--status-cancelled)"},Q0=["continuous","on-demand-single","on-demand-batch"];function G0(){const l=Bn(),{agentQueryParam:s,agentId:c}=Ia(),[u,d]=j.useState(""),[f,p]=j.useState(""),[m,y]=j.useState(""),[g,b]=j.useState(new Date),x=ve({queryKey:["queue-settings"],queryFn:()=>re.queueSettings()}),T=ve({queryKey:["overview-runs",s??"all",u,f,m],queryFn:()=>re.factoryRuns({agent:s,sourceType:u||void 0,workId:f||void 0,entity:m||void 0,pageSize:1e3})}),R=ve({queryKey:["throughput"],queryFn:()=>re.throughput({hours:24,bucket:"hour"})}),w=ve({queryKey:["entities",s??"all"],queryFn:()=>re.listEntities(s)}),q=ve({queryKey:["work",s??"all"],queryFn:()=>re.listWork(s)}),H=j.useMemo(()=>{var J;return((J=T.data)==null?void 0:J.runs)??[]},[T.data]),U=j.useMemo(()=>{const J={blocked:0,pending:0,running:0,done:0,failed:0,cancelled:0};for(const Z of H)J[Z.status]+=1;return J},[H]),X=H.filter(J=>J.status==="running").slice(0,8),G=[...H.filter(J=>J.status==="pending")].sort((J,Z)=>+new Date(J.availableAt)-+new Date(Z.availableAt)).slice(0,8),V=H.filter(J=>J.status==="failed").slice(0,8),P=j.useCallback(()=>{T.refetch(),b(new Date)},[T]);return i.jsxs("div",{children:[i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"Overview"}),i.jsxs("span",{className:"page-subtitle",children:["Factory health and queue monitoring.",c?i.jsxs(i.Fragment,{children:[" Agent scope: ",i.jsx("span",{className:"mono",children:c})," ·"]}):null,x.data&&i.jsxs(i.Fragment,{children:[" Running: ",x.data.admittedCount??"—"," / ",x.data.maxConcurrentJobs," capacity"]})]})]}),i.jsx(mv,{onRefresh:P,lastRefreshed:g??void 0})]}),i.jsxs("div",{className:"filters",children:[i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Source type"}),i.jsxs("select",{value:u,onChange:J=>d(J.target.value),children:[i.jsx("option",{value:"",children:"All"}),Q0.map(J=>i.jsx("option",{value:J,children:Cs[J]},J))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Ongoing work"}),i.jsxs("select",{value:f,onChange:J=>p(J.target.value),children:[i.jsx("option",{value:"",children:"All"}),(q.data??[]).map(J=>i.jsx("option",{value:J.id,children:J.name},J.id))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Entity"}),i.jsxs("select",{value:m,onChange:J=>y(J.target.value),children:[i.jsx("option",{value:"",children:"All"}),(w.data??[]).map(J=>i.jsx("option",{value:J.name,children:J.label},J.name))]})]})]}),i.jsx("div",{className:"status-cards",style:{gridTemplateColumns:"repeat(6, 1fr)"},children:H0.map(J=>i.jsxs("div",{className:"status-card",onClick:()=>l(`/journal?status=${J}`),children:[i.jsx("div",{className:"status-card-label",style:{color:my[J]},children:J}),i.jsx("div",{className:"status-card-count",style:{color:my[J]},children:U[J].toLocaleString()})]},J))}),i.jsxs("div",{className:"card",style:{marginBottom:20},children:[i.jsx("div",{className:"card-title",children:"Throughput (24h)"}),R.isLoading&&i.jsx("span",{className:"spinner"}),R.data&&i.jsx(U0,{buckets:R.data})]}),i.jsxs("div",{className:"overview-cols",children:[i.jsx(Zo,{title:"Recent failed",runs:V,emptyMsg:"No failed runs"}),i.jsx(Zo,{title:"Currently running",runs:X,emptyMsg:"No running runs"}),i.jsx(Zo,{title:"Oldest pending",runs:G,emptyMsg:"No pending runs"})]})]})}function Zo({title:l,runs:s,emptyMsg:c}){return i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:l}),s.length===0&&i.jsx("div",{className:"empty-state",style:{padding:"24px 0"},children:c}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:s.map(u=>i.jsx(Ke,{to:`/journal/${u.id}`,style:{display:"block",textDecoration:"none"},children:i.jsxs("div",{style:{padding:"8px 10px",background:"var(--color-surface-raised)",borderRadius:"var(--radius)",border:"1px solid var(--color-border)"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[i.jsx(jt,{status:u.status}),i.jsx("span",{className:"text-dim mono",style:{fontSize:11},children:Ln(u.updatedAt)})]}),i.jsxs("div",{className:"mono",style:{color:"var(--color-text-muted)",fontSize:11},children:[Cs[u.sourceType]," · ",u.entity,"/",u.recordLabel??u.recordId]}),u.error&&i.jsx("div",{style:{color:"var(--status-failed)",fontSize:11},children:u.error.message})]})},u.id))})]})}function Zt({title:l,message:s,detail:c,onRetry:u,safeActionLabel:d,onSafeAction:f}){const[p,m]=j.useState(!1),y=c===void 0?"":typeof c=="string"?c:String((c==null?void 0:c.message)??JSON.stringify(c,null,2));return i.jsxs("div",{className:"error-state",style:{color:"var(--color-text)"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{color:"var(--status-failed)",fontSize:16},children:"⚠"}),i.jsx("strong",{style:{color:"var(--status-failed)"},children:l})]}),s&&i.jsx("div",{style:{marginTop:6,lineHeight:1.5},children:s}),i.jsxs("div",{style:{display:"flex",gap:8,marginTop:12,flexWrap:"wrap"},children:[u&&i.jsx("button",{type:"button",onClick:u,children:"Retry"}),d&&i.jsx("button",{type:"button",onClick:f,children:d}),y&&i.jsx("button",{type:"button",onClick:()=>m(g=>!g),children:p?"Hide technical details":"Show technical details"})]}),p&&y&&i.jsx("pre",{style:{marginTop:10,fontSize:11,whiteSpace:"pre-wrap",opacity:.8,fontFamily:"var(--font-mono)"},children:y})]})}const k0=[{ms:15e3,label:"15 seconds"},{ms:3e4,label:"30 seconds"},{ms:6e4,label:"1 minute"},{ms:12e4,label:"2 minutes"}];function Y0(){const l=ji(),[s,c]=j.useState(""),[u,d]=j.useState(""),[f,p]=j.useState(!1),m=ve({queryKey:["queue-settings"],queryFn:()=>re.queueSettings()});j.useEffect(()=>{m.data&&(c(m.data.maxConcurrentJobs),d(m.data.queueAdmissionIntervalMs),p(!1))},[m.data]);const y=Xt({mutationFn:()=>re.saveQueueSettings({maxConcurrentJobs:Number(s),queueAdmissionIntervalMs:Number(u)}),onSuccess:()=>{p(!0),l.invalidateQueries({queryKey:["queue-settings"]})}});return i.jsxs("div",{children:[i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"Settings"}),i.jsx("span",{className:"page-subtitle",children:"App-wide jobs factory configuration."})]})}),i.jsxs("div",{className:"card",style:{maxWidth:640},children:[i.jsx("div",{className:"card-title",children:"Queue execution"}),i.jsx("p",{className:"text-muted",style:{fontSize:13,marginBottom:16},children:"Controls how many jobs run in parallel across all work, batches, and on-demand runs. When capacity frees up, waiting jobs are promoted automatically on the check interval."}),m.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}),m.isError&&i.jsx(Zt,{title:"Failed to load settings",detail:m.error}),m.data&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Max concurrent jobs"}),i.jsx("input",{type:"number",min:1,value:s,onChange:g=>{c(Number(g.target.value)),p(!1)}})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Admission check interval"}),i.jsx("select",{value:u,onChange:g=>{d(Number(g.target.value)),p(!1)},children:k0.map(g=>i.jsx("option",{value:g.ms,children:g.label},g.ms))}),i.jsx("span",{className:"hint",children:"How often the factory checks for free capacity and promotes waiting jobs."})]})]}),i.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",marginTop:16},children:[i.jsx("button",{type:"button",className:"primary",disabled:y.isPending,onClick:()=>y.mutate(),children:y.isPending?"Saving…":"Save settings"}),f&&!y.isPending&&i.jsx("span",{className:"text-muted",style:{fontSize:13},children:"Saved"})]}),y.isError&&i.jsx("div",{style:{marginTop:12},children:i.jsx(Zt,{title:"Failed to save settings",detail:y.error})})]})]})]})}function yv({page:l,pageSize:s,total:c,onPage:u}){const d=Math.max(1,Math.ceil(c/s)),f=(l-1)*s+1,p=Math.min(l*s,c);return i.jsxs("div",{className:"pagination",children:[i.jsxs("span",{children:[c===0?"0":`${f}–${p}`," of ",c]}),i.jsx("button",{disabled:l<=1,onClick:()=>u(l-1),children:"← Prev"}),i.jsxs("span",{children:[l," / ",d]}),i.jsx("button",{disabled:l>=d,onClick:()=>u(l+1),children:"Next →"})]})}function Dt({title:l,message:s,actionLabel:c,actionTo:u,onAction:d,icon:f="○"}){return i.jsxs("div",{className:"empty-state",style:{padding:"40px 24px"},children:[i.jsx("div",{style:{fontSize:28,opacity:.5,marginBottom:10},children:f}),i.jsx("div",{style:{fontSize:15,fontWeight:600,color:"var(--color-text)",marginBottom:6},children:l}),s&&i.jsx("div",{style:{maxWidth:480,margin:"0 auto",lineHeight:1.55},children:s}),c&&i.jsx("div",{style:{marginTop:16},children:u?i.jsx(Ke,{to:u,children:i.jsx("button",{type:"button",className:"primary",children:c})}):i.jsx("button",{type:"button",className:"primary",onClick:d,children:c})})]})}const py=["blocked","pending","running","done","failed","cancelled"],K0=["continuous","on-demand-single","on-demand-batch"],Vo={blocked:"var(--status-blocked)",pending:"var(--status-pending)",running:"var(--status-running)",done:"var(--status-done)",failed:"var(--status-failed)",cancelled:"var(--status-cancelled)"},X0=[{key:"total",label:"Total"},{key:"today",label:"Today"},{key:"this-week",label:"This week"},{key:"this-month",label:"This month"}];function Z0(){const[l,s]=hu(),c=Bn(),{agentQueryParam:u,agentId:d}=Ia(),[f,p]=j.useState(new Date),[m,y]=j.useState("total"),g=l.get("status")??"",b=l.get("sourceType")??"",x=l.get("workId")??"",T=l.get("batchId")??"",R=l.get("graphId")??"",w=l.get("entity")??"",q=l.get("recordId")??"",H=Number(l.get("page")??1),U=(O,le)=>{s(ue=>{const de=new URLSearchParams(ue);return le?de.set(O,le):de.delete(O),O!=="page"&&de.delete("page"),de})},X=ve({queryKey:["factory-runs",u??"all",g,b,x,T,R,w,q,H],queryFn:()=>re.factoryRuns({agent:u,status:g||void 0,sourceType:b||void 0,workId:x||void 0,batchId:T||void 0,graphId:R||void 0,entity:w||void 0,recordId:q||void 0,page:H,pageSize:25})}),G=ve({queryKey:["run-status-counts",m,u??"all"],queryFn:()=>re.runStatusCounts(m,u)}),V=ve({queryKey:["entities",u??"all"],queryFn:()=>re.listEntities(u)}),P=ve({queryKey:["work",u??"all"],queryFn:()=>re.listWork(u)}),J=j.useCallback(()=>{X.refetch(),p(new Date)},[X]),Z=X.data,I=G.data;return i.jsxs("div",{children:[i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"Journal"}),Z&&i.jsxs("span",{className:"page-subtitle",children:[d?i.jsxs(i.Fragment,{children:["Agent scope: ",i.jsx("span",{className:"mono",children:d})," · "]}):null,Z.total.toLocaleString()," total job executions"]})]}),i.jsx(mv,{onRefresh:J,lastRefreshed:f??void 0})]}),i.jsxs("div",{style:{marginBottom:20},children:[i.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:10},children:X0.map(({key:O,label:le})=>i.jsx("button",{className:`btn btn-sm${m===O?" active":""}`,onClick:()=>y(O),children:le},O))}),i.jsx("div",{className:"status-cards",style:{gridTemplateColumns:"repeat(6, 1fr)"},children:py.map(O=>i.jsxs("div",{className:`status-card${g===O?" selected":""}`,style:g===O?{outline:`2px solid ${Vo[O]}`}:void 0,onClick:()=>U("status",g===O?"":O),title:`Filter by ${O}`,children:[i.jsx("div",{className:"status-card-label",style:{color:Vo[O]},children:O}),i.jsx("div",{className:"status-card-count",style:{color:Vo[O]},children:I?I[O].toLocaleString():"—"})]},O))})]}),i.jsxs("div",{className:"filters",children:[i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Status"}),i.jsxs("select",{value:g,onChange:O=>U("status",O.target.value),children:[i.jsx("option",{value:"",children:"All"}),py.map(O=>i.jsx("option",{value:O,children:O},O))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Source type"}),i.jsxs("select",{value:b,onChange:O=>U("sourceType",O.target.value),children:[i.jsx("option",{value:"",children:"All"}),K0.map(O=>i.jsx("option",{value:O,children:Cs[O]},O))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Ongoing work"}),i.jsxs("select",{value:x,onChange:O=>U("workId",O.target.value),children:[i.jsx("option",{value:"",children:"All"}),(P.data??[]).map(O=>i.jsx("option",{value:O.id,children:O.name},O.id))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Entity"}),i.jsxs("select",{value:w,onChange:O=>U("entity",O.target.value),children:[i.jsx("option",{value:"",children:"All"}),(V.data??[]).map(O=>i.jsx("option",{value:O.name,children:O.label},O.name))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Item id"}),i.jsx("input",{type:"text",value:q,placeholder:"item id",onChange:O=>U("recordId",O.target.value),style:{width:160}})]})]}),X.isError&&i.jsx(Zt,{title:"Failed to load journal",detail:X.error,onRetry:J}),X.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading journal…"]}),Z&&Z.runs.length===0&&i.jsx(Dt,{title:"No journal entries",message:"No executions match the current filters."}),Z&&Z.runs.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Source type"}),i.jsx("th",{children:"Source"}),i.jsx("th",{children:"Entity"}),i.jsx("th",{children:"Item"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Attempts"}),i.jsx("th",{children:"Priority"}),i.jsx("th",{children:"Created"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:Z.runs.map(O=>i.jsxs("tr",{onClick:()=>c(`/journal/${O.id}`),children:[i.jsx("td",{children:i.jsx(jt,{status:O.status})}),i.jsx("td",{children:i.jsx("span",{className:"chip",children:Cs[O.sourceType]})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:O.sourceName??"—"}),i.jsx("td",{className:"td-mono",children:O.entity}),i.jsx("td",{className:"td-mono",children:O.recordLabel??O.recordId}),i.jsx("td",{className:"td-mono",children:O.graphName??O.graphId}),i.jsxs("td",{className:"td-mono",children:[O.attempts,"/",O.maxAttempts]}),i.jsx("td",{className:"td-mono",children:O.priority}),i.jsx("td",{className:"td-mono",children:ia(O.createdAt)}),i.jsx("td",{className:"td-mono",children:ia(O.updatedAt)})]},O.id))})]})}),i.jsx(yv,{page:Z.page,pageSize:Z.pageSize,total:Z.total,onPage:O=>U("page",String(O))})]})]})}function fa({label:l,value:s,defaultOpen:c=!1}){const[u,d]=j.useState(c);if(s==null)return null;const f=JSON.stringify(s,null,2);return i.jsxs("div",{className:"json-section",children:[i.jsxs("div",{className:`json-section-header${u?" open":""}`,onClick:()=>d(p=>!p),role:"button",tabIndex:0,onKeyDown:p=>p.key==="Enter"&&d(m=>!m),children:[i.jsx("span",{className:`json-chevron${u?" open":""}`,children:"▶"}),l,i.jsx("span",{className:"text-dim",style:{marginLeft:"auto",fontWeight:400,textTransform:"none",fontSize:"11px"},children:u?"collapse":`${f.split(`
|
|
61
|
-
`).length} lines`})]}),u&&i.jsx("div",{className:"json-body",children:i.jsx("pre",{children:f})})]})}const V0={enqueued:"muted",claimed:"start",done:"done",failed:"fail",retry:"info",lease_expired:"fail",cancelled:"muted"},$0={info:"var(--color-text)",start:"var(--status-running)",done:"var(--status-done)",fail:"var(--status-failed)",muted:"var(--color-text-muted)"};function $a(l){if(typeof l=="number")return l>1e12?l:l*1e3;if(typeof l=="string"){const s=new Date(l).getTime();return Number.isNaN(s)?void 0:s}}function vv(l){return new Date(l).toLocaleTimeString(void 0,{hour12:!1})}function fd(l){return l&&typeof l=="object"&&!Array.isArray(l)?l:void 0}function yy(l){const s=(l??"").toLowerCase();return s.includes("fail")||s.includes("error")?"fail":s.includes("complete")||s.includes("done")||s.includes("success")||s.includes("ended")?"done":s.includes("start")||s.includes("running")||s.includes("progress")?"start":"info"}function J0(l){return l==="fail"?"✕":l==="done"?"✓":l==="start"?"▶":"·"}function F0(l){if(l)return typeof l=="string"?l:typeof l=="object"&&l&&"message"in l?String(l.message):JSON.stringify(l)}function gv(l,s=120){return l.length<=s?l:`${l.slice(0,s-1)}…`}function I0(l){const s=fd(l.runContext);return{...l,nodeId:l.nodeId??(s==null?void 0:s.nodeId),graphId:l.graphId??(s==null?void 0:s.graphId),skillKey:l.skillKey??(s==null?void 0:s.skillKey)}}function W0(l){const s=l.nodeId??l.skillKey??"node",c=l.skillKey&&l.skillKey!==l.nodeId?` · ${l.skillKey}`:"";return`${s}${c}`}function xv(l,s,c){if(typeof l.durationMs=="number")return l.durationMs;if(typeof l.duration=="number")return l.duration;if(s!=null&&c!=null)return Math.max(0,Math.round(c-s))}function P0(l){const s=[],c=fd(l.runContext),u=fd(l.outer),d=$a(l.startTime)??$a(l.createdAt),f=$a(l.endTime)??$a(l.updatedAt),p=xv(l,d,f);s.push({label:"Summary",value:{activityId:l.activityId,status:l.status,phase:l.phase,nodeId:l.nodeId??(c==null?void 0:c.nodeId),graphId:l.graphId??(c==null?void 0:c.graphId),skillKey:l.skillKey??(c==null?void 0:c.skillKey),kind:l.kind,startTime:d!=null?new Date(d).toISOString():l.startTime,endTime:f!=null?new Date(f).toISOString():l.endTime,durationMs:p}}),l.inputVariableKeys&&s.push({label:"Input variable keys",value:l.inputVariableKeys}),l.executionKeys&&s.push({label:"Execution keys",value:l.executionKeys}),(u==null?void 0:u.input)!=null&&s.push({label:"Input",value:u.input}),(u==null?void 0:u.output)!=null&&s.push({label:"Output",value:u.output}),(u==null?void 0:u.metadata)!=null&&s.push({label:"Metadata",value:u.metadata}),(u==null?void 0:u.memory)!=null&&s.push({label:"Memory",value:u.memory}),l.outputSummary!=null&&s.push({label:"Output summary",value:l.outputSummary}),l.narrixSummary!=null&&s.push({label:"Narrix",value:l.narrixSummary}),l.error!=null&&s.push({label:"Error",value:l.error}),Array.isArray(l.inner)&&l.inner.length>0&&s.push({label:"Inner steps",value:l.inner});const m={},y=new Set(["activityId","status","phase","nodeId","graphId","skillKey","kind","startTime","endTime","createdAt","updatedAt","durationMs","duration","runContext","outer","inner","error","inputVariableKeys","executionKeys","outputSummary","narrixSummary"]);for(const[g,b]of Object.entries(l))y.has(g)||b==null||(m[g]=b);return Object.keys(m).length>0&&s.push({label:"Record fields",value:m}),s}function eS(l){return l.map((s,c)=>{const u=$a(s.at)??0,d=s.meta&&Object.keys(s.meta).length?s.meta:void 0;return{id:`event-${c}-${s.kind}-${u}`,ts:u,time:vv(u),level:V0[s.kind]??"info",label:s.kind.replace(/_/g," "),summary:d?gv(JSON.stringify(d)):void 0,sections:d?[{label:"Event meta",value:d}]:void 0}})}function tS(l){return l.map((s,c)=>{const u=I0(s),d=$a(u.startTime)??$a(u.createdAt)??0,f=$a(u.endTime)??(yy(u.status)!=="start"?$a(u.updatedAt):void 0),p=yy(u.status),m=xv(u,d,f),y=F0(u.error),g=P0(u);return{id:`activity-${u.activityId??u.nodeId??c}-${d}`,ts:d,time:vv(d),level:p,label:`${J0(p)} ${W0(u)}`,summary:y?gv(y):m!=null?`${m}ms`:void 0,sections:g.length>0?g:void 0}})}function aS({entry:l}){var d;const[s,c]=j.useState(!1),u=(((d=l.sections)==null?void 0:d.length)??0)>0;return i.jsxs("div",{className:`live-console-entry${s?" open":""}`,children:[i.jsxs("div",{className:`live-console-line${u?" expandable":""}`,onClick:u?()=>c(f=>!f):void 0,role:u?"button":void 0,tabIndex:u?0:void 0,onKeyDown:u?f=>f.key==="Enter"&&c(p=>!p):void 0,children:[u&&i.jsx("span",{className:`live-console-chevron${s?" open":""}`,children:"▶"}),i.jsx("span",{className:"live-console-time",children:l.time}),i.jsx("span",{style:{color:$0[l.level]},children:l.label}),l.summary&&i.jsx("span",{className:"live-console-detail",children:l.summary})]}),s&&l.sections&&i.jsx("div",{className:"live-console-expand",children:l.sections.map(f=>i.jsx(fa,{label:f.label,value:f.value},f.label))})]})}function nS({runId:l,live:s}){var T;const c=s?1200:!1,u=ve({queryKey:["run-events",l],queryFn:()=>re.runEvents(l),refetchInterval:c}),d=ve({queryKey:["run-activities",l],queryFn:()=>re.runActivities(l),refetchInterval:c}),f=j.useMemo(()=>{var w,q;const R=[...eS(((w=u.data)==null?void 0:w.events)??[]),...tS(((q=d.data)==null?void 0:q.activities)??[])];return R.sort((H,U)=>H.ts-U.ts),R},[u.data,d.data]),p=j.useRef(null),m=j.useRef(!0),y=()=>{const R=p.current;R&&(m.current=R.scrollHeight-R.scrollTop-R.clientHeight<40)};j.useEffect(()=>{m.current&&p.current&&(p.current.scrollTop=p.current.scrollHeight)},[f.length]);const g=((T=d.data)==null?void 0:T.available)??!0,b=f.length===0,x=f.filter(R=>{var w;return(((w=R.sections)==null?void 0:w.length)??0)>0}).length;return i.jsxs("div",{className:"live-console",children:[i.jsxs("div",{className:"live-console-head",children:[i.jsxs("span",{className:"live-console-title",children:[i.jsx("span",{className:`live-dot${s?" live":""}`}),"Live Console"]}),i.jsxs("span",{className:"live-console-meta mono",children:[s?"streaming…":"idle"," · ",f.length," entr",f.length===1?"y":"ies",x>0?` · ${x} expandable`:""]})]}),i.jsxs("div",{className:"live-console-body",ref:p,onScroll:y,children:[b&&i.jsx("div",{className:"live-console-line muted",children:s?"Waiting for execution events…":"No execution activity recorded yet."}),f.map(R=>i.jsx(aS,{entry:R},R.id))]}),!g&&i.jsx("div",{className:"live-console-foot",children:"Per-node activity tracking is unavailable — showing run lifecycle events only."})]})}function nu(l){return l&&typeof l=="object"&&!Array.isArray(l)?l:void 0}function vy(l){if(!l)return{payload:void 0,memorixRef:void 0};const{_memorixRef:s,...c}=l;return{payload:Object.keys(c).length>0?c:void 0,memorixRef:s}}function gy(l){try{return JSON.stringify(l)}catch{return""}}function lS(l){const s=nu(l);if(!s)return{};const c=nu(s.outer),u=nu(c==null?void 0:c.output);return{runtimeInput:c==null?void 0:c.input,runtimeOutput:(u==null?void 0:u.response)??(u&&!u.data?u:void 0),runtimeData:u==null?void 0:u.data,status:s.status,nodesExecuted:s.nodesExecuted,completedAt:s.completedAt,error:s.error??(u==null?void 0:u.error)}}function iS({runId:l,status:s,input:c,result:u,assemblySelection:d,live:f}){var X;const p=ve({queryKey:["run-activities",l],queryFn:()=>re.runActivities(l),refetchInterval:f?1200:!1}),m=j.useMemo(()=>{var G;return lS((G=p.data)==null?void 0:G.graphRun)},[(X=p.data)==null?void 0:X.graphRun]),y=vy(c),g=vy(nu(m.runtimeInput)),b=u??m.runtimeOutput,x=g.payload!=null&&gy(g.payload)!==gy(y.payload),T=d!=null,R=b!=null,w=m.runtimeData!=null,q=y.memorixRef!=null||g.memorixRef!=null,H=m.status!=null||m.nodesExecuted!=null||m.error!=null;return!c&&!T&&!x&&!R&&!w&&!q&&!H&&!p.isLoading?i.jsxs("div",{className:"card",style:{marginBottom:16},children:[i.jsx("div",{className:"card-title",children:"Request & response"}),i.jsx("span",{className:"text-muted",style:{fontSize:13},children:"No input or output recorded for this run yet."})]}):i.jsxs("div",{className:"card run-io-panel",style:{marginBottom:16},children:[i.jsx("div",{className:"card-title",children:"Request & response"}),i.jsx("p",{className:"run-io-hint",children:"What was queued for this job, what the graph received at runtime, and the final response."}),y.payload!=null&&i.jsx(fa,{label:"Queued input",value:y.payload,defaultOpen:s==="pending"}),T&&i.jsx(fa,{label:"Assembly selection",value:d}),q&&i.jsx(fa,{label:"Memorix reference",value:g.memorixRef??y.memorixRef}),x&&i.jsx(fa,{label:"Sent to graph (runtime input)",value:g.payload,defaultOpen:!0}),!x&&m.runtimeInput!=null&&s!=="pending"&&i.jsx(fa,{label:"Sent to graph (runtime input)",value:m.runtimeInput}),R?i.jsx(fa,{label:"Response",value:b,defaultOpen:!0}):i.jsx("div",{className:"run-io-pending",children:f||s==="running"?"Response will appear when the graph finishes.":s==="failed"?"No response — run failed before producing output.":"No response recorded yet."}),w&&i.jsx(fa,{label:"Execution diagnostics",value:m.runtimeData}),m.error!=null&&i.jsx(fa,{label:"Graph error",value:m.error,defaultOpen:!0}),H&&i.jsx(fa,{label:"Run telemetry",value:{status:m.status,nodesExecuted:m.nodesExecuted,completedAt:m.completedAt}})]})}function pt({label:l,value:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",children:s})]})}function sS(l){if(l.sourceType==="continuous"&&l.sourceRef)return`/work/${l.sourceRef}`;if(l.sourceType==="on-demand-batch"&&l.sourceRef)return`/on-demand/batch/${l.sourceRef}`}function rS(l){const s=l.queueOptions;return l.status!=="pending"?ia(l.availableAt):s!=null&&s.admissionHeld?s.slotsAvailable>0?"Waiting for capacity — a slot is available; you can execute now":`Waiting for capacity (${s.admittedCount}/${s.maxConcurrentJobs} slots in use)`:s&&s.slotsAvailable<=0?`Queued (${s.admittedCount}/${s.maxConcurrentJobs} slots in use) — waiting for worker or execute now`:"Queued — ready to execute"}function uS(){var U;const{id:l}=Ds(),s=ji(),c=ve({queryKey:["factory-run",l],queryFn:()=>re.factoryRun(l),enabled:!!l,refetchInterval:X=>{var G;return((G=X.state.data)==null?void 0:G.status)==="running"?1500:!1}}),u=Xt({mutationFn:()=>re.retryRun(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),d=Xt({mutationFn:()=>re.cancelRun(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),f=Xt({mutationFn:()=>re.executeRun(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),p=Xt({mutationFn:()=>re.queueRunNext(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),m=c.data;if(c.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]});if(c.isError||!m)return i.jsx(Zt,{title:"Journal entry not found",detail:c.error});const y=m.queueOptions,g=m.status==="failed"||m.status==="cancelled",b=m.status==="blocked"||m.status==="pending"||m.status==="running",x=m.status==="pending"&&((y==null?void 0:y.canExecuteNow)??!0),T=m.status==="pending"&&((y==null?void 0:y.admissionHeld)||((y==null?void 0:y.slotsAvailable)??1)<=0),R=sS(m),w=m.processingUpdate,q=f.isPending||m.status==="running",H=m.status!=="pending"||m.attempts>0;return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/journal",children:"Journal"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),i.jsx("span",{className:"mono",children:m.id})]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[i.jsx(jt,{status:m.status}),i.jsxs("span",{className:"page-subtitle mono",children:[m.entity," / ",m.recordLabel??m.recordId," / ",m.graphName??m.graphId]})]}),i.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"flex-end"},children:[x&&i.jsx("button",{className:"primary",disabled:f.isPending,onClick:()=>f.mutate(),children:f.isPending?"Executing…":"Execute now"}),T&&i.jsx("button",{disabled:p.isPending,onClick:()=>p.mutate(),children:p.isPending?"Updating…":"Run next when slot available"}),g&&i.jsx("button",{className:"primary",disabled:u.isPending,onClick:()=>u.mutate(),children:u.isPending?"Retrying…":"Retry"}),b&&i.jsx("button",{disabled:d.isPending,onClick:()=>d.mutate(),style:{color:"var(--status-cancelled)"},children:d.isPending?"Cancelling…":"Cancel"})]})]}),m.status==="pending"&&y&&i.jsxs("div",{className:"memorix-panel",style:{marginBottom:16,fontSize:13},children:[y.slotsAvailable>0?`${y.slotsAvailable} execution slot${y.slotsAvailable===1?"":"s"} available (${y.admittedCount}/${y.maxConcurrentJobs} in use).`:`All ${y.maxConcurrentJobs} execution slots are in use.`,T&&" Use “Run next when slot available” to move this job to the front of the waiting queue."]}),(q||H)&&i.jsx(nS,{runId:m.id,live:q}),i.jsx(iS,{runId:m.id,status:m.status,input:m.input,result:m.result,assemblySelection:m.assemblySelection,live:q}),i.jsxs("div",{className:"detail-grid",children:[i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Source"}),i.jsx(pt,{label:"Source type",value:Cs[m.sourceType]}),i.jsx(pt,{label:"Source name",value:R?i.jsx(Ke,{to:R,children:m.sourceName}):m.sourceName??"—"}),i.jsx(pt,{label:"Source ref",value:m.sourceRef??"—"})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Target"}),i.jsx(pt,{label:"Entity",value:`${m.entity} · ${m.collection}`}),i.jsx(pt,{label:"Item",value:i.jsx(Ke,{to:`/information/${encodeURIComponent(m.recordId)}?entity=${m.entity}`,children:m.recordLabel??m.recordId})}),i.jsx(pt,{label:"Graph",value:`${m.graphName??m.graphId}`}),i.jsx(pt,{label:"Context",value:(U=m.relatedRecords)!=null&&U.length?m.relatedRecords.join(", "):"—"}),i.jsx(pt,{label:"Output collection",value:m.outputCollection??"—"})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Execution"}),i.jsx(pt,{label:"Attempts",value:`${m.attempts} / ${m.maxAttempts}`}),i.jsx(pt,{label:"Priority",value:m.priority}),i.jsx(pt,{label:"Claimed by",value:m.claimedBy??i.jsx("span",{className:"text-dim",children:"unclaimed"})}),i.jsx(pt,{label:"Queue state",value:rS(m)})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Timestamps"}),i.jsx(pt,{label:"Created",value:ia(m.createdAt)}),i.jsx(pt,{label:"Updated",value:ia(m.updatedAt)})]})]}),i.jsxs("div",{className:"card",style:{marginBottom:16,borderColor:(w==null?void 0:w.status)==="updated"?"var(--status-done)":(w==null?void 0:w.status)==="failed"?"var(--status-failed)":void 0},children:[i.jsx("div",{className:"card-title",children:"Processing result"}),!w&&i.jsx("span",{className:"text-muted",style:{fontSize:13},children:"No processing result recorded."}),w&&i.jsxs(i.Fragment,{children:[i.jsx(pt,{label:"Status",value:i.jsx(jt,{status:w.status==="updated"?"succeeded":w.status==="failed"?"failed":"pending"})}),i.jsx(pt,{label:"Graph",value:w.graphId}),i.jsxs("div",{style:{fontSize:13,marginTop:8,color:w.status==="failed"?"var(--status-failed)":"var(--color-text-muted)"},children:[w.status==="updated"&&`processing.graphs.${w.graphId}.processedAt was updated.`,w.status==="failed"&&(w.detail??"Processing metadata update failed."),w.status==="pending"&&"Processing metadata will be updated when the run succeeds.",w.status==="skipped"&&(w.detail??"Processing metadata update was skipped.")]})]})]}),f.isError&&i.jsxs("div",{className:"error-state",style:{marginBottom:16},children:["Execute failed: ",String(f.error)]}),m.error&&i.jsxs("div",{className:"error-state",style:{marginBottom:16},children:[i.jsxs("div",{style:{color:"var(--status-failed)",fontWeight:600},children:["Error: ",m.error.message]}),m.error.code&&i.jsxs("div",{className:"mono text-muted",style:{fontSize:12,marginTop:4},children:["code: ",m.error.code]})]})]})}function cS(l){const s=new Map,c=new Map(l.nodes.map(d=>[d.id,d]));function u(d,f=new Set){if(s.has(d))return s.get(d);if(f.has(d))return 0;f.add(d);const p=c.get(d);if(!p||!p.dependsOn.length)return s.set(d,0),0;const m=Math.max(...p.dependsOn.map(y=>u(y,f)))+1;return s.set(d,m),m}for(const d of l.nodes)u(d.id);return s}function oS({graph:l}){if(!l.nodes.length)return i.jsx("div",{className:"empty-state",children:"No graph data"});const s=cS(l),c=Math.max(...s.values(),0),u=Array.from({length:c+1},()=>[]);for(const d of l.nodes)u[s.get(d.id)??0].push(d);return i.jsxs("div",{className:"card",style:{marginBottom:20,overflow:"auto"},children:[i.jsx("div",{className:"card-title",children:"Dependency Graph"}),i.jsx("div",{style:{display:"flex",gap:24,padding:"12px 0",minWidth:"max-content"},children:u.map((d,f)=>i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,minWidth:160},children:[i.jsxs("div",{className:"text-dim",style:{fontSize:11,textAlign:"center"},children:["Layer ",f]}),d.map(p=>i.jsxs(Ke,{to:`/journal/${p.id}`,style:{display:"block",padding:"10px 12px",background:"var(--color-surface-raised)",border:"1px solid var(--color-border)",borderLeft:`3px solid var(--status-${p.status})`,borderRadius:"var(--radius)",textDecoration:"none"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8,marginBottom:4},children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:p.graphId}),i.jsx(jt,{status:p.status})]}),i.jsx("div",{className:"mono text-dim",style:{fontSize:10},children:p.id})]},p.id))]},f))}),l.edges.length>0&&i.jsxs("div",{className:"text-dim",style:{fontSize:11,marginTop:8},children:[l.edges.length," dependency edge",l.edges.length===1?"":"s"]})]})}function dS({run:l,allRuns:s}){var d;const c=(d=l.input)==null?void 0:d.upstream;if(!c||typeof c!="object"||Array.isArray(c))return null;const u=Object.entries(c);return u.length?i.jsxs("div",{className:"card",style:{marginBottom:16},children:[i.jsx("div",{className:"card-title",children:"Received from Upstream"}),u.map(([f,p])=>{const m=s==null?void 0:s.find(y=>y.graphId===f&&y.status==="done");return i.jsxs("div",{style:{marginBottom:10},children:[i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:f}),m&&i.jsx(Ke,{to:`/journal/${m.id}`,style:{fontSize:11},children:"view in journal"})]}),i.jsx("pre",{style:{fontSize:11,overflow:"auto",maxHeight:120,padding:8,background:"var(--color-bg)",borderRadius:"var(--radius)"},children:JSON.stringify(p,null,2)})]},f)})]}):null}function fS({run:l,allRuns:s}){var u;if(((u=l.error)==null?void 0:u.code)!=="DEP_FAILED"||!l.dependsOn.length)return null;const c=(s==null?void 0:s.find(d=>l.dependsOn.includes(d.id)&&d.status==="failed"))??(s==null?void 0:s.find(d=>l.dependsOn.includes(d.id)));return i.jsxs("div",{style:{fontSize:12,marginTop:6},children:["Root cause:"," ",c?i.jsxs(Ke,{to:`/journal/${c.id}`,style:{color:"var(--status-failed)"},children:[c.graphId," (",c.id,")"]}):i.jsx("span",{className:"mono",children:l.dependsOn[0]})]})}function hS(l){return new Date(l).toLocaleString()}function mS({run:l,allRuns:s}){if(l.status!=="blocked"||l.dependsOn.length===0)return null;const c=l.dependsOn.map(f=>s.find(p=>p.id===f)).filter(f=>f!=null),u=c.filter(f=>f.status==="failed"||f.status==="cancelled"),d=c.filter(f=>f.status==="pending"||f.status==="running");return u.length===0&&d.length===0?null:i.jsxs("div",{style:{padding:"10px 14px",background:"var(--status-blocked-bg)",border:"1px solid var(--status-blocked)",borderRadius:"var(--radius)",marginBottom:8,fontSize:13},children:[i.jsx("strong",{style:{color:"var(--status-blocked)"},children:"Blocked"}),u.length>0&&i.jsxs("div",{style:{marginTop:6},children:["Upstream failures:"," ",u.map(f=>i.jsx(Ke,{to:`/journal/${f.id}`,style:{marginRight:8,color:"var(--status-failed)"},children:f.graphId},f.id))]}),d.length>0&&i.jsxs("div",{style:{marginTop:6},children:["Waiting on:"," ",d.map(f=>i.jsx(Ke,{to:`/journal/${f.id}`,style:{marginRight:8,color:"var(--status-pending)"},children:f.graphId},f.id))]})]})}function pS(){const{itemId:l}=Ds(),s=ve({queryKey:["item-runs",l],queryFn:()=>re.itemRuns(l),enabled:!!l}),c=ve({queryKey:["item-graph",l],queryFn:()=>re.itemGraph(l),enabled:!!l}),u=s.data??[];if(s.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading timeline…"]});if(s.isError)return i.jsxs("div",{className:"error-state",children:["Error: ",String(s.error)]});const d=[...new Set(u.map(f=>f.graphId))];return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/journal",children:"Journal"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),i.jsx(Ke,{to:`/journal?itemId=${l}`,children:"Item journal"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),i.jsx("span",{className:"mono",children:l})]}),i.jsxs("div",{className:"page-header",children:[i.jsx("h1",{className:"page-title",children:"Run timeline"}),i.jsx("span",{className:"page-subtitle mono",children:l})]}),u.length===0&&i.jsx("div",{className:"empty-state",children:"No job runs found for this item."}),u.length>0&&i.jsxs(i.Fragment,{children:[c.data&&i.jsx(oS,{graph:c.data}),i.jsxs("div",{className:"card",style:{marginBottom:20},children:[i.jsx("div",{className:"card-title",children:"Pipeline status"}),i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:10,marginTop:8},children:d.map(f=>{const p=u.filter(y=>y.graphId===f),m=p[p.length-1];return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",background:"var(--color-surface-raised)",borderRadius:"var(--radius)",border:"1px solid var(--color-border)"},children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:f}),m&&i.jsx(jt,{status:m.status}),i.jsxs("span",{className:"text-dim",style:{fontSize:11},children:[p.length,"×"]})]},f)})})]}),i.jsx("div",{className:"timeline",children:u.map(f=>i.jsxs("div",{className:"timeline-item",children:[i.jsx("div",{className:`timeline-dot timeline-dot-${f.status}`}),i.jsxs("div",{className:"card",style:{borderLeft:`3px solid var(--status-${f.status})`},children:[i.jsx(mS,{run:f,allRuns:u}),i.jsx(dS,{run:f,allRuns:u}),i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[i.jsx(jt,{status:f.status}),i.jsx("span",{className:"mono",style:{fontSize:13},children:f.graphId})]}),i.jsx(Ke,{to:`/journal/${f.id}`,className:"mono text-muted",style:{fontSize:11},children:f.id})]}),i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 24px",fontSize:12,color:"var(--color-text-muted)"},children:[i.jsxs("span",{children:["Job: ",i.jsx("span",{className:"mono",children:f.jobDefId})]}),i.jsxs("span",{children:["Attempts: ",i.jsxs("span",{className:"mono",children:[f.attempts,"/",f.maxAttempts]})]}),i.jsxs("span",{children:["Created: ",i.jsx("span",{className:"mono",children:hS(f.createdAt)})]})]}),f.error&&i.jsxs("div",{style:{marginTop:10,padding:"8px 10px",background:"var(--status-failed-bg)",borderRadius:"var(--radius)",fontSize:12,color:"var(--status-failed)"},children:[f.error.message,i.jsx(fS,{run:f,allRuns:u})]}),f.dependsOn.length>0&&i.jsx("div",{style:{marginTop:10},children:i.jsx(fa,{label:`Depends On (${f.dependsOn.length})`,value:f.dependsOn})})]})]},f.id))})]})]})}function yS(){const l=Bn(),s=ji(),{agentQueryParam:c,agentId:u}=Ia(),d=ve({queryKey:["work",c??"all"],queryFn:()=>re.listWork(c)}),f=Xt({mutationFn:y=>re.runEvaluation(y),onSuccess:()=>s.invalidateQueries({queryKey:["work"]})}),p=Xt({mutationFn:({id:y,status:g})=>re.setWorkStatus(y,g),onSuccess:()=>s.invalidateQueries({queryKey:["work"]})}),m=d.data??[];return i.jsxs("div",{children:[i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"Ongoing Work"}),i.jsx("span",{className:"page-subtitle",children:u?i.jsxs(i.Fragment,{children:["Ongoing work for object types in agent scope ",i.jsx("span",{className:"mono",children:u}),"."]}):"Ongoing work evaluates information on a schedule and queues jobs automatically."})]}),i.jsx(Ke,{to:"/work/new",children:i.jsx("button",{className:"primary",children:"+ New ongoing work"})})]}),d.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}),d.isError&&i.jsx(Zt,{title:"Failed to load ongoing work",detail:d.error,onRetry:()=>d.refetch()}),m.length===0&&!d.isLoading&&i.jsx(Dt,{title:"No ongoing work yet",message:"Ongoing work evaluates information on a schedule and queues jobs for items that match your narratives and processing rules.",actionLabel:"New ongoing work",actionTo:"/work/new"}),m.length>0&&i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Name"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Entity"}),i.jsx("th",{children:"Narratives"}),i.jsx("th",{children:"Reprocessing"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Re-scan interval"}),i.jsx("th",{children:"Last scanned"}),i.jsx("th",{children:"Jobs created"}),i.jsx("th",{children:"Last result"}),i.jsx("th",{})]})}),i.jsx("tbody",{children:m.map(y=>{var g;return i.jsxs("tr",{onClick:()=>l(`/work/${y.id}`),children:[i.jsx("td",{children:i.jsx("strong",{children:y.name})}),i.jsx("td",{children:i.jsx(jt,{status:y.status})}),i.jsx("td",{className:"mono",children:y.entity}),i.jsx("td",{children:i.jsx("span",{className:"chip-row",children:y.narratives.map(b=>i.jsx("span",{className:"chip narrative",children:b},b))})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:(g=y.processing)!=null&&g.reprocessingMode&&y.processing.reprocessingMode!=="skip"?y.processing.reprocessingMode:"skip (default)"}),i.jsx("td",{className:"mono",style:{fontSize:12},children:y.graphName??y.graphId}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:Es(y.policy.rescanIntervalMinutes)}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:Ln(y.lastEvaluatedAt)}),i.jsx("td",{className:"mono",children:y.jobsCreated}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:y.lastResult}),i.jsx("td",{onClick:b=>b.stopPropagation(),children:i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("button",{type:"button",style:{fontSize:12},disabled:f.isPending,onClick:()=>f.mutate(y.id),title:"Run evaluation now",children:"Evaluate"}),i.jsx("button",{type:"button",style:{fontSize:12},disabled:p.isPending,onClick:()=>p.mutate({id:y.id,status:y.status==="active"?"inactive":"active"}),children:y.status==="active"?"Deactivate":"Activate"})]})})]},y.id)})})]})})]})}function zd({steps:l,current:s,isComplete:c,canGoTo:u,onGoTo:d,maxWidth:f}){return i.jsx("div",{className:"wizard-steps",style:f?{maxWidth:f}:void 0,children:l.map((p,m)=>{const y=s===m,g=(c==null?void 0:c(m))??m<s,b=(u==null?void 0:u(m))??m<=s;return i.jsxs("button",{type:"button",className:`wizard-step${y?" is-active":""}${g?" is-done":""}${b?" is-clickable":""}`,onClick:()=>b&&d(m),disabled:!b&&!y,children:[i.jsx("span",{className:"wizard-step-num",children:g&&!y?"✓":m+1}),i.jsxs("span",{className:"wizard-step-label",children:[i.jsx("span",{className:"wizard-step-title",children:p.title}),p.summary&&i.jsx("span",{className:"wizard-step-summary",children:p.summary})]})]},p.id)})})}function ht({onBack:l,backLabel:s="Back",onNext:c,nextLabel:u="Next",nextDisabled:d,children:f}){return i.jsxs("div",{className:"wizard-nav",children:[l?i.jsx("button",{type:"button",onClick:l,children:s}):i.jsx("span",{}),i.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[f,c&&i.jsx("button",{type:"button",className:"primary",disabled:d,onClick:c,children:u})]})]})}function mu({entity:l,selected:s,onChange:c,requireSelection:u=!0}){const d=ve({queryKey:["narratives",l],queryFn:()=>re.listNarratives(l),enabled:!!l}),f=d.data??[];function p(x){c(s.includes(x)?s.filter(T=>T!==x):[...s,x])}if(d.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading narratives…"]});if(f.length===0)return i.jsx(Dt,{title:"No narratives available",message:u?"No narrative filters defined for this object type. You can continue — all information will be included.":"No narrative filters are available for this object type."});const m=s.length===f.length,y=f.map(x=>x.key);function g(){c(y)}function b(){c([])}return i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10,gap:12,flexWrap:"wrap"},children:[i.jsxs("span",{style:{fontWeight:600,color:"var(--color-text)",fontSize:13},children:[s.length," of ",f.length," selected"]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:m,onClick:g,children:"Select all"}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:s.length===0,onClick:b,children:"Clear"})]})]}),s.length>0&&i.jsxs("div",{className:"selector-summary",children:[s.map(x=>{const T=f.find(R=>R.key===x);return i.jsx("span",{className:"chip narrative",children:(T==null?void 0:T.label)??x},x)}),i.jsx("span",{style:{color:"var(--color-text-dim)"},children:"·"}),i.jsx("span",{style:{color:"var(--color-text-dim)",fontSize:11},children:"information must match ALL (AND)"})]}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:f.map(x=>{const T=s.includes(x.key);return i.jsxs("div",{role:"checkbox","aria-checked":T,tabIndex:0,className:`selector-card${T?" selected":""}`,onClick:()=>p(x.key),onKeyDown:R=>(R.key===" "||R.key==="Enter")&&p(x.key),children:[i.jsx("div",{className:"selector-card-check-indicator"}),i.jsxs("div",{className:"selector-card-body",children:[i.jsxs("div",{className:"selector-card-meta",children:[i.jsx("span",{className:"selector-card-title",children:x.label}),i.jsx("span",{className:"selector-card-id",children:x.key})]}),x.description&&i.jsx("div",{className:"selector-card-desc",children:x.description})]}),x.activeRecords!==void 0&&i.jsxs("div",{className:"selector-card-count",children:[i.jsx("div",{className:"selector-card-count-num",children:x.activeRecords.toLocaleString()}),i.jsx("div",{className:"selector-card-count-label",children:"items"})]})]},x.key)})}),u&&s.length===0&&i.jsx("p",{className:"text-dim",style:{fontSize:12,marginTop:12},children:"Select at least one narrative to continue."}),!u&&s.length===0&&i.jsxs("p",{className:"text-dim",style:{fontSize:12,marginTop:12},children:["Information must match ",i.jsx("strong",{style:{color:"var(--color-text-muted)"},children:"all"})," selected narratives (AND). For OR logic, create another ongoing work or batch."]})]})}const vS={core:"Core",snapshot:"Snapshot",scoped:"Scoped",lens:"Lens",enrichment:"Enrichment","processing-output":"Processing",unknown:""};function uu(l){const s=vS[l.role];return s||l.key.charAt(0).toUpperCase()+l.key.slice(1)}function Md({options:l,selected:s,onChange:c}){function u(d){if(s.includes(d)){if(s.length===1)return;c(s.filter(f=>f!==d))}else c([...s,d])}return l.length===0?null:l.length===1?i.jsx("span",{className:"mono",style:{fontSize:13},children:uu(l[0])}):i.jsx("div",{className:"chip-row",children:l.map(d=>i.jsxs("button",{type:"button",className:`chip selectable${s.includes(d.key)?" selected":""}`,onClick:()=>u(d.key),children:[uu(d),d.count>0&&i.jsx("span",{style:{opacity:.65,marginLeft:5,fontSize:11},children:d.count.toLocaleString()})]},d.key))})}const bv="jobs-ui-recent-graphs",gS=20;function jv(){try{const l=localStorage.getItem(bv);if(!l)return[];const s=JSON.parse(l);return Array.isArray(s)?s:[]}catch{return[]}}function xS(l){localStorage.setItem(bv,JSON.stringify(l.slice(0,gS)))}function bS(l){if(!l)return;const s=Date.now(),c=[{graphId:l,usedAt:s},...jv().filter(u=>u.graphId!==l)];xS(c)}function jS(){return jv().sort((l,s)=>s.usedAt-l.usedAt).map(l=>l.graphId)}function hd(l){var s;return(s=l.name)!=null&&s.trim()?l.name.trim():l.graphId.replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase())}function SS(l,s){const c=s.trim().toLowerCase();return c?[l.graphId,l.name,l.description,l.version,...l.entityCompatible].filter(Boolean).join(" ").toLowerCase().includes(c):!0}function xy(l,s){var d,f;if(!s)return 0;const c=s.toLowerCase();let u=0;l.graphId.toLowerCase()===c&&(u+=100),l.graphId.toLowerCase().includes(c)&&(u+=40);for(const p of l.entityCompatible){const m=p.toLowerCase();m===c?u+=80:(m.includes(c)||c.includes(m))&&(u+=30)}return(d=l.name)!=null&&d.toLowerCase().includes(c)&&(u+=20),(f=l.description)!=null&&f.toLowerCase().includes(c)&&(u+=10),u}function NS(l,s,c,u){const d=l.filter(f=>SS(f,u));if(s==="recent"){const f=new Map(d.map(m=>[m.graphId,m])),p=[];for(const m of jS()){const y=f.get(m);y&&p.push(y)}for(const m of d)p.some(y=>y.graphId===m.graphId)||p.push(m);return p}return[...d].sort((f,p)=>{const m=xy(p,c)-xy(f,c);return m!==0?m:hd(f).localeCompare(hd(p))})}const ES=52,CS=5;function pu({entity:l,value:s,onChange:c}){const[u,d]=j.useState("recent"),[f,p]=j.useState(""),m=ve({queryKey:["graphs",l],queryFn:()=>re.graphsForEntity(l),enabled:!!l}),y=m.data??[],g=j.useMemo(()=>NS(y,u,l,f),[y,u,l,f]);function b(x){bS(x.graphId),c(x.graphId,x)}return m.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading graphs…"]}):m.isError?i.jsx(Dt,{title:"Could not load graphs",message:m.error instanceof Error?m.error.message:"The graph list failed to load."}):y.length===0?i.jsx(Dt,{title:"No graphs found",message:`No pipelines are available for "${l}". Choose a different object type or add a graph for this type in Graphs Studio.`}):i.jsxs("div",{className:"graph-picker",children:[i.jsxs("div",{className:"graph-picker-toolbar",children:[i.jsxs("div",{className:"chip-row",children:[i.jsx("button",{type:"button",className:`chip selectable${u==="recent"?" selected":""}`,onClick:()=>d("recent"),children:"Recent"}),i.jsx("button",{type:"button",className:`chip selectable${u==="relevant"?" selected":""}`,onClick:()=>d("relevant"),children:"Relevant"})]}),i.jsx("input",{type:"search",className:"graph-picker-search",placeholder:"Search graphs…",value:f,onChange:x=>p(x.target.value)})]}),i.jsx("div",{className:"graph-picker-list",style:{maxHeight:ES*CS},role:"listbox","aria-label":"Graphs",children:g.length===0?i.jsx("div",{className:"graph-picker-empty",children:"No graphs match your search."}):g.map(x=>{const T=s===x.graphId,R=hd(x);return i.jsxs("button",{type:"button",role:"option","aria-selected":T,className:`graph-picker-row${T?" selected":""}`,onClick:()=>b(x),children:[i.jsxs("div",{className:"graph-picker-row-main",children:[i.jsx("span",{className:"graph-picker-row-title",children:R}),x.version&&i.jsx("span",{className:"chip",style:{fontSize:10},children:x.version})]}),i.jsx("span",{className:"graph-picker-row-id mono",children:x.graphId}),x.description&&i.jsx("span",{className:"graph-picker-row-desc",children:x.description})]},x.graphId)})})]})}function Dd({value:l,entities:s,loading:c,error:u,onChange:d,style:f}){if(u){const p=u instanceof Error?u.message:String(u);return i.jsxs("div",{className:"memorix-panel",style:{borderColor:"var(--status-failed)",background:"var(--status-failed-bg)"},children:[i.jsx("div",{className:"memorix-panel-title",style:{color:"var(--status-failed)"},children:"Could not load object types"}),i.jsx("p",{style:{fontSize:13,margin:"4px 0 0"},children:p||"The API is unavailable. Use http://localhost:3099 or start the API before the Vite dev server (5190)."})]})}return i.jsxs("select",{value:l,disabled:c,onChange:p=>d(p.target.value),style:f??{maxWidth:320},children:[i.jsx("option",{value:"",children:c?"Loading object types…":"— select object type —"}),!c&&["entity","event","knowledge"].map(p=>{const m=s.filter(y=>y.target===p);return m.length?i.jsx("optgroup",{label:L0[p],children:m.map(y=>i.jsx("option",{value:y.name,children:y.label},y.name))},p):null})]})}function wd({included:l,excluded:s,includedLabel:c="Matching information"}){const u=s.reduce((d,f)=>d+f.count,0);return i.jsxs("div",{className:"card",style:{padding:14},children:[i.jsxs("div",{style:{display:"flex",gap:24,marginBottom:s.length?12:0},children:[i.jsxs("div",{children:[i.jsx("div",{className:"status-card-count",style:{fontSize:24,color:"var(--status-done)"},children:l.toLocaleString()}),i.jsx("div",{className:"text-muted",style:{fontSize:12},children:c})]}),i.jsxs("div",{children:[i.jsx("div",{className:"status-card-count",style:{fontSize:24,color:u?"var(--status-blocked)":"var(--color-text-dim)"},children:u.toLocaleString()}),i.jsx("div",{className:"text-muted",style:{fontSize:12},children:"Excluded"})]})]}),s.length>0&&i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.map(d=>i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,padding:"4px 0",borderTop:"1px solid var(--color-border)"},children:[i.jsx("span",{className:"text-muted",children:B0[d.reason]}),i.jsx("span",{className:"mono",style:{color:"var(--status-blocked)"},children:d.count})]},d.reason))})]})}function xi({entity:l,collection:s,narratives:c,processing:u,graphId:d}){const f=ve({queryKey:["matching",l,s,c,u,d],queryFn:()=>re.previewMatching({entity:l,collection:s,narratives:c,processing:u,graphId:d}),enabled:!!l});if(f.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Evaluating matching information…"]});if(!f.data)return null;const{matched:p,total:m,excluded:y,sample:g}=f.data;return i.jsxs("div",{children:[i.jsx(wd,{included:p,excluded:y}),i.jsxs("p",{className:"text-dim",style:{fontSize:12,margin:"10px 0"},children:[p.toLocaleString()," of ",m.toLocaleString()," ",l," items match the current selection."]}),g.length>0&&i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Item"}),i.jsx("th",{children:"Label"}),i.jsx("th",{children:"Narratives"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:g.map(b=>i.jsxs("tr",{style:{cursor:"default"},children:[i.jsx("td",{className:"mono",style:{fontSize:12},children:b.id}),i.jsx("td",{children:b.label}),i.jsx("td",{children:i.jsx("span",{className:"chip-row",children:Object.keys(b.narratives).map(x=>i.jsx("span",{className:"chip narrative",children:x},x))})}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:new Date(b.updatedAt).toLocaleString()})]},b.id))})]})})]})}const TS=["ttl","failed-only","condition","all","skip"],RS=["skip","failed-only","before-date","after-date","condition","all"],by={value:7,unit:"days"};function _d({context:l="recurring",entity:s,targetGraphId:c,value:u,onChange:d}){const{agentQueryParam:f}=Ia(),p=ve({queryKey:["graphs",s],queryFn:()=>re.graphsForEntity(s),enabled:!!s}),m=ve({queryKey:["entities",f??"all"],queryFn:()=>re.listEntities(f)}),y=ve({queryKey:["relationships"],queryFn:()=>"listRelationships"in re?re.listRelationships():Promise.resolve([])}),g=p.data??[],b=g.filter(B=>B.graphId!==c),x=(m.data??[]).filter(B=>B.name!==s),T=y.data??[],R=l==="recurring"?TS:RS,w=l==="recurring"?"ttl":"skip",q=u.reprocessingMode??w,H=u.reprocessingTtl??by,U=u.requiredGraphs??[],X=u.crossEntityPrerequisites??[];function G(B){d({...u,excludeInFlight:!0,...B})}function V(B){G({reprocessingMode:B,reprocessingTtl:B==="ttl"?by:void 0,reprocessingDate:void 0,reprocessingCondition:void 0})}function P(B){const ne=g.find(me=>me.graphId===B);!ne||U.some(me=>me.graphId===B)||G({requiredGraphs:[...U,{graphId:B,graphName:ne.name}]})}function J(B){G({requiredGraphs:U.filter(ne=>ne.graphId!==B)})}const[Z,I]=j.useState(""),[O,le]=j.useState(""),[ue,de]=j.useState(""),Ne=ve({queryKey:["graphs",Z],queryFn:()=>re.graphsForEntity(Z),enabled:!!Z}).data??[],pe=T.filter(B=>B.sourceEntity===s&&B.targetEntity===Z);function Q(){if(!Z||!ue)return;const B=pe.find(me=>me.relationKey===O),ne=Ne.find(me=>me.graphId===ue);X.some(me=>me.entity===Z&&me.relationshipKey===O&&me.graphId===ue)||(G({crossEntityPrerequisites:[...X,{entity:Z,relationshipKey:O,relationshipLabel:B==null?void 0:B.relationKey,graphId:ue,graphName:ne==null?void 0:ne.name}]}),I(""),le(""),de(""))}function $(B){G({crossEntityPrerequisites:X.filter((ne,me)=>me!==B)})}return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[i.jsxs("div",{className:"prereq-section",children:[i.jsxs("div",{className:"prereq-section-header",children:[i.jsx("span",{style:{fontSize:13,fontWeight:600},children:"Reprocessing"}),q!==w&&i.jsx("span",{className:"chip",style:{background:"var(--color-warning-subtle, #2a2000)",borderColor:"var(--color-warning-border, #5a4000)",color:"var(--color-warning, #e6c200)"},children:"custom"})]}),i.jsxs("div",{className:"prereq-section-body",style:{display:"flex",flexDirection:"column",gap:10},children:[i.jsx("select",{value:q,onChange:B=>V(B.target.value),style:{width:"100%"},children:R.map(B=>i.jsx("option",{value:B,children:pv[B]},B))}),q==="ttl"&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",whiteSpace:"nowrap"},children:"Only if older than"}),i.jsx("input",{type:"number",min:1,value:H.value,onChange:B=>G({reprocessingTtl:{...H,value:Math.max(1,Number(B.target.value))}}),style:{width:70}}),i.jsxs("select",{value:H.unit,onChange:B=>G({reprocessingTtl:{...H,unit:B.target.value}}),style:{width:90},children:[i.jsx("option",{value:"hours",children:"hours"}),i.jsx("option",{value:"days",children:"days"}),i.jsx("option",{value:"weeks",children:"weeks"})]})]}),(q==="before-date"||q==="after-date")&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",whiteSpace:"nowrap"},children:q==="before-date"?"Before":"After"}),i.jsx("input",{type:"date",value:u.reprocessingDate??"",onChange:B=>G({reprocessingDate:B.target.value||void 0}),style:{flex:1}})]}),q==="condition"&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("textarea",{rows:3,value:u.reprocessingCondition??"",onChange:B=>G({reprocessingCondition:B.target.value||void 0}),placeholder:'{ "fields.criticality": "high" }',style:{fontFamily:"var(--font-mono)",fontSize:12}}),i.jsx("span",{style:{fontSize:11,color:"var(--color-text-dim)"},children:"Information matching this JSON condition will be re-run even if already processed."})]}),q!=="skip"&&i.jsx("p",{style:{fontSize:11,color:"var(--color-text-dim)",lineHeight:1.5},children:"Information currently queued or running is always excluded to prevent overlapping work."})]})]}),i.jsxs("div",{className:"prereq-section",children:[i.jsxs("div",{className:"prereq-section-header",children:[i.jsx("span",{style:{fontSize:13,fontWeight:600},children:"Required prior processing"}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{className:"text-dim",style:{fontSize:12},children:"same entity"}),U.length>0&&i.jsx("span",{className:"chip",style:{background:"var(--color-accent-subtle)",borderColor:"var(--color-accent-border)",color:"var(--color-accent)"},children:U.length})]})]}),i.jsxs("div",{className:"prereq-section-body",children:[i.jsx("p",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:12,lineHeight:1.5},children:"This item must have been successfully processed by these graphs before it becomes eligible."}),b.length>0?i.jsxs("select",{value:"",onChange:B=>{B.target.value&&P(B.target.value)},style:{width:"100%",marginBottom:U.length?10:0},children:[i.jsx("option",{value:"",children:"+ Add required graph…"}),b.filter(B=>!U.some(ne=>ne.graphId===B.graphId)).map(B=>i.jsxs("option",{value:B.graphId,children:[B.name,B.version?` (${B.version})`:""]},B.graphId))]}):i.jsxs("p",{className:"text-dim",style:{fontSize:12,marginBottom:8},children:['No other graphs compatible with "',s,'".']}),U.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:U.map(B=>i.jsxs("span",{className:"prereq-tag",children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:B.graphName??B.graphId}),i.jsx("button",{className:"prereq-tag-remove",onClick:()=>J(B.graphId),title:"Remove",children:"×"})]},B.graphId))})]})]}),i.jsxs("div",{className:"prereq-section",children:[i.jsxs("div",{className:"prereq-section-header",children:[i.jsx("span",{style:{fontSize:13,fontWeight:600},children:"Cross-entity prerequisites"}),X.length>0&&i.jsx("span",{className:"chip",style:{background:"var(--color-accent-subtle)",borderColor:"var(--color-accent-border)",color:"var(--color-accent)"},children:X.length})]}),i.jsxs("div",{className:"prereq-section-body",children:[i.jsx("p",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:12,lineHeight:1.5},children:"Information from a linked entity must have been processed first — e.g. process child records only after their linked parent records have been enriched."}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr auto",gap:8,alignItems:"center",marginBottom:10},children:[i.jsxs("select",{value:Z,onChange:B=>{I(B.target.value),le(""),de("")},children:[i.jsx("option",{value:"",children:"Linked entity…"}),x.map(B=>i.jsx("option",{value:B.name,children:B.label},B.name))]}),i.jsxs("select",{value:O,onChange:B=>le(B.target.value),disabled:!Z,children:[i.jsx("option",{value:"",children:"Relationship…"}),pe.map(B=>i.jsx("option",{value:B.relationKey,children:B.relationKey},B.relationKey))]}),i.jsxs("select",{value:ue,onChange:B=>de(B.target.value),disabled:!Z,children:[i.jsx("option",{value:"",children:"Processed by…"}),Ne.map(B=>i.jsx("option",{value:B.graphId,children:B.name},B.graphId))]}),i.jsx("button",{type:"button",className:"btn btn-sm",disabled:!Z||!ue,onClick:Q,children:"Add"})]}),X.length>0&&i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:X.map((B,ne)=>i.jsxs("span",{className:"prereq-tag",style:{justifyContent:"space-between"},children:[i.jsxs("span",{style:{fontSize:12},children:[i.jsx("span",{className:"mono",children:B.entity}),B.relationshipKey&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-dim",children:" via "}),i.jsx("span",{className:"mono",children:B.relationshipKey})]}),i.jsx("span",{className:"text-dim",children:" → processed by "}),i.jsx("span",{className:"mono",children:B.graphName??B.graphId})]}),i.jsx("button",{className:"prereq-tag-remove",onClick:()=>$(ne),title:"Remove",children:"×"})]},ne))})]})]})]})}const AS={success:{icon:"✓",color:"var(--status-done)",bg:"var(--status-done-bg)",label:"Success"},partial:{icon:"◐",color:"var(--status-blocked)",bg:"var(--status-blocked-bg)",label:"Partially completed"},failed:{icon:"✕",color:"var(--status-failed)",bg:"var(--status-failed-bg)",label:"Failed"},"created-inactive":{icon:"◌",color:"var(--status-pending)",bg:"var(--status-pending-bg)",label:"Created (inactive)"}},OS={good:"var(--status-done)",warn:"var(--status-blocked)",bad:"var(--status-failed)",default:"var(--color-text)"};function yu({result:l}){const s=AS[l.status];return i.jsxs("div",{className:"card",style:{maxWidth:640,margin:"0 auto",borderColor:s.color},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[i.jsx("span",{style:{width:40,height:40,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:s.bg,color:s.color,fontSize:20,fontWeight:700},children:s.icon}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:17,fontWeight:600},children:l.title}),l.summary&&i.jsx("div",{className:"text-muted",style:{fontSize:13},children:l.summary})]})]}),l.stats&&l.stats.length>0&&i.jsx("div",{className:"review-grid",style:{marginTop:16},children:l.stats.map(c=>i.jsxs("div",{className:"review-row",children:[i.jsx("span",{className:"review-label",children:c.label}),i.jsx("span",{style:{color:OS[c.tone??"default"],fontWeight:c.tone&&c.tone!=="default"?600:400},children:String(c.value)})]},c.label))}),l.errors&&l.errors.length>0&&i.jsxs("div",{className:"error-state",style:{marginTop:16,fontSize:12},children:[i.jsxs("strong",{children:[l.errors.length," issue",l.errors.length===1?"":"s",":"]}),i.jsx("ul",{style:{margin:"6px 0 0 18px"},children:l.errors.map((c,u)=>i.jsx("li",{children:c},u))})]}),l.actions&&l.actions.length>0&&i.jsx("div",{style:{display:"flex",gap:10,flexWrap:"wrap",marginTop:20,paddingTop:16,borderTop:"1px solid var(--color-border)"},children:l.actions.map(c=>c.to?i.jsx(Ke,{to:c.to,children:i.jsx("button",{type:"button",className:c.primary?"primary":"",children:c.label})},c.label):i.jsx("button",{type:"button",className:c.primary?"primary":"",children:c.label},c.label))})]})}const jy={entityId:"same-as-input",contentType:dd,newRecord:!0};function zS(l){if(!l)return"not declared on graph";const s=l.entityId==="same-as-input"?"same as input":l.entityId,c=l.newRecord===!1?"replace existing":"always new record";return`${s} · ${l.contentType} · ${c}`}function Sv({enabled:l,value:s,sourceEntity:c,graphPersistency:u,onEnabledChange:d,onChange:f}){const p=s??jy,m=p.entityId==="same-as-input"?"same-as-input":"custom";function y(g){f({...p,...g})}return i.jsxs("div",{className:"persistency-override",children:[i.jsxs("label",{className:"checkbox-row",style:{display:"flex",gap:8,alignItems:"flex-start",marginBottom:12},children:[i.jsx("input",{type:"checkbox",checked:l,onChange:g=>{const b=g.target.checked;d(b),b&&!s&&f({...jy}),b||f(void 0)}}),i.jsxs("span",{children:[i.jsx("strong",{children:"Override result persistence"}),i.jsxs("span",{className:"hint",style:{display:"block",marginTop:4},children:["Graph default: ",zS(u),l?" — work-level settings below merge over the graph at job completion.":" — enable to specify or override where graph results are written."]})]})]}),l&&i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Target object type"}),i.jsxs("select",{value:m,onChange:g=>{g.target.value==="same-as-input"?y({entityId:"same-as-input"}):y({entityId:c??""})},children:[i.jsxs("option",{value:"same-as-input",children:["Same as input",c?` (${c})`:""]}),i.jsx("option",{value:"custom",children:"Other object type…"})]})]}),m==="custom"&&i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type name"}),i.jsx("input",{value:p.entityId==="same-as-input"?"":p.entityId,onChange:g=>y({entityId:g.target.value||"same-as-input"}),placeholder:"e.g. vulnerabilities"})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Content type"}),i.jsx("input",{value:p.contentType,onChange:g=>y({contentType:g.target.value||dd}),placeholder:dd})]}),i.jsxs("div",{className:"field",children:[i.jsxs("label",{className:"checkbox-row",style:{display:"flex",gap:8,alignItems:"center"},children:[i.jsx("input",{type:"checkbox",checked:p.newRecord!==!1,onChange:g=>y({newRecord:g.target.checked})}),"Always insert a new result record"]}),i.jsx("span",{className:"hint",children:"When unchecked, results replace the existing record at the target (legacy mode)."})]})]})]})}const MS=[{id:"basic",title:"Basic info",summary:"Name & entity"},{id:"narratives",title:"Narratives",summary:"Select information"},{id:"prereqs",title:"Prerequisites",summary:"Processing rules"},{id:"graph",title:"Graph",summary:"Pipeline to run"},{id:"policy",title:"Execution policy",summary:"Interval & concurrency"},{id:"review",title:"Review",summary:"Create"},{id:"result",title:"Created",summary:"Result"}],DS=[5,15,30,60,240,1440];function wS(){const{agentQueryParam:l}=Ia(),[s,c]=j.useState(0),[u,d]=j.useState(""),[f,p]=j.useState(""),[m,y]=j.useState(""),[g,b]=j.useState(["core"]),[x,T]=j.useState([]),[R,w]=j.useState(""),[q,H]=j.useState(),[U,X]=j.useState(!1),[G,V]=j.useState(),[P,J]=j.useState({reprocessingMode:"ttl",reprocessingTtl:{value:7,unit:"days"},excludeInFlight:!0,requiredGraphs:[],crossEntityPrerequisites:[]}),[Z,I]=j.useState({rescanIntervalMinutes:15,priority:100}),[O,le]=j.useState(null),ue=ve({queryKey:["entities",l??"all"],queryFn:()=>re.listEntities(l),retry:2}),de=ue.data??[];j.useEffect(()=>{if(!m||!ue.isSuccess)return;de.map(F=>F.name).includes(m)||y("")},[ue.isSuccess,de,m]);const se=de.find(z=>z.name===m),Ne=Xt({mutationFn:z=>re.createWork({name:u,description:f,entity:m,collection:g[0]??"core",narratives:x,processing:P,graphId:R,policy:Z,activate:z,...U?{persistency:G}:{}}),onSuccess:({result:z})=>{le(z),c(6)}}),pe=!!(u.trim()&&m),Q=!!R,B=!(((se==null?void 0:se.narratives.length)??0)>0)||x.length>0;function ne(z){if(z<=s)return c(z);z>=1&&!pe||z>=2&&!B||z>=4&&!Q||c(z)}const me=(()=>{var he,ge;const z=P.reprocessingMode??"ttl";let F;if(z==="ttl"){const W=P.reprocessingTtl??{value:7,unit:"days"};F=`re-run if older than ${W.value} ${W.unit}`}else F=pv[z].split(" — ")[0];const ee=[F];return(((he=P.requiredGraphs)==null?void 0:he.length)??0)>0&&ee.push(`${P.requiredGraphs.length} prior graph(s) required`),(((ge=P.crossEntityPrerequisites)==null?void 0:ge.length)??0)>0&&ee.push(`${P.crossEntityPrerequisites.length} cross-entity prerequisite(s)`),ee.join(" · ")})(),C=g.map(z=>{const F=se==null?void 0:se.collections.find(ee=>ee.key===z);return F?uu(F):z}).join(", ");return i.jsxs("div",{children:[i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"New ongoing work"}),i.jsx("span",{className:"page-subtitle",children:"Ongoing work evaluates matching information on a schedule and queues jobs automatically."})]})}),i.jsx(zd,{steps:MS,current:s,canGoTo:z=>z<=s||z<=5&&pe,onGoTo:ne,maxWidth:980}),i.jsxs("div",{style:{maxWidth:720},children:[s===0&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"1. Basic info"}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Name *"}),i.jsx("input",{value:u,onChange:z=>d(z.target.value),placeholder:"e.g. Process selected records"})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type *"}),i.jsx(Dd,{value:m,entities:de,loading:ue.isLoading,error:ue.error,onChange:z=>{var F,ee;y(z),T([]),w(""),H(void 0),b([((ee=(F=de.find(he=>he.name===z))==null?void 0:F.collections[0])==null?void 0:ee.key)??"core"])}})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Data sources"}),i.jsx(Md,{options:(se==null?void 0:se.collections)??[],selected:g,onChange:b}),i.jsx("span",{className:"hint",children:"Select which data sources are passed to the graph as input."})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Description"}),i.jsx("textarea",{value:f,onChange:z=>p(z.target.value),placeholder:"Optional — describe what this ongoing work does",rows:3})]})]}),i.jsx(ht,{onNext:()=>ne(1),nextLabel:"Next: narratives",nextDisabled:!pe})]}),s===1&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"2. Select information by narratives"}),i.jsx(mu,{entity:m,selected:x,onChange:T}),m&&i.jsx("div",{style:{marginTop:16},children:i.jsx(xi,{entity:m,collection:g[0]??"core",narratives:x})}),i.jsx(ht,{onBack:()=>ne(0),onNext:()=>ne(2),nextLabel:"Next: prerequisites",nextDisabled:!B})]}),s===2&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"3. Processing prerequisites"}),i.jsx("p",{className:"wizard-lead",children:"Control which information is eligible. By default, items processed within the last 7 days are skipped — keeping results fresh without re-running everything on every scan."}),i.jsx(_d,{context:"recurring",entity:m,targetGraphId:R||void 0,value:P,onChange:J}),i.jsx(ht,{onBack:()=>ne(1),onNext:()=>ne(3),nextLabel:"Next: graph"})]}),s===3&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"4. Choose graph / pipeline"}),i.jsxs("p",{className:"wizard-lead",children:['Only graphs compatible with "',m,'" are shown. This graph is also used for reprocessing checks.']}),i.jsx(pu,{entity:m,value:R,onChange:(z,F)=>{w(z),H(F)}}),i.jsx("div",{className:"section-title",style:{marginTop:20},children:"Result persistence"}),i.jsx(Sv,{enabled:U,value:G,sourceEntity:m,graphPersistency:q==null?void 0:q.persistency,onEnabledChange:X,onChange:V}),i.jsx(ht,{onBack:()=>ne(2),onNext:()=>ne(4),nextLabel:"Next: execution policy",nextDisabled:!Q})]}),s===4&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"5. Execution policy"}),i.jsx("p",{className:"wizard-lead",children:"Running jobs are never interrupted — this policy controls how often new eligible information is discovered. How many jobs run in parallel is configured app-wide in Settings."}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Re-scan for new eligible information"}),i.jsx("select",{value:Z.rescanIntervalMinutes,onChange:z=>I({...Z,rescanIntervalMinutes:Number(z.target.value)}),children:DS.map(z=>i.jsx("option",{value:z,children:Es(z)},z))}),i.jsx("span",{className:"hint",children:"Every X minutes, information that has become newly eligible (new or changed data matching your narratives) is discovered and queued. Running jobs are not affected."})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:Z.priority,onChange:z=>I({...Z,priority:Number(z.target.value)})}),i.jsx("span",{className:"hint",children:"Higher priority jobs are picked up before lower priority ones when the queue is contested."})]})]}),i.jsx(ht,{onBack:()=>ne(3),onNext:()=>ne(5),nextLabel:"Next: review"})]}),s===5&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"6. Review & create"}),i.jsxs("div",{className:"review-grid",style:{marginBottom:20},children:[i.jsx(Cn,{label:"Object type",value:m}),i.jsx(Cn,{label:"Data sources",value:C||"—"}),i.jsx(Cn,{label:"Narratives (AND)",value:x.join(", ")||"none"}),i.jsx(Cn,{label:"Prerequisites",value:me}),i.jsx(Cn,{label:"Graph / pipeline",value:(q==null?void 0:q.name)??R}),U&&i.jsx(Cn,{label:"Result persistence",value:`${(G==null?void 0:G.entityId)??"same-as-input"} · ${(G==null?void 0:G.contentType)??"inferences"}`}),i.jsx(Cn,{label:"Re-scan interval",value:Es(Z.rescanIntervalMinutes)}),i.jsx(Cn,{label:"Priority",value:String(Z.priority)})]}),i.jsx("div",{className:"section-title",children:"Estimated matching information"}),i.jsx(xi,{entity:m,collection:g[0]??"core",narratives:x,processing:P,graphId:R}),Ne.isError&&i.jsx(Zt,{title:"Failed to create ongoing work",detail:Ne.error}),i.jsxs(ht,{onBack:()=>ne(4),children:[i.jsx("button",{type:"button",disabled:Ne.isPending,onClick:()=>Ne.mutate(!1),children:"Create inactive"}),i.jsx("button",{type:"button",className:"primary",disabled:Ne.isPending,onClick:()=>Ne.mutate(!0),children:Ne.isPending?"Creating…":"Create and activate"})]})]}),s===6&&O&&i.jsx(yu,{result:O})]})]})}function Cn({label:l,value:s}){return i.jsxs("div",{className:"review-row",children:[i.jsx("span",{className:"review-label",children:l}),i.jsx("span",{children:s})]})}const _S=[5,15,30,60,240,1440];function qS({work:l,onSaved:s}){var le,ue,de;const[c,u]=j.useState(l.name),[d,f]=j.useState(l.description??""),[p,m]=j.useState(l.narratives),[y,g]=j.useState(l.graphId),[b,x]=j.useState(l.processing??{reprocessingMode:"ttl",reprocessingTtl:{value:7,unit:"days"},excludeInFlight:!0,requiredGraphs:[],crossEntityPrerequisites:[]}),[T,R]=j.useState(l.policy),[w,q]=j.useState(l.persistency!==void 0),[H,U]=j.useState(l.persistency),[X,G]=j.useState(!1);j.useEffect(()=>{u(l.name),f(l.description??""),m(l.narratives),g(l.graphId),x(l.processing??{reprocessingMode:"ttl",reprocessingTtl:{value:7,unit:"days"},excludeInFlight:!0,requiredGraphs:[],crossEntityPrerequisites:[]}),R(l.policy),q(l.persistency!==void 0),U(l.persistency),G(!1)},[l]);const P=(((le=ve({queryKey:["narratives",l.entity],queryFn:()=>re.listNarratives(l.entity)}).data)==null?void 0:le.length)??0)>0,Z=(de=(ue=ve({queryKey:["graphs",l.entity],queryFn:()=>re.graphsForEntity(l.entity)}).data)==null?void 0:ue.find(se=>se.graphId===y))==null?void 0:de.persistency,I=Xt({mutationFn:()=>re.updateWork(l.id,{name:c.trim(),description:d.trim()||void 0,narratives:p,processing:b,graphId:y,policy:T,persistency:w?H:null}),onSuccess:()=>{G(!0),s()}}),O=!!(c.trim()&&y&&(!P||p.length>0));return i.jsxs("div",{className:"card",style:{maxWidth:720},children:[i.jsx("div",{className:"card-title",children:"Configuration"}),i.jsx("p",{className:"text-muted",style:{fontSize:13,marginBottom:16},children:"Edit selection, prerequisites, graph, and schedule for this ongoing work. Parallel execution is configured app-wide in Settings."}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Name"}),i.jsx("input",{value:c,onChange:se=>{u(se.target.value),G(!1)}})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Description"}),i.jsx("textarea",{value:d,onChange:se=>{f(se.target.value),G(!1)},rows:2,placeholder:"Optional"})]})]}),i.jsx("div",{className:"section-title",style:{marginTop:20},children:"Information selection"}),i.jsxs("p",{className:"text-dim",style:{fontSize:12,marginBottom:10},children:["Object type: ",i.jsx("strong",{style:{color:"var(--color-text-muted)"},children:l.entity})," · ","Data source: ",i.jsx("strong",{style:{color:"var(--color-text-muted)"},children:l.collection})]}),i.jsx(mu,{entity:l.entity,selected:p,onChange:se=>{m(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Processing prerequisites"}),i.jsx(_d,{context:"recurring",entity:l.entity,targetGraphId:y||void 0,value:b,onChange:se=>{x(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Graph / pipeline"}),i.jsx(pu,{entity:l.entity,value:y,onChange:se=>{g(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Result persistence"}),i.jsx(Sv,{enabled:w,value:H,sourceEntity:l.entity,graphPersistency:Z,onEnabledChange:se=>{q(se),G(!1)},onChange:se=>{U(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Execution policy"}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Re-scan for new eligible information"}),i.jsx("select",{value:T.rescanIntervalMinutes,onChange:se=>{R({...T,rescanIntervalMinutes:Number(se.target.value)}),G(!1)},children:_S.map(se=>i.jsx("option",{value:se,children:Es(se)},se))})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:T.priority,onChange:se=>{R({...T,priority:Number(se.target.value)}),G(!1)}})]})]}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Matching preview"}),i.jsx(xi,{entity:l.entity,collection:l.collection,narratives:p,processing:b,graphId:y}),I.isError&&i.jsx("div",{style:{marginTop:16},children:i.jsx(Zt,{title:"Failed to save",detail:I.error})}),i.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",marginTop:20},children:[i.jsx("button",{type:"button",className:"primary",disabled:!O||I.isPending,onClick:()=>I.mutate(),children:I.isPending?"Saving…":"Save configuration"}),X&&!I.isPending&&i.jsx("span",{className:"text-muted",style:{fontSize:13},children:"Saved"})]})]})}const US=["Overview","Evaluations","Matching Information","Runs","Settings"];function LS(){var T,R;const{id:l=""}=Ds(),s=ji(),[c,u]=j.useState("Overview"),[d,f]=j.useState(null),p=ve({queryKey:["work",l],queryFn:()=>re.work(l)}),m=p.data,y=ve({queryKey:["work-evals",l],queryFn:()=>re.workEvaluations(l),enabled:!!m}),g=ve({queryKey:["work-runs",l],queryFn:()=>re.factoryRuns({workId:l}),enabled:c==="Runs"}),b=Xt({mutationFn:()=>re.runEvaluation(l),onSuccess:({result:w})=>{f(w),s.invalidateQueries({queryKey:["work",l]}),s.invalidateQueries({queryKey:["work-evals",l]})}}),x=Xt({mutationFn:()=>re.setWorkStatus(l,m.status==="active"?"inactive":"active"),onSuccess:()=>s.invalidateQueries({queryKey:["work",l]})});return p.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):p.isError||!m?i.jsx(Zt,{title:"Ongoing work not found",detail:p.error}):i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/work",children:"Work"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),m.name]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[i.jsx("h1",{className:"page-title",children:m.name}),i.jsx(jt,{status:m.status})]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{disabled:b.isPending,onClick:()=>b.mutate(),children:"Run evaluation now"}),i.jsx("button",{disabled:x.isPending,onClick:()=>x.mutate(),children:m.status==="active"?"Deactivate":"Activate"})]})]}),d&&i.jsx("div",{style:{marginBottom:16},children:i.jsx(yu,{result:d})}),i.jsx("div",{className:"tabs",children:US.map(w=>i.jsx("button",{className:`tab${c===w?" active":""}`,onClick:()=>u(w),children:w},w))}),c==="Overview"&&i.jsxs("div",{className:"detail-grid",children:[i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Configuration"}),i.jsx(da,{k:"Entity",v:`${m.entity} · ${m.collection}`}),i.jsx(da,{k:"Narratives",v:m.narratives.join(", ")||"none"}),i.jsx(da,{k:"Processing rule",v:(T=m.processing)!=null&&T.overrideDuplicatePrevention?"reprocess (override)":"skip already processed / queued / running"}),i.jsx(da,{k:"Graph",v:m.graphName??m.graphId}),i.jsx(da,{k:"Description",v:m.description??"—"})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Schedule & results"}),i.jsx(da,{k:"Re-scan interval",v:Es(m.policy.rescanIntervalMinutes)}),i.jsx(da,{k:"Last scanned",v:`${Ln(m.lastEvaluatedAt)} (${ia(m.lastEvaluatedAt)})`}),i.jsx(da,{k:"Next scan",v:m.status==="active"?Ln(m.nextEvaluationAt):"paused (inactive)"}),i.jsx(da,{k:"Jobs created",v:String(m.jobsCreated)}),i.jsx(da,{k:"Estimated matching",v:String(m.estimatedMatching??"—")}),i.jsx(da,{k:"Priority",v:String(m.policy.priority)})]})]}),c==="Evaluations"&&i.jsx(BS,{id:l,evalsQuery:y}),c==="Matching Information"&&i.jsx(xi,{entity:m.entity,collection:m.collection,narratives:m.narratives,processing:m.processing,graphId:m.graphId}),c==="Runs"&&i.jsx(HS,{runs:((R=g.data)==null?void 0:R.runs)??[],loading:g.isLoading}),c==="Settings"&&i.jsx(qS,{work:m,onSaved:()=>s.invalidateQueries({queryKey:["work",l]})})]})}function BS({evalsQuery:l}){const s=l.data??[];return l.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):s.length===0?i.jsx(Dt,{title:"No evaluations yet",message:"When this work is active (or you run an evaluation now), each cycle is recorded here with what it matched, created, and excluded."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:s.map(c=>i.jsxs("div",{className:"card",children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[i.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[i.jsx(jt,{status:c.status}),i.jsx("span",{className:"text-muted",style:{fontSize:12},children:ia(c.at)})]}),i.jsxs("span",{className:"text-dim",style:{fontSize:12},children:[c.durationMs," ms"]})]}),c.error&&i.jsx("div",{className:"error-state",style:{fontSize:12,marginBottom:8},children:c.error}),c.zeroReason&&i.jsxs("div",{className:"text-muted",style:{fontSize:12,marginBottom:8},children:["Zero jobs: ",c.zeroReason]}),i.jsxs("div",{style:{display:"flex",gap:24,fontSize:13},children:[i.jsxs("span",{children:[i.jsx("strong",{children:c.matched})," ",i.jsx("span",{className:"text-muted",children:"matched"})]}),i.jsxs("span",{children:[i.jsx("strong",{style:{color:"var(--status-done)"},children:c.created})," ",i.jsx("span",{className:"text-muted",children:"created"})]}),i.jsxs("span",{children:[i.jsx("strong",{style:{color:"var(--status-blocked)"},children:c.excluded})," ",i.jsx("span",{className:"text-muted",children:"excluded"})]})]}),c.exclusionReasons.length>0&&i.jsx("div",{style:{marginTop:10},children:i.jsx(wd,{included:c.created,excluded:c.exclusionReasons,includedLabel:"Jobs created"})})]},c.id))})}function HS({runs:l,loading:s}){return s?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):l.length===0?i.jsx(Dt,{title:"No runs yet",message:"Jobs created by this ongoing work will appear here."}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Item"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:l.map(c=>i.jsxs("tr",{onClick:()=>{window.location.href=`/journal/${c.id}`},children:[i.jsx("td",{children:i.jsx(jt,{status:c.status})}),i.jsx("td",{className:"mono",style:{fontSize:12},children:c.recordLabel??c.recordId}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:c.graphName??c.graphId}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:Ln(c.updatedAt)})]},c.id))})]})})}function da({k:l,v:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",style:{fontFamily:"inherit"},children:s})]})}function QS(){const l=Bn();return i.jsxs("div",{children:[i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"On-Demand"}),i.jsx("span",{className:"page-subtitle",children:"Run processing now — pick a single item or a batch selected by narratives."})]})}),i.jsxs("div",{className:"mode-cards",children:[i.jsxs("button",{type:"button",className:"mode-card",onClick:()=>l("/on-demand/single"),children:[i.jsx("div",{className:"mode-card-icon",children:"▶"}),i.jsxs("div",{children:[i.jsx("div",{className:"mode-card-title",children:"Single item"}),i.jsx("div",{className:"mode-card-desc",children:"Run a graph on one item you select manually or at random. Optionally include context."})]}),i.jsx("div",{className:"mode-card-arrow",children:"→"})]}),i.jsxs("button",{type:"button",className:"mode-card",onClick:()=>l("/on-demand/batch"),children:[i.jsx("div",{className:"mode-card-icon",children:"⊞"}),i.jsxs("div",{children:[i.jsx("div",{className:"mode-card-title",children:"Batch"}),i.jsx("div",{className:"mode-card-desc",children:"Run a graph on multiple items that match selected narratives. One job per matching item."})]}),i.jsx("div",{className:"mode-card-arrow",children:"→"})]})]})]})}const GS=new Set(["core","snapshots"]);function md(l){return GS.has(l)}function Nv({node:l,prefix:s,selected:c,onToggle:u}){var b,x,T;const d=s?`${s}.${l.path}`:l.path,f=((b=l.children)==null?void 0:b.map(R=>`${d}.${R.path}`))??[],p=f.length===0||f.every(R=>c.has(R)),m=!((x=l.children)!=null&&x.length),y=m?c.has(d):p;function g(R){if(m)u(d,R.target.checked);else{const w=Ev(l,s);for(const q of w)u(q,R.target.checked)}}return i.jsxs("div",{style:{paddingLeft:s?16:0},children:[i.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:13,paddingBottom:2},children:[i.jsx("input",{type:"checkbox",checked:y,onChange:g}),i.jsx("span",{className:"mono",style:{color:"var(--color-text)"},children:l.path}),l.inferredType&&i.jsx("span",{style:{color:"var(--color-text-dim)",fontSize:11},children:l.inferredType})]}),(T=l.children)==null?void 0:T.map(R=>i.jsx(Nv,{node:R,prefix:d,selected:c,onToggle:u},R.path))]})}function Ev(l,s){var u;const c=s?`${s}.${l.path}`:l.path;return(u=l.children)!=null&&u.length?l.children.flatMap(d=>Ev(d,c)):[c]}function kS({order:l,onChange:s}){function c(u,d){const f=[...l],p=u+d;p<0||p>=f.length||([f[u],f[p]]=[f[p],f[u]],s(f))}return i.jsxs("div",{style:{marginBottom:12},children:[i.jsx("label",{style:{display:"block",marginBottom:4,fontSize:12,color:"var(--color-text-dim)"},children:"Merge priority (top wins on key collision)"}),l.map((u,d)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[i.jsxs("span",{style:{fontSize:11,color:"var(--color-text-dim)",width:16,textAlign:"right"},children:[d+1,"."]}),i.jsx("span",{className:"mono",style:{fontSize:13,flex:1},children:u}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:d===0,onClick:()=>c(d,-1),children:"↑"}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:d===l.length-1,onClick:()=>c(d,1),children:"↓"})]},u))]})}function YS({objectType:l,contentTypeKey:s,target:c,selectedPaths:u,onPathsChange:d}){var q,H;const f=ve({queryKey:["assembler-props",l,s,c],queryFn:()=>re.assemblerProperties({objectType:l,contentType:s,target:c}),staleTime:6e4}),p=((q=f.data)==null?void 0:q.flatPaths)??[],m=((H=f.data)==null?void 0:H.properties)??[],y=new Set(u??p);function g(U,X){const G=new Set(y);X?G.add(U):G.delete(U);const V=p.filter(P=>G.has(P));d(V.length===p.length?void 0:V)}function b(){d(void 0)}function x(){d([])}const T=u===void 0?p.length:u.length,R=md(s)?"1:1":"1:n",w={fontSize:10,padding:"1px 5px",borderRadius:3,background:md(s)?"var(--color-accent-dim, #1a3a5c)":"var(--color-bg-3, #2a2a2a)",color:"var(--color-text-dim)",marginLeft:6};return i.jsxs("div",{style:{border:"1px solid var(--color-border)",borderRadius:6,marginBottom:12,overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"8px 12px",background:"var(--color-bg-2)",display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{className:"mono",style:{fontWeight:600,fontSize:13},children:s}),i.jsx("span",{style:w,children:R}),i.jsx("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--color-text-dim)"},children:f.isLoading?"Loading…":`${T} / ${p.length} properties`}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",onClick:b,children:"All"}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",onClick:x,children:"None"})]}),!f.isLoading&&m.length===0&&i.jsx("div",{style:{padding:"10px 12px",fontSize:12,color:"var(--color-text-dim)"},children:"No properties sampled (collection may be empty)."}),m.length>0&&i.jsx("div",{style:{padding:"10px 12px",maxHeight:240,overflowY:"auto"},children:m.map(U=>i.jsx(Nv,{node:U,prefix:"",selected:y,onToggle:g},U.path))})]})}function KS({objectType:l,target:s,collections:c,value:u,onChange:d}){const f=c.filter(md),p=c.map(b=>{const x=u==null?void 0:u.contentTypes.find(T=>T.key===b);return{key:b,selectedProperties:x==null?void 0:x.selectedProperties}}),m=(()=>{const b=(u==null?void 0:u.priority)??[],x=f,T=x.filter(R=>!b.includes(R));return[...b.filter(R=>x.includes(R)),...T]})();function y(b,x){const T=p.map(R=>R.key===b?{key:b,selectedProperties:x}:R);d({objectType:l,target:s,contentTypes:T,priority:m})}function g(b){d({objectType:l,target:s,contentTypes:p,priority:b})}return i.jsxs("div",{children:[f.length>1&&i.jsx(kS,{order:m,onChange:g}),c.map(b=>{var x;return i.jsx(YS,{objectType:l,contentTypeKey:b,target:s,selectedPaths:(x=p.find(T=>T.key===b))==null?void 0:x.selectedProperties,onPathsChange:T=>y(b,T)},b)})]})}const XS=[{id:"record",title:"Choose item",summary:"What to process"},{id:"related",title:"Context",summary:"Optional linked data"},{id:"graph",title:"Choose graph",summary:"Pipeline to run"},{id:"properties",title:"Properties",summary:"Data to include"},{id:"review",title:"Review & queue",summary:"Confirm"},{id:"result",title:"Queued",summary:"Result"}];function ZS(){var ge;const{agentQueryParam:l}=Ia(),[s,c]=j.useState(0),[u,d]=j.useState(""),[f,p]=j.useState(["core"]),[m,y]=j.useState([]),[g,b]=j.useState(!1),[x,T]=j.useState(""),[R,w]=j.useState(""),[q,H]=j.useState(),[U,X]=j.useState(100),[G,V]=j.useState(),[P,J]=j.useState(null),Z=ve({queryKey:["entities",l??"all"],queryFn:()=>re.listEntities(l),retry:2}),I=Z.data??[];j.useEffect(()=>{if(!u||!Z.isSuccess)return;I.map(Ee=>Ee.name).includes(u)||d("")},[Z.isSuccess,I,u]);const O=I.find(W=>W.name===u),le=(O==null?void 0:O.target)==="event"?"event":"entity",ue=f[0]??"core",de=ve({queryKey:["core-records",u,f,m],queryFn:()=>re.coreRecords({entity:u,collection:ue,narratives:m,pageSize:100}),enabled:!!u}),se=((ge=de.data)==null?void 0:ge.records)??[],Ne=se.find(W=>W.id===x);function pe(W){p(W),T(""),V(void 0)}function Q(W){y(W),T("")}function $(){se.length&&T(se[Math.floor(Math.random()*se.length)].id)}function B(){if(G)return G;const W=f.filter(Ee=>Ee==="core"||Ee==="snapshots");return{objectType:u,target:le,contentTypes:f.map(Ee=>({key:Ee})),priority:W}}const ne=Xt({mutationFn:()=>re.queueSingle({entity:u,collections:f,recordId:x,graphId:R,priority:U,assemblySelection:B()}),onSuccess:({result:W})=>{J(W),c(5)}}),me=!!(u&&x),C=!!R;function z(W){if(W<=s)return c(W);W>=1&&!me||W>=3&&!C||c(W)}const F=(O==null?void 0:O.collections)??[],ee=f.map(W=>{const Ee=F.find(_e=>_e.key===W);return Ee?uu(Ee):W}).join(", "),he=G?(G.contentTypes.reduce((W,Ee)=>{var _e;return W+(((_e=Ee.selectedProperties)==null?void 0:_e.length)??999)},0),`${G.contentTypes.length} content type${G.contentTypes.length!==1?"s":""} selected`):"All properties (default)";return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx("a",{href:"/on-demand",children:"On-Demand"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),"Single item"]}),i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"On-Demand: single item"}),i.jsx("span",{className:"page-subtitle",children:"Process one item through a graph."})]})}),i.jsx(zd,{steps:XS,current:s,canGoTo:W=>W<=s,onGoTo:z,maxWidth:840}),i.jsxs("div",{style:{maxWidth:720},children:[s===0&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"1. Choose item"}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type"}),i.jsx(Dd,{value:u,entities:I,loading:Z.isLoading,error:Z.error,onChange:W=>{var Wa;const Ee=I.find(yl=>yl.name===W),_e=((Wa=Ee==null?void 0:Ee.collections[0])==null?void 0:Wa.key)??"core";d(W),p([_e]),y([]),b(!1),T(""),w(""),H(void 0),V(void 0)}})]}),u&&i.jsxs("div",{className:"field",style:{marginBottom:12},children:[i.jsx("label",{children:"Data sources"}),i.jsx(Md,{options:F,selected:f,onChange:pe}),i.jsx("span",{className:"hint",children:"Select which content types are merged and sent to the graph."})]}),u&&i.jsxs("div",{className:"field",style:{marginBottom:12},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[i.jsxs("label",{style:{marginBottom:0},children:["Narratives",i.jsx("span",{style:{fontWeight:400,color:"var(--color-text-dim)",marginLeft:6},children:"— optional filter"})]}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",onClick:()=>b(W=>!W),children:g?"Hide":m.length>0?`${m.length} active ▾`:"Filter ▾"})]}),m.length>0&&!g&&i.jsx("div",{className:"chip-row",style:{marginBottom:6},children:m.map(W=>{const Ee=O==null?void 0:O.narratives.find(_e=>_e.key===W);return i.jsx("span",{className:"chip narrative",children:(Ee==null?void 0:Ee.label)??W},W)})}),g&&i.jsx("div",{style:{marginTop:8},children:i.jsx(mu,{entity:u,selected:m,onChange:Q,requireSelection:!1})})]}),u&&i.jsxs("div",{className:"field",style:{marginBottom:12},children:[i.jsx("label",{children:"Item *"}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsxs("select",{value:x,onChange:W=>T(W.target.value),style:{flex:1},children:[i.jsx("option",{value:"",children:de.isLoading?"Loading…":se.length?"Select an item…":"No information"}),se.map(W=>i.jsxs("option",{value:W.id,children:[W.label," (",W.id,")"]},W.id))]}),i.jsx("button",{type:"button",onClick:$,disabled:!se.length,children:"Random"})]}),i.jsxs("span",{className:"hint",children:[se.length," items loaded",m.length>0?` (filtered by ${m.length} narrative${m.length>1?"s":""})`:""," · ",i.jsx("a",{href:`/information?entity=${u}`,children:"Browse all information"})]})]}),i.jsx(ht,{onNext:()=>z(1),nextLabel:"Next: context",nextDisabled:!me})]}),s===1&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"2. Context (optional)"}),Ne&&i.jsxs("div",{className:"memorix-panel",children:[i.jsx("div",{className:"memorix-panel-title",children:"Starting item"}),i.jsxs("span",{className:"mono",children:[u," / ",ee," / ",Ne.label]})]}),i.jsx("div",{className:"empty-state",style:{padding:24},children:"Context is not applicable — there are no relations linked to related entities. You can skip this step and continue."}),i.jsx(ht,{onBack:()=>z(0),onNext:()=>z(2),nextLabel:"Skip — no context"})]}),s===2&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"3. Choose graph"}),i.jsx(pu,{entity:u,value:R,onChange:(W,Ee)=>{w(W),H(Ee)}}),i.jsx(ht,{onBack:()=>z(1),onNext:()=>z(3),nextLabel:"Next: properties",nextDisabled:!C})]}),s===3&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"4. Properties to include"}),i.jsxs("div",{style:{marginBottom:12,color:"var(--color-text-dim)",fontSize:13},children:["Choose which properties are sent to the graph as input. Only domain data is sent — system fields are always excluded.",i.jsxs("ul",{style:{margin:"8px 0 0 16px",lineHeight:1.8,fontSize:12},children:[i.jsxs("li",{children:[i.jsx("strong",{children:"1:1 types"})," (core, snapshots): one record per item, merged at the root. Higher priority wins on duplicate keys."]}),i.jsxs("li",{children:[i.jsx("strong",{children:"1:n types"}),": all matching records, placed as an array under the content-type name."]})]})]}),u&&f.length>0&&i.jsx(KS,{objectType:u,target:le,collections:f,value:G,onChange:V}),i.jsx(ht,{onBack:()=>z(2),onNext:()=>z(4),nextLabel:"Next: review"})]}),s===4&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"5. Review & queue"}),i.jsxs("div",{className:"review-grid",style:{marginBottom:16},children:[i.jsx(ti,{label:"Object type",value:u}),i.jsx(ti,{label:"Data sources",value:ee}),i.jsx(ti,{label:"Properties",value:he}),i.jsx(ti,{label:"Item",value:(Ne==null?void 0:Ne.label)??x}),i.jsx(ti,{label:"Graph",value:(q==null?void 0:q.name)??R}),i.jsx(ti,{label:"Expected update",value:`processing.graphs.${R}.processedAt on success`})]}),i.jsx("div",{className:"form-grid",children:i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:U,onChange:W=>X(Number(W.target.value))}),i.jsx("span",{className:"hint",children:"Higher priority is picked up first when the queue is contested."})]})}),ne.isError&&i.jsx(Zt,{title:"Failed to queue job",detail:ne.error}),i.jsx(ht,{onBack:()=>z(3),children:i.jsx("button",{type:"button",className:"primary",disabled:ne.isPending,onClick:()=>ne.mutate(),children:ne.isPending?"Queueing…":"Queue one job"})})]}),s===5&&P&&i.jsx(yu,{result:P})]})]})}function ti({label:l,value:s}){return i.jsxs("div",{className:"review-row",children:[i.jsx("span",{className:"review-label",children:l}),i.jsx("span",{className:"mono",style:{fontSize:12},children:s})]})}const VS=[{id:"entity",title:"Entity",summary:"Choose entity"},{id:"narratives",title:"Narratives",summary:"Select information"},{id:"processing",title:"Processing",summary:"Filters"},{id:"graph",title:"Graph",summary:"Pipeline"},{id:"review",title:"Review",summary:"Matching information"},{id:"queue",title:"Queue policy",summary:"Concurrency"},{id:"result",title:"Queued",summary:"Result"}];function $S(){var Q;const{agentQueryParam:l}=Ia(),[s]=hu(),[c,u]=j.useState(0),[d,f]=j.useState(s.get("entity")??""),[p,m]=j.useState(["core"]),[y,g]=j.useState([]),[b,x]=j.useState(""),[T,R]=j.useState(),[w,q]=j.useState({reprocessingMode:"skip",excludeInFlight:!0}),[H,U]=j.useState(""),[X,G]=j.useState({priority:100}),[V,P]=j.useState(null),J=ve({queryKey:["entities",l??"all"],queryFn:()=>re.listEntities(l),retry:2}),Z=J.data??[];j.useEffect(()=>{if(!d||!J.isSuccess)return;Z.map(B=>B.name).includes(d)||f("")},[J.isSuccess,Z,d]);const I=Z.find($=>$.name===d),le=((Q=ve({queryKey:["matching",d,p,y,w,b,"count"],queryFn:()=>re.previewMatching({entity:d,collection:p[0]??"core",narratives:y,processing:w,graphId:b}),enabled:!!(d&&b)}).data)==null?void 0:Q.matched)??0,ue=Xt({mutationFn:()=>re.queueBatch({name:H||`${d} batch`,entity:d,collections:p,narratives:y,processing:w,graphId:b,policy:X}),onSuccess:({result:$})=>{P($),u(6)}}),de=!!b,Ne=!(((I==null?void 0:I.narratives.length)??0)>0)||y.length>0;function pe($){if($<=c)return u($);$>=1&&!d||$>=2&&!Ne||$>=4&&!de||u($)}return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx("a",{href:"/on-demand",children:"On-Demand"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),"Batch"]}),i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"On-Demand: batch"}),i.jsx("span",{className:"page-subtitle",children:"Run one graph on many items that match your selected narratives."})]})}),i.jsx(zd,{steps:VS,current:c,canGoTo:$=>$<=c,onGoTo:pe,maxWidth:980}),i.jsxs("div",{style:{maxWidth:720},children:[c===0&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"1. Choose entity"}),i.jsx("div",{className:"form-grid",children:i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type"}),i.jsx(Dd,{value:d,entities:Z,loading:J.isLoading,error:J.error,onChange:$=>{var ne;const B=Z.find(me=>me.name===$);f($),m([((ne=B==null?void 0:B.collections[0])==null?void 0:ne.key)??"core"]),g([]),x(""),R(void 0)}})]})}),I&&i.jsxs("div",{className:"field",style:{marginTop:12},children:[i.jsx("label",{children:"Data sources"}),i.jsx(Md,{options:I.collections,selected:p,onChange:m}),i.jsx("span",{className:"hint",children:"Select which data sources are passed to the graph as input."})]}),I&&i.jsxs("p",{className:"text-dim",style:{fontSize:12},children:[I.coreCount," core information · ",I.narratives.length," narratives · ",I.graphs.length," compatible graphs"]}),i.jsx(ht,{onNext:()=>pe(1),nextLabel:"Next: narratives",nextDisabled:!d})]}),c===1&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"2. Select narratives"}),i.jsx(mu,{entity:d,selected:y,onChange:g}),i.jsx("div",{style:{marginTop:16},children:i.jsx(xi,{entity:d,collection:p[0]??"core",narratives:y})}),i.jsx(ht,{onBack:()=>pe(0),onNext:()=>pe(2),nextLabel:"Next: processing",nextDisabled:!Ne})]}),c===2&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"3. Processing prerequisites"}),i.jsx("p",{className:"wizard-lead",children:"Control which information is eligible. Skip already-processed items by default, and optionally require other graphs to have run first."}),i.jsx(_d,{context:"batch",entity:d,targetGraphId:b||void 0,value:w,onChange:q}),i.jsx(ht,{onBack:()=>pe(1),onNext:()=>pe(3),nextLabel:"Next: graph"})]}),c===3&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"4. Choose graph / pipeline"}),i.jsx(pu,{entity:d,value:b,onChange:($,B)=>{x($),R(B)}}),i.jsx(ht,{onBack:()=>pe(2),onNext:()=>pe(4),nextLabel:"Next: review",nextDisabled:!de})]}),c===4&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"5. Review matching information"}),i.jsx(xi,{entity:d,collection:p[0]??"core",narratives:y,processing:w,graphId:b}),i.jsx(ht,{onBack:()=>pe(3),onNext:()=>pe(5),nextLabel:"Next: queue policy"})]}),c===5&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"6. Queue policy"}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Batch name"}),i.jsx("input",{value:H,onChange:$=>U($.target.value),placeholder:`${d} batch`})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:X.priority,onChange:$=>G({...X,priority:Number($.target.value)})}),i.jsx("span",{className:"hint",children:"Higher priority is picked up first when the queue is contested. Parallel execution is configured app-wide in Settings."})]})]}),i.jsx("div",{className:"memorix-panel",children:i.jsxs("div",{style:{fontSize:13},children:["This will create ",i.jsx("strong",{children:le.toLocaleString()})," jobs — one per matching item. The app queue settings control how many run in parallel."]})}),ue.isError&&i.jsx(Zt,{title:"Failed to queue batch",detail:ue.error}),i.jsx(ht,{onBack:()=>pe(4),children:i.jsx("button",{type:"button",className:"primary",disabled:ue.isPending,onClick:()=>ue.mutate(),children:ue.isPending?"Queueing…":"Queue batch"})})]}),c===6&&V&&i.jsx(yu,{result:V})]})]})}function JS(){var p,m;const{id:l=""}=Ds(),s=ve({queryKey:["batch",l],queryFn:()=>re.batch(l)}),c=ve({queryKey:["batch-runs",l],queryFn:()=>re.factoryRuns({batchId:l})}),u=s.data;if(s.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]});if(s.isError||!u)return i.jsx(Zt,{title:"Batch not found",detail:s.error});const d=((p=c.data)==null?void 0:p.runs)??[],f=u.counts;return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/on-demand/batch",children:"Batch"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),u.name]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[i.jsx("h1",{className:"page-title",children:u.name}),i.jsx(jt,{status:u.status})]}),i.jsxs("span",{className:"text-dim",style:{fontSize:12},children:["created ",Ln(u.createdAt)]})]}),i.jsx("div",{className:"status-cards",style:{gridTemplateColumns:"repeat(6, 1fr)"},children:[["Total",f.total],["Pending",f.pending],["Running",f.running],["Done",f.done],["Failed",f.failed],["Cancelled",f.cancelled]].map(([y,g])=>i.jsxs("div",{className:"status-card",style:{cursor:"default"},children:[i.jsx("div",{className:"status-card-label",children:y}),i.jsx("div",{className:"status-card-count",children:g})]},y))}),i.jsxs("div",{className:"detail-grid",children:[i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Selection summary"}),i.jsx(ai,{k:"Entity",v:`${u.entity} · ${u.collection}`}),i.jsx(ai,{k:"Narratives",v:u.narratives.join(", ")||"none"}),i.jsx(ai,{k:"Reprocessing",v:(m=u.processing)!=null&&m.reprocessingMode&&u.processing.reprocessingMode!=="skip"?u.processing.reprocessingMode:"skip (default)"}),i.jsx(ai,{k:"Graph",v:u.graphName??u.graphId}),i.jsx(ai,{k:"Priority",v:String(u.policy.priority)}),i.jsx(ai,{k:"Created",v:ia(u.createdAt)})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Excluded information"}),u.excluded.length?i.jsx(wd,{included:f.total,excluded:u.excluded,includedLabel:"Queued"}):i.jsx("p",{className:"text-muted",style:{fontSize:13},children:"No information was excluded."})]})]}),i.jsxs("div",{className:"section",children:[i.jsxs("div",{className:"section-title",style:{display:"flex",justifyContent:"space-between"},children:[i.jsx("span",{children:"Runs"}),f.failed>0&&i.jsxs("button",{type:"button",disabled:!0,title:"Backend TODO",children:["Retry failed (",f.failed,")"]})]}),c.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}),!c.isLoading&&d.length===0&&i.jsx(Dt,{title:"No runs for this batch yet"}),d.length>0&&i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Item"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Attempts"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:d.map(y=>i.jsxs("tr",{onClick:()=>{window.location.href=`/journal/${y.id}`},children:[i.jsx("td",{children:i.jsx(jt,{status:y.status})}),i.jsx("td",{className:"mono",style:{fontSize:12},children:y.recordLabel??y.recordId}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:y.graphName??y.graphId}),i.jsxs("td",{className:"mono",children:[y.attempts,"/",y.maxAttempts]}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:Ln(y.updatedAt)})]},y.id))})]})})]})]})}function ai({k:l,v:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",style:{fontFamily:"inherit"},children:s})]})}function FS(l){const s=Object.values(l.processing.graphs);if(s.length===0)return"not processed";const c=s.filter(d=>d.lastStatus==="succeeded").length,u=s.filter(d=>d.lastStatus==="failed").length;return`${c} done${u?`, ${u} failed`:""}`}function IS(){var J,Z,I;const l=Bn(),{agentQueryParam:s,agentId:c}=Ia(),[u,d]=hu(),f=u.get("entity")??"",p=u.get("collection")??"core",m=u.get("graphId")??"",y=u.get("processing")??"",g=(u.get("narratives")??"").split(",").filter(Boolean),[b,x]=j.useState(1);function T(O){const le=new URLSearchParams(u);for(const[ue,de]of Object.entries(O))de?le.set(ue,de):le.delete(ue);d(le),x(1)}const w=ve({queryKey:["entities",s??"all"],queryFn:()=>re.listEntities(s)}).data??[],q=w.find(O=>O.name===f),H=ve({queryKey:["narratives",f],queryFn:()=>re.listNarratives(f),enabled:!!f}),U=ve({queryKey:["graphs",f],queryFn:()=>re.graphsForEntity(f),enabled:!!f}),X=ve({queryKey:["core-records",f,p,g,m,y,b],queryFn:()=>re.coreRecords({entity:f,collection:p,narratives:g.length?g:void 0,processingGraphId:m||void 0,processingCondition:y||void 0,page:b,pageSize:25}),enabled:!!f});function G(O){const le=g.includes(O)?g.filter(ue=>ue!==O):[...g,O];T({narratives:le.join(",")||void 0})}const V=((J=X.data)==null?void 0:J.records)??[],P=j.useMemo(()=>{const O=V[0];if(!O)return[];const le=new Set(["recordId","entityId","eventId","knowledgeId","displayName","data","_memorix"]);return Object.keys(O.fields).filter(ue=>!le.has(ue)&&!ue.startsWith("_")).filter(ue=>{const de=O.fields[ue];return de===null||["string","number","boolean"].includes(typeof de)}).slice(0,3)},[V]);return i.jsxs("div",{children:[i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"Information"}),i.jsxs("span",{className:"page-subtitle",children:[c?i.jsxs(i.Fragment,{children:["Object types in agent scope ",i.jsx("span",{className:"mono",children:c}),". · "]}):null,"Browse processed items, their narratives, and processing state."]})]}),f&&i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx(Ke,{to:`/on-demand/single?entity=${f}`,children:i.jsx("button",{children:"Run on-demand"})}),i.jsx(Ke,{to:`/on-demand/batch?entity=${f}`,children:i.jsx("button",{className:"primary",children:"Create batch from filter"})})]})]}),i.jsxs("div",{className:"filters",children:[i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Entity"}),i.jsxs("select",{value:f,onChange:O=>T({entity:O.target.value||void 0,narratives:void 0,graphId:void 0,processing:void 0}),children:[i.jsx("option",{value:"",children:"— select —"}),w.map(O=>i.jsx("option",{value:O.name,children:O.label},O.name))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Collection type"}),i.jsx("select",{value:p,onChange:O=>T({collection:O.target.value}),disabled:!q,children:((q==null?void 0:q.collections)??[{key:"core"}]).map(O=>i.jsx("option",{value:O.key,children:O.key},O.key))})]}),i.jsx("div",{className:"filter-divider"}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Processed by"}),i.jsxs("select",{value:m,onChange:O=>T({graphId:O.target.value||void 0,processing:void 0}),disabled:!f,children:[i.jsx("option",{value:"",children:"any graph"}),(U.data??[]).map(O=>i.jsx("option",{value:O.graphId,children:O.name},O.graphId))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"with status"}),i.jsxs("select",{value:y,onChange:O=>T({processing:O.target.value||void 0}),disabled:!m,title:m?void 0:"Select a graph first",children:[i.jsx("option",{value:"",children:"any status"}),i.jsx("option",{value:"succeeded",children:"succeeded"}),i.jsx("option",{value:"failed",children:"failed"}),i.jsx("option",{value:"running",children:"running"}),i.jsx("option",{value:"queued",children:"queued"}),i.jsx("option",{value:"not-processed",children:"not processed"}),i.jsx("option",{value:"unknown",children:"unknown"})]})]})]}),f&&(((Z=H.data)==null?void 0:Z.length)??0)>0&&i.jsx("div",{className:"chip-row",style:{marginBottom:16},children:(H.data??[]).map(O=>i.jsx("span",{className:`chip selectable${g.includes(O.key)?" selected":""}`,onClick:()=>G(O.key),title:O.description,children:O.label},O.key))}),!f&&i.jsx(Dt,{title:"Select an entity",message:"Choose an entity to browse its items, narratives, and processing state.",icon:"◇"}),f&&X.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}),X.isError&&i.jsx(Zt,{title:"Failed to load information",detail:X.error,onRetry:()=>X.refetch()}),f&&!X.isLoading&&V.length===0&&i.jsx(Dt,{title:"No matching items",message:"No items match the current filters. Try removing a narrative or changing the processing filter."}),V.length>0&&i.jsxs("div",{className:"table-wrap",children:[i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"ID"}),i.jsx("th",{children:"Label"}),P.map(O=>i.jsx("th",{children:O},O)),i.jsx("th",{children:"Narratives"}),i.jsx("th",{children:"Processing"}),i.jsx("th",{children:"Updated"}),i.jsx("th",{})]})}),i.jsx("tbody",{children:V.map(O=>i.jsxs("tr",{onClick:()=>l(`/information/${encodeURIComponent(O.id)}?entity=${f}&collection=${p}`),children:[i.jsx("td",{className:"mono",style:{fontSize:12},children:O.id}),i.jsx("td",{children:O.label}),P.map(le=>i.jsx("td",{className:"text-muted",style:{fontSize:12},children:String(O.fields[le]??"—")},le)),i.jsx("td",{children:i.jsx("span",{className:"chip-row",children:Object.keys(O.narratives).map(le=>i.jsx("span",{className:"chip narrative",children:le},le))})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:FS(O)}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:new Date(O.updatedAt).toLocaleString()}),i.jsx("td",{onClick:le=>le.stopPropagation(),children:i.jsx(Ke,{to:`/on-demand/single?entity=${f}`,style:{fontSize:12},children:"Run"})})]},O.id))})]}),i.jsx(yv,{page:b,pageSize:25,total:((I=X.data)==null?void 0:I.total)??0,onPage:x})]})]})}const WS=["Core","Narratives","Processing","Snapshots","Journal"];function PS(){var g,b;const{recordId:l}=Ds(),s=decodeURIComponent(l??""),[c]=hu(),u=c.get("entity")??"",[d,f]=j.useState("Core"),p=ve({queryKey:["core-record",u,s],queryFn:()=>re.coreRecord(u,s),enabled:!!(u&&s)}),m=ve({queryKey:["record-runs",u,s],queryFn:()=>re.factoryRuns({entity:u,recordId:s}),enabled:d==="Journal"}),y=p.data;return p.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):p.isError||!y?i.jsx(Zt,{title:"Failed to load",detail:p.error}):i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:`/information?entity=${u}`,children:"Information"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),y.label]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:y.label}),i.jsxs("span",{className:"page-subtitle mono",children:[u," · ",y.id]})]}),i.jsx(Ke,{to:`/on-demand/single?entity=${u}`,children:i.jsx("button",{className:"primary",children:"Run on-demand"})})]}),i.jsx("div",{className:"tabs",children:WS.map(x=>i.jsx("button",{className:`tab${d===x?" active":""}`,onClick:()=>f(x),children:x},x))}),d==="Core"&&i.jsxs("div",{className:"card",style:{maxWidth:560},children:[i.jsx("div",{className:"card-title",children:"Core fields"}),i.jsx(ni,{k:"Item id",v:y.id}),i.jsx(ni,{k:"Entity",v:y.entity}),i.jsx(ni,{k:"Label",v:y.label}),Object.entries(y.fields).map(([x,T])=>i.jsx(ni,{k:x,v:String(T)},x)),i.jsx(ni,{k:"Created",v:ia(y.createdAt)}),i.jsx(ni,{k:"Updated",v:ia(y.updatedAt)})]}),d==="Narratives"&&(Object.keys(y.narratives).length===0?i.jsx(Dt,{title:"No narratives on this item",message:"This item has no narratives assigned."}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Narrative"}),i.jsx("th",{children:"Added"}),i.jsx("th",{children:"Detected by"})]})}),i.jsx("tbody",{children:Object.entries(y.narratives).map(([x,T])=>i.jsxs("tr",{style:{cursor:"default"},children:[i.jsx("td",{children:i.jsx("span",{className:"chip narrative",children:x})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:ia(T.addedAt)}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:T.detectedBy??"—"})]},x))})]})})),d==="Processing"&&(Object.keys(y.processing.graphs).length===0?i.jsx(Dt,{title:"No processing yet",message:"This item has not been processed by any graph."}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Version"}),i.jsx("th",{children:"Run"}),i.jsx("th",{children:"Processed at"})]})}),i.jsx("tbody",{children:Object.values(y.processing.graphs).map(x=>i.jsxs("tr",{style:{cursor:"default"},children:[i.jsx("td",{className:"mono",style:{fontSize:12},children:x.graphName??x.graphId}),i.jsx("td",{children:i.jsx(jt,{status:x.lastStatus})}),i.jsx("td",{className:"text-muted",children:x.graphVersion??"—"}),i.jsx("td",{children:x.lastRunId?i.jsx(Ke,{to:`/journal/${x.lastRunId}`,className:"mono",style:{fontSize:12},children:x.lastRunId}):"—"}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:ia(x.processedAt)})]},x.graphId))})]})})),d==="Snapshots"&&i.jsx(Dt,{title:"Snapshots view",message:"Snapshot perspectives for this item live in the Memorix UI. Core is the operational perspective shown here.",icon:"▤"}),d==="Journal"&&(m.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):(((g=m.data)==null?void 0:g.runs.length)??0)===0?i.jsx(Dt,{title:"No journal entries for this item"}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Source"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:(((b=m.data)==null?void 0:b.runs)??[]).map(x=>i.jsxs("tr",{onClick:()=>{window.location.href=`/journal/${x.id}`},children:[i.jsx("td",{children:i.jsx(jt,{status:x.status})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:x.sourceName}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:x.graphName??x.graphId}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:Ln(x.updatedAt)})]},x.id))})]})}))]})}function ni({k:l,v:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",children:s})]})}const Cv=j.createContext("Exellix"),Tv=j.createContext(null);function e1(){return j.useContext(Cv)}function t1(){return j.useContext(Tv)}function a1({children:l}){const{data:s}=ve({queryKey:["config"],queryFn:re.config,staleTime:1/0}),c=(s==null?void 0:s.name)||"Exellix";return j.useEffect(()=>{document.title=`${c} Jobs`},[c]),i.jsx(Tv.Provider,{value:s??null,children:i.jsx(Cv.Provider,{value:c,children:l})})}const li={overview:"Overview",work:"Work",onDemand:"On-Demand",information:"Information",journal:"Journal",settings:"Settings"},n1="2.0.1",l1="/api/agents";class i1 extends j.Component{constructor(){super(...arguments);Bp(this,"state",{error:null,componentStack:null})}static getDerivedStateFromError(c){return{error:c,componentStack:null}}componentDidCatch(c,u){console.error("UI error:",c,u),this.setState({componentStack:u.componentStack??null})}render(){return this.state.error?i.jsxs("div",{style:{padding:32},children:[i.jsxs("div",{className:"error-state",children:[i.jsx("strong",{children:"Something went wrong on this page."}),i.jsx("pre",{style:{marginTop:8,fontSize:11,whiteSpace:"pre-wrap"},children:this.state.error.message}),this.state.componentStack&&i.jsx("pre",{style:{marginTop:8,fontSize:10,whiteSpace:"pre-wrap",opacity:.75},children:this.state.componentStack})]}),i.jsx("button",{style:{marginTop:12},onClick:()=>this.setState({error:null,componentStack:null}),children:"Try again"})]}):this.props.children}}function s1(){const l=ra(),s=e1(),c=t1(),u=d=>d==="/"?l.pathname==="/":l.pathname.startsWith(d);return i.jsxs("header",{className:"topbar",children:[i.jsxs("div",{className:"topbar-brand",children:[i.jsx("span",{className:"topbar-brand-icon",children:"⚙"}),i.jsxs("span",{children:[i.jsx("span",{style:{color:"var(--color-text)"},children:s})," ",i.jsx("span",{children:"Jobs"})]}),i.jsxs("span",{className:"app-pkg-version",children:["v",n1]})]}),i.jsxs("nav",{className:"topbar-nav",children:[i.jsx(ll,{to:"/",className:u("/")?"active":"",children:li.overview}),i.jsx(ll,{to:"/work",className:u("/work")?"active":"",children:li.work}),i.jsx(ll,{to:"/on-demand",className:u("/on-demand")?"active":"",children:li.onDemand}),i.jsx(ll,{to:"/information",className:u("/information")?"active":"",children:li.information}),i.jsx(ll,{to:"/journal",className:u("/journal")?"active":"",children:li.journal}),i.jsx(ll,{to:"/settings",className:u("/settings")?"active":"",children:li.settings})]}),i.jsxs("div",{className:"topbar-meta",title:c?`${c.mongoHost} / ${c.runtimeDb}`:void 0,children:[i.jsx(Ib,{apiBase:l1}),c?i.jsxs("span",{className:"mono",style:{fontSize:11},children:[c.runtimeDb," @ ",c.mongoHost]}):window.location.host]})]})}const Ot=l=>i.jsx(i1,{children:l});function r1(){return i.jsx(j0,{children:i.jsxs("div",{className:"layout",children:[i.jsx(s1,{}),i.jsx("main",{className:"page",children:i.jsxs(Fj,{children:[i.jsx(Ze,{path:"/",element:Ot(i.jsx(G0,{}))}),i.jsx(Ze,{path:"/settings",element:Ot(i.jsx(Y0,{}))}),i.jsx(Ze,{path:"/work",element:Ot(i.jsx(yS,{}))}),i.jsx(Ze,{path:"/work/new",element:Ot(i.jsx(wS,{}))}),i.jsx(Ze,{path:"/work/:id",element:Ot(i.jsx(LS,{}))}),i.jsx(Ze,{path:"/on-demand",element:Ot(i.jsx(QS,{}))}),i.jsx(Ze,{path:"/on-demand/single",element:Ot(i.jsx(ZS,{}))}),i.jsx(Ze,{path:"/on-demand/batch",element:Ot(i.jsx($S,{}))}),i.jsx(Ze,{path:"/on-demand/batch/:id",element:Ot(i.jsx(JS,{}))}),i.jsx(Ze,{path:"/information",element:Ot(i.jsx(IS,{}))}),i.jsx(Ze,{path:"/information/:recordId",element:Ot(i.jsx(PS,{}))}),i.jsx(Ze,{path:"/journal",element:Ot(i.jsx(Z0,{}))}),i.jsx(Ze,{path:"/journal/:id",element:Ot(i.jsx(uS,{}))}),i.jsx(Ze,{path:"/items/:itemId",element:Ot(i.jsx(pS,{}))}),i.jsx(Ze,{path:"/records",element:i.jsx(ka,{to:"/information",replace:!0})}),i.jsx(Ze,{path:"/records/:recordId",element:i.jsx(ka,{to:"/information",replace:!0})}),i.jsx(Ze,{path:"/runs",element:i.jsx(ka,{to:"/journal",replace:!0})}),i.jsx(Ze,{path:"/runs/:id",element:i.jsx(ka,{to:"/journal",replace:!0})}),i.jsx(Ze,{path:"/sources",element:i.jsx(ka,{to:"/information",replace:!0})}),i.jsx(Ze,{path:"/job-defs",element:i.jsx(ka,{to:"/work",replace:!0})}),i.jsx(Ze,{path:"/job-defs/:id",element:i.jsx(ka,{to:"/work",replace:!0})}),i.jsx(Ze,{path:"/jobs/new",element:i.jsx(ka,{to:"/on-demand",replace:!0})}),i.jsx(Ze,{path:"*",element:i.jsx(ka,{to:"/",replace:!0})})]})})]})})}const u1=new _b({defaultOptions:{queries:{retry:1,staleTime:2e3}}}),Rv=document.getElementById("root");if(!Rv)throw new Error("No #root element");ub.createRoot(Rv).render(i.jsx(j.StrictMode,{children:i.jsx(qb,{client:u1,children:i.jsx(a1,{children:i.jsx($b,{storageKey:"exellix-memorix-ui.selected-agent",children:i.jsx(r1,{})})})})}));
|
|
61
|
+
`).length} lines`})]}),u&&i.jsx("div",{className:"json-body",children:i.jsx("pre",{children:f})})]})}const V0={enqueued:"muted",claimed:"start",done:"done",failed:"fail",retry:"info",lease_expired:"fail",cancelled:"muted"},$0={info:"var(--color-text)",start:"var(--status-running)",done:"var(--status-done)",fail:"var(--status-failed)",muted:"var(--color-text-muted)"};function $a(l){if(typeof l=="number")return l>1e12?l:l*1e3;if(typeof l=="string"){const s=new Date(l).getTime();return Number.isNaN(s)?void 0:s}}function vv(l){return new Date(l).toLocaleTimeString(void 0,{hour12:!1})}function fd(l){return l&&typeof l=="object"&&!Array.isArray(l)?l:void 0}function yy(l){const s=(l??"").toLowerCase();return s.includes("fail")||s.includes("error")?"fail":s.includes("complete")||s.includes("done")||s.includes("success")||s.includes("ended")?"done":s.includes("start")||s.includes("running")||s.includes("progress")?"start":"info"}function J0(l){return l==="fail"?"✕":l==="done"?"✓":l==="start"?"▶":"·"}function F0(l){if(l)return typeof l=="string"?l:typeof l=="object"&&l&&"message"in l?String(l.message):JSON.stringify(l)}function gv(l,s=120){return l.length<=s?l:`${l.slice(0,s-1)}…`}function I0(l){const s=fd(l.runContext);return{...l,nodeId:l.nodeId??(s==null?void 0:s.nodeId),graphId:l.graphId??(s==null?void 0:s.graphId),skillKey:l.skillKey??(s==null?void 0:s.skillKey)}}function W0(l){const s=l.nodeId??l.skillKey??"node",c=l.skillKey&&l.skillKey!==l.nodeId?` · ${l.skillKey}`:"";return`${s}${c}`}function xv(l,s,c){if(typeof l.durationMs=="number")return l.durationMs;if(typeof l.duration=="number")return l.duration;if(s!=null&&c!=null)return Math.max(0,Math.round(c-s))}function P0(l){const s=[],c=fd(l.runContext),u=fd(l.outer),d=$a(l.startTime)??$a(l.createdAt),f=$a(l.endTime)??$a(l.updatedAt),p=xv(l,d,f);s.push({label:"Summary",value:{activityId:l.activityId,status:l.status,phase:l.phase,nodeId:l.nodeId??(c==null?void 0:c.nodeId),graphId:l.graphId??(c==null?void 0:c.graphId),skillKey:l.skillKey??(c==null?void 0:c.skillKey),kind:l.kind,startTime:d!=null?new Date(d).toISOString():l.startTime,endTime:f!=null?new Date(f).toISOString():l.endTime,durationMs:p}}),l.inputVariableKeys&&s.push({label:"Input variable keys",value:l.inputVariableKeys}),l.executionKeys&&s.push({label:"Execution keys",value:l.executionKeys}),(u==null?void 0:u.input)!=null&&s.push({label:"Input",value:u.input}),(u==null?void 0:u.output)!=null&&s.push({label:"Output",value:u.output}),(u==null?void 0:u.metadata)!=null&&s.push({label:"Metadata",value:u.metadata}),(u==null?void 0:u.memory)!=null&&s.push({label:"Memory",value:u.memory}),l.outputSummary!=null&&s.push({label:"Output summary",value:l.outputSummary}),l.narrixSummary!=null&&s.push({label:"Narrix",value:l.narrixSummary}),l.error!=null&&s.push({label:"Error",value:l.error}),Array.isArray(l.inner)&&l.inner.length>0&&s.push({label:"Inner steps",value:l.inner});const m={},y=new Set(["activityId","status","phase","nodeId","graphId","skillKey","kind","startTime","endTime","createdAt","updatedAt","durationMs","duration","runContext","outer","inner","error","inputVariableKeys","executionKeys","outputSummary","narrixSummary"]);for(const[g,b]of Object.entries(l))y.has(g)||b==null||(m[g]=b);return Object.keys(m).length>0&&s.push({label:"Record fields",value:m}),s}function eS(l){return l.map((s,c)=>{const u=$a(s.at)??0,d=s.meta&&Object.keys(s.meta).length?s.meta:void 0;return{id:`event-${c}-${s.kind}-${u}`,ts:u,time:vv(u),level:V0[s.kind]??"info",label:s.kind.replace(/_/g," "),summary:d?gv(JSON.stringify(d)):void 0,sections:d?[{label:"Event meta",value:d}]:void 0}})}function tS(l){return l.map((s,c)=>{const u=I0(s),d=$a(u.startTime)??$a(u.createdAt)??0,f=$a(u.endTime)??(yy(u.status)!=="start"?$a(u.updatedAt):void 0),p=yy(u.status),m=xv(u,d,f),y=F0(u.error),g=P0(u);return{id:`activity-${u.activityId??u.nodeId??c}-${d}`,ts:d,time:vv(d),level:p,label:`${J0(p)} ${W0(u)}`,summary:y?gv(y):m!=null?`${m}ms`:void 0,sections:g.length>0?g:void 0}})}function aS({entry:l}){var d;const[s,c]=j.useState(!1),u=(((d=l.sections)==null?void 0:d.length)??0)>0;return i.jsxs("div",{className:`live-console-entry${s?" open":""}`,children:[i.jsxs("div",{className:`live-console-line${u?" expandable":""}`,onClick:u?()=>c(f=>!f):void 0,role:u?"button":void 0,tabIndex:u?0:void 0,onKeyDown:u?f=>f.key==="Enter"&&c(p=>!p):void 0,children:[u&&i.jsx("span",{className:`live-console-chevron${s?" open":""}`,children:"▶"}),i.jsx("span",{className:"live-console-time",children:l.time}),i.jsx("span",{style:{color:$0[l.level]},children:l.label}),l.summary&&i.jsx("span",{className:"live-console-detail",children:l.summary})]}),s&&l.sections&&i.jsx("div",{className:"live-console-expand",children:l.sections.map(f=>i.jsx(fa,{label:f.label,value:f.value},f.label))})]})}function nS({runId:l,live:s}){var T;const c=s?1200:!1,u=ve({queryKey:["run-events",l],queryFn:()=>re.runEvents(l),refetchInterval:c}),d=ve({queryKey:["run-activities",l],queryFn:()=>re.runActivities(l),refetchInterval:c}),f=j.useMemo(()=>{var w,q;const R=[...eS(((w=u.data)==null?void 0:w.events)??[]),...tS(((q=d.data)==null?void 0:q.activities)??[])];return R.sort((H,U)=>H.ts-U.ts),R},[u.data,d.data]),p=j.useRef(null),m=j.useRef(!0),y=()=>{const R=p.current;R&&(m.current=R.scrollHeight-R.scrollTop-R.clientHeight<40)};j.useEffect(()=>{m.current&&p.current&&(p.current.scrollTop=p.current.scrollHeight)},[f.length]);const g=((T=d.data)==null?void 0:T.available)??!0,b=f.length===0,x=f.filter(R=>{var w;return(((w=R.sections)==null?void 0:w.length)??0)>0}).length;return i.jsxs("div",{className:"live-console",children:[i.jsxs("div",{className:"live-console-head",children:[i.jsxs("span",{className:"live-console-title",children:[i.jsx("span",{className:`live-dot${s?" live":""}`}),"Live Console"]}),i.jsxs("span",{className:"live-console-meta mono",children:[s?"streaming…":"idle"," · ",f.length," entr",f.length===1?"y":"ies",x>0?` · ${x} expandable`:""]})]}),i.jsxs("div",{className:"live-console-body",ref:p,onScroll:y,children:[b&&i.jsx("div",{className:"live-console-line muted",children:s?"Waiting for execution events…":"No execution activity recorded yet."}),f.map(R=>i.jsx(aS,{entry:R},R.id))]}),!g&&i.jsx("div",{className:"live-console-foot",children:"Per-node activity tracking is unavailable — showing run lifecycle events only."})]})}function nu(l){return l&&typeof l=="object"&&!Array.isArray(l)?l:void 0}function vy(l){if(!l)return{payload:void 0,memorixRef:void 0};const{_memorixRef:s,...c}=l;return{payload:Object.keys(c).length>0?c:void 0,memorixRef:s}}function gy(l){try{return JSON.stringify(l)}catch{return""}}function lS(l){const s=nu(l);if(!s)return{};const c=nu(s.outer),u=nu(c==null?void 0:c.output);return{runtimeInput:c==null?void 0:c.input,runtimeOutput:(u==null?void 0:u.response)??(u&&!u.data?u:void 0),runtimeData:u==null?void 0:u.data,status:s.status,nodesExecuted:s.nodesExecuted,completedAt:s.completedAt,error:s.error??(u==null?void 0:u.error)}}function iS({runId:l,status:s,input:c,result:u,assemblySelection:d,live:f}){var X;const p=ve({queryKey:["run-activities",l],queryFn:()=>re.runActivities(l),refetchInterval:f?1200:!1}),m=j.useMemo(()=>{var G;return lS((G=p.data)==null?void 0:G.graphRun)},[(X=p.data)==null?void 0:X.graphRun]),y=vy(c),g=vy(nu(m.runtimeInput)),b=u??m.runtimeOutput,x=g.payload!=null&&gy(g.payload)!==gy(y.payload),T=d!=null,R=b!=null,w=m.runtimeData!=null,q=y.memorixRef!=null||g.memorixRef!=null,H=m.status!=null||m.nodesExecuted!=null||m.error!=null;return!c&&!T&&!x&&!R&&!w&&!q&&!H&&!p.isLoading?i.jsxs("div",{className:"card",style:{marginBottom:16},children:[i.jsx("div",{className:"card-title",children:"Request & response"}),i.jsx("span",{className:"text-muted",style:{fontSize:13},children:"No input or output recorded for this run yet."})]}):i.jsxs("div",{className:"card run-io-panel",style:{marginBottom:16},children:[i.jsx("div",{className:"card-title",children:"Request & response"}),i.jsx("p",{className:"run-io-hint",children:"What was queued for this job, what the graph received at runtime, and the final response."}),y.payload!=null&&i.jsx(fa,{label:"Queued input",value:y.payload,defaultOpen:s==="pending"}),T&&i.jsx(fa,{label:"Assembly selection",value:d}),q&&i.jsx(fa,{label:"Memorix reference",value:g.memorixRef??y.memorixRef}),x&&i.jsx(fa,{label:"Sent to graph (runtime input)",value:g.payload,defaultOpen:!0}),!x&&m.runtimeInput!=null&&s!=="pending"&&i.jsx(fa,{label:"Sent to graph (runtime input)",value:m.runtimeInput}),R?i.jsx(fa,{label:"Response",value:b,defaultOpen:!0}):i.jsx("div",{className:"run-io-pending",children:f||s==="running"?"Response will appear when the graph finishes.":s==="failed"?"No response — run failed before producing output.":"No response recorded yet."}),w&&i.jsx(fa,{label:"Execution diagnostics",value:m.runtimeData}),m.error!=null&&i.jsx(fa,{label:"Graph error",value:m.error,defaultOpen:!0}),H&&i.jsx(fa,{label:"Run telemetry",value:{status:m.status,nodesExecuted:m.nodesExecuted,completedAt:m.completedAt}})]})}function pt({label:l,value:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",children:s})]})}function sS(l){if(l.sourceType==="continuous"&&l.sourceRef)return`/work/${l.sourceRef}`;if(l.sourceType==="on-demand-batch"&&l.sourceRef)return`/on-demand/batch/${l.sourceRef}`}function rS(l){const s=l.queueOptions;return l.status!=="pending"?ia(l.availableAt):s!=null&&s.admissionHeld?s.slotsAvailable>0?"Waiting for capacity — a slot is available; you can execute now":`Waiting for capacity (${s.admittedCount}/${s.maxConcurrentJobs} slots in use)`:s&&s.slotsAvailable<=0?`Queued (${s.admittedCount}/${s.maxConcurrentJobs} slots in use) — waiting for worker or execute now`:"Queued — ready to execute"}function uS(){var U;const{id:l}=Ds(),s=ji(),c=ve({queryKey:["factory-run",l],queryFn:()=>re.factoryRun(l),enabled:!!l,refetchInterval:X=>{var G;return((G=X.state.data)==null?void 0:G.status)==="running"?1500:!1}}),u=Xt({mutationFn:()=>re.retryRun(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),d=Xt({mutationFn:()=>re.cancelRun(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),f=Xt({mutationFn:()=>re.executeRun(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),p=Xt({mutationFn:()=>re.queueRunNext(l),onSuccess:()=>s.invalidateQueries({queryKey:["factory-run",l]})}),m=c.data;if(c.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]});if(c.isError||!m)return i.jsx(Zt,{title:"Journal entry not found",detail:c.error});const y=m.queueOptions,g=m.status==="failed"||m.status==="cancelled",b=m.status==="blocked"||m.status==="pending"||m.status==="running",x=m.status==="pending"&&((y==null?void 0:y.canExecuteNow)??!0),T=m.status==="pending"&&((y==null?void 0:y.admissionHeld)||((y==null?void 0:y.slotsAvailable)??1)<=0),R=sS(m),w=m.processingUpdate,q=f.isPending||m.status==="running",H=m.status!=="pending"||m.attempts>0;return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/journal",children:"Journal"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),i.jsx("span",{className:"mono",children:m.id})]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[i.jsx(jt,{status:m.status}),i.jsxs("span",{className:"page-subtitle mono",children:[m.entity," / ",m.recordLabel??m.recordId," / ",m.graphName??m.graphId]})]}),i.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",justifyContent:"flex-end"},children:[x&&i.jsx("button",{className:"primary",disabled:f.isPending,onClick:()=>f.mutate(),children:f.isPending?"Executing…":"Execute now"}),T&&i.jsx("button",{disabled:p.isPending,onClick:()=>p.mutate(),children:p.isPending?"Updating…":"Run next when slot available"}),g&&i.jsx("button",{className:"primary",disabled:u.isPending,onClick:()=>u.mutate(),children:u.isPending?"Retrying…":"Retry"}),b&&i.jsx("button",{disabled:d.isPending,onClick:()=>d.mutate(),style:{color:"var(--status-cancelled)"},children:d.isPending?"Cancelling…":"Cancel"})]})]}),m.status==="pending"&&y&&i.jsxs("div",{className:"memorix-panel",style:{marginBottom:16,fontSize:13},children:[y.slotsAvailable>0?`${y.slotsAvailable} execution slot${y.slotsAvailable===1?"":"s"} available (${y.admittedCount}/${y.maxConcurrentJobs} in use).`:`All ${y.maxConcurrentJobs} execution slots are in use.`,T&&" Use “Run next when slot available” to move this job to the front of the waiting queue."]}),(q||H)&&i.jsx(nS,{runId:m.id,live:q}),i.jsx(iS,{runId:m.id,status:m.status,input:m.input,result:m.result,assemblySelection:m.assemblySelection,live:q}),i.jsxs("div",{className:"detail-grid",children:[i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Source"}),i.jsx(pt,{label:"Source type",value:Cs[m.sourceType]}),i.jsx(pt,{label:"Source name",value:R?i.jsx(Ke,{to:R,children:m.sourceName}):m.sourceName??"—"}),i.jsx(pt,{label:"Source ref",value:m.sourceRef??"—"})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Target"}),i.jsx(pt,{label:"Entity",value:`${m.entity} · ${m.collection}`}),i.jsx(pt,{label:"Item",value:i.jsx(Ke,{to:`/information/${encodeURIComponent(m.recordId)}?entity=${m.entity}`,children:m.recordLabel??m.recordId})}),i.jsx(pt,{label:"Graph",value:`${m.graphName??m.graphId}`}),i.jsx(pt,{label:"Context",value:(U=m.relatedRecords)!=null&&U.length?m.relatedRecords.join(", "):"—"}),i.jsx(pt,{label:"Output collection",value:m.outputCollection??"—"})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Execution"}),i.jsx(pt,{label:"Attempts",value:`${m.attempts} / ${m.maxAttempts}`}),i.jsx(pt,{label:"Priority",value:m.priority}),i.jsx(pt,{label:"Claimed by",value:m.claimedBy??i.jsx("span",{className:"text-dim",children:"unclaimed"})}),i.jsx(pt,{label:"Queue state",value:rS(m)})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Timestamps"}),i.jsx(pt,{label:"Created",value:ia(m.createdAt)}),i.jsx(pt,{label:"Updated",value:ia(m.updatedAt)})]})]}),i.jsxs("div",{className:"card",style:{marginBottom:16,borderColor:(w==null?void 0:w.status)==="updated"?"var(--status-done)":(w==null?void 0:w.status)==="failed"?"var(--status-failed)":void 0},children:[i.jsx("div",{className:"card-title",children:"Processing result"}),!w&&i.jsx("span",{className:"text-muted",style:{fontSize:13},children:"No processing result recorded."}),w&&i.jsxs(i.Fragment,{children:[i.jsx(pt,{label:"Status",value:i.jsx(jt,{status:w.status==="updated"?"succeeded":w.status==="failed"?"failed":"pending"})}),i.jsx(pt,{label:"Graph",value:w.graphId}),i.jsxs("div",{style:{fontSize:13,marginTop:8,color:w.status==="failed"?"var(--status-failed)":"var(--color-text-muted)"},children:[w.status==="updated"&&`processing.graphs.${w.graphId}.processedAt was updated.`,w.status==="failed"&&(w.detail??"Processing metadata update failed."),w.status==="pending"&&"Processing metadata will be updated when the run succeeds.",w.status==="skipped"&&(w.detail??"Processing metadata update was skipped.")]})]})]}),f.isError&&i.jsxs("div",{className:"error-state",style:{marginBottom:16},children:["Execute failed: ",String(f.error)]}),m.error&&i.jsxs("div",{className:"error-state",style:{marginBottom:16},children:[i.jsxs("div",{style:{color:"var(--status-failed)",fontWeight:600},children:["Error: ",m.error.message]}),m.error.code&&i.jsxs("div",{className:"mono text-muted",style:{fontSize:12,marginTop:4},children:["code: ",m.error.code]})]})]})}function cS(l){const s=new Map,c=new Map(l.nodes.map(d=>[d.id,d]));function u(d,f=new Set){if(s.has(d))return s.get(d);if(f.has(d))return 0;f.add(d);const p=c.get(d);if(!p||!p.dependsOn.length)return s.set(d,0),0;const m=Math.max(...p.dependsOn.map(y=>u(y,f)))+1;return s.set(d,m),m}for(const d of l.nodes)u(d.id);return s}function oS({graph:l}){if(!l.nodes.length)return i.jsx("div",{className:"empty-state",children:"No graph data"});const s=cS(l),c=Math.max(...s.values(),0),u=Array.from({length:c+1},()=>[]);for(const d of l.nodes)u[s.get(d.id)??0].push(d);return i.jsxs("div",{className:"card",style:{marginBottom:20,overflow:"auto"},children:[i.jsx("div",{className:"card-title",children:"Dependency Graph"}),i.jsx("div",{style:{display:"flex",gap:24,padding:"12px 0",minWidth:"max-content"},children:u.map((d,f)=>i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,minWidth:160},children:[i.jsxs("div",{className:"text-dim",style:{fontSize:11,textAlign:"center"},children:["Layer ",f]}),d.map(p=>i.jsxs(Ke,{to:`/journal/${p.id}`,style:{display:"block",padding:"10px 12px",background:"var(--color-surface-raised)",border:"1px solid var(--color-border)",borderLeft:`3px solid var(--status-${p.status})`,borderRadius:"var(--radius)",textDecoration:"none"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8,marginBottom:4},children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:p.graphId}),i.jsx(jt,{status:p.status})]}),i.jsx("div",{className:"mono text-dim",style:{fontSize:10},children:p.id})]},p.id))]},f))}),l.edges.length>0&&i.jsxs("div",{className:"text-dim",style:{fontSize:11,marginTop:8},children:[l.edges.length," dependency edge",l.edges.length===1?"":"s"]})]})}function dS({run:l,allRuns:s}){var d;const c=(d=l.input)==null?void 0:d.upstream;if(!c||typeof c!="object"||Array.isArray(c))return null;const u=Object.entries(c);return u.length?i.jsxs("div",{className:"card",style:{marginBottom:16},children:[i.jsx("div",{className:"card-title",children:"Received from Upstream"}),u.map(([f,p])=>{const m=s==null?void 0:s.find(y=>y.graphId===f&&y.status==="done");return i.jsxs("div",{style:{marginBottom:10},children:[i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:f}),m&&i.jsx(Ke,{to:`/journal/${m.id}`,style:{fontSize:11},children:"view in journal"})]}),i.jsx("pre",{style:{fontSize:11,overflow:"auto",maxHeight:120,padding:8,background:"var(--color-bg)",borderRadius:"var(--radius)"},children:JSON.stringify(p,null,2)})]},f)})]}):null}function fS({run:l,allRuns:s}){var u;if(((u=l.error)==null?void 0:u.code)!=="DEP_FAILED"||!l.dependsOn.length)return null;const c=(s==null?void 0:s.find(d=>l.dependsOn.includes(d.id)&&d.status==="failed"))??(s==null?void 0:s.find(d=>l.dependsOn.includes(d.id)));return i.jsxs("div",{style:{fontSize:12,marginTop:6},children:["Root cause:"," ",c?i.jsxs(Ke,{to:`/journal/${c.id}`,style:{color:"var(--status-failed)"},children:[c.graphId," (",c.id,")"]}):i.jsx("span",{className:"mono",children:l.dependsOn[0]})]})}function hS(l){return new Date(l).toLocaleString()}function mS({run:l,allRuns:s}){if(l.status!=="blocked"||l.dependsOn.length===0)return null;const c=l.dependsOn.map(f=>s.find(p=>p.id===f)).filter(f=>f!=null),u=c.filter(f=>f.status==="failed"||f.status==="cancelled"),d=c.filter(f=>f.status==="pending"||f.status==="running");return u.length===0&&d.length===0?null:i.jsxs("div",{style:{padding:"10px 14px",background:"var(--status-blocked-bg)",border:"1px solid var(--status-blocked)",borderRadius:"var(--radius)",marginBottom:8,fontSize:13},children:[i.jsx("strong",{style:{color:"var(--status-blocked)"},children:"Blocked"}),u.length>0&&i.jsxs("div",{style:{marginTop:6},children:["Upstream failures:"," ",u.map(f=>i.jsx(Ke,{to:`/journal/${f.id}`,style:{marginRight:8,color:"var(--status-failed)"},children:f.graphId},f.id))]}),d.length>0&&i.jsxs("div",{style:{marginTop:6},children:["Waiting on:"," ",d.map(f=>i.jsx(Ke,{to:`/journal/${f.id}`,style:{marginRight:8,color:"var(--status-pending)"},children:f.graphId},f.id))]})]})}function pS(){const{itemId:l}=Ds(),s=ve({queryKey:["item-runs",l],queryFn:()=>re.itemRuns(l),enabled:!!l}),c=ve({queryKey:["item-graph",l],queryFn:()=>re.itemGraph(l),enabled:!!l}),u=s.data??[];if(s.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading timeline…"]});if(s.isError)return i.jsxs("div",{className:"error-state",children:["Error: ",String(s.error)]});const d=[...new Set(u.map(f=>f.graphId))];return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/journal",children:"Journal"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),i.jsx(Ke,{to:`/journal?itemId=${l}`,children:"Item journal"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),i.jsx("span",{className:"mono",children:l})]}),i.jsxs("div",{className:"page-header",children:[i.jsx("h1",{className:"page-title",children:"Run timeline"}),i.jsx("span",{className:"page-subtitle mono",children:l})]}),u.length===0&&i.jsx("div",{className:"empty-state",children:"No job runs found for this item."}),u.length>0&&i.jsxs(i.Fragment,{children:[c.data&&i.jsx(oS,{graph:c.data}),i.jsxs("div",{className:"card",style:{marginBottom:20},children:[i.jsx("div",{className:"card-title",children:"Pipeline status"}),i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:10,marginTop:8},children:d.map(f=>{const p=u.filter(y=>y.graphId===f),m=p[p.length-1];return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",background:"var(--color-surface-raised)",borderRadius:"var(--radius)",border:"1px solid var(--color-border)"},children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:f}),m&&i.jsx(jt,{status:m.status}),i.jsxs("span",{className:"text-dim",style:{fontSize:11},children:[p.length,"×"]})]},f)})})]}),i.jsx("div",{className:"timeline",children:u.map(f=>i.jsxs("div",{className:"timeline-item",children:[i.jsx("div",{className:`timeline-dot timeline-dot-${f.status}`}),i.jsxs("div",{className:"card",style:{borderLeft:`3px solid var(--status-${f.status})`},children:[i.jsx(mS,{run:f,allRuns:u}),i.jsx(dS,{run:f,allRuns:u}),i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[i.jsx(jt,{status:f.status}),i.jsx("span",{className:"mono",style:{fontSize:13},children:f.graphId})]}),i.jsx(Ke,{to:`/journal/${f.id}`,className:"mono text-muted",style:{fontSize:11},children:f.id})]}),i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 24px",fontSize:12,color:"var(--color-text-muted)"},children:[i.jsxs("span",{children:["Job: ",i.jsx("span",{className:"mono",children:f.jobDefId})]}),i.jsxs("span",{children:["Attempts: ",i.jsxs("span",{className:"mono",children:[f.attempts,"/",f.maxAttempts]})]}),i.jsxs("span",{children:["Created: ",i.jsx("span",{className:"mono",children:hS(f.createdAt)})]})]}),f.error&&i.jsxs("div",{style:{marginTop:10,padding:"8px 10px",background:"var(--status-failed-bg)",borderRadius:"var(--radius)",fontSize:12,color:"var(--status-failed)"},children:[f.error.message,i.jsx(fS,{run:f,allRuns:u})]}),f.dependsOn.length>0&&i.jsx("div",{style:{marginTop:10},children:i.jsx(fa,{label:`Depends On (${f.dependsOn.length})`,value:f.dependsOn})})]})]},f.id))})]})]})}function yS(){const l=Bn(),s=ji(),{agentQueryParam:c,agentId:u}=Ia(),d=ve({queryKey:["work",c??"all"],queryFn:()=>re.listWork(c)}),f=Xt({mutationFn:y=>re.runEvaluation(y),onSuccess:()=>s.invalidateQueries({queryKey:["work"]})}),p=Xt({mutationFn:({id:y,status:g})=>re.setWorkStatus(y,g),onSuccess:()=>s.invalidateQueries({queryKey:["work"]})}),m=d.data??[];return i.jsxs("div",{children:[i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"Ongoing Work"}),i.jsx("span",{className:"page-subtitle",children:u?i.jsxs(i.Fragment,{children:["Ongoing work for object types in agent scope ",i.jsx("span",{className:"mono",children:u}),"."]}):"Ongoing work evaluates information on a schedule and queues jobs automatically."})]}),i.jsx(Ke,{to:"/work/new",children:i.jsx("button",{className:"primary",children:"+ New ongoing work"})})]}),d.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}),d.isError&&i.jsx(Zt,{title:"Failed to load ongoing work",detail:d.error,onRetry:()=>d.refetch()}),m.length===0&&!d.isLoading&&i.jsx(Dt,{title:"No ongoing work yet",message:"Ongoing work evaluates information on a schedule and queues jobs for items that match your narratives and processing rules.",actionLabel:"New ongoing work",actionTo:"/work/new"}),m.length>0&&i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Name"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Entity"}),i.jsx("th",{children:"Narratives"}),i.jsx("th",{children:"Reprocessing"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Re-scan interval"}),i.jsx("th",{children:"Last scanned"}),i.jsx("th",{children:"Jobs created"}),i.jsx("th",{children:"Last result"}),i.jsx("th",{})]})}),i.jsx("tbody",{children:m.map(y=>{var g;return i.jsxs("tr",{onClick:()=>l(`/work/${y.id}`),children:[i.jsx("td",{children:i.jsx("strong",{children:y.name})}),i.jsx("td",{children:i.jsx(jt,{status:y.status})}),i.jsx("td",{className:"mono",children:y.entity}),i.jsx("td",{children:i.jsx("span",{className:"chip-row",children:y.narratives.map(b=>i.jsx("span",{className:"chip narrative",children:b},b))})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:(g=y.processing)!=null&&g.reprocessingMode&&y.processing.reprocessingMode!=="skip"?y.processing.reprocessingMode:"skip (default)"}),i.jsx("td",{className:"mono",style:{fontSize:12},children:y.graphName??y.graphId}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:Es(y.policy.rescanIntervalMinutes)}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:Ln(y.lastEvaluatedAt)}),i.jsx("td",{className:"mono",children:y.jobsCreated}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:y.lastResult}),i.jsx("td",{onClick:b=>b.stopPropagation(),children:i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("button",{type:"button",style:{fontSize:12},disabled:f.isPending,onClick:()=>f.mutate(y.id),title:"Run evaluation now",children:"Evaluate"}),i.jsx("button",{type:"button",style:{fontSize:12},disabled:p.isPending,onClick:()=>p.mutate({id:y.id,status:y.status==="active"?"inactive":"active"}),children:y.status==="active"?"Deactivate":"Activate"})]})})]},y.id)})})]})})]})}function zd({steps:l,current:s,isComplete:c,canGoTo:u,onGoTo:d,maxWidth:f}){return i.jsx("div",{className:"wizard-steps",style:f?{maxWidth:f}:void 0,children:l.map((p,m)=>{const y=s===m,g=(c==null?void 0:c(m))??m<s,b=(u==null?void 0:u(m))??m<=s;return i.jsxs("button",{type:"button",className:`wizard-step${y?" is-active":""}${g?" is-done":""}${b?" is-clickable":""}`,onClick:()=>b&&d(m),disabled:!b&&!y,children:[i.jsx("span",{className:"wizard-step-num",children:g&&!y?"✓":m+1}),i.jsxs("span",{className:"wizard-step-label",children:[i.jsx("span",{className:"wizard-step-title",children:p.title}),p.summary&&i.jsx("span",{className:"wizard-step-summary",children:p.summary})]})]},p.id)})})}function ht({onBack:l,backLabel:s="Back",onNext:c,nextLabel:u="Next",nextDisabled:d,children:f}){return i.jsxs("div",{className:"wizard-nav",children:[l?i.jsx("button",{type:"button",onClick:l,children:s}):i.jsx("span",{}),i.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[f,c&&i.jsx("button",{type:"button",className:"primary",disabled:d,onClick:c,children:u})]})]})}function mu({entity:l,selected:s,onChange:c,requireSelection:u=!0}){const d=ve({queryKey:["narratives",l],queryFn:()=>re.listNarratives(l),enabled:!!l}),f=d.data??[];function p(x){c(s.includes(x)?s.filter(T=>T!==x):[...s,x])}if(d.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading narratives…"]});if(f.length===0)return i.jsx(Dt,{title:"No narratives available",message:u?"No narrative filters defined for this object type. You can continue — all information will be included.":"No narrative filters are available for this object type."});const m=s.length===f.length,y=f.map(x=>x.key);function g(){c(y)}function b(){c([])}return i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10,gap:12,flexWrap:"wrap"},children:[i.jsxs("span",{style:{fontWeight:600,color:"var(--color-text)",fontSize:13},children:[s.length," of ",f.length," selected"]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:m,onClick:g,children:"Select all"}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:s.length===0,onClick:b,children:"Clear"})]})]}),s.length>0&&i.jsxs("div",{className:"selector-summary",children:[s.map(x=>{const T=f.find(R=>R.key===x);return i.jsx("span",{className:"chip narrative",children:(T==null?void 0:T.label)??x},x)}),i.jsx("span",{style:{color:"var(--color-text-dim)"},children:"·"}),i.jsx("span",{style:{color:"var(--color-text-dim)",fontSize:11},children:"information must match ALL (AND)"})]}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:f.map(x=>{const T=s.includes(x.key);return i.jsxs("div",{role:"checkbox","aria-checked":T,tabIndex:0,className:`selector-card${T?" selected":""}`,onClick:()=>p(x.key),onKeyDown:R=>(R.key===" "||R.key==="Enter")&&p(x.key),children:[i.jsx("div",{className:"selector-card-check-indicator"}),i.jsxs("div",{className:"selector-card-body",children:[i.jsxs("div",{className:"selector-card-meta",children:[i.jsx("span",{className:"selector-card-title",children:x.label}),i.jsx("span",{className:"selector-card-id",children:x.key})]}),x.description&&i.jsx("div",{className:"selector-card-desc",children:x.description})]}),x.activeRecords!==void 0&&i.jsxs("div",{className:"selector-card-count",children:[i.jsx("div",{className:"selector-card-count-num",children:x.activeRecords.toLocaleString()}),i.jsx("div",{className:"selector-card-count-label",children:"items"})]})]},x.key)})}),u&&s.length===0&&i.jsx("p",{className:"text-dim",style:{fontSize:12,marginTop:12},children:"Select at least one narrative to continue."}),!u&&s.length===0&&i.jsxs("p",{className:"text-dim",style:{fontSize:12,marginTop:12},children:["Information must match ",i.jsx("strong",{style:{color:"var(--color-text-muted)"},children:"all"})," selected narratives (AND). For OR logic, create another ongoing work or batch."]})]})}const vS={core:"Core",snapshot:"Snapshot",scoped:"Scoped",lens:"Lens",enrichment:"Enrichment","processing-output":"Processing",unknown:""};function uu(l){const s=vS[l.role];return s||l.key.charAt(0).toUpperCase()+l.key.slice(1)}function Md({options:l,selected:s,onChange:c}){function u(d){if(s.includes(d)){if(s.length===1)return;c(s.filter(f=>f!==d))}else c([...s,d])}return l.length===0?null:l.length===1?i.jsx("span",{className:"mono",style:{fontSize:13},children:uu(l[0])}):i.jsx("div",{className:"chip-row",children:l.map(d=>i.jsxs("button",{type:"button",className:`chip selectable${s.includes(d.key)?" selected":""}`,onClick:()=>u(d.key),children:[uu(d),d.count>0&&i.jsx("span",{style:{opacity:.65,marginLeft:5,fontSize:11},children:d.count.toLocaleString()})]},d.key))})}const bv="jobs-ui-recent-graphs",gS=20;function jv(){try{const l=localStorage.getItem(bv);if(!l)return[];const s=JSON.parse(l);return Array.isArray(s)?s:[]}catch{return[]}}function xS(l){localStorage.setItem(bv,JSON.stringify(l.slice(0,gS)))}function bS(l){if(!l)return;const s=Date.now(),c=[{graphId:l,usedAt:s},...jv().filter(u=>u.graphId!==l)];xS(c)}function jS(){return jv().sort((l,s)=>s.usedAt-l.usedAt).map(l=>l.graphId)}function hd(l){var s;return(s=l.name)!=null&&s.trim()?l.name.trim():l.graphId.replace(/[-_]+/g," ").replace(/\b\w/g,c=>c.toUpperCase())}function SS(l,s){const c=s.trim().toLowerCase();return c?[l.graphId,l.name,l.description,l.version,...l.entityCompatible].filter(Boolean).join(" ").toLowerCase().includes(c):!0}function xy(l,s){var d,f;if(!s)return 0;const c=s.toLowerCase();let u=0;l.graphId.toLowerCase()===c&&(u+=100),l.graphId.toLowerCase().includes(c)&&(u+=40);for(const p of l.entityCompatible){const m=p.toLowerCase();m===c?u+=80:(m.includes(c)||c.includes(m))&&(u+=30)}return(d=l.name)!=null&&d.toLowerCase().includes(c)&&(u+=20),(f=l.description)!=null&&f.toLowerCase().includes(c)&&(u+=10),u}function NS(l,s,c,u){const d=l.filter(f=>SS(f,u));if(s==="recent"){const f=new Map(d.map(m=>[m.graphId,m])),p=[];for(const m of jS()){const y=f.get(m);y&&p.push(y)}for(const m of d)p.some(y=>y.graphId===m.graphId)||p.push(m);return p}return[...d].sort((f,p)=>{const m=xy(p,c)-xy(f,c);return m!==0?m:hd(f).localeCompare(hd(p))})}const ES=52,CS=5;function pu({entity:l,value:s,onChange:c}){const[u,d]=j.useState("recent"),[f,p]=j.useState(""),m=ve({queryKey:["graphs",l],queryFn:()=>re.graphsForEntity(l),enabled:!!l}),y=m.data??[],g=j.useMemo(()=>NS(y,u,l,f),[y,u,l,f]);function b(x){bS(x.graphId),c(x.graphId,x)}return m.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading graphs…"]}):m.isError?i.jsx(Dt,{title:"Could not load graphs",message:m.error instanceof Error?m.error.message:"The graph list failed to load."}):y.length===0?i.jsx(Dt,{title:"No graphs found",message:`No pipelines are available for "${l}". Choose a different object type or add a graph for this type in Graphs Studio.`}):i.jsxs("div",{className:"graph-picker",children:[i.jsxs("div",{className:"graph-picker-toolbar",children:[i.jsxs("div",{className:"chip-row",children:[i.jsx("button",{type:"button",className:`chip selectable${u==="recent"?" selected":""}`,onClick:()=>d("recent"),children:"Recent"}),i.jsx("button",{type:"button",className:`chip selectable${u==="relevant"?" selected":""}`,onClick:()=>d("relevant"),children:"Relevant"})]}),i.jsx("input",{type:"search",className:"graph-picker-search",placeholder:"Search graphs…",value:f,onChange:x=>p(x.target.value)})]}),i.jsx("div",{className:"graph-picker-list",style:{maxHeight:ES*CS},role:"listbox","aria-label":"Graphs",children:g.length===0?i.jsx("div",{className:"graph-picker-empty",children:"No graphs match your search."}):g.map(x=>{const T=s===x.graphId,R=hd(x);return i.jsxs("button",{type:"button",role:"option","aria-selected":T,className:`graph-picker-row${T?" selected":""}`,onClick:()=>b(x),children:[i.jsxs("div",{className:"graph-picker-row-main",children:[i.jsx("span",{className:"graph-picker-row-title",children:R}),x.version&&i.jsx("span",{className:"chip",style:{fontSize:10},children:x.version})]}),i.jsx("span",{className:"graph-picker-row-id mono",children:x.graphId}),x.description&&i.jsx("span",{className:"graph-picker-row-desc",children:x.description})]},x.graphId)})})]})}function Dd({value:l,entities:s,loading:c,error:u,onChange:d,style:f}){if(u){const p=u instanceof Error?u.message:String(u);return i.jsxs("div",{className:"memorix-panel",style:{borderColor:"var(--status-failed)",background:"var(--status-failed-bg)"},children:[i.jsx("div",{className:"memorix-panel-title",style:{color:"var(--status-failed)"},children:"Could not load object types"}),i.jsx("p",{style:{fontSize:13,margin:"4px 0 0"},children:p||"The API is unavailable. Use http://localhost:3099 or start the API before the Vite dev server (5190)."})]})}return i.jsxs("select",{value:l,disabled:c,onChange:p=>d(p.target.value),style:f??{maxWidth:320},children:[i.jsx("option",{value:"",children:c?"Loading object types…":"— select object type —"}),!c&&["entity","event","knowledge"].map(p=>{const m=s.filter(y=>y.target===p);return m.length?i.jsx("optgroup",{label:L0[p],children:m.map(y=>i.jsx("option",{value:y.name,children:y.label},y.name))},p):null})]})}function wd({included:l,excluded:s,includedLabel:c="Matching information"}){const u=s.reduce((d,f)=>d+f.count,0);return i.jsxs("div",{className:"card",style:{padding:14},children:[i.jsxs("div",{style:{display:"flex",gap:24,marginBottom:s.length?12:0},children:[i.jsxs("div",{children:[i.jsx("div",{className:"status-card-count",style:{fontSize:24,color:"var(--status-done)"},children:l.toLocaleString()}),i.jsx("div",{className:"text-muted",style:{fontSize:12},children:c})]}),i.jsxs("div",{children:[i.jsx("div",{className:"status-card-count",style:{fontSize:24,color:u?"var(--status-blocked)":"var(--color-text-dim)"},children:u.toLocaleString()}),i.jsx("div",{className:"text-muted",style:{fontSize:12},children:"Excluded"})]})]}),s.length>0&&i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.map(d=>i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:12,padding:"4px 0",borderTop:"1px solid var(--color-border)"},children:[i.jsx("span",{className:"text-muted",children:B0[d.reason]}),i.jsx("span",{className:"mono",style:{color:"var(--status-blocked)"},children:d.count})]},d.reason))})]})}function xi({entity:l,collection:s,narratives:c,processing:u,graphId:d}){const f=ve({queryKey:["matching",l,s,c,u,d],queryFn:()=>re.previewMatching({entity:l,collection:s,narratives:c,processing:u,graphId:d}),enabled:!!l});if(f.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Evaluating matching information…"]});if(!f.data)return null;const{matched:p,total:m,excluded:y,sample:g}=f.data;return i.jsxs("div",{children:[i.jsx(wd,{included:p,excluded:y}),i.jsxs("p",{className:"text-dim",style:{fontSize:12,margin:"10px 0"},children:[p.toLocaleString()," of ",m.toLocaleString()," ",l," items match the current selection."]}),g.length>0&&i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Item"}),i.jsx("th",{children:"Label"}),i.jsx("th",{children:"Narratives"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:g.map(b=>i.jsxs("tr",{style:{cursor:"default"},children:[i.jsx("td",{className:"mono",style:{fontSize:12},children:b.id}),i.jsx("td",{children:b.label}),i.jsx("td",{children:i.jsx("span",{className:"chip-row",children:Object.keys(b.narratives).map(x=>i.jsx("span",{className:"chip narrative",children:x},x))})}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:new Date(b.updatedAt).toLocaleString()})]},b.id))})]})})]})}const TS=["ttl","failed-only","condition","all","skip"],RS=["skip","failed-only","before-date","after-date","condition","all"],by={value:7,unit:"days"};function _d({context:l="recurring",entity:s,targetGraphId:c,value:u,onChange:d}){const{agentQueryParam:f}=Ia(),p=ve({queryKey:["graphs",s],queryFn:()=>re.graphsForEntity(s),enabled:!!s}),m=ve({queryKey:["entities",f??"all"],queryFn:()=>re.listEntities(f)}),y=ve({queryKey:["relationships"],queryFn:()=>"listRelationships"in re?re.listRelationships():Promise.resolve([])}),g=p.data??[],b=g.filter(B=>B.graphId!==c),x=(m.data??[]).filter(B=>B.name!==s),T=y.data??[],R=l==="recurring"?TS:RS,w=l==="recurring"?"ttl":"skip",q=u.reprocessingMode??w,H=u.reprocessingTtl??by,U=u.requiredGraphs??[],X=u.crossEntityPrerequisites??[];function G(B){d({...u,excludeInFlight:!0,...B})}function V(B){G({reprocessingMode:B,reprocessingTtl:B==="ttl"?by:void 0,reprocessingDate:void 0,reprocessingCondition:void 0})}function P(B){const ne=g.find(me=>me.graphId===B);!ne||U.some(me=>me.graphId===B)||G({requiredGraphs:[...U,{graphId:B,graphName:ne.name}]})}function J(B){G({requiredGraphs:U.filter(ne=>ne.graphId!==B)})}const[Z,I]=j.useState(""),[O,le]=j.useState(""),[ue,de]=j.useState(""),Ne=ve({queryKey:["graphs",Z],queryFn:()=>re.graphsForEntity(Z),enabled:!!Z}).data??[],pe=T.filter(B=>B.sourceEntity===s&&B.targetEntity===Z);function Q(){if(!Z||!ue)return;const B=pe.find(me=>me.relationKey===O),ne=Ne.find(me=>me.graphId===ue);X.some(me=>me.entity===Z&&me.relationshipKey===O&&me.graphId===ue)||(G({crossEntityPrerequisites:[...X,{entity:Z,relationshipKey:O,relationshipLabel:B==null?void 0:B.relationKey,graphId:ue,graphName:ne==null?void 0:ne.name}]}),I(""),le(""),de(""))}function $(B){G({crossEntityPrerequisites:X.filter((ne,me)=>me!==B)})}return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[i.jsxs("div",{className:"prereq-section",children:[i.jsxs("div",{className:"prereq-section-header",children:[i.jsx("span",{style:{fontSize:13,fontWeight:600},children:"Reprocessing"}),q!==w&&i.jsx("span",{className:"chip",style:{background:"var(--color-warning-subtle, #2a2000)",borderColor:"var(--color-warning-border, #5a4000)",color:"var(--color-warning, #e6c200)"},children:"custom"})]}),i.jsxs("div",{className:"prereq-section-body",style:{display:"flex",flexDirection:"column",gap:10},children:[i.jsx("select",{value:q,onChange:B=>V(B.target.value),style:{width:"100%"},children:R.map(B=>i.jsx("option",{value:B,children:pv[B]},B))}),q==="ttl"&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",whiteSpace:"nowrap"},children:"Only if older than"}),i.jsx("input",{type:"number",min:1,value:H.value,onChange:B=>G({reprocessingTtl:{...H,value:Math.max(1,Number(B.target.value))}}),style:{width:70}}),i.jsxs("select",{value:H.unit,onChange:B=>G({reprocessingTtl:{...H,unit:B.target.value}}),style:{width:90},children:[i.jsx("option",{value:"hours",children:"hours"}),i.jsx("option",{value:"days",children:"days"}),i.jsx("option",{value:"weeks",children:"weeks"})]})]}),(q==="before-date"||q==="after-date")&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,color:"var(--color-text-muted)",whiteSpace:"nowrap"},children:q==="before-date"?"Before":"After"}),i.jsx("input",{type:"date",value:u.reprocessingDate??"",onChange:B=>G({reprocessingDate:B.target.value||void 0}),style:{flex:1}})]}),q==="condition"&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("textarea",{rows:3,value:u.reprocessingCondition??"",onChange:B=>G({reprocessingCondition:B.target.value||void 0}),placeholder:'{ "fields.criticality": "high" }',style:{fontFamily:"var(--font-mono)",fontSize:12}}),i.jsx("span",{style:{fontSize:11,color:"var(--color-text-dim)"},children:"Information matching this JSON condition will be re-run even if already processed."})]}),q!=="skip"&&i.jsx("p",{style:{fontSize:11,color:"var(--color-text-dim)",lineHeight:1.5},children:"Information currently queued or running is always excluded to prevent overlapping work."})]})]}),i.jsxs("div",{className:"prereq-section",children:[i.jsxs("div",{className:"prereq-section-header",children:[i.jsx("span",{style:{fontSize:13,fontWeight:600},children:"Required prior processing"}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{className:"text-dim",style:{fontSize:12},children:"same entity"}),U.length>0&&i.jsx("span",{className:"chip",style:{background:"var(--color-accent-subtle)",borderColor:"var(--color-accent-border)",color:"var(--color-accent)"},children:U.length})]})]}),i.jsxs("div",{className:"prereq-section-body",children:[i.jsx("p",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:12,lineHeight:1.5},children:"This item must have been successfully processed by these graphs before it becomes eligible."}),b.length>0?i.jsxs("select",{value:"",onChange:B=>{B.target.value&&P(B.target.value)},style:{width:"100%",marginBottom:U.length?10:0},children:[i.jsx("option",{value:"",children:"+ Add required graph…"}),b.filter(B=>!U.some(ne=>ne.graphId===B.graphId)).map(B=>i.jsxs("option",{value:B.graphId,children:[B.name,B.version?` (${B.version})`:""]},B.graphId))]}):i.jsxs("p",{className:"text-dim",style:{fontSize:12,marginBottom:8},children:['No other graphs compatible with "',s,'".']}),U.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:U.map(B=>i.jsxs("span",{className:"prereq-tag",children:[i.jsx("span",{className:"mono",style:{fontSize:12},children:B.graphName??B.graphId}),i.jsx("button",{className:"prereq-tag-remove",onClick:()=>J(B.graphId),title:"Remove",children:"×"})]},B.graphId))})]})]}),i.jsxs("div",{className:"prereq-section",children:[i.jsxs("div",{className:"prereq-section-header",children:[i.jsx("span",{style:{fontSize:13,fontWeight:600},children:"Cross-entity prerequisites"}),X.length>0&&i.jsx("span",{className:"chip",style:{background:"var(--color-accent-subtle)",borderColor:"var(--color-accent-border)",color:"var(--color-accent)"},children:X.length})]}),i.jsxs("div",{className:"prereq-section-body",children:[i.jsx("p",{style:{fontSize:12,color:"var(--color-text-muted)",marginBottom:12,lineHeight:1.5},children:"Information from a linked entity must have been processed first — e.g. process child records only after their linked parent records have been enriched."}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr auto",gap:8,alignItems:"center",marginBottom:10},children:[i.jsxs("select",{value:Z,onChange:B=>{I(B.target.value),le(""),de("")},children:[i.jsx("option",{value:"",children:"Linked entity…"}),x.map(B=>i.jsx("option",{value:B.name,children:B.label},B.name))]}),i.jsxs("select",{value:O,onChange:B=>le(B.target.value),disabled:!Z,children:[i.jsx("option",{value:"",children:"Relationship…"}),pe.map(B=>i.jsx("option",{value:B.relationKey,children:B.relationKey},B.relationKey))]}),i.jsxs("select",{value:ue,onChange:B=>de(B.target.value),disabled:!Z,children:[i.jsx("option",{value:"",children:"Processed by…"}),Ne.map(B=>i.jsx("option",{value:B.graphId,children:B.name},B.graphId))]}),i.jsx("button",{type:"button",className:"btn btn-sm",disabled:!Z||!ue,onClick:Q,children:"Add"})]}),X.length>0&&i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:X.map((B,ne)=>i.jsxs("span",{className:"prereq-tag",style:{justifyContent:"space-between"},children:[i.jsxs("span",{style:{fontSize:12},children:[i.jsx("span",{className:"mono",children:B.entity}),B.relationshipKey&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-dim",children:" via "}),i.jsx("span",{className:"mono",children:B.relationshipKey})]}),i.jsx("span",{className:"text-dim",children:" → processed by "}),i.jsx("span",{className:"mono",children:B.graphName??B.graphId})]}),i.jsx("button",{className:"prereq-tag-remove",onClick:()=>$(ne),title:"Remove",children:"×"})]},ne))})]})]})]})}const AS={success:{icon:"✓",color:"var(--status-done)",bg:"var(--status-done-bg)",label:"Success"},partial:{icon:"◐",color:"var(--status-blocked)",bg:"var(--status-blocked-bg)",label:"Partially completed"},failed:{icon:"✕",color:"var(--status-failed)",bg:"var(--status-failed-bg)",label:"Failed"},"created-inactive":{icon:"◌",color:"var(--status-pending)",bg:"var(--status-pending-bg)",label:"Created (inactive)"}},OS={good:"var(--status-done)",warn:"var(--status-blocked)",bad:"var(--status-failed)",default:"var(--color-text)"};function yu({result:l}){const s=AS[l.status];return i.jsxs("div",{className:"card",style:{maxWidth:640,margin:"0 auto",borderColor:s.color},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[i.jsx("span",{style:{width:40,height:40,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:s.bg,color:s.color,fontSize:20,fontWeight:700},children:s.icon}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:17,fontWeight:600},children:l.title}),l.summary&&i.jsx("div",{className:"text-muted",style:{fontSize:13},children:l.summary})]})]}),l.stats&&l.stats.length>0&&i.jsx("div",{className:"review-grid",style:{marginTop:16},children:l.stats.map(c=>i.jsxs("div",{className:"review-row",children:[i.jsx("span",{className:"review-label",children:c.label}),i.jsx("span",{style:{color:OS[c.tone??"default"],fontWeight:c.tone&&c.tone!=="default"?600:400},children:String(c.value)})]},c.label))}),l.errors&&l.errors.length>0&&i.jsxs("div",{className:"error-state",style:{marginTop:16,fontSize:12},children:[i.jsxs("strong",{children:[l.errors.length," issue",l.errors.length===1?"":"s",":"]}),i.jsx("ul",{style:{margin:"6px 0 0 18px"},children:l.errors.map((c,u)=>i.jsx("li",{children:c},u))})]}),l.actions&&l.actions.length>0&&i.jsx("div",{style:{display:"flex",gap:10,flexWrap:"wrap",marginTop:20,paddingTop:16,borderTop:"1px solid var(--color-border)"},children:l.actions.map(c=>c.to?i.jsx(Ke,{to:c.to,children:i.jsx("button",{type:"button",className:c.primary?"primary":"",children:c.label})},c.label):i.jsx("button",{type:"button",className:c.primary?"primary":"",children:c.label},c.label))})]})}const jy={entityId:"same-as-input",contentType:dd,newRecord:!0};function zS(l){if(!l)return"not declared on graph";const s=l.entityId==="same-as-input"?"same as input":l.entityId,c=l.newRecord===!1?"replace existing":"always new record";return`${s} · ${l.contentType} · ${c}`}function Sv({enabled:l,value:s,sourceEntity:c,graphPersistency:u,onEnabledChange:d,onChange:f}){const p=s??jy,m=p.entityId==="same-as-input"?"same-as-input":"custom";function y(g){f({...p,...g})}return i.jsxs("div",{className:"persistency-override",children:[i.jsxs("label",{className:"checkbox-row",style:{display:"flex",gap:8,alignItems:"flex-start",marginBottom:12},children:[i.jsx("input",{type:"checkbox",checked:l,onChange:g=>{const b=g.target.checked;d(b),b&&!s&&f({...jy}),b||f(void 0)}}),i.jsxs("span",{children:[i.jsx("strong",{children:"Override result persistence"}),i.jsxs("span",{className:"hint",style:{display:"block",marginTop:4},children:["Graph default: ",zS(u),l?" — work-level settings below merge over the graph at job completion.":" — enable to specify or override where graph results are written."]})]})]}),l&&i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Target object type"}),i.jsxs("select",{value:m,onChange:g=>{g.target.value==="same-as-input"?y({entityId:"same-as-input"}):y({entityId:c??""})},children:[i.jsxs("option",{value:"same-as-input",children:["Same as input",c?` (${c})`:""]}),i.jsx("option",{value:"custom",children:"Other object type…"})]})]}),m==="custom"&&i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type name"}),i.jsx("input",{value:p.entityId==="same-as-input"?"":p.entityId,onChange:g=>y({entityId:g.target.value||"same-as-input"}),placeholder:"e.g. vulnerabilities"})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Content type"}),i.jsx("input",{value:p.contentType,onChange:g=>y({contentType:g.target.value||dd}),placeholder:dd})]}),i.jsxs("div",{className:"field",children:[i.jsxs("label",{className:"checkbox-row",style:{display:"flex",gap:8,alignItems:"center"},children:[i.jsx("input",{type:"checkbox",checked:p.newRecord!==!1,onChange:g=>y({newRecord:g.target.checked})}),"Always insert a new result record"]}),i.jsx("span",{className:"hint",children:"When unchecked, results replace the existing record at the target (legacy mode)."})]})]})]})}const MS=[{id:"basic",title:"Basic info",summary:"Name & entity"},{id:"narratives",title:"Narratives",summary:"Select information"},{id:"prereqs",title:"Prerequisites",summary:"Processing rules"},{id:"graph",title:"Graph",summary:"Pipeline to run"},{id:"policy",title:"Execution policy",summary:"Interval & concurrency"},{id:"review",title:"Review",summary:"Create"},{id:"result",title:"Created",summary:"Result"}],DS=[5,15,30,60,240,1440];function wS(){const{agentQueryParam:l}=Ia(),[s,c]=j.useState(0),[u,d]=j.useState(""),[f,p]=j.useState(""),[m,y]=j.useState(""),[g,b]=j.useState(["core"]),[x,T]=j.useState([]),[R,w]=j.useState(""),[q,H]=j.useState(),[U,X]=j.useState(!1),[G,V]=j.useState(),[P,J]=j.useState({reprocessingMode:"ttl",reprocessingTtl:{value:7,unit:"days"},excludeInFlight:!0,requiredGraphs:[],crossEntityPrerequisites:[]}),[Z,I]=j.useState({rescanIntervalMinutes:15,priority:100}),[O,le]=j.useState(null),ue=ve({queryKey:["entities",l??"all"],queryFn:()=>re.listEntities(l),retry:2}),de=ue.data??[];j.useEffect(()=>{if(!m||!ue.isSuccess)return;de.map(F=>F.name).includes(m)||y("")},[ue.isSuccess,de,m]);const se=de.find(z=>z.name===m),Ne=Xt({mutationFn:z=>re.createWork({name:u,description:f,entity:m,collection:g[0]??"core",narratives:x,processing:P,graphId:R,policy:Z,activate:z,...U?{persistency:G}:{}}),onSuccess:({result:z})=>{le(z),c(6)}}),pe=!!(u.trim()&&m),Q=!!R,B=!(((se==null?void 0:se.narratives.length)??0)>0)||x.length>0;function ne(z){if(z<=s)return c(z);z>=1&&!pe||z>=2&&!B||z>=4&&!Q||c(z)}const me=(()=>{var he,ge;const z=P.reprocessingMode??"ttl";let F;if(z==="ttl"){const W=P.reprocessingTtl??{value:7,unit:"days"};F=`re-run if older than ${W.value} ${W.unit}`}else F=pv[z].split(" — ")[0];const ee=[F];return(((he=P.requiredGraphs)==null?void 0:he.length)??0)>0&&ee.push(`${P.requiredGraphs.length} prior graph(s) required`),(((ge=P.crossEntityPrerequisites)==null?void 0:ge.length)??0)>0&&ee.push(`${P.crossEntityPrerequisites.length} cross-entity prerequisite(s)`),ee.join(" · ")})(),C=g.map(z=>{const F=se==null?void 0:se.collections.find(ee=>ee.key===z);return F?uu(F):z}).join(", ");return i.jsxs("div",{children:[i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"New ongoing work"}),i.jsx("span",{className:"page-subtitle",children:"Ongoing work evaluates matching information on a schedule and queues jobs automatically."})]})}),i.jsx(zd,{steps:MS,current:s,canGoTo:z=>z<=s||z<=5&&pe,onGoTo:ne,maxWidth:980}),i.jsxs("div",{style:{maxWidth:720},children:[s===0&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"1. Basic info"}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Name *"}),i.jsx("input",{value:u,onChange:z=>d(z.target.value),placeholder:"e.g. Process selected records"})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type *"}),i.jsx(Dd,{value:m,entities:de,loading:ue.isLoading,error:ue.error,onChange:z=>{var F,ee;y(z),T([]),w(""),H(void 0),b([((ee=(F=de.find(he=>he.name===z))==null?void 0:F.collections[0])==null?void 0:ee.key)??"core"])}})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Data sources"}),i.jsx(Md,{options:(se==null?void 0:se.collections)??[],selected:g,onChange:b}),i.jsx("span",{className:"hint",children:"Select which data sources are passed to the graph as input."})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Description"}),i.jsx("textarea",{value:f,onChange:z=>p(z.target.value),placeholder:"Optional — describe what this ongoing work does",rows:3})]})]}),i.jsx(ht,{onNext:()=>ne(1),nextLabel:"Next: narratives",nextDisabled:!pe})]}),s===1&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"2. Select information by narratives"}),i.jsx(mu,{entity:m,selected:x,onChange:T}),m&&i.jsx("div",{style:{marginTop:16},children:i.jsx(xi,{entity:m,collection:g[0]??"core",narratives:x})}),i.jsx(ht,{onBack:()=>ne(0),onNext:()=>ne(2),nextLabel:"Next: prerequisites",nextDisabled:!B})]}),s===2&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"3. Processing prerequisites"}),i.jsx("p",{className:"wizard-lead",children:"Control which information is eligible. By default, items processed within the last 7 days are skipped — keeping results fresh without re-running everything on every scan."}),i.jsx(_d,{context:"recurring",entity:m,targetGraphId:R||void 0,value:P,onChange:J}),i.jsx(ht,{onBack:()=>ne(1),onNext:()=>ne(3),nextLabel:"Next: graph"})]}),s===3&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"4. Choose graph / pipeline"}),i.jsxs("p",{className:"wizard-lead",children:['Only graphs compatible with "',m,'" are shown. This graph is also used for reprocessing checks.']}),i.jsx(pu,{entity:m,value:R,onChange:(z,F)=>{w(z),H(F)}}),i.jsx("div",{className:"section-title",style:{marginTop:20},children:"Result persistence"}),i.jsx(Sv,{enabled:U,value:G,sourceEntity:m,graphPersistency:q==null?void 0:q.persistency,onEnabledChange:X,onChange:V}),i.jsx(ht,{onBack:()=>ne(2),onNext:()=>ne(4),nextLabel:"Next: execution policy",nextDisabled:!Q})]}),s===4&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"5. Execution policy"}),i.jsx("p",{className:"wizard-lead",children:"Running jobs are never interrupted — this policy controls how often new eligible information is discovered. How many jobs run in parallel is configured app-wide in Settings."}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Re-scan for new eligible information"}),i.jsx("select",{value:Z.rescanIntervalMinutes,onChange:z=>I({...Z,rescanIntervalMinutes:Number(z.target.value)}),children:DS.map(z=>i.jsx("option",{value:z,children:Es(z)},z))}),i.jsx("span",{className:"hint",children:"Every X minutes, information that has become newly eligible (new or changed data matching your narratives) is discovered and queued. Running jobs are not affected."})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:Z.priority,onChange:z=>I({...Z,priority:Number(z.target.value)})}),i.jsx("span",{className:"hint",children:"Higher priority jobs are picked up before lower priority ones when the queue is contested."})]})]}),i.jsx(ht,{onBack:()=>ne(3),onNext:()=>ne(5),nextLabel:"Next: review"})]}),s===5&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"6. Review & create"}),i.jsxs("div",{className:"review-grid",style:{marginBottom:20},children:[i.jsx(Cn,{label:"Object type",value:m}),i.jsx(Cn,{label:"Data sources",value:C||"—"}),i.jsx(Cn,{label:"Narratives (AND)",value:x.join(", ")||"none"}),i.jsx(Cn,{label:"Prerequisites",value:me}),i.jsx(Cn,{label:"Graph / pipeline",value:(q==null?void 0:q.name)??R}),U&&i.jsx(Cn,{label:"Result persistence",value:`${(G==null?void 0:G.entityId)??"same-as-input"} · ${(G==null?void 0:G.contentType)??"inferences"}`}),i.jsx(Cn,{label:"Re-scan interval",value:Es(Z.rescanIntervalMinutes)}),i.jsx(Cn,{label:"Priority",value:String(Z.priority)})]}),i.jsx("div",{className:"section-title",children:"Estimated matching information"}),i.jsx(xi,{entity:m,collection:g[0]??"core",narratives:x,processing:P,graphId:R}),Ne.isError&&i.jsx(Zt,{title:"Failed to create ongoing work",detail:Ne.error}),i.jsxs(ht,{onBack:()=>ne(4),children:[i.jsx("button",{type:"button",disabled:Ne.isPending,onClick:()=>Ne.mutate(!1),children:"Create inactive"}),i.jsx("button",{type:"button",className:"primary",disabled:Ne.isPending,onClick:()=>Ne.mutate(!0),children:Ne.isPending?"Creating…":"Create and activate"})]})]}),s===6&&O&&i.jsx(yu,{result:O})]})]})}function Cn({label:l,value:s}){return i.jsxs("div",{className:"review-row",children:[i.jsx("span",{className:"review-label",children:l}),i.jsx("span",{children:s})]})}const _S=[5,15,30,60,240,1440];function qS({work:l,onSaved:s}){var le,ue,de;const[c,u]=j.useState(l.name),[d,f]=j.useState(l.description??""),[p,m]=j.useState(l.narratives),[y,g]=j.useState(l.graphId),[b,x]=j.useState(l.processing??{reprocessingMode:"ttl",reprocessingTtl:{value:7,unit:"days"},excludeInFlight:!0,requiredGraphs:[],crossEntityPrerequisites:[]}),[T,R]=j.useState(l.policy),[w,q]=j.useState(l.persistency!==void 0),[H,U]=j.useState(l.persistency),[X,G]=j.useState(!1);j.useEffect(()=>{u(l.name),f(l.description??""),m(l.narratives),g(l.graphId),x(l.processing??{reprocessingMode:"ttl",reprocessingTtl:{value:7,unit:"days"},excludeInFlight:!0,requiredGraphs:[],crossEntityPrerequisites:[]}),R(l.policy),q(l.persistency!==void 0),U(l.persistency),G(!1)},[l]);const P=(((le=ve({queryKey:["narratives",l.entity],queryFn:()=>re.listNarratives(l.entity)}).data)==null?void 0:le.length)??0)>0,Z=(de=(ue=ve({queryKey:["graphs",l.entity],queryFn:()=>re.graphsForEntity(l.entity)}).data)==null?void 0:ue.find(se=>se.graphId===y))==null?void 0:de.persistency,I=Xt({mutationFn:()=>re.updateWork(l.id,{name:c.trim(),description:d.trim()||void 0,narratives:p,processing:b,graphId:y,policy:T,persistency:w?H:null}),onSuccess:()=>{G(!0),s()}}),O=!!(c.trim()&&y&&(!P||p.length>0));return i.jsxs("div",{className:"card",style:{maxWidth:720},children:[i.jsx("div",{className:"card-title",children:"Configuration"}),i.jsx("p",{className:"text-muted",style:{fontSize:13,marginBottom:16},children:"Edit selection, prerequisites, graph, and schedule for this ongoing work. Parallel execution is configured app-wide in Settings."}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Name"}),i.jsx("input",{value:c,onChange:se=>{u(se.target.value),G(!1)}})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Description"}),i.jsx("textarea",{value:d,onChange:se=>{f(se.target.value),G(!1)},rows:2,placeholder:"Optional"})]})]}),i.jsx("div",{className:"section-title",style:{marginTop:20},children:"Information selection"}),i.jsxs("p",{className:"text-dim",style:{fontSize:12,marginBottom:10},children:["Object type: ",i.jsx("strong",{style:{color:"var(--color-text-muted)"},children:l.entity})," · ","Data source: ",i.jsx("strong",{style:{color:"var(--color-text-muted)"},children:l.collection})]}),i.jsx(mu,{entity:l.entity,selected:p,onChange:se=>{m(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Processing prerequisites"}),i.jsx(_d,{context:"recurring",entity:l.entity,targetGraphId:y||void 0,value:b,onChange:se=>{x(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Graph / pipeline"}),i.jsx(pu,{entity:l.entity,value:y,onChange:se=>{g(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Result persistence"}),i.jsx(Sv,{enabled:w,value:H,sourceEntity:l.entity,graphPersistency:Z,onEnabledChange:se=>{q(se),G(!1)},onChange:se=>{U(se),G(!1)}}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Execution policy"}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Re-scan for new eligible information"}),i.jsx("select",{value:T.rescanIntervalMinutes,onChange:se=>{R({...T,rescanIntervalMinutes:Number(se.target.value)}),G(!1)},children:_S.map(se=>i.jsx("option",{value:se,children:Es(se)},se))})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:T.priority,onChange:se=>{R({...T,priority:Number(se.target.value)}),G(!1)}})]})]}),i.jsx("div",{className:"section-title",style:{marginTop:24},children:"Matching preview"}),i.jsx(xi,{entity:l.entity,collection:l.collection,narratives:p,processing:b,graphId:y}),I.isError&&i.jsx("div",{style:{marginTop:16},children:i.jsx(Zt,{title:"Failed to save",detail:I.error})}),i.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",marginTop:20},children:[i.jsx("button",{type:"button",className:"primary",disabled:!O||I.isPending,onClick:()=>I.mutate(),children:I.isPending?"Saving…":"Save configuration"}),X&&!I.isPending&&i.jsx("span",{className:"text-muted",style:{fontSize:13},children:"Saved"})]})]})}const US=["Overview","Evaluations","Matching Information","Runs","Settings"];function LS(){var T,R;const{id:l=""}=Ds(),s=ji(),[c,u]=j.useState("Overview"),[d,f]=j.useState(null),p=ve({queryKey:["work",l],queryFn:()=>re.work(l)}),m=p.data,y=ve({queryKey:["work-evals",l],queryFn:()=>re.workEvaluations(l),enabled:!!m}),g=ve({queryKey:["work-runs",l],queryFn:()=>re.factoryRuns({workId:l}),enabled:c==="Runs"}),b=Xt({mutationFn:()=>re.runEvaluation(l),onSuccess:({result:w})=>{f(w),s.invalidateQueries({queryKey:["work",l]}),s.invalidateQueries({queryKey:["work-evals",l]})}}),x=Xt({mutationFn:()=>re.setWorkStatus(l,m.status==="active"?"inactive":"active"),onSuccess:()=>s.invalidateQueries({queryKey:["work",l]})});return p.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):p.isError||!m?i.jsx(Zt,{title:"Ongoing work not found",detail:p.error}):i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/work",children:"Work"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),m.name]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[i.jsx("h1",{className:"page-title",children:m.name}),i.jsx(jt,{status:m.status})]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{disabled:b.isPending,onClick:()=>b.mutate(),children:"Run evaluation now"}),i.jsx("button",{disabled:x.isPending,onClick:()=>x.mutate(),children:m.status==="active"?"Deactivate":"Activate"})]})]}),d&&i.jsx("div",{style:{marginBottom:16},children:i.jsx(yu,{result:d})}),i.jsx("div",{className:"tabs",children:US.map(w=>i.jsx("button",{className:`tab${c===w?" active":""}`,onClick:()=>u(w),children:w},w))}),c==="Overview"&&i.jsxs("div",{className:"detail-grid",children:[i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Configuration"}),i.jsx(da,{k:"Entity",v:`${m.entity} · ${m.collection}`}),i.jsx(da,{k:"Narratives",v:m.narratives.join(", ")||"none"}),i.jsx(da,{k:"Processing rule",v:(T=m.processing)!=null&&T.overrideDuplicatePrevention?"reprocess (override)":"skip already processed / queued / running"}),i.jsx(da,{k:"Graph",v:m.graphName??m.graphId}),i.jsx(da,{k:"Description",v:m.description??"—"})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Schedule & results"}),i.jsx(da,{k:"Re-scan interval",v:Es(m.policy.rescanIntervalMinutes)}),i.jsx(da,{k:"Last scanned",v:`${Ln(m.lastEvaluatedAt)} (${ia(m.lastEvaluatedAt)})`}),i.jsx(da,{k:"Next scan",v:m.status==="active"?Ln(m.nextEvaluationAt):"paused (inactive)"}),i.jsx(da,{k:"Jobs created",v:String(m.jobsCreated)}),i.jsx(da,{k:"Estimated matching",v:String(m.estimatedMatching??"—")}),i.jsx(da,{k:"Priority",v:String(m.policy.priority)})]})]}),c==="Evaluations"&&i.jsx(BS,{id:l,evalsQuery:y}),c==="Matching Information"&&i.jsx(xi,{entity:m.entity,collection:m.collection,narratives:m.narratives,processing:m.processing,graphId:m.graphId}),c==="Runs"&&i.jsx(HS,{runs:((R=g.data)==null?void 0:R.runs)??[],loading:g.isLoading}),c==="Settings"&&i.jsx(qS,{work:m,onSaved:()=>s.invalidateQueries({queryKey:["work",l]})})]})}function BS({evalsQuery:l}){const s=l.data??[];return l.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):s.length===0?i.jsx(Dt,{title:"No evaluations yet",message:"When this work is active (or you run an evaluation now), each cycle is recorded here with what it matched, created, and excluded."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:s.map(c=>i.jsxs("div",{className:"card",children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[i.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[i.jsx(jt,{status:c.status}),i.jsx("span",{className:"text-muted",style:{fontSize:12},children:ia(c.at)})]}),i.jsxs("span",{className:"text-dim",style:{fontSize:12},children:[c.durationMs," ms"]})]}),c.error&&i.jsx("div",{className:"error-state",style:{fontSize:12,marginBottom:8},children:c.error}),c.zeroReason&&i.jsxs("div",{className:"text-muted",style:{fontSize:12,marginBottom:8},children:["Zero jobs: ",c.zeroReason]}),i.jsxs("div",{style:{display:"flex",gap:24,fontSize:13},children:[i.jsxs("span",{children:[i.jsx("strong",{children:c.matched})," ",i.jsx("span",{className:"text-muted",children:"matched"})]}),i.jsxs("span",{children:[i.jsx("strong",{style:{color:"var(--status-done)"},children:c.created})," ",i.jsx("span",{className:"text-muted",children:"created"})]}),i.jsxs("span",{children:[i.jsx("strong",{style:{color:"var(--status-blocked)"},children:c.excluded})," ",i.jsx("span",{className:"text-muted",children:"excluded"})]})]}),c.exclusionReasons.length>0&&i.jsx("div",{style:{marginTop:10},children:i.jsx(wd,{included:c.created,excluded:c.exclusionReasons,includedLabel:"Jobs created"})})]},c.id))})}function HS({runs:l,loading:s}){return s?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):l.length===0?i.jsx(Dt,{title:"No runs yet",message:"Jobs created by this ongoing work will appear here."}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Item"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:l.map(c=>i.jsxs("tr",{onClick:()=>{window.location.href=`/journal/${c.id}`},children:[i.jsx("td",{children:i.jsx(jt,{status:c.status})}),i.jsx("td",{className:"mono",style:{fontSize:12},children:c.recordLabel??c.recordId}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:c.graphName??c.graphId}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:Ln(c.updatedAt)})]},c.id))})]})})}function da({k:l,v:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",style:{fontFamily:"inherit"},children:s})]})}function QS(){const l=Bn();return i.jsxs("div",{children:[i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"On-Demand"}),i.jsx("span",{className:"page-subtitle",children:"Run processing now — pick a single item or a batch selected by narratives."})]})}),i.jsxs("div",{className:"mode-cards",children:[i.jsxs("button",{type:"button",className:"mode-card",onClick:()=>l("/on-demand/single"),children:[i.jsx("div",{className:"mode-card-icon",children:"▶"}),i.jsxs("div",{children:[i.jsx("div",{className:"mode-card-title",children:"Single item"}),i.jsx("div",{className:"mode-card-desc",children:"Run a graph on one item you select manually or at random. Optionally include context."})]}),i.jsx("div",{className:"mode-card-arrow",children:"→"})]}),i.jsxs("button",{type:"button",className:"mode-card",onClick:()=>l("/on-demand/batch"),children:[i.jsx("div",{className:"mode-card-icon",children:"⊞"}),i.jsxs("div",{children:[i.jsx("div",{className:"mode-card-title",children:"Batch"}),i.jsx("div",{className:"mode-card-desc",children:"Run a graph on multiple items that match selected narratives. One job per matching item."})]}),i.jsx("div",{className:"mode-card-arrow",children:"→"})]})]})]})}const GS=new Set(["core","snapshots"]);function md(l){return GS.has(l)}function Nv({node:l,prefix:s,selected:c,onToggle:u}){var b,x,T;const d=s?`${s}.${l.path}`:l.path,f=((b=l.children)==null?void 0:b.map(R=>`${d}.${R.path}`))??[],p=f.length===0||f.every(R=>c.has(R)),m=!((x=l.children)!=null&&x.length),y=m?c.has(d):p;function g(R){if(m)u(d,R.target.checked);else{const w=Ev(l,s);for(const q of w)u(q,R.target.checked)}}return i.jsxs("div",{style:{paddingLeft:s?16:0},children:[i.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:13,paddingBottom:2},children:[i.jsx("input",{type:"checkbox",checked:y,onChange:g}),i.jsx("span",{className:"mono",style:{color:"var(--color-text)"},children:l.path}),l.inferredType&&i.jsx("span",{style:{color:"var(--color-text-dim)",fontSize:11},children:l.inferredType})]}),(T=l.children)==null?void 0:T.map(R=>i.jsx(Nv,{node:R,prefix:d,selected:c,onToggle:u},R.path))]})}function Ev(l,s){var u;const c=s?`${s}.${l.path}`:l.path;return(u=l.children)!=null&&u.length?l.children.flatMap(d=>Ev(d,c)):[c]}function kS({order:l,onChange:s}){function c(u,d){const f=[...l],p=u+d;p<0||p>=f.length||([f[u],f[p]]=[f[p],f[u]],s(f))}return i.jsxs("div",{style:{marginBottom:12},children:[i.jsx("label",{style:{display:"block",marginBottom:4,fontSize:12,color:"var(--color-text-dim)"},children:"Merge priority (top wins on key collision)"}),l.map((u,d)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[i.jsxs("span",{style:{fontSize:11,color:"var(--color-text-dim)",width:16,textAlign:"right"},children:[d+1,"."]}),i.jsx("span",{className:"mono",style:{fontSize:13,flex:1},children:u}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:d===0,onClick:()=>c(d,-1),children:"↑"}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",disabled:d===l.length-1,onClick:()=>c(d,1),children:"↓"})]},u))]})}function YS({objectType:l,contentTypeKey:s,target:c,selectedPaths:u,onPathsChange:d}){var q,H;const f=ve({queryKey:["assembler-props",l,s,c],queryFn:()=>re.assemblerProperties({objectType:l,contentType:s,target:c}),staleTime:6e4}),p=((q=f.data)==null?void 0:q.flatPaths)??[],m=((H=f.data)==null?void 0:H.properties)??[],y=new Set(u??p);function g(U,X){const G=new Set(y);X?G.add(U):G.delete(U);const V=p.filter(P=>G.has(P));d(V.length===p.length?void 0:V)}function b(){d(void 0)}function x(){d([])}const T=u===void 0?p.length:u.length,R=md(s)?"1:1":"1:n",w={fontSize:10,padding:"1px 5px",borderRadius:3,background:md(s)?"var(--color-accent-dim, #1a3a5c)":"var(--color-bg-3, #2a2a2a)",color:"var(--color-text-dim)",marginLeft:6};return i.jsxs("div",{style:{border:"1px solid var(--color-border)",borderRadius:6,marginBottom:12,overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"8px 12px",background:"var(--color-bg-2)",display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{className:"mono",style:{fontWeight:600,fontSize:13},children:s}),i.jsx("span",{style:w,children:R}),i.jsx("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--color-text-dim)"},children:f.isLoading?"Loading…":`${T} / ${p.length} properties`}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",onClick:b,children:"All"}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",onClick:x,children:"None"})]}),!f.isLoading&&m.length===0&&i.jsx("div",{style:{padding:"10px 12px",fontSize:12,color:"var(--color-text-dim)"},children:"No properties sampled (collection may be empty)."}),m.length>0&&i.jsx("div",{style:{padding:"10px 12px",maxHeight:240,overflowY:"auto"},children:m.map(U=>i.jsx(Nv,{node:U,prefix:"",selected:y,onToggle:g},U.path))})]})}function KS({objectType:l,target:s,collections:c,value:u,onChange:d}){const f=c.filter(md),p=c.map(b=>{const x=u==null?void 0:u.contentTypes.find(T=>T.key===b);return{key:b,selectedProperties:x==null?void 0:x.selectedProperties}}),m=(()=>{const b=(u==null?void 0:u.priority)??[],x=f,T=x.filter(R=>!b.includes(R));return[...b.filter(R=>x.includes(R)),...T]})();function y(b,x){const T=p.map(R=>R.key===b?{key:b,selectedProperties:x}:R);d({objectType:l,target:s,contentTypes:T,priority:m})}function g(b){d({objectType:l,target:s,contentTypes:p,priority:b})}return i.jsxs("div",{children:[f.length>1&&i.jsx(kS,{order:m,onChange:g}),c.map(b=>{var x;return i.jsx(YS,{objectType:l,contentTypeKey:b,target:s,selectedPaths:(x=p.find(T=>T.key===b))==null?void 0:x.selectedProperties,onPathsChange:T=>y(b,T)},b)})]})}const XS=[{id:"record",title:"Choose item",summary:"What to process"},{id:"related",title:"Context",summary:"Optional linked data"},{id:"graph",title:"Choose graph",summary:"Pipeline to run"},{id:"properties",title:"Properties",summary:"Data to include"},{id:"review",title:"Review & queue",summary:"Confirm"},{id:"result",title:"Queued",summary:"Result"}];function ZS(){var ge;const{agentQueryParam:l}=Ia(),[s,c]=j.useState(0),[u,d]=j.useState(""),[f,p]=j.useState(["core"]),[m,y]=j.useState([]),[g,b]=j.useState(!1),[x,T]=j.useState(""),[R,w]=j.useState(""),[q,H]=j.useState(),[U,X]=j.useState(100),[G,V]=j.useState(),[P,J]=j.useState(null),Z=ve({queryKey:["entities",l??"all"],queryFn:()=>re.listEntities(l),retry:2}),I=Z.data??[];j.useEffect(()=>{if(!u||!Z.isSuccess)return;I.map(Ee=>Ee.name).includes(u)||d("")},[Z.isSuccess,I,u]);const O=I.find(W=>W.name===u),le=(O==null?void 0:O.target)==="event"?"event":"entity",ue=f[0]??"core",de=ve({queryKey:["core-records",u,f,m],queryFn:()=>re.coreRecords({entity:u,collection:ue,narratives:m,pageSize:100}),enabled:!!u}),se=((ge=de.data)==null?void 0:ge.records)??[],Ne=se.find(W=>W.id===x);function pe(W){p(W),T(""),V(void 0)}function Q(W){y(W),T("")}function $(){se.length&&T(se[Math.floor(Math.random()*se.length)].id)}function B(){if(G)return G;const W=f.filter(Ee=>Ee==="core"||Ee==="snapshots");return{objectType:u,target:le,contentTypes:f.map(Ee=>({key:Ee})),priority:W}}const ne=Xt({mutationFn:()=>re.queueSingle({entity:u,collections:f,recordId:x,graphId:R,priority:U,assemblySelection:B()}),onSuccess:({result:W})=>{J(W),c(5)}}),me=!!(u&&x),C=!!R;function z(W){if(W<=s)return c(W);W>=1&&!me||W>=3&&!C||c(W)}const F=(O==null?void 0:O.collections)??[],ee=f.map(W=>{const Ee=F.find(_e=>_e.key===W);return Ee?uu(Ee):W}).join(", "),he=G?(G.contentTypes.reduce((W,Ee)=>{var _e;return W+(((_e=Ee.selectedProperties)==null?void 0:_e.length)??999)},0),`${G.contentTypes.length} content type${G.contentTypes.length!==1?"s":""} selected`):"All properties (default)";return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx("a",{href:"/on-demand",children:"On-Demand"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),"Single item"]}),i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"On-Demand: single item"}),i.jsx("span",{className:"page-subtitle",children:"Process one item through a graph."})]})}),i.jsx(zd,{steps:XS,current:s,canGoTo:W=>W<=s,onGoTo:z,maxWidth:840}),i.jsxs("div",{style:{maxWidth:720},children:[s===0&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"1. Choose item"}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type"}),i.jsx(Dd,{value:u,entities:I,loading:Z.isLoading,error:Z.error,onChange:W=>{var Wa;const Ee=I.find(yl=>yl.name===W),_e=((Wa=Ee==null?void 0:Ee.collections[0])==null?void 0:Wa.key)??"core";d(W),p([_e]),y([]),b(!1),T(""),w(""),H(void 0),V(void 0)}})]}),u&&i.jsxs("div",{className:"field",style:{marginBottom:12},children:[i.jsx("label",{children:"Data sources"}),i.jsx(Md,{options:F,selected:f,onChange:pe}),i.jsx("span",{className:"hint",children:"Select which content types are merged and sent to the graph."})]}),u&&i.jsxs("div",{className:"field",style:{marginBottom:12},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[i.jsxs("label",{style:{marginBottom:0},children:["Narratives",i.jsx("span",{style:{fontWeight:400,color:"var(--color-text-dim)",marginLeft:6},children:"— optional filter"})]}),i.jsx("button",{type:"button",className:"btn-ghost btn-xs",onClick:()=>b(W=>!W),children:g?"Hide":m.length>0?`${m.length} active ▾`:"Filter ▾"})]}),m.length>0&&!g&&i.jsx("div",{className:"chip-row",style:{marginBottom:6},children:m.map(W=>{const Ee=O==null?void 0:O.narratives.find(_e=>_e.key===W);return i.jsx("span",{className:"chip narrative",children:(Ee==null?void 0:Ee.label)??W},W)})}),g&&i.jsx("div",{style:{marginTop:8},children:i.jsx(mu,{entity:u,selected:m,onChange:Q,requireSelection:!1})})]}),u&&i.jsxs("div",{className:"field",style:{marginBottom:12},children:[i.jsx("label",{children:"Item *"}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsxs("select",{value:x,onChange:W=>T(W.target.value),style:{flex:1},children:[i.jsx("option",{value:"",children:de.isLoading?"Loading…":se.length?"Select an item…":"No information"}),se.map(W=>i.jsxs("option",{value:W.id,children:[W.label," (",W.id,")"]},W.id))]}),i.jsx("button",{type:"button",onClick:$,disabled:!se.length,children:"Random"})]}),i.jsxs("span",{className:"hint",children:[se.length," items loaded",m.length>0?` (filtered by ${m.length} narrative${m.length>1?"s":""})`:""," · ",i.jsx("a",{href:`/information?entity=${u}`,children:"Browse all information"})]})]}),i.jsx(ht,{onNext:()=>z(1),nextLabel:"Next: context",nextDisabled:!me})]}),s===1&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"2. Context (optional)"}),Ne&&i.jsxs("div",{className:"memorix-panel",children:[i.jsx("div",{className:"memorix-panel-title",children:"Starting item"}),i.jsxs("span",{className:"mono",children:[u," / ",ee," / ",Ne.label]})]}),i.jsx("div",{className:"empty-state",style:{padding:24},children:"Context is not applicable — there are no relations linked to related entities. You can skip this step and continue."}),i.jsx(ht,{onBack:()=>z(0),onNext:()=>z(2),nextLabel:"Skip — no context"})]}),s===2&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"3. Choose graph"}),i.jsx(pu,{entity:u,value:R,onChange:(W,Ee)=>{w(W),H(Ee)}}),i.jsx(ht,{onBack:()=>z(1),onNext:()=>z(3),nextLabel:"Next: properties",nextDisabled:!C})]}),s===3&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"4. Properties to include"}),i.jsxs("div",{style:{marginBottom:12,color:"var(--color-text-dim)",fontSize:13},children:["Choose which properties are sent to the graph as input. Only domain data is sent — system fields are always excluded.",i.jsxs("ul",{style:{margin:"8px 0 0 16px",lineHeight:1.8,fontSize:12},children:[i.jsxs("li",{children:[i.jsx("strong",{children:"1:1 types"})," (core, snapshots): one record per item, merged at the root. Higher priority wins on duplicate keys."]}),i.jsxs("li",{children:[i.jsx("strong",{children:"1:n types"}),": all matching records, placed as an array under the content-type name."]})]})]}),u&&f.length>0&&i.jsx(KS,{objectType:u,target:le,collections:f,value:G,onChange:V}),i.jsx(ht,{onBack:()=>z(2),onNext:()=>z(4),nextLabel:"Next: review"})]}),s===4&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"5. Review & queue"}),i.jsxs("div",{className:"review-grid",style:{marginBottom:16},children:[i.jsx(ti,{label:"Object type",value:u}),i.jsx(ti,{label:"Data sources",value:ee}),i.jsx(ti,{label:"Properties",value:he}),i.jsx(ti,{label:"Item",value:(Ne==null?void 0:Ne.label)??x}),i.jsx(ti,{label:"Graph",value:(q==null?void 0:q.name)??R}),i.jsx(ti,{label:"Expected update",value:`processing.graphs.${R}.processedAt on success`})]}),i.jsx("div",{className:"form-grid",children:i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:U,onChange:W=>X(Number(W.target.value))}),i.jsx("span",{className:"hint",children:"Higher priority is picked up first when the queue is contested."})]})}),ne.isError&&i.jsx(Zt,{title:"Failed to queue job",detail:ne.error}),i.jsx(ht,{onBack:()=>z(3),children:i.jsx("button",{type:"button",className:"primary",disabled:ne.isPending,onClick:()=>ne.mutate(),children:ne.isPending?"Queueing…":"Queue one job"})})]}),s===5&&P&&i.jsx(yu,{result:P})]})]})}function ti({label:l,value:s}){return i.jsxs("div",{className:"review-row",children:[i.jsx("span",{className:"review-label",children:l}),i.jsx("span",{className:"mono",style:{fontSize:12},children:s})]})}const VS=[{id:"entity",title:"Entity",summary:"Choose entity"},{id:"narratives",title:"Narratives",summary:"Select information"},{id:"processing",title:"Processing",summary:"Filters"},{id:"graph",title:"Graph",summary:"Pipeline"},{id:"review",title:"Review",summary:"Matching information"},{id:"queue",title:"Queue policy",summary:"Concurrency"},{id:"result",title:"Queued",summary:"Result"}];function $S(){var Q;const{agentQueryParam:l}=Ia(),[s]=hu(),[c,u]=j.useState(0),[d,f]=j.useState(s.get("entity")??""),[p,m]=j.useState(["core"]),[y,g]=j.useState([]),[b,x]=j.useState(""),[T,R]=j.useState(),[w,q]=j.useState({reprocessingMode:"skip",excludeInFlight:!0}),[H,U]=j.useState(""),[X,G]=j.useState({priority:100}),[V,P]=j.useState(null),J=ve({queryKey:["entities",l??"all"],queryFn:()=>re.listEntities(l),retry:2}),Z=J.data??[];j.useEffect(()=>{if(!d||!J.isSuccess)return;Z.map(B=>B.name).includes(d)||f("")},[J.isSuccess,Z,d]);const I=Z.find($=>$.name===d),le=((Q=ve({queryKey:["matching",d,p,y,w,b,"count"],queryFn:()=>re.previewMatching({entity:d,collection:p[0]??"core",narratives:y,processing:w,graphId:b}),enabled:!!(d&&b)}).data)==null?void 0:Q.matched)??0,ue=Xt({mutationFn:()=>re.queueBatch({name:H||`${d} batch`,entity:d,collections:p,narratives:y,processing:w,graphId:b,policy:X}),onSuccess:({result:$})=>{P($),u(6)}}),de=!!b,Ne=!(((I==null?void 0:I.narratives.length)??0)>0)||y.length>0;function pe($){if($<=c)return u($);$>=1&&!d||$>=2&&!Ne||$>=4&&!de||u($)}return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx("a",{href:"/on-demand",children:"On-Demand"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),"Batch"]}),i.jsx("div",{className:"page-header",children:i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"On-Demand: batch"}),i.jsx("span",{className:"page-subtitle",children:"Run one graph on many items that match your selected narratives."})]})}),i.jsx(zd,{steps:VS,current:c,canGoTo:$=>$<=c,onGoTo:pe,maxWidth:980}),i.jsxs("div",{style:{maxWidth:720},children:[c===0&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"1. Choose entity"}),i.jsx("div",{className:"form-grid",children:i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Object type"}),i.jsx(Dd,{value:d,entities:Z,loading:J.isLoading,error:J.error,onChange:$=>{var ne;const B=Z.find(me=>me.name===$);f($),m([((ne=B==null?void 0:B.collections[0])==null?void 0:ne.key)??"core"]),g([]),x(""),R(void 0)}})]})}),I&&i.jsxs("div",{className:"field",style:{marginTop:12},children:[i.jsx("label",{children:"Data sources"}),i.jsx(Md,{options:I.collections,selected:p,onChange:m}),i.jsx("span",{className:"hint",children:"Select which data sources are passed to the graph as input."})]}),I&&i.jsxs("p",{className:"text-dim",style:{fontSize:12},children:[I.coreCount," core information · ",I.narratives.length," narratives · ",I.graphs.length," compatible graphs"]}),i.jsx(ht,{onNext:()=>pe(1),nextLabel:"Next: narratives",nextDisabled:!d})]}),c===1&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"2. Select narratives"}),i.jsx(mu,{entity:d,selected:y,onChange:g}),i.jsx("div",{style:{marginTop:16},children:i.jsx(xi,{entity:d,collection:p[0]??"core",narratives:y})}),i.jsx(ht,{onBack:()=>pe(0),onNext:()=>pe(2),nextLabel:"Next: processing",nextDisabled:!Ne})]}),c===2&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"3. Processing prerequisites"}),i.jsx("p",{className:"wizard-lead",children:"Control which information is eligible. Skip already-processed items by default, and optionally require other graphs to have run first."}),i.jsx(_d,{context:"batch",entity:d,targetGraphId:b||void 0,value:w,onChange:q}),i.jsx(ht,{onBack:()=>pe(1),onNext:()=>pe(3),nextLabel:"Next: graph"})]}),c===3&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"4. Choose graph / pipeline"}),i.jsx(pu,{entity:d,value:b,onChange:($,B)=>{x($),R(B)}}),i.jsx(ht,{onBack:()=>pe(2),onNext:()=>pe(4),nextLabel:"Next: review",nextDisabled:!de})]}),c===4&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"5. Review matching information"}),i.jsx(xi,{entity:d,collection:p[0]??"core",narratives:y,processing:w,graphId:b}),i.jsx(ht,{onBack:()=>pe(3),onNext:()=>pe(5),nextLabel:"Next: queue policy"})]}),c===5&&i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"6. Queue policy"}),i.jsxs("div",{className:"form-grid",children:[i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Batch name"}),i.jsx("input",{value:H,onChange:$=>U($.target.value),placeholder:`${d} batch`})]}),i.jsxs("div",{className:"field",children:[i.jsx("label",{children:"Priority"}),i.jsx("input",{type:"number",value:X.priority,onChange:$=>G({...X,priority:Number($.target.value)})}),i.jsx("span",{className:"hint",children:"Higher priority is picked up first when the queue is contested. Parallel execution is configured app-wide in Settings."})]})]}),i.jsx("div",{className:"memorix-panel",children:i.jsxs("div",{style:{fontSize:13},children:["This will create ",i.jsx("strong",{children:le.toLocaleString()})," jobs — one per matching item. The app queue settings control how many run in parallel."]})}),ue.isError&&i.jsx(Zt,{title:"Failed to queue batch",detail:ue.error}),i.jsx(ht,{onBack:()=>pe(4),children:i.jsx("button",{type:"button",className:"primary",disabled:ue.isPending,onClick:()=>ue.mutate(),children:ue.isPending?"Queueing…":"Queue batch"})})]}),c===6&&V&&i.jsx(yu,{result:V})]})]})}function JS(){var p,m;const{id:l=""}=Ds(),s=ve({queryKey:["batch",l],queryFn:()=>re.batch(l)}),c=ve({queryKey:["batch-runs",l],queryFn:()=>re.factoryRuns({batchId:l})}),u=s.data;if(s.isLoading)return i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]});if(s.isError||!u)return i.jsx(Zt,{title:"Batch not found",detail:s.error});const d=((p=c.data)==null?void 0:p.runs)??[],f=u.counts;return i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:"/on-demand/batch",children:"Batch"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),u.name]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[i.jsx("h1",{className:"page-title",children:u.name}),i.jsx(jt,{status:u.status})]}),i.jsxs("span",{className:"text-dim",style:{fontSize:12},children:["created ",Ln(u.createdAt)]})]}),i.jsx("div",{className:"status-cards",style:{gridTemplateColumns:"repeat(6, 1fr)"},children:[["Total",f.total],["Pending",f.pending],["Running",f.running],["Done",f.done],["Failed",f.failed],["Cancelled",f.cancelled]].map(([y,g])=>i.jsxs("div",{className:"status-card",style:{cursor:"default"},children:[i.jsx("div",{className:"status-card-label",children:y}),i.jsx("div",{className:"status-card-count",children:g})]},y))}),i.jsxs("div",{className:"detail-grid",children:[i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Selection summary"}),i.jsx(ai,{k:"Entity",v:`${u.entity} · ${u.collection}`}),i.jsx(ai,{k:"Narratives",v:u.narratives.join(", ")||"none"}),i.jsx(ai,{k:"Reprocessing",v:(m=u.processing)!=null&&m.reprocessingMode&&u.processing.reprocessingMode!=="skip"?u.processing.reprocessingMode:"skip (default)"}),i.jsx(ai,{k:"Graph",v:u.graphName??u.graphId}),i.jsx(ai,{k:"Priority",v:String(u.policy.priority)}),i.jsx(ai,{k:"Created",v:ia(u.createdAt)})]}),i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"card-title",children:"Excluded information"}),u.excluded.length?i.jsx(wd,{included:f.total,excluded:u.excluded,includedLabel:"Queued"}):i.jsx("p",{className:"text-muted",style:{fontSize:13},children:"No information was excluded."})]})]}),i.jsxs("div",{className:"section",children:[i.jsxs("div",{className:"section-title",style:{display:"flex",justifyContent:"space-between"},children:[i.jsx("span",{children:"Runs"}),f.failed>0&&i.jsxs("button",{type:"button",disabled:!0,title:"Backend TODO",children:["Retry failed (",f.failed,")"]})]}),c.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}),!c.isLoading&&d.length===0&&i.jsx(Dt,{title:"No runs for this batch yet"}),d.length>0&&i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Item"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Attempts"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:d.map(y=>i.jsxs("tr",{onClick:()=>{window.location.href=`/journal/${y.id}`},children:[i.jsx("td",{children:i.jsx(jt,{status:y.status})}),i.jsx("td",{className:"mono",style:{fontSize:12},children:y.recordLabel??y.recordId}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:y.graphName??y.graphId}),i.jsxs("td",{className:"mono",children:[y.attempts,"/",y.maxAttempts]}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:Ln(y.updatedAt)})]},y.id))})]})})]})]})}function ai({k:l,v:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",style:{fontFamily:"inherit"},children:s})]})}function FS(l){const s=Object.values(l.processing.graphs);if(s.length===0)return"not processed";const c=s.filter(d=>d.lastStatus==="succeeded").length,u=s.filter(d=>d.lastStatus==="failed").length;return`${c} done${u?`, ${u} failed`:""}`}function IS(){var J,Z,I;const l=Bn(),{agentQueryParam:s,agentId:c}=Ia(),[u,d]=hu(),f=u.get("entity")??"",p=u.get("collection")??"core",m=u.get("graphId")??"",y=u.get("processing")??"",g=(u.get("narratives")??"").split(",").filter(Boolean),[b,x]=j.useState(1);function T(O){const le=new URLSearchParams(u);for(const[ue,de]of Object.entries(O))de?le.set(ue,de):le.delete(ue);d(le),x(1)}const w=ve({queryKey:["entities",s??"all"],queryFn:()=>re.listEntities(s)}).data??[],q=w.find(O=>O.name===f),H=ve({queryKey:["narratives",f],queryFn:()=>re.listNarratives(f),enabled:!!f}),U=ve({queryKey:["graphs",f],queryFn:()=>re.graphsForEntity(f),enabled:!!f}),X=ve({queryKey:["core-records",f,p,g,m,y,b],queryFn:()=>re.coreRecords({entity:f,collection:p,narratives:g.length?g:void 0,processingGraphId:m||void 0,processingCondition:y||void 0,page:b,pageSize:25}),enabled:!!f});function G(O){const le=g.includes(O)?g.filter(ue=>ue!==O):[...g,O];T({narratives:le.join(",")||void 0})}const V=((J=X.data)==null?void 0:J.records)??[],P=j.useMemo(()=>{const O=V[0];if(!O)return[];const le=new Set(["recordId","entityId","eventId","knowledgeId","displayName","data","_memorix"]);return Object.keys(O.fields).filter(ue=>!le.has(ue)&&!ue.startsWith("_")).filter(ue=>{const de=O.fields[ue];return de===null||["string","number","boolean"].includes(typeof de)}).slice(0,3)},[V]);return i.jsxs("div",{children:[i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:"Information"}),i.jsxs("span",{className:"page-subtitle",children:[c?i.jsxs(i.Fragment,{children:["Object types in agent scope ",i.jsx("span",{className:"mono",children:c}),". · "]}):null,"Browse processed items, their narratives, and processing state."]})]}),f&&i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx(Ke,{to:`/on-demand/single?entity=${f}`,children:i.jsx("button",{children:"Run on-demand"})}),i.jsx(Ke,{to:`/on-demand/batch?entity=${f}`,children:i.jsx("button",{className:"primary",children:"Create batch from filter"})})]})]}),i.jsxs("div",{className:"filters",children:[i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Entity"}),i.jsxs("select",{value:f,onChange:O=>T({entity:O.target.value||void 0,narratives:void 0,graphId:void 0,processing:void 0}),children:[i.jsx("option",{value:"",children:"— select —"}),w.map(O=>i.jsx("option",{value:O.name,children:O.label},O.name))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Collection type"}),i.jsx("select",{value:p,onChange:O=>T({collection:O.target.value}),disabled:!q,children:((q==null?void 0:q.collections)??[{key:"core"}]).map(O=>i.jsx("option",{value:O.key,children:O.key},O.key))})]}),i.jsx("div",{className:"filter-divider"}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"Processed by"}),i.jsxs("select",{value:m,onChange:O=>T({graphId:O.target.value||void 0,processing:void 0}),disabled:!f,children:[i.jsx("option",{value:"",children:"any graph"}),(U.data??[]).map(O=>i.jsx("option",{value:O.graphId,children:O.name},O.graphId))]})]}),i.jsxs("div",{className:"filter-group",children:[i.jsx("label",{children:"with status"}),i.jsxs("select",{value:y,onChange:O=>T({processing:O.target.value||void 0}),disabled:!m,title:m?void 0:"Select a graph first",children:[i.jsx("option",{value:"",children:"any status"}),i.jsx("option",{value:"succeeded",children:"succeeded"}),i.jsx("option",{value:"failed",children:"failed"}),i.jsx("option",{value:"running",children:"running"}),i.jsx("option",{value:"queued",children:"queued"}),i.jsx("option",{value:"not-processed",children:"not processed"}),i.jsx("option",{value:"unknown",children:"unknown"})]})]})]}),f&&(((Z=H.data)==null?void 0:Z.length)??0)>0&&i.jsx("div",{className:"chip-row",style:{marginBottom:16},children:(H.data??[]).map(O=>i.jsx("span",{className:`chip selectable${g.includes(O.key)?" selected":""}`,onClick:()=>G(O.key),title:O.description,children:O.label},O.key))}),!f&&i.jsx(Dt,{title:"Select an entity",message:"Choose an entity to browse its items, narratives, and processing state.",icon:"◇"}),f&&X.isLoading&&i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}),X.isError&&i.jsx(Zt,{title:"Failed to load information",detail:X.error,onRetry:()=>X.refetch()}),f&&!X.isLoading&&V.length===0&&i.jsx(Dt,{title:"No matching items",message:"No items match the current filters. Try removing a narrative or changing the processing filter."}),V.length>0&&i.jsxs("div",{className:"table-wrap",children:[i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"ID"}),i.jsx("th",{children:"Label"}),P.map(O=>i.jsx("th",{children:O},O)),i.jsx("th",{children:"Narratives"}),i.jsx("th",{children:"Processing"}),i.jsx("th",{children:"Updated"}),i.jsx("th",{})]})}),i.jsx("tbody",{children:V.map(O=>i.jsxs("tr",{onClick:()=>l(`/information/${encodeURIComponent(O.id)}?entity=${f}&collection=${p}`),children:[i.jsx("td",{className:"mono",style:{fontSize:12},children:O.id}),i.jsx("td",{children:O.label}),P.map(le=>i.jsx("td",{className:"text-muted",style:{fontSize:12},children:String(O.fields[le]??"—")},le)),i.jsx("td",{children:i.jsx("span",{className:"chip-row",children:Object.keys(O.narratives).map(le=>i.jsx("span",{className:"chip narrative",children:le},le))})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:FS(O)}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:new Date(O.updatedAt).toLocaleString()}),i.jsx("td",{onClick:le=>le.stopPropagation(),children:i.jsx(Ke,{to:`/on-demand/single?entity=${f}`,style:{fontSize:12},children:"Run"})})]},O.id))})]}),i.jsx(yv,{page:b,pageSize:25,total:((I=X.data)==null?void 0:I.total)??0,onPage:x})]})]})}const WS=["Core","Narratives","Processing","Snapshots","Journal"];function PS(){var g,b;const{recordId:l}=Ds(),s=decodeURIComponent(l??""),[c]=hu(),u=c.get("entity")??"",[d,f]=j.useState("Core"),p=ve({queryKey:["core-record",u,s],queryFn:()=>re.coreRecord(u,s),enabled:!!(u&&s)}),m=ve({queryKey:["record-runs",u,s],queryFn:()=>re.factoryRuns({entity:u,recordId:s}),enabled:d==="Journal"}),y=p.data;return p.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):p.isError||!y?i.jsx(Zt,{title:"Failed to load",detail:p.error}):i.jsxs("div",{children:[i.jsxs("div",{className:"breadcrumb",children:[i.jsx(Ke,{to:`/information?entity=${u}`,children:"Information"}),i.jsx("span",{className:"breadcrumb-sep",children:"/"}),y.label]}),i.jsxs("div",{className:"page-header",style:{justifyContent:"space-between"},children:[i.jsxs("div",{children:[i.jsx("h1",{className:"page-title",children:y.label}),i.jsxs("span",{className:"page-subtitle mono",children:[u," · ",y.id]})]}),i.jsx(Ke,{to:`/on-demand/single?entity=${u}`,children:i.jsx("button",{className:"primary",children:"Run on-demand"})})]}),i.jsx("div",{className:"tabs",children:WS.map(x=>i.jsx("button",{className:`tab${d===x?" active":""}`,onClick:()=>f(x),children:x},x))}),d==="Core"&&i.jsxs("div",{className:"card",style:{maxWidth:560},children:[i.jsx("div",{className:"card-title",children:"Core fields"}),i.jsx(ni,{k:"Item id",v:y.id}),i.jsx(ni,{k:"Entity",v:y.entity}),i.jsx(ni,{k:"Label",v:y.label}),Object.entries(y.fields).map(([x,T])=>i.jsx(ni,{k:x,v:String(T)},x)),i.jsx(ni,{k:"Created",v:ia(y.createdAt)}),i.jsx(ni,{k:"Updated",v:ia(y.updatedAt)})]}),d==="Narratives"&&(Object.keys(y.narratives).length===0?i.jsx(Dt,{title:"No narratives on this item",message:"This item has no narratives assigned."}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Narrative"}),i.jsx("th",{children:"Added"}),i.jsx("th",{children:"Detected by"})]})}),i.jsx("tbody",{children:Object.entries(y.narratives).map(([x,T])=>i.jsxs("tr",{style:{cursor:"default"},children:[i.jsx("td",{children:i.jsx("span",{className:"chip narrative",children:x})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:ia(T.addedAt)}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:T.detectedBy??"—"})]},x))})]})})),d==="Processing"&&(Object.keys(y.processing.graphs).length===0?i.jsx(Dt,{title:"No processing yet",message:"This item has not been processed by any graph."}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Version"}),i.jsx("th",{children:"Run"}),i.jsx("th",{children:"Processed at"})]})}),i.jsx("tbody",{children:Object.values(y.processing.graphs).map(x=>i.jsxs("tr",{style:{cursor:"default"},children:[i.jsx("td",{className:"mono",style:{fontSize:12},children:x.graphName??x.graphId}),i.jsx("td",{children:i.jsx(jt,{status:x.lastStatus})}),i.jsx("td",{className:"text-muted",children:x.graphVersion??"—"}),i.jsx("td",{children:x.lastRunId?i.jsx(Ke,{to:`/journal/${x.lastRunId}`,className:"mono",style:{fontSize:12},children:x.lastRunId}):"—"}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:ia(x.processedAt)})]},x.graphId))})]})})),d==="Snapshots"&&i.jsx(Dt,{title:"Snapshots view",message:"Snapshot perspectives for this item live in the Memorix UI. Core is the operational perspective shown here.",icon:"▤"}),d==="Journal"&&(m.isLoading?i.jsxs("div",{className:"loading-row",children:[i.jsx("span",{className:"spinner"})," Loading…"]}):(((g=m.data)==null?void 0:g.runs.length)??0)===0?i.jsx(Dt,{title:"No journal entries for this item"}):i.jsx("div",{className:"table-wrap",children:i.jsxs("table",{children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Source"}),i.jsx("th",{children:"Graph"}),i.jsx("th",{children:"Updated"})]})}),i.jsx("tbody",{children:(((b=m.data)==null?void 0:b.runs)??[]).map(x=>i.jsxs("tr",{onClick:()=>{window.location.href=`/journal/${x.id}`},children:[i.jsx("td",{children:i.jsx(jt,{status:x.status})}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:x.sourceName}),i.jsx("td",{className:"text-muted",style:{fontSize:12},children:x.graphName??x.graphId}),i.jsx("td",{className:"text-dim",style:{fontSize:12},children:Ln(x.updatedAt)})]},x.id))})]})}))]})}function ni({k:l,v:s}){return i.jsxs("div",{className:"detail-row",children:[i.jsx("span",{className:"detail-key",children:l}),i.jsx("span",{className:"detail-val",children:s})]})}const Cv=j.createContext("Exellix"),Tv=j.createContext(null);function e1(){return j.useContext(Cv)}function t1(){return j.useContext(Tv)}function a1({children:l}){const{data:s}=ve({queryKey:["config"],queryFn:re.config,staleTime:1/0}),c=(s==null?void 0:s.name)||"Exellix";return j.useEffect(()=>{document.title=`${c} Jobs`},[c]),i.jsx(Tv.Provider,{value:s??null,children:i.jsx(Cv.Provider,{value:c,children:l})})}const li={overview:"Overview",work:"Work",onDemand:"On-Demand",information:"Information",journal:"Journal",settings:"Settings"},n1="2.0.2",l1="/api/agents";class i1 extends j.Component{constructor(){super(...arguments);Bp(this,"state",{error:null,componentStack:null})}static getDerivedStateFromError(c){return{error:c,componentStack:null}}componentDidCatch(c,u){console.error("UI error:",c,u),this.setState({componentStack:u.componentStack??null})}render(){return this.state.error?i.jsxs("div",{style:{padding:32},children:[i.jsxs("div",{className:"error-state",children:[i.jsx("strong",{children:"Something went wrong on this page."}),i.jsx("pre",{style:{marginTop:8,fontSize:11,whiteSpace:"pre-wrap"},children:this.state.error.message}),this.state.componentStack&&i.jsx("pre",{style:{marginTop:8,fontSize:10,whiteSpace:"pre-wrap",opacity:.75},children:this.state.componentStack})]}),i.jsx("button",{style:{marginTop:12},onClick:()=>this.setState({error:null,componentStack:null}),children:"Try again"})]}):this.props.children}}function s1(){const l=ra(),s=e1(),c=t1(),u=d=>d==="/"?l.pathname==="/":l.pathname.startsWith(d);return i.jsxs("header",{className:"topbar",children:[i.jsxs("div",{className:"topbar-brand",children:[i.jsx("span",{className:"topbar-brand-icon",children:"⚙"}),i.jsxs("span",{children:[i.jsx("span",{style:{color:"var(--color-text)"},children:s})," ",i.jsx("span",{children:"Jobs"})]}),i.jsxs("span",{className:"app-pkg-version",children:["v",n1]})]}),i.jsxs("nav",{className:"topbar-nav",children:[i.jsx(ll,{to:"/",className:u("/")?"active":"",children:li.overview}),i.jsx(ll,{to:"/work",className:u("/work")?"active":"",children:li.work}),i.jsx(ll,{to:"/on-demand",className:u("/on-demand")?"active":"",children:li.onDemand}),i.jsx(ll,{to:"/information",className:u("/information")?"active":"",children:li.information}),i.jsx(ll,{to:"/journal",className:u("/journal")?"active":"",children:li.journal}),i.jsx(ll,{to:"/settings",className:u("/settings")?"active":"",children:li.settings})]}),i.jsxs("div",{className:"topbar-meta",title:c?`${c.mongoHost} / ${c.runtimeDb}`:void 0,children:[i.jsx(Ib,{apiBase:l1}),c?i.jsxs("span",{className:"mono",style:{fontSize:11},children:[c.runtimeDb," @ ",c.mongoHost]}):window.location.host]})]})}const Ot=l=>i.jsx(i1,{children:l});function r1(){return i.jsx(j0,{children:i.jsxs("div",{className:"layout",children:[i.jsx(s1,{}),i.jsx("main",{className:"page",children:i.jsxs(Fj,{children:[i.jsx(Ze,{path:"/",element:Ot(i.jsx(G0,{}))}),i.jsx(Ze,{path:"/settings",element:Ot(i.jsx(Y0,{}))}),i.jsx(Ze,{path:"/work",element:Ot(i.jsx(yS,{}))}),i.jsx(Ze,{path:"/work/new",element:Ot(i.jsx(wS,{}))}),i.jsx(Ze,{path:"/work/:id",element:Ot(i.jsx(LS,{}))}),i.jsx(Ze,{path:"/on-demand",element:Ot(i.jsx(QS,{}))}),i.jsx(Ze,{path:"/on-demand/single",element:Ot(i.jsx(ZS,{}))}),i.jsx(Ze,{path:"/on-demand/batch",element:Ot(i.jsx($S,{}))}),i.jsx(Ze,{path:"/on-demand/batch/:id",element:Ot(i.jsx(JS,{}))}),i.jsx(Ze,{path:"/information",element:Ot(i.jsx(IS,{}))}),i.jsx(Ze,{path:"/information/:recordId",element:Ot(i.jsx(PS,{}))}),i.jsx(Ze,{path:"/journal",element:Ot(i.jsx(Z0,{}))}),i.jsx(Ze,{path:"/journal/:id",element:Ot(i.jsx(uS,{}))}),i.jsx(Ze,{path:"/items/:itemId",element:Ot(i.jsx(pS,{}))}),i.jsx(Ze,{path:"/records",element:i.jsx(ka,{to:"/information",replace:!0})}),i.jsx(Ze,{path:"/records/:recordId",element:i.jsx(ka,{to:"/information",replace:!0})}),i.jsx(Ze,{path:"/runs",element:i.jsx(ka,{to:"/journal",replace:!0})}),i.jsx(Ze,{path:"/runs/:id",element:i.jsx(ka,{to:"/journal",replace:!0})}),i.jsx(Ze,{path:"/sources",element:i.jsx(ka,{to:"/information",replace:!0})}),i.jsx(Ze,{path:"/job-defs",element:i.jsx(ka,{to:"/work",replace:!0})}),i.jsx(Ze,{path:"/job-defs/:id",element:i.jsx(ka,{to:"/work",replace:!0})}),i.jsx(Ze,{path:"/jobs/new",element:i.jsx(ka,{to:"/on-demand",replace:!0})}),i.jsx(Ze,{path:"*",element:i.jsx(ka,{to:"/",replace:!0})})]})})]})})}const u1=new _b({defaultOptions:{queries:{retry:1,staleTime:2e3}}}),Rv=document.getElementById("root");if(!Rv)throw new Error("No #root element");ub.createRoot(Rv).render(i.jsx(j.StrictMode,{children:i.jsx(qb,{client:u1,children:i.jsx(a1,{children:i.jsx($b,{storageKey:"exellix-memorix-ui.selected-agent",children:i.jsx(r1,{})})})})}));
|
package/dist/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Exellix Jobs</title>
|
|
7
7
|
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚙</text></svg>" />
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-8-dkbxjX.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="/assets/index-CUeGAvCJ.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exellix/jobs-ui",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.2",
|
|
4
4
|
"description": "Exellix jobs operator dashboard — React SPA for queue views, record-centric workflows, and work-factory wizards. Talks to @exellix/jobs-api over HTTP.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"@tanstack/react-query": "^5.101.0",
|
|
29
|
-
"@x12i/memorix-agents": "^1.2.
|
|
29
|
+
"@x12i/memorix-agents": "^1.2.1",
|
|
30
30
|
"react": "^19.2.7",
|
|
31
31
|
"react-dom": "^19.2.7",
|
|
32
32
|
"react-router-dom": "^7.17.0"
|