@gobing-ai/spur 0.3.85 → 0.3.86

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.
Files changed (106) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/config/pipeline-budgets.json +0 -25
  3. package/config/plugin-scripts.json +0 -5
  4. package/config/rules/boundary/env-var-hygiene.yaml +41 -0
  5. package/config/transition-shims.json +1 -1
  6. package/config/workflow-candidates.json +41 -0
  7. package/config/workflows/feature-lifecycle.yaml +4 -2
  8. package/config/workflows/feature-verification.yaml +70 -0
  9. package/config/workflows/idea-pipeline.yaml +24 -12
  10. package/config/workflows/task-pipeline.yaml +43 -12
  11. package/config/workflows/wrapup-pipeline.yaml +70 -7
  12. package/package.json +9 -9
  13. package/plugins/sp/README.md +0 -3
  14. package/plugins/sp/hooks/agent-hint.ts +5 -4
  15. package/plugins/sp/hooks/careful-guard.ts +3 -1
  16. package/plugins/sp/hooks/context-post-tool.ts +2 -1
  17. package/plugins/sp/hooks/context-session-start.ts +4 -3
  18. package/plugins/sp/hooks/context-session-stop.ts +2 -1
  19. package/plugins/sp/hooks/pi/guard-extension.ts +4 -3
  20. package/plugins/sp/hooks/task-write-guard.ts +4 -3
  21. package/plugins/sp/lib/idea-handoff.generated.mjs +260 -260
  22. package/plugins/sp/plugin.json +1 -1
  23. package/plugins/sp/scripts/daily-summary/daily-summary.mjs +13 -4
  24. package/plugins/sp/scripts/daily-summary/daily-summary.ts +6 -4
  25. package/plugins/sp/scripts/feature-sync-bounded.mjs +10 -2
  26. package/plugins/sp/scripts/feature-sync-bounded.ts +2 -1
  27. package/plugins/sp/scripts/idea-handoff.mjs +6 -1
  28. package/plugins/sp/scripts/idea-handoff.ts +4 -1
  29. package/plugins/sp/scripts/inline-pipeline-parity-check.ts +1 -1
  30. package/plugins/sp/scripts/inline-run-setup.ts +185 -2
  31. package/plugins/sp/scripts/pr-reviewing.mjs +8 -1
  32. package/plugins/sp/scripts/pr-reviewing.ts +2 -1
  33. package/plugins/sp/scripts/quality-gate.mjs +8 -1
  34. package/plugins/sp/scripts/quality-gate.ts +2 -1
  35. package/plugins/sp/scripts/surface-drift-inventory.ts +1 -4
  36. package/plugins/sp/scripts/task-evidence-precheck.ts +2 -1
  37. package/plugins/sp/scripts/task-size-precheck.ts +6 -4
  38. package/plugins/sp/scripts/verify-answer-lint.ts +2 -1
  39. package/plugins/sp/scripts/workflow-step-profile.mjs +10 -2
  40. package/plugins/sp/scripts/workflow-step-profile.ts +2 -1
  41. package/plugins/sp/scripts/wrapup-steps.mjs +8 -1
  42. package/plugins/sp/scripts/wrapup-steps.ts +2 -1
  43. package/plugins/sp/skills/spur-cli/references/workflows.md +8 -7
  44. package/plugins/sp/skills/spur-dev/references/cross-cutting.md +4 -5
  45. package/plugins/sp/skills/spur-dev/references/done-housekeeping.md +1 -1
  46. package/plugins/sp/skills/spur-dev/references/gate-checklists.md +2 -2
  47. package/plugins/sp/skills/spur-dev/references/inline-pipeline-driver.md +59 -1
  48. package/schemas/state-machine-workflow.schema.json +5 -0
  49. package/schemas/transition-flow-workflow.schema.json +5 -0
  50. package/spur.js +20988 -20652
  51. package/web/_astro/BoardApp.CJiqp5pS.js +1 -0
  52. package/web/_astro/{BoardApp.yW425dRZ.js → BoardApp.yBBcFXWP.js} +4 -4
  53. package/web/_astro/{TaskDetail.CGwJAinW.js → TaskDetail.DqFJbRFc.js} +1 -1
  54. package/web/_astro/{arc.B-qNXzSO.js → arc.DL-BpHoi.js} +1 -1
  55. package/web/_astro/{architectureDiagram-3BPJPVTR.Bdg-xiji.js → architectureDiagram-3BPJPVTR.9IdQYyDq.js} +1 -1
  56. package/web/_astro/{blockDiagram-GPEHLZMM.DFArg3Kp.js → blockDiagram-GPEHLZMM.BKsFCqTl.js} +1 -1
  57. package/web/_astro/{c4Diagram-AAUBKEIU.BkOLcjyx.js → c4Diagram-AAUBKEIU.DhwI0dh1.js} +1 -1
  58. package/web/_astro/channel.CX5453qQ.js +1 -0
  59. package/web/_astro/{chunk-2J33WTMH.DN3c20V4.js → chunk-2J33WTMH.B3QVmQ9S.js} +1 -1
  60. package/web/_astro/{chunk-4BX2VUAB.B64K0Ttd.js → chunk-4BX2VUAB.DBSuqs9F.js} +1 -1
  61. package/web/_astro/{chunk-55IACEB6.C-AJvNwa.js → chunk-55IACEB6.BSYTWAYD.js} +1 -1
  62. package/web/_astro/{chunk-727SXJPM.DMkr46uS.js → chunk-727SXJPM.cWVuxXfS.js} +1 -1
  63. package/web/_astro/{chunk-AQP2D5EJ.4_WGbI64.js → chunk-AQP2D5EJ.DpU_Ob3d.js} +1 -1
  64. package/web/_astro/{chunk-FMBD7UC4.cbFW_lVE.js → chunk-FMBD7UC4.BykFkyji.js} +1 -1
  65. package/web/_astro/{chunk-ND2GUHAM.CDW_-2O1.js → chunk-ND2GUHAM.DwgHlMdY.js} +1 -1
  66. package/web/_astro/{chunk-QZHKN3VN.BoYOt_yg.js → chunk-QZHKN3VN.CusXUGWM.js} +1 -1
  67. package/web/_astro/{classDiagram-4FO5ZUOK.BNT6XpHQ.js → classDiagram-4FO5ZUOK.fx0ObzkN.js} +1 -1
  68. package/web/_astro/{classDiagram-v2-Q7XG4LA2.BNT6XpHQ.js → classDiagram-v2-Q7XG4LA2.fx0ObzkN.js} +1 -1
  69. package/web/_astro/{cose-bilkent-S5V4N54A.CI1DQxR3.js → cose-bilkent-S5V4N54A.Z4HgOlsd.js} +1 -1
  70. package/web/_astro/{cynefin-OW5HDTMX.A8ARH61p.js → cynefin-OW5HDTMX.B5dIZHJu.js} +1 -1
  71. package/web/_astro/{dagre-BM42HDAG.u28ZmqwR.js → dagre-BM42HDAG.DT70Q_Yw.js} +1 -1
  72. package/web/_astro/{diagram-2AECGRRQ.Dx8JcrGc.js → diagram-2AECGRRQ.DqHA3XBF.js} +1 -1
  73. package/web/_astro/{diagram-5GNKFQAL.BXJUG9GY.js → diagram-5GNKFQAL.BmCem957.js} +1 -1
  74. package/web/_astro/{diagram-KO2AKTUF.BtlMuWqW.js → diagram-KO2AKTUF.sn0-hrE0.js} +1 -1
  75. package/web/_astro/{diagram-LMA3HP47.C4T7qaAy.js → diagram-LMA3HP47.BSHe9tVc.js} +1 -1
  76. package/web/_astro/{diagram-OG6HWLK6.D5HECE10.js → diagram-OG6HWLK6.DHIc-86k.js} +1 -1
  77. package/web/_astro/{erDiagram-TEJ5UH35.B_hMR3yw.js → erDiagram-TEJ5UH35.Bxayrs7v.js} +1 -1
  78. package/web/_astro/{flowDiagram-I6XJVG4X.BAmpcYl3.js → flowDiagram-I6XJVG4X.BkzoE_5I.js} +1 -1
  79. package/web/_astro/{ganttDiagram-6RSMTGT7.DV1bSWK-.js → ganttDiagram-6RSMTGT7.okT6CvTo.js} +1 -1
  80. package/web/_astro/{gitGraphDiagram-PVQCEYII.DxYKkKrJ.js → gitGraphDiagram-PVQCEYII.CJuYbhC7.js} +1 -1
  81. package/web/_astro/{infoDiagram-5YYISTIA.BAWY2xMb.js → infoDiagram-5YYISTIA.RqLy7nBo.js} +1 -1
  82. package/web/_astro/{ishikawaDiagram-YF4QCWOH.CZssRn6V.js → ishikawaDiagram-YF4QCWOH.BwIcoagw.js} +1 -1
  83. package/web/_astro/{journeyDiagram-JHISSGLW.C--muARd.js → journeyDiagram-JHISSGLW.UB1VbWtH.js} +1 -1
  84. package/web/_astro/{kanban-definition-UN3LZRKU.D_QCK4et.js → kanban-definition-UN3LZRKU.AaxMKpTk.js} +1 -1
  85. package/web/_astro/{linear.DzrmTtZ0.js → linear.Nv_xOUjP.js} +1 -1
  86. package/web/_astro/{mermaid.core.Da03W3iu.js → mermaid.core.Bc4LqQgX.js} +4 -4
  87. package/web/_astro/{mindmap-definition-RKZ34NQL.6cy-8hR_.js → mindmap-definition-RKZ34NQL.oKUvU_qi.js} +1 -1
  88. package/web/_astro/{pieDiagram-4H26LBE5.C5rS1pdU.js → pieDiagram-4H26LBE5.DQk0oo03.js} +1 -1
  89. package/web/_astro/{quadrantDiagram-W4KKPZXB.w56GZZ6Q.js → quadrantDiagram-W4KKPZXB.BdDjESDa.js} +1 -1
  90. package/web/_astro/{requirementDiagram-4Y6WPE33.CipX3Pwu.js → requirementDiagram-4Y6WPE33.C2u9hUeH.js} +1 -1
  91. package/web/_astro/{sankeyDiagram-5OEKKPKP.C0VVzgJm.js → sankeyDiagram-5OEKKPKP.CDEoiJST.js} +1 -1
  92. package/web/_astro/{sequenceDiagram-3UESZ5HK.BX2dUUbF.js → sequenceDiagram-3UESZ5HK.D_hT_GAT.js} +1 -1
  93. package/web/_astro/{stateDiagram-AJRCARHV.ypCdgODQ.js → stateDiagram-AJRCARHV.DI8RYG0b.js} +1 -1
  94. package/web/_astro/{stateDiagram-v2-BHNVJYJU.In0baEtg.js → stateDiagram-v2-BHNVJYJU.Bkxz4DnP.js} +1 -1
  95. package/web/_astro/{timeline-definition-PNZ67QCA.CJN4Vkvl.js → timeline-definition-PNZ67QCA.DSY-kH3-.js} +1 -1
  96. package/web/_astro/{vennDiagram-CIIHVFJN.Cf8KkIPY.js → vennDiagram-CIIHVFJN.CpaDtuGr.js} +1 -1
  97. package/web/_astro/{wardleyDiagram-YWT4CUSO.DCZBo9xw.js → wardleyDiagram-YWT4CUSO.DujQWvo8.js} +1 -1
  98. package/web/_astro/{xychartDiagram-2RQKCTM6.Cm4v_MiJ.js → xychartDiagram-2RQKCTM6.DcM5Y4b9.js} +1 -1
  99. package/web/index.html +1 -1
  100. package/config/workflows/basic.yaml +0 -146
  101. package/config/workflows/docs-pipeline.yaml +0 -350
  102. package/config/workflows/feature-dev.yaml +0 -288
  103. package/plugins/sp/scripts/feature-dev-precheck.mjs +0 -146
  104. package/plugins/sp/scripts/feature-dev-precheck.ts +0 -238
  105. package/web/_astro/BoardApp.CHenHFia.js +0 -1
  106. package/web/_astro/channel.CbDHK5UQ.js +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/mermaid.core.Da03W3iu.js","_astro/index.De90oHcH.js","_astro/TaskDetail.CGwJAinW.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/mermaid.core.Bc4LqQgX.js","_astro/index.De90oHcH.js","_astro/TaskDetail.DqFJbRFc.js"])))=>i.map(i=>d[i]);
2
2
  import{r as g,R as UN,g as Gl,c as at,b as $N}from"./index.De90oHcH.js";var qu={exports:{}},Ps={};var n0;function zN(){if(n0)return Ps;n0=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,a,s){var i=null;if(s!==void 0&&(i=""+s),a.key!==void 0&&(i=""+a.key),"key"in a){s={};for(var l in a)l!=="key"&&(s[l]=a[l])}else s=a;return a=s.ref,{$$typeof:e,type:r,key:i,ref:a!==void 0?a:null,props:s}}return Ps.Fragment=t,Ps.jsx=n,Ps.jsxs=n,Ps}var r0;function HN(){return r0||(r0=1,qu.exports=zN()),qu.exports}var o=HN();var d1=e=>{throw TypeError(e)},GN=(e,t,n)=>t.has(e)||d1("Cannot "+n),Vu=(e,t,n)=>(GN(e,t,"read from private field"),n?n.call(e):t.get(e)),WN=(e,t,n)=>t.has(e)?d1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),a0="popstate";function qN(e={}){function t(r,a){let{pathname:s,search:i,hash:l}=r.location;return wi("",{pathname:s,search:i,hash:l},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}function n(r,a){return typeof a=="string"?a:Ar(a)}return YN(t,n,null,e)}function ut(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Yt(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function VN(){return Math.random().toString(36).substring(2,10)}function s0(e,t){return{usr:e.state,key:e.key,idx:t}}function wi(e,t,n=null,r){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?aa(t):t,state:n,key:t&&t.key||r||VN()}}function Ar({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function aa(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function YN(e,t,n,r={}){let{window:a=document.defaultView,v5Compat:s=!1}=r,i=a.history,l="POP",u=null,c=d();c==null&&(c=0,i.replaceState({...i.state,idx:c},""));function d(){return(i.state||{idx:null}).idx}function p(){l="POP";let E=d(),y=E==null?null:E-c;c=E,u&&u({action:l,location:x.location,delta:y})}function m(E,y){l="PUSH";let S=wi(x.location,E,y);c=d()+1;let v=s0(S,c),N=x.createHref(S);try{i.pushState(v,"",N)}catch(A){if(A instanceof DOMException&&A.name==="DataCloneError")throw A;a.location.assign(N)}s&&u&&u({action:l,location:x.location,delta:1})}function f(E,y){l="REPLACE";let S=wi(x.location,E,y);c=d();let v=s0(S,c),N=x.createHref(S);i.replaceState(v,"",N),s&&u&&u({action:l,location:x.location,delta:0})}function b(E){return p1(E)}let x={get action(){return l},get location(){return e(a,i)},listen(E){if(u)throw new Error("A history only accepts one active listener");return a.addEventListener(a0,p),u=E,()=>{a.removeEventListener(a0,p),u=null}},createHref(E){return t(a,E)},createURL:b,encodeLocation(E){let y=b(E);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:m,replace:f,go(E){return i.go(E)}};return x}function p1(e,t=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),ut(n,"No window.location.(origin|href) available to create URL");let r=typeof e=="string"?e:Ar(e);return r=r.replace(/ $/,"%20"),!t&&r.startsWith("//")&&(r=n+r),new URL(r,n)}var ei,i0=class{constructor(e){if(WN(this,ei,new Map),e)for(let[t,n]of e)this.set(t,n)}get(e){if(Vu(this,ei).has(e))return Vu(this,ei).get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw new Error("No value found for context")}set(e,t){Vu(this,ei).set(e,t)}};ei=new WeakMap;var KN=new Set(["lazy","caseSensitive","path","id","index","children"]);function ZN(e){return KN.has(e)}var XN=new Set(["lazy","caseSensitive","path","id","index","middleware","children"]);function QN(e){return XN.has(e)}function JN(e){return e.index===!0}function Ni(e,t,n=[],r={},a=!1){return e.map((s,i)=>{let l=[...n,String(i)],u=typeof s.id=="string"?s.id:l.join("-");if(ut(s.index!==!0||!s.children,"Cannot specify children on an index route"),ut(a||!r[u],`Found a route id collision on id "${u}". Route id's must be globally unique within Data Router usages`),JN(s)){let c={...s,id:u};return r[u]=o0(c,t(c)),c}else{let c={...s,id:u,children:void 0};return r[u]=o0(c,t(c)),s.children&&(c.children=Ni(s.children,t,l,r,a)),c}})}function o0(e,t){return Object.assign(e,{...t,...typeof t.lazy=="object"&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function Zr(e,t,n="/"){return ti(e,t,n,!1)}function ti(e,t,n,r){let a=typeof t=="string"?aa(t):t,s=ir(a.pathname||"/",n);if(s==null)return null;let i=f1(e);tA(i);let l=null;for(let u=0;l==null&&u<i.length;++u){let c=pA(s);l=cA(i[u],c,r)}return l}function eA(e,t){let{route:n,pathname:r,params:a}=e;return{id:n.id,pathname:r,params:a,data:t[n.id],loaderData:t[n.id],handle:n.handle}}function f1(e,t=[],n=[],r="",a=!1){let s=(i,l,u=a,c)=>{let d={relativePath:c===void 0?i.path||"":c,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};if(d.relativePath.startsWith("/")){if(!d.relativePath.startsWith(r)&&u)return;ut(d.relativePath.startsWith(r),`Absolute route path "${d.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),d.relativePath=d.relativePath.slice(r.length)}let p=Nr([r,d.relativePath]),m=n.concat(d);i.children&&i.children.length>0&&(ut(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${p}".`),f1(i.children,t,m,p,u)),!(i.path==null&&!i.index)&&t.push({path:p,score:lA(p,i.index),routesMeta:m})};return e.forEach((i,l)=>{if(i.path===""||!i.path?.includes("?"))s(i,l);else for(let u of m1(i.path))s(i,l,!0,u)}),t}function m1(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return a?[s,""]:[s];let i=m1(r.join("/")),l=[];return l.push(...i.map(u=>u===""?s:[s,u].join("/"))),a&&l.push(...i),l.map(u=>e.startsWith("/")&&u===""?"/":u)}function tA(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:uA(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var nA=/^:[\w-]+$/,rA=3,aA=2,sA=1,iA=10,oA=-2,l0=e=>e==="*";function lA(e,t){let n=e.split("/"),r=n.length;return n.some(l0)&&(r+=oA),t&&(r+=aA),n.filter(a=>!l0(a)).reduce((a,s)=>a+(nA.test(s)?rA:s===""?sA:iA),r)}function uA(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function cA(e,t,n=!1){let{routesMeta:r}=e,a={},s="/",i=[];for(let l=0;l<r.length;++l){let u=r[l],c=l===r.length-1,d=s==="/"?t:t.slice(s.length)||"/",p=dl({path:u.relativePath,caseSensitive:u.caseSensitive,end:c},d),m=u.route;if(!p&&c&&n&&!r[r.length-1].route.index&&(p=dl({path:u.relativePath,caseSensitive:u.caseSensitive,end:!1},d)),!p)return null;Object.assign(a,p.params),i.push({params:a,pathname:Nr([s,p.pathname]),pathnameBase:hA(Nr([s,p.pathnameBase])),route:m}),p.pathnameBase!=="/"&&(s=Nr([s,p.pathnameBase]))}return i}function dl(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=dA(e.path,e.caseSensitive,e.end),a=t.match(n);if(!a)return null;let s=a[0],i=s.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:r.reduce((c,{paramName:d,isOptional:p},m)=>{if(d==="*"){let b=l[m]||"";i=s.slice(0,s.length-b.length).replace(/(.)\/+$/,"$1")}const f=l[m];return p&&!f?c[d]=void 0:c[d]=(f||"").replace(/%2F/g,"/"),c},{}),pathname:s,pathnameBase:i,pattern:e}}function dA(e,t=!1,n=!0){Yt(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,l,u)=>(r.push({paramName:l,isOptional:u!=null}),u?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function pA(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Yt(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function ir(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function fA({basename:e,pathname:t}){return t==="/"?e:Nr([e,t])}var h1=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Wl=e=>h1.test(e);function mA(e,t="/"){let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?aa(e):e,s;if(n)if(Wl(n))s=n;else{if(n.includes("//")){let i=n;n=n.replace(/\/\/+/g,"/"),Yt(!1,`Pathnames cannot have embedded double slashes - normalizing ${i} -> ${n}`)}n.startsWith("/")?s=u0(n.substring(1),"/"):s=u0(n,t)}else s=t;return{pathname:s,search:gA(r),hash:bA(a)}}function u0(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function Yu(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function g1(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function ql(e){let t=g1(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function Vl(e,t,n,r=!1){let a;typeof e=="string"?a=aa(e):(a={...e},ut(!a.pathname||!a.pathname.includes("?"),Yu("?","pathname","search",a)),ut(!a.pathname||!a.pathname.includes("#"),Yu("#","pathname","hash",a)),ut(!a.search||!a.search.includes("#"),Yu("#","search","hash",a)));let s=e===""||a.pathname==="",i=s?"/":a.pathname,l;if(i==null)l=n;else{let p=t.length-1;if(!r&&i.startsWith("..")){let m=i.split("/");for(;m[0]==="..";)m.shift(),p-=1;a.pathname=m.join("/")}l=p>=0?t[p]:"/"}let u=mA(a,l),c=i&&i!=="/"&&i.endsWith("/"),d=(s||i===".")&&n.endsWith("/");return!u.pathname.endsWith("/")&&(c||d)&&(u.pathname+="/"),u}var Nr=e=>e.join("/").replace(/\/\/+/g,"/"),hA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),gA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,bA=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,Hi=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function Ai(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function Gi(e){return e.map(t=>t.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var b1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function x1(e,t){let n=e;if(typeof n!="string"||!h1.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(b1)try{let s=new URL(window.location.href),i=n.startsWith("//")?new URL(s.protocol+n):new URL(n),l=ir(i.pathname,t);i.origin===s.origin&&l!=null?n=l+i.search+i.hash:a=!0}catch{Yt(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:a,to:n}}var Jr=Symbol("Uninstrumented");function xA(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(a=>a({id:t.id,index:t.index,path:t.path,instrument(s){let i=Object.keys(n);for(let l of i)s[l]&&n[l].push(s[l])}}));let r={};if(typeof t.lazy=="function"&&n.lazy.length>0){let a=Za(n.lazy,t.lazy,()=>{});a&&(r.lazy=a)}if(typeof t.lazy=="object"){let a=t.lazy;["middleware","loader","action"].forEach(s=>{let i=a[s],l=n[`lazy.${s}`];if(typeof i=="function"&&l.length>0){let u=Za(l,i,()=>{});u&&(r.lazy=Object.assign(r.lazy||{},{[s]:u}))}})}return["loader","action"].forEach(a=>{let s=t[a];if(typeof s=="function"&&n[a].length>0){let i=s[Jr]??s,l=Za(n[a],i,(...u)=>c0(u[0]));l&&(l[Jr]=i,r[a]=l)}}),t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(a=>{let s=a[Jr]??a,i=Za(n.middleware,s,(...l)=>c0(l[0]));return i?(i[Jr]=s,i):a})),r}function EA(e,t){let n={navigate:[],fetch:[]};if(t.forEach(r=>r({instrument(a){let s=Object.keys(a);for(let i of s)a[i]&&n[i].push(a[i])}})),n.navigate.length>0){let r=e.navigate[Jr]??e.navigate,a=Za(n.navigate,r,(...s)=>{let[i,l]=s;return{to:typeof i=="number"||typeof i=="string"?i:i?Ar(i):".",...d0(e,l??{})}});a&&(a[Jr]=r,e.navigate=a)}if(n.fetch.length>0){let r=e.fetch[Jr]??e.fetch,a=Za(n.fetch,r,(...s)=>{let[i,,l,u]=s;return{href:l??".",fetcherKey:i,...d0(e,u??{})}});a&&(a[Jr]=r,e.fetch=a)}return e}function Za(e,t,n){return e.length===0?null:async(...r)=>{let a=await E1(e,n(...r),()=>t(...r),e.length-1);if(a.type==="error")throw a.value;return a.value}}async function E1(e,t,n,r){let a=e[r],s;if(a){let i,l=async()=>(i?console.error("You cannot call instrumented handlers more than once"):i=E1(e,t,n,r-1),s=await i,ut(s,"Expected a result"),s.type==="error"&&s.value instanceof Error?{status:"error",error:s.value}:{status:"success",error:void 0});try{await a(l,t)}catch(u){console.error("An instrumentation function threw an error:",u)}i||await l(),await i}else try{s={type:"success",value:await n()}}catch(i){s={type:"error",value:i}}return s||{type:"error",value:new Error("No result assigned in instrumentation chain.")}}function c0(e){let{request:t,context:n,params:r,unstable_pattern:a}=e;return{request:yA(t),params:{...r},unstable_pattern:a,context:TA(n)}}function d0(e,t){return{currentUrl:Ar(e.state.location),..."formMethod"in t?{formMethod:t.formMethod}:{},..."formEncType"in t?{formEncType:t.formEncType}:{},..."formData"in t?{formData:t.formData}:{},..."body"in t?{body:t.body}:{}}}function yA(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function TA(e){if(vA(e)){let t={...e};return Object.freeze(t),t}else return{get:t=>e.get(t)}}var SA=Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function vA(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null||Object.getOwnPropertyNames(t).sort().join("\0")===SA}var y1=["POST","PUT","PATCH","DELETE"],wA=new Set(y1),NA=["GET",...y1],AA=new Set(NA),T1=new Set([301,302,303,307,308]),_A=new Set([307,308]),Ku={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},kA={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Bs={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},CA=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),S1="remix-router-transitions",v1=Symbol("ResetLoaderData");function IA(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u";ut(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let r=e.hydrationRouteProperties||[],a=e.mapRouteProperties||CA,s=a;if(e.unstable_instrumentations){let F=e.unstable_instrumentations;s=q=>({...a(q),...xA(F.map(X=>X.route).filter(Boolean),q)})}let i={},l=Ni(e.routes,s,void 0,i),u,c=e.basename||"/";c.startsWith("/")||(c=`/${c}`);let d=e.dataStrategy||MA,p={...e.future},m=null,f=new Set,b=null,x=null,E=null,y=e.hydrationData!=null,S=Zr(l,e.history.location,c),v=!1,N=null,A;if(S==null&&!e.patchRoutesOnNavigation){let F=tr(404,{pathname:e.history.location.pathname}),{matches:q,route:X}=xo(l);A=!0,S=q,N={[X.id]:F}}else if(S&&!e.hydrationData&&he(S,l,e.history.location.pathname).active&&(S=null),S)if(S.some(F=>F.route.lazy))A=!1;else if(!S.some(F=>Jd(F.route)))A=!0;else{let F=e.hydrationData?e.hydrationData.loaderData:null,q=e.hydrationData?e.hydrationData.errors:null;if(q){let X=S.findIndex(me=>q[me.route.id]!==void 0);A=S.slice(0,X+1).every(me=>!nd(me.route,F,q))}else A=S.every(X=>!nd(X.route,F,q))}else{A=!1,S=[];let F=he(null,l,e.history.location.pathname);F.active&&F.matches&&(v=!0,S=F.matches)}let w,T={historyAction:e.history.action,location:e.history.location,matches:S,initialized:A,navigation:Ku,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||N,fetchers:new Map,blockers:new Map},_="POP",B=null,k=!1,$,V=!1,P=new Map,H=null,W=!1,L=!1,te=new Set,ie=new Map,be=0,I=-1,ne=new Map,ue=new Set,O=new Map,Ne=new Map,de=new Set,K=new Map,Ee,re=null;function D(){if(m=e.history.listen(({action:F,location:q,delta:X})=>{if(Ee){Ee(),Ee=void 0;return}Yt(K.size===0||X!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let me=zt({currentLocation:T.location,nextLocation:q,historyAction:F});if(me&&X!=null){let ve=new Promise(Le=>{Ee=Le});e.history.go(X*-1),Et(me,{state:"blocked",location:q,proceed(){Et(me,{state:"proceeding",proceed:void 0,reset:void 0,location:q}),ve.then(()=>e.history.go(X))},reset(){let Le=new Map(T.blockers);Le.set(me,Bs),pe({blockers:Le})}}),B?.resolve(),B=null;return}return Je(F,q)}),n){JA(t,P);let F=()=>e_(t,P);t.addEventListener("pagehide",F),H=()=>t.removeEventListener("pagehide",F)}return T.initialized||Je("POP",T.location,{initialHydration:!0}),w}function ye(){m&&m(),H&&H(),f.clear(),$&&$.abort(),T.fetchers.forEach((F,q)=>pt(q)),T.blockers.forEach((F,q)=>je(q))}function Se(F){return f.add(F),()=>f.delete(F)}function pe(F,q={}){F.matches&&(F.matches=F.matches.map(ve=>{let Le=i[ve.route.id],Oe=ve.route;return Oe.element!==Le.element||Oe.errorElement!==Le.errorElement||Oe.hydrateFallbackElement!==Le.hydrateFallbackElement?{...ve,route:Le}:ve})),T={...T,...F};let X=[],me=[];T.fetchers.forEach((ve,Le)=>{ve.state==="idle"&&(de.has(Le)?X.push(Le):me.push(Le))}),de.forEach(ve=>{!T.fetchers.has(ve)&&!ie.has(ve)&&X.push(ve)}),[...f].forEach(ve=>ve(T,{deletedFetchers:X,newErrors:F.errors??null,viewTransitionOpts:q.viewTransitionOpts,flushSync:q.flushSync===!0})),X.forEach(ve=>pt(ve)),me.forEach(ve=>T.fetchers.delete(ve))}function Ae(F,q,{flushSync:X}={}){let me=T.actionData!=null&&T.navigation.formMethod!=null&&Cn(T.navigation.formMethod)&&T.navigation.state==="loading"&&F.state?._isRedirect!==!0,ve;q.actionData?Object.keys(q.actionData).length>0?ve=q.actionData:ve=null:me?ve=T.actionData:ve=null;let Le=q.loaderData?T0(T.loaderData,q.loaderData,q.matches||[],q.errors):T.loaderData,Oe=T.blockers;Oe.size>0&&(Oe=new Map(Oe),Oe.forEach((Qe,We)=>Oe.set(We,Bs)));let Pe=W?!1:se(F,q.matches||T.matches),Ie=k===!0||T.navigation.formMethod!=null&&Cn(T.navigation.formMethod)&&F.state?._isRedirect!==!0;u&&(l=u,u=void 0),W||_==="POP"||(_==="PUSH"?e.history.push(F,F.state):_==="REPLACE"&&e.history.replace(F,F.state));let $e;if(_==="POP"){let Qe=P.get(T.location.pathname);Qe&&Qe.has(F.pathname)?$e={currentLocation:T.location,nextLocation:F}:P.has(F.pathname)&&($e={currentLocation:F,nextLocation:T.location})}else if(V){let Qe=P.get(T.location.pathname);Qe?Qe.add(F.pathname):(Qe=new Set([F.pathname]),P.set(T.location.pathname,Qe)),$e={currentLocation:T.location,nextLocation:F}}pe({...q,actionData:ve,loaderData:Le,historyAction:_,location:F,initialized:!0,navigation:Ku,revalidation:"idle",restoreScrollPosition:Pe,preventScrollReset:Ie,blockers:Oe},{viewTransitionOpts:$e,flushSync:X===!0}),_="POP",k=!1,V=!1,W=!1,L=!1,B?.resolve(),B=null,re?.resolve(),re=null}async function He(F,q){if(B?.resolve(),B=null,typeof F=="number"){B||(B=N0());let yt=B.promise;return e.history.go(F),yt}let X=td(T.location,T.matches,c,F,q?.fromRouteId,q?.relative),{path:me,submission:ve,error:Le}=p0(!1,X,q),Oe=T.location,Pe=wi(T.location,me,q&&q.state);Pe={...Pe,...e.history.encodeLocation(Pe)};let Ie=q&&q.replace!=null?q.replace:void 0,$e="PUSH";Ie===!0?$e="REPLACE":Ie===!1||ve!=null&&Cn(ve.formMethod)&&ve.formAction===T.location.pathname+T.location.search&&($e="REPLACE");let Qe=q&&"preventScrollReset"in q?q.preventScrollReset===!0:void 0,We=(q&&q.flushSync)===!0,xt=zt({currentLocation:Oe,nextLocation:Pe,historyAction:$e});if(xt){Et(xt,{state:"blocked",location:Pe,proceed(){Et(xt,{state:"proceeding",proceed:void 0,reset:void 0,location:Pe}),He(F,q)},reset(){let yt=new Map(T.blockers);yt.set(xt,Bs),pe({blockers:yt})}});return}await Je($e,Pe,{submission:ve,pendingError:Le,preventScrollReset:Qe,replace:q&&q.replace,enableViewTransition:q&&q.viewTransition,flushSync:We,callSiteDefaultShouldRevalidate:q&&q.unstable_defaultShouldRevalidate})}function fe(){re||(re=N0()),ce(),pe({revalidation:"loading"});let F=re.promise;return T.navigation.state==="submitting"?F:T.navigation.state==="idle"?(Je(T.historyAction,T.location,{startUninterruptedRevalidation:!0}),F):(Je(_||T.historyAction,T.navigation.location,{overrideNavigation:T.navigation,enableViewTransition:V===!0}),F)}async function Je(F,q,X){$&&$.abort(),$=null,_=F,W=(X&&X.startUninterruptedRevalidation)===!0,kt(T.location,T.matches),k=(X&&X.preventScrollReset)===!0,V=(X&&X.enableViewTransition)===!0;let me=u||l,ve=X&&X.overrideNavigation,Le=X?.initialHydration&&T.matches&&T.matches.length>0&&!v?T.matches:Zr(me,q,c),Oe=(X&&X.flushSync)===!0;if(Le&&T.initialized&&!L&&HA(T.location,q)&&!(X&&X.submission&&Cn(X.submission.formMethod))){Ae(q,{matches:Le},{flushSync:Oe});return}let Pe=he(Le,me,q.pathname);if(Pe.active&&Pe.matches&&(Le=Pe.matches),!Le){let{error:en,notFoundMatches:xn,route:Dt}=De(q.pathname);Ae(q,{matches:xn,loaderData:{},errors:{[Dt.id]:en}},{flushSync:Oe});return}$=new AbortController;let Ie=Wa(e.history,q,$.signal,X&&X.submission),$e=e.getContext?await e.getContext():new i0,Qe;if(X&&X.pendingError)Qe=[Xr(Le).route.id,{type:"error",error:X.pendingError}];else if(X&&X.submission&&Cn(X.submission.formMethod)){let en=await bt(Ie,q,X.submission,Le,$e,Pe.active,X&&X.initialHydration===!0,{replace:X.replace,flushSync:Oe});if(en.shortCircuited)return;if(en.pendingActionResult){let[xn,Dt]=en.pendingActionResult;if(Wn(Dt)&&Ai(Dt.error)&&Dt.error.status===404){$=null,Ae(q,{matches:en.matches,loaderData:{},errors:{[xn]:Dt.error}});return}}Le=en.matches||Le,Qe=en.pendingActionResult,ve=Zu(q,X.submission),Oe=!1,Pe.active=!1,Ie=Wa(e.history,Ie.url,Ie.signal)}let{shortCircuited:We,matches:xt,loaderData:yt,errors:Jt}=await it(Ie,q,Le,$e,Pe.active,ve,X&&X.submission,X&&X.fetcherSubmission,X&&X.replace,X&&X.initialHydration===!0,Oe,Qe,X&&X.callSiteDefaultShouldRevalidate);We||($=null,Ae(q,{matches:xt||Le,...S0(Qe),loaderData:yt,errors:Jt}))}async function bt(F,q,X,me,ve,Le,Oe,Pe={}){ce();let Ie=XA(q,X);if(pe({navigation:Ie},{flushSync:Pe.flushSync===!0}),Le){let We=await st(me,q.pathname,F.signal);if(We.type==="aborted")return{shortCircuited:!0};if(We.type==="error"){if(We.partialMatches.length===0){let{matches:yt,route:Jt}=xo(l);return{matches:yt,pendingActionResult:[Jt.id,{type:"error",error:We.error}]}}let xt=Xr(We.partialMatches).route.id;return{matches:We.partialMatches,pendingActionResult:[xt,{type:"error",error:We.error}]}}else if(We.matches)me=We.matches;else{let{notFoundMatches:xt,error:yt,route:Jt}=De(q.pathname);return{matches:xt,pendingActionResult:[Jt.id,{type:"error",error:yt}]}}}let $e,Qe=Qo(me,q);if(!Qe.route.action&&!Qe.route.lazy)$e={type:"error",error:tr(405,{method:F.method,pathname:q.pathname,routeId:Qe.route.id})};else{let We=ss(s,i,F,me,Qe,Oe?[]:r,ve),xt=await et(F,We,ve,null);if($e=xt[Qe.route.id],!$e){for(let yt of me)if(xt[yt.route.id]){$e=xt[yt.route.id];break}}if(F.signal.aborted)return{shortCircuited:!0}}if(ma($e)){let We;return Pe&&Pe.replace!=null?We=Pe.replace:We=x0($e.response.headers.get("Location"),new URL(F.url),c)===T.location.pathname+T.location.search,await Me(F,$e,!0,{submission:X,replace:We}),{shortCircuited:!0}}if(Wn($e)){let We=Xr(me,Qe.route.id);return(Pe&&Pe.replace)!==!0&&(_="PUSH"),{matches:me,pendingActionResult:[We.route.id,$e,Qe.route.id]}}return{matches:me,pendingActionResult:[Qe.route.id,$e]}}async function it(F,q,X,me,ve,Le,Oe,Pe,Ie,$e,Qe,We,xt){let yt=Le||Zu(q,Oe),Jt=Oe||Pe||w0(yt),en=!W&&!$e;if(ve){if(en){let Vt=Ft(We);pe({navigation:yt,...Vt!==void 0?{actionData:Vt}:{}},{flushSync:Qe})}let ct=await st(X,q.pathname,F.signal);if(ct.type==="aborted")return{shortCircuited:!0};if(ct.type==="error"){if(ct.partialMatches.length===0){let{matches:Qn,route:En}=xo(l);return{matches:Qn,loaderData:{},errors:{[En.id]:ct.error}}}let Vt=Xr(ct.partialMatches).route.id;return{matches:ct.partialMatches,loaderData:{},errors:{[Vt]:ct.error}}}else if(ct.matches)X=ct.matches;else{let{error:Vt,notFoundMatches:Qn,route:En}=De(q.pathname);return{matches:Qn,loaderData:{},errors:{[En.id]:Vt}}}}let xn=u||l,{dsMatches:Dt,revalidatingFetchers:Pn}=f0(F,me,s,i,e.history,T,X,Jt,q,$e?[]:r,$e===!0,L,te,de,O,ue,xn,c,e.patchRoutesOnNavigation!=null,We,xt);if(I=++be,!e.dataStrategy&&!Dt.some(ct=>ct.shouldLoad)&&!Dt.some(ct=>ct.route.middleware&&ct.route.middleware.length>0)&&Pn.length===0){let ct=le();return Ae(q,{matches:X,loaderData:{},errors:We&&Wn(We[1])?{[We[0]]:We[1].error}:null,...S0(We),...ct?{fetchers:new Map(T.fetchers)}:{}},{flushSync:Qe}),{shortCircuited:!0}}if(en){let ct={};if(!ve){ct.navigation=yt;let Vt=Ft(We);Vt!==void 0&&(ct.actionData=Vt)}Pn.length>0&&(ct.fetchers=Nt(Pn)),pe(ct,{flushSync:Qe})}Pn.forEach(ct=>{St(ct.key),ct.controller&&ie.set(ct.key,ct.controller)});let _n=()=>Pn.forEach(ct=>St(ct.key));$&&$.signal.addEventListener("abort",_n);let{loaderResults:$r,fetcherResults:kn}=await Q(Dt,Pn,F,me);if(F.signal.aborted)return{shortCircuited:!0};$&&$.signal.removeEventListener("abort",_n),Pn.forEach(ct=>ie.delete(ct.key));let Xn=Eo($r);if(Xn)return await Me(F,Xn.result,!0,{replace:Ie}),{shortCircuited:!0};if(Xn=Eo(kn),Xn)return ue.add(Xn.key),await Me(F,Xn.result,!0,{replace:Ie}),{shortCircuited:!0};let{loaderData:Fs,errors:zr}=y0(T,X,$r,We,Pn,kn);$e&&T.errors&&(zr={...T.errors,...zr});let br=le(),Dr=Ce(I),Hr=br||Dr||Pn.length>0;return{matches:X,loaderData:Fs,errors:zr,...Hr?{fetchers:new Map(T.fetchers)}:{}}}function Ft(F){if(F&&!Wn(F[1]))return{[F[0]]:F[1].data};if(T.actionData)return Object.keys(T.actionData).length===0?null:T.actionData}function Nt(F){return F.forEach(q=>{let X=T.fetchers.get(q.key),me=Us(void 0,X?X.data:void 0);T.fetchers.set(q.key,me)}),new Map(T.fetchers)}async function Tt(F,q,X,me){St(F);let ve=(me&&me.flushSync)===!0,Le=u||l,Oe=td(T.location,T.matches,c,X,q,me?.relative),Pe=Zr(Le,Oe,c),Ie=he(Pe,Le,Oe);if(Ie.active&&Ie.matches&&(Pe=Ie.matches),!Pe){G(F,q,tr(404,{pathname:Oe}),{flushSync:ve});return}let{path:$e,submission:Qe,error:We}=p0(!0,Oe,me);if(We){G(F,q,We,{flushSync:ve});return}let xt=e.getContext?await e.getContext():new i0,yt=(me&&me.preventScrollReset)===!0;if(Qe&&Cn(Qe.formMethod)){await $t(F,q,$e,Pe,xt,Ie.active,ve,yt,Qe,me&&me.unstable_defaultShouldRevalidate);return}O.set(F,{routeId:q,path:$e}),await rt(F,q,$e,Pe,xt,Ie.active,ve,yt,Qe)}async function $t(F,q,X,me,ve,Le,Oe,Pe,Ie,$e){ce(),O.delete(F);let Qe=T.fetchers.get(F);Re(F,QA(Ie,Qe),{flushSync:Oe});let We=new AbortController,xt=Wa(e.history,X,We.signal,Ie);if(Le){let Ht=await st(me,new URL(xt.url).pathname,xt.signal,F);if(Ht.type==="aborted")return;if(Ht.type==="error"){G(F,q,Ht.error,{flushSync:Oe});return}else if(Ht.matches)me=Ht.matches;else{G(F,q,tr(404,{pathname:X}),{flushSync:Oe});return}}let yt=Qo(me,X);if(!yt.route.action&&!yt.route.lazy){let Ht=tr(405,{method:Ie.formMethod,pathname:X,routeId:q});G(F,q,Ht,{flushSync:Oe});return}ie.set(F,We);let Jt=be,en=ss(s,i,xt,me,yt,r,ve),xn=await et(xt,en,ve,F),Dt=xn[yt.route.id];if(!Dt){for(let Ht of en)if(xn[Ht.route.id]){Dt=xn[Ht.route.id];break}}if(xt.signal.aborted){ie.get(F)===We&&ie.delete(F);return}if(de.has(F)){if(ma(Dt)||Wn(Dt)){Re(F,Or(void 0));return}}else{if(ma(Dt))if(ie.delete(F),I>Jt){Re(F,Or(void 0));return}else return ue.add(F),Re(F,Us(Ie)),Me(xt,Dt,!1,{fetcherSubmission:Ie,preventScrollReset:Pe});if(Wn(Dt)){G(F,q,Dt.error);return}}let Pn=T.navigation.location||T.location,_n=Wa(e.history,Pn,We.signal),$r=u||l,kn=T.navigation.state!=="idle"?Zr($r,T.navigation.location,c):T.matches;ut(kn,"Didn't find any matches after fetcher action");let Xn=++be;ne.set(F,Xn);let Fs=Us(Ie,Dt.data);T.fetchers.set(F,Fs);let{dsMatches:zr,revalidatingFetchers:br}=f0(_n,ve,s,i,e.history,T,kn,Ie,Pn,r,!1,L,te,de,O,ue,$r,c,e.patchRoutesOnNavigation!=null,[yt.route.id,Dt],$e);br.filter(Ht=>Ht.key!==F).forEach(Ht=>{let Pa=Ht.key,js=T.fetchers.get(Pa),go=Us(void 0,js?js.data:void 0);T.fetchers.set(Pa,go),St(Pa),Ht.controller&&ie.set(Pa,Ht.controller)}),pe({fetchers:new Map(T.fetchers)});let Dr=()=>br.forEach(Ht=>St(Ht.key));We.signal.addEventListener("abort",Dr);let{loaderResults:Hr,fetcherResults:ct}=await Q(zr,br,_n,ve);if(We.signal.aborted)return;if(We.signal.removeEventListener("abort",Dr),ne.delete(F),ie.delete(F),br.forEach(Ht=>ie.delete(Ht.key)),T.fetchers.has(F)){let Ht=Or(Dt.data);T.fetchers.set(F,Ht)}let Vt=Eo(Hr);if(Vt)return Me(_n,Vt.result,!1,{preventScrollReset:Pe});if(Vt=Eo(ct),Vt)return ue.add(Vt.key),Me(_n,Vt.result,!1,{preventScrollReset:Pe});let{loaderData:Qn,errors:En}=y0(T,kn,Hr,void 0,br,ct);Ce(Xn),T.navigation.state==="loading"&&Xn>I?(ut(_,"Expected pending action"),$&&$.abort(),Ae(T.navigation.location,{matches:kn,loaderData:Qn,errors:En,fetchers:new Map(T.fetchers)})):(pe({errors:En,loaderData:T0(T.loaderData,Qn,kn,En),fetchers:new Map(T.fetchers)}),L=!1)}async function rt(F,q,X,me,ve,Le,Oe,Pe,Ie){let $e=T.fetchers.get(F);Re(F,Us(Ie,$e?$e.data:void 0),{flushSync:Oe});let Qe=new AbortController,We=Wa(e.history,X,Qe.signal);if(Le){let Dt=await st(me,new URL(We.url).pathname,We.signal,F);if(Dt.type==="aborted")return;if(Dt.type==="error"){G(F,q,Dt.error,{flushSync:Oe});return}else if(Dt.matches)me=Dt.matches;else{G(F,q,tr(404,{pathname:X}),{flushSync:Oe});return}}let xt=Qo(me,X);ie.set(F,Qe);let yt=be,Jt=ss(s,i,We,me,xt,r,ve),xn=(await et(We,Jt,ve,F))[xt.route.id];if(ie.get(F)===Qe&&ie.delete(F),!We.signal.aborted){if(de.has(F)){Re(F,Or(void 0));return}if(ma(xn))if(I>yt){Re(F,Or(void 0));return}else{ue.add(F),await Me(We,xn,!1,{preventScrollReset:Pe});return}if(Wn(xn)){G(F,q,xn.error);return}Re(F,Or(xn.data))}}async function Me(F,q,X,{submission:me,fetcherSubmission:ve,preventScrollReset:Le,replace:Oe}={}){X||(B?.resolve(),B=null),q.response.headers.has("X-Remix-Revalidate")&&(L=!0);let Pe=q.response.headers.get("Location");ut(Pe,"Expected a Location header on the redirect Response"),Pe=x0(Pe,new URL(F.url),c);let Ie=wi(T.location,Pe,{_isRedirect:!0});if(n){let Jt=!1;if(q.response.headers.has("X-Remix-Reload-Document"))Jt=!0;else if(Wl(Pe)){const en=p1(Pe,!0);Jt=en.origin!==t.location.origin||ir(en.pathname,c)==null}if(Jt){Oe?t.location.replace(Pe):t.location.assign(Pe);return}}$=null;let $e=Oe===!0||q.response.headers.has("X-Remix-Replace")?"REPLACE":"PUSH",{formMethod:Qe,formAction:We,formEncType:xt}=T.navigation;!me&&!ve&&Qe&&We&&xt&&(me=w0(T.navigation));let yt=me||ve;if(_A.has(q.response.status)&&yt&&Cn(yt.formMethod))await Je($e,Ie,{submission:{...yt,formAction:Pe},preventScrollReset:Le||k,enableViewTransition:X?V:void 0});else{let Jt=Zu(Ie,me);await Je($e,Ie,{overrideNavigation:Jt,fetcherSubmission:ve,preventScrollReset:Le||k,enableViewTransition:X?V:void 0})}}async function et(F,q,X,me){let ve,Le={};try{ve=await jA(d,F,q,me,X,!1)}catch(Oe){return q.filter(Pe=>Pe.shouldLoad).forEach(Pe=>{Le[Pe.route.id]={type:"error",error:Oe}}),Le}if(F.signal.aborted)return Le;if(!Cn(F.method))for(let Oe of q){if(ve[Oe.route.id]?.type==="error")break;!ve.hasOwnProperty(Oe.route.id)&&!T.loaderData.hasOwnProperty(Oe.route.id)&&(!T.errors||!T.errors.hasOwnProperty(Oe.route.id))&&Oe.shouldCallHandler()&&(ve[Oe.route.id]={type:"error",result:new Error(`No result returned from dataStrategy for route ${Oe.route.id}`)})}for(let[Oe,Pe]of Object.entries(ve))if(VA(Pe)){let Ie=Pe.result;Le[Oe]={type:"redirect",response:$A(Ie,F,Oe,q,c)}}else Le[Oe]=await UA(Pe);return Le}async function Q(F,q,X,me){let ve=et(X,F,me,null),Le=Promise.all(q.map(async Ie=>{if(Ie.matches&&Ie.match&&Ie.request&&Ie.controller){let Qe=(await et(Ie.request,Ie.matches,me,Ie.key))[Ie.match.route.id];return{[Ie.key]:Qe}}else return Promise.resolve({[Ie.key]:{type:"error",error:tr(404,{pathname:Ie.path})}})})),Oe=await ve,Pe=(await Le).reduce((Ie,$e)=>Object.assign(Ie,$e),{});return{loaderResults:Oe,fetcherResults:Pe}}function ce(){L=!0,O.forEach((F,q)=>{ie.has(q)&&te.add(q),St(q)})}function Re(F,q,X={}){T.fetchers.set(F,q),pe({fetchers:new Map(T.fetchers)},{flushSync:(X&&X.flushSync)===!0})}function G(F,q,X,me={}){let ve=Xr(T.matches,q);pt(F),pe({errors:{[ve.route.id]:X},fetchers:new Map(T.fetchers)},{flushSync:(me&&me.flushSync)===!0})}function Fe(F){return Ne.set(F,(Ne.get(F)||0)+1),de.has(F)&&de.delete(F),T.fetchers.get(F)||kA}function Ve(F,q){St(F,q?.reason),Re(F,Or(null))}function pt(F){let q=T.fetchers.get(F);ie.has(F)&&!(q&&q.state==="loading"&&ne.has(F))&&St(F),O.delete(F),ne.delete(F),ue.delete(F),de.delete(F),te.delete(F),T.fetchers.delete(F)}function At(F){let q=(Ne.get(F)||0)-1;q<=0?(Ne.delete(F),de.add(F)):Ne.set(F,q),pe({fetchers:new Map(T.fetchers)})}function St(F,q){let X=ie.get(F);X&&(X.abort(q),ie.delete(F))}function Rt(F){for(let q of F){let X=Fe(q),me=Or(X.data);T.fetchers.set(q,me)}}function le(){let F=[],q=!1;for(let X of ue){let me=T.fetchers.get(X);ut(me,`Expected fetcher: ${X}`),me.state==="loading"&&(ue.delete(X),F.push(X),q=!0)}return Rt(F),q}function Ce(F){let q=[];for(let[X,me]of ne)if(me<F){let ve=T.fetchers.get(X);ut(ve,`Expected fetcher: ${X}`),ve.state==="loading"&&(St(X),ne.delete(X),q.push(X))}return Rt(q),q.length>0}function Ue(F,q){let X=T.blockers.get(F)||Bs;return K.get(F)!==q&&K.set(F,q),X}function je(F){T.blockers.delete(F),K.delete(F)}function Et(F,q){let X=T.blockers.get(F)||Bs;ut(X.state==="unblocked"&&q.state==="blocked"||X.state==="blocked"&&q.state==="blocked"||X.state==="blocked"&&q.state==="proceeding"||X.state==="blocked"&&q.state==="unblocked"||X.state==="proceeding"&&q.state==="unblocked",`Invalid blocker state transition: ${X.state} -> ${q.state}`);let me=new Map(T.blockers);me.set(F,q),pe({blockers:me})}function zt({currentLocation:F,nextLocation:q,historyAction:X}){if(K.size===0)return;K.size>1&&Yt(!1,"A router only supports one blocker at a time");let me=Array.from(K.entries()),[ve,Le]=me[me.length-1],Oe=T.blockers.get(ve);if(!(Oe&&Oe.state==="proceeding")&&Le({currentLocation:F,nextLocation:q,historyAction:X}))return ve}function De(F){let q=tr(404,{pathname:F}),X=u||l,{matches:me,route:ve}=xo(X);return{notFoundMatches:me,route:ve,error:q}}function tt(F,q,X){if(b=F,E=q,x=X||null,!y&&T.navigation===Ku){y=!0;let me=se(T.location,T.matches);me!=null&&pe({restoreScrollPosition:me})}return()=>{b=null,E=null,x=null}}function Xe(F,q){return x&&x(F,q.map(me=>eA(me,T.loaderData)))||F.key}function kt(F,q){if(b&&E){let X=Xe(F,q);b[X]=E()}}function se(F,q){if(b){let X=Xe(F,q),me=b[X];if(typeof me=="number")return me}return null}function he(F,q,X){if(e.patchRoutesOnNavigation)if(F){if(Object.keys(F[0].params).length>0)return{active:!0,matches:ti(q,X,c,!0)}}else return{active:!0,matches:ti(q,X,c,!0)||[]};return{active:!1,matches:null}}async function st(F,q,X,me){if(!e.patchRoutesOnNavigation)return{type:"success",matches:F};let ve=F;for(;;){let Le=u==null,Oe=u||l,Pe=i;try{await e.patchRoutesOnNavigation({signal:X,path:q,matches:ve,fetcherKey:me,patch:(Qe,We)=>{X.aborted||m0(Qe,We,Oe,Pe,s,!1)}})}catch(Qe){return{type:"error",error:Qe,partialMatches:ve}}finally{Le&&!X.aborted&&(l=[...l])}if(X.aborted)return{type:"aborted"};let Ie=Zr(Oe,q,c),$e=null;if(Ie){if(Object.keys(Ie[0].params).length===0)return{type:"success",matches:Ie};if($e=ti(Oe,q,c,!0),!($e&&ve.length<$e.length&&Ot(ve,$e.slice(0,ve.length))))return{type:"success",matches:Ie}}if($e||($e=ti(Oe,q,c,!0)),!$e||Ot(ve,$e))return{type:"success",matches:null};ve=$e}}function Ot(F,q){return F.length===q.length&&F.every((X,me)=>X.route.id===q[me].route.id)}function Y(F){i={},u=Ni(F,s,void 0,i)}function Ge(F,q,X=!1){let me=u==null;m0(F,q,u||l,i,s,X),me&&(l=[...l],pe({}))}return w={get basename(){return c},get future(){return p},get state(){return T},get routes(){return l},get window(){return t},initialize:D,subscribe:Se,enableScrollRestoration:tt,navigate:He,fetch:Tt,revalidate:fe,createHref:F=>e.history.createHref(F),encodeLocation:F=>e.history.encodeLocation(F),getFetcher:Fe,resetFetcher:Ve,deleteFetcher:At,dispose:ye,getBlocker:Ue,deleteBlocker:je,patchRoutes:Ge,_internalFetchControllers:ie,_internalSetRoutes:Y,_internalSetStateDoNotUseOrYouWillBreakYourApp(F){pe(F)}},e.unstable_instrumentations&&(w=EA(w,e.unstable_instrumentations.map(F=>F.router).filter(Boolean))),w}function RA(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function td(e,t,n,r,a,s){let i,l;if(a){i=[];for(let c of t)if(i.push(c),c.route.id===a){l=c;break}}else i=t,l=t[t.length-1];let u=Vl(r||".",ql(i),ir(e.pathname,n)||e.pathname,s==="path");if(r==null&&(u.search=e.search,u.hash=e.hash),(r==null||r===""||r===".")&&l){let c=tp(u.search);if(l.route.index&&!c)u.search=u.search?u.search.replace(/^\?/,"?index&"):"?index";else if(!l.route.index&&c){let d=new URLSearchParams(u.search),p=d.getAll("index");d.delete("index"),p.filter(f=>f).forEach(f=>d.append("index",f));let m=d.toString();u.search=m?`?${m}`:""}}return n!=="/"&&(u.pathname=fA({basename:n,pathname:u.pathname})),Ar(u)}function p0(e,t,n){if(!n||!RA(n))return{path:t};if(n.formMethod&&!ZA(n.formMethod))return{path:t,error:tr(405,{method:n.formMethod})};let r=()=>({path:t,error:tr(400,{type:"invalid-body"})}),s=(n.formMethod||"get").toUpperCase(),i=C1(t);if(n.body!==void 0){if(n.formEncType==="text/plain"){if(!Cn(s))return r();let p=typeof n.body=="string"?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((m,[f,b])=>`${m}${f}=${b}
3
3
  `,""):String(n.body);return{path:t,submission:{formMethod:s,formAction:i,formEncType:n.formEncType,formData:void 0,json:void 0,text:p}}}else if(n.formEncType==="application/json"){if(!Cn(s))return r();try{let p=typeof n.body=="string"?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:s,formAction:i,formEncType:n.formEncType,formData:void 0,json:p,text:void 0}}}catch{return r()}}}ut(typeof FormData=="function","FormData is not available in this environment");let l,u;if(n.formData)l=ad(n.formData),u=n.formData;else if(n.body instanceof FormData)l=ad(n.body),u=n.body;else if(n.body instanceof URLSearchParams)l=n.body,u=E0(l);else if(n.body==null)l=new URLSearchParams,u=new FormData;else try{l=new URLSearchParams(n.body),u=E0(l)}catch{return r()}let c={formMethod:s,formAction:i,formEncType:n&&n.formEncType||"application/x-www-form-urlencoded",formData:u,json:void 0,text:void 0};if(Cn(c.formMethod))return{path:t,submission:c};let d=aa(t);return e&&d.search&&tp(d.search)&&l.append("index",""),d.search=`?${l}`,{path:Ar(d),submission:c}}function f0(e,t,n,r,a,s,i,l,u,c,d,p,m,f,b,x,E,y,S,v,N){let A=v?Wn(v[1])?v[1].error:v[1].data:void 0,w=a.createURL(s.location),T=a.createURL(u),_;if(d&&s.errors){let W=Object.keys(s.errors)[0];_=i.findIndex(L=>L.route.id===W)}else if(v&&Wn(v[1])){let W=v[0];_=i.findIndex(L=>L.route.id===W)-1}let B=v?v[1].statusCode:void 0,k=B&&B>=400,$={currentUrl:w,currentParams:s.matches[0]?.params||{},nextUrl:T,nextParams:i[0].params,...l,actionResult:A,actionStatus:B},V=Gi(i),P=i.map((W,L)=>{let{route:te}=W,ie=null;if(_!=null&&L>_?ie=!1:te.lazy?ie=!0:Jd(te)?d?ie=nd(te,s.loaderData,s.errors):DA(s.loaderData,s.matches[L],W)&&(ie=!0):ie=!1,ie!==null)return rd(n,r,e,V,W,c,t,ie);let be=!1;typeof N=="boolean"?be=N:k?be=!1:(p||w.pathname+w.search===T.pathname+T.search||w.search!==T.search||OA(s.matches[L],W))&&(be=!0);let I={...$,defaultShouldRevalidate:be},ne=ii(W,I);return rd(n,r,e,V,W,c,t,ne,I,N)}),H=[];return b.forEach((W,L)=>{if(d||!i.some(Ne=>Ne.route.id===W.routeId)||f.has(L))return;let te=s.fetchers.get(L),ie=te&&te.state!=="idle"&&te.data===void 0,be=Zr(E,W.path,y);if(!be){if(S&&ie)return;H.push({key:L,routeId:W.routeId,path:W.path,matches:null,match:null,request:null,controller:null});return}if(x.has(L))return;let I=Qo(be,W.path),ne=new AbortController,ue=Wa(a,W.path,ne.signal),O=null;if(m.has(L))m.delete(L),O=ss(n,r,ue,be,I,c,t);else if(ie)p&&(O=ss(n,r,ue,be,I,c,t));else{let Ne;typeof N=="boolean"?Ne=N:k?Ne=!1:Ne=p;let de={...$,defaultShouldRevalidate:Ne};ii(I,de)&&(O=ss(n,r,ue,be,I,c,t,de))}O&&H.push({key:L,routeId:W.routeId,path:W.path,matches:O,match:I,request:ue,controller:ne})}),{dsMatches:P,revalidatingFetchers:H}}function Jd(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function nd(e,t,n){if(e.lazy)return!0;if(!Jd(e))return!1;let r=t!=null&&e.id in t,a=n!=null&&n[e.id]!==void 0;return!r&&a?!1:typeof e.loader=="function"&&e.loader.hydrate===!0?!0:!r&&!a}function DA(e,t,n){let r=!t||n.route.id!==t.route.id,a=!e.hasOwnProperty(n.route.id);return r||a}function OA(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function ii(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}function m0(e,t,n,r,a,s){let i;if(e){let c=r[e];ut(c,`No route found to patch children into: routeId = ${e}`),c.children||(c.children=[]),i=c.children}else i=n;let l=[],u=[];if(t.forEach(c=>{let d=i.find(p=>w1(c,p));d?u.push({existingRoute:d,newRoute:c}):l.push(c)}),l.length>0){let c=Ni(l,a,[e||"_","patch",String(i?.length||"0")],r);i.push(...c)}if(s&&u.length>0)for(let c=0;c<u.length;c++){let{existingRoute:d,newRoute:p}=u[c],m=d,[f]=Ni([p],a,[],{},!0);Object.assign(m,{element:f.element?f.element:m.element,errorElement:f.errorElement?f.errorElement:m.errorElement,hydrateFallbackElement:f.hydrateFallbackElement?f.hydrateFallbackElement:m.hydrateFallbackElement})}}function w1(e,t){return"id"in e&&"id"in t&&e.id===t.id?!0:e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive?(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children.every((n,r)=>t.children?.some(a=>w1(n,a))):!1}var h0=new WeakMap,N1=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let a=n[t.id];if(ut(a,"No route found in manifest"),!a.lazy||typeof a.lazy!="object")return;let s=a.lazy[e];if(!s)return;let i=h0.get(a);i||(i={},h0.set(a,i));let l=i[e];if(l)return l;let u=(async()=>{let c=ZN(e),p=a[e]!==void 0&&e!=="hasErrorBoundary";if(c)Yt(!c,"Route property "+e+" is not a supported lazy route property. This property will be ignored."),i[e]=Promise.resolve();else if(p)Yt(!1,`Route "${a.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let m=await s();m!=null&&(Object.assign(a,{[e]:m}),Object.assign(a,r(a)))}typeof a.lazy=="object"&&(a.lazy[e]=void 0,Object.values(a.lazy).every(m=>m===void 0)&&(a.lazy=void 0))})();return i[e]=u,u},g0=new WeakMap;function LA(e,t,n,r,a){let s=n[e.id];if(ut(s,"No route found in manifest"),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy=="function"){let d=g0.get(s);if(d)return{lazyRoutePromise:d,lazyHandlerPromise:d};let p=(async()=>{ut(typeof e.lazy=="function","No lazy route function found");let m=await e.lazy(),f={};for(let b in m){let x=m[b];if(x===void 0)continue;let E=QN(b),S=s[b]!==void 0&&b!=="hasErrorBoundary";E?Yt(!E,"Route property "+b+" is not a supported property to be returned from a lazy route function. This property will be ignored."):S?Yt(!S,`Route "${s.id}" has a static property "${b}" defined but its lazy function is also returning a value for this property. The lazy route property "${b}" will be ignored.`):f[b]=x}Object.assign(s,f),Object.assign(s,{...r(s),lazy:void 0})})();return g0.set(s,p),p.catch(()=>{}),{lazyRoutePromise:p,lazyHandlerPromise:p}}let i=Object.keys(e.lazy),l=[],u;for(let d of i){if(a&&a.includes(d))continue;let p=N1({key:d,route:e,manifest:n,mapRouteProperties:r});p&&(l.push(p),d===t&&(u=p))}let c=l.length>0?Promise.all(l).then(()=>{}):void 0;return c?.catch(()=>{}),u?.catch(()=>{}),{lazyRoutePromise:c,lazyHandlerPromise:u}}async function b0(e){let t=e.matches.filter(a=>a.shouldLoad),n={};return(await Promise.all(t.map(a=>a.resolve()))).forEach((a,s)=>{n[t[s].route.id]=a}),n}async function MA(e){return e.matches.some(t=>t.route.middleware)?A1(e,()=>b0(e)):b0(e)}function A1(e,t){return FA(e,t,r=>{if(KA(r))throw r;return r},WA,n);function n(r,a,s){if(s)return Promise.resolve(Object.assign(s.value,{[a]:{type:"error",result:r}}));{let{matches:i}=e,l=Math.min(Math.max(i.findIndex(c=>c.route.id===a),0),Math.max(i.findIndex(c=>c.shouldCallHandler()),0)),u=Xr(i,i[l].route.id).route.id;return Promise.resolve({[u]:{type:"error",result:r}})}}}async function FA(e,t,n,r,a){let{matches:s,request:i,params:l,context:u,unstable_pattern:c}=e,d=s.flatMap(m=>m.route.middleware?m.route.middleware.map(f=>[m.route.id,f]):[]);return await _1({request:i,params:l,context:u,unstable_pattern:c},d,t,n,r,a)}async function _1(e,t,n,r,a,s,i=0){let{request:l}=e;if(l.signal.aborted)throw l.signal.reason??new Error(`Request aborted: ${l.method} ${l.url}`);let u=t[i];if(!u)return await n();let[c,d]=u,p,m=async()=>{if(p)throw new Error("You may only call `next()` once per middleware");try{return p={value:await _1(e,t,n,r,a,s,i+1)},p.value}catch(f){return p={value:await s(f,c,p)},p.value}};try{let f=await d(e,m),b=f!=null?r(f):void 0;return a(b)?b:p?b??p.value:(p={value:await m()},p.value)}catch(f){return await s(f,c,p)}}function k1(e,t,n,r,a){let s=N1({key:"middleware",route:r.route,manifest:t,mapRouteProperties:e}),i=LA(r.route,Cn(n.method)?"action":"loader",t,e,a);return{middleware:s,route:i.lazyRoutePromise,handler:i.lazyHandlerPromise}}function rd(e,t,n,r,a,s,i,l,u=null,c){let d=!1,p=k1(e,t,n,a,s);return{...a,_lazyPromises:p,shouldLoad:l,shouldRevalidateArgs:u,shouldCallHandler(m){return d=!0,u?typeof c=="boolean"?ii(a,{...u,defaultShouldRevalidate:c}):typeof m=="boolean"?ii(a,{...u,defaultShouldRevalidate:m}):ii(a,u):l},resolve(m){let{lazy:f,loader:b,middleware:x}=a.route,E=d||l||m&&!Cn(n.method)&&(f||b),y=x&&x.length>0&&!b&&!f;return E&&(Cn(n.method)||!y)?PA({request:n,unstable_pattern:r,match:a,lazyHandlerPromise:p?.handler,lazyRoutePromise:p?.route,handlerOverride:m,scopedContext:i}):Promise.resolve({type:"data",result:void 0})}}}function ss(e,t,n,r,a,s,i,l=null){return r.map(u=>u.route.id!==a.route.id?{...u,shouldLoad:!1,shouldRevalidateArgs:l,shouldCallHandler:()=>!1,_lazyPromises:k1(e,t,n,u,s),resolve:()=>Promise.resolve({type:"data",result:void 0})}:rd(e,t,n,Gi(r),u,s,i,!0,l))}async function jA(e,t,n,r,a,s){n.some(c=>c._lazyPromises?.middleware)&&await Promise.all(n.map(c=>c._lazyPromises?.middleware));let i={request:t,unstable_pattern:Gi(n),params:n[0].params,context:a,matches:n},u=await e({...i,fetcherKey:r,runClientMiddleware:c=>{let d=i;return A1(d,()=>c({...d,fetcherKey:r,runClientMiddleware:()=>{throw new Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))}});try{await Promise.all(n.flatMap(c=>[c._lazyPromises?.handler,c._lazyPromises?.route]))}catch{}return u}async function PA({request:e,unstable_pattern:t,match:n,lazyHandlerPromise:r,lazyRoutePromise:a,handlerOverride:s,scopedContext:i}){let l,u,c=Cn(e.method),d=c?"action":"loader",p=m=>{let f,b=new Promise((y,S)=>f=S);u=()=>f(),e.signal.addEventListener("abort",u);let x=y=>typeof m!="function"?Promise.reject(new Error(`You cannot call the handler for a route which defines a boolean "${d}" [routeId: ${n.route.id}]`)):m({request:e,unstable_pattern:t,params:n.params,context:i},...y!==void 0?[y]:[]),E=(async()=>{try{return{type:"data",result:await(s?s(S=>x(S)):x())}}catch(y){return{type:"error",result:y}}})();return Promise.race([E,b])};try{let m=c?n.route.action:n.route.loader;if(r||a)if(m){let f,[b]=await Promise.all([p(m).catch(x=>{f=x}),r,a]);if(f!==void 0)throw f;l=b}else{await r;let f=c?n.route.action:n.route.loader;if(f)[l]=await Promise.all([p(f),a]);else if(d==="action"){let b=new URL(e.url),x=b.pathname+b.search;throw tr(405,{method:e.method,pathname:x,routeId:n.route.id})}else return{type:"data",result:void 0}}else if(m)l=await p(m);else{let f=new URL(e.url),b=f.pathname+f.search;throw tr(404,{pathname:b})}}catch(m){return{type:"error",result:m}}finally{u&&e.signal.removeEventListener("abort",u)}return l}async function BA(e){let t=e.headers.get("Content-Type");return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function UA(e){let{result:t,type:n}=e;if(ep(t)){let r;try{r=await BA(t)}catch(a){return{type:"error",error:a}}return n==="error"?{type:"error",error:new Hi(t.status,t.statusText,r),statusCode:t.status,headers:t.headers}:{type:"data",data:r,statusCode:t.status,headers:t.headers}}return n==="error"?v0(t)?t.data instanceof Error?{type:"error",error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"error",error:GA(t),statusCode:Ai(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"error",error:t,statusCode:Ai(t)?t.status:void 0}:v0(t)?{type:"data",data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"data",data:t}}function $A(e,t,n,r,a){let s=e.headers.get("Location");if(ut(s,"Redirects returned/thrown from loaders/actions must have a Location header"),!Wl(s)){let i=r.slice(0,r.findIndex(l=>l.route.id===n)+1);s=td(new URL(t.url),i,a,s),e.headers.set("Location",s)}return e}function x0(e,t,n){if(Wl(e)){let r=e,a=r.startsWith("//")?new URL(t.protocol+r):new URL(r),s=ir(a.pathname,n)!=null;if(a.origin===t.origin&&s)return a.pathname+a.search+a.hash}return e}function Wa(e,t,n,r){let a=e.createURL(C1(t)).toString(),s={signal:n};if(r&&Cn(r.formMethod)){let{formMethod:i,formEncType:l}=r;s.method=i.toUpperCase(),l==="application/json"?(s.headers=new Headers({"Content-Type":l}),s.body=JSON.stringify(r.json)):l==="text/plain"?s.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?s.body=ad(r.formData):s.body=r.formData}return new Request(a,s)}function ad(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function E0(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function zA(e,t,n,r=!1,a=!1){let s={},i=null,l,u=!1,c={},d=n&&Wn(n[1])?n[1].error:void 0;return e.forEach(p=>{if(!(p.route.id in t))return;let m=p.route.id,f=t[m];if(ut(!ma(f),"Cannot handle redirect results in processLoaderData"),Wn(f)){let b=f.error;if(d!==void 0&&(b=d,d=void 0),i=i||{},a)i[m]=b;else{let x=Xr(e,m);i[x.route.id]==null&&(i[x.route.id]=b)}r||(s[m]=v1),u||(u=!0,l=Ai(f.error)?f.error.status:500),f.headers&&(c[m]=f.headers)}else s[m]=f.data,f.statusCode&&f.statusCode!==200&&!u&&(l=f.statusCode),f.headers&&(c[m]=f.headers)}),d!==void 0&&n&&(i={[n[0]]:d},n[2]&&(s[n[2]]=void 0)),{loaderData:s,errors:i,statusCode:l||200,loaderHeaders:c}}function y0(e,t,n,r,a,s){let{loaderData:i,errors:l}=zA(t,n,r);return a.filter(u=>!u.matches||u.matches.some(c=>c.shouldLoad)).forEach(u=>{let{key:c,match:d,controller:p}=u;if(p&&p.signal.aborted)return;let m=s[c];if(ut(m,"Did not find corresponding fetcher result"),Wn(m)){let f=Xr(e.matches,d?.route.id);l&&l[f.route.id]||(l={...l,[f.route.id]:m.error}),e.fetchers.delete(c)}else if(ma(m))ut(!1,"Unhandled fetcher revalidation redirect");else{let f=Or(m.data);e.fetchers.set(c,f)}}),{loaderData:i,errors:l}}function T0(e,t,n,r){let a=Object.entries(t).filter(([,s])=>s!==v1).reduce((s,[i,l])=>(s[i]=l,s),{});for(let s of n){let i=s.route.id;if(!t.hasOwnProperty(i)&&e.hasOwnProperty(i)&&s.route.loader&&(a[i]=e[i]),r&&r.hasOwnProperty(i))break}return a}function S0(e){return e?Wn(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Xr(e,t){return(t?e.slice(0,e.findIndex(r=>r.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function xo(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function tr(e,{pathname:t,routeId:n,method:r,type:a,message:s}={}){let i="Unknown Server Error",l="Unknown @remix-run/router error";return e===400?(i="Bad Request",r&&t&&n?l=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:a==="invalid-body"&&(l="Unable to encode submission body")):e===403?(i="Forbidden",l=`Route "${n}" does not match URL "${t}"`):e===404?(i="Not Found",l=`No route matches URL "${t}"`):e===405&&(i="Method Not Allowed",r&&t&&n?l=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(l=`Invalid request method "${r.toUpperCase()}"`)),new Hi(e||500,i,new Error(l),!0)}function Eo(e){let t=Object.entries(e);for(let n=t.length-1;n>=0;n--){let[r,a]=t[n];if(ma(a))return{key:r,result:a}}}function C1(e){let t=typeof e=="string"?aa(e):e;return Ar({...t,hash:""})}function HA(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function GA(e){return new Hi(e.init?.status??500,e.init?.statusText??"Internal Server Error",e.data)}function WA(e){return e!=null&&typeof e=="object"&&Object.entries(e).every(([t,n])=>typeof t=="string"&&qA(n))}function qA(e){return e!=null&&typeof e=="object"&&"type"in e&&"result"in e&&(e.type==="data"||e.type==="error")}function VA(e){return ep(e.result)&&T1.has(e.result.status)}function Wn(e){return e.type==="error"}function ma(e){return(e&&e.type)==="redirect"}function v0(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function ep(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function YA(e){return T1.has(e)}function KA(e){return ep(e)&&YA(e.status)&&e.headers.has("Location")}function ZA(e){return AA.has(e.toUpperCase())}function Cn(e){return wA.has(e.toUpperCase())}function tp(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function Qo(e,t){let n=typeof t=="string"?aa(t).search:t.search;if(e[e.length-1].route.index&&tp(n||""))return e[e.length-1];let r=g1(e);return r[r.length-1]}function w0(e){let{formMethod:t,formAction:n,formEncType:r,text:a,formData:s,json:i}=e;if(!(!t||!n||!r)){if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:a};if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:s,json:void 0,text:void 0};if(i!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:i,text:void 0}}}function Zu(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function XA(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Us(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function QA(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Or(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function JA(e,t){try{let n=e.sessionStorage.getItem(S1);if(n){let r=JSON.parse(n);for(let[a,s]of Object.entries(r||{}))s&&Array.isArray(s)&&t.set(a,new Set(s||[]))}}catch{}}function e_(e,t){if(t.size>0){let n={};for(let[r,a]of t)n[r]=[...a];try{e.sessionStorage.setItem(S1,JSON.stringify(n))}catch(r){Yt(!1,`Failed to save applied view transitions in sessionStorage (${r}).`)}}}function N0(){let e,t,n=new Promise((r,a)=>{e=async s=>{r(s);try{await n}catch{}},t=async s=>{a(s);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var Aa=g.createContext(null);Aa.displayName="DataRouter";var Wi=g.createContext(null);Wi.displayName="DataRouterState";var I1=g.createContext(!1);function t_(){return g.useContext(I1)}var np=g.createContext({isTransitioning:!1});np.displayName="ViewTransition";var R1=g.createContext(new Map);R1.displayName="Fetchers";var n_=g.createContext(null);n_.displayName="Await";var Kn=g.createContext(null);Kn.displayName="Navigation";var Yl=g.createContext(null);Yl.displayName="Location";var fr=g.createContext({outlet:null,matches:[],isDataRoute:!1});fr.displayName="Route";var rp=g.createContext(null);rp.displayName="RouteError";var D1="REACT_ROUTER_ERROR",r_="REDIRECT",a_="ROUTE_ERROR_RESPONSE";function s_(e){if(e.startsWith(`${D1}:${r_}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function i_(e){if(e.startsWith(`${D1}:${a_}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new Hi(t.status,t.statusText,t.data)}catch{}}function o_(e,{relative:t}={}){ut(xs(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=g.useContext(Kn),{hash:a,pathname:s,search:i}=Vi(e,{relative:t}),l=s;return n!=="/"&&(l=s==="/"?n:Nr([n,s])),r.createHref({pathname:l,search:i,hash:a})}function xs(){return g.useContext(Yl)!=null}function Zn(){return ut(xs(),"useLocation() may be used only in the context of a <Router> component."),g.useContext(Yl).location}var O1="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function L1(e){g.useContext(Kn).static||g.useLayoutEffect(e)}function qi(){let{isDataRoute:e}=g.useContext(fr);return e?S_():l_()}function l_(){ut(xs(),"useNavigate() may be used only in the context of a <Router> component.");let e=g.useContext(Aa),{basename:t,navigator:n}=g.useContext(Kn),{matches:r}=g.useContext(fr),{pathname:a}=Zn(),s=JSON.stringify(ql(r)),i=g.useRef(!1);return L1(()=>{i.current=!0}),g.useCallback((u,c={})=>{if(Yt(i.current,O1),!i.current)return;if(typeof u=="number"){n.go(u);return}let d=Vl(u,JSON.parse(s),a,c.relative==="path");e==null&&t!=="/"&&(d.pathname=d.pathname==="/"?t:Nr([t,d.pathname])),(c.replace?n.replace:n.push)(d,c.state,c)},[t,n,s,a,e])}var u_=g.createContext(null);function c_(e){let t=g.useContext(fr).outlet;return g.useMemo(()=>t&&g.createElement(u_.Provider,{value:e},t),[t,e])}function Vi(e,{relative:t}={}){let{matches:n}=g.useContext(fr),{pathname:r}=Zn(),a=JSON.stringify(ql(n));return g.useMemo(()=>Vl(e,JSON.parse(a),r,t==="path"),[e,a,r,t])}function d_(e,t,n,r,a){ut(xs(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=g.useContext(Kn),{matches:i}=g.useContext(fr),l=i[i.length-1],u=l?l.params:{},c=l?l.pathname:"/",d=l?l.pathnameBase:"/",p=l&&l.route;{let S=p&&p.path||"";F1(c,!p||S.endsWith("*")||S.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${c}" (under <Route path="${S}">) 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.
4
4
 
@@ -169,7 +169,7 @@ ${e}`}function Vj(e){return e.kind==="task"?{kind:"task",wbs:e.wbs}:{kind:"featu
169
169
 
170
170
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const l=i[1];if(t===i[0]){s(i);continue}if(e.external){const c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(l.cycle){s(i);continue}if(l.count>1&&e.reused==="ref"){s(i);continue}}}function ew(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=l=>{const u=e.seen.get(l);if(u.ref===null)return;const c=u.def??u.schema,d={...c},p=u.ref;if(u.ref=null,p){r(p);const f=e.seen.get(p),b=f.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(b)):Object.assign(c,b),Object.assign(c,d),l._zod.parent===p)for(const E in c)E==="$ref"||E==="allOf"||E in d||delete c[E];if(b.$ref&&f.def)for(const E in c)E==="$ref"||E==="allOf"||E in f.def&&JSON.stringify(c[E])===JSON.stringify(f.def[E])&&delete c[E]}const m=l._zod.parent;if(m&&m!==p){r(m);const f=e.seen.get(m);if(f?.schema.$ref&&(c.$ref=f.schema.$ref,f.def))for(const b in c)b==="$ref"||b==="allOf"||b in f.def&&JSON.stringify(c[b])===JSON.stringify(f.def[b])&&delete c[b]}e.override({zodSchema:l,jsonSchema:c,path:u.path??[]})};for(const l of[...e.seen.entries()].reverse())r(l[0]);const a={};if(e.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");a.$id=e.external.uri(l)}Object.assign(a,n.def??n.schema);const s=e.metadataRegistry.get(t)?.id;s!==void 0&&a.id===s&&delete a.id;const i=e.external?.defs??{};for(const l of e.seen.entries()){const u=l[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,i[u.defId]=u.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?a.$defs=i:a.definitions=i);try{const l=JSON.parse(JSON.stringify(a));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Il(t,"input",e.processors),output:Il(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function On(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return On(r.element,n);if(r.type==="set")return On(r.valueType,n);if(r.type==="lazy")return On(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return On(r.innerType,n);if(r.type==="intersection")return On(r.left,n)||On(r.right,n);if(r.type==="record"||r.type==="map")return On(r.keyType,n)||On(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:On(r.in,n)||On(r.out,n);if(r.type==="object"){for(const a in r.shape)if(On(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(On(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(On(a,n))return!0;return!!(r.rest&&On(r.rest,n))}return!1}const WU=(e,t={})=>n=>{const r=Qv({...n,processors:t});return an(e,r),Jv(r,e),ew(r,e)},Il=(e,t,n={})=>r=>{const{libraryOptions:a,target:s}=r??{},i=Qv({...a??{},target:s,io:t,processors:n});return an(e,i),Jv(i,e),ew(i,e)},qU={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},VU=(e,t,n,r)=>{const a=n;a.type="string";const{minimum:s,maximum:i,format:l,patterns:u,contentEncoding:c}=e._zod.bag;if(typeof s=="number"&&(a.minLength=s),typeof i=="number"&&(a.maxLength=i),l&&(a.format=qU[l]??l,a.format===""&&delete a.format,l==="time"&&delete a.format),c&&(a.contentEncoding=c),u&&u.size>0){const d=[...u];d.length===1?a.pattern=d[0].source:d.length>1&&(a.allOf=[...d.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},YU=(e,t,n,r)=>{const a=n,{minimum:s,maximum:i,format:l,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:d}=e._zod.bag;typeof l=="string"&&l.includes("int")?a.type="integer":a.type="number";const p=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";p?f?(a.minimum=d,a.exclusiveMinimum=!0):a.exclusiveMinimum=d:typeof s=="number"&&(a.minimum=s),m?f?(a.maximum=c,a.exclusiveMaximum=!0):a.exclusiveMaximum=c:typeof i=="number"&&(a.maximum=i),typeof u=="number"&&(a.multipleOf=u)},KU=(e,t,n,r)=>{n.type="boolean"},ZU=(e,t,n,r)=>{n.not={}},XU=(e,t,n,r)=>{},QU=(e,t,n,r)=>{const a=e._zod.def,s=Iv(a.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},JU=(e,t,n,r)=>{const a=e._zod.def,s=[];for(const i of a.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s},e7=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},t7=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},n7=(e,t,n,r)=>{const a=n,s=e._zod.def,{minimum:i,maximum:l}=e._zod.bag;typeof i=="number"&&(a.minItems=i),typeof l=="number"&&(a.maxItems=l),a.type="array",a.items=an(s.element,t,{...r,path:[...r.path,"items"]})},r7=(e,t,n,r)=>{const a=n,s=e._zod.def;a.type="object",a.properties={};const i=s.shape;for(const c in i)a.properties[c]=an(i[c],t,{...r,path:[...r.path,"properties",c]});const l=new Set(Object.keys(i)),u=new Set([...l].filter(c=>{const d=s.shape[c]._zod;return t.io==="input"?d.optin===void 0:d.optout===void 0}));u.size>0&&(a.required=Array.from(u)),s.catchall?._zod.def.type==="never"?a.additionalProperties=!1:s.catchall?s.catchall&&(a.additionalProperties=an(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},a7=(e,t,n,r)=>{const a=e._zod.def,s=a.inclusive===!1,i=a.options.map((l,u)=>an(l,t,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=i:n.anyOf=i},s7=(e,t,n,r)=>{const a=e._zod.def,s=an(a.left,t,{...r,path:[...r.path,"allOf",0]}),i=an(a.right,t,{...r,path:[...r.path,"allOf",1]}),l=c=>"allOf"in c&&Object.keys(c).length===1,u=[...l(s)?s.allOf:[s],...l(i)?i.allOf:[i]];n.allOf=u},i7=(e,t,n,r)=>{const a=n,s=e._zod.def;a.type="object";const i=s.keyType,u=i._zod.bag?.patterns;if(s.mode==="loose"&&u&&u.size>0){const d=an(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});a.patternProperties={};for(const p of u)a.patternProperties[p.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(a.propertyNames=an(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),a.additionalProperties=an(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=i._zod.values;if(c){const d=[...c].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(a.required=d)}},o7=(e,t,n,r)=>{const a=e._zod.def,s=an(a.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=a.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},l7=(e,t,n,r)=>{const a=e._zod.def;an(a.innerType,t,r);const s=t.seen.get(e);s.ref=a.innerType},u7=(e,t,n,r)=>{const a=e._zod.def;an(a.innerType,t,r);const s=t.seen.get(e);s.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},c7=(e,t,n,r)=>{const a=e._zod.def;an(a.innerType,t,r);const s=t.seen.get(e);s.ref=a.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},d7=(e,t,n,r)=>{const a=e._zod.def;an(a.innerType,t,r);const s=t.seen.get(e);s.ref=a.innerType;let i;try{i=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},p7=(e,t,n,r)=>{const a=e._zod.def,s=a.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?a.out:a.in:a.out;an(i,t,r);const l=t.seen.get(e);l.ref=i},f7=(e,t,n,r)=>{const a=e._zod.def;an(a.innerType,t,r);const s=t.seen.get(e);s.ref=a.innerType,n.readOnly=!0},tw=(e,t,n,r)=>{const a=e._zod.def;an(a.innerType,t,r);const s=t.seen.get(e);s.ref=a.innerType},m7=oe("ZodISODateTime",(e,t)=>{hB.init(e,t),Xt.init(e,t)});function h7(e){return TU(m7,e)}const g7=oe("ZodISODate",(e,t)=>{gB.init(e,t),Xt.init(e,t)});function b7(e){return SU(g7,e)}const x7=oe("ZodISOTime",(e,t)=>{bB.init(e,t),Xt.init(e,t)});function E7(e){return vU(x7,e)}const y7=oe("ZodISODuration",(e,t)=>{xB.init(e,t),Xt.init(e,t)});function T7(e){return wU(y7,e)}const S7=(e,t)=>{Lv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>o8(e,n)},flatten:{value:n=>i8(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Md,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Md,2)}},isEmpty:{get(){return e.issues.length===0}}})},or=oe("ZodError",S7,{Parent:Error}),v7=Db(or),w7=Ob(or),N7=Du(or),A7=Ou(or),_7=c8(or),k7=d8(or),C7=p8(or),I7=f8(or),R7=m8(or),D7=h8(or),O7=g8(or),L7=b8(or),zE=new WeakMap;function co(e,t,n){const r=Object.getPrototypeOf(e);let a=zE.get(r);if(a||(a=new Set,zE.set(r,a)),!a.has(t)){a.add(t);for(const s in n){const i=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){const l=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const Zt=oe("ZodType",(e,t)=>(Kt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Il(e,"input"),output:Il(e,"output")}}),e.toJSONSchema=WU(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>v7(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>N7(e,n,r),e.parseAsync=async(n,r)=>w7(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>A7(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>_7(e,n,r),e.decode=(n,r)=>k7(e,n,r),e.encodeAsync=async(n,r)=>C7(e,n,r),e.decodeAsync=async(n,r)=>I7(e,n,r),e.safeEncode=(n,r)=>R7(e,n,r),e.safeDecode=(n,r)=>D7(e,n,r),e.safeEncodeAsync=async(n,r)=>O7(e,n,r),e.safeDecodeAsync=async(n,r)=>L7(e,n,r),co(e,"ZodType",{check(...n){const r=this.def;return this.clone(oa(r,{checks:[...r.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return la(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(N9(n,r))},superRefine(n,r){return this.check(A9(n,r))},overwrite(n){return this.check(Is(n))},optional(){return qE(this)},exactOptional(){return p9(this)},nullable(){return VE(this)},nullish(){return qE(VE(this))},nonoptional(n){return x9(this,n)},array(){return Ye(this)},or(n){return i9([this,n])},and(n){return iw(this,n)},transform(n){return YE(this,ow(n))},default(n){return h9(this,n)},prefault(n){return b9(this,n)},catch(n){return y9(this,n)},pipe(n){return YE(this,n)},readonly(){return v9(this)},describe(n){const r=this.clone();return ai.add(r,{description:n}),r},meta(...n){if(n.length===0)return ai.get(this);const r=this.clone();return ai.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return ai.get(e)?.description},configurable:!0}),e)),nw=oe("_ZodString",(e,t)=>{Lb.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(r,a,s)=>VU(e,r,a);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,co(e,"_ZodString",{regex(...r){return this.check(IU(...r))},includes(...r){return this.check(OU(...r))},startsWith(...r){return this.check(LU(...r))},endsWith(...r){return this.check(MU(...r))},min(...r){return this.check(Cl(...r))},max(...r){return this.check(Zv(...r))},length(...r){return this.check(Xv(...r))},nonempty(...r){return this.check(Cl(1,...r))},lowercase(r){return this.check(RU(r))},uppercase(r){return this.check(DU(r))},trim(){return this.check(jU())},normalize(...r){return this.check(FU(...r))},toLowerCase(){return this.check(PU())},toUpperCase(){return this.check(BU())},slugify(){return this.check(UU())}})}),M7=oe("ZodString",(e,t)=>{Lb.init(e,t),nw.init(e,t),e.email=n=>e.check(eU(F7,n)),e.url=n=>e.check(sU(j7,n)),e.jwt=n=>e.check(yU(Q7,n)),e.emoji=n=>e.check(iU(P7,n)),e.guid=n=>e.check(PE(HE,n)),e.uuid=n=>e.check(tU(Po,n)),e.uuidv4=n=>e.check(nU(Po,n)),e.uuidv6=n=>e.check(rU(Po,n)),e.uuidv7=n=>e.check(aU(Po,n)),e.nanoid=n=>e.check(oU(B7,n)),e.guid=n=>e.check(PE(HE,n)),e.cuid=n=>e.check(lU(U7,n)),e.cuid2=n=>e.check(uU($7,n)),e.ulid=n=>e.check(cU(z7,n)),e.base64=n=>e.check(bU(K7,n)),e.base64url=n=>e.check(xU(Z7,n)),e.xid=n=>e.check(dU(H7,n)),e.ksuid=n=>e.check(pU(G7,n)),e.ipv4=n=>e.check(fU(W7,n)),e.ipv6=n=>e.check(mU(q7,n)),e.cidrv4=n=>e.check(hU(V7,n)),e.cidrv6=n=>e.check(gU(Y7,n)),e.e164=n=>e.check(EU(X7,n)),e.datetime=n=>e.check(h7(n)),e.date=n=>e.check(b7(n)),e.time=n=>e.check(E7(n)),e.duration=n=>e.check(T7(n))});function z(e){return JB(M7,e)}const Xt=oe("ZodStringFormat",(e,t)=>{qt.init(e,t),nw.init(e,t)}),F7=oe("ZodEmail",(e,t)=>{iB.init(e,t),Xt.init(e,t)}),HE=oe("ZodGUID",(e,t)=>{aB.init(e,t),Xt.init(e,t)}),Po=oe("ZodUUID",(e,t)=>{sB.init(e,t),Xt.init(e,t)}),j7=oe("ZodURL",(e,t)=>{oB.init(e,t),Xt.init(e,t)}),P7=oe("ZodEmoji",(e,t)=>{lB.init(e,t),Xt.init(e,t)}),B7=oe("ZodNanoID",(e,t)=>{uB.init(e,t),Xt.init(e,t)}),U7=oe("ZodCUID",(e,t)=>{cB.init(e,t),Xt.init(e,t)}),$7=oe("ZodCUID2",(e,t)=>{dB.init(e,t),Xt.init(e,t)}),z7=oe("ZodULID",(e,t)=>{pB.init(e,t),Xt.init(e,t)}),H7=oe("ZodXID",(e,t)=>{fB.init(e,t),Xt.init(e,t)}),G7=oe("ZodKSUID",(e,t)=>{mB.init(e,t),Xt.init(e,t)}),W7=oe("ZodIPv4",(e,t)=>{EB.init(e,t),Xt.init(e,t)}),q7=oe("ZodIPv6",(e,t)=>{yB.init(e,t),Xt.init(e,t)}),V7=oe("ZodCIDRv4",(e,t)=>{TB.init(e,t),Xt.init(e,t)}),Y7=oe("ZodCIDRv6",(e,t)=>{SB.init(e,t),Xt.init(e,t)}),K7=oe("ZodBase64",(e,t)=>{vB.init(e,t),Xt.init(e,t)}),Z7=oe("ZodBase64URL",(e,t)=>{NB.init(e,t),Xt.init(e,t)}),X7=oe("ZodE164",(e,t)=>{AB.init(e,t),Xt.init(e,t)}),Q7=oe("ZodJWT",(e,t)=>{kB.init(e,t),Xt.init(e,t)}),rw=oe("ZodNumber",(e,t)=>{Gv.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(r,a,s)=>YU(e,r,a),co(e,"ZodNumber",{gt(r,a){return this.check(UE(r,a))},gte(r,a){return this.check(Ic(r,a))},min(r,a){return this.check(Ic(r,a))},lt(r,a){return this.check(BE(r,a))},lte(r,a){return this.check(Cc(r,a))},max(r,a){return this.check(Cc(r,a))},int(r){return this.check(GE(r))},safe(r){return this.check(GE(r))},positive(r){return this.check(UE(0,r))},nonnegative(r){return this.check(Ic(0,r))},negative(r){return this.check(BE(0,r))},nonpositive(r){return this.check(Cc(0,r))},multipleOf(r,a){return this.check($E(r,a))},step(r,a){return this.check($E(r,a))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ee(e){return NU(rw,e)}const J7=oe("ZodNumberFormat",(e,t)=>{CB.init(e,t),rw.init(e,t)});function GE(e){return AU(J7,e)}const e9=oe("ZodBoolean",(e,t)=>{IB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>KU(e,n,r)});function dr(e){return _U(e9,e)}const t9=oe("ZodUnknown",(e,t)=>{RB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>XU()});function wa(){return kU(t9)}const n9=oe("ZodNever",(e,t)=>{DB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>ZU(e,n,r)});function r9(e){return CU(n9,e)}const a9=oe("ZodArray",(e,t)=>{OB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>n7(e,n,r,a),e.element=t.element,co(e,"ZodArray",{min(n,r){return this.check(Cl(n,r))},nonempty(n){return this.check(Cl(1,n))},max(n,r){return this.check(Zv(n,r))},length(n,r){return this.check(Xv(n,r))},unwrap(){return this.element}})});function Ye(e,t){return $U(a9,e,t)}const s9=oe("ZodObject",(e,t)=>{MB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>r7(e,n,r,a),Lt(e,"shape",()=>t.shape),co(e,"ZodObject",{keyof(){return Ze(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:wa()})},loose(){return this.clone({...this._zod.def,catchall:wa()})},strict(){return this.clone({...this._zod.def,catchall:r9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return e8(this,n)},safeExtend(n){return t8(this,n)},merge(n){return n8(this,n)},pick(n){return QP(this,n)},omit(n){return JP(this,n)},partial(...n){return r8(lw,this,n[0])},required(...n){return a8(uw,this,n[0])}})});function ge(e,t){const n={type:"object",shape:e??{},...qe(t)};return new s9(n)}const aw=oe("ZodUnion",(e,t)=>{Vv.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>a7(e,n,r,a),e.options=t.options});function i9(e,t){return new aw({type:"union",options:e,...qe(t)})}const o9=oe("ZodDiscriminatedUnion",(e,t)=>{aw.init(e,t),FB.init(e,t)});function sw(e,t,n){return new o9({type:"union",options:t,discriminator:e,...qe(n)})}const l9=oe("ZodIntersection",(e,t)=>{jB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>s7(e,n,r,a)});function iw(e,t){return new l9({type:"intersection",left:e,right:t})}const WE=oe("ZodRecord",(e,t)=>{PB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>i7(e,n,r,a),e.keyType=t.keyType,e.valueType=t.valueType});function Rs(e,t,n){return!t||!t._zod?new WE({type:"record",keyType:z(),valueType:e,...qe(t)}):new WE({type:"record",keyType:e,valueType:t,...qe(n)})}const jd=oe("ZodEnum",(e,t)=>{BB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(r,a,s)=>QU(e,r,a),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,a)=>{const s={};for(const i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new jd({...t,checks:[],...qe(a),entries:s})},e.exclude=(r,a)=>{const s={...t.entries};for(const i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new jd({...t,checks:[],...qe(a),entries:s})}});function Ze(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new jd({type:"enum",entries:n,...qe(t)})}const u9=oe("ZodLiteral",(e,t)=>{UB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>JU(e,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Vn(e,t){return new u9({type:"literal",values:Array.isArray(e)?e:[e],...qe(t)})}const c9=oe("ZodTransform",(e,t)=>{$B.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>t7(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Cv(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Bi(s,n.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(Bi(i))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=a,n.fallback=!0,n)}});function ow(e){return new c9({type:"transform",transform:e})}const lw=oe("ZodOptional",(e,t)=>{Yv.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>tw(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function qE(e){return new lw({type:"optional",innerType:e})}const d9=oe("ZodExactOptional",(e,t)=>{zB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>tw(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function p9(e){return new d9({type:"optional",innerType:e})}const f9=oe("ZodNullable",(e,t)=>{HB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>o7(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function VE(e){return new f9({type:"nullable",innerType:e})}const m9=oe("ZodDefault",(e,t)=>{GB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>u7(e,n,r,a),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function h9(e,t){return new m9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Dv(t)}})}const g9=oe("ZodPrefault",(e,t)=>{WB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>c7(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function b9(e,t){return new g9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Dv(t)}})}const uw=oe("ZodNonOptional",(e,t)=>{qB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>l7(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function x9(e,t){return new uw({type:"nonoptional",innerType:e,...qe(t)})}const E9=oe("ZodCatch",(e,t)=>{VB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>d7(e,n,r,a),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function y9(e,t){return new E9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const cw=oe("ZodPipe",(e,t)=>{Kv.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>p7(e,n,r,a),e.in=t.in,e.out=t.out});function YE(e,t){return new cw({type:"pipe",in:e,out:t})}const T9=oe("ZodPreprocess",(e,t)=>{cw.init(e,t),YB.init(e,t)}),S9=oe("ZodReadonly",(e,t)=>{KB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>f7(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function v9(e){return new S9({type:"readonly",innerType:e})}const w9=oe("ZodCustom",(e,t)=>{ZB.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,r,a)=>e7(e,n)});function N9(e,t={}){return zU(w9,e,t)}function A9(e,t){return HU(e,t)}function Bo(e,t){return new T9({type:"pipe",in:ow(e),out:t})}const sr=["backlog","todo","wip","testing","blocked","done","cancelled"],Ds=["backlog","active","verifying","blocked","done","cancelled"],_9={backlog:"📋",todo:"🔲",wip:"🚧",testing:"🧪",blocked:"🚫",done:"✅",cancelled:"⛔"};function Mb(e){try{return _9[pw(e)]??""}catch{return""}}const Mu=["P0","P1","P2","P3"],k9=["simple","standard","complex","research","refine","plan","unit","review","docs"],dw=["task","issue","review","meta","brainstorm"],Fu=["standard","feature-impl","issue","review","meta","brainstorm"],Fb=/^[A-Z][1-9]*$/,C9={completed:"done",complete:"done","in-progress":"wip","in progress":"wip",in_progress:"wip",dropped:"cancelled",cancel:"cancelled",canceled:"cancelled",new:"backlog",pending:"backlog",blocked:"blocked",wip:"wip",testing:"testing",done:"done",cancelled:"cancelled",backlog:"backlog",todo:"todo"};function pw(e){const t=e.trim().toLowerCase(),n=C9[t];if(n===void 0)throw new Error(`Unknown task status: ${JSON.stringify(e)} (allowed: ${sr.join(", ")})`);return n}const Rl=z().min(1).refine(e=>!Number.isNaN(Date.parse(e)),{message:"must be an ISO 8601 timestamp"}),fw=z().regex(Fb,{message:"feature id must match ^[A-Z][1-9]*$ (DD-14)"}).nullable().optional(),mw=z().regex(/^\d{4}$/,{message:"parent_wbs must be a 4-digit WBS string"}).nullable().optional();ge({schema_version:Vn(1),name:z().min(1),description:z().optional(),status:Bo(e=>{if(typeof e=="string")try{return pw(e)}catch{}return e},Ze(sr)),type:Ze(dw).optional().default("task"),template:Ze(Fu).optional(),profile:Ze(k9).optional(),feature_id:fw,parent_wbs:mw,priority:Ze(Mu).optional(),tags:Ye(z()).optional(),dependencies:Ye(z()).optional(),ac_numbering:Vn("task-local").optional(),ac_altitude:Ze(["graduating","task-local"]).optional(),done_forced:Bo(e=>typeof e=="string"?e==="true":e,dr().optional()),done_reason:z().optional(),feature_link_declined:Bo(e=>typeof e=="string"?e==="true":e,dr().optional()),estimate_hours:Bo(e=>typeof e=="string"&&e.trim()!==""?Number(e):e,ee().positive().optional()),created_at:Rl,updated_at:Rl});ge({schema_version:Vn(1),id:z().regex(Fb,{message:"feature id must match ^[A-Z][1-9]*$ (DD-14)"}),name:z().min(1),status:Ze(Ds),priority:Ze(Mu).optional(),tags:Ye(z()).optional(),created_at:Rl,updated_at:Rl});const I9=ge({name:z().min(1,"name is required"),background:z().optional(),requirements:z().optional(),design:z().optional(),plan:z().optional(),acceptance_criteria:z().optional(),feature_id:fw,parent_wbs:mw,priority:Ze(Mu).optional(),tags:Ye(z()).optional(),template:Ze(Fu).optional(),estimate_hours:ee().positive().optional()}).strict();Ye(I9).min(1,"batch must contain at least one task");const R9=["NOT_FOUND","VALIDATION_FAILED","GUARD_DENIED","LOCK_TIMEOUT","CONFLICT","INTERNAL_ERROR"];function Ut(e){return ge({ok:Vn(!0),data:e})}ge({ok:Vn(!1),error:ge({code:Ze(R9),message:z(),details:wa().optional()})});ge({nextCursor:z().optional(),hasMore:dr(),limit:ee().int().positive()});const Yn=z().regex(Fb,{message:"feature id must match ^[A-Z][1-9]*$ (DD-14)"}),D9=ge({id:Yn,name:z().min(1),status:Ze(Ds),priority:Ze(Mu).optional(),parentId:Yn.nullable().optional(),wbsCount:ee().int().nonnegative().optional()}),O9=Ut(Ye(D9)),L9=Ut(ge({id:Yn,name:z(),status:Ze(Ds),frontmatter:Rs(z(),wa()),content:z(),filePath:z()})),M9=ge({id:Yn}),F9=ge({name:z().min(1),parentId:Yn.optional()}),j9=Ut(ge({id:z(),filePath:z()})),P9=ge({id:Yn,toStatus:Ze(Ds),actor:z().optional()}),B9=Ut(ge({id:z(),status:Ze(Ds)})),U9=ge({id:Yn,body:z(),actor:z().optional()}),$9=Ut(ge({})),z9=Ze(["brainstorm","plan"]),H9=Ze(["claude","codex","gemini","pi","opencode","antigravity","openclaw"]),G9=ge({id:Yn,action:z9,channel:H9.optional(),skipDeps:dr().optional()}),W9=ge({runId:z(),action:z(),status:Vn("queued")}),q9=Ut(W9),V9=ge({id:Yn,name:z().min(1)}),Y9=Ut(ge({id:z(),filePath:z()})),K9=ge({id:Yn,title:z().min(1)}),Z9=Ut(ge({wbs:z(),filePath:z()})),X9=ge({id:Yn,wbs:z().regex(/^\d{4}$/)}),Q9=Ut(ge({})),hw=Ze(["pull","push"]),J9=ge({id:Yn,direction:hw}),e$=Ut(ge({direction:hw,affectedTasks:ee().int().nonnegative(),applied:dr(),newStatus:z().optional()})),t$={list:Mt.route({method:"GET",path:"/features",summary:"List features",tags:["feature"]}).output(O9),show:Mt.route({method:"GET",path:"/features/{id}",summary:"Show feature detail",tags:["feature"]}).input(M9).output(L9),create:Mt.route({method:"POST",path:"/features",summary:"Create a feature",tags:["feature"]}).input(F9).output(j9),transition:Mt.route({method:"PATCH",path:"/features/{id}/status",summary:"Transition feature status",tags:["feature"]}).input(P9).output(B9),refresh:Mt.route({method:"POST",path:"/features/refresh",summary:"Refresh feature index and kanban",tags:["feature"]}).output(Ut(ge({rebuilt:ee().int().nonnegative()}))),check:Mt.route({method:"POST",path:"/features/{id}/check",summary:"Run the four-layer feature check",tags:["feature"]}).input(ge({id:Yn})).output(Ut(ge({id:z(),status:z(),pass:dr(),findings:Ye(ge({layer:Ze(["L1","L2","L3","L4"]),severity:Ze(["error","warning","info"]),section:z(),message:z()})),requiredSections:Ye(z()),missingSections:Ye(z())}))),body:Mt.route({method:"PATCH",path:"/features/{id}/body",summary:"Update feature body",tags:["feature"]}).input(U9).output($9),action:Mt.route({method:"POST",path:"/features/{id}/action",summary:"Run a feature workflow action",tags:["feature"]}).input(G9).output(q9),children:Mt.route({method:"POST",path:"/features/{id}/children",summary:"Create a child feature",tags:["feature"]}).input(V9).output(Y9),tasks:Mt.route({method:"POST",path:"/features/{id}/tasks",summary:"Create a task linked to feature",tags:["feature"]}).input(K9).output(Z9),link:Mt.route({method:"PATCH",path:"/features/{id}/link",summary:"Link an existing task to feature",tags:["feature"]}).input(X9).output(Q9),sync:Mt.route({method:"POST",path:"/features/{id}/sync",summary:"Sync feature status with linked tasks",tags:["feature"]}).input(J9).output(e$)},n$=Ze(["1h","4h","24h","7d","30d","all","custom"]),r$=Ze(["auto","1m","3m","5m","10m","30m","1h","4h","1d"]),a$=Ze(["model","source","tool","skill"]),Ui=ge({range:n$.default("4h"),from:z().datetime().optional(),to:z().datetime().optional(),sources:Ye(z()).optional(),models:Ye(z()).optional(),tools:Ye(z()).optional(),skills:Ye(z()).optional(),bucket:r$.default("auto"),dimension:a$.default("model")}),ju=ge({billedTokens:ee(),cacheSavedTokens:ee(),cacheReadTokens:ee(),freshInputTokens:ee(),outputTokens:ee()}),KE=ge({totalBilledTokens:ee(),cacheSavedTokens:ee(),cacheSavedPercent:ee(),sessionsCount:ee(),toolCallsCount:ee(),errorRate:ee()}),s$=ge({day:z(),totalBilledTokens:ee(),cacheSavedTokens:ee(),sessionsCount:ee(),toolCallsCount:ee(),cacheHitRatio:ee()}),Va=ge({bucketStart:z(),cacheHitRatio:ee(),gainRatio:ee().optional(),series:Rs(z(),ee())}),ZE=ge({id:z(),label:z(),color:z(),tokens:ee(),share:ee(),freshInputTokens:ee().optional(),cacheReadTokens:ee().optional(),outputTokens:ee().optional()}),i$=ge({id:z(),count:ee(),errors:ee(),errorRate:ee(),durationMs:ee().optional(),tokens:ee().optional(),usageShare:ee().optional(),timeShare:ee().optional(),tokenShare:ee().optional()}),o$=ge({id:z(),label:z(),color:z(),count:ee()}),l$=ge({bySkill:Ye(ge({skillName:z(),calls:ee()})),bySource:Ye(ge({source:z(),calls:ee()})),byInvocationKind:Ye(ge({invocationKind:z(),calls:ee()})),trend:Ye(Va),fresh:dr().default(!0)}),u$=ge({source:z(),sourceName:z(),color:z(),hitRatio:ee(),savedTokens:ee(),freshTokens:ee(),totalRead:ee(),billedTokens:ee()}),c$=ge({model:z(),modelName:z(),color:z(),hitRatio:ee(),savedTokens:ee(),freshTokens:ee(),totalRead:ee(),billedTokens:ee()}),d$=ge({source:z(),sourceName:z(),model:z(),modelName:z(),color:z(),hitRatio:ee(),savedTokens:ee(),totalRead:ee(),billedTokens:ee()}),p$=ge({hitRatio:ee(),savedTokens:ee(),totalRead:ee(),bySource:Ye(u$).optional(),byModel:Ye(c$).optional(),byAgentModel:Ye(d$).optional()}),f$=ge({kpis:KE,timeSeries:Ye(Va),topModels:Ye(ZE),topSources:Ye(ZE),topTools:Ye(i$),skillsUsed:Ye(o$),skillBreakdown:l$,cacheEfficiency:p$,kpiTrend:Ye(s$),previousKpis:KE.nullable(),skillTimeSeries:Ye(Va),modelTimeSeries:Ye(Va).optional(),sourceTimeSeries:Ye(Va).optional(),toolTimeSeries:Ye(Va).optional()}),m$=Ut(f$),h$=Ze(["read","write","bash","search","run","user","assistant","unknown"]),gw=Ze(["measured","inferred","unmeasured"]),g$=Ze(["exact","estimated"]),b$=sw("mode",[ge({mode:Vn("session"),source:z().min(1),sessionId:z().min(1)}),ge({mode:Vn("consolidated"),filter:Ui.optional(),taskWbs:z().optional(),runId:z().optional()})]),x$=ge({seq:ee(),eventType:Ze(["message","tool"]),kind:h$,title:z(),toolName:z().nullable(),durationMs:ee().nullable(),durationSource:gw,tokens:ee(),freshInputTokens:ee(),cacheReadTokens:ee(),outputTokens:ee(),promptTokens:ju.nullable(),exitCode:ee().nullable(),payload:z().nullable(),agent:z(),model:z()}),E$=ge({key:z(),sessionId:z(),turnIndex:ee(),timestamp:z().nullable(),source:z(),model:z(),correlationExactness:g$.nullable(),totalDurationMs:ee(),totalTokens:ee(),operationCount:ee(),events:Ye(x$)}),y$=ge({sessionId:z().nullable(),source:z().nullable(),model:z().nullable(),start:z().nullable(),end:z().nullable(),durationMs:ee(),tokens:ju,messageCount:ee(),toolCallCount:ee(),sessionCount:ee()}),T$=ge({mode:Ze(["session","consolidated"]),scope:y$,truncated:dr(),blocks:Ye(E$)}),S$=Ut(T$),v$=ge({id:z(),source:z(),model:z(),modelDetail:z().optional(),start:z(),durationMs:ee(),messages:ee(),toolCalls:ee(),billedTokens:ee(),cacheReadTokens:ee(),freshInputTokens:ee(),outputTokens:ee(),topTool:z(),state:z()}),w$=ge({items:Ye(v$),total:ee(),page:ee(),pageSize:ee()}),N$=Ut(w$),A$=ge({filter:Ui.optional(),page:ee().int().min(1).default(1),pageSize:ee().int().min(1).max(100).default(20),sortBy:Ze(["start","duration","messages","toolCalls","billedTokens","cacheRead","freshInput"]).default("start"),sortDir:Ze(["asc","desc"]).default("desc")}),_$=Ze(["read","write","bash","search","mcp","other"]),k$=Ze(["all","ok","error"]),bw=ge({seq:ee(),toolSeq:ee(),ts:z().nullable(),toolName:z(),category:_$,status:Ze(["ok","error","unknown"]),durationMs:ee().nullable(),durationSource:gw,resultBytes:ee().nullable(),argsRaw:z().nullable(),argsDigest:z().nullable(),errorText:z().nullable(),callId:z().nullable(),messageHash:z(),sessionId:z(),source:z(),model:z().nullable(),tokens:ju}),C$=ge({sessionId:z().nullable(),source:z().nullable(),model:z().nullable(),start:z().nullable(),end:z().nullable(),totalCalls:ee(),uniqueTools:ee(),errorCount:ee(),errorRate:ee(),totalDurationMs:ee(),meanDurationMs:ee(),durationUnmeasured:ee(),sessionCount:ee(),tokens:ju}),I$=iw(sw("mode",[ge({mode:Vn("session"),source:z().min(1),sessionId:z().min(1)}),ge({mode:Vn("consolidated"),filter:Ui.optional()})]),ge({toolNames:Ye(z()).optional(),status:k$.default("all"),search:z().optional()})),R$=ge({mode:Ze(["session","consolidated"]),scope:C$,truncated:dr(),items:Ye(bw)}),D$=Ut(R$),O$=ge({tool:z(),argsHint:z(),sessionId:z(),repeats:ee(),fromSeq:ee(),toSeq:ee(),wastedTokens:ee(),repeatedCalls:Ye(bw).optional()}),L$=ge({sessionId:z(),timestamp:z(),freshTokens:ee(),reason:z()}),M$=ge({id:z(),source:z(),model:z(),tokens:ee(),durationMs:ee()}),XE=ge({stepIndex:ee(),sessionId:z(),toolName:z(),tokens:ee(),durationMs:ee().optional(),agent:z(),model:z()}),F$=ge({model:z(),speedMsMean:ee(),cacheRatio:ee(),reliability:ee(),outputRatio:ee()}),j$=ge({loops:Ye(O$),cacheWaste:Ye(L$),heavySessions:Ye(M$),largestTokenSteps:Ye(XE),slowSteps:Ye(XE),modelComparison:Ye(F$)}),P$=Ut(j$),B$=ge({date:z(),tokens:ee(),sessions:ee()}),U$=ge({id:z(),name:z(),color:z(),importPath:z(),filePattern:z(),filesCount:ee(),sizeMb:ee().nullable(),sessionCount:ee(),totalTokens:ee(),cacheSavedTokens:ee(),freshTokens:ee(),toolCalls:ee(),firstDate:z().nullable(),lastDate:z().nullable(),heatmapDays:Ye(B$),maxDailyTokens:ee()}),$$=ge({agentId:z(),agentName:z(),path:z(),matchPattern:z(),fileCount:ee(),status:Ze(["active","empty","missing"])}),z$=ge({totalFiles:ee(),corpusSizeBytes:ee(),dateCoverage:ge({from:z().nullable(),to:z().nullable()}),totalSessions:ee(),lastImportedAt:z().nullable()}),H$=ge({overview:z$,agents:Ye(U$),roots:Ye($$)}),G$=Ut(H$),W$=ge({mode:Ze(["full","incremental"]).default("incremental")}),q$=ge({runId:z(),status:Ze(["queued","coalesced","already-running"]),message:z()}),V$=Ut(q$),Y$={getSummary:Mt.route({method:"POST",path:"/history/summary",summary:"Get conversation history analytics summary",tags:["history"]}).input(Ui.optional()).output(m$),getTimeline:Mt.route({method:"POST",path:"/history/timeline",summary:"Get chronological session or consolidated execution timeline",tags:["history"]}).input(b$).output(S$),getToolSequence:Mt.route({method:"POST",path:"/history/tool-sequence",summary:"Get ordered tool invocation sequence for a session or filtered scope",tags:["history"]}).input(I$).output(D$),getSessions:Mt.route({method:"POST",path:"/history/sessions",summary:"List and filter conversation sessions",tags:["history"]}).input(A$).output(N$),getInsights:Mt.route({method:"POST",path:"/history/insights",summary:"Get conversation forensic insights and loops",tags:["history"]}).input(Ui.optional()).output(P$),getSources:Mt.route({method:"GET",path:"/history/sources",summary:"Get all-time agent sources overview and heatmaps",tags:["history"]}).output(G$),triggerImport:Mt.route({method:"POST",path:"/history/import",summary:"Trigger history transcript import and analysis",tags:["history"]}).input(W$).output(V$)},K$=Ut(ge({eventName:z(),occurredAt:z().datetime(),actor:z().nullable().optional(),payload:Rs(z(),wa())})),Z$={stream:Mt.route({method:"GET",path:"/events/planning",summary:"Stream planning events (SSE)",tags:["events"]}).output(K$)},X$=ge({wbs:z().regex(/^\d{4}$/),name:z().min(1),status:Ze(sr),priority:z().optional(),featureId:z().nullable().optional(),parentWbs:z().regex(/^\d{4}$/).nullable().optional(),type:Ze(dw).optional(),filePath:z(),updatedAt:z().optional()}),Q$=Ut(Ye(X$)),J$=ge({folder:z().optional(),status:z().optional(),parent:z().optional()}),ez=Ut(ge({wbs:z(),name:z(),status:Ze(sr),frontmatter:Rs(z(),wa()),content:z(),filePath:z()})),tz=ge({wbs:z().regex(/^\d{4}$/)}),nz=ge({title:z().min(1),featureId:z().optional(),parentWbs:z().regex(/^\d{4}$/).optional(),folder:z().optional(),template:Ze(Fu).optional()}),rz=Ut(ge({wbs:z(),filePath:z()})),az=ge({wbs:z().regex(/^\d{4}$/),toStatus:Ze(sr),actor:z().optional()}),sz=Ut(ge({wbs:z(),status:Ze(sr)})),iz=ge({wbs:z().regex(/^\d{4}$/),body:z(),actor:z().optional()}),oz=Ut(ge({wbs:z(),filePath:z()})),lz=Ze(["claude","codex","gemini","pi","opencode","antigravity","openclaw"]),uz=Ze(["refine","plan","run","verify","decompose","evaluate"]),cz=ge({wbs:z().regex(/^\d{4}$/),action:uz,channel:lz.optional(),skipDeps:dr().optional()}),dz=Ut(ge({runId:z(),action:z(),status:Vn("queued")})),pz=ge({path:z(),label:z().optional()}),fz=Ut(Ye(pz)).extend({activeFolder:z().optional()}),mz={list:Mt.route({method:"GET",path:"/tasks",summary:"List tasks",tags:["task"]}).input(J$).output(Q$),folders:Mt.route({method:"GET",path:"/tasks/folders",summary:"List configured task folders",tags:["task"]}).output(fz),show:Mt.route({method:"GET",path:"/tasks/{wbs}",summary:"Show task detail",tags:["task"]}).input(tz).output(ez),create:Mt.route({method:"POST",path:"/tasks",summary:"Create a task",tags:["task"]}).input(nz).output(rz),transition:Mt.route({method:"PATCH",path:"/tasks/{wbs}/status",summary:"Transition task status",tags:["task"]}).input(az).output(sz),body:Mt.route({method:"PATCH",path:"/tasks/{wbs}/body",summary:"Update task body",tags:["task"]}).input(iz).output(oz),action:Mt.route({method:"POST",path:"/tasks/{wbs}/actions",summary:"Run a task action",tags:["task"]}).input(cz).output(dz)},hz=ge({totalEvents:ee(),activeJobs:ee(),completedJobs:ee(),failedJobs:ee(),successRatePct:ee(),errorEventCount:ee(),warningEventCount:ee()}),gz=ge({timestamp:z(),total:ee(),byPrefix:Rs(z(),ee()),bySeverity:ge({info:ee(),warning:ee(),error:ee(),unknown:ee()})}),bz=ge({name:z(),prefix:z(),count:ee(),latestAt:z(),avgDurationMs:ee().nullable(),failureCount:ee()}),xz=ge({id:z(),source:Ze(["event","job"]),name:z(),occurredAt:z(),message:z(),refId:z().optional()});ge({window:ge({since:z(),until:z(),range:z()}),kpis:hz,eventVolumeBuckets:Ye(gz),topEventTypes:Ye(bz),recentErrors:Ye(xz)});const Ez=Ze(["pending","processing","completed","failed"]),yz=ge({id:z(),type:z(),status:Ez,attempts:ee(),maxRetries:ee(),queuedAt:z(),startedAt:z().nullable(),endedAt:z().nullable(),durationMs:ee().nullable(),lastError:z().nullable(),payload:Rs(z(),wa()).nullable()}),Tz=ge({all:ee(),pending:ee(),processing:ee(),completed:ee(),failed:ee()});ge({jobs:Ye(yz),total:ee(),hasMore:dr(),countsByStatus:Tz});const Sz=Ze(["completed","failed","processing","none"]),vz=ge({name:z(),cron:z(),cadence:z(),nextFireAt:z().nullable(),lastFiredAt:z().nullable(),lastStatus:Sz,source:Ze(["builtin","config"])});ge({schedules:Ye(vz)});const wz=ge({status:Vn("ok"),timestamp:z(),service:Vn("spur"),version:z()}),Nz={health:Mt.route({method:"GET",path:"/health",summary:"Read application health",tags:["system"]}).output(wz),task:{...mz},feature:{...t$},history:{...Y$},...Z$};class Az extends _v{initRuntimeAdapter(t){for(const n of this.plugins)n.initRuntimeAdapter?.(t)}}class _z{fetch;toFetchRequestOptions;adapterInterceptors;constructor(t){new Az(t.plugins).initRuntimeAdapter(t),this.fetch=t.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=t,this.adapterInterceptors=Al(t.adapterInterceptors)}async call(t,n,r,a){const s=OP(t,this.toFetchRequestOptions),i=await Rd(this.adapterInterceptors,{...n,request:s,path:r,input:a,init:{redirect:"manual"}},({request:u,path:c,input:d,init:p,...m})=>this.fetch(u,p,m,c,d));return LP(i,{signal:s.signal})}}class kz{maxArrayIndex;constructor(t={}){this.maxArrayIndex=t.maxBracketNotationArrayIndex??9999}serialize(t,n=[],r=[]){if(Array.isArray(t))t.forEach((a,s)=>{this.serialize(a,[...n,s],r)});else if(ta(t))for(const a in t)this.serialize(t[a],[...n,a],r);else r.push([this.stringifyPath(n),t]);return r}deserialize(t){if(t.length===0)return{};const n=new WeakSet,r={value:[]};for(const[a,s]of t){const i=this.parsePath(a);let l=r,u="value";i.forEach((c,d)=>{!Array.isArray(l[u])&&!ta(l[u])&&(l[u]=[]),d!==i.length-1?Array.isArray(l[u])&&!QE(c,this.maxArrayIndex)&&(n.has(l[u])?(n.delete(l[u]),l[u]=JE(l[u])):l[u]=Rc(l[u])):Array.isArray(l[u])&&(c===""?l[u].length&&!n.has(l[u])&&(l[u]=Rc(l[u])):n.has(l[u])?(n.delete(l[u]),l[u]=JE(l[u])):QE(c,this.maxArrayIndex)||(l[u]=Rc(l[u]))),l=l[u],u=c}),Array.isArray(l)&&u===""?(n.add(l),l.push(s)):u in l?Array.isArray(l[u])?l[u].push(s):l[u]=[l[u],s]:l[u]=s}return r.value}stringifyPath(t){return t.map(n=>n.toString().replace(/[\\[\]]/g,r=>{switch(r){case"\\":return"\\\\";case"[":return"\\[";case"]":return"\\]";default:return r}})).reduce((n,r,a)=>a===0?r:`${n}[${r}]`,"")}parsePath(t){const n=[];let r=!1,a="",s=0;for(let i=0;i<t.length;i++){const l=t[i],u=t[i+1];r&&l==="]"&&(u===void 0||u==="[")&&s%2===0?(u===void 0&&(r=!1),n.push(a),a="",i++):n.length===0&&l==="["&&s%2===0?(r=!0,n.push(a),a=""):l==="\\"?s++:(a+="\\".repeat(s/2)+l,s=0)}return r||n.length===0?[t]:n}}function QE(e,t){return/^0$|^[1-9]\d*$/.test(e)&&Number(e)<=t}function Rc(e){const t=new hv;return e.forEach((n,r)=>{t[r]=n}),t}function JE(e){const t=new hv;return t[""]=e.length===1?e[0]:e,t}class Cz{customSerializers;constructor(t={}){this.customSerializers=t.customJsonSerializers??[]}serialize(t,n={value:!1}){for(const r of this.customSerializers)if(r.condition(t))return this.serialize(r.serialize(t),n);if(t instanceof Blob)return n.value=!0,[t,n.value];if(t instanceof Set)return this.serialize(Array.from(t),n);if(t instanceof Map)return this.serialize(Array.from(t.entries()),n);if(Array.isArray(t))return[t.map(a=>a===void 0?null:this.serialize(a,n)[0]),n.value];if(ta(t)){const r={};for(const a in t)a==="toJSON"&&typeof t[a]=="function"||(r[a]=this.serialize(t[a],n)[0]);return[r,n.value]}return typeof t=="bigint"||t instanceof RegExp||t instanceof URL?[t.toString(),n.value]:t instanceof Date?[Number.isNaN(t.getTime())?null:t.toISOString(),n.value]:Number.isNaN(t)?[null,n.value]:[t,n.value]}}function Pd(e){return`/${e.replace(/\/{2,}/g,"/").replace(/^\/|\/$/g,"")}`}function ey(e){return e?Pd(e).match(/\/\{[^}]+\}/g)?.map(t=>({raw:t,name:t.match(/\{\+?([^}]+)\}/)[1]})):void 0}class Iz{constructor(t,n,r){this.contract=t,this.serializer=n,this.baseUrl=r.url,this.headers=r.headers??{},this.customErrorResponseBodyDecoder=r.customErrorResponseBodyDecoder}baseUrl;headers;customErrorResponseBodyDecoder;async encode(t,n,r){let a=FP(await TE(this.headers,r,t,n));r.lastEventId!==void 0&&(a=SE(a,{"last-event-id":r.lastEventId}));const s=await TE(this.baseUrl,r,t,n),i=yE(this.contract,t);if(!Ld(i))throw new Error(`[StandardOpenapiLinkCodec] expect a contract procedure at ${t.join(".")}`);return Mo("defaultInputStructure",i["~orpc"].route.inputStructure)==="compact"?this.#e(i,t,n,r,s,a):this.#t(i,t,n,r,s,a)}#e(t,n,r,a,s,i){let l=Pd(t["~orpc"].route.path??wE(n)),u=r;const c=ey(l);if(c?.length){if(!ta(r))throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input shape for "compact" structure when has dynamic params at ${n.join(".")}.`);const m={...r};for(const f of c){const b=r[f.name];l=l.replace(f.raw,`/${encodeURIComponent(`${this.serializer.serialize(b)}`)}`),delete m[f.name]}u=Object.keys(m).length?m:void 0}const d=Mo("defaultMethod",t["~orpc"].route.method),p=new URL(s);if(p.pathname=`${p.pathname.replace(/\/$/,"")}${l}`,d==="GET"){const m=this.serializer.serialize(u,{outputFormat:"URLSearchParams"});for(const[f,b]of m)p.searchParams.append(f,b);return{url:p,method:d,headers:i,body:void 0,signal:a.signal}}return{url:p,method:d,headers:i,body:this.serializer.serialize(u),signal:a.signal}}#t(t,n,r,a,s,i){let l=Pd(t["~orpc"].route.path??wE(n));const u=ey(l);if(!ta(r)&&r!==void 0)throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input shape for "detailed" structure at ${n.join(".")}.`);if(u?.length){if(!ta(r?.params))throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input.params shape for "detailed" structure when has dynamic params at ${n.join(".")}.`);for(const m of u){const f=r.params[m.name];l=l.replace(m.raw,`/${encodeURIComponent(`${this.serializer.serialize(f)}`)}`)}}let c=i;if(r?.headers!==void 0){if(!ta(r.headers))throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input.headers shape for "detailed" structure at ${n.join(".")}.`);c=SE(r.headers,i)}const d=Mo("defaultMethod",t["~orpc"].route.method),p=new URL(s);if(p.pathname=`${p.pathname.replace(/\/$/,"")}${l}`,r?.query!==void 0){const m=this.serializer.serialize(r.query,{outputFormat:"URLSearchParams"});for(const[f,b]of m)p.searchParams.append(f,b)}return d==="GET"?{url:p,method:d,headers:c,body:void 0,signal:a.signal}:{url:p,method:d,headers:c,body:this.serializer.serialize(r?.body),signal:a.signal}}async decode(t,n,r){const a=!Fi(t.status),s=await(async()=>{let u=!1;try{const c=await t.body();return u=!0,this.serializer.deserialize(c)}catch(c){throw u?new Error("Invalid OpenAPI response format.",{cause:c}):new Error("Cannot parse response body, please check the response body and content-type.",{cause:c})}})();if(!a){const u=this.customErrorResponseBodyDecoder?.(s,t);throw u??(xv(s)?Ev(s):new Mi(jP(t.status),{status:t.status,data:{...t,body:s}}))}const i=yE(this.contract,r);if(!Ld(i))throw new Error(`[StandardOpenapiLinkCodec] expect a contract procedure at ${r.join(".")}`);return Mo("defaultOutputStructure",i["~orpc"].route.outputStructure)==="compact"?s:{status:t.status,headers:t.headers,body:s}}}class Rz{constructor(t,n){this.jsonSerializer=t,this.bracketNotation=n}serialize(t,n={}){return Li(t)&&!n.outputFormat?vE(t,{value:async r=>this.#e(r,{outputFormat:"plain"}),error:async r=>new ji({data:this.#e(bP(r).toJSON(),{outputFormat:"plain"}),cause:r})}):this.#e(t,n)}#e(t,n){const[r,a]=this.jsonSerializer.serialize(t);if(n.outputFormat==="plain")return r;if(n.outputFormat==="URLSearchParams"){const i=new URLSearchParams;for(const[l,u]of this.bracketNotation.serialize(r))(typeof u=="string"||typeof u=="number"||typeof u=="boolean")&&i.append(l,u.toString());return i}if(r instanceof Blob||r===void 0||!a)return r;const s=new FormData;for(const[i,l]of this.bracketNotation.serialize(r))typeof l=="string"||typeof l=="number"||typeof l=="boolean"?s.append(i,l.toString()):l instanceof Blob&&s.append(i,l);return s}deserialize(t){return t instanceof URLSearchParams||t instanceof FormData?this.bracketNotation.deserialize(Array.from(t.entries())):Li(t)?vE(t,{value:async n=>n,error:async n=>n instanceof ji&&xv(n.data)?Ev(n.data,{cause:n}):n}):t}}class Dz extends MP{constructor(t,n,r){const a=new Cz(r),s=new kz({maxBracketNotationArrayIndex:4294967294}),i=new Rz(a,s),l=new Iz(t,i,r);super(l,n,r)}}class Oz extends Dz{constructor(t,n){const r=new _z(n);super(t,r,n)}}function Ct(e=void 0,t=globalThis.location?.origin,n=!1){return e||(t&&t!=="null"?new URL("/api",t).toString():"http://localhost:3000/api")}function ht(e,t=1e4){const n=new AbortController,r=setTimeout(()=>n.abort(),t),a=e.signal;a&&a.addEventListener("abort",()=>n.abort(),{once:!0});const s=new Request(e,{signal:n.signal});return fetch(s).finally(()=>clearTimeout(r))}function Lz(e){return ht(e)}function Mz(e){typeof globalThis<"u"&&globalThis.dispatchEvent&&globalThis.dispatchEvent(new CustomEvent("api-error",{detail:{message:e instanceof Error?e.message:String(e)}}))}const rn=wv(new Oz(Nz,{url:Ct(),fetch:Lz,adapterInterceptors:[lP(Mz)]})),xw={path:null,name:"",fleet:null,state:"loading"},Ew=g.createContext(xw);function Fz({children:e}){const[t,n]=g.useState(xw);return g.useEffect(()=>{const r=new AbortController;let a=!1;return ht(new Request(`${Ct()}/project`,{signal:r.signal})).then(async s=>s.ok?await s.json():null).then(s=>{if(a)return;if(!s?.path){n({path:null,name:"",fleet:null,state:"unresolvable"});return}const i=s.path;n(l=>({...l,path:i,name:s.name??"",state:"ready"}))}).catch(()=>{a||n({path:null,name:"",fleet:null,state:"unresolvable"})}),ht(new Request(`${Ct()}/project/fleet`,{signal:r.signal})).then(async s=>s.ok?await s.json():null).then(s=>{a||s===null||n(i=>({...i,fleet:s}))}).catch(()=>{}),()=>{a=!0,r.abort()}},[]),o.jsx(Ew.Provider,{value:t,children:e})}function Os(){return g.useContext(Ew)}const yw="spur.board.projects.draft.v1";function ts(e){return{path:e,text:"",refs:[],revision:0}}function jz(e){if(e===null||typeof e!="object")return!1;const t=e;return t.kind==="task"?typeof t.wbs=="string"&&t.wbs.length>0:t.kind==="feature"?typeof t.id=="string"&&t.id.length>0:!1}function Pz(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;const t=e;return typeof t.path!="string"||typeof t.text!="string"||typeof t.revision!="number"||!Number.isFinite(t.revision)||!Array.isArray(t.refs)||!t.refs.every(n=>jz(n))?null:{...t,path:t.path,text:t.text,refs:t.refs,revision:t.revision}}function Bz(e){try{const t=globalThis.localStorage?.getItem(yw);if(t==null)return ts(e);const n=Pz(JSON.parse(t));return n===null||n.path!==e?(Ya(ts(e)),ts(e)):n}catch{return ts(e)}}function Ya(e){try{globalThis.localStorage?.setItem(yw,JSON.stringify(e))}catch{}}const Uz={draft:ts(""),setText:()=>{},addRef:()=>{},removeRef:()=>{},persistPending:()=>{},clearSubmitted:()=>{}},Tw=g.createContext(Uz);function Sw(){return g.useContext(Tw)}function $z({children:e}){const n=Os().path,[r,a]=g.useState(()=>ts(""));g.useEffect(()=>{n!==null&&a(Bz(n))},[n]);const s=g.useMemo(()=>({draft:r,setText:i=>a(l=>{if(l.path==="")return l;const u={...l,text:i,revision:l.revision+1};return Ya(u),u}),addRef:i=>a(l=>{if(l.path===""||l.refs.some(c=>kc(c,i)))return l;const u={...l,refs:[...l.refs,i],revision:l.revision+1};return Ya(u),u}),removeRef:i=>a(l=>{if(l.path===""||!l.refs.some(c=>kc(c,i)))return l;const u={...l,refs:l.refs.filter(c=>!kc(c,i)),revision:l.revision+1};return Ya(u),u}),persistPending:i=>a(l=>{if(l.path==="")return l;const u={...l,pending:{requestKey:i,revision:l.revision}};return Ya(u),u}),clearSubmitted:i=>a(l=>{if(l.path===""||l.revision!==i)return l;const u={path:l.path,text:"",refs:[],revision:l.revision+1};return Ya(u),u})}),[r]);return o.jsx(Tw.Provider,{value:s,children:e})}const zz=[],Rr=()=>`${Ct()}/features`;async function Hz(e){const t=await ht(new Request(Rr(),{signal:e}));if(!t.ok)throw new Error(`feature list fetch failed: ${t.status}`);const r=await t.json();if(!r.ok||!Array.isArray(r.data))throw new Error("feature list: invalid response shape");return r.data}async function ty(e,t){const n=await ht(new Request(`${Rr()}/${encodeURIComponent(e)}`,{signal:t}));if(!n.ok)throw new Error(`feature show fetch failed: ${n.status}`);const a=await n.json();if(!a.ok||!a.data)throw new Error("feature show: invalid response shape");return a.data}async function Gz(e,t,n){const r=await ht(new Request(`${Rr()}/${encodeURIComponent(e)}/status`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,toStatus:t}),signal:n})),a=await r.json();if(!r.ok){const i=a;throw new Error(i.error?.message??`transition failed: ${r.status}`)}return a.data?.status??t}async function Wz(e,t){const n=await ht(new Request(`${Rr()}/${encodeURIComponent(e.id)}/body`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const a=await n.json();throw new Error(a.error?.message??`body update failed: ${n.status}`)}}async function qz(e,t){const n=await ht(new Request(`${Rr()}/${encodeURIComponent(e.id)}/action`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const s=await n.json();throw new Error(s.error?.message??`action dispatch failed: ${n.status}`)}return await n.json()}async function vw(e,t){const n=await ht(new Request(`${Rr()}/${encodeURIComponent(e.id)}/children`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const s=await n.json();throw new Error(s.error?.message??`create child failed: ${n.status}`)}return await n.json()}async function Vz(e,t){const n=await ht(new Request(Rr(),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:e}),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`create feature failed: ${n.status}`)}const a=await n.json();if(!a.ok||!a.data)throw new Error("create feature: invalid response shape");return a.data}async function Yz(e,t){const n=await ht(new Request(`${Rr()}/${encodeURIComponent(e.id)}/tasks`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const s=await n.json();throw new Error(s.error?.message??`create task failed: ${n.status}`)}return await n.json()}async function Kz(e,t){const n=await ht(new Request(`${Rr()}/${encodeURIComponent(e.id)}/link`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const s=await n.json();throw new Error(s.error?.message??`link task failed: ${n.status}`)}return await n.json()}async function Zz(e,t){const n=await ht(new Request(`${Rr()}/${encodeURIComponent(e.id)}/sync`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const s=await n.json();throw new Error(s.error?.message??`sync failed: ${n.status}`)}return await n.json()}var na=$N();const Xz=(function(){const t=typeof document<"u"&&document.createElement("link").relList;return t&&t.supports&&t.supports("modulepreload")?"modulepreload":"preload"})(),Qz=function(e){return"/"+e},ny={},ww=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){let u=function(c){return Promise.all(c.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),l=i?.nonce||i?.getAttribute("nonce");a=u(n.map(c=>{if(c=Qz(c),c in ny)return;ny[c]=!0;const d=c.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Xz,d||(m.as="script"),m.crossOrigin="",m.href=c,l&&m.setAttribute("nonce",l),document.head.appendChild(m),d)return new Promise((f,b)=>{m.addEventListener("load",f),m.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${c}`)))})}))}function s(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return a.then(i=>{for(const l of i||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})};function ry(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Jz(e){if(Array.isArray(e))return e}function eH(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,s,i,l=[],u=!0,c=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(u=(r=s.call(n)).done)&&(l.push(r.value),l.length!==t);u=!0);}catch(d){c=!0,a=d}finally{try{if(!u&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(c)throw a}}return l}}function tH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
171
171
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function nH(e,t){return Jz(e)||eH(e,t)||rH(e,t)||tH()}function rH(e,t){if(e){if(typeof e=="string")return ry(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ry(e,t):void 0}}const Nw=Object.entries,ay=Object.setPrototypeOf,aH=Object.isFrozen,sH=Object.getPrototypeOf,iH=Object.getOwnPropertyDescriptor;let Tn=Object.freeze,vn=Object.seal,Ka=Object.create,Aw=typeof Reflect<"u"&&Reflect,Bd=Aw.apply,Ud=Aw.construct;Tn||(Tn=function(t){return t});vn||(vn=function(t){return t});Bd||(Bd=function(t,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),s=2;s<r;s++)a[s-2]=arguments[s];return t.apply(n,a)});Ud||(Ud=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return new t(...r)});const Zs=sn(Array.prototype.forEach),oH=sn(Array.prototype.lastIndexOf),sy=sn(Array.prototype.pop),$a=sn(Array.prototype.push),lH=sn(Array.prototype.splice),Qr=Array.isArray,si=sn(String.prototype.toLowerCase),Dc=sn(String.prototype.toString),iy=sn(String.prototype.match),Xs=sn(String.prototype.replace),oy=sn(String.prototype.indexOf),uH=sn(String.prototype.trim),cH=sn(Number.prototype.toString),dH=sn(Boolean.prototype.toString),ly=typeof BigInt>"u"?null:sn(BigInt.prototype.toString),uy=typeof Symbol>"u"?null:sn(Symbol.prototype.toString),pn=sn(Object.prototype.hasOwnProperty),Qs=sn(Object.prototype.toString),yn=sn(RegExp.prototype.test),ca=pH(TypeError);function sn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return Bd(e,t,r)}}function pH(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Ud(e,n)}}function vt(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:si;if(ay&&ay(e,null),!Qr(t))return e;let r=t.length;for(;r--;){let a=t[r];if(typeof a=="string"){const s=n(a);s!==a&&(aH(t)||(t[r]=s),a=s)}e[a]=!0}return e}function fH(e){for(let t=0;t<e.length;t++)pn(e,t)||(e[t]=null);return e}function Ln(e){const t=Ka(null);for(const r of Nw(e)){var n=nH(r,2);const a=n[0],s=n[1];pn(e,a)&&(Qr(s)?t[a]=fH(s):s&&typeof s=="object"&&s.constructor===Object?t[a]=Ln(s):t[a]=s)}return t}function mH(e){switch(typeof e){case"string":return e;case"number":return cH(e);case"boolean":return dH(e);case"bigint":return ly?ly(e):"0";case"symbol":return uy?uy(e):"Symbol()";case"undefined":return Qs(e);case"function":case"object":{if(e===null)return Qs(e);const t=e,n=Sr(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:Qs(r)}return Qs(e)}default:return Qs(e)}}function Sr(e,t){for(;e!==null;){const r=iH(e,t);if(r){if(r.get)return sn(r.get);if(typeof r.value=="function")return sn(r.value)}e=sH(e)}function n(){return null}return n}function hH(e){try{return yn(e,""),!0}catch{return!1}}const cy=Tn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Oc=Tn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Lc=Tn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),gH=Tn(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Mc=Tn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),bH=Tn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),dy=Tn(["#text"]),py=Tn(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Fc=Tn(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),fy=Tn(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Uo=Tn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),xH=vn(/{{[\w\W]*|^[\w\W]*}}/g),EH=vn(/<%[\w\W]*|^[\w\W]*%>/g),yH=vn(/\${[\w\W]*/g),TH=vn(/^data-[\-\w.\u00B7-\uFFFF]+$/),SH=vn(/^aria-[\-\w]+$/),my=vn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),vH=vn(/^(?:\w+script|data):/i),wH=vn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),NH=vn(/^html$/i),AH=vn(/^[a-z][.\w]*(-[.\w]+)+$/i),hy=vn(/<[/\w!]/g),_H=vn(/<[/\w]/g),kH=vn(/<\/no(script|embed|frames)/i),CH=vn(/\/>/i),yr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},IH=function(){return typeof window>"u"?null:window},RH=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const a="data-tt-policy-suffix";n&&n.hasAttribute(a)&&(r=n.getAttribute(a));const s="dompurify"+(r?"#"+r:"");try{return t.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},gy=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Wr=function(t,n,r,a){return pn(t,n)&&Qr(t[n])?vt(a.base?Ln(a.base):{},t[n],a.transform):r};function _w(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:IH();const t=ke=>_w(ke);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==yr.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,a=r.currentScript;e.DocumentFragment;const s=e.HTMLTemplateElement,i=e.Node,l=e.Element,u=e.NodeFilter,c=e.NamedNodeMap;c===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,p=e.trustedTypes,m=l.prototype,f=Sr(m,"cloneNode"),b=Sr(m,"remove"),x=Sr(m,"nextSibling"),E=Sr(m,"childNodes"),y=Sr(m,"parentNode"),S=Sr(m,"shadowRoot"),v=Sr(m,"attributes"),N=i&&i.prototype?Sr(i.prototype,"nodeType"):null,A=i&&i.prototype?Sr(i.prototype,"nodeName"):null;if(typeof s=="function"){const ke=n.createElement("template");ke.content&&ke.content.ownerDocument&&(n=ke.content.ownerDocument)}let w,T="",_,B=!1,k=0;const $=function(){if(k>0)throw ca('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},V=function(j){$(),k++;try{return w.createHTML(j)}finally{k--}},P=function(j){$(),k++;try{return w.createScriptURL(j)}finally{k--}},H=function(){return B||(_=RH(p,a),B=!0),_},W=n,L=W.implementation,te=W.createNodeIterator,ie=W.createDocumentFragment,be=W.getElementsByTagName,I=r.importNode;let ne=gy();t.isSupported=typeof Nw=="function"&&typeof y=="function"&&L&&L.createHTMLDocument!==void 0;const ue=xH,O=EH,Ne=yH,de=TH,K=SH,Ee=vH,re=wH,D=AH;let ye=my,Se=null;const pe=vt({},[...cy,...Oc,...Lc,...Mc,...dy]);let Ae=null;const He=vt({},[...py,...Fc,...fy,...Uo]);let fe=Object.seal(Ka(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Je=null,bt=null;const it=Object.seal(Ka(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ft=!0,Nt=!0,Tt=!1,$t=!0,rt=!1,Me=!0,et=!1,Q=!1,ce=null,Re=null,G=!1,Fe=!1,Ve=!1,pt=!1,At=!0,St=!1;const Rt="user-content-";let le=!0,Ce=!1,Ue={},je=null;const Et=vt({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let zt=null;const De=vt({},["audio","video","img","source","image","track"]);let tt=null;const Xe=vt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),kt="http://www.w3.org/1998/Math/MathML",se="http://www.w3.org/2000/svg",he="http://www.w3.org/1999/xhtml";let st=he,Ot=!1,Y=null;const Ge=vt({},[kt,se,he],Dc),F=Tn(["mi","mo","mn","ms","mtext"]);let q=vt({},F);const X=Tn(["annotation-xml"]);let me=vt({},X);const ve=vt({},["title","style","font","a","script"]);let Le=null;const Oe=["application/xhtml+xml","text/html"],Pe="text/html";let Ie=null,$e=null;const Qe=n.createElement("form"),We=function(j){return j instanceof RegExp||j instanceof Function},xt=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if($e&&$e===j)return;(!j||typeof j!="object")&&(j={}),j=Ln(j),Le=Oe.indexOf(j.PARSER_MEDIA_TYPE)===-1?Pe:j.PARSER_MEDIA_TYPE,Ie=Le==="application/xhtml+xml"?Dc:si,Se=Wr(j,"ALLOWED_TAGS",pe,{transform:Ie}),Ae=Wr(j,"ALLOWED_ATTR",He,{transform:Ie}),Y=Wr(j,"ALLOWED_NAMESPACES",Ge,{transform:Dc}),tt=Wr(j,"ADD_URI_SAFE_ATTR",Xe,{transform:Ie,base:Xe}),zt=Wr(j,"ADD_DATA_URI_TAGS",De,{transform:Ie,base:De}),je=Wr(j,"FORBID_CONTENTS",Et,{transform:Ie}),Je=Wr(j,"FORBID_TAGS",Ln({}),{transform:Ie}),bt=Wr(j,"FORBID_ATTR",Ln({}),{transform:Ie}),Ue=pn(j,"USE_PROFILES")?j.USE_PROFILES&&typeof j.USE_PROFILES=="object"?Ln(j.USE_PROFILES):j.USE_PROFILES:!1,Ft=j.ALLOW_ARIA_ATTR!==!1,Nt=j.ALLOW_DATA_ATTR!==!1,Tt=j.ALLOW_UNKNOWN_PROTOCOLS||!1,$t=j.ALLOW_SELF_CLOSE_IN_ATTR!==!1,rt=j.SAFE_FOR_TEMPLATES||!1,Me=j.SAFE_FOR_XML!==!1,et=j.WHOLE_DOCUMENT||!1,Fe=j.RETURN_DOM||!1,Ve=j.RETURN_DOM_FRAGMENT||!1,pt=j.RETURN_TRUSTED_TYPE||!1,G=j.FORCE_BODY||!1,At=j.SANITIZE_DOM!==!1,St=j.SANITIZE_NAMED_PROPS||!1,le=j.KEEP_CONTENT!==!1,Ce=j.IN_PLACE||!1,ye=hH(j.ALLOWED_URI_REGEXP)?j.ALLOWED_URI_REGEXP:my,st=typeof j.NAMESPACE=="string"?j.NAMESPACE:he,q=pn(j,"MATHML_TEXT_INTEGRATION_POINTS")&&j.MATHML_TEXT_INTEGRATION_POINTS&&typeof j.MATHML_TEXT_INTEGRATION_POINTS=="object"?Ln(j.MATHML_TEXT_INTEGRATION_POINTS):vt({},F),me=pn(j,"HTML_INTEGRATION_POINTS")&&j.HTML_INTEGRATION_POINTS&&typeof j.HTML_INTEGRATION_POINTS=="object"?Ln(j.HTML_INTEGRATION_POINTS):vt({},X);const J=pn(j,"CUSTOM_ELEMENT_HANDLING")&&j.CUSTOM_ELEMENT_HANDLING&&typeof j.CUSTOM_ELEMENT_HANDLING=="object"?Ln(j.CUSTOM_ELEMENT_HANDLING):Ka(null);if(fe=Ka(null),pn(J,"tagNameCheck")&&We(J.tagNameCheck)&&(fe.tagNameCheck=J.tagNameCheck),pn(J,"attributeNameCheck")&&We(J.attributeNameCheck)&&(fe.attributeNameCheck=J.attributeNameCheck),pn(J,"allowCustomizedBuiltInElements")&&typeof J.allowCustomizedBuiltInElements=="boolean"&&(fe.allowCustomizedBuiltInElements=J.allowCustomizedBuiltInElements),vn(fe),rt&&(Nt=!1),Ve&&(Fe=!0),Ue&&(Se=vt({},dy),Ae=Ka(null),Ue.html===!0&&(vt(Se,cy),vt(Ae,py)),Ue.svg===!0&&(vt(Se,Oc),vt(Ae,Fc),vt(Ae,Uo)),Ue.svgFilters===!0&&(vt(Se,Lc),vt(Ae,Fc),vt(Ae,Uo)),Ue.mathMl===!0&&(vt(Se,Mc),vt(Ae,fy),vt(Ae,Uo))),it.tagCheck=null,it.attributeCheck=null,pn(j,"ADD_TAGS")&&(typeof j.ADD_TAGS=="function"?it.tagCheck=j.ADD_TAGS:Qr(j.ADD_TAGS)&&(Se===pe&&(Se=Ln(Se)),vt(Se,j.ADD_TAGS,Ie))),pn(j,"ADD_ATTR")&&(typeof j.ADD_ATTR=="function"?it.attributeCheck=j.ADD_ATTR:Qr(j.ADD_ATTR)&&(Ae===He&&(Ae=Ln(Ae)),vt(Ae,j.ADD_ATTR,Ie))),pn(j,"ADD_URI_SAFE_ATTR")&&Qr(j.ADD_URI_SAFE_ATTR)&&vt(tt,j.ADD_URI_SAFE_ATTR,Ie),pn(j,"FORBID_CONTENTS")&&Qr(j.FORBID_CONTENTS)&&(je===Et&&(je=Ln(je)),vt(je,j.FORBID_CONTENTS,Ie)),pn(j,"ADD_FORBID_CONTENTS")&&Qr(j.ADD_FORBID_CONTENTS)&&(je===Et&&(je=Ln(je)),vt(je,j.ADD_FORBID_CONTENTS,Ie)),le&&(Se["#text"]=!0),et&&vt(Se,["html","head","body"]),Se.table&&(vt(Se,["tbody"]),delete Je.tbody),j.TRUSTED_TYPES_POLICY){if(typeof j.TRUSTED_TYPES_POLICY.createHTML!="function")throw ca('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof j.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ca('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const _e=w;w=j.TRUSTED_TYPES_POLICY;try{T=V("")}catch(ze){throw w=_e,ze}}else j.TRUSTED_TYPES_POLICY===null?(w=void 0,T=""):(w===void 0&&(w=H()),w&&typeof T=="string"&&(T=V("")));Tn&&Tn(j),$e=j},yt=vt({},[...Oc,...Lc,...gH]),Jt=vt({},[...Mc,...bH]),en=function(j,J,_e){return J.namespaceURI===he?j==="svg":J.namespaceURI===kt?j==="svg"&&(_e==="annotation-xml"||q[_e]):!!yt[j]},xn=function(j,J,_e){return J.namespaceURI===he?j==="math":J.namespaceURI===se?j==="math"&&me[_e]:!!Jt[j]},Dt=function(j,J,_e){return J.namespaceURI===se&&!me[_e]||J.namespaceURI===kt&&!q[_e]?!1:!Jt[j]&&(ve[j]||!yt[j])},Pn=function(j){let J=y(j);(!J||!J.tagName)&&(J={namespaceURI:st,tagName:"template"});const _e=si(j.tagName),ze=si(J.tagName);return Y[j.namespaceURI]?j.namespaceURI===se?en(_e,J,ze):j.namespaceURI===kt?xn(_e,J,ze):j.namespaceURI===he?Dt(_e,J,ze):!!(Le==="application/xhtml+xml"&&Y[j.namespaceURI]):!1},_n=function(j){$a(t.removed,{element:j});try{y(j).removeChild(j)}catch{if(b(j),!y(j))throw ca("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},$r=function(j){const J=E(j);if(J){const ze=[];Zs(J,lt=>{$a(ze,lt)}),Zs(ze,lt=>{try{b(lt)}catch{}})}const _e=v(j);if(_e)for(let ze=_e.length-1;ze>=0;--ze){const lt=_e[ze],_t=lt&&lt.name;if(typeof _t=="string")try{j.removeAttribute(_t)}catch{}}},kn=function(j,J){try{$a(t.removed,{attribute:J.getAttributeNode(j),from:J})}catch{$a(t.removed,{attribute:null,from:J})}if(J.removeAttribute(j),j==="is")if(Fe||Ve)try{_n(J)}catch{}else try{J.setAttribute(j,"")}catch{}},Xn=function(j){const J=v(j);if(J)for(let _e=J.length-1;_e>=0;--_e){const ze=J[_e],lt=ze&&ze.name;if(!(typeof lt!="string"||Ae[Ie(lt)]))try{j.removeAttribute(lt)}catch{}}},Fs=function(j){const J=[j];for(;J.length>0;){const _e=J.pop();(N?N(_e):_e.nodeType)===yr.element&&Xn(_e);const lt=E(_e);if(lt)for(let _t=lt.length-1;_t>=0;--_t)J.push(lt[_t])}},zr=function(j){let J=null,_e=null;if(G)j="<remove></remove>"+j;else{const _t=iy(j,/^[\r\n\t ]+/);_e=_t&&_t[0]}Le==="application/xhtml+xml"&&st===he&&(j='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+j+"</body></html>");const ze=w?V(j):j;if(st===he)try{J=new d().parseFromString(ze,Le)}catch{}if(!J||!J.documentElement){J=L.createDocument(st,"template",null);try{J.documentElement.innerHTML=Ot?T:ze}catch{}}const lt=J.body||J.documentElement;return j&&_e&&lt.insertBefore(n.createTextNode(_e),lt.childNodes[0]||null),st===he?be.call(J,et?"html":"body")[0]:et?J.documentElement:lt},br=function(j){return te.call(j.ownerDocument||j,j,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},Dr=function(j){return j=Xs(j,ue," "),j=Xs(j,O," "),j=Xs(j,Ne," "),j},Hr=function(j){var J;j.normalize();const _e=te.call(j.ownerDocument||j,j,u.SHOW_TEXT|u.SHOW_COMMENT|u.SHOW_CDATA_SECTION|u.SHOW_PROCESSING_INSTRUCTION,null);let ze=_e.nextNode();for(;ze;)ze.data=Dr(ze.data),ze=_e.nextNode();const lt=(J=j.querySelectorAll)===null||J===void 0?void 0:J.call(j,"template");lt&&Zs(lt,_t=>{Vt(_t.content)&&Hr(_t.content)})},ct=function(j){const J=A?A(j):null;return typeof J!="string"||Ie(J)!=="form"?!1:typeof j.nodeName!="string"||typeof j.textContent!="string"||typeof j.removeChild!="function"||j.attributes!==v(j)||typeof j.removeAttribute!="function"||typeof j.setAttribute!="function"||typeof j.namespaceURI!="string"||typeof j.insertBefore!="function"||typeof j.hasChildNodes!="function"||j.nodeType!==N(j)||j.childNodes!==E(j)},Vt=function(j){if(!N||typeof j!="object"||j===null)return!1;try{return N(j)===yr.documentFragment}catch{return!1}},Qn=function(j){if(!N||typeof j!="object"||j===null)return!1;try{return typeof N(j)=="number"}catch{return!1}};function En(ke,j,J){ke.length!==0&&Zs(ke,_e=>{_e.call(t,j,J,$e)})}const Ht=function(j,J){return!!(Me&&j.hasChildNodes()&&!Qn(j.firstElementChild)&&yn(hy,j.textContent)&&yn(hy,j.innerHTML)||Me&&j.namespaceURI===he&&J==="style"&&Qn(j.firstElementChild)||j.nodeType===yr.processingInstruction||Me&&j.nodeType===yr.comment&&yn(_H,j.data))},Pa=function(j,J){if(!Je[J]&&e0(J)&&(fe.tagNameCheck instanceof RegExp&&yn(fe.tagNameCheck,J)||fe.tagNameCheck instanceof Function&&fe.tagNameCheck(J)))return!1;if(le&&!je[J]){const _e=y(j),ze=E(j);if(ze&&_e){const lt=ze.length;for(let _t=lt-1;_t>=0;--_t){const un=Ce?ze[_t]:f(ze[_t],!0);_e.insertBefore(un,x(j))}}}return _n(j),!0},js=function(j){if(En(ne.beforeSanitizeElements,j,null),ct(j))return _n(j),!0;const J=Ie(A?A(j):j.nodeName);if(En(ne.uponSanitizeElement,j,{tagName:J,allowedTags:Se}),Ht(j,J))return _n(j),!0;if(Je[J]||!(it.tagCheck instanceof Function&&it.tagCheck(J))&&!Se[J])return Pa(j,J);if((N?N(j):j.nodeType)===yr.element&&!Pn(j)||(J==="noscript"||J==="noembed"||J==="noframes")&&yn(kH,j.innerHTML))return _n(j),!0;if(rt&&j.nodeType===yr.text){const ze=Dr(j.textContent);j.textContent!==ze&&($a(t.removed,{element:j.cloneNode()}),j.textContent=ze)}return En(ne.afterSanitizeElements,j,null),!1},go=function(j,J,_e){if(bt[J]||At&&(J==="id"||J==="name")&&(_e in n||_e in Qe))return!1;const ze=Ae[J]||it.attributeCheck instanceof Function&&it.attributeCheck(J,j);if(!(Nt&&yn(de,J))){if(!(Ft&&yn(K,J))){if(ze){if(!tt[J]){if(!yn(ye,Xs(_e,re,""))){if(!((J==="src"||J==="xlink:href"||J==="href")&&j!=="script"&&oy(_e,"data:")===0&&zt[j])){if(!(Tt&&!yn(Ee,Xs(_e,re,"")))){if(_e)return!1}}}}}else if(!(e0(j)&&(fe.tagNameCheck instanceof RegExp&&yn(fe.tagNameCheck,j)||fe.tagNameCheck instanceof Function&&fe.tagNameCheck(j))&&(fe.attributeNameCheck instanceof RegExp&&yn(fe.attributeNameCheck,J)||fe.attributeNameCheck instanceof Function&&fe.attributeNameCheck(J,j))||J==="is"&&fe.allowCustomizedBuiltInElements&&(fe.tagNameCheck instanceof RegExp&&yn(fe.tagNameCheck,_e)||fe.tagNameCheck instanceof Function&&fe.tagNameCheck(_e))))return!1}}return!0},jN=vt({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),e0=function(j){return!jN[si(j)]&&yn(D,j)},PN=function(j,J,_e,ze){if(w&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!_e)switch(p.getAttributeType(j,J)){case"TrustedHTML":return V(ze);case"TrustedScriptURL":return P(ze)}return ze},BN=function(j,J,_e,ze){try{_e?j.setAttributeNS(_e,J,ze):j.setAttribute(J,ze),ct(j)?_n(j):sy(t.removed)}catch{kn(J,j)}},t0=function(j){En(ne.beforeSanitizeAttributes,j,null);const J=j.attributes;if(!J||ct(j))return;const _e={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ae,forceKeepAttr:void 0};let ze=J.length;const lt=Ie(j.nodeName);for(;ze--;){const _t=J[ze],un=_t.name,tn=_t.namespaceURI,Jn=_t.value,lr=Ie(un),Wu=Jn;let Dn=un==="value"?Wu:uH(Wu);if(_e.attrName=lr,_e.attrValue=Dn,_e.keepAttr=!0,_e.forceKeepAttr=void 0,En(ne.uponSanitizeAttribute,j,_e),Dn=_e.attrValue,St&&(lr==="id"||lr==="name")&&oy(Dn,Rt)!==0&&(kn(un,j),Dn=Rt+Dn),Me&&yn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Dn)){kn(un,j);continue}if(lr==="attributename"&&iy(Dn,"href")){kn(un,j);continue}if(!_e.forceKeepAttr){if(!_e.keepAttr){kn(un,j);continue}if(!$t&&yn(CH,Dn)){kn(un,j);continue}if(rt&&(Dn=Dr(Dn)),!go(lt,lr,Dn)){kn(un,j);continue}Dn=PN(lt,lr,tn,Dn),Dn!==Wu&&BN(j,un,tn,Dn)}}En(ne.afterSanitizeAttributes,j,null)},bo=function(j){let J=null;const _e=br(j);for(En(ne.beforeSanitizeShadowDOM,j,null);J=_e.nextNode();)if(En(ne.uponSanitizeShadowNode,J,null),js(J),t0(J),Vt(J.content)&&bo(J.content),(N?N(J):J.nodeType)===yr.element){const lt=S(J);Vt(lt)&&(Gu(lt),bo(lt))}En(ne.afterSanitizeShadowDOM,j,null)},Gu=function(j){const J=[{node:j,shadow:null}];for(;J.length>0;){const _e=J.pop();if(_e.shadow){bo(_e.shadow);continue}const ze=_e.node,_t=(N?N(ze):ze.nodeType)===yr.element,un=E(ze);if(un)for(let tn=un.length-1;tn>=0;--tn)J.push({node:un[tn],shadow:null});if(_t){const tn=A?A(ze):null;if(typeof tn=="string"&&Ie(tn)==="template"){const Jn=ze.content;Vt(Jn)&&J.push({node:Jn,shadow:null})}}if(_t){const tn=S(ze);Vt(tn)&&J.push({node:null,shadow:tn},{node:tn,shadow:null})}}};return t.sanitize=function(ke){let j=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},J=null,_e=null,ze=null,lt=null;if(Ot=!ke,Ot&&(ke="<!-->"),typeof ke!="string"&&!Qn(ke)&&(ke=mH(ke),typeof ke!="string"))throw ca("dirty is not a string, aborting");if(!t.isSupported)return ke;Q?(Se=ce,Ae=Re):xt(j),(ne.uponSanitizeElement.length>0||ne.uponSanitizeAttribute.length>0)&&(Se=Ln(Se)),ne.uponSanitizeAttribute.length>0&&(Ae=Ln(Ae)),t.removed=[];const _t=Ce&&typeof ke!="string"&&Qn(ke);if(_t){const Jn=A?A(ke):ke.nodeName;if(typeof Jn=="string"){const lr=Ie(Jn);if(!Se[lr]||Je[lr])throw ca("root node is forbidden and cannot be sanitized in-place")}if(ct(ke))throw ca("root node is clobbered and cannot be sanitized in-place");try{Gu(ke)}catch(lr){throw $r(ke),lr}}else if(Qn(ke))J=zr("<!---->"),_e=J.ownerDocument.importNode(ke,!0),_e.nodeType===yr.element&&_e.nodeName==="BODY"||_e.nodeName==="HTML"?J=_e:J.appendChild(_e),Gu(_e);else{if(!Fe&&!rt&&!et&&ke.indexOf("<")===-1)return w&&pt?V(ke):ke;if(J=zr(ke),!J)return Fe?null:pt?T:""}J&&G&&_n(J.firstChild);const un=br(_t?ke:J);try{for(;ze=un.nextNode();)js(ze),t0(ze),Vt(ze.content)&&bo(ze.content)}catch(Jn){throw _t&&$r(ke),Jn}if(_t)return Zs(t.removed,Jn=>{Jn.element&&Fs(Jn.element)}),rt&&Hr(ke),ke;if(Fe){if(rt&&Hr(J),Ve)for(lt=ie.call(J.ownerDocument);J.firstChild;)lt.appendChild(J.firstChild);else lt=J;return(Ae.shadowroot||Ae.shadowrootmode)&&(lt=I.call(r,lt,!0)),lt}let tn=et?J.outerHTML:J.innerHTML;return et&&Se["!doctype"]&&J.ownerDocument&&J.ownerDocument.doctype&&J.ownerDocument.doctype.name&&yn(NH,J.ownerDocument.doctype.name)&&(tn="<!DOCTYPE "+J.ownerDocument.doctype.name+`>
172
- `+tn),rt&&(tn=Dr(tn)),w&&pt?V(tn):tn},t.setConfig=function(){let ke=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xt(ke),Q=!0,ce=Se,Re=Ae},t.clearConfig=function(){$e=null,Q=!1,ce=null,Re=null,w=_,T=""},t.isValidAttribute=function(ke,j,J){$e||xt({});const _e=Ie(ke),ze=Ie(j);return go(_e,ze,J)},t.addHook=function(ke,j){typeof j=="function"&&pn(ne,ke)&&$a(ne[ke],j)},t.removeHook=function(ke,j){if(pn(ne,ke)){if(j!==void 0){const J=oH(ne[ke],j);return J===-1?void 0:lH(ne[ke],J,1)[0]}return sy(ne[ke])}},t.removeHooks=function(ke){pn(ne,ke)&&(ne[ke]=[])},t.removeAllHooks=function(){ne=gy()},t}var DH=_w();function OH({code:e}){const t=g.useId().replace(/:/g,""),n=g.useRef(null),[r,a]=g.useState(null),[s,i]=g.useState(!1);return g.useEffect(()=>{let l=!1;return(async()=>{try{const u=(await ww(async()=>{const{default:p}=await import("./mermaid.core.Da03W3iu.js").then(m=>m.bl);return{default:p}},__vite__mapDeps([0,1]))).default;u.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict"});const c=await u.render(`mermaid-${t}`,e),d=DH.sanitize(c.svg,{USE_PROFILES:{svg:!0,svgFilters:!0}});l||a(d)}catch{l||i(!0)}})(),()=>{l=!0}},[e,t]),g.useEffect(()=>{n.current&&(n.current.innerHTML=r??"")},[r]),s?o.jsx("pre",{children:o.jsx("code",{children:e})}):o.jsx("div",{ref:n,className:"mermaid-diagram flex justify-center","data-testid":"mermaid-diagram"})}function LH(e){return(e??"").match(/language-(\w+)/)?.[1]??null}function $d(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map($d).join(""):typeof e=="object"&&"props"in e?$d(e.props.children):""}function MH({className:e,children:t,...n}){return LH(e)==="mermaid"?o.jsx(OH,{code:$d(t).trim()}):o.jsx("code",{className:e,...n,children:t})}function FH({source:e}){return o.jsx(Nl.Markdown,{source:e,wrapperElement:{"data-color-mode":"light"},components:{code:MH}})}function Dl({targetVar:e,onResizeEnd:t,direction:n="horizontal",invert:r=!1}){const a=g.useRef(null),s=g.useCallback(l=>{l.preventDefault();const u=document.documentElement,d=getComputedStyle(u).getPropertyValue(e).trim(),p=parseFloat(d)||0;a.current={x:l.clientX,y:l.clientY,w:p},l.target.setPointerCapture(l.pointerId);const m=b=>{if(!a.current)return;const x=n==="horizontal"?b.clientX-a.current.x:b.clientY-a.current.y,E=r?-x:x,y=Math.max(0,a.current.w+E);u.style.setProperty(e,`${y}px`)},f=()=>{if(!a.current)return;const b=getComputedStyle(u).getPropertyValue(e).trim(),x=parseFloat(b)||a.current.w;t(Math.round(x)),a.current=null,window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",f)};window.addEventListener("pointermove",m),window.addEventListener("pointerup",f,{once:!0})},[e,t,n,r]),i=n==="horizontal";return o.jsx("hr",{"data-testid":`resize-handle-${i?"h":"v"}`,"aria-orientation":i?"vertical":"horizontal","aria-label":i?"Resize sidebar":"Resize panel",tabIndex:0,className:"resize-handle shrink-0 bg-spur-border hover:bg-spur-accent cursor-col-resize transition-colors border-0",style:{width:i?4:"100%",height:i?"100%":4,margin:0},onPointerDown:s})}const by="spur:new-task-panel-width",xy=384,jc=384;function Ey({id:e,label:t,placeholder:n,value:r,mode:a,onChange:s,onModeChange:i,disabled:l}){return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[o.jsxs("label",{htmlFor:e,className:"text-xs font-semibold text-spur-text-muted uppercase tracking-wide",children:[t," ",o.jsx("span",{className:"text-spur-text-muted font-normal",children:"(optional, markdown)"})]}),o.jsxs("fieldset",{className:"flex items-center gap-1",children:[o.jsxs("legend",{className:"sr-only",children:[t," mode"]}),o.jsx(ot,{type:"button",variant:a==="edit"?"primary":"ghost",size:"xs",onClick:()=>i("edit"),disabled:l,"aria-pressed":a==="edit",children:"Edit"}),o.jsx(ot,{type:"button",variant:a==="preview"?"primary":"ghost",size:"xs",onClick:()=>i("preview"),disabled:l,"aria-pressed":a==="preview",children:"Preview"})]})]}),a==="edit"?o.jsx("div",{className:"min-h-40","data-testid":`${e}-editor`,children:o.jsx(Nl,{value:r,onChange:u=>s(u??""),height:160,textareaProps:{id:e,placeholder:n,disabled:l,"aria-label":t},"data-color-mode":"dark"})}):o.jsx("div",{className:"min-h-40 rounded border border-spur-border bg-spur-bg p-3 text-sm text-spur-text overflow-y-auto","data-testid":`${e}-preview`,children:r.trim()?o.jsx(Nl.Markdown,{source:r,"data-color-mode":"dark"}):o.jsx("p",{className:"text-xs text-spur-text-muted",children:n})})]})}function kw({open:e,onClose:t,onCreated:n,folder:r,featureId:a}){const[s,i]=g.useState(""),[l,u]=g.useState(""),[c,d]=g.useState(""),[p,m]=g.useState("edit"),[f,b]=g.useState("edit"),[x,E]=g.useState("standard"),[y,S]=g.useState(!1),[v,N]=g.useState(""),[A,w]=g.useState(!1),[T,_]=g.useState(()=>{if(typeof window>"u")return xy;try{const V=Number.parseFloat(window.localStorage.getItem(by)??"");if(Number.isFinite(V)&&V>0)return Math.max(jc,Math.min(V,window.innerWidth*.9))}catch{}return xy}),B=A&&s.trim()===""?"Name is required":"";g.useEffect(()=>{document.documentElement.style.setProperty("--new-task-panel-w",`${T}px`)},[T]);const k=()=>{y||(i(""),u(""),d(""),m("edit"),b("edit"),E("standard"),N(""),w(!1),t())},$=async()=>{w(!0);const V=s.trim();if(V!==""){S(!0),N("");try{const H=(await rn.task.create({title:V,folder:r,template:x,featureId:a})).data.wbs,W=[];if(l.trim()&&W.push(`### Background
172
+ `+tn),rt&&(tn=Dr(tn)),w&&pt?V(tn):tn},t.setConfig=function(){let ke=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xt(ke),Q=!0,ce=Se,Re=Ae},t.clearConfig=function(){$e=null,Q=!1,ce=null,Re=null,w=_,T=""},t.isValidAttribute=function(ke,j,J){$e||xt({});const _e=Ie(ke),ze=Ie(j);return go(_e,ze,J)},t.addHook=function(ke,j){typeof j=="function"&&pn(ne,ke)&&$a(ne[ke],j)},t.removeHook=function(ke,j){if(pn(ne,ke)){if(j!==void 0){const J=oH(ne[ke],j);return J===-1?void 0:lH(ne[ke],J,1)[0]}return sy(ne[ke])}},t.removeHooks=function(ke){pn(ne,ke)&&(ne[ke]=[])},t.removeAllHooks=function(){ne=gy()},t}var DH=_w();function OH({code:e}){const t=g.useId().replace(/:/g,""),n=g.useRef(null),[r,a]=g.useState(null),[s,i]=g.useState(!1);return g.useEffect(()=>{let l=!1;return(async()=>{try{const u=(await ww(async()=>{const{default:p}=await import("./mermaid.core.Bc4LqQgX.js").then(m=>m.bl);return{default:p}},__vite__mapDeps([0,1]))).default;u.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict"});const c=await u.render(`mermaid-${t}`,e),d=DH.sanitize(c.svg,{USE_PROFILES:{svg:!0,svgFilters:!0}});l||a(d)}catch{l||i(!0)}})(),()=>{l=!0}},[e,t]),g.useEffect(()=>{n.current&&(n.current.innerHTML=r??"")},[r]),s?o.jsx("pre",{children:o.jsx("code",{children:e})}):o.jsx("div",{ref:n,className:"mermaid-diagram flex justify-center","data-testid":"mermaid-diagram"})}function LH(e){return(e??"").match(/language-(\w+)/)?.[1]??null}function $d(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map($d).join(""):typeof e=="object"&&"props"in e?$d(e.props.children):""}function MH({className:e,children:t,...n}){return LH(e)==="mermaid"?o.jsx(OH,{code:$d(t).trim()}):o.jsx("code",{className:e,...n,children:t})}function FH({source:e}){return o.jsx(Nl.Markdown,{source:e,wrapperElement:{"data-color-mode":"light"},components:{code:MH}})}function Dl({targetVar:e,onResizeEnd:t,direction:n="horizontal",invert:r=!1}){const a=g.useRef(null),s=g.useCallback(l=>{l.preventDefault();const u=document.documentElement,d=getComputedStyle(u).getPropertyValue(e).trim(),p=parseFloat(d)||0;a.current={x:l.clientX,y:l.clientY,w:p},l.target.setPointerCapture(l.pointerId);const m=b=>{if(!a.current)return;const x=n==="horizontal"?b.clientX-a.current.x:b.clientY-a.current.y,E=r?-x:x,y=Math.max(0,a.current.w+E);u.style.setProperty(e,`${y}px`)},f=()=>{if(!a.current)return;const b=getComputedStyle(u).getPropertyValue(e).trim(),x=parseFloat(b)||a.current.w;t(Math.round(x)),a.current=null,window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",f)};window.addEventListener("pointermove",m),window.addEventListener("pointerup",f,{once:!0})},[e,t,n,r]),i=n==="horizontal";return o.jsx("hr",{"data-testid":`resize-handle-${i?"h":"v"}`,"aria-orientation":i?"vertical":"horizontal","aria-label":i?"Resize sidebar":"Resize panel",tabIndex:0,className:"resize-handle shrink-0 bg-spur-border hover:bg-spur-accent cursor-col-resize transition-colors border-0",style:{width:i?4:"100%",height:i?"100%":4,margin:0},onPointerDown:s})}const by="spur:new-task-panel-width",xy=384,jc=384;function Ey({id:e,label:t,placeholder:n,value:r,mode:a,onChange:s,onModeChange:i,disabled:l}){return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[o.jsxs("label",{htmlFor:e,className:"text-xs font-semibold text-spur-text-muted uppercase tracking-wide",children:[t," ",o.jsx("span",{className:"text-spur-text-muted font-normal",children:"(optional, markdown)"})]}),o.jsxs("fieldset",{className:"flex items-center gap-1",children:[o.jsxs("legend",{className:"sr-only",children:[t," mode"]}),o.jsx(ot,{type:"button",variant:a==="edit"?"primary":"ghost",size:"xs",onClick:()=>i("edit"),disabled:l,"aria-pressed":a==="edit",children:"Edit"}),o.jsx(ot,{type:"button",variant:a==="preview"?"primary":"ghost",size:"xs",onClick:()=>i("preview"),disabled:l,"aria-pressed":a==="preview",children:"Preview"})]})]}),a==="edit"?o.jsx("div",{className:"min-h-40","data-testid":`${e}-editor`,children:o.jsx(Nl,{value:r,onChange:u=>s(u??""),height:160,textareaProps:{id:e,placeholder:n,disabled:l,"aria-label":t},"data-color-mode":"dark"})}):o.jsx("div",{className:"min-h-40 rounded border border-spur-border bg-spur-bg p-3 text-sm text-spur-text overflow-y-auto","data-testid":`${e}-preview`,children:r.trim()?o.jsx(Nl.Markdown,{source:r,"data-color-mode":"dark"}):o.jsx("p",{className:"text-xs text-spur-text-muted",children:n})})]})}function kw({open:e,onClose:t,onCreated:n,folder:r,featureId:a}){const[s,i]=g.useState(""),[l,u]=g.useState(""),[c,d]=g.useState(""),[p,m]=g.useState("edit"),[f,b]=g.useState("edit"),[x,E]=g.useState("standard"),[y,S]=g.useState(!1),[v,N]=g.useState(""),[A,w]=g.useState(!1),[T,_]=g.useState(()=>{if(typeof window>"u")return xy;try{const V=Number.parseFloat(window.localStorage.getItem(by)??"");if(Number.isFinite(V)&&V>0)return Math.max(jc,Math.min(V,window.innerWidth*.9))}catch{}return xy}),B=A&&s.trim()===""?"Name is required":"";g.useEffect(()=>{document.documentElement.style.setProperty("--new-task-panel-w",`${T}px`)},[T]);const k=()=>{y||(i(""),u(""),d(""),m("edit"),b("edit"),E("standard"),N(""),w(!1),t())},$=async()=>{w(!0);const V=s.trim();if(V!==""){S(!0),N("");try{const H=(await rn.task.create({title:V,folder:r,template:x,featureId:a})).data.wbs,W=[];if(l.trim()&&W.push(`### Background
173
173
  ${l.trim()}`),c.trim()&&W.push(`### Requirements
174
174
  ${c.trim()}`),W.length>0)try{await rn.task.body({wbs:H,body:W.join(`
175
175
 
@@ -180,9 +180,9 @@ ${c.trim()}`),W.length>0)try{await rn.task.body({wbs:H,body:W.join(`
180
180
  `),n=[];let r=0;for(const a of t){const s=`json-line-${r++}-${a.slice(0,16)}`,i=a.split(/("(?:[^"\\]|\\.)*")/g),l=[];let u=0;for(const c of i){const d=`${s}-p-${u++}`;if(c.startsWith('"')&&c.endsWith('"')){const p=a.indexOf(c)<a.indexOf(":")&&a.includes(":");l.push(o.jsx("span",{className:p?"text-sky-300 font-semibold":"text-emerald-400",children:c},d))}else/\b(true|false|null)\b/.test(c)?l.push(o.jsx("span",{className:"text-purple-400",children:c},d)):/\b\d+(\.\d+)?\b/.test(c)?l.push(o.jsx("span",{className:"text-amber-300",children:c},d)):l.push(o.jsx("span",{className:"text-base-content/80",children:c},d))}n.push(o.jsx("div",{className:"leading-5 whitespace-pre",children:l},s))}return n}const gG=e=>{const t=e.split(`
181
181
  `),n=[];let r=0;for(const a of t){const s=`xml-line-${r++}-${a.slice(0,16)}`,i=/(<!--[\s\S]*?-->|<\/?[a-zA-Z0-9_:-]+(?:(?:\s+[a-zA-Z0-9_:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s>]+))?)*\s*\/?>)|&[a-zA-Z0-9#]+;|[^<&]+|<)/g,l=[];let u=0,c=i.exec(a);for(;c!==null;){const d=c[0],p=`${s}-tok-${u++}`;if(d.startsWith("<!--"))l.push(o.jsx("span",{className:"text-base-content/40 italic",children:d},p));else if(d.startsWith("<")&&(d.endsWith(">")||d.length>1)){const m=d.match(/^(<\/?[a-zA-Z0-9_:-]+)([\s\S]*?)(\/?>)$/);if(m?.[1]){const f=m[1],b=m[2]??"",x=m[3]??">",E=[];let y=0;const v=f.startsWith("</")?"</":"<",N=f.slice(v.length);if(E.push(o.jsx("span",{className:"text-sky-400/60 font-mono",children:v},`${p}-bracket-1`),o.jsx("span",{className:"text-sky-300 font-semibold font-mono",children:N},`${p}-name`)),b){const A=/(\s+)([a-zA-Z0-9_:-]+)(?:(=)("[^"]*"|'[^']*'|[^\s>]+))?/g;let w=A.exec(b),T=0;for(;w!==null;){const[_,B,k,$,V]=w;w.index>T&&E.push(o.jsx("span",{children:b.slice(T,w.index)},`${p}-ws-${y++}`)),E.push(o.jsx("span",{children:B},`${p}-attr-ws-${y++}`),o.jsx("span",{className:"text-cyan-300 font-mono",children:k},`${p}-attr-name-${y++}`)),$&&E.push(o.jsx("span",{className:"text-base-content/50",children:"="},`${p}-attr-eq-${y++}`)),V&&E.push(o.jsx("span",{className:"text-emerald-300 font-mono",children:V},`${p}-attr-val-${y++}`)),T=w.index+_.length,w=A.exec(b)}T<b.length&&E.push(o.jsx("span",{children:b.slice(T)},`${p}-attr-rest-${y++}`))}E.push(o.jsx("span",{className:"text-sky-400/60 font-mono",children:x},`${p}-bracket-2`)),l.push(o.jsx("span",{children:E},p))}else l.push(o.jsx("span",{className:"text-sky-300 font-semibold",children:d},p))}else d.startsWith("&")&&d.endsWith(";")?l.push(o.jsx("span",{className:"text-amber-300 font-semibold",children:d},p)):l.push(o.jsx("span",{className:"text-slate-100",children:d},p));c=i.exec(a)}n.push(o.jsx("div",{className:"leading-5",children:l.length>0?l:" "},s))}return n},bG=e=>{const t=e.split(`
182
182
  `),n=[];let r=!1,a=0;for(let s=0;s<t.length;s++){const i=t[s]??"",l=`md-line-${a++}-${i.slice(0,16)}`,u=i.trim();if(u==="---"){r=s===0?!0:!r,n.push(o.jsx("div",{className:"text-purple-400 font-bold leading-5",children:i},l));continue}if(r){const f=i.indexOf(":");if(f>0){const b=i.slice(0,f),x=i.slice(f+1);n.push(o.jsxs("div",{className:"leading-5",children:[o.jsx("span",{className:"text-cyan-300 font-semibold",children:b}),o.jsx("span",{className:"text-base-content/50",children:":"}),o.jsx("span",{className:"text-emerald-300",children:x})]},l));continue}n.push(o.jsx("div",{className:"text-slate-300 leading-5",children:i||" "},l));continue}if(u.startsWith("```")){n.push(o.jsx("div",{className:"text-pink-400 font-mono font-semibold leading-5",children:i},l));continue}if(u.startsWith("#")){n.push(o.jsx("div",{className:"text-sky-300 font-bold leading-5",children:i},l));continue}if(u.startsWith(">")){n.push(o.jsx("div",{className:"text-emerald-300/80 italic pl-1.5 border-l border-emerald-500/40 leading-5",children:i},l));continue}const c=i.match(/^(\s*[-*+]|\s*\d+\.)/);if(c){n.push(o.jsxs("div",{className:"leading-5",children:[o.jsx("span",{className:"text-amber-300 font-semibold",children:c[0]}),o.jsx("span",{className:"text-slate-100",children:i.slice(c[0].length)})]},l));continue}const d=i.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g),p=[];let m=0;for(const f of d){const b=`${l}-p-${m++}`;f.startsWith("`")&&f.endsWith("`")?p.push(o.jsx("span",{className:"text-emerald-300 bg-white/10 px-1 rounded font-mono",children:f},b)):f.startsWith("**")&&f.endsWith("**")?p.push(o.jsx("span",{className:"text-amber-200 font-bold",children:f},b)):f.startsWith("[")&&f.includes("](")&&f.endsWith(")")?p.push(o.jsx("span",{className:"text-sky-400 underline",children:f},b)):p.push(o.jsx("span",{className:"text-slate-100",children:f},b))}n.push(o.jsx("div",{className:"leading-5",children:p.length>0?p:" "},l))}return n};function xG(e,t){if(t&&/^(bash|shell)$/i.test(t.trim()))return"bash";const n=e.trim();return n?n.startsWith("<")&&n.endsWith(">")?"xml":n.startsWith("{")&&n.endsWith("}")?"json":n.split(`
183
- `)[0]?.trim()==="---"?"markdown":"text":"text"}function $c(e,t){if(!e)return null;switch(xG(e,t)){case"bash":return Ml(e);case"xml":return gG(e);case"json":{const r=t?Hw(t):{defaultLanguage:"json"};return qw(e,r)}case"markdown":return bG(e);default:return e}}const EG=({code:e,toolName:t="",language:n,className:r=""})=>{const a=g.useMemo(()=>Hw(t),[t]),s=n??a.defaultLanguage,i=g.useMemo(()=>s==="bash"?Ml(e):s==="diff"?Ww(e):qw(e,a),[e,s,a]);return o.jsx("div",{className:`font-mono text-[11px] select-text cursor-text ${r}`,children:i})},yG=({agentId:e,model:t="—",timestamp:n,tooltipId:r,freshInputTokens:a=0,cacheReadTokens:s=0,outputTokens:i=0,sessionId:l,className:u=""})=>{const[c,d]=g.useState(!1),p=g.useMemo(()=>`agent-badge-tt-${e}-${Math.random().toString(36).slice(2,7)}`,[e]),m=r||p,f=a+s+i;return o.jsxs("div",{className:`relative inline-flex items-center z-30 ${u}`,children:[o.jsx("button",{type:"button","aria-describedby":m,"aria-label":`Coding agent ${e} icon and metadata`,className:"p-1 rounded-md bg-base-300 border border-base-content/15 hover:border-primary text-base-content/80 hover:text-primary transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-primary shrink-0",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),onFocus:()=>d(!0),onBlur:()=>d(!1),onKeyDown:b=>{b.key==="Escape"&&d(!1)},"data-testid":`agent-badge-${m}`,children:o.jsx(_r,{id:e})}),c&&o.jsxs("div",{id:m,role:"tooltip","data-testid":m,className:"absolute left-0 top-full z-50 mt-1.5 w-64 p-3 rounded-xl bg-base-300 border border-base-content/20 shadow-2xl text-[11px] font-mono leading-relaxed pointer-events-none backdrop-blur-md flex flex-col gap-2.5 select-none",children:[o.jsx("div",{className:"flex items-center justify-between border-b border-base-content/10 pb-2",children:o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"p-1 rounded bg-base-200 text-primary shrink-0",children:o.jsx(_r,{id:e})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"font-bold text-base-content uppercase tracking-wider text-[11px]",children:e}),o.jsx("div",{className:"text-[10px] text-base-content/60 truncate",title:t??"",children:t||"—"})]})]})}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-1 text-base-content/80 text-[10.5px]",children:[o.jsx("span",{className:"text-base-content/50",children:"Timestamp:"}),o.jsx("span",{className:"truncate",children:n?mG(n):"—"}),l&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-base-content/50",children:"Session:"}),o.jsx("span",{className:"truncate font-bold text-primary",title:l,children:l.length>16?`${l.slice(0,14)}…`:l})]})]}),o.jsxs("div",{className:"pt-2 border-t border-base-content/10 flex flex-col gap-1 text-[10.5px]",children:[o.jsx("div",{className:"font-bold text-base-content/70 text-[10px] uppercase tracking-wider",children:"Token Breakdown"}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80",children:[o.jsx("span",{className:"text-base-content/50",children:"📥 Fresh input:"}),o.jsx("span",{children:Fr(a)}),o.jsx("span",{className:"text-base-content/50",children:"💾 Cache read:"}),o.jsx("span",{className:"text-cyan-400",children:Fr(s)}),o.jsx("span",{className:"text-base-content/50",children:"📤 Output:"}),o.jsx("span",{children:Fr(i)}),o.jsx("span",{className:"text-base-content/50 border-t border-base-content/10 pt-0.5",children:"⚡ Total load:"}),o.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Fr(f)})]})]})]})]})},Ub=({item:e,categoryColor:t,label:n,badgePrefix:r,size:a="sm",className:s="",testId:i,tooltipId:l,onClick:u})=>{const[c,d]=g.useState(!1),[p,m]=g.useState(!1),[f,b]=g.useState(!1),[x,E]=g.useState(!1),y=g.useRef(null),S=e.category??Gw(e.toolName),v=t??Ll[S]??Ll.other,N=e.seq??e.toolSeq??1,A=l||`tool-tooltip-${N}-${e.toolName}`,w=g.useMemo(()=>{if(!e.argsRaw)return null;try{const te=JSON.parse(e.argsRaw);return JSON.stringify(te,null,2)}catch{return e.argsRaw}},[e.argsRaw]),T=async te=>{if(te.stopPropagation(),!!w)try{await navigator.clipboard.writeText(w),b(!0),setTimeout(()=>b(!1),2e3)}catch{}},_=async te=>{if(te.stopPropagation(),!!e.errorText)try{await navigator.clipboard.writeText(e.errorText),E(!0),setTimeout(()=>E(!1),2e3)}catch{}},B=()=>{y.current&&(clearTimeout(y.current),y.current=null)},k=()=>{B(),d(!0)},$=()=>{p||(B(),y.current=setTimeout(()=>{d(!1)},150))},V=te=>{te.stopPropagation(),m(ie=>!ie),d(!0),u?.(te)},P=c||p,H=e.status==="error",W=a==="xs"?"px-1.5 py-0.2 text-[10px]":a==="md"?"px-2.5 py-1 text-xs":"px-2 py-0.5 text-[11px]",L=n??`${r??""}${e.toolName}`;return o.jsxs("div",{className:`relative inline-flex items-center ${s}`,children:[o.jsx("button",{type:"button","aria-describedby":A,className:`${W} rounded-md font-mono font-bold text-white shrink-0 tracking-wide cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-xs transition-opacity hover:opacity-90`,style:{backgroundColor:v},onClick:V,onMouseEnter:k,onMouseLeave:$,onFocus:()=>{B(),d(!0)},onBlur:()=>{p||d(!1)},onKeyDown:te=>{te.key==="Escape"&&(m(!1),d(!1))},"data-testid":i??`tool-tag-${N}`,children:L}),o.jsxs("div",{id:A,role:"tooltip","data-testid":l??`tool-tooltip-${N}`,"data-inspector-tooltip":"true",className:`absolute left-0 top-full mt-2 z-50 w-[880px] max-w-[95vw] bg-base-300 border border-base-content/20 shadow-2xl rounded-xl p-4 text-xs font-mono text-base-content backdrop-blur-md flex flex-col gap-3 pointer-events-auto select-text cursor-default ${P?"block":"hidden"}`,onMouseEnter:()=>{B(),d(!0)},onMouseLeave:$,onClick:te=>te.stopPropagation(),onKeyDown:te=>{te.key==="Escape"&&(m(!1),d(!1)),te.stopPropagation()},children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-base-content/10 pb-2.5",children:[o.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[o.jsx("span",{className:"px-2.5 py-0.5 rounded-md text-xs font-bold text-white shrink-0 tracking-wide",style:{backgroundColor:v},children:e.toolName}),o.jsxs("span",{className:"text-xs text-base-content/50 font-bold",children:["#",N]}),o.jsxs("span",{className:"text-[11px] text-base-content/60 uppercase tracking-wider",children:["(",S,")"]})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("span",{className:`px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider ${H?"bg-error/20 text-error":"bg-success/20 text-success"}`,children:e.status??"ok"}),p&&o.jsx("button",{type:"button",className:"text-base-content/50 hover:text-base-content text-xs p-1 leading-none rounded hover:bg-base-content/10 cursor-pointer",onClick:te=>{te.stopPropagation(),m(!1),d(!1)},title:"Close tooltip",children:"✕"})]})]}),e.errorText&&o.jsxs("div",{className:"bg-error/10 text-error border border-error/20 rounded-lg p-2.5 text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{className:"font-bold",children:"Execution Error:"}),o.jsx("button",{type:"button",className:"px-1.5 py-0.5 rounded text-[10px] bg-error/20 hover:bg-error/30 transition-colors cursor-pointer",onClick:_,children:x?"✓ Copied":"Copy"})]}),o.jsx("pre",{className:"font-mono text-[11px] whitespace-pre-wrap max-h-36 overflow-y-auto",children:e.errorText})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-[11px] font-semibold text-base-content/70",children:["Arguments (raw)"," ",o.jsx("span",{className:"text-base-content/40 font-normal",children:"(syntax-highlighted)"})]}),w&&o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded text-[10px] font-mono text-base-content/70 hover:text-base-content hover:bg-base-content/10 transition-colors cursor-pointer border border-base-content/10",onClick:T,children:f?"✓ Copied":"Copy"})]}),w?o.jsx("div",{className:"bg-base-100 p-3 rounded-lg text-[11px] font-mono overflow-x-auto max-h-60 border border-base-content/10 whitespace-pre-wrap break-all text-base-content/90 overflow-y-auto",children:o.jsx(EG,{code:w,toolName:e.toolName})}):o.jsxs("div",{className:"p-2.5 bg-base-100/50 rounded-lg text-xs text-base-content/50 italic border border-base-content/10",children:["Raw payload omitted at import; digest available: ",e.argsDigest??"—"]}),e.argsDigest&&e.argsDigest!==e.argsRaw&&o.jsxs("div",{className:"text-[10px] text-base-content/50 truncate mt-0.5",children:[o.jsx("span",{className:"font-semibold",children:"Digest: "}),e.argsDigest]})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-xs font-mono bg-base-200/70 p-2.5 rounded-lg border border-base-content/10",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"DURATION"}),o.jsx("span",{className:"text-[11px]",children:e.durationMs!==null&&e.durationMs!==void 0?`${e.durationMs} ms (${e.durationSource??"measured"})`:`— (${e.durationSource??"unmeasured"})`})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"TIMESTAMP"}),o.jsx("span",{className:"text-[11px] truncate block",children:e.ts??"—"})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"SOURCE / MODEL"}),o.jsxs("span",{className:"text-[11px] truncate block",title:`${e.source??"—"} / ${e.model??"—"}`,children:[e.source??"—"," / ",e.model??"—"]})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"SESSION ID"}),o.jsx("span",{className:"text-[11px] truncate block",title:e.sessionId??"—",children:e.sessionId??"—"})]}),e.callId&&o.jsxs("div",{className:"col-span-2 md:col-span-4",children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"CALL ID"}),o.jsx("span",{className:"text-[11px] truncate block",title:e.callId,children:e.callId})]}),e.tokens&&o.jsxs("div",{className:"col-span-2 md:col-span-4 pt-1 border-t border-base-content/10",children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"TOKEN LOAD (SHARE)"}),o.jsxs("span",{className:"text-[11px]",children:["Billed: ",Fr(e.tokens.billedTokens)," (Fresh:"," ",Fr(e.tokens.freshInputTokens),", Cache:"," ",Fr(e.tokens.cacheReadTokens),", Output:"," ",Fr(e.tokens.outputTokens),")"]})]})]})]})]})},TG=Ub,SG=({calls:e,fromSeq:t=1,toSeq:n=1,toolName:r,sessionId:a,maxVisible:s=12,className:i=""})=>{const[l,u]=g.useState(!1),c=g.useMemo(()=>{if(e&&e.length>0)return e;const m=[],f=Math.max(1,n-t+1);for(let b=0;b<f;b++)m.push({seq:t+b,toolSeq:t+b,toolName:r,sessionId:a,category:Gw(r),status:"ok"});return m},[e,t,n,r,a]),d=l?c:c.slice(0,s),p=c.length-d.length;return o.jsxs("div",{className:`flex flex-wrap items-center gap-1.5 ${i}`,children:[d.map(m=>o.jsx(Ub,{item:m,label:`#${m.seq}`,size:"xs"},`${m.sessionId}-${m.seq}-${m.callId??""}`)),p>0&&o.jsxs("button",{type:"button",className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-base-content/10 text-base-content/70 hover:bg-base-content/20 transition-colors cursor-pointer",onClick:()=>u(!0),children:["+",p," more"]}),l&&c.length>s&&o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-base-content/10 text-base-content/70 hover:bg-base-content/20 transition-colors cursor-pointer",onClick:()=>u(!1),children:"Show less"})]})};function Ny(e){const t=e.toLowerCase();return t.includes("read")||t.includes("view")||t.includes("cat")?"read":t.includes("write")||t.includes("edit")||t.includes("replace")||t.includes("patch")?"write":t.includes("bash")||t.includes("command")||t.includes("exec")||t.includes("terminal")?"bash":t.includes("grep")||t.includes("find")||t.includes("search")||t.includes("glob")?"search":t.includes("mcp")?"mcp":"other"}const Vw=({data:e,loading:t,error:n,cacheHitTrend:r,onSelectSession:a})=>{const[s,i]=g.useState("model"),[l,u]=g.useState("asc"),c=g.useMemo(()=>({"claude-opus-4.6":"#3987e5","claude-sonnet-4.6":"#199e70","gpt-5.6-sol":"#9085e9","grok-4.6":"#d95926",other:"#898781"}),[]),d=g.useMemo(()=>["Speed","Cache Ratio","Reliability","Output Ratio"],[]);if(t)return o.jsxs("div",{className:"flex flex-col items-center justify-center p-20 gap-3",children:[o.jsx("div",{className:"w-9 h-9 rounded-full border-3 border-primary border-t-transparent animate-spin"}),o.jsx("span",{className:"text-xs font-mono text-base-content/60",children:"Analyzing operational insights..."})]});if(n)return o.jsxs("div",{className:"p-5 rounded-xl bg-error/10 border border-error/20 text-error flex items-center gap-3",children:[o.jsx("span",{className:"text-lg",children:"⚠️"}),o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-sm",children:"Failed to load insights"}),o.jsx("p",{className:"text-xs opacity-80",children:n})]})]});if(!e)return null;const{loops:p,cacheWaste:m,heavySessions:f,largestTokenSteps:b,slowSteps:x,modelComparison:E}=e,y=L=>{s===L?u(te=>te==="asc"?"desc":"asc"):(i(L),u(L==="model"?"asc":"desc"))},S=[...E].sort((L,te)=>{const ie=l==="asc"?1:-1;return s==="model"?ie*L.model.localeCompare(te.model):ie*((L[s]??0)-(te[s]??0))}),v=L=>s!==L?o.jsx("span",{className:"opacity-30 ml-1 text-[10px]",children:"↕"}):o.jsx("span",{className:"text-primary ml-1 text-[10px]",children:l==="asc"?"▲":"▼"}),N=Math.max(1,...f.map(L=>L.tokens)),A=Math.max(1,...x.map(L=>L.durationMs??0)),w=p.reduce((L,te)=>L+(te.wastedTokens??0),0),T=m.reduce((L,te)=>L+(te.freshTokens??0),0),_=x[0],B=b[0],k=E.map(L=>L.speedMsMean),$=k.length>0?Math.min(...k):0,V=k.length>0?Math.max(...k):0,P=L=>V===$?100:Math.max(0,Math.min(100,Math.round((V-L)/(V-$)*100))),H=L=>Math.max(0,Math.min(100,Math.round(L*100))),W=E.map(L=>{const te=P(L.speedMsMean),ie=H(L.cacheRatio),be=H(L.reliability),I=H(L.outputRatio*5);return{label:L.model,color:c[L.model]??"#3987e5",values:[te,ie,be,I]}});return o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsxs("div",{className:`rounded-xl p-4 border flex flex-col justify-between transition-all ${p.length>0?"bg-warning/10 border-warning/30 text-warning":"bg-base-200 border-base-content/10"}`,children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Loop Anomalies"}),o.jsx("span",{children:p.length>0?"⚠️":"✓"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsxs("div",{className:"text-xl font-bold font-mono",children:[p.length," ",p.length===1?"incident":"incidents"]}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:p.length>0?`${Be(w)} wasted tokens`:"Clean execution"})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Cache Waste"}),o.jsx("span",{className:"text-cyan-400",children:"⚡"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-error",children:Be(T)}),o.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Across ",m.length," un-cached steps"]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Peak Step Tokens"}),o.jsx("span",{className:"text-primary",children:"📊"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-primary",children:B?Be(B.tokens):"—"}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5 truncate",children:B?`${B.toolName} (#${B.stepIndex})`:"No outlier steps"})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Peak Latency"}),o.jsx("span",{className:"text-amber-400",children:"⏱️"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-amber-400",children:_?.durationMs?ns(_.durationMs):"—"}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5 truncate",children:_?`${_.toolName} (#${_.stepIndex})`:"No slow steps"})]})]})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[o.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col justify-between",children:o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Top Cache-Wasting Incidents"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[m.length," incidents"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Steps that re-sent full context without cache hits"}),o.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3 items-start",children:[(r?.length??0)>1&&o.jsxs("div",{"data-testid":"cache-hit-trend-chart",className:"p-3 bg-base-300/40 rounded-xl border border-base-content/5",children:[o.jsx("div",{className:"text-[10px] font-mono text-base-content/60 uppercase tracking-wider mb-2",children:"Cache Hit Ratio Trend"}),o.jsx(uG,{points:(r??[]).map(L=>({id:L.day,label:L.day.slice(5),v:L.cacheHitRatio})),color:"#22d3ee",height:130})]}),o.jsx("div",{className:"overflow-x-auto w-full",children:m.length>0?o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Session"}),o.jsx("th",{className:"py-1.5 text-right",children:"Fresh Tokens"}),o.jsx("th",{className:"py-1.5 pl-3",children:"Cause"})]})}),o.jsx("tbody",{children:m.map(L=>o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[o.jsx("td",{className:"py-1.5",children:o.jsxs("button",{type:"button",className:"text-primary hover:underline font-mono inline-flex items-center gap-1 cursor-pointer",onClick:()=>a?.(L.sessionId),title:`Jump to session ${L.sessionId}`,children:[o.jsx("span",{children:L.sessionId}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),o.jsx("td",{className:"py-1.5 text-right text-error font-bold whitespace-nowrap",children:Be(L.freshTokens)}),o.jsx("td",{className:"py-1.5 pl-3 text-base-content/70 truncate max-w-[140px]",title:L.reason,children:L.reason})]},`${L.sessionId}-${L.freshTokens}-${L.timestamp}`))})]}):o.jsx("div",{className:"p-6 text-center text-xs font-mono text-base-content/50",children:"✓ No cache-wasting incidents detected"})})]})]})}),o.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col justify-between",children:o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Heaviest Token Sessions"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[f.length," sessions"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Sessions consuming highest billed volume"}),o.jsx("div",{className:"flex flex-col gap-3",children:f.length>0?f.map(L=>o.jsxs("div",{className:"p-3 bg-base-300/40 rounded-xl border border-base-content/5 flex flex-col gap-1.5 hover:bg-base-300/70 transition-colors",children:[o.jsxs("div",{className:"flex justify-between items-center text-xs font-mono",children:[o.jsxs("button",{type:"button",className:"text-primary hover:underline font-bold inline-flex items-center gap-1.5 cursor-pointer text-left",onClick:()=>a?.(L.id,L.source),title:`Jump to session ${L.id}`,children:[o.jsx("span",{children:L.id}),o.jsxs("span",{className:"text-[10px] font-normal px-1.5 py-0.2 rounded bg-base-content/10 text-base-content/70",children:[L.source," · ",L.model]}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]}),o.jsx("span",{className:"font-bold",children:Be(L.tokens)})]}),o.jsx(yi,{value:L.tokens,max:N,color:"#3987e5",height:6})]},L.id)):o.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No heavy sessions recorded in this timeframe"})})]})})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Top Time-Consuming Steps"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[x.length," steps"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Longest tool execution durations"}),o.jsx("div",{className:"overflow-x-auto",children:x.length>0?o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Tool / Step"}),o.jsx("th",{className:"py-1.5",children:"Session"}),o.jsx("th",{className:"py-1.5 text-right",children:"Duration"}),o.jsx("th",{className:"py-1.5 text-right",children:"Tokens"})]})}),o.jsx("tbody",{children:x.map(L=>{const te=Ny(L.toolName),ie=rs[te]??rs.other;return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[o.jsxs("td",{className:"py-1.5 font-bold",children:[o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[11px] border gap-1 mr-1.5 ${ie}`,children:L.toolName}),o.jsxs("span",{className:"text-[10px] text-base-content/50",children:["#",L.stepIndex]})]}),o.jsx("td",{className:"py-1.5",children:o.jsxs("button",{type:"button",className:"text-primary hover:underline inline-flex items-center gap-1 cursor-pointer",onClick:()=>a?.(L.sessionId,L.agent),title:`Jump to session ${L.sessionId}`,children:[o.jsx("span",{children:L.sessionId}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),o.jsx("td",{className:"py-1.5 text-right text-amber-400 font-bold w-24",children:o.jsxs("div",{className:"flex flex-col items-end gap-1",children:[o.jsx("span",{children:ns(L.durationMs??0)}),o.jsx(yi,{value:L.durationMs??0,max:A,color:"#fbbf24",height:4})]})}),o.jsx("td",{className:"py-1.5 text-right tabular-nums",children:Be(L.tokens)})]},`${L.sessionId}-${L.toolName}-${L.stepIndex}`)})})]}):o.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No slow steps recorded"})})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Largest Token Steps"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[b.length," steps"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Single tool calls with highest token load"}),o.jsx("div",{className:"overflow-x-auto",children:b.length>0?o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Tool / Step"}),o.jsx("th",{className:"py-1.5",children:"Session"}),o.jsx("th",{className:"py-1.5",children:"Agent / Model"}),o.jsx("th",{className:"py-1.5 text-right",children:"Tokens"})]})}),o.jsx("tbody",{children:b.map(L=>{const te=Ny(L.toolName),ie=rs[te]??rs.other;return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[o.jsxs("td",{className:"py-1.5 font-bold",children:[o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[11px] border gap-1 mr-1.5 ${ie}`,children:L.toolName}),o.jsxs("span",{className:"text-[10px] text-base-content/50",children:["#",L.stepIndex]})]}),o.jsx("td",{className:"py-1.5",children:o.jsxs("button",{type:"button",className:"text-primary hover:underline inline-flex items-center gap-1 cursor-pointer",onClick:()=>a?.(L.sessionId,L.agent),title:`Jump to session ${L.sessionId}`,children:[o.jsx("span",{children:L.sessionId}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),o.jsx("td",{className:"py-1.5 text-xs text-base-content/70",children:o.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-base-300 text-[11px]",children:[L.agent," · ",L.model]})}),o.jsx("td",{className:"py-1.5 text-right text-primary font-bold tabular-nums",children:Be(L.tokens)})]},`${L.sessionId}-${L.toolName}-${L.stepIndex}`)})})]}):o.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No large token step outliers found"})})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Model Multi-Axis Comparison"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[E.length," models evaluated"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-4",children:"Evaluation across Speed, Cache ratio, Reliability, and Output ratio"}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 items-center",children:[o.jsxs("div",{className:"flex flex-col items-center justify-center p-3 bg-base-300/30 rounded-xl border border-base-content/5",children:[o.jsx(cG,{axes:d,series:W,height:280}),o.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3 mt-3",children:W.map(L=>o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-mono text-base-content/80 px-2 py-0.5 rounded-full bg-base-300 border border-base-content/10",children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:L.color}}),L.label]},L.label))})]}),o.jsx("div",{className:"overflow-x-auto w-full",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsxs("th",{className:"py-2 cursor-pointer select-none hover:text-base-content",onClick:()=>y("model"),children:["Model ",v("model")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("speedMsMean"),children:["Mean Speed (ms) ",v("speedMsMean")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("cacheRatio"),children:["Cache Ratio ",v("cacheRatio")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("reliability"),children:["Reliability ",v("reliability")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("outputRatio"),children:["Output Ratio ",v("outputRatio")]})]})}),o.jsx("tbody",{children:S.map(L=>o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/40 transition-colors",children:[o.jsxs("td",{className:"py-2 font-bold flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0 shadow-xs",style:{background:c[L.model]??"#3987e5"}}),o.jsx("span",{className:"truncate",children:L.model})]}),o.jsx("td",{className:"py-2 text-right font-mono tabular-nums",children:Wt(L.speedMsMean)}),o.jsx("td",{className:"py-2 text-right font-mono tabular-nums text-cyan-400 font-bold",children:ur(L.cacheRatio*100)}),o.jsx("td",{className:`py-2 text-right font-mono tabular-nums font-bold ${L.reliability>=.95?"text-emerald-400":L.reliability>=.8?"text-amber-400":"text-error"}`,children:ur(L.reliability*100)}),o.jsx("td",{className:"py-2 text-right font-mono tabular-nums text-base-content/80",children:ur(L.outputRatio*100)})]},L.model))})]})})]})]}),p.length>0&&o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-warning/30 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-warning text-lg",children:"⚠️"}),o.jsx("h3",{className:"font-bold text-base",children:"Detected Execution Loops (Repeats ≥ 3)"})]}),o.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-xs font-mono font-bold bg-warning/20 text-warning border border-warning/30",children:[p.length," loop ",p.length===1?"pattern":"patterns"," detected"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-4",children:"Identified consecutive identical tool invocations without intervening state changes. Hover or click on any invocation badge to inspect full arguments, duration, and diagnostics."}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:p.map(L=>o.jsxs("div",{className:"p-4 bg-base-300/70 rounded-xl border border-base-content/10 flex flex-col justify-between gap-3 shadow-xs hover:border-warning/40 transition-colors",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-xs font-mono font-bold bg-warning/20 text-warning border border-warning/30",children:[L.tool," × ",L.repeats," repeats"]}),o.jsxs("button",{type:"button",className:"text-xs font-mono text-primary hover:underline cursor-pointer inline-flex items-center gap-1 font-bold",onClick:()=>a?.(L.sessionId),title:"Jump to session in Tool Using & Timeline",children:[L.sessionId," →"]})]}),o.jsxs("div",{className:"font-mono text-xs text-base-content/80 mt-2 p-2 bg-base-200/80 rounded-lg border border-base-content/5 truncate",title:L.argsHint,children:[o.jsx("span",{className:"text-[10px] text-base-content/50 block mb-0.5 uppercase tracking-wider",children:"Argument signature"}),L.argsHint==="74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b"?"empty/unrecorded arguments":L.argsHint]}),o.jsxs("div",{className:"text-[11px] font-mono text-base-content/60 mt-2",children:["Step sequence: #",L.fromSeq," → #",L.toSeq]}),o.jsxs("div",{className:"mt-3 pt-2.5 border-t border-base-content/10",children:[o.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50 mb-1.5",children:"Repeated Invocations (hover/click for details):"}),o.jsx(SG,{calls:L.repeatedCalls,fromSeq:L.fromSeq,toSeq:L.toSeq,toolName:L.tool,sessionId:L.sessionId})]})]}),o.jsxs("div",{className:"flex justify-between items-center text-xs font-mono pt-2 border-t border-base-content/10 bg-base-200/40 -mx-4 -mb-4 p-3 rounded-b-xl",children:[o.jsx("span",{className:"text-base-content/60",children:"Estimated Wasted Tokens:"}),o.jsx("span",{className:"text-error font-bold text-sm",children:Be(L.wastedTokens)})]})]},`${L.tool}-${L.sessionId}-${L.fromSeq}`))})]})]})};function vG(e){const t=e.toLowerCase();return t.includes("read")||t.includes("view")||t.includes("cat")?"read":t.includes("write")||t.includes("edit")||t.includes("replace")||t.includes("patch")?"write":t.includes("bash")||t.includes("command")||t.includes("exec")||t.includes("terminal")?"bash":t.includes("grep")||t.includes("find")||t.includes("search")||t.includes("glob")?"search":t.includes("mcp")?"mcp":"other"}const Yw=({data:e,loading:t,error:n,sortBy:r="start",sortDir:a="desc",page:s=1,pageSize:i=20,onSortChange:l,onPageChange:u,onSelectSession:c})=>{const[d,p]=g.useState(""),[m,f]=g.useState("all");if(t)return o.jsxs("div",{className:"flex flex-col items-center justify-center p-20 gap-3",children:[o.jsx("div",{className:"w-9 h-9 rounded-full border-3 border-primary border-t-transparent animate-spin"}),o.jsx("span",{className:"text-xs font-mono text-base-content/60",children:"Loading session records..."})]});if(n)return o.jsxs("div",{className:"p-5 rounded-xl bg-error/10 border border-error/20 text-error flex items-center gap-3",children:[o.jsx("span",{className:"text-lg",children:"⚠️"}),o.jsxs("div",{children:[o.jsxs("h5",{className:"font-bold text-sm",children:["Failed to load sessions: ",n]}),o.jsx("p",{className:"text-xs opacity-80",children:"Please check your connection and try refreshing."})]})]});if(!e)return null;const{items:b,total:x}=e,E=Math.max(1,Math.ceil(x/i)),y=b.reduce((T,_)=>T+_.billedTokens,0),S=b.reduce((T,_)=>T+_.cacheReadTokens,0),v=b.filter(T=>T.state==="error").length,N=Math.max(1,...b.map(T=>T.billedTokens)),A=b.filter(T=>{if(m!=="all"&&T.state!==m)return!1;if(!d.trim())return!0;const _=d.toLowerCase();return T.id.toLowerCase().includes(_)||T.source.toLowerCase().includes(_)||T.model.toLowerCase().includes(_)||T.topTool.toLowerCase().includes(_)}),w=T=>r!==T?o.jsx("span",{className:"opacity-25 ml-1 text-[10px]",children:"↕"}):o.jsx("span",{className:"ml-1 text-primary font-bold",children:a==="asc"?"▲":"▼"});return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Total Sessions"}),o.jsx("span",{className:"text-primary",children:"📋"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-base-content",children:Wt(x)}),o.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Showing page ",s," of ",E]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Page Billed Tokens"}),o.jsx("span",{className:"text-primary",children:"⚡"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-primary",children:Be(y)}),o.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Across ",b.length," page sessions"]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Page Cache Read"}),o.jsx("span",{className:"text-cyan-400",children:"💾"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-cyan-400",children:Be(S)}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:"Reused context tokens"})]})]}),o.jsxs("div",{className:`rounded-xl p-4 border flex flex-col justify-between transition-all ${v>0?"bg-error/10 border-error/30 text-error":"bg-base-200 border-base-content/10"}`,children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Session Status"}),o.jsx("span",{children:v>0?"⚠️":"✓"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsxs("div",{className:"text-xl font-bold font-mono",children:[b.length-v," OK · ",v," Error"]}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:v===0?"100% successful on page":`${v} failed sessions`})]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 bg-base-200 p-3 rounded-xl border border-base-content/10",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[o.jsx("span",{className:"text-base-content/40 text-xs",children:"🔍"}),o.jsx("input",{type:"text",placeholder:"Filter sessions by ID, model, agent, or tool...",value:d,onChange:T=>p(T.target.value),className:"bg-base-300/60 text-xs font-mono px-3 py-1.5 rounded-lg border border-base-content/10 w-full focus:outline-hidden focus:border-primary placeholder:text-base-content/40"}),d&&o.jsx("button",{type:"button",onClick:()=>p(""),className:"text-xs text-base-content/50 hover:text-base-content cursor-pointer",children:"✕"})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-mono",children:[o.jsx("span",{className:"text-base-content/50 text-[11px] uppercase tracking-wider mr-1",children:"State:"}),["all","ok","error"].map(T=>o.jsx("button",{type:"button",onClick:()=>f(T),className:`px-2.5 py-1 rounded-md text-xs uppercase font-bold transition-colors cursor-pointer ${m===T?"bg-primary text-primary-content shadow-xs":"bg-base-300 text-base-content/70 hover:bg-base-300/80"}`,children:T},T))]})]}),o.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 overflow-hidden",children:o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"bg-base-300/80 text-base-content/70 border-b border-base-content/10 select-none",children:[o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Session ID"}),o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Agent"}),o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Model"}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors whitespace-nowrap",onClick:()=>l?.("start"),children:["Start Time ",w("start")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("duration"),children:["Duration ",w("duration")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("messages"),children:["Msgs ",w("messages")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("toolCalls"),children:["Tools ",w("toolCalls")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("billedTokens"),children:["Billed Tok ",w("billedTokens")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("cacheRead"),children:["Cache Read ",w("cacheRead")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("freshInput"),children:["Fresh Input ",w("freshInput")]}),o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Top Tool"}),o.jsx("th",{className:"p-3 text-center whitespace-nowrap",children:"State"})]})}),o.jsx("tbody",{children:A.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:12,className:"text-center py-12 text-base-content/50",children:"No sessions matching the current filter."})}):A.map(T=>{const _=vG(T.topTool),B=rs[_]??rs.other,k=Math.min(100,Math.round(T.billedTokens/N*100));return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-primary/10 cursor-pointer transition-colors group",onClick:()=>c?.(T.source,T.id),title:"Click to view execution timeline",children:[o.jsx("td",{className:"p-3 font-bold text-primary whitespace-nowrap",children:o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"font-mono text-xs",title:T.id,children:T.id.length>18?`${T.id.slice(0,16)}…`:T.id}),o.jsx("span",{className:"text-[10px] opacity-40 group-hover:opacity-100 transition-opacity",children:"↗"})]})}),o.jsx("td",{className:"p-3 whitespace-nowrap",children:o.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] bg-base-300 border border-base-content/10 font-mono text-base-content",children:[o.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center opacity-80",children:o.jsx(_r,{id:T.source})}),o.jsx("span",{children:T.source})]})}),o.jsx("td",{className:"p-3 text-base-content/80 whitespace-nowrap",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded bg-base-300/60 border border-base-content/5 text-[11px]",children:T.model})}),o.jsx("td",{className:"p-3 font-mono text-xs text-base-content/70 whitespace-nowrap",children:lG(T.start)}),o.jsx("td",{className:"p-3 text-right font-semibold tabular-nums whitespace-nowrap",children:Bw(T.durationMs/6e4)}),o.jsx("td",{className:"p-3 text-right tabular-nums text-base-content/80 whitespace-nowrap",children:Wt(T.messages)}),o.jsx("td",{className:"p-3 text-right tabular-nums text-base-content/80 whitespace-nowrap",children:Wt(T.toolCalls)}),o.jsx("td",{className:"p-3 text-right font-bold text-primary tabular-nums whitespace-nowrap",children:o.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[o.jsx("span",{children:Be(T.billedTokens)}),o.jsx("div",{className:"w-12 bg-base-300 h-1 rounded-full overflow-hidden",children:o.jsx("div",{className:"bg-primary h-full rounded-full",style:{width:`${k}%`}})})]})}),o.jsx("td",{className:"p-3 text-right text-cyan-400 font-bold tabular-nums whitespace-nowrap",children:Be(T.cacheReadTokens)}),o.jsx("td",{className:"p-3 text-right text-base-content/70 tabular-nums whitespace-nowrap",children:Be(T.freshInputTokens)}),o.jsx("td",{className:"p-3 whitespace-nowrap",children:o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] border font-mono ${B}`,children:T.topTool})}),o.jsx("td",{className:"p-3 text-center whitespace-nowrap",children:o.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-mono font-bold border ${T.state==="error"?"bg-error/15 text-error border-error/30":T.state==="running"?"bg-cyan-500/15 text-cyan-400 border-cyan-500/30 animate-pulse":"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"}`,children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current"}),T.state]})})]},`${T.source}:::${T.id}`)})})]})})}),o.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-3 px-2 py-1 text-xs",children:[o.jsxs("span",{className:"text-base-content/70 font-mono text-[11px]",children:["Showing ",(s-1)*i+1,"–",Math.min(s*i,x)," of ",x," sessions"]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("button",{type:"button",className:"px-3 py-1.5 text-xs rounded-lg border border-base-content/20 hover:bg-base-content/10 font-medium disabled:opacity-40 disabled:hover:bg-transparent cursor-pointer transition-colors",disabled:s<=1,onClick:()=>u?.(s-1),children:"« Previous"}),o.jsxs("span",{className:"px-3 py-1.5 text-xs font-mono bg-base-300 rounded-lg border border-base-content/10 text-base-content font-bold",children:[s," / ",E]}),o.jsx("button",{type:"button",className:"px-3 py-1.5 text-xs rounded-lg border border-base-content/20 hover:bg-base-content/10 font-medium disabled:opacity-40 disabled:hover:bg-transparent cursor-pointer transition-colors",disabled:s>=E,onClick:()=>u?.(s+1),children:"Next »"})]})]})]})},Kw=({data:e,loading:t,error:n,onTriggerImport:r})=>{const[a,s]=g.useState(!1),[i,l]=g.useState(null),u=async()=>{s(!0),l("Running import & analytics rollup...");try{const f=await r?.("incremental");l(f?.message??"Import queued.")}catch(f){l(`Import failed: ${f instanceof Error?f.message:String(f)}`)}finally{s(!1)}};if(t)return o.jsx("div",{className:"flex items-center justify-center p-16",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin"})});if(n)return o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:o.jsxs("span",{children:["Failed to load sources registry: ",n]})});if(!e)return null;const{overview:c,agents:d,roots:p}=e,m=d[0]?.heatmapDays.length;return o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col md:flex-row justify-between items-start md:items-center gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xl",children:"🗄️"}),o.jsx("h3",{className:"font-bold text-base",children:"Transcripts Corpus & Ingestion Registry"})]}),o.jsxs("div",{className:"flex flex-wrap gap-4 text-xs font-mono text-base-content/70 mt-1",children:[o.jsxs("span",{children:["Files: ",o.jsx("strong",{className:"text-base-content",children:Wt(c.totalFiles)})]}),o.jsxs("span",{children:["Corpus Size:"," ",o.jsxs("strong",{className:"text-base-content",children:[(c.corpusSizeBytes/(1024*1024)).toFixed(1)," MB"]})]}),o.jsxs("span",{children:["Total Sessions:"," ",o.jsx("strong",{className:"text-base-content",children:Wt(c.totalSessions)})]}),o.jsxs("span",{children:["Coverage:"," ",o.jsxs("strong",{className:"text-base-content",children:[c.dateCoverage.from?.slice(0,10)??"N/A"," →"," ",c.dateCoverage.to?.slice(0,10)??"N/A"]})]}),o.jsxs("span",{children:["Last Import:"," ",o.jsx("strong",{className:"text-base-content",children:c.lastImportedAt?new Date(c.lastImportedAt).toLocaleString():"never imported"})]})]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[o.jsx("button",{type:"button",className:"px-4 py-2 rounded-lg bg-primary text-primary-content font-medium text-xs hover:bg-primary/90 transition-colors disabled:opacity-50",disabled:a,onClick:u,children:a?"Importing...":"🔄 Import & Analyze"}),i&&o.jsx("span",{className:"text-[11px] font-mono text-info","aria-live":"polite",children:i})]})]}),o.jsxs("div",{children:[o.jsxs("h4",{className:"font-bold text-sm mb-3",children:["Agent Activity (",m??"—","-Day Daily Heatmaps)"]}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:d.map(f=>o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 hover:border-base-content/30 transition-all p-4 flex flex-col justify-between gap-3",children:[o.jsxs("div",{className:"flex justify-between items-start",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("button",{type:"button",className:"w-7 h-7 rounded-lg flex items-center justify-center text-white shadow-xs focus:outline-2 focus:outline-offset-2 focus:outline-primary",style:{background:f.color},"aria-label":`${f.name} source metrics`,"aria-describedby":`source-tooltip-${f.id}`,children:o.jsx(_r,{id:f.id})}),o.jsxs("div",{id:`source-tooltip-${f.id}`,role:"tooltip",className:"pointer-events-none absolute z-20 left-0 top-9 w-64 rounded-lg border border-base-content/15 bg-base-100 p-3 text-[11px] font-mono shadow-xl opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:[o.jsxs("div",{className:"mb-2 font-bold text-sm",children:[f.name," Summary"]}),o.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1",children:[o.jsx("span",{className:"text-base-content/60",children:"Imported Files"}),o.jsx("strong",{className:"text-right",children:Wt(f.filesCount)}),o.jsx("span",{className:"text-base-content/60",children:"Sessions"}),o.jsx("strong",{className:"text-right",children:Wt(f.sessionCount)}),o.jsx("span",{className:"text-base-content/60",children:"Total Tokens"}),o.jsx("strong",{className:"text-right",children:Be(f.totalTokens)}),o.jsx("span",{className:"text-base-content/60",children:"Cache Saved"}),o.jsx("strong",{className:"text-right",children:Be(f.cacheSavedTokens)}),o.jsx("span",{className:"text-base-content/60",children:"Tool Calls"}),o.jsx("strong",{className:"text-right",children:Wt(f.toolCalls)}),o.jsx("span",{className:"text-base-content/60",children:"Date Range"}),o.jsxs("strong",{className:"text-right",children:[f.firstDate?.slice(0,10)??"N/A"," →"," ",f.lastDate?.slice(0,10)??"N/A"]})]})]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"font-bold text-sm",children:f.name}),o.jsx("div",{className:"text-[10px] font-mono text-base-content/60",children:f.importPath})]})]}),o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-mono font-bold bg-base-300 border border-base-content/10 text-base-content",children:[Be(f.totalTokens)," tok"]})]}),o.jsxs("div",{className:"bg-base-300/60 p-2 rounded-lg border border-base-content/5",children:[o.jsxs("div",{className:"text-[10px] font-mono text-base-content/50 mb-1 flex justify-between",children:[o.jsxs("span",{children:[m??"—"," days ago"]}),o.jsx("span",{children:"Today"})]}),o.jsx(pG,{days:f.heatmapDays,color:f.color,maxDailyTokens:f.maxDailyTokens})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-2 border-t border-base-content/10 font-mono text-[11px]",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Sessions"}),o.jsx("span",{className:"font-semibold",children:Wt(f.sessionCount)})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Tool Calls"}),o.jsx("span",{className:"font-semibold",children:Wt(f.toolCalls)})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Cache Saved"}),o.jsx("span",{className:"font-semibold text-emerald-400",children:Be(f.cacheSavedTokens)})]})]})]},f.id))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Source Directories & Import Roots"}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Agent"}),o.jsx("th",{className:"py-1.5",children:"Filesystem Path"}),o.jsx("th",{className:"py-1.5",children:"Match Pattern"}),o.jsx("th",{className:"py-1.5 text-right",children:"Files Count"}),o.jsx("th",{className:"py-1.5 text-center",children:"Status"})]})}),o.jsx("tbody",{children:p.map(f=>o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[o.jsx("td",{className:"py-1.5 font-bold",children:f.agentName}),o.jsx("td",{className:"py-1.5 text-base-content/80",children:f.path}),o.jsx("td",{className:"py-1.5 text-base-content/60",children:f.matchPattern}),o.jsx("td",{className:"py-1.5 text-right font-semibold",children:Wt(f.fileCount)}),o.jsx("td",{className:"py-1.5 text-center",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-400 uppercase font-bold",children:f.status})})]},f.agentId))})]})})]})]})},wG=["auto","1m","3m","5m","10m","30m","1h","4h","1d"],da=["#3987e5","#199e70","#d95926","#9085e9","#c98500","#ec4899","#8b5cf6","#06b6d4","#f59e0b","#10b981"],NG=(e,t)=>t===void 0||t===0?null:(e-t)/Math.abs(t)*100,Hd=g.memo(({current:e,previous:t,invert:n=!1})=>{const r=NG(e,t);if(r===null)return o.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});const a=r>=0,s=n?!a:a;return o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold font-mono ${s?"bg-emerald-500/15 text-emerald-400":"bg-error/15 text-error"}`,children:[a?"↑ +":"↓ ",Math.abs(r).toFixed(1),"% vs previous period"]})}),zo=g.memo(({label:e,value:t,sub:n,trend:r,trendColor:a,current:s,previous:i,invert:l,badge:u})=>o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-4",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:e}),u]}),o.jsxs("div",{className:"flex items-end justify-between gap-2 mt-1",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-2xl font-bold font-mono text-primary",children:t}),o.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[o.jsx(Hd,{current:s,previous:i,invert:l}),o.jsx("span",{className:"text-xs text-base-content/60",children:n})]})]}),r.length>1&&o.jsx(zw,{values:r,color:a,width:100,height:34})]})]})),Ho=g.memo(({title:e,description:t,series:n,buckets:r,chartMode:a,onToggleChartMode:s,testId:i})=>{const l=r.length>0&&n.length>0&&r.some(u=>Object.values(u.v).some(c=>c>0));return o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col gap-3 w-full","data-testid":i,children:[o.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-2 pb-2 border-b border-base-content/10",children:[o.jsxs("div",{children:[o.jsxs("h4",{className:"font-bold text-sm text-base-content flex items-center gap-2",children:[e,o.jsxs("span",{className:"text-[11px] font-normal text-base-content/60 font-mono",children:["(",n.length," ",(n.length===1,"tracked"),")"]})]}),o.jsx("p",{className:"text-[11px] text-base-content/60",children:t})]}),o.jsxs("div",{className:"flex items-center gap-1 bg-base-300 p-0.5 rounded-lg text-xs",children:[o.jsx("button",{type:"button","aria-pressed":a==="chart",className:`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${a==="chart"?"bg-base-100 text-base-content font-bold shadow-xs":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>a!=="chart"&&s(),children:"Chart"}),o.jsx("button",{type:"button","aria-pressed":a==="table",className:`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${a==="table"?"bg-base-100 text-base-content font-bold shadow-xs":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>a!=="table"&&s(),children:"Table"})]})]}),o.jsx("div",{className:"min-h-[220px]",children:a==="table"&&r.length>0&&n.length>0?o.jsx("div",{className:"overflow-x-auto max-h-72 overflow-y-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono","data-testid":"summary-bucket-table",children:[o.jsx("thead",{className:"sticky top-0 bg-base-200",children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5 pr-2",children:"Bucket"}),n.map(u=>o.jsx("th",{className:"py-1.5 pr-2 text-right",children:o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx("span",{className:"w-2 h-2 rounded-full inline-block shrink-0",style:{background:u.color}}),u.label]})},u.id)),o.jsx("th",{className:"py-1.5 pr-2 text-right",children:"Total"}),o.jsx("th",{className:"py-1.5 pr-2 text-right",children:"Cache Hit %"}),o.jsx("th",{className:"py-1.5 text-right",children:"Gain Ratio %"})]})}),o.jsx("tbody",{children:r.map(u=>{const c=Object.values(u.v).reduce((d,p)=>d+p,0);return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[o.jsx("td",{className:"py-1.5 pr-2 font-bold",children:Uw(u.id??u.label)}),n.map(d=>o.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums",children:u.v[d.id]!==void 0?Be(u.v[d.id]??0):"—"},d.id)),o.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums font-bold",children:Be(c)}),o.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums text-cyan-400",children:u.lineValue!==void 0?`${u.lineValue.toFixed(1)}%`:"—"}),o.jsx("td",{className:"py-1.5 text-right tabular-nums text-amber-400",children:u.secondLineValue!==void 0?`${u.secondLineValue.toFixed(1)}%`:"—"})]},u.id??u.label)})})]})}):l?o.jsx($w,{buckets:r,series:n,height:220}):r.length>0&&n.length>0?o.jsxs("div",{className:"flex flex-col items-center justify-center h-[220px] text-base-content/50 text-xs font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30 text-center px-4 gap-1",children:[o.jsxs("span",{className:"font-semibold text-base-content/70",children:["No token or call activity recorded for ",e.toLowerCase()," in this time range."]}),o.jsx("span",{className:"text-[11px] text-base-content/40",children:"Activity is unmeasured or zero in this window. Adjust the time range filter or switch to Table view."})]}):o.jsx("div",{className:"flex flex-col items-center justify-center h-[220px] text-base-content/40 text-xs font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30",children:o.jsxs("span",{children:["No ",e.toLowerCase()," activity recorded for this time range."]})})}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1.5 border-t border-base-content/5",children:[n.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(u=>o.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-md bg-base-300/80 border border-base-content/5 gap-1.5 font-mono text-[10px] text-base-content/80",children:[o.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:u.color}}),o.jsx("span",{className:"truncate max-w-[150px]",children:u.label})]},u.id))}),o.jsxs("div",{className:"flex items-center gap-3 text-[10px] font-mono text-base-content/70 ml-auto",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx("span",{className:"w-3 h-0.5 bg-cyan-400 rounded-full inline-block"}),o.jsx("span",{className:"text-cyan-400",children:"Cache Hit %"})]}),o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx("span",{className:"w-3 h-0.5 bg-amber-400 rounded-full inline-block"}),o.jsx("span",{className:"text-amber-400",children:"Gain Ratio %"})]})]})]})]})}),Go=(e,t,n)=>{const r=new Map;e.forEach((s,i)=>{r.set(s.id,{id:s.id,label:s.label||s.id,color:s.color||n[i%n.length]||"#3987e5"})});let a=r.size;for(const s of t)for(const i of Object.keys(s.series))i&&!r.has(i)&&(r.set(i,{id:i,label:i,color:n[a%n.length]||"#3987e5"}),a++);return Array.from(r.values())},Wo=e=>e.map(t=>({id:t.bucketStart,label:Ol(t.bucketStart),v:t.series,lineValue:t.cacheHitRatio,secondLineValue:t.gainRatio})),zc=["#199e70","#3987e5","#d95926","#9085e9","#c98500","#ec4899","#8b5cf6","#06b6d4","#f59e0b","#10b981"],Zw=g.memo(({data:e,loading:t,error:n,dimension:r="model",onDimensionChange:a,bucket:s="auto",onBucketChange:i,loopSummary:l})=>{const[u,c]=g.useState("chart"),[d,p]=g.useState({model:"chart",source:"chart",tool:"chart",skill:"chart"}),m=g.useCallback(()=>p(G=>({...G,model:G.model==="chart"?"table":"chart"})),[]),f=g.useCallback(()=>p(G=>({...G,source:G.source==="chart"?"table":"chart"})),[]),b=g.useCallback(()=>p(G=>({...G,tool:G.tool==="chart"?"table":"chart"})),[]),x=g.useCallback(()=>p(G=>({...G,skill:G.skill==="chart"?"table":"chart"})),[]),E=e?.kpis,y=e?.previousKpis,S=e?.kpiTrend??[],v=e?.timeSeries??[],N=e?.topModels??[],A=e?.topSources??[],w=e?.topTools??[],T=g.useMemo(()=>Math.max(0,...N.map(G=>G.tokens),...A.map(G=>G.tokens)),[N,A]),_=e?.skillsUsed??[],B=e?.skillTimeSeries??[],k=e?.skillBreakdown??{bySkill:[],bySource:[],byInvocationKind:[],trend:[],fresh:!0},$=e?.modelTimeSeries??[],V=e?.sourceTimeSeries??[],P=e?.toolTimeSeries??[],H=e?.cacheEfficiency??{savedTokens:0,hitRatio:0,totalRead:0,bySource:[],byModel:[],byAgentModel:[]},W=y??void 0,L=H.byAgentModel??[],te=g.useMemo(()=>Array.from(new Set(L.map(G=>G.model))),[L]),ie=g.useMemo(()=>Array.from(new Set(L.map(G=>G.source))),[L]),be=g.useMemo(()=>new Map(L.map(G=>[`${G.source}\0${G.model}`,G])),[L]),I=g.useMemo(()=>new Map(A.map(G=>[G.id,G.label])),[A]),ne=g.useMemo(()=>({billed:S.map(G=>G.totalBilledTokens),cacheSaved:S.map(G=>G.cacheSavedTokens),sessions:S.map(G=>G.sessionsCount),toolCalls:S.map(G=>G.toolCallsCount)}),[S]),ue=g.useMemo(()=>w.map(G=>({...G,id:G.id&&G.id.trim()!==""?G.id.trim():"unknown"})),[w]),O=g.useMemo(()=>_.filter(G=>G.id&&G.id.trim()!==""&&G.id!=="unknown"),[_]),Ne=g.useMemo(()=>$&&$.length>0?$:r==="model"?v:[],[$,r,v]),de=g.useMemo(()=>V&&V.length>0?V:r==="source"?v:[],[V,r,v]),K=g.useMemo(()=>P&&P.length>0?P:r==="tool"?v:[],[P,r,v]),Ee=g.useMemo(()=>B&&B.length>0?B:r==="skill"?v:[],[B,r,v]),re=g.useMemo(()=>Go(N,Ne,da),[N,Ne]),D=g.useMemo(()=>Go(A,de,da),[A,de]),ye=g.useMemo(()=>Go(ue.map((G,Fe)=>({id:G.id,label:G.id,color:zc[Fe%zc.length]})),K,zc),[ue,K]),Se=g.useMemo(()=>Go(O,Ee,da),[O,Ee]),pe=g.useMemo(()=>Wo(Ne),[Ne]),Ae=g.useMemo(()=>Wo(de),[de]),He=g.useMemo(()=>Wo(K),[K]),fe=g.useMemo(()=>Wo(Ee),[Ee]),Je=g.useMemo(()=>B.map(G=>({id:G.bucketStart,label:Ol(G.bucketStart),v:G.series})),[B]),bt=g.useMemo(()=>k.trend.map(G=>({id:G.bucketStart,label:Ol(G.bucketStart),v:G.series})),[k.trend]),it=g.useMemo(()=>k.bySkill.map((G,Fe)=>({id:G.skillName,label:G.skillName,color:da[Fe%da.length]||"#3987e5"})),[k.bySkill]),{toolCallTotal:Ft,toolTimeTotal:Nt,toolTokenTotal:Tt,avgBilledPerSession:$t,avgBilledPerCall:rt,prevAvgPerSession:Me,prevAvgPerCall:et,freshInputTokens:Q,outputTokens:ce,skillTokenTotals:Re}=g.useMemo(()=>{const G=ue.reduce((De,tt)=>De+tt.count,0),Fe=ue.reduce((De,tt)=>De+(tt.durationMs??0),0),Ve=ue.reduce((De,tt)=>De+(tt.tokens??0),0),pt=E?.totalBilledTokens??0,At=E?.sessionsCount??0,St=E?.toolCallsCount??0,Rt=At>0?pt/At:0,le=St>0?pt/St:0,Ce=W&&W.sessionsCount>0?W.totalBilledTokens/W.sessionsCount:void 0,Ue=W&&W.toolCallsCount>0?W.totalBilledTokens/W.toolCallsCount:void 0,je=Math.max(0,H.totalRead-H.savedTokens),Et=Math.max(0,pt-je),zt=B.reduce((De,tt)=>{for(const[Xe,kt]of Object.entries(tt.series))De[Xe]=(De[Xe]??0)+kt;return De},{});return{toolCallTotal:G,toolTimeTotal:Fe,toolTokenTotal:Ve,avgBilledPerSession:Rt,avgBilledPerCall:le,prevAvgPerSession:Ce,prevAvgPerCall:Ue,freshInputTokens:je,outputTokens:Et,skillTokenTotals:zt}},[ue,E,W,H,B]);return t?o.jsx("div",{className:"flex items-center justify-center p-16",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin"})}):n?o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:o.jsxs("span",{children:["Failed to load history summary: ",n]})}):!e||!E?null:o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[o.jsx(zo,{label:"Total Billed Tokens",value:Be(E.totalBilledTokens),sub:`Fresh ${Be(Q)} · Output ${Be(ce)}`,trend:ne.billed,trendColor:"#3987e5",current:E.totalBilledTokens,previous:W?.totalBilledTokens}),o.jsx(zo,{label:"Cache-Saved Tokens",value:Be(E.cacheSavedTokens),sub:`Share ${ur(E.cacheSavedPercent)} · Hit ${ur(H.hitRatio)}`,trend:ne.cacheSaved,trendColor:"#22d3ee",current:E.cacheSavedTokens,previous:W?.cacheSavedTokens,badge:o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",children:[E.cacheSavedPercent,"% saved"]})}),o.jsx(zo,{label:"Sessions",value:Wt(E.sessionsCount),sub:`${Wt(E.sessionsCount>0?E.toolCallsCount/E.sessionsCount:0)} calls / session`,trend:ne.sessions,trendColor:"#9085e9",current:E.sessionsCount,previous:W?.sessionsCount}),o.jsx(zo,{label:"Tool Calls",value:Wt(E.toolCallsCount),sub:`${Be(rt)} billed / step`,trend:ne.toolCalls,trendColor:"#c98500",current:E.toolCallsCount,previous:W?.toolCallsCount,badge:o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-mono bg-amber-500/20 text-amber-400 border border-amber-500/30",children:[ur(E.errorRate)," err"]})})]}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-3",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"font-bold text-base text-base-content",children:"Token Activity & Cache Hit Ratio & Gain Ratio"}),o.jsx("p",{className:"text-xs text-base-content/60",children:"4-block breakdown across Model, Source, Tool, and Skill (Stacked token bars with Cache Hit % and Gain Ratio % line overlays)"})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("fieldset",{className:"flex items-center bg-base-300 p-0.5 rounded-lg text-xs border-0",children:[o.jsx("legend",{className:"sr-only",children:"Bucket interval"}),wG.map(G=>o.jsx("button",{type:"button","aria-pressed":s===G,className:`px-2 py-1 rounded font-medium transition-colors ${s===G?"bg-base-100 text-base-content font-bold shadow-sm":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>i?.(G),children:G},G))]}),o.jsx("div",{className:"flex items-center bg-base-300 p-0.5 rounded-lg text-xs",children:["chart","table"].map(G=>o.jsx("button",{type:"button","aria-pressed":u===G,className:`px-2.5 py-1 rounded font-medium transition-colors ${u===G?"bg-base-100 text-base-content font-bold shadow-sm":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>{c(G),p({model:G,source:G,tool:G,skill:G})},children:G==="chart"?"All Charts":"All Tables"},G))})]})]}),o.jsxs("div",{className:"flex flex-col gap-6 w-full",children:[o.jsx(Ho,{title:"By Model",description:"Token load by LLM model with cache hit ratio and gain ratio overlays",series:re,buckets:pe,chartMode:d.model,onToggleChartMode:m,testId:"summary-block-model"}),o.jsx(Ho,{title:"By Source",description:"Token load by agent platform with cache hit ratio and gain ratio overlays",series:D,buckets:Ae,chartMode:d.source,onToggleChartMode:f,testId:"summary-block-source"}),o.jsx(Ho,{title:"By Tool",description:"Token load (or call volume when unmeasured) by tool execution with cache hit ratio and gain ratio overlays",series:ye,buckets:He,chartMode:d.tool,onToggleChartMode:b,testId:"summary-block-tool"}),o.jsx(Ho,{title:"By Skill",description:"Token load by specialized skill with cache hit ratio and gain ratio overlays",series:Se,buckets:fe,chartMode:d.skill,onToggleChartMode:x,testId:"summary-block-skill"})]})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Token by Model"}),o.jsx("div",{className:"flex flex-col gap-3",children:N.map(G=>o.jsx(Ay,{item:G,maxTotal:T},G.id))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Token by Agent Source"}),o.jsx("div",{className:"flex flex-col gap-3",children:A.map(G=>o.jsx(Ay,{item:G,maxTotal:T},G.id))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Cache Efficiency By Agent"}),(H.bySource&&H.bySource.length>0||A.length>0)&&o.jsx(_y,{items:(H.bySource&&H.bySource.length>0?H.bySource:A.map(G=>({source:G.id,sourceName:G.label,color:G.color,hitRatio:H.hitRatio,savedTokens:Math.round(H.savedTokens*(G.share/100)),totalRead:Math.round(H.totalRead*(G.share/100)),billedTokens:G.tokens}))).map(G=>({id:G.source,label:G.sourceName,color:G.color,hitRatio:G.hitRatio,savedTokens:G.savedTokens,totalRead:G.totalRead,billedTokens:G.billedTokens}))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Cache Efficiency By Model"}),H.byModel&&H.byModel.length>0&&o.jsx(_y,{items:H.byModel.map(G=>({id:G.model,label:G.modelName,color:G.color,hitRatio:G.hitRatio,savedTokens:G.savedTokens,totalRead:G.totalRead,billedTokens:G.billedTokens}))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Agent × Model Correlation Matrix"}),te.length>0&&ie.length>0&&o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{className:"text-left pr-2 py-1 text-base-content/60 sticky left-0 bg-base-200 z-10",children:"Model \\ Agent"}),ie.map(G=>o.jsx("th",{className:"px-1 py-1 text-base-content/60 whitespace-nowrap",title:I.get(G)??G,children:I.get(G)??G},G))]})}),o.jsx("tbody",{children:te.map(G=>o.jsxs("tr",{children:[o.jsx("td",{className:"pr-2 py-1 font-bold text-base-content/80 whitespace-nowrap sticky left-0 bg-base-200",children:G}),ie.map(Fe=>{const Ve=be.get(`${Fe}\0${G}`);return o.jsx("td",{className:"p-0.5",children:Ve?o.jsxs("div",{className:"h-8 min-w-[3rem] rounded-md flex items-center justify-center text-[10px] font-bold border border-base-content/10 cursor-default",style:{background:`rgba(6, 182, 212, ${.08+.5*(Ve.hitRatio/100)})`},title:`${Ve.sourceName} × ${Ve.modelName}: ${Ve.hitRatio}% hit · saved ${Be(Ve.savedTokens)} / read ${Be(Ve.totalRead)} / billed ${Be(Ve.billedTokens)}`,children:[Ve.hitRatio,"%"]}):o.jsx("div",{className:"h-8 min-w-[3rem] rounded-md flex items-center justify-center text-[10px] text-base-content/25 bg-base-300/40",children:"—"})},Fe)})]},G))})]})}),o.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono text-base-content/60",children:[o.jsx("span",{children:"0%"}),o.jsx("div",{className:"h-1.5 w-32 rounded-full bg-gradient-to-r from-base-300 to-cyan-400"}),o.jsx("span",{children:"100% cache hit ratio"})]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-2",children:"Top Tools & Error Rates"}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Tool"}),o.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Usage Share"}),o.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Time Share"}),o.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Token Share"}),o.jsx("th",{className:"py-1.5 text-right",children:"Calls"}),o.jsx("th",{className:"py-1.5 text-right",children:"Errors"}),o.jsx("th",{className:"py-1.5 text-right",children:"Error Rate"})]})}),o.jsx("tbody",{children:ue.map(G=>{const Fe=G.usageShare??(Ft>0?Math.round(G.count/Ft*1e3)/10:0),Ve=G.timeShare??(Nt>0?Math.round((G.durationMs??0)/Nt*1e3)/10:0),pt=G.tokenShare??(Tt>0?Math.round((G.tokens??0)/Tt*1e3)/10:0);return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[o.jsx("td",{className:"py-1.5 font-bold",children:G.id}),o.jsx("td",{className:"py-1.5",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-16",children:o.jsx(yi,{value:Fe,max:100,color:"#3987e5"})}),o.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:ur(Fe)})]})}),o.jsx("td",{className:"py-1.5",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-16",children:o.jsx(yi,{value:Ve,max:100,color:"#10b981"})}),o.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:Ve>0?ur(Ve):"—"})]})}),o.jsx("td",{className:"py-1.5",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-16",children:o.jsx(yi,{value:pt,max:100,color:"#f59e0b"})}),o.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:pt>0?ur(pt):"—"})]})}),o.jsx("td",{className:"py-1.5 text-right tabular-nums",children:Wt(G.count)}),o.jsx("td",{className:"py-1.5 text-right tabular-nums",children:G.errors>0?Wt(G.errors):"0"}),o.jsx("td",{className:"py-1.5 text-right",children:o.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${G.errorRate>1?"bg-error/20 text-error font-bold":"bg-base-300 text-base-content/70"}`,children:ur(G.errorRate)})})]},G.id)})})]})})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col gap-4",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Efficiency Stats & Skills"}),o.jsx("div",{children:o.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs font-mono",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Avg Billed / Session"}),o.jsx("span",{className:"font-bold",children:Be($t)}),o.jsx(Hd,{current:$t,previous:Me,invert:!0})]}),o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Avg Billed / Step"}),o.jsx("span",{className:"font-bold",children:Be(rt)}),o.jsx(Hd,{current:rt,previous:et,invert:!0})]}),o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Loop Detection Findings"}),o.jsxs("span",{className:"font-bold",children:[Wt(l?.redundantCalls??0)," redundant"]}),o.jsxs("span",{className:"text-[10px] text-base-content/60",children:[Be(l?.wastedTokens??0)," wasted"]})]})]})}),_.length>0&&o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2",children:"Skills Invocation Mix"}),o.jsx(Ty,{buckets:Je,series:AG(_),height:150}),o.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:_.map(G=>o.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full bg-base-300 border border-base-content/10 gap-1.5 font-mono text-[11px]",children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:G.color}}),o.jsxs("span",{children:[G.label,":"]}),o.jsxs("span",{className:"font-bold",children:[Be(Re[G.id]??0)," tokens"]})]},G.id))})]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col gap-4","data-testid":"summary-skill-breakdown",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-bold text-sm mb-1",children:"Skill Load Breakdown"}),o.jsx("p",{className:"text-[11px] text-base-content/60",children:"Skill invocations by name, agent, and invocation kind over the selected window."})]}),k.fresh===!1?o.jsx("div",{className:"flex flex-col items-center justify-center text-[11px] text-base-content/40 font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30 py-6",children:o.jsx("span",{children:"Skill rollup not yet built — run history analyze to populate this section."})}):k.bySkill.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-xs font-mono",children:[o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"Top Skills"}),o.jsx("div",{className:"flex flex-col gap-1.5",children:k.bySkill.map((G,Fe)=>o.jsxs("div",{className:"flex justify-between items-center gap-2",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:da[Fe%da.length]??"#3987e5"}}),G.skillName]}),o.jsx("span",{className:"font-bold tabular-nums",children:Wt(G.calls)})]},G.skillName))})]}),o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"By Agent"}),o.jsx("div",{className:"flex flex-col gap-1.5",children:k.bySource.map(G=>o.jsxs("div",{className:"flex justify-between items-center gap-2",children:[o.jsx("span",{children:G.source}),o.jsx("span",{className:"font-bold tabular-nums",children:Wt(G.calls)})]},G.source))})]}),o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"By Invocation Kind"}),o.jsx("div",{className:"flex flex-col gap-1.5",children:k.byInvocationKind.map(G=>o.jsxs("div",{className:"flex justify-between items-center gap-2",children:[o.jsx("span",{className:"capitalize",children:G.invocationKind}),o.jsx("span",{className:"font-bold tabular-nums",children:Wt(G.calls)})]},G.invocationKind))})]})]}),bt.length>0&&o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"Skill Call Trend"}),o.jsx(Ty,{buckets:bt,series:it,height:150})]})]}):o.jsx("div",{className:"flex flex-col items-center justify-center text-[11px] text-base-content/40 font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30 py-6",children:o.jsx("span",{children:"No skill activity recorded for this window."})})]})]})}),AG=e=>e.map(t=>({id:t.id,label:t.label,color:t.color})),Ay=g.memo(({item:e,maxTotal:t})=>{const n=e.freshInputTokens??(e.outputTokens?e.tokens-e.outputTokens:e.tokens),r=e.cacheReadTokens??0,a=e.outputTokens??0,s=t>0?t:1,i=l=>`${Math.round(l/s*1e3)/10}%`;return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex justify-between text-xs font-mono",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:e.color}}),e.label]}),o.jsx("span",{children:Be(e.tokens)})]}),o.jsxs("div",{className:"w-full bg-base-300 h-3 rounded-full overflow-hidden flex",children:[n>0&&o.jsx("div",{className:"h-full",style:{width:i(n),background:"#3987e5"}}),a>0&&o.jsx("div",{className:"h-full",style:{width:i(a),background:"#f59e0b"}})]}),o.jsxs("div",{className:"flex justify-between text-[10px] text-base-content/60 font-mono",children:[o.jsxs("span",{children:["Fresh ",Be(n)," · Cached ",Be(r)," · Output ",Be(a)]}),o.jsxs("span",{children:["Total ",Be(n+r+a)]})]})]})}),_y=g.memo(({items:e})=>o.jsx("div",{className:"flex flex-col gap-2",children:e.map(t=>o.jsxs("div",{className:"flex flex-col gap-1 bg-base-300/40 p-2.5 rounded-lg border border-base-content/5",children:[o.jsxs("div",{className:"flex justify-between items-center text-xs",children:[o.jsxs("span",{className:"flex items-center gap-1.5 font-medium",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:t.color}}),t.label]}),o.jsxs("span",{className:"font-mono font-bold text-cyan-400",children:[t.hitRatio,"%"]})]}),o.jsx("div",{className:"w-full bg-base-100 h-1.5 rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full rounded-full",style:{width:`${t.hitRatio}%`,background:t.color}})}),o.jsxs("div",{className:"flex justify-between text-[10px] text-base-content/60 font-mono",children:[o.jsxs("span",{children:["Saved: ",Be(t.savedTokens)]}),o.jsxs("span",{children:["Total Read: ",Be(t.totalRead)," · Billed: ",Be(t.billedTokens)]})]})]},t.id))})),_G=({blocks:e,start:t,end:n,onJumpToTime:r})=>{const a=g.useId(),{bins:s,maxBinTokens:i,maxBinOperations:l,startMs:u,endMs:c,hasValidRange:d}=g.useMemo(()=>{if(!t||!n||e.length===0)return{bins:[],maxBinTokens:0,maxBinOperations:0,startMs:0,endMs:0,hasValidRange:!1};const p=Date.parse(t),m=Date.parse(n);if(Number.isNaN(p)||Number.isNaN(m)||m<p)return{bins:[],maxBinTokens:0,maxBinOperations:0,startMs:0,endMs:0,hasValidRange:!1};const f=96,x=Math.max(1,m-p)/f,E=Array.from({length:f},(v,N)=>({index:N,timeMs:p+N*x,tokens:0,operations:0}));for(const v of e){if(!v.timestamp)continue;const N=Date.parse(v.timestamp);if(Number.isNaN(N)||N<p||N>m)continue;const A=Math.min(f-1,Math.max(0,Math.floor((N-p)/x))),w=E[A];w&&(w.tokens+=v.totalTokens,w.operations+=v.operationCount)}const y=Math.max(1,...E.map(v=>v.tokens)),S=Math.max(1,...E.map(v=>v.operations));return{bins:E,maxBinTokens:y,maxBinOperations:S,startMs:p,endMs:m,hasValidRange:!0}},[e,t,n]);return!d||s.length===0?null:o.jsxs("div",{"data-testid":"timeline-scrubber",className:"flex flex-col gap-1.5 p-3 bg-base-200/80 rounded-xl border border-base-content/10 font-mono text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-base-content/60 px-1",children:[o.jsxs("span",{children:["Timeline Activity (",s.length," bins)"]}),o.jsxs("span",{children:["Peak: ",Be(i)]})]}),o.jsx("div",{className:"relative h-10 w-full bg-base-300/60 rounded-lg overflow-hidden flex items-end p-1",children:o.jsx("svg",{viewBox:"0 0 96 32",preserveAspectRatio:"none",className:"w-full h-full text-primary/70","aria-hidden":"true",children:s.map(p=>{const m=p.operations>0?Math.max(2,Math.round(p.operations/l*30)):0,f=p.tokens>0?.35+p.tokens/i*.65:.25,b=32-m;return o.jsx("rect",{x:p.index,y:b,width:"0.85",height:m,fill:"currentColor",fillOpacity:f,"data-operations":p.operations,"data-tokens":p.tokens,className:"hover:text-cyan-400 transition-colors",children:o.jsx("title",{children:`${new Date(p.timeMs).toISOString()} · ${Be(p.tokens)} · ${p.operations} ops`})},p.index)})})}),o.jsx("label",{htmlFor:a,className:"sr-only",children:"Timeline scrub slider"}),o.jsx("input",{id:a,type:"range",min:u,max:c,defaultValue:u,"aria-label":"Timeline navigation scrubber","data-testid":"timeline-scrubber-range",className:"w-full range range-xs range-primary cursor-pointer accent-primary",onInput:p=>{const m=Number(p.currentTarget.value);Number.isFinite(m)&&r?.(new Date(m).toISOString())}})]})},za=(e,t)=>`${e}:${t}`,Ha=(e,t)=>JSON.stringify([e,t]),pa=e=>e.replace(/[^a-zA-Z0-9_-]/g,"-"),Fl=(e,t,n)=>e+t+n,kG=(e,t)=>{const n=e+t;return n>0?t/n*100:0},Gd=e=>e.length<=12?e:`${e.slice(0,8)}…${e.slice(-4)}`,CG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Xw=e=>{if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=CG[t.getUTCMonth()],r=t.getUTCDate(),a=String(t.getUTCHours()).padStart(2,"0"),s=String(t.getUTCMinutes()).padStart(2,"0");return`${n} ${r} ${a}:${s}`},Wd=e=>{if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return e.slice(11,19)||e;const n=String(t.getUTCHours()).padStart(2,"0"),r=String(t.getUTCMinutes()).padStart(2,"0"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}:${r}:${a}`},ky=e=>`${Gd(e.id)} · ${e.source} · ${Xw(e.start)} · ${Be(e.tokenLoad)}`,IG=e=>{const t=e.payload?.trim();return t&&t.length>0?t:e.title},Cy=e=>e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)??e,Iy=e=>e.kind==="assistant"||e.eventType==="message"&&e.kind!=="user",RG=e=>{const t=(e.toolName||e.kind||"").toLowerCase();return t.includes("glob")?{label:e.toolName||"glob",color:"#6366f1"}:t.includes("grep")?{label:e.toolName||"grep",color:"#a855f7"}:t.includes("edit")||t.includes("write")||t.includes("patch")?{label:e.toolName||"edit",color:"#eab308"}:t.includes("read")||t.includes("view")||t.includes("list")?{label:e.toolName||"read",color:"#10b981"}:t.includes("bash")||t.includes("exec")||t.includes("command")||t.includes("terminal")?{label:e.toolName||"bash",color:"#3b82f6"}:t.includes("search")||t.includes("find")?{label:e.toolName||"search",color:"#a855f7"}:t.includes("run")?{label:e.toolName||"run",color:"#f59e0b"}:{label:e.toolName||e.kind,color:"#64748b"}},DG=()=>o.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":"User icon",children:[o.jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),o.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),OG=({promptTokens:e,fullText:t,tooltipId:n})=>{const[r,a]=g.useState(!1),s=e?.freshInputTokens??0,i=e?.cacheReadTokens??0,l=e?.outputTokens??0,u=Fl(s,i,l),c=t.length>0?t.split(/\r?\n/).length:0,d=t.length;return o.jsxs("div",{className:"relative inline-flex items-center z-20",children:[o.jsx("button",{type:"button","aria-label":"Show user prompt token breakdown","aria-describedby":n,"data-testid":`timeline-user-badge-${n}`,className:"p-1 rounded bg-base-300 text-cyan-400 shrink-0 hover:bg-base-content/10 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary transition-colors cursor-pointer",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onFocus:()=>a(!0),onBlur:()=>a(!1),onKeyDown:p=>{p.key==="Escape"&&a(!1)},children:o.jsx(DG,{})}),o.jsxs("div",{id:n,role:"tooltip","data-testid":n,className:`absolute left-0 top-full z-50 mt-1.5 w-56 p-2 rounded-lg bg-base-300 border border-base-content/20 shadow-2xl text-[11px] font-mono leading-relaxed pointer-events-none ${r?"block":"hidden"}`,children:[o.jsx("div",{className:"font-bold text-base-content mb-1",children:"User Prompt Telemetry"}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80",children:[o.jsx("span",{className:"text-base-content/60",children:"Lines / chars:"}),o.jsxs("span",{children:[c," lines (",d," chars)"]}),o.jsx("span",{className:"text-base-content/60",children:"📥 Fresh input:"}),o.jsx("span",{children:Be(s)}),o.jsx("span",{className:"text-base-content/60",children:"💾 Cache read:"}),o.jsx("span",{className:"text-cyan-400",children:Be(i)}),o.jsx("span",{className:"text-base-content/60",children:"📤 Output:"}),o.jsx("span",{children:Be(l)}),o.jsx("span",{className:"text-base-content/60 border-t border-base-content/10 pt-0.5",children:"⚡ Turn load:"}),o.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Be(u)})]})]})]})},Ry=({agentId:e,model:t,timestamp:n,tooltipId:r,freshInputTokens:a=0,cacheReadTokens:s=0,outputTokens:i=0,sessionId:l})=>{const[u,c]=g.useState(!1),d=Fl(a,s,i);return o.jsxs("div",{className:"relative inline-flex items-center z-20",children:[o.jsx("button",{type:"button","aria-label":`Show ${e} metadata and token breakdown`,"aria-describedby":r,"data-testid":`timeline-agent-badge-${r}`,className:"inline-flex items-center justify-center p-1 rounded hover:bg-base-content/10 text-base-content focus:outline-none focus-visible:ring-1 focus-visible:ring-primary transition-colors cursor-pointer",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>c(!0),onBlur:()=>c(!1),onKeyDown:p=>{p.key==="Escape"&&c(!1)},children:o.jsx(_r,{id:e})}),o.jsxs("div",{id:r,role:"tooltip","data-testid":r,className:`absolute left-0 top-full z-50 mt-1.5 w-60 p-2.5 rounded-xl bg-base-300 border border-base-content/20 shadow-2xl text-[11px] font-mono leading-relaxed pointer-events-none ${u?"block":"hidden"}`,children:[o.jsxs("div",{className:"font-bold text-base-content mb-1.5 flex items-center gap-1.5 border-b border-base-content/10 pb-1",children:[o.jsx(_r,{id:e}),o.jsx("span",{className:"uppercase",children:e}),o.jsxs("span",{className:"text-base-content/50 font-normal truncate",children:["(",t,")"]})]}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80 text-[10.5px]",children:[o.jsx("span",{className:"text-base-content/60",children:"Timestamp:"}),o.jsx("span",{className:"truncate",children:Wd(n)}),l&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-base-content/60",children:"Session:"}),o.jsx("span",{className:"truncate font-bold text-primary",children:l})]})]}),o.jsxs("div",{className:"mt-1.5 pt-1.5 border-t border-base-content/10",children:[o.jsx("div",{className:"font-bold text-base-content/70 text-[10px] uppercase tracking-wider mb-0.5",children:"Token Breakdown"}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80 text-[10.5px]",children:[o.jsx("span",{className:"text-base-content/60",children:"📥 Fresh input:"}),o.jsx("span",{children:Be(a)}),o.jsx("span",{className:"text-base-content/60",children:"💾 Cache read:"}),o.jsx("span",{className:"text-cyan-400",children:Be(s)}),o.jsx("span",{className:"text-base-content/60",children:"📤 Output:"}),o.jsx("span",{children:Be(i)}),o.jsx("span",{className:"text-base-content/60 border-t border-base-content/10 pt-0.5",children:"⚡ Total:"}),o.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Be(d)})]})]})]})]})},Qw=({data:e,loading:t,error:n,mode:r="session",sessionId:a,availableSessions:s=[],onSelectSession:i,onModeChange:l,consolidatedTaskWbs:u="",consolidatedRunId:c="",onConsolidatedScopeSubmit:d})=>{const p=e?.scope.sessionId,m=e?.scope.source,[f,b]=g.useState({}),[x,E]=g.useState(!0),[y,S]=g.useState(!0),[v,N]=g.useState(!0),[A,w]=g.useState(u),[T,_]=g.useState(c),B=p&&m?Ha(m,p):"consolidated",k=f[B]||{},$=K=>{b(Ee=>({...Ee,[B]:K(Ee[B]||{})}))},V=(K,Ee)=>{const re=za(K,Ee);$(D=>({...D,[re]:!D[re]}))};if(t)return o.jsx("div",{className:"flex items-center justify-center p-16",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin motion-reduce:animate-none"})});if(n)return o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:o.jsxs("span",{children:["Failed to load timeline: ",n]})});if(!e)return o.jsx("div",{className:"p-4 rounded-lg bg-info/10 border border-info/20 text-info",children:o.jsx("span",{children:"No timeline data available."})});const{scope:P,blocks:H,truncated:W}=e,L=Fl(P.tokens.freshInputTokens,P.tokens.cacheReadTokens,P.tokens.outputTokens),te=kG(P.tokens.freshInputTokens,P.tokens.cacheReadTokens),ie=H.map(K=>{const Ee=K.events.filter(re=>Iy(re)?!x:re.kind==="unknown"||re.agent==="unknown"?!y:!(v&&!re.payload?.trim()&&(re.durationMs===null||re.durationMs===0)&&Fl(re.freshInputTokens,re.cacheReadTokens,re.outputTokens)===0));return{...K,events:Ee}}).filter(K=>K.events.length>0),be=ie.flatMap(K=>K.events.filter(Ee=>!!Ee.payload?.trim()).map(Ee=>za(K.key,Ee.seq))),I=be.length>0&&be.every(K=>k[K]),ne=()=>$(()=>I?{}:Object.fromEntries(be.map(K=>[K,!0]))),ue=s.findIndex(K=>K.id===P.sessionId&&K.source===P.source),O=ue>0?s[ue-1]:void 0,Ne=ue>=0&&ue<s.length-1?s[ue+1]:void 0,de=K=>{const Ee=Date.parse(K),re=ie.find(D=>{const ye=D.timestamp?Date.parse(D.timestamp):Number.NaN;return Number.isFinite(ye)&&ye>=Ee})??ie.at(-1);re&&document.getElementById(`timeline-block-${pa(re.key)}`)?.scrollIntoView({behavior:"smooth",block:"center"})};return o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsx("h3",{className:"text-base font-bold tracking-tight",children:"Conversation"}),o.jsxs("fieldset",{className:"inline-flex border border-base-content/20 rounded-lg p-0.5 bg-base-300 font-mono text-xs",children:[o.jsx("legend",{className:"sr-only",children:"Timeline mode"}),o.jsx("button",{type:"button","data-testid":"timeline-mode-session","aria-pressed":r==="session",className:`px-3 py-1 font-bold rounded-md transition-all cursor-pointer ${r==="session"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content"}`,onClick:()=>l?.("session"),children:"Single Session"}),o.jsx("button",{type:"button","data-testid":"timeline-mode-consolidated","aria-pressed":r==="consolidated",className:`px-3 py-1 font-bold rounded-md transition-all cursor-pointer ${r==="consolidated"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content"}`,onClick:()=>l?.("consolidated"),children:"Consolidated"})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3",children:[r==="session"?o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"sr-only",children:"Session"}),o.jsx("select",{"aria-label":"Select Session","data-testid":"timeline-session-select",className:"px-3 py-1.5 min-h-[44px] text-xs rounded-lg border border-base-content/20 bg-base-300 font-mono text-base-content max-w-xs focus:outline-hidden focus:border-primary cursor-pointer",value:P.source&&P.sessionId?Ha(P.source,P.sessionId):"",onChange:K=>{const Ee=s.find(re=>Ha(re.source,re.id)===K.target.value);Ee&&i?.(Ee.source,Ee.id)},children:s.length>0?s.map(K=>o.jsx("option",{value:Ha(K.source,K.id),children:ky(K)},Ha(K.source,K.id))):o.jsx("option",{value:P.source&&P.sessionId?Ha(P.source,P.sessionId):"",children:P.sessionId?ky({id:P.sessionId,source:P.source??"unknown",start:P.start??"",tokenLoad:L}):"No session selected"})})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{type:"button","aria-label":"Previous session",disabled:!O,className:"px-3 py-2 min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-xs font-mono rounded-lg border border-base-content/20 bg-base-300 text-base-content/80 disabled:opacity-40 disabled:cursor-not-allowed hover:bg-base-content/10 transition-colors focus-visible:ring-2 focus-visible:ring-primary cursor-pointer",onClick:()=>O&&i?.(O.source,O.id),children:"←"}),o.jsx("button",{type:"button","aria-label":"Next session",disabled:!Ne,className:"px-3 py-2 min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-xs font-mono rounded-lg border border-base-content/20 bg-base-300 text-base-content/80 disabled:opacity-40 disabled:cursor-not-allowed hover:bg-base-content/10 transition-colors focus-visible:ring-2 focus-visible:ring-primary cursor-pointer",onClick:()=>Ne&&i?.(Ne.source,Ne.id),children:"→"})]})]}):o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-lg bg-base-300 border border-base-content/20 text-xs font-mono",children:[o.jsx("span",{className:"text-base-content/60",children:"Scope:"}),o.jsxs("span",{className:"font-semibold text-primary",children:[P.sessionCount," sessions"]})]}),o.jsxs("form",{className:"flex flex-wrap items-end gap-2",onSubmit:K=>{K.preventDefault(),d?.({taskWbs:A.trim(),runId:T.trim()})},children:[o.jsxs("label",{className:"flex flex-col gap-1 text-[10px] font-mono text-base-content/60",children:["Task WBS",o.jsx("input",{type:"text",value:A,onInput:K=>w(K.currentTarget.value),className:"min-h-[44px] w-28 rounded-lg border border-base-content/20 bg-base-300 px-2 text-xs text-base-content focus:outline-hidden focus:border-primary"})]}),o.jsxs("label",{className:"flex flex-col gap-1 text-[10px] font-mono text-base-content/60",children:["Run ID",o.jsx("input",{type:"text",value:T,onInput:K=>_(K.currentTarget.value),className:"min-h-[44px] w-40 rounded-lg border border-base-content/20 bg-base-300 px-2 text-xs text-base-content focus:outline-hidden focus:border-primary"})]}),o.jsx("button",{type:"submit",className:"min-h-[44px] rounded-lg bg-primary px-3 text-xs font-semibold text-primary-content focus-visible:ring-2 focus-visible:ring-primary cursor-pointer hover:bg-primary/90 transition-colors",children:"Apply scope"})]})]}),o.jsx("button",{type:"button","aria-pressed":I,disabled:be.length===0,className:"px-3.5 py-2 min-h-[44px] rounded-lg text-xs font-semibold border border-primary/30 text-primary hover:bg-primary/10 disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:ring-2 focus-visible:ring-primary cursor-pointer",onClick:ne,children:I?"Collapse all":"Expand all"}),o.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs font-mono text-base-content/80",children:[o.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox","data-testid":"timeline-filter-assistant",className:"w-3.5 h-3.5 rounded border border-base-content/30 accent-primary focus-visible:ring-1 focus-visible:ring-primary",checked:x,onChange:K=>E(K.target.checked)}),o.jsx("span",{children:"Hide assistant"})]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox","data-testid":"timeline-filter-unknown",className:"w-3.5 h-3.5 rounded border border-base-content/30 accent-primary focus-visible:ring-1 focus-visible:ring-primary",checked:y,onChange:K=>S(K.target.checked)}),o.jsx("span",{children:"Hide unknown"})]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox","data-testid":"timeline-filter-empty",className:"w-3.5 h-3.5 rounded border border-base-content/30 accent-primary focus-visible:ring-1 focus-visible:ring-primary",checked:v,onChange:K=>N(K.target.checked)}),o.jsx("span",{children:"Hide other empty"})]})]})]})]}),o.jsxs("div",{"data-testid":"timeline-metadata-strip",className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-9 gap-3 pt-3 border-t border-base-content/10 text-xs font-mono",children:[o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:r==="session"?"SESSION":"SESSIONS"}),o.jsx("span",{className:"font-semibold truncate text-base-content mt-0.5",title:P.sessionId??`${P.sessionCount} sessions`,children:P.sessionId?Gd(P.sessionId):`${P.sessionCount} total`})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"AGENT"}),o.jsx("span",{className:"inline-flex items-center gap-1 font-semibold truncate text-base-content mt-0.5",children:P.source?o.jsxs(o.Fragment,{children:[o.jsx(_r,{id:P.source}),P.source]}):"multiple"})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"MODEL"}),o.jsxs("span",{className:"inline-flex items-center gap-1.5 truncate text-base-content mt-0.5",children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary/70 shrink-0"}),P.model??"multiple"]})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"STARTED"}),o.jsx("span",{className:"truncate text-base-content/80 mt-0.5",children:Xw(P.start)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"DURATION"}),o.jsx("span",{className:"font-semibold truncate text-base-content mt-0.5",children:Bw(P.durationMs/6e4)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"TOTAL TOKENS"}),o.jsx("span",{className:"font-bold text-primary truncate mt-0.5",children:Be(L)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"CACHE READ"}),o.jsxs("span",{className:"font-semibold text-cyan-400 truncate mt-0.5",children:[te.toFixed(1),"%"]})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"OUTPUT TOKENS"}),o.jsx("span",{className:"truncate text-base-content/80 mt-0.5",children:Be(P.tokens.outputTokens)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"TOOL CALLS"}),o.jsx("span",{className:"truncate text-base-content font-bold mt-0.5",children:Wt(P.toolCallCount)})]})]}),o.jsx(_G,{blocks:ie,start:P.start,end:P.end,onJumpToTime:de})]}),W&&o.jsxs("div",{"data-testid":"timeline-truncated-banner",className:"p-3 rounded-lg bg-info/10 border border-info/20 text-info font-mono text-xs flex items-center gap-2",children:[o.jsx("span",{children:"ℹ️"}),o.jsx("span",{children:"Showing newest 5,000 events. Apply a narrower filter or time window to inspect earlier events."})]}),o.jsx("div",{"data-testid":"timeline-rail",className:"relative py-2 sm:py-4 before:absolute before:left-2 sm:before:left-[136px] before:top-0 before:bottom-0 before:w-[2px] before:bg-base-content/20 flex flex-col gap-3",children:ie.map(K=>{const Ee=K.events.filter(D=>D.kind==="user"),re=K.events.filter(D=>D.kind!=="user");return o.jsxs("div",{id:`timeline-block-${pa(K.key)}`,"data-testid":`timeline-block-${K.key}`,className:"flex flex-col gap-2.5",children:[r==="consolidated"&&o.jsxs("div",{className:"flex items-center gap-2 pl-6 sm:pl-[144px] pt-2 pb-1 font-mono text-xs text-base-content/70",children:[o.jsx(_r,{id:K.source}),o.jsx("span",{className:"font-bold text-base-content",children:K.source}),o.jsxs("span",{children:["· ",Gd(K.sessionId)]}),o.jsxs("span",{children:["· Turn #",K.turnIndex]}),K.correlationExactness&&o.jsx("span",{"data-testid":`timeline-exactness-${K.key}`,className:`px-1.5 py-0.2 rounded text-[10px] font-bold ${K.correlationExactness==="exact"?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-amber-500/10 text-amber-400 border border-amber-500/20"}`,children:K.correlationExactness})]}),Ee.map(D=>{const ye=IG(D),Se=D.payload?.trim()??"",pe=Cy(ye),Ae=!!D.payload?.trim(),He=!!k[za(K.key,D.seq)],fe=pa(`timeline-user-drawer-${K.key}-${D.seq}`),Je=pa(`user-tt-${K.key}-${D.seq}`);return o.jsxs("div",{className:"relative flex flex-col sm:grid sm:grid-cols-[136px_minmax(0,1fr)] py-1","data-testid":`timeline-user-event-${K.key}-${D.seq}`,children:[o.jsxs("div",{className:"hidden sm:flex flex-col items-end justify-center pr-4 font-mono text-[10.5px] text-base-content/80 select-none",title:K.timestamp?`Timestamp: ${Wd(K.timestamp)}`:void 0,children:[o.jsxs("span",{className:"font-semibold text-primary truncate",children:["📥 ",Be(D.freshInputTokens)," in"]}),D.durationSource==="measured"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,className:D.durationMs>=5e3?"font-bold text-amber-400":"text-base-content/60",children:["⏱ ",ns(D.durationMs)]}):D.durationSource==="inferred"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Inferred from next event timestamp within session",className:"text-base-content/60 italic",children:["⏱ ~",ns(D.durationMs)]}):o.jsx("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Unmeasured (gap > 10m or last event)",className:"text-base-content/40",children:"⏱ —"})]}),o.jsx("span",{"data-timeline-node":"prompt",className:"absolute left-[3.5px] sm:left-[131.5px] top-1/2 -translate-y-1/2 w-[9px] h-[9px] rounded-full bg-cyan-400 ring-4 ring-base-100 z-10","aria-hidden":"true"}),o.jsx("div",{className:"pl-6 sm:pl-5 min-w-0 flex justify-end",children:o.jsxs("div",{className:"w-[80%] max-w-none bg-base-100 rounded-xl border border-primary/20 hover:border-primary/40 hover:bg-base-200/40 transition-all p-2.5 sm:px-3.5 sm:py-2.5 flex flex-col gap-1 shadow-xs relative",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 min-h-[32px]",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:"relative z-10",children:o.jsx(OG,{promptTokens:D.promptTokens,fullText:Se,tooltipId:Je})}),o.jsx("span",{className:"font-mono text-xs font-semibold text-base-content/90 truncate min-w-0",children:pe})]}),o.jsx("div",{className:"flex items-center gap-2 shrink-0 font-mono text-[11px] text-base-content/60",children:Ae?o.jsx("button",{type:"button","aria-label":He?"Collapse full user prompt":"Expand full user prompt","aria-expanded":He,"aria-controls":fe,onClick:()=>V(K.key,D.seq),className:"p-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 inline-flex items-center justify-center text-base-content/60 hover:text-base-content transition-colors cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-primary rounded after:absolute after:inset-0 after:rounded-xl after:content-['']",children:o.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${He?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null})]}),He&&Ae&&o.jsx("div",{id:fe,className:"mt-1 p-3 bg-[#0d141f] text-slate-100 rounded-md font-mono text-xs whitespace-pre-wrap overflow-x-auto border border-white/10 relative z-10",children:$c(ye)})]})})]},za(K.key,D.seq))}),re.map(D=>{const ye=RG(D),Se=!!k[za(K.key,D.seq)],pe=!!D.payload?.trim(),Ae=pa(`timeline-op-drawer-${K.key}-${D.seq}`),He=pa(`agent-tt-${K.key}-${D.seq}`),fe=pa(`tool-tt-${K.key}-${D.seq}`),Je=Iy(D);return o.jsxs("div",{className:"relative flex flex-col sm:grid sm:grid-cols-[136px_minmax(0,1fr)] py-1 hover:z-30 focus-within:z-30","data-testid":`timeline-op-event-${K.key}-${D.seq}`,children:[o.jsxs("div",{className:"hidden sm:flex flex-col items-end justify-center pr-4 font-mono text-[10.5px] text-base-content/80 select-none",title:K.timestamp?`Timestamp: ${Wd(K.timestamp)}`:void 0,children:[o.jsx("span",{className:"font-semibold text-base-content/90 truncate",children:Je&&D.outputTokens>0?`📤 ${Be(D.outputTokens)} out`:`⚡ ${Be(D.tokens)} tok`}),D.durationSource==="measured"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,className:D.durationMs>=5e3?"font-bold text-amber-400":"text-base-content/60",children:["⏱ ",ns(D.durationMs)]}):D.durationSource==="inferred"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Inferred from next event timestamp within session",className:"text-base-content/60 italic",children:["⏱ ~",ns(D.durationMs)]}):o.jsx("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Unmeasured (gap > 10m or last event)",className:"text-base-content/40",children:"⏱ —"})]}),o.jsx("span",{"data-timeline-node":"operation",className:"absolute left-[3.5px] sm:left-[131.5px] top-1/2 -translate-y-1/2 w-[9px] h-[9px] rounded-full ring-4 ring-base-100 z-10",style:{backgroundColor:ye.color},"aria-hidden":"true"}),o.jsx("div",{className:"pl-6 sm:pl-5 min-w-0 flex justify-start",children:Je?o.jsxs("div",{className:"w-[80%] max-w-none bg-base-100 rounded-xl border border-base-content/10 border-l-[3px] border-l-primary/70 hover:border-base-content/30 hover:bg-base-200/40 transition-all relative shadow-xs",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2 min-h-[38px]",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:"relative z-10",children:o.jsx(Ry,{agentId:D.agent||K.source,model:D.model||K.model,timestamp:K.timestamp,tooltipId:He,freshInputTokens:D.freshInputTokens,cacheReadTokens:D.cacheReadTokens,outputTokens:D.outputTokens,sessionId:K.sessionId})}),o.jsx("span",{className:"font-mono text-xs text-base-content/60 truncate",children:D.model}),o.jsx("span",{className:"font-mono text-xs text-base-content/90 truncate min-w-0",children:Cy(D.payload||D.title)})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0 font-mono text-[11px] text-base-content/60",children:[o.jsxs("span",{children:["📤 ",Be(D.outputTokens)]}),pe?o.jsx("button",{type:"button","aria-label":Se?"Collapse response":"Expand response","aria-expanded":Se,"aria-controls":Ae,onClick:()=>V(K.key,D.seq),className:"p-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 inline-flex items-center justify-center text-base-content/60 hover:text-base-content transition-colors cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-primary rounded after:absolute after:inset-0 after:rounded-xl after:content-['']",children:o.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${Se?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null]})]}),Se&&D.payload&&o.jsx("div",{id:Ae,className:"p-3 bg-[#0d141f] text-slate-100 font-mono text-xs whitespace-pre-wrap overflow-x-auto rounded-b-xl border-t border-base-content/10 relative z-10",children:$c(D.payload,D.toolName)})]}):o.jsxs("div",{className:"w-[80%] max-w-none bg-base-100 rounded-xl border border-base-content/10 border-l-[3px] hover:border-base-content/30 hover:bg-base-200/40 transition-all relative shadow-xs",style:{borderLeftColor:ye.color},children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 px-2.5 py-1.5 min-h-[38px]",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:"relative z-10",children:o.jsx(Ry,{agentId:D.agent||K.source,model:D.model||K.model,timestamp:K.timestamp,tooltipId:He,freshInputTokens:D.freshInputTokens,cacheReadTokens:D.cacheReadTokens,outputTokens:D.outputTokens,sessionId:K.sessionId})}),o.jsx("span",{className:"relative z-10",children:o.jsx(Ub,{item:{toolName:ye.label,seq:D.seq,status:D.exitCode===0?"ok":D.exitCode!==null?"error":"ok",durationMs:D.durationMs,durationSource:D.durationSource,tokens:{billedTokens:D.tokens,freshInputTokens:D.freshInputTokens,cacheReadTokens:D.cacheReadTokens,outputTokens:D.outputTokens,cacheSavedTokens:0},argsRaw:D.payload,sessionId:K.sessionId??p,source:D.agent||K.source,model:D.model||K.model,ts:K.timestamp,errorText:D.exitCode!==null&&D.exitCode!==0?D.payload||`Exit code ${D.exitCode}`:null},categoryColor:ye.color,testId:`timeline-tool-badge-${fe}`,tooltipId:fe,size:"xs"})}),D.title&&D.title.trim().length>0?o.jsx("span",{className:"font-mono text-xs font-semibold text-base-content/90 truncate min-w-0",title:D.title,children:D.title}):null]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0 font-mono",children:[D.exitCode!==null&&o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold relative z-10 ${D.exitCode===0?"bg-emerald-500/20 text-emerald-400 border border-emerald-500/30":"bg-error/20 text-error border border-error/30"}`,children:["EXIT_CODE=",D.exitCode]}),pe?o.jsx("button",{type:"button","aria-label":Se?"Collapse operation payload":"Expand operation payload","aria-expanded":Se,"aria-controls":Ae,onClick:()=>V(K.key,D.seq),className:"p-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 inline-flex items-center justify-center text-base-content/60 hover:text-base-content transition-colors cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-primary rounded after:absolute after:inset-0 after:rounded-xl after:content-['']",children:o.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${Se?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null]})]}),Se&&D.payload&&o.jsx("div",{id:Ae,className:"p-3 bg-[#0d141f] text-slate-100 font-mono text-xs whitespace-pre-wrap overflow-x-auto rounded-b-xl border-t border-base-content/10 relative z-10",children:$c(D.payload,ye.label)})]})})]},za(K.key,D.seq))})]},K.key)})})]})},Js=Fr,Jw=({data:e,loading:t=!1,error:n=null,mode:r="session",onModeChange:a=()=>{},sessionId:s,sessionSource:i,availableSessions:l=[],onSelectSession:u=()=>{},toolNames:c=[],onToolNamesChange:d=()=>{},status:p="all",onStatusChange:m=()=>{},search:f="",onSearchChange:b=()=>{}})=>{const x=e?.items??[],E=e?.scope,y=g.useMemo(()=>{const N=new Set;for(const A of x)N.add(A.toolName);return Array.from(N).sort()},[x]),S=N=>{c.includes(N)?d(c.filter(A=>A!==N)):d([...c,N])},v=c.length>0||p!=="all"||f.trim().length>0;return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col gap-4 shadow-xs",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-base-content/10",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsxs("div",{className:"inline-flex bg-base-300 p-1 rounded-xl border border-base-content/5 text-xs font-mono",children:[o.jsx("button",{type:"button",className:`px-3.5 py-1.5 font-bold rounded-lg transition-all cursor-pointer ${r==="session"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content hover:bg-base-content/5"}`,onClick:()=>a("session"),children:"Single Session"}),o.jsx("button",{type:"button",className:`px-3.5 py-1.5 font-bold rounded-lg transition-all cursor-pointer ${r==="consolidated"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content hover:bg-base-content/5"}`,onClick:()=>a("consolidated"),children:"Consolidated Stream"})]}),r==="session"&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[i&&o.jsx("span",{className:"w-5 h-5 flex items-center justify-center text-base-content/80",children:o.jsx(_r,{id:i})}),o.jsx("select",{className:"bg-base-300 border border-base-content/20 rounded-xl px-3 py-1.5 text-xs font-mono max-w-sm focus:outline-hidden focus:border-primary cursor-pointer text-base-content",value:s?`${i??""}:${s}`:"",onChange:N=>{const A=N.target.value,[w,...T]=A.split(":");w&&T.length>0&&u(w,T.join(":"))},children:l.map(N=>o.jsxs("option",{value:`${N.source}:${N.id}`,children:["[",N.source,"] ",N.id.slice(0,16),"... (",N.model,")"]},`${N.source}:${N.id}`))})]})]}),r==="consolidated"&&o.jsx("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2.5 py-1 rounded-full",children:"Consolidated across all window sessions"})]}),o.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3",children:[o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Total Calls"}),o.jsx("div",{className:"mt-1",children:o.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-calls",children:E?.totalCalls??0})})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Unique Tools"}),o.jsx("div",{className:"mt-1",children:o.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-unique",children:E?.uniqueTools??0})})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Errors / Rate"}),o.jsx("div",{className:"mt-1",children:o.jsxs("span",{className:`text-lg font-bold font-mono ${(E?.errorCount??0)>0?"text-error":"text-success"}`,"data-testid":"tool-scope-errors",children:[E?.errorCount??0," (",Math.round((E?.errorRate??0)*100),"%)"]})})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Mean Duration"}),o.jsxs("div",{className:"mt-1",children:[o.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-duration",children:E?.meanDurationMs?`${E.meanDurationMs} ms`:"—"}),(E?.durationUnmeasured??0)>0&&o.jsxs("span",{className:"text-[10px] text-base-content/50 ml-1 font-mono block",children:["(",E?.durationUnmeasured," unmeasured)"]})]})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Billed Tokens"}),o.jsx("div",{className:"mt-1",children:o.jsx("span",{className:"text-lg font-bold font-mono text-primary","data-testid":"tool-scope-tokens",children:E?Js(E.tokens.billedTokens):0})})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-base-content/10",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs text-base-content/60 font-semibold font-mono",children:"Status:"}),o.jsx("div",{className:"inline-flex bg-base-300 p-0.5 rounded-lg text-xs font-mono",children:["all","ok","error"].map(N=>o.jsx("button",{type:"button",className:`px-2.5 py-1 text-xs font-bold rounded-md transition-all cursor-pointer ${p===N?N==="error"?"bg-error text-error-content shadow-xs":"bg-base-content text-base-100 shadow-xs":"text-base-content/70 hover:bg-base-content/10"}`,onClick:()=>m(N),children:N.toUpperCase()},N))})]}),o.jsxs("div",{className:"flex-1 max-w-md relative",children:[o.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-xs opacity-40",children:"🔍"}),o.jsx("input",{type:"text",className:"bg-base-300 border border-base-content/20 rounded-xl pl-8 pr-7 py-1.5 w-full text-xs font-mono focus:outline-hidden focus:border-primary placeholder:text-base-content/40",placeholder:"Search tool arguments, digest, or error text...",value:f,onChange:N=>b(N.target.value)}),f&&o.jsx("button",{type:"button",onClick:()=>b(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-xs text-base-content/40 hover:text-base-content cursor-pointer",children:"✕"})]})]}),y.length>0&&o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-2 border-t border-base-content/5",children:[o.jsx("span",{className:"text-[11px] text-base-content/50 font-semibold font-mono",children:"Tools:"}),y.map(N=>{const A=c.includes(N);return o.jsx("button",{type:"button","data-testid":`tool-filter-${N}`,className:`px-2.5 py-0.5 rounded-full text-[11px] font-mono transition-all border cursor-pointer ${A?"bg-primary text-primary-content border-primary font-bold shadow-xs":"bg-base-300 text-base-content/80 border-base-content/10 hover:border-base-content/30"}`,onClick:()=>S(N),children:N},N)}),c.length>0&&o.jsxs("button",{type:"button",className:"text-[11px] text-base-content/60 hover:text-base-content underline ml-1 font-mono cursor-pointer",onClick:()=>d([]),children:["Clear (",c.length,")"]})]})]}),e?.truncated&&o.jsxs("div",{className:"bg-warning/10 text-warning border border-warning/20 p-3 rounded-xl text-xs font-medium flex items-center gap-2",children:[o.jsx("span",{children:"⚠️"}),o.jsxs("span",{children:["Showing the first ",x.length," tool calls. Refine your filters or search to narrow the scope."]})]}),n&&o.jsxs("div",{className:"bg-error/10 text-error border border-error/20 p-4 text-xs rounded-xl flex items-center gap-2",children:[o.jsx("span",{children:"⚠️"}),o.jsx("span",{children:n})]}),t&&x.length===0&&o.jsx("div",{className:"flex flex-col gap-2.5 animate-pulse",children:[1,2,3,4,5].map(N=>o.jsx("div",{className:"h-16 bg-base-200 rounded-xl border border-base-content/5"},N))}),!t&&!n&&x.length===0&&o.jsxs("div",{className:"bg-base-200/40 rounded-xl border border-base-content/10 p-12 text-center text-base-content/60 flex flex-col items-center gap-2",children:[o.jsx("span",{className:"text-3xl block mb-1",children:"🔍"}),o.jsx("p",{className:"text-sm font-semibold",children:"No tool calls found"}),o.jsx("p",{className:"text-xs max-w-sm",children:v?"No tool calls match your active filter criteria. Try clearing search or status filters.":"No tool invocations recorded for this scope."})]}),x.length>0&&o.jsx("div",{className:"flex flex-col gap-2 w-full",children:x.map(N=>{const A=`${N.sessionId}:${N.messageHash}:${N.toolSeq}`,w=Ll[N.category]??Ll.other,T=N.status==="error";return o.jsxs("div",{className:"w-full text-left group p-3 rounded-xl border border-base-content/10 hover:border-base-content/30 hover:bg-base-200/60 bg-base-200/30 transition-all flex items-center justify-between gap-3 relative","data-testid":`tool-item-${N.seq}`,children:[o.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[o.jsx(yG,{agentId:N.source,model:N.model,timestamp:N.ts,freshInputTokens:N.tokens.freshInputTokens,cacheReadTokens:N.tokens.cacheReadTokens,outputTokens:N.tokens.outputTokens,sessionId:N.sessionId}),o.jsxs("span",{className:"text-xs font-mono text-base-content/40 font-bold min-w-[28px]",children:["#",N.seq]}),o.jsx(TG,{item:N,categoryColor:w}),o.jsx("span",{className:"text-xs font-mono text-base-content/80 truncate min-w-0 flex-1",title:N.argsRaw||N.argsDigest||"",children:hG(N)})]}),o.jsxs("div",{className:"flex items-center gap-3 shrink-0 text-xs font-mono",children:[o.jsx("span",{className:"text-base-content/70 tabular-nums",title:`Duration source: ${N.durationSource}`,children:N.durationMs!==null?`${N.durationMs} ms`:"—"}),o.jsxs("span",{className:"text-base-content/50 text-[11px] tabular-nums",title:`Tokens: ${Js(N.tokens.freshInputTokens)} fresh input, ${Js(N.tokens.cacheReadTokens)} cache read, ${Js(N.tokens.outputTokens)} output`,children:[Js(N.tokens.billedTokens)," tok"]}),o.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border ${T?"bg-error/15 text-error border-error/30":"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"}`,children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-current"}),N.status]})]})]},A)})})]})},LG=[{id:"summary",label:"Summary",component:Zw},{id:"timeline",label:"Timeline",component:Qw},{id:"tool-using",label:"Tool Using",component:Jw},{id:"sessions",label:"Sessions",component:Yw},{id:"insights",label:"Insights",component:Vw},{id:"sources",label:"Sources",component:Kw}],qo=(e,t)=>{const n=new Map;for(const r of e)n.set(r.id,r);for(const r of t??[])n.has(r)||n.set(r,{id:r,label:r});return[...n.values()]},MG=e=>e.range==="1h"?"Last 1h":e.range==="4h"?"Last 4h":e.range==="24h"?"Last 24h":e.range==="7d"?"Last 7d":e.range==="30d"?"Last 30d":e.range==="all"?"All time":`${e.from?.slice(0,10)??"…"} → ${e.to?.slice(0,10)??"…"}`,Ga=e=>e instanceof Error?e.message:String(e),FG=()=>{const[e,t]=g.useState("summary"),[n,r]=g.useState({range:"4h",bucket:"auto",dimension:"model"}),[a,s]=g.useState("session"),[i,l]=g.useState(null),[u,c]=g.useState({taskWbs:"",runId:""}),[d,p]=g.useState("session"),[m,f]=g.useState([]),[b,x]=g.useState("all"),[E,y]=g.useState(""),[S,v]=g.useState(""),[N,A]=g.useState(1),[w,T]=g.useState("start"),[_,B]=g.useState("desc"),[k,$]=g.useState(void 0),[V,P]=g.useState(void 0),[H,W]=g.useState(void 0),[L,te]=g.useState(void 0),[ie,be]=g.useState(void 0),[I,ne]=g.useState(void 0),[ue,O]=g.useState([]),[Ne,de]=g.useState(!1),[K,Ee]=g.useState(!0),[re,D]=g.useState(null),[ye,Se]=g.useState(!0),[pe,Ae]=g.useState(null),[He,fe]=g.useState(!0),[Je,bt]=g.useState(null),[it,Ft]=g.useState(!1),[Nt,Tt]=g.useState(null),[$t,rt]=g.useState(!1),[Me,et]=g.useState(null),[Q,ce]=g.useState(!1),[Re,G]=g.useState(null);g.useEffect(()=>{let se=!0;return Ee(!0),D(null),Se(!0),Ae(null),rn.history.getSummary(n).then(he=>{se&&(he?.data?$(he.data):D("Failed to load summary"))}).catch(he=>{se&&D(Ga(he))}).finally(()=>{se&&Ee(!1)}),rn.history.getInsights(n).then(he=>{se&&(he?.data?be(he.data):Ae("Failed to load insights"))}).catch(he=>{se&&Ae(Ga(he))}).finally(()=>{se&&Se(!1)}),()=>{se=!1}},[n]),g.useEffect(()=>{let se=!0;return fe(!0),bt(null),(async()=>{try{const he=await rn.history.getSources();if(!se)return;he?.data?ne(he.data):bt("Failed to load sources")}catch(he){se&&bt(Ga(he))}finally{se&&fe(!1)}})(),()=>{se=!1}},[]),g.useEffect(()=>{if(e!=="timeline"&&e!=="tool-using")return;let se=!0;return de(!0),(async()=>{try{const he=await rn.history.getSessions({filter:n,page:1,pageSize:100,sortBy:"start",sortDir:"desc"});if(!se)return;const st=(he?.data?.items??[]).map(Y=>({id:Y.id,source:Y.source,model:Y.model,start:Y.start,tokenLoad:Y.freshInputTokens+Y.cacheReadTokens+Y.outputTokens}));O(st);const Ot=st[0];Ot&&!i&&l({source:Ot.source,id:Ot.id})}catch{se&&O([])}finally{se&&de(!1)}})(),()=>{se=!1}},[e,n,i]),g.useEffect(()=>{if(e!=="sessions")return;let se=!0;return Ft(!0),Tt(null),(async()=>{try{const he=await rn.history.getSessions({filter:n,page:N,pageSize:20,sortBy:w,sortDir:_});if(!se)return;he?.data?te(he.data):Tt("Failed to load sessions")}catch(he){se&&Tt(Ga(he))}finally{se&&Ft(!1)}})(),()=>{se=!1}},[e,n,N,w,_]),g.useEffect(()=>{if(e!=="timeline")return;if(a==="session"&&!i){const he=ue[0];!Ne&&he&&l({source:he.source,id:he.id});return}let se=!0;return rt(!0),et(null),(async()=>{try{const he=a==="session"&&i?await rn.history.getTimeline({mode:"session",source:i.source,sessionId:i.id}):await rn.history.getTimeline({mode:"consolidated",filter:n,...u.taskWbs?{taskWbs:u.taskWbs}:{},...u.runId?{runId:u.runId}:{}});if(!se)return;he?.data?P(he.data):et("Failed to load timeline")}catch(he){se&&et(Ga(he))}finally{se&&rt(!1)}})(),()=>{se=!1}},[e,a,i,n,Ne,ue,u]),g.useEffect(()=>{const se=setTimeout(()=>{v(E)},250);return()=>clearTimeout(se)},[E]),g.useEffect(()=>{if(e!=="tool-using")return;if(d==="session"&&!i){const he=ue[0];!Ne&&he&&l({source:he.source,id:he.id});return}let se=!0;return ce(!0),G(null),(async()=>{try{const he=d==="session"&&i?{mode:"session",source:i.source,sessionId:i.id,toolNames:m.length>0?m:void 0,status:b,search:S||void 0}:{mode:"consolidated",filter:n,toolNames:m.length>0?m:void 0,status:b,search:S||void 0},st=await rn.history.getToolSequence(he);if(!se)return;st?.data?W(st.data):G("Failed to load tool sequence")}catch(he){se&&G(Ga(he))}finally{se&&ce(!1)}})(),()=>{se=!1}},[e,d,i,n,m,b,S,Ne,ue]);const Fe=(se,he)=>{l({source:se,id:he}),s("session"),t("timeline")},Ve=(se,he)=>{l({source:se,id:he}),p("session")},pt=(se,he)=>{const st=he?{source:he,id:se}:L?.items.find(Ot=>Ot.id===se)??ue.find(Ot=>Ot.id===se);st&&Fe(st.source,st.id)},At=async se=>(await rn.history.triggerImport({mode:se})).data,St=re?"—":K||k===void 0?"…":String(k.kpis.sessionsCount),Rt=Re?"—":Q||H===void 0?"…":String(H.scope.totalCalls),le=pe?"—":ye||ie===void 0?"…":String(ie.loops.length),Ce=Je?"—":He||I===void 0?"…":String(I.agents.length),Ue={summary:null,timeline:null,"tool-using":Rt,sessions:St,insights:le,sources:Ce},je=Je?"—":He?"…":I?.overview.lastImportedAt?new Date(I.overview.lastImportedAt).toLocaleString():"never imported",Et=g.useMemo(()=>ie?{count:ie.loops.length,redundantCalls:ie.loops.reduce((se,he)=>se+Math.max(0,he.repeats-1),0),wastedTokens:ie.loops.reduce((se,he)=>se+he.wastedTokens,0)}:void 0,[ie]),zt=g.useMemo(()=>qo(I?.agents.map(se=>({id:se.id,label:se.name,color:se.color}))??[],n.sources),[I?.agents,n.sources]),De=g.useMemo(()=>qo(k?.topModels.map(se=>({id:se.id,label:se.label,color:se.color}))??[],n.models),[k?.topModels,n.models]),tt=g.useMemo(()=>qo(k?.topTools.map(se=>{const he=se.id&&se.id.trim()!==""?se.id.trim():"unknown";return{id:he,label:he}})??[],n.tools?.map(se=>se&&se.trim()!==""?se.trim():"unknown")),[k?.topTools,n.tools]),Xe=g.useMemo(()=>qo(k?.skillsUsed.filter(se=>se.id&&se.id.trim()!==""&&se.id!=="unknown").map(se=>({id:se.id,label:se.label,color:se.color}))??[],n.skills?.filter(se=>se&&se.trim()!==""&&se!=="unknown")),[k?.skillsUsed,n.skills]),kt=g.useMemo(()=>({rangeLabel:MG(n),sessionCount:re?null:K&&k===void 0?void 0:k?.kpis.sessionsCount,sourceCount:n.sources?.length??I?.agents.length}),[n,re,K,k,I?.agents.length]);return o.jsxs("div",{className:"flex flex-col gap-4 p-4 max-w-[1600px] mx-auto w-full",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-2xl",children:"📊"}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"History"}),o.jsx("p",{className:"text-xs text-base-content/60",children:"Transcript telemetry, session traces, and prompt cache analytics"}),o.jsxs("p",{className:"livechip mt-1 inline-flex items-center gap-1.5 rounded-full border border-base-content/10 px-2 py-0.5 text-xs text-base-content/60 font-mono","data-testid":"history-last-import",role:"status",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Je?"bg-error":"bg-emerald-400 animate-pulse"}`,"aria-hidden":"true"}),"last import ",je]})]})]}),o.jsx("div",{className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:LG.map(se=>o.jsxs("button",{type:"button",className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all ${e===se.id?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,onClick:()=>t(se.id),children:[se.label,Ue[se.id]!==null&&o.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 rounded-full text-[10px] font-mono bg-base-content/10","data-testid":`history-badge-${se.id}`,children:Ue[se.id]})]},se.id))})]}),e!=="sources"&&o.jsx(oG,{filter:n,onChange:r,sourceOptions:zt,modelOptions:De,toolOptions:tt,skillOptions:Xe,scope:kt}),o.jsxs("div",{className:"mt-2",children:[e==="summary"&&o.jsx(Zw,{data:k,loading:K,error:re,dimension:n.dimension??"model",onDimensionChange:se=>r(he=>({...he,dimension:se})),bucket:n.bucket??"auto",onBucketChange:se=>r(he=>({...he,bucket:se})),loopSummary:Et}),e==="timeline"&&o.jsx(Qw,{data:V,loading:$t,error:Me,mode:a,sessionId:i?.id,sessionSource:i?.source,availableSessions:ue,onSelectSession:Fe,onModeChange:s,consolidatedTaskWbs:u.taskWbs,consolidatedRunId:u.runId,onConsolidatedScopeSubmit:c}),e==="tool-using"&&o.jsx(Jw,{data:H,loading:Q,error:Re,mode:d,onModeChange:p,sessionId:i?.id,sessionSource:i?.source,availableSessions:ue,onSelectSession:Ve,toolNames:m,onToolNamesChange:f,status:b,onStatusChange:x,search:E,onSearchChange:y}),e==="sessions"&&o.jsx(Yw,{data:L,loading:it,error:Nt,sortBy:w,sortDir:_,page:N,pageSize:20,onSortChange:se=>{w===se?B(he=>he==="asc"?"desc":"asc"):(T(se),B("desc"))},onPageChange:A,onSelectSession:Fe}),e==="insights"&&o.jsx(Vw,{data:ie,loading:ye,error:pe,cacheHitTrend:k?.kpiTrend??[],onSelectSession:pt}),e==="sources"&&o.jsx(Kw,{data:I,loading:He,error:Je,onTriggerImport:At})]})]})},jG={id:"history",name:"History",icon:"📊",route:"history",component:FG,sidebarLabel:"Histories",description:"Imported agent sessions, token analytics, and tool-call forensics",order:20},PG=Object.freeze(Object.defineProperty({__proto__:null,module:jG},Symbol.toStringTag,{value:"Module"})),BG=["30s","5m","1h","4h","24h","7d","all"],UG={"30s":3e4,"5m":5*6e4,"1h":60*6e4,"4h":240*6e4,"24h":1440*6e4,"7d":10080*6e4,all:null};function Pu(e,t=Date.now()){const n=UG[e];if(n!=null)return new Date(t-n).toISOString()}function $G({timeRange:e,onTimeRangeChange:t}){return o.jsxs("fieldset",{className:"flex items-center gap-1 bg-base-200 p-1 rounded-lg border-0 m-0","aria-label":"Time range presets",children:[o.jsx("legend",{className:"sr-only",children:"Time range presets"}),BG.map(n=>{const r=e===n;return o.jsx("button",{type:"button",onClick:()=>t(n),"aria-pressed":r,className:`px-2.5 py-1 text-xs font-semibold rounded-md transition-all cursor-pointer ${r?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,children:n==="all"?"All":n},n)})]})}function zG(e){return e.selectedPrefixes.size>0||e.searchQuery.trim()!==""||e.searchScope!=="all"||e.severity!=="all"||e.tierFilter!=="all"||e.runId.trim()!==""}function Dy({label:e,value:t,onChange:n,options:r}){return o.jsxs("fieldset",{className:"flex items-center gap-0.5 bg-base-100 border border-base-content/20 rounded-md p-0.5","aria-label":e,children:[o.jsx("legend",{className:"sr-only",children:e}),r.map(a=>{const s=a.value===t;return o.jsxs("label",{className:`flex-1 text-[11px] text-center px-2 py-0.5 rounded cursor-pointer transition-all ${s?"bg-primary text-primary-content font-bold shadow-xs":"text-base-content/70 hover:bg-base-content/10"}`,children:[o.jsx("input",{type:"radio",name:`segmented-${e}`,value:a.value,checked:s,onChange:()=>n(a.value),className:"sr-only"}),a.label]},a.value)})]})}const Oy="Retention: events capped at 10,000 rows per prefix · terminal jobs pruned after 30d";function eN(){return o.jsxs("span",{"data-testid":"observability-retention-badge",className:"inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-lg border border-base-content/15 bg-base-100 text-base-content/70 whitespace-nowrap",title:Oy,children:[o.jsx("span",{"aria-hidden":"true",children:"ℹ️"}),o.jsx("span",{children:Oy})]})}function HG({filters:e,onFiltersChange:t,onClearFilters:n,prefixOptions:r,getPrefixColor:a,liveEnabled:s,onToggleLive:i,shownCount:l,totalCount:u,actions:c}){const d=g.useMemo(()=>{let f=0;return e.selectedPrefixes.size>0&&(f+=e.selectedPrefixes.size),e.searchQuery.trim()!==""&&(f+=1),e.severity!=="all"&&(f+=1),e.tierFilter!=="all"&&(f+=1),e.runId.trim()!==""&&(f+=1),f},[e]),p=zG(e),m=f=>{t(b=>{const x=new Set(b.selectedPrefixes);return x.has(f)?x.delete(f):x.add(f),{...b,selectedPrefixes:x}})};return o.jsx("div",{className:"flex flex-wrap items-center justify-between gap-3 p-3 bg-base-200/50 rounded-xl border border-base-content/10 shrink-0",children:o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("span",{"aria-live":"polite",className:"text-xs font-mono text-base-content/60 whitespace-nowrap","data-testid":"observability-result-count",children:[l," of ",u," shown"]}),o.jsxs("details",{className:"relative inline-block","data-testid":"observability-filter-disclosure",children:[o.jsxs("summary",{className:"px-2.5 py-1 text-xs font-medium rounded-lg border border-base-content/20 bg-base-200 text-base-content/80 hover:bg-base-300 transition-colors cursor-pointer list-none flex items-center gap-1.5 focus:outline-none focus:ring-2 focus:ring-primary/40","aria-label":"Toggle filter panel",children:[o.jsx("span",{children:"🔍 Filter"}),d>0&&o.jsx("span",{className:"px-1.5 py-0.2 rounded-full text-[10px] font-bold bg-primary text-primary-content",children:d})]}),o.jsxs("div",{className:"absolute right-0 top-full z-30 p-3 shadow-xl bg-base-200 border border-base-content/10 rounded-xl w-80 sm:w-96 mt-2 flex flex-col gap-3",children:[o.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-base-content/10",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wide text-base-content/70",children:"Filters"}),p&&o.jsx("button",{type:"button",onClick:n,className:"text-xs text-error hover:underline cursor-pointer","aria-label":"Clear all filters",children:"Clear all"})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:"filter-search-input",className:"text-[11px] font-semibold text-base-content/60",children:"Search"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("select",{value:e.searchScope,onChange:f=>t(b=>({...b,searchScope:f.target.value})),className:"bg-base-100 border border-base-content/20 rounded px-2 py-1 text-xs text-base-content focus:outline-none focus:ring-2 focus:ring-primary/40 cursor-pointer","aria-label":"Search scope",children:[o.jsx("option",{value:"all",children:"all"}),o.jsx("option",{value:"name",children:"name"}),o.jsx("option",{value:"actor",children:"actor"}),o.jsx("option",{value:"payload",children:"payload"})]}),o.jsx(Oi,{id:"filter-search-input",size:"sm",variant:"bordered",placeholder:`Search ${e.searchScope}…`,value:e.searchQuery,onChange:f=>t(b=>({...b,searchQuery:f.target.value})),className:"flex-1 input-xs","aria-label":`Search ${e.searchScope}`})]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Severity"}),o.jsx(Dy,{label:"Severity",value:e.severity,onChange:f=>t(b=>({...b,severity:f})),options:[{value:"all",label:"All"},{value:"info",label:"Info"},{value:"warning",label:"Warning"},{value:"error",label:"Error"}]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Tier"}),o.jsx(Dy,{label:"Tier",value:e.tierFilter,onChange:f=>t(b=>({...b,tierFilter:f})),options:[{value:"all",label:"All"},{value:"default",label:"Default"},{value:"diagnostic",label:"Diagnostic"}]})]}),r.length>0&&o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Prefix"}),o.jsxs("fieldset",{className:"flex flex-wrap items-center gap-1.5 border-0 p-0 m-0","aria-label":"Filter by prefix",children:[o.jsx("legend",{className:"sr-only",children:"Filter by prefix"}),r.map(f=>{const b=e.selectedPrefixes.has(f),x=a(f);return o.jsxs("button",{type:"button",role:"switch","aria-checked":b,"aria-label":`Prefix ${f}${b?" (selected)":""}`,onClick:()=>m(f),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border transition-colors cursor-pointer ${b?`${x} border-current bg-base-100 font-bold`:"text-base-content/60 border-base-content/20 hover:bg-base-100"}`,children:[f,".*"]},f)})]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:"filter-run-id-input",className:"text-[11px] font-semibold text-base-content/60",children:"Run ID"}),o.jsx(Oi,{id:"filter-run-id-input",size:"sm",variant:"bordered",placeholder:"Filter by run id…",value:e.runId,onChange:f=>t(b=>({...b,runId:f.target.value})),className:"w-full input-xs","aria-label":"Filter by run id"})]})]})]}),o.jsx(eN,{}),o.jsx("button",{type:"button",onClick:i,className:`px-2.5 py-1 text-xs font-semibold rounded-lg border transition-all cursor-pointer flex items-center gap-1.5 ${s?"border-emerald-500/40 bg-emerald-500/10 text-emerald-500 hover:bg-emerald-500/20":"border-amber-500/40 bg-amber-500/10 text-amber-500 hover:bg-amber-500/20"}`,"aria-label":s?"Pause live event stream":"Resume live event stream","aria-pressed":s,children:o.jsx("span",{children:s?"⏸ Pause Live":"▶ Resume Live"})}),c]})})}const us=[{key:"time",label:"Time",description:"Event timestamp",defaultVisible:!0,sortable:!0,colWidth:"w-36"},{key:"severity",label:"Severity",description:"Diagnostic severity level",defaultVisible:!0,sortable:!0,colWidth:"w-24"},{key:"event",label:"Event",description:"Event name with domain prefix",defaultVisible:!0,sortable:!0,colWidth:"w-[15%]"},{key:"summary",label:"Summary",description:"Rendered human summary",defaultVisible:!0,sortable:!0,colWidth:"w-[20%]"},{key:"correlation",label:"Correlation",description:"Entity or run correlation identifier",defaultVisible:!0,sortable:!0,colWidth:"w-[16%]"},{key:"outcome",label:"Outcome",description:"Execution result or state change",defaultVisible:!0,sortable:!0,colWidth:"w-28"},{key:"agent",label:"Agent",description:"Target or actor agent role",defaultVisible:!0,sortable:!0,colWidth:"w-28"},{key:"producer",label:"Producer",description:"Subsystem or source package",defaultVisible:!1,sortable:!1,colWidth:"w-[16%]"},{key:"action",label:"Action",description:"Action link or remediation command",defaultVisible:!1,sortable:!1,colWidth:"w-[15%]"},{key:"actor",label:"Actor",description:"Originating user or system actor",defaultVisible:!1,sortable:!1,colWidth:"w-24"}],GG=new Set(us.map(e=>e.key)),ra=["time","severity","event","summary","correlation","outcome","agent"],tN="spur:observability:columns:v1";function WG(e){if(!Array.isArray(e)||e.length===0)return[...ra];const t=new Set;for(const n of e)typeof n=="string"&&GG.has(n)&&t.add(n);return t.size===0?[...ra]:us.filter(n=>t.has(n.key)).map(n=>n.key)}function qG(e){try{const t=e??(typeof window<"u"?window.localStorage:void 0);if(!t)return[...ra];const n=t.getItem(tN);if(!n)return[...ra];const r=JSON.parse(n);return WG(r)}catch{return[...ra]}}function Ly(e,t){try{const n=t??(typeof window<"u"?window.localStorage:void 0);if(!n)return;n.setItem(tN,JSON.stringify(e))}catch{}}function VG({visibleColumns:e,onVisibleColumnsChange:t}){const n=g.useMemo(()=>new Set(e),[e]),r=s=>{const i=new Set(n);if(i.has(s)){if(i.size<=1)return;i.delete(s)}else i.add(s);const l=us.filter(u=>i.has(u.key)).map(u=>u.key);t(l),Ly(l)},a=()=>{const s=[...ra];t(s),Ly(s)};return o.jsxs("details",{className:"relative inline-block","data-testid":"observability-column-customizer",children:[o.jsxs("summary",{className:"px-2.5 py-1 text-xs font-medium rounded-lg border border-base-content/20 bg-base-200 text-base-content/80 hover:bg-base-300 transition-colors cursor-pointer list-none flex items-center gap-1.5 focus:outline-none focus:ring-2 focus:ring-primary/40","aria-label":"Customize visible columns",children:[o.jsx("span",{children:"📊 Columns"}),o.jsxs("span",{className:"text-[10px] text-base-content/60 font-mono",children:["(",e.length,"/",us.length,")"]})]}),o.jsxs("div",{className:"absolute right-0 top-full z-30 p-3 shadow-xl bg-base-200 border border-base-content/10 rounded-xl w-64 mt-2 flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-base-content/10",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wide text-base-content/70",children:"Columns"}),o.jsx("button",{type:"button",onClick:a,className:"text-xs text-primary hover:underline cursor-pointer","aria-label":"Reset columns to default",children:"Reset defaults"})]}),o.jsxs("fieldset",{className:"flex flex-col gap-1.5 border-0 p-0 m-0","aria-label":"Visible columns",children:[o.jsx("legend",{className:"sr-only",children:"Select visible columns"}),us.map(s=>{const i=n.has(s.key),l=i&&n.size===1,u=`observability-col-${s.key}`;return o.jsxs("label",{htmlFor:u,className:`flex items-center justify-between px-2 py-1 rounded-md text-xs transition-colors ${l?"opacity-60 cursor-not-allowed":"hover:bg-base-100 cursor-pointer text-base-content/90"}`,children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Sb,{id:u,size:"xs",variant:"primary",checked:i,disabled:l,onChange:()=>r(s.key),"aria-label":s.label}),o.jsx("span",{className:"font-medium",children:s.label})]}),s.defaultVisible&&o.jsx("span",{className:"text-[10px] text-base-content/50 uppercase",children:"default"})]},s.key)})]})]})]})}const YG=()=>`${Ct()}/events/planning`,qd=100;function Vd(e){const t=`${Ct()}/events/history`,n=[],r=e.limit??qd;return n.push(`limit=${r}`),e.prefix&&n.push(`prefix=${encodeURIComponent(e.prefix)}`),e.names&&n.push(`names=${encodeURIComponent(e.names)}`),e.actor&&n.push(`actor=${encodeURIComponent(e.actor)}`),e.runId&&n.push(`runId=${encodeURIComponent(e.runId)}`),e.since&&n.push(`since=${encodeURIComponent(e.since)}`),e.cursor&&n.push(`cursor=${encodeURIComponent(e.cursor)}`),`${t}?${n.join("&")}`}const KG={workflow:"text-cyan-400",task:"text-emerald-400",feature:"text-emerald-400",agent:"text-amber-400",rule:"text-rose-400",message:"text-sky-400",process:"text-violet-400",queue:"text-orange-400",bus:"text-pink-400",api:"text-teal-400"},My="text-spur-text-muted";function nN(e){return e?KG[e]??My:My}const Hc={selectedPrefixes:new Set,searchQuery:"",searchScope:"all",severity:"all",tierFilter:"all",runId:""};function ZG(){const e=g.useRef([]),[t,n]=g.useState(0);g.useEffect(()=>{const a=window.setInterval(()=>{const s=Date.now()-6e4,i=e.current.filter(l=>l>=s);e.current=i,n(i.length)},1e3);return()=>window.clearInterval(a)},[]);const r=g.useCallback(()=>{const a=Date.now(),s=a-6e4,i=e.current.filter(l=>l>=s);i.push(a),e.current=i,n(i.length)},[]);return{rate:t,recordEvent:r}}function Yd(e){if(e===null||typeof e!="object"||!("events"in e)||!("count"in e))return null;const t=e.events;if(!Array.isArray(t))return null;const n=e.count;if(typeof n!="number")return null;const r=e.nextCursor,a=typeof r=="string"?r:null,s=e.hasMore,i=typeof s=="boolean"?s:!1,l=[];for(const d of t){const p=XG(d);p&&l.push(p)}const u=e.catalog,c=Array.isArray(u)?QG(u):void 0;return{events:l,count:n,nextCursor:a,hasMore:i,...c?{catalog:c}:{}}}function XG(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.id!="string"||typeof t.eventName!="string"||typeof t.occurredAt!="string")return null;const n=typeof t.prefix=="string"?t.prefix:void 0,r=typeof t.renderer=="string"?t.renderer:void 0,a=t.actor;if(a!==null&&typeof a!="string")return null;const s=t.payload,i=typeof t.runId=="string"?t.runId:t.runId===null?null:void 0,l=typeof t.entityKind=="string"?t.entityKind:t.entityKind===null?null:void 0,u=typeof t.entityId=="string"?t.entityId:t.entityId===null?null:void 0,c=typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:t.sequence===null?null:void 0,d={id:t.id,eventName:t.eventName,occurredAt:t.occurredAt,actor:a,...n?{prefix:n}:{},...r?{renderer:r}:{}};if(s===null)return{...d,payload:null,view:Na(t.eventName,null),...jl(i,l,u,c)};if(typeof s!="object")return null;const p=s,m=p.schemaVersion===2?p:void 0;return{...d,payload:rN(p),...m?{envelope:m}:{},view:Na(t.eventName,p),...jl(i,l,u,c)}}function jl(e,t,n,r){const a={};return e!==void 0&&(a.runId=e),t!==void 0&&(a.entityKind=t),n!==void 0&&(a.entityId=n),r!==void 0&&(a.sequence=r),a}function QG(e){const t=[];for(const n of e){if(n===null||typeof n!="object")return;const r=n;if(typeof r.name!="string"||typeof r.prefix!="string"||typeof r.source!="string"||typeof r.renderer!="string")return;const a=typeof r.tier=="string"?r.tier:void 0,s={name:r.name,prefix:r.prefix,source:r.source,renderer:r.renderer,...a!==void 0?{tier:a}:{}};t.push(s)}return t}function JG(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.eventName!="string"||t.eventName.length===0||typeof t.occurredAt!="string")return null;const n=typeof t.prefix=="string"?t.prefix:void 0,r=typeof t.renderer=="string"?t.renderer:void 0,a=t.actor;if(a!==null&&typeof a!="string")return null;const s=t.payload;if(s!==null&&typeof s!="object")return null;const i=s,l=i?.schemaVersion===2?i:void 0,u=rN(i),c=t.runId??u?.runId,d=t.entityKind??u?.entityKind,p=t.entityId??u?.entityId,m=t.sequence??u?.sequence,f=typeof c=="string"?c:c===null?null:void 0,b=typeof d=="string"?d:d===null?null:void 0,x=typeof p=="string"?p:p===null?null:void 0,E=typeof m=="number"&&Number.isFinite(m)?m:m===null?null:void 0;return{eventName:t.eventName,occurredAt:t.occurredAt,actor:a,...n?{prefix:n}:{},...r?{renderer:r}:{},payload:u,...l?{envelope:l}:{},view:Na(t.eventName,i),...jl(f,b,x,E)}}function Na(e,t){const n=eW(e);if(t?.schemaVersion!==2)return n;const r=Yr(t.context),a=Yr(t.presentation),s=Yr(r?.project),i=Yr(r?.producer),l=Yr(r?.correlation);if(!r||!a||!s||!i||!l)return n;const u=a.severity==="info"||a.severity==="warning"||a.severity==="error"?a.severity:"warning",c=Array.isArray(a.fields)?a.fields.flatMap(S=>{const v=Yr(S),N=fn(v?.label,64),A=fn(v?.value,256);return N&&A?[{label:N,value:A}]:[]}).slice(0,8):[],d=[],p=(S,v)=>{const N=fn(v,128);N&&d.push({label:S,value:N})};p("Run",l.runId),p("Execution",l.executionId),p("Action",l.actionId),p("Entity",nW(l.entityKind,l.entityId)),p("Job",l.jobId),typeof l.sequence=="number"&&Number.isFinite(l.sequence)&&d.push({label:"Sequence",value:String(l.sequence)});const m=fn(i.package,128)??"unavailable",f=fn(i.subsystem,128),b=tW(a.action),x=fn(a.actionLabel,128)??"unavailable",E=fn(a.agent,128),y=fn(a.correlators,512);return{severity:u,summary:fn(a.summary,512)??"unavailable",description:fn(a.description,512)??"Description unavailable.",fields:c,projectName:fn(s.name,128)??"unavailable",projectRoot:fn(s.root,256)??"unavailable",producer:f?`${m} / ${f}`:m,correlation:y??"unavailable",correlationFields:d,outcome:fn(a.outcome,128)??"unavailable",action:b,actionLabel:x,agent:E}}function eW(e){return{severity:"warning",summary:"unavailable",description:`Canonical context unavailable for ${fn(e,128)??"unknown"}.`,fields:[],projectName:"unavailable",projectRoot:"unavailable",producer:"unavailable",correlation:"unavailable",correlationFields:[],outcome:"unavailable",action:null,actionLabel:"unavailable",agent:null}}function tW(e){const t=Yr(e);if(!t||t.kind!=="command"&&t.kind!=="filter"&&t.kind!=="path")return null;const n=fn(t.label,128),r=fn(t.value,256);return n&&r?{label:n,kind:t.kind,value:r}:null}function fn(e,t){return typeof e!="string"||e.length===0?null:e.length<=t?e:`${e.slice(0,t-1)}…`}function nW(e,t){const n=fn(e,64),r=fn(t,128);return n&&r?`${n}:${r}`:n??r}const rW=["Entity","Run","Execution","Action","Job"];function aW(e,t){for(const n of rW){const r=t.correlationFields.find(a=>a.label===n);if(r!==void 0&&r.value!=="")return`${e.eventName} · ${r.value}`}return e.id!==""&&!e.id.startsWith("live-")?`${e.eventName} · ${e.id}`:e.eventName}function Yr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function rN(e){return e?.schemaVersion!==2?e:Yr(e.data)}const sW=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Fy(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=sW[t.getMonth()],r=t.getDate(),a=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0"),i=String(t.getSeconds()).padStart(2,"0");return`${n} ${r} ${a}:${s}:${i}`}function aN(e){return typeof e!="number"||!Number.isFinite(e)?null:e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}function It(e){return e&&e!=="unavailable"?e:"-"}function iW(e,t){const n={};e.selectedPrefixes&&e.selectedPrefixes.size===1&&(n.prefix=[...e.selectedPrefixes][0]);const r=e.searchQuery?.trim()??"";r!==""&&e.searchScope==="name"&&(n.names=r),r!==""&&e.searchScope==="actor"&&(n.actor=r),e.runId&&e.runId.trim()!==""&&(n.runId=e.runId.trim());const a=Pu(t);return a&&(n.since=a),n}function jy(e,t,n){if(t.selectedPrefixes.size>=1){const r=e.prefix??e.eventName.split(".")[0]??e.eventName;if(!t.selectedPrefixes.has(r))return!1}if(t.tierFilter!=="all"){const r=n.get(e.eventName);if(r!==t.tierFilter&&!(t.tierFilter==="default"&&r===void 0))return!1}if(t.severity!=="all"&&(e.view??Na(e.eventName,e.payload??null)).severity!==t.severity)return!1;if(t.searchQuery.trim()!==""){const r=t.searchQuery.toLowerCase();let a=!1;if((t.searchScope==="name"||t.searchScope==="all")&&(a=a||e.eventName.toLowerCase().includes(r)),(t.searchScope==="actor"||t.searchScope==="all")&&(a=a||(e.actor?.toLowerCase().includes(r)??!1)),t.searchScope==="payload"&&e.payload&&(a=a||JSON.stringify(e.payload).toLowerCase().includes(r)),!a)return!1}return!(t.runId.trim()!==""&&e.runId!==t.runId.trim())}const $b={key:"time",direction:"desc"};function oW(e,t=$b){const n=e.map((r,a)=>({row:r,idx:a}));return n.sort((r,a)=>{let s=0;const i=r.row.view??Na(r.row.eventName,r.row.payload??null),l=a.row.view??Na(a.row.eventName,a.row.payload??null);switch(t.key){case"time":{const u=Date.parse(r.row.occurredAt),c=Date.parse(a.row.occurredAt),d=Number.isNaN(u)?-1/0:u,p=Number.isNaN(c)?-1/0:c;s=d-p;break}case"severity":{const u=c=>c==="info"?0:c==="warning"?1:2;s=u(i.severity)-u(l.severity);break}case"event":{s=r.row.eventName.localeCompare(a.row.eventName);break}case"summary":{s=(i.summary??"").localeCompare(l.summary??"");break}case"correlation":{s=(i.correlation??"").localeCompare(l.correlation??"");break}case"agent":{s=(i.agent??"").localeCompare(l.agent??"");break}case"outcome":{s=(i.outcome??"").localeCompare(l.outcome??"");break}default:s=0}return s!==0?t.direction==="asc"?s:-s:r.idx-a.idx}),n.map(r=>r.row)}function Vo({value:e,label:t}){const[n,r]=g.useState("idle"),a=async s=>{s.preventDefault(),s.stopPropagation();try{typeof navigator<"u"&&navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),r("copied"),setTimeout(()=>r("idle"),1500)):(r("failed"),setTimeout(()=>r("idle"),2e3))}catch{r("failed"),setTimeout(()=>r("idle"),2e3)}};return!e||e==="-"||e==="unavailable"?null:o.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center justify-center p-0.5 rounded text-base-content/40 hover:text-base-content hover:bg-base-content/10 transition-colors cursor-pointer shrink-0 text-[10px] focus:outline-none focus:ring-1 focus:ring-primary/40",title:n==="copied"?"Copied":n==="failed"?"Copy failed":`Copy ${t}`,"aria-label":n==="copied"?`Copied ${t}`:n==="failed"?`Copy ${t} failed`:`Copy ${t}`,children:[o.jsx("span",{"aria-hidden":"true",children:n==="copied"?"✓":n==="failed"?"!":"📋"}),o.jsx("span",{className:"sr-only","aria-live":"polite",children:n==="copied"?`${t} copied`:n==="failed"?`${t} copy failed`:""})]})}function lW({onLivenessChange:e,timeRange:t}){const[n,r]=g.useState(()=>qG()),[a,s]=g.useState($b),i=g.useCallback(de=>{s(K=>K.key===de?{key:de,direction:K.direction==="asc"?"desc":"asc"}:{key:de,direction:"asc"})},[]),[l,u]=g.useState(!0),[c,d]=g.useState([]),[p,m]=g.useState([]),[f,b]=g.useState("idle"),[x,E]=g.useState(null),[y,S]=g.useState(null),[v,N]=g.useState(!1),[A,w]=g.useState(!1),[T,_]=g.useState(Hc),[B,k]=g.useState(Hc),[$,V]=g.useState("connecting"),{rate:P,recordEvent:H}=ZG();g.useEffect(()=>{e?.({status:l?$:"paused",rate:P,lastEventAt:c[0]?.occurredAt??null})},[l,$,P,c,e]);const W=g.useMemo(()=>{const de=new Map;for(const K of p)K.tier&&de.set(K.name,K.tier);return de},[p]);g.useEffect(()=>{const de=window.setTimeout(()=>{k(T)},250);return()=>window.clearTimeout(de)},[T]);const L=g.useMemo(()=>iW(B,t),[B,t]),te=g.useRef(0);g.useEffect(()=>{const de=++te.current,K=new AbortController;return b("loading"),E(null),(async()=>{try{const Ee=await ht(new Request(Vd({...L,limit:qd}),{signal:K.signal}));if(!Ee.ok){const ye=await Ee.json().catch(()=>null),Se=ye?.code;throw Se==="UNKNOWN_PREFIX"||Se==="MALFORMED_CURSOR"?new Error(`${Se}: ${ye.error??Ee.status}`):new Error(`history fetch failed: ${Ee.status}`)}const re=await Ee.json(),D=Yd(re);if(!D)throw new Error("history response failed schema validation");if(de!==te.current)return;d(D.events),D.catalog&&m(D.catalog),S(D.nextCursor),N(D.hasMore),b("loaded")}catch(Ee){if(K.signal.aborted||de!==te.current)return;E(Ee instanceof Error?Ee.message:String(Ee)),b("error")}})(),()=>K.abort()},[L]);const ie=g.useCallback(async()=>{if(!(!v||A||y===null)){w(!0);try{const de=await ht(new Request(Vd({...L,limit:qd,cursor:y})));if(!de.ok)throw new Error(`history fetch failed: ${de.status}`);const K=await de.json(),Ee=Yd(K);if(!Ee)throw new Error("history response failed schema validation");d(re=>{const D=new Set(re.map(Se=>Se.id)),ye=Ee.events.filter(Se=>!D.has(Se.id));return[...re,...ye]}),Ee.catalog&&m(Ee.catalog),S(Ee.nextCursor),N(Ee.hasMore)}catch(de){E(de instanceof Error?de.message:String(de))}finally{w(!1)}}},[v,A,y,L]),be=g.useRef(T);be.current=T;const I=g.useRef(W);I.current=W,g.useEffect(()=>{if(!l||typeof EventSource>"u")return;V("connecting");const de=new EventSource(YG());return de.onopen=()=>{V("live")},de.onerror=()=>{V("errored")},de.onmessage=K=>{try{const Ee=JSON.parse(K.data),re=JG(Ee);if(!re||re.eventName==="connected")return;const D=be.current,ye=I.current;if(!jy({eventName:re.eventName,occurredAt:re.occurredAt,actor:re.actor,...re.prefix?{prefix:re.prefix}:{},payload:re.payload,view:re.view,...re.runId!==void 0?{runId:re.runId}:{}},D,ye))return;const Se={id:`live-${re.occurredAt}-${re.eventName}`,eventName:re.eventName,occurredAt:re.occurredAt,actor:re.actor,...re.prefix?{prefix:re.prefix}:{},...re.renderer?{renderer:re.renderer}:{},payload:re.payload,...re.envelope?{envelope:re.envelope}:{},view:re.view,...jl(re.runId,re.entityKind,re.entityId,re.sequence)};d(pe=>[Se,...pe]),H()}catch{}},()=>de.close()},[l,H]);const ne=g.useMemo(()=>Array.from(new Set([...p.map(de=>de.prefix),...c.map(de=>de.prefix??de.eventName.split(".")[0]??de.eventName)])).sort(),[p,c]),ue=g.useCallback(()=>{_(Hc)},[]),O=g.useMemo(()=>c.filter(de=>jy(de,T,W)),[c,T,W]),Ne=g.useMemo(()=>oW(O,a),[O,a]);return f==="error"?o.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load event history: ",x]}):f==="idle"||f==="loading"?o.jsxs("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:[o.jsx(Fa,{size:"sm"})," Loading event history…"]}):o.jsxs("div",{className:"flex flex-col gap-4","data-system-events-tab":!0,children:[o.jsx(HG,{filters:T,onFiltersChange:_,onClearFilters:ue,prefixOptions:ne,getPrefixColor:nN,liveEnabled:l,onToggleLive:()=>u(de=>!de),shownCount:O.length,totalCount:c.length,actions:o.jsx(VG,{visibleColumns:n,onVisibleColumnsChange:r})}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 overflow-hidden flex flex-col",children:[Ne.length===0?o.jsx("div",{className:"p-8 text-sm text-spur-text-muted italic text-center",children:c.length===0?"No system events yet. New events from the planning bus will appear here in real time.":"No events match the active filters."}):o.jsx(cW,{rows:Ne,catalog:p,visibleColumns:n,sortState:a,onSortChange:i}),v&&o.jsx("div",{className:"px-4 py-2 border-t border-base-content/10 bg-base-200/50 shrink-0 flex justify-center",children:o.jsx("button",{type:"button",onClick:ie,disabled:A,"data-load-older":!0,className:"text-[11px] text-spur-text-muted hover:text-spur-text px-3 py-1 rounded border border-spur-border/40 hover:border-spur-text/40 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait focus:outline-none focus:ring-2 focus:ring-spur-text/40",children:A?"Loading…":"Load older"})})]})]})}function uW(e){const[t,n]=g.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches);return g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),a=s=>n(s.matches);return r.addEventListener("change",a),n(r.matches),()=>r.removeEventListener("change",a)},[e]),t}function cW({rows:e,catalog:t,visibleColumns:n=ra,sortState:r=$b,onSortChange:a=()=>{}}){const s=g.useMemo(()=>{const u=new Map;for(const c of t)c.tier&&u.set(c.name,c.tier);return u},[t]),i=uW("(max-width: 639px)"),l=g.useMemo(()=>new Map(us.map(u=>[u.key,u])),[]);return o.jsx("section",{className:"overflow-x-auto min-w-0","data-system-events-tab":!0,"aria-label":"System events",children:o.jsxs("table",{className:`w-full ${i?"min-w-0":"min-w-[1000px]"} text-xs border-separate border-spacing-0 table-fixed`,children:[o.jsx("colgroup",{children:i?o.jsxs(o.Fragment,{children:[o.jsx("col",{className:"w-24"}),o.jsx("col",{className:"w-full"})]}):n.map(u=>o.jsx("col",{className:l.get(u)?.colWidth??"w-24"},u))}),o.jsx("thead",{className:"sticky top-0 z-10 bg-base-200",children:o.jsx("tr",{className:"text-left text-spur-text-muted uppercase tracking-wide text-[10px]",children:i?o.jsxs(o.Fragment,{children:[o.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:"Time"}),o.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:"Event"})]}):n.map(u=>{const c=l.get(u);if(!c)return null;const d=r.key===u,p=d?r.direction==="asc"?" ▲":" ▼":"",m=d?r.direction==="asc"?"ascending":"descending":"none";return c.sortable?o.jsx("th",{scope:"col","aria-sort":m,className:"font-semibold px-3 py-1.5 border-b border-spur-border select-none",children:o.jsxs("button",{type:"button",onClick:()=>a(u),className:"flex items-center gap-1 uppercase tracking-wide text-[10px] font-semibold text-spur-text-muted hover:text-spur-text transition-colors cursor-pointer bg-transparent border-0 p-0 focus:outline-none focus:ring-1 focus:ring-primary/40 rounded",children:[o.jsx("span",{children:c.label}),p&&o.jsx("span",{"aria-hidden":"true",children:p})]})},u):o.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:c.label},u)})})}),o.jsx("tbody",{children:e.map(u=>o.jsx(dW,{event:u,tier:s.get(u.eventName)??"default",compact:i,visibleColumns:n},u.id))})]})})}const Gc="system-events-payload-tooltip-pin";function Wc({severity:e}){const t=g.useMemo(()=>{switch(e){case"error":return{icon:"✕",badgeClass:"bg-error/15 text-error border-error/30"};case"warning":return{icon:"▲",badgeClass:"bg-warning/15 text-warning border-warning/30"};default:return{icon:"●",badgeClass:"bg-base-content/10 text-base-content/70 border-base-content/20"}}},[e]);return o.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-semibold border ${t.badgeClass} whitespace-nowrap`,children:[o.jsx("span",{"aria-hidden":"true",children:t.icon}),o.jsx("span",{children:e})]})}function dW({event:e,tier:t,compact:n,visibleColumns:r=ra}){const a=e.prefix??e.eventName.split(".")[0]??e.eventName,s=g.useMemo(()=>e.view??Na(e.eventName,e.payload??null),[e.eventName,e.payload,e.view]),i=nN(a),[l,u]=g.useState(!1),[c,d]=g.useState(!1),[p,m]=g.useState(!1),[f,b]=g.useState(null),x=g.useRef(null),E=g.useRef(null),y=g.useRef(0),S=g.useRef(null),v=It(e.actor),N=c||p,A=g.useCallback(()=>{S.current!==null&&(clearTimeout(S.current),S.current=null)},[]),w=g.useCallback(()=>{m(!1),b(null)},[]),T=g.useCallback((P,H)=>{y.current=performance.now()+400,m(!0),d(!1),A();const W=Number.isFinite(P)&&P>0?P:8,L=Number.isFinite(H)&&H>0?H:8;b({x:W,y:L}),window.dispatchEvent(new CustomEvent(Gc,{detail:{id:e.id}}))},[e.id,A]),_=g.useCallback((P,H,W)=>{const L=P.getBoundingClientRect(),te=H&&H>0?H:L.left,ie=W&&W>0?W+4:L.bottom+6;T(te,ie)},[T]);g.useEffect(()=>{const P=H=>{H.detail?.id!==e.id&&w()};return window.addEventListener(Gc,P),()=>window.removeEventListener(Gc,P)},[e.id,w]),g.useEffect(()=>{if(!p)return;const P=W=>{performance.now()<y.current||x.current?.contains(W.target)||E.current?.contains(W.target)||w()},H=W=>{W.key==="Escape"&&(w(),W.stopPropagation())};return document.addEventListener("pointerdown",P,!0),document.addEventListener("keydown",H,!0),()=>{document.removeEventListener("pointerdown",P,!0),document.removeEventListener("keydown",H,!0)}},[p,w]),g.useEffect(()=>()=>{A()},[A]);const B=g.useCallback(()=>u(P=>!P),[]),k=g.useCallback(P=>{if(P.key==="Escape"){if(p){w(),P.stopPropagation();return}u(!1),P.stopPropagation()}},[p,w]),$=N?o.jsxs("div",{ref:x,id:`system-event-tooltip-${e.id}`,role:"tooltip","data-testid":"system-event-payload-tooltip","data-pinned":p?"true":"false",className:p?"pointer-events-auto fixed z-50 rounded shadow-lg p-2.5 text-[11px] min-w-[min(400px,90vw)] max-w-[min(840px,95vw)] whitespace-normal border border-[#30363d] bg-[#0d1117] text-[#c9d1d9] select-text cursor-text":"pointer-events-auto absolute left-0 top-full mt-1 z-30 rounded shadow-lg p-2.5 text-[11px] min-w-[min(400px,90vw)] max-w-[min(840px,95vw)] whitespace-normal border border-[#30363d] bg-[#0d1117] text-[#c9d1d9]",style:p&&f?{top:f.y,left:f.x}:void 0,onMouseEnter:()=>{A(),d(!0)},onMouseLeave:()=>{p||(A(),S.current=setTimeout(()=>d(!1),150))},onFocusCapture:()=>d(!0),onBlurCapture:P=>{!p&&!P.currentTarget.contains(P.relatedTarget)&&d(!1)},onPointerDown:P=>{p&&P.stopPropagation()},children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[o.jsx("div",{className:"text-[11px] font-sans font-semibold text-[#c9d1d9] truncate","data-testid":"system-event-tooltip-title",children:aW(e,s)}),o.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[!p&&o.jsx("button",{type:"button","data-testid":"system-event-payload-tooltip-pin",className:"text-[10px] text-[#c9d1d9] hover:text-white px-1.5 py-0.5 rounded border border-[#30363d] bg-[#21262d] cursor-pointer",onClick:P=>{P.stopPropagation(),P.preventDefault();const H=E.current;H?_(H):T(P.clientX,P.clientY)},children:"Pin"}),p&&o.jsx("button",{type:"button","data-testid":"system-event-payload-tooltip-close",className:"text-[10px] text-[#8b949e] hover:text-[#c9d1d9] px-1 rounded border border-[#30363d] cursor-pointer",onClick:P=>{P.stopPropagation(),w()},children:"close"})]})]}),o.jsx("p",{className:"mb-2 text-spur-text leading-relaxed","data-testid":"system-event-description",children:s.description}),o.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 max-h-80 overflow-y-auto",children:[o.jsx("dt",{className:"text-spur-text-muted",children:"Summary"}),o.jsx("dd",{className:"break-words",children:It(s.summary)}),o.jsx("dt",{className:"text-spur-text-muted",children:"Severity"}),o.jsx("dd",{children:o.jsx(Wc,{severity:s.severity})}),s.fields.map(P=>o.jsxs("div",{className:"contents",children:[o.jsx("dt",{className:"text-spur-text-muted",children:P.label}),o.jsx("dd",{className:"font-mono break-all",children:It(P.value)})]},P.label+P.value)),o.jsx("dt",{className:"text-spur-text-muted",children:"Producer"}),o.jsx("dd",{className:"font-mono break-all",children:It(s.producer)}),s.correlationFields.length>0?s.correlationFields.map(P=>o.jsxs("div",{className:"contents",children:[o.jsx("dt",{className:"text-spur-text-muted",children:P.label}),o.jsx("dd",{className:"font-mono break-all",children:It(P.value)})]},`correlation-${P.label}`)):o.jsxs(o.Fragment,{children:[o.jsx("dt",{className:"text-spur-text-muted",children:"Correlation"}),o.jsx("dd",{className:"font-mono",children:"-"})]}),o.jsx("dt",{className:"text-spur-text-muted",children:"Outcome"}),o.jsx("dd",{className:"font-mono break-all",children:It(s.outcome)})]}),s.action&&o.jsxs("div",{className:"mt-2 border-t border-[#30363d] pt-2","data-testid":"system-event-remediation",children:[o.jsx("div",{className:"text-spur-text-muted",children:s.action.label}),o.jsx("code",{className:"block mt-0.5 font-mono break-all select-text",children:s.action.value})]}),o.jsx("div",{className:"mt-2 border-t border-[#30363d] pt-1.5 text-[10px] text-[#8b949e] font-sans","data-testid":"system-event-tooltip-footer",children:p?"Select to copy · Esc or outside click to close":"Click event name or Pin to lock for copy"})]}):null,V=P=>{switch(P){case"time":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-spur-text-muted whitespace-nowrap align-middle",children:Fy(e.occurredAt)},"time");case"severity":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 align-middle text-[10px]",children:o.jsx(Wc,{severity:s.severity})},"severity");case"event":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 relative align-middle min-w-0",children:o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("button",{type:"button","aria-expanded":l,"aria-controls":`detail-${e.id}`,"aria-label":`${l?"Collapse":"Expand"} detail for ${e.eventName}`,onClick:B,onKeyDown:k,className:"inline-flex items-center justify-center w-4 h-4 text-spur-text-muted hover:text-spur-text text-[10px] transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-spur-text/40 shrink-0",children:l?"▾":"▸"}),o.jsxs("div",{className:"relative min-w-0 max-w-full flex items-center gap-1",children:[o.jsx("button",{ref:E,type:"button",className:`font-mono font-semibold truncate block max-w-full text-left cursor-pointer bg-transparent border-0 p-0 ${i}`,"data-testid":"system-event-name","aria-label":`Context for ${e.eventName}. Hover to preview; click to pin for select and copy.`,"aria-describedby":N?`system-event-tooltip-${e.id}`:void 0,onMouseEnter:()=>{A(),d(!0)},onFocus:()=>{A(),d(!0)},onBlur:H=>{!p&&!x.current?.contains(H.relatedTarget)&&d(!1)},onMouseLeave:()=>{A(),S.current=setTimeout(()=>{p||d(!1)},200)},onClick:H=>{H.preventDefault(),H.stopPropagation(),!p&&_(H.currentTarget,H.clientX,H.clientY)},onKeyDown:H=>{if(H.key==="Enter"||H.key===" "){if(H.preventDefault(),p)return;_(H.currentTarget)}},children:e.eventName}),o.jsx(Vo,{value:e.eventName,label:"event name"}),!p&&$]})]})},"event");case"summary":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 text-spur-text align-middle truncate",title:It(s.summary),children:It(s.summary)},"summary");case"correlation":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle",children:o.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[o.jsx("span",{className:"truncate",title:It(s.correlation),children:It(s.correlation)}),s.correlation&&s.correlation!=="unavailable"&&o.jsx(Vo,{value:s.correlation,label:"correlation"})]})},"correlation");case"outcome":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:It(s.outcome),children:It(s.outcome)},"outcome");case"agent":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:s.agent??"",children:s.agent??""},"agent");case"producer":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:It(s.producer),children:It(s.producer)},"producer");case"action":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:It(s.actionLabel),children:It(s.actionLabel)},"action");case"actor":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:v,children:v},"actor")}};return o.jsxs(o.Fragment,{children:[o.jsx("tr",{className:"group hover:bg-base-200/60 transition-colors",style:{height:n?void 0:28},children:n?o.jsxs(o.Fragment,{children:[o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-spur-text-muted whitespace-nowrap align-middle",children:Fy(e.occurredAt)}),o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 relative align-middle min-w-0",children:o.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("button",{type:"button","aria-expanded":l,"aria-controls":`detail-${e.id}`,"aria-label":`${l?"Collapse":"Expand"} detail for ${e.eventName}`,onClick:B,onKeyDown:k,className:"inline-flex items-center justify-center w-4 h-4 text-spur-text-muted hover:text-spur-text text-[10px] transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-spur-text/40 shrink-0",children:l?"▾":"▸"}),o.jsxs("div",{className:"relative min-w-0 max-w-full flex items-center gap-1",children:[o.jsx("button",{ref:E,type:"button",className:`font-mono font-semibold truncate block max-w-full text-left cursor-pointer bg-transparent border-0 p-0 ${i}`,"data-testid":"system-event-name","aria-label":`Context for ${e.eventName}. Hover to preview; click to pin for select and copy.`,"aria-describedby":N?`system-event-tooltip-${e.id}`:void 0,onMouseEnter:()=>{A(),d(!0)},onFocus:()=>{A(),d(!0)},onBlur:P=>{!p&&!x.current?.contains(P.relatedTarget)&&d(!1)},onMouseLeave:()=>{A(),S.current=setTimeout(()=>{p||d(!1)},200)},onClick:P=>{P.preventDefault(),P.stopPropagation(),!p&&_(P.currentTarget,P.clientX,P.clientY)},onKeyDown:P=>{if(P.key==="Enter"||P.key===" "){if(P.preventDefault(),p)return;_(P.currentTarget)}},children:e.eventName}),o.jsx(Vo,{value:e.eventName,label:"event name"}),!p&&$]})]}),o.jsxs("div",{className:"flex flex-col gap-0.5 text-[10px] text-spur-text-muted min-w-0",children:[o.jsx(Wc,{severity:s.severity}),o.jsx("span",{className:"truncate text-spur-text",title:It(s.summary),children:It(s.summary)}),o.jsx("span",{className:"truncate",title:It(s.producer),children:It(s.producer)}),o.jsx("span",{className:"truncate",title:It(s.correlation),children:It(s.correlation)}),s.agent&&o.jsxs("span",{className:"truncate font-mono",title:s.agent,children:["agent: ",s.agent]}),o.jsxs("span",{className:"truncate",children:["outcome: ",It(s.outcome)]}),o.jsxs("span",{className:"truncate",title:It(s.actionLabel),children:["action: ",It(s.actionLabel)]})]})]})})]}):r.map(P=>V(P))}),l&&o.jsx("tr",{children:o.jsx("td",{colSpan:n?2:r.length,className:"px-3 py-2 border-b border-spur-border/40 bg-base-300/40",children:o.jsxs("section",{id:`detail-${e.id}`,"aria-label":`Detail for ${e.eventName}`,onKeyDown:k,tabIndex:-1,className:"flex flex-col gap-2 text-[11px] text-spur-text max-w-full",children:[o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 font-mono text-[10px]",children:[o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"project:"})," ",It(s.projectName)]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"root:"})," ",It(s.projectRoot)]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"producer:"})," ",It(s.producer)]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"correlation:"})," ",It(s.correlation)]}),e.runId&&o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx("span",{className:"text-spur-text-muted",children:"runId:"})," ",e.runId," ",o.jsx(Vo,{value:e.runId,label:"run ID"})]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"agent:"})," ",s.agent||"-"]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"actor:"})," ",v]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"prefix:"})," ",a]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"tier:"})," ",t]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"outcome:"})," ",It(s.outcome)]})]}),s.fields.length>0&&o.jsx("dl",{className:"space-y-0.5",children:s.fields.map(P=>o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("dt",{className:"text-spur-text-muted shrink-0",children:[P.label,":"]}),o.jsx("dd",{className:"font-mono break-all",children:It(P.value)})]},P.label+P.value))}),o.jsxs("div",{className:"border-t border-spur-border/40 pt-1",children:[o.jsx("div",{className:"text-spur-text-muted text-[10px] mb-0.5",children:"payload (redacted):"}),o.jsx("pre",{className:"font-mono text-[10px] text-spur-text-muted overflow-x-auto whitespace-pre-wrap break-all",children:e.envelope?JSON.stringify(e.envelope,null,2):"-"})]}),o.jsx("button",{type:"button",onClick:()=>u(!1),className:"self-start text-[10px] text-spur-text-muted hover:text-error px-2 py-0.5 rounded border border-spur-border/40 hover:border-error/40 transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-spur-text/40",children:"Close (Esc)"})]})})}),p&&$&&typeof document<"u"?na.createPortal($,document.body):null]})}function pW(e){if(!e.payload)return;if(typeof e.payload.jobId=="string")return e.payload.jobId;const n=e.payload.context?.correlation;if(typeof n?.jobId=="string")return n.jobId}function fW(e){switch(e){case"completed":return"success";case"processing":return"info";case"failed":return"error";default:return"neutral"}}function mW({job:e,onClose:t,onNavigate:n}){const[r,a]=g.useState([]),[s,i]=g.useState(null),[l,u]=g.useState(!1),c=g.useRef(0);return g.useEffect(()=>{if(!e){a([]),i(null);return}const d=f=>{f.key==="Escape"&&t()};window.addEventListener("keydown",d);const p=new AbortController,m=++c.current;return u(!0),(async()=>{try{const f=Vd({prefix:"queue",since:e.queuedAt,limit:200}),b=await ht(new Request(f,{signal:p.signal}));if(!b.ok)throw new Error(`HTTP ${b.status}`);const x=Yd(await b.json());if(p.signal.aborted||m!==c.current)return;const E=(x?.events??[]).filter(S=>pW(S)===e.id);i(E.length);const y=E.map(S=>{const v=S.payload;return{id:S.id,eventName:S.eventName,occurredAt:S.occurredAt,error:typeof v?.error=="string"?v.error:void 0,attempt:typeof v?.attempt=="number"?v.attempt:void 0}});e.startedAt&&y.push({id:`synth-started-${e.id}`,eventName:"queue.job.started",occurredAt:e.startedAt,derived:!0}),y.sort((S,v)=>new Date(S.occurredAt).getTime()-new Date(v.occurredAt).getTime()),a(y)}catch{if(p.signal.aborted||m!==c.current)return;i(0);const f=[];e.startedAt&&f.push({id:`synth-started-${e.id}`,eventName:"queue.job.started",occurredAt:e.startedAt,derived:!0}),a(f)}finally{!p.signal.aborted&&m===c.current&&u(!1)}})(),()=>{window.removeEventListener("keydown",d),p.abort()}},[e,t]),e?o.jsx("div",{className:"fixed inset-0 z-50 flex justify-end bg-black/60 backdrop-blur-xs",onClick:t,onKeyDown:d=>{d.key==="Escape"&&t()},role:"dialog","aria-modal":"true","aria-label":`Job details for ${e.id}`,"data-testid":"job-detail-drawer",children:o.jsxs("div",{className:"w-full max-w-xl h-full bg-base-100 border-l border-base-content/10 shadow-2xl flex flex-col overflow-hidden",onClick:d=>d.stopPropagation(),onKeyDown:d=>d.stopPropagation(),role:"document",children:[o.jsxs("div",{className:"px-5 py-4 border-b border-base-content/10 flex items-center justify-between bg-base-200/50",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(gn,{variant:fW(e.status),size:"sm",children:e.status}),o.jsx("span",{className:"font-mono text-sm font-semibold text-base-content truncate max-w-xs",children:e.id})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[n&&o.jsx(ot,{variant:"outline",size:"xs","data-testid":"navigate-system-events-btn",onClick:()=>n({tab:"system-events",runId:e.id}),children:"View in System Events"}),o.jsx(ot,{variant:"ghost",size:"xs",onClick:t,"aria-label":"Close drawer","data-testid":"close-job-drawer",children:"✕"})]})]}),o.jsxs("div",{className:"p-5 flex-1 overflow-y-auto space-y-5",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3 bg-base-200/40 p-3 rounded-lg border border-base-content/10 text-xs font-mono",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Type"}),o.jsx("span",{className:"font-semibold text-base-content",children:e.type})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Attempts"}),o.jsxs("span",{className:"text-base-content",children:[e.attempts," / ",e.maxRetries]})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Queued At"}),o.jsx("span",{className:"text-base-content",children:new Date(e.queuedAt).toLocaleString()})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Started At"}),o.jsx("span",{className:"text-base-content",children:e.startedAt?new Date(e.startedAt).toLocaleString():"—"})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Ended At"}),o.jsx("span",{className:"text-base-content",children:e.endedAt?new Date(e.endedAt).toLocaleString():"—"})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Duration"}),o.jsx("span",{className:"text-base-content",children:e.durationMs!==null?aN(e.durationMs):"—"})]})]}),e.lastError&&o.jsxs("div",{className:"p-3 rounded-lg bg-error/10 border border-error/20 text-error text-xs font-mono whitespace-pre-wrap break-words",children:[o.jsx("span",{className:"font-bold block mb-1",children:"Last Error:"}),e.lastError]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Payload"}),o.jsx("div",{className:"bg-base-200 p-3 rounded-lg border border-base-content/10 font-mono text-xs overflow-x-auto max-h-48 text-base-content/90",children:e.payload?o.jsx("pre",{className:"whitespace-pre-wrap",children:JSON.stringify(e.payload,null,2)}):o.jsx("span",{className:"text-base-content/50 italic",children:"payload unavailable"})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Lifecycle Timeline"}),l&&o.jsx("span",{className:"text-[10px] text-base-content/50",children:"Loading…"})]}),s===0&&!l&&o.jsxs("div",{className:"p-4 rounded-lg border border-base-content/10 bg-base-200/40 text-xs text-base-content/60 italic","data-testid":"empty-lifecycle-timeline",children:["No lifecycle events recorded. Queue lifecycle events are diagnostic-tier — set"," ",o.jsx("code",{className:"font-mono text-base-content",children:"SPUR_DIAGNOSTIC_EVENTS=1"})," to capture them."]}),r.length>0&&o.jsx("div",{className:"space-y-2 font-mono text-xs","data-testid":"lifecycle-timeline-list",children:r.map(d=>o.jsxs("div",{className:"p-2.5 rounded-lg border border-base-content/10 bg-base-200/60 flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[o.jsx("span",{className:"font-semibold text-base-content",children:d.eventName}),d.derived&&o.jsx(gn,{size:"xs",variant:"outline",children:"derived"}),d.attempt!==void 0&&o.jsxs(gn,{size:"xs",variant:"neutral",children:["attempt ",d.attempt]}),d.error&&o.jsx("span",{className:"text-error truncate max-w-xs",children:d.error})]}),o.jsx("span",{className:"text-[11px] text-base-content/50 shrink-0",children:new Date(d.occurredAt).toLocaleTimeString()})]},d.id))})]})]})]})}):null}function hW(e){switch(e){case"failed":return"failed";case"running":return"processing";case"completed":return"completed";default:return}}function gW(e){switch(e){case"completed":return"success";case"processing":return"info";case"failed":return"error";default:return"neutral"}}const bW=()=>{const[e,t]=g.useState(null),[n,r]=g.useState(null),[a,s]=g.useState(!0);return g.useEffect(()=>{const i=new AbortController;return(async()=>{try{const l=await ht(new Request(`${Ct()}/jobs/schedules`,{signal:i.signal}));if(!l.ok)throw new Error(`HTTP ${l.status}`);const u=await l.json();if(i.signal.aborted)return;t(u.schedules)}catch(l){if(i.signal.aborted)return;r(l instanceof Error?l.message:String(l))}finally{i.signal.aborted||s(!1)}})(),()=>i.abort()},[]),o.jsxs("div",{className:"p-4 rounded-xl border border-base-content/10 bg-base-200/80 shadow-xs space-y-3","data-testid":"active-schedules-card",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/70",children:"Active Schedules"}),e&&o.jsx(gn,{size:"xs",variant:"outline",children:e.length})]}),o.jsx("span",{className:"text-[11px] text-base-content/50",children:"Recurring background cron jobs"})]}),a?o.jsx("div",{className:"text-xs text-base-content/50 py-2",children:"Loading schedules…"}):n?o.jsxs("div",{className:"text-xs text-error/80 py-1","data-testid":"schedules-error",children:["Schedules unavailable: ",n]}):!e||e.length===0?o.jsx("div",{className:"text-xs text-base-content/50 py-2 italic",children:"No active schedules registered."}):o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2.5 font-mono text-xs",children:e.map(i=>o.jsxs("div",{className:"p-2.5 rounded-lg border border-base-content/10 bg-base-100 flex flex-col gap-1.5","data-testid":`schedule-item-${i.name}`,children:[o.jsxs("div",{className:"flex items-center justify-between gap-1",children:[o.jsx("span",{className:"font-semibold text-base-content truncate",children:i.name}),o.jsx(gn,{size:"xs",variant:i.source==="builtin"?"neutral":"info",children:i.source})]}),o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-base-content/60",children:[o.jsx("span",{children:i.cadence}),o.jsx("span",{className:"text-base-content/40",children:i.cron})]}),o.jsxs("div",{className:"flex items-center justify-between text-[10px] text-base-content/50 border-t border-base-content/5 pt-1 mt-0.5",children:[o.jsx("span",{children:i.nextFireAt===null?"next run: cron (unknown)":`next: ${new Date(i.nextFireAt).toLocaleTimeString()}`}),o.jsx("span",{children:i.lastStatus==="none"?"never run":i.lastStatus})]})]},i.name))})]})};function xW({timeRange:e,onNavigate:t}){const[n,r]=g.useState("all"),[a,s]=g.useState([]),[i,l]=g.useState({all:0,pending:0,processing:0,completed:0,failed:0}),[u,c]=g.useState(!1),[d,p]=g.useState(0),[m,f]=g.useState(!0),[b,x]=g.useState(null),[E,y]=g.useState(new Set),[S,v]=g.useState(null),N=g.useRef(0),A=g.useRef({timeRange:e,statusFilter:n});g.useEffect(()=>{const _=new AbortController,B=++N.current;return f(!0),x(null),(async()=>{try{const k=A.current.timeRange!==e||A.current.statusFilter!==n;k&&(A.current={timeRange:e,statusFilter:n});const $=k?0:d;k&&d!==0&&p(0);const V=Pu(e),P=new URLSearchParams,H=hW(n);H&&P.set("status",H),V&&P.set("since",V),P.set("limit","100"),P.set("offset",String($));const W=await ht(new Request(`${Ct()}/jobs?${P.toString()}`,{signal:_.signal}));if(!W.ok){const te=await W.text();throw new Error(`HTTP ${W.status}: ${te||W.statusText}`)}const L=await W.json();if(_.signal.aborted||B!==N.current)return;s($===0?L.jobs:te=>[...te,...L.jobs]),l(L.countsByStatus),c(L.hasMore),f(!1)}catch(k){if(_.signal.aborted||B!==N.current)return;x(k instanceof Error?k.message:String(k)),f(!1)}})(),()=>_.abort()},[e,n,d]);const w=(_,B)=>{B.stopPropagation(),y(k=>{const $=new Set(k);return $.has(_)?$.delete(_):$.add(_),$})},T=[{id:"all",label:"All",count:i.all},{id:"failed",label:"Failed",count:i.failed},{id:"running",label:"Running",count:i.processing},{id:"completed",label:"Completed",count:i.completed}];return o.jsxs("div",{className:"flex flex-col gap-4","data-jobs-tab":!0,"data-testid":"observability-jobs-tab",children:[o.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[o.jsx("div",{className:"flex items-center gap-1.5","data-testid":"job-status-chips",children:T.map(_=>{const B=n===_.id;return o.jsxs("button",{type:"button",onClick:()=>r(_.id),"data-testid":`status-chip-${_.id}`,className:`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-semibold rounded-full transition-colors cursor-pointer ${B?_.id==="failed"?"bg-error text-error-content":"bg-neutral text-neutral-content":"bg-base-100 text-base-content/70 hover:bg-base-200 border border-base-content/10"}`,children:[o.jsx("span",{children:_.label}),o.jsx("span",{className:`px-1.5 py-0.2 text-[10px] rounded-full ${B?"bg-base-100/20":"bg-base-200 text-base-content/70"}`,children:_.count.toLocaleString()})]},_.id)})}),o.jsx(eN,{})]}),i.failed>0&&o.jsxs("div",{className:"p-3 rounded-xl bg-error/10 border border-error/20 flex items-center justify-between text-xs text-error font-medium","data-testid":"jobs-failure-banner",children:[o.jsxs("span",{children:["⚠️ ",i.failed," ",i.failed===1?"job":"jobs"," failed in this window"]}),o.jsx("button",{type:"button",className:"px-2.5 py-1 text-xs font-semibold rounded-lg border border-error text-error hover:bg-error hover:text-error-content transition-colors cursor-pointer","data-testid":"filter-to-failed-btn",onClick:()=>r("failed"),children:"Filter to Failed"})]}),o.jsx(bW,{}),o.jsxs("div",{className:"rounded-xl border border-base-content/10 bg-base-200/50 shadow-xs overflow-hidden flex flex-col",children:[o.jsxs("div",{className:"px-4 py-3 border-b border-base-content/10 bg-base-200 flex items-center justify-between flex-wrap gap-2",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/70",children:"Queue Jobs"}),o.jsxs("span",{className:"text-xs text-base-content/50 font-mono",children:["Showing ",a.length," of ",i.all," job(s)"]})]}),b?o.jsxs("div",{className:"p-4 text-xs text-error",role:"alert","data-testid":"jobs-table-error",children:["Failed to load jobs: ",b]}):m&&a.length===0?o.jsxs("div",{className:"flex items-center justify-center h-32 text-base-content/50 text-sm",children:[o.jsx(Fa,{size:"sm"})," Loading jobs…"]}):a.length===0?o.jsx("div",{className:"p-8 text-center text-xs text-base-content/50 italic","data-testid":"jobs-empty-state",children:"No jobs found in this time range."}):o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"table table-xs w-full font-mono text-xs","data-testid":"queue-jobs-table",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{children:"Status"}),o.jsx("th",{children:"Job Type"}),o.jsx("th",{children:"Enqueued At"}),o.jsx("th",{children:"Started At"}),o.jsx("th",{children:"Duration"}),o.jsx("th",{children:"Attempts"}),o.jsx("th",{children:"Error"})]})}),o.jsx("tbody",{children:a.map(_=>{const B=E.has(_.id);return o.jsxs("tr",{className:"hover:bg-base-300/40 cursor-pointer transition-colors",onClick:()=>v(_),"data-testid":`job-row-${_.id}`,children:[o.jsx("td",{children:o.jsx(gn,{size:"xs",variant:gW(_.status),children:_.status})}),o.jsx("td",{className:"font-semibold text-base-content",children:_.type}),o.jsx("td",{className:"text-base-content/60",children:new Date(_.queuedAt).toLocaleTimeString()}),o.jsx("td",{className:"text-base-content/60",children:_.startedAt?new Date(_.startedAt).toLocaleTimeString():"—"}),o.jsx("td",{className:"text-base-content/80",children:_.durationMs!==null?aN(_.durationMs):"—"}),o.jsxs("td",{className:"text-base-content/60",children:[_.attempts," / ",_.maxRetries]}),o.jsx("td",{className:"max-w-xs",children:_.lastError?o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("div",{className:`text-error ${B?"whitespace-pre-wrap":"truncate"}`,"data-testid":`job-error-${_.id}`,children:_.lastError}),o.jsx("button",{type:"button",className:"text-[10px] text-base-content/60 hover:text-base-content underline self-start","data-testid":`expand-error-btn-${_.id}`,onClick:k=>w(_.id,k),children:B?"Hide":"Details"})]}):null})]},_.id)})})]})}),u&&o.jsx("div",{className:"p-3 border-t border-base-content/10 flex justify-center bg-base-200/30",children:o.jsx(ot,{variant:"ghost",size:"xs",disabled:m,onClick:()=>p(_=>_+100),"data-testid":"jobs-load-more-btn",children:m?"Loading…":"Load more"})})]}),o.jsx(mW,{job:S,onClose:()=>v(null),onNavigate:t})]})}function Py(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.inputTokens!="number"||typeof t.outputTokens!="number"||typeof t.cacheReadTokens!="number"||typeof t.cacheCreationTokens!="number"||typeof t.records!="number"||typeof t.recordsWithUsage!="number"?null:{inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheReadTokens:t.cacheReadTokens,cacheCreationTokens:t.cacheCreationTokens,records:t.records,recordsWithUsage:t.recordsWithUsage}}function EW(e){if(e===null||typeof e!="object")return null;const t=e;return!(t.role===null||typeof t.role=="string")||typeof t.totalRuns!="number"||typeof t.matchedRuns!="number"||typeof t.unmeasured!="boolean"?null:{role:t.role,totalRuns:t.totalRuns,matchedRuns:t.matchedRuns,exact:Py(t.exact),estimated:Py(t.estimated),unmeasured:t.unmeasured}}function yW(e){if(e===null||typeof e!="object")return null;const t=e;return!(t.role===null||typeof t.role=="string")||typeof t.executor!="string"||!(t.source===null||typeof t.source=="string")||typeof t.runs!="number"||typeof t.escalations!="number"?null:{role:t.role,executor:t.executor,source:t.source,runs:t.runs,escalations:t.escalations}}function TW(e){if(e===null||typeof e!="object")return null;const t=e,n=t.routing,r=t.tokens;if(n===null||typeof n!="object"||r===null||typeof r!="object")return null;const a=n,s=r,i=a.window;if(i===null||typeof i!="object")return null;const l=i;if(typeof l.since!="string"||typeof l.until!="string"||!Array.isArray(a.pairs)||!Array.isArray(s.roles))return null;const u=[];for(const d of a.pairs){const p=yW(d);p&&u.push(p)}const c=[];for(const d of s.roles){const p=EW(d);p&&c.push(p)}return{window:{since:l.since,until:l.until},pairs:u,roles:c}}function SW(e){switch(e){case"explicit":return"pinned";case"role":return"resolved";case"default":return"default";case null:return"—";default:return e}}const vW=new Intl.NumberFormat("en-US");function as(e){return vW.format(e)}function By({label:e,totals:t}){return o.jsxs("div",{"data-token-bucket":e,className:"text-xs",children:[o.jsx(gn,{size:"xs",variant:e==="estimated"?"warning":"success",children:e}),o.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-0.5 mt-1",children:[o.jsx("dt",{className:"text-spur-text-muted",children:"input"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.inputTokens)}),o.jsx("dt",{className:"text-spur-text-muted",children:"cache read"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.cacheReadTokens)}),o.jsx("dt",{className:"text-spur-text-muted",children:"cache write"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.cacheCreationTokens)}),o.jsx("dt",{className:"text-spur-text-muted",children:"output"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.outputTokens)})]})]})}function wW({role:e}){const t=e.role??"—";return o.jsxs("div",{className:"bg-base-100 border border-spur-border rounded-md p-3","data-role-attribution":t,children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-sm font-semibold text-spur-text",children:t}),o.jsxs("span",{className:"text-[10px] text-spur-text-muted tabular-nums",children:["matched ",e.matchedRuns," of ",e.totalRuns," runs"]})]}),e.unmeasured?o.jsxs("div",{className:"mt-1 text-xs","data-unmeasured":!0,children:[o.jsx(gn,{size:"xs",variant:"ghost",children:"unmeasured"}),o.jsx("span",{className:"ml-1 text-spur-text-muted",children:"no token data recorded for this role — not a measured zero"})]}):o.jsxs("div",{className:"mt-2 flex flex-wrap gap-4",children:[e.exact?o.jsx(By,{label:"exact",totals:e.exact}):null,e.estimated?o.jsx(By,{label:"estimated",totals:e.estimated}):null]})]})}function NW({timeRange:e}){const[t,n]=g.useState(null),[r,a]=g.useState(null);if(g.useEffect(()=>{const i=new AbortController,l=Pu(e),u=Ct(),c=l?`${u}/observability/routing-summary?since=${encodeURIComponent(l)}`:`${u}/observability/routing-summary`;return(async()=>{try{const d=await ht(new Request(c,{signal:i.signal}));if(!d.ok)throw new Error(`routing summary fetch failed: ${d.status}`);const p=TW(await d.json());if(!p)throw new Error("routing summary response failed schema validation");n(p)}catch(d){if(i.signal.aborted)return;a(d instanceof Error?d.message:String(d))}})(),()=>i.abort()},[e]),r)return o.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load routing summary: ",r]});if(t===null)return o.jsxs("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:[o.jsx(Fa,{size:"sm"})," Loading routing summary…"]});const s=t.pairs.length===0&&t.roles.length===0;return o.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-routing-tab":!0,children:[o.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-base-200 shrink-0 flex items-baseline justify-between",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Routing & token consumption"}),o.jsxs("span",{className:"text-[10px] text-spur-text-muted tabular-nums","data-covered-window":!0,children:["covered ",t.window.since," → ",t.window.until]})]}),s?o.jsx("div",{className:"flex-1 flex items-center justify-center p-4","data-routing-empty":!0,children:o.jsx("div",{className:"text-sm text-spur-text-muted italic",children:"No routing attribution has been recorded in the covered window — nothing to show yet."})}):o.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[t.pairs.length>0?o.jsxs("section",{className:"bg-base-100 border border-spur-border rounded-md","data-routing-table":!0,children:[o.jsxs("div",{className:"px-3 py-2 border-b border-spur-border",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Role → executor"}),o.jsx("span",{className:"ml-2 text-[10px] text-spur-text-muted",children:"runs and escalations per pair; pinned and role-resolved counted separately"})]}),o.jsxs("table",{className:"table table-sm w-full",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"text-[10px] uppercase text-spur-text-muted",children:[o.jsx("th",{children:"Role"}),o.jsx("th",{children:"Executor"}),o.jsx("th",{children:"Source"}),o.jsx("th",{className:"text-right",children:"Runs"}),o.jsx("th",{className:"text-right",children:"Escalations"})]})}),o.jsx("tbody",{children:t.pairs.map(i=>o.jsxs("tr",{children:[o.jsx("td",{className:"text-sm text-spur-text",children:i.role??"—"}),o.jsx("td",{className:"text-sm text-spur-text",children:i.executor}),o.jsx("td",{children:o.jsx(gn,{size:"xs",variant:i.source==="explicit"?"warning":"ghost",children:SW(i.source)})}),o.jsx("td",{className:"text-right tabular-nums text-spur-text",children:as(i.runs)}),o.jsx("td",{className:"text-right tabular-nums text-spur-text",children:as(i.escalations)})]},`${i.role??""}:${i.executor}:${i.source??""}`))})]}),o.jsx("div",{className:"px-3 py-1.5 border-t border-spur-border text-[10px] text-spur-text-muted",children:"“—” role groups pure pins (no role recorded); escalations count runs that started too cheap on this executor."})]}):null,t.roles.length>0?o.jsxs("section",{"data-token-section":!0,children:[o.jsxs("div",{className:"px-1 pb-1.5",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Token consumption by role"}),o.jsx("span",{className:"ml-2 text-[10px] text-spur-text-muted",children:"input, cache read, cache write, output — token totals only"})]}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:t.roles.map(i=>o.jsx(wW,{role:i},i.role??"pin"))})]}):null]})]})}const AW={system:"#38bdf8",task:"#818cf8",feature:"#a78bfa",queue:"#f59e0b",scheduler:"#10b981",rule:"#ec4899",agent:"#06b6d4",history:"#64748b"},Uy=["#38bdf8","#818cf8","#a78bfa","#f59e0b","#10b981","#ec4899","#06b6d4","#f43f5e","#64748b"];function qc(e){const t=AW[e];if(t)return t;let n=0;for(let a=0;a<e.length;a++)n=(n<<5)-n+e.charCodeAt(a),n|=0;const r=Math.abs(n)%Uy.length;return Uy[r]??"#38bdf8"}function _W(e){return e==null||!Number.isFinite(e)?"—":(e/1e3).toFixed(2)}const kW=(e,t)=>t===void 0||t===0?null:(e-t)/Math.abs(t)*100,CW=g.memo(({current:e,previous:t,invert:n=!1})=>{if(t===void 0)return o.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});if(t===0)return o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-bold font-mono bg-info/15 text-info",children:"new"});const r=kW(e,t);if(r===null)return o.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});const a=r>=0,s=n?!a:a;return o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold font-mono ${s?"bg-emerald-500/15 text-emerald-400":"bg-error/15 text-error"}`,children:[a?"↑ +":"↓ ",Math.abs(r).toFixed(1),"% vs previous period"]})}),Yo=g.memo(({label:e,value:t,sub:n,trend:r,trendColor:a="#38bdf8",current:s,previous:i,invert:l,testId:u})=>o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-4","data-testid":u,children:[o.jsx("div",{className:"flex justify-between items-center",children:o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:e})}),o.jsxs("div",{className:"flex items-end justify-between gap-2 mt-1",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-2xl font-bold font-mono text-primary",children:t}),o.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[o.jsx(CW,{current:s,previous:i,invert:l}),o.jsx("span",{className:"text-xs text-base-content/60",children:n})]})]}),r&&r.length>1?o.jsx(zw,{values:r,color:a,width:100,height:34}):null]})]}));function IW(e){const t=g.useRef(0),[n,r]=g.useState(null),[a,s]=g.useState(null),[i,l]=g.useState(!0),[u,c]=g.useState(null),d=e.timeRange??"4h";g.useEffect(()=>{const A=++t.current,w=new AbortController;l(!0),c(null);async function T(){try{const _=Date.now(),B=Pu(d,_),k=new Date(_).toISOString();let $=`${Ct()}/observability/summary`;if(B){const ie=new URLSearchParams({since:B,until:k});$+=`?${ie.toString()}`}const V=ht(new Request($,{signal:w.signal}),1e4);let P=Promise.resolve(null);if(B){const ie=new Date(B).getTime(),be=_-ie,I=new Date(ie-be).toISOString(),ne=B,ue=new URLSearchParams({since:I,until:ne,period:"previous"}),O=`${Ct()}/observability/summary?${ue.toString()}`;P=ht(new Request(O,{signal:w.signal}),1e4).catch(()=>null)}const[H,W]=await Promise.all([V,P]);if(A!==t.current)return;if(!H.ok){const ie=await H.text();throw new Error(`HTTP ${H.status}: ${ie||H.statusText}`)}const L=await H.json();let te=null;if(W?.ok)try{te=await W.json()}catch{}if(A!==t.current)return;r(L),s(te),l(!1)}catch(_){if(w.signal.aborted||A!==t.current)return;c(_ instanceof Error?_.message:String(_)),l(!1)}}return T(),()=>{w.abort()}},[d]);const{series:p,chartBuckets:m}=g.useMemo(()=>{const A=n?.eventVolumeBuckets??[],w={};for(const k of A)for(const[$,V]of Object.entries(k.byPrefix))w[$]=(w[$]??0)+V;const _=Object.keys(w).sort((k,$)=>(w[$]??0)-(w[k]??0)).map(k=>({id:k,label:k,color:qc(k)})),B=A.map(k=>({id:k.timestamp,label:Ol(k.timestamp),v:k.byPrefix}));return{series:_,chartBuckets:B}},[n?.eventVolumeBuckets]),f=g.useMemo(()=>{const A={info:0,warning:0,error:0,unknown:0};for(const T of n?.eventVolumeBuckets??[])A.info+=T.bySeverity.info,A.warning+=T.bySeverity.warning,A.error+=T.bySeverity.error,A.unknown+=T.bySeverity.unknown;const w=A.info+A.warning+A.error+A.unknown;return{counts:A,sum:w}},[n?.eventVolumeBuckets]);if(i)return o.jsxs("div",{className:"flex flex-col gap-6 animate-pulse","data-testid":"observability-summary-tab","data-summary-tab":!0,children:[o.jsx("div",{"data-testid":"observability-summary-skeleton",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[1,2,3,4].map(A=>o.jsx("div",{className:"h-24 bg-base-200/60 rounded-xl"},A))}),o.jsx("div",{className:"h-64 bg-base-200/60 rounded-xl"})]});if(u)return o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error","data-testid":"observability-summary-error","data-summary-tab":!0,children:o.jsxs("span",{children:["Failed to load observability summary: ",u]})});const b=n?.kpis??{totalEvents:0,activeJobs:0,completedJobs:0,failedJobs:0,successRatePct:0,errorEventCount:0,warningEventCount:0},x=a?.kpis,E=n?.eventVolumeBuckets??[],y=E.map(A=>A.total),S=E.map(A=>A.bySeverity.error+A.bySeverity.warning),v=A=>{e.onNavigate?.({tab:"jobs",jobId:A})},N=(A,w)=>{e.onNavigate?.({tab:"system-events",eventName:A,runId:w})};return o.jsxs("div",{className:"flex flex-col gap-6","data-testid":"observability-summary-tab","data-summary-tab":!0,children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[o.jsx(Yo,{label:"Total Events",value:Wt(b.totalEvents),sub:"events in window",trend:y,trendColor:"#38bdf8",current:b.totalEvents,previous:x?.totalEvents,testId:"kpi-card-total-events"}),o.jsx(Yo,{label:"Active In-Flight Jobs",value:Wt(b.activeJobs),sub:"pending & processing",current:b.activeJobs,previous:x?.activeJobs,testId:"kpi-card-active-jobs"}),o.jsx(Yo,{label:"Success Rate",value:`${b.successRatePct}%`,sub:`${b.completedJobs} ok / ${b.failedJobs} fail`,current:b.successRatePct,previous:x?.successRatePct,testId:"kpi-card-success-rate"}),o.jsx(Yo,{label:"Errors & Warnings",value:`${b.errorEventCount} / ${b.warningEventCount}`,sub:"error / warning events",trend:S,trendColor:"#ef4444",current:b.errorEventCount+b.warningEventCount,previous:x?x.errorEventCount+x.warningEventCount:void 0,invert:!0,testId:"kpi-card-errors-warnings"})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[o.jsx("div",{className:"flex justify-between items-center",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Event Volume Over Time"}),o.jsx("p",{className:"text-xs text-base-content/60 mt-0.5",children:"Distribution stacked by event prefix"})]})}),m.length>0&&p.length>0?o.jsx("div",{className:"mt-2","data-testid":"stacked-event-volume-chart",children:o.jsx($w,{buckets:m,series:p,height:240})}):o.jsx("div",{className:"p-8 text-center text-xs text-base-content/50","data-testid":"empty-chart-fallback",children:"No event activity recorded in this time range."})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-2",children:[o.jsxs("div",{className:"flex justify-between items-center text-xs font-semibold uppercase tracking-wider text-base-content/60",children:[o.jsx("span",{children:"Severity Distribution"}),o.jsxs("span",{children:[f.sum.toLocaleString()," classified events"]})]}),o.jsx("div",{className:"w-full h-3 rounded-full bg-base-300 overflow-hidden flex","data-testid":"severity-distribution-bar",children:f.sum>0?o.jsxs(o.Fragment,{children:[f.counts.info>0&&o.jsx("div",{style:{width:`${f.counts.info/f.sum*100}%`},className:"bg-info h-full",title:`Info: ${f.counts.info}`,"data-testid":"severity-bar-info"}),f.counts.warning>0&&o.jsx("div",{style:{width:`${f.counts.warning/f.sum*100}%`},className:"bg-warning h-full",title:`Warning: ${f.counts.warning}`,"data-testid":"severity-bar-warning"}),f.counts.error>0&&o.jsx("div",{style:{width:`${f.counts.error/f.sum*100}%`},className:"bg-error h-full",title:`Error: ${f.counts.error}`,"data-testid":"severity-bar-error"}),f.counts.unknown>0&&o.jsx("div",{style:{width:`${f.counts.unknown/f.sum*100}%`},className:"bg-base-content/20 h-full",title:`Unknown: ${f.counts.unknown}`,"data-testid":"severity-bar-unknown"})]}):o.jsx("div",{className:"w-full h-full bg-base-content/10"})}),o.jsxs("div",{className:"flex flex-wrap gap-4 text-xs text-base-content/70 mt-1",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-info inline-block"})," Info:"," ",f.counts.info.toLocaleString()]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-warning inline-block"})," Warning:"," ",f.counts.warning.toLocaleString()]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-error inline-block"})," Error:"," ",f.counts.error.toLocaleString()]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-base-content/20 inline-block"})," Unknown:"," ",f.counts.unknown.toLocaleString()]})]})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Top Event Types"}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"table table-xs w-full font-mono text-xs","data-testid":"top-event-types-table",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{children:"Event Name"}),o.jsx("th",{children:"Prefix"}),o.jsx("th",{className:"text-right",children:"Count"}),o.jsx("th",{className:"text-right",title:"Average duration in seconds",children:"Avg(Duration - s)"}),o.jsx("th",{className:"text-right",title:"Events with error severity",children:"Failures"}),o.jsx("th",{className:"text-right",children:"Latest"})]})}),o.jsxs("tbody",{children:[(n?.topEventTypes??[]).map(A=>o.jsxs("tr",{className:"hover:bg-base-300/40",children:[o.jsx("td",{className:"font-semibold text-base-content",children:A.name}),o.jsx("td",{children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-bold border",style:{color:qc(A.prefix),borderColor:qc(A.prefix)},children:A.prefix})}),o.jsx("td",{className:"text-right text-base-content/80 tabular-nums",children:A.count.toLocaleString()}),o.jsx("td",{className:"text-right text-base-content/80 tabular-nums","data-testid":`top-event-avg-${A.name}`,children:_W(A.avgDurationMs)}),o.jsx("td",{className:`text-right tabular-nums ${A.failureCount>0?"text-error font-semibold":"text-base-content/80"}`,"data-testid":`top-event-failures-${A.name}`,children:A.failureCount.toLocaleString()}),o.jsx("td",{className:"text-right text-base-content/50",children:new Date(A.latestAt).toLocaleTimeString()})]},A.name)),(!n||(n.topEventTypes??[]).length===0)&&o.jsx("tr",{children:o.jsx("td",{colSpan:6,className:"text-center text-base-content/40 py-4",children:"No events recorded"})})]})]})})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Recent Failures"}),o.jsxs("div",{className:"flex flex-col gap-2 max-h-[320px] overflow-y-auto","data-testid":"recent-failures-feed",children:[(n?.recentErrors??[]).map(A=>{const w=!!e.onNavigate,T=()=>{A.source==="job"?v(A.id):N(A.name,A.refId)},_=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(gn,{size:"xs",variant:A.source==="job"?"warning":"error",children:A.source}),o.jsx("span",{className:"font-mono text-xs font-semibold text-base-content",children:A.name})]}),o.jsx("span",{className:"text-[11px] text-base-content/50 font-mono",children:new Date(A.occurredAt).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-error font-mono truncate",children:A.message})]});return w?o.jsx("button",{type:"button",className:"w-full text-left p-2.5 rounded-lg border border-base-content/10 bg-base-100 flex flex-col gap-1 transition-colors hover:bg-base-200/80 cursor-pointer",onClick:T,"data-testid":`failure-row-${A.source}-${A.id}`,children:_},`${A.source}-${A.id}-${A.occurredAt}`):o.jsx("div",{className:"p-2.5 rounded-lg border border-base-content/10 bg-base-100 flex flex-col gap-1","data-testid":`failure-row-${A.source}-${A.id}`,children:_},`${A.source}-${A.id}-${A.occurredAt}`)}),(!n||(n.recentErrors??[]).length===0)&&o.jsx("div",{className:"p-8 text-center text-xs text-base-content/50",children:"No recent failures in this time range."})]})]})]})]})}const Vc=[{id:"summary",label:"Summary",component:IW},{id:"system-events",label:"System Events",component:lW},{id:"jobs",label:"Jobs",component:xW},{id:"routing",label:"Routing",component:NW}];function RW(){const[e,t]=g.useState(Vc[0]?.id??""),[n,r]=g.useState("4h"),[a,s]=g.useState({status:"connecting",rate:0,lastEventAt:null}),l=Vc.find(b=>b.id===e)?.component,u=g.useCallback(b=>{s(b)},[]),c=g.useCallback(b=>{t(b.tab)},[]),d=e==="system-events",p=d?a.status:"idle",m=d?a.status==="live"?`live tail · ${a.rate} evt/60s`:a.status==="connecting"?"connecting…":a.status==="paused"?"live tail paused":"stream error":"live tail idle",f=p==="live"?"bg-emerald-400 animate-pulse":p==="connecting"?"bg-amber-400":p==="errored"?"bg-error":"bg-base-content/40";return o.jsxs("div",{className:"flex flex-col gap-4 p-4 max-w-[1600px] mx-auto w-full","data-observability-shell":!0,children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-2xl",children:"📡"}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Observabilities"}),o.jsx("p",{className:"text-xs text-base-content/60",children:"System event streams, queue execution telemetry, and routing attribution"}),o.jsxs("p",{className:"livechip mt-1 inline-flex items-center gap-1.5 rounded-full border border-base-content/10 px-2 py-0.5 text-xs text-base-content/60 font-mono","data-testid":"observability-liveness-chip",role:"status","aria-live":"polite",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f}`,"aria-hidden":"true"}),m,d&&a.lastEventAt&&o.jsxs(o.Fragment,{children:[" · last ",o.jsx("time",{dateTime:a.lastEventAt,children:new Date(a.lastEventAt).toLocaleTimeString()})]})]})]})]}),o.jsx($G,{timeRange:n,onTimeRangeChange:r}),o.jsx("div",{role:"tablist","aria-label":"Observability tabs",className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:Vc.map(b=>{const x=b.id===e;return o.jsx("button",{type:"button",role:"tab","aria-selected":x,"aria-controls":`observability-tab-panel-${b.id}`,id:`observability-tab-${b.id}`,onClick:()=>t(b.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer ${x?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,children:b.label},b.id)})})]}),o.jsx("div",{role:"tabpanel",id:`observability-tab-panel-${e}`,"aria-labelledby":`observability-tab-${e}`,className:"mt-2 flex flex-col gap-4",children:l?o.jsx(l,{onLivenessChange:u,timeRange:n,onNavigate:c}):null})]})}const DW={id:"observability",name:"Observabilities",icon:"📡",route:"observability",component:RW,sidebarLabel:"Observabilities",description:"Real-time system events, execution traces, and agent doctor telemetry",order:10},OW=Object.freeze(Object.defineProperty({__proto__:null,module:DW},Symbol.toStringTag,{value:"Module"})),LW=100,MW=()=>`${Ct()}/events/history?limit=${LW}`,FW=["agent.","message.","task.","supervisor.","process."];function jW(e){return FW.some(t=>e.startsWith(t))}function PW(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.eventName!="string"||typeof t.occurredAt!="string"||!jW(t.eventName))return null;const n=t.payload!==null&&typeof t.payload=="object"?t.payload:null,r=n&&typeof n.teamId=="string"&&n.teamId.length>0?n.teamId:void 0,a=n&&typeof n.agentType=="string"&&n.agentType.length>0?n.agentType:void 0,s=n&&typeof n.memberLabel=="string"&&n.memberLabel.length>0?n.memberLabel:n&&typeof n.agentId=="string"&&n.agentId.length>0?n.agentId:void 0,i=typeof t.actor=="string"&&t.actor.length>0?t.actor:n&&typeof n.agentId=="string"&&n.agentId.length>0?n.agentId:null;return{id:typeof t.id=="string"?t.id:`${t.eventName}-${t.occurredAt}`,eventName:t.eventName,occurredAt:t.occurredAt,actor:i,...r?{teamId:r}:{},...s?{memberLabel:s}:{},...a?{agentType:a}:{}}}function BW(e){if(e===null||typeof e!="object"||!("events"in e))return null;const t=e.events;if(!Array.isArray(t))return null;const n=[];for(const r of t){const a=PW(r);a&&n.push(a)}return n}const Ko=1e3,Yc=[1e3,2e3,4e3,8e3,15e3],UW=15e3;function $W(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.stream!="string"||typeof t.ts!="string"||typeof t.line!="string")return null;const n=t.stream;if(n!=="stdout"&&n!=="stderr"&&n!=="meta")return null;const r=t.seq;return r!==void 0&&typeof r!="number"?null:{stream:n,ts:t.ts,line:t.line,...r!==void 0?{seq:r}:{}}}function zW(e){return e<0?Yc[0]:e>=Yc.length?UW:Yc[e]}function $y(e,t,n){if(t.seq===void 0){const a=[...e,t];return a.length>Ko&&a.splice(0,a.length-Ko),{frames:a,lastSeq:n}}if(t.seq<=n)return{frames:e,lastSeq:n};const r=[...e,t];return r.length>Ko&&r.splice(0,r.length-Ko),{frames:r,lastSeq:t.seq}}const HW=(e,t)=>t!==void 0?`${Ct()}/processes/${encodeURIComponent(e)}/stream?sinceSeq=${t}`:`${Ct()}/processes/${encodeURIComponent(e)}/stream`,zb=3e3;function Hb(e){if(e===null||typeof e!="object")return null;const t=e;if(!Array.isArray(t.processes))return null;const n=[];for(const r of t.processes){if(r===null||typeof r!="object")return null;const a=r;if(typeof a.agentId!="string"||typeof a.status!="string"||typeof a.startedAt!="string"||typeof a.pid!="number")return null;const s=a.exitCode;if(s!==null&&typeof s!="number")return null;const i=a.teamId;n.push({agentId:a.agentId,pid:a.pid,status:a.status,startedAt:a.startedAt,exitCode:s,teamId:typeof i=="string"?i:null})}return n}function GW(e){if(e===null||typeof e!="object")return null;const t=e;if(!Array.isArray(t.executions))return null;const n=[];for(const r of t.executions){if(r===null||typeof r!="object")return null;const a=r;if(typeof a.id!="string"||typeof a.label!="string"||typeof a.command!="string"||!Array.isArray(a.args)||!a.args.every(i=>typeof i=="string")||a.pid!==null&&typeof a.pid!="number"||typeof a.status!="string"||typeof a.startedAt!="string"||a.exitedAt!==null&&typeof a.exitedAt!="string"||a.exitCode!==null&&typeof a.exitCode!="number"||typeof a.source!="string"||a.agentId!==null&&typeof a.agentId!="string")return null;const s=a.teamId;n.push({id:a.id,label:a.label,command:a.command,args:a.args,pid:a.pid,status:a.status,startedAt:a.startedAt,exitedAt:a.exitedAt,exitCode:a.exitCode,source:a.source,teamId:typeof s=="string"?s:null,agentId:a.agentId})}return n}const WW=e=>`${Ct()}/processes/${encodeURIComponent(e)}/stdin`,qW=()=>`${Ct()}/messages`,VW=()=>`${Ct()}/processes`;function YW({agentId:e}){const[t,n]=g.useState([]),[r,a]=g.useState("unknown"),[s,i]=g.useState(""),[l,u]=g.useState(null),[c,d]=g.useState(!1),p=g.useRef(-1),m=g.useRef(null),f=g.useRef(void 0),b=g.useRef(0),x=g.useRef(!0),E=g.useRef(null),y=g.useCallback(async w=>{try{const T=await ht(new Request(VW(),{signal:w}));if(!T.ok)return;const _=await T.json(),B=Hb(_);if(!B)return;const k=B.find($=>$.agentId===e);k&&x.current&&a(k.status)}catch{}},[e]);g.useEffect(()=>{x.current=!0;let w=null;const T=()=>{w?.abort(),w=new AbortController,y(w.signal)};T();const _=setInterval(T,zb);return()=>{x.current=!1,w?.abort(),clearInterval(_)}},[y]);const S=g.useCallback(()=>{if(!x.current)return;const w=new EventSource(HW(e,p.current>-1?p.current:void 0));m.current=w,w.onmessage=T=>{try{const _=JSON.parse(T.data),B=$W(_);if(!B)return;n(k=>{const $=$y(k,B,p.current);return p.current=$.lastSeq,$.frames}),b.current=0,d(!0)}catch{}},w.onerror=()=>{if(w.close(),m.current=null,d(!1),!x.current)return;const T=zW(b.current);b.current+=1,f.current=setTimeout(S,T)}},[e]);g.useEffect(()=>(S(),()=>{x.current=!1,m.current?.close(),m.current=null,f.current&&clearTimeout(f.current)}),[S]),g.useEffect(()=>{E.current&&t.length>0&&(E.current.scrollTop=E.current.scrollHeight)},[t]);const v=g.useCallback(async()=>{const w=s;if(w.length===0)return;u(null);const T={stream:"meta",ts:new Date().toISOString(),line:`> ${w}`};n(_=>$y(_,T,p.current).frames);try{const _=await ht(new Request(WW(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({line:w})}));if(ht(new Request(qW(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:"terminal",to:e,body:w})})).catch(()=>{}),!_.ok){const k=(await _.json().catch(()=>null))?.error??`stdin POST failed: ${_.status}`;u(k);return}i("")}catch(_){u(_ instanceof Error?_.message:String(_))}},[e,s]),N=r==="running",A=w=>{w.key==="Enter"&&N&&(w.preventDefault(),v())};return o.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-member-terminal":e,children:[o.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-base-200 shrink-0 flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Terminal"}),o.jsx("span",{className:"font-mono text-xs text-spur-text-muted",children:e}),o.jsx(gn,{variant:N?"success":"ghost",size:"xs","data-terminal-status":!0,children:r}),o.jsx("span",{className:"text-[10px] text-spur-text-muted","data-terminal-connected":!0,children:c?"connected":"reconnecting…"})]}),!N&&o.jsxs("div",{className:"px-4 py-1 text-xs text-warning border-b border-spur-border",role:"status","data-status-banner":!0,children:["Member is ",r," — input disabled."]}),o.jsx("pre",{ref:E,className:"flex-1 overflow-x-auto overflow-y-auto p-2 text-xs font-mono leading-snug bg-base-100","data-terminal-output":!0,children:t.length===0?o.jsxs("span",{className:"text-spur-text-muted italic",children:["Waiting for output from ",e,"…"]}):t.map((w,T)=>o.jsx("div",{className:w.stream==="stderr"?"text-error":w.stream==="meta"?"text-spur-text-muted italic":"text-spur-text","data-stream":w.stream,children:w.line},w.seq??`meta-${T}`))}),l&&o.jsx("div",{className:"px-4 py-1 text-xs text-error border-t border-spur-border",role:"alert","data-input-error":!0,children:l}),o.jsx("div",{className:"flex items-center gap-2 px-2 py-2 border-t border-spur-border bg-base-200 shrink-0",children:o.jsx("input",{type:"text",value:s,onChange:w=>i(w.target.value),onKeyDown:A,disabled:!N,placeholder:N?"Type a line and press Enter…":"Input disabled (member not running)",className:"flex-1 input input-sm font-mono","data-terminal-input":!0})})]})}const KW=e=>`${Ct()}/messages/inbox?agent=${encodeURIComponent(e)}`,ZW=(e,t)=>`${Ct()}/agents/${encodeURIComponent(e)}/${t}`;function XW({entry:e,onClose:t}){const n=Os(),r=n.fleet?.path??n.path??"Unavailable",a=e.declared===null?"Unavailable":e.declared.model??"Executor default",[s,i]=g.useState(null),[l,u]=g.useState(null),[c,d]=g.useState(!1),[p,m]=g.useState(null);g.useEffect(()=>{const y=S=>{S.key==="Escape"&&t()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t]),g.useEffect(()=>{let y=!1;return i(null),ht(new Request(KW(e.instanceId))).then(async S=>S.ok?mv(await S.json()):[]).then(S=>{y||i(S)}).catch(()=>{y||i([])}),()=>{y=!0}},[e.instanceId]),g.useEffect(()=>{let y=!1;return u(null),ht(new Request(MW())).then(async S=>S.ok?BW(await S.json()):[]).then(S=>{y||u((S??[]).filter(v=>v.memberLabel===e.instanceId||v.actor===e.instanceId))}).catch(()=>{y||u([])}),()=>{y=!0}},[e.instanceId]);const f=e.issues.includes("executor-unavailable")||e.issues.includes("unresolved"),b=e.issues.includes("executor-unavailable")?"controls disabled — executor unavailable":e.issues.includes("unresolved")?"controls disabled — member unresolved":null,x=async y=>{d(!0),m(null);try{const S=await ht(new Request(ZW(e.instanceId,y),{method:"POST"}));S.ok||m(`${y} failed: ${S.status}`)}catch(S){m(S instanceof Error?S.message:String(S))}finally{d(!1)}},E=e.observed.status==="running";return o.jsxs("div",{className:"shrink-0 h-[55%] flex flex-col border-t border-spur-border bg-spur-surface","data-member-detail":!0,children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-spur-border shrink-0",children:[o.jsx("span",{className:"text-sm font-semibold text-spur-text",children:e.declared?.role??"member"}),o.jsx("button",{type:"button",className:"ml-auto px-2 py-0.5 rounded-lg text-xs text-spur-text-muted hover:text-spur-text","aria-label":"Close member detail",onClick:t,"data-member-detail-close":!0,children:"close ✕"})]}),o.jsxs("div",{className:"px-3 py-2 border-b border-spur-border shrink-0 flex flex-col gap-1 text-xs",children:[o.jsxs("span",{className:"text-spur-text-muted",children:["declared:"," ",o.jsx("span",{className:"text-spur-text",children:e.declared===null?"none":`${e.declared.enabled?"enabled":"disabled"} · capability ${e.declared.capabilityState}`})]}),o.jsxs("span",{className:"text-spur-text-muted",children:["observed:"," ",o.jsxs("span",{className:"text-spur-text",children:[e.observed.status,e.observed.pid!==null?` — pid ${e.observed.pid}`:"",e.observed.exitCode!==null?` — exit ${e.observed.exitCode}`:""]})]}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-1",children:[o.jsx("dt",{className:"text-spur-text-muted",children:"Working directory"}),o.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-workdir":!0,children:r}),o.jsx("dt",{className:"text-spur-text-muted",children:"Model"}),o.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-model":!0,children:a})]})]}),o.jsxs("div",{className:"px-3 py-2 border-b border-spur-border shrink-0 flex items-center gap-2 flex-wrap",children:[o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded-lg text-xs bg-spur-accent text-white disabled:opacity-40",disabled:c||f||E,onClick:()=>{x("start")},"data-member-start":!0,children:"start"}),o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded-lg text-xs bg-spur-surface-3 text-spur-text disabled:opacity-40",disabled:c||f||!E,onClick:()=>{x("stop")},"data-member-stop":!0,children:"stop"}),b!==null&&o.jsx("span",{className:"text-xs text-spur-text-muted","data-lifecycle-reason":!0,children:b}),p!==null&&o.jsx("span",{className:"text-xs text-error",role:"alert","data-lifecycle-error":!0,children:p})]}),o.jsx("div",{className:"flex-1 min-h-0 border-b border-spur-border",children:o.jsx(YW,{agentId:e.instanceId})}),o.jsxs("div",{className:"shrink-0 h-[35%] flex overflow-hidden",children:[o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 border-r border-spur-border","data-member-messages":!0,children:[o.jsx("div",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide mb-1",children:"Messages"}),(s??[]).length===0&&o.jsx("div",{className:"text-xs text-spur-text-muted italic",children:s===null?"Loading…":"No inbox messages."}),(s??[]).slice(0,20).map(y=>o.jsxs("div",{className:"text-xs border-t border-spur-border py-1","data-member-message":y.id,children:[o.jsxs("span",{className:"font-mono text-spur-text-muted",children:[y.fromId??"system"," → ",y.toId]}),o.jsx("span",{className:"ml-1 px-1 rounded bg-spur-surface-3 text-spur-text",children:y.status}),o.jsx("span",{className:"ml-1 font-mono text-spur-text-muted",children:y.createdAt}),o.jsx("p",{className:"text-spur-text mt-0.5 whitespace-pre-wrap break-words",children:y.body})]},y.id))]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-2","data-member-activity":!0,children:[o.jsx("div",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide mb-1",children:"Activity"}),(l??[]).length===0&&o.jsx("div",{className:"text-xs text-spur-text-muted italic",children:l===null?"Loading…":"No activity for this member."}),(l??[]).slice(0,20).map(y=>o.jsxs("div",{className:"text-xs border-t border-spur-border py-1","data-member-activity-row":y.eventName,children:[o.jsx("span",{className:"font-mono text-spur-text-muted",children:y.occurredAt})," ",o.jsx("span",{className:"text-spur-text",children:y.eventName})]},y.id))]})]})]})}function zy(e,t){const{state:n,instanceId:r}=t.orchestrator;return n!=="bound-online"&&n!=="bound-offline"?!1:r!==void 0&&r===e.instanceId}function QW(e,t){const n=new Map(t.map(a=>[a.agentId,a])),r=[];for(const a of e.members){const s=n.get(a.instanceId),i={status:Hy(s),pid:s?.pid??null,startedAt:s?.startedAt??null,exitCode:s?.exitCode??null},l=[];a.enabled===!1&&l.push("disabled"),a.capabilityState==="unavailable"&&l.push("executor-unavailable"),a.capabilityState==="unknown"&&l.push("capability-unknown"),e.capacity.missing.includes(a.instanceId)&&l.push("unresolved"),r.push({instanceId:a.instanceId,declared:a,observed:i,isOrchestrator:zy({instanceId:a.instanceId},e),issues:l})}for(const a of t)e.members.some(s=>s.instanceId===a.agentId)||a.agentId!==ku&&r.push({instanceId:a.agentId,declared:null,observed:{status:Hy(a),pid:a.pid,startedAt:a.startedAt,exitCode:a.exitCode},isOrchestrator:zy({instanceId:a.agentId},e),issues:["undeclared"]});return r.sort((a,s)=>a.isOrchestrator!==s.isOrchestrator?a.isOrchestrator?-1:1:a.instanceId<s.instanceId?-1:a.instanceId>s.instanceId?1:0),r}function Hy(e){return e===void 0?"not-started":e.status==="running"?"running":"exited"}const sN=6e4,Kd=60*sN,Gy=24*Kd;function JW(e,t){if(e===null)return null;const n=new Date(e).getTime(),r=Date.now()-n;if(Number.isNaN(n)||r<0)return null;const a=Math.floor(r/Gy),s=Math.floor(r%Gy/Kd),i=Math.floor(r%Kd/sN);return a>0?`up ${a}d ${s}h`:s>0?`up ${s}h ${i}m`:`up ${i}m`}const eq=()=>`${Ct()}/project/fleet`,tq=()=>`${Ct()}/processes`;function nq(e){if(e===null||typeof e!="object")return!1;const t=e,n=t.capacity;return Array.isArray(t.members)&&t.members.every(r=>r!==null&&typeof r=="object"&&typeof r.instanceId=="string")&&n!==null&&typeof n=="object"&&Array.isArray(n.missing)&&t.orchestrator!==null&&typeof t.orchestrator=="object"}const Kc={"executor-unavailable":{icon:"⛔",label:"executor unavailable",action:"the executor cannot run here — check the executor's install/attestation"},"capability-unknown":{icon:"❔",label:"capability unknown",action:"no attestation exists; it grants nothing and is not a failure"},unresolved:{icon:"⚠️",label:"unresolved",action:"the instance is listed in the fleet capacity as missing"},undeclared:{icon:"❗",label:"undeclared",action:"a live process with no declared member"},disabled:{icon:"⏸️",label:"disabled",action:"declared with enabled: false"}};function rq(e,t){return e.observed.status==="running"?{label:"running",action:null}:t&&e.isOrchestrator?{label:"orchestrator offline",action:"its claim is held but stale — see project_claims"}:e.issues.includes("executor-unavailable")||e.issues.includes("capability-unknown")?{label:e.observed.status==="exited"?"exited":"not started",action:null}:{label:"not running",action:"start it"}}function aq({pollMs:e=zb}){const t=Os(),[n,r]=g.useState(null),[a,s]=g.useState(!1),[i,l]=g.useState(null),[u,c]=g.useState(!1),d=g.useRef(null);g.useEffect(()=>{let b=!1,x=null;const E=async()=>{x?.abort(),x=new AbortController;const S=x.signal;try{const[v,N]=await Promise.all([ht(new Request(eq(),{signal:S})),ht(new Request(tq(),{signal:S}))]);if(b||!v.ok||!N.ok)return;const A=await v.json(),w=await N.json();if(b||!nq(A))return;const T=Hb(w);if(!T)return;r(QW(A,T)),c(A.orchestrator.state==="bound-offline"),s(!1)}catch{b||s(!0)}};E();const y=setInterval(()=>{E()},e);return()=>{b=!0,clearInterval(y),x?.abort()}},[e]);const p=g.useCallback((b,x)=>{d.current=x,l(b.instanceId)},[]),m=g.useCallback(()=>{l(null),d.current?.focus()},[]),f=n?.find(b=>b.instanceId===i)??null;return o.jsxs("div",{className:"flex flex-col h-full overflow-hidden bg-spur-bg","data-agents-view":!0,children:[o.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[n===null&&!a&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-roster-loading":!0,children:"Loading fleet roster…"}),a&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-roster-fetch-failed":!0,role:"alert",children:"Fleet roster unavailable — the fleet or process feed could not be read."}),n!==null&&n.length===0&&o.jsxs("div",{className:"p-4 text-sm text-spur-text-muted italic","data-roster-empty":!0,children:["No agents for this project — declare members under"," ",o.jsx("code",{className:"font-mono",children:"agent.fleet"})," in"," ",o.jsx("code",{className:"font-mono",children:`${t.path??"this project"}/.spur/config.yaml`}),"."]}),n!==null&&n.length>0&&o.jsx("div",{className:"grid gap-2 md:grid-cols-2 xl:grid-cols-3","data-roster-grid":!0,children:n.map(b=>o.jsx(sq,{entry:b,orchestratorOffline:u,onOpen:p},b.instanceId))})]}),f!==null&&o.jsx(XW,{entry:f,onClose:m})]})}function sq({entry:e,orchestratorOffline:t,onOpen:n}){const r=rq(e,t),a=e.observed.status==="running"?JW(e.observed.startedAt):null;return o.jsxs("button",{type:"button",className:"text-left p-3 bg-spur-surface border border-spur-border rounded-xl hover:bg-spur-surface-2 focus:outline-none focus:ring-1 focus:ring-spur-accent","data-roster-entry":e.instanceId,"data-g6":"open-member","aria-haspopup":"dialog",onClick:s=>n(e,s.currentTarget),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{"data-roster-role":!0,className:"font-medium text-spur-text text-sm",children:e.declared?.role??"member"}),e.isOrchestrator&&o.jsx("span",{"data-roster-orchestrator":!0,className:"text-xs px-1 rounded bg-spur-accent/20 text-spur-accent",children:"orchestrator"})]}),o.jsxs("div",{className:"mt-1 text-xs text-spur-text-muted",children:["executor"," ",o.jsx("span",{"data-roster-executor":!0,className:"font-mono text-spur-text",children:e.declared?.executor??"—"})]}),o.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs",children:[o.jsxs("span",{"data-roster-declared":!0,children:[o.jsx("span",{className:"text-spur-text-muted",children:"declared:"})," ",o.jsx("span",{className:"text-spur-text",children:e.declared===null?"none":`${e.declared.enabled?"enabled":"disabled"} · capability ${e.declared.capabilityState}`})]}),o.jsxs("span",{"data-roster-observed":!0,children:[o.jsx("span",{className:"text-spur-text-muted",children:"observed:"})," ",o.jsxs("span",{className:"text-spur-text",children:[e.observed.status,e.observed.pid!==null?` — pid ${e.observed.pid}`:"",e.observed.exitCode!==null?` — exit ${e.observed.exitCode}`:""]})]})]}),a!==null&&o.jsx("div",{"data-roster-uptime":!0,className:"mt-1 text-xs text-spur-text-muted",children:a}),e.issues.length>0&&o.jsx("div",{className:"mt-1 space-y-0.5",children:e.issues.map(s=>o.jsxs("div",{"data-roster-issue":s,className:"text-xs",children:[o.jsx("span",{"aria-hidden":"true",children:Kc[s].icon})," ",o.jsx("span",{className:"text-spur-text",children:Kc[s].label}),o.jsxs("span",{className:"text-spur-text-muted",children:[" — ",Kc[s].action]})]},s))}),r.action!==null&&o.jsxs("div",{"data-roster-next-action":!0,className:"mt-1 text-xs text-spur-text-muted",children:["next: ",r.action]})]})}const iN={pending:{icon:"◐",label:"pending",meaning:"Receipt captured; waiting for durable acceptance. The submitted revision clears only on acceptance.",action:"wait — the request is being persisted",tone:"warn"},"queued-awaiting-orchestrator":{icon:"⏸",label:"queued-awaiting-orchestrator",meaning:"Durable receipt exists but no active orchestrator has consumed it. NOT “working”. ",action:"bind/restore an orchestrator (Agents → Planner · Scout)",tone:"warn"},"orchestrator-missing":{icon:"⏸",label:"orchestrator-missing",meaning:"No orchestrator instance is bound, so the durable request cannot be consumed.",action:"bind/restore an orchestrator (Agents → Planner · Scout)",tone:"warn"},"orchestrator-offline":{icon:"⏸",label:"orchestrator-offline",meaning:"The orchestrator’s claim is held but stale — it is not consuming the queue.",action:"start the orchestrator member (Agents tab)",tone:"warn"},"executor-unavailable":{icon:"⊘",label:"executor-unavailable",meaning:"No executor tier can serve the addressed member, so the request was not accepted; the draft is preserved.",action:"fix the member’s executor binding, then retry — same payload, same requestId",tone:"err"},"rest-held":{icon:"⏳",label:"rest-held",meaning:"Rest accepted the request into a visible hold.",action:"release from rest (Agents) or let rest wake it; results from already-running work keep arriving",tone:"warn"},blocked:{icon:"⛔",label:"blocked",meaning:"The strategy is holding the task on a first-class condition (unauthorized, not-ready, unmet-dependency, no idle instance).",action:"inspect Activity for the pending signal, then unblock",tone:"warn"},"accepted-working":{icon:"▶",label:"accepted · executor working",meaning:"Durable acceptance; an executor is working. This is occupancy, NOT a verified result.",action:"wait for the run receipt",tone:"ok"},"failed-delivery":{icon:"✕",label:"failed-delivery",meaning:"The run could not accept this payload; the draft is preserved.",action:"Retry keeps the SAME requestId for this immutable payload; editing text first creates a NEW requestId",tone:"err"},"outcome-unknown":{icon:"?",label:"outcome-unknown",meaning:"The run consumed the request without ever reporting a receipt.",action:"inspect Messages/Activity and reconcile before any resend — a blind retry would duplicate the payload",tone:"err"},"completed-exit-only":{icon:"✓",label:"run exit 0 recorded (unverified)",meaning:"A process exit code is not proof of success (run exit ≠ verified result).",action:"reconcile in Messages/Activity; only then mark the result verified",tone:"warn"},"completed-verified":{icon:"✓",label:"completed · verified result",meaning:"Result received and reconciled against the original request.",action:"none — this request is finished",tone:"ok"}};function oN(e,t,n){if(n&&e===null)return"pending";const r=e?.deliveryStatus??"queued",a=e?.reason??null,s=e?.outcome??null,i=e?.hold??null;if(r==="failed")return"failed-delivery";if(a==="outcome-unknown")return"outcome-unknown";if(a==="attempts-exhausted")return"failed-delivery";if(s==="verified")return"completed-verified";if(s==="run-exit-only")return"completed-exit-only";if(s==="errored")return"failed-delivery";if(i==="rest-after-drain")return"rest-held";if(i==="executor-unavailable")return"executor-unavailable";if(i!==null)return"blocked";if(r==="injected"||r==="delivered")return"accepted-working";const l=t?.orchestrator.state??null;if(r==="queued"&&(l==="missing"||l==="unresolvable"))return"orchestrator-missing";if(r==="queued"&&l==="bound-offline")return"orchestrator-offline";const u=t?.orchestrator.instanceId,c=t!==null&&u!==void 0?t.members.find(d=>d.instanceId===u):void 0;return r==="queued"&&c!==void 0&&(c.enabled===!1||c.capabilityState==="unavailable")?"executor-unavailable":r==="queued"&&t?.strategy?.name==="rest"?"rest-held":"queued-awaiting-orchestrator"}const iq=15e3;function oq(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.messageId!="string"||t.messageId.length===0||typeof t.deliveryStatus!="string"||typeof t.injectAttempts!="number"?null:{messageId:t.messageId,requestKey:typeof t.requestKey=="string"?t.requestKey:null,deliveryStatus:t.deliveryStatus,injectAttempts:t.injectAttempts,injectError:typeof t.injectError=="string"?t.injectError:null,runId:typeof t.runId=="string"?t.runId:null,taskId:typeof t.taskId=="string"?t.taskId:null,outcome:t.outcome==="run-exit-only"||t.outcome==="errored"||t.outcome==="verified"?t.outcome:null,reason:typeof t.reason=="string"?t.reason:null,hold:typeof t.hold=="string"?t.hold:null}}function lN(e,t=iq){const[n,r]=g.useState(()=>new Map),[a,s]=g.useState(!1);return g.useEffect(()=>{if(e==null){r(new Map),s(!1);return}const i=new AbortController;let l=!1;const u=`${Ct()}/project/requests`,c=()=>{ht(new Request(u,{signal:i.signal})).then(async p=>{if(!p.ok)throw new Error(`requests fetch failed: ${p.status}`);const f=(await p.json()).requests,b=Array.isArray(f)?f.map(oq).filter(x=>x!==null):[];l||(r(new Map(b.map(x=>[x.messageId,x]))),s(!1))}).catch(()=>{l||s(!0)})};c();const d=setInterval(c,t);return()=>{l=!0,clearInterval(d),i.abort()}},[e,t]),{requests:n,failed:a}}function lq(e){if(e===null)return!0;const{state:t,instanceId:n}=e.orchestrator;return t==="missing"||t==="unresolvable"||!n}function uq(e){return`${Ct()}/messages/inbox?agent=${encodeURIComponent(e)}`}function cq(){const e=Os(),{draft:t,setText:n,removeRef:r}=Sw(),[a,s]=g.useState(null),[i,l]=g.useState(!1),u=e.fleet?.orchestrator.instanceId??null,c=lq(e.fleet),{requests:d,failed:p}=lN(u),m=a?.map(f=>{const b=d.get(f.id);return b===void 0?f:{...f,requestKey:b.requestKey??void 0,receipt:b}})??null;return g.useEffect(()=>{if(e.path===null)return;const f=new AbortController;let b=!1;const x=async y=>{const S=await ht(new Request(uq(y),{signal:f.signal}));if(!S.ok)throw new Error(`inbox fetch failed: ${S.status}`);return mv(await S.json())},E=u!==null?x(u):Promise.resolve([]);return Promise.all([E,x(ku)]).then(([y,S])=>{b||(s(Zj(y,S)),l(!1))}).catch(()=>{b||l(!0)}),()=>{b=!0,f.abort()}},[e.path,u]),o.jsxs("div",{className:"flex flex-col h-full overflow-hidden bg-spur-bg","data-conversation-view":!0,children:[o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-1","data-conversation-thread":!0,children:[a===null&&!i&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-conversation-loading":!0,children:"Loading conversation…"}),i&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-conversation-fetch-failed":!0,role:"alert",children:"Conversation unavailable — the message feed could not be read."}),p&&!i&&o.jsx("div",{className:"p-4 text-xs text-spur-text-muted","data-conversation-requests-failed":!0,role:"status",children:"Results feed unavailable — receipt states may be stale."}),a!==null&&a.length===0&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-conversation-empty":!0,children:"No messages yet for this project."}),m?.map(f=>o.jsx(dq,{entry:f},f.id))]}),o.jsxs("div",{className:"border-t border-spur-border bg-spur-surface shrink-0 p-2 space-y-1","data-conversation-composer":!0,children:[c&&o.jsx("div",{className:"text-xs text-spur-text-muted","data-conversation-orchestrator-missing":!0,children:"Orchestrator unavailable — no orchestrator instance is bound to this project, so requests cannot be delivered yet."}),t.refs.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1","data-draft-refs":!0,children:t.refs.map(f=>o.jsx(pq,{ref_:f,onRemove:r},uN(f)))}),o.jsx("textarea",{className:"w-full resize-none rounded-xl border border-spur-border bg-spur-bg p-2 text-sm text-spur-text focus:outline-none focus:ring-1 focus:ring-spur-accent",rows:3,value:t.text,onChange:f=>n(f.target.value),"aria-label":"Conversation draft",placeholder:"Describe what you need — submission is wired to the global input.","data-conversation-draft-input":!0})]})]})}function uN(e){return e.kind==="task"?`task:${e.wbs}`:`feature:${e.id}`}function dq({entry:e}){const t=e.receipt,n=oN(t??null,null,!1),r=iN[n];return o.jsxs("div",{className:"p-2 bg-spur-surface-2 border border-spur-border rounded-xl text-sm","data-conversation-entry":!0,"data-conversation-kind":e.kind,children:[o.jsxs("div",{className:"flex items-center gap-2 text-spur-text-muted text-xs",children:[o.jsx("span",{className:"font-medium text-spur-text",children:e.kind==="request"?"Request":"Response"}),o.jsxs("span",{className:"font-mono truncate","data-conversation-route":!0,children:[e.fromId??"system"," → ",e.toId]}),o.jsx("span",{className:"text-xs px-1 rounded bg-spur-surface-3 text-spur-text","data-conversation-delivery":!0,children:e.deliveryStatus}),e.kind==="request"&&o.jsxs("span",{className:"text-xs px-1 rounded font-medium","data-conversation-receipt-state":n,title:`${r.meaning} Next: ${r.action}`,children:[o.jsx("span",{"aria-hidden":"true",children:r.icon})," ",r.label]}),e.inReplyTo!==null&&o.jsxs("span",{className:"font-mono text-xs opacity-70","data-conversation-reply-to":!0,children:["↩ ",e.inReplyTo]}),o.jsx("span",{className:"ml-auto font-mono text-xs text-spur-text-muted",children:e.createdAt})]}),e.refs.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1 mt-1","data-conversation-entry-refs":!0,children:e.refs.map(a=>o.jsx("span",{className:"text-xs px-1 rounded bg-info/20 text-info font-mono","data-conversation-ref":a.kind,children:a.kind==="task"?`task ${a.wbs}`:`feature ${a.id}`},uN(a)))}),o.jsx("p",{className:"text-spur-text mt-1 whitespace-pre-wrap break-words",children:e.text})]})}function pq({ref_:e,onRemove:t}){const n=e.kind==="task"?`task ${e.wbs}`:`feature ${e.id}`;return o.jsxs("button",{type:"button",className:"text-xs px-1 rounded bg-info/20 text-info font-mono hover:bg-info/30","aria-label":`Remove ${n} reference from the draft`,onClick:()=>t(e),"data-draft-ref":e.kind,"data-g6":e.kind==="task"?"task-chip":void 0,children:[n," ✕"]})}const fq=()=>`${Ct()}/processes`;function mq(e,t){const n=e.map(s=>({key:`sup:${s.agentId}`,label:s.agentId,agentId:s.agentId,pid:s.pid,status:s.status,startedAt:s.startedAt,source:"supervisor",teamId:s.teamId??null})),r=new Set(e.map(s=>s.agentId)),a=new Set(e.map(s=>s.pid).filter(s=>s!=null));for(const s of t)s.agentId&&r.has(s.agentId)||s.pid!=null&&a.has(s.pid)||n.push({key:`reg:${s.id}`,label:s.label||s.command,agentId:s.agentId??void 0,pid:s.pid,status:s.status,startedAt:s.startedAt,source:s.source,teamId:s.teamId??null});return n}function hq(e,t){return e.filter(n=>{if(t.runningOnly&&n.status!=="running")return!1;if(t.source==="other"){if(n.source==="supervisor"||n.source==="one-shot")return!1}else if(t.source!=="all"&&n.source!==t.source)return!1;if(t.team==="unassigned"){if(n.teamId!=null)return!1}else if(t.team!=="all"&&n.teamId!==t.team)return!1;return!0})}function Wy({filters:e,onFilters:t,teamIds:n,totalCount:r,shownCount:a}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-2 text-xs","data-processes-filters":!0,children:[o.jsxs("label",{className:"flex items-center gap-1","data-processes-filter-running":!0,children:[o.jsx("input",{type:"checkbox",checked:e.runningOnly,onChange:s=>t({...e,runningOnly:s.target.checked}),"data-processes-filter-running-input":!0}),o.jsx("span",{children:"Running only"})]}),o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("span",{children:"Source"}),o.jsxs("select",{value:e.source,onChange:s=>t({...e,source:s.target.value}),className:"border border-spur-border rounded px-1 py-0.5 bg-spur-bg text-spur-text","data-processes-filter-source":!0,"aria-label":"Source filter",children:[o.jsx("option",{value:"all",children:"all"}),o.jsx("option",{value:"supervisor",children:"supervisor"}),o.jsx("option",{value:"one-shot",children:"one-shot"}),o.jsx("option",{value:"other",children:"other"})]})]}),o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("span",{children:"Team"}),o.jsxs("select",{value:e.team,onChange:s=>t({...e,team:s.target.value}),className:"border border-spur-border rounded px-1 py-0.5 bg-spur-bg text-spur-text","data-processes-filter-team":!0,"aria-label":"Team filter",children:[o.jsx("option",{value:"all",children:"all teams"}),o.jsx("option",{value:"unassigned",children:"unassigned"}),n.map(s=>o.jsx("option",{value:s,children:s},s))]})]}),o.jsx("button",{type:"button",className:"border border-spur-border rounded px-2 py-0.5 text-spur-text hover:bg-base-200 transition-colors cursor-pointer",onClick:()=>t({runningOnly:!1,source:"all",team:"all"}),"data-processes-filter-clear":!0,children:"Clear"}),o.jsxs("span",{className:"text-spur-text-muted","data-processes-filter-count":!0,children:[a,"/",r," shown"]})]})}function gq({pollMs:e=zb}){const[t,n]=g.useState(null),[r,a]=g.useState(null),[s,i]=g.useState({runningOnly:!1,source:"all",team:"all"}),l=g.useRef(!0),u=g.useCallback(async b=>{try{const x=await ht(new Request(fq(),{signal:b}));if(!x.ok)throw new Error(`processes fetch failed: ${x.status}`);const E=await x.json(),y=Hb(E),S=GW(E);if(!y||!S)return;l.current&&(n({processes:y,executions:S}),a(null))}catch(x){if(b.aborted)return;l.current&&a(x instanceof Error?x.message:String(x))}},[]);g.useEffect(()=>{l.current=!0;let b=null;const x=()=>{b?.abort(),b=new AbortController,u(b.signal)};x();const E=setInterval(x,e);return()=>{l.current=!1,b?.abort(),clearInterval(E)}},[u,e]);const c=g.useMemo(()=>t?mq(t.processes,t.executions):[],[t]),d=g.useMemo(()=>hq(c,s),[c,s]),p=g.useMemo(()=>{const b=new Set;for(const x of t?.processes??[])x.teamId&&b.add(x.teamId);for(const x of t?.executions??[])x.teamId&&b.add(x.teamId);return[...b].sort()},[t]);if(r&&(!t||c.length===0))return o.jsxs("div",{className:"p-4 text-sm text-error",role:"alert","data-processes-tab-error":!0,children:["Failed to load processes: ",r]});if(!t)return o.jsx("div",{className:"p-4","data-processes-tab-loading":!0,children:o.jsx(Fa,{size:"sm"})});if(c.length===0)return o.jsxs("div",{className:"p-4 text-sm text-spur-text-muted","data-processes-tab-empty":!0,children:["No processes. Start an agent from the Agents tab or via"," ",o.jsx("code",{className:"font-mono",children:"spur agent start"}),"."]});if(d.length===0)return o.jsxs("div",{className:"p-3 overflow-auto h-full","data-processes-tab":!0,"data-processes-tab-filtered-empty":!0,children:[o.jsx(Wy,{filters:s,onFilters:i,teamIds:p,totalCount:c.length,shownCount:0}),o.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-processes-tab-no-matches":!0,children:"No processes match the current filters. Adjust or clear filters to see rows."})]});const m=t.processes.length,f=Math.max(0,c.length-m);return o.jsxs("div",{className:"p-3 overflow-auto h-full","data-processes-tab":!0,children:[o.jsx(Wy,{filters:s,onFilters:i,teamIds:p,totalCount:c.length,shownCount:d.length}),o.jsxs("div",{className:"flex items-center gap-2 mb-2 text-xs text-spur-text-muted",children:[o.jsxs("span",{"data-processes-header":!0,children:["Process watch list (",c.length,m>0||f>0?` · ${m} supervised${f>0?` · ${f} other`:""}`:"",")"]}),o.jsx("span",{className:"italic",children:"— ProcessExecutor registry (ts-runtime)"})]}),o.jsxs("table",{className:"table table-xs",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Name"}),o.jsx("th",{children:"Source"}),o.jsx("th",{children:"Team"}),o.jsx("th",{children:"PID"}),o.jsx("th",{children:"Status"}),o.jsx("th",{children:"Started"})]})}),o.jsx("tbody",{children:d.map(b=>{const x=b.status==="running";return o.jsxs("tr",{"data-processes-row":b.key,children:[o.jsx("td",{className:"font-mono text-xs",children:b.label}),o.jsx("td",{className:"text-xs text-spur-text-muted","data-process-source":b.source,children:b.source}),o.jsx("td",{className:"font-mono text-xs text-spur-text-muted","data-process-team":b.teamId??"",children:b.teamId??"—"}),o.jsx("td",{className:"font-mono text-xs text-spur-text-muted",children:b.pid??"—"}),o.jsx("td",{children:o.jsx(gn,{variant:x?"success":"ghost",size:"xs",children:b.status})}),o.jsx("td",{className:"text-xs text-spur-text-muted",children:new Date(b.startedAt).toLocaleTimeString()})]},b.key)})})]})]})}const bq="conversation",Lr=[{id:"conversation",label:"Conversation",component:cq},{id:"agents",label:"Agents",component:aq},{id:"processes",label:"Processes",component:gq}];function xq(){const e=Zn(),t=qi();return{activeTab:(()=>{const a=e.pathname.split("/"),s=a.indexOf("projects"),i=s>=0?a[s+1]:void 0;return Lr.some(l=>l.id===i)?i:bq})(),selectTab:a=>{const s=new URLSearchParams(e.search).toString();t(`/board/projects/${a}${s?`?${s}`:""}`,{replace:!0})}}}function Eq(e){if(e.state==="loading")return"loading";if(e.state==="unresolvable")return"unresolvable";if(e.fleet===null)return"fleet-unavailable";const{orchestrator:t,capacity:n,strategy:r}=e.fleet;return t.state!=="bound-online"?t.state:n.total===0?"no-fleet":n.missing.length>0?"capacity-missing":r===null?"strategy-unavailable":"ready"}function yq(e){switch(e.orchestrator.state){case"bound-online":return`online${e.orchestrator.instanceId?` — ${e.orchestrator.instanceId}`:""}`;case"bound-offline":return"bound but not responding";case"missing":return"no orchestrator bound";case"unresolvable":return`unresolvable${e.orchestrator.reason?` — ${e.orchestrator.reason}`:""}`}}function cN(){const e=Os(),{activeTab:t,selectTab:n}=xq(),a=(Lr.find(u=>u.id===t)??Lr[0])?.component,s=Eq(e),i=e.fleet,l=u=>{if(u.key!=="ArrowRight"&&u.key!=="ArrowLeft")return;u.preventDefault();const c=Lr.findIndex(m=>m.id===t),d=u.key==="ArrowRight"?1:-1,p=Lr[(c+d+Lr.length)%Lr.length];p&&(u.currentTarget.querySelectorAll('[role="tab"]')[Lr.indexOf(p)]?.focus(),n(p.id))};return o.jsxs("div",{className:"projects flex flex-col h-full overflow-hidden bg-spur-bg","data-projects-shell":!0,children:[o.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-spur-surface shrink-0 flex flex-col gap-1","data-projects-header":!0,"data-projects-state":s,children:[e.state==="unresolvable"?o.jsxs("div",{className:"text-xs",children:[o.jsx("span",{className:"font-semibold text-spur-text",children:"Project path unavailable"}),o.jsxs("span",{className:"text-spur-text-muted",children:[" ","— the server did not report this project's worktree path; project-scoped state stays unloaded."]})]}):o.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[o.jsx("span",{className:"text-sm font-semibold text-spur-text shrink-0",children:e.name||"Projects"}),o.jsx("span",{className:"text-xs text-spur-text-muted font-mono",children:e.path})]}),e.state!=="unresolvable"&&i===null&&o.jsx("div",{className:"text-xs text-spur-text-muted",children:"Fleet status unavailable"}),i!==null&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-xs text-spur-text-muted",children:["Orchestrator: ",o.jsx("span",{className:"text-spur-text",children:yq(i)})]}),o.jsxs("div",{className:"text-xs text-spur-text-muted",children:["Fleet:"," ",i.capacity.total===0?o.jsxs("span",{className:"text-spur-text",children:["no fleet declared — expected"," ",o.jsx("code",{className:"font-mono",children:"agent.fleet in .spur/config.yaml"})]}):i.enabled===!1?o.jsxs("span",{className:"text-spur-text",children:["disabled (",o.jsx("code",{className:"font-mono",children:"agent.fleet.enabled: false"}),") —"," ",i.capacity.total," member",i.capacity.total===1?"":"s"," declared"]}):o.jsxs("span",{className:"text-spur-text",children:[i.capacity.total," member",i.capacity.total===1?"":"s"," ·"," ",i.capacity.enabled," enabled · ",i.capacity.writeCapable," write-capable",i.capacity.missing.length>0?` · unresolved: ${i.capacity.missing.join(", ")}`:""]})]}),o.jsxs("div",{className:"text-xs text-spur-text-muted",children:["Strategy:"," ",i.strategy===null?o.jsx("span",{className:"text-spur-text",children:"strategy unavailable"}):o.jsxs("span",{className:"text-spur-text",children:[i.strategy.name," (v",i.strategy.version,")"]})]})]})]}),o.jsx("div",{role:"tablist","aria-label":"Projects tabs",onKeyDown:l,className:"flex items-center gap-1 px-2 py-1 border-b border-spur-border bg-spur-surface shrink-0",children:Lr.map(u=>{const c=u.id===t;return o.jsx("button",{type:"button",role:"tab","aria-selected":c,"aria-controls":`projects-tab-panel-${u.id}`,id:`projects-tab-${u.id}`,onClick:()=>n(u.id),className:`px-3 py-1 rounded-lg text-xs font-medium transition-colors ${c?"bg-spur-accent text-white":"text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-3"}`,"data-projects-tab":u.id,children:u.label},u.id)})}),o.jsx("div",{role:"tabpanel",id:`projects-tab-panel-${t}`,"aria-labelledby":`projects-tab-${t}`,className:"flex-1 overflow-hidden",children:a?o.jsx(a,{}):null})]})}const Tq={id:"projects",name:"Projects",icon:"📁",route:"projects",component:cN,sidebarLabel:"Projects",description:"Conversation, agents, and processes for this project",order:45},Sq=Object.freeze(Object.defineProperty({__proto__:null,ProjectsShell:cN,module:Tq},Symbol.toStringTag,{value:"Module"})),Bu=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Ls(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Gb(e){return"nodeType"in e}function jn(e){var t,n;return e?Ls(e)?e:Gb(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Wb(e){const{Document:t}=jn(e);return e instanceof t}function po(e){return Ls(e)?!1:e instanceof jn(e).HTMLElement}function dN(e){return e instanceof jn(e).SVGElement}function Ms(e){return e?Ls(e)?e.document:Gb(e)?Wb(e)?e:po(e)||dN(e)?e.ownerDocument:document:document:document}const Br=Bu?g.useLayoutEffect:g.useEffect;function Uu(e){const t=g.useRef(e);return Br(()=>{t.current=e}),g.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return t.current==null?void 0:t.current(...r)},[])}function vq(){const e=g.useRef(null),t=g.useCallback((r,a)=>{e.current=setInterval(r,a)},[]),n=g.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function $i(e,t){t===void 0&&(t=[e]);const n=g.useRef(e);return Br(()=>{n.current!==e&&(n.current=e)},t),n}function fo(e,t){const n=g.useRef();return g.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function Pl(e){const t=Uu(e),n=g.useRef(null),r=g.useCallback(a=>{a!==n.current&&t?.(a,n.current),n.current=a},[]);return[n,r]}function Bl(e){const t=g.useRef();return g.useEffect(()=>{t.current=e},[e]),t.current}let Zc={};function $u(e,t){return g.useMemo(()=>{if(t)return t;const n=Zc[e]==null?0:Zc[e]+1;return Zc[e]=n,e+"-"+n},[e,t])}function pN(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return r.reduce((s,i)=>{const l=Object.entries(i);for(const[u,c]of l){const d=s[u];d!=null&&(s[u]=d+e*c)}return s},{...t})}}const cs=pN(1),Ul=pN(-1);function wq(e){return"clientX"in e&&"clientY"in e}function qb(e){if(!e)return!1;const{KeyboardEvent:t}=jn(e.target);return t&&e instanceof t}function Nq(e){if(!e)return!1;const{TouchEvent:t}=jn(e.target);return t&&e instanceof t}function $l(e){if(Nq(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return wq(e)?{x:e.clientX,y:e.clientY}:null}const bs=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[bs.Translate.toString(e),bs.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),qy="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Aq(e){return e.matches(qy)?e:e.querySelector(qy)}const _q={display:"none"};function kq(e){let{id:t,value:n}=e;return at.createElement("div",{id:t,style:_q},n)}function Cq(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return at.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function Iq(){const[e,t]=g.useState("");return{announce:g.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const fN=g.createContext(null);function Rq(e){const t=g.useContext(fN);g.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function Dq(){const[e]=g.useState(()=>new Set),t=g.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[g.useCallback(r=>{let{type:a,event:s}=r;e.forEach(i=>{var l;return(l=i[a])==null?void 0:l.call(i,s)})},[e]),t]}const Oq={draggable:`
183
+ `)[0]?.trim()==="---"?"markdown":"text":"text"}function $c(e,t){if(!e)return null;switch(xG(e,t)){case"bash":return Ml(e);case"xml":return gG(e);case"json":{const r=t?Hw(t):{defaultLanguage:"json"};return qw(e,r)}case"markdown":return bG(e);default:return e}}const EG=({code:e,toolName:t="",language:n,className:r=""})=>{const a=g.useMemo(()=>Hw(t),[t]),s=n??a.defaultLanguage,i=g.useMemo(()=>s==="bash"?Ml(e):s==="diff"?Ww(e):qw(e,a),[e,s,a]);return o.jsx("div",{className:`font-mono text-[11px] select-text cursor-text ${r}`,children:i})},yG=({agentId:e,model:t="—",timestamp:n,tooltipId:r,freshInputTokens:a=0,cacheReadTokens:s=0,outputTokens:i=0,sessionId:l,className:u=""})=>{const[c,d]=g.useState(!1),p=g.useMemo(()=>`agent-badge-tt-${e}-${Math.random().toString(36).slice(2,7)}`,[e]),m=r||p,f=a+s+i;return o.jsxs("div",{className:`relative inline-flex items-center z-30 ${u}`,children:[o.jsx("button",{type:"button","aria-describedby":m,"aria-label":`Coding agent ${e} icon and metadata`,className:"p-1 rounded-md bg-base-300 border border-base-content/15 hover:border-primary text-base-content/80 hover:text-primary transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-primary shrink-0",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),onFocus:()=>d(!0),onBlur:()=>d(!1),onKeyDown:b=>{b.key==="Escape"&&d(!1)},"data-testid":`agent-badge-${m}`,children:o.jsx(_r,{id:e})}),c&&o.jsxs("div",{id:m,role:"tooltip","data-testid":m,className:"absolute left-0 top-full z-50 mt-1.5 w-64 p-3 rounded-xl bg-base-300 border border-base-content/20 shadow-2xl text-[11px] font-mono leading-relaxed pointer-events-none backdrop-blur-md flex flex-col gap-2.5 select-none",children:[o.jsx("div",{className:"flex items-center justify-between border-b border-base-content/10 pb-2",children:o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"p-1 rounded bg-base-200 text-primary shrink-0",children:o.jsx(_r,{id:e})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"font-bold text-base-content uppercase tracking-wider text-[11px]",children:e}),o.jsx("div",{className:"text-[10px] text-base-content/60 truncate",title:t??"",children:t||"—"})]})]})}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-1 text-base-content/80 text-[10.5px]",children:[o.jsx("span",{className:"text-base-content/50",children:"Timestamp:"}),o.jsx("span",{className:"truncate",children:n?mG(n):"—"}),l&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-base-content/50",children:"Session:"}),o.jsx("span",{className:"truncate font-bold text-primary",title:l,children:l.length>16?`${l.slice(0,14)}…`:l})]})]}),o.jsxs("div",{className:"pt-2 border-t border-base-content/10 flex flex-col gap-1 text-[10.5px]",children:[o.jsx("div",{className:"font-bold text-base-content/70 text-[10px] uppercase tracking-wider",children:"Token Breakdown"}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80",children:[o.jsx("span",{className:"text-base-content/50",children:"📥 Fresh input:"}),o.jsx("span",{children:Fr(a)}),o.jsx("span",{className:"text-base-content/50",children:"💾 Cache read:"}),o.jsx("span",{className:"text-cyan-400",children:Fr(s)}),o.jsx("span",{className:"text-base-content/50",children:"📤 Output:"}),o.jsx("span",{children:Fr(i)}),o.jsx("span",{className:"text-base-content/50 border-t border-base-content/10 pt-0.5",children:"⚡ Total load:"}),o.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Fr(f)})]})]})]})]})},Ub=({item:e,categoryColor:t,label:n,badgePrefix:r,size:a="sm",className:s="",testId:i,tooltipId:l,onClick:u})=>{const[c,d]=g.useState(!1),[p,m]=g.useState(!1),[f,b]=g.useState(!1),[x,E]=g.useState(!1),y=g.useRef(null),S=e.category??Gw(e.toolName),v=t??Ll[S]??Ll.other,N=e.seq??e.toolSeq??1,A=l||`tool-tooltip-${N}-${e.toolName}`,w=g.useMemo(()=>{if(!e.argsRaw)return null;try{const te=JSON.parse(e.argsRaw);return JSON.stringify(te,null,2)}catch{return e.argsRaw}},[e.argsRaw]),T=async te=>{if(te.stopPropagation(),!!w)try{await navigator.clipboard.writeText(w),b(!0),setTimeout(()=>b(!1),2e3)}catch{}},_=async te=>{if(te.stopPropagation(),!!e.errorText)try{await navigator.clipboard.writeText(e.errorText),E(!0),setTimeout(()=>E(!1),2e3)}catch{}},B=()=>{y.current&&(clearTimeout(y.current),y.current=null)},k=()=>{B(),d(!0)},$=()=>{p||(B(),y.current=setTimeout(()=>{d(!1)},150))},V=te=>{te.stopPropagation(),m(ie=>!ie),d(!0),u?.(te)},P=c||p,H=e.status==="error",W=a==="xs"?"px-1.5 py-0.2 text-[10px]":a==="md"?"px-2.5 py-1 text-xs":"px-2 py-0.5 text-[11px]",L=n??`${r??""}${e.toolName}`;return o.jsxs("div",{className:`relative inline-flex items-center ${s}`,children:[o.jsx("button",{type:"button","aria-describedby":A,className:`${W} rounded-md font-mono font-bold text-white shrink-0 tracking-wide cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-primary shadow-xs transition-opacity hover:opacity-90`,style:{backgroundColor:v},onClick:V,onMouseEnter:k,onMouseLeave:$,onFocus:()=>{B(),d(!0)},onBlur:()=>{p||d(!1)},onKeyDown:te=>{te.key==="Escape"&&(m(!1),d(!1))},"data-testid":i??`tool-tag-${N}`,children:L}),o.jsxs("div",{id:A,role:"tooltip","data-testid":l??`tool-tooltip-${N}`,"data-inspector-tooltip":"true",className:`absolute left-0 top-full mt-2 z-50 w-[880px] max-w-[95vw] bg-base-300 border border-base-content/20 shadow-2xl rounded-xl p-4 text-xs font-mono text-base-content backdrop-blur-md flex flex-col gap-3 pointer-events-auto select-text cursor-default ${P?"block":"hidden"}`,onMouseEnter:()=>{B(),d(!0)},onMouseLeave:$,onClick:te=>te.stopPropagation(),onKeyDown:te=>{te.key==="Escape"&&(m(!1),d(!1)),te.stopPropagation()},children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-base-content/10 pb-2.5",children:[o.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[o.jsx("span",{className:"px-2.5 py-0.5 rounded-md text-xs font-bold text-white shrink-0 tracking-wide",style:{backgroundColor:v},children:e.toolName}),o.jsxs("span",{className:"text-xs text-base-content/50 font-bold",children:["#",N]}),o.jsxs("span",{className:"text-[11px] text-base-content/60 uppercase tracking-wider",children:["(",S,")"]})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("span",{className:`px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider ${H?"bg-error/20 text-error":"bg-success/20 text-success"}`,children:e.status??"ok"}),p&&o.jsx("button",{type:"button",className:"text-base-content/50 hover:text-base-content text-xs p-1 leading-none rounded hover:bg-base-content/10 cursor-pointer",onClick:te=>{te.stopPropagation(),m(!1),d(!1)},title:"Close tooltip",children:"✕"})]})]}),e.errorText&&o.jsxs("div",{className:"bg-error/10 text-error border border-error/20 rounded-lg p-2.5 text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{className:"font-bold",children:"Execution Error:"}),o.jsx("button",{type:"button",className:"px-1.5 py-0.5 rounded text-[10px] bg-error/20 hover:bg-error/30 transition-colors cursor-pointer",onClick:_,children:x?"✓ Copied":"Copy"})]}),o.jsx("pre",{className:"font-mono text-[11px] whitespace-pre-wrap max-h-36 overflow-y-auto",children:e.errorText})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-[11px] font-semibold text-base-content/70",children:["Arguments (raw)"," ",o.jsx("span",{className:"text-base-content/40 font-normal",children:"(syntax-highlighted)"})]}),w&&o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded text-[10px] font-mono text-base-content/70 hover:text-base-content hover:bg-base-content/10 transition-colors cursor-pointer border border-base-content/10",onClick:T,children:f?"✓ Copied":"Copy"})]}),w?o.jsx("div",{className:"bg-base-100 p-3 rounded-lg text-[11px] font-mono overflow-x-auto max-h-60 border border-base-content/10 whitespace-pre-wrap break-all text-base-content/90 overflow-y-auto",children:o.jsx(EG,{code:w,toolName:e.toolName})}):o.jsxs("div",{className:"p-2.5 bg-base-100/50 rounded-lg text-xs text-base-content/50 italic border border-base-content/10",children:["Raw payload omitted at import; digest available: ",e.argsDigest??"—"]}),e.argsDigest&&e.argsDigest!==e.argsRaw&&o.jsxs("div",{className:"text-[10px] text-base-content/50 truncate mt-0.5",children:[o.jsx("span",{className:"font-semibold",children:"Digest: "}),e.argsDigest]})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-xs font-mono bg-base-200/70 p-2.5 rounded-lg border border-base-content/10",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"DURATION"}),o.jsx("span",{className:"text-[11px]",children:e.durationMs!==null&&e.durationMs!==void 0?`${e.durationMs} ms (${e.durationSource??"measured"})`:`— (${e.durationSource??"unmeasured"})`})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"TIMESTAMP"}),o.jsx("span",{className:"text-[11px] truncate block",children:e.ts??"—"})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"SOURCE / MODEL"}),o.jsxs("span",{className:"text-[11px] truncate block",title:`${e.source??"—"} / ${e.model??"—"}`,children:[e.source??"—"," / ",e.model??"—"]})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"SESSION ID"}),o.jsx("span",{className:"text-[11px] truncate block",title:e.sessionId??"—",children:e.sessionId??"—"})]}),e.callId&&o.jsxs("div",{className:"col-span-2 md:col-span-4",children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"CALL ID"}),o.jsx("span",{className:"text-[11px] truncate block",title:e.callId,children:e.callId})]}),e.tokens&&o.jsxs("div",{className:"col-span-2 md:col-span-4 pt-1 border-t border-base-content/10",children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"TOKEN LOAD (SHARE)"}),o.jsxs("span",{className:"text-[11px]",children:["Billed: ",Fr(e.tokens.billedTokens)," (Fresh:"," ",Fr(e.tokens.freshInputTokens),", Cache:"," ",Fr(e.tokens.cacheReadTokens),", Output:"," ",Fr(e.tokens.outputTokens),")"]})]})]})]})]})},TG=Ub,SG=({calls:e,fromSeq:t=1,toSeq:n=1,toolName:r,sessionId:a,maxVisible:s=12,className:i=""})=>{const[l,u]=g.useState(!1),c=g.useMemo(()=>{if(e&&e.length>0)return e;const m=[],f=Math.max(1,n-t+1);for(let b=0;b<f;b++)m.push({seq:t+b,toolSeq:t+b,toolName:r,sessionId:a,category:Gw(r),status:"ok"});return m},[e,t,n,r,a]),d=l?c:c.slice(0,s),p=c.length-d.length;return o.jsxs("div",{className:`flex flex-wrap items-center gap-1.5 ${i}`,children:[d.map(m=>o.jsx(Ub,{item:m,label:`#${m.seq}`,size:"xs"},`${m.sessionId}-${m.seq}-${m.callId??""}`)),p>0&&o.jsxs("button",{type:"button",className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-base-content/10 text-base-content/70 hover:bg-base-content/20 transition-colors cursor-pointer",onClick:()=>u(!0),children:["+",p," more"]}),l&&c.length>s&&o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-base-content/10 text-base-content/70 hover:bg-base-content/20 transition-colors cursor-pointer",onClick:()=>u(!1),children:"Show less"})]})};function Ny(e){const t=e.toLowerCase();return t.includes("read")||t.includes("view")||t.includes("cat")?"read":t.includes("write")||t.includes("edit")||t.includes("replace")||t.includes("patch")?"write":t.includes("bash")||t.includes("command")||t.includes("exec")||t.includes("terminal")?"bash":t.includes("grep")||t.includes("find")||t.includes("search")||t.includes("glob")?"search":t.includes("mcp")?"mcp":"other"}const Vw=({data:e,loading:t,error:n,cacheHitTrend:r,onSelectSession:a})=>{const[s,i]=g.useState("model"),[l,u]=g.useState("asc"),c=g.useMemo(()=>({"claude-opus-4.6":"#3987e5","claude-sonnet-4.6":"#199e70","gpt-5.6-sol":"#9085e9","grok-4.6":"#d95926",other:"#898781"}),[]),d=g.useMemo(()=>["Speed","Cache Ratio","Reliability","Output Ratio"],[]);if(t)return o.jsxs("div",{className:"flex flex-col items-center justify-center p-20 gap-3",children:[o.jsx("div",{className:"w-9 h-9 rounded-full border-3 border-primary border-t-transparent animate-spin"}),o.jsx("span",{className:"text-xs font-mono text-base-content/60",children:"Analyzing operational insights..."})]});if(n)return o.jsxs("div",{className:"p-5 rounded-xl bg-error/10 border border-error/20 text-error flex items-center gap-3",children:[o.jsx("span",{className:"text-lg",children:"⚠️"}),o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-sm",children:"Failed to load insights"}),o.jsx("p",{className:"text-xs opacity-80",children:n})]})]});if(!e)return null;const{loops:p,cacheWaste:m,heavySessions:f,largestTokenSteps:b,slowSteps:x,modelComparison:E}=e,y=L=>{s===L?u(te=>te==="asc"?"desc":"asc"):(i(L),u(L==="model"?"asc":"desc"))},S=[...E].sort((L,te)=>{const ie=l==="asc"?1:-1;return s==="model"?ie*L.model.localeCompare(te.model):ie*((L[s]??0)-(te[s]??0))}),v=L=>s!==L?o.jsx("span",{className:"opacity-30 ml-1 text-[10px]",children:"↕"}):o.jsx("span",{className:"text-primary ml-1 text-[10px]",children:l==="asc"?"▲":"▼"}),N=Math.max(1,...f.map(L=>L.tokens)),A=Math.max(1,...x.map(L=>L.durationMs??0)),w=p.reduce((L,te)=>L+(te.wastedTokens??0),0),T=m.reduce((L,te)=>L+(te.freshTokens??0),0),_=x[0],B=b[0],k=E.map(L=>L.speedMsMean),$=k.length>0?Math.min(...k):0,V=k.length>0?Math.max(...k):0,P=L=>V===$?100:Math.max(0,Math.min(100,Math.round((V-L)/(V-$)*100))),H=L=>Math.max(0,Math.min(100,Math.round(L*100))),W=E.map(L=>{const te=P(L.speedMsMean),ie=H(L.cacheRatio),be=H(L.reliability),I=H(L.outputRatio*5);return{label:L.model,color:c[L.model]??"#3987e5",values:[te,ie,be,I]}});return o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsxs("div",{className:`rounded-xl p-4 border flex flex-col justify-between transition-all ${p.length>0?"bg-warning/10 border-warning/30 text-warning":"bg-base-200 border-base-content/10"}`,children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Loop Anomalies"}),o.jsx("span",{children:p.length>0?"⚠️":"✓"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsxs("div",{className:"text-xl font-bold font-mono",children:[p.length," ",p.length===1?"incident":"incidents"]}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:p.length>0?`${Be(w)} wasted tokens`:"Clean execution"})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Cache Waste"}),o.jsx("span",{className:"text-cyan-400",children:"⚡"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-error",children:Be(T)}),o.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Across ",m.length," un-cached steps"]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Peak Step Tokens"}),o.jsx("span",{className:"text-primary",children:"📊"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-primary",children:B?Be(B.tokens):"—"}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5 truncate",children:B?`${B.toolName} (#${B.stepIndex})`:"No outlier steps"})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Peak Latency"}),o.jsx("span",{className:"text-amber-400",children:"⏱️"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-amber-400",children:_?.durationMs?ns(_.durationMs):"—"}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5 truncate",children:_?`${_.toolName} (#${_.stepIndex})`:"No slow steps"})]})]})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[o.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col justify-between",children:o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Top Cache-Wasting Incidents"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[m.length," incidents"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Steps that re-sent full context without cache hits"}),o.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3 items-start",children:[(r?.length??0)>1&&o.jsxs("div",{"data-testid":"cache-hit-trend-chart",className:"p-3 bg-base-300/40 rounded-xl border border-base-content/5",children:[o.jsx("div",{className:"text-[10px] font-mono text-base-content/60 uppercase tracking-wider mb-2",children:"Cache Hit Ratio Trend"}),o.jsx(uG,{points:(r??[]).map(L=>({id:L.day,label:L.day.slice(5),v:L.cacheHitRatio})),color:"#22d3ee",height:130})]}),o.jsx("div",{className:"overflow-x-auto w-full",children:m.length>0?o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Session"}),o.jsx("th",{className:"py-1.5 text-right",children:"Fresh Tokens"}),o.jsx("th",{className:"py-1.5 pl-3",children:"Cause"})]})}),o.jsx("tbody",{children:m.map(L=>o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[o.jsx("td",{className:"py-1.5",children:o.jsxs("button",{type:"button",className:"text-primary hover:underline font-mono inline-flex items-center gap-1 cursor-pointer",onClick:()=>a?.(L.sessionId),title:`Jump to session ${L.sessionId}`,children:[o.jsx("span",{children:L.sessionId}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),o.jsx("td",{className:"py-1.5 text-right text-error font-bold whitespace-nowrap",children:Be(L.freshTokens)}),o.jsx("td",{className:"py-1.5 pl-3 text-base-content/70 truncate max-w-[140px]",title:L.reason,children:L.reason})]},`${L.sessionId}-${L.freshTokens}-${L.timestamp}`))})]}):o.jsx("div",{className:"p-6 text-center text-xs font-mono text-base-content/50",children:"✓ No cache-wasting incidents detected"})})]})]})}),o.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col justify-between",children:o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Heaviest Token Sessions"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[f.length," sessions"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Sessions consuming highest billed volume"}),o.jsx("div",{className:"flex flex-col gap-3",children:f.length>0?f.map(L=>o.jsxs("div",{className:"p-3 bg-base-300/40 rounded-xl border border-base-content/5 flex flex-col gap-1.5 hover:bg-base-300/70 transition-colors",children:[o.jsxs("div",{className:"flex justify-between items-center text-xs font-mono",children:[o.jsxs("button",{type:"button",className:"text-primary hover:underline font-bold inline-flex items-center gap-1.5 cursor-pointer text-left",onClick:()=>a?.(L.id,L.source),title:`Jump to session ${L.id}`,children:[o.jsx("span",{children:L.id}),o.jsxs("span",{className:"text-[10px] font-normal px-1.5 py-0.2 rounded bg-base-content/10 text-base-content/70",children:[L.source," · ",L.model]}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]}),o.jsx("span",{className:"font-bold",children:Be(L.tokens)})]}),o.jsx(yi,{value:L.tokens,max:N,color:"#3987e5",height:6})]},L.id)):o.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No heavy sessions recorded in this timeframe"})})]})})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Top Time-Consuming Steps"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[x.length," steps"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Longest tool execution durations"}),o.jsx("div",{className:"overflow-x-auto",children:x.length>0?o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Tool / Step"}),o.jsx("th",{className:"py-1.5",children:"Session"}),o.jsx("th",{className:"py-1.5 text-right",children:"Duration"}),o.jsx("th",{className:"py-1.5 text-right",children:"Tokens"})]})}),o.jsx("tbody",{children:x.map(L=>{const te=Ny(L.toolName),ie=rs[te]??rs.other;return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[o.jsxs("td",{className:"py-1.5 font-bold",children:[o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[11px] border gap-1 mr-1.5 ${ie}`,children:L.toolName}),o.jsxs("span",{className:"text-[10px] text-base-content/50",children:["#",L.stepIndex]})]}),o.jsx("td",{className:"py-1.5",children:o.jsxs("button",{type:"button",className:"text-primary hover:underline inline-flex items-center gap-1 cursor-pointer",onClick:()=>a?.(L.sessionId,L.agent),title:`Jump to session ${L.sessionId}`,children:[o.jsx("span",{children:L.sessionId}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),o.jsx("td",{className:"py-1.5 text-right text-amber-400 font-bold w-24",children:o.jsxs("div",{className:"flex flex-col items-end gap-1",children:[o.jsx("span",{children:ns(L.durationMs??0)}),o.jsx(yi,{value:L.durationMs??0,max:A,color:"#fbbf24",height:4})]})}),o.jsx("td",{className:"py-1.5 text-right tabular-nums",children:Be(L.tokens)})]},`${L.sessionId}-${L.toolName}-${L.stepIndex}`)})})]}):o.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No slow steps recorded"})})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Largest Token Steps"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[b.length," steps"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Single tool calls with highest token load"}),o.jsx("div",{className:"overflow-x-auto",children:b.length>0?o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Tool / Step"}),o.jsx("th",{className:"py-1.5",children:"Session"}),o.jsx("th",{className:"py-1.5",children:"Agent / Model"}),o.jsx("th",{className:"py-1.5 text-right",children:"Tokens"})]})}),o.jsx("tbody",{children:b.map(L=>{const te=Ny(L.toolName),ie=rs[te]??rs.other;return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[o.jsxs("td",{className:"py-1.5 font-bold",children:[o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[11px] border gap-1 mr-1.5 ${ie}`,children:L.toolName}),o.jsxs("span",{className:"text-[10px] text-base-content/50",children:["#",L.stepIndex]})]}),o.jsx("td",{className:"py-1.5",children:o.jsxs("button",{type:"button",className:"text-primary hover:underline inline-flex items-center gap-1 cursor-pointer",onClick:()=>a?.(L.sessionId,L.agent),title:`Jump to session ${L.sessionId}`,children:[o.jsx("span",{children:L.sessionId}),o.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),o.jsx("td",{className:"py-1.5 text-xs text-base-content/70",children:o.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-base-300 text-[11px]",children:[L.agent," · ",L.model]})}),o.jsx("td",{className:"py-1.5 text-right text-primary font-bold tabular-nums",children:Be(L.tokens)})]},`${L.sessionId}-${L.toolName}-${L.stepIndex}`)})})]}):o.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No large token step outliers found"})})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("h4",{className:"font-bold text-sm",children:"Model Multi-Axis Comparison"}),o.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[E.length," models evaluated"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-4",children:"Evaluation across Speed, Cache ratio, Reliability, and Output ratio"}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 items-center",children:[o.jsxs("div",{className:"flex flex-col items-center justify-center p-3 bg-base-300/30 rounded-xl border border-base-content/5",children:[o.jsx(cG,{axes:d,series:W,height:280}),o.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3 mt-3",children:W.map(L=>o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-mono text-base-content/80 px-2 py-0.5 rounded-full bg-base-300 border border-base-content/10",children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:L.color}}),L.label]},L.label))})]}),o.jsx("div",{className:"overflow-x-auto w-full",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsxs("th",{className:"py-2 cursor-pointer select-none hover:text-base-content",onClick:()=>y("model"),children:["Model ",v("model")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("speedMsMean"),children:["Mean Speed (ms) ",v("speedMsMean")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("cacheRatio"),children:["Cache Ratio ",v("cacheRatio")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("reliability"),children:["Reliability ",v("reliability")]}),o.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>y("outputRatio"),children:["Output Ratio ",v("outputRatio")]})]})}),o.jsx("tbody",{children:S.map(L=>o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/40 transition-colors",children:[o.jsxs("td",{className:"py-2 font-bold flex items-center gap-2",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0 shadow-xs",style:{background:c[L.model]??"#3987e5"}}),o.jsx("span",{className:"truncate",children:L.model})]}),o.jsx("td",{className:"py-2 text-right font-mono tabular-nums",children:Wt(L.speedMsMean)}),o.jsx("td",{className:"py-2 text-right font-mono tabular-nums text-cyan-400 font-bold",children:ur(L.cacheRatio*100)}),o.jsx("td",{className:`py-2 text-right font-mono tabular-nums font-bold ${L.reliability>=.95?"text-emerald-400":L.reliability>=.8?"text-amber-400":"text-error"}`,children:ur(L.reliability*100)}),o.jsx("td",{className:"py-2 text-right font-mono tabular-nums text-base-content/80",children:ur(L.outputRatio*100)})]},L.model))})]})})]})]}),p.length>0&&o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-warning/30 p-5",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-warning text-lg",children:"⚠️"}),o.jsx("h3",{className:"font-bold text-base",children:"Detected Execution Loops (Repeats ≥ 3)"})]}),o.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-xs font-mono font-bold bg-warning/20 text-warning border border-warning/30",children:[p.length," loop ",p.length===1?"pattern":"patterns"," detected"]})]}),o.jsx("p",{className:"text-xs text-base-content/60 mb-4",children:"Identified consecutive identical tool invocations without intervening state changes. Hover or click on any invocation badge to inspect full arguments, duration, and diagnostics."}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:p.map(L=>o.jsxs("div",{className:"p-4 bg-base-300/70 rounded-xl border border-base-content/10 flex flex-col justify-between gap-3 shadow-xs hover:border-warning/40 transition-colors",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsxs("span",{className:"px-2.5 py-0.5 rounded-full text-xs font-mono font-bold bg-warning/20 text-warning border border-warning/30",children:[L.tool," × ",L.repeats," repeats"]}),o.jsxs("button",{type:"button",className:"text-xs font-mono text-primary hover:underline cursor-pointer inline-flex items-center gap-1 font-bold",onClick:()=>a?.(L.sessionId),title:"Jump to session in Tool Using & Timeline",children:[L.sessionId," →"]})]}),o.jsxs("div",{className:"font-mono text-xs text-base-content/80 mt-2 p-2 bg-base-200/80 rounded-lg border border-base-content/5 truncate",title:L.argsHint,children:[o.jsx("span",{className:"text-[10px] text-base-content/50 block mb-0.5 uppercase tracking-wider",children:"Argument signature"}),L.argsHint==="74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b"?"empty/unrecorded arguments":L.argsHint]}),o.jsxs("div",{className:"text-[11px] font-mono text-base-content/60 mt-2",children:["Step sequence: #",L.fromSeq," → #",L.toSeq]}),o.jsxs("div",{className:"mt-3 pt-2.5 border-t border-base-content/10",children:[o.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50 mb-1.5",children:"Repeated Invocations (hover/click for details):"}),o.jsx(SG,{calls:L.repeatedCalls,fromSeq:L.fromSeq,toSeq:L.toSeq,toolName:L.tool,sessionId:L.sessionId})]})]}),o.jsxs("div",{className:"flex justify-between items-center text-xs font-mono pt-2 border-t border-base-content/10 bg-base-200/40 -mx-4 -mb-4 p-3 rounded-b-xl",children:[o.jsx("span",{className:"text-base-content/60",children:"Estimated Wasted Tokens:"}),o.jsx("span",{className:"text-error font-bold text-sm",children:Be(L.wastedTokens)})]})]},`${L.tool}-${L.sessionId}-${L.fromSeq}`))})]})]})};function vG(e){const t=e.toLowerCase();return t.includes("read")||t.includes("view")||t.includes("cat")?"read":t.includes("write")||t.includes("edit")||t.includes("replace")||t.includes("patch")?"write":t.includes("bash")||t.includes("command")||t.includes("exec")||t.includes("terminal")?"bash":t.includes("grep")||t.includes("find")||t.includes("search")||t.includes("glob")?"search":t.includes("mcp")?"mcp":"other"}const Yw=({data:e,loading:t,error:n,sortBy:r="start",sortDir:a="desc",page:s=1,pageSize:i=20,onSortChange:l,onPageChange:u,onSelectSession:c})=>{const[d,p]=g.useState(""),[m,f]=g.useState("all");if(t)return o.jsxs("div",{className:"flex flex-col items-center justify-center p-20 gap-3",children:[o.jsx("div",{className:"w-9 h-9 rounded-full border-3 border-primary border-t-transparent animate-spin"}),o.jsx("span",{className:"text-xs font-mono text-base-content/60",children:"Loading session records..."})]});if(n)return o.jsxs("div",{className:"p-5 rounded-xl bg-error/10 border border-error/20 text-error flex items-center gap-3",children:[o.jsx("span",{className:"text-lg",children:"⚠️"}),o.jsxs("div",{children:[o.jsxs("h5",{className:"font-bold text-sm",children:["Failed to load sessions: ",n]}),o.jsx("p",{className:"text-xs opacity-80",children:"Please check your connection and try refreshing."})]})]});if(!e)return null;const{items:b,total:x}=e,E=Math.max(1,Math.ceil(x/i)),y=b.reduce((T,_)=>T+_.billedTokens,0),S=b.reduce((T,_)=>T+_.cacheReadTokens,0),v=b.filter(T=>T.state==="error").length,N=Math.max(1,...b.map(T=>T.billedTokens)),A=b.filter(T=>{if(m!=="all"&&T.state!==m)return!1;if(!d.trim())return!0;const _=d.toLowerCase();return T.id.toLowerCase().includes(_)||T.source.toLowerCase().includes(_)||T.model.toLowerCase().includes(_)||T.topTool.toLowerCase().includes(_)}),w=T=>r!==T?o.jsx("span",{className:"opacity-25 ml-1 text-[10px]",children:"↕"}):o.jsx("span",{className:"ml-1 text-primary font-bold",children:a==="asc"?"▲":"▼"});return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Total Sessions"}),o.jsx("span",{className:"text-primary",children:"📋"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-base-content",children:Wt(x)}),o.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Showing page ",s," of ",E]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Page Billed Tokens"}),o.jsx("span",{className:"text-primary",children:"⚡"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-primary",children:Be(y)}),o.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Across ",b.length," page sessions"]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Page Cache Read"}),o.jsx("span",{className:"text-cyan-400",children:"💾"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsx("div",{className:"text-xl font-bold font-mono text-cyan-400",children:Be(S)}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:"Reused context tokens"})]})]}),o.jsxs("div",{className:`rounded-xl p-4 border flex flex-col justify-between transition-all ${v>0?"bg-error/10 border-error/30 text-error":"bg-base-200 border-base-content/10"}`,children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Session Status"}),o.jsx("span",{children:v>0?"⚠️":"✓"})]}),o.jsxs("div",{className:"mt-2",children:[o.jsxs("div",{className:"text-xl font-bold font-mono",children:[b.length-v," OK · ",v," Error"]}),o.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:v===0?"100% successful on page":`${v} failed sessions`})]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 bg-base-200 p-3 rounded-xl border border-base-content/10",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[o.jsx("span",{className:"text-base-content/40 text-xs",children:"🔍"}),o.jsx("input",{type:"text",placeholder:"Filter sessions by ID, model, agent, or tool...",value:d,onChange:T=>p(T.target.value),className:"bg-base-300/60 text-xs font-mono px-3 py-1.5 rounded-lg border border-base-content/10 w-full focus:outline-hidden focus:border-primary placeholder:text-base-content/40"}),d&&o.jsx("button",{type:"button",onClick:()=>p(""),className:"text-xs text-base-content/50 hover:text-base-content cursor-pointer",children:"✕"})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-mono",children:[o.jsx("span",{className:"text-base-content/50 text-[11px] uppercase tracking-wider mr-1",children:"State:"}),["all","ok","error"].map(T=>o.jsx("button",{type:"button",onClick:()=>f(T),className:`px-2.5 py-1 rounded-md text-xs uppercase font-bold transition-colors cursor-pointer ${m===T?"bg-primary text-primary-content shadow-xs":"bg-base-300 text-base-content/70 hover:bg-base-300/80"}`,children:T},T))]})]}),o.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 overflow-hidden",children:o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"bg-base-300/80 text-base-content/70 border-b border-base-content/10 select-none",children:[o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Session ID"}),o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Agent"}),o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Model"}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors whitespace-nowrap",onClick:()=>l?.("start"),children:["Start Time ",w("start")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("duration"),children:["Duration ",w("duration")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("messages"),children:["Msgs ",w("messages")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("toolCalls"),children:["Tools ",w("toolCalls")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("billedTokens"),children:["Billed Tok ",w("billedTokens")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("cacheRead"),children:["Cache Read ",w("cacheRead")]}),o.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("freshInput"),children:["Fresh Input ",w("freshInput")]}),o.jsx("th",{className:"p-3 whitespace-nowrap",children:"Top Tool"}),o.jsx("th",{className:"p-3 text-center whitespace-nowrap",children:"State"})]})}),o.jsx("tbody",{children:A.length===0?o.jsx("tr",{children:o.jsx("td",{colSpan:12,className:"text-center py-12 text-base-content/50",children:"No sessions matching the current filter."})}):A.map(T=>{const _=vG(T.topTool),B=rs[_]??rs.other,k=Math.min(100,Math.round(T.billedTokens/N*100));return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-primary/10 cursor-pointer transition-colors group",onClick:()=>c?.(T.source,T.id),title:"Click to view execution timeline",children:[o.jsx("td",{className:"p-3 font-bold text-primary whitespace-nowrap",children:o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"font-mono text-xs",title:T.id,children:T.id.length>18?`${T.id.slice(0,16)}…`:T.id}),o.jsx("span",{className:"text-[10px] opacity-40 group-hover:opacity-100 transition-opacity",children:"↗"})]})}),o.jsx("td",{className:"p-3 whitespace-nowrap",children:o.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] bg-base-300 border border-base-content/10 font-mono text-base-content",children:[o.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center opacity-80",children:o.jsx(_r,{id:T.source})}),o.jsx("span",{children:T.source})]})}),o.jsx("td",{className:"p-3 text-base-content/80 whitespace-nowrap",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded bg-base-300/60 border border-base-content/5 text-[11px]",children:T.model})}),o.jsx("td",{className:"p-3 font-mono text-xs text-base-content/70 whitespace-nowrap",children:lG(T.start)}),o.jsx("td",{className:"p-3 text-right font-semibold tabular-nums whitespace-nowrap",children:Bw(T.durationMs/6e4)}),o.jsx("td",{className:"p-3 text-right tabular-nums text-base-content/80 whitespace-nowrap",children:Wt(T.messages)}),o.jsx("td",{className:"p-3 text-right tabular-nums text-base-content/80 whitespace-nowrap",children:Wt(T.toolCalls)}),o.jsx("td",{className:"p-3 text-right font-bold text-primary tabular-nums whitespace-nowrap",children:o.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[o.jsx("span",{children:Be(T.billedTokens)}),o.jsx("div",{className:"w-12 bg-base-300 h-1 rounded-full overflow-hidden",children:o.jsx("div",{className:"bg-primary h-full rounded-full",style:{width:`${k}%`}})})]})}),o.jsx("td",{className:"p-3 text-right text-cyan-400 font-bold tabular-nums whitespace-nowrap",children:Be(T.cacheReadTokens)}),o.jsx("td",{className:"p-3 text-right text-base-content/70 tabular-nums whitespace-nowrap",children:Be(T.freshInputTokens)}),o.jsx("td",{className:"p-3 whitespace-nowrap",children:o.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] border font-mono ${B}`,children:T.topTool})}),o.jsx("td",{className:"p-3 text-center whitespace-nowrap",children:o.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-mono font-bold border ${T.state==="error"?"bg-error/15 text-error border-error/30":T.state==="running"?"bg-cyan-500/15 text-cyan-400 border-cyan-500/30 animate-pulse":"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"}`,children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current"}),T.state]})})]},`${T.source}:::${T.id}`)})})]})})}),o.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-3 px-2 py-1 text-xs",children:[o.jsxs("span",{className:"text-base-content/70 font-mono text-[11px]",children:["Showing ",(s-1)*i+1,"–",Math.min(s*i,x)," of ",x," sessions"]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("button",{type:"button",className:"px-3 py-1.5 text-xs rounded-lg border border-base-content/20 hover:bg-base-content/10 font-medium disabled:opacity-40 disabled:hover:bg-transparent cursor-pointer transition-colors",disabled:s<=1,onClick:()=>u?.(s-1),children:"« Previous"}),o.jsxs("span",{className:"px-3 py-1.5 text-xs font-mono bg-base-300 rounded-lg border border-base-content/10 text-base-content font-bold",children:[s," / ",E]}),o.jsx("button",{type:"button",className:"px-3 py-1.5 text-xs rounded-lg border border-base-content/20 hover:bg-base-content/10 font-medium disabled:opacity-40 disabled:hover:bg-transparent cursor-pointer transition-colors",disabled:s>=E,onClick:()=>u?.(s+1),children:"Next »"})]})]})]})},Kw=({data:e,loading:t,error:n,onTriggerImport:r})=>{const[a,s]=g.useState(!1),[i,l]=g.useState(null),u=async()=>{s(!0),l("Running import & analytics rollup...");try{const f=await r?.("incremental");l(f?.message??"Import queued.")}catch(f){l(`Import failed: ${f instanceof Error?f.message:String(f)}`)}finally{s(!1)}};if(t)return o.jsx("div",{className:"flex items-center justify-center p-16",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin"})});if(n)return o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:o.jsxs("span",{children:["Failed to load sources registry: ",n]})});if(!e)return null;const{overview:c,agents:d,roots:p}=e,m=d[0]?.heatmapDays.length;return o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col md:flex-row justify-between items-start md:items-center gap-4",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xl",children:"🗄️"}),o.jsx("h3",{className:"font-bold text-base",children:"Transcripts Corpus & Ingestion Registry"})]}),o.jsxs("div",{className:"flex flex-wrap gap-4 text-xs font-mono text-base-content/70 mt-1",children:[o.jsxs("span",{children:["Files: ",o.jsx("strong",{className:"text-base-content",children:Wt(c.totalFiles)})]}),o.jsxs("span",{children:["Corpus Size:"," ",o.jsxs("strong",{className:"text-base-content",children:[(c.corpusSizeBytes/(1024*1024)).toFixed(1)," MB"]})]}),o.jsxs("span",{children:["Total Sessions:"," ",o.jsx("strong",{className:"text-base-content",children:Wt(c.totalSessions)})]}),o.jsxs("span",{children:["Coverage:"," ",o.jsxs("strong",{className:"text-base-content",children:[c.dateCoverage.from?.slice(0,10)??"N/A"," →"," ",c.dateCoverage.to?.slice(0,10)??"N/A"]})]}),o.jsxs("span",{children:["Last Import:"," ",o.jsx("strong",{className:"text-base-content",children:c.lastImportedAt?new Date(c.lastImportedAt).toLocaleString():"never imported"})]})]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[o.jsx("button",{type:"button",className:"px-4 py-2 rounded-lg bg-primary text-primary-content font-medium text-xs hover:bg-primary/90 transition-colors disabled:opacity-50",disabled:a,onClick:u,children:a?"Importing...":"🔄 Import & Analyze"}),i&&o.jsx("span",{className:"text-[11px] font-mono text-info","aria-live":"polite",children:i})]})]}),o.jsxs("div",{children:[o.jsxs("h4",{className:"font-bold text-sm mb-3",children:["Agent Activity (",m??"—","-Day Daily Heatmaps)"]}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:d.map(f=>o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 hover:border-base-content/30 transition-all p-4 flex flex-col justify-between gap-3",children:[o.jsxs("div",{className:"flex justify-between items-start",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("button",{type:"button",className:"w-7 h-7 rounded-lg flex items-center justify-center text-white shadow-xs focus:outline-2 focus:outline-offset-2 focus:outline-primary",style:{background:f.color},"aria-label":`${f.name} source metrics`,"aria-describedby":`source-tooltip-${f.id}`,children:o.jsx(_r,{id:f.id})}),o.jsxs("div",{id:`source-tooltip-${f.id}`,role:"tooltip",className:"pointer-events-none absolute z-20 left-0 top-9 w-64 rounded-lg border border-base-content/15 bg-base-100 p-3 text-[11px] font-mono shadow-xl opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:[o.jsxs("div",{className:"mb-2 font-bold text-sm",children:[f.name," Summary"]}),o.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1",children:[o.jsx("span",{className:"text-base-content/60",children:"Imported Files"}),o.jsx("strong",{className:"text-right",children:Wt(f.filesCount)}),o.jsx("span",{className:"text-base-content/60",children:"Sessions"}),o.jsx("strong",{className:"text-right",children:Wt(f.sessionCount)}),o.jsx("span",{className:"text-base-content/60",children:"Total Tokens"}),o.jsx("strong",{className:"text-right",children:Be(f.totalTokens)}),o.jsx("span",{className:"text-base-content/60",children:"Cache Saved"}),o.jsx("strong",{className:"text-right",children:Be(f.cacheSavedTokens)}),o.jsx("span",{className:"text-base-content/60",children:"Tool Calls"}),o.jsx("strong",{className:"text-right",children:Wt(f.toolCalls)}),o.jsx("span",{className:"text-base-content/60",children:"Date Range"}),o.jsxs("strong",{className:"text-right",children:[f.firstDate?.slice(0,10)??"N/A"," →"," ",f.lastDate?.slice(0,10)??"N/A"]})]})]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"font-bold text-sm",children:f.name}),o.jsx("div",{className:"text-[10px] font-mono text-base-content/60",children:f.importPath})]})]}),o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-mono font-bold bg-base-300 border border-base-content/10 text-base-content",children:[Be(f.totalTokens)," tok"]})]}),o.jsxs("div",{className:"bg-base-300/60 p-2 rounded-lg border border-base-content/5",children:[o.jsxs("div",{className:"text-[10px] font-mono text-base-content/50 mb-1 flex justify-between",children:[o.jsxs("span",{children:[m??"—"," days ago"]}),o.jsx("span",{children:"Today"})]}),o.jsx(pG,{days:f.heatmapDays,color:f.color,maxDailyTokens:f.maxDailyTokens})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-2 border-t border-base-content/10 font-mono text-[11px]",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Sessions"}),o.jsx("span",{className:"font-semibold",children:Wt(f.sessionCount)})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Tool Calls"}),o.jsx("span",{className:"font-semibold",children:Wt(f.toolCalls)})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Cache Saved"}),o.jsx("span",{className:"font-semibold text-emerald-400",children:Be(f.cacheSavedTokens)})]})]})]},f.id))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Source Directories & Import Roots"}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Agent"}),o.jsx("th",{className:"py-1.5",children:"Filesystem Path"}),o.jsx("th",{className:"py-1.5",children:"Match Pattern"}),o.jsx("th",{className:"py-1.5 text-right",children:"Files Count"}),o.jsx("th",{className:"py-1.5 text-center",children:"Status"})]})}),o.jsx("tbody",{children:p.map(f=>o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[o.jsx("td",{className:"py-1.5 font-bold",children:f.agentName}),o.jsx("td",{className:"py-1.5 text-base-content/80",children:f.path}),o.jsx("td",{className:"py-1.5 text-base-content/60",children:f.matchPattern}),o.jsx("td",{className:"py-1.5 text-right font-semibold",children:Wt(f.fileCount)}),o.jsx("td",{className:"py-1.5 text-center",children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-400 uppercase font-bold",children:f.status})})]},f.agentId))})]})})]})]})},wG=["auto","1m","3m","5m","10m","30m","1h","4h","1d"],da=["#3987e5","#199e70","#d95926","#9085e9","#c98500","#ec4899","#8b5cf6","#06b6d4","#f59e0b","#10b981"],NG=(e,t)=>t===void 0||t===0?null:(e-t)/Math.abs(t)*100,Hd=g.memo(({current:e,previous:t,invert:n=!1})=>{const r=NG(e,t);if(r===null)return o.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});const a=r>=0,s=n?!a:a;return o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold font-mono ${s?"bg-emerald-500/15 text-emerald-400":"bg-error/15 text-error"}`,children:[a?"↑ +":"↓ ",Math.abs(r).toFixed(1),"% vs previous period"]})}),zo=g.memo(({label:e,value:t,sub:n,trend:r,trendColor:a,current:s,previous:i,invert:l,badge:u})=>o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-4",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:e}),u]}),o.jsxs("div",{className:"flex items-end justify-between gap-2 mt-1",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-2xl font-bold font-mono text-primary",children:t}),o.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[o.jsx(Hd,{current:s,previous:i,invert:l}),o.jsx("span",{className:"text-xs text-base-content/60",children:n})]})]}),r.length>1&&o.jsx(zw,{values:r,color:a,width:100,height:34})]})]})),Ho=g.memo(({title:e,description:t,series:n,buckets:r,chartMode:a,onToggleChartMode:s,testId:i})=>{const l=r.length>0&&n.length>0&&r.some(u=>Object.values(u.v).some(c=>c>0));return o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col gap-3 w-full","data-testid":i,children:[o.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-2 pb-2 border-b border-base-content/10",children:[o.jsxs("div",{children:[o.jsxs("h4",{className:"font-bold text-sm text-base-content flex items-center gap-2",children:[e,o.jsxs("span",{className:"text-[11px] font-normal text-base-content/60 font-mono",children:["(",n.length," ",(n.length===1,"tracked"),")"]})]}),o.jsx("p",{className:"text-[11px] text-base-content/60",children:t})]}),o.jsxs("div",{className:"flex items-center gap-1 bg-base-300 p-0.5 rounded-lg text-xs",children:[o.jsx("button",{type:"button","aria-pressed":a==="chart",className:`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${a==="chart"?"bg-base-100 text-base-content font-bold shadow-xs":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>a!=="chart"&&s(),children:"Chart"}),o.jsx("button",{type:"button","aria-pressed":a==="table",className:`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${a==="table"?"bg-base-100 text-base-content font-bold shadow-xs":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>a!=="table"&&s(),children:"Table"})]})]}),o.jsx("div",{className:"min-h-[220px]",children:a==="table"&&r.length>0&&n.length>0?o.jsx("div",{className:"overflow-x-auto max-h-72 overflow-y-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono","data-testid":"summary-bucket-table",children:[o.jsx("thead",{className:"sticky top-0 bg-base-200",children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5 pr-2",children:"Bucket"}),n.map(u=>o.jsx("th",{className:"py-1.5 pr-2 text-right",children:o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx("span",{className:"w-2 h-2 rounded-full inline-block shrink-0",style:{background:u.color}}),u.label]})},u.id)),o.jsx("th",{className:"py-1.5 pr-2 text-right",children:"Total"}),o.jsx("th",{className:"py-1.5 pr-2 text-right",children:"Cache Hit %"}),o.jsx("th",{className:"py-1.5 text-right",children:"Gain Ratio %"})]})}),o.jsx("tbody",{children:r.map(u=>{const c=Object.values(u.v).reduce((d,p)=>d+p,0);return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[o.jsx("td",{className:"py-1.5 pr-2 font-bold",children:Uw(u.id??u.label)}),n.map(d=>o.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums",children:u.v[d.id]!==void 0?Be(u.v[d.id]??0):"—"},d.id)),o.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums font-bold",children:Be(c)}),o.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums text-cyan-400",children:u.lineValue!==void 0?`${u.lineValue.toFixed(1)}%`:"—"}),o.jsx("td",{className:"py-1.5 text-right tabular-nums text-amber-400",children:u.secondLineValue!==void 0?`${u.secondLineValue.toFixed(1)}%`:"—"})]},u.id??u.label)})})]})}):l?o.jsx($w,{buckets:r,series:n,height:220}):r.length>0&&n.length>0?o.jsxs("div",{className:"flex flex-col items-center justify-center h-[220px] text-base-content/50 text-xs font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30 text-center px-4 gap-1",children:[o.jsxs("span",{className:"font-semibold text-base-content/70",children:["No token or call activity recorded for ",e.toLowerCase()," in this time range."]}),o.jsx("span",{className:"text-[11px] text-base-content/40",children:"Activity is unmeasured or zero in this window. Adjust the time range filter or switch to Table view."})]}):o.jsx("div",{className:"flex flex-col items-center justify-center h-[220px] text-base-content/40 text-xs font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30",children:o.jsxs("span",{children:["No ",e.toLowerCase()," activity recorded for this time range."]})})}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1.5 border-t border-base-content/5",children:[n.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(u=>o.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-md bg-base-300/80 border border-base-content/5 gap-1.5 font-mono text-[10px] text-base-content/80",children:[o.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:u.color}}),o.jsx("span",{className:"truncate max-w-[150px]",children:u.label})]},u.id))}),o.jsxs("div",{className:"flex items-center gap-3 text-[10px] font-mono text-base-content/70 ml-auto",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx("span",{className:"w-3 h-0.5 bg-cyan-400 rounded-full inline-block"}),o.jsx("span",{className:"text-cyan-400",children:"Cache Hit %"})]}),o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx("span",{className:"w-3 h-0.5 bg-amber-400 rounded-full inline-block"}),o.jsx("span",{className:"text-amber-400",children:"Gain Ratio %"})]})]})]})]})}),Go=(e,t,n)=>{const r=new Map;e.forEach((s,i)=>{r.set(s.id,{id:s.id,label:s.label||s.id,color:s.color||n[i%n.length]||"#3987e5"})});let a=r.size;for(const s of t)for(const i of Object.keys(s.series))i&&!r.has(i)&&(r.set(i,{id:i,label:i,color:n[a%n.length]||"#3987e5"}),a++);return Array.from(r.values())},Wo=e=>e.map(t=>({id:t.bucketStart,label:Ol(t.bucketStart),v:t.series,lineValue:t.cacheHitRatio,secondLineValue:t.gainRatio})),zc=["#199e70","#3987e5","#d95926","#9085e9","#c98500","#ec4899","#8b5cf6","#06b6d4","#f59e0b","#10b981"],Zw=g.memo(({data:e,loading:t,error:n,dimension:r="model",onDimensionChange:a,bucket:s="auto",onBucketChange:i,loopSummary:l})=>{const[u,c]=g.useState("chart"),[d,p]=g.useState({model:"chart",source:"chart",tool:"chart",skill:"chart"}),m=g.useCallback(()=>p(G=>({...G,model:G.model==="chart"?"table":"chart"})),[]),f=g.useCallback(()=>p(G=>({...G,source:G.source==="chart"?"table":"chart"})),[]),b=g.useCallback(()=>p(G=>({...G,tool:G.tool==="chart"?"table":"chart"})),[]),x=g.useCallback(()=>p(G=>({...G,skill:G.skill==="chart"?"table":"chart"})),[]),E=e?.kpis,y=e?.previousKpis,S=e?.kpiTrend??[],v=e?.timeSeries??[],N=e?.topModels??[],A=e?.topSources??[],w=e?.topTools??[],T=g.useMemo(()=>Math.max(0,...N.map(G=>G.tokens),...A.map(G=>G.tokens)),[N,A]),_=e?.skillsUsed??[],B=e?.skillTimeSeries??[],k=e?.skillBreakdown??{bySkill:[],bySource:[],byInvocationKind:[],trend:[],fresh:!0},$=e?.modelTimeSeries??[],V=e?.sourceTimeSeries??[],P=e?.toolTimeSeries??[],H=e?.cacheEfficiency??{savedTokens:0,hitRatio:0,totalRead:0,bySource:[],byModel:[],byAgentModel:[]},W=y??void 0,L=H.byAgentModel??[],te=g.useMemo(()=>Array.from(new Set(L.map(G=>G.model))),[L]),ie=g.useMemo(()=>Array.from(new Set(L.map(G=>G.source))),[L]),be=g.useMemo(()=>new Map(L.map(G=>[`${G.source}\0${G.model}`,G])),[L]),I=g.useMemo(()=>new Map(A.map(G=>[G.id,G.label])),[A]),ne=g.useMemo(()=>({billed:S.map(G=>G.totalBilledTokens),cacheSaved:S.map(G=>G.cacheSavedTokens),sessions:S.map(G=>G.sessionsCount),toolCalls:S.map(G=>G.toolCallsCount)}),[S]),ue=g.useMemo(()=>w.map(G=>({...G,id:G.id&&G.id.trim()!==""?G.id.trim():"unknown"})),[w]),O=g.useMemo(()=>_.filter(G=>G.id&&G.id.trim()!==""&&G.id!=="unknown"),[_]),Ne=g.useMemo(()=>$&&$.length>0?$:r==="model"?v:[],[$,r,v]),de=g.useMemo(()=>V&&V.length>0?V:r==="source"?v:[],[V,r,v]),K=g.useMemo(()=>P&&P.length>0?P:r==="tool"?v:[],[P,r,v]),Ee=g.useMemo(()=>B&&B.length>0?B:r==="skill"?v:[],[B,r,v]),re=g.useMemo(()=>Go(N,Ne,da),[N,Ne]),D=g.useMemo(()=>Go(A,de,da),[A,de]),ye=g.useMemo(()=>Go(ue.map((G,Fe)=>({id:G.id,label:G.id,color:zc[Fe%zc.length]})),K,zc),[ue,K]),Se=g.useMemo(()=>Go(O,Ee,da),[O,Ee]),pe=g.useMemo(()=>Wo(Ne),[Ne]),Ae=g.useMemo(()=>Wo(de),[de]),He=g.useMemo(()=>Wo(K),[K]),fe=g.useMemo(()=>Wo(Ee),[Ee]),Je=g.useMemo(()=>B.map(G=>({id:G.bucketStart,label:Ol(G.bucketStart),v:G.series})),[B]),bt=g.useMemo(()=>k.trend.map(G=>({id:G.bucketStart,label:Ol(G.bucketStart),v:G.series})),[k.trend]),it=g.useMemo(()=>k.bySkill.map((G,Fe)=>({id:G.skillName,label:G.skillName,color:da[Fe%da.length]||"#3987e5"})),[k.bySkill]),{toolCallTotal:Ft,toolTimeTotal:Nt,toolTokenTotal:Tt,avgBilledPerSession:$t,avgBilledPerCall:rt,prevAvgPerSession:Me,prevAvgPerCall:et,freshInputTokens:Q,outputTokens:ce,skillTokenTotals:Re}=g.useMemo(()=>{const G=ue.reduce((De,tt)=>De+tt.count,0),Fe=ue.reduce((De,tt)=>De+(tt.durationMs??0),0),Ve=ue.reduce((De,tt)=>De+(tt.tokens??0),0),pt=E?.totalBilledTokens??0,At=E?.sessionsCount??0,St=E?.toolCallsCount??0,Rt=At>0?pt/At:0,le=St>0?pt/St:0,Ce=W&&W.sessionsCount>0?W.totalBilledTokens/W.sessionsCount:void 0,Ue=W&&W.toolCallsCount>0?W.totalBilledTokens/W.toolCallsCount:void 0,je=Math.max(0,H.totalRead-H.savedTokens),Et=Math.max(0,pt-je),zt=B.reduce((De,tt)=>{for(const[Xe,kt]of Object.entries(tt.series))De[Xe]=(De[Xe]??0)+kt;return De},{});return{toolCallTotal:G,toolTimeTotal:Fe,toolTokenTotal:Ve,avgBilledPerSession:Rt,avgBilledPerCall:le,prevAvgPerSession:Ce,prevAvgPerCall:Ue,freshInputTokens:je,outputTokens:Et,skillTokenTotals:zt}},[ue,E,W,H,B]);return t?o.jsx("div",{className:"flex items-center justify-center p-16",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin"})}):n?o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:o.jsxs("span",{children:["Failed to load history summary: ",n]})}):!e||!E?null:o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[o.jsx(zo,{label:"Total Billed Tokens",value:Be(E.totalBilledTokens),sub:`Fresh ${Be(Q)} · Output ${Be(ce)}`,trend:ne.billed,trendColor:"#3987e5",current:E.totalBilledTokens,previous:W?.totalBilledTokens}),o.jsx(zo,{label:"Cache-Saved Tokens",value:Be(E.cacheSavedTokens),sub:`Share ${ur(E.cacheSavedPercent)} · Hit ${ur(H.hitRatio)}`,trend:ne.cacheSaved,trendColor:"#22d3ee",current:E.cacheSavedTokens,previous:W?.cacheSavedTokens,badge:o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",children:[E.cacheSavedPercent,"% saved"]})}),o.jsx(zo,{label:"Sessions",value:Wt(E.sessionsCount),sub:`${Wt(E.sessionsCount>0?E.toolCallsCount/E.sessionsCount:0)} calls / session`,trend:ne.sessions,trendColor:"#9085e9",current:E.sessionsCount,previous:W?.sessionsCount}),o.jsx(zo,{label:"Tool Calls",value:Wt(E.toolCallsCount),sub:`${Be(rt)} billed / step`,trend:ne.toolCalls,trendColor:"#c98500",current:E.toolCallsCount,previous:W?.toolCallsCount,badge:o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-mono bg-amber-500/20 text-amber-400 border border-amber-500/30",children:[ur(E.errorRate)," err"]})})]}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-3",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"font-bold text-base text-base-content",children:"Token Activity & Cache Hit Ratio & Gain Ratio"}),o.jsx("p",{className:"text-xs text-base-content/60",children:"4-block breakdown across Model, Source, Tool, and Skill (Stacked token bars with Cache Hit % and Gain Ratio % line overlays)"})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("fieldset",{className:"flex items-center bg-base-300 p-0.5 rounded-lg text-xs border-0",children:[o.jsx("legend",{className:"sr-only",children:"Bucket interval"}),wG.map(G=>o.jsx("button",{type:"button","aria-pressed":s===G,className:`px-2 py-1 rounded font-medium transition-colors ${s===G?"bg-base-100 text-base-content font-bold shadow-sm":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>i?.(G),children:G},G))]}),o.jsx("div",{className:"flex items-center bg-base-300 p-0.5 rounded-lg text-xs",children:["chart","table"].map(G=>o.jsx("button",{type:"button","aria-pressed":u===G,className:`px-2.5 py-1 rounded font-medium transition-colors ${u===G?"bg-base-100 text-base-content font-bold shadow-sm":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>{c(G),p({model:G,source:G,tool:G,skill:G})},children:G==="chart"?"All Charts":"All Tables"},G))})]})]}),o.jsxs("div",{className:"flex flex-col gap-6 w-full",children:[o.jsx(Ho,{title:"By Model",description:"Token load by LLM model with cache hit ratio and gain ratio overlays",series:re,buckets:pe,chartMode:d.model,onToggleChartMode:m,testId:"summary-block-model"}),o.jsx(Ho,{title:"By Source",description:"Token load by agent platform with cache hit ratio and gain ratio overlays",series:D,buckets:Ae,chartMode:d.source,onToggleChartMode:f,testId:"summary-block-source"}),o.jsx(Ho,{title:"By Tool",description:"Token load (or call volume when unmeasured) by tool execution with cache hit ratio and gain ratio overlays",series:ye,buckets:He,chartMode:d.tool,onToggleChartMode:b,testId:"summary-block-tool"}),o.jsx(Ho,{title:"By Skill",description:"Token load by specialized skill with cache hit ratio and gain ratio overlays",series:Se,buckets:fe,chartMode:d.skill,onToggleChartMode:x,testId:"summary-block-skill"})]})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Token by Model"}),o.jsx("div",{className:"flex flex-col gap-3",children:N.map(G=>o.jsx(Ay,{item:G,maxTotal:T},G.id))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Token by Agent Source"}),o.jsx("div",{className:"flex flex-col gap-3",children:A.map(G=>o.jsx(Ay,{item:G,maxTotal:T},G.id))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Cache Efficiency By Agent"}),(H.bySource&&H.bySource.length>0||A.length>0)&&o.jsx(_y,{items:(H.bySource&&H.bySource.length>0?H.bySource:A.map(G=>({source:G.id,sourceName:G.label,color:G.color,hitRatio:H.hitRatio,savedTokens:Math.round(H.savedTokens*(G.share/100)),totalRead:Math.round(H.totalRead*(G.share/100)),billedTokens:G.tokens}))).map(G=>({id:G.source,label:G.sourceName,color:G.color,hitRatio:G.hitRatio,savedTokens:G.savedTokens,totalRead:G.totalRead,billedTokens:G.billedTokens}))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Cache Efficiency By Model"}),H.byModel&&H.byModel.length>0&&o.jsx(_y,{items:H.byModel.map(G=>({id:G.model,label:G.modelName,color:G.color,hitRatio:G.hitRatio,savedTokens:G.savedTokens,totalRead:G.totalRead,billedTokens:G.billedTokens}))})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Agent × Model Correlation Matrix"}),te.length>0&&ie.length>0&&o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{className:"text-left pr-2 py-1 text-base-content/60 sticky left-0 bg-base-200 z-10",children:"Model \\ Agent"}),ie.map(G=>o.jsx("th",{className:"px-1 py-1 text-base-content/60 whitespace-nowrap",title:I.get(G)??G,children:I.get(G)??G},G))]})}),o.jsx("tbody",{children:te.map(G=>o.jsxs("tr",{children:[o.jsx("td",{className:"pr-2 py-1 font-bold text-base-content/80 whitespace-nowrap sticky left-0 bg-base-200",children:G}),ie.map(Fe=>{const Ve=be.get(`${Fe}\0${G}`);return o.jsx("td",{className:"p-0.5",children:Ve?o.jsxs("div",{className:"h-8 min-w-[3rem] rounded-md flex items-center justify-center text-[10px] font-bold border border-base-content/10 cursor-default",style:{background:`rgba(6, 182, 212, ${.08+.5*(Ve.hitRatio/100)})`},title:`${Ve.sourceName} × ${Ve.modelName}: ${Ve.hitRatio}% hit · saved ${Be(Ve.savedTokens)} / read ${Be(Ve.totalRead)} / billed ${Be(Ve.billedTokens)}`,children:[Ve.hitRatio,"%"]}):o.jsx("div",{className:"h-8 min-w-[3rem] rounded-md flex items-center justify-center text-[10px] text-base-content/25 bg-base-300/40",children:"—"})},Fe)})]},G))})]})}),o.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono text-base-content/60",children:[o.jsx("span",{children:"0%"}),o.jsx("div",{className:"h-1.5 w-32 rounded-full bg-gradient-to-r from-base-300 to-cyan-400"}),o.jsx("span",{children:"100% cache hit ratio"})]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[o.jsx("h4",{className:"font-bold text-sm mb-2",children:"Top Tools & Error Rates"}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{className:"py-1.5",children:"Tool"}),o.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Usage Share"}),o.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Time Share"}),o.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Token Share"}),o.jsx("th",{className:"py-1.5 text-right",children:"Calls"}),o.jsx("th",{className:"py-1.5 text-right",children:"Errors"}),o.jsx("th",{className:"py-1.5 text-right",children:"Error Rate"})]})}),o.jsx("tbody",{children:ue.map(G=>{const Fe=G.usageShare??(Ft>0?Math.round(G.count/Ft*1e3)/10:0),Ve=G.timeShare??(Nt>0?Math.round((G.durationMs??0)/Nt*1e3)/10:0),pt=G.tokenShare??(Tt>0?Math.round((G.tokens??0)/Tt*1e3)/10:0);return o.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[o.jsx("td",{className:"py-1.5 font-bold",children:G.id}),o.jsx("td",{className:"py-1.5",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-16",children:o.jsx(yi,{value:Fe,max:100,color:"#3987e5"})}),o.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:ur(Fe)})]})}),o.jsx("td",{className:"py-1.5",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-16",children:o.jsx(yi,{value:Ve,max:100,color:"#10b981"})}),o.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:Ve>0?ur(Ve):"—"})]})}),o.jsx("td",{className:"py-1.5",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-16",children:o.jsx(yi,{value:pt,max:100,color:"#f59e0b"})}),o.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:pt>0?ur(pt):"—"})]})}),o.jsx("td",{className:"py-1.5 text-right tabular-nums",children:Wt(G.count)}),o.jsx("td",{className:"py-1.5 text-right tabular-nums",children:G.errors>0?Wt(G.errors):"0"}),o.jsx("td",{className:"py-1.5 text-right",children:o.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${G.errorRate>1?"bg-error/20 text-error font-bold":"bg-base-300 text-base-content/70"}`,children:ur(G.errorRate)})})]},G.id)})})]})})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col gap-4",children:[o.jsx("h4",{className:"font-bold text-sm mb-3",children:"Efficiency Stats & Skills"}),o.jsx("div",{children:o.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs font-mono",children:[o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Avg Billed / Session"}),o.jsx("span",{className:"font-bold",children:Be($t)}),o.jsx(Hd,{current:$t,previous:Me,invert:!0})]}),o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Avg Billed / Step"}),o.jsx("span",{className:"font-bold",children:Be(rt)}),o.jsx(Hd,{current:rt,previous:et,invert:!0})]}),o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Loop Detection Findings"}),o.jsxs("span",{className:"font-bold",children:[Wt(l?.redundantCalls??0)," redundant"]}),o.jsxs("span",{className:"text-[10px] text-base-content/60",children:[Be(l?.wastedTokens??0)," wasted"]})]})]})}),_.length>0&&o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2",children:"Skills Invocation Mix"}),o.jsx(Ty,{buckets:Je,series:AG(_),height:150}),o.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:_.map(G=>o.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full bg-base-300 border border-base-content/10 gap-1.5 font-mono text-[11px]",children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:G.color}}),o.jsxs("span",{children:[G.label,":"]}),o.jsxs("span",{className:"font-bold",children:[Be(Re[G.id]??0)," tokens"]})]},G.id))})]})]})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col gap-4","data-testid":"summary-skill-breakdown",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-bold text-sm mb-1",children:"Skill Load Breakdown"}),o.jsx("p",{className:"text-[11px] text-base-content/60",children:"Skill invocations by name, agent, and invocation kind over the selected window."})]}),k.fresh===!1?o.jsx("div",{className:"flex flex-col items-center justify-center text-[11px] text-base-content/40 font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30 py-6",children:o.jsx("span",{children:"Skill rollup not yet built — run history analyze to populate this section."})}):k.bySkill.length>0?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-xs font-mono",children:[o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"Top Skills"}),o.jsx("div",{className:"flex flex-col gap-1.5",children:k.bySkill.map((G,Fe)=>o.jsxs("div",{className:"flex justify-between items-center gap-2",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:da[Fe%da.length]??"#3987e5"}}),G.skillName]}),o.jsx("span",{className:"font-bold tabular-nums",children:Wt(G.calls)})]},G.skillName))})]}),o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"By Agent"}),o.jsx("div",{className:"flex flex-col gap-1.5",children:k.bySource.map(G=>o.jsxs("div",{className:"flex justify-between items-center gap-2",children:[o.jsx("span",{children:G.source}),o.jsx("span",{className:"font-bold tabular-nums",children:Wt(G.calls)})]},G.source))})]}),o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"By Invocation Kind"}),o.jsx("div",{className:"flex flex-col gap-1.5",children:k.byInvocationKind.map(G=>o.jsxs("div",{className:"flex justify-between items-center gap-2",children:[o.jsx("span",{className:"capitalize",children:G.invocationKind}),o.jsx("span",{className:"font-bold tabular-nums",children:Wt(G.calls)})]},G.invocationKind))})]})]}),bt.length>0&&o.jsxs("div",{children:[o.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"Skill Call Trend"}),o.jsx(Ty,{buckets:bt,series:it,height:150})]})]}):o.jsx("div",{className:"flex flex-col items-center justify-center text-[11px] text-base-content/40 font-mono border border-dashed border-base-content/10 rounded-xl bg-base-100/30 py-6",children:o.jsx("span",{children:"No skill activity recorded for this window."})})]})]})}),AG=e=>e.map(t=>({id:t.id,label:t.label,color:t.color})),Ay=g.memo(({item:e,maxTotal:t})=>{const n=e.freshInputTokens??(e.outputTokens?e.tokens-e.outputTokens:e.tokens),r=e.cacheReadTokens??0,a=e.outputTokens??0,s=t>0?t:1,i=l=>`${Math.round(l/s*1e3)/10}%`;return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("div",{className:"flex justify-between text-xs font-mono",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:e.color}}),e.label]}),o.jsx("span",{children:Be(e.tokens)})]}),o.jsxs("div",{className:"w-full bg-base-300 h-3 rounded-full overflow-hidden flex",children:[n>0&&o.jsx("div",{className:"h-full",style:{width:i(n),background:"#3987e5"}}),a>0&&o.jsx("div",{className:"h-full",style:{width:i(a),background:"#f59e0b"}})]}),o.jsxs("div",{className:"flex justify-between text-[10px] text-base-content/60 font-mono",children:[o.jsxs("span",{children:["Fresh ",Be(n)," · Cached ",Be(r)," · Output ",Be(a)]}),o.jsxs("span",{children:["Total ",Be(n+r+a)]})]})]})}),_y=g.memo(({items:e})=>o.jsx("div",{className:"flex flex-col gap-2",children:e.map(t=>o.jsxs("div",{className:"flex flex-col gap-1 bg-base-300/40 p-2.5 rounded-lg border border-base-content/5",children:[o.jsxs("div",{className:"flex justify-between items-center text-xs",children:[o.jsxs("span",{className:"flex items-center gap-1.5 font-medium",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:t.color}}),t.label]}),o.jsxs("span",{className:"font-mono font-bold text-cyan-400",children:[t.hitRatio,"%"]})]}),o.jsx("div",{className:"w-full bg-base-100 h-1.5 rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full rounded-full",style:{width:`${t.hitRatio}%`,background:t.color}})}),o.jsxs("div",{className:"flex justify-between text-[10px] text-base-content/60 font-mono",children:[o.jsxs("span",{children:["Saved: ",Be(t.savedTokens)]}),o.jsxs("span",{children:["Total Read: ",Be(t.totalRead)," · Billed: ",Be(t.billedTokens)]})]})]},t.id))})),_G=({blocks:e,start:t,end:n,onJumpToTime:r})=>{const a=g.useId(),{bins:s,maxBinTokens:i,maxBinOperations:l,startMs:u,endMs:c,hasValidRange:d}=g.useMemo(()=>{if(!t||!n||e.length===0)return{bins:[],maxBinTokens:0,maxBinOperations:0,startMs:0,endMs:0,hasValidRange:!1};const p=Date.parse(t),m=Date.parse(n);if(Number.isNaN(p)||Number.isNaN(m)||m<p)return{bins:[],maxBinTokens:0,maxBinOperations:0,startMs:0,endMs:0,hasValidRange:!1};const f=96,x=Math.max(1,m-p)/f,E=Array.from({length:f},(v,N)=>({index:N,timeMs:p+N*x,tokens:0,operations:0}));for(const v of e){if(!v.timestamp)continue;const N=Date.parse(v.timestamp);if(Number.isNaN(N)||N<p||N>m)continue;const A=Math.min(f-1,Math.max(0,Math.floor((N-p)/x))),w=E[A];w&&(w.tokens+=v.totalTokens,w.operations+=v.operationCount)}const y=Math.max(1,...E.map(v=>v.tokens)),S=Math.max(1,...E.map(v=>v.operations));return{bins:E,maxBinTokens:y,maxBinOperations:S,startMs:p,endMs:m,hasValidRange:!0}},[e,t,n]);return!d||s.length===0?null:o.jsxs("div",{"data-testid":"timeline-scrubber",className:"flex flex-col gap-1.5 p-3 bg-base-200/80 rounded-xl border border-base-content/10 font-mono text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-base-content/60 px-1",children:[o.jsxs("span",{children:["Timeline Activity (",s.length," bins)"]}),o.jsxs("span",{children:["Peak: ",Be(i)]})]}),o.jsx("div",{className:"relative h-10 w-full bg-base-300/60 rounded-lg overflow-hidden flex items-end p-1",children:o.jsx("svg",{viewBox:"0 0 96 32",preserveAspectRatio:"none",className:"w-full h-full text-primary/70","aria-hidden":"true",children:s.map(p=>{const m=p.operations>0?Math.max(2,Math.round(p.operations/l*30)):0,f=p.tokens>0?.35+p.tokens/i*.65:.25,b=32-m;return o.jsx("rect",{x:p.index,y:b,width:"0.85",height:m,fill:"currentColor",fillOpacity:f,"data-operations":p.operations,"data-tokens":p.tokens,className:"hover:text-cyan-400 transition-colors",children:o.jsx("title",{children:`${new Date(p.timeMs).toISOString()} · ${Be(p.tokens)} · ${p.operations} ops`})},p.index)})})}),o.jsx("label",{htmlFor:a,className:"sr-only",children:"Timeline scrub slider"}),o.jsx("input",{id:a,type:"range",min:u,max:c,defaultValue:u,"aria-label":"Timeline navigation scrubber","data-testid":"timeline-scrubber-range",className:"w-full range range-xs range-primary cursor-pointer accent-primary",onInput:p=>{const m=Number(p.currentTarget.value);Number.isFinite(m)&&r?.(new Date(m).toISOString())}})]})},za=(e,t)=>`${e}:${t}`,Ha=(e,t)=>JSON.stringify([e,t]),pa=e=>e.replace(/[^a-zA-Z0-9_-]/g,"-"),Fl=(e,t,n)=>e+t+n,kG=(e,t)=>{const n=e+t;return n>0?t/n*100:0},Gd=e=>e.length<=12?e:`${e.slice(0,8)}…${e.slice(-4)}`,CG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Xw=e=>{if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=CG[t.getUTCMonth()],r=t.getUTCDate(),a=String(t.getUTCHours()).padStart(2,"0"),s=String(t.getUTCMinutes()).padStart(2,"0");return`${n} ${r} ${a}:${s}`},Wd=e=>{if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return e.slice(11,19)||e;const n=String(t.getUTCHours()).padStart(2,"0"),r=String(t.getUTCMinutes()).padStart(2,"0"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}:${r}:${a}`},ky=e=>`${Gd(e.id)} · ${e.source} · ${Xw(e.start)} · ${Be(e.tokenLoad)}`,IG=e=>{const t=e.payload?.trim();return t&&t.length>0?t:e.title},Cy=e=>e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)??e,Iy=e=>e.kind==="assistant"||e.eventType==="message"&&e.kind!=="user",RG=e=>{const t=(e.toolName||e.kind||"").toLowerCase();return t.includes("glob")?{label:e.toolName||"glob",color:"#6366f1"}:t.includes("grep")?{label:e.toolName||"grep",color:"#a855f7"}:t.includes("edit")||t.includes("write")||t.includes("patch")?{label:e.toolName||"edit",color:"#eab308"}:t.includes("read")||t.includes("view")||t.includes("list")?{label:e.toolName||"read",color:"#10b981"}:t.includes("bash")||t.includes("exec")||t.includes("command")||t.includes("terminal")?{label:e.toolName||"bash",color:"#3b82f6"}:t.includes("search")||t.includes("find")?{label:e.toolName||"search",color:"#a855f7"}:t.includes("run")?{label:e.toolName||"run",color:"#f59e0b"}:{label:e.toolName||e.kind,color:"#64748b"}},DG=()=>o.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",role:"img","aria-label":"User icon",children:[o.jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),o.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),OG=({promptTokens:e,fullText:t,tooltipId:n})=>{const[r,a]=g.useState(!1),s=e?.freshInputTokens??0,i=e?.cacheReadTokens??0,l=e?.outputTokens??0,u=Fl(s,i,l),c=t.length>0?t.split(/\r?\n/).length:0,d=t.length;return o.jsxs("div",{className:"relative inline-flex items-center z-20",children:[o.jsx("button",{type:"button","aria-label":"Show user prompt token breakdown","aria-describedby":n,"data-testid":`timeline-user-badge-${n}`,className:"p-1 rounded bg-base-300 text-cyan-400 shrink-0 hover:bg-base-content/10 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary transition-colors cursor-pointer",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onFocus:()=>a(!0),onBlur:()=>a(!1),onKeyDown:p=>{p.key==="Escape"&&a(!1)},children:o.jsx(DG,{})}),o.jsxs("div",{id:n,role:"tooltip","data-testid":n,className:`absolute left-0 top-full z-50 mt-1.5 w-56 p-2 rounded-lg bg-base-300 border border-base-content/20 shadow-2xl text-[11px] font-mono leading-relaxed pointer-events-none ${r?"block":"hidden"}`,children:[o.jsx("div",{className:"font-bold text-base-content mb-1",children:"User Prompt Telemetry"}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80",children:[o.jsx("span",{className:"text-base-content/60",children:"Lines / chars:"}),o.jsxs("span",{children:[c," lines (",d," chars)"]}),o.jsx("span",{className:"text-base-content/60",children:"📥 Fresh input:"}),o.jsx("span",{children:Be(s)}),o.jsx("span",{className:"text-base-content/60",children:"💾 Cache read:"}),o.jsx("span",{className:"text-cyan-400",children:Be(i)}),o.jsx("span",{className:"text-base-content/60",children:"📤 Output:"}),o.jsx("span",{children:Be(l)}),o.jsx("span",{className:"text-base-content/60 border-t border-base-content/10 pt-0.5",children:"⚡ Turn load:"}),o.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Be(u)})]})]})]})},Ry=({agentId:e,model:t,timestamp:n,tooltipId:r,freshInputTokens:a=0,cacheReadTokens:s=0,outputTokens:i=0,sessionId:l})=>{const[u,c]=g.useState(!1),d=Fl(a,s,i);return o.jsxs("div",{className:"relative inline-flex items-center z-20",children:[o.jsx("button",{type:"button","aria-label":`Show ${e} metadata and token breakdown`,"aria-describedby":r,"data-testid":`timeline-agent-badge-${r}`,className:"inline-flex items-center justify-center p-1 rounded hover:bg-base-content/10 text-base-content focus:outline-none focus-visible:ring-1 focus-visible:ring-primary transition-colors cursor-pointer",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>c(!0),onBlur:()=>c(!1),onKeyDown:p=>{p.key==="Escape"&&c(!1)},children:o.jsx(_r,{id:e})}),o.jsxs("div",{id:r,role:"tooltip","data-testid":r,className:`absolute left-0 top-full z-50 mt-1.5 w-60 p-2.5 rounded-xl bg-base-300 border border-base-content/20 shadow-2xl text-[11px] font-mono leading-relaxed pointer-events-none ${u?"block":"hidden"}`,children:[o.jsxs("div",{className:"font-bold text-base-content mb-1.5 flex items-center gap-1.5 border-b border-base-content/10 pb-1",children:[o.jsx(_r,{id:e}),o.jsx("span",{className:"uppercase",children:e}),o.jsxs("span",{className:"text-base-content/50 font-normal truncate",children:["(",t,")"]})]}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80 text-[10.5px]",children:[o.jsx("span",{className:"text-base-content/60",children:"Timestamp:"}),o.jsx("span",{className:"truncate",children:Wd(n)}),l&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-base-content/60",children:"Session:"}),o.jsx("span",{className:"truncate font-bold text-primary",children:l})]})]}),o.jsxs("div",{className:"mt-1.5 pt-1.5 border-t border-base-content/10",children:[o.jsx("div",{className:"font-bold text-base-content/70 text-[10px] uppercase tracking-wider mb-0.5",children:"Token Breakdown"}),o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80 text-[10.5px]",children:[o.jsx("span",{className:"text-base-content/60",children:"📥 Fresh input:"}),o.jsx("span",{children:Be(a)}),o.jsx("span",{className:"text-base-content/60",children:"💾 Cache read:"}),o.jsx("span",{className:"text-cyan-400",children:Be(s)}),o.jsx("span",{className:"text-base-content/60",children:"📤 Output:"}),o.jsx("span",{children:Be(i)}),o.jsx("span",{className:"text-base-content/60 border-t border-base-content/10 pt-0.5",children:"⚡ Total:"}),o.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Be(d)})]})]})]})]})},Qw=({data:e,loading:t,error:n,mode:r="session",sessionId:a,availableSessions:s=[],onSelectSession:i,onModeChange:l,consolidatedTaskWbs:u="",consolidatedRunId:c="",onConsolidatedScopeSubmit:d})=>{const p=e?.scope.sessionId,m=e?.scope.source,[f,b]=g.useState({}),[x,E]=g.useState(!0),[y,S]=g.useState(!0),[v,N]=g.useState(!0),[A,w]=g.useState(u),[T,_]=g.useState(c),B=p&&m?Ha(m,p):"consolidated",k=f[B]||{},$=K=>{b(Ee=>({...Ee,[B]:K(Ee[B]||{})}))},V=(K,Ee)=>{const re=za(K,Ee);$(D=>({...D,[re]:!D[re]}))};if(t)return o.jsx("div",{className:"flex items-center justify-center p-16",children:o.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin motion-reduce:animate-none"})});if(n)return o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:o.jsxs("span",{children:["Failed to load timeline: ",n]})});if(!e)return o.jsx("div",{className:"p-4 rounded-lg bg-info/10 border border-info/20 text-info",children:o.jsx("span",{children:"No timeline data available."})});const{scope:P,blocks:H,truncated:W}=e,L=Fl(P.tokens.freshInputTokens,P.tokens.cacheReadTokens,P.tokens.outputTokens),te=kG(P.tokens.freshInputTokens,P.tokens.cacheReadTokens),ie=H.map(K=>{const Ee=K.events.filter(re=>Iy(re)?!x:re.kind==="unknown"||re.agent==="unknown"?!y:!(v&&!re.payload?.trim()&&(re.durationMs===null||re.durationMs===0)&&Fl(re.freshInputTokens,re.cacheReadTokens,re.outputTokens)===0));return{...K,events:Ee}}).filter(K=>K.events.length>0),be=ie.flatMap(K=>K.events.filter(Ee=>!!Ee.payload?.trim()).map(Ee=>za(K.key,Ee.seq))),I=be.length>0&&be.every(K=>k[K]),ne=()=>$(()=>I?{}:Object.fromEntries(be.map(K=>[K,!0]))),ue=s.findIndex(K=>K.id===P.sessionId&&K.source===P.source),O=ue>0?s[ue-1]:void 0,Ne=ue>=0&&ue<s.length-1?s[ue+1]:void 0,de=K=>{const Ee=Date.parse(K),re=ie.find(D=>{const ye=D.timestamp?Date.parse(D.timestamp):Number.NaN;return Number.isFinite(ye)&&ye>=Ee})??ie.at(-1);re&&document.getElementById(`timeline-block-${pa(re.key)}`)?.scrollIntoView({behavior:"smooth",block:"center"})};return o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col gap-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsx("h3",{className:"text-base font-bold tracking-tight",children:"Conversation"}),o.jsxs("fieldset",{className:"inline-flex border border-base-content/20 rounded-lg p-0.5 bg-base-300 font-mono text-xs",children:[o.jsx("legend",{className:"sr-only",children:"Timeline mode"}),o.jsx("button",{type:"button","data-testid":"timeline-mode-session","aria-pressed":r==="session",className:`px-3 py-1 font-bold rounded-md transition-all cursor-pointer ${r==="session"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content"}`,onClick:()=>l?.("session"),children:"Single Session"}),o.jsx("button",{type:"button","data-testid":"timeline-mode-consolidated","aria-pressed":r==="consolidated",className:`px-3 py-1 font-bold rounded-md transition-all cursor-pointer ${r==="consolidated"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content"}`,onClick:()=>l?.("consolidated"),children:"Consolidated"})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3",children:[r==="session"?o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"sr-only",children:"Session"}),o.jsx("select",{"aria-label":"Select Session","data-testid":"timeline-session-select",className:"px-3 py-1.5 min-h-[44px] text-xs rounded-lg border border-base-content/20 bg-base-300 font-mono text-base-content max-w-xs focus:outline-hidden focus:border-primary cursor-pointer",value:P.source&&P.sessionId?Ha(P.source,P.sessionId):"",onChange:K=>{const Ee=s.find(re=>Ha(re.source,re.id)===K.target.value);Ee&&i?.(Ee.source,Ee.id)},children:s.length>0?s.map(K=>o.jsx("option",{value:Ha(K.source,K.id),children:ky(K)},Ha(K.source,K.id))):o.jsx("option",{value:P.source&&P.sessionId?Ha(P.source,P.sessionId):"",children:P.sessionId?ky({id:P.sessionId,source:P.source??"unknown",start:P.start??"",tokenLoad:L}):"No session selected"})})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{type:"button","aria-label":"Previous session",disabled:!O,className:"px-3 py-2 min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-xs font-mono rounded-lg border border-base-content/20 bg-base-300 text-base-content/80 disabled:opacity-40 disabled:cursor-not-allowed hover:bg-base-content/10 transition-colors focus-visible:ring-2 focus-visible:ring-primary cursor-pointer",onClick:()=>O&&i?.(O.source,O.id),children:"←"}),o.jsx("button",{type:"button","aria-label":"Next session",disabled:!Ne,className:"px-3 py-2 min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-xs font-mono rounded-lg border border-base-content/20 bg-base-300 text-base-content/80 disabled:opacity-40 disabled:cursor-not-allowed hover:bg-base-content/10 transition-colors focus-visible:ring-2 focus-visible:ring-primary cursor-pointer",onClick:()=>Ne&&i?.(Ne.source,Ne.id),children:"→"})]})]}):o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-lg bg-base-300 border border-base-content/20 text-xs font-mono",children:[o.jsx("span",{className:"text-base-content/60",children:"Scope:"}),o.jsxs("span",{className:"font-semibold text-primary",children:[P.sessionCount," sessions"]})]}),o.jsxs("form",{className:"flex flex-wrap items-end gap-2",onSubmit:K=>{K.preventDefault(),d?.({taskWbs:A.trim(),runId:T.trim()})},children:[o.jsxs("label",{className:"flex flex-col gap-1 text-[10px] font-mono text-base-content/60",children:["Task WBS",o.jsx("input",{type:"text",value:A,onInput:K=>w(K.currentTarget.value),className:"min-h-[44px] w-28 rounded-lg border border-base-content/20 bg-base-300 px-2 text-xs text-base-content focus:outline-hidden focus:border-primary"})]}),o.jsxs("label",{className:"flex flex-col gap-1 text-[10px] font-mono text-base-content/60",children:["Run ID",o.jsx("input",{type:"text",value:T,onInput:K=>_(K.currentTarget.value),className:"min-h-[44px] w-40 rounded-lg border border-base-content/20 bg-base-300 px-2 text-xs text-base-content focus:outline-hidden focus:border-primary"})]}),o.jsx("button",{type:"submit",className:"min-h-[44px] rounded-lg bg-primary px-3 text-xs font-semibold text-primary-content focus-visible:ring-2 focus-visible:ring-primary cursor-pointer hover:bg-primary/90 transition-colors",children:"Apply scope"})]})]}),o.jsx("button",{type:"button","aria-pressed":I,disabled:be.length===0,className:"px-3.5 py-2 min-h-[44px] rounded-lg text-xs font-semibold border border-primary/30 text-primary hover:bg-primary/10 disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:ring-2 focus-visible:ring-primary cursor-pointer",onClick:ne,children:I?"Collapse all":"Expand all"}),o.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs font-mono text-base-content/80",children:[o.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox","data-testid":"timeline-filter-assistant",className:"w-3.5 h-3.5 rounded border border-base-content/30 accent-primary focus-visible:ring-1 focus-visible:ring-primary",checked:x,onChange:K=>E(K.target.checked)}),o.jsx("span",{children:"Hide assistant"})]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox","data-testid":"timeline-filter-unknown",className:"w-3.5 h-3.5 rounded border border-base-content/30 accent-primary focus-visible:ring-1 focus-visible:ring-primary",checked:y,onChange:K=>S(K.target.checked)}),o.jsx("span",{children:"Hide unknown"})]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox","data-testid":"timeline-filter-empty",className:"w-3.5 h-3.5 rounded border border-base-content/30 accent-primary focus-visible:ring-1 focus-visible:ring-primary",checked:v,onChange:K=>N(K.target.checked)}),o.jsx("span",{children:"Hide other empty"})]})]})]})]}),o.jsxs("div",{"data-testid":"timeline-metadata-strip",className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-9 gap-3 pt-3 border-t border-base-content/10 text-xs font-mono",children:[o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:r==="session"?"SESSION":"SESSIONS"}),o.jsx("span",{className:"font-semibold truncate text-base-content mt-0.5",title:P.sessionId??`${P.sessionCount} sessions`,children:P.sessionId?Gd(P.sessionId):`${P.sessionCount} total`})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"AGENT"}),o.jsx("span",{className:"inline-flex items-center gap-1 font-semibold truncate text-base-content mt-0.5",children:P.source?o.jsxs(o.Fragment,{children:[o.jsx(_r,{id:P.source}),P.source]}):"multiple"})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"MODEL"}),o.jsxs("span",{className:"inline-flex items-center gap-1.5 truncate text-base-content mt-0.5",children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary/70 shrink-0"}),P.model??"multiple"]})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"STARTED"}),o.jsx("span",{className:"truncate text-base-content/80 mt-0.5",children:Xw(P.start)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"DURATION"}),o.jsx("span",{className:"font-semibold truncate text-base-content mt-0.5",children:Bw(P.durationMs/6e4)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"TOTAL TOKENS"}),o.jsx("span",{className:"font-bold text-primary truncate mt-0.5",children:Be(L)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"CACHE READ"}),o.jsxs("span",{className:"font-semibold text-cyan-400 truncate mt-0.5",children:[te.toFixed(1),"%"]})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"OUTPUT TOKENS"}),o.jsx("span",{className:"truncate text-base-content/80 mt-0.5",children:Be(P.tokens.outputTokens)})]}),o.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"TOOL CALLS"}),o.jsx("span",{className:"truncate text-base-content font-bold mt-0.5",children:Wt(P.toolCallCount)})]})]}),o.jsx(_G,{blocks:ie,start:P.start,end:P.end,onJumpToTime:de})]}),W&&o.jsxs("div",{"data-testid":"timeline-truncated-banner",className:"p-3 rounded-lg bg-info/10 border border-info/20 text-info font-mono text-xs flex items-center gap-2",children:[o.jsx("span",{children:"ℹ️"}),o.jsx("span",{children:"Showing newest 5,000 events. Apply a narrower filter or time window to inspect earlier events."})]}),o.jsx("div",{"data-testid":"timeline-rail",className:"relative py-2 sm:py-4 before:absolute before:left-2 sm:before:left-[136px] before:top-0 before:bottom-0 before:w-[2px] before:bg-base-content/20 flex flex-col gap-3",children:ie.map(K=>{const Ee=K.events.filter(D=>D.kind==="user"),re=K.events.filter(D=>D.kind!=="user");return o.jsxs("div",{id:`timeline-block-${pa(K.key)}`,"data-testid":`timeline-block-${K.key}`,className:"flex flex-col gap-2.5",children:[r==="consolidated"&&o.jsxs("div",{className:"flex items-center gap-2 pl-6 sm:pl-[144px] pt-2 pb-1 font-mono text-xs text-base-content/70",children:[o.jsx(_r,{id:K.source}),o.jsx("span",{className:"font-bold text-base-content",children:K.source}),o.jsxs("span",{children:["· ",Gd(K.sessionId)]}),o.jsxs("span",{children:["· Turn #",K.turnIndex]}),K.correlationExactness&&o.jsx("span",{"data-testid":`timeline-exactness-${K.key}`,className:`px-1.5 py-0.2 rounded text-[10px] font-bold ${K.correlationExactness==="exact"?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-amber-500/10 text-amber-400 border border-amber-500/20"}`,children:K.correlationExactness})]}),Ee.map(D=>{const ye=IG(D),Se=D.payload?.trim()??"",pe=Cy(ye),Ae=!!D.payload?.trim(),He=!!k[za(K.key,D.seq)],fe=pa(`timeline-user-drawer-${K.key}-${D.seq}`),Je=pa(`user-tt-${K.key}-${D.seq}`);return o.jsxs("div",{className:"relative flex flex-col sm:grid sm:grid-cols-[136px_minmax(0,1fr)] py-1","data-testid":`timeline-user-event-${K.key}-${D.seq}`,children:[o.jsxs("div",{className:"hidden sm:flex flex-col items-end justify-center pr-4 font-mono text-[10.5px] text-base-content/80 select-none",title:K.timestamp?`Timestamp: ${Wd(K.timestamp)}`:void 0,children:[o.jsxs("span",{className:"font-semibold text-primary truncate",children:["📥 ",Be(D.freshInputTokens)," in"]}),D.durationSource==="measured"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,className:D.durationMs>=5e3?"font-bold text-amber-400":"text-base-content/60",children:["⏱ ",ns(D.durationMs)]}):D.durationSource==="inferred"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Inferred from next event timestamp within session",className:"text-base-content/60 italic",children:["⏱ ~",ns(D.durationMs)]}):o.jsx("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Unmeasured (gap > 10m or last event)",className:"text-base-content/40",children:"⏱ —"})]}),o.jsx("span",{"data-timeline-node":"prompt",className:"absolute left-[3.5px] sm:left-[131.5px] top-1/2 -translate-y-1/2 w-[9px] h-[9px] rounded-full bg-cyan-400 ring-4 ring-base-100 z-10","aria-hidden":"true"}),o.jsx("div",{className:"pl-6 sm:pl-5 min-w-0 flex justify-end",children:o.jsxs("div",{className:"w-[80%] max-w-none bg-base-100 rounded-xl border border-primary/20 hover:border-primary/40 hover:bg-base-200/40 transition-all p-2.5 sm:px-3.5 sm:py-2.5 flex flex-col gap-1 shadow-xs relative",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 min-h-[32px]",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:"relative z-10",children:o.jsx(OG,{promptTokens:D.promptTokens,fullText:Se,tooltipId:Je})}),o.jsx("span",{className:"font-mono text-xs font-semibold text-base-content/90 truncate min-w-0",children:pe})]}),o.jsx("div",{className:"flex items-center gap-2 shrink-0 font-mono text-[11px] text-base-content/60",children:Ae?o.jsx("button",{type:"button","aria-label":He?"Collapse full user prompt":"Expand full user prompt","aria-expanded":He,"aria-controls":fe,onClick:()=>V(K.key,D.seq),className:"p-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 inline-flex items-center justify-center text-base-content/60 hover:text-base-content transition-colors cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-primary rounded after:absolute after:inset-0 after:rounded-xl after:content-['']",children:o.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${He?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null})]}),He&&Ae&&o.jsx("div",{id:fe,className:"mt-1 p-3 bg-[#0d141f] text-slate-100 rounded-md font-mono text-xs whitespace-pre-wrap overflow-x-auto border border-white/10 relative z-10",children:$c(ye)})]})})]},za(K.key,D.seq))}),re.map(D=>{const ye=RG(D),Se=!!k[za(K.key,D.seq)],pe=!!D.payload?.trim(),Ae=pa(`timeline-op-drawer-${K.key}-${D.seq}`),He=pa(`agent-tt-${K.key}-${D.seq}`),fe=pa(`tool-tt-${K.key}-${D.seq}`),Je=Iy(D);return o.jsxs("div",{className:"relative flex flex-col sm:grid sm:grid-cols-[136px_minmax(0,1fr)] py-1 hover:z-30 focus-within:z-30","data-testid":`timeline-op-event-${K.key}-${D.seq}`,children:[o.jsxs("div",{className:"hidden sm:flex flex-col items-end justify-center pr-4 font-mono text-[10.5px] text-base-content/80 select-none",title:K.timestamp?`Timestamp: ${Wd(K.timestamp)}`:void 0,children:[o.jsx("span",{className:"font-semibold text-base-content/90 truncate",children:Je&&D.outputTokens>0?`📤 ${Be(D.outputTokens)} out`:`⚡ ${Be(D.tokens)} tok`}),D.durationSource==="measured"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,className:D.durationMs>=5e3?"font-bold text-amber-400":"text-base-content/60",children:["⏱ ",ns(D.durationMs)]}):D.durationSource==="inferred"&&D.durationMs!==null?o.jsxs("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Inferred from next event timestamp within session",className:"text-base-content/60 italic",children:["⏱ ~",ns(D.durationMs)]}):o.jsx("span",{"data-testid":`timeline-step-duration-${K.key}-${D.seq}`,title:"Unmeasured (gap > 10m or last event)",className:"text-base-content/40",children:"⏱ —"})]}),o.jsx("span",{"data-timeline-node":"operation",className:"absolute left-[3.5px] sm:left-[131.5px] top-1/2 -translate-y-1/2 w-[9px] h-[9px] rounded-full ring-4 ring-base-100 z-10",style:{backgroundColor:ye.color},"aria-hidden":"true"}),o.jsx("div",{className:"pl-6 sm:pl-5 min-w-0 flex justify-start",children:Je?o.jsxs("div",{className:"w-[80%] max-w-none bg-base-100 rounded-xl border border-base-content/10 border-l-[3px] border-l-primary/70 hover:border-base-content/30 hover:bg-base-200/40 transition-all relative shadow-xs",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2 min-h-[38px]",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:"relative z-10",children:o.jsx(Ry,{agentId:D.agent||K.source,model:D.model||K.model,timestamp:K.timestamp,tooltipId:He,freshInputTokens:D.freshInputTokens,cacheReadTokens:D.cacheReadTokens,outputTokens:D.outputTokens,sessionId:K.sessionId})}),o.jsx("span",{className:"font-mono text-xs text-base-content/60 truncate",children:D.model}),o.jsx("span",{className:"font-mono text-xs text-base-content/90 truncate min-w-0",children:Cy(D.payload||D.title)})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0 font-mono text-[11px] text-base-content/60",children:[o.jsxs("span",{children:["📤 ",Be(D.outputTokens)]}),pe?o.jsx("button",{type:"button","aria-label":Se?"Collapse response":"Expand response","aria-expanded":Se,"aria-controls":Ae,onClick:()=>V(K.key,D.seq),className:"p-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 inline-flex items-center justify-center text-base-content/60 hover:text-base-content transition-colors cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-primary rounded after:absolute after:inset-0 after:rounded-xl after:content-['']",children:o.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${Se?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null]})]}),Se&&D.payload&&o.jsx("div",{id:Ae,className:"p-3 bg-[#0d141f] text-slate-100 font-mono text-xs whitespace-pre-wrap overflow-x-auto rounded-b-xl border-t border-base-content/10 relative z-10",children:$c(D.payload,D.toolName)})]}):o.jsxs("div",{className:"w-[80%] max-w-none bg-base-100 rounded-xl border border-base-content/10 border-l-[3px] hover:border-base-content/30 hover:bg-base-200/40 transition-all relative shadow-xs",style:{borderLeftColor:ye.color},children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 px-2.5 py-1.5 min-h-[38px]",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:"relative z-10",children:o.jsx(Ry,{agentId:D.agent||K.source,model:D.model||K.model,timestamp:K.timestamp,tooltipId:He,freshInputTokens:D.freshInputTokens,cacheReadTokens:D.cacheReadTokens,outputTokens:D.outputTokens,sessionId:K.sessionId})}),o.jsx("span",{className:"relative z-10",children:o.jsx(Ub,{item:{toolName:ye.label,seq:D.seq,status:D.exitCode===0?"ok":D.exitCode!==null?"error":"ok",durationMs:D.durationMs,durationSource:D.durationSource,tokens:{billedTokens:D.tokens,freshInputTokens:D.freshInputTokens,cacheReadTokens:D.cacheReadTokens,outputTokens:D.outputTokens,cacheSavedTokens:0},argsRaw:D.payload,sessionId:K.sessionId??p,source:D.agent||K.source,model:D.model||K.model,ts:K.timestamp,errorText:D.exitCode!==null&&D.exitCode!==0?D.payload||`Exit code ${D.exitCode}`:null},categoryColor:ye.color,testId:`timeline-tool-badge-${fe}`,tooltipId:fe,size:"xs"})}),D.title&&D.title.trim().length>0?o.jsx("span",{className:"font-mono text-xs font-semibold text-base-content/90 truncate min-w-0",title:D.title,children:D.title}):null]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0 font-mono",children:[D.exitCode!==null&&o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold relative z-10 ${D.exitCode===0?"bg-emerald-500/20 text-emerald-400 border border-emerald-500/30":"bg-error/20 text-error border border-error/30"}`,children:["EXIT_CODE=",D.exitCode]}),pe?o.jsx("button",{type:"button","aria-label":Se?"Collapse operation payload":"Expand operation payload","aria-expanded":Se,"aria-controls":Ae,onClick:()=>V(K.key,D.seq),className:"p-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 inline-flex items-center justify-center text-base-content/60 hover:text-base-content transition-colors cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-primary rounded after:absolute after:inset-0 after:rounded-xl after:content-['']",children:o.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${Se?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null]})]}),Se&&D.payload&&o.jsx("div",{id:Ae,className:"p-3 bg-[#0d141f] text-slate-100 font-mono text-xs whitespace-pre-wrap overflow-x-auto rounded-b-xl border-t border-base-content/10 relative z-10",children:$c(D.payload,ye.label)})]})})]},za(K.key,D.seq))})]},K.key)})})]})},Js=Fr,Jw=({data:e,loading:t=!1,error:n=null,mode:r="session",onModeChange:a=()=>{},sessionId:s,sessionSource:i,availableSessions:l=[],onSelectSession:u=()=>{},toolNames:c=[],onToolNamesChange:d=()=>{},status:p="all",onStatusChange:m=()=>{},search:f="",onSearchChange:b=()=>{}})=>{const x=e?.items??[],E=e?.scope,y=g.useMemo(()=>{const N=new Set;for(const A of x)N.add(A.toolName);return Array.from(N).sort()},[x]),S=N=>{c.includes(N)?d(c.filter(A=>A!==N)):d([...c,N])},v=c.length>0||p!=="all"||f.trim().length>0;return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col gap-4 shadow-xs",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-base-content/10",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[o.jsxs("div",{className:"inline-flex bg-base-300 p-1 rounded-xl border border-base-content/5 text-xs font-mono",children:[o.jsx("button",{type:"button",className:`px-3.5 py-1.5 font-bold rounded-lg transition-all cursor-pointer ${r==="session"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content hover:bg-base-content/5"}`,onClick:()=>a("session"),children:"Single Session"}),o.jsx("button",{type:"button",className:`px-3.5 py-1.5 font-bold rounded-lg transition-all cursor-pointer ${r==="consolidated"?"bg-primary text-primary-content shadow-xs":"text-base-content/70 hover:text-base-content hover:bg-base-content/5"}`,onClick:()=>a("consolidated"),children:"Consolidated Stream"})]}),r==="session"&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[i&&o.jsx("span",{className:"w-5 h-5 flex items-center justify-center text-base-content/80",children:o.jsx(_r,{id:i})}),o.jsx("select",{className:"bg-base-300 border border-base-content/20 rounded-xl px-3 py-1.5 text-xs font-mono max-w-sm focus:outline-hidden focus:border-primary cursor-pointer text-base-content",value:s?`${i??""}:${s}`:"",onChange:N=>{const A=N.target.value,[w,...T]=A.split(":");w&&T.length>0&&u(w,T.join(":"))},children:l.map(N=>o.jsxs("option",{value:`${N.source}:${N.id}`,children:["[",N.source,"] ",N.id.slice(0,16),"... (",N.model,")"]},`${N.source}:${N.id}`))})]})]}),r==="consolidated"&&o.jsx("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2.5 py-1 rounded-full",children:"Consolidated across all window sessions"})]}),o.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3",children:[o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Total Calls"}),o.jsx("div",{className:"mt-1",children:o.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-calls",children:E?.totalCalls??0})})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Unique Tools"}),o.jsx("div",{className:"mt-1",children:o.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-unique",children:E?.uniqueTools??0})})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Errors / Rate"}),o.jsx("div",{className:"mt-1",children:o.jsxs("span",{className:`text-lg font-bold font-mono ${(E?.errorCount??0)>0?"text-error":"text-success"}`,"data-testid":"tool-scope-errors",children:[E?.errorCount??0," (",Math.round((E?.errorRate??0)*100),"%)"]})})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Mean Duration"}),o.jsxs("div",{className:"mt-1",children:[o.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-duration",children:E?.meanDurationMs?`${E.meanDurationMs} ms`:"—"}),(E?.durationUnmeasured??0)>0&&o.jsxs("span",{className:"text-[10px] text-base-content/50 ml-1 font-mono block",children:["(",E?.durationUnmeasured," unmeasured)"]})]})]}),o.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[o.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Billed Tokens"}),o.jsx("div",{className:"mt-1",children:o.jsx("span",{className:"text-lg font-bold font-mono text-primary","data-testid":"tool-scope-tokens",children:E?Js(E.tokens.billedTokens):0})})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-base-content/10",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs text-base-content/60 font-semibold font-mono",children:"Status:"}),o.jsx("div",{className:"inline-flex bg-base-300 p-0.5 rounded-lg text-xs font-mono",children:["all","ok","error"].map(N=>o.jsx("button",{type:"button",className:`px-2.5 py-1 text-xs font-bold rounded-md transition-all cursor-pointer ${p===N?N==="error"?"bg-error text-error-content shadow-xs":"bg-base-content text-base-100 shadow-xs":"text-base-content/70 hover:bg-base-content/10"}`,onClick:()=>m(N),children:N.toUpperCase()},N))})]}),o.jsxs("div",{className:"flex-1 max-w-md relative",children:[o.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-xs opacity-40",children:"🔍"}),o.jsx("input",{type:"text",className:"bg-base-300 border border-base-content/20 rounded-xl pl-8 pr-7 py-1.5 w-full text-xs font-mono focus:outline-hidden focus:border-primary placeholder:text-base-content/40",placeholder:"Search tool arguments, digest, or error text...",value:f,onChange:N=>b(N.target.value)}),f&&o.jsx("button",{type:"button",onClick:()=>b(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-xs text-base-content/40 hover:text-base-content cursor-pointer",children:"✕"})]})]}),y.length>0&&o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-2 border-t border-base-content/5",children:[o.jsx("span",{className:"text-[11px] text-base-content/50 font-semibold font-mono",children:"Tools:"}),y.map(N=>{const A=c.includes(N);return o.jsx("button",{type:"button","data-testid":`tool-filter-${N}`,className:`px-2.5 py-0.5 rounded-full text-[11px] font-mono transition-all border cursor-pointer ${A?"bg-primary text-primary-content border-primary font-bold shadow-xs":"bg-base-300 text-base-content/80 border-base-content/10 hover:border-base-content/30"}`,onClick:()=>S(N),children:N},N)}),c.length>0&&o.jsxs("button",{type:"button",className:"text-[11px] text-base-content/60 hover:text-base-content underline ml-1 font-mono cursor-pointer",onClick:()=>d([]),children:["Clear (",c.length,")"]})]})]}),e?.truncated&&o.jsxs("div",{className:"bg-warning/10 text-warning border border-warning/20 p-3 rounded-xl text-xs font-medium flex items-center gap-2",children:[o.jsx("span",{children:"⚠️"}),o.jsxs("span",{children:["Showing the first ",x.length," tool calls. Refine your filters or search to narrow the scope."]})]}),n&&o.jsxs("div",{className:"bg-error/10 text-error border border-error/20 p-4 text-xs rounded-xl flex items-center gap-2",children:[o.jsx("span",{children:"⚠️"}),o.jsx("span",{children:n})]}),t&&x.length===0&&o.jsx("div",{className:"flex flex-col gap-2.5 animate-pulse",children:[1,2,3,4,5].map(N=>o.jsx("div",{className:"h-16 bg-base-200 rounded-xl border border-base-content/5"},N))}),!t&&!n&&x.length===0&&o.jsxs("div",{className:"bg-base-200/40 rounded-xl border border-base-content/10 p-12 text-center text-base-content/60 flex flex-col items-center gap-2",children:[o.jsx("span",{className:"text-3xl block mb-1",children:"🔍"}),o.jsx("p",{className:"text-sm font-semibold",children:"No tool calls found"}),o.jsx("p",{className:"text-xs max-w-sm",children:v?"No tool calls match your active filter criteria. Try clearing search or status filters.":"No tool invocations recorded for this scope."})]}),x.length>0&&o.jsx("div",{className:"flex flex-col gap-2 w-full",children:x.map(N=>{const A=`${N.sessionId}:${N.messageHash}:${N.toolSeq}`,w=Ll[N.category]??Ll.other,T=N.status==="error";return o.jsxs("div",{className:"w-full text-left group p-3 rounded-xl border border-base-content/10 hover:border-base-content/30 hover:bg-base-200/60 bg-base-200/30 transition-all flex items-center justify-between gap-3 relative","data-testid":`tool-item-${N.seq}`,children:[o.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[o.jsx(yG,{agentId:N.source,model:N.model,timestamp:N.ts,freshInputTokens:N.tokens.freshInputTokens,cacheReadTokens:N.tokens.cacheReadTokens,outputTokens:N.tokens.outputTokens,sessionId:N.sessionId}),o.jsxs("span",{className:"text-xs font-mono text-base-content/40 font-bold min-w-[28px]",children:["#",N.seq]}),o.jsx(TG,{item:N,categoryColor:w}),o.jsx("span",{className:"text-xs font-mono text-base-content/80 truncate min-w-0 flex-1",title:N.argsRaw||N.argsDigest||"",children:hG(N)})]}),o.jsxs("div",{className:"flex items-center gap-3 shrink-0 text-xs font-mono",children:[o.jsx("span",{className:"text-base-content/70 tabular-nums",title:`Duration source: ${N.durationSource}`,children:N.durationMs!==null?`${N.durationMs} ms`:"—"}),o.jsxs("span",{className:"text-base-content/50 text-[11px] tabular-nums",title:`Tokens: ${Js(N.tokens.freshInputTokens)} fresh input, ${Js(N.tokens.cacheReadTokens)} cache read, ${Js(N.tokens.outputTokens)} output`,children:[Js(N.tokens.billedTokens)," tok"]}),o.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border ${T?"bg-error/15 text-error border-error/30":"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"}`,children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-current"}),N.status]})]})]},A)})})]})},LG=[{id:"summary",label:"Summary",component:Zw},{id:"timeline",label:"Timeline",component:Qw},{id:"tool-using",label:"Tool Using",component:Jw},{id:"sessions",label:"Sessions",component:Yw},{id:"insights",label:"Insights",component:Vw},{id:"sources",label:"Sources",component:Kw}],qo=(e,t)=>{const n=new Map;for(const r of e)n.set(r.id,r);for(const r of t??[])n.has(r)||n.set(r,{id:r,label:r});return[...n.values()]},MG=e=>e.range==="1h"?"Last 1h":e.range==="4h"?"Last 4h":e.range==="24h"?"Last 24h":e.range==="7d"?"Last 7d":e.range==="30d"?"Last 30d":e.range==="all"?"All time":`${e.from?.slice(0,10)??"…"} → ${e.to?.slice(0,10)??"…"}`,Ga=e=>e instanceof Error?e.message:String(e),FG=()=>{const[e,t]=g.useState("summary"),[n,r]=g.useState({range:"4h",bucket:"auto",dimension:"model"}),[a,s]=g.useState("session"),[i,l]=g.useState(null),[u,c]=g.useState({taskWbs:"",runId:""}),[d,p]=g.useState("session"),[m,f]=g.useState([]),[b,x]=g.useState("all"),[E,y]=g.useState(""),[S,v]=g.useState(""),[N,A]=g.useState(1),[w,T]=g.useState("start"),[_,B]=g.useState("desc"),[k,$]=g.useState(void 0),[V,P]=g.useState(void 0),[H,W]=g.useState(void 0),[L,te]=g.useState(void 0),[ie,be]=g.useState(void 0),[I,ne]=g.useState(void 0),[ue,O]=g.useState([]),[Ne,de]=g.useState(!1),[K,Ee]=g.useState(!0),[re,D]=g.useState(null),[ye,Se]=g.useState(!0),[pe,Ae]=g.useState(null),[He,fe]=g.useState(!0),[Je,bt]=g.useState(null),[it,Ft]=g.useState(!1),[Nt,Tt]=g.useState(null),[$t,rt]=g.useState(!1),[Me,et]=g.useState(null),[Q,ce]=g.useState(!1),[Re,G]=g.useState(null);g.useEffect(()=>{let se=!0;return Ee(!0),D(null),Se(!0),Ae(null),rn.history.getSummary(n).then(he=>{se&&(he?.data?$(he.data):D("Failed to load summary"))}).catch(he=>{se&&D(Ga(he))}).finally(()=>{se&&Ee(!1)}),rn.history.getInsights(n).then(he=>{se&&(he?.data?be(he.data):Ae("Failed to load insights"))}).catch(he=>{se&&Ae(Ga(he))}).finally(()=>{se&&Se(!1)}),()=>{se=!1}},[n]),g.useEffect(()=>{let se=!0;return fe(!0),bt(null),(async()=>{try{const he=await rn.history.getSources();if(!se)return;he?.data?ne(he.data):bt("Failed to load sources")}catch(he){se&&bt(Ga(he))}finally{se&&fe(!1)}})(),()=>{se=!1}},[]),g.useEffect(()=>{if(e!=="timeline"&&e!=="tool-using")return;let se=!0;return de(!0),(async()=>{try{const he=await rn.history.getSessions({filter:n,page:1,pageSize:100,sortBy:"start",sortDir:"desc"});if(!se)return;const st=(he?.data?.items??[]).map(Y=>({id:Y.id,source:Y.source,model:Y.model,start:Y.start,tokenLoad:Y.freshInputTokens+Y.cacheReadTokens+Y.outputTokens}));O(st);const Ot=st[0];Ot&&!i&&l({source:Ot.source,id:Ot.id})}catch{se&&O([])}finally{se&&de(!1)}})(),()=>{se=!1}},[e,n,i]),g.useEffect(()=>{if(e!=="sessions")return;let se=!0;return Ft(!0),Tt(null),(async()=>{try{const he=await rn.history.getSessions({filter:n,page:N,pageSize:20,sortBy:w,sortDir:_});if(!se)return;he?.data?te(he.data):Tt("Failed to load sessions")}catch(he){se&&Tt(Ga(he))}finally{se&&Ft(!1)}})(),()=>{se=!1}},[e,n,N,w,_]),g.useEffect(()=>{if(e!=="timeline")return;if(a==="session"&&!i){const he=ue[0];!Ne&&he&&l({source:he.source,id:he.id});return}let se=!0;return rt(!0),et(null),(async()=>{try{const he=a==="session"&&i?await rn.history.getTimeline({mode:"session",source:i.source,sessionId:i.id}):await rn.history.getTimeline({mode:"consolidated",filter:n,...u.taskWbs?{taskWbs:u.taskWbs}:{},...u.runId?{runId:u.runId}:{}});if(!se)return;he?.data?P(he.data):et("Failed to load timeline")}catch(he){se&&et(Ga(he))}finally{se&&rt(!1)}})(),()=>{se=!1}},[e,a,i,n,Ne,ue,u]),g.useEffect(()=>{const se=setTimeout(()=>{v(E)},250);return()=>clearTimeout(se)},[E]),g.useEffect(()=>{if(e!=="tool-using")return;if(d==="session"&&!i){const he=ue[0];!Ne&&he&&l({source:he.source,id:he.id});return}let se=!0;return ce(!0),G(null),(async()=>{try{const he=d==="session"&&i?{mode:"session",source:i.source,sessionId:i.id,toolNames:m.length>0?m:void 0,status:b,search:S||void 0}:{mode:"consolidated",filter:n,toolNames:m.length>0?m:void 0,status:b,search:S||void 0},st=await rn.history.getToolSequence(he);if(!se)return;st?.data?W(st.data):G("Failed to load tool sequence")}catch(he){se&&G(Ga(he))}finally{se&&ce(!1)}})(),()=>{se=!1}},[e,d,i,n,m,b,S,Ne,ue]);const Fe=(se,he)=>{l({source:se,id:he}),s("session"),t("timeline")},Ve=(se,he)=>{l({source:se,id:he}),p("session")},pt=(se,he)=>{const st=he?{source:he,id:se}:L?.items.find(Ot=>Ot.id===se)??ue.find(Ot=>Ot.id===se);st&&Fe(st.source,st.id)},At=async se=>(await rn.history.triggerImport({mode:se})).data,St=re?"—":K||k===void 0?"…":String(k.kpis.sessionsCount),Rt=Re?"—":Q||H===void 0?"…":String(H.scope.totalCalls),le=pe?"—":ye||ie===void 0?"…":String(ie.loops.length),Ce=Je?"—":He||I===void 0?"…":String(I.agents.length),Ue={summary:null,timeline:null,"tool-using":Rt,sessions:St,insights:le,sources:Ce},je=Je?"—":He?"…":I?.overview.lastImportedAt?new Date(I.overview.lastImportedAt).toLocaleString():"never imported",Et=g.useMemo(()=>ie?{count:ie.loops.length,redundantCalls:ie.loops.reduce((se,he)=>se+Math.max(0,he.repeats-1),0),wastedTokens:ie.loops.reduce((se,he)=>se+he.wastedTokens,0)}:void 0,[ie]),zt=g.useMemo(()=>qo(I?.agents.map(se=>({id:se.id,label:se.name,color:se.color}))??[],n.sources),[I?.agents,n.sources]),De=g.useMemo(()=>qo(k?.topModels.map(se=>({id:se.id,label:se.label,color:se.color}))??[],n.models),[k?.topModels,n.models]),tt=g.useMemo(()=>qo(k?.topTools.map(se=>{const he=se.id&&se.id.trim()!==""?se.id.trim():"unknown";return{id:he,label:he}})??[],n.tools?.map(se=>se&&se.trim()!==""?se.trim():"unknown")),[k?.topTools,n.tools]),Xe=g.useMemo(()=>qo(k?.skillsUsed.filter(se=>se.id&&se.id.trim()!==""&&se.id!=="unknown").map(se=>({id:se.id,label:se.label,color:se.color}))??[],n.skills?.filter(se=>se&&se.trim()!==""&&se!=="unknown")),[k?.skillsUsed,n.skills]),kt=g.useMemo(()=>({rangeLabel:MG(n),sessionCount:re?null:K&&k===void 0?void 0:k?.kpis.sessionsCount,sourceCount:n.sources?.length??I?.agents.length}),[n,re,K,k,I?.agents.length]);return o.jsxs("div",{className:"flex flex-col gap-4 p-4 max-w-[1600px] mx-auto w-full",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-2xl",children:"📊"}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Histories"}),o.jsx("p",{className:"text-xs text-base-content/60",children:"Transcript telemetry, session traces, and prompt cache analytics"}),o.jsxs("p",{className:"livechip mt-1 inline-flex items-center gap-1.5 rounded-full border border-base-content/10 px-2 py-0.5 text-xs text-base-content/60 font-mono","data-testid":"history-last-import",role:"status",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Je?"bg-error":"bg-emerald-400 animate-pulse"}`,"aria-hidden":"true"}),"last import ",je]})]})]}),o.jsx("div",{className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:LG.map(se=>o.jsxs("button",{type:"button",className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all ${e===se.id?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,onClick:()=>t(se.id),children:[se.label,Ue[se.id]!==null&&o.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 rounded-full text-[10px] font-mono bg-base-content/10","data-testid":`history-badge-${se.id}`,children:Ue[se.id]})]},se.id))})]}),e!=="sources"&&o.jsx(oG,{filter:n,onChange:r,sourceOptions:zt,modelOptions:De,toolOptions:tt,skillOptions:Xe,scope:kt}),o.jsxs("div",{className:"mt-2",children:[e==="summary"&&o.jsx(Zw,{data:k,loading:K,error:re,dimension:n.dimension??"model",onDimensionChange:se=>r(he=>({...he,dimension:se})),bucket:n.bucket??"auto",onBucketChange:se=>r(he=>({...he,bucket:se})),loopSummary:Et}),e==="timeline"&&o.jsx(Qw,{data:V,loading:$t,error:Me,mode:a,sessionId:i?.id,sessionSource:i?.source,availableSessions:ue,onSelectSession:Fe,onModeChange:s,consolidatedTaskWbs:u.taskWbs,consolidatedRunId:u.runId,onConsolidatedScopeSubmit:c}),e==="tool-using"&&o.jsx(Jw,{data:H,loading:Q,error:Re,mode:d,onModeChange:p,sessionId:i?.id,sessionSource:i?.source,availableSessions:ue,onSelectSession:Ve,toolNames:m,onToolNamesChange:f,status:b,onStatusChange:x,search:E,onSearchChange:y}),e==="sessions"&&o.jsx(Yw,{data:L,loading:it,error:Nt,sortBy:w,sortDir:_,page:N,pageSize:20,onSortChange:se=>{w===se?B(he=>he==="asc"?"desc":"asc"):(T(se),B("desc"))},onPageChange:A,onSelectSession:Fe}),e==="insights"&&o.jsx(Vw,{data:ie,loading:ye,error:pe,cacheHitTrend:k?.kpiTrend??[],onSelectSession:pt}),e==="sources"&&o.jsx(Kw,{data:I,loading:He,error:Je,onTriggerImport:At})]})]})},jG={id:"history",name:"History",icon:"📊",route:"history",component:FG,sidebarLabel:"Histories",description:"Imported agent sessions, token analytics, and tool-call forensics",order:20},PG=Object.freeze(Object.defineProperty({__proto__:null,module:jG},Symbol.toStringTag,{value:"Module"})),BG=["30s","5m","1h","4h","24h","7d","all"],UG={"30s":3e4,"5m":5*6e4,"1h":60*6e4,"4h":240*6e4,"24h":1440*6e4,"7d":10080*6e4,all:null};function Pu(e,t=Date.now()){const n=UG[e];if(n!=null)return new Date(t-n).toISOString()}function $G({timeRange:e,onTimeRangeChange:t}){return o.jsxs("fieldset",{className:"flex items-center gap-1 bg-base-200 p-1 rounded-lg border-0 m-0","aria-label":"Time range presets",children:[o.jsx("legend",{className:"sr-only",children:"Time range presets"}),BG.map(n=>{const r=e===n;return o.jsx("button",{type:"button",onClick:()=>t(n),"aria-pressed":r,className:`px-2.5 py-1 text-xs font-semibold rounded-md transition-all cursor-pointer ${r?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,children:n==="all"?"All":n},n)})]})}function zG(e){return e.selectedPrefixes.size>0||e.searchQuery.trim()!==""||e.searchScope!=="all"||e.severity!=="all"||e.tierFilter!=="all"||e.runId.trim()!==""}function Dy({label:e,value:t,onChange:n,options:r}){return o.jsxs("fieldset",{className:"flex items-center gap-0.5 bg-base-100 border border-base-content/20 rounded-md p-0.5","aria-label":e,children:[o.jsx("legend",{className:"sr-only",children:e}),r.map(a=>{const s=a.value===t;return o.jsxs("label",{className:`flex-1 text-[11px] text-center px-2 py-0.5 rounded cursor-pointer transition-all ${s?"bg-primary text-primary-content font-bold shadow-xs":"text-base-content/70 hover:bg-base-content/10"}`,children:[o.jsx("input",{type:"radio",name:`segmented-${e}`,value:a.value,checked:s,onChange:()=>n(a.value),className:"sr-only"}),a.label]},a.value)})]})}const Oy="Retention: events capped at 10,000 rows per prefix · terminal jobs pruned after 30d";function eN(){return o.jsxs("span",{"data-testid":"observability-retention-badge",className:"inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium rounded-lg border border-base-content/15 bg-base-100 text-base-content/70 whitespace-nowrap",title:Oy,children:[o.jsx("span",{"aria-hidden":"true",children:"ℹ️"}),o.jsx("span",{children:Oy})]})}function HG({filters:e,onFiltersChange:t,onClearFilters:n,prefixOptions:r,getPrefixColor:a,liveEnabled:s,onToggleLive:i,shownCount:l,totalCount:u,actions:c}){const d=g.useMemo(()=>{let f=0;return e.selectedPrefixes.size>0&&(f+=e.selectedPrefixes.size),e.searchQuery.trim()!==""&&(f+=1),e.severity!=="all"&&(f+=1),e.tierFilter!=="all"&&(f+=1),e.runId.trim()!==""&&(f+=1),f},[e]),p=zG(e),m=f=>{t(b=>{const x=new Set(b.selectedPrefixes);return x.has(f)?x.delete(f):x.add(f),{...b,selectedPrefixes:x}})};return o.jsx("div",{className:"flex flex-wrap items-center justify-between gap-3 p-3 bg-base-200/50 rounded-xl border border-base-content/10 shrink-0",children:o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("span",{"aria-live":"polite",className:"text-xs font-mono text-base-content/60 whitespace-nowrap","data-testid":"observability-result-count",children:[l," of ",u," shown"]}),o.jsxs("details",{className:"relative inline-block","data-testid":"observability-filter-disclosure",children:[o.jsxs("summary",{className:"px-2.5 py-1 text-xs font-medium rounded-lg border border-base-content/20 bg-base-200 text-base-content/80 hover:bg-base-300 transition-colors cursor-pointer list-none flex items-center gap-1.5 focus:outline-none focus:ring-2 focus:ring-primary/40","aria-label":"Toggle filter panel",children:[o.jsx("span",{children:"🔍 Filter"}),d>0&&o.jsx("span",{className:"px-1.5 py-0.2 rounded-full text-[10px] font-bold bg-primary text-primary-content",children:d})]}),o.jsxs("div",{className:"absolute right-0 top-full z-30 p-3 shadow-xl bg-base-200 border border-base-content/10 rounded-xl w-80 sm:w-96 mt-2 flex flex-col gap-3",children:[o.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-base-content/10",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wide text-base-content/70",children:"Filters"}),p&&o.jsx("button",{type:"button",onClick:n,className:"text-xs text-error hover:underline cursor-pointer","aria-label":"Clear all filters",children:"Clear all"})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:"filter-search-input",className:"text-[11px] font-semibold text-base-content/60",children:"Search"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("select",{value:e.searchScope,onChange:f=>t(b=>({...b,searchScope:f.target.value})),className:"bg-base-100 border border-base-content/20 rounded px-2 py-1 text-xs text-base-content focus:outline-none focus:ring-2 focus:ring-primary/40 cursor-pointer","aria-label":"Search scope",children:[o.jsx("option",{value:"all",children:"all"}),o.jsx("option",{value:"name",children:"name"}),o.jsx("option",{value:"actor",children:"actor"}),o.jsx("option",{value:"payload",children:"payload"})]}),o.jsx(Oi,{id:"filter-search-input",size:"sm",variant:"bordered",placeholder:`Search ${e.searchScope}…`,value:e.searchQuery,onChange:f=>t(b=>({...b,searchQuery:f.target.value})),className:"flex-1 input-xs","aria-label":`Search ${e.searchScope}`})]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Severity"}),o.jsx(Dy,{label:"Severity",value:e.severity,onChange:f=>t(b=>({...b,severity:f})),options:[{value:"all",label:"All"},{value:"info",label:"Info"},{value:"warning",label:"Warning"},{value:"error",label:"Error"}]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Tier"}),o.jsx(Dy,{label:"Tier",value:e.tierFilter,onChange:f=>t(b=>({...b,tierFilter:f})),options:[{value:"all",label:"All"},{value:"default",label:"Default"},{value:"diagnostic",label:"Diagnostic"}]})]}),r.length>0&&o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Prefix"}),o.jsxs("fieldset",{className:"flex flex-wrap items-center gap-1.5 border-0 p-0 m-0","aria-label":"Filter by prefix",children:[o.jsx("legend",{className:"sr-only",children:"Filter by prefix"}),r.map(f=>{const b=e.selectedPrefixes.has(f),x=a(f);return o.jsxs("button",{type:"button",role:"switch","aria-checked":b,"aria-label":`Prefix ${f}${b?" (selected)":""}`,onClick:()=>m(f),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border transition-colors cursor-pointer ${b?`${x} border-current bg-base-100 font-bold`:"text-base-content/60 border-base-content/20 hover:bg-base-100"}`,children:[f,".*"]},f)})]})]}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:"filter-run-id-input",className:"text-[11px] font-semibold text-base-content/60",children:"Run ID"}),o.jsx(Oi,{id:"filter-run-id-input",size:"sm",variant:"bordered",placeholder:"Filter by run id…",value:e.runId,onChange:f=>t(b=>({...b,runId:f.target.value})),className:"w-full input-xs","aria-label":"Filter by run id"})]})]})]}),o.jsx(eN,{}),o.jsx("button",{type:"button",onClick:i,className:`px-2.5 py-1 text-xs font-semibold rounded-lg border transition-all cursor-pointer flex items-center gap-1.5 ${s?"border-emerald-500/40 bg-emerald-500/10 text-emerald-500 hover:bg-emerald-500/20":"border-amber-500/40 bg-amber-500/10 text-amber-500 hover:bg-amber-500/20"}`,"aria-label":s?"Pause live event stream":"Resume live event stream","aria-pressed":s,children:o.jsx("span",{children:s?"⏸ Pause Live":"▶ Resume Live"})}),c]})})}const us=[{key:"time",label:"Time",description:"Event timestamp",defaultVisible:!0,sortable:!0,colWidth:"w-36"},{key:"severity",label:"Severity",description:"Diagnostic severity level",defaultVisible:!0,sortable:!0,colWidth:"w-24"},{key:"event",label:"Event",description:"Event name with domain prefix",defaultVisible:!0,sortable:!0,colWidth:"w-[15%]"},{key:"summary",label:"Summary",description:"Rendered human summary",defaultVisible:!0,sortable:!0,colWidth:"w-[20%]"},{key:"correlation",label:"Correlation",description:"Entity or run correlation identifier",defaultVisible:!0,sortable:!0,colWidth:"w-[16%]"},{key:"outcome",label:"Outcome",description:"Execution result or state change",defaultVisible:!0,sortable:!0,colWidth:"w-28"},{key:"agent",label:"Agent",description:"Target or actor agent role",defaultVisible:!0,sortable:!0,colWidth:"w-28"},{key:"producer",label:"Producer",description:"Subsystem or source package",defaultVisible:!1,sortable:!1,colWidth:"w-[16%]"},{key:"action",label:"Action",description:"Action link or remediation command",defaultVisible:!1,sortable:!1,colWidth:"w-[15%]"},{key:"actor",label:"Actor",description:"Originating user or system actor",defaultVisible:!1,sortable:!1,colWidth:"w-24"}],GG=new Set(us.map(e=>e.key)),ra=["time","severity","event","summary","correlation","outcome","agent"],tN="spur:observability:columns:v1";function WG(e){if(!Array.isArray(e)||e.length===0)return[...ra];const t=new Set;for(const n of e)typeof n=="string"&&GG.has(n)&&t.add(n);return t.size===0?[...ra]:us.filter(n=>t.has(n.key)).map(n=>n.key)}function qG(e){try{const t=e??(typeof window<"u"?window.localStorage:void 0);if(!t)return[...ra];const n=t.getItem(tN);if(!n)return[...ra];const r=JSON.parse(n);return WG(r)}catch{return[...ra]}}function Ly(e,t){try{const n=t??(typeof window<"u"?window.localStorage:void 0);if(!n)return;n.setItem(tN,JSON.stringify(e))}catch{}}function VG({visibleColumns:e,onVisibleColumnsChange:t}){const n=g.useMemo(()=>new Set(e),[e]),r=s=>{const i=new Set(n);if(i.has(s)){if(i.size<=1)return;i.delete(s)}else i.add(s);const l=us.filter(u=>i.has(u.key)).map(u=>u.key);t(l),Ly(l)},a=()=>{const s=[...ra];t(s),Ly(s)};return o.jsxs("details",{className:"relative inline-block","data-testid":"observability-column-customizer",children:[o.jsxs("summary",{className:"px-2.5 py-1 text-xs font-medium rounded-lg border border-base-content/20 bg-base-200 text-base-content/80 hover:bg-base-300 transition-colors cursor-pointer list-none flex items-center gap-1.5 focus:outline-none focus:ring-2 focus:ring-primary/40","aria-label":"Customize visible columns",children:[o.jsx("span",{children:"📊 Columns"}),o.jsxs("span",{className:"text-[10px] text-base-content/60 font-mono",children:["(",e.length,"/",us.length,")"]})]}),o.jsxs("div",{className:"absolute right-0 top-full z-30 p-3 shadow-xl bg-base-200 border border-base-content/10 rounded-xl w-64 mt-2 flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-base-content/10",children:[o.jsx("span",{className:"text-xs font-bold uppercase tracking-wide text-base-content/70",children:"Columns"}),o.jsx("button",{type:"button",onClick:a,className:"text-xs text-primary hover:underline cursor-pointer","aria-label":"Reset columns to default",children:"Reset defaults"})]}),o.jsxs("fieldset",{className:"flex flex-col gap-1.5 border-0 p-0 m-0","aria-label":"Visible columns",children:[o.jsx("legend",{className:"sr-only",children:"Select visible columns"}),us.map(s=>{const i=n.has(s.key),l=i&&n.size===1,u=`observability-col-${s.key}`;return o.jsxs("label",{htmlFor:u,className:`flex items-center justify-between px-2 py-1 rounded-md text-xs transition-colors ${l?"opacity-60 cursor-not-allowed":"hover:bg-base-100 cursor-pointer text-base-content/90"}`,children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Sb,{id:u,size:"xs",variant:"primary",checked:i,disabled:l,onChange:()=>r(s.key),"aria-label":s.label}),o.jsx("span",{className:"font-medium",children:s.label})]}),s.defaultVisible&&o.jsx("span",{className:"text-[10px] text-base-content/50 uppercase",children:"default"})]},s.key)})]})]})]})}const YG=()=>`${Ct()}/events/planning`,qd=100;function Vd(e){const t=`${Ct()}/events/history`,n=[],r=e.limit??qd;return n.push(`limit=${r}`),e.prefix&&n.push(`prefix=${encodeURIComponent(e.prefix)}`),e.names&&n.push(`names=${encodeURIComponent(e.names)}`),e.actor&&n.push(`actor=${encodeURIComponent(e.actor)}`),e.runId&&n.push(`runId=${encodeURIComponent(e.runId)}`),e.since&&n.push(`since=${encodeURIComponent(e.since)}`),e.cursor&&n.push(`cursor=${encodeURIComponent(e.cursor)}`),`${t}?${n.join("&")}`}const KG={workflow:"text-cyan-400",task:"text-emerald-400",feature:"text-emerald-400",agent:"text-amber-400",rule:"text-rose-400",message:"text-sky-400",process:"text-violet-400",queue:"text-orange-400",bus:"text-pink-400",api:"text-teal-400"},My="text-spur-text-muted";function nN(e){return e?KG[e]??My:My}const Hc={selectedPrefixes:new Set,searchQuery:"",searchScope:"all",severity:"all",tierFilter:"all",runId:""};function ZG(){const e=g.useRef([]),[t,n]=g.useState(0);g.useEffect(()=>{const a=window.setInterval(()=>{const s=Date.now()-6e4,i=e.current.filter(l=>l>=s);e.current=i,n(i.length)},1e3);return()=>window.clearInterval(a)},[]);const r=g.useCallback(()=>{const a=Date.now(),s=a-6e4,i=e.current.filter(l=>l>=s);i.push(a),e.current=i,n(i.length)},[]);return{rate:t,recordEvent:r}}function Yd(e){if(e===null||typeof e!="object"||!("events"in e)||!("count"in e))return null;const t=e.events;if(!Array.isArray(t))return null;const n=e.count;if(typeof n!="number")return null;const r=e.nextCursor,a=typeof r=="string"?r:null,s=e.hasMore,i=typeof s=="boolean"?s:!1,l=[];for(const d of t){const p=XG(d);p&&l.push(p)}const u=e.catalog,c=Array.isArray(u)?QG(u):void 0;return{events:l,count:n,nextCursor:a,hasMore:i,...c?{catalog:c}:{}}}function XG(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.id!="string"||typeof t.eventName!="string"||typeof t.occurredAt!="string")return null;const n=typeof t.prefix=="string"?t.prefix:void 0,r=typeof t.renderer=="string"?t.renderer:void 0,a=t.actor;if(a!==null&&typeof a!="string")return null;const s=t.payload,i=typeof t.runId=="string"?t.runId:t.runId===null?null:void 0,l=typeof t.entityKind=="string"?t.entityKind:t.entityKind===null?null:void 0,u=typeof t.entityId=="string"?t.entityId:t.entityId===null?null:void 0,c=typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:t.sequence===null?null:void 0,d={id:t.id,eventName:t.eventName,occurredAt:t.occurredAt,actor:a,...n?{prefix:n}:{},...r?{renderer:r}:{}};if(s===null)return{...d,payload:null,view:Na(t.eventName,null),...jl(i,l,u,c)};if(typeof s!="object")return null;const p=s,m=p.schemaVersion===2?p:void 0;return{...d,payload:rN(p),...m?{envelope:m}:{},view:Na(t.eventName,p),...jl(i,l,u,c)}}function jl(e,t,n,r){const a={};return e!==void 0&&(a.runId=e),t!==void 0&&(a.entityKind=t),n!==void 0&&(a.entityId=n),r!==void 0&&(a.sequence=r),a}function QG(e){const t=[];for(const n of e){if(n===null||typeof n!="object")return;const r=n;if(typeof r.name!="string"||typeof r.prefix!="string"||typeof r.source!="string"||typeof r.renderer!="string")return;const a=typeof r.tier=="string"?r.tier:void 0,s={name:r.name,prefix:r.prefix,source:r.source,renderer:r.renderer,...a!==void 0?{tier:a}:{}};t.push(s)}return t}function JG(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.eventName!="string"||t.eventName.length===0||typeof t.occurredAt!="string")return null;const n=typeof t.prefix=="string"?t.prefix:void 0,r=typeof t.renderer=="string"?t.renderer:void 0,a=t.actor;if(a!==null&&typeof a!="string")return null;const s=t.payload;if(s!==null&&typeof s!="object")return null;const i=s,l=i?.schemaVersion===2?i:void 0,u=rN(i),c=t.runId??u?.runId,d=t.entityKind??u?.entityKind,p=t.entityId??u?.entityId,m=t.sequence??u?.sequence,f=typeof c=="string"?c:c===null?null:void 0,b=typeof d=="string"?d:d===null?null:void 0,x=typeof p=="string"?p:p===null?null:void 0,E=typeof m=="number"&&Number.isFinite(m)?m:m===null?null:void 0;return{eventName:t.eventName,occurredAt:t.occurredAt,actor:a,...n?{prefix:n}:{},...r?{renderer:r}:{},payload:u,...l?{envelope:l}:{},view:Na(t.eventName,i),...jl(f,b,x,E)}}function Na(e,t){const n=eW(e);if(t?.schemaVersion!==2)return n;const r=Yr(t.context),a=Yr(t.presentation),s=Yr(r?.project),i=Yr(r?.producer),l=Yr(r?.correlation);if(!r||!a||!s||!i||!l)return n;const u=a.severity==="info"||a.severity==="warning"||a.severity==="error"?a.severity:"warning",c=Array.isArray(a.fields)?a.fields.flatMap(S=>{const v=Yr(S),N=fn(v?.label,64),A=fn(v?.value,256);return N&&A?[{label:N,value:A}]:[]}).slice(0,8):[],d=[],p=(S,v)=>{const N=fn(v,128);N&&d.push({label:S,value:N})};p("Run",l.runId),p("Execution",l.executionId),p("Action",l.actionId),p("Entity",nW(l.entityKind,l.entityId)),p("Job",l.jobId),typeof l.sequence=="number"&&Number.isFinite(l.sequence)&&d.push({label:"Sequence",value:String(l.sequence)});const m=fn(i.package,128)??"unavailable",f=fn(i.subsystem,128),b=tW(a.action),x=fn(a.actionLabel,128)??"unavailable",E=fn(a.agent,128),y=fn(a.correlators,512);return{severity:u,summary:fn(a.summary,512)??"unavailable",description:fn(a.description,512)??"Description unavailable.",fields:c,projectName:fn(s.name,128)??"unavailable",projectRoot:fn(s.root,256)??"unavailable",producer:f?`${m} / ${f}`:m,correlation:y??"unavailable",correlationFields:d,outcome:fn(a.outcome,128)??"unavailable",action:b,actionLabel:x,agent:E}}function eW(e){return{severity:"warning",summary:"unavailable",description:`Canonical context unavailable for ${fn(e,128)??"unknown"}.`,fields:[],projectName:"unavailable",projectRoot:"unavailable",producer:"unavailable",correlation:"unavailable",correlationFields:[],outcome:"unavailable",action:null,actionLabel:"unavailable",agent:null}}function tW(e){const t=Yr(e);if(!t||t.kind!=="command"&&t.kind!=="filter"&&t.kind!=="path")return null;const n=fn(t.label,128),r=fn(t.value,256);return n&&r?{label:n,kind:t.kind,value:r}:null}function fn(e,t){return typeof e!="string"||e.length===0?null:e.length<=t?e:`${e.slice(0,t-1)}…`}function nW(e,t){const n=fn(e,64),r=fn(t,128);return n&&r?`${n}:${r}`:n??r}const rW=["Entity","Run","Execution","Action","Job"];function aW(e,t){for(const n of rW){const r=t.correlationFields.find(a=>a.label===n);if(r!==void 0&&r.value!=="")return`${e.eventName} · ${r.value}`}return e.id!==""&&!e.id.startsWith("live-")?`${e.eventName} · ${e.id}`:e.eventName}function Yr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function rN(e){return e?.schemaVersion!==2?e:Yr(e.data)}const sW=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Fy(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=sW[t.getMonth()],r=t.getDate(),a=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0"),i=String(t.getSeconds()).padStart(2,"0");return`${n} ${r} ${a}:${s}:${i}`}function aN(e){return typeof e!="number"||!Number.isFinite(e)?null:e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}function It(e){return e&&e!=="unavailable"?e:"-"}function iW(e,t){const n={};e.selectedPrefixes&&e.selectedPrefixes.size===1&&(n.prefix=[...e.selectedPrefixes][0]);const r=e.searchQuery?.trim()??"";r!==""&&e.searchScope==="name"&&(n.names=r),r!==""&&e.searchScope==="actor"&&(n.actor=r),e.runId&&e.runId.trim()!==""&&(n.runId=e.runId.trim());const a=Pu(t);return a&&(n.since=a),n}function jy(e,t,n){if(t.selectedPrefixes.size>=1){const r=e.prefix??e.eventName.split(".")[0]??e.eventName;if(!t.selectedPrefixes.has(r))return!1}if(t.tierFilter!=="all"){const r=n.get(e.eventName);if(r!==t.tierFilter&&!(t.tierFilter==="default"&&r===void 0))return!1}if(t.severity!=="all"&&(e.view??Na(e.eventName,e.payload??null)).severity!==t.severity)return!1;if(t.searchQuery.trim()!==""){const r=t.searchQuery.toLowerCase();let a=!1;if((t.searchScope==="name"||t.searchScope==="all")&&(a=a||e.eventName.toLowerCase().includes(r)),(t.searchScope==="actor"||t.searchScope==="all")&&(a=a||(e.actor?.toLowerCase().includes(r)??!1)),t.searchScope==="payload"&&e.payload&&(a=a||JSON.stringify(e.payload).toLowerCase().includes(r)),!a)return!1}return!(t.runId.trim()!==""&&e.runId!==t.runId.trim())}const $b={key:"time",direction:"desc"};function oW(e,t=$b){const n=e.map((r,a)=>({row:r,idx:a}));return n.sort((r,a)=>{let s=0;const i=r.row.view??Na(r.row.eventName,r.row.payload??null),l=a.row.view??Na(a.row.eventName,a.row.payload??null);switch(t.key){case"time":{const u=Date.parse(r.row.occurredAt),c=Date.parse(a.row.occurredAt),d=Number.isNaN(u)?-1/0:u,p=Number.isNaN(c)?-1/0:c;s=d-p;break}case"severity":{const u=c=>c==="info"?0:c==="warning"?1:2;s=u(i.severity)-u(l.severity);break}case"event":{s=r.row.eventName.localeCompare(a.row.eventName);break}case"summary":{s=(i.summary??"").localeCompare(l.summary??"");break}case"correlation":{s=(i.correlation??"").localeCompare(l.correlation??"");break}case"agent":{s=(i.agent??"").localeCompare(l.agent??"");break}case"outcome":{s=(i.outcome??"").localeCompare(l.outcome??"");break}default:s=0}return s!==0?t.direction==="asc"?s:-s:r.idx-a.idx}),n.map(r=>r.row)}function Vo({value:e,label:t}){const[n,r]=g.useState("idle"),a=async s=>{s.preventDefault(),s.stopPropagation();try{typeof navigator<"u"&&navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),r("copied"),setTimeout(()=>r("idle"),1500)):(r("failed"),setTimeout(()=>r("idle"),2e3))}catch{r("failed"),setTimeout(()=>r("idle"),2e3)}};return!e||e==="-"||e==="unavailable"?null:o.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center justify-center p-0.5 rounded text-base-content/40 hover:text-base-content hover:bg-base-content/10 transition-colors cursor-pointer shrink-0 text-[10px] focus:outline-none focus:ring-1 focus:ring-primary/40",title:n==="copied"?"Copied":n==="failed"?"Copy failed":`Copy ${t}`,"aria-label":n==="copied"?`Copied ${t}`:n==="failed"?`Copy ${t} failed`:`Copy ${t}`,children:[o.jsx("span",{"aria-hidden":"true",children:n==="copied"?"✓":n==="failed"?"!":"📋"}),o.jsx("span",{className:"sr-only","aria-live":"polite",children:n==="copied"?`${t} copied`:n==="failed"?`${t} copy failed`:""})]})}function lW({onLivenessChange:e,timeRange:t}){const[n,r]=g.useState(()=>qG()),[a,s]=g.useState($b),i=g.useCallback(de=>{s(K=>K.key===de?{key:de,direction:K.direction==="asc"?"desc":"asc"}:{key:de,direction:"asc"})},[]),[l,u]=g.useState(!0),[c,d]=g.useState([]),[p,m]=g.useState([]),[f,b]=g.useState("idle"),[x,E]=g.useState(null),[y,S]=g.useState(null),[v,N]=g.useState(!1),[A,w]=g.useState(!1),[T,_]=g.useState(Hc),[B,k]=g.useState(Hc),[$,V]=g.useState("connecting"),{rate:P,recordEvent:H}=ZG();g.useEffect(()=>{e?.({status:l?$:"paused",rate:P,lastEventAt:c[0]?.occurredAt??null})},[l,$,P,c,e]);const W=g.useMemo(()=>{const de=new Map;for(const K of p)K.tier&&de.set(K.name,K.tier);return de},[p]);g.useEffect(()=>{const de=window.setTimeout(()=>{k(T)},250);return()=>window.clearTimeout(de)},[T]);const L=g.useMemo(()=>iW(B,t),[B,t]),te=g.useRef(0);g.useEffect(()=>{const de=++te.current,K=new AbortController;return b("loading"),E(null),(async()=>{try{const Ee=await ht(new Request(Vd({...L,limit:qd}),{signal:K.signal}));if(!Ee.ok){const ye=await Ee.json().catch(()=>null),Se=ye?.code;throw Se==="UNKNOWN_PREFIX"||Se==="MALFORMED_CURSOR"?new Error(`${Se}: ${ye.error??Ee.status}`):new Error(`history fetch failed: ${Ee.status}`)}const re=await Ee.json(),D=Yd(re);if(!D)throw new Error("history response failed schema validation");if(de!==te.current)return;d(D.events),D.catalog&&m(D.catalog),S(D.nextCursor),N(D.hasMore),b("loaded")}catch(Ee){if(K.signal.aborted||de!==te.current)return;E(Ee instanceof Error?Ee.message:String(Ee)),b("error")}})(),()=>K.abort()},[L]);const ie=g.useCallback(async()=>{if(!(!v||A||y===null)){w(!0);try{const de=await ht(new Request(Vd({...L,limit:qd,cursor:y})));if(!de.ok)throw new Error(`history fetch failed: ${de.status}`);const K=await de.json(),Ee=Yd(K);if(!Ee)throw new Error("history response failed schema validation");d(re=>{const D=new Set(re.map(Se=>Se.id)),ye=Ee.events.filter(Se=>!D.has(Se.id));return[...re,...ye]}),Ee.catalog&&m(Ee.catalog),S(Ee.nextCursor),N(Ee.hasMore)}catch(de){E(de instanceof Error?de.message:String(de))}finally{w(!1)}}},[v,A,y,L]),be=g.useRef(T);be.current=T;const I=g.useRef(W);I.current=W,g.useEffect(()=>{if(!l||typeof EventSource>"u")return;V("connecting");const de=new EventSource(YG());return de.onopen=()=>{V("live")},de.onerror=()=>{V("errored")},de.onmessage=K=>{try{const Ee=JSON.parse(K.data),re=JG(Ee);if(!re||re.eventName==="connected")return;const D=be.current,ye=I.current;if(!jy({eventName:re.eventName,occurredAt:re.occurredAt,actor:re.actor,...re.prefix?{prefix:re.prefix}:{},payload:re.payload,view:re.view,...re.runId!==void 0?{runId:re.runId}:{}},D,ye))return;const Se={id:`live-${re.occurredAt}-${re.eventName}`,eventName:re.eventName,occurredAt:re.occurredAt,actor:re.actor,...re.prefix?{prefix:re.prefix}:{},...re.renderer?{renderer:re.renderer}:{},payload:re.payload,...re.envelope?{envelope:re.envelope}:{},view:re.view,...jl(re.runId,re.entityKind,re.entityId,re.sequence)};d(pe=>[Se,...pe]),H()}catch{}},()=>de.close()},[l,H]);const ne=g.useMemo(()=>Array.from(new Set([...p.map(de=>de.prefix),...c.map(de=>de.prefix??de.eventName.split(".")[0]??de.eventName)])).sort(),[p,c]),ue=g.useCallback(()=>{_(Hc)},[]),O=g.useMemo(()=>c.filter(de=>jy(de,T,W)),[c,T,W]),Ne=g.useMemo(()=>oW(O,a),[O,a]);return f==="error"?o.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load event history: ",x]}):f==="idle"||f==="loading"?o.jsxs("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:[o.jsx(Fa,{size:"sm"})," Loading event history…"]}):o.jsxs("div",{className:"flex flex-col gap-4","data-system-events-tab":!0,children:[o.jsx(HG,{filters:T,onFiltersChange:_,onClearFilters:ue,prefixOptions:ne,getPrefixColor:nN,liveEnabled:l,onToggleLive:()=>u(de=>!de),shownCount:O.length,totalCount:c.length,actions:o.jsx(VG,{visibleColumns:n,onVisibleColumnsChange:r})}),o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 overflow-hidden flex flex-col",children:[Ne.length===0?o.jsx("div",{className:"p-8 text-sm text-spur-text-muted italic text-center",children:c.length===0?"No system events yet. New events from the planning bus will appear here in real time.":"No events match the active filters."}):o.jsx(cW,{rows:Ne,catalog:p,visibleColumns:n,sortState:a,onSortChange:i}),v&&o.jsx("div",{className:"px-4 py-2 border-t border-base-content/10 bg-base-200/50 shrink-0 flex justify-center",children:o.jsx("button",{type:"button",onClick:ie,disabled:A,"data-load-older":!0,className:"text-[11px] text-spur-text-muted hover:text-spur-text px-3 py-1 rounded border border-spur-border/40 hover:border-spur-text/40 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait focus:outline-none focus:ring-2 focus:ring-spur-text/40",children:A?"Loading…":"Load older"})})]})]})}function uW(e){const[t,n]=g.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches);return g.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),a=s=>n(s.matches);return r.addEventListener("change",a),n(r.matches),()=>r.removeEventListener("change",a)},[e]),t}function cW({rows:e,catalog:t,visibleColumns:n=ra,sortState:r=$b,onSortChange:a=()=>{}}){const s=g.useMemo(()=>{const u=new Map;for(const c of t)c.tier&&u.set(c.name,c.tier);return u},[t]),i=uW("(max-width: 639px)"),l=g.useMemo(()=>new Map(us.map(u=>[u.key,u])),[]);return o.jsx("section",{className:"overflow-x-auto min-w-0","data-system-events-tab":!0,"aria-label":"System events",children:o.jsxs("table",{className:`w-full ${i?"min-w-0":"min-w-[1000px]"} text-xs border-separate border-spacing-0 table-fixed`,children:[o.jsx("colgroup",{children:i?o.jsxs(o.Fragment,{children:[o.jsx("col",{className:"w-24"}),o.jsx("col",{className:"w-full"})]}):n.map(u=>o.jsx("col",{className:l.get(u)?.colWidth??"w-24"},u))}),o.jsx("thead",{className:"sticky top-0 z-10 bg-base-200",children:o.jsx("tr",{className:"text-left text-spur-text-muted uppercase tracking-wide text-[10px]",children:i?o.jsxs(o.Fragment,{children:[o.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:"Time"}),o.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:"Event"})]}):n.map(u=>{const c=l.get(u);if(!c)return null;const d=r.key===u,p=d?r.direction==="asc"?" ▲":" ▼":"",m=d?r.direction==="asc"?"ascending":"descending":"none";return c.sortable?o.jsx("th",{scope:"col","aria-sort":m,className:"font-semibold px-3 py-1.5 border-b border-spur-border select-none",children:o.jsxs("button",{type:"button",onClick:()=>a(u),className:"flex items-center gap-1 uppercase tracking-wide text-[10px] font-semibold text-spur-text-muted hover:text-spur-text transition-colors cursor-pointer bg-transparent border-0 p-0 focus:outline-none focus:ring-1 focus:ring-primary/40 rounded",children:[o.jsx("span",{children:c.label}),p&&o.jsx("span",{"aria-hidden":"true",children:p})]})},u):o.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:c.label},u)})})}),o.jsx("tbody",{children:e.map(u=>o.jsx(dW,{event:u,tier:s.get(u.eventName)??"default",compact:i,visibleColumns:n},u.id))})]})})}const Gc="system-events-payload-tooltip-pin";function Wc({severity:e}){const t=g.useMemo(()=>{switch(e){case"error":return{icon:"✕",badgeClass:"bg-error/15 text-error border-error/30"};case"warning":return{icon:"▲",badgeClass:"bg-warning/15 text-warning border-warning/30"};default:return{icon:"●",badgeClass:"bg-base-content/10 text-base-content/70 border-base-content/20"}}},[e]);return o.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-semibold border ${t.badgeClass} whitespace-nowrap`,children:[o.jsx("span",{"aria-hidden":"true",children:t.icon}),o.jsx("span",{children:e})]})}function dW({event:e,tier:t,compact:n,visibleColumns:r=ra}){const a=e.prefix??e.eventName.split(".")[0]??e.eventName,s=g.useMemo(()=>e.view??Na(e.eventName,e.payload??null),[e.eventName,e.payload,e.view]),i=nN(a),[l,u]=g.useState(!1),[c,d]=g.useState(!1),[p,m]=g.useState(!1),[f,b]=g.useState(null),x=g.useRef(null),E=g.useRef(null),y=g.useRef(0),S=g.useRef(null),v=It(e.actor),N=c||p,A=g.useCallback(()=>{S.current!==null&&(clearTimeout(S.current),S.current=null)},[]),w=g.useCallback(()=>{m(!1),b(null)},[]),T=g.useCallback((P,H)=>{y.current=performance.now()+400,m(!0),d(!1),A();const W=Number.isFinite(P)&&P>0?P:8,L=Number.isFinite(H)&&H>0?H:8;b({x:W,y:L}),window.dispatchEvent(new CustomEvent(Gc,{detail:{id:e.id}}))},[e.id,A]),_=g.useCallback((P,H,W)=>{const L=P.getBoundingClientRect(),te=H&&H>0?H:L.left,ie=W&&W>0?W+4:L.bottom+6;T(te,ie)},[T]);g.useEffect(()=>{const P=H=>{H.detail?.id!==e.id&&w()};return window.addEventListener(Gc,P),()=>window.removeEventListener(Gc,P)},[e.id,w]),g.useEffect(()=>{if(!p)return;const P=W=>{performance.now()<y.current||x.current?.contains(W.target)||E.current?.contains(W.target)||w()},H=W=>{W.key==="Escape"&&(w(),W.stopPropagation())};return document.addEventListener("pointerdown",P,!0),document.addEventListener("keydown",H,!0),()=>{document.removeEventListener("pointerdown",P,!0),document.removeEventListener("keydown",H,!0)}},[p,w]),g.useEffect(()=>()=>{A()},[A]);const B=g.useCallback(()=>u(P=>!P),[]),k=g.useCallback(P=>{if(P.key==="Escape"){if(p){w(),P.stopPropagation();return}u(!1),P.stopPropagation()}},[p,w]),$=N?o.jsxs("div",{ref:x,id:`system-event-tooltip-${e.id}`,role:"tooltip","data-testid":"system-event-payload-tooltip","data-pinned":p?"true":"false",className:p?"pointer-events-auto fixed z-50 rounded shadow-lg p-2.5 text-[11px] min-w-[min(400px,90vw)] max-w-[min(840px,95vw)] whitespace-normal border border-[#30363d] bg-[#0d1117] text-[#c9d1d9] select-text cursor-text":"pointer-events-auto absolute left-0 top-full mt-1 z-30 rounded shadow-lg p-2.5 text-[11px] min-w-[min(400px,90vw)] max-w-[min(840px,95vw)] whitespace-normal border border-[#30363d] bg-[#0d1117] text-[#c9d1d9]",style:p&&f?{top:f.y,left:f.x}:void 0,onMouseEnter:()=>{A(),d(!0)},onMouseLeave:()=>{p||(A(),S.current=setTimeout(()=>d(!1),150))},onFocusCapture:()=>d(!0),onBlurCapture:P=>{!p&&!P.currentTarget.contains(P.relatedTarget)&&d(!1)},onPointerDown:P=>{p&&P.stopPropagation()},children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[o.jsx("div",{className:"text-[11px] font-sans font-semibold text-[#c9d1d9] truncate","data-testid":"system-event-tooltip-title",children:aW(e,s)}),o.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[!p&&o.jsx("button",{type:"button","data-testid":"system-event-payload-tooltip-pin",className:"text-[10px] text-[#c9d1d9] hover:text-white px-1.5 py-0.5 rounded border border-[#30363d] bg-[#21262d] cursor-pointer",onClick:P=>{P.stopPropagation(),P.preventDefault();const H=E.current;H?_(H):T(P.clientX,P.clientY)},children:"Pin"}),p&&o.jsx("button",{type:"button","data-testid":"system-event-payload-tooltip-close",className:"text-[10px] text-[#8b949e] hover:text-[#c9d1d9] px-1 rounded border border-[#30363d] cursor-pointer",onClick:P=>{P.stopPropagation(),w()},children:"close"})]})]}),o.jsx("p",{className:"mb-2 text-spur-text leading-relaxed","data-testid":"system-event-description",children:s.description}),o.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 max-h-80 overflow-y-auto",children:[o.jsx("dt",{className:"text-spur-text-muted",children:"Summary"}),o.jsx("dd",{className:"break-words",children:It(s.summary)}),o.jsx("dt",{className:"text-spur-text-muted",children:"Severity"}),o.jsx("dd",{children:o.jsx(Wc,{severity:s.severity})}),s.fields.map(P=>o.jsxs("div",{className:"contents",children:[o.jsx("dt",{className:"text-spur-text-muted",children:P.label}),o.jsx("dd",{className:"font-mono break-all",children:It(P.value)})]},P.label+P.value)),o.jsx("dt",{className:"text-spur-text-muted",children:"Producer"}),o.jsx("dd",{className:"font-mono break-all",children:It(s.producer)}),s.correlationFields.length>0?s.correlationFields.map(P=>o.jsxs("div",{className:"contents",children:[o.jsx("dt",{className:"text-spur-text-muted",children:P.label}),o.jsx("dd",{className:"font-mono break-all",children:It(P.value)})]},`correlation-${P.label}`)):o.jsxs(o.Fragment,{children:[o.jsx("dt",{className:"text-spur-text-muted",children:"Correlation"}),o.jsx("dd",{className:"font-mono",children:"-"})]}),o.jsx("dt",{className:"text-spur-text-muted",children:"Outcome"}),o.jsx("dd",{className:"font-mono break-all",children:It(s.outcome)})]}),s.action&&o.jsxs("div",{className:"mt-2 border-t border-[#30363d] pt-2","data-testid":"system-event-remediation",children:[o.jsx("div",{className:"text-spur-text-muted",children:s.action.label}),o.jsx("code",{className:"block mt-0.5 font-mono break-all select-text",children:s.action.value})]}),o.jsx("div",{className:"mt-2 border-t border-[#30363d] pt-1.5 text-[10px] text-[#8b949e] font-sans","data-testid":"system-event-tooltip-footer",children:p?"Select to copy · Esc or outside click to close":"Click event name or Pin to lock for copy"})]}):null,V=P=>{switch(P){case"time":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-spur-text-muted whitespace-nowrap align-middle",children:Fy(e.occurredAt)},"time");case"severity":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 align-middle text-[10px]",children:o.jsx(Wc,{severity:s.severity})},"severity");case"event":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 relative align-middle min-w-0",children:o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("button",{type:"button","aria-expanded":l,"aria-controls":`detail-${e.id}`,"aria-label":`${l?"Collapse":"Expand"} detail for ${e.eventName}`,onClick:B,onKeyDown:k,className:"inline-flex items-center justify-center w-4 h-4 text-spur-text-muted hover:text-spur-text text-[10px] transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-spur-text/40 shrink-0",children:l?"▾":"▸"}),o.jsxs("div",{className:"relative min-w-0 max-w-full flex items-center gap-1",children:[o.jsx("button",{ref:E,type:"button",className:`font-mono font-semibold truncate block max-w-full text-left cursor-pointer bg-transparent border-0 p-0 ${i}`,"data-testid":"system-event-name","aria-label":`Context for ${e.eventName}. Hover to preview; click to pin for select and copy.`,"aria-describedby":N?`system-event-tooltip-${e.id}`:void 0,onMouseEnter:()=>{A(),d(!0)},onFocus:()=>{A(),d(!0)},onBlur:H=>{!p&&!x.current?.contains(H.relatedTarget)&&d(!1)},onMouseLeave:()=>{A(),S.current=setTimeout(()=>{p||d(!1)},200)},onClick:H=>{H.preventDefault(),H.stopPropagation(),!p&&_(H.currentTarget,H.clientX,H.clientY)},onKeyDown:H=>{if(H.key==="Enter"||H.key===" "){if(H.preventDefault(),p)return;_(H.currentTarget)}},children:e.eventName}),o.jsx(Vo,{value:e.eventName,label:"event name"}),!p&&$]})]})},"event");case"summary":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 text-spur-text align-middle truncate",title:It(s.summary),children:It(s.summary)},"summary");case"correlation":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle",children:o.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[o.jsx("span",{className:"truncate",title:It(s.correlation),children:It(s.correlation)}),s.correlation&&s.correlation!=="unavailable"&&o.jsx(Vo,{value:s.correlation,label:"correlation"})]})},"correlation");case"outcome":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:It(s.outcome),children:It(s.outcome)},"outcome");case"agent":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:s.agent??"",children:s.agent??""},"agent");case"producer":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:It(s.producer),children:It(s.producer)},"producer");case"action":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:It(s.actionLabel),children:It(s.actionLabel)},"action");case"actor":return o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle truncate",title:v,children:v},"actor")}};return o.jsxs(o.Fragment,{children:[o.jsx("tr",{className:"group hover:bg-base-200/60 transition-colors",style:{height:n?void 0:28},children:n?o.jsxs(o.Fragment,{children:[o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-spur-text-muted whitespace-nowrap align-middle",children:Fy(e.occurredAt)}),o.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 relative align-middle min-w-0",children:o.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("button",{type:"button","aria-expanded":l,"aria-controls":`detail-${e.id}`,"aria-label":`${l?"Collapse":"Expand"} detail for ${e.eventName}`,onClick:B,onKeyDown:k,className:"inline-flex items-center justify-center w-4 h-4 text-spur-text-muted hover:text-spur-text text-[10px] transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-spur-text/40 shrink-0",children:l?"▾":"▸"}),o.jsxs("div",{className:"relative min-w-0 max-w-full flex items-center gap-1",children:[o.jsx("button",{ref:E,type:"button",className:`font-mono font-semibold truncate block max-w-full text-left cursor-pointer bg-transparent border-0 p-0 ${i}`,"data-testid":"system-event-name","aria-label":`Context for ${e.eventName}. Hover to preview; click to pin for select and copy.`,"aria-describedby":N?`system-event-tooltip-${e.id}`:void 0,onMouseEnter:()=>{A(),d(!0)},onFocus:()=>{A(),d(!0)},onBlur:P=>{!p&&!x.current?.contains(P.relatedTarget)&&d(!1)},onMouseLeave:()=>{A(),S.current=setTimeout(()=>{p||d(!1)},200)},onClick:P=>{P.preventDefault(),P.stopPropagation(),!p&&_(P.currentTarget,P.clientX,P.clientY)},onKeyDown:P=>{if(P.key==="Enter"||P.key===" "){if(P.preventDefault(),p)return;_(P.currentTarget)}},children:e.eventName}),o.jsx(Vo,{value:e.eventName,label:"event name"}),!p&&$]})]}),o.jsxs("div",{className:"flex flex-col gap-0.5 text-[10px] text-spur-text-muted min-w-0",children:[o.jsx(Wc,{severity:s.severity}),o.jsx("span",{className:"truncate text-spur-text",title:It(s.summary),children:It(s.summary)}),o.jsx("span",{className:"truncate",title:It(s.producer),children:It(s.producer)}),o.jsx("span",{className:"truncate",title:It(s.correlation),children:It(s.correlation)}),s.agent&&o.jsxs("span",{className:"truncate font-mono",title:s.agent,children:["agent: ",s.agent]}),o.jsxs("span",{className:"truncate",children:["outcome: ",It(s.outcome)]}),o.jsxs("span",{className:"truncate",title:It(s.actionLabel),children:["action: ",It(s.actionLabel)]})]})]})})]}):r.map(P=>V(P))}),l&&o.jsx("tr",{children:o.jsx("td",{colSpan:n?2:r.length,className:"px-3 py-2 border-b border-spur-border/40 bg-base-300/40",children:o.jsxs("section",{id:`detail-${e.id}`,"aria-label":`Detail for ${e.eventName}`,onKeyDown:k,tabIndex:-1,className:"flex flex-col gap-2 text-[11px] text-spur-text max-w-full",children:[o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 font-mono text-[10px]",children:[o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"project:"})," ",It(s.projectName)]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"root:"})," ",It(s.projectRoot)]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"producer:"})," ",It(s.producer)]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"correlation:"})," ",It(s.correlation)]}),e.runId&&o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx("span",{className:"text-spur-text-muted",children:"runId:"})," ",e.runId," ",o.jsx(Vo,{value:e.runId,label:"run ID"})]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"agent:"})," ",s.agent||"-"]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"actor:"})," ",v]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"prefix:"})," ",a]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"tier:"})," ",t]}),o.jsxs("span",{children:[o.jsx("span",{className:"text-spur-text-muted",children:"outcome:"})," ",It(s.outcome)]})]}),s.fields.length>0&&o.jsx("dl",{className:"space-y-0.5",children:s.fields.map(P=>o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("dt",{className:"text-spur-text-muted shrink-0",children:[P.label,":"]}),o.jsx("dd",{className:"font-mono break-all",children:It(P.value)})]},P.label+P.value))}),o.jsxs("div",{className:"border-t border-spur-border/40 pt-1",children:[o.jsx("div",{className:"text-spur-text-muted text-[10px] mb-0.5",children:"payload (redacted):"}),o.jsx("pre",{className:"font-mono text-[10px] text-spur-text-muted overflow-x-auto whitespace-pre-wrap break-all",children:e.envelope?JSON.stringify(e.envelope,null,2):"-"})]}),o.jsx("button",{type:"button",onClick:()=>u(!1),className:"self-start text-[10px] text-spur-text-muted hover:text-error px-2 py-0.5 rounded border border-spur-border/40 hover:border-error/40 transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-spur-text/40",children:"Close (Esc)"})]})})}),p&&$&&typeof document<"u"?na.createPortal($,document.body):null]})}function pW(e){if(!e.payload)return;if(typeof e.payload.jobId=="string")return e.payload.jobId;const n=e.payload.context?.correlation;if(typeof n?.jobId=="string")return n.jobId}function fW(e){switch(e){case"completed":return"success";case"processing":return"info";case"failed":return"error";default:return"neutral"}}function mW({job:e,onClose:t,onNavigate:n}){const[r,a]=g.useState([]),[s,i]=g.useState(null),[l,u]=g.useState(!1),c=g.useRef(0);return g.useEffect(()=>{if(!e){a([]),i(null);return}const d=f=>{f.key==="Escape"&&t()};window.addEventListener("keydown",d);const p=new AbortController,m=++c.current;return u(!0),(async()=>{try{const f=Vd({prefix:"queue",since:e.queuedAt,limit:200}),b=await ht(new Request(f,{signal:p.signal}));if(!b.ok)throw new Error(`HTTP ${b.status}`);const x=Yd(await b.json());if(p.signal.aborted||m!==c.current)return;const E=(x?.events??[]).filter(S=>pW(S)===e.id);i(E.length);const y=E.map(S=>{const v=S.payload;return{id:S.id,eventName:S.eventName,occurredAt:S.occurredAt,error:typeof v?.error=="string"?v.error:void 0,attempt:typeof v?.attempt=="number"?v.attempt:void 0}});e.startedAt&&y.push({id:`synth-started-${e.id}`,eventName:"queue.job.started",occurredAt:e.startedAt,derived:!0}),y.sort((S,v)=>new Date(S.occurredAt).getTime()-new Date(v.occurredAt).getTime()),a(y)}catch{if(p.signal.aborted||m!==c.current)return;i(0);const f=[];e.startedAt&&f.push({id:`synth-started-${e.id}`,eventName:"queue.job.started",occurredAt:e.startedAt,derived:!0}),a(f)}finally{!p.signal.aborted&&m===c.current&&u(!1)}})(),()=>{window.removeEventListener("keydown",d),p.abort()}},[e,t]),e?o.jsx("div",{className:"fixed inset-0 z-50 flex justify-end bg-black/60 backdrop-blur-xs",onClick:t,onKeyDown:d=>{d.key==="Escape"&&t()},role:"dialog","aria-modal":"true","aria-label":`Job details for ${e.id}`,"data-testid":"job-detail-drawer",children:o.jsxs("div",{className:"w-full max-w-xl h-full bg-base-100 border-l border-base-content/10 shadow-2xl flex flex-col overflow-hidden",onClick:d=>d.stopPropagation(),onKeyDown:d=>d.stopPropagation(),role:"document",children:[o.jsxs("div",{className:"px-5 py-4 border-b border-base-content/10 flex items-center justify-between bg-base-200/50",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(gn,{variant:fW(e.status),size:"sm",children:e.status}),o.jsx("span",{className:"font-mono text-sm font-semibold text-base-content truncate max-w-xs",children:e.id})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[n&&o.jsx(ot,{variant:"outline",size:"xs","data-testid":"navigate-system-events-btn",onClick:()=>n({tab:"system-events",runId:e.id}),children:"View in System Events"}),o.jsx(ot,{variant:"ghost",size:"xs",onClick:t,"aria-label":"Close drawer","data-testid":"close-job-drawer",children:"✕"})]})]}),o.jsxs("div",{className:"p-5 flex-1 overflow-y-auto space-y-5",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3 bg-base-200/40 p-3 rounded-lg border border-base-content/10 text-xs font-mono",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Type"}),o.jsx("span",{className:"font-semibold text-base-content",children:e.type})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Attempts"}),o.jsxs("span",{className:"text-base-content",children:[e.attempts," / ",e.maxRetries]})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Queued At"}),o.jsx("span",{className:"text-base-content",children:new Date(e.queuedAt).toLocaleString()})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Started At"}),o.jsx("span",{className:"text-base-content",children:e.startedAt?new Date(e.startedAt).toLocaleString():"—"})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Ended At"}),o.jsx("span",{className:"text-base-content",children:e.endedAt?new Date(e.endedAt).toLocaleString():"—"})]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Duration"}),o.jsx("span",{className:"text-base-content",children:e.durationMs!==null?aN(e.durationMs):"—"})]})]}),e.lastError&&o.jsxs("div",{className:"p-3 rounded-lg bg-error/10 border border-error/20 text-error text-xs font-mono whitespace-pre-wrap break-words",children:[o.jsx("span",{className:"font-bold block mb-1",children:"Last Error:"}),e.lastError]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Payload"}),o.jsx("div",{className:"bg-base-200 p-3 rounded-lg border border-base-content/10 font-mono text-xs overflow-x-auto max-h-48 text-base-content/90",children:e.payload?o.jsx("pre",{className:"whitespace-pre-wrap",children:JSON.stringify(e.payload,null,2)}):o.jsx("span",{className:"text-base-content/50 italic",children:"payload unavailable"})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Lifecycle Timeline"}),l&&o.jsx("span",{className:"text-[10px] text-base-content/50",children:"Loading…"})]}),s===0&&!l&&o.jsxs("div",{className:"p-4 rounded-lg border border-base-content/10 bg-base-200/40 text-xs text-base-content/60 italic","data-testid":"empty-lifecycle-timeline",children:["No lifecycle events recorded. Queue lifecycle events are diagnostic-tier — set"," ",o.jsx("code",{className:"font-mono text-base-content",children:"SPUR_DIAGNOSTIC_EVENTS=1"})," to capture them."]}),r.length>0&&o.jsx("div",{className:"space-y-2 font-mono text-xs","data-testid":"lifecycle-timeline-list",children:r.map(d=>o.jsxs("div",{className:"p-2.5 rounded-lg border border-base-content/10 bg-base-200/60 flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[o.jsx("span",{className:"font-semibold text-base-content",children:d.eventName}),d.derived&&o.jsx(gn,{size:"xs",variant:"outline",children:"derived"}),d.attempt!==void 0&&o.jsxs(gn,{size:"xs",variant:"neutral",children:["attempt ",d.attempt]}),d.error&&o.jsx("span",{className:"text-error truncate max-w-xs",children:d.error})]}),o.jsx("span",{className:"text-[11px] text-base-content/50 shrink-0",children:new Date(d.occurredAt).toLocaleTimeString()})]},d.id))})]})]})]})}):null}function hW(e){switch(e){case"failed":return"failed";case"running":return"processing";case"completed":return"completed";default:return}}function gW(e){switch(e){case"completed":return"success";case"processing":return"info";case"failed":return"error";default:return"neutral"}}const bW=()=>{const[e,t]=g.useState(null),[n,r]=g.useState(null),[a,s]=g.useState(!0);return g.useEffect(()=>{const i=new AbortController;return(async()=>{try{const l=await ht(new Request(`${Ct()}/jobs/schedules`,{signal:i.signal}));if(!l.ok)throw new Error(`HTTP ${l.status}`);const u=await l.json();if(i.signal.aborted)return;t(u.schedules)}catch(l){if(i.signal.aborted)return;r(l instanceof Error?l.message:String(l))}finally{i.signal.aborted||s(!1)}})(),()=>i.abort()},[]),o.jsxs("div",{className:"p-4 rounded-xl border border-base-content/10 bg-base-200/80 shadow-xs space-y-3","data-testid":"active-schedules-card",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/70",children:"Active Schedules"}),e&&o.jsx(gn,{size:"xs",variant:"outline",children:e.length})]}),o.jsx("span",{className:"text-[11px] text-base-content/50",children:"Recurring background cron jobs"})]}),a?o.jsx("div",{className:"text-xs text-base-content/50 py-2",children:"Loading schedules…"}):n?o.jsxs("div",{className:"text-xs text-error/80 py-1","data-testid":"schedules-error",children:["Schedules unavailable: ",n]}):!e||e.length===0?o.jsx("div",{className:"text-xs text-base-content/50 py-2 italic",children:"No active schedules registered."}):o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2.5 font-mono text-xs",children:e.map(i=>o.jsxs("div",{className:"p-2.5 rounded-lg border border-base-content/10 bg-base-100 flex flex-col gap-1.5","data-testid":`schedule-item-${i.name}`,children:[o.jsxs("div",{className:"flex items-center justify-between gap-1",children:[o.jsx("span",{className:"font-semibold text-base-content truncate",children:i.name}),o.jsx(gn,{size:"xs",variant:i.source==="builtin"?"neutral":"info",children:i.source})]}),o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-base-content/60",children:[o.jsx("span",{children:i.cadence}),o.jsx("span",{className:"text-base-content/40",children:i.cron})]}),o.jsxs("div",{className:"flex items-center justify-between text-[10px] text-base-content/50 border-t border-base-content/5 pt-1 mt-0.5",children:[o.jsx("span",{children:i.nextFireAt===null?"next run: cron (unknown)":`next: ${new Date(i.nextFireAt).toLocaleTimeString()}`}),o.jsx("span",{children:i.lastStatus==="none"?"never run":i.lastStatus})]})]},i.name))})]})};function xW({timeRange:e,onNavigate:t}){const[n,r]=g.useState("all"),[a,s]=g.useState([]),[i,l]=g.useState({all:0,pending:0,processing:0,completed:0,failed:0}),[u,c]=g.useState(!1),[d,p]=g.useState(0),[m,f]=g.useState(!0),[b,x]=g.useState(null),[E,y]=g.useState(new Set),[S,v]=g.useState(null),N=g.useRef(0),A=g.useRef({timeRange:e,statusFilter:n});g.useEffect(()=>{const _=new AbortController,B=++N.current;return f(!0),x(null),(async()=>{try{const k=A.current.timeRange!==e||A.current.statusFilter!==n;k&&(A.current={timeRange:e,statusFilter:n});const $=k?0:d;k&&d!==0&&p(0);const V=Pu(e),P=new URLSearchParams,H=hW(n);H&&P.set("status",H),V&&P.set("since",V),P.set("limit","100"),P.set("offset",String($));const W=await ht(new Request(`${Ct()}/jobs?${P.toString()}`,{signal:_.signal}));if(!W.ok){const te=await W.text();throw new Error(`HTTP ${W.status}: ${te||W.statusText}`)}const L=await W.json();if(_.signal.aborted||B!==N.current)return;s($===0?L.jobs:te=>[...te,...L.jobs]),l(L.countsByStatus),c(L.hasMore),f(!1)}catch(k){if(_.signal.aborted||B!==N.current)return;x(k instanceof Error?k.message:String(k)),f(!1)}})(),()=>_.abort()},[e,n,d]);const w=(_,B)=>{B.stopPropagation(),y(k=>{const $=new Set(k);return $.has(_)?$.delete(_):$.add(_),$})},T=[{id:"all",label:"All",count:i.all},{id:"failed",label:"Failed",count:i.failed},{id:"running",label:"Running",count:i.processing},{id:"completed",label:"Completed",count:i.completed}];return o.jsxs("div",{className:"flex flex-col gap-4","data-jobs-tab":!0,"data-testid":"observability-jobs-tab",children:[o.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[o.jsx("div",{className:"flex items-center gap-1.5","data-testid":"job-status-chips",children:T.map(_=>{const B=n===_.id;return o.jsxs("button",{type:"button",onClick:()=>r(_.id),"data-testid":`status-chip-${_.id}`,className:`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-semibold rounded-full transition-colors cursor-pointer ${B?_.id==="failed"?"bg-error text-error-content":"bg-neutral text-neutral-content":"bg-base-100 text-base-content/70 hover:bg-base-200 border border-base-content/10"}`,children:[o.jsx("span",{children:_.label}),o.jsx("span",{className:`px-1.5 py-0.2 text-[10px] rounded-full ${B?"bg-base-100/20":"bg-base-200 text-base-content/70"}`,children:_.count.toLocaleString()})]},_.id)})}),o.jsx(eN,{})]}),i.failed>0&&o.jsxs("div",{className:"p-3 rounded-xl bg-error/10 border border-error/20 flex items-center justify-between text-xs text-error font-medium","data-testid":"jobs-failure-banner",children:[o.jsxs("span",{children:["⚠️ ",i.failed," ",i.failed===1?"job":"jobs"," failed in this window"]}),o.jsx("button",{type:"button",className:"px-2.5 py-1 text-xs font-semibold rounded-lg border border-error text-error hover:bg-error hover:text-error-content transition-colors cursor-pointer","data-testid":"filter-to-failed-btn",onClick:()=>r("failed"),children:"Filter to Failed"})]}),o.jsx(bW,{}),o.jsxs("div",{className:"rounded-xl border border-base-content/10 bg-base-200/50 shadow-xs overflow-hidden flex flex-col",children:[o.jsxs("div",{className:"px-4 py-3 border-b border-base-content/10 bg-base-200 flex items-center justify-between flex-wrap gap-2",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/70",children:"Queue Jobs"}),o.jsxs("span",{className:"text-xs text-base-content/50 font-mono",children:["Showing ",a.length," of ",i.all," job(s)"]})]}),b?o.jsxs("div",{className:"p-4 text-xs text-error",role:"alert","data-testid":"jobs-table-error",children:["Failed to load jobs: ",b]}):m&&a.length===0?o.jsxs("div",{className:"flex items-center justify-center h-32 text-base-content/50 text-sm",children:[o.jsx(Fa,{size:"sm"})," Loading jobs…"]}):a.length===0?o.jsx("div",{className:"p-8 text-center text-xs text-base-content/50 italic","data-testid":"jobs-empty-state",children:"No jobs found in this time range."}):o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"table table-xs w-full font-mono text-xs","data-testid":"queue-jobs-table",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{children:"Status"}),o.jsx("th",{children:"Job Type"}),o.jsx("th",{children:"Enqueued At"}),o.jsx("th",{children:"Started At"}),o.jsx("th",{children:"Duration"}),o.jsx("th",{children:"Attempts"}),o.jsx("th",{children:"Error"})]})}),o.jsx("tbody",{children:a.map(_=>{const B=E.has(_.id);return o.jsxs("tr",{className:"hover:bg-base-300/40 cursor-pointer transition-colors",onClick:()=>v(_),"data-testid":`job-row-${_.id}`,children:[o.jsx("td",{children:o.jsx(gn,{size:"xs",variant:gW(_.status),children:_.status})}),o.jsx("td",{className:"font-semibold text-base-content",children:_.type}),o.jsx("td",{className:"text-base-content/60",children:new Date(_.queuedAt).toLocaleTimeString()}),o.jsx("td",{className:"text-base-content/60",children:_.startedAt?new Date(_.startedAt).toLocaleTimeString():"—"}),o.jsx("td",{className:"text-base-content/80",children:_.durationMs!==null?aN(_.durationMs):"—"}),o.jsxs("td",{className:"text-base-content/60",children:[_.attempts," / ",_.maxRetries]}),o.jsx("td",{className:"max-w-xs",children:_.lastError?o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("div",{className:`text-error ${B?"whitespace-pre-wrap":"truncate"}`,"data-testid":`job-error-${_.id}`,children:_.lastError}),o.jsx("button",{type:"button",className:"text-[10px] text-base-content/60 hover:text-base-content underline self-start","data-testid":`expand-error-btn-${_.id}`,onClick:k=>w(_.id,k),children:B?"Hide":"Details"})]}):null})]},_.id)})})]})}),u&&o.jsx("div",{className:"p-3 border-t border-base-content/10 flex justify-center bg-base-200/30",children:o.jsx(ot,{variant:"ghost",size:"xs",disabled:m,onClick:()=>p(_=>_+100),"data-testid":"jobs-load-more-btn",children:m?"Loading…":"Load more"})})]}),o.jsx(mW,{job:S,onClose:()=>v(null),onNavigate:t})]})}function Py(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.inputTokens!="number"||typeof t.outputTokens!="number"||typeof t.cacheReadTokens!="number"||typeof t.cacheCreationTokens!="number"||typeof t.records!="number"||typeof t.recordsWithUsage!="number"?null:{inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheReadTokens:t.cacheReadTokens,cacheCreationTokens:t.cacheCreationTokens,records:t.records,recordsWithUsage:t.recordsWithUsage}}function EW(e){if(e===null||typeof e!="object")return null;const t=e;return!(t.role===null||typeof t.role=="string")||typeof t.totalRuns!="number"||typeof t.matchedRuns!="number"||typeof t.unmeasured!="boolean"?null:{role:t.role,totalRuns:t.totalRuns,matchedRuns:t.matchedRuns,exact:Py(t.exact),estimated:Py(t.estimated),unmeasured:t.unmeasured}}function yW(e){if(e===null||typeof e!="object")return null;const t=e;return!(t.role===null||typeof t.role=="string")||typeof t.executor!="string"||!(t.source===null||typeof t.source=="string")||typeof t.runs!="number"||typeof t.escalations!="number"?null:{role:t.role,executor:t.executor,source:t.source,runs:t.runs,escalations:t.escalations}}function TW(e){if(e===null||typeof e!="object")return null;const t=e,n=t.routing,r=t.tokens;if(n===null||typeof n!="object"||r===null||typeof r!="object")return null;const a=n,s=r,i=a.window;if(i===null||typeof i!="object")return null;const l=i;if(typeof l.since!="string"||typeof l.until!="string"||!Array.isArray(a.pairs)||!Array.isArray(s.roles))return null;const u=[];for(const d of a.pairs){const p=yW(d);p&&u.push(p)}const c=[];for(const d of s.roles){const p=EW(d);p&&c.push(p)}return{window:{since:l.since,until:l.until},pairs:u,roles:c}}function SW(e){switch(e){case"explicit":return"pinned";case"role":return"resolved";case"default":return"default";case null:return"—";default:return e}}const vW=new Intl.NumberFormat("en-US");function as(e){return vW.format(e)}function By({label:e,totals:t}){return o.jsxs("div",{"data-token-bucket":e,className:"text-xs",children:[o.jsx(gn,{size:"xs",variant:e==="estimated"?"warning":"success",children:e}),o.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-0.5 mt-1",children:[o.jsx("dt",{className:"text-spur-text-muted",children:"input"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.inputTokens)}),o.jsx("dt",{className:"text-spur-text-muted",children:"cache read"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.cacheReadTokens)}),o.jsx("dt",{className:"text-spur-text-muted",children:"cache write"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.cacheCreationTokens)}),o.jsx("dt",{className:"text-spur-text-muted",children:"output"}),o.jsx("dd",{className:"tabular-nums text-right",children:as(t.outputTokens)})]})]})}function wW({role:e}){const t=e.role??"—";return o.jsxs("div",{className:"bg-base-100 border border-spur-border rounded-md p-3","data-role-attribution":t,children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-sm font-semibold text-spur-text",children:t}),o.jsxs("span",{className:"text-[10px] text-spur-text-muted tabular-nums",children:["matched ",e.matchedRuns," of ",e.totalRuns," runs"]})]}),e.unmeasured?o.jsxs("div",{className:"mt-1 text-xs","data-unmeasured":!0,children:[o.jsx(gn,{size:"xs",variant:"ghost",children:"unmeasured"}),o.jsx("span",{className:"ml-1 text-spur-text-muted",children:"no token data recorded for this role — not a measured zero"})]}):o.jsxs("div",{className:"mt-2 flex flex-wrap gap-4",children:[e.exact?o.jsx(By,{label:"exact",totals:e.exact}):null,e.estimated?o.jsx(By,{label:"estimated",totals:e.estimated}):null]})]})}function NW({timeRange:e}){const[t,n]=g.useState(null),[r,a]=g.useState(null);if(g.useEffect(()=>{const i=new AbortController,l=Pu(e),u=Ct(),c=l?`${u}/observability/routing-summary?since=${encodeURIComponent(l)}`:`${u}/observability/routing-summary`;return(async()=>{try{const d=await ht(new Request(c,{signal:i.signal}));if(!d.ok)throw new Error(`routing summary fetch failed: ${d.status}`);const p=TW(await d.json());if(!p)throw new Error("routing summary response failed schema validation");n(p)}catch(d){if(i.signal.aborted)return;a(d instanceof Error?d.message:String(d))}})(),()=>i.abort()},[e]),r)return o.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load routing summary: ",r]});if(t===null)return o.jsxs("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:[o.jsx(Fa,{size:"sm"})," Loading routing summary…"]});const s=t.pairs.length===0&&t.roles.length===0;return o.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-routing-tab":!0,children:[o.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-base-200 shrink-0 flex items-baseline justify-between",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Routing & token consumption"}),o.jsxs("span",{className:"text-[10px] text-spur-text-muted tabular-nums","data-covered-window":!0,children:["covered ",t.window.since," → ",t.window.until]})]}),s?o.jsx("div",{className:"flex-1 flex items-center justify-center p-4","data-routing-empty":!0,children:o.jsx("div",{className:"text-sm text-spur-text-muted italic",children:"No routing attribution has been recorded in the covered window — nothing to show yet."})}):o.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[t.pairs.length>0?o.jsxs("section",{className:"bg-base-100 border border-spur-border rounded-md","data-routing-table":!0,children:[o.jsxs("div",{className:"px-3 py-2 border-b border-spur-border",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Role → executor"}),o.jsx("span",{className:"ml-2 text-[10px] text-spur-text-muted",children:"runs and escalations per pair; pinned and role-resolved counted separately"})]}),o.jsxs("table",{className:"table table-sm w-full",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"text-[10px] uppercase text-spur-text-muted",children:[o.jsx("th",{children:"Role"}),o.jsx("th",{children:"Executor"}),o.jsx("th",{children:"Source"}),o.jsx("th",{className:"text-right",children:"Runs"}),o.jsx("th",{className:"text-right",children:"Escalations"})]})}),o.jsx("tbody",{children:t.pairs.map(i=>o.jsxs("tr",{children:[o.jsx("td",{className:"text-sm text-spur-text",children:i.role??"—"}),o.jsx("td",{className:"text-sm text-spur-text",children:i.executor}),o.jsx("td",{children:o.jsx(gn,{size:"xs",variant:i.source==="explicit"?"warning":"ghost",children:SW(i.source)})}),o.jsx("td",{className:"text-right tabular-nums text-spur-text",children:as(i.runs)}),o.jsx("td",{className:"text-right tabular-nums text-spur-text",children:as(i.escalations)})]},`${i.role??""}:${i.executor}:${i.source??""}`))})]}),o.jsx("div",{className:"px-3 py-1.5 border-t border-spur-border text-[10px] text-spur-text-muted",children:"“—” role groups pure pins (no role recorded); escalations count runs that started too cheap on this executor."})]}):null,t.roles.length>0?o.jsxs("section",{"data-token-section":!0,children:[o.jsxs("div",{className:"px-1 pb-1.5",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Token consumption by role"}),o.jsx("span",{className:"ml-2 text-[10px] text-spur-text-muted",children:"input, cache read, cache write, output — token totals only"})]}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:t.roles.map(i=>o.jsx(wW,{role:i},i.role??"pin"))})]}):null]})]})}const AW={system:"#38bdf8",task:"#818cf8",feature:"#a78bfa",queue:"#f59e0b",scheduler:"#10b981",rule:"#ec4899",agent:"#06b6d4",history:"#64748b"},Uy=["#38bdf8","#818cf8","#a78bfa","#f59e0b","#10b981","#ec4899","#06b6d4","#f43f5e","#64748b"];function qc(e){const t=AW[e];if(t)return t;let n=0;for(let a=0;a<e.length;a++)n=(n<<5)-n+e.charCodeAt(a),n|=0;const r=Math.abs(n)%Uy.length;return Uy[r]??"#38bdf8"}function _W(e){return e==null||!Number.isFinite(e)?"—":(e/1e3).toFixed(2)}const kW=(e,t)=>t===void 0||t===0?null:(e-t)/Math.abs(t)*100,CW=g.memo(({current:e,previous:t,invert:n=!1})=>{if(t===void 0)return o.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});if(t===0)return o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-bold font-mono bg-info/15 text-info",children:"new"});const r=kW(e,t);if(r===null)return o.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});const a=r>=0,s=n?!a:a;return o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold font-mono ${s?"bg-emerald-500/15 text-emerald-400":"bg-error/15 text-error"}`,children:[a?"↑ +":"↓ ",Math.abs(r).toFixed(1),"% vs previous period"]})}),Yo=g.memo(({label:e,value:t,sub:n,trend:r,trendColor:a="#38bdf8",current:s,previous:i,invert:l,testId:u})=>o.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-4","data-testid":u,children:[o.jsx("div",{className:"flex justify-between items-center",children:o.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:e})}),o.jsxs("div",{className:"flex items-end justify-between gap-2 mt-1",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-2xl font-bold font-mono text-primary",children:t}),o.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[o.jsx(CW,{current:s,previous:i,invert:l}),o.jsx("span",{className:"text-xs text-base-content/60",children:n})]})]}),r&&r.length>1?o.jsx(zw,{values:r,color:a,width:100,height:34}):null]})]}));function IW(e){const t=g.useRef(0),[n,r]=g.useState(null),[a,s]=g.useState(null),[i,l]=g.useState(!0),[u,c]=g.useState(null),d=e.timeRange??"4h";g.useEffect(()=>{const A=++t.current,w=new AbortController;l(!0),c(null);async function T(){try{const _=Date.now(),B=Pu(d,_),k=new Date(_).toISOString();let $=`${Ct()}/observability/summary`;if(B){const ie=new URLSearchParams({since:B,until:k});$+=`?${ie.toString()}`}const V=ht(new Request($,{signal:w.signal}),1e4);let P=Promise.resolve(null);if(B){const ie=new Date(B).getTime(),be=_-ie,I=new Date(ie-be).toISOString(),ne=B,ue=new URLSearchParams({since:I,until:ne,period:"previous"}),O=`${Ct()}/observability/summary?${ue.toString()}`;P=ht(new Request(O,{signal:w.signal}),1e4).catch(()=>null)}const[H,W]=await Promise.all([V,P]);if(A!==t.current)return;if(!H.ok){const ie=await H.text();throw new Error(`HTTP ${H.status}: ${ie||H.statusText}`)}const L=await H.json();let te=null;if(W?.ok)try{te=await W.json()}catch{}if(A!==t.current)return;r(L),s(te),l(!1)}catch(_){if(w.signal.aborted||A!==t.current)return;c(_ instanceof Error?_.message:String(_)),l(!1)}}return T(),()=>{w.abort()}},[d]);const{series:p,chartBuckets:m}=g.useMemo(()=>{const A=n?.eventVolumeBuckets??[],w={};for(const k of A)for(const[$,V]of Object.entries(k.byPrefix))w[$]=(w[$]??0)+V;const _=Object.keys(w).sort((k,$)=>(w[$]??0)-(w[k]??0)).map(k=>({id:k,label:k,color:qc(k)})),B=A.map(k=>({id:k.timestamp,label:Ol(k.timestamp),v:k.byPrefix}));return{series:_,chartBuckets:B}},[n?.eventVolumeBuckets]),f=g.useMemo(()=>{const A={info:0,warning:0,error:0,unknown:0};for(const T of n?.eventVolumeBuckets??[])A.info+=T.bySeverity.info,A.warning+=T.bySeverity.warning,A.error+=T.bySeverity.error,A.unknown+=T.bySeverity.unknown;const w=A.info+A.warning+A.error+A.unknown;return{counts:A,sum:w}},[n?.eventVolumeBuckets]);if(i)return o.jsxs("div",{className:"flex flex-col gap-6 animate-pulse","data-testid":"observability-summary-tab","data-summary-tab":!0,children:[o.jsx("div",{"data-testid":"observability-summary-skeleton",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[1,2,3,4].map(A=>o.jsx("div",{className:"h-24 bg-base-200/60 rounded-xl"},A))}),o.jsx("div",{className:"h-64 bg-base-200/60 rounded-xl"})]});if(u)return o.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error","data-testid":"observability-summary-error","data-summary-tab":!0,children:o.jsxs("span",{children:["Failed to load observability summary: ",u]})});const b=n?.kpis??{totalEvents:0,activeJobs:0,completedJobs:0,failedJobs:0,successRatePct:0,errorEventCount:0,warningEventCount:0},x=a?.kpis,E=n?.eventVolumeBuckets??[],y=E.map(A=>A.total),S=E.map(A=>A.bySeverity.error+A.bySeverity.warning),v=A=>{e.onNavigate?.({tab:"jobs",jobId:A})},N=(A,w)=>{e.onNavigate?.({tab:"system-events",eventName:A,runId:w})};return o.jsxs("div",{className:"flex flex-col gap-6","data-testid":"observability-summary-tab","data-summary-tab":!0,children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[o.jsx(Yo,{label:"Total Events",value:Wt(b.totalEvents),sub:"events in window",trend:y,trendColor:"#38bdf8",current:b.totalEvents,previous:x?.totalEvents,testId:"kpi-card-total-events"}),o.jsx(Yo,{label:"Active In-Flight Jobs",value:Wt(b.activeJobs),sub:"pending & processing",current:b.activeJobs,previous:x?.activeJobs,testId:"kpi-card-active-jobs"}),o.jsx(Yo,{label:"Success Rate",value:`${b.successRatePct}%`,sub:`${b.completedJobs} ok / ${b.failedJobs} fail`,current:b.successRatePct,previous:x?.successRatePct,testId:"kpi-card-success-rate"}),o.jsx(Yo,{label:"Errors & Warnings",value:`${b.errorEventCount} / ${b.warningEventCount}`,sub:"error / warning events",trend:S,trendColor:"#ef4444",current:b.errorEventCount+b.warningEventCount,previous:x?x.errorEventCount+x.warningEventCount:void 0,invert:!0,testId:"kpi-card-errors-warnings"})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[o.jsx("div",{className:"flex justify-between items-center",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Event Volume Over Time"}),o.jsx("p",{className:"text-xs text-base-content/60 mt-0.5",children:"Distribution stacked by event prefix"})]})}),m.length>0&&p.length>0?o.jsx("div",{className:"mt-2","data-testid":"stacked-event-volume-chart",children:o.jsx($w,{buckets:m,series:p,height:240})}):o.jsx("div",{className:"p-8 text-center text-xs text-base-content/50","data-testid":"empty-chart-fallback",children:"No event activity recorded in this time range."})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-2",children:[o.jsxs("div",{className:"flex justify-between items-center text-xs font-semibold uppercase tracking-wider text-base-content/60",children:[o.jsx("span",{children:"Severity Distribution"}),o.jsxs("span",{children:[f.sum.toLocaleString()," classified events"]})]}),o.jsx("div",{className:"w-full h-3 rounded-full bg-base-300 overflow-hidden flex","data-testid":"severity-distribution-bar",children:f.sum>0?o.jsxs(o.Fragment,{children:[f.counts.info>0&&o.jsx("div",{style:{width:`${f.counts.info/f.sum*100}%`},className:"bg-info h-full",title:`Info: ${f.counts.info}`,"data-testid":"severity-bar-info"}),f.counts.warning>0&&o.jsx("div",{style:{width:`${f.counts.warning/f.sum*100}%`},className:"bg-warning h-full",title:`Warning: ${f.counts.warning}`,"data-testid":"severity-bar-warning"}),f.counts.error>0&&o.jsx("div",{style:{width:`${f.counts.error/f.sum*100}%`},className:"bg-error h-full",title:`Error: ${f.counts.error}`,"data-testid":"severity-bar-error"}),f.counts.unknown>0&&o.jsx("div",{style:{width:`${f.counts.unknown/f.sum*100}%`},className:"bg-base-content/20 h-full",title:`Unknown: ${f.counts.unknown}`,"data-testid":"severity-bar-unknown"})]}):o.jsx("div",{className:"w-full h-full bg-base-content/10"})}),o.jsxs("div",{className:"flex flex-wrap gap-4 text-xs text-base-content/70 mt-1",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-info inline-block"})," Info:"," ",f.counts.info.toLocaleString()]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-warning inline-block"})," Warning:"," ",f.counts.warning.toLocaleString()]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-error inline-block"})," Error:"," ",f.counts.error.toLocaleString()]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-base-content/20 inline-block"})," Unknown:"," ",f.counts.unknown.toLocaleString()]})]})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Top Event Types"}),o.jsx("div",{className:"overflow-x-auto",children:o.jsxs("table",{className:"table table-xs w-full font-mono text-xs","data-testid":"top-event-types-table",children:[o.jsx("thead",{children:o.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[o.jsx("th",{children:"Event Name"}),o.jsx("th",{children:"Prefix"}),o.jsx("th",{className:"text-right",children:"Count"}),o.jsx("th",{className:"text-right",title:"Average duration in seconds",children:"Avg(Duration - s)"}),o.jsx("th",{className:"text-right",title:"Events with error severity",children:"Failures"}),o.jsx("th",{className:"text-right",children:"Latest"})]})}),o.jsxs("tbody",{children:[(n?.topEventTypes??[]).map(A=>o.jsxs("tr",{className:"hover:bg-base-300/40",children:[o.jsx("td",{className:"font-semibold text-base-content",children:A.name}),o.jsx("td",{children:o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-bold border",style:{color:qc(A.prefix),borderColor:qc(A.prefix)},children:A.prefix})}),o.jsx("td",{className:"text-right text-base-content/80 tabular-nums",children:A.count.toLocaleString()}),o.jsx("td",{className:"text-right text-base-content/80 tabular-nums","data-testid":`top-event-avg-${A.name}`,children:_W(A.avgDurationMs)}),o.jsx("td",{className:`text-right tabular-nums ${A.failureCount>0?"text-error font-semibold":"text-base-content/80"}`,"data-testid":`top-event-failures-${A.name}`,children:A.failureCount.toLocaleString()}),o.jsx("td",{className:"text-right text-base-content/50",children:new Date(A.latestAt).toLocaleTimeString()})]},A.name)),(!n||(n.topEventTypes??[]).length===0)&&o.jsx("tr",{children:o.jsx("td",{colSpan:6,className:"text-center text-base-content/40 py-4",children:"No events recorded"})})]})]})})]}),o.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[o.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Recent Failures"}),o.jsxs("div",{className:"flex flex-col gap-2 max-h-[320px] overflow-y-auto","data-testid":"recent-failures-feed",children:[(n?.recentErrors??[]).map(A=>{const w=!!e.onNavigate,T=()=>{A.source==="job"?v(A.id):N(A.name,A.refId)},_=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(gn,{size:"xs",variant:A.source==="job"?"warning":"error",children:A.source}),o.jsx("span",{className:"font-mono text-xs font-semibold text-base-content",children:A.name})]}),o.jsx("span",{className:"text-[11px] text-base-content/50 font-mono",children:new Date(A.occurredAt).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-error font-mono truncate",children:A.message})]});return w?o.jsx("button",{type:"button",className:"w-full text-left p-2.5 rounded-lg border border-base-content/10 bg-base-100 flex flex-col gap-1 transition-colors hover:bg-base-200/80 cursor-pointer",onClick:T,"data-testid":`failure-row-${A.source}-${A.id}`,children:_},`${A.source}-${A.id}-${A.occurredAt}`):o.jsx("div",{className:"p-2.5 rounded-lg border border-base-content/10 bg-base-100 flex flex-col gap-1","data-testid":`failure-row-${A.source}-${A.id}`,children:_},`${A.source}-${A.id}-${A.occurredAt}`)}),(!n||(n.recentErrors??[]).length===0)&&o.jsx("div",{className:"p-8 text-center text-xs text-base-content/50",children:"No recent failures in this time range."})]})]})]})]})}const Vc=[{id:"summary",label:"Summary",component:IW},{id:"system-events",label:"System Events",component:lW},{id:"jobs",label:"Jobs",component:xW},{id:"routing",label:"Routing",component:NW}];function RW(){const[e,t]=g.useState(Vc[0]?.id??""),[n,r]=g.useState("4h"),[a,s]=g.useState({status:"connecting",rate:0,lastEventAt:null}),l=Vc.find(b=>b.id===e)?.component,u=g.useCallback(b=>{s(b)},[]),c=g.useCallback(b=>{t(b.tab)},[]),d=e==="system-events",p=d?a.status:"idle",m=d?a.status==="live"?`live tail · ${a.rate} evt/60s`:a.status==="connecting"?"connecting…":a.status==="paused"?"live tail paused":"stream error":"live tail idle",f=p==="live"?"bg-emerald-400 animate-pulse":p==="connecting"?"bg-amber-400":p==="errored"?"bg-error":"bg-base-content/40";return o.jsxs("div",{className:"flex flex-col gap-4 p-4 max-w-[1600px] mx-auto w-full","data-observability-shell":!0,children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-2xl",children:"📡"}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Observabilities"}),o.jsx("p",{className:"text-xs text-base-content/60",children:"System event streams, queue execution telemetry, and routing attribution"}),o.jsxs("p",{className:"livechip mt-1 inline-flex items-center gap-1.5 rounded-full border border-base-content/10 px-2 py-0.5 text-xs text-base-content/60 font-mono","data-testid":"observability-liveness-chip",role:"status","aria-live":"polite",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f}`,"aria-hidden":"true"}),m,d&&a.lastEventAt&&o.jsxs(o.Fragment,{children:[" · last ",o.jsx("time",{dateTime:a.lastEventAt,children:new Date(a.lastEventAt).toLocaleTimeString()})]})]})]})]}),o.jsx($G,{timeRange:n,onTimeRangeChange:r}),o.jsx("div",{role:"tablist","aria-label":"Observability tabs",className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:Vc.map(b=>{const x=b.id===e;return o.jsx("button",{type:"button",role:"tab","aria-selected":x,"aria-controls":`observability-tab-panel-${b.id}`,id:`observability-tab-${b.id}`,onClick:()=>t(b.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer ${x?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,children:b.label},b.id)})})]}),o.jsx("div",{role:"tabpanel",id:`observability-tab-panel-${e}`,"aria-labelledby":`observability-tab-${e}`,className:"mt-2 flex flex-col gap-4",children:l?o.jsx(l,{onLivenessChange:u,timeRange:n,onNavigate:c}):null})]})}const DW={id:"observability",name:"Observabilities",icon:"📡",route:"observability",component:RW,sidebarLabel:"Observabilities",description:"Real-time system events, execution traces, and agent doctor telemetry",order:10},OW=Object.freeze(Object.defineProperty({__proto__:null,module:DW},Symbol.toStringTag,{value:"Module"})),LW=100,MW=()=>`${Ct()}/events/history?limit=${LW}`,FW=["agent.","message.","task.","supervisor.","process."];function jW(e){return FW.some(t=>e.startsWith(t))}function PW(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.eventName!="string"||typeof t.occurredAt!="string"||!jW(t.eventName))return null;const n=t.payload!==null&&typeof t.payload=="object"?t.payload:null,r=n&&typeof n.teamId=="string"&&n.teamId.length>0?n.teamId:void 0,a=n&&typeof n.agentType=="string"&&n.agentType.length>0?n.agentType:void 0,s=n&&typeof n.memberLabel=="string"&&n.memberLabel.length>0?n.memberLabel:n&&typeof n.agentId=="string"&&n.agentId.length>0?n.agentId:void 0,i=typeof t.actor=="string"&&t.actor.length>0?t.actor:n&&typeof n.agentId=="string"&&n.agentId.length>0?n.agentId:null;return{id:typeof t.id=="string"?t.id:`${t.eventName}-${t.occurredAt}`,eventName:t.eventName,occurredAt:t.occurredAt,actor:i,...r?{teamId:r}:{},...s?{memberLabel:s}:{},...a?{agentType:a}:{}}}function BW(e){if(e===null||typeof e!="object"||!("events"in e))return null;const t=e.events;if(!Array.isArray(t))return null;const n=[];for(const r of t){const a=PW(r);a&&n.push(a)}return n}const Ko=1e3,Yc=[1e3,2e3,4e3,8e3,15e3],UW=15e3;function $W(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.stream!="string"||typeof t.ts!="string"||typeof t.line!="string")return null;const n=t.stream;if(n!=="stdout"&&n!=="stderr"&&n!=="meta")return null;const r=t.seq;return r!==void 0&&typeof r!="number"?null:{stream:n,ts:t.ts,line:t.line,...r!==void 0?{seq:r}:{}}}function zW(e){return e<0?Yc[0]:e>=Yc.length?UW:Yc[e]}function $y(e,t,n){if(t.seq===void 0){const a=[...e,t];return a.length>Ko&&a.splice(0,a.length-Ko),{frames:a,lastSeq:n}}if(t.seq<=n)return{frames:e,lastSeq:n};const r=[...e,t];return r.length>Ko&&r.splice(0,r.length-Ko),{frames:r,lastSeq:t.seq}}const HW=(e,t)=>t!==void 0?`${Ct()}/processes/${encodeURIComponent(e)}/stream?sinceSeq=${t}`:`${Ct()}/processes/${encodeURIComponent(e)}/stream`,zb=3e3;function Hb(e){if(e===null||typeof e!="object")return null;const t=e;if(!Array.isArray(t.processes))return null;const n=[];for(const r of t.processes){if(r===null||typeof r!="object")return null;const a=r;if(typeof a.agentId!="string"||typeof a.status!="string"||typeof a.startedAt!="string"||typeof a.pid!="number")return null;const s=a.exitCode;if(s!==null&&typeof s!="number")return null;const i=a.teamId;n.push({agentId:a.agentId,pid:a.pid,status:a.status,startedAt:a.startedAt,exitCode:s,teamId:typeof i=="string"?i:null})}return n}function GW(e){if(e===null||typeof e!="object")return null;const t=e;if(!Array.isArray(t.executions))return null;const n=[];for(const r of t.executions){if(r===null||typeof r!="object")return null;const a=r;if(typeof a.id!="string"||typeof a.label!="string"||typeof a.command!="string"||!Array.isArray(a.args)||!a.args.every(i=>typeof i=="string")||a.pid!==null&&typeof a.pid!="number"||typeof a.status!="string"||typeof a.startedAt!="string"||a.exitedAt!==null&&typeof a.exitedAt!="string"||a.exitCode!==null&&typeof a.exitCode!="number"||typeof a.source!="string"||a.agentId!==null&&typeof a.agentId!="string")return null;const s=a.teamId;n.push({id:a.id,label:a.label,command:a.command,args:a.args,pid:a.pid,status:a.status,startedAt:a.startedAt,exitedAt:a.exitedAt,exitCode:a.exitCode,source:a.source,teamId:typeof s=="string"?s:null,agentId:a.agentId})}return n}const WW=e=>`${Ct()}/processes/${encodeURIComponent(e)}/stdin`,qW=()=>`${Ct()}/messages`,VW=()=>`${Ct()}/processes`;function YW({agentId:e}){const[t,n]=g.useState([]),[r,a]=g.useState("unknown"),[s,i]=g.useState(""),[l,u]=g.useState(null),[c,d]=g.useState(!1),p=g.useRef(-1),m=g.useRef(null),f=g.useRef(void 0),b=g.useRef(0),x=g.useRef(!0),E=g.useRef(null),y=g.useCallback(async w=>{try{const T=await ht(new Request(VW(),{signal:w}));if(!T.ok)return;const _=await T.json(),B=Hb(_);if(!B)return;const k=B.find($=>$.agentId===e);k&&x.current&&a(k.status)}catch{}},[e]);g.useEffect(()=>{x.current=!0;let w=null;const T=()=>{w?.abort(),w=new AbortController,y(w.signal)};T();const _=setInterval(T,zb);return()=>{x.current=!1,w?.abort(),clearInterval(_)}},[y]);const S=g.useCallback(()=>{if(!x.current)return;const w=new EventSource(HW(e,p.current>-1?p.current:void 0));m.current=w,w.onmessage=T=>{try{const _=JSON.parse(T.data),B=$W(_);if(!B)return;n(k=>{const $=$y(k,B,p.current);return p.current=$.lastSeq,$.frames}),b.current=0,d(!0)}catch{}},w.onerror=()=>{if(w.close(),m.current=null,d(!1),!x.current)return;const T=zW(b.current);b.current+=1,f.current=setTimeout(S,T)}},[e]);g.useEffect(()=>(S(),()=>{x.current=!1,m.current?.close(),m.current=null,f.current&&clearTimeout(f.current)}),[S]),g.useEffect(()=>{E.current&&t.length>0&&(E.current.scrollTop=E.current.scrollHeight)},[t]);const v=g.useCallback(async()=>{const w=s;if(w.length===0)return;u(null);const T={stream:"meta",ts:new Date().toISOString(),line:`> ${w}`};n(_=>$y(_,T,p.current).frames);try{const _=await ht(new Request(WW(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({line:w})}));if(ht(new Request(qW(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:"terminal",to:e,body:w})})).catch(()=>{}),!_.ok){const k=(await _.json().catch(()=>null))?.error??`stdin POST failed: ${_.status}`;u(k);return}i("")}catch(_){u(_ instanceof Error?_.message:String(_))}},[e,s]),N=r==="running",A=w=>{w.key==="Enter"&&N&&(w.preventDefault(),v())};return o.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-member-terminal":e,children:[o.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-base-200 shrink-0 flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Terminal"}),o.jsx("span",{className:"font-mono text-xs text-spur-text-muted",children:e}),o.jsx(gn,{variant:N?"success":"ghost",size:"xs","data-terminal-status":!0,children:r}),o.jsx("span",{className:"text-[10px] text-spur-text-muted","data-terminal-connected":!0,children:c?"connected":"reconnecting…"})]}),!N&&o.jsxs("div",{className:"px-4 py-1 text-xs text-warning border-b border-spur-border",role:"status","data-status-banner":!0,children:["Member is ",r," — input disabled."]}),o.jsx("pre",{ref:E,className:"flex-1 overflow-x-auto overflow-y-auto p-2 text-xs font-mono leading-snug bg-base-100","data-terminal-output":!0,children:t.length===0?o.jsxs("span",{className:"text-spur-text-muted italic",children:["Waiting for output from ",e,"…"]}):t.map((w,T)=>o.jsx("div",{className:w.stream==="stderr"?"text-error":w.stream==="meta"?"text-spur-text-muted italic":"text-spur-text","data-stream":w.stream,children:w.line},w.seq??`meta-${T}`))}),l&&o.jsx("div",{className:"px-4 py-1 text-xs text-error border-t border-spur-border",role:"alert","data-input-error":!0,children:l}),o.jsx("div",{className:"flex items-center gap-2 px-2 py-2 border-t border-spur-border bg-base-200 shrink-0",children:o.jsx("input",{type:"text",value:s,onChange:w=>i(w.target.value),onKeyDown:A,disabled:!N,placeholder:N?"Type a line and press Enter…":"Input disabled (member not running)",className:"flex-1 input input-sm font-mono","data-terminal-input":!0})})]})}const KW=e=>`${Ct()}/messages/inbox?agent=${encodeURIComponent(e)}`,ZW=(e,t)=>`${Ct()}/agents/${encodeURIComponent(e)}/${t}`;function XW({entry:e,onClose:t}){const n=Os(),r=n.fleet?.path??n.path??"Unavailable",a=e.declared===null?"Unavailable":e.declared.model??"Executor default",[s,i]=g.useState(null),[l,u]=g.useState(null),[c,d]=g.useState(!1),[p,m]=g.useState(null);g.useEffect(()=>{const y=S=>{S.key==="Escape"&&t()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t]),g.useEffect(()=>{let y=!1;return i(null),ht(new Request(KW(e.instanceId))).then(async S=>S.ok?mv(await S.json()):[]).then(S=>{y||i(S)}).catch(()=>{y||i([])}),()=>{y=!0}},[e.instanceId]),g.useEffect(()=>{let y=!1;return u(null),ht(new Request(MW())).then(async S=>S.ok?BW(await S.json()):[]).then(S=>{y||u((S??[]).filter(v=>v.memberLabel===e.instanceId||v.actor===e.instanceId))}).catch(()=>{y||u([])}),()=>{y=!0}},[e.instanceId]);const f=e.issues.includes("executor-unavailable")||e.issues.includes("unresolved"),b=e.issues.includes("executor-unavailable")?"controls disabled — executor unavailable":e.issues.includes("unresolved")?"controls disabled — member unresolved":null,x=async y=>{d(!0),m(null);try{const S=await ht(new Request(ZW(e.instanceId,y),{method:"POST"}));S.ok||m(`${y} failed: ${S.status}`)}catch(S){m(S instanceof Error?S.message:String(S))}finally{d(!1)}},E=e.observed.status==="running";return o.jsxs("div",{className:"shrink-0 h-[55%] flex flex-col border-t border-spur-border bg-spur-surface","data-member-detail":!0,children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-spur-border shrink-0",children:[o.jsx("span",{className:"text-sm font-semibold text-spur-text",children:e.declared?.role??"member"}),o.jsx("button",{type:"button",className:"ml-auto px-2 py-0.5 rounded-lg text-xs text-spur-text-muted hover:text-spur-text","aria-label":"Close member detail",onClick:t,"data-member-detail-close":!0,children:"close ✕"})]}),o.jsxs("div",{className:"px-3 py-2 border-b border-spur-border shrink-0 flex flex-col gap-1 text-xs",children:[o.jsxs("span",{className:"text-spur-text-muted",children:["declared:"," ",o.jsx("span",{className:"text-spur-text",children:e.declared===null?"none":`${e.declared.enabled?"enabled":"disabled"} · capability ${e.declared.capabilityState}`})]}),o.jsxs("span",{className:"text-spur-text-muted",children:["observed:"," ",o.jsxs("span",{className:"text-spur-text",children:[e.observed.status,e.observed.pid!==null?` — pid ${e.observed.pid}`:"",e.observed.exitCode!==null?` — exit ${e.observed.exitCode}`:""]})]}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-1",children:[o.jsx("dt",{className:"text-spur-text-muted",children:"Working directory"}),o.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-workdir":!0,children:r}),o.jsx("dt",{className:"text-spur-text-muted",children:"Model"}),o.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-model":!0,children:a})]})]}),o.jsxs("div",{className:"px-3 py-2 border-b border-spur-border shrink-0 flex items-center gap-2 flex-wrap",children:[o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded-lg text-xs bg-spur-accent text-white disabled:opacity-40",disabled:c||f||E,onClick:()=>{x("start")},"data-member-start":!0,children:"start"}),o.jsx("button",{type:"button",className:"px-2 py-0.5 rounded-lg text-xs bg-spur-surface-3 text-spur-text disabled:opacity-40",disabled:c||f||!E,onClick:()=>{x("stop")},"data-member-stop":!0,children:"stop"}),b!==null&&o.jsx("span",{className:"text-xs text-spur-text-muted","data-lifecycle-reason":!0,children:b}),p!==null&&o.jsx("span",{className:"text-xs text-error",role:"alert","data-lifecycle-error":!0,children:p})]}),o.jsx("div",{className:"flex-1 min-h-0 border-b border-spur-border",children:o.jsx(YW,{agentId:e.instanceId})}),o.jsxs("div",{className:"shrink-0 h-[35%] flex overflow-hidden",children:[o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 border-r border-spur-border","data-member-messages":!0,children:[o.jsx("div",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide mb-1",children:"Messages"}),(s??[]).length===0&&o.jsx("div",{className:"text-xs text-spur-text-muted italic",children:s===null?"Loading…":"No inbox messages."}),(s??[]).slice(0,20).map(y=>o.jsxs("div",{className:"text-xs border-t border-spur-border py-1","data-member-message":y.id,children:[o.jsxs("span",{className:"font-mono text-spur-text-muted",children:[y.fromId??"system"," → ",y.toId]}),o.jsx("span",{className:"ml-1 px-1 rounded bg-spur-surface-3 text-spur-text",children:y.status}),o.jsx("span",{className:"ml-1 font-mono text-spur-text-muted",children:y.createdAt}),o.jsx("p",{className:"text-spur-text mt-0.5 whitespace-pre-wrap break-words",children:y.body})]},y.id))]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-2","data-member-activity":!0,children:[o.jsx("div",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide mb-1",children:"Activity"}),(l??[]).length===0&&o.jsx("div",{className:"text-xs text-spur-text-muted italic",children:l===null?"Loading…":"No activity for this member."}),(l??[]).slice(0,20).map(y=>o.jsxs("div",{className:"text-xs border-t border-spur-border py-1","data-member-activity-row":y.eventName,children:[o.jsx("span",{className:"font-mono text-spur-text-muted",children:y.occurredAt})," ",o.jsx("span",{className:"text-spur-text",children:y.eventName})]},y.id))]})]})]})}function zy(e,t){const{state:n,instanceId:r}=t.orchestrator;return n!=="bound-online"&&n!=="bound-offline"?!1:r!==void 0&&r===e.instanceId}function QW(e,t){const n=new Map(t.map(a=>[a.agentId,a])),r=[];for(const a of e.members){const s=n.get(a.instanceId),i={status:Hy(s),pid:s?.pid??null,startedAt:s?.startedAt??null,exitCode:s?.exitCode??null},l=[];a.enabled===!1&&l.push("disabled"),a.capabilityState==="unavailable"&&l.push("executor-unavailable"),a.capabilityState==="unknown"&&l.push("capability-unknown"),e.capacity.missing.includes(a.instanceId)&&l.push("unresolved"),r.push({instanceId:a.instanceId,declared:a,observed:i,isOrchestrator:zy({instanceId:a.instanceId},e),issues:l})}for(const a of t)e.members.some(s=>s.instanceId===a.agentId)||a.agentId!==ku&&r.push({instanceId:a.agentId,declared:null,observed:{status:Hy(a),pid:a.pid,startedAt:a.startedAt,exitCode:a.exitCode},isOrchestrator:zy({instanceId:a.agentId},e),issues:["undeclared"]});return r.sort((a,s)=>a.isOrchestrator!==s.isOrchestrator?a.isOrchestrator?-1:1:a.instanceId<s.instanceId?-1:a.instanceId>s.instanceId?1:0),r}function Hy(e){return e===void 0?"not-started":e.status==="running"?"running":"exited"}const sN=6e4,Kd=60*sN,Gy=24*Kd;function JW(e,t){if(e===null)return null;const n=new Date(e).getTime(),r=Date.now()-n;if(Number.isNaN(n)||r<0)return null;const a=Math.floor(r/Gy),s=Math.floor(r%Gy/Kd),i=Math.floor(r%Kd/sN);return a>0?`up ${a}d ${s}h`:s>0?`up ${s}h ${i}m`:`up ${i}m`}const eq=()=>`${Ct()}/project/fleet`,tq=()=>`${Ct()}/processes`;function nq(e){if(e===null||typeof e!="object")return!1;const t=e,n=t.capacity;return Array.isArray(t.members)&&t.members.every(r=>r!==null&&typeof r=="object"&&typeof r.instanceId=="string")&&n!==null&&typeof n=="object"&&Array.isArray(n.missing)&&t.orchestrator!==null&&typeof t.orchestrator=="object"}const Kc={"executor-unavailable":{icon:"⛔",label:"executor unavailable",action:"the executor cannot run here — check the executor's install/attestation"},"capability-unknown":{icon:"❔",label:"capability unknown",action:"no attestation exists; it grants nothing and is not a failure"},unresolved:{icon:"⚠️",label:"unresolved",action:"the instance is listed in the fleet capacity as missing"},undeclared:{icon:"❗",label:"undeclared",action:"a live process with no declared member"},disabled:{icon:"⏸️",label:"disabled",action:"declared with enabled: false"}};function rq(e,t){return e.observed.status==="running"?{label:"running",action:null}:t&&e.isOrchestrator?{label:"orchestrator offline",action:"its claim is held but stale — see project_claims"}:e.issues.includes("executor-unavailable")||e.issues.includes("capability-unknown")?{label:e.observed.status==="exited"?"exited":"not started",action:null}:{label:"not running",action:"start it"}}function aq({pollMs:e=zb}){const t=Os(),[n,r]=g.useState(null),[a,s]=g.useState(!1),[i,l]=g.useState(null),[u,c]=g.useState(!1),d=g.useRef(null);g.useEffect(()=>{let b=!1,x=null;const E=async()=>{x?.abort(),x=new AbortController;const S=x.signal;try{const[v,N]=await Promise.all([ht(new Request(eq(),{signal:S})),ht(new Request(tq(),{signal:S}))]);if(b||!v.ok||!N.ok)return;const A=await v.json(),w=await N.json();if(b||!nq(A))return;const T=Hb(w);if(!T)return;r(QW(A,T)),c(A.orchestrator.state==="bound-offline"),s(!1)}catch{b||s(!0)}};E();const y=setInterval(()=>{E()},e);return()=>{b=!0,clearInterval(y),x?.abort()}},[e]);const p=g.useCallback((b,x)=>{d.current=x,l(b.instanceId)},[]),m=g.useCallback(()=>{l(null),d.current?.focus()},[]),f=n?.find(b=>b.instanceId===i)??null;return o.jsxs("div",{className:"flex flex-col h-full overflow-hidden bg-spur-bg","data-agents-view":!0,children:[o.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[n===null&&!a&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-roster-loading":!0,children:"Loading fleet roster…"}),a&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-roster-fetch-failed":!0,role:"alert",children:"Fleet roster unavailable — the fleet or process feed could not be read."}),n!==null&&n.length===0&&o.jsxs("div",{className:"p-4 text-sm text-spur-text-muted italic","data-roster-empty":!0,children:["No agents for this project — declare members under"," ",o.jsx("code",{className:"font-mono",children:"agent.fleet"})," in"," ",o.jsx("code",{className:"font-mono",children:`${t.path??"this project"}/.spur/config.yaml`}),"."]}),n!==null&&n.length>0&&o.jsx("div",{className:"grid gap-2 md:grid-cols-2 xl:grid-cols-3","data-roster-grid":!0,children:n.map(b=>o.jsx(sq,{entry:b,orchestratorOffline:u,onOpen:p},b.instanceId))})]}),f!==null&&o.jsx(XW,{entry:f,onClose:m})]})}function sq({entry:e,orchestratorOffline:t,onOpen:n}){const r=rq(e,t),a=e.observed.status==="running"?JW(e.observed.startedAt):null;return o.jsxs("button",{type:"button",className:"text-left p-3 bg-spur-surface border border-spur-border rounded-xl hover:bg-spur-surface-2 focus:outline-none focus:ring-1 focus:ring-spur-accent","data-roster-entry":e.instanceId,"data-g6":"open-member","aria-haspopup":"dialog",onClick:s=>n(e,s.currentTarget),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{"data-roster-role":!0,className:"font-medium text-spur-text text-sm",children:e.declared?.role??"member"}),e.isOrchestrator&&o.jsx("span",{"data-roster-orchestrator":!0,className:"text-xs px-1 rounded bg-spur-accent/20 text-spur-accent",children:"orchestrator"})]}),o.jsxs("div",{className:"mt-1 text-xs text-spur-text-muted",children:["executor"," ",o.jsx("span",{"data-roster-executor":!0,className:"font-mono text-spur-text",children:e.declared?.executor??"—"})]}),o.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs",children:[o.jsxs("span",{"data-roster-declared":!0,children:[o.jsx("span",{className:"text-spur-text-muted",children:"declared:"})," ",o.jsx("span",{className:"text-spur-text",children:e.declared===null?"none":`${e.declared.enabled?"enabled":"disabled"} · capability ${e.declared.capabilityState}`})]}),o.jsxs("span",{"data-roster-observed":!0,children:[o.jsx("span",{className:"text-spur-text-muted",children:"observed:"})," ",o.jsxs("span",{className:"text-spur-text",children:[e.observed.status,e.observed.pid!==null?` — pid ${e.observed.pid}`:"",e.observed.exitCode!==null?` — exit ${e.observed.exitCode}`:""]})]})]}),a!==null&&o.jsx("div",{"data-roster-uptime":!0,className:"mt-1 text-xs text-spur-text-muted",children:a}),e.issues.length>0&&o.jsx("div",{className:"mt-1 space-y-0.5",children:e.issues.map(s=>o.jsxs("div",{"data-roster-issue":s,className:"text-xs",children:[o.jsx("span",{"aria-hidden":"true",children:Kc[s].icon})," ",o.jsx("span",{className:"text-spur-text",children:Kc[s].label}),o.jsxs("span",{className:"text-spur-text-muted",children:[" — ",Kc[s].action]})]},s))}),r.action!==null&&o.jsxs("div",{"data-roster-next-action":!0,className:"mt-1 text-xs text-spur-text-muted",children:["next: ",r.action]})]})}const iN={pending:{icon:"◐",label:"pending",meaning:"Receipt captured; waiting for durable acceptance. The submitted revision clears only on acceptance.",action:"wait — the request is being persisted",tone:"warn"},"queued-awaiting-orchestrator":{icon:"⏸",label:"queued-awaiting-orchestrator",meaning:"Durable receipt exists but no active orchestrator has consumed it. NOT “working”. ",action:"bind/restore an orchestrator (Agents → Planner · Scout)",tone:"warn"},"orchestrator-missing":{icon:"⏸",label:"orchestrator-missing",meaning:"No orchestrator instance is bound, so the durable request cannot be consumed.",action:"bind/restore an orchestrator (Agents → Planner · Scout)",tone:"warn"},"orchestrator-offline":{icon:"⏸",label:"orchestrator-offline",meaning:"The orchestrator’s claim is held but stale — it is not consuming the queue.",action:"start the orchestrator member (Agents tab)",tone:"warn"},"executor-unavailable":{icon:"⊘",label:"executor-unavailable",meaning:"No executor tier can serve the addressed member, so the request was not accepted; the draft is preserved.",action:"fix the member’s executor binding, then retry — same payload, same requestId",tone:"err"},"rest-held":{icon:"⏳",label:"rest-held",meaning:"Rest accepted the request into a visible hold.",action:"release from rest (Agents) or let rest wake it; results from already-running work keep arriving",tone:"warn"},blocked:{icon:"⛔",label:"blocked",meaning:"The strategy is holding the task on a first-class condition (unauthorized, not-ready, unmet-dependency, no idle instance).",action:"inspect Activity for the pending signal, then unblock",tone:"warn"},"accepted-working":{icon:"▶",label:"accepted · executor working",meaning:"Durable acceptance; an executor is working. This is occupancy, NOT a verified result.",action:"wait for the run receipt",tone:"ok"},"failed-delivery":{icon:"✕",label:"failed-delivery",meaning:"The run could not accept this payload; the draft is preserved.",action:"Retry keeps the SAME requestId for this immutable payload; editing text first creates a NEW requestId",tone:"err"},"outcome-unknown":{icon:"?",label:"outcome-unknown",meaning:"The run consumed the request without ever reporting a receipt.",action:"inspect Messages/Activity and reconcile before any resend — a blind retry would duplicate the payload",tone:"err"},"completed-exit-only":{icon:"✓",label:"run exit 0 recorded (unverified)",meaning:"A process exit code is not proof of success (run exit ≠ verified result).",action:"reconcile in Messages/Activity; only then mark the result verified",tone:"warn"},"completed-verified":{icon:"✓",label:"completed · verified result",meaning:"Result received and reconciled against the original request.",action:"none — this request is finished",tone:"ok"}};function oN(e,t,n){if(n&&e===null)return"pending";const r=e?.deliveryStatus??"queued",a=e?.reason??null,s=e?.outcome??null,i=e?.hold??null;if(r==="failed")return"failed-delivery";if(a==="outcome-unknown")return"outcome-unknown";if(a==="attempts-exhausted")return"failed-delivery";if(s==="verified")return"completed-verified";if(s==="run-exit-only")return"completed-exit-only";if(s==="errored")return"failed-delivery";if(i==="rest-after-drain")return"rest-held";if(i==="executor-unavailable")return"executor-unavailable";if(i!==null)return"blocked";if(r==="injected"||r==="delivered")return"accepted-working";const l=t?.orchestrator.state??null;if(r==="queued"&&(l==="missing"||l==="unresolvable"))return"orchestrator-missing";if(r==="queued"&&l==="bound-offline")return"orchestrator-offline";const u=t?.orchestrator.instanceId,c=t!==null&&u!==void 0?t.members.find(d=>d.instanceId===u):void 0;return r==="queued"&&c!==void 0&&(c.enabled===!1||c.capabilityState==="unavailable")?"executor-unavailable":r==="queued"&&t?.strategy?.name==="rest"?"rest-held":"queued-awaiting-orchestrator"}const iq=15e3;function oq(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.messageId!="string"||t.messageId.length===0||typeof t.deliveryStatus!="string"||typeof t.injectAttempts!="number"?null:{messageId:t.messageId,requestKey:typeof t.requestKey=="string"?t.requestKey:null,deliveryStatus:t.deliveryStatus,injectAttempts:t.injectAttempts,injectError:typeof t.injectError=="string"?t.injectError:null,runId:typeof t.runId=="string"?t.runId:null,taskId:typeof t.taskId=="string"?t.taskId:null,outcome:t.outcome==="run-exit-only"||t.outcome==="errored"||t.outcome==="verified"?t.outcome:null,reason:typeof t.reason=="string"?t.reason:null,hold:typeof t.hold=="string"?t.hold:null}}function lN(e,t=iq){const[n,r]=g.useState(()=>new Map),[a,s]=g.useState(!1);return g.useEffect(()=>{if(e==null){r(new Map),s(!1);return}const i=new AbortController;let l=!1;const u=`${Ct()}/project/requests`,c=()=>{ht(new Request(u,{signal:i.signal})).then(async p=>{if(!p.ok)throw new Error(`requests fetch failed: ${p.status}`);const f=(await p.json()).requests,b=Array.isArray(f)?f.map(oq).filter(x=>x!==null):[];l||(r(new Map(b.map(x=>[x.messageId,x]))),s(!1))}).catch(()=>{l||s(!0)})};c();const d=setInterval(c,t);return()=>{l=!0,clearInterval(d),i.abort()}},[e,t]),{requests:n,failed:a}}function lq(e){if(e===null)return!0;const{state:t,instanceId:n}=e.orchestrator;return t==="missing"||t==="unresolvable"||!n}function uq(e){return`${Ct()}/messages/inbox?agent=${encodeURIComponent(e)}`}function cq(){const e=Os(),{draft:t,setText:n,removeRef:r}=Sw(),[a,s]=g.useState(null),[i,l]=g.useState(!1),u=e.fleet?.orchestrator.instanceId??null,c=lq(e.fleet),{requests:d,failed:p}=lN(u),m=a?.map(f=>{const b=d.get(f.id);return b===void 0?f:{...f,requestKey:b.requestKey??void 0,receipt:b}})??null;return g.useEffect(()=>{if(e.path===null)return;const f=new AbortController;let b=!1;const x=async y=>{const S=await ht(new Request(uq(y),{signal:f.signal}));if(!S.ok)throw new Error(`inbox fetch failed: ${S.status}`);return mv(await S.json())},E=u!==null?x(u):Promise.resolve([]);return Promise.all([E,x(ku)]).then(([y,S])=>{b||(s(Zj(y,S)),l(!1))}).catch(()=>{b||l(!0)}),()=>{b=!0,f.abort()}},[e.path,u]),o.jsxs("div",{className:"flex flex-col h-full overflow-hidden bg-spur-bg","data-conversation-view":!0,children:[o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-1","data-conversation-thread":!0,children:[a===null&&!i&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-conversation-loading":!0,children:"Loading conversation…"}),i&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-conversation-fetch-failed":!0,role:"alert",children:"Conversation unavailable — the message feed could not be read."}),p&&!i&&o.jsx("div",{className:"p-4 text-xs text-spur-text-muted","data-conversation-requests-failed":!0,role:"status",children:"Results feed unavailable — receipt states may be stale."}),a!==null&&a.length===0&&o.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-conversation-empty":!0,children:"No messages yet for this project."}),m?.map(f=>o.jsx(dq,{entry:f},f.id))]}),o.jsxs("div",{className:"border-t border-spur-border bg-spur-surface shrink-0 p-2 space-y-1","data-conversation-composer":!0,children:[c&&o.jsx("div",{className:"text-xs text-spur-text-muted","data-conversation-orchestrator-missing":!0,children:"Orchestrator unavailable — no orchestrator instance is bound to this project, so requests cannot be delivered yet."}),t.refs.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1","data-draft-refs":!0,children:t.refs.map(f=>o.jsx(pq,{ref_:f,onRemove:r},uN(f)))}),o.jsx("textarea",{className:"w-full resize-none rounded-xl border border-spur-border bg-spur-bg p-2 text-sm text-spur-text focus:outline-none focus:ring-1 focus:ring-spur-accent",rows:3,value:t.text,onChange:f=>n(f.target.value),"aria-label":"Conversation draft",placeholder:"Describe what you need — submission is wired to the global input.","data-conversation-draft-input":!0})]})]})}function uN(e){return e.kind==="task"?`task:${e.wbs}`:`feature:${e.id}`}function dq({entry:e}){const t=e.receipt,n=oN(t??null,null,!1),r=iN[n];return o.jsxs("div",{className:"p-2 bg-spur-surface-2 border border-spur-border rounded-xl text-sm","data-conversation-entry":!0,"data-conversation-kind":e.kind,children:[o.jsxs("div",{className:"flex items-center gap-2 text-spur-text-muted text-xs",children:[o.jsx("span",{className:"font-medium text-spur-text",children:e.kind==="request"?"Request":"Response"}),o.jsxs("span",{className:"font-mono truncate","data-conversation-route":!0,children:[e.fromId??"system"," → ",e.toId]}),o.jsx("span",{className:"text-xs px-1 rounded bg-spur-surface-3 text-spur-text","data-conversation-delivery":!0,children:e.deliveryStatus}),e.kind==="request"&&o.jsxs("span",{className:"text-xs px-1 rounded font-medium","data-conversation-receipt-state":n,title:`${r.meaning} Next: ${r.action}`,children:[o.jsx("span",{"aria-hidden":"true",children:r.icon})," ",r.label]}),e.inReplyTo!==null&&o.jsxs("span",{className:"font-mono text-xs opacity-70","data-conversation-reply-to":!0,children:["↩ ",e.inReplyTo]}),o.jsx("span",{className:"ml-auto font-mono text-xs text-spur-text-muted",children:e.createdAt})]}),e.refs.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1 mt-1","data-conversation-entry-refs":!0,children:e.refs.map(a=>o.jsx("span",{className:"text-xs px-1 rounded bg-info/20 text-info font-mono","data-conversation-ref":a.kind,children:a.kind==="task"?`task ${a.wbs}`:`feature ${a.id}`},uN(a)))}),o.jsx("p",{className:"text-spur-text mt-1 whitespace-pre-wrap break-words",children:e.text})]})}function pq({ref_:e,onRemove:t}){const n=e.kind==="task"?`task ${e.wbs}`:`feature ${e.id}`;return o.jsxs("button",{type:"button",className:"text-xs px-1 rounded bg-info/20 text-info font-mono hover:bg-info/30","aria-label":`Remove ${n} reference from the draft`,onClick:()=>t(e),"data-draft-ref":e.kind,"data-g6":e.kind==="task"?"task-chip":void 0,children:[n," ✕"]})}const fq=()=>`${Ct()}/processes`;function mq(e,t){const n=e.map(s=>({key:`sup:${s.agentId}`,label:s.agentId,agentId:s.agentId,pid:s.pid,status:s.status,startedAt:s.startedAt,source:"supervisor",teamId:s.teamId??null})),r=new Set(e.map(s=>s.agentId)),a=new Set(e.map(s=>s.pid).filter(s=>s!=null));for(const s of t)s.agentId&&r.has(s.agentId)||s.pid!=null&&a.has(s.pid)||n.push({key:`reg:${s.id}`,label:s.label||s.command,agentId:s.agentId??void 0,pid:s.pid,status:s.status,startedAt:s.startedAt,source:s.source,teamId:s.teamId??null});return n}function hq(e,t){return e.filter(n=>{if(t.runningOnly&&n.status!=="running")return!1;if(t.source==="other"){if(n.source==="supervisor"||n.source==="one-shot")return!1}else if(t.source!=="all"&&n.source!==t.source)return!1;if(t.team==="unassigned"){if(n.teamId!=null)return!1}else if(t.team!=="all"&&n.teamId!==t.team)return!1;return!0})}function Wy({filters:e,onFilters:t,teamIds:n,totalCount:r,shownCount:a}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-2 text-xs","data-processes-filters":!0,children:[o.jsxs("label",{className:"flex items-center gap-1","data-processes-filter-running":!0,children:[o.jsx("input",{type:"checkbox",checked:e.runningOnly,onChange:s=>t({...e,runningOnly:s.target.checked}),"data-processes-filter-running-input":!0}),o.jsx("span",{children:"Running only"})]}),o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("span",{children:"Source"}),o.jsxs("select",{value:e.source,onChange:s=>t({...e,source:s.target.value}),className:"border border-spur-border rounded px-1 py-0.5 bg-spur-bg text-spur-text","data-processes-filter-source":!0,"aria-label":"Source filter",children:[o.jsx("option",{value:"all",children:"all"}),o.jsx("option",{value:"supervisor",children:"supervisor"}),o.jsx("option",{value:"one-shot",children:"one-shot"}),o.jsx("option",{value:"other",children:"other"})]})]}),o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("span",{children:"Team"}),o.jsxs("select",{value:e.team,onChange:s=>t({...e,team:s.target.value}),className:"border border-spur-border rounded px-1 py-0.5 bg-spur-bg text-spur-text","data-processes-filter-team":!0,"aria-label":"Team filter",children:[o.jsx("option",{value:"all",children:"all teams"}),o.jsx("option",{value:"unassigned",children:"unassigned"}),n.map(s=>o.jsx("option",{value:s,children:s},s))]})]}),o.jsx("button",{type:"button",className:"border border-spur-border rounded px-2 py-0.5 text-spur-text hover:bg-base-200 transition-colors cursor-pointer",onClick:()=>t({runningOnly:!1,source:"all",team:"all"}),"data-processes-filter-clear":!0,children:"Clear"}),o.jsxs("span",{className:"text-spur-text-muted","data-processes-filter-count":!0,children:[a,"/",r," shown"]})]})}function gq({pollMs:e=zb}){const[t,n]=g.useState(null),[r,a]=g.useState(null),[s,i]=g.useState({runningOnly:!1,source:"all",team:"all"}),l=g.useRef(!0),u=g.useCallback(async b=>{try{const x=await ht(new Request(fq(),{signal:b}));if(!x.ok)throw new Error(`processes fetch failed: ${x.status}`);const E=await x.json(),y=Hb(E),S=GW(E);if(!y||!S)return;l.current&&(n({processes:y,executions:S}),a(null))}catch(x){if(b.aborted)return;l.current&&a(x instanceof Error?x.message:String(x))}},[]);g.useEffect(()=>{l.current=!0;let b=null;const x=()=>{b?.abort(),b=new AbortController,u(b.signal)};x();const E=setInterval(x,e);return()=>{l.current=!1,b?.abort(),clearInterval(E)}},[u,e]);const c=g.useMemo(()=>t?mq(t.processes,t.executions):[],[t]),d=g.useMemo(()=>hq(c,s),[c,s]),p=g.useMemo(()=>{const b=new Set;for(const x of t?.processes??[])x.teamId&&b.add(x.teamId);for(const x of t?.executions??[])x.teamId&&b.add(x.teamId);return[...b].sort()},[t]);if(r&&(!t||c.length===0))return o.jsxs("div",{className:"p-4 text-sm text-error",role:"alert","data-processes-tab-error":!0,children:["Failed to load processes: ",r]});if(!t)return o.jsx("div",{className:"p-4","data-processes-tab-loading":!0,children:o.jsx(Fa,{size:"sm"})});if(c.length===0)return o.jsxs("div",{className:"p-4 text-sm text-spur-text-muted","data-processes-tab-empty":!0,children:["No processes. Start an agent from the Agents tab or via"," ",o.jsx("code",{className:"font-mono",children:"spur agent start"}),"."]});if(d.length===0)return o.jsxs("div",{className:"p-3 overflow-auto h-full","data-processes-tab":!0,"data-processes-tab-filtered-empty":!0,children:[o.jsx(Wy,{filters:s,onFilters:i,teamIds:p,totalCount:c.length,shownCount:0}),o.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-processes-tab-no-matches":!0,children:"No processes match the current filters. Adjust or clear filters to see rows."})]});const m=t.processes.length,f=Math.max(0,c.length-m);return o.jsxs("div",{className:"p-3 overflow-auto h-full","data-processes-tab":!0,children:[o.jsx(Wy,{filters:s,onFilters:i,teamIds:p,totalCount:c.length,shownCount:d.length}),o.jsxs("div",{className:"flex items-center gap-2 mb-2 text-xs text-spur-text-muted",children:[o.jsxs("span",{"data-processes-header":!0,children:["Process watch list (",c.length,m>0||f>0?` · ${m} supervised${f>0?` · ${f} other`:""}`:"",")"]}),o.jsx("span",{className:"italic",children:"— ProcessExecutor registry (ts-runtime)"})]}),o.jsxs("table",{className:"table table-xs",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Name"}),o.jsx("th",{children:"Source"}),o.jsx("th",{children:"Team"}),o.jsx("th",{children:"PID"}),o.jsx("th",{children:"Status"}),o.jsx("th",{children:"Started"})]})}),o.jsx("tbody",{children:d.map(b=>{const x=b.status==="running";return o.jsxs("tr",{"data-processes-row":b.key,children:[o.jsx("td",{className:"font-mono text-xs",children:b.label}),o.jsx("td",{className:"text-xs text-spur-text-muted","data-process-source":b.source,children:b.source}),o.jsx("td",{className:"font-mono text-xs text-spur-text-muted","data-process-team":b.teamId??"",children:b.teamId??"—"}),o.jsx("td",{className:"font-mono text-xs text-spur-text-muted",children:b.pid??"—"}),o.jsx("td",{children:o.jsx(gn,{variant:x?"success":"ghost",size:"xs",children:b.status})}),o.jsx("td",{className:"text-xs text-spur-text-muted",children:new Date(b.startedAt).toLocaleTimeString()})]},b.key)})})]})]})}const bq="conversation",Lr=[{id:"conversation",label:"Conversation",component:cq},{id:"agents",label:"Agents",component:aq},{id:"processes",label:"Processes",component:gq}];function xq(){const e=Zn(),t=qi();return{activeTab:(()=>{const a=e.pathname.split("/"),s=a.indexOf("projects"),i=s>=0?a[s+1]:void 0;return Lr.some(l=>l.id===i)?i:bq})(),selectTab:a=>{const s=new URLSearchParams(e.search).toString();t(`/board/projects/${a}${s?`?${s}`:""}`,{replace:!0})}}}function Eq(e){if(e.state==="loading")return"loading";if(e.state==="unresolvable")return"unresolvable";if(e.fleet===null)return"fleet-unavailable";const{orchestrator:t,capacity:n,strategy:r}=e.fleet;return t.state!=="bound-online"?t.state:n.total===0?"no-fleet":n.missing.length>0?"capacity-missing":r===null?"strategy-unavailable":"ready"}function yq(e){switch(e.orchestrator.state){case"bound-online":return`online${e.orchestrator.instanceId?` — ${e.orchestrator.instanceId}`:""}`;case"bound-offline":return"bound but not responding";case"missing":return"no orchestrator bound";case"unresolvable":return`unresolvable${e.orchestrator.reason?` — ${e.orchestrator.reason}`:""}`}}function cN(){const e=Os(),{activeTab:t,selectTab:n}=xq(),a=(Lr.find(u=>u.id===t)??Lr[0])?.component,s=Eq(e),i=e.fleet,l=u=>{if(u.key!=="ArrowRight"&&u.key!=="ArrowLeft")return;u.preventDefault();const c=Lr.findIndex(m=>m.id===t),d=u.key==="ArrowRight"?1:-1,p=Lr[(c+d+Lr.length)%Lr.length];p&&(u.currentTarget.querySelectorAll('[role="tab"]')[Lr.indexOf(p)]?.focus(),n(p.id))};return o.jsxs("div",{className:"projects flex flex-col h-full overflow-hidden bg-spur-bg","data-projects-shell":!0,children:[o.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-spur-surface shrink-0 flex flex-col gap-1","data-projects-header":!0,"data-projects-state":s,children:[e.state==="unresolvable"?o.jsxs("div",{className:"text-xs",children:[o.jsx("span",{className:"font-semibold text-spur-text",children:"Project path unavailable"}),o.jsxs("span",{className:"text-spur-text-muted",children:[" ","— the server did not report this project's worktree path; project-scoped state stays unloaded."]})]}):o.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[o.jsx("span",{className:"text-sm font-semibold text-spur-text shrink-0",children:e.name||"Projects"}),o.jsx("span",{className:"text-xs text-spur-text-muted font-mono",children:e.path})]}),e.state!=="unresolvable"&&i===null&&o.jsx("div",{className:"text-xs text-spur-text-muted",children:"Fleet status unavailable"}),i!==null&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-xs text-spur-text-muted",children:["Orchestrator: ",o.jsx("span",{className:"text-spur-text",children:yq(i)})]}),o.jsxs("div",{className:"text-xs text-spur-text-muted",children:["Fleet:"," ",i.capacity.total===0?o.jsxs("span",{className:"text-spur-text",children:["no fleet declared — expected"," ",o.jsx("code",{className:"font-mono",children:"agent.fleet in .spur/config.yaml"})]}):i.enabled===!1?o.jsxs("span",{className:"text-spur-text",children:["disabled (",o.jsx("code",{className:"font-mono",children:"agent.fleet.enabled: false"}),") —"," ",i.capacity.total," member",i.capacity.total===1?"":"s"," declared"]}):o.jsxs("span",{className:"text-spur-text",children:[i.capacity.total," member",i.capacity.total===1?"":"s"," ·"," ",i.capacity.enabled," enabled · ",i.capacity.writeCapable," write-capable",i.capacity.missing.length>0?` · unresolved: ${i.capacity.missing.join(", ")}`:""]})]}),o.jsxs("div",{className:"text-xs text-spur-text-muted",children:["Strategy:"," ",i.strategy===null?o.jsx("span",{className:"text-spur-text",children:"strategy unavailable"}):o.jsxs("span",{className:"text-spur-text",children:[i.strategy.name," (v",i.strategy.version,")"]})]})]})]}),o.jsx("div",{role:"tablist","aria-label":"Projects tabs",onKeyDown:l,className:"flex items-center gap-1 px-2 py-1 border-b border-spur-border bg-spur-surface shrink-0",children:Lr.map(u=>{const c=u.id===t;return o.jsx("button",{type:"button",role:"tab","aria-selected":c,"aria-controls":`projects-tab-panel-${u.id}`,id:`projects-tab-${u.id}`,onClick:()=>n(u.id),className:`px-3 py-1 rounded-lg text-xs font-medium transition-colors ${c?"bg-spur-accent text-white":"text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-3"}`,"data-projects-tab":u.id,children:u.label},u.id)})}),o.jsx("div",{role:"tabpanel",id:`projects-tab-panel-${t}`,"aria-labelledby":`projects-tab-${t}`,className:"flex-1 overflow-hidden",children:a?o.jsx(a,{}):null})]})}const Tq={id:"projects",name:"Projects",icon:"📁",route:"projects",component:cN,sidebarLabel:"Projects",description:"Conversation, agents, and processes for this project",order:45},Sq=Object.freeze(Object.defineProperty({__proto__:null,ProjectsShell:cN,module:Tq},Symbol.toStringTag,{value:"Module"})),Bu=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Ls(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Gb(e){return"nodeType"in e}function jn(e){var t,n;return e?Ls(e)?e:Gb(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Wb(e){const{Document:t}=jn(e);return e instanceof t}function po(e){return Ls(e)?!1:e instanceof jn(e).HTMLElement}function dN(e){return e instanceof jn(e).SVGElement}function Ms(e){return e?Ls(e)?e.document:Gb(e)?Wb(e)?e:po(e)||dN(e)?e.ownerDocument:document:document:document}const Br=Bu?g.useLayoutEffect:g.useEffect;function Uu(e){const t=g.useRef(e);return Br(()=>{t.current=e}),g.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return t.current==null?void 0:t.current(...r)},[])}function vq(){const e=g.useRef(null),t=g.useCallback((r,a)=>{e.current=setInterval(r,a)},[]),n=g.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function $i(e,t){t===void 0&&(t=[e]);const n=g.useRef(e);return Br(()=>{n.current!==e&&(n.current=e)},t),n}function fo(e,t){const n=g.useRef();return g.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function Pl(e){const t=Uu(e),n=g.useRef(null),r=g.useCallback(a=>{a!==n.current&&t?.(a,n.current),n.current=a},[]);return[n,r]}function Bl(e){const t=g.useRef();return g.useEffect(()=>{t.current=e},[e]),t.current}let Zc={};function $u(e,t){return g.useMemo(()=>{if(t)return t;const n=Zc[e]==null?0:Zc[e]+1;return Zc[e]=n,e+"-"+n},[e,t])}function pN(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return r.reduce((s,i)=>{const l=Object.entries(i);for(const[u,c]of l){const d=s[u];d!=null&&(s[u]=d+e*c)}return s},{...t})}}const cs=pN(1),Ul=pN(-1);function wq(e){return"clientX"in e&&"clientY"in e}function qb(e){if(!e)return!1;const{KeyboardEvent:t}=jn(e.target);return t&&e instanceof t}function Nq(e){if(!e)return!1;const{TouchEvent:t}=jn(e.target);return t&&e instanceof t}function $l(e){if(Nq(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return wq(e)?{x:e.clientX,y:e.clientY}:null}const bs=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[bs.Translate.toString(e),bs.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),qy="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Aq(e){return e.matches(qy)?e:e.querySelector(qy)}const _q={display:"none"};function kq(e){let{id:t,value:n}=e;return at.createElement("div",{id:t,style:_q},n)}function Cq(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return at.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function Iq(){const[e,t]=g.useState("");return{announce:g.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const fN=g.createContext(null);function Rq(e){const t=g.useContext(fN);g.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function Dq(){const[e]=g.useState(()=>new Set),t=g.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[g.useCallback(r=>{let{type:a,event:s}=r;e.forEach(i=>{var l;return(l=i[a])==null?void 0:l.call(i,s)})},[e]),t]}const Oq={draggable:`
184
184
  To pick up a draggable item, press the space bar.
185
185
  While dragging, use the arrow keys to move the item.
186
186
  Press space again to drop the item in its new position, or press escape to cancel.
187
- `},Lq={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function Mq(e){let{announcements:t=Lq,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=Oq}=e;const{announce:s,announcement:i}=Iq(),l=$u("DndLiveRegion"),[u,c]=g.useState(!1);if(g.useEffect(()=>{c(!0)},[]),Rq(g.useMemo(()=>({onDragStart(p){let{active:m}=p;s(t.onDragStart({active:m}))},onDragMove(p){let{active:m,over:f}=p;t.onDragMove&&s(t.onDragMove({active:m,over:f}))},onDragOver(p){let{active:m,over:f}=p;s(t.onDragOver({active:m,over:f}))},onDragEnd(p){let{active:m,over:f}=p;s(t.onDragEnd({active:m,over:f}))},onDragCancel(p){let{active:m,over:f}=p;s(t.onDragCancel({active:m,over:f}))}}),[s,t])),!u)return null;const d=at.createElement(at.Fragment,null,at.createElement(kq,{id:r,value:a.draggable}),at.createElement(Cq,{id:l,announcement:i}));return n?na.createPortal(d,n):d}var on;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(on||(on={}));function zl(){}function Vy(e,t){return g.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function Fq(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return g.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const pr=Object.freeze({x:0,y:0});function jq(e,t){const n=$l(e);if(!n)return"0 0";const r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+"% "+r.y+"%"}function Pq(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function Bq(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function Uq(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),a=Math.min(t.left+t.width,e.left+e.width),s=Math.min(t.top+t.height,e.top+e.height),i=a-r,l=s-n;if(r<a&&n<s){const u=t.width*t.height,c=e.width*e.height,d=i*l,p=d/(u+c-d);return Number(p.toFixed(4))}return 0}const $q=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const a=[];for(const s of r){const{id:i}=s,l=n.get(i);if(l){const u=Uq(l,t);u>0&&a.push({id:i,data:{droppableContainer:s,value:u}})}}return a.sort(Pq)};function zq(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function mN(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:pr}function Hq(e){return function(n){for(var r=arguments.length,a=new Array(r>1?r-1:0),s=1;s<r;s++)a[s-1]=arguments[s];return a.reduce((i,l)=>({...i,top:i.top+e*l.y,bottom:i.bottom+e*l.y,left:i.left+e*l.x,right:i.right+e*l.x}),{...n})}}const Gq=Hq(1);function hN(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Wq(e,t,n){const r=hN(t);if(!r)return e;const{scaleX:a,scaleY:s,x:i,y:l}=r,u=e.left-i-(1-a)*parseFloat(n),c=e.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),d=a?e.width/a:e.width,p=s?e.height/s:e.height;return{width:d,height:p,top:c,right:u+d,bottom:c+p,left:u}}const qq={ignoreTransform:!1};function mo(e,t){t===void 0&&(t=qq);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:d}=jn(e).getComputedStyle(e);c&&(n=Wq(n,c,d))}const{top:r,left:a,width:s,height:i,bottom:l,right:u}=n;return{top:r,left:a,width:s,height:i,bottom:l,right:u}}function Yy(e){return mo(e,{ignoreTransform:!0})}function Vq(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Yq(e,t){return t===void 0&&(t=jn(e).getComputedStyle(e)),t.position==="fixed"}function Kq(e,t){t===void 0&&(t=jn(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const s=t[a];return typeof s=="string"?n.test(s):!1})}function Vb(e,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(Wb(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!po(a)||dN(a)||n.includes(a))return n;const s=jn(e).getComputedStyle(a);return a!==e&&Kq(a,s)&&n.push(a),Yq(a,s)?n:r(a.parentNode)}return e?r(e):n}function gN(e){const[t]=Vb(e,1);return t??null}function Xc(e){return!Bu||!e?null:Ls(e)?e:Gb(e)?Wb(e)||e===Ms(e).scrollingElement?window:po(e)?e:null:null}function bN(e){return Ls(e)?e.scrollX:e.scrollLeft}function xN(e){return Ls(e)?e.scrollY:e.scrollTop}function Zd(e){return{x:bN(e),y:xN(e)}}var mn;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(mn||(mn={}));function EN(e){return!Bu||!e?!1:e===document.scrollingElement}function yN(e){const t={x:0,y:0},n=EN(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},a=e.scrollTop<=t.y,s=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,l=e.scrollLeft>=r.x;return{isTop:a,isLeft:s,isBottom:i,isRight:l,maxScroll:r,minScroll:t}}const Zq={x:.2,y:.2};function Xq(e,t,n,r,a){let{top:s,left:i,right:l,bottom:u}=n;r===void 0&&(r=10),a===void 0&&(a=Zq);const{isTop:c,isBottom:d,isLeft:p,isRight:m}=yN(e),f={x:0,y:0},b={x:0,y:0},x={height:t.height*a.y,width:t.width*a.x};return!c&&s<=t.top+x.height?(f.y=mn.Backward,b.y=r*Math.abs((t.top+x.height-s)/x.height)):!d&&u>=t.bottom-x.height&&(f.y=mn.Forward,b.y=r*Math.abs((t.bottom-x.height-u)/x.height)),!m&&l>=t.right-x.width?(f.x=mn.Forward,b.x=r*Math.abs((t.right-x.width-l)/x.width)):!p&&i<=t.left+x.width&&(f.x=mn.Backward,b.x=r*Math.abs((t.left+x.width-i)/x.width)),{direction:f,speed:b}}function Qq(e){if(e===document.scrollingElement){const{innerWidth:s,innerHeight:i}=window;return{top:0,left:0,right:s,bottom:i,width:s,height:i}}const{top:t,left:n,right:r,bottom:a}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:a,width:e.clientWidth,height:e.clientHeight}}function TN(e){return e.reduce((t,n)=>cs(t,Zd(n)),pr)}function Jq(e){return e.reduce((t,n)=>t+bN(n),0)}function eV(e){return e.reduce((t,n)=>t+xN(n),0)}function SN(e,t){if(t===void 0&&(t=mo),!e)return;const{top:n,left:r,bottom:a,right:s}=t(e);gN(e)&&(a<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const tV=[["x",["left","right"],Jq],["y",["top","bottom"],eV]];class Yb{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=Vb(n),a=TN(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,i,l]of tV)for(const u of i)Object.defineProperty(this,u,{get:()=>{const c=l(r),d=a[s]-c;return this.rect[u]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ti{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var a;(a=this.target)==null||a.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function nV(e){const{EventTarget:t}=jn(e);return e instanceof t?e:Ms(e)}function Qc(e,t){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var nr;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(nr||(nr={}));function Ky(e){e.preventDefault()}function rV(e){e.stopPropagation()}var Pt;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Pt||(Pt={}));const vN={start:[Pt.Space,Pt.Enter],cancel:[Pt.Esc],end:[Pt.Space,Pt.Enter,Pt.Tab]},aV=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Pt.Right:return{...n,x:n.x+25};case Pt.Left:return{...n,x:n.x-25};case Pt.Down:return{...n,y:n.y+25};case Pt.Up:return{...n,y:n.y-25}}};class Kb{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Ti(Ms(n)),this.windowListeners=new Ti(jn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(nr.Resize,this.handleCancel),this.windowListeners.add(nr.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(nr.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&SN(r),n(pr)}handleKeyDown(t){if(qb(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:s=vN,coordinateGetter:i=aV,scrollBehavior:l="smooth"}=a,{code:u}=t;if(s.end.includes(u)){this.handleEnd(t);return}if(s.cancel.includes(u)){this.handleCancel(t);return}const{collisionRect:c}=r.current,d=c?{x:c.left,y:c.top}:pr;this.referenceCoordinates||(this.referenceCoordinates=d);const p=i(t,{active:n,context:r.current,currentCoordinates:d});if(p){const m=Ul(p,d),f={x:0,y:0},{scrollableAncestors:b}=r.current;for(const x of b){const E=t.code,{isTop:y,isRight:S,isLeft:v,isBottom:N,maxScroll:A,minScroll:w}=yN(x),T=Qq(x),_={x:Math.min(E===Pt.Right?T.right-T.width/2:T.right,Math.max(E===Pt.Right?T.left:T.left+T.width/2,p.x)),y:Math.min(E===Pt.Down?T.bottom-T.height/2:T.bottom,Math.max(E===Pt.Down?T.top:T.top+T.height/2,p.y))},B=E===Pt.Right&&!S||E===Pt.Left&&!v,k=E===Pt.Down&&!N||E===Pt.Up&&!y;if(B&&_.x!==p.x){const $=x.scrollLeft+m.x,V=E===Pt.Right&&$<=A.x||E===Pt.Left&&$>=w.x;if(V&&!m.y){x.scrollTo({left:$,behavior:l});return}V?f.x=x.scrollLeft-$:f.x=E===Pt.Right?x.scrollLeft-A.x:x.scrollLeft-w.x,f.x&&x.scrollBy({left:-f.x,behavior:l});break}else if(k&&_.y!==p.y){const $=x.scrollTop+m.y,V=E===Pt.Down&&$<=A.y||E===Pt.Up&&$>=w.y;if(V&&!m.x){x.scrollTo({top:$,behavior:l});return}V?f.y=x.scrollTop-$:f.y=E===Pt.Down?x.scrollTop-A.y:x.scrollTop-w.y,f.y&&x.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(t,cs(Ul(p,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Kb.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=vN,onActivation:a}=t,{active:s}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const l=s.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),a?.({event:e.nativeEvent}),!0)}return!1}}];function Zy(e){return!!(e&&"distance"in e)}function Xy(e){return!!(e&&"delay"in e)}class Zb{constructor(t,n,r){var a;r===void 0&&(r=nV(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:s}=t,{target:i}=s;this.props=t,this.events=n,this.document=Ms(i),this.documentListeners=new Ti(this.document),this.listeners=new Ti(r),this.windowListeners=new Ti(jn(i)),this.initialCoordinates=(a=$l(s))!=null?a:pr,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(nr.Resize,this.handleCancel),this.windowListeners.add(nr.DragStart,Ky),this.windowListeners.add(nr.VisibilityChange,this.handleCancel),this.windowListeners.add(nr.ContextMenu,Ky),this.documentListeners.add(nr.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Xy(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Zy(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:a}=this.props;a(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(nr.Click,rV,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(nr.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:a,props:s}=this,{onMove:i,options:{activationConstraint:l}}=s;if(!a)return;const u=(n=$l(t))!=null?n:pr,c=Ul(a,u);if(!r&&l){if(Zy(l)){if(l.tolerance!=null&&Qc(c,l.tolerance))return this.handleCancel();if(Qc(c,l.distance))return this.handleStart()}if(Xy(l)&&Qc(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}t.cancelable&&t.preventDefault(),i(u)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Pt.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const sV={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Xb extends Zb{constructor(t){const{event:n}=t,r=Ms(n.target);super(t,sV,r)}}Xb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const iV={move:{name:"mousemove"},end:{name:"mouseup"}};var Xd;(function(e){e[e.RightClick=2]="RightClick"})(Xd||(Xd={}));class oV extends Zb{constructor(t){super(t,iV,Ms(t.event.target))}}oV.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===Xd.RightClick?!1:(r?.({event:n}),!0)}}];const Jc={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class lV extends Zb{constructor(t){super(t,Jc)}static setup(){return window.addEventListener(Jc.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Jc.move.name,t)};function t(){}}}lV.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:a}=n;return a.length>1?!1:(r?.({event:n}),!0)}}];var Si;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Si||(Si={}));var Hl;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(Hl||(Hl={}));function uV(e){let{acceleration:t,activator:n=Si.Pointer,canScroll:r,draggingRect:a,enabled:s,interval:i=5,order:l=Hl.TreeOrder,pointerCoordinates:u,scrollableAncestors:c,scrollableAncestorRects:d,delta:p,threshold:m}=e;const f=dV({delta:p,disabled:!s}),[b,x]=vq(),E=g.useRef({x:0,y:0}),y=g.useRef({x:0,y:0}),S=g.useMemo(()=>{switch(n){case Si.Pointer:return u?{top:u.y,bottom:u.y,left:u.x,right:u.x}:null;case Si.DraggableRect:return a}},[n,a,u]),v=g.useRef(null),N=g.useCallback(()=>{const w=v.current;if(!w)return;const T=E.current.x*y.current.x,_=E.current.y*y.current.y;w.scrollBy(T,_)},[]),A=g.useMemo(()=>l===Hl.TreeOrder?[...c].reverse():c,[l,c]);g.useEffect(()=>{if(!s||!c.length||!S){x();return}for(const w of A){if(r?.(w)===!1)continue;const T=c.indexOf(w),_=d[T];if(!_)continue;const{direction:B,speed:k}=Xq(w,_,S,t,m);for(const $ of["x","y"])f[$][B[$]]||(k[$]=0,B[$]=0);if(k.x>0||k.y>0){x(),v.current=w,b(N,i),E.current=k,y.current=B;return}}E.current={x:0,y:0},y.current={x:0,y:0},x()},[t,N,r,x,s,i,JSON.stringify(S),JSON.stringify(f),b,c,A,d,JSON.stringify(m)])}const cV={x:{[mn.Backward]:!1,[mn.Forward]:!1},y:{[mn.Backward]:!1,[mn.Forward]:!1}};function dV(e){let{delta:t,disabled:n}=e;const r=Bl(t);return fo(a=>{if(n||!r||!a)return cV;const s={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[mn.Backward]:a.x[mn.Backward]||s.x===-1,[mn.Forward]:a.x[mn.Forward]||s.x===1},y:{[mn.Backward]:a.y[mn.Backward]||s.y===-1,[mn.Forward]:a.y[mn.Forward]||s.y===1}}},[n,t,r])}function pV(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return fo(a=>{var s;return t==null?null:(s=r??a)!=null?s:null},[r,t])}function fV(e,t){return g.useMemo(()=>e.reduce((n,r)=>{const{sensor:a}=r,s=a.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...s]},[]),[e,t])}var zi;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(zi||(zi={}));var Qd;(function(e){e.Optimized="optimized"})(Qd||(Qd={}));const Qy=new Map;function mV(e,t){let{dragging:n,dependencies:r,config:a}=t;const[s,i]=g.useState(null),{frequency:l,measure:u,strategy:c}=a,d=g.useRef(e),p=E(),m=$i(p),f=g.useCallback(function(y){y===void 0&&(y=[]),!m.current&&i(S=>S===null?y:S.concat(y.filter(v=>!S.includes(v))))},[m]),b=g.useRef(null),x=fo(y=>{if(p&&!n)return Qy;if(!y||y===Qy||d.current!==e||s!=null){const S=new Map;for(let v of e){if(!v)continue;if(s&&s.length>0&&!s.includes(v.id)&&v.rect.current){S.set(v.id,v.rect.current);continue}const N=v.node.current,A=N?new Yb(u(N),N):null;v.rect.current=A,A&&S.set(v.id,A)}return S}return y},[e,s,n,p,u]);return g.useEffect(()=>{d.current=e},[e]),g.useEffect(()=>{p||f()},[n,p]),g.useEffect(()=>{s&&s.length>0&&i(null)},[JSON.stringify(s)]),g.useEffect(()=>{p||typeof l!="number"||b.current!==null||(b.current=setTimeout(()=>{f(),b.current=null},l))},[l,p,f,...r]),{droppableRects:x,measureDroppableContainers:f,measuringScheduled:s!=null};function E(){switch(c){case zi.Always:return!1;case zi.BeforeDragging:return n;default:return!n}}}function Qb(e,t){return fo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function hV(e,t){return Qb(e,t)}function gV(e){let{callback:t,disabled:n}=e;const r=Uu(t),a=g.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return g.useEffect(()=>()=>a?.disconnect(),[a]),a}function zu(e){let{callback:t,disabled:n}=e;const r=Uu(t),a=g.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return g.useEffect(()=>()=>a?.disconnect(),[a]),a}function bV(e){return new Yb(mo(e),e)}function Jy(e,t,n){t===void 0&&(t=bV);const[r,a]=g.useState(null);function s(){a(u=>{if(!e)return null;if(e.isConnected===!1){var c;return(c=u??n)!=null?c:null}const d=t(e);return JSON.stringify(u)===JSON.stringify(d)?u:d})}const i=gV({callback(u){if(e)for(const c of u){const{type:d,target:p}=c;if(d==="childList"&&p instanceof HTMLElement&&p.contains(e)){s();break}}}}),l=zu({callback:s});return Br(()=>{s(),e?(l?.observe(e),i?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),i?.disconnect())},[e]),r}function xV(e){const t=Qb(e);return mN(e,t)}const e1=[];function EV(e){const t=g.useRef(e),n=fo(r=>e?r&&r!==e1&&e&&t.current&&e.parentNode===t.current.parentNode?r:Vb(e):e1,[e]);return g.useEffect(()=>{t.current=e},[e]),n}function yV(e){const[t,n]=g.useState(null),r=g.useRef(e),a=g.useCallback(s=>{const i=Xc(s.target);i&&n(l=>l?(l.set(i,Zd(i)),new Map(l)):null)},[]);return g.useEffect(()=>{const s=r.current;if(e!==s){i(s);const l=e.map(u=>{const c=Xc(u);return c?(c.addEventListener("scroll",a,{passive:!0}),[c,Zd(c)]):null}).filter(u=>u!=null);n(l.length?new Map(l):null),r.current=e}return()=>{i(e),i(s)};function i(l){l.forEach(u=>{const c=Xc(u);c?.removeEventListener("scroll",a)})}},[a,e]),g.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,i)=>cs(s,i),pr):TN(e):pr,[e,t])}function t1(e,t){t===void 0&&(t=[]);const n=g.useRef(null);return g.useEffect(()=>{n.current=null},t),g.useEffect(()=>{const r=e!==pr;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?Ul(e,n.current):pr}function TV(e){g.useEffect(()=>{if(!Bu)return;const t=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function SV(e,t){return g.useMemo(()=>e.reduce((n,r)=>{let{eventName:a,handler:s}=r;return n[a]=i=>{s(i,t)},n},{}),[e,t])}function wN(e){return g.useMemo(()=>e?Vq(e):null,[e])}const n1=[];function vV(e,t){t===void 0&&(t=mo);const[n]=e,r=wN(n?jn(n):null),[a,s]=g.useState(n1);function i(){s(()=>e.length?e.map(u=>EN(u)?r:new Yb(t(u),u)):n1)}const l=zu({callback:i});return Br(()=>{l?.disconnect(),i(),e.forEach(u=>l?.observe(u))},[e]),a}function NN(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return po(t)?t:e}function wV(e){let{measure:t}=e;const[n,r]=g.useState(null),a=g.useCallback(c=>{for(const{target:d}of c)if(po(d)){r(p=>{const m=t(d);return p?{...p,width:m.width,height:m.height}:m});break}},[t]),s=zu({callback:a}),i=g.useCallback(c=>{const d=NN(c);s?.disconnect(),d&&s?.observe(d),r(d?t(d):null)},[t,s]),[l,u]=Pl(i);return g.useMemo(()=>({nodeRef:l,rect:n,setRef:u}),[n,l,u])}const NV=[{sensor:Xb,options:{}},{sensor:Kb,options:{}}],AV={current:{}},cl={draggable:{measure:Yy},droppable:{measure:Yy,strategy:zi.WhileDragging,frequency:Qd.Optimized},dragOverlay:{measure:mo}};class vi extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const _V={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new vi,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:zl},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:cl,measureDroppableContainers:zl,windowRect:null,measuringScheduled:!1},AN={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:zl,draggableNodes:new Map,over:null,measureDroppableContainers:zl},ho=g.createContext(AN),_N=g.createContext(_V);function kV(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new vi}}}function CV(e,t){switch(t.type){case on.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case on.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case on.DragEnd:case on.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case on.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new vi(e.droppable.containers);return a.set(r,n),{...e,droppable:{...e.droppable,containers:a}}}case on.SetDroppableDisabled:{const{id:n,key:r,disabled:a}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const i=new vi(e.droppable.containers);return i.set(n,{...s,disabled:a}),{...e,droppable:{...e.droppable,containers:i}}}case on.UnregisterDroppable:{const{id:n,key:r}=t,a=e.droppable.containers.get(n);if(!a||r!==a.key)return e;const s=new vi(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function IV(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:a}=g.useContext(ho),s=Bl(r),i=Bl(n?.id);return g.useEffect(()=>{if(!t&&!r&&s&&i!=null){if(!qb(s)||document.activeElement===s.target)return;const l=a.get(i);if(!l)return;const{activatorNode:u,node:c}=l;if(!u.current&&!c.current)return;requestAnimationFrame(()=>{for(const d of[u.current,c.current]){if(!d)continue;const p=Aq(d);if(p){p.focus();break}}})}},[r,t,a,i,s]),null}function kN(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((a,s)=>s({transform:a,...r}),n):n}function RV(e){return g.useMemo(()=>({draggable:{...cl.draggable,...e?.draggable},droppable:{...cl.droppable,...e?.droppable},dragOverlay:{...cl.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function DV(e){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=e;const s=g.useRef(!1),{x:i,y:l}=typeof a=="boolean"?{x:a,y:a}:a;Br(()=>{if(!i&&!l||!t){s.current=!1;return}if(s.current||!r)return;const c=t?.node.current;if(!c||c.isConnected===!1)return;const d=n(c),p=mN(d,r);if(i||(p.x=0),l||(p.y=0),s.current=!0,Math.abs(p.x)>0||Math.abs(p.y)>0){const m=gN(c);m&&m.scrollBy({top:p.y,left:p.x})}},[t,i,l,r,n])}const Hu=g.createContext({...pr,scaleX:1,scaleY:1});var Kr;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Kr||(Kr={}));const OV=g.memo(function(t){var n,r,a,s;let{id:i,accessibility:l,autoScroll:u=!0,children:c,sensors:d=NV,collisionDetection:p=$q,measuring:m,modifiers:f,...b}=t;const x=g.useReducer(CV,void 0,kV),[E,y]=x,[S,v]=Dq(),[N,A]=g.useState(Kr.Uninitialized),w=N===Kr.Initialized,{draggable:{active:T,nodes:_,translate:B},droppable:{containers:k}}=E,$=T!=null?_.get(T):null,V=g.useRef({initial:null,translated:null}),P=g.useMemo(()=>{var De;return T!=null?{id:T,data:(De=$?.data)!=null?De:AV,rect:V}:null},[T,$]),H=g.useRef(null),[W,L]=g.useState(null),[te,ie]=g.useState(null),be=$i(b,Object.values(b)),I=$u("DndDescribedBy",i),ne=g.useMemo(()=>k.getEnabled(),[k]),ue=RV(m),{droppableRects:O,measureDroppableContainers:Ne,measuringScheduled:de}=mV(ne,{dragging:w,dependencies:[B.x,B.y],config:ue.droppable}),K=pV(_,T),Ee=g.useMemo(()=>te?$l(te):null,[te]),re=zt(),D=hV(K,ue.draggable.measure);DV({activeNode:T!=null?_.get(T):null,config:re.layoutShiftCompensation,initialRect:D,measure:ue.draggable.measure});const ye=Jy(K,ue.draggable.measure,D),Se=Jy(K?K.parentElement:null),pe=g.useRef({activatorEvent:null,active:null,activeNode:K,collisionRect:null,collisions:null,droppableRects:O,draggableNodes:_,draggingNode:null,draggingNodeRect:null,droppableContainers:k,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ae=k.getNodeFor((n=pe.current.over)==null?void 0:n.id),He=wV({measure:ue.dragOverlay.measure}),fe=(r=He.nodeRef.current)!=null?r:K,Je=w?(a=He.rect)!=null?a:ye:null,bt=!!(He.nodeRef.current&&He.rect),it=xV(bt?null:ye),Ft=wN(fe?jn(fe):null),Nt=EV(w?Ae??K:null),Tt=vV(Nt),$t=kN(f,{transform:{x:B.x-it.x,y:B.y-it.y,scaleX:1,scaleY:1},activatorEvent:te,active:P,activeNodeRect:ye,containerNodeRect:Se,draggingNodeRect:Je,over:pe.current.over,overlayNodeRect:He.rect,scrollableAncestors:Nt,scrollableAncestorRects:Tt,windowRect:Ft}),rt=Ee?cs(Ee,B):null,Me=yV(Nt),et=t1(Me),Q=t1(Me,[ye]),ce=cs($t,et),Re=Je?Gq(Je,$t):null,G=P&&Re?p({active:P,collisionRect:Re,droppableRects:O,droppableContainers:ne,pointerCoordinates:rt}):null,Fe=Bq(G,"id"),[Ve,pt]=g.useState(null),At=bt?$t:cs($t,Q),St=zq(At,(s=Ve?.rect)!=null?s:null,ye),Rt=g.useRef(null),le=g.useCallback((De,tt)=>{let{sensor:Xe,options:kt}=tt;if(H.current==null)return;const se=_.get(H.current);if(!se)return;const he=De.nativeEvent,st=new Xe({active:H.current,activeNode:se,event:he,options:kt,context:pe,onAbort(Y){if(!_.get(Y))return;const{onDragAbort:F}=be.current,q={id:Y};F?.(q),S({type:"onDragAbort",event:q})},onPending(Y,Ge,F,q){if(!_.get(Y))return;const{onDragPending:me}=be.current,ve={id:Y,constraint:Ge,initialCoordinates:F,offset:q};me?.(ve),S({type:"onDragPending",event:ve})},onStart(Y){const Ge=H.current;if(Ge==null)return;const F=_.get(Ge);if(!F)return;const{onDragStart:q}=be.current,X={activatorEvent:he,active:{id:Ge,data:F.data,rect:V}};na.unstable_batchedUpdates(()=>{q?.(X),A(Kr.Initializing),y({type:on.DragStart,initialCoordinates:Y,active:Ge}),S({type:"onDragStart",event:X}),L(Rt.current),ie(he)})},onMove(Y){y({type:on.DragMove,coordinates:Y})},onEnd:Ot(on.DragEnd),onCancel:Ot(on.DragCancel)});Rt.current=st;function Ot(Y){return async function(){const{active:F,collisions:q,over:X,scrollAdjustedTranslate:me}=pe.current;let ve=null;if(F&&me){const{cancelDrop:Le}=be.current;ve={activatorEvent:he,active:F,collisions:q,delta:me,over:X},Y===on.DragEnd&&typeof Le=="function"&&await Promise.resolve(Le(ve))&&(Y=on.DragCancel)}H.current=null,na.unstable_batchedUpdates(()=>{y({type:Y}),A(Kr.Uninitialized),pt(null),L(null),ie(null),Rt.current=null;const Le=Y===on.DragEnd?"onDragEnd":"onDragCancel";if(ve){const Oe=be.current[Le];Oe?.(ve),S({type:Le,event:ve})}})}}},[_]),Ce=g.useCallback((De,tt)=>(Xe,kt)=>{const se=Xe.nativeEvent,he=_.get(kt);if(H.current!==null||!he||se.dndKit||se.defaultPrevented)return;const st={active:he};De(Xe,tt.options,st)===!0&&(se.dndKit={capturedBy:tt.sensor},H.current=kt,le(Xe,tt))},[_,le]),Ue=fV(d,Ce);TV(d),Br(()=>{ye&&N===Kr.Initializing&&A(Kr.Initialized)},[ye,N]),g.useEffect(()=>{const{onDragMove:De}=be.current,{active:tt,activatorEvent:Xe,collisions:kt,over:se}=pe.current;if(!tt||!Xe)return;const he={active:tt,activatorEvent:Xe,collisions:kt,delta:{x:ce.x,y:ce.y},over:se};na.unstable_batchedUpdates(()=>{De?.(he),S({type:"onDragMove",event:he})})},[ce.x,ce.y]),g.useEffect(()=>{const{active:De,activatorEvent:tt,collisions:Xe,droppableContainers:kt,scrollAdjustedTranslate:se}=pe.current;if(!De||H.current==null||!tt||!se)return;const{onDragOver:he}=be.current,st=kt.get(Fe),Ot=st&&st.rect.current?{id:st.id,rect:st.rect.current,data:st.data,disabled:st.disabled}:null,Y={active:De,activatorEvent:tt,collisions:Xe,delta:{x:se.x,y:se.y},over:Ot};na.unstable_batchedUpdates(()=>{pt(Ot),he?.(Y),S({type:"onDragOver",event:Y})})},[Fe]),Br(()=>{pe.current={activatorEvent:te,active:P,activeNode:K,collisionRect:Re,collisions:G,droppableRects:O,draggableNodes:_,draggingNode:fe,draggingNodeRect:Je,droppableContainers:k,over:Ve,scrollableAncestors:Nt,scrollAdjustedTranslate:ce},V.current={initial:Je,translated:Re}},[P,K,G,Re,_,fe,Je,O,k,Ve,Nt,ce]),uV({...re,delta:B,draggingRect:Re,pointerCoordinates:rt,scrollableAncestors:Nt,scrollableAncestorRects:Tt});const je=g.useMemo(()=>({active:P,activeNode:K,activeNodeRect:ye,activatorEvent:te,collisions:G,containerNodeRect:Se,dragOverlay:He,draggableNodes:_,droppableContainers:k,droppableRects:O,over:Ve,measureDroppableContainers:Ne,scrollableAncestors:Nt,scrollableAncestorRects:Tt,measuringConfiguration:ue,measuringScheduled:de,windowRect:Ft}),[P,K,ye,te,G,Se,He,_,k,O,Ve,Ne,Nt,Tt,ue,de,Ft]),Et=g.useMemo(()=>({activatorEvent:te,activators:Ue,active:P,activeNodeRect:ye,ariaDescribedById:{draggable:I},dispatch:y,draggableNodes:_,over:Ve,measureDroppableContainers:Ne}),[te,Ue,P,ye,y,I,_,Ve,Ne]);return at.createElement(fN.Provider,{value:v},at.createElement(ho.Provider,{value:Et},at.createElement(_N.Provider,{value:je},at.createElement(Hu.Provider,{value:St},c)),at.createElement(IV,{disabled:l?.restoreFocus===!1})),at.createElement(Mq,{...l,hiddenTextDescribedById:I}));function zt(){const De=W?.autoScrollEnabled===!1,tt=typeof u=="object"?u.enabled===!1:u===!1,Xe=w&&!De&&!tt;return typeof u=="object"?{...u,enabled:Xe}:{enabled:Xe}}}),LV=g.createContext(null),r1="button",MV="Draggable";function FV(e){let{id:t,data:n,disabled:r=!1,attributes:a}=e;const s=$u(MV),{activators:i,activatorEvent:l,active:u,activeNodeRect:c,ariaDescribedById:d,draggableNodes:p,over:m}=g.useContext(ho),{role:f=r1,roleDescription:b="draggable",tabIndex:x=0}=a??{},E=u?.id===t,y=g.useContext(E?Hu:LV),[S,v]=Pl(),[N,A]=Pl(),w=SV(i,t),T=$i(n);Br(()=>(p.set(t,{id:t,key:s,node:S,activatorNode:N,data:T}),()=>{const B=p.get(t);B&&B.key===s&&p.delete(t)}),[p,t]);const _=g.useMemo(()=>({role:f,tabIndex:x,"aria-disabled":r,"aria-pressed":E&&f===r1?!0:void 0,"aria-roledescription":b,"aria-describedby":d.draggable}),[r,f,x,E,b,d.draggable]);return{active:u,activatorEvent:l,activeNodeRect:c,attributes:_,isDragging:E,listeners:r?void 0:w,node:S,over:m,setNodeRef:v,setActivatorNodeRef:A,transform:y}}function jV(){return g.useContext(_N)}const PV="Droppable",BV={timeout:25};function UV(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=e;const s=$u(PV),{active:i,dispatch:l,over:u,measureDroppableContainers:c}=g.useContext(ho),d=g.useRef({disabled:n}),p=g.useRef(!1),m=g.useRef(null),f=g.useRef(null),{disabled:b,updateMeasurementsFor:x,timeout:E}={...BV,...a},y=$i(x??r),S=g.useCallback(()=>{if(!p.current){p.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),f.current=null},E)},[E]),v=zu({callback:S,disabled:b||!i}),N=g.useCallback((_,B)=>{v&&(B&&(v.unobserve(B),p.current=!1),_&&v.observe(_))},[v]),[A,w]=Pl(N),T=$i(t);return g.useEffect(()=>{!v||!A.current||(v.disconnect(),p.current=!1,v.observe(A.current))},[A,v]),g.useEffect(()=>(l({type:on.RegisterDroppable,element:{id:r,key:s,disabled:n,node:A,rect:m,data:T}}),()=>l({type:on.UnregisterDroppable,key:s,id:r})),[r]),g.useEffect(()=>{n!==d.current.disabled&&(l({type:on.SetDroppableDisabled,id:r,key:s,disabled:n}),d.current.disabled=n)},[r,s,n,l]),{active:i,rect:m,isOver:u?.id===r,node:A,over:u,setNodeRef:w}}function $V(e){let{animation:t,children:n}=e;const[r,a]=g.useState(null),[s,i]=g.useState(null),l=Bl(n);return!n&&!r&&l&&a(l),Br(()=>{if(!s)return;const u=r?.key,c=r?.props.id;if(u==null||c==null){a(null);return}Promise.resolve(t(c,s)).then(()=>{a(null)})},[t,r,s]),at.createElement(at.Fragment,null,n,r?g.cloneElement(r,{ref:i}):null)}const zV={x:0,y:0,scaleX:1,scaleY:1};function HV(e){let{children:t}=e;return at.createElement(ho.Provider,{value:AN},at.createElement(Hu.Provider,{value:zV},t))}const GV={position:"fixed",touchAction:"none"},WV=e=>qb(e)?"transform 250ms ease":void 0,qV=g.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:a,children:s,className:i,rect:l,style:u,transform:c,transition:d=WV}=e;if(!l)return null;const p=a?c:{...c,scaleX:1,scaleY:1},m={...GV,width:l.width,height:l.height,top:l.top,left:l.left,transform:bs.Transform.toString(p),transformOrigin:a&&r?jq(r,l):void 0,transition:typeof d=="function"?d(r):d,...u};return at.createElement(n,{className:i,style:m,ref:t},s)}),VV=e=>t=>{let{active:n,dragOverlay:r}=t;const a={},{styles:s,className:i}=e;if(s!=null&&s.active)for(const[l,u]of Object.entries(s.active))u!==void 0&&(a[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,u));if(s!=null&&s.dragOverlay)for(const[l,u]of Object.entries(s.dragOverlay))u!==void 0&&r.node.style.setProperty(l,u);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[u,c]of Object.entries(a))n.node.style.setProperty(u,c);i!=null&&i.active&&n.node.classList.remove(i.active)}},YV=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:bs.Transform.toString(t)},{transform:bs.Transform.toString(n)}]},KV={duration:250,easing:"ease",keyframes:YV,sideEffects:VV({styles:{active:{opacity:"0"}}})};function ZV(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:a}=e;return Uu((s,i)=>{if(t===null)return;const l=n.get(s);if(!l)return;const u=l.node.current;if(!u)return;const c=NN(i);if(!c)return;const{transform:d}=jn(i).getComputedStyle(i),p=hN(d);if(!p)return;const m=typeof t=="function"?t:XV(t);return SN(u,a.draggable.measure),m({active:{id:s,data:l.data,node:u,rect:a.draggable.measure(u)},draggableNodes:n,dragOverlay:{node:i,rect:a.dragOverlay.measure(c)},droppableContainers:r,measuringConfiguration:a,transform:p})})}function XV(e){const{duration:t,easing:n,sideEffects:r,keyframes:a}={...KV,...e};return s=>{let{active:i,dragOverlay:l,transform:u,...c}=s;if(!t)return;const d={x:l.rect.left-i.rect.left,y:l.rect.top-i.rect.top},p={scaleX:u.scaleX!==1?i.rect.width*u.scaleX/l.rect.width:1,scaleY:u.scaleY!==1?i.rect.height*u.scaleY/l.rect.height:1},m={x:u.x-d.x,y:u.y-d.y,...p},f=a({...c,active:i,dragOverlay:l,transform:{initial:u,final:m}}),[b]=f,x=f[f.length-1];if(JSON.stringify(b)===JSON.stringify(x))return;const E=r?.({active:i,dragOverlay:l,...c}),y=l.node.animate(f,{duration:t,easing:n,fill:"forwards"});return new Promise(S=>{y.onfinish=()=>{E?.(),S()}})}}let a1=0;function QV(e){return g.useMemo(()=>{if(e!=null)return a1++,a1},[e])}const JV=at.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:a,transition:s,modifiers:i,wrapperElement:l="div",className:u,zIndex:c=999}=e;const{activatorEvent:d,active:p,activeNodeRect:m,containerNodeRect:f,draggableNodes:b,droppableContainers:x,dragOverlay:E,over:y,measuringConfiguration:S,scrollableAncestors:v,scrollableAncestorRects:N,windowRect:A}=jV(),w=g.useContext(Hu),T=QV(p?.id),_=kN(i,{activatorEvent:d,active:p,activeNodeRect:m,containerNodeRect:f,draggingNodeRect:E.rect,over:y,overlayNodeRect:E.rect,scrollableAncestors:v,scrollableAncestorRects:N,transform:w,windowRect:A}),B=Qb(m),k=ZV({config:r,draggableNodes:b,droppableContainers:x,measuringConfiguration:S}),$=B?E.setRef:void 0;return at.createElement(HV,null,at.createElement($V,{animation:k},p&&T?at.createElement(qV,{key:T,id:p.id,ref:$,as:l,activatorEvent:d,adjustScale:t,className:u,transition:s,rect:B,style:{zIndex:c,...a},transform:_},n):null))}),eY=6e4,tY=10080*60*1e3,nY={P1:"error",P2:"warning",P3:"neutral"},rY={backlog:"bg-spur-text-faint",todo:"bg-spur-info",wip:"bg-spur-warning",testing:"bg-spur-accent",done:"bg-spur-success",blocked:"bg-spur-error",cancelled:"bg-spur-text-faint"};function aY(e,t){const n=new Date(e).getTime(),r=t-n,a=Math.floor(r/1e3);if(a<60)return"just now";const s=Math.floor(a/60);if(s<60)return`${s}m ago`;const i=Math.floor(s/60);if(i<24)return`${i}h ago`;const l=Math.floor(i/24);return l<30?`${l}d ago`:`${Math.floor(l/30)}mo ago`}function CN({task:e,onClick:t}){const{attributes:n,listeners:r,setNodeRef:a,transform:s,isDragging:i}=FV({id:e.wbs,data:{task:e}}),[l,u]=g.useState(Date.now());g.useEffect(()=>{const f=setInterval(()=>u(Date.now()),eY);return()=>clearInterval(f)},[]);const c=s?{transform:bs.Transform.toString(s),zIndex:i?50:void 0}:void 0,{subtaskProgress:d}=jb(),p=d.get(e.wbs),m=e.updatedAt?l-new Date(e.updatedAt).getTime()>tY:!1;return o.jsx(kj,{variant:"compact",asChild:!0,className:`bg-spur-surface-2 hover:bg-spur-surface-3 rounded-xl border border-spur-border hover:border-spur-accent/40 cursor-pointer transition-colors w-full text-left ${i?"opacity-30":""}`,children:o.jsx("button",{ref:a,type:"button",style:c,onClick:()=>t(e.wbs),...r,...n,"aria-roledescription":"draggable card",children:o.jsxs(Cj,{className:"p-3 gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-mono font-semibold text-spur-text",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${rY[e.status]??"bg-spur-text-faint"}`,"data-status":e.status,"aria-hidden":"true"}),e.wbs]}),e.priority&&o.jsx(gn,{variant:nY[e.priority]??"outline",size:"xs",children:e.priority})]}),o.jsx("p",{className:"text-sm font-medium text-spur-text leading-snug line-clamp-2",children:e.name}),o.jsxs("div",{className:"flex gap-1 flex-wrap items-center",children:[p&&p.total>0&&o.jsxs("div",{className:"flex items-center gap-1.5","data-testid":"subtask-progress",title:"subtasks done/total",children:[o.jsx("div",{className:"h-1 flex-1 rounded-full bg-spur-border overflow-hidden",children:o.jsx("div",{className:"h-full bg-spur-success",style:{width:`${Math.round(p.done/p.total*100)}%`}})}),o.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted shrink-0",children:[p.done,"/",p.total]})]}),e.type&&e.type!=="task"&&o.jsx(gn,{variant:"outline",size:"xs",children:e.type}),e.featureId&&o.jsx(gn,{variant:"outline",size:"xs",children:e.featureId}),e.updatedAt&&o.jsx("span",{className:`text-xs font-mono ml-auto ${m?"text-spur-text-faint":"text-spur-text-muted"}`,title:e.updatedAt,children:aY(e.updatedAt,l)})]})]})})})}function sY({status:e,label:t,tasks:n,onCardClick:r,sortDir:a,onSortToggle:s}){const{setNodeRef:i,isOver:l}=UV({id:e,data:{status:e}});return o.jsxs("section",{ref:i,"aria-label":`${t} column`,className:`flex flex-col flex-1 min-w-[16rem] rounded-xl border transition-colors duration-200 ${l?"bg-spur-surface-2 border-spur-accent shadow-lg":"bg-spur-surface border-spur-border"}`,children:[o.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border shrink-0",children:[o.jsxs("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:[Mb(e)," ",t]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(gn,{variant:"ghost",size:"sm",children:n.length}),s&&o.jsx(ot,{variant:"ghost",size:"xs",className:"px-1",onClick:s,"aria-label":`Sort ${t} by WBS`,title:`Sort ${t}: ${a==="asc"?"WBS ↓":a==="desc"?"WBS ↑":"none"}`,children:a==="asc"?"↓":a==="desc"?"↑":"⇅"})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-2 min-h-[4rem]",children:[n.map(u=>o.jsx(CN,{task:u,onClick:r},u.wbs)),n.length===0&&o.jsx("div",{className:"flex items-center justify-center h-16 text-xs text-spur-text-muted italic",children:"No tasks"})]})]})}const iY=g.lazy(()=>ww(()=>import("./TaskDetail.CGwJAinW.js"),__vite__mapDeps([2,1]))),oY=sr,IN="docs/tasks",s1="spur:detail-width",lY=new Set(["blocked","cancelled"]);function uY(e,t){return t?e.filter(n=>!(t.status!==void 0&&!t.status.split(",").includes(n.status)||t.featureId&&!n.featureId?.toLowerCase().includes(t.featureId.toLowerCase())||t.parentWbs&&n.parentWbs!==t.parentWbs)):e}function RN(e){const{onSelectTask:t,filters:n,folder:r,hiddenColumns:a,onConnectionChange:s,onSyncChange:i}=e,[l,u]=g.useState({}),[c,d]=g.useState(IN),[p,m]=g.useState(null),[f,b]=g.useState(()=>{const ne=typeof window<"u"?Math.min(1728,window.innerWidth*.8):1728;if(typeof window>"u")return ne;try{const ue=Number.parseFloat(window.localStorage.getItem(s1)??"");if(Number.isFinite(ue)&&ue>0)return Math.min(ue,window.innerWidth*.8)}catch{}return ne}),x=r??c,E=a??lY,y=g.useCallback(()=>rn.task.list({folder:x}),[x]),{tasks:S,loading:v,error:N,connected:A,lastSyncAt:w,setTasks:T,store:_}=jb(y),[B,k]=g.useState(null);g.useEffect(()=>{s?.(A)},[A,s]),g.useEffect(()=>{i?.(w)},[w,i]),g.useEffect(()=>{typeof rn.task.folders=="function"&&rn.task.folders({}).then(ne=>{const{data:ue,activeFolder:O}=ne,Ne=O??ue?.[0]?.path;Ne!==void 0&&d(Ne)}).catch(()=>{})},[]),g.useEffect(()=>{document.documentElement.style.setProperty("--detail-w",`${f}px`)},[f]),g.useEffect(()=>{if(!p)return;const ne=ue=>{ue.key==="Escape"&&m(null)};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[p]);const $=Zn();g.useEffect(()=>{const ne=$.pathname.split("/"),ue=ne.indexOf("tasks"),O=ue>=0?ne[ue+1]:void 0;O&&/^\d{4}$/.test(O)&&m(O)},[$.pathname]);const V=Vy(Xb,{activationConstraint:{distance:5}}),P=Vy(Kb),H=Fq(V,P),W=uY(S,n),L=ne=>{u(ue=>{const O={...ue};return ue[ne]==="asc"?O[ne]="desc":ue[ne]==="desc"?delete O[ne]:O[ne]="asc",O})},te=ne=>{const ue=W.filter(Ne=>Ne.status===ne),O=l[ne]??"desc";return[...ue].sort((Ne,de)=>{const K=Ne.wbs.localeCompare(de.wbs);return O==="asc"?K:-K})},ie=ne=>S.find(ue=>ue.wbs===ne),be=ne=>{k(String(ne.active.id))},I=ne=>{k(null);const{active:ue,over:O}=ne;if(!O)return;const Ne=String(ue.id),de=String(O.id),K=ie(Ne);if(!K||K.status===de)return;const Ee=[...S];T(re=>re.map(D=>D.wbs===Ne?{...D,status:de}:D)),rn.task.transition({wbs:Ne,toStatus:de}).catch(re=>{T(Ee);const D=re instanceof Error?re.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:D}}))})};return v?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx(Fa,{size:"lg",className:"text-spur-accent"})}):N?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("div",{className:"text-center text-spur-text-muted",children:[o.jsx("p",{className:"text-lg font-semibold",children:"Failed to load tasks"}),o.jsx("p",{className:"text-sm",children:N.message})]})}):o.jsx(Iw.Provider,{value:_,children:o.jsxs(OV,{sensors:H,onDragStart:be,onDragEnd:I,children:[o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx("div",{className:"flex gap-3 overflow-x-auto h-full p-4",children:oY.filter(ne=>!E.has(ne)).map(ne=>o.jsx(sY,{status:ne,label:ne,tasks:te(ne),onCardClick:ue=>{m(ue),t(ue)},sortDir:l[ne],onSortToggle:()=>L(ne)},ne))}),p&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button","aria-label":"Close task detail",className:"fixed inset-0 z-50 bg-black/40 border-0 p-0 cursor-default",onClick:()=>m(null)}),o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Task detail",className:"fixed top-0 right-0 h-full z-50 bg-spur-surface border-l border-spur-border shadow-2xl flex",style:{width:"var(--detail-w)",minWidth:"36rem",maxWidth:"80vw"},children:[o.jsx(Dl,{targetVar:"--detail-w",onResizeEnd:ne=>{const ue=Math.max(576,Math.min(ne,window.innerWidth*.8));b(ue);try{window.localStorage.setItem(s1,String(ue))}catch{}},direction:"horizontal",invert:!0}),o.jsx("div",{className:"flex flex-col flex-1 overflow-hidden",children:o.jsx("div",{className:"flex-1 overflow-y-auto","data-testid":"detail-body",children:(()=>{const ne=S.find(ue=>ue.wbs===p);return ne?o.jsx(g.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:"Loading detail..."}),children:o.jsx(iY,{task:ne,onClose:()=>m(null),onTransition:(ue,O)=>{T(Ne=>Ne.map(de=>de.wbs===ue?{...de,status:O}:de)),rn.task.transition({wbs:ue,toStatus:O}).catch(Ne=>{const de=Ne instanceof Error?Ne.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:de}}))})}})}):null})()})})]})]})]}),o.jsx(JV,{dropAnimation:null,children:B?(()=>{const ne=ie(B);return ne?o.jsx("div",{className:"opacity-90",children:o.jsx(CN,{task:ne,onClick:()=>{}})}):null})():null})]})})}const ed=[{id:"kanban",label:"Kanban",component:RN}];function DN(){const[e,t]=ck(),n=Zn(),r=qi(),a=g.useMemo(()=>{const u=n.pathname.split("/"),c=u.indexOf("tasks"),d=c>=0?u[c+1]:void 0;return d&&/^\d{4}$/.test(d)?d:e.get("selected")},[n.pathname,e]),s=g.useMemo(()=>{const u={},c=e.get("status"),d=e.get("feature"),p=e.get("parent"),m=e.get("assignee"),f=e.get("folder");return c!==null&&(u.status=c),d&&(u.featureId=d),p&&(u.parentWbs=p),m&&(u.assignee=m),f&&(u.folder=f),u},[e]);return{selected:a,filters:s,selectTask:u=>{const c=new URLSearchParams(e);c.delete("selected");const d=c.toString(),p=u?`/board/tasks/${u}`:"/board/tasks";r(`${p}${d?`?${d}`:""}`,{replace:!0})},setFilter:(u,c)=>{t(d=>{const p=new URLSearchParams(d);return u==="feature"&&p.delete("parent"),u==="parent"&&p.delete("feature"),c!==null?p.set(u,c):p.delete(u),p},{replace:!0})}}}function cY(e){const t=e.trim();return/^\d{4}$/.test(t)?{kind:"navigate",wbs:t}:t.includes(".")?{kind:"filter",key:"parent",value:t}:{kind:"filter",key:"feature",value:t}}function dY(){const{selectTask:e,setFilter:t,filters:n}=DN(),[r,a]=g.useState(IN),[s,i]=g.useState([]),[l,u]=g.useState("kanban"),[c,d]=g.useState(!1),[p,m]=g.useState(""),[f,b]=g.useState(!1),[x,E]=g.useState(void 0),y=n.folder??r,S=new Set(n.status===void 0?sr.filter(T=>T!=="blocked"&&T!=="cancelled"):n.status.split(",").filter(T=>sr.some(_=>_===T))),v=new Set(sr.filter(T=>!S.has(T)));g.useEffect(()=>{m(n.featureId??n.parentWbs??"")},[n.featureId,n.parentWbs]),g.useEffect(()=>{typeof rn.task.folders=="function"&&rn.task.folders({}).then(T=>{const{data:_,activeFolder:B}=T,k=B??_?.[0]?.path;_&&i(_),k!==void 0&&a(k)}).catch(()=>{})},[]);const N=T=>{const _=new Set(S);_.has(T)?_.delete(T):_.add(T),t("status",sr.filter(B=>_.has(B)).join(","))},A=T=>{T.preventDefault();const _=cY(p);if(_.kind==="navigate"){e(_.wbs),m("");return}t(_.key,_.value||null)},w=(ed.find(T=>T.id===l)??ed[0]).component;return o.jsxs("div",{className:"task-kanban flex flex-col h-full",children:[o.jsx("header",{className:"mx-auto w-full max-w-[1600px] shrink-0 px-4 pt-3",children:o.jsxs("div",{className:"flex flex-nowrap items-center justify-between gap-4 border-b border-base-content/10 pb-3",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[o.jsx("span",{className:"text-2xl","aria-hidden":"true",children:"📋"}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold tracking-tight text-spur-text",children:"Tasks"}),o.jsx("p",{className:"text-xs text-spur-text-muted",children:"Task corpus, kanban lanes, and phase filters"}),o.jsxs("p",{className:"mt-1 inline-flex items-center gap-1.5 rounded-full border border-spur-border px-2 py-0.5 text-xs text-spur-text-muted font-mono",role:"status","data-testid":"tasks-live-chip",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f?"bg-spur-success":"bg-spur-error"}`,"aria-hidden":"true"}),"last sync ",x?new Date(x).toLocaleString():"—"]})]})]}),o.jsxs("div",{className:"flex min-w-0 flex-nowrap items-center gap-2 overflow-x-auto",children:[o.jsx(xi,{variant:"ghost",size:"xs",className:"text-xs shrink-0 w-44",value:y,onChange:T=>t("folder",T.target.value),"aria-label":"Task phase folder",children:s.map(T=>o.jsx("option",{value:T.path,children:T.label?`${T.label} (${T.path})`:T.path},T.path))}),o.jsx("div",{className:"flex shrink-0 items-center gap-1",children:sr.map(T=>o.jsxs("label",{htmlFor:`tasks-status-${T}`,className:"flex items-center gap-1 cursor-pointer",children:[o.jsx(Sb,{id:`tasks-status-${T}`,size:"xs",checked:!v.has(T),onChange:()=>N(T)}),o.jsxs("span",{className:"text-[10px] text-spur-text-muted",children:[Mb(T)," ",T]})]},T))}),o.jsx("form",{onSubmit:A,className:"flex shrink-0 items-center",children:o.jsx(Oi,{"aria-label":"Filter by WBS or feature",type:"text",placeholder:"WBS or feature",variant:"bordered",size:"xs",className:"w-36",value:p,onChange:T=>m(T.target.value)})}),o.jsx(ot,{variant:"primary",size:"sm",className:"shrink-0",onClick:()=>d(!0),children:"+ New Task"}),o.jsx("div",{className:"flex shrink-0 items-center gap-1 bg-base-300 p-1 rounded-xl",children:ed.map(T=>o.jsx("button",{type:"button",className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all ${l===T.id?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,onClick:()=>u(T.id),children:T.label},T.id))})]})]})}),o.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:o.jsx(w,{onSelectTask:e,filters:n,folder:y,hiddenColumns:v,onConnectionChange:b,onSyncChange:E})}),o.jsx(kw,{open:c,onClose:()=>d(!1),onCreated:()=>{},folder:y})]})}function pY(e,t){rn.task.transition({wbs:e,toStatus:t}).catch(n=>{const r=n instanceof Error?n.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:r}}))})}function fY(){const{filters:e,selectTask:t}=DN();return o.jsx("div",{className:"task-kanban flex flex-col h-full",children:o.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:o.jsx(RN,{onSelectTask:t,filters:e})})})}const mY={id:"tasks",name:"Tasks",icon:"📋",route:"tasks",component:dY,sidebarLabel:"Tasks",description:"Task kanban, lifecycle status, and per-task detail",order:40},hY=Object.freeze(Object.defineProperty({__proto__:null,TaskKanbanView:fY,module:mY,transition:pY},Symbol.toStringTag,{value:"Module"}));function ON(e){return e===null||typeof e!="object"?null:"module"in e&&i1(e.module)?e.module:"default"in e&&i1(e.default)?e.default:null}function i1(e){return e===null||typeof e!="object"?!1:"id"in e&&typeof e.id=="string"&&"name"in e&&typeof e.name=="string"&&"icon"in e&&typeof e.icon=="string"&&"route"in e&&typeof e.route=="string"&&"component"in e&&typeof e.component=="function"}function LN(e,t){const n=typeof e.order=="number",r=typeof t.order=="number";return n&&r?e.order-t.order:n?-1:r?1:0}function gY(e){const t=[],n=e("./*/index.{ts,tsx}",{eager:!0});for(const r of Object.values(n)){const a=ON(r);a&&t.push(a)}return t.sort((r,a)=>r.id.localeCompare(a.id)),t.sort(LN),t}function bY(){try{return gY(()=>Object.assign({"./features/index.tsx":aG,"./history/index.tsx":PG,"./observability/index.tsx":OW,"./projects/index.tsx":Sq,"./task-kanban/index.tsx":hY}))}catch(a){if(typeof require!="function")throw a}const e=require("node:fs"),t=require("node:path"),n=require("node:url"),r=typeof __dirname<"u"?__dirname:t.dirname(n.fileURLToPath(import.meta.url));return xY(r,{readdirSync:(a,s)=>e.readdirSync(a,s),tryRequire:a=>require(a)})}function xY(e,t){const n=require("node:path"),r=[];let a=[];try{a=t.readdirSync(e,{withFileTypes:!0})}catch{return r}const s=a.filter(i=>i.isDirectory()).map(i=>i.name).sort((i,l)=>i.localeCompare(l));for(const i of s)for(const l of["tsx","ts"]){const u=n.join(e,i,`index.${l}`);try{const c=t.tryRequire(u),d=ON(c);if(d){r.push(d);break}}catch{}}return r.sort(LN),r}function EY(e,t){const n=new Set(t?.disabled??[]),r=e.slice(),a=new Set(n);function s(){return r.filter(i=>!a.has(i.id))}return yY(r),{get modules(){return s()},getModule(i){return s().find(l=>l.id===i)},get defaultModule(){return s()[0]},disableModule(i){a.add(i)},enableModule(i){a.delete(i)},getEnabledModules(){return s().map(i=>i.id)},registerModuleRoot(i){}}}function yY(e){const t=new Map,n=new Map;for(const r of e){const a=t.get(r.id);if(a!==void 0)throw new Error(`Duplicate module id "${r.id}" discovered in two sources: ${a} and ${Zo(r)}`);t.set(r.id,Zo(r));const s=n.get(r.route);if(s!==void 0)throw new Error(`Duplicate module route "${r.route}" discovered in two sources: ${s} and ${Zo(r)}`);n.set(r.route,Zo(r))}}function Zo(e){return e.id}const Jb=EY(bY(),{disabled:zz}),MN=Jb.modules;function TY(e){return Jb.getModule(e)}const Xo=Jb.defaultModule;function SY(){const[e,t]=g.useState([]);return g.useEffect(()=>{if(typeof window>"u")return;const n=r=>{const s=r.detail?.message||"An error occurred",i=`${Date.now()}-${Math.random().toString(36).slice(2,7)}`;t(l=>[...l,{id:i,message:s}]),setTimeout(()=>{t(l=>l.filter(u=>u.id!==i))},5e3)};return window.addEventListener("api-error",n),()=>{window.removeEventListener("api-error",n)}},[]),e.length===0?null:o.jsx("div",{className:"fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-md w-full px-4 pointer-events-none",children:e.map(n=>o.jsxs("div",{className:"pointer-events-auto flex items-center justify-between gap-3 p-3 bg-red-950/90 border border-red-500/40 text-red-200 text-sm rounded-md shadow-lg backdrop-blur",role:"alert",children:[o.jsx("span",{className:"flex-1 break-words",children:n.message}),o.jsx("button",{type:"button",className:"text-red-400 hover:text-red-100 text-base font-bold leading-none px-1",onClick:()=>t(r=>r.filter(a=>a.id!==n.id)),"aria-label":"Close error toast",children:"×"})]},n.id))})}const vY="Enter",wY=229;function NY(e){return e.key===vY&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==wY}const AY=[{name:"/review",description:"Inspect staged git diff, verify test coverage & lint",category:"git",argumentHint:"[target] [--cached]",tags:["builtin","git","review"]},{name:"/commit",description:"Draft conventional commit message from staged hunks",category:"git",argumentHint:"[--all] [-m <message>]",tags:["builtin","git","commit"]},{name:"/compact",description:"Purge execution trace and condense context window",category:"sys",argumentHint:"[focus]",tags:["builtin","sys","compact"]},{name:"/revert",description:"Undo last agent file changes or restore git stash",category:"git",argumentHint:"[stash-id | file]",tags:["builtin","git","revert"]},{name:"/resume",description:"Resume paused background agent run",category:"dev",argumentHint:"[run-id]",tags:["builtin","dev","resume"]},{name:"/terminal",description:"Run isolated bash execution in sandbox mirror",category:"sys",argumentHint:"[command]",tags:["builtin","sys","terminal"]},{name:"/cost",description:"Inspect token breakdown and USD expenditure",category:"sys",tags:["builtin","sys","cost"]},{name:"/sp:dev-plan",description:"Plan a feature from description (intake → AC → tasks)",category:"harness",argumentHint:'"<description>" [--feature <id>]',tags:["sp","dev","plan"]},{name:"/sp:dev-run",description:"Drive one task end-to-end through verification pipeline",category:"harness",argumentHint:"<wbs> [--mode <full|implement>]",tags:["sp","dev","run"]},{name:"/sp:dev-verify",description:"Verify a task against requirements and acceptance criteria",category:"harness",argumentHint:"<wbs> [--bdd] [--auto]",tags:["sp","dev","verify"]}],_Y=[{id:"auto",label:"auto",desc:"Orchestrator auto-dispatch (default)"},{id:"coder",label:"coder",desc:"Implementation & refactoring specialist"},{id:"reviewer",label:"reviewer",desc:"Verification, lint & SECUA reviewer"},{id:"planner",label:"planner",desc:"Architecture & decomposition specialist"}];function kY(e){if(!e)return!0;const{state:t,instanceId:n}=e.orchestrator;return t==="missing"||t==="unresolvable"||!n}function CY({activeModule:e}){const[t,n]=g.useState(!1),[r,a]=g.useState(!1),[s,i]=g.useState(null),[l,u]=g.useState("auto"),[c,d]=g.useState(!1),[p,m]=g.useState(!1),[f,b]=g.useState(0),[x,E]=g.useState("all"),[y,S]=g.useState(AY),v=g.useMemo(()=>{const D=new Map;for(const pe of y){if(Array.isArray(pe.tags)){for(const Ae of pe.tags)if(Ae&&typeof Ae=="string"){const He=Ae.trim().toLowerCase();D.set(He,(D.get(He)??0)+1)}}if(pe.category){const Ae=pe.category.trim().toLowerCase();D.set(Ae,(D.get(Ae)??0)+1)}}const ye=["sp","cc","kk","wt","git","dev","sys","harness","builtin"];return["all",...Array.from(D.keys()).sort((pe,Ae)=>{const He=ye.indexOf(pe),fe=ye.indexOf(Ae);if(He!==-1&&fe!==-1)return He-fe;if(He!==-1)return-1;if(fe!==-1)return 1;const Je=(D.get(Ae)??0)-(D.get(pe)??0);return Je!==0?Je:pe.localeCompare(Ae)})]},[y]),N=Os(),{draft:A,setText:w,persistPending:T,clearSubmitted:_}=Sw(),B=N.fleet?.orchestrator?.instanceId,k=kY(N.fleet),{requests:$,failed:V}=lN(B??null),P=s!==null?$.get(s)??null:null,H=oN(P,N.fleet,r),W=iN[H],L=r||s!==null,te=L?`${W.label} — Next: ${W.action}`:"",ie=g.useRef(null);g.useEffect(()=>{let D=!0;return(async()=>{try{const ye=await ht(new Request(`${Ct()}/agent/commands`));if(ye.ok){const Se=await ye.json();D&&Array.isArray(Se.commands)&&Se.commands.length>0&&S(Se.commands)}}catch{}})(),()=>{D=!1}},[]),g.useEffect(()=>{if(!c)return;const D=ye=>{ie.current&&!ie.current.contains(ye.target)&&d(!1)};return document.addEventListener("click",D),()=>document.removeEventListener("click",D)},[c]),g.useEffect(()=>{A.text.startsWith("/")&&m(!1)},[A.text]);const be=A.text.trim().toLowerCase(),I=be.startsWith("/")&&!p,ne=I?y.filter(D=>{const ye=x==="all"||Array.isArray(D.tags)&&D.tags.map(Ae=>Ae.toLowerCase()).includes(x)||D.category.toLowerCase()===x,Se=be.startsWith("/")?be.slice(1):be,pe=D.name.toLowerCase().startsWith(be)||D.name.toLowerCase().includes(Se)||!!D.argumentHint?.toLowerCase().includes(Se)||D.description.toLowerCase().includes(Se)||Array.isArray(D.tags)&&D.tags.some(Ae=>Ae.toLowerCase().includes(Se));return ye&&pe}):[],ue=I&&ne.length>0,O=D=>{w(`${D} `),m(!0),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},Ne=D=>{const ye=A.text,Se=ye.length>0&&!ye.endsWith(" ")?`${ye} ${D}`:`${ye}${D}`;w(Se),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},de=()=>l==="auto"?B:N.fleet?.members?.find(ye=>ye.role===l||ye.instanceId===l)?.instanceId??B,K=async()=>{const D=N.path,ye=de();if(D===null||ye===void 0||r)return;const Se=A.text;if(Se.trim().length===0)return;const pe={text:Se,refs:A.refs,revision:A.revision},Ae=A.pending!==void 0&&typeof A.pending.requestKey=="string"&&A.pending.requestKey.length>0&&A.pending.revision===A.revision?A.pending:void 0,He=Ae!==void 0?Ae.requestKey:crypto.randomUUID();T(He),a(!0),i(null),m(!0);try{const fe=await ht(new Request(`${Ct()}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({to:ye,from:ku,body:qj(pe.text,pe.refs),requestKey:He,projectPath:D})}));if(!fe.ok)return;const bt=(await fe.json().catch(()=>null))?.msgId;i(typeof bt=="string"?bt:null),_(pe.revision)}catch{}finally{a(!1)}};if(!t)return o.jsxs(o.Fragment,{children:[o.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:te}),o.jsx(ot,{variant:"ghost",className:"fixed bottom-6 right-6 z-30 h-12 w-12 rounded-full backdrop-blur-md bg-base-100/80 border border-spur-border shadow-2xl text-xl text-spur-text",onClick:()=>n(!0),"aria-label":"Open agent prompt bar","aria-expanded":!1,"data-testid":"agent-bar-dock",children:"✨"})]});const Ee=N.fleet?.members&&N.fleet.members.length>0?[{id:"auto",label:"auto",desc:"Orchestrator auto-dispatch (default)"},...N.fleet.members.map(D=>({id:D.instanceId,label:D.role||D.instanceId,desc:`${D.executor}${D.model?` · ${D.model}`:""}`}))]:_Y,re=A.text.trim().length===0||l==="auto"&&k;return o.jsxs("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-30 w-[calc(100vw-2rem)] max-w-[84rem] backdrop-blur-md bg-base-100/80 border border-spur-border shadow-2xl rounded-2xl p-2.5 flex flex-col gap-2 transition-colors","data-testid":"agent-bar",children:[o.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:te}),ue&&o.jsxs("div",{"data-testid":"agent-bar-palette",className:"w-full rounded-2xl bg-base-100/95 border border-spur-border shadow-2xl overflow-hidden flex flex-col backdrop-blur-2xl mb-1 transition-colors",children:[o.jsxs("div",{className:"flex items-center justify-between px-3.5 py-2 border-b border-spur-border bg-base-200/50 text-xs",children:[o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("span",{className:"font-mono text-spur-accent font-semibold text-[13px]",children:"/"}),o.jsx("span",{className:"font-mono text-[12px] font-medium text-spur-text",children:"Commands"}),o.jsxs("span",{className:"text-[11px] font-mono text-spur-text-muted",children:[ne.length," available"]})]}),o.jsx("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar max-w-[65%] py-0.5",role:"tablist",children:v.slice(0,10).map(D=>o.jsx("button",{type:"button",role:"tab","aria-selected":x===D,onClick:()=>E(D),className:`px-2 py-0.5 rounded text-[11px] font-mono transition-colors shrink-0 cursor-pointer ${x===D?"bg-spur-accent/15 text-spur-accent border border-spur-accent/30 font-medium":"text-spur-text-muted hover:text-spur-text hover:bg-base-200"}`,children:D==="all"?"All":D},D))})]}),o.jsx("div",{className:"flex flex-col py-1.5 px-2 max-h-[260px] overflow-y-auto",role:"listbox",children:ne.map((D,ye)=>{const Se=ye===f;return o.jsxs("button",{type:"button",role:"option","aria-selected":Se,onClick:()=>O(D.name),title:D.description,className:`flex items-center w-full text-left px-3 py-2 rounded-lg cursor-pointer transition-colors ${Se?"bg-spur-surface text-spur-accent font-medium":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[o.jsxs("div",{className:"flex items-center gap-2 font-mono text-[13px] min-w-0 truncate flex-1",children:[o.jsx("span",{className:Se?"font-semibold text-spur-accent":"font-medium text-spur-text",children:D.name}),D.argumentHint?o.jsx("span",{className:`font-mono text-xs truncate ${Se?"text-spur-text/80":"text-spur-text-muted"}`,children:D.argumentHint}):o.jsx("span",{className:`font-sans text-xs italic truncate ${Se?"text-spur-text/60":"text-spur-text-muted/60"}`,children:D.description})]}),o.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-2",children:(D.tags&&D.tags.length>0?D.tags.slice(0,2):[D.category]).map(pe=>o.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-base-200 text-spur-text-muted border border-spur-border",children:pe},pe))})]},D.name)})}),o.jsxs("div",{"data-testid":"agent-bar-hints",className:"flex items-center justify-between px-4 py-2 border-t border-spur-border bg-base-200/70 font-mono text-[11px] text-spur-text-muted select-none",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"↑↓"}),o.jsx("span",{children:"navigate"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"Tab"}),o.jsx("span",{children:"complete"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"↵"}),o.jsx("span",{children:"execute"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"ESC"}),o.jsx("span",{children:"dismiss"})]})]}),o.jsxs("div",{className:"flex items-center gap-3 font-mono text-[11px]",children:[o.jsxs("button",{type:"button",onClick:()=>Ne("@"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Reference files",children:[o.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"@"}),o.jsx("span",{className:"group-hover:text-spur-text",children:"files"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("button",{type:"button",onClick:()=>Ne("#"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Reference tasks and context",children:[o.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"#"}),o.jsx("span",{className:"group-hover:text-spur-text",children:"context"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("button",{type:"button",onClick:()=>Ne("!"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Execute shell directly",children:[o.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"!"}),o.jsx("span",{className:"group-hover:text-spur-text",children:"bash"})]})]})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-spur-text-muted font-mono text-sm select-none font-bold pl-1",children:">"}),o.jsxs("div",{className:"relative shrink-0",ref:ie,children:[o.jsxs("button",{type:"button",onClick:()=>d(D=>!D),className:"flex items-center gap-1 px-2.5 py-1 rounded-lg bg-spur-surface hover:bg-base-200 border border-spur-border text-xs font-mono text-spur-accent transition-colors cursor-pointer group",title:"Target Agent Receiver (default: auto dispatch to orchestrator)","data-testid":"agent-bar-role-tag",children:[o.jsx("span",{className:"text-spur-text-muted font-sans text-[11px]",children:"to:"}),o.jsx("span",{className:"font-semibold",children:l}),o.jsx("span",{className:"text-spur-text-muted text-[10px] group-hover:text-spur-text transition-colors",children:"▾"})]}),c&&o.jsxs("div",{"data-testid":"agent-bar-role-menu",className:"absolute bottom-full left-0 mb-2 w-56 rounded-xl bg-base-100 border border-spur-border shadow-2xl p-1.5 z-50 flex flex-col gap-1 text-spur-text",children:[o.jsx("div",{className:"px-2.5 py-1 text-[10px] font-mono text-spur-text-muted uppercase tracking-wider",children:"Dispatch Target"}),Ee.map(D=>o.jsxs("button",{type:"button",onClick:()=>{u(D.label),d(!1)},className:`flex items-center justify-between px-2.5 py-1.5 rounded-lg text-left text-xs font-mono transition-colors ${l===D.label?"bg-spur-accent/15 text-spur-accent font-semibold":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"font-medium text-spur-text",children:D.label}),o.jsx("span",{className:"text-[10px] text-spur-text-muted",children:D.desc})]}),l===D.label&&o.jsx("span",{className:"text-[12px]",children:"✓"})]},D.id))]})]}),o.jsx(zj,{variant:"ghost",rows:1,value:A.text,onChange:D=>w(D.target.value),onKeyDown:D=>{if(ue&&ne.length>0){if(D.key==="ArrowDown"){D.preventDefault(),b(ye=>(ye+1)%ne.length);return}if(D.key==="ArrowUp"){D.preventDefault(),b(ye=>(ye-1+ne.length)%ne.length);return}if(D.key==="Tab"){D.preventDefault();const ye=ne[f];ye&&O(ye.name);return}if(D.key==="Escape"){D.preventDefault(),m(!0);return}}NY(D)&&(re||(D.preventDefault(),K()))},placeholder:"Ask a coding agent to refine or implement, or type / for commands…","aria-label":"Agent prompt",className:"flex-1 min-h-9 resize-none bg-transparent text-spur-text placeholder:text-spur-text-muted border-0 focus:ring-0 focus:outline-none","data-testid":"agent-bar-input"}),o.jsx(ot,{variant:"ghost",size:"sm",onClick:()=>n(!1),"aria-label":"Collapse agent prompt bar","aria-expanded":!0,className:"text-spur-text-muted hover:text-spur-text h-8 w-8 p-0 shrink-0",children:"▾"})]}),l==="auto"&&k&&o.jsx("div",{"data-testid":"agent-bar-orchestrator-missing",role:"status",className:"px-1 text-xs text-spur-text-muted",children:"Orchestrator unavailable — no orchestrator instance is bound to this project, so requests cannot be delivered yet."}),L&&o.jsxs("div",{"data-receipt-state":H,role:"status",className:`rounded-lg px-2.5 py-1 text-xs ${W.tone==="err"?"bg-spur-error/10 text-spur-error":W.tone==="warn"?"bg-spur-warning/10 text-spur-warning":"bg-spur-success/10 text-spur-success"}`,children:[o.jsx("span",{"aria-hidden":"true",className:"mr-1",children:W.icon}),o.jsx("span",{className:"font-medium",children:W.label}),o.jsxs("span",{className:"text-spur-text-muted",children:[" ","— ",W.meaning," Next: ",W.action,"."]}),V&&o.jsx("span",{className:"text-spur-text-muted",children:" (results feed unavailable)"})]})]})}function IY({name:e}){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;const n=Math.abs(t)%8,a=["text-emerald-400 bg-emerald-500/10 border-emerald-500/30","text-sky-400 bg-sky-500/10 border-sky-500/30","text-indigo-400 bg-indigo-500/10 border-indigo-500/30","text-amber-400 bg-amber-500/10 border-amber-500/30","text-rose-400 bg-rose-500/10 border-rose-500/30","text-purple-400 bg-purple-500/10 border-purple-500/30","text-teal-400 bg-teal-500/10 border-teal-500/30","text-cyan-400 bg-cyan-500/10 border-cyan-500/30"][n],s=()=>{switch(n){case 0:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M8 1.5l5.5 3.2v6.6L8 14.5l-5.5-3.2V4.7L8 1.5z"}),o.jsx("path",{d:"M8 1.5v13M2.5 4.7l5.5 3.3 5.5-3.3"})]});case 1:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("rect",{x:"2",y:"2.5",width:"12",height:"11",rx:"2"}),o.jsx("path",{d:"M5 6l2.5 2L5 10M8.5 10H11"})]});case 2:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("circle",{cx:"4.5",cy:"4",r:"1.5"}),o.jsx("circle",{cx:"4.5",cy:"12",r:"1.5"}),o.jsx("circle",{cx:"11.5",cy:"7",r:"1.5"}),o.jsx("path",{d:"M4.5 5.5v5M4.5 7.5a4 4 0 004-1"})]});case 3:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M8 2l5.5 3-5.5 3-5.5-3L8 2z"}),o.jsx("path",{d:"M2.5 8l5.5 3 5.5-3M2.5 11l5.5 3 5.5-3"})]});case 4:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1.5"}),o.jsx("path",{d:"M6 1.5v2M10 1.5v2M6 12.5v2M10 12.5v2M1.5 6h2M1.5 10h2M12.5 6h2M12.5 10h2"})]});case 5:return o.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M5.5 4.5L2 8l3.5 3.5M10.5 4.5L14 8l-3.5 3.5M9 3l-2 10"})});case 6:return o.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M2 4a1.5 1.5 0 011.5-1.5h2.8a1.5 1.5 0 011.06.44l1.14 1.14c.28.28.66.42 1.06.42H12.5A1.5 1.5 0 0114 6v6a1.5 1.5 0 01-1.5 1.5h-9A1.5 1.5 0 012 12V4z"})});default:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("circle",{cx:"8",cy:"8",r:"6"}),o.jsx("path",{d:"M2 8h12M8 2a9 9 0 010 12 9 9 0 010-12z"})]})}};return o.jsx("span",{"data-testid":"project-avatar-icon",className:`flex h-7 w-7 items-center justify-center rounded border ${a}`,children:s()})}function o1({currentName:e,collapsed:t=!1}){const[n,r]=g.useState(!1),[a,s]=g.useState([]),[i,l]=g.useState(null),[u,c]=g.useState(null),d=g.useRef(null);g.useEffect(()=>{if(!n)return;const f=new AbortController;return ht(new Request(`${Ct()}/projects`,{signal:f.signal})).then(async b=>{if(!b.ok)return;const x=await b.json();s(x.projects??[])}).catch(()=>{c("Failed to load projects")}),()=>f.abort()},[n]),g.useEffect(()=>{if(!n)return;const f=x=>{x.key==="Escape"&&r(!1)},b=x=>{d.current&&!d.current.contains(x.target)&&r(!1)};return document.addEventListener("keydown",f),document.addEventListener("mousedown",b),()=>{document.removeEventListener("keydown",f),document.removeEventListener("mousedown",b)}},[n]);const p=async f=>{if(f.current){r(!1);return}if(f.running&&f.port>0){window.location.href=`http://localhost:${f.port}/board`;return}l(f.name);try{const b=await ht(new Request(`${Ct()}/projects/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:f.name,path:f.path})}));if(!b.ok)throw new Error("Failed to start project");const x=await b.json();window.location.href=x.url||`http://localhost:${x.port}/board`}catch(b){c(b instanceof Error?b.message:"Start failed"),l(null)}},m=o.jsxs("button",{type:"button",onClick:()=>r(f=>!f),"aria-haspopup":"listbox","aria-expanded":n,"aria-label":`Switch project: ${e}`,title:e,"data-testid":"project-switcher-trigger",className:"group relative flex h-8 w-8 items-center justify-center rounded-md hover:bg-spur-accent/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-spur-accent",children:[o.jsx("span",{className:`items-center justify-center ${n?"hidden":"flex group-hover:hidden"}`,children:o.jsx(IY,{name:e})}),o.jsx("span",{"data-testid":"project-switcher-chevron",className:`h-7 w-7 items-center justify-center rounded text-spur-text ${n?"flex":"hidden group-hover:flex"}`,children:o.jsx("svg",{className:`h-4 w-4 shrink-0 transition-transform ${n?"rotate-180 text-spur-accent":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M4 6l4 4 4-4"})})})]});return o.jsxs("div",{className:`relative ${t?"flex items-center justify-center":"min-w-0 flex-1"}`,ref:d,children:[t?n?m:o.jsx(vb,{position:"right",tip:`Switch project: ${e}`,className:"block",children:m}):o.jsxs("button",{type:"button",onClick:()=>r(f=>!f),"aria-haspopup":"listbox","aria-expanded":n,"aria-label":"Switch project",title:e,"data-testid":"project-switcher-trigger",className:"flex w-full items-center justify-between gap-1 rounded-md px-1.5 py-1 text-left text-sm font-semibold text-spur-text hover:bg-spur-border/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-spur-accent",children:[o.jsx("span",{className:"font-semibold truncate",children:e}),o.jsx("svg",{className:`h-4 w-4 shrink-0 transition-transform ${n?"rotate-180":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M4 6l4 4 4-4"})})]}),n&&o.jsxs("div",{role:"listbox","aria-label":"Registered projects","data-testid":"project-switcher-menu",className:`absolute z-50 w-64 rounded-md border border-spur-border bg-spur-surface p-1 shadow-lg ${t?"left-full top-0 ml-2":"left-0 top-full mt-1"}`,children:[o.jsx("div",{className:"px-2 py-1 text-xs font-medium text-spur-text-muted border-b border-spur-border/50 mb-1",children:"Projects"}),a.length===0?o.jsx("div",{className:"px-2 py-1.5 text-xs text-spur-text-muted",children:u||"No projects registered"}):a.map(f=>o.jsxs("button",{type:"button",role:"option","aria-selected":f.current,disabled:i===f.name,onClick:()=>p(f),"data-testid":`project-item-${f.name}`,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-xs text-left transition-colors ${f.current?"bg-spur-accent/15 text-spur-accent font-medium":"text-spur-text hover:bg-spur-border/30"}`,children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ${f.running?"bg-green-500":"bg-gray-400"}`,title:f.running?`Running on port ${f.port}`:"Stopped"}),o.jsx("span",{className:"truncate",children:f.name})]}),i===f.name?o.jsx("span",{className:"text-[10px] text-spur-accent animate-pulse",children:"Starting..."}):f.current?o.jsx("span",{className:"text-[10px] font-semibold text-spur-accent",children:"current"}):f.running?o.jsxs("span",{className:"text-[10px] text-spur-text-muted",children:[":",f.port]}):o.jsx("span",{className:"text-[10px] text-spur-text-muted",children:"stopped"})]},f.path))]})]})}function RY({open:e,onClose:t}){if(!e)return null;const n=o.jsxs(jj,{open:e,onClose:t,"aria-labelledby":"settings-modal-title",children:[o.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-spur-border",children:[o.jsx("h3",{id:"settings-modal-title",className:"text-base font-semibold text-spur-text",children:"Settings"}),o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text-muted hover:text-spur-text",onClick:t,"aria-label":"Close settings",children:"✕"})]}),o.jsx("div",{className:"py-6 text-sm text-spur-text-muted",children:"Settings configuration and workspace preferences will be available in a future release."})]});return typeof document<"u"?na.createPortal(n,document.body):n}const FN="spur-theme";function DY(){try{const e=localStorage.getItem(FN);if(e==="light"||e==="dark")return e}catch{}return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function OY(e){document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(FN,e)}catch{}}function LY(e){const t=e==="dark"?"light":"dark";return OY(t),t}function l1(){const[e,t]=g.useState(DY);g.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),a=s=>{if(!(()=>{try{return localStorage.getItem("spur-theme")}catch{return null}})()){const l=s.matches?"dark":"light";t(l),document.documentElement.setAttribute("data-theme",l)}};return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[]);const n=g.useCallback(()=>t(LY),[]);return o.jsx(ot,{variant:"ghost",size:"sm",onClick:n,className:"text-spur-text-muted","aria-label":e==="dark"?"Switch to light mode":"Switch to dark mode",children:e==="dark"?"☀️":"🌙"})}const MY="Modules";function FY(){const[e,t]=g.useState(MY);return g.useEffect(()=>{const n=new AbortController;return ht(new Request(`${Ct()}/project`,{signal:n.signal})).then(async r=>{if(!r.ok)return;const a=await r.json();a.name&&t(a.name)}).catch(()=>{}),()=>n.abort()},[]),e}function jY({direction:e}){const t=e==="expand";return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"}),o.jsx("line",{x1:"6",y1:"2",x2:"6",y2:"14"}),t?o.jsx("path",{d:"M9 6l2 2-2 2"}):o.jsx("path",{d:"M11 6l-2 2 2 2"})]})}function u1({collapsed:e,onToggle:t}){const n=e?"Expand sidebar":"Collapse sidebar";return o.jsx("button",{type:"button",onClick:t,"aria-label":n,title:n,"data-testid":e?"sidebar-expand":"sidebar-collapse",className:"flex h-8 w-8 items-center justify-center rounded-md text-spur-text-muted hover:bg-spur-accent/20 hover:text-spur-accent focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-spur-accent",children:o.jsx(jY,{direction:e?"expand":"collapse"})})}function c1({onClick:e}){return o.jsx("button",{type:"button",onClick:e,"aria-label":"Open settings",title:"Open settings","data-testid":"sidebar-settings",className:"flex h-8 w-8 items-center justify-center rounded-md text-spur-text-muted hover:bg-spur-accent/20 hover:text-spur-accent focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-spur-accent",children:o.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{fillRule:"evenodd",d:"M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z",clipRule:"evenodd"})})})}function PY({collapsed:e,onToggle:t,onMobileClose:n}){const r=FY(),[a,s]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs("aside",{className:`flex flex-col bg-spur-surface border-r border-spur-border ${e?"overflow-visible":"overflow-hidden"}`,children:[e?o.jsx("div",{className:"flex items-center justify-center border-b border-spur-border shrink-0 py-2",children:o.jsx(o1,{currentName:r,collapsed:!0})}):o.jsxs("div",{className:"flex items-center justify-between gap-1 p-3 border-b border-spur-border shrink-0",children:[o.jsx(o1,{currentName:r}),n&&o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text-muted md:hidden",onClick:n,"aria-label":"Close navigation",children:"✕"})]}),o.jsx("nav",{className:`flex-1 ${e?"overflow-visible":"overflow-y-auto"}`,children:MN.map(i=>{const l=i.sidebarLabel??i.name,u=o.jsxs($1,{to:`/board/${i.route}`,className:({isActive:c})=>`flex items-center gap-2 px-3 py-2 text-sm transition-colors ${c?"bg-spur-accent/20 text-spur-accent":"text-spur-text-muted hover:text-spur-text hover:bg-spur-border/30"} ${e?"justify-center py-3":""}`,children:[o.jsx("span",{className:"text-lg",children:i.icon}),!e&&o.jsx("span",{children:l})]},i.id);if(e){const c=i.description?`${l}
187
+ `},Lq={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function Mq(e){let{announcements:t=Lq,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=Oq}=e;const{announce:s,announcement:i}=Iq(),l=$u("DndLiveRegion"),[u,c]=g.useState(!1);if(g.useEffect(()=>{c(!0)},[]),Rq(g.useMemo(()=>({onDragStart(p){let{active:m}=p;s(t.onDragStart({active:m}))},onDragMove(p){let{active:m,over:f}=p;t.onDragMove&&s(t.onDragMove({active:m,over:f}))},onDragOver(p){let{active:m,over:f}=p;s(t.onDragOver({active:m,over:f}))},onDragEnd(p){let{active:m,over:f}=p;s(t.onDragEnd({active:m,over:f}))},onDragCancel(p){let{active:m,over:f}=p;s(t.onDragCancel({active:m,over:f}))}}),[s,t])),!u)return null;const d=at.createElement(at.Fragment,null,at.createElement(kq,{id:r,value:a.draggable}),at.createElement(Cq,{id:l,announcement:i}));return n?na.createPortal(d,n):d}var on;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(on||(on={}));function zl(){}function Vy(e,t){return g.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function Fq(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return g.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const pr=Object.freeze({x:0,y:0});function jq(e,t){const n=$l(e);if(!n)return"0 0";const r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+"% "+r.y+"%"}function Pq(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function Bq(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function Uq(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),a=Math.min(t.left+t.width,e.left+e.width),s=Math.min(t.top+t.height,e.top+e.height),i=a-r,l=s-n;if(r<a&&n<s){const u=t.width*t.height,c=e.width*e.height,d=i*l,p=d/(u+c-d);return Number(p.toFixed(4))}return 0}const $q=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const a=[];for(const s of r){const{id:i}=s,l=n.get(i);if(l){const u=Uq(l,t);u>0&&a.push({id:i,data:{droppableContainer:s,value:u}})}}return a.sort(Pq)};function zq(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function mN(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:pr}function Hq(e){return function(n){for(var r=arguments.length,a=new Array(r>1?r-1:0),s=1;s<r;s++)a[s-1]=arguments[s];return a.reduce((i,l)=>({...i,top:i.top+e*l.y,bottom:i.bottom+e*l.y,left:i.left+e*l.x,right:i.right+e*l.x}),{...n})}}const Gq=Hq(1);function hN(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Wq(e,t,n){const r=hN(t);if(!r)return e;const{scaleX:a,scaleY:s,x:i,y:l}=r,u=e.left-i-(1-a)*parseFloat(n),c=e.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),d=a?e.width/a:e.width,p=s?e.height/s:e.height;return{width:d,height:p,top:c,right:u+d,bottom:c+p,left:u}}const qq={ignoreTransform:!1};function mo(e,t){t===void 0&&(t=qq);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:d}=jn(e).getComputedStyle(e);c&&(n=Wq(n,c,d))}const{top:r,left:a,width:s,height:i,bottom:l,right:u}=n;return{top:r,left:a,width:s,height:i,bottom:l,right:u}}function Yy(e){return mo(e,{ignoreTransform:!0})}function Vq(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Yq(e,t){return t===void 0&&(t=jn(e).getComputedStyle(e)),t.position==="fixed"}function Kq(e,t){t===void 0&&(t=jn(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const s=t[a];return typeof s=="string"?n.test(s):!1})}function Vb(e,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(Wb(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!po(a)||dN(a)||n.includes(a))return n;const s=jn(e).getComputedStyle(a);return a!==e&&Kq(a,s)&&n.push(a),Yq(a,s)?n:r(a.parentNode)}return e?r(e):n}function gN(e){const[t]=Vb(e,1);return t??null}function Xc(e){return!Bu||!e?null:Ls(e)?e:Gb(e)?Wb(e)||e===Ms(e).scrollingElement?window:po(e)?e:null:null}function bN(e){return Ls(e)?e.scrollX:e.scrollLeft}function xN(e){return Ls(e)?e.scrollY:e.scrollTop}function Zd(e){return{x:bN(e),y:xN(e)}}var mn;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(mn||(mn={}));function EN(e){return!Bu||!e?!1:e===document.scrollingElement}function yN(e){const t={x:0,y:0},n=EN(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},a=e.scrollTop<=t.y,s=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,l=e.scrollLeft>=r.x;return{isTop:a,isLeft:s,isBottom:i,isRight:l,maxScroll:r,minScroll:t}}const Zq={x:.2,y:.2};function Xq(e,t,n,r,a){let{top:s,left:i,right:l,bottom:u}=n;r===void 0&&(r=10),a===void 0&&(a=Zq);const{isTop:c,isBottom:d,isLeft:p,isRight:m}=yN(e),f={x:0,y:0},b={x:0,y:0},x={height:t.height*a.y,width:t.width*a.x};return!c&&s<=t.top+x.height?(f.y=mn.Backward,b.y=r*Math.abs((t.top+x.height-s)/x.height)):!d&&u>=t.bottom-x.height&&(f.y=mn.Forward,b.y=r*Math.abs((t.bottom-x.height-u)/x.height)),!m&&l>=t.right-x.width?(f.x=mn.Forward,b.x=r*Math.abs((t.right-x.width-l)/x.width)):!p&&i<=t.left+x.width&&(f.x=mn.Backward,b.x=r*Math.abs((t.left+x.width-i)/x.width)),{direction:f,speed:b}}function Qq(e){if(e===document.scrollingElement){const{innerWidth:s,innerHeight:i}=window;return{top:0,left:0,right:s,bottom:i,width:s,height:i}}const{top:t,left:n,right:r,bottom:a}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:a,width:e.clientWidth,height:e.clientHeight}}function TN(e){return e.reduce((t,n)=>cs(t,Zd(n)),pr)}function Jq(e){return e.reduce((t,n)=>t+bN(n),0)}function eV(e){return e.reduce((t,n)=>t+xN(n),0)}function SN(e,t){if(t===void 0&&(t=mo),!e)return;const{top:n,left:r,bottom:a,right:s}=t(e);gN(e)&&(a<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const tV=[["x",["left","right"],Jq],["y",["top","bottom"],eV]];class Yb{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=Vb(n),a=TN(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,i,l]of tV)for(const u of i)Object.defineProperty(this,u,{get:()=>{const c=l(r),d=a[s]-c;return this.rect[u]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ti{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var a;(a=this.target)==null||a.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function nV(e){const{EventTarget:t}=jn(e);return e instanceof t?e:Ms(e)}function Qc(e,t){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var nr;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(nr||(nr={}));function Ky(e){e.preventDefault()}function rV(e){e.stopPropagation()}var Pt;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Pt||(Pt={}));const vN={start:[Pt.Space,Pt.Enter],cancel:[Pt.Esc],end:[Pt.Space,Pt.Enter,Pt.Tab]},aV=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Pt.Right:return{...n,x:n.x+25};case Pt.Left:return{...n,x:n.x-25};case Pt.Down:return{...n,y:n.y+25};case Pt.Up:return{...n,y:n.y-25}}};class Kb{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Ti(Ms(n)),this.windowListeners=new Ti(jn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(nr.Resize,this.handleCancel),this.windowListeners.add(nr.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(nr.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&SN(r),n(pr)}handleKeyDown(t){if(qb(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:s=vN,coordinateGetter:i=aV,scrollBehavior:l="smooth"}=a,{code:u}=t;if(s.end.includes(u)){this.handleEnd(t);return}if(s.cancel.includes(u)){this.handleCancel(t);return}const{collisionRect:c}=r.current,d=c?{x:c.left,y:c.top}:pr;this.referenceCoordinates||(this.referenceCoordinates=d);const p=i(t,{active:n,context:r.current,currentCoordinates:d});if(p){const m=Ul(p,d),f={x:0,y:0},{scrollableAncestors:b}=r.current;for(const x of b){const E=t.code,{isTop:y,isRight:S,isLeft:v,isBottom:N,maxScroll:A,minScroll:w}=yN(x),T=Qq(x),_={x:Math.min(E===Pt.Right?T.right-T.width/2:T.right,Math.max(E===Pt.Right?T.left:T.left+T.width/2,p.x)),y:Math.min(E===Pt.Down?T.bottom-T.height/2:T.bottom,Math.max(E===Pt.Down?T.top:T.top+T.height/2,p.y))},B=E===Pt.Right&&!S||E===Pt.Left&&!v,k=E===Pt.Down&&!N||E===Pt.Up&&!y;if(B&&_.x!==p.x){const $=x.scrollLeft+m.x,V=E===Pt.Right&&$<=A.x||E===Pt.Left&&$>=w.x;if(V&&!m.y){x.scrollTo({left:$,behavior:l});return}V?f.x=x.scrollLeft-$:f.x=E===Pt.Right?x.scrollLeft-A.x:x.scrollLeft-w.x,f.x&&x.scrollBy({left:-f.x,behavior:l});break}else if(k&&_.y!==p.y){const $=x.scrollTop+m.y,V=E===Pt.Down&&$<=A.y||E===Pt.Up&&$>=w.y;if(V&&!m.x){x.scrollTo({top:$,behavior:l});return}V?f.y=x.scrollTop-$:f.y=E===Pt.Down?x.scrollTop-A.y:x.scrollTop-w.y,f.y&&x.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(t,cs(Ul(p,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Kb.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=vN,onActivation:a}=t,{active:s}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const l=s.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),a?.({event:e.nativeEvent}),!0)}return!1}}];function Zy(e){return!!(e&&"distance"in e)}function Xy(e){return!!(e&&"delay"in e)}class Zb{constructor(t,n,r){var a;r===void 0&&(r=nV(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:s}=t,{target:i}=s;this.props=t,this.events=n,this.document=Ms(i),this.documentListeners=new Ti(this.document),this.listeners=new Ti(r),this.windowListeners=new Ti(jn(i)),this.initialCoordinates=(a=$l(s))!=null?a:pr,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(nr.Resize,this.handleCancel),this.windowListeners.add(nr.DragStart,Ky),this.windowListeners.add(nr.VisibilityChange,this.handleCancel),this.windowListeners.add(nr.ContextMenu,Ky),this.documentListeners.add(nr.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Xy(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Zy(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:a}=this.props;a(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(nr.Click,rV,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(nr.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:a,props:s}=this,{onMove:i,options:{activationConstraint:l}}=s;if(!a)return;const u=(n=$l(t))!=null?n:pr,c=Ul(a,u);if(!r&&l){if(Zy(l)){if(l.tolerance!=null&&Qc(c,l.tolerance))return this.handleCancel();if(Qc(c,l.distance))return this.handleStart()}if(Xy(l)&&Qc(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}t.cancelable&&t.preventDefault(),i(u)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Pt.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const sV={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Xb extends Zb{constructor(t){const{event:n}=t,r=Ms(n.target);super(t,sV,r)}}Xb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const iV={move:{name:"mousemove"},end:{name:"mouseup"}};var Xd;(function(e){e[e.RightClick=2]="RightClick"})(Xd||(Xd={}));class oV extends Zb{constructor(t){super(t,iV,Ms(t.event.target))}}oV.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===Xd.RightClick?!1:(r?.({event:n}),!0)}}];const Jc={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class lV extends Zb{constructor(t){super(t,Jc)}static setup(){return window.addEventListener(Jc.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Jc.move.name,t)};function t(){}}}lV.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:a}=n;return a.length>1?!1:(r?.({event:n}),!0)}}];var Si;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Si||(Si={}));var Hl;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(Hl||(Hl={}));function uV(e){let{acceleration:t,activator:n=Si.Pointer,canScroll:r,draggingRect:a,enabled:s,interval:i=5,order:l=Hl.TreeOrder,pointerCoordinates:u,scrollableAncestors:c,scrollableAncestorRects:d,delta:p,threshold:m}=e;const f=dV({delta:p,disabled:!s}),[b,x]=vq(),E=g.useRef({x:0,y:0}),y=g.useRef({x:0,y:0}),S=g.useMemo(()=>{switch(n){case Si.Pointer:return u?{top:u.y,bottom:u.y,left:u.x,right:u.x}:null;case Si.DraggableRect:return a}},[n,a,u]),v=g.useRef(null),N=g.useCallback(()=>{const w=v.current;if(!w)return;const T=E.current.x*y.current.x,_=E.current.y*y.current.y;w.scrollBy(T,_)},[]),A=g.useMemo(()=>l===Hl.TreeOrder?[...c].reverse():c,[l,c]);g.useEffect(()=>{if(!s||!c.length||!S){x();return}for(const w of A){if(r?.(w)===!1)continue;const T=c.indexOf(w),_=d[T];if(!_)continue;const{direction:B,speed:k}=Xq(w,_,S,t,m);for(const $ of["x","y"])f[$][B[$]]||(k[$]=0,B[$]=0);if(k.x>0||k.y>0){x(),v.current=w,b(N,i),E.current=k,y.current=B;return}}E.current={x:0,y:0},y.current={x:0,y:0},x()},[t,N,r,x,s,i,JSON.stringify(S),JSON.stringify(f),b,c,A,d,JSON.stringify(m)])}const cV={x:{[mn.Backward]:!1,[mn.Forward]:!1},y:{[mn.Backward]:!1,[mn.Forward]:!1}};function dV(e){let{delta:t,disabled:n}=e;const r=Bl(t);return fo(a=>{if(n||!r||!a)return cV;const s={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[mn.Backward]:a.x[mn.Backward]||s.x===-1,[mn.Forward]:a.x[mn.Forward]||s.x===1},y:{[mn.Backward]:a.y[mn.Backward]||s.y===-1,[mn.Forward]:a.y[mn.Forward]||s.y===1}}},[n,t,r])}function pV(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return fo(a=>{var s;return t==null?null:(s=r??a)!=null?s:null},[r,t])}function fV(e,t){return g.useMemo(()=>e.reduce((n,r)=>{const{sensor:a}=r,s=a.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...s]},[]),[e,t])}var zi;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(zi||(zi={}));var Qd;(function(e){e.Optimized="optimized"})(Qd||(Qd={}));const Qy=new Map;function mV(e,t){let{dragging:n,dependencies:r,config:a}=t;const[s,i]=g.useState(null),{frequency:l,measure:u,strategy:c}=a,d=g.useRef(e),p=E(),m=$i(p),f=g.useCallback(function(y){y===void 0&&(y=[]),!m.current&&i(S=>S===null?y:S.concat(y.filter(v=>!S.includes(v))))},[m]),b=g.useRef(null),x=fo(y=>{if(p&&!n)return Qy;if(!y||y===Qy||d.current!==e||s!=null){const S=new Map;for(let v of e){if(!v)continue;if(s&&s.length>0&&!s.includes(v.id)&&v.rect.current){S.set(v.id,v.rect.current);continue}const N=v.node.current,A=N?new Yb(u(N),N):null;v.rect.current=A,A&&S.set(v.id,A)}return S}return y},[e,s,n,p,u]);return g.useEffect(()=>{d.current=e},[e]),g.useEffect(()=>{p||f()},[n,p]),g.useEffect(()=>{s&&s.length>0&&i(null)},[JSON.stringify(s)]),g.useEffect(()=>{p||typeof l!="number"||b.current!==null||(b.current=setTimeout(()=>{f(),b.current=null},l))},[l,p,f,...r]),{droppableRects:x,measureDroppableContainers:f,measuringScheduled:s!=null};function E(){switch(c){case zi.Always:return!1;case zi.BeforeDragging:return n;default:return!n}}}function Qb(e,t){return fo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function hV(e,t){return Qb(e,t)}function gV(e){let{callback:t,disabled:n}=e;const r=Uu(t),a=g.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return g.useEffect(()=>()=>a?.disconnect(),[a]),a}function zu(e){let{callback:t,disabled:n}=e;const r=Uu(t),a=g.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return g.useEffect(()=>()=>a?.disconnect(),[a]),a}function bV(e){return new Yb(mo(e),e)}function Jy(e,t,n){t===void 0&&(t=bV);const[r,a]=g.useState(null);function s(){a(u=>{if(!e)return null;if(e.isConnected===!1){var c;return(c=u??n)!=null?c:null}const d=t(e);return JSON.stringify(u)===JSON.stringify(d)?u:d})}const i=gV({callback(u){if(e)for(const c of u){const{type:d,target:p}=c;if(d==="childList"&&p instanceof HTMLElement&&p.contains(e)){s();break}}}}),l=zu({callback:s});return Br(()=>{s(),e?(l?.observe(e),i?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),i?.disconnect())},[e]),r}function xV(e){const t=Qb(e);return mN(e,t)}const e1=[];function EV(e){const t=g.useRef(e),n=fo(r=>e?r&&r!==e1&&e&&t.current&&e.parentNode===t.current.parentNode?r:Vb(e):e1,[e]);return g.useEffect(()=>{t.current=e},[e]),n}function yV(e){const[t,n]=g.useState(null),r=g.useRef(e),a=g.useCallback(s=>{const i=Xc(s.target);i&&n(l=>l?(l.set(i,Zd(i)),new Map(l)):null)},[]);return g.useEffect(()=>{const s=r.current;if(e!==s){i(s);const l=e.map(u=>{const c=Xc(u);return c?(c.addEventListener("scroll",a,{passive:!0}),[c,Zd(c)]):null}).filter(u=>u!=null);n(l.length?new Map(l):null),r.current=e}return()=>{i(e),i(s)};function i(l){l.forEach(u=>{const c=Xc(u);c?.removeEventListener("scroll",a)})}},[a,e]),g.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,i)=>cs(s,i),pr):TN(e):pr,[e,t])}function t1(e,t){t===void 0&&(t=[]);const n=g.useRef(null);return g.useEffect(()=>{n.current=null},t),g.useEffect(()=>{const r=e!==pr;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?Ul(e,n.current):pr}function TV(e){g.useEffect(()=>{if(!Bu)return;const t=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function SV(e,t){return g.useMemo(()=>e.reduce((n,r)=>{let{eventName:a,handler:s}=r;return n[a]=i=>{s(i,t)},n},{}),[e,t])}function wN(e){return g.useMemo(()=>e?Vq(e):null,[e])}const n1=[];function vV(e,t){t===void 0&&(t=mo);const[n]=e,r=wN(n?jn(n):null),[a,s]=g.useState(n1);function i(){s(()=>e.length?e.map(u=>EN(u)?r:new Yb(t(u),u)):n1)}const l=zu({callback:i});return Br(()=>{l?.disconnect(),i(),e.forEach(u=>l?.observe(u))},[e]),a}function NN(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return po(t)?t:e}function wV(e){let{measure:t}=e;const[n,r]=g.useState(null),a=g.useCallback(c=>{for(const{target:d}of c)if(po(d)){r(p=>{const m=t(d);return p?{...p,width:m.width,height:m.height}:m});break}},[t]),s=zu({callback:a}),i=g.useCallback(c=>{const d=NN(c);s?.disconnect(),d&&s?.observe(d),r(d?t(d):null)},[t,s]),[l,u]=Pl(i);return g.useMemo(()=>({nodeRef:l,rect:n,setRef:u}),[n,l,u])}const NV=[{sensor:Xb,options:{}},{sensor:Kb,options:{}}],AV={current:{}},cl={draggable:{measure:Yy},droppable:{measure:Yy,strategy:zi.WhileDragging,frequency:Qd.Optimized},dragOverlay:{measure:mo}};class vi extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const _V={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new vi,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:zl},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:cl,measureDroppableContainers:zl,windowRect:null,measuringScheduled:!1},AN={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:zl,draggableNodes:new Map,over:null,measureDroppableContainers:zl},ho=g.createContext(AN),_N=g.createContext(_V);function kV(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new vi}}}function CV(e,t){switch(t.type){case on.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case on.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case on.DragEnd:case on.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case on.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new vi(e.droppable.containers);return a.set(r,n),{...e,droppable:{...e.droppable,containers:a}}}case on.SetDroppableDisabled:{const{id:n,key:r,disabled:a}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const i=new vi(e.droppable.containers);return i.set(n,{...s,disabled:a}),{...e,droppable:{...e.droppable,containers:i}}}case on.UnregisterDroppable:{const{id:n,key:r}=t,a=e.droppable.containers.get(n);if(!a||r!==a.key)return e;const s=new vi(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function IV(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:a}=g.useContext(ho),s=Bl(r),i=Bl(n?.id);return g.useEffect(()=>{if(!t&&!r&&s&&i!=null){if(!qb(s)||document.activeElement===s.target)return;const l=a.get(i);if(!l)return;const{activatorNode:u,node:c}=l;if(!u.current&&!c.current)return;requestAnimationFrame(()=>{for(const d of[u.current,c.current]){if(!d)continue;const p=Aq(d);if(p){p.focus();break}}})}},[r,t,a,i,s]),null}function kN(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((a,s)=>s({transform:a,...r}),n):n}function RV(e){return g.useMemo(()=>({draggable:{...cl.draggable,...e?.draggable},droppable:{...cl.droppable,...e?.droppable},dragOverlay:{...cl.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function DV(e){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=e;const s=g.useRef(!1),{x:i,y:l}=typeof a=="boolean"?{x:a,y:a}:a;Br(()=>{if(!i&&!l||!t){s.current=!1;return}if(s.current||!r)return;const c=t?.node.current;if(!c||c.isConnected===!1)return;const d=n(c),p=mN(d,r);if(i||(p.x=0),l||(p.y=0),s.current=!0,Math.abs(p.x)>0||Math.abs(p.y)>0){const m=gN(c);m&&m.scrollBy({top:p.y,left:p.x})}},[t,i,l,r,n])}const Hu=g.createContext({...pr,scaleX:1,scaleY:1});var Kr;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Kr||(Kr={}));const OV=g.memo(function(t){var n,r,a,s;let{id:i,accessibility:l,autoScroll:u=!0,children:c,sensors:d=NV,collisionDetection:p=$q,measuring:m,modifiers:f,...b}=t;const x=g.useReducer(CV,void 0,kV),[E,y]=x,[S,v]=Dq(),[N,A]=g.useState(Kr.Uninitialized),w=N===Kr.Initialized,{draggable:{active:T,nodes:_,translate:B},droppable:{containers:k}}=E,$=T!=null?_.get(T):null,V=g.useRef({initial:null,translated:null}),P=g.useMemo(()=>{var De;return T!=null?{id:T,data:(De=$?.data)!=null?De:AV,rect:V}:null},[T,$]),H=g.useRef(null),[W,L]=g.useState(null),[te,ie]=g.useState(null),be=$i(b,Object.values(b)),I=$u("DndDescribedBy",i),ne=g.useMemo(()=>k.getEnabled(),[k]),ue=RV(m),{droppableRects:O,measureDroppableContainers:Ne,measuringScheduled:de}=mV(ne,{dragging:w,dependencies:[B.x,B.y],config:ue.droppable}),K=pV(_,T),Ee=g.useMemo(()=>te?$l(te):null,[te]),re=zt(),D=hV(K,ue.draggable.measure);DV({activeNode:T!=null?_.get(T):null,config:re.layoutShiftCompensation,initialRect:D,measure:ue.draggable.measure});const ye=Jy(K,ue.draggable.measure,D),Se=Jy(K?K.parentElement:null),pe=g.useRef({activatorEvent:null,active:null,activeNode:K,collisionRect:null,collisions:null,droppableRects:O,draggableNodes:_,draggingNode:null,draggingNodeRect:null,droppableContainers:k,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ae=k.getNodeFor((n=pe.current.over)==null?void 0:n.id),He=wV({measure:ue.dragOverlay.measure}),fe=(r=He.nodeRef.current)!=null?r:K,Je=w?(a=He.rect)!=null?a:ye:null,bt=!!(He.nodeRef.current&&He.rect),it=xV(bt?null:ye),Ft=wN(fe?jn(fe):null),Nt=EV(w?Ae??K:null),Tt=vV(Nt),$t=kN(f,{transform:{x:B.x-it.x,y:B.y-it.y,scaleX:1,scaleY:1},activatorEvent:te,active:P,activeNodeRect:ye,containerNodeRect:Se,draggingNodeRect:Je,over:pe.current.over,overlayNodeRect:He.rect,scrollableAncestors:Nt,scrollableAncestorRects:Tt,windowRect:Ft}),rt=Ee?cs(Ee,B):null,Me=yV(Nt),et=t1(Me),Q=t1(Me,[ye]),ce=cs($t,et),Re=Je?Gq(Je,$t):null,G=P&&Re?p({active:P,collisionRect:Re,droppableRects:O,droppableContainers:ne,pointerCoordinates:rt}):null,Fe=Bq(G,"id"),[Ve,pt]=g.useState(null),At=bt?$t:cs($t,Q),St=zq(At,(s=Ve?.rect)!=null?s:null,ye),Rt=g.useRef(null),le=g.useCallback((De,tt)=>{let{sensor:Xe,options:kt}=tt;if(H.current==null)return;const se=_.get(H.current);if(!se)return;const he=De.nativeEvent,st=new Xe({active:H.current,activeNode:se,event:he,options:kt,context:pe,onAbort(Y){if(!_.get(Y))return;const{onDragAbort:F}=be.current,q={id:Y};F?.(q),S({type:"onDragAbort",event:q})},onPending(Y,Ge,F,q){if(!_.get(Y))return;const{onDragPending:me}=be.current,ve={id:Y,constraint:Ge,initialCoordinates:F,offset:q};me?.(ve),S({type:"onDragPending",event:ve})},onStart(Y){const Ge=H.current;if(Ge==null)return;const F=_.get(Ge);if(!F)return;const{onDragStart:q}=be.current,X={activatorEvent:he,active:{id:Ge,data:F.data,rect:V}};na.unstable_batchedUpdates(()=>{q?.(X),A(Kr.Initializing),y({type:on.DragStart,initialCoordinates:Y,active:Ge}),S({type:"onDragStart",event:X}),L(Rt.current),ie(he)})},onMove(Y){y({type:on.DragMove,coordinates:Y})},onEnd:Ot(on.DragEnd),onCancel:Ot(on.DragCancel)});Rt.current=st;function Ot(Y){return async function(){const{active:F,collisions:q,over:X,scrollAdjustedTranslate:me}=pe.current;let ve=null;if(F&&me){const{cancelDrop:Le}=be.current;ve={activatorEvent:he,active:F,collisions:q,delta:me,over:X},Y===on.DragEnd&&typeof Le=="function"&&await Promise.resolve(Le(ve))&&(Y=on.DragCancel)}H.current=null,na.unstable_batchedUpdates(()=>{y({type:Y}),A(Kr.Uninitialized),pt(null),L(null),ie(null),Rt.current=null;const Le=Y===on.DragEnd?"onDragEnd":"onDragCancel";if(ve){const Oe=be.current[Le];Oe?.(ve),S({type:Le,event:ve})}})}}},[_]),Ce=g.useCallback((De,tt)=>(Xe,kt)=>{const se=Xe.nativeEvent,he=_.get(kt);if(H.current!==null||!he||se.dndKit||se.defaultPrevented)return;const st={active:he};De(Xe,tt.options,st)===!0&&(se.dndKit={capturedBy:tt.sensor},H.current=kt,le(Xe,tt))},[_,le]),Ue=fV(d,Ce);TV(d),Br(()=>{ye&&N===Kr.Initializing&&A(Kr.Initialized)},[ye,N]),g.useEffect(()=>{const{onDragMove:De}=be.current,{active:tt,activatorEvent:Xe,collisions:kt,over:se}=pe.current;if(!tt||!Xe)return;const he={active:tt,activatorEvent:Xe,collisions:kt,delta:{x:ce.x,y:ce.y},over:se};na.unstable_batchedUpdates(()=>{De?.(he),S({type:"onDragMove",event:he})})},[ce.x,ce.y]),g.useEffect(()=>{const{active:De,activatorEvent:tt,collisions:Xe,droppableContainers:kt,scrollAdjustedTranslate:se}=pe.current;if(!De||H.current==null||!tt||!se)return;const{onDragOver:he}=be.current,st=kt.get(Fe),Ot=st&&st.rect.current?{id:st.id,rect:st.rect.current,data:st.data,disabled:st.disabled}:null,Y={active:De,activatorEvent:tt,collisions:Xe,delta:{x:se.x,y:se.y},over:Ot};na.unstable_batchedUpdates(()=>{pt(Ot),he?.(Y),S({type:"onDragOver",event:Y})})},[Fe]),Br(()=>{pe.current={activatorEvent:te,active:P,activeNode:K,collisionRect:Re,collisions:G,droppableRects:O,draggableNodes:_,draggingNode:fe,draggingNodeRect:Je,droppableContainers:k,over:Ve,scrollableAncestors:Nt,scrollAdjustedTranslate:ce},V.current={initial:Je,translated:Re}},[P,K,G,Re,_,fe,Je,O,k,Ve,Nt,ce]),uV({...re,delta:B,draggingRect:Re,pointerCoordinates:rt,scrollableAncestors:Nt,scrollableAncestorRects:Tt});const je=g.useMemo(()=>({active:P,activeNode:K,activeNodeRect:ye,activatorEvent:te,collisions:G,containerNodeRect:Se,dragOverlay:He,draggableNodes:_,droppableContainers:k,droppableRects:O,over:Ve,measureDroppableContainers:Ne,scrollableAncestors:Nt,scrollableAncestorRects:Tt,measuringConfiguration:ue,measuringScheduled:de,windowRect:Ft}),[P,K,ye,te,G,Se,He,_,k,O,Ve,Ne,Nt,Tt,ue,de,Ft]),Et=g.useMemo(()=>({activatorEvent:te,activators:Ue,active:P,activeNodeRect:ye,ariaDescribedById:{draggable:I},dispatch:y,draggableNodes:_,over:Ve,measureDroppableContainers:Ne}),[te,Ue,P,ye,y,I,_,Ve,Ne]);return at.createElement(fN.Provider,{value:v},at.createElement(ho.Provider,{value:Et},at.createElement(_N.Provider,{value:je},at.createElement(Hu.Provider,{value:St},c)),at.createElement(IV,{disabled:l?.restoreFocus===!1})),at.createElement(Mq,{...l,hiddenTextDescribedById:I}));function zt(){const De=W?.autoScrollEnabled===!1,tt=typeof u=="object"?u.enabled===!1:u===!1,Xe=w&&!De&&!tt;return typeof u=="object"?{...u,enabled:Xe}:{enabled:Xe}}}),LV=g.createContext(null),r1="button",MV="Draggable";function FV(e){let{id:t,data:n,disabled:r=!1,attributes:a}=e;const s=$u(MV),{activators:i,activatorEvent:l,active:u,activeNodeRect:c,ariaDescribedById:d,draggableNodes:p,over:m}=g.useContext(ho),{role:f=r1,roleDescription:b="draggable",tabIndex:x=0}=a??{},E=u?.id===t,y=g.useContext(E?Hu:LV),[S,v]=Pl(),[N,A]=Pl(),w=SV(i,t),T=$i(n);Br(()=>(p.set(t,{id:t,key:s,node:S,activatorNode:N,data:T}),()=>{const B=p.get(t);B&&B.key===s&&p.delete(t)}),[p,t]);const _=g.useMemo(()=>({role:f,tabIndex:x,"aria-disabled":r,"aria-pressed":E&&f===r1?!0:void 0,"aria-roledescription":b,"aria-describedby":d.draggable}),[r,f,x,E,b,d.draggable]);return{active:u,activatorEvent:l,activeNodeRect:c,attributes:_,isDragging:E,listeners:r?void 0:w,node:S,over:m,setNodeRef:v,setActivatorNodeRef:A,transform:y}}function jV(){return g.useContext(_N)}const PV="Droppable",BV={timeout:25};function UV(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=e;const s=$u(PV),{active:i,dispatch:l,over:u,measureDroppableContainers:c}=g.useContext(ho),d=g.useRef({disabled:n}),p=g.useRef(!1),m=g.useRef(null),f=g.useRef(null),{disabled:b,updateMeasurementsFor:x,timeout:E}={...BV,...a},y=$i(x??r),S=g.useCallback(()=>{if(!p.current){p.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),f.current=null},E)},[E]),v=zu({callback:S,disabled:b||!i}),N=g.useCallback((_,B)=>{v&&(B&&(v.unobserve(B),p.current=!1),_&&v.observe(_))},[v]),[A,w]=Pl(N),T=$i(t);return g.useEffect(()=>{!v||!A.current||(v.disconnect(),p.current=!1,v.observe(A.current))},[A,v]),g.useEffect(()=>(l({type:on.RegisterDroppable,element:{id:r,key:s,disabled:n,node:A,rect:m,data:T}}),()=>l({type:on.UnregisterDroppable,key:s,id:r})),[r]),g.useEffect(()=>{n!==d.current.disabled&&(l({type:on.SetDroppableDisabled,id:r,key:s,disabled:n}),d.current.disabled=n)},[r,s,n,l]),{active:i,rect:m,isOver:u?.id===r,node:A,over:u,setNodeRef:w}}function $V(e){let{animation:t,children:n}=e;const[r,a]=g.useState(null),[s,i]=g.useState(null),l=Bl(n);return!n&&!r&&l&&a(l),Br(()=>{if(!s)return;const u=r?.key,c=r?.props.id;if(u==null||c==null){a(null);return}Promise.resolve(t(c,s)).then(()=>{a(null)})},[t,r,s]),at.createElement(at.Fragment,null,n,r?g.cloneElement(r,{ref:i}):null)}const zV={x:0,y:0,scaleX:1,scaleY:1};function HV(e){let{children:t}=e;return at.createElement(ho.Provider,{value:AN},at.createElement(Hu.Provider,{value:zV},t))}const GV={position:"fixed",touchAction:"none"},WV=e=>qb(e)?"transform 250ms ease":void 0,qV=g.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:a,children:s,className:i,rect:l,style:u,transform:c,transition:d=WV}=e;if(!l)return null;const p=a?c:{...c,scaleX:1,scaleY:1},m={...GV,width:l.width,height:l.height,top:l.top,left:l.left,transform:bs.Transform.toString(p),transformOrigin:a&&r?jq(r,l):void 0,transition:typeof d=="function"?d(r):d,...u};return at.createElement(n,{className:i,style:m,ref:t},s)}),VV=e=>t=>{let{active:n,dragOverlay:r}=t;const a={},{styles:s,className:i}=e;if(s!=null&&s.active)for(const[l,u]of Object.entries(s.active))u!==void 0&&(a[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,u));if(s!=null&&s.dragOverlay)for(const[l,u]of Object.entries(s.dragOverlay))u!==void 0&&r.node.style.setProperty(l,u);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[u,c]of Object.entries(a))n.node.style.setProperty(u,c);i!=null&&i.active&&n.node.classList.remove(i.active)}},YV=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:bs.Transform.toString(t)},{transform:bs.Transform.toString(n)}]},KV={duration:250,easing:"ease",keyframes:YV,sideEffects:VV({styles:{active:{opacity:"0"}}})};function ZV(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:a}=e;return Uu((s,i)=>{if(t===null)return;const l=n.get(s);if(!l)return;const u=l.node.current;if(!u)return;const c=NN(i);if(!c)return;const{transform:d}=jn(i).getComputedStyle(i),p=hN(d);if(!p)return;const m=typeof t=="function"?t:XV(t);return SN(u,a.draggable.measure),m({active:{id:s,data:l.data,node:u,rect:a.draggable.measure(u)},draggableNodes:n,dragOverlay:{node:i,rect:a.dragOverlay.measure(c)},droppableContainers:r,measuringConfiguration:a,transform:p})})}function XV(e){const{duration:t,easing:n,sideEffects:r,keyframes:a}={...KV,...e};return s=>{let{active:i,dragOverlay:l,transform:u,...c}=s;if(!t)return;const d={x:l.rect.left-i.rect.left,y:l.rect.top-i.rect.top},p={scaleX:u.scaleX!==1?i.rect.width*u.scaleX/l.rect.width:1,scaleY:u.scaleY!==1?i.rect.height*u.scaleY/l.rect.height:1},m={x:u.x-d.x,y:u.y-d.y,...p},f=a({...c,active:i,dragOverlay:l,transform:{initial:u,final:m}}),[b]=f,x=f[f.length-1];if(JSON.stringify(b)===JSON.stringify(x))return;const E=r?.({active:i,dragOverlay:l,...c}),y=l.node.animate(f,{duration:t,easing:n,fill:"forwards"});return new Promise(S=>{y.onfinish=()=>{E?.(),S()}})}}let a1=0;function QV(e){return g.useMemo(()=>{if(e!=null)return a1++,a1},[e])}const JV=at.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:a,transition:s,modifiers:i,wrapperElement:l="div",className:u,zIndex:c=999}=e;const{activatorEvent:d,active:p,activeNodeRect:m,containerNodeRect:f,draggableNodes:b,droppableContainers:x,dragOverlay:E,over:y,measuringConfiguration:S,scrollableAncestors:v,scrollableAncestorRects:N,windowRect:A}=jV(),w=g.useContext(Hu),T=QV(p?.id),_=kN(i,{activatorEvent:d,active:p,activeNodeRect:m,containerNodeRect:f,draggingNodeRect:E.rect,over:y,overlayNodeRect:E.rect,scrollableAncestors:v,scrollableAncestorRects:N,transform:w,windowRect:A}),B=Qb(m),k=ZV({config:r,draggableNodes:b,droppableContainers:x,measuringConfiguration:S}),$=B?E.setRef:void 0;return at.createElement(HV,null,at.createElement($V,{animation:k},p&&T?at.createElement(qV,{key:T,id:p.id,ref:$,as:l,activatorEvent:d,adjustScale:t,className:u,transition:s,rect:B,style:{zIndex:c,...a},transform:_},n):null))}),eY=6e4,tY=10080*60*1e3,nY={P1:"error",P2:"warning",P3:"neutral"},rY={backlog:"bg-spur-text-faint",todo:"bg-spur-info",wip:"bg-spur-warning",testing:"bg-spur-accent",done:"bg-spur-success",blocked:"bg-spur-error",cancelled:"bg-spur-text-faint"};function aY(e,t){const n=new Date(e).getTime(),r=t-n,a=Math.floor(r/1e3);if(a<60)return"just now";const s=Math.floor(a/60);if(s<60)return`${s}m ago`;const i=Math.floor(s/60);if(i<24)return`${i}h ago`;const l=Math.floor(i/24);return l<30?`${l}d ago`:`${Math.floor(l/30)}mo ago`}function CN({task:e,onClick:t}){const{attributes:n,listeners:r,setNodeRef:a,transform:s,isDragging:i}=FV({id:e.wbs,data:{task:e}}),[l,u]=g.useState(Date.now());g.useEffect(()=>{const f=setInterval(()=>u(Date.now()),eY);return()=>clearInterval(f)},[]);const c=s?{transform:bs.Transform.toString(s),zIndex:i?50:void 0}:void 0,{subtaskProgress:d}=jb(),p=d.get(e.wbs),m=e.updatedAt?l-new Date(e.updatedAt).getTime()>tY:!1;return o.jsx(kj,{variant:"compact",asChild:!0,className:`bg-spur-surface-2 hover:bg-spur-surface-3 rounded-xl border border-spur-border hover:border-spur-accent/40 cursor-pointer transition-colors w-full text-left ${i?"opacity-30":""}`,children:o.jsx("button",{ref:a,type:"button",style:c,onClick:()=>t(e.wbs),...r,...n,"aria-roledescription":"draggable card",children:o.jsxs(Cj,{className:"p-3 gap-1",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-mono font-semibold text-spur-text",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${rY[e.status]??"bg-spur-text-faint"}`,"data-status":e.status,"aria-hidden":"true"}),e.wbs]}),e.priority&&o.jsx(gn,{variant:nY[e.priority]??"outline",size:"xs",children:e.priority})]}),o.jsx("p",{className:"text-sm font-medium text-spur-text leading-snug line-clamp-2",children:e.name}),o.jsxs("div",{className:"flex gap-1 flex-wrap items-center",children:[p&&p.total>0&&o.jsxs("div",{className:"flex items-center gap-1.5","data-testid":"subtask-progress",title:"subtasks done/total",children:[o.jsx("div",{className:"h-1 flex-1 rounded-full bg-spur-border overflow-hidden",children:o.jsx("div",{className:"h-full bg-spur-success",style:{width:`${Math.round(p.done/p.total*100)}%`}})}),o.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted shrink-0",children:[p.done,"/",p.total]})]}),e.type&&e.type!=="task"&&o.jsx(gn,{variant:"outline",size:"xs",children:e.type}),e.featureId&&o.jsx(gn,{variant:"outline",size:"xs",children:e.featureId}),e.updatedAt&&o.jsx("span",{className:`text-xs font-mono ml-auto ${m?"text-spur-text-faint":"text-spur-text-muted"}`,title:e.updatedAt,children:aY(e.updatedAt,l)})]})]})})})}function sY({status:e,label:t,tasks:n,onCardClick:r,sortDir:a,onSortToggle:s}){const{setNodeRef:i,isOver:l}=UV({id:e,data:{status:e}});return o.jsxs("section",{ref:i,"aria-label":`${t} column`,className:`flex flex-col flex-1 min-w-[16rem] rounded-xl border transition-colors duration-200 ${l?"bg-spur-surface-2 border-spur-accent shadow-lg":"bg-spur-surface border-spur-border"}`,children:[o.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border shrink-0",children:[o.jsxs("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:[Mb(e)," ",t]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(gn,{variant:"ghost",size:"sm",children:n.length}),s&&o.jsx(ot,{variant:"ghost",size:"xs",className:"px-1",onClick:s,"aria-label":`Sort ${t} by WBS`,title:`Sort ${t}: ${a==="asc"?"WBS ↓":a==="desc"?"WBS ↑":"none"}`,children:a==="asc"?"↓":a==="desc"?"↑":"⇅"})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-2 min-h-[4rem]",children:[n.map(u=>o.jsx(CN,{task:u,onClick:r},u.wbs)),n.length===0&&o.jsx("div",{className:"flex items-center justify-center h-16 text-xs text-spur-text-muted italic",children:"No tasks"})]})]})}const iY=g.lazy(()=>ww(()=>import("./TaskDetail.DqFJbRFc.js"),__vite__mapDeps([2,1]))),oY=sr,IN="docs/tasks",s1="spur:detail-width",lY=new Set(["blocked","cancelled"]);function uY(e,t){return t?e.filter(n=>!(t.status!==void 0&&!t.status.split(",").includes(n.status)||t.featureId&&!n.featureId?.toLowerCase().includes(t.featureId.toLowerCase())||t.parentWbs&&n.parentWbs!==t.parentWbs)):e}function RN(e){const{onSelectTask:t,filters:n,folder:r,hiddenColumns:a,onConnectionChange:s,onSyncChange:i}=e,[l,u]=g.useState({}),[c,d]=g.useState(IN),[p,m]=g.useState(null),[f,b]=g.useState(()=>{const ne=typeof window<"u"?Math.min(1728,window.innerWidth*.8):1728;if(typeof window>"u")return ne;try{const ue=Number.parseFloat(window.localStorage.getItem(s1)??"");if(Number.isFinite(ue)&&ue>0)return Math.min(ue,window.innerWidth*.8)}catch{}return ne}),x=r??c,E=a??lY,y=g.useCallback(()=>rn.task.list({folder:x}),[x]),{tasks:S,loading:v,error:N,connected:A,lastSyncAt:w,setTasks:T,store:_}=jb(y),[B,k]=g.useState(null);g.useEffect(()=>{s?.(A)},[A,s]),g.useEffect(()=>{i?.(w)},[w,i]),g.useEffect(()=>{typeof rn.task.folders=="function"&&rn.task.folders({}).then(ne=>{const{data:ue,activeFolder:O}=ne,Ne=O??ue?.[0]?.path;Ne!==void 0&&d(Ne)}).catch(()=>{})},[]),g.useEffect(()=>{document.documentElement.style.setProperty("--detail-w",`${f}px`)},[f]),g.useEffect(()=>{if(!p)return;const ne=ue=>{ue.key==="Escape"&&m(null)};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[p]);const $=Zn();g.useEffect(()=>{const ne=$.pathname.split("/"),ue=ne.indexOf("tasks"),O=ue>=0?ne[ue+1]:void 0;O&&/^\d{4}$/.test(O)&&m(O)},[$.pathname]);const V=Vy(Xb,{activationConstraint:{distance:5}}),P=Vy(Kb),H=Fq(V,P),W=uY(S,n),L=ne=>{u(ue=>{const O={...ue};return ue[ne]==="asc"?O[ne]="desc":ue[ne]==="desc"?delete O[ne]:O[ne]="asc",O})},te=ne=>{const ue=W.filter(Ne=>Ne.status===ne),O=l[ne]??"desc";return[...ue].sort((Ne,de)=>{const K=Ne.wbs.localeCompare(de.wbs);return O==="asc"?K:-K})},ie=ne=>S.find(ue=>ue.wbs===ne),be=ne=>{k(String(ne.active.id))},I=ne=>{k(null);const{active:ue,over:O}=ne;if(!O)return;const Ne=String(ue.id),de=String(O.id),K=ie(Ne);if(!K||K.status===de)return;const Ee=[...S];T(re=>re.map(D=>D.wbs===Ne?{...D,status:de}:D)),rn.task.transition({wbs:Ne,toStatus:de}).catch(re=>{T(Ee);const D=re instanceof Error?re.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:D}}))})};return v?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx(Fa,{size:"lg",className:"text-spur-accent"})}):N?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("div",{className:"text-center text-spur-text-muted",children:[o.jsx("p",{className:"text-lg font-semibold",children:"Failed to load tasks"}),o.jsx("p",{className:"text-sm",children:N.message})]})}):o.jsx(Iw.Provider,{value:_,children:o.jsxs(OV,{sensors:H,onDragStart:be,onDragEnd:I,children:[o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx("div",{className:"flex gap-3 overflow-x-auto h-full p-4",children:oY.filter(ne=>!E.has(ne)).map(ne=>o.jsx(sY,{status:ne,label:ne,tasks:te(ne),onCardClick:ue=>{m(ue),t(ue)},sortDir:l[ne],onSortToggle:()=>L(ne)},ne))}),p&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button","aria-label":"Close task detail",className:"fixed inset-0 z-50 bg-black/40 border-0 p-0 cursor-default",onClick:()=>m(null)}),o.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Task detail",className:"fixed top-0 right-0 h-full z-50 bg-spur-surface border-l border-spur-border shadow-2xl flex",style:{width:"var(--detail-w)",minWidth:"36rem",maxWidth:"80vw"},children:[o.jsx(Dl,{targetVar:"--detail-w",onResizeEnd:ne=>{const ue=Math.max(576,Math.min(ne,window.innerWidth*.8));b(ue);try{window.localStorage.setItem(s1,String(ue))}catch{}},direction:"horizontal",invert:!0}),o.jsx("div",{className:"flex flex-col flex-1 overflow-hidden",children:o.jsx("div",{className:"flex-1 overflow-y-auto","data-testid":"detail-body",children:(()=>{const ne=S.find(ue=>ue.wbs===p);return ne?o.jsx(g.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:"Loading detail..."}),children:o.jsx(iY,{task:ne,onClose:()=>m(null),onTransition:(ue,O)=>{T(Ne=>Ne.map(de=>de.wbs===ue?{...de,status:O}:de)),rn.task.transition({wbs:ue,toStatus:O}).catch(Ne=>{const de=Ne instanceof Error?Ne.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:de}}))})}})}):null})()})})]})]})]}),o.jsx(JV,{dropAnimation:null,children:B?(()=>{const ne=ie(B);return ne?o.jsx("div",{className:"opacity-90",children:o.jsx(CN,{task:ne,onClick:()=>{}})}):null})():null})]})})}const ed=[{id:"kanban",label:"Kanban",component:RN}];function DN(){const[e,t]=ck(),n=Zn(),r=qi(),a=g.useMemo(()=>{const u=n.pathname.split("/"),c=u.indexOf("tasks"),d=c>=0?u[c+1]:void 0;return d&&/^\d{4}$/.test(d)?d:e.get("selected")},[n.pathname,e]),s=g.useMemo(()=>{const u={},c=e.get("status"),d=e.get("feature"),p=e.get("parent"),m=e.get("assignee"),f=e.get("folder");return c!==null&&(u.status=c),d&&(u.featureId=d),p&&(u.parentWbs=p),m&&(u.assignee=m),f&&(u.folder=f),u},[e]);return{selected:a,filters:s,selectTask:u=>{const c=new URLSearchParams(e);c.delete("selected");const d=c.toString(),p=u?`/board/tasks/${u}`:"/board/tasks";r(`${p}${d?`?${d}`:""}`,{replace:!0})},setFilter:(u,c)=>{t(d=>{const p=new URLSearchParams(d);return u==="feature"&&p.delete("parent"),u==="parent"&&p.delete("feature"),c!==null?p.set(u,c):p.delete(u),p},{replace:!0})}}}function cY(e){const t=e.trim();return/^\d{4}$/.test(t)?{kind:"navigate",wbs:t}:t.includes(".")?{kind:"filter",key:"parent",value:t}:{kind:"filter",key:"feature",value:t}}function dY(){const{selectTask:e,setFilter:t,filters:n}=DN(),[r,a]=g.useState(IN),[s,i]=g.useState([]),[l,u]=g.useState("kanban"),[c,d]=g.useState(!1),[p,m]=g.useState(""),[f,b]=g.useState(!1),[x,E]=g.useState(void 0),y=n.folder??r,S=new Set(n.status===void 0?sr.filter(T=>T!=="blocked"&&T!=="cancelled"):n.status.split(",").filter(T=>sr.some(_=>_===T))),v=new Set(sr.filter(T=>!S.has(T)));g.useEffect(()=>{m(n.featureId??n.parentWbs??"")},[n.featureId,n.parentWbs]),g.useEffect(()=>{typeof rn.task.folders=="function"&&rn.task.folders({}).then(T=>{const{data:_,activeFolder:B}=T,k=B??_?.[0]?.path;_&&i(_),k!==void 0&&a(k)}).catch(()=>{})},[]);const N=T=>{const _=new Set(S);_.has(T)?_.delete(T):_.add(T),t("status",sr.filter(B=>_.has(B)).join(","))},A=T=>{T.preventDefault();const _=cY(p);if(_.kind==="navigate"){e(_.wbs),m("");return}t(_.key,_.value||null)},w=(ed.find(T=>T.id===l)??ed[0]).component;return o.jsxs("div",{className:"task-kanban flex flex-col h-full",children:[o.jsx("header",{className:"mx-auto w-full max-w-[1600px] shrink-0 px-4 pt-3",children:o.jsxs("div",{className:"flex flex-nowrap items-center justify-between gap-4 border-b border-base-content/10 pb-3",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[o.jsx("span",{className:"text-2xl","aria-hidden":"true",children:"📋"}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold tracking-tight text-spur-text",children:"Tasks"}),o.jsx("p",{className:"text-xs text-spur-text-muted",children:"Task corpus, kanban lanes, and phase filters"}),o.jsxs("p",{className:"mt-1 inline-flex items-center gap-1.5 rounded-full border border-spur-border px-2 py-0.5 text-xs text-spur-text-muted font-mono",role:"status","data-testid":"tasks-live-chip",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${f?"bg-spur-success":"bg-spur-error"}`,"aria-hidden":"true"}),"last sync ",x?new Date(x).toLocaleString():"—"]})]})]}),o.jsxs("div",{className:"flex min-w-0 flex-nowrap items-center gap-2 overflow-x-auto",children:[o.jsx(xi,{variant:"ghost",size:"xs",className:"text-xs shrink-0 w-44",value:y,onChange:T=>t("folder",T.target.value),"aria-label":"Task phase folder",children:s.map(T=>o.jsx("option",{value:T.path,children:T.label?`${T.label} (${T.path})`:T.path},T.path))}),o.jsx("div",{className:"flex shrink-0 items-center gap-1",children:sr.map(T=>o.jsxs("label",{htmlFor:`tasks-status-${T}`,className:"flex items-center gap-1 cursor-pointer",children:[o.jsx(Sb,{id:`tasks-status-${T}`,size:"xs",checked:!v.has(T),onChange:()=>N(T)}),o.jsxs("span",{className:"text-[10px] text-spur-text-muted",children:[Mb(T)," ",T]})]},T))}),o.jsx("form",{onSubmit:A,className:"flex shrink-0 items-center",children:o.jsx(Oi,{"aria-label":"Filter by WBS or feature",type:"text",placeholder:"WBS or feature",variant:"bordered",size:"xs",className:"w-36",value:p,onChange:T=>m(T.target.value)})}),o.jsx(ot,{variant:"primary",size:"sm",className:"shrink-0",onClick:()=>d(!0),children:"+ New Task"}),o.jsx("div",{className:"flex shrink-0 items-center gap-1 bg-base-300 p-1 rounded-xl",children:ed.map(T=>o.jsx("button",{type:"button",className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all ${l===T.id?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,onClick:()=>u(T.id),children:T.label},T.id))})]})]})}),o.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:o.jsx(w,{onSelectTask:e,filters:n,folder:y,hiddenColumns:v,onConnectionChange:b,onSyncChange:E})}),o.jsx(kw,{open:c,onClose:()=>d(!1),onCreated:()=>{},folder:y})]})}function pY(e,t){rn.task.transition({wbs:e,toStatus:t}).catch(n=>{const r=n instanceof Error?n.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:r}}))})}function fY(){const{filters:e,selectTask:t}=DN();return o.jsx("div",{className:"task-kanban flex flex-col h-full",children:o.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:o.jsx(RN,{onSelectTask:t,filters:e})})})}const mY={id:"tasks",name:"Tasks",icon:"📋",route:"tasks",component:dY,sidebarLabel:"Tasks",description:"Task kanban, lifecycle status, and per-task detail",order:40},hY=Object.freeze(Object.defineProperty({__proto__:null,TaskKanbanView:fY,module:mY,transition:pY},Symbol.toStringTag,{value:"Module"}));function ON(e){return e===null||typeof e!="object"?null:"module"in e&&i1(e.module)?e.module:"default"in e&&i1(e.default)?e.default:null}function i1(e){return e===null||typeof e!="object"?!1:"id"in e&&typeof e.id=="string"&&"name"in e&&typeof e.name=="string"&&"icon"in e&&typeof e.icon=="string"&&"route"in e&&typeof e.route=="string"&&"component"in e&&typeof e.component=="function"}function LN(e,t){const n=typeof e.order=="number",r=typeof t.order=="number";return n&&r?e.order-t.order:n?-1:r?1:0}function gY(e){const t=[],n=e("./*/index.{ts,tsx}",{eager:!0});for(const r of Object.values(n)){const a=ON(r);a&&t.push(a)}return t.sort((r,a)=>r.id.localeCompare(a.id)),t.sort(LN),t}function bY(){try{return gY(()=>Object.assign({"./features/index.tsx":aG,"./history/index.tsx":PG,"./observability/index.tsx":OW,"./projects/index.tsx":Sq,"./task-kanban/index.tsx":hY}))}catch(a){if(typeof require!="function")throw a}const e=require("node:fs"),t=require("node:path"),n=require("node:url"),r=typeof __dirname<"u"?__dirname:t.dirname(n.fileURLToPath(import.meta.url));return xY(r,{readdirSync:(a,s)=>e.readdirSync(a,s),tryRequire:a=>require(a)})}function xY(e,t){const n=require("node:path"),r=[];let a=[];try{a=t.readdirSync(e,{withFileTypes:!0})}catch{return r}const s=a.filter(i=>i.isDirectory()).map(i=>i.name).sort((i,l)=>i.localeCompare(l));for(const i of s)for(const l of["tsx","ts"]){const u=n.join(e,i,`index.${l}`);try{const c=t.tryRequire(u),d=ON(c);if(d){r.push(d);break}}catch{}}return r.sort(LN),r}function EY(e,t){const n=new Set(t?.disabled??[]),r=e.slice(),a=new Set(n);function s(){return r.filter(i=>!a.has(i.id))}return yY(r),{get modules(){return s()},getModule(i){return s().find(l=>l.id===i)},get defaultModule(){return s()[0]},disableModule(i){a.add(i)},enableModule(i){a.delete(i)},getEnabledModules(){return s().map(i=>i.id)},registerModuleRoot(i){}}}function yY(e){const t=new Map,n=new Map;for(const r of e){const a=t.get(r.id);if(a!==void 0)throw new Error(`Duplicate module id "${r.id}" discovered in two sources: ${a} and ${Zo(r)}`);t.set(r.id,Zo(r));const s=n.get(r.route);if(s!==void 0)throw new Error(`Duplicate module route "${r.route}" discovered in two sources: ${s} and ${Zo(r)}`);n.set(r.route,Zo(r))}}function Zo(e){return e.id}const Jb=EY(bY(),{disabled:zz}),MN=Jb.modules;function TY(e){return Jb.getModule(e)}const Xo=Jb.defaultModule;function SY(){const[e,t]=g.useState([]);return g.useEffect(()=>{if(typeof window>"u")return;const n=r=>{const s=r.detail?.message||"An error occurred",i=`${Date.now()}-${Math.random().toString(36).slice(2,7)}`;t(l=>[...l,{id:i,message:s}]),setTimeout(()=>{t(l=>l.filter(u=>u.id!==i))},5e3)};return window.addEventListener("api-error",n),()=>{window.removeEventListener("api-error",n)}},[]),e.length===0?null:o.jsx("div",{className:"fixed bottom-4 right-4 z-50 flex flex-col gap-2 max-w-md w-full px-4 pointer-events-none",children:e.map(n=>o.jsxs("div",{className:"pointer-events-auto flex items-center justify-between gap-3 p-3 bg-red-950/90 border border-red-500/40 text-red-200 text-sm rounded-md shadow-lg backdrop-blur",role:"alert",children:[o.jsx("span",{className:"flex-1 break-words",children:n.message}),o.jsx("button",{type:"button",className:"text-red-400 hover:text-red-100 text-base font-bold leading-none px-1",onClick:()=>t(r=>r.filter(a=>a.id!==n.id)),"aria-label":"Close error toast",children:"×"})]},n.id))})}const vY="Enter",wY=229;function NY(e){return e.key===vY&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==wY}const AY=[{name:"/review",description:"Inspect staged git diff, verify test coverage & lint",category:"git",argumentHint:"[target] [--cached]",tags:["builtin","git","review"]},{name:"/commit",description:"Draft conventional commit message from staged hunks",category:"git",argumentHint:"[--all] [-m <message>]",tags:["builtin","git","commit"]},{name:"/compact",description:"Purge execution trace and condense context window",category:"sys",argumentHint:"[focus]",tags:["builtin","sys","compact"]},{name:"/revert",description:"Undo last agent file changes or restore git stash",category:"git",argumentHint:"[stash-id | file]",tags:["builtin","git","revert"]},{name:"/resume",description:"Resume paused background agent run",category:"dev",argumentHint:"[run-id]",tags:["builtin","dev","resume"]},{name:"/terminal",description:"Run isolated bash execution in sandbox mirror",category:"sys",argumentHint:"[command]",tags:["builtin","sys","terminal"]},{name:"/cost",description:"Inspect token breakdown and USD expenditure",category:"sys",tags:["builtin","sys","cost"]},{name:"/sp:dev-plan",description:"Plan a feature from description (intake → AC → tasks)",category:"harness",argumentHint:'"<description>" [--feature <id>]',tags:["sp","dev","plan"]},{name:"/sp:dev-run",description:"Drive one task end-to-end through verification pipeline",category:"harness",argumentHint:"<wbs> [--mode <full|implement>]",tags:["sp","dev","run"]},{name:"/sp:dev-verify",description:"Verify a task against requirements and acceptance criteria",category:"harness",argumentHint:"<wbs> [--bdd] [--auto]",tags:["sp","dev","verify"]}],_Y=[{id:"auto",label:"auto",desc:"Orchestrator auto-dispatch (default)"},{id:"coder",label:"coder",desc:"Implementation & refactoring specialist"},{id:"reviewer",label:"reviewer",desc:"Verification, lint & SECUA reviewer"},{id:"planner",label:"planner",desc:"Architecture & decomposition specialist"}];function kY(e){if(!e)return!0;const{state:t,instanceId:n}=e.orchestrator;return t==="missing"||t==="unresolvable"||!n}function CY({activeModule:e}){const[t,n]=g.useState(!1),[r,a]=g.useState(!1),[s,i]=g.useState(null),[l,u]=g.useState("auto"),[c,d]=g.useState(!1),[p,m]=g.useState(!1),[f,b]=g.useState(0),[x,E]=g.useState("all"),[y,S]=g.useState(AY),v=g.useMemo(()=>{const D=new Map;for(const pe of y){if(Array.isArray(pe.tags)){for(const Ae of pe.tags)if(Ae&&typeof Ae=="string"){const He=Ae.trim().toLowerCase();D.set(He,(D.get(He)??0)+1)}}if(pe.category){const Ae=pe.category.trim().toLowerCase();D.set(Ae,(D.get(Ae)??0)+1)}}const ye=["sp","cc","kk","wt","git","dev","sys","harness","builtin"];return["all",...Array.from(D.keys()).sort((pe,Ae)=>{const He=ye.indexOf(pe),fe=ye.indexOf(Ae);if(He!==-1&&fe!==-1)return He-fe;if(He!==-1)return-1;if(fe!==-1)return 1;const Je=(D.get(Ae)??0)-(D.get(pe)??0);return Je!==0?Je:pe.localeCompare(Ae)})]},[y]),N=Os(),{draft:A,setText:w,persistPending:T,clearSubmitted:_}=Sw(),B=N.fleet?.orchestrator?.instanceId,k=kY(N.fleet),{requests:$,failed:V}=lN(B??null),P=s!==null?$.get(s)??null:null,H=oN(P,N.fleet,r),W=iN[H],L=r||s!==null,te=L?`${W.label} — Next: ${W.action}`:"",ie=g.useRef(null);g.useEffect(()=>{let D=!0;return(async()=>{try{const ye=await ht(new Request(`${Ct()}/agent/commands`));if(ye.ok){const Se=await ye.json();D&&Array.isArray(Se.commands)&&Se.commands.length>0&&S(Se.commands)}}catch{}})(),()=>{D=!1}},[]),g.useEffect(()=>{if(!c)return;const D=ye=>{ie.current&&!ie.current.contains(ye.target)&&d(!1)};return document.addEventListener("click",D),()=>document.removeEventListener("click",D)},[c]),g.useEffect(()=>{A.text.startsWith("/")&&m(!1)},[A.text]);const be=A.text.trim().toLowerCase(),I=be.startsWith("/")&&!p,ne=I?y.filter(D=>{const ye=x==="all"||Array.isArray(D.tags)&&D.tags.map(Ae=>Ae.toLowerCase()).includes(x)||D.category.toLowerCase()===x,Se=be.startsWith("/")?be.slice(1):be,pe=D.name.toLowerCase().startsWith(be)||D.name.toLowerCase().includes(Se)||!!D.argumentHint?.toLowerCase().includes(Se)||D.description.toLowerCase().includes(Se)||Array.isArray(D.tags)&&D.tags.some(Ae=>Ae.toLowerCase().includes(Se));return ye&&pe}):[],ue=I&&ne.length>0,O=D=>{w(`${D} `),m(!0),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},Ne=D=>{const ye=A.text,Se=ye.length>0&&!ye.endsWith(" ")?`${ye} ${D}`:`${ye}${D}`;w(Se),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},de=()=>l==="auto"?B:N.fleet?.members?.find(ye=>ye.role===l||ye.instanceId===l)?.instanceId??B,K=async()=>{const D=N.path,ye=de();if(D===null||ye===void 0||r)return;const Se=A.text;if(Se.trim().length===0)return;const pe={text:Se,refs:A.refs,revision:A.revision},Ae=A.pending!==void 0&&typeof A.pending.requestKey=="string"&&A.pending.requestKey.length>0&&A.pending.revision===A.revision?A.pending:void 0,He=Ae!==void 0?Ae.requestKey:crypto.randomUUID();T(He),a(!0),i(null),m(!0);try{const fe=await ht(new Request(`${Ct()}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({to:ye,from:ku,body:qj(pe.text,pe.refs),requestKey:He,projectPath:D})}));if(!fe.ok)return;const bt=(await fe.json().catch(()=>null))?.msgId;i(typeof bt=="string"?bt:null),_(pe.revision)}catch{}finally{a(!1)}};if(!t)return o.jsxs(o.Fragment,{children:[o.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:te}),o.jsx(ot,{variant:"ghost",className:"fixed bottom-6 right-6 z-30 h-12 w-12 rounded-full backdrop-blur-md bg-base-100/80 border border-spur-border shadow-2xl text-xl text-spur-text",onClick:()=>n(!0),"aria-label":"Open agent prompt bar","aria-expanded":!1,"data-testid":"agent-bar-dock",children:"✨"})]});const Ee=N.fleet?.members&&N.fleet.members.length>0?[{id:"auto",label:"auto",desc:"Orchestrator auto-dispatch (default)"},...N.fleet.members.map(D=>({id:D.instanceId,label:D.role||D.instanceId,desc:`${D.executor}${D.model?` · ${D.model}`:""}`}))]:_Y,re=A.text.trim().length===0||l==="auto"&&k;return o.jsxs("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-30 w-[calc(100vw-2rem)] max-w-[84rem] backdrop-blur-md bg-base-100/80 border border-spur-border shadow-2xl rounded-2xl p-2.5 flex flex-col gap-2 transition-colors","data-testid":"agent-bar",children:[o.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:te}),ue&&o.jsxs("div",{"data-testid":"agent-bar-palette",className:"w-full rounded-2xl bg-base-100/95 border border-spur-border shadow-2xl overflow-hidden flex flex-col backdrop-blur-2xl mb-1 transition-colors",children:[o.jsxs("div",{className:"flex items-center justify-between px-3.5 py-2 border-b border-spur-border bg-base-200/50 text-xs",children:[o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("span",{className:"font-mono text-spur-accent font-semibold text-[13px]",children:"/"}),o.jsx("span",{className:"font-mono text-[12px] font-medium text-spur-text",children:"Commands"}),o.jsxs("span",{className:"text-[11px] font-mono text-spur-text-muted",children:[ne.length," available"]})]}),o.jsx("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar max-w-[65%] py-0.5",role:"tablist",children:v.slice(0,10).map(D=>o.jsx("button",{type:"button",role:"tab","aria-selected":x===D,onClick:()=>E(D),className:`px-2 py-0.5 rounded text-[11px] font-mono transition-colors shrink-0 cursor-pointer ${x===D?"bg-spur-accent/15 text-spur-accent border border-spur-accent/30 font-medium":"text-spur-text-muted hover:text-spur-text hover:bg-base-200"}`,children:D==="all"?"All":D},D))})]}),o.jsx("div",{className:"flex flex-col py-1.5 px-2 max-h-[260px] overflow-y-auto",role:"listbox",children:ne.map((D,ye)=>{const Se=ye===f;return o.jsxs("button",{type:"button",role:"option","aria-selected":Se,onClick:()=>O(D.name),title:D.description,className:`flex items-center w-full text-left px-3 py-2 rounded-lg cursor-pointer transition-colors ${Se?"bg-spur-surface text-spur-accent font-medium":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[o.jsxs("div",{className:"flex items-center gap-2 font-mono text-[13px] min-w-0 truncate flex-1",children:[o.jsx("span",{className:Se?"font-semibold text-spur-accent":"font-medium text-spur-text",children:D.name}),D.argumentHint?o.jsx("span",{className:`font-mono text-xs truncate ${Se?"text-spur-text/80":"text-spur-text-muted"}`,children:D.argumentHint}):o.jsx("span",{className:`font-sans text-xs italic truncate ${Se?"text-spur-text/60":"text-spur-text-muted/60"}`,children:D.description})]}),o.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-2",children:(D.tags&&D.tags.length>0?D.tags.slice(0,2):[D.category]).map(pe=>o.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-base-200 text-spur-text-muted border border-spur-border",children:pe},pe))})]},D.name)})}),o.jsxs("div",{"data-testid":"agent-bar-hints",className:"flex items-center justify-between px-4 py-2 border-t border-spur-border bg-base-200/70 font-mono text-[11px] text-spur-text-muted select-none",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"↑↓"}),o.jsx("span",{children:"navigate"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"Tab"}),o.jsx("span",{children:"complete"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"↵"}),o.jsx("span",{children:"execute"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("kbd",{className:"px-1.5 py-0.5 rounded bg-base-100 border border-spur-border text-spur-text font-semibold text-[10px] shadow-sm",children:"ESC"}),o.jsx("span",{children:"dismiss"})]})]}),o.jsxs("div",{className:"flex items-center gap-3 font-mono text-[11px]",children:[o.jsxs("button",{type:"button",onClick:()=>Ne("@"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Reference files",children:[o.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"@"}),o.jsx("span",{className:"group-hover:text-spur-text",children:"files"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("button",{type:"button",onClick:()=>Ne("#"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Reference tasks and context",children:[o.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"#"}),o.jsx("span",{className:"group-hover:text-spur-text",children:"context"})]}),o.jsx("span",{className:"text-spur-border",children:"•"}),o.jsxs("button",{type:"button",onClick:()=>Ne("!"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Execute shell directly",children:[o.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"!"}),o.jsx("span",{className:"group-hover:text-spur-text",children:"bash"})]})]})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-spur-text-muted font-mono text-sm select-none font-bold pl-1",children:">"}),o.jsxs("div",{className:"relative shrink-0",ref:ie,children:[o.jsxs("button",{type:"button",onClick:()=>d(D=>!D),className:"flex items-center gap-1 px-2.5 py-1 rounded-lg bg-spur-surface hover:bg-base-200 border border-spur-border text-xs font-mono text-spur-accent transition-colors cursor-pointer group",title:"Target Agent Receiver (default: auto dispatch to orchestrator)","data-testid":"agent-bar-role-tag",children:[o.jsx("span",{className:"text-spur-text-muted font-sans text-[11px]",children:"to:"}),o.jsx("span",{className:"font-semibold",children:l}),o.jsx("span",{className:"text-spur-text-muted text-[10px] group-hover:text-spur-text transition-colors",children:"▾"})]}),c&&o.jsxs("div",{"data-testid":"agent-bar-role-menu",className:"absolute bottom-full left-0 mb-2 w-56 rounded-xl bg-base-100 border border-spur-border shadow-2xl p-1.5 z-50 flex flex-col gap-1 text-spur-text",children:[o.jsx("div",{className:"px-2.5 py-1 text-[10px] font-mono text-spur-text-muted uppercase tracking-wider",children:"Dispatch Target"}),Ee.map(D=>o.jsxs("button",{type:"button",onClick:()=>{u(D.label),d(!1)},className:`flex items-center justify-between px-2.5 py-1.5 rounded-lg text-left text-xs font-mono transition-colors ${l===D.label?"bg-spur-accent/15 text-spur-accent font-semibold":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"font-medium text-spur-text",children:D.label}),o.jsx("span",{className:"text-[10px] text-spur-text-muted",children:D.desc})]}),l===D.label&&o.jsx("span",{className:"text-[12px]",children:"✓"})]},D.id))]})]}),o.jsx(zj,{variant:"ghost",rows:1,value:A.text,onChange:D=>w(D.target.value),onKeyDown:D=>{if(ue&&ne.length>0){if(D.key==="ArrowDown"){D.preventDefault(),b(ye=>(ye+1)%ne.length);return}if(D.key==="ArrowUp"){D.preventDefault(),b(ye=>(ye-1+ne.length)%ne.length);return}if(D.key==="Tab"){D.preventDefault();const ye=ne[f];ye&&O(ye.name);return}if(D.key==="Escape"){D.preventDefault(),m(!0);return}}NY(D)&&(re||(D.preventDefault(),K()))},placeholder:"Ask a coding agent to refine or implement, or type / for commands…","aria-label":"Agent prompt",className:"flex-1 min-h-9 resize-none bg-transparent text-spur-text placeholder:text-spur-text-muted border-0 focus:ring-0 focus:outline-none","data-testid":"agent-bar-input"}),o.jsx(ot,{variant:"ghost",size:"sm",onClick:()=>n(!1),"aria-label":"Collapse agent prompt bar","aria-expanded":!0,className:"text-spur-text-muted hover:text-spur-text h-8 w-8 p-0 shrink-0",children:"▾"})]}),l==="auto"&&k&&o.jsx("div",{"data-testid":"agent-bar-orchestrator-missing",role:"status",className:"px-1 text-xs text-spur-text-muted",children:"Orchestrator unavailable — no orchestrator instance is bound to this project, so requests cannot be delivered yet."}),L&&o.jsxs("div",{"data-receipt-state":H,role:"status",className:`rounded-lg px-2.5 py-1 text-xs ${W.tone==="err"?"bg-spur-error/10 text-spur-error":W.tone==="warn"?"bg-spur-warning/10 text-spur-warning":"bg-spur-success/10 text-spur-success"}`,children:[o.jsx("span",{"aria-hidden":"true",className:"mr-1",children:W.icon}),o.jsx("span",{className:"font-medium",children:W.label}),o.jsxs("span",{className:"text-spur-text-muted",children:[" ","— ",W.meaning," Next: ",W.action,"."]}),V&&o.jsx("span",{className:"text-spur-text-muted",children:" (results feed unavailable)"})]})]})}function IY({name:e}){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;const n=Math.abs(t)%8,a=["text-emerald-400 bg-emerald-500/10 border-emerald-500/30","text-sky-400 bg-sky-500/10 border-sky-500/30","text-indigo-400 bg-indigo-500/10 border-indigo-500/30","text-amber-400 bg-amber-500/10 border-amber-500/30","text-rose-400 bg-rose-500/10 border-rose-500/30","text-purple-400 bg-purple-500/10 border-purple-500/30","text-teal-400 bg-teal-500/10 border-teal-500/30","text-cyan-400 bg-cyan-500/10 border-cyan-500/30"][n],s=()=>{switch(n){case 0:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M8 1.5l5.5 3.2v6.6L8 14.5l-5.5-3.2V4.7L8 1.5z"}),o.jsx("path",{d:"M8 1.5v13M2.5 4.7l5.5 3.3 5.5-3.3"})]});case 1:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("rect",{x:"2",y:"2.5",width:"12",height:"11",rx:"2"}),o.jsx("path",{d:"M5 6l2.5 2L5 10M8.5 10H11"})]});case 2:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("circle",{cx:"4.5",cy:"4",r:"1.5"}),o.jsx("circle",{cx:"4.5",cy:"12",r:"1.5"}),o.jsx("circle",{cx:"11.5",cy:"7",r:"1.5"}),o.jsx("path",{d:"M4.5 5.5v5M4.5 7.5a4 4 0 004-1"})]});case 3:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M8 2l5.5 3-5.5 3-5.5-3L8 2z"}),o.jsx("path",{d:"M2.5 8l5.5 3 5.5-3M2.5 11l5.5 3 5.5-3"})]});case 4:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1.5"}),o.jsx("path",{d:"M6 1.5v2M10 1.5v2M6 12.5v2M10 12.5v2M1.5 6h2M1.5 10h2M12.5 6h2M12.5 10h2"})]});case 5:return o.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M5.5 4.5L2 8l3.5 3.5M10.5 4.5L14 8l-3.5 3.5M9 3l-2 10"})});case 6:return o.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M2 4a1.5 1.5 0 011.5-1.5h2.8a1.5 1.5 0 011.06.44l1.14 1.14c.28.28.66.42 1.06.42H12.5A1.5 1.5 0 0114 6v6a1.5 1.5 0 01-1.5 1.5h-9A1.5 1.5 0 012 12V4z"})});default:return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("circle",{cx:"8",cy:"8",r:"6"}),o.jsx("path",{d:"M2 8h12M8 2a9 9 0 010 12 9 9 0 010-12z"})]})}};return o.jsx("span",{"data-testid":"project-avatar-icon",className:`flex h-7 w-7 items-center justify-center rounded border ${a}`,children:s()})}function o1({currentName:e,collapsed:t=!1}){const[n,r]=g.useState(!1),[a,s]=g.useState([]),[i,l]=g.useState(null),[u,c]=g.useState(null),d=g.useRef(null);g.useEffect(()=>{if(!n)return;const f=new AbortController;return ht(new Request(`${Ct()}/projects`,{signal:f.signal})).then(async b=>{if(!b.ok)return;const x=await b.json();s(x.projects??[])}).catch(()=>{c("Failed to load projects")}),()=>f.abort()},[n]),g.useEffect(()=>{if(!n)return;const f=x=>{x.key==="Escape"&&r(!1)},b=x=>{d.current&&!d.current.contains(x.target)&&r(!1)};return document.addEventListener("keydown",f),document.addEventListener("mousedown",b),()=>{document.removeEventListener("keydown",f),document.removeEventListener("mousedown",b)}},[n]);const p=async f=>{if(f.current){r(!1);return}if(f.running&&f.port>0){window.location.href=`http://localhost:${f.port}/board`;return}l(f.name);try{const b=await ht(new Request(`${Ct()}/projects/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:f.name,path:f.path})}));if(!b.ok)throw new Error("Failed to start project");const x=await b.json();window.location.href=x.url||`http://localhost:${x.port}/board`}catch(b){c(b instanceof Error?b.message:"Start failed"),l(null)}},m=o.jsxs("button",{type:"button",onClick:()=>r(f=>!f),"aria-haspopup":"listbox","aria-expanded":n,"aria-label":`Switch project: ${e}`,title:e,"data-testid":"project-switcher-trigger",className:"group relative flex h-8 w-8 items-center justify-center rounded-md hover:bg-spur-accent/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-spur-accent",children:[o.jsx("span",{className:`items-center justify-center ${n?"hidden":"flex group-hover:hidden"}`,children:o.jsx(IY,{name:e})}),o.jsx("span",{"data-testid":"project-switcher-chevron",className:`h-7 w-7 items-center justify-center rounded text-spur-text ${n?"flex":"hidden group-hover:flex"}`,children:o.jsx("svg",{className:`h-4 w-4 shrink-0 transition-transform ${n?"rotate-180 text-spur-accent":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M4 6l4 4 4-4"})})})]});return o.jsxs("div",{className:`relative ${t?"flex items-center justify-center":"min-w-0 flex-1"}`,ref:d,children:[t?n?m:o.jsx(vb,{position:"right",tip:`Switch project: ${e}`,className:"block",children:m}):o.jsxs("button",{type:"button",onClick:()=>r(f=>!f),"aria-haspopup":"listbox","aria-expanded":n,"aria-label":"Switch project",title:e,"data-testid":"project-switcher-trigger",className:"flex w-full items-center justify-between gap-1 rounded-md px-1.5 py-1 text-left text-sm font-semibold text-spur-text hover:bg-spur-border/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-spur-accent",children:[o.jsx("span",{className:"font-semibold truncate",children:e}),o.jsx("svg",{className:`h-4 w-4 shrink-0 transition-transform ${n?"rotate-180":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M4 6l4 4 4-4"})})]}),n&&o.jsxs("div",{role:"listbox","aria-label":"Registered projects","data-testid":"project-switcher-menu",className:`absolute z-50 w-64 rounded-md border border-spur-border bg-spur-surface p-1 shadow-lg ${t?"left-full top-0 ml-2":"left-0 top-full mt-1"}`,children:[o.jsx("div",{className:"px-2 py-1 text-xs font-medium text-spur-text-muted border-b border-spur-border/50 mb-1",children:"Projects"}),a.length===0?o.jsx("div",{className:"px-2 py-1.5 text-xs text-spur-text-muted",children:u||"No projects registered"}):a.map(f=>o.jsxs("button",{type:"button",role:"option","aria-selected":f.current,disabled:i===f.name,onClick:()=>p(f),"data-testid":`project-item-${f.name}`,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-xs text-left transition-colors ${f.current?"bg-spur-accent/15 text-spur-accent font-medium":"text-spur-text hover:bg-spur-border/30"}`,children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ${f.running?"bg-green-500":"bg-gray-400"}`,title:f.running?`Running on port ${f.port}`:"Stopped"}),o.jsx("span",{className:"truncate",children:f.name})]}),i===f.name?o.jsx("span",{className:"text-[10px] text-spur-accent animate-pulse",children:"Starting..."}):f.current?o.jsx("span",{className:"text-[10px] font-semibold text-spur-accent",children:"current"}):f.running?o.jsxs("span",{className:"text-[10px] text-spur-text-muted",children:[":",f.port]}):o.jsx("span",{className:"text-[10px] text-spur-text-muted",children:"stopped"})]},f.path))]})]})}function RY({open:e,onClose:t}){if(!e)return null;const n=o.jsxs(jj,{open:e,onClose:t,"aria-labelledby":"settings-modal-title",children:[o.jsxs("div",{className:"flex items-center justify-between pb-3 border-b border-spur-border",children:[o.jsx("h3",{id:"settings-modal-title",className:"text-base font-semibold text-spur-text",children:"Settings"}),o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text-muted hover:text-spur-text",onClick:t,"aria-label":"Close settings",children:"✕"})]}),o.jsx("div",{className:"py-6 text-sm text-spur-text-muted",children:"Settings configuration and workspace preferences will be available in a future release."})]});return typeof document<"u"?na.createPortal(n,document.body):n}const FN="spur-theme";function DY(){try{const e=localStorage.getItem(FN);if(e==="light"||e==="dark")return e}catch{}return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function OY(e){document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(FN,e)}catch{}}function LY(e){const t=e==="dark"?"light":"dark";return OY(t),t}function l1(){const[e,t]=g.useState(DY);g.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),a=s=>{if(!(()=>{try{return localStorage.getItem("spur-theme")}catch{return null}})()){const l=s.matches?"dark":"light";t(l),document.documentElement.setAttribute("data-theme",l)}};return r.addEventListener("change",a),()=>r.removeEventListener("change",a)},[]);const n=g.useCallback(()=>t(LY),[]);return o.jsx(ot,{variant:"ghost",size:"sm",onClick:n,className:"text-spur-text-muted","aria-label":e==="dark"?"Switch to light mode":"Switch to dark mode",children:e==="dark"?"☀️":"🌙"})}const MY="Modules";function FY(){const[e,t]=g.useState(MY);return g.useEffect(()=>{const n=new AbortController;return ht(new Request(`${Ct()}/project`,{signal:n.signal})).then(async r=>{if(!r.ok)return;const a=await r.json();a.name&&t(a.name)}).catch(()=>{}),()=>n.abort()},[]),e}function jY({direction:e}){const t=e==="expand";return o.jsxs("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"}),o.jsx("line",{x1:"6",y1:"2",x2:"6",y2:"14"}),t?o.jsx("path",{d:"M9 6l2 2-2 2"}):o.jsx("path",{d:"M11 6l-2 2 2 2"})]})}function u1({collapsed:e,onToggle:t}){const n=e?"Expand sidebar":"Collapse sidebar";return o.jsx("button",{type:"button",onClick:t,"aria-label":n,title:n,"data-testid":e?"sidebar-expand":"sidebar-collapse",className:"flex h-8 w-8 items-center justify-center rounded-md text-spur-text-muted hover:bg-spur-accent/20 hover:text-spur-accent focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-spur-accent",children:o.jsx(jY,{direction:e?"expand":"collapse"})})}function c1({onClick:e}){return o.jsx("button",{type:"button",onClick:e,"aria-label":"Open settings",title:"Open settings","data-testid":"sidebar-settings",className:"flex h-8 w-8 items-center justify-center rounded-md text-spur-text-muted hover:bg-spur-accent/20 hover:text-spur-accent focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-spur-accent",children:o.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:o.jsx("path",{fillRule:"evenodd",d:"M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z",clipRule:"evenodd"})})})}function PY({collapsed:e,onToggle:t,onMobileClose:n}){const r=FY(),[a,s]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs("aside",{className:`flex flex-col bg-spur-surface border-r border-spur-border ${e?"overflow-visible":"overflow-hidden"}`,children:[e?o.jsx("div",{className:"flex items-center justify-center border-b border-spur-border shrink-0 py-2",children:o.jsx(o1,{currentName:r,collapsed:!0})}):o.jsxs("div",{className:"flex items-center justify-between gap-1 p-3 border-b border-spur-border shrink-0",children:[o.jsx(o1,{currentName:r}),n&&o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text-muted md:hidden",onClick:n,"aria-label":"Close navigation",children:"✕"})]}),o.jsx("nav",{className:`flex-1 ${e?"overflow-visible":"overflow-y-auto"}`,children:MN.map(i=>{const l=i.sidebarLabel??i.name,u=o.jsxs($1,{to:`/board/${i.route}`,className:({isActive:c})=>`flex items-center gap-2 px-3 py-2 text-sm transition-colors ${c?"bg-spur-accent/20 text-spur-accent":"text-spur-text-muted hover:text-spur-text hover:bg-spur-border/30"} ${e?"justify-center py-3":""}`,children:[o.jsx("span",{className:"text-lg",children:i.icon}),!e&&o.jsx("span",{children:l})]},i.id);if(e){const c=i.description?`${l}
188
188
  ${i.description}`:l;return o.jsx(vb,{position:"right",tip:c,className:"[&:before]:whitespace-pre-line block",children:u},i.id)}return u})}),o.jsx("div",{"data-testid":"sidebar-footer",className:`border-t border-spur-border shrink-0 ${e?"py-2 flex flex-col items-center gap-2":"p-3 flex items-center justify-between gap-2"}`,children:e?o.jsxs(o.Fragment,{children:[o.jsx(l1,{}),o.jsx(c1,{onClick:()=>s(!0)}),o.jsx(u1,{collapsed:!0,onToggle:t})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(l1,{}),o.jsx(c1,{onClick:()=>s(!0)})]}),o.jsx(u1,{collapsed:!1,onToggle:t})]})})]}),o.jsx(RY,{open:a,onClose:()=>s(!1)})]})}function BY({children:e,mobileHeader:t}){return o.jsxs("main",{className:"flex flex-col h-full overflow-hidden bg-spur-bg",children:[t,o.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:e})]})}function UY({collapsed:e,onToggle:t,onMobileClose:n,children:r,actions:a}){return o.jsxs("aside",{className:"flex flex-col bg-spur-surface border-l border-spur-border overflow-hidden",children:[n&&o.jsx("div",{className:"hidden max-md:flex items-center justify-center py-2 shrink-0",children:o.jsx("div",{className:"w-10 h-1 rounded-full bg-spur-border"})}),o.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-spur-border shrink-0",children:[!e&&o.jsx("span",{className:"text-sm font-semibold text-spur-text",children:r?"Context":""}),o.jsx("div",{className:"flex items-center gap-1",children:a}),o.jsxs("div",{className:"flex items-center gap-1",children:[n&&o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text-muted md:hidden",onClick:n,"aria-label":"Close panel",children:"✕"}),o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text-muted hidden md:inline-flex",onClick:t,"aria-label":e?"Expand panel":"Collapse panel",children:e?"◀":"▶"})]})]}),!e&&o.jsx("div",{className:"flex-1 overflow-y-auto p-3",children:r})]})}const $Y=g.createContext(void 0);function zY(){const[e,t]=g.useState(()=>Gj()),[n,r]=g.useState(!1),[a,s]=g.useState(!1),i=Zn(),l=(()=>{const S=i.pathname.split("/"),v=S.indexOf("board"),N=v>=0?S[v+1]:void 0;return TY(N??"")})();g.useLayoutEffect(()=>{const S=document.documentElement;S.style.setProperty("--sidebar-w",`${e.sidebarWidth}px`),S.style.setProperty("--rightpanel-w",`${e.rightPanelWidth}px`)},[e.sidebarWidth,e.rightPanelWidth]);const u=g.useCallback(S=>Wj(S),[]),c=g.useCallback(()=>{t(S=>{const v={...S,sidebarCollapsed:!S.sidebarCollapsed};return u(v),v})},[u]),d=g.useCallback(()=>{t(S=>{const v={...S,rightPanelCollapsed:!S.rightPanelCollapsed};return u(v),v})},[u]),p=g.useCallback(S=>t(v=>{const N={...v,sidebarWidth:S};return u(N),N}),[u]),m=g.useCallback(S=>t(v=>{const N={...v,rightPanelWidth:S};return u(N),N}),[u]),f=g.useCallback(()=>{r(!1),s(!1)},[]),b=g.useCallback(S=>{S.key==="Escape"&&f()},[f]),x=l?.rightPanelComponent;g.useLayoutEffect(()=>{x&&e.rightPanelCollapsed&&t(S=>({...S,rightPanelCollapsed:!1}))},[x,e.rightPanelCollapsed]);const E=o.jsxs("div",{className:"mobile-bar",children:[o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text",onClick:()=>r(!0),"aria-label":"Open navigation",children:"☰"}),o.jsx("span",{className:"text-sm font-semibold text-spur-text",children:l?.name??"Spur"}),o.jsx(ot,{variant:"ghost",size:"sm",className:"text-spur-text",onClick:()=>s(!0),"aria-label":"Open panel",children:"◧"})]}),y=n||a;return o.jsx(Fz,{children:o.jsxs($z,{children:[y&&o.jsx("div",{className:"fixed inset-0 z-40 bg-black/50 md:hidden",onClick:f,onKeyDown:b,"aria-hidden":"true"}),o.jsx("div",{className:"board-layout","data-sidebar-collapsed":String(e.sidebarCollapsed),"data-rightpanel-collapsed":String(e.rightPanelCollapsed),"data-mobile-sidebar-open":String(n),"data-mobile-panel-open":String(a),children:o.jsxs($Y.Provider,{value:l,children:[o.jsx(PY,{collapsed:e.sidebarCollapsed&&!n,onToggle:c,onMobileClose:f}),o.jsx(Dl,{targetVar:"--sidebar-w",onResizeEnd:p}),o.jsx(BY,{mobileHeader:E,children:o.jsx(D_,{})}),o.jsx(Dl,{targetVar:"--rightpanel-w",onResizeEnd:m}),o.jsx(UY,{collapsed:e.rightPanelCollapsed,onToggle:d,onMobileClose:f,children:x?o.jsx(x,{}):null})]})}),o.jsx(CY,{activeModule:l}),o.jsx(SY,{})]})})}const HY=[{from:"workspace",to:"/board/projects"},{from:"inbox",to:"/board/projects/conversation"},{from:"teams",to:"/board/projects/agents"}],GY=[{path:"/board",element:o.jsx(zY,{}),children:[{index:!0,element:o.jsx(yo,{to:Xo?Xo.route:"/board",replace:!0})},...HY.flatMap(e=>[{path:e.from,element:o.jsx(yo,{to:e.to,replace:!0})},{path:`${e.from}/*`,element:o.jsx(yo,{to:e.to,replace:!0})}]),...MN.flatMap(e=>[{path:e.route,element:o.jsx(e.component,{})},{path:`${e.route}/*`,element:o.jsx(e.component,{})}])]},{path:"/",element:o.jsx(yo,{to:Xo?`/board/${Xo.route}`:"/board",replace:!0})}];function WY(){return ak(GY)}function VY(){const[e]=g.useState(WY);return o.jsx(C_,{router:e})}export{ot as B,Sb as C,Fa as L,Nl as M,xi as S,ww as _,rn as a,gn as b,FH as c,VY as d,o as j,DH as p,Mb as t,jb as u};