@gobing-ai/spur 0.4.27 → 0.4.29

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 (62) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/config/workflows/task-pipeline.yaml +63 -4
  3. package/package.json +1 -1
  4. package/plugins/sp/plugin.json +1 -1
  5. package/plugins/sp/skills/code-implementation/SKILL.md +6 -0
  6. package/plugins/sp/skills/code-testing/SKILL.md +7 -0
  7. package/plugins/sp/skills/spur-dev/references/cross-cutting.md +2 -2
  8. package/plugins/sp/skills/spur-dev/references/execution-parallel-isolation.md +2 -2
  9. package/plugins/sp/skills/spur-dev/references/execution-workflow.md +11 -0
  10. package/plugins/sp/skills/spur-dev/references/execution-worktree-landing.md +10 -6
  11. package/plugins/sp/skills/spur-dev/references/execution-worktree-setup.md +15 -0
  12. package/spur.js +633 -137
  13. package/web/_astro/{BoardApp.H0GHCpML.js → BoardApp.BGGDrfHl.js} +4 -4
  14. package/web/_astro/{BoardApp.BpVPF1yi.js → BoardApp.CuCuw0lw.js} +1 -1
  15. package/web/_astro/{TaskDetail.C3fD4iNx.js → TaskDetail.DWXct9_X.js} +1 -1
  16. package/web/_astro/{arc.CwmuZ1Pw.js → arc.BxG3NS1o.js} +1 -1
  17. package/web/_astro/{architectureDiagram-3BPJPVTR.D2r2pAtD.js → architectureDiagram-3BPJPVTR.BxaiM2Hv.js} +1 -1
  18. package/web/_astro/{blockDiagram-GPEHLZMM.LRgyDihu.js → blockDiagram-GPEHLZMM.DJ3r6SdD.js} +1 -1
  19. package/web/_astro/{c4Diagram-AAUBKEIU.OscV13G7.js → c4Diagram-AAUBKEIU.BkzpXBQs.js} +1 -1
  20. package/web/_astro/channel.CYWRkoDI.js +1 -0
  21. package/web/_astro/{chunk-2J33WTMH.BcbENXnC.js → chunk-2J33WTMH.DI7UanTc.js} +1 -1
  22. package/web/_astro/{chunk-4BX2VUAB.CcRidR01.js → chunk-4BX2VUAB.C2uLhAlQ.js} +1 -1
  23. package/web/_astro/{chunk-55IACEB6.DxAFaIIp.js → chunk-55IACEB6.KwNI2kxL.js} +1 -1
  24. package/web/_astro/{chunk-727SXJPM.Cjvuc3en.js → chunk-727SXJPM.CHZUthkg.js} +1 -1
  25. package/web/_astro/{chunk-AQP2D5EJ.B3GSEPXo.js → chunk-AQP2D5EJ.DLr4QNJo.js} +1 -1
  26. package/web/_astro/{chunk-FMBD7UC4.DbpwRXpL.js → chunk-FMBD7UC4.B1G8WrnE.js} +1 -1
  27. package/web/_astro/{chunk-ND2GUHAM.CdiLgZ9z.js → chunk-ND2GUHAM.CzsA-SkD.js} +1 -1
  28. package/web/_astro/{chunk-QZHKN3VN.DT_2ovxF.js → chunk-QZHKN3VN.DAvBQYli.js} +1 -1
  29. package/web/_astro/{classDiagram-4FO5ZUOK.B4Y_Byb0.js → classDiagram-4FO5ZUOK.Cddmz8Ze.js} +1 -1
  30. package/web/_astro/{classDiagram-v2-Q7XG4LA2.B4Y_Byb0.js → classDiagram-v2-Q7XG4LA2.Cddmz8Ze.js} +1 -1
  31. package/web/_astro/{cose-bilkent-S5V4N54A.0UOSbCRW.js → cose-bilkent-S5V4N54A.CKEu7KRX.js} +1 -1
  32. package/web/_astro/{cynefin-OW5HDTMX.iaVw7KUy.js → cynefin-OW5HDTMX.-B4Cy_Vl.js} +1 -1
  33. package/web/_astro/{dagre-BM42HDAG.DzBLfYbl.js → dagre-BM42HDAG.bLxFvI-t.js} +1 -1
  34. package/web/_astro/{diagram-2AECGRRQ.CtoO_RXO.js → diagram-2AECGRRQ.DAHU0t5h.js} +1 -1
  35. package/web/_astro/{diagram-5GNKFQAL.C1ah--0o.js → diagram-5GNKFQAL.DFciwCNk.js} +1 -1
  36. package/web/_astro/{diagram-KO2AKTUF.DAawwAoM.js → diagram-KO2AKTUF.BvH0dGId.js} +1 -1
  37. package/web/_astro/{diagram-LMA3HP47.kC7Zg0ru.js → diagram-LMA3HP47.BgVlskRO.js} +1 -1
  38. package/web/_astro/{diagram-OG6HWLK6.B3dSXJ9m.js → diagram-OG6HWLK6.BpurMISo.js} +1 -1
  39. package/web/_astro/{erDiagram-TEJ5UH35.cVJXYJkv.js → erDiagram-TEJ5UH35.SDj5bUMU.js} +1 -1
  40. package/web/_astro/{flowDiagram-I6XJVG4X.CwD6KgFD.js → flowDiagram-I6XJVG4X.Bm5U58FE.js} +1 -1
  41. package/web/_astro/{ganttDiagram-6RSMTGT7.UB88xr_u.js → ganttDiagram-6RSMTGT7.CnMnds77.js} +1 -1
  42. package/web/_astro/{gitGraphDiagram-PVQCEYII.C4B3FNOY.js → gitGraphDiagram-PVQCEYII.BQUwwyWo.js} +1 -1
  43. package/web/_astro/{infoDiagram-5YYISTIA.6QC564C4.js → infoDiagram-5YYISTIA.BiSKdORH.js} +1 -1
  44. package/web/_astro/{ishikawaDiagram-YF4QCWOH.sQBtM0gc.js → ishikawaDiagram-YF4QCWOH.Br69sBTI.js} +1 -1
  45. package/web/_astro/{journeyDiagram-JHISSGLW.Dslglgu2.js → journeyDiagram-JHISSGLW.C39WX1W8.js} +1 -1
  46. package/web/_astro/{kanban-definition-UN3LZRKU.CPKaPyzi.js → kanban-definition-UN3LZRKU.DppWcbSX.js} +1 -1
  47. package/web/_astro/{linear.DNHY6BCF.js → linear.DeivTDuc.js} +1 -1
  48. package/web/_astro/{mermaid.core.VoW0rvGv.js → mermaid.core.Dixrjrnj.js} +4 -4
  49. package/web/_astro/{mindmap-definition-RKZ34NQL.jYZ-jCh7.js → mindmap-definition-RKZ34NQL.BWIQ2MWG.js} +1 -1
  50. package/web/_astro/{pieDiagram-4H26LBE5.DQ0fapSh.js → pieDiagram-4H26LBE5.vvtHpfT7.js} +1 -1
  51. package/web/_astro/{quadrantDiagram-W4KKPZXB.CWF406ut.js → quadrantDiagram-W4KKPZXB.9c-T6qCy.js} +1 -1
  52. package/web/_astro/{requirementDiagram-4Y6WPE33.BmUiiY0p.js → requirementDiagram-4Y6WPE33.9ZuRw-kn.js} +1 -1
  53. package/web/_astro/{sankeyDiagram-5OEKKPKP.CzUeGGUK.js → sankeyDiagram-5OEKKPKP.CTIWteEl.js} +1 -1
  54. package/web/_astro/{sequenceDiagram-3UESZ5HK.DKvkUeEk.js → sequenceDiagram-3UESZ5HK.DEvu4vLL.js} +1 -1
  55. package/web/_astro/{stateDiagram-AJRCARHV.ByedXnFB.js → stateDiagram-AJRCARHV.Bxvsgk-_.js} +1 -1
  56. package/web/_astro/{stateDiagram-v2-BHNVJYJU.Bx7wyAlv.js → stateDiagram-v2-BHNVJYJU.CVuog5yY.js} +1 -1
  57. package/web/_astro/{timeline-definition-PNZ67QCA.Chzu_dUX.js → timeline-definition-PNZ67QCA.CpPItB3E.js} +1 -1
  58. package/web/_astro/{vennDiagram-CIIHVFJN.PuxG68DI.js → vennDiagram-CIIHVFJN.C7eKaLRK.js} +1 -1
  59. package/web/_astro/{wardleyDiagram-YWT4CUSO.C9ZKxfsC.js → wardleyDiagram-YWT4CUSO.DWXHT_CW.js} +1 -1
  60. package/web/_astro/{xychartDiagram-2RQKCTM6.B7qR-3HU.js → xychartDiagram-2RQKCTM6.DOsrNQOF.js} +1 -1
  61. package/web/index.html +1 -1
  62. package/web/_astro/channel.OpZyofHt.js +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/mermaid.core.VoW0rvGv.js","_astro/_commonjsHelpers.CqkleIqs.js","_astro/TaskDetail.C3fD4iNx.js","_astro/jsx-runtime.DWOiEOII.js","_astro/index.5dn-Zm-2.js","_astro/index.tZfqwSut.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["_astro/mermaid.core.Dixrjrnj.js","_astro/_commonjsHelpers.CqkleIqs.js","_astro/TaskDetail.DWXct9_X.js","_astro/jsx-runtime.DWOiEOII.js","_astro/index.5dn-Zm-2.js","_astro/index.tZfqwSut.js"])))=>i.map(i=>d[i]);
2
2
  import{j as a}from"./jsx-runtime.DWOiEOII.js";import{r as h,R as st}from"./index.5dn-Zm-2.js";import{aQ as Ca,aF as mc,L as gl,aC as Ji,N as MS,O as bC,e as _o,a2 as xC,i as yC}from"./chunk-JMJ3UQ3L.BQJEJHu4.js";import{g as hc}from"./_commonjsHelpers.CqkleIqs.js";import{r as Ur}from"./index.Cyc_GA4f.js";function EC(e){return e[0]??{}}function Dl(e){return Array.isArray(e)?e:e==null?[]:[e]}const S0="orpc",SC="@orpc/shared",wC="1.14.4";class vC extends Error{constructor(...t){super(...t),this.name="AbortError"}}function NC(e){let t;return()=>{if(t)return t.result;const n=e();return t={result:n},n}}function TC(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}const kC=2,AC=`__${SC}@${wC}/otel/config__`;function gc(){return globalThis[AC]}function Hp(e,t={},n){return gc()?.tracer?.startSpan(e,t,n)}function xs(e,t,n={}){if(!e)return;const r=CC(t);e.recordException(r),(!n.signal?.aborted||n.signal.reason!==t)&&e.setStatus({code:kC,message:r.message})}function CC(e){if(e instanceof Error){const t={message:e.message,name:e.name,stack:e.stack};return"code"in e&&(typeof e.code=="string"||typeof e.code=="number")&&(t.code=e.code),t}return{message:String(e)}}async function ui({name:e,context:t,...n},r){const s=gc()?.tracer;if(!s)return r();const i=async o=>{try{return await r(o)}catch(l){throw xs(o,l,n),l}finally{o.end()}};return t?s.startActiveSpan(e,n,t,i):s.startActiveSpan(e,n,i)}async function ga(e,t){const n=gc();if(!e||!n)return t();const r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function Li(e){return!e||typeof e!="object"?!1:"next"in e&&typeof e.next=="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]=="function"}const _C=Symbol.for("asyncDispose"),IC=Symbol.asyncDispose??_C;class Gp{#e=!1;#t=!1;#n;#r;constructor(t,n){this.#n=n,this.#r=TC(async()=>{if(this.#e)return{done:!0,value:void 0};try{const r=await t();return r.done&&(this.#e=!0),r}catch(r){throw this.#e=!0,r}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n("next"))}})}next(){return this.#r()}async return(t){return this.#e=!0,this.#t||(this.#t=!0,await this.#n("return")),{done:!0,value:t}}async throw(t){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n("throw")),t}async[IC](){this.#e=!0,this.#t||(this.#t=!0,await this.#n("dispose"))}[Symbol.asyncIterator](){return this}}function w0({name:e,...t},n){let r;return new Gp(async()=>{r??=Hp(e);try{const s=await ga(r,()=>n.next());return r?.addEvent(s.done?"completed":"yielded"),s}catch(s){throw xs(r,s,t),s}},async s=>{try{s!=="next"&&await ga(r,()=>n.return?.())}catch(i){throw xs(r,i,t),i}finally{r?.end()}})}function RC(e){return async(t,...n)=>{try{return await t.next()}catch(r){throw await e(r,t,...n),r}}}function Fd(e,t,n){const r=(s,i)=>{const o=e[i];return o?o({...s,next:(l=s)=>r(l,i+1)}):n(s)};return r(t,0)}function bl(e){if(e)return JSON.parse(e)}function Pd(e){return JSON.stringify(e)}function DC(e){return ys(e)?Object.getPrototypeOf(e)?.constructor:null}function zr(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function ys(e){return!!e&&(typeof e=="object"||typeof e=="function")}function v0(e,t){let n=e;for(const r of t){if(!ys(n))return;n=n[r]}return n}const FS=(()=>{const e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function N0(e,...t){return typeof e=="function"?e(...t):e}function PS(e){return new Proxy(e,{get(t,n,r){const s=Reflect.get(t,n,r);return n!=="then"||typeof s!="function"?s:new Proxy(s,{apply(i,o,l){if(l.length!==2||l.some(u=>!LC(u)))return Reflect.apply(i,o,l);let c=!0;l[0].call(o,PS(new Proxy(t,{get:(u,d,p)=>{if(c&&d==="then"){c=!1;return}return Reflect.get(u,d,p)}})))}})}})}const OC=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function LC(e){return typeof e=="function"&&OC.test(e.toString())}function jC(e){try{return decodeURIComponent(e)}catch{return e}}const MC="@orpc/client",FC="1.14.4",Wp={BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_SUPPORTED:{status:405,message:"Method Not Supported"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},UNPROCESSABLE_CONTENT:{status:422,message:"Unprocessable Content"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},CLIENT_CLOSED_REQUEST:{status:499,message:"Client Closed Request"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"}};function PC(e,t){return t??Wp[e]?.status??500}function BC(e,t){return t||Wp[e]?.message||e}const BS=Symbol.for(`__${MC}@${FC}/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[BS]??=new WeakSet;const Bd=globalThis[BS];class ba extends Error{defined;code;status;data;constructor(t,...n){const r=EC(n);if(r.status!==void 0&&!ji(r.status))throw new Error("[ORPCError] Invalid error status code.");const s=BC(t,r.message);super(s,r),this.code=t,this.status=PC(t,r.status),this.defined=r.defined??!1,this.data=r.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](t){if(Bd.has(this)){const n=DC(t);if(n&&Bd.has(n))return!0}return super[Symbol.hasInstance](t)}}Bd.add(ba);function $C(e){return e instanceof ba?e:new ba("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:e})}function ji(e){return e<200||e>=400}function $S(e){if(!zr(e))return!1;const t=["defined","code","status","message","data"];return Object.keys(e).some(n=>!t.includes(n))?!1:"defined"in e&&typeof e.defined=="boolean"&&"code"in e&&typeof e.code=="string"&&"status"in e&&typeof e.status=="number"&&ji(e.status)&&"message"in e&&typeof e.message=="string"}function US(e,t={}){return new ba(e.code,{...t,...e})}class bc extends TypeError{}class UC extends TypeError{}class Mi extends Error{data;constructor(t){super(t?.message??"An error event was received",t),this.data=t?.data}}function zC(e){const t=e.replace(/\n+$/,"").split(/\n/),n={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(const r of t){const s=r.indexOf(":"),i=s===-1?r:r.slice(0,s),o=s===-1?"":r.slice(s+1).replace(/^\s/,"");if(s===0)n.comments.push(o);else if(i==="data")n.data??="",n.data+=`${o}
3
3
  `;else if(i==="event")n.event=o;else if(i==="id")n.id=o;else if(i==="retry"){const l=Number.parseInt(o);Number.isInteger(l)&&l>=0&&l.toString()===o&&(n.retry=l)}}return n.data=n.data?.replace(/\n$/,""),n}class HC{constructor(t={}){this.options=t}incomplete="";feed(t){this.incomplete+=t;const n=this.incomplete.lastIndexOf(`
4
4
 
@@ -294,7 +294,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
294
294
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
295
295
  `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const n=Jo(t),r=zs(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const n=Jo(t),r=zs(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function BW(e){const t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new FW||null,prettyErrors:t}}function $W(e,t={}){const{lineCounter:n,prettyErrors:r}=BW(t),s=new PW(n?.addNewLine),i=new DW(t);let o=null;for(const l of i.compose(s.parse(e),!0,e.length))if(!o)o=l;else if(o.options.logLevel!=="silent"){o.errors.push(new mi(l.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(s1(e,n)),o.warnings.forEach(s1(e,n))),o}function UW(e,t,n){let r;const s=$W(e,n);if(!s)return null;if(s.warnings.forEach(i=>qT(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}const Sk=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;function Px(e){if(!e)return"";const t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(Sk);return n?t.slice(n[0].length):t}function zW(e){if(!e)return{frontmatterRaw:null,body:""};const t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(Sk);return n?{frontmatterRaw:n[1]?.trim()??"",body:t.slice(n[0].length)}:{frontmatterRaw:null,body:t}}function wk(e){const{frontmatterRaw:t,body:n}=zW(e);if(!t)return{frontmatterRaw:null,frontmatter:null,body:n};let r=null;try{const s=UW(t);s&&typeof s=="object"&&!Array.isArray(s)&&(r=s)}catch{r=null}return{frontmatterRaw:t,frontmatter:r,body:n}}function HW({files:e,selectedPath:t,onSelect:n}){const[r,s]=h.useState(""),i=h.useMemo(()=>{if(!r.trim())return e;const c=r.toLowerCase();return e.filter(u=>u.name.toLowerCase().includes(c)||u.title.toLowerCase().includes(c)||u.path.toLowerCase().includes(c))},[e,r]),o=h.useMemo(()=>i.filter(c=>c.category==="root"||c.category==="architecture"),[i]),l=h.useMemo(()=>i.filter(c=>c.category==="satellite"),[i]);return a.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-testid":"design-file-list",children:[a.jsx("div",{className:"p-2 border-b border-spur-border bg-base-100/50 shrink-0",children:a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",value:r,onChange:c=>s(c.target.value),placeholder:"Filter design docs...",className:"w-full text-xs px-2.5 py-1.5 pl-7 rounded border border-spur-border bg-base-100 text-spur-text placeholder:text-spur-text-muted/60 focus:outline-none focus:border-spur-accent","aria-label":"Filter design documents"}),a.jsx("span",{className:"absolute left-2 top-1.5 text-xs text-spur-text-muted pointer-events-none",children:"🔍"}),r&&a.jsx("button",{type:"button",onClick:()=>s(""),className:"absolute right-2 top-1 text-xs text-spur-text-muted hover:text-spur-text p-0.5","aria-label":"Clear filter",children:"✕"})]})}),a.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-3",children:i.length===0?a.jsx("div",{className:"p-4 text-xs text-spur-text-muted italic text-center",children:r?`No documents match "${r}"`:"No design documents found."}):a.jsxs(a.Fragment,{children:[o.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"px-2 py-1 text-[11px] font-bold uppercase tracking-wider text-spur-text-muted flex items-center justify-between",children:[a.jsx("span",{children:"Core Specifications"}),a.jsx("span",{className:"text-[10px] font-mono",children:o.length})]}),a.jsx("div",{className:"space-y-0.5 mt-1",children:o.map(c=>{const u=t===c.path;return a.jsxs("button",{type:"button",onClick:()=>n(c.path),title:c.name,className:`w-full text-left px-2.5 py-1.5 rounded-md transition-colors flex items-center gap-2 cursor-pointer ${u?"bg-spur-accent/15 text-spur-accent font-semibold shadow-xs":"hover:bg-base-300 text-spur-text hover:text-spur-text"}`,children:[a.jsx("span",{className:"text-sm shrink-0",children:c.name==="DESIGN.md"?"🎨":"📐"}),a.jsx("span",{className:"flex-1 min-w-0 text-xs truncate font-medium",title:c.name,children:c.title})]},c.id)})})]}),l.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"px-2 py-1 text-[11px] font-bold uppercase tracking-wider text-spur-text-muted flex items-center justify-between",children:[a.jsx("span",{children:"Design Satellites"}),a.jsx("span",{className:"text-[10px] font-mono",children:l.length})]}),a.jsx("div",{className:"space-y-0.5 mt-1",children:l.map(c=>{const u=t===c.path;return a.jsxs("button",{type:"button",onClick:()=>n(c.path),title:c.name,className:`w-full text-left px-2.5 py-1.5 rounded-md transition-colors flex items-center gap-2 cursor-pointer ${u?"bg-spur-accent/15 text-spur-accent font-semibold shadow-xs":"hover:bg-base-300 text-spur-text hover:text-spur-text"}`,children:[a.jsx("span",{className:"text-xs shrink-0 text-spur-text-muted",children:"📄"}),a.jsx("span",{className:"flex-1 min-w-0 text-xs truncate",title:c.name,children:c.title})]},c.id)})})]})]})})]})}function u1(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 GW(e){if(Array.isArray(e))return e}function WW(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw s}}return l}}function qW(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
296
296
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VW(e,t){return GW(e)||WW(e,t)||YW(e,t)||qW()}function YW(e,t){if(e){if(typeof e=="string")return u1(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)?u1(e,t):void 0}}const vk=Object.entries,d1=Object.setPrototypeOf,KW=Object.isFrozen,ZW=Object.getPrototypeOf,XW=Object.getOwnPropertyDescriptor;let cn=Object.freeze,dn=Object.seal,Zs=Object.create,Nk=typeof Reflect<"u"&&Reflect,vp=Nk.apply,Np=Nk.construct;cn||(cn=function(t){return t});dn||(dn=function(t){return t});vp||(vp=function(t,n){for(var r=arguments.length,s=new Array(r>2?r-2:0),i=2;i<r;i++)s[i-2]=arguments[i];return t.apply(n,s)});Np||(Np=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return new t(...r)});const ii=Kt(Array.prototype.forEach),QW=Kt(Array.prototype.lastIndexOf),p1=Kt(Array.prototype.pop),Hs=Kt(Array.prototype.push),JW=Kt(Array.prototype.splice),$r=Array.isArray,hi=Kt(String.prototype.toLowerCase),ud=Kt(String.prototype.toString),f1=Kt(String.prototype.match),oi=Kt(String.prototype.replace),m1=Kt(String.prototype.indexOf),eq=Kt(String.prototype.trim),tq=Kt(Number.prototype.toString),nq=Kt(Boolean.prototype.toString),h1=typeof BigInt>"u"?null:Kt(BigInt.prototype.toString),g1=typeof Symbol>"u"?null:Kt(Symbol.prototype.toString),tn=Kt(Object.prototype.hasOwnProperty),li=Kt(Object.prototype.toString),on=Kt(RegExp.prototype.test),ss=rq(TypeError);function Kt(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return vp(e,t,r)}}function rq(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Np(e,n)}}function ht(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:hi;if(d1&&d1(e,null),!$r(t))return e;let r=t.length;for(;r--;){let s=t[r];if(typeof s=="string"){const i=n(s);i!==s&&(KW(t)||(t[r]=i),s=i)}e[s]=!0}return e}function sq(e){for(let t=0;t<e.length;t++)tn(e,t)||(e[t]=null);return e}function yn(e){const t=Zs(null);for(const r of vk(e)){var n=VW(r,2);const s=n[0],i=n[1];tn(e,s)&&($r(i)?t[s]=sq(i):i&&typeof i=="object"&&i.constructor===Object?t[s]=yn(i):t[s]=i)}return t}function aq(e){switch(typeof e){case"string":return e;case"number":return tq(e);case"boolean":return nq(e);case"bigint":return h1?h1(e):"0";case"symbol":return g1?g1(e):"Symbol()";case"undefined":return li(e);case"function":case"object":{if(e===null)return li(e);const t=e,n=or(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:li(r)}return li(e)}default:return li(e)}}function or(e,t){for(;e!==null;){const r=XW(e,t);if(r){if(r.get)return Kt(r.get);if(typeof r.value=="function")return Kt(r.value)}e=ZW(e)}function n(){return null}return n}function iq(e){try{return on(e,""),!0}catch{return!1}}const b1=cn(["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"]),dd=cn(["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"]),pd=cn(["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"]),oq=cn(["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"]),fd=cn(["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"]),lq=cn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),x1=cn(["#text"]),y1=cn(["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"]),md=cn(["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"]),E1=cn(["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"]),el=cn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),cq=dn(/{{[\w\W]*|^[\w\W]*}}/g),uq=dn(/<%[\w\W]*|^[\w\W]*%>/g),dq=dn(/\${[\w\W]*/g),pq=dn(/^data-[\-\w.\u00B7-\uFFFF]+$/),fq=dn(/^aria-[\-\w]+$/),S1=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),mq=dn(/^(?:\w+script|data):/i),hq=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),gq=dn(/^html$/i),bq=dn(/^[a-z][.\w]*(-[.\w]+)+$/i),w1=dn(/<[/\w!]/g),xq=dn(/<[/\w]/g),yq=dn(/<\/no(script|embed|frames)/i),Eq=dn(/\/>/i),sr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Sq=function(){return typeof window>"u"?null:window},wq=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const s="data-tt-policy-suffix";n&&n.hasAttribute(s)&&(r=n.getAttribute(s));const i="dompurify"+(r?"#"+r:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},v1=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Lr=function(t,n,r,s){return tn(t,n)&&$r(t[n])?ht(s.base?yn(s.base):{},t[n],s.transform):r};function Tk(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Sq();const t=Ae=>Tk(Ae);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==sr.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,s=r.currentScript;e.DocumentFragment;const i=e.HTMLTemplateElement,o=e.Node,l=e.Element,c=e.NodeFilter,u=e.NamedNodeMap;u===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,p=e.trustedTypes,f=l.prototype,m=or(f,"cloneNode"),b=or(f,"remove"),x=or(f,"nextSibling"),y=or(f,"childNodes"),E=or(f,"parentNode"),A=or(f,"shadowRoot"),w=or(f,"attributes"),N=o&&o.prototype?or(o.prototype,"nodeType"):null,_=o&&o.prototype?or(o.prototype,"nodeName"):null;if(typeof i=="function"){const Ae=n.createElement("template");Ae.content&&Ae.content.ownerDocument&&(n=Ae.content.ownerDocument)}let k,S="",v,O=!1,C=0;const M=function(){if(C>0)throw ss('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.')},B=function(U){M(),C++;try{return k.createHTML(U)}finally{C--}},R=function(U){M(),C++;try{return k.createScriptURL(U)}finally{C--}},z=function(){return O||(v=wq(p,s),O=!0),v},W=n,F=W.implementation,J=W.createNodeIterator,K=W.createDocumentFragment,X=W.getElementsByTagName,I=r.importNode;let V=v1();t.isSupported=typeof vk=="function"&&typeof E=="function"&&F&&F.createHTMLDocument!==void 0;const te=cq,L=uq,ye=dq,xe=pq,P=fq,oe=mq,re=hq,H=bq;let Ce=S1,me=null;const he=ht({},[...b1,...dd,...pd,...fd,...x1]);let Ne=null;const Ge=ht({},[...y1,...md,...E1,...el]);let Z=Object.seal(Zs(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}})),ke=null,Fe=null;const Re=Object.seal(Zs(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let rt=!0,ae=!0,pe=!1,De=!0,Me=!1,Le=!0,ot=!1,dt=!1,se=null,fe=null,je=!1,Y=!1,He=!1,Ue=!1,at=!0,Nt=!1;const At="user-content-";let de=!0,_e=!1,Ve={},Pe=null;const Je=ht({},["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 Ct=null;const Oe=ht({},["audio","video","img","source","image","track"]);let Qe=null;const qe=ht({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),St="http://www.w3.org/1998/Math/MathML",ce="http://www.w3.org/2000/svg",Ee="http://www.w3.org/1999/xhtml";let Ye=Ee,Dt=!1,ee=null;const We=ht({},[St,ce,Ee],ud),lt=cn(["mi","mo","mn","ms","mtext"]);let bt=ht({},lt);const In=cn(["annotation-xml"]);let xr=ht({},In);const nr=ht({},["title","style","font","a","script"]);let Hn=null;const Ka=["application/xhtml+xml","text/html"],sC="text/html";let Ut=null,Fs=null;const aC=n.createElement("form"),d0=function(U){return U instanceof RegExp||U instanceof Function},Su=function(){let U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Fs&&Fs===U)return;(!U||typeof U!="object")&&(U={}),U=yn(U),Hn=Ka.indexOf(U.PARSER_MEDIA_TYPE)===-1?sC:U.PARSER_MEDIA_TYPE,Ut=Hn==="application/xhtml+xml"?ud:hi,me=Lr(U,"ALLOWED_TAGS",he,{transform:Ut}),Ne=Lr(U,"ALLOWED_ATTR",Ge,{transform:Ut}),ee=Lr(U,"ALLOWED_NAMESPACES",We,{transform:ud}),Qe=Lr(U,"ADD_URI_SAFE_ATTR",qe,{transform:Ut,base:qe}),Ct=Lr(U,"ADD_DATA_URI_TAGS",Oe,{transform:Ut,base:Oe}),Pe=Lr(U,"FORBID_CONTENTS",Je,{transform:Ut}),ke=Lr(U,"FORBID_TAGS",yn({}),{transform:Ut}),Fe=Lr(U,"FORBID_ATTR",yn({}),{transform:Ut}),Ve=tn(U,"USE_PROFILES")?U.USE_PROFILES&&typeof U.USE_PROFILES=="object"?yn(U.USE_PROFILES):U.USE_PROFILES:!1,rt=U.ALLOW_ARIA_ATTR!==!1,ae=U.ALLOW_DATA_ATTR!==!1,pe=U.ALLOW_UNKNOWN_PROTOCOLS||!1,De=U.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Me=U.SAFE_FOR_TEMPLATES||!1,Le=U.SAFE_FOR_XML!==!1,ot=U.WHOLE_DOCUMENT||!1,Y=U.RETURN_DOM||!1,He=U.RETURN_DOM_FRAGMENT||!1,Ue=U.RETURN_TRUSTED_TYPE||!1,je=U.FORCE_BODY||!1,at=U.SANITIZE_DOM!==!1,Nt=U.SANITIZE_NAMED_PROPS||!1,de=U.KEEP_CONTENT!==!1,_e=U.IN_PLACE||!1,Ce=iq(U.ALLOWED_URI_REGEXP)?U.ALLOWED_URI_REGEXP:S1,Ye=typeof U.NAMESPACE=="string"?U.NAMESPACE:Ee,bt=tn(U,"MATHML_TEXT_INTEGRATION_POINTS")&&U.MATHML_TEXT_INTEGRATION_POINTS&&typeof U.MATHML_TEXT_INTEGRATION_POINTS=="object"?yn(U.MATHML_TEXT_INTEGRATION_POINTS):ht({},lt),xr=tn(U,"HTML_INTEGRATION_POINTS")&&U.HTML_INTEGRATION_POINTS&&typeof U.HTML_INTEGRATION_POINTS=="object"?yn(U.HTML_INTEGRATION_POINTS):ht({},In);const ie=tn(U,"CUSTOM_ELEMENT_HANDLING")&&U.CUSTOM_ELEMENT_HANDLING&&typeof U.CUSTOM_ELEMENT_HANDLING=="object"?yn(U.CUSTOM_ELEMENT_HANDLING):Zs(null);if(Z=Zs(null),tn(ie,"tagNameCheck")&&d0(ie.tagNameCheck)&&(Z.tagNameCheck=ie.tagNameCheck),tn(ie,"attributeNameCheck")&&d0(ie.attributeNameCheck)&&(Z.attributeNameCheck=ie.attributeNameCheck),tn(ie,"allowCustomizedBuiltInElements")&&typeof ie.allowCustomizedBuiltInElements=="boolean"&&(Z.allowCustomizedBuiltInElements=ie.allowCustomizedBuiltInElements),dn(Z),Me&&(ae=!1),He&&(Y=!0),Ve&&(me=ht({},x1),Ne=Zs(null),Ve.html===!0&&(ht(me,b1),ht(Ne,y1)),Ve.svg===!0&&(ht(me,dd),ht(Ne,md),ht(Ne,el)),Ve.svgFilters===!0&&(ht(me,pd),ht(Ne,md),ht(Ne,el)),Ve.mathMl===!0&&(ht(me,fd),ht(Ne,E1),ht(Ne,el))),Re.tagCheck=null,Re.attributeCheck=null,tn(U,"ADD_TAGS")&&(typeof U.ADD_TAGS=="function"?Re.tagCheck=U.ADD_TAGS:$r(U.ADD_TAGS)&&(me===he&&(me=yn(me)),ht(me,U.ADD_TAGS,Ut))),tn(U,"ADD_ATTR")&&(typeof U.ADD_ATTR=="function"?Re.attributeCheck=U.ADD_ATTR:$r(U.ADD_ATTR)&&(Ne===Ge&&(Ne=yn(Ne)),ht(Ne,U.ADD_ATTR,Ut))),tn(U,"ADD_URI_SAFE_ATTR")&&$r(U.ADD_URI_SAFE_ATTR)&&ht(Qe,U.ADD_URI_SAFE_ATTR,Ut),tn(U,"FORBID_CONTENTS")&&$r(U.FORBID_CONTENTS)&&(Pe===Je&&(Pe=yn(Pe)),ht(Pe,U.FORBID_CONTENTS,Ut)),tn(U,"ADD_FORBID_CONTENTS")&&$r(U.ADD_FORBID_CONTENTS)&&(Pe===Je&&(Pe=yn(Pe)),ht(Pe,U.ADD_FORBID_CONTENTS,Ut)),de&&(me["#text"]=!0),ot&&ht(me,["html","head","body"]),me.table&&(ht(me,["tbody"]),delete ke.tbody),U.TRUSTED_TYPES_POLICY){if(typeof U.TRUSTED_TYPES_POLICY.createHTML!="function")throw ss('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof U.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ss('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Te=k;k=U.TRUSTED_TYPES_POLICY;try{S=B("")}catch($e){throw k=Te,$e}}else U.TRUSTED_TYPES_POLICY===null?(k=void 0,S=""):(k===void 0&&(k=z()),k&&typeof S=="string"&&(S=B("")));cn&&cn(U),Fs=U},p0=ht({},[...dd,...pd,...oq]),f0=ht({},[...fd,...lq]),iC=function(U,ie,Te){return ie.namespaceURI===Ee?U==="svg":ie.namespaceURI===St?U==="svg"&&(Te==="annotation-xml"||bt[Te]):!!p0[U]},oC=function(U,ie,Te){return ie.namespaceURI===Ee?U==="math":ie.namespaceURI===ce?U==="math"&&xr[Te]:!!f0[U]},lC=function(U,ie,Te){return ie.namespaceURI===ce&&!xr[Te]||ie.namespaceURI===St&&!bt[Te]?!1:!f0[U]&&(nr[U]||!p0[U])},cC=function(U){let ie=E(U);(!ie||!ie.tagName)&&(ie={namespaceURI:Ye,tagName:"template"});const Te=hi(U.tagName),$e=hi(ie.tagName);return ee[U.namespaceURI]?U.namespaceURI===ce?iC(Te,ie,$e):U.namespaceURI===St?oC(Te,ie,$e):U.namespaceURI===Ee?lC(Te,ie,$e):!!(Hn==="application/xhtml+xml"&&ee[U.namespaceURI]):!1},Dr=function(U){Hs(t.removed,{element:U});try{E(U).removeChild(U)}catch{if(b(U),!E(U))throw ss("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},m0=function(U){const ie=y(U);if(ie){const $e=[];ii(ie,ct=>{Hs($e,ct)}),ii($e,ct=>{try{b(ct)}catch{}})}const Te=w(U);if(Te)for(let $e=Te.length-1;$e>=0;--$e){const ct=Te[$e],gt=ct&&ct.name;if(typeof gt=="string")try{U.removeAttribute(gt)}catch{}}},ts=function(U,ie){try{Hs(t.removed,{attribute:ie.getAttributeNode(U),from:ie})}catch{Hs(t.removed,{attribute:null,from:ie})}if(ie.removeAttribute(U),U==="is")if(Y||He)try{Dr(ie)}catch{}else try{ie.setAttribute(U,"")}catch{}},uC=function(U){const ie=w(U);if(ie)for(let Te=ie.length-1;Te>=0;--Te){const $e=ie[Te],ct=$e&&$e.name;if(!(typeof ct!="string"||Ne[Ut(ct)]))try{U.removeAttribute(ct)}catch{}}},dC=function(U){const ie=[U];for(;ie.length>0;){const Te=ie.pop();(N?N(Te):Te.nodeType)===sr.element&&uC(Te);const ct=y(Te);if(ct)for(let gt=ct.length-1;gt>=0;--gt)ie.push(ct[gt])}},h0=function(U){let ie=null,Te=null;if(je)U="<remove></remove>"+U;else{const gt=f1(U,/^[\r\n\t ]+/);Te=gt&&gt[0]}Hn==="application/xhtml+xml"&&Ye===Ee&&(U='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+U+"</body></html>");const $e=k?B(U):U;if(Ye===Ee)try{ie=new d().parseFromString($e,Hn)}catch{}if(!ie||!ie.documentElement){ie=F.createDocument(Ye,"template",null);try{ie.documentElement.innerHTML=Dt?S:$e}catch{}}const ct=ie.body||ie.documentElement;return U&&Te&&ct.insertBefore(n.createTextNode(Te),ct.childNodes[0]||null),Ye===Ee?X.call(ie,ot?"html":"body")[0]:ot?ie.documentElement:ct},g0=function(U){return J.call(U.ownerDocument||U,U,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ko=function(U){return U=oi(U,te," "),U=oi(U,L," "),U=oi(U,ye," "),U},wu=function(U){var ie;U.normalize();const Te=J.call(U.ownerDocument||U,U,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let $e=Te.nextNode();for(;$e;)$e.data=ko($e.data),$e=Te.nextNode();const ct=(ie=U.querySelectorAll)===null||ie===void 0?void 0:ie.call(U,"template");ct&&ii(ct,gt=>{Ps(gt.content)&&wu(gt.content)})},Ao=function(U){const ie=_?_(U):null;return typeof ie!="string"||Ut(ie)!=="form"?!1:typeof U.nodeName!="string"||typeof U.textContent!="string"||typeof U.removeChild!="function"||U.attributes!==w(U)||typeof U.removeAttribute!="function"||typeof U.setAttribute!="function"||typeof U.namespaceURI!="string"||typeof U.insertBefore!="function"||typeof U.hasChildNodes!="function"||U.nodeType!==N(U)||U.childNodes!==y(U)},Ps=function(U){if(!N||typeof U!="object"||U===null)return!1;try{return N(U)===sr.documentFragment}catch{return!1}},Za=function(U){if(!N||typeof U!="object"||U===null)return!1;try{return typeof N(U)=="number"}catch{return!1}};function yr(Ae,U,ie){Ae.length!==0&&ii(Ae,Te=>{Te.call(t,U,ie,Fs)})}const pC=function(U,ie){return!!(Le&&U.hasChildNodes()&&!Za(U.firstElementChild)&&on(w1,U.textContent)&&on(w1,U.innerHTML)||Le&&U.namespaceURI===Ee&&ie==="style"&&Za(U.firstElementChild)||U.nodeType===sr.processingInstruction||Le&&U.nodeType===sr.comment&&on(xq,U.data))},fC=function(U,ie){if(!ke[ie]&&y0(ie)&&(Z.tagNameCheck instanceof RegExp&&on(Z.tagNameCheck,ie)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(ie)))return!1;if(de&&!Pe[ie]){const Te=E(U),$e=y(U);if($e&&Te){const ct=$e.length;for(let gt=ct-1;gt>=0;--gt){const Qt=_e?$e[gt]:m($e[gt],!0);Te.insertBefore(Qt,x(U))}}}return Dr(U),!0},b0=function(U){if(yr(V.beforeSanitizeElements,U,null),Ao(U))return Dr(U),!0;const ie=Ut(_?_(U):U.nodeName);if(yr(V.uponSanitizeElement,U,{tagName:ie,allowedTags:me}),pC(U,ie))return Dr(U),!0;if(ke[ie]||!(Re.tagCheck instanceof Function&&Re.tagCheck(ie))&&!me[ie])return fC(U,ie);if((N?N(U):U.nodeType)===sr.element&&!cC(U)||(ie==="noscript"||ie==="noembed"||ie==="noframes")&&on(yq,U.innerHTML))return Dr(U),!0;if(Me&&U.nodeType===sr.text){const $e=ko(U.textContent);U.textContent!==$e&&(Hs(t.removed,{element:U.cloneNode()}),U.textContent=$e)}return yr(V.afterSanitizeElements,U,null),!1},x0=function(U,ie,Te){if(Fe[ie]||at&&(ie==="id"||ie==="name")&&(Te in n||Te in aC))return!1;const $e=Ne[ie]||Re.attributeCheck instanceof Function&&Re.attributeCheck(ie,U);if(!(ae&&on(xe,ie))){if(!(rt&&on(P,ie))){if($e){if(!Qe[ie]){if(!on(Ce,oi(Te,re,""))){if(!((ie==="src"||ie==="xlink:href"||ie==="href")&&U!=="script"&&m1(Te,"data:")===0&&Ct[U])){if(!(pe&&!on(oe,oi(Te,re,"")))){if(Te)return!1}}}}}else if(!(y0(U)&&(Z.tagNameCheck instanceof RegExp&&on(Z.tagNameCheck,U)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(U))&&(Z.attributeNameCheck instanceof RegExp&&on(Z.attributeNameCheck,ie)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(ie,U))||ie==="is"&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&on(Z.tagNameCheck,Te)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(Te))))return!1}}return!0},mC=ht({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),y0=function(U){return!mC[hi(U)]&&on(H,U)},hC=function(U,ie,Te,$e){if(k&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Te)switch(p.getAttributeType(U,ie)){case"TrustedHTML":return B($e);case"TrustedScriptURL":return R($e)}return $e},gC=function(U,ie,Te,$e){try{Te?U.setAttributeNS(Te,ie,$e):U.setAttribute(ie,$e),Ao(U)?Dr(U):p1(t.removed)}catch{ts(ie,U)}},E0=function(U){yr(V.beforeSanitizeAttributes,U,null);const ie=U.attributes;if(!ie||Ao(U))return;const Te={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ne,forceKeepAttr:void 0};let $e=ie.length;const ct=Ut(U.nodeName);for(;$e--;){const gt=ie[$e],Qt=gt.name,qt=gt.namespaceURI,On=gt.value,Gn=Ut(Qt),Nu=On;let bn=Qt==="value"?Nu:eq(Nu);if(Te.attrName=Gn,Te.attrValue=bn,Te.keepAttr=!0,Te.forceKeepAttr=void 0,yr(V.uponSanitizeAttribute,U,Te),bn=Te.attrValue,Nt&&(Gn==="id"||Gn==="name")&&m1(bn,At)!==0&&(ts(Qt,U),bn=At+bn),Le&&on(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,bn)){ts(Qt,U);continue}if(Gn==="attributename"&&f1(bn,"href")){ts(Qt,U);continue}if(!Te.forceKeepAttr){if(!Te.keepAttr){ts(Qt,U);continue}if(!De&&on(Eq,bn)){ts(Qt,U);continue}if(Me&&(bn=ko(bn)),!x0(ct,Gn,bn)){ts(Qt,U);continue}bn=hC(ct,Gn,qt,bn),bn!==Nu&&gC(U,Qt,qt,bn)}}yr(V.afterSanitizeAttributes,U,null)},Co=function(U){let ie=null;const Te=g0(U);for(yr(V.beforeSanitizeShadowDOM,U,null);ie=Te.nextNode();)if(yr(V.uponSanitizeShadowNode,ie,null),b0(ie),E0(ie),Ps(ie.content)&&Co(ie.content),(N?N(ie):ie.nodeType)===sr.element){const ct=A(ie);Ps(ct)&&(vu(ct),Co(ct))}yr(V.afterSanitizeShadowDOM,U,null)},vu=function(U){const ie=[{node:U,shadow:null}];for(;ie.length>0;){const Te=ie.pop();if(Te.shadow){Co(Te.shadow);continue}const $e=Te.node,gt=(N?N($e):$e.nodeType)===sr.element,Qt=y($e);if(Qt)for(let qt=Qt.length-1;qt>=0;--qt)ie.push({node:Qt[qt],shadow:null});if(gt){const qt=_?_($e):null;if(typeof qt=="string"&&Ut(qt)==="template"){const On=$e.content;Ps(On)&&ie.push({node:On,shadow:null})}}if(gt){const qt=A($e);Ps(qt)&&ie.push({node:null,shadow:qt},{node:qt,shadow:null})}}};return t.sanitize=function(Ae){let U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ie=null,Te=null,$e=null,ct=null;if(Dt=!Ae,Dt&&(Ae="<!-->"),typeof Ae!="string"&&!Za(Ae)&&(Ae=aq(Ae),typeof Ae!="string"))throw ss("dirty is not a string, aborting");if(!t.isSupported)return Ae;dt?(me=se,Ne=fe):Su(U),(V.uponSanitizeElement.length>0||V.uponSanitizeAttribute.length>0)&&(me=yn(me)),V.uponSanitizeAttribute.length>0&&(Ne=yn(Ne)),t.removed=[];const gt=_e&&typeof Ae!="string"&&Za(Ae);if(gt){const On=_?_(Ae):Ae.nodeName;if(typeof On=="string"){const Gn=Ut(On);if(!me[Gn]||ke[Gn])throw ss("root node is forbidden and cannot be sanitized in-place")}if(Ao(Ae))throw ss("root node is clobbered and cannot be sanitized in-place");try{vu(Ae)}catch(Gn){throw m0(Ae),Gn}}else if(Za(Ae))ie=h0("<!---->"),Te=ie.ownerDocument.importNode(Ae,!0),Te.nodeType===sr.element&&Te.nodeName==="BODY"||Te.nodeName==="HTML"?ie=Te:ie.appendChild(Te),vu(Te);else{if(!Y&&!Me&&!ot&&Ae.indexOf("<")===-1)return k&&Ue?B(Ae):Ae;if(ie=h0(Ae),!ie)return Y?null:Ue?S:""}ie&&je&&Dr(ie.firstChild);const Qt=g0(gt?Ae:ie);try{for(;$e=Qt.nextNode();)b0($e),E0($e),Ps($e.content)&&Co($e.content)}catch(On){throw gt&&m0(Ae),On}if(gt)return ii(t.removed,On=>{On.element&&dC(On.element)}),Me&&wu(Ae),Ae;if(Y){if(Me&&wu(ie),He)for(ct=K.call(ie.ownerDocument);ie.firstChild;)ct.appendChild(ie.firstChild);else ct=ie;return(Ne.shadowroot||Ne.shadowrootmode)&&(ct=I.call(r,ct,!0)),ct}let qt=ot?ie.outerHTML:ie.innerHTML;return ot&&me["!doctype"]&&ie.ownerDocument&&ie.ownerDocument.doctype&&ie.ownerDocument.doctype.name&&on(gq,ie.ownerDocument.doctype.name)&&(qt="<!DOCTYPE "+ie.ownerDocument.doctype.name+`>
297
- `+qt),Me&&(qt=ko(qt)),k&&Ue?B(qt):qt},t.setConfig=function(){let Ae=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Su(Ae),dt=!0,se=me,fe=Ne},t.clearConfig=function(){Fs=null,dt=!1,se=null,fe=null,k=v,S=""},t.isValidAttribute=function(Ae,U,ie){Fs||Su({});const Te=Ut(Ae),$e=Ut(U);return x0(Te,$e,ie)},t.addHook=function(Ae,U){typeof U=="function"&&tn(V,Ae)&&Hs(V[Ae],U)},t.removeHook=function(Ae,U){if(tn(V,Ae)){if(U!==void 0){const ie=QW(V[Ae],U);return ie===-1?void 0:JW(V[Ae],ie,1)[0]}return p1(V[Ae])}},t.removeHooks=function(Ae){tn(V,Ae)&&(V[Ae]=[])},t.removeAllHooks=function(){V=v1()},t}var kk=Tk();const vq=()=>e=>{const t=e,n=kk(window).sanitize(gT(e),{USE_PROFILES:{html:!0},FORBID_TAGS:["style"],FORBID_ATTR:["style"]});t.children=uT(n,{fragment:!0}).children},Ta={pluginsFilter:(e,t)=>e==="rehype"?[...t,vq]:t},Nq=(function(){const t=typeof document<"u"&&document.createElement("link").relList;return t&&t.supports&&t.supports("modulepreload")?"modulepreload":"preload"})(),Tq=function(e){return"/"+e},N1={},Ak=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let c=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");s=c(n.map(u=>{if(u=Tq(u),u in N1)return;N1[u]=!0;const d=u.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${p}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Nq,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((m,b)=>{f.addEventListener("load",m),f.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return s.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})},kq={USE_PROFILES:{svg:!0,svgFilters:!0,html:!0},ADD_TAGS:["foreignObject"],HTML_INTEGRATION_POINTS:{foreignobject:!0}};function Aq(e){return kk(window).sanitize(e,kq)}function Cq({code:e}){const t=h.useId().replace(/:/g,""),n=h.useRef(null),[r,s]=h.useState(null),[i,o]=h.useState(!1),[l,c]=h.useState("light");return h.useEffect(()=>{if(typeof document>"u")return;const u=document.documentElement.getAttribute("data-theme");(u==="dark"||u==="light")&&c(u)},[]),h.useEffect(()=>{if(typeof MutationObserver>"u"||typeof document>"u")return;const u=new MutationObserver(()=>{const d=document.documentElement.getAttribute("data-theme")||"light";c(d)});return u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>u.disconnect()},[]),h.useEffect(()=>{let u=!1;return(async()=>{try{const d=(await Ak(async()=>{const{default:m}=await import("./mermaid.core.VoW0rvGv.js").then(b=>b.bn);return{default:m}},__vite__mapDeps([0,1]))).default;d.initialize({startOnLoad:!1,securityLevel:"loose",theme:l==="dark"?"dark":"default",fontFamily:"ui-sans-serif, system-ui, -apple-system, sans-serif",flowchart:{htmlLabels:!1,useMaxWidth:!1}});const p=await d.render(`mermaid-${t}`,e),f=Aq(p.svg).replace(/(<svg[^>]*?)\s+width="[^"]*"/,'$1 width="100%"').replace(/(<svg[^>]*?)\s+height="[^"]*"/,'$1 height="auto"');u||s(f)}catch{u||o(!0)}})(),()=>{u=!0}},[e,t,l]),h.useEffect(()=>{n.current&&(n.current.innerHTML=r??"")},[r]),i?a.jsx("pre",{className:"text-xs font-mono p-3 bg-spur-surface-2 rounded border border-spur-border overflow-x-auto",children:a.jsx("code",{children:e})}):a.jsx("div",{ref:n,className:"mermaid-diagram","data-testid":"mermaid-diagram"})}function _q(e){return(e??"").match(/language-(\w+)/)?.[1]??null}function Vi(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(Vi).join(""):typeof e=="object"&&"props"in e?Vi(e.props.children):""}function Bx({className:e,children:t,...n}){return _q(e)==="mermaid"?a.jsx(Cq,{code:Vi(t).trim()}):a.jsx("code",{className:e,...n,children:t})}function Ck({source:e,className:t,style:n}){return a.jsx(wa.Markdown,{source:e,className:t,style:n,wrapperElement:{"data-color-mode":"light"},...Ta,components:{code:Bx}})}function Iq(e){if(!e)return[];const t=e.split(/\r?\n/),n=[],r=new Map;let s=!1;for(const i of t){if(i.trim().startsWith("```")){s=!s;continue}if(s)continue;const l=i.match(/^(#{1,6})\s+(.+)$/);if(l?.[1]&&l[2]){const c=l[1].length,d=l[2].trim().replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim(),f=d.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-")||`heading-${n.length+1}`,m=r.get(f)??0;r.set(f,m+1);const b=m===0?f:`${f}-${m}`;n.push({id:b,text:d,level:c})}}return n}function Rq(){const e=new Map;return{nextId(t){const r=t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-")||"heading",s=e.get(r)??0;return e.set(r,s+1),s===0?r:`${r}-${s}`}}}function Dq({markdown:e,scrollContainerRef:t,onClose:n}){const r=h.useMemo(()=>Iq(e),[e]),[s,i]=h.useState(null);h.useEffect(()=>{const l=t?.current;if(!l||r.length===0)return;const c=()=>{const u=l.getBoundingClientRect().top;let d=null;for(const p of r){const f=document.getElementById(p.id);f&&f.getBoundingClientRect().top-u<=100&&(d=p.id)}d&&i(d)};return l.addEventListener("scroll",c,{passive:!0}),c(),()=>l.removeEventListener("scroll",c)},[r,t]);const o=l=>{i(l);const c=document.getElementById(l);c&&c.scrollIntoView({behavior:"smooth",block:"start"})};return a.jsxs("aside",{id:"design-toc-dock","aria-label":"Table of Contents",className:"w-64 lg:w-72 shrink-0 rounded-lg border border-spur-border bg-base-200 shadow-xs flex flex-col overflow-hidden 3xl:absolute 3xl:top-0 3xl:bottom-0 3xl:left-[calc(100%_+_12px)] 3xl:z-20 3xl:w-72 4xl:w-80 3xl:shadow-xl","data-testid":"design-toc-dock",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border bg-base-300/60 shrink-0",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text flex items-center gap-1.5",children:[a.jsx("span",{children:"📑"})," Table of Contents"]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[r.length>0&&a.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-spur-accent/15 text-spur-accent font-semibold",children:r.length}),n&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent h-5 w-5 p-0 text-xs flex items-center justify-center cursor-pointer",onClick:n,"aria-label":"Close table of contents",title:"Close table of contents",children:"✕"})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-1.5 space-y-0.5",children:r.length===0?a.jsx("div",{className:"p-3 text-xs text-spur-text-muted italic",children:"No headings in document."}):r.map(l=>{const c=s===l.id;let u="pl-2 text-xs font-semibold";return l.level===2?u="pl-4 text-xs font-medium":l.level===3?u="pl-6 text-xs text-spur-text-muted":l.level>=4&&(u="pl-8 text-[11px] text-spur-text-muted"),a.jsx("button",{type:"button",onClick:()=>o(l.id),title:l.text,className:`w-full text-left py-1 pr-2 rounded transition-colors truncate block cursor-pointer ${u} ${c?"bg-spur-accent/15 text-spur-accent font-semibold":"hover:bg-base-300 hover:text-spur-text text-spur-text/80"}`,children:l.text},l.id)})})]})}function Oq({source:e,className:t}){const n=Px(e),r=Rq(),s=o=>{const l=`h${o}`;return({children:c,...u})=>{const p=Vi(c).trim().replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim(),f=r.nextId(p);return a.jsx(l,{id:f,className:"scroll-mt-6 group",...u,children:c})}},i={code:Bx,h1:s(1),h2:s(2),h3:s(3),h4:s(4),h5:s(5),h6:s(6)};return a.jsx("div",{className:`design-markdown-container ${t??""}`,"data-testid":"design-markdown-body",children:a.jsx(wa.Markdown,{source:n,wrapperElement:{"data-color-mode":"light"},...Ta,components:i})})}function Lq(){const[e,t]=Ca(),[n,r]=h.useState(null),[s,i]=h.useState(()=>e.get("file")),o=h.useRef({}),[l,c]=h.useState({}),[u,d]=h.useState(!0),[p,f]=h.useState(!0),[m,b]=h.useState(!1),[x,y]=h.useState(!0),[E,A]=h.useState(!1),[w,N]=h.useState(null),[_,k]=h.useState(null),[S,v]=h.useState(!1),O=h.useRef(null),C=h.useRef(null),M=h.useCallback(async I=>{try{y(!0);const V=await IG(I);return r(V),N(null),V}catch(V){return I?.aborted||N(V instanceof Error?V.message:String(V)),null}finally{y(!1)}},[]),B=h.useCallback(async(I,V)=>{if(!o.current[I])try{A(!0),k(null);const te=await RG(I,V);o.current[I]=te,c(L=>({...L,[I]:te}))}catch(te){if(V?.aborted)return;k(te instanceof Error?te.message:String(te))}finally{A(!1)}},[]),R=e.get("file");h.useEffect(()=>{const I=new AbortController;return(async()=>{const V=await M(I.signal);if(V&&V.length>0){if(R&&V.some(L=>L.path===R))i(R);else if(!R){const L=V[0]?.path;L&&i(L)}}})(),()=>I.abort()},[M,R]),h.useEffect(()=>{R&&R!==s&&i(R)},[R,s]),h.useEffect(()=>{if(!s)return;const I=new AbortController;return B(s,I.signal),()=>I.abort()},[s,B]);const z=I=>{i(I),f(!0),t({file:I},{replace:!0}),O.current&&(O.current.scrollTop=0)},W=()=>{s&&(navigator.clipboard.writeText(s),v(!0),setTimeout(()=>v(!1),2e3))},F=s?l[s]:null,{frontmatterRaw:J,frontmatter:K,body:X}=h.useMemo(()=>F?.content?wk(F.content):{frontmatterRaw:null,frontmatter:null,body:""},[F?.content]);return w?a.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load design documents: ",w]}):x&&n===null?a.jsx("div",{className:"flex items-center justify-center h-full text-spur-text-muted text-sm",children:"Loading design documents…"}):a.jsxs("div",{className:"relative h-full w-full p-4 overflow-hidden","data-designs-shell":!0,children:[a.jsxs("div",{className:"flex flex-col h-full w-full max-w-full 3xl:max-w-[1200px] 4xl:max-w-[1600px] mx-auto gap-3","data-designs-workspace":!0,children:[a.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-spur-border pb-3 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rr,{id:"designs",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight text-spur-text",children:"Designs"}),a.jsx("p",{className:"text-xs text-spur-text-muted",children:"Design documents, architecture specifications, and surface contracts"})]})]}),a.jsxs("div",{className:"flex items-center gap-1","data-designs-actions":!0,children:[a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>d(I=>!I),"aria-label":u?"Collapse design file list":"Expand design file list","aria-expanded":u,"aria-controls":"design-files-dock",title:u?"Collapse design file list":"Expand design file list",children:u?"◧":"▶"}),s&&F?.content&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>f(I=>!I),"aria-label":p?"Collapse table of contents":"Expand table of contents","aria-expanded":p,"aria-controls":"design-toc-dock",title:p?"Collapse table of contents":"Expand table of contents",children:p?"📑":"📖"}),a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>{(async()=>(await M(),s&&(c(I=>{const V={...I};return delete V[s],V}),B(s))))()},"aria-label":"Refresh design documents",title:"Refresh design documents",children:"🔄"})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-stretch gap-3 overflow-hidden 3xl:relative 3xl:block 3xl:overflow-visible",ref:C,children:[a.jsxs("div",{id:"design-files-dock",hidden:!u,className:`${u?"flex":"hidden"} w-64 lg:w-72 shrink-0 flex-col overflow-hidden rounded-lg border border-spur-border bg-base-200 shadow-xs 3xl:absolute 3xl:right-[calc(100%_+_12px)] 3xl:top-0 3xl:bottom-0 3xl:z-20 3xl:w-72 4xl:w-80 3xl:shadow-xl`,"data-testid":"design-files-dock",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border bg-base-300/60 shrink-0",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text flex items-center gap-1.5",children:[a.jsx("span",{children:"📐"})," Design Docs"]}),n&&n.length>0&&a.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-spur-accent/15 text-spur-accent font-semibold",children:n.length})]}),a.jsx("div",{className:"flex-1 overflow-hidden",children:n&&n.length>0?a.jsx(HW,{files:n,selectedPath:s,onSelect:z}):a.jsx("div",{className:"p-3 text-xs text-spur-text-muted italic",children:"No design documents found."})})]}),a.jsx("div",{className:"flex-1 min-w-0 h-full overflow-hidden rounded-lg border border-spur-border bg-base-100 relative 3xl:w-full 3xl:flex-none","data-testid":"design-workspace",children:a.jsx("div",{className:"w-full h-full overflow-y-auto",ref:O,children:s?a.jsxs("div",{className:"flex flex-col min-h-full",children:[a.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-6 py-3 border-b border-spur-border bg-base-100/90 backdrop-blur-xs",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-base-200 text-spur-text-muted border border-spur-border shrink-0",children:s}),F?.title&&a.jsx("h2",{className:"text-sm font-semibold text-spur-text truncate",children:F.title})]}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent flex items-center gap-1 shrink-0",onClick:()=>b(!0),"aria-label":"View document metadata",title:"View document metadata","data-testid":"metadata-toggle",children:"ℹ Metadata"}),a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-text shrink-0",onClick:W,"aria-label":"Copy file path",title:"Copy file path",children:S?"✓ Copied":"📋 Copy Path"})]})]}),a.jsx("div",{className:"p-6 md:p-8 flex-1","data-testid":"design-body-container",children:E&&!F?a.jsx("div",{className:"flex items-center justify-center py-20 text-spur-text-muted text-sm",children:"Loading document content…"}):_?a.jsxs("div",{className:"p-4 text-sm text-error bg-error/10 rounded-md border border-error/20",children:["Failed to load document: ",_]}):F?a.jsx(Oq,{source:X}):null})]}):a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-spur-text-muted gap-2",children:[a.jsx("span",{className:"text-3xl","aria-hidden":"true",children:"📐"}),a.jsx("span",{className:"text-sm font-medium",children:"Select a design document to view"})]})})}),s&&F?.content&&p&&a.jsx(Dq,{markdown:X,scrollContainerRef:O,onClose:()=>f(!1)})]})]}),a.jsx(NT,{open:m,onClose:()=>b(!1),title:F?.title,filePath:s,frontmatterRaw:J,frontmatter:K})]})}const jq={id:"designs",name:"Designs",icon:"📐",route:"designs",component:Lq,sidebarLabel:"Designs",description:"Design documents, architecture specifications, and surface contracts",order:25},Mq=Object.freeze(Object.defineProperty({__proto__:null,module:jq},Symbol.toStringTag,{value:"Module"})),br=()=>`${it()}/features`;async function Fq(e){const t=await Xe(new Request(br(),{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 T1(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e)}`,{signal:t}));if(!n.ok)throw new Error(`feature show fetch failed: ${n.status}`);const s=await n.json();if(!s.ok||!s.data)throw new Error("feature show: invalid response shape");return s.data}async function Pq(e,t,n){const r=await Xe(new Request(`${br()}/${encodeURIComponent(e)}/status`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,toStatus:t}),signal:n})),s=await r.json();if(!r.ok){const o=s;throw new Error(o.error?.message??`transition failed: ${r.status}`)}return s.data?.status??t}async function Bq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/body`,{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??`body update failed: ${n.status}`)}}async function $q(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/action`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`action dispatch failed: ${n.status}`)}return await n.json()}async function _k(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/children`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`create child failed: ${n.status}`)}return await n.json()}async function Uq(e,t){const n=await Xe(new Request(br(),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:e}),signal:t}));if(!n.ok){const o=await n.json();throw new Error(o.error?.message??`create feature failed: ${n.status}`)}const s=await n.json();if(!s.ok||!s.data)throw new Error("create feature: invalid response shape");return s.data}async function zq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/tasks`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`create task failed: ${n.status}`)}return await n.json()}async function Hq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/link`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`link task failed: ${n.status}`)}return await n.json()}async function Gq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/sync`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`sync failed: ${n.status}`)}return await n.json()}const nc=new Set,rc=new Set;let ls,$x=!1;function k1(e){$x=e;for(const t of rc)t(e)}function Ik(){if(ls||typeof window>"u"||typeof EventSource>"u")return;const e=new EventSource(`${it()}/events/planning`);ls=e,e.onopen=()=>{ls===e&&k1(!0)},e.onerror=()=>{ls===e&&k1(!1)},e.onmessage=t=>{if(ls!==e)return;let n;try{n=JSON.parse(t.data)}catch{return}if(!n||typeof n!="object"||Array.isArray(n))return;const{eventName:r,payload:s}=n;if(typeof r!="string"||!["task.","feature.","queue.job."].some(o=>r.startsWith(o)))return;const i={eventName:r,payload:s};for(const o of nc)o(i)}}function Rk(){if(nc.size||rc.size)return;const e=ls;ls=void 0,$x=!1,e&&(e.onmessage=null,e.onopen=null,e.onerror=null,e.close())}function mu(e){const t=n=>e(n);return nc.add(t),Ik(),()=>{nc.delete(t),Rk()}}function Dk(e){const t=n=>e(n);return rc.add(t),e($x),Ik(),()=>{rc.delete(t),Rk()}}function ka({targetVar:e,onResizeEnd:t,direction:n="horizontal",invert:r=!1}){const s=h.useRef(null),i=h.useCallback(l=>{l.preventDefault();const c=document.documentElement,d=getComputedStyle(c).getPropertyValue(e).trim(),p=parseFloat(d)||0;s.current={x:l.clientX,y:l.clientY,w:p},l.target.setPointerCapture(l.pointerId);const f=b=>{if(!s.current)return;const x=n==="horizontal"?b.clientX-s.current.x:b.clientY-s.current.y,y=r?-x:x,E=Math.max(0,s.current.w+y);c.style.setProperty(e,`${E}px`)},m=()=>{if(!s.current)return;const b=getComputedStyle(c).getPropertyValue(e).trim(),x=parseFloat(b)||s.current.w;t(Math.round(x)),s.current=null,window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",m)};window.addEventListener("pointermove",f),window.addEventListener("pointerup",m,{once:!0})},[e,t,n,r]),o=n==="horizontal";return a.jsx("hr",{"data-testid":`resize-handle-${o?"h":"v"}`,"aria-orientation":o?"vertical":"horizontal","aria-label":o?"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:o?4:"100%",height:o?"100%":4,margin:0},onPointerDown:i})}const A1="spur:new-task-panel-width",C1=384,hd=384;function _1({id:e,label:t,placeholder:n,value:r,mode:s,onChange:i,onModeChange:o,disabled:l}){return a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[a.jsxs("label",{htmlFor:e,className:"text-xs font-semibold text-spur-text-muted uppercase tracking-wide",children:[t," ",a.jsx("span",{className:"text-spur-text-muted font-normal",children:"(optional, markdown)"})]}),a.jsxs("fieldset",{className:"flex items-center gap-1",children:[a.jsxs("legend",{className:"sr-only",children:[t," mode"]}),a.jsx(Ie,{type:"button",variant:s==="edit"?"primary":"ghost",size:"xs",onClick:()=>o("edit"),disabled:l,"aria-pressed":s==="edit",children:"Edit"}),a.jsx(Ie,{type:"button",variant:s==="preview"?"primary":"ghost",size:"xs",onClick:()=>o("preview"),disabled:l,"aria-pressed":s==="preview",children:"Preview"})]})]}),s==="edit"?a.jsx("div",{className:"min-h-40","data-testid":`${e}-editor`,children:a.jsx(wa,{value:r,onChange:c=>i(c??""),height:160,textareaProps:{id:e,placeholder:n,disabled:l,"aria-label":t},"data-color-mode":"dark",previewOptions:Ta})}):a.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()?a.jsx(wa.Markdown,{source:r,"data-color-mode":"dark",...Ta}):a.jsx("p",{className:"text-xs text-spur-text-muted",children:n})})]})}function Ok({open:e,onClose:t,onCreated:n,folder:r,featureId:s}){const[i,o]=h.useState(""),[l,c]=h.useState(""),[u,d]=h.useState(""),[p,f]=h.useState("edit"),[m,b]=h.useState("edit"),[x,y]=h.useState("standard"),[E,A]=h.useState(!1),[w,N]=h.useState(""),[_,k]=h.useState(!1),[S,v]=h.useState(()=>{if(typeof window>"u")return C1;try{const B=Number.parseFloat(window.localStorage.getItem(A1)??"");if(Number.isFinite(B)&&B>0)return Math.max(hd,Math.min(B,window.innerWidth*.9))}catch{}return C1}),O=_&&i.trim()===""?"Name is required":"";h.useEffect(()=>{document.documentElement.style.setProperty("--new-task-panel-w",`${S}px`)},[S]);const C=()=>{E||(o(""),c(""),d(""),f("edit"),b("edit"),y("standard"),N(""),k(!1),t())},M=async()=>{k(!0);const B=i.trim();if(B!==""){A(!0),N("");try{const z=(await xt.task.create({title:B,folder:r,template:x,featureId:s})).data.wbs,W=[];if(l.trim()&&W.push(`### Background
297
+ `+qt),Me&&(qt=ko(qt)),k&&Ue?B(qt):qt},t.setConfig=function(){let Ae=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Su(Ae),dt=!0,se=me,fe=Ne},t.clearConfig=function(){Fs=null,dt=!1,se=null,fe=null,k=v,S=""},t.isValidAttribute=function(Ae,U,ie){Fs||Su({});const Te=Ut(Ae),$e=Ut(U);return x0(Te,$e,ie)},t.addHook=function(Ae,U){typeof U=="function"&&tn(V,Ae)&&Hs(V[Ae],U)},t.removeHook=function(Ae,U){if(tn(V,Ae)){if(U!==void 0){const ie=QW(V[Ae],U);return ie===-1?void 0:JW(V[Ae],ie,1)[0]}return p1(V[Ae])}},t.removeHooks=function(Ae){tn(V,Ae)&&(V[Ae]=[])},t.removeAllHooks=function(){V=v1()},t}var kk=Tk();const vq=()=>e=>{const t=e,n=kk(window).sanitize(gT(e),{USE_PROFILES:{html:!0},FORBID_TAGS:["style"],FORBID_ATTR:["style"]});t.children=uT(n,{fragment:!0}).children},Ta={pluginsFilter:(e,t)=>e==="rehype"?[...t,vq]:t},Nq=(function(){const t=typeof document<"u"&&document.createElement("link").relList;return t&&t.supports&&t.supports("modulepreload")?"modulepreload":"preload"})(),Tq=function(e){return"/"+e},N1={},Ak=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let c=function(u){return Promise.all(u.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");s=c(n.map(u=>{if(u=Tq(u),u in N1)return;N1[u]=!0;const d=u.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${p}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Nq,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((m,b)=>{f.addEventListener("load",m),f.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return s.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})},kq={USE_PROFILES:{svg:!0,svgFilters:!0,html:!0},ADD_TAGS:["foreignObject"],HTML_INTEGRATION_POINTS:{foreignobject:!0}};function Aq(e){return kk(window).sanitize(e,kq)}function Cq({code:e}){const t=h.useId().replace(/:/g,""),n=h.useRef(null),[r,s]=h.useState(null),[i,o]=h.useState(!1),[l,c]=h.useState("light");return h.useEffect(()=>{if(typeof document>"u")return;const u=document.documentElement.getAttribute("data-theme");(u==="dark"||u==="light")&&c(u)},[]),h.useEffect(()=>{if(typeof MutationObserver>"u"||typeof document>"u")return;const u=new MutationObserver(()=>{const d=document.documentElement.getAttribute("data-theme")||"light";c(d)});return u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>u.disconnect()},[]),h.useEffect(()=>{let u=!1;return(async()=>{try{const d=(await Ak(async()=>{const{default:m}=await import("./mermaid.core.Dixrjrnj.js").then(b=>b.bn);return{default:m}},__vite__mapDeps([0,1]))).default;d.initialize({startOnLoad:!1,securityLevel:"loose",theme:l==="dark"?"dark":"default",fontFamily:"ui-sans-serif, system-ui, -apple-system, sans-serif",flowchart:{htmlLabels:!1,useMaxWidth:!1}});const p=await d.render(`mermaid-${t}`,e),f=Aq(p.svg).replace(/(<svg[^>]*?)\s+width="[^"]*"/,'$1 width="100%"').replace(/(<svg[^>]*?)\s+height="[^"]*"/,'$1 height="auto"');u||s(f)}catch{u||o(!0)}})(),()=>{u=!0}},[e,t,l]),h.useEffect(()=>{n.current&&(n.current.innerHTML=r??"")},[r]),i?a.jsx("pre",{className:"text-xs font-mono p-3 bg-spur-surface-2 rounded border border-spur-border overflow-x-auto",children:a.jsx("code",{children:e})}):a.jsx("div",{ref:n,className:"mermaid-diagram","data-testid":"mermaid-diagram"})}function _q(e){return(e??"").match(/language-(\w+)/)?.[1]??null}function Vi(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(Vi).join(""):typeof e=="object"&&"props"in e?Vi(e.props.children):""}function Bx({className:e,children:t,...n}){return _q(e)==="mermaid"?a.jsx(Cq,{code:Vi(t).trim()}):a.jsx("code",{className:e,...n,children:t})}function Ck({source:e,className:t,style:n}){return a.jsx(wa.Markdown,{source:e,className:t,style:n,wrapperElement:{"data-color-mode":"light"},...Ta,components:{code:Bx}})}function Iq(e){if(!e)return[];const t=e.split(/\r?\n/),n=[],r=new Map;let s=!1;for(const i of t){if(i.trim().startsWith("```")){s=!s;continue}if(s)continue;const l=i.match(/^(#{1,6})\s+(.+)$/);if(l?.[1]&&l[2]){const c=l[1].length,d=l[2].trim().replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim(),f=d.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-")||`heading-${n.length+1}`,m=r.get(f)??0;r.set(f,m+1);const b=m===0?f:`${f}-${m}`;n.push({id:b,text:d,level:c})}}return n}function Rq(){const e=new Map;return{nextId(t){const r=t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-")||"heading",s=e.get(r)??0;return e.set(r,s+1),s===0?r:`${r}-${s}`}}}function Dq({markdown:e,scrollContainerRef:t,onClose:n}){const r=h.useMemo(()=>Iq(e),[e]),[s,i]=h.useState(null);h.useEffect(()=>{const l=t?.current;if(!l||r.length===0)return;const c=()=>{const u=l.getBoundingClientRect().top;let d=null;for(const p of r){const f=document.getElementById(p.id);f&&f.getBoundingClientRect().top-u<=100&&(d=p.id)}d&&i(d)};return l.addEventListener("scroll",c,{passive:!0}),c(),()=>l.removeEventListener("scroll",c)},[r,t]);const o=l=>{i(l);const c=document.getElementById(l);c&&c.scrollIntoView({behavior:"smooth",block:"start"})};return a.jsxs("aside",{id:"design-toc-dock","aria-label":"Table of Contents",className:"w-64 lg:w-72 shrink-0 rounded-lg border border-spur-border bg-base-200 shadow-xs flex flex-col overflow-hidden 3xl:absolute 3xl:top-0 3xl:bottom-0 3xl:left-[calc(100%_+_12px)] 3xl:z-20 3xl:w-72 4xl:w-80 3xl:shadow-xl","data-testid":"design-toc-dock",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border bg-base-300/60 shrink-0",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text flex items-center gap-1.5",children:[a.jsx("span",{children:"📑"})," Table of Contents"]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[r.length>0&&a.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-spur-accent/15 text-spur-accent font-semibold",children:r.length}),n&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent h-5 w-5 p-0 text-xs flex items-center justify-center cursor-pointer",onClick:n,"aria-label":"Close table of contents",title:"Close table of contents",children:"✕"})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-1.5 space-y-0.5",children:r.length===0?a.jsx("div",{className:"p-3 text-xs text-spur-text-muted italic",children:"No headings in document."}):r.map(l=>{const c=s===l.id;let u="pl-2 text-xs font-semibold";return l.level===2?u="pl-4 text-xs font-medium":l.level===3?u="pl-6 text-xs text-spur-text-muted":l.level>=4&&(u="pl-8 text-[11px] text-spur-text-muted"),a.jsx("button",{type:"button",onClick:()=>o(l.id),title:l.text,className:`w-full text-left py-1 pr-2 rounded transition-colors truncate block cursor-pointer ${u} ${c?"bg-spur-accent/15 text-spur-accent font-semibold":"hover:bg-base-300 hover:text-spur-text text-spur-text/80"}`,children:l.text},l.id)})})]})}function Oq({source:e,className:t}){const n=Px(e),r=Rq(),s=o=>{const l=`h${o}`;return({children:c,...u})=>{const p=Vi(c).trim().replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim(),f=r.nextId(p);return a.jsx(l,{id:f,className:"scroll-mt-6 group",...u,children:c})}},i={code:Bx,h1:s(1),h2:s(2),h3:s(3),h4:s(4),h5:s(5),h6:s(6)};return a.jsx("div",{className:`design-markdown-container ${t??""}`,"data-testid":"design-markdown-body",children:a.jsx(wa.Markdown,{source:n,wrapperElement:{"data-color-mode":"light"},...Ta,components:i})})}function Lq(){const[e,t]=Ca(),[n,r]=h.useState(null),[s,i]=h.useState(()=>e.get("file")),o=h.useRef({}),[l,c]=h.useState({}),[u,d]=h.useState(!0),[p,f]=h.useState(!0),[m,b]=h.useState(!1),[x,y]=h.useState(!0),[E,A]=h.useState(!1),[w,N]=h.useState(null),[_,k]=h.useState(null),[S,v]=h.useState(!1),O=h.useRef(null),C=h.useRef(null),M=h.useCallback(async I=>{try{y(!0);const V=await IG(I);return r(V),N(null),V}catch(V){return I?.aborted||N(V instanceof Error?V.message:String(V)),null}finally{y(!1)}},[]),B=h.useCallback(async(I,V)=>{if(!o.current[I])try{A(!0),k(null);const te=await RG(I,V);o.current[I]=te,c(L=>({...L,[I]:te}))}catch(te){if(V?.aborted)return;k(te instanceof Error?te.message:String(te))}finally{A(!1)}},[]),R=e.get("file");h.useEffect(()=>{const I=new AbortController;return(async()=>{const V=await M(I.signal);if(V&&V.length>0){if(R&&V.some(L=>L.path===R))i(R);else if(!R){const L=V[0]?.path;L&&i(L)}}})(),()=>I.abort()},[M,R]),h.useEffect(()=>{R&&R!==s&&i(R)},[R,s]),h.useEffect(()=>{if(!s)return;const I=new AbortController;return B(s,I.signal),()=>I.abort()},[s,B]);const z=I=>{i(I),f(!0),t({file:I},{replace:!0}),O.current&&(O.current.scrollTop=0)},W=()=>{s&&(navigator.clipboard.writeText(s),v(!0),setTimeout(()=>v(!1),2e3))},F=s?l[s]:null,{frontmatterRaw:J,frontmatter:K,body:X}=h.useMemo(()=>F?.content?wk(F.content):{frontmatterRaw:null,frontmatter:null,body:""},[F?.content]);return w?a.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load design documents: ",w]}):x&&n===null?a.jsx("div",{className:"flex items-center justify-center h-full text-spur-text-muted text-sm",children:"Loading design documents…"}):a.jsxs("div",{className:"relative h-full w-full p-4 overflow-hidden","data-designs-shell":!0,children:[a.jsxs("div",{className:"flex flex-col h-full w-full max-w-full 3xl:max-w-[1200px] 4xl:max-w-[1600px] mx-auto gap-3","data-designs-workspace":!0,children:[a.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-spur-border pb-3 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rr,{id:"designs",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight text-spur-text",children:"Designs"}),a.jsx("p",{className:"text-xs text-spur-text-muted",children:"Design documents, architecture specifications, and surface contracts"})]})]}),a.jsxs("div",{className:"flex items-center gap-1","data-designs-actions":!0,children:[a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>d(I=>!I),"aria-label":u?"Collapse design file list":"Expand design file list","aria-expanded":u,"aria-controls":"design-files-dock",title:u?"Collapse design file list":"Expand design file list",children:u?"◧":"▶"}),s&&F?.content&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>f(I=>!I),"aria-label":p?"Collapse table of contents":"Expand table of contents","aria-expanded":p,"aria-controls":"design-toc-dock",title:p?"Collapse table of contents":"Expand table of contents",children:p?"📑":"📖"}),a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>{(async()=>(await M(),s&&(c(I=>{const V={...I};return delete V[s],V}),B(s))))()},"aria-label":"Refresh design documents",title:"Refresh design documents",children:"🔄"})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-stretch gap-3 overflow-hidden 3xl:relative 3xl:block 3xl:overflow-visible",ref:C,children:[a.jsxs("div",{id:"design-files-dock",hidden:!u,className:`${u?"flex":"hidden"} w-64 lg:w-72 shrink-0 flex-col overflow-hidden rounded-lg border border-spur-border bg-base-200 shadow-xs 3xl:absolute 3xl:right-[calc(100%_+_12px)] 3xl:top-0 3xl:bottom-0 3xl:z-20 3xl:w-72 4xl:w-80 3xl:shadow-xl`,"data-testid":"design-files-dock",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border bg-base-300/60 shrink-0",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text flex items-center gap-1.5",children:[a.jsx("span",{children:"📐"})," Design Docs"]}),n&&n.length>0&&a.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-spur-accent/15 text-spur-accent font-semibold",children:n.length})]}),a.jsx("div",{className:"flex-1 overflow-hidden",children:n&&n.length>0?a.jsx(HW,{files:n,selectedPath:s,onSelect:z}):a.jsx("div",{className:"p-3 text-xs text-spur-text-muted italic",children:"No design documents found."})})]}),a.jsx("div",{className:"flex-1 min-w-0 h-full overflow-hidden rounded-lg border border-spur-border bg-base-100 relative 3xl:w-full 3xl:flex-none","data-testid":"design-workspace",children:a.jsx("div",{className:"w-full h-full overflow-y-auto",ref:O,children:s?a.jsxs("div",{className:"flex flex-col min-h-full",children:[a.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-6 py-3 border-b border-spur-border bg-base-100/90 backdrop-blur-xs",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-base-200 text-spur-text-muted border border-spur-border shrink-0",children:s}),F?.title&&a.jsx("h2",{className:"text-sm font-semibold text-spur-text truncate",children:F.title})]}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent flex items-center gap-1 shrink-0",onClick:()=>b(!0),"aria-label":"View document metadata",title:"View document metadata","data-testid":"metadata-toggle",children:"ℹ Metadata"}),a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-text shrink-0",onClick:W,"aria-label":"Copy file path",title:"Copy file path",children:S?"✓ Copied":"📋 Copy Path"})]})]}),a.jsx("div",{className:"p-6 md:p-8 flex-1","data-testid":"design-body-container",children:E&&!F?a.jsx("div",{className:"flex items-center justify-center py-20 text-spur-text-muted text-sm",children:"Loading document content…"}):_?a.jsxs("div",{className:"p-4 text-sm text-error bg-error/10 rounded-md border border-error/20",children:["Failed to load document: ",_]}):F?a.jsx(Oq,{source:X}):null})]}):a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-spur-text-muted gap-2",children:[a.jsx("span",{className:"text-3xl","aria-hidden":"true",children:"📐"}),a.jsx("span",{className:"text-sm font-medium",children:"Select a design document to view"})]})})}),s&&F?.content&&p&&a.jsx(Dq,{markdown:X,scrollContainerRef:O,onClose:()=>f(!1)})]})]}),a.jsx(NT,{open:m,onClose:()=>b(!1),title:F?.title,filePath:s,frontmatterRaw:J,frontmatter:K})]})}const jq={id:"designs",name:"Designs",icon:"📐",route:"designs",component:Lq,sidebarLabel:"Designs",description:"Design documents, architecture specifications, and surface contracts",order:25},Mq=Object.freeze(Object.defineProperty({__proto__:null,module:jq},Symbol.toStringTag,{value:"Module"})),br=()=>`${it()}/features`;async function Fq(e){const t=await Xe(new Request(br(),{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 T1(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e)}`,{signal:t}));if(!n.ok)throw new Error(`feature show fetch failed: ${n.status}`);const s=await n.json();if(!s.ok||!s.data)throw new Error("feature show: invalid response shape");return s.data}async function Pq(e,t,n){const r=await Xe(new Request(`${br()}/${encodeURIComponent(e)}/status`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,toStatus:t}),signal:n})),s=await r.json();if(!r.ok){const o=s;throw new Error(o.error?.message??`transition failed: ${r.status}`)}return s.data?.status??t}async function Bq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/body`,{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??`body update failed: ${n.status}`)}}async function $q(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/action`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`action dispatch failed: ${n.status}`)}return await n.json()}async function _k(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/children`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`create child failed: ${n.status}`)}return await n.json()}async function Uq(e,t){const n=await Xe(new Request(br(),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:e}),signal:t}));if(!n.ok){const o=await n.json();throw new Error(o.error?.message??`create feature failed: ${n.status}`)}const s=await n.json();if(!s.ok||!s.data)throw new Error("create feature: invalid response shape");return s.data}async function zq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/tasks`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`create task failed: ${n.status}`)}return await n.json()}async function Hq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/link`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`link task failed: ${n.status}`)}return await n.json()}async function Gq(e,t){const n=await Xe(new Request(`${br()}/${encodeURIComponent(e.id)}/sync`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:t}));if(!n.ok){const i=await n.json();throw new Error(i.error?.message??`sync failed: ${n.status}`)}return await n.json()}const nc=new Set,rc=new Set;let ls,$x=!1;function k1(e){$x=e;for(const t of rc)t(e)}function Ik(){if(ls||typeof window>"u"||typeof EventSource>"u")return;const e=new EventSource(`${it()}/events/planning`);ls=e,e.onopen=()=>{ls===e&&k1(!0)},e.onerror=()=>{ls===e&&k1(!1)},e.onmessage=t=>{if(ls!==e)return;let n;try{n=JSON.parse(t.data)}catch{return}if(!n||typeof n!="object"||Array.isArray(n))return;const{eventName:r,payload:s}=n;if(typeof r!="string"||!["task.","feature.","queue.job."].some(o=>r.startsWith(o)))return;const i={eventName:r,payload:s};for(const o of nc)o(i)}}function Rk(){if(nc.size||rc.size)return;const e=ls;ls=void 0,$x=!1,e&&(e.onmessage=null,e.onopen=null,e.onerror=null,e.close())}function mu(e){const t=n=>e(n);return nc.add(t),Ik(),()=>{nc.delete(t),Rk()}}function Dk(e){const t=n=>e(n);return rc.add(t),e($x),Ik(),()=>{rc.delete(t),Rk()}}function ka({targetVar:e,onResizeEnd:t,direction:n="horizontal",invert:r=!1}){const s=h.useRef(null),i=h.useCallback(l=>{l.preventDefault();const c=document.documentElement,d=getComputedStyle(c).getPropertyValue(e).trim(),p=parseFloat(d)||0;s.current={x:l.clientX,y:l.clientY,w:p},l.target.setPointerCapture(l.pointerId);const f=b=>{if(!s.current)return;const x=n==="horizontal"?b.clientX-s.current.x:b.clientY-s.current.y,y=r?-x:x,E=Math.max(0,s.current.w+y);c.style.setProperty(e,`${E}px`)},m=()=>{if(!s.current)return;const b=getComputedStyle(c).getPropertyValue(e).trim(),x=parseFloat(b)||s.current.w;t(Math.round(x)),s.current=null,window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",m)};window.addEventListener("pointermove",f),window.addEventListener("pointerup",m,{once:!0})},[e,t,n,r]),o=n==="horizontal";return a.jsx("hr",{"data-testid":`resize-handle-${o?"h":"v"}`,"aria-orientation":o?"vertical":"horizontal","aria-label":o?"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:o?4:"100%",height:o?"100%":4,margin:0},onPointerDown:i})}const A1="spur:new-task-panel-width",C1=384,hd=384;function _1({id:e,label:t,placeholder:n,value:r,mode:s,onChange:i,onModeChange:o,disabled:l}){return a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[a.jsxs("label",{htmlFor:e,className:"text-xs font-semibold text-spur-text-muted uppercase tracking-wide",children:[t," ",a.jsx("span",{className:"text-spur-text-muted font-normal",children:"(optional, markdown)"})]}),a.jsxs("fieldset",{className:"flex items-center gap-1",children:[a.jsxs("legend",{className:"sr-only",children:[t," mode"]}),a.jsx(Ie,{type:"button",variant:s==="edit"?"primary":"ghost",size:"xs",onClick:()=>o("edit"),disabled:l,"aria-pressed":s==="edit",children:"Edit"}),a.jsx(Ie,{type:"button",variant:s==="preview"?"primary":"ghost",size:"xs",onClick:()=>o("preview"),disabled:l,"aria-pressed":s==="preview",children:"Preview"})]})]}),s==="edit"?a.jsx("div",{className:"min-h-40","data-testid":`${e}-editor`,children:a.jsx(wa,{value:r,onChange:c=>i(c??""),height:160,textareaProps:{id:e,placeholder:n,disabled:l,"aria-label":t},"data-color-mode":"dark",previewOptions:Ta})}):a.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()?a.jsx(wa.Markdown,{source:r,"data-color-mode":"dark",...Ta}):a.jsx("p",{className:"text-xs text-spur-text-muted",children:n})})]})}function Ok({open:e,onClose:t,onCreated:n,folder:r,featureId:s}){const[i,o]=h.useState(""),[l,c]=h.useState(""),[u,d]=h.useState(""),[p,f]=h.useState("edit"),[m,b]=h.useState("edit"),[x,y]=h.useState("standard"),[E,A]=h.useState(!1),[w,N]=h.useState(""),[_,k]=h.useState(!1),[S,v]=h.useState(()=>{if(typeof window>"u")return C1;try{const B=Number.parseFloat(window.localStorage.getItem(A1)??"");if(Number.isFinite(B)&&B>0)return Math.max(hd,Math.min(B,window.innerWidth*.9))}catch{}return C1}),O=_&&i.trim()===""?"Name is required":"";h.useEffect(()=>{document.documentElement.style.setProperty("--new-task-panel-w",`${S}px`)},[S]);const C=()=>{E||(o(""),c(""),d(""),f("edit"),b("edit"),y("standard"),N(""),k(!1),t())},M=async()=>{k(!0);const B=i.trim();if(B!==""){A(!0),N("");try{const z=(await xt.task.create({title:B,folder:r,template:x,featureId:s})).data.wbs,W=[];if(l.trim()&&W.push(`### Background
298
298
  ${l.trim()}`),u.trim()&&W.push(`### Requirements
299
299
  ${u.trim()}`),W.length>0)try{await xt.task.body({wbs:z,body:W.join(`
300
300
 
@@ -307,7 +307,7 @@ ${u.trim()}`),W.length>0)try{await xt.task.body({wbs:z,body:W.join(`
307
307
  `),n=[];let r=!1,s=0;for(let i=0;i<t.length;i++){const o=t[i]??"",l=`md-line-${s++}-${o.slice(0,16)}`,c=o.trim();if(c==="---"){r=i===0?!0:!r,n.push(a.jsx("div",{className:"text-purple-400 font-bold leading-5",children:o},l));continue}if(r){const m=o.indexOf(":");if(m>0){const b=o.slice(0,m),x=o.slice(m+1);n.push(a.jsxs("div",{className:"leading-5",children:[a.jsx("span",{className:"text-cyan-300 font-semibold",children:b}),a.jsx("span",{className:"text-base-content/50",children:":"}),a.jsx("span",{className:"text-emerald-300",children:x})]},l));continue}n.push(a.jsx("div",{className:"text-slate-300 leading-5",children:o||" "},l));continue}if(c.startsWith("```")){n.push(a.jsx("div",{className:"text-pink-400 font-mono font-semibold leading-5",children:o},l));continue}if(c.startsWith("#")){n.push(a.jsx("div",{className:"text-sky-300 font-bold leading-5",children:o},l));continue}if(c.startsWith(">")){n.push(a.jsx("div",{className:"text-emerald-300/80 italic pl-1.5 border-l border-emerald-500/40 leading-5",children:o},l));continue}const u=o.match(/^(\s*[-*+]|\s*\d+\.)/);if(u){n.push(a.jsxs("div",{className:"leading-5",children:[a.jsx("span",{className:"text-amber-300 font-semibold",children:u[0]}),a.jsx("span",{className:"text-slate-100",children:o.slice(u[0].length)})]},l));continue}const d=o.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g),p=[];let f=0;for(const m of d){const b=`${l}-p-${f++}`;m.startsWith("`")&&m.endsWith("`")?p.push(a.jsx("span",{className:"text-emerald-300 bg-white/10 px-1 rounded font-mono",children:m},b)):m.startsWith("**")&&m.endsWith("**")?p.push(a.jsx("span",{className:"text-amber-200 font-bold",children:m},b)):m.startsWith("[")&&m.includes("](")&&m.endsWith(")")?p.push(a.jsx("span",{className:"text-sky-400 underline",children:m},b)):p.push(a.jsx("span",{className:"text-slate-100",children:m},b))}n.push(a.jsx("div",{className:"leading-5",children:p.length>0?p:" "},l))}return n};function vV(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(`
308
308
  `)[0]?.trim()==="---"?"markdown":"text":"text"}function yd(e,t){if(!e)return null;switch(vV(e,t)){case"bash":return ac(e);case"xml":return SV(e);case"json":{const r=t?Yk(t):{defaultLanguage:"json"};return Xk(e,r)}case"markdown":return wV(e);default:return e}}const NV=({code:e,toolName:t="",language:n,className:r=""})=>{const s=h.useMemo(()=>Yk(t),[t]),i=n??s.defaultLanguage,o=h.useMemo(()=>i==="bash"?ac(e):i==="diff"?Zk(e):Xk(e,s),[e,i,s]);return a.jsx("div",{className:`font-mono text-[11px] select-text cursor-text ${r}`,children:o})},TV=({agentId:e,model:t="—",timestamp:n,tooltipId:r,freshInputTokens:s=0,cacheReadTokens:i=0,outputTokens:o=0,sessionId:l,className:c=""})=>{const[u,d]=h.useState(!1),p=h.useMemo(()=>`agent-badge-tt-${e}-${Math.random().toString(36).slice(2,7)}`,[e]),f=r||p,m=s+i+o;return a.jsxs("div",{className:`relative inline-flex items-center z-30 ${c}`,children:[a.jsx("button",{type:"button","aria-describedby":f,"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-${f}`,children:a.jsx(pr,{id:e})}),u&&a.jsxs("div",{id:f,role:"tooltip","data-testid":f,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:[a.jsx("div",{className:"flex items-center justify-between border-b border-base-content/10 pb-2",children:a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"p-1 rounded bg-base-200 text-primary shrink-0",children:a.jsx(pr,{id:e})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("div",{className:"font-bold text-base-content uppercase tracking-wider text-[11px]",children:e}),a.jsx("div",{className:"text-[10px] text-base-content/60 truncate",title:t??"",children:t||"—"})]})]})}),a.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-1 text-base-content/80 text-[10.5px]",children:[a.jsx("span",{className:"text-base-content/50",children:"Timestamp:"}),a.jsx("span",{className:"truncate",children:n?yV(n):"—"}),l&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-base-content/50",children:"Session:"}),a.jsx("span",{className:"truncate font-bold text-primary",title:l,children:l.length>16?`${l.slice(0,14)}…`:l})]})]}),a.jsxs("div",{className:"pt-2 border-t border-base-content/10 flex flex-col gap-1 text-[10.5px]",children:[a.jsx("div",{className:"font-bold text-base-content/70 text-[10px] uppercase tracking-wider",children:"Token Breakdown"}),a.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80",children:[a.jsx("span",{className:"text-base-content/50",children:"📥 Fresh input:"}),a.jsx("span",{children:Tr(s)}),a.jsx("span",{className:"text-base-content/50",children:"💾 Cache read:"}),a.jsx("span",{className:"text-cyan-400",children:Tr(i)}),a.jsx("span",{className:"text-base-content/50",children:"📤 Output:"}),a.jsx("span",{children:Tr(o)}),a.jsx("span",{className:"text-base-content/50 border-t border-base-content/10 pt-0.5",children:"⚡ Total load:"}),a.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Tr(m)})]})]})]})]})},Gx=({item:e,categoryColor:t,label:n,badgePrefix:r,size:s="sm",className:i="",testId:o,tooltipId:l,onClick:c})=>{const[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,b]=h.useState(!1),[x,y]=h.useState(!1),E=h.useRef(null),A=e.category??Kk(e.toolName),w=t??sc[A]??sc.other,N=e.seq??e.toolSeq??1,_=l||`tool-tooltip-${N}-${e.toolName}`,k=h.useMemo(()=>{if(!e.argsRaw)return null;try{const J=JSON.parse(e.argsRaw);return JSON.stringify(J,null,2)}catch{return e.argsRaw}},[e.argsRaw]),S=async J=>{if(J.stopPropagation(),!!k)try{await navigator.clipboard.writeText(k),b(!0),setTimeout(()=>b(!1),2e3)}catch{}},v=async J=>{if(J.stopPropagation(),!!e.errorText)try{await navigator.clipboard.writeText(e.errorText),y(!0),setTimeout(()=>y(!1),2e3)}catch{}},O=()=>{E.current&&(clearTimeout(E.current),E.current=null)},C=()=>{O(),d(!0)},M=()=>{p||(O(),E.current=setTimeout(()=>{d(!1)},150))},B=J=>{J.stopPropagation(),f(K=>!K),d(!0),c?.(J)},R=u||p,z=e.status==="error",W=s==="xs"?"px-1.5 py-0.2 text-[10px]":s==="md"?"px-2.5 py-1 text-xs":"px-2 py-0.5 text-[11px]",F=n??`${r??""}${e.toolName}`;return a.jsxs("div",{className:`relative inline-flex items-center ${i}`,children:[a.jsx("button",{type:"button","aria-describedby":_,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:w},onClick:B,onMouseEnter:C,onMouseLeave:M,onFocus:()=>{O(),d(!0)},onBlur:()=>{p||d(!1)},onKeyDown:J=>{J.key==="Escape"&&(f(!1),d(!1))},"data-testid":o??`tool-tag-${N}`,children:F}),a.jsxs("div",{id:_,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 ${R?"block":"hidden"}`,onMouseEnter:()=>{O(),d(!0)},onMouseLeave:M,onClick:J=>J.stopPropagation(),onKeyDown:J=>{J.key==="Escape"&&(f(!1),d(!1)),J.stopPropagation()},children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-base-content/10 pb-2.5",children:[a.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[a.jsx("span",{className:"px-2.5 py-0.5 rounded-md text-xs font-bold text-white shrink-0 tracking-wide",style:{backgroundColor:w},children:e.toolName}),a.jsxs("span",{className:"text-xs text-base-content/50 font-bold",children:["#",N]}),a.jsxs("span",{className:"text-[11px] text-base-content/60 uppercase tracking-wider",children:["(",A,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsx("span",{className:`px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider ${z?"bg-error/20 text-error":"bg-success/20 text-success"}`,children:e.status??"ok"}),p&&a.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:J=>{J.stopPropagation(),f(!1),d(!1)},title:"Close tooltip",children:"✕"})]})]}),e.errorText&&a.jsxs("div",{className:"bg-error/10 text-error border border-error/20 rounded-lg p-2.5 text-xs",children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("span",{className:"font-bold",children:"Execution Error:"}),a.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:v,children:x?"✓ Copied":"Copy"})]}),a.jsx("pre",{className:"font-mono text-[11px] whitespace-pre-wrap max-h-36 overflow-y-auto",children:e.errorText})]}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"text-[11px] font-semibold text-base-content/70",children:["Arguments (raw)"," ",a.jsx("span",{className:"text-base-content/40 font-normal",children:"(syntax-highlighted)"})]}),k&&a.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:S,children:m?"✓ Copied":"Copy"})]}),k?a.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:a.jsx(NV,{code:k,toolName:e.toolName})}):a.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&&a.jsxs("div",{className:"text-[10px] text-base-content/50 truncate mt-0.5",children:[a.jsx("span",{className:"font-semibold",children:"Digest: "}),e.argsDigest]})]}),a.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:[a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"DURATION"}),a.jsx("span",{className:"text-[11px]",children:e.durationMs!==null&&e.durationMs!==void 0?`${e.durationMs} ms (${e.durationSource??"measured"})`:`— (${e.durationSource??"unmeasured"})`})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"TIMESTAMP"}),a.jsx("span",{className:"text-[11px] truncate block",children:e.ts??"—"})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"SOURCE / MODEL"}),a.jsxs("span",{className:"text-[11px] truncate block",title:`${e.source??"—"} / ${e.model??"—"}`,children:[e.source??"—"," / ",e.model??"—"]})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"SESSION ID"}),a.jsx("span",{className:"text-[11px] truncate block",title:e.sessionId??"—",children:e.sessionId??"—"})]}),e.callId&&a.jsxs("div",{className:"col-span-2 md:col-span-4",children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"CALL ID"}),a.jsx("span",{className:"text-[11px] truncate block",title:e.callId,children:e.callId})]}),e.tokens&&a.jsxs("div",{className:"col-span-2 md:col-span-4 pt-1 border-t border-base-content/10",children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"TOKEN LOAD (SHARE)"}),a.jsxs("span",{className:"text-[11px]",children:["Billed: ",Tr(e.tokens.billedTokens)," (Fresh:"," ",Tr(e.tokens.freshInputTokens),", Cache:"," ",Tr(e.tokens.cacheReadTokens),", Output:"," ",Tr(e.tokens.outputTokens),")"]})]})]})]})]})},kV=Gx,AV=({calls:e,fromSeq:t=1,toSeq:n=1,toolName:r,sessionId:s,maxVisible:i=12,className:o=""})=>{const[l,c]=h.useState(!1),u=h.useMemo(()=>{if(e&&e.length>0)return e;const f=[],m=Math.max(1,n-t+1);for(let b=0;b<m;b++)f.push({seq:t+b,toolSeq:t+b,toolName:r,sessionId:s,category:Kk(r),status:"ok"});return f},[e,t,n,r,s]),d=l?u:u.slice(0,i),p=u.length-d.length;return a.jsxs("div",{className:`flex flex-wrap items-center gap-1.5 ${o}`,children:[d.map(f=>a.jsx(Gx,{item:f,label:`#${f.seq}`,size:"xs"},`${f.sessionId}-${f.seq}-${f.callId??""}`)),p>0&&a.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:()=>c(!0),children:["+",p," more"]}),l&&u.length>i&&a.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:()=>c(!1),children:"Show less"})]})};function j1(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 Qk=({data:e,loading:t,error:n,cacheHitTrend:r,onSelectSession:s})=>{const[i,o]=h.useState("model"),[l,c]=h.useState("asc"),u=h.useMemo(()=>({"claude-opus-4.6":"#3987e5","claude-sonnet-4.6":"#199e70","gpt-5.6-sol":"#9085e9","grok-4.6":"#d95926",other:"#898781"}),[]),d=h.useMemo(()=>["Speed","Cache Ratio","Reliability","Output Ratio"],[]);if(t)return a.jsxs("div",{className:"flex flex-col items-center justify-center p-20 gap-3",children:[a.jsx("div",{className:"w-9 h-9 rounded-full border-3 border-primary border-t-transparent animate-spin"}),a.jsx("span",{className:"text-xs font-mono text-base-content/60",children:"Analyzing operational insights..."})]});if(n)return a.jsxs("div",{className:"p-5 rounded-xl bg-error/10 border border-error/20 text-error flex items-center gap-3",children:[a.jsx("span",{className:"text-lg",children:"⚠️"}),a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-sm",children:"Failed to load insights"}),a.jsx("p",{className:"text-xs opacity-80",children:n})]})]});if(!e)return null;const{loops:p,cacheWaste:f,heavySessions:m,largestTokenSteps:b,slowSteps:x,modelComparison:y}=e,E=F=>{i===F?c(J=>J==="asc"?"desc":"asc"):(o(F),c(F==="model"?"asc":"desc"))},A=[...y].sort((F,J)=>{const K=l==="asc"?1:-1;return i==="model"?K*F.model.localeCompare(J.model):K*((F[i]??0)-(J[i]??0))}),w=F=>i!==F?a.jsx("span",{className:"opacity-30 ml-1 text-[10px]",children:"↕"}):a.jsx("span",{className:"text-primary ml-1 text-[10px]",children:l==="asc"?"▲":"▼"}),N=Math.max(1,...m.map(F=>F.tokens)),_=Math.max(1,...x.map(F=>F.durationMs??0)),k=p.reduce((F,J)=>F+(J.wastedTokens??0),0),S=f.reduce((F,J)=>F+(J.freshTokens??0),0),v=x[0],O=b[0],C=y.map(F=>F.speedMsMean),M=C.length>0?Math.min(...C):0,B=C.length>0?Math.max(...C):0,R=F=>B===M?100:Math.max(0,Math.min(100,Math.round((B-F)/(B-M)*100))),z=F=>Math.max(0,Math.min(100,Math.round(F*100))),W=y.map(F=>{const J=R(F.speedMsMean),K=z(F.cacheRatio),X=z(F.reliability),I=z(F.outputRatio*5);return{label:F.model,color:u[F.model]??"#3987e5",values:[J,K,X,I]}});return a.jsxs("div",{className:"flex flex-col gap-6",children:[a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.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:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Loop Anomalies"}),a.jsx("span",{children:p.length>0?"⚠️":"✓"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsxs("div",{className:"text-xl font-bold font-mono",children:[p.length," ",p.length===1?"incident":"incidents"]}),a.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:p.length>0?`${Be(k)} wasted tokens`:"Clean execution"})]})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Cache Waste"}),a.jsx("span",{className:"text-cyan-400",children:"⚡"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsx("div",{className:"text-xl font-bold font-mono text-error",children:Be(S)}),a.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Across ",f.length," un-cached steps"]})]})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Peak Step Tokens"}),a.jsx("span",{className:"text-primary",children:"📊"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsx("div",{className:"text-xl font-bold font-mono text-primary",children:O?Be(O.tokens):"—"}),a.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5 truncate",children:O?`${O.toolName} (#${O.stepIndex})`:"No outlier steps"})]})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Peak Latency"}),a.jsx("span",{className:"text-amber-400",children:"⏱️"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsx("div",{className:"text-xl font-bold font-mono text-amber-400",children:v?.durationMs?sa(v.durationMs):"—"}),a.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5 truncate",children:v?`${v.toolName} (#${v.stepIndex})`:"No slow steps"})]})]})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col justify-between",children:a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("h4",{className:"font-bold text-sm",children:"Top Cache-Wasting Incidents"}),a.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[f.length," incidents"]})]}),a.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Steps that re-sent full context without cache hits"}),a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-3 items-start",children:[(r?.length??0)>1&&a.jsxs("div",{"data-testid":"cache-hit-trend-chart",className:"p-3 bg-base-300/40 rounded-xl border border-base-content/5",children:[a.jsx("div",{className:"text-[10px] font-mono text-base-content/60 uppercase tracking-wider mb-2",children:"Cache Hit Ratio Trend"}),a.jsx(mV,{points:(r??[]).map(F=>({id:F.day,label:F.day.slice(5),v:F.cacheHitRatio})),color:"#22d3ee",height:130})]}),a.jsx("div",{className:"overflow-x-auto w-full",children:f.length>0?a.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{className:"py-1.5",children:"Session"}),a.jsx("th",{className:"py-1.5 text-right",children:"Fresh Tokens"}),a.jsx("th",{className:"py-1.5 pl-3",children:"Cause"})]})}),a.jsx("tbody",{children:f.map(F=>a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[a.jsx("td",{className:"py-1.5",children:a.jsxs("button",{type:"button",className:"text-primary hover:underline font-mono inline-flex items-center gap-1 cursor-pointer",onClick:()=>s?.(F.sessionId),title:`Jump to session ${F.sessionId}`,children:[a.jsx("span",{children:F.sessionId}),a.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),a.jsx("td",{className:"py-1.5 text-right text-error font-bold whitespace-nowrap",children:Be(F.freshTokens)}),a.jsx("td",{className:"py-1.5 pl-3 text-base-content/70 truncate max-w-[140px]",title:F.reason,children:F.reason})]},`${F.sessionId}-${F.freshTokens}-${F.timestamp}`))})]}):a.jsx("div",{className:"p-6 text-center text-xs font-mono text-base-content/50",children:"✓ No cache-wasting incidents detected"})})]})]})}),a.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col justify-between",children:a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("h4",{className:"font-bold text-sm",children:"Heaviest Token Sessions"}),a.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[m.length," sessions"]})]}),a.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Sessions consuming highest billed volume"}),a.jsx("div",{className:"flex flex-col gap-3",children:m.length>0?m.map(F=>a.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:[a.jsxs("div",{className:"flex justify-between items-center text-xs font-mono",children:[a.jsxs("button",{type:"button",className:"text-primary hover:underline font-bold inline-flex items-center gap-1.5 cursor-pointer text-left",onClick:()=>s?.(F.id,F.source),title:`Jump to session ${F.id}`,children:[a.jsx("span",{children:F.id}),a.jsxs("span",{className:"text-[10px] font-normal px-1.5 py-0.2 rounded bg-base-content/10 text-base-content/70",children:[F.source," · ",F.model]}),a.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]}),a.jsx("span",{className:"font-bold",children:Be(F.tokens)})]}),a.jsx(Ii,{value:F.tokens,max:N,color:"#3987e5",height:6})]},F.id)):a.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No heavy sessions recorded in this timeframe"})})]})})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("h4",{className:"font-bold text-sm",children:"Top Time-Consuming Steps"}),a.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"]})]}),a.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Longest tool execution durations"}),a.jsx("div",{className:"overflow-x-auto",children:x.length>0?a.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{className:"py-1.5",children:"Tool / Step"}),a.jsx("th",{className:"py-1.5",children:"Session"}),a.jsx("th",{className:"py-1.5 text-right",children:"Duration"}),a.jsx("th",{className:"py-1.5 text-right",children:"Tokens"})]})}),a.jsx("tbody",{children:x.map(F=>{const J=j1(F.toolName),K=aa[J]??aa.other;return a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[a.jsxs("td",{className:"py-1.5 font-bold",children:[a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[11px] border gap-1 mr-1.5 ${K}`,children:F.toolName}),a.jsxs("span",{className:"text-[10px] text-base-content/50",children:["#",F.stepIndex]})]}),a.jsx("td",{className:"py-1.5",children:a.jsxs("button",{type:"button",className:"text-primary hover:underline inline-flex items-center gap-1 cursor-pointer",onClick:()=>s?.(F.sessionId,F.agent),title:`Jump to session ${F.sessionId}`,children:[a.jsx("span",{children:F.sessionId}),a.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),a.jsx("td",{className:"py-1.5 text-right text-amber-400 font-bold w-24",children:a.jsxs("div",{className:"flex flex-col items-end gap-1",children:[a.jsx("span",{children:sa(F.durationMs??0)}),a.jsx(Ii,{value:F.durationMs??0,max:_,color:"#fbbf24",height:4})]})}),a.jsx("td",{className:"py-1.5 text-right tabular-nums",children:Be(F.tokens)})]},`${F.sessionId}-${F.toolName}-${F.stepIndex}`)})})]}):a.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No slow steps recorded"})})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("h4",{className:"font-bold text-sm",children:"Largest Token Steps"}),a.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"]})]}),a.jsx("p",{className:"text-xs text-base-content/60 mb-3",children:"Single tool calls with highest token load"}),a.jsx("div",{className:"overflow-x-auto",children:b.length>0?a.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{className:"py-1.5",children:"Tool / Step"}),a.jsx("th",{className:"py-1.5",children:"Session"}),a.jsx("th",{className:"py-1.5",children:"Agent / Model"}),a.jsx("th",{className:"py-1.5 text-right",children:"Tokens"})]})}),a.jsx("tbody",{children:b.map(F=>{const J=j1(F.toolName),K=aa[J]??aa.other;return a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30 transition-colors",children:[a.jsxs("td",{className:"py-1.5 font-bold",children:[a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[11px] border gap-1 mr-1.5 ${K}`,children:F.toolName}),a.jsxs("span",{className:"text-[10px] text-base-content/50",children:["#",F.stepIndex]})]}),a.jsx("td",{className:"py-1.5",children:a.jsxs("button",{type:"button",className:"text-primary hover:underline inline-flex items-center gap-1 cursor-pointer",onClick:()=>s?.(F.sessionId,F.agent),title:`Jump to session ${F.sessionId}`,children:[a.jsx("span",{children:F.sessionId}),a.jsx("span",{className:"text-[10px] opacity-60",children:"↗"})]})}),a.jsx("td",{className:"py-1.5 text-xs text-base-content/70",children:a.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-base-300 text-[11px]",children:[F.agent," · ",F.model]})}),a.jsx("td",{className:"py-1.5 text-right text-primary font-bold tabular-nums",children:Be(F.tokens)})]},`${F.sessionId}-${F.toolName}-${F.stepIndex}`)})})]}):a.jsx("div",{className:"p-8 text-center text-xs font-mono text-base-content/50",children:"No large token step outliers found"})})]})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5",children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("h4",{className:"font-bold text-sm",children:"Model Multi-Axis Comparison"}),a.jsxs("span",{className:"text-[11px] font-mono text-base-content/50 bg-base-300 px-2 py-0.5 rounded-full",children:[y.length," models evaluated"]})]}),a.jsx("p",{className:"text-xs text-base-content/60 mb-4",children:"Evaluation across Speed, Cache ratio, Reliability, and Output ratio"}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 items-center",children:[a.jsxs("div",{className:"flex flex-col items-center justify-center p-3 bg-base-300/30 rounded-xl border border-base-content/5",children:[a.jsx(hV,{axes:d,series:W,height:280}),a.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3 mt-3",children:W.map(F=>a.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:[a.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:F.color}}),F.label]},F.label))})]}),a.jsx("div",{className:"overflow-x-auto w-full",children:a.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsxs("th",{className:"py-2 cursor-pointer select-none hover:text-base-content",onClick:()=>E("model"),children:["Model ",w("model")]}),a.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>E("speedMsMean"),children:["Mean Speed (ms) ",w("speedMsMean")]}),a.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>E("cacheRatio"),children:["Cache Ratio ",w("cacheRatio")]}),a.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>E("reliability"),children:["Reliability ",w("reliability")]}),a.jsxs("th",{className:"py-2 text-right cursor-pointer select-none hover:text-base-content",onClick:()=>E("outputRatio"),children:["Output Ratio ",w("outputRatio")]})]})}),a.jsx("tbody",{children:A.map(F=>a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/40 transition-colors",children:[a.jsxs("td",{className:"py-2 font-bold flex items-center gap-2",children:[a.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0 shadow-xs",style:{background:u[F.model]??"#3987e5"}}),a.jsx("span",{className:"truncate",children:F.model})]}),a.jsx("td",{className:"py-2 text-right font-mono tabular-nums",children:Lt(F.speedMsMean)}),a.jsx("td",{className:"py-2 text-right font-mono tabular-nums text-cyan-400 font-bold",children:qn(F.cacheRatio*100)}),a.jsx("td",{className:`py-2 text-right font-mono tabular-nums font-bold ${F.reliability>=.95?"text-emerald-400":F.reliability>=.8?"text-amber-400":"text-error"}`,children:qn(F.reliability*100)}),a.jsx("td",{className:"py-2 text-right font-mono tabular-nums text-base-content/80",children:qn(F.outputRatio*100)})]},F.model))})]})})]})]}),p.length>0&&a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-warning/30 p-5",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-warning text-lg",children:"⚠️"}),a.jsx("h3",{className:"font-bold text-base",children:"Detected Execution Loops (Repeats ≥ 3)"})]}),a.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"]})]}),a.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."}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:p.map(F=>a.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:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between items-center",children:[a.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:[F.tool," × ",F.repeats," repeats"]}),a.jsxs("button",{type:"button",className:"text-xs font-mono text-primary hover:underline cursor-pointer inline-flex items-center gap-1 font-bold",onClick:()=>s?.(F.sessionId),title:"Jump to session in Tool Using & Timeline",children:[F.sessionId," →"]})]}),a.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:F.argsHint,children:[a.jsx("span",{className:"text-[10px] text-base-content/50 block mb-0.5 uppercase tracking-wider",children:"Argument signature"}),F.argsHint==="74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b"?"empty/unrecorded arguments":F.argsHint]}),a.jsxs("div",{className:"text-[11px] font-mono text-base-content/60 mt-2",children:["Step sequence: #",F.fromSeq," → #",F.toSeq]}),a.jsxs("div",{className:"mt-3 pt-2.5 border-t border-base-content/10",children:[a.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50 mb-1.5",children:"Repeated Invocations (hover/click for details):"}),a.jsx(AV,{calls:F.repeatedCalls,fromSeq:F.fromSeq,toSeq:F.toSeq,toolName:F.tool,sessionId:F.sessionId})]})]}),a.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:[a.jsx("span",{className:"text-base-content/60",children:"Estimated Wasted Tokens:"}),a.jsx("span",{className:"text-error font-bold text-sm",children:Be(F.wastedTokens)})]})]},`${F.tool}-${F.sessionId}-${F.fromSeq}`))})]})]})};function CV(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 Jk=({data:e,loading:t,error:n,sortBy:r="start",sortDir:s="desc",page:i=1,pageSize:o=20,onSortChange:l,onPageChange:c,onSelectSession:u})=>{const[d,p]=h.useState(""),[f,m]=h.useState("all");if(t)return a.jsxs("div",{className:"flex flex-col items-center justify-center p-20 gap-3",children:[a.jsx("div",{className:"w-9 h-9 rounded-full border-3 border-primary border-t-transparent animate-spin"}),a.jsx("span",{className:"text-xs font-mono text-base-content/60",children:"Loading session records..."})]});if(n)return a.jsxs("div",{className:"p-5 rounded-xl bg-error/10 border border-error/20 text-error flex items-center gap-3",children:[a.jsx("span",{className:"text-lg",children:"⚠️"}),a.jsxs("div",{children:[a.jsxs("h5",{className:"font-bold text-sm",children:["Failed to load sessions: ",n]}),a.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,y=Math.max(1,Math.ceil(x/o)),E=b.reduce((S,v)=>S+v.billedTokens,0),A=b.reduce((S,v)=>S+v.cacheReadTokens,0),w=b.filter(S=>S.state==="error").length,N=Math.max(1,...b.map(S=>S.billedTokens)),_=b.filter(S=>{if(f!=="all"&&S.state!==f)return!1;if(!d.trim())return!0;const v=d.toLowerCase();return S.id.toLowerCase().includes(v)||S.source.toLowerCase().includes(v)||S.model.toLowerCase().includes(v)||S.topTool.toLowerCase().includes(v)}),k=S=>r!==S?a.jsx("span",{className:"opacity-25 ml-1 text-[10px]",children:"↕"}):a.jsx("span",{className:"ml-1 text-primary font-bold",children:s==="asc"?"▲":"▼"});return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Total Sessions"}),a.jsx("span",{className:"text-primary",children:"📋"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsx("div",{className:"text-xl font-bold font-mono text-base-content",children:Lt(x)}),a.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Showing page ",i," of ",y]})]})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Page Billed Tokens"}),a.jsx("span",{className:"text-primary",children:"⚡"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsx("div",{className:"text-xl font-bold font-mono text-primary",children:Be(E)}),a.jsxs("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:["Across ",b.length," page sessions"]})]})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col justify-between",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Page Cache Read"}),a.jsx("span",{className:"text-cyan-400",children:"💾"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsx("div",{className:"text-xl font-bold font-mono text-cyan-400",children:Be(A)}),a.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:"Reused context tokens"})]})]}),a.jsxs("div",{className:`rounded-xl p-4 border flex flex-col justify-between transition-all ${w>0?"bg-error/10 border-error/30 text-error":"bg-base-200 border-base-content/10"}`,children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[11px] font-mono uppercase tracking-wider text-base-content/60",children:"Session Status"}),a.jsx("span",{children:w>0?"⚠️":"✓"})]}),a.jsxs("div",{className:"mt-2",children:[a.jsxs("div",{className:"text-xl font-bold font-mono",children:[b.length-w," OK · ",w," Error"]}),a.jsx("div",{className:"text-[11px] text-base-content/60 font-mono mt-0.5",children:w===0?"100% successful on page":`${w} failed sessions`})]})]})]}),a.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:[a.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[a.jsx("span",{className:"text-base-content/40 text-xs",children:"🔍"}),a.jsx("input",{type:"text",placeholder:"Filter sessions by ID, model, agent, or tool...",value:d,onChange:S=>p(S.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&&a.jsx("button",{type:"button",onClick:()=>p(""),className:"text-xs text-base-content/50 hover:text-base-content cursor-pointer",children:"✕"})]}),a.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-mono",children:[a.jsx("span",{className:"text-base-content/50 text-[11px] uppercase tracking-wider mr-1",children:"State:"}),["all","ok","error"].map(S=>a.jsx("button",{type:"button",onClick:()=>m(S),className:`px-2.5 py-1 rounded-md text-xs uppercase font-bold transition-colors cursor-pointer ${f===S?"bg-primary text-primary-content shadow-xs":"bg-base-300 text-base-content/70 hover:bg-base-300/80"}`,children:S},S))]})]}),a.jsx("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 overflow-hidden",children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"bg-base-300/80 text-base-content/70 border-b border-base-content/10 select-none",children:[a.jsx("th",{className:"p-3 whitespace-nowrap",children:"Session ID"}),a.jsx("th",{className:"p-3 whitespace-nowrap",children:"Agent"}),a.jsx("th",{className:"p-3 whitespace-nowrap",children:"Model"}),a.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors whitespace-nowrap",onClick:()=>l?.("start"),children:["Start Time ",k("start")]}),a.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("duration"),children:["Duration ",k("duration")]}),a.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("messages"),children:["Msgs ",k("messages")]}),a.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("toolCalls"),children:["Tools ",k("toolCalls")]}),a.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("billedTokens"),children:["Billed Tok ",k("billedTokens")]}),a.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("cacheRead"),children:["Cache Read ",k("cacheRead")]}),a.jsxs("th",{className:"p-3 cursor-pointer hover:text-primary transition-colors text-right whitespace-nowrap",onClick:()=>l?.("freshInput"),children:["Fresh Input ",k("freshInput")]}),a.jsx("th",{className:"p-3 whitespace-nowrap",children:"Top Tool"}),a.jsx("th",{className:"p-3 text-center whitespace-nowrap",children:"State"})]})}),a.jsx("tbody",{children:_.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:12,className:"text-center py-12 text-base-content/50",children:"No sessions matching the current filter."})}):_.map(S=>{const v=CV(S.topTool),O=aa[v]??aa.other,C=Math.min(100,Math.round(S.billedTokens/N*100));return a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-primary/10 cursor-pointer transition-colors group",onClick:()=>u?.(S.source,S.id),title:"Click to view execution timeline",children:[a.jsx("td",{className:"p-3 font-bold text-primary whitespace-nowrap",children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"font-mono text-xs",title:S.id,children:S.id.length>18?`${S.id.slice(0,16)}…`:S.id}),a.jsx("span",{className:"text-[10px] opacity-40 group-hover:opacity-100 transition-opacity",children:"↗"})]})}),a.jsx("td",{className:"p-3 whitespace-nowrap",children:a.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:[a.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center opacity-80",children:a.jsx(pr,{id:S.source})}),a.jsx("span",{children:S.source})]})}),a.jsx("td",{className:"p-3 text-base-content/80 whitespace-nowrap",children:a.jsx("span",{className:"px-1.5 py-0.5 rounded bg-base-300/60 border border-base-content/5 text-[11px]",children:S.model})}),a.jsx("td",{className:"p-3 font-mono text-xs text-base-content/70 whitespace-nowrap",children:fV(S.start)}),a.jsx("td",{className:"p-3 text-right font-semibold tabular-nums whitespace-nowrap",children:Wk(S.durationMs/6e4)}),a.jsx("td",{className:"p-3 text-right tabular-nums text-base-content/80 whitespace-nowrap",children:Lt(S.messages)}),a.jsx("td",{className:"p-3 text-right tabular-nums text-base-content/80 whitespace-nowrap",children:Lt(S.toolCalls)}),a.jsx("td",{className:"p-3 text-right font-bold text-primary tabular-nums whitespace-nowrap",children:a.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[a.jsx("span",{children:Be(S.billedTokens)}),a.jsx("div",{className:"w-12 bg-base-300 h-1 rounded-full overflow-hidden",children:a.jsx("div",{className:"bg-primary h-full rounded-full",style:{width:`${C}%`}})})]})}),a.jsx("td",{className:"p-3 text-right text-cyan-400 font-bold tabular-nums whitespace-nowrap",children:Be(S.cacheReadTokens)}),a.jsx("td",{className:"p-3 text-right text-base-content/70 tabular-nums whitespace-nowrap",children:Be(S.freshInputTokens)}),a.jsx("td",{className:"p-3 whitespace-nowrap",children:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-[10px] border font-mono ${O}`,children:S.topTool})}),a.jsx("td",{className:"p-3 text-center whitespace-nowrap",children:a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-mono font-bold border ${S.state==="error"?"bg-error/15 text-error border-error/30":S.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:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current"}),S.state]})})]},`${S.source}:::${S.id}`)})})]})})}),a.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-3 px-2 py-1 text-xs",children:[a.jsxs("span",{className:"text-base-content/70 font-mono text-[11px]",children:["Showing ",(i-1)*o+1,"–",Math.min(i*o,x)," of ",x," sessions"]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.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:i<=1,onClick:()=>c?.(i-1),children:"« Previous"}),a.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:[i," / ",y]}),a.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:i>=y,onClick:()=>c?.(i+1),children:"Next »"})]})]})]})},eA=({data:e,loading:t,error:n,onTriggerImport:r})=>{const[s,i]=h.useState(!1),[o,l]=h.useState(null),c=async()=>{i(!0),l("Running import & analytics rollup...");try{const m=await r?.("incremental");l(m?.message??"Import queued.")}catch(m){l(`Import failed: ${m instanceof Error?m.message:String(m)}`)}finally{i(!1)}};if(t)return a.jsx("div",{className:"flex items-center justify-center p-16",children:a.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin"})});if(n)return a.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:a.jsxs("span",{children:["Failed to load sources registry: ",n]})});if(!e)return null;const{overview:u,agents:d,roots:p}=e,f=d[0]?.heatmapDays.length;return a.jsxs("div",{className:"flex flex-col gap-6",children:[a.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:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl",children:"🗄️"}),a.jsx("h3",{className:"font-bold text-base",children:"Transcripts Corpus & Ingestion Registry"})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 text-xs font-mono text-base-content/70 mt-1",children:[a.jsxs("span",{children:["Files: ",a.jsx("strong",{className:"text-base-content",children:Lt(u.totalFiles)})]}),a.jsxs("span",{children:["Corpus Size:"," ",a.jsxs("strong",{className:"text-base-content",children:[(u.corpusSizeBytes/(1024*1024)).toFixed(1)," MB"]})]}),a.jsxs("span",{children:["Total Sessions:"," ",a.jsx("strong",{className:"text-base-content",children:Lt(u.totalSessions)})]}),a.jsxs("span",{children:["Coverage:"," ",a.jsxs("strong",{className:"text-base-content",children:[u.dateCoverage.from?.slice(0,10)??"N/A"," →"," ",u.dateCoverage.to?.slice(0,10)??"N/A"]})]}),a.jsxs("span",{children:["Last Import:"," ",a.jsx("strong",{className:"text-base-content",children:u.lastImportedAt?new Date(u.lastImportedAt).toLocaleString():"never imported"})]})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[a.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:s,onClick:c,children:s?"Importing...":"🔄 Import & Analyze"}),o&&a.jsx("span",{className:"text-[11px] font-mono text-info","aria-live":"polite",children:o})]})]}),a.jsxs("div",{children:[a.jsxs("h4",{className:"font-bold text-sm mb-3",children:["Agent Activity (",f??"—","-Day Daily Heatmaps)"]}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:d.map(m=>a.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:[a.jsxs("div",{className:"flex justify-between items-start",children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsxs("div",{className:"relative group",children:[a.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:m.color},"aria-label":`${m.name} source metrics`,"aria-describedby":`source-tooltip-${m.id}`,children:a.jsx(pr,{id:m.id})}),a.jsxs("div",{id:`source-tooltip-${m.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:[a.jsxs("div",{className:"mb-2 font-bold text-sm",children:[m.name," Summary"]}),a.jsxs("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1",children:[a.jsx("span",{className:"text-base-content/60",children:"Imported Files"}),a.jsx("strong",{className:"text-right",children:Lt(m.filesCount)}),a.jsx("span",{className:"text-base-content/60",children:"Sessions"}),a.jsx("strong",{className:"text-right",children:Lt(m.sessionCount)}),a.jsx("span",{className:"text-base-content/60",children:"Total Tokens"}),a.jsx("strong",{className:"text-right",children:Be(m.totalTokens)}),a.jsx("span",{className:"text-base-content/60",children:"Cache Saved"}),a.jsx("strong",{className:"text-right",children:Be(m.cacheSavedTokens)}),a.jsx("span",{className:"text-base-content/60",children:"Tool Calls"}),a.jsx("strong",{className:"text-right",children:Lt(m.toolCalls)}),a.jsx("span",{className:"text-base-content/60",children:"Date Range"}),a.jsxs("strong",{className:"text-right",children:[m.firstDate?.slice(0,10)??"N/A"," →"," ",m.lastDate?.slice(0,10)??"N/A"]})]})]})]}),a.jsxs("div",{children:[a.jsx("div",{className:"font-bold text-sm",children:m.name}),a.jsx("div",{className:"text-[10px] font-mono text-base-content/60",children:m.importPath})]})]}),a.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(m.totalTokens)," tok"]})]}),a.jsxs("div",{className:"bg-base-300/60 p-2 rounded-lg border border-base-content/5",children:[a.jsxs("div",{className:"text-[10px] font-mono text-base-content/50 mb-1 flex justify-between",children:[a.jsxs("span",{children:[f??"—"," days ago"]}),a.jsx("span",{children:"Today"})]}),a.jsx(bV,{days:m.heatmapDays,color:m.color,maxDailyTokens:m.maxDailyTokens})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-2 border-t border-base-content/10 font-mono text-[11px]",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Sessions"}),a.jsx("span",{className:"font-semibold",children:Lt(m.sessionCount)})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Tool Calls"}),a.jsx("span",{className:"font-semibold",children:Lt(m.toolCalls)})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px]",children:"Cache Saved"}),a.jsx("span",{className:"font-semibold text-emerald-400",children:Be(m.cacheSavedTokens)})]})]})]},m.id))})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[a.jsx("h4",{className:"font-bold text-sm mb-3",children:"Source Directories & Import Roots"}),a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{className:"py-1.5",children:"Agent"}),a.jsx("th",{className:"py-1.5",children:"Filesystem Path"}),a.jsx("th",{className:"py-1.5",children:"Match Pattern"}),a.jsx("th",{className:"py-1.5 text-right",children:"Files Count"}),a.jsx("th",{className:"py-1.5 text-center",children:"Status"})]})}),a.jsx("tbody",{children:p.map(m=>a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[a.jsx("td",{className:"py-1.5 font-bold",children:m.agentName}),a.jsx("td",{className:"py-1.5 text-base-content/80",children:m.path}),a.jsx("td",{className:"py-1.5 text-base-content/60",children:m.matchPattern}),a.jsx("td",{className:"py-1.5 text-right font-semibold",children:Lt(m.fileCount)}),a.jsx("td",{className:"py-1.5 text-center",children:a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-400 uppercase font-bold",children:m.status})})]},m.agentId))})]})})]})]})},_V=["auto","1m","3m","5m","10m","30m","1h","4h","1d"],Er=["#3987e5","#199e70","#d95926","#9085e9","#c98500","#ec4899","#8b5cf6","#06b6d4","#f59e0b","#10b981"],IV=(e,t)=>t===void 0||t===0?null:(e-t)/Math.abs(t)*100,Ap=h.memo(({current:e,previous:t,invert:n=!1})=>{const r=IV(e,t);if(r===null)return a.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});const s=r>=0,i=n?!s:s;return a.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold font-mono ${i?"bg-emerald-500/15 text-emerald-400":"bg-error/15 text-error"}`,children:[s?"↑ +":"↓ ",Math.abs(r).toFixed(1),"% vs previous period"]})}),nl=h.memo(({label:e,value:t,sub:n,trend:r,trendColor:s,current:i,previous:o,invert:l,badge:c})=>a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-4",children:[a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:e}),c]}),a.jsxs("div",{className:"flex items-end justify-between gap-2 mt-1",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold font-mono text-primary",children:t}),a.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[a.jsx(Ap,{current:i,previous:o,invert:l}),a.jsx("span",{className:"text-xs text-base-content/60",children:n})]})]}),r.length>1&&a.jsx(Vk,{values:r,color:s,width:100,height:34})]})]})),rl=h.memo(({title:e,description:t,series:n,buckets:r,chartMode:s,onToggleChartMode:i,testId:o})=>{const l=r.length>0&&n.length>0&&r.some(c=>Object.values(c.v).some(u=>u>0));return a.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":o,children:[a.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-2 pb-2 border-b border-base-content/10",children:[a.jsx("div",{children:a.jsxs("h4",{className:"font-bold text-sm text-base-content flex items-center gap-2",children:[a.jsx(ur,{tip:t,position:"top",className:"cursor-help [&:before]:whitespace-normal [&:before]:max-w-xs [&:before]:text-left [&:before]:text-[11px] [&:before]:font-normal [&:before]:leading-snug z-20","data-testid":o?`${o}-tooltip`:void 0,children:a.jsx("span",{className:"hover:text-primary transition-colors",children:e})}),a.jsxs("span",{className:"text-[11px] font-normal text-base-content/60 font-mono",children:["(",n.length," tracked)"]})]})}),a.jsxs("div",{className:"flex items-center gap-1 bg-base-300 p-0.5 rounded-lg text-xs",children:[a.jsx("button",{type:"button","aria-pressed":s==="chart",className:`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${s==="chart"?"bg-base-100 text-base-content font-bold shadow-xs":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>s!=="chart"&&i(),children:"Chart"}),a.jsx("button",{type:"button","aria-pressed":s==="table",className:`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${s==="table"?"bg-base-100 text-base-content font-bold shadow-xs":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>s!=="table"&&i(),children:"Table"})]})]}),a.jsx("div",{className:"min-h-[220px]",children:s==="table"&&r.length>0&&n.length>0?a.jsx("div",{className:"overflow-x-auto max-h-72 overflow-y-auto",children:a.jsxs("table",{className:"w-full text-xs text-left font-mono","data-testid":"summary-bucket-table",children:[a.jsx("thead",{className:"sticky top-0 bg-base-200",children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{className:"py-1.5 pr-2",children:"Bucket"}),n.map(c=>a.jsx("th",{className:"py-1.5 pr-2 text-right",children:a.jsxs("span",{className:"inline-flex items-center gap-1",children:[a.jsx("span",{className:"w-2 h-2 rounded-full inline-block shrink-0",style:{background:c.color}}),c.label]})},c.id)),a.jsx("th",{className:"py-1.5 pr-2 text-right",children:"Total"}),a.jsx("th",{className:"py-1.5 pr-2 text-right",children:"Cache Hit %"}),a.jsx("th",{className:"py-1.5 text-right",children:"Gain Ratio %"})]})}),a.jsx("tbody",{children:r.map(c=>{const u=Object.values(c.v).reduce((d,p)=>d+p,0);return a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[a.jsx("td",{className:"py-1.5 pr-2 font-bold",children:qk(c.id??c.label)}),n.map(d=>a.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums",children:c.v[d.id]!==void 0?Be(c.v[d.id]??0):"—"},d.id)),a.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums font-bold",children:Be(u)}),a.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums text-cyan-400",children:c.lineValue!==void 0?`${c.lineValue.toFixed(1)}%`:"—"}),a.jsx("td",{className:"py-1.5 text-right tabular-nums text-amber-400",children:c.secondLineValue!==void 0?`${c.secondLineValue.toFixed(1)}%`:"—"})]},c.id??c.label)})})]})}):l?a.jsx(kp,{buckets:r,series:n,height:220}):r.length>0&&n.length>0?a.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:[a.jsxs("span",{className:"font-semibold text-base-content/70",children:["No token or call activity recorded for ",e.toLowerCase()," in this time range."]}),a.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."})]}):a.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:a.jsxs("span",{children:["No ",e.toLowerCase()," activity recorded for this time range."]})})}),a.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&&a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(c=>a.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:[a.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:c.color}}),a.jsx("span",{className:"truncate max-w-[150px]",children:c.label})]},c.id))}),a.jsxs("div",{className:"flex items-center gap-3 text-[10px] font-mono text-base-content/70 ml-auto",children:[a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[a.jsx("span",{className:"w-3 h-0.5 bg-cyan-400 rounded-full inline-block"}),a.jsx("span",{className:"text-cyan-400",children:"Cache Hit %"})]}),a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[a.jsx("span",{className:"w-3 h-0.5 bg-amber-400 rounded-full inline-block"}),a.jsx("span",{className:"text-amber-400",children:"Gain Ratio %"})]})]})]})]})}),sl=(e,t,n)=>{const r=new Map;e.forEach((i,o)=>{r.set(i.id,{id:i.id,label:i.label||i.id,color:i.color||n[o%n.length]||"#3987e5"})});let s=r.size;for(const i of t)for(const o of Object.keys(i.series))o&&!r.has(o)&&(r.set(o,{id:o,label:o,color:n[s%n.length]||"#3987e5"}),s++);return Array.from(r.values())},al=e=>e.map(t=>({id:t.bucketStart,label:Yi(t.bucketStart),v:t.series,lineValue:t.cacheHitRatio,secondLineValue:t.gainRatio})),Ed=["#199e70","#3987e5","#d95926","#9085e9","#c98500","#ec4899","#8b5cf6","#06b6d4","#f59e0b","#10b981"],tA=h.memo(({data:e,loading:t,error:n,dimension:r="model",onDimensionChange:s,bucket:i="auto",onBucketChange:o,loopSummary:l})=>{const[c,u]=h.useState("chart"),[d,p]=h.useState({model:"chart",source:"chart",tool:"chart",skill:"chart"}),f=h.useCallback(()=>p(Y=>({...Y,model:Y.model==="chart"?"table":"chart"})),[]),m=h.useCallback(()=>p(Y=>({...Y,source:Y.source==="chart"?"table":"chart"})),[]),b=h.useCallback(()=>p(Y=>({...Y,tool:Y.tool==="chart"?"table":"chart"})),[]),x=h.useCallback(()=>p(Y=>({...Y,skill:Y.skill==="chart"?"table":"chart"})),[]),y=e?.kpis,E=e?.previousKpis,A=e?.kpiTrend??[],w=e?.timeSeries??[],N=e?.topModels??[],_=e?.topSources??[],k=e?.topTools??[],S=h.useMemo(()=>Math.max(0,...N.map(Y=>Y.tokens),..._.map(Y=>Y.tokens)),[N,_]),v=e?.skillsUsed??[],O=e?.skillTimeSeries??[],C=e?.skillBreakdown??{bySkill:[],bySource:[],byInvocationKind:[],byCapability:[],trend:[],fresh:!0},M=C.byCapability??[],B=e?.modelTimeSeries??[],R=e?.sourceTimeSeries??[],z=e?.toolTimeSeries??[],W=e?.cacheEfficiency??{savedTokens:0,hitRatio:0,totalRead:0,bySource:[],byModel:[],byAgentModel:[]},F=E??void 0,J=W.byAgentModel??[],K=h.useMemo(()=>Array.from(new Set(J.map(Y=>Y.model))),[J]),X=h.useMemo(()=>Array.from(new Set(J.map(Y=>Y.source))),[J]),I=h.useMemo(()=>new Map(J.map(Y=>[`${Y.source}\0${Y.model}`,Y])),[J]),V=h.useMemo(()=>new Map(_.map(Y=>[Y.id,Y.label])),[_]),te=h.useMemo(()=>({billed:A.map(Y=>Y.totalBilledTokens),cacheSaved:A.map(Y=>Y.cacheSavedTokens),sessions:A.map(Y=>Y.sessionsCount),toolCalls:A.map(Y=>Y.toolCallsCount)}),[A]),L=h.useMemo(()=>k.map(Y=>({...Y,id:Y.id&&Y.id.trim()!==""?Y.id.trim():"unknown"})),[k]),ye=h.useMemo(()=>v.filter(Y=>Y.id&&Y.id.trim()!==""&&Y.id!=="unknown"),[v]),xe=h.useMemo(()=>B&&B.length>0?B:r==="model"?w:[],[B,r,w]),P=h.useMemo(()=>R&&R.length>0?R:r==="source"?w:[],[R,r,w]),oe=h.useMemo(()=>z&&z.length>0?z:r==="tool"?w:[],[z,r,w]),re=h.useMemo(()=>O&&O.length>0?O:r==="skill"?w:[],[O,r,w]),H=h.useMemo(()=>sl(N,xe,Er),[N,xe]),Ce=h.useMemo(()=>sl(_,P,Er),[_,P]),me=h.useMemo(()=>sl(L.map((Y,He)=>({id:Y.id,label:Y.id,color:Ed[He%Ed.length]})),oe,Ed),[L,oe]),he=h.useMemo(()=>sl(ye,re,Er),[ye,re]),Ne=h.useMemo(()=>al(xe),[xe]),Ge=h.useMemo(()=>al(P),[P]),Z=h.useMemo(()=>al(oe),[oe]),ke=h.useMemo(()=>al(re),[re]),Fe=h.useMemo(()=>O.map(Y=>({id:Y.bucketStart,label:Yi(Y.bucketStart),v:Y.series})),[O]),Re=h.useMemo(()=>C.trend.map(Y=>({id:Y.bucketStart,label:Yi(Y.bucketStart),v:Y.series})),[C.trend]),rt=h.useMemo(()=>C.bySkill.map((Y,He)=>({id:Y.skillName,label:Y.skillName,color:Er[He%Er.length]||"#3987e5"})),[C.bySkill]),{toolCallTotal:ae,toolTimeTotal:pe,toolTokenTotal:De,avgBilledPerSession:Me,avgBilledPerCall:Le,prevAvgPerSession:ot,prevAvgPerCall:dt,freshInputTokens:se,outputTokens:fe,skillTokenTotals:je}=h.useMemo(()=>{const Y=L.reduce((Qe,qe)=>Qe+qe.count,0),He=L.reduce((Qe,qe)=>Qe+(qe.durationMs??0),0),Ue=L.reduce((Qe,qe)=>Qe+(qe.tokens??0),0),at=y?.totalBilledTokens??0,Nt=y?.sessionsCount??0,At=y?.toolCallsCount??0,de=Nt>0?at/Nt:0,_e=At>0?at/At:0,Ve=F&&F.sessionsCount>0?F.totalBilledTokens/F.sessionsCount:void 0,Pe=F&&F.toolCallsCount>0?F.totalBilledTokens/F.toolCallsCount:void 0,Je=Math.max(0,W.totalRead-W.savedTokens),Ct=Math.max(0,at-Je),Oe=O.reduce((Qe,qe)=>{for(const[St,ce]of Object.entries(qe.series))Qe[St]=(Qe[St]??0)+ce;return Qe},{});return{toolCallTotal:Y,toolTimeTotal:He,toolTokenTotal:Ue,avgBilledPerSession:de,avgBilledPerCall:_e,prevAvgPerSession:Ve,prevAvgPerCall:Pe,freshInputTokens:Je,outputTokens:Ct,skillTokenTotals:Oe}},[L,y,F,W,O]);return t?a.jsx("div",{className:"flex items-center justify-center p-16",children:a.jsx("div",{className:"w-8 h-8 rounded-full border-4 border-primary border-t-transparent animate-spin"})}):n?a.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:a.jsxs("span",{children:["Failed to load history summary: ",n]})}):!e||!y?null:a.jsxs("div",{className:"flex flex-col gap-6",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsx(nl,{label:"Total Billed Tokens",value:Be(y.totalBilledTokens),sub:`Fresh ${Be(se)} · Output ${Be(fe)}`,trend:te.billed,trendColor:"#3987e5",current:y.totalBilledTokens,previous:F?.totalBilledTokens}),a.jsx(nl,{label:"Cache-Saved Tokens",value:Be(y.cacheSavedTokens),sub:`Share ${qn(y.cacheSavedPercent)} · Hit ${qn(W.hitRatio)}`,trend:te.cacheSaved,trendColor:"#22d3ee",current:y.cacheSavedTokens,previous:F?.cacheSavedTokens,badge:a.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:[y.cacheSavedPercent,"% saved"]})}),a.jsx(nl,{label:"Sessions",value:Lt(y.sessionsCount),sub:`${Lt(y.sessionsCount>0?y.toolCallsCount/y.sessionsCount:0)} calls / session`,trend:te.sessions,trendColor:"#9085e9",current:y.sessionsCount,previous:F?.sessionsCount}),a.jsx(nl,{label:"Tool Calls",value:Lt(y.toolCallsCount),sub:`${Be(Le)} billed / step`,trend:te.toolCalls,trendColor:"#c98500",current:y.toolCallsCount,previous:F?.toolCallsCount,badge:a.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:[qn(y.errorRate)," err"]})})]}),a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"flex flex-wrap justify-between items-center gap-3",children:[a.jsx("div",{children:a.jsx("h3",{className:"font-bold text-base text-base-content",children:a.jsx(ur,{tip:"4-block breakdown across Model, Source, Tool, and Skill (Stacked token bars with Cache Hit % and Gain Ratio % line overlays)",position:"bottom",className:"cursor-help [&:before]:whitespace-normal [&:before]:max-w-xs [&:before]:text-left [&:before]:text-[11px] [&:before]:font-normal [&:before]:leading-snug z-20","data-testid":"summary-overview-tooltip",children:a.jsx("span",{className:"hover:text-primary transition-colors",children:"Token Activity & Cache Hit Ratio & Gain Ratio"})})})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("fieldset",{className:"flex items-center bg-base-300 p-0.5 rounded-lg text-xs border-0",children:[a.jsx("legend",{className:"sr-only",children:"Bucket interval"}),_V.map(Y=>a.jsx("button",{type:"button","aria-pressed":i===Y,className:`px-2 py-1 rounded font-medium transition-colors ${i===Y?"bg-base-100 text-base-content font-bold shadow-sm":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>o?.(Y),children:Y},Y))]}),a.jsx("div",{className:"flex items-center bg-base-300 p-0.5 rounded-lg text-xs",children:["chart","table"].map(Y=>a.jsx("button",{type:"button","aria-pressed":c===Y,className:`px-2.5 py-1 rounded font-medium transition-colors ${c===Y?"bg-base-100 text-base-content font-bold shadow-sm":"text-base-content/60 hover:bg-base-content/10"}`,onClick:()=>{u(Y),p({model:Y,source:Y,tool:Y,skill:Y})},children:Y==="chart"?"All Charts":"All Tables"},Y))})]})]}),a.jsxs("div",{className:"flex flex-col gap-6 w-full",children:[a.jsx(rl,{title:"By Model",description:"Token load by LLM model with cache hit ratio and gain ratio overlays",series:H,buckets:Ne,chartMode:d.model,onToggleChartMode:f,testId:"summary-block-model"}),a.jsx(rl,{title:"By Source",description:"Token load by agent platform with cache hit ratio and gain ratio overlays",series:Ce,buckets:Ge,chartMode:d.source,onToggleChartMode:m,testId:"summary-block-source"}),a.jsx(rl,{title:"By Tool",description:"Token load (or call volume when unmeasured) by tool execution with cache hit ratio and gain ratio overlays",series:me,buckets:Z,chartMode:d.tool,onToggleChartMode:b,testId:"summary-block-tool"}),a.jsx(rl,{title:"By Skill",description:"Token load by specialized skill with cache hit ratio and gain ratio overlays",series:he,buckets:ke,chartMode:d.skill,onToggleChartMode:x,testId:"summary-block-skill"})]})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[a.jsx("h4",{className:"font-bold text-sm mb-3",children:"Token by Model"}),a.jsx("div",{className:"flex flex-col gap-3",children:N.map(Y=>a.jsx(M1,{item:Y,maxTotal:S},Y.id))})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[a.jsx("h4",{className:"font-bold text-sm mb-3",children:"Token by Agent"}),a.jsx("div",{className:"flex flex-col gap-3",children:_.map(Y=>a.jsx(M1,{item:Y,maxTotal:S},Y.id))})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[a.jsx("h4",{className:"font-bold text-sm mb-3",children:"Cache Efficiency By Model"}),W.byModel&&W.byModel.length>0&&a.jsx(F1,{items:W.byModel.map(Y=>({id:Y.model,label:Y.modelName,color:Y.color,hitRatio:Y.hitRatio,savedTokens:Y.savedTokens,totalRead:Y.totalRead,billedTokens:Y.billedTokens}))})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[a.jsx("h4",{className:"font-bold text-sm mb-3",children:"Cache Efficiency By Agent"}),(W.bySource&&W.bySource.length>0||_.length>0)&&a.jsx(F1,{items:(W.bySource&&W.bySource.length>0?W.bySource:_.map(Y=>({source:Y.id,sourceName:Y.label,color:Y.color,hitRatio:W.hitRatio,savedTokens:Math.round(W.savedTokens*(Y.share/100)),totalRead:Math.round(W.totalRead*(Y.share/100)),billedTokens:Y.tokens}))).map(Y=>({id:Y.source,label:Y.sourceName,color:Y.color,hitRatio:Y.hitRatio,savedTokens:Y.savedTokens,totalRead:Y.totalRead,billedTokens:Y.billedTokens}))})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[a.jsx("h4",{className:"font-bold text-sm mb-3",children:"Agent × Model Correlation Matrix"}),K.length>0&&X.length>0&&a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{className:"text-left pr-2 py-1 text-base-content/60 sticky left-0 bg-base-200 z-10",children:"Model \\ Agent"}),X.map(Y=>a.jsx("th",{className:"px-1 py-1 text-base-content/60 whitespace-nowrap",title:V.get(Y)??Y,children:V.get(Y)??Y},Y))]})}),a.jsx("tbody",{children:K.map(Y=>a.jsxs("tr",{children:[a.jsx("td",{className:"pr-2 py-1 font-bold text-base-content/80 whitespace-nowrap sticky left-0 bg-base-200",children:Y}),X.map(He=>{const Ue=I.get(`${He}\0${Y}`);return a.jsx("td",{className:"p-0.5",children:Ue?a.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*(Ue.hitRatio/100)})`},title:`${Ue.sourceName} × ${Ue.modelName}: ${Ue.hitRatio}% hit · saved ${Be(Ue.savedTokens)} / read ${Be(Ue.totalRead)} / billed ${Be(Ue.billedTokens)}`,children:[Ue.hitRatio,"%"]}):a.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:"—"})},He)})]},Y))})]})}),a.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono text-base-content/60",children:[a.jsx("span",{children:"0%"}),a.jsx("div",{className:"h-1.5 w-32 rounded-full bg-gradient-to-r from-base-300 to-cyan-400"}),a.jsx("span",{children:"100% cache hit ratio"})]})]})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5",children:[a.jsx("h4",{className:"font-bold text-sm mb-2",children:"Top Tools & Error Rates"}),a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs text-left font-mono",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{className:"py-1.5",children:"Tool"}),a.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Usage Share"}),a.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Time Share"}),a.jsx("th",{className:"py-1.5 min-w-[120px]",children:"Token Share"}),a.jsx("th",{className:"py-1.5 text-right",children:"Calls"}),a.jsx("th",{className:"py-1.5 text-right",children:"Errors"}),a.jsx("th",{className:"py-1.5 text-right",children:"Error Rate"})]})}),a.jsx("tbody",{children:L.map(Y=>{const He=Y.usageShare??(ae>0?Math.round(Y.count/ae*1e3)/10:0),Ue=Y.timeShare??(pe>0?Math.round((Y.durationMs??0)/pe*1e3)/10:0),at=Y.tokenShare??(De>0?Math.round((Y.tokens??0)/De*1e3)/10:0);return a.jsxs("tr",{className:"border-b border-base-content/5 hover:bg-base-300/30",children:[a.jsx("td",{className:"py-1.5 font-bold",children:Y.id}),a.jsx("td",{className:"py-1.5",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-16",children:a.jsx(Ii,{value:He,max:100,color:"#3987e5"})}),a.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:qn(He)})]})}),a.jsx("td",{className:"py-1.5",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-16",children:a.jsx(Ii,{value:Ue,max:100,color:"#10b981"})}),a.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:Ue>0?qn(Ue):"—"})]})}),a.jsx("td",{className:"py-1.5",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-16",children:a.jsx(Ii,{value:at,max:100,color:"#f59e0b"})}),a.jsx("span",{className:"tabular-nums text-[10px] text-base-content/70",children:at>0?qn(at):"—"})]})}),a.jsx("td",{className:"py-1.5 text-right tabular-nums",children:Lt(Y.count)}),a.jsx("td",{className:"py-1.5 text-right tabular-nums",children:Y.errors>0?Lt(Y.errors):"0"}),a.jsx("td",{className:"py-1.5 text-right",children:a.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${Y.errorRate>1?"bg-error/20 text-error font-bold":"bg-base-300 text-base-content/70"}`,children:qn(Y.errorRate)})})]},Y.id)})})]})})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 p-5 flex flex-col gap-4",children:[a.jsx("h4",{className:"font-bold text-sm mb-3",children:"Efficiency Stats & Skills"}),a.jsx("div",{children:a.jsxs("div",{className:"grid grid-cols-2 gap-3 text-xs font-mono",children:[a.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Avg Billed / Session"}),a.jsx("span",{className:"font-bold",children:Be(Me)}),a.jsx(Ap,{current:Me,previous:ot,invert:!0})]}),a.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Avg Billed / Step"}),a.jsx("span",{className:"font-bold",children:Be(Le)}),a.jsx(Ap,{current:Le,previous:dt,invert:!0})]}),a.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.jsx("span",{className:"text-base-content/60 text-[10px] uppercase tracking-wider",children:"Loop Detection Findings"}),a.jsxs("span",{className:"font-bold",children:[Lt(l?.redundantCalls??0)," redundant"]}),a.jsxs("span",{className:"text-[10px] text-base-content/60",children:[Be(l?.wastedTokens??0)," wasted"]})]})]})}),v.length>0&&a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-xs mb-2",children:"Skills Invocation Mix"}),a.jsx(R1,{buckets:Fe,series:RV(v),height:150}),a.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:v.map(Y=>a.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:[a.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:Y.color}}),a.jsxs("span",{children:[Y.label,":"]}),a.jsxs("span",{className:"font-bold",children:[Be(je[Y.id]??0)," tokens"]})]},Y.id))})]})]})]}),a.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:[a.jsx("div",{children:a.jsx("h4",{className:"font-bold text-sm",children:a.jsx(ur,{tip:"Skill invocations by name, agent, and invocation kind over the selected window.",position:"top",className:"cursor-help [&:before]:whitespace-normal [&:before]:max-w-xs [&:before]:text-left [&:before]:text-[11px] [&:before]:font-normal [&:before]:leading-snug z-20","data-testid":"summary-skill-breakdown-tooltip",children:a.jsx("span",{className:"hover:text-primary transition-colors",children:"Skill Load Breakdown"})})})}),C.fresh===!1?a.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:a.jsx("span",{children:"Skill rollup not yet built — run history analyze to populate this section."})}):C.bySkill.length>0||M.length>0?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-xs font-mono",children:[a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"Top Skills"}),a.jsx("div",{className:"flex flex-col gap-1.5",children:C.bySkill.map((Y,He)=>a.jsxs("div",{className:"flex justify-between items-center gap-2",children:[a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:Er[He%Er.length]??"#3987e5"}}),Y.skillName]}),a.jsx("span",{className:"font-bold tabular-nums",children:Lt(Y.calls)})]},Y.skillName))})]}),a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"By Agent"}),a.jsx("div",{className:"flex flex-col gap-1.5",children:C.bySource.map(Y=>a.jsxs("div",{className:"flex justify-between items-center gap-2",children:[a.jsx("span",{children:Y.source}),a.jsx("span",{className:"font-bold tabular-nums",children:Lt(Y.calls)})]},Y.source))})]}),a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"By Invocation Kind"}),a.jsx("div",{className:"flex flex-col gap-1.5",children:C.byInvocationKind.map(Y=>a.jsxs("div",{className:"flex justify-between items-center gap-2",children:[a.jsx("span",{className:"capitalize",children:Y.invocationKind}),a.jsx("span",{className:"font-bold tabular-nums",children:Lt(Y.calls)})]},Y.invocationKind))})]})]}),M.length>0&&a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"By Capability"}),a.jsx("div",{className:"flex flex-col gap-1.5",children:M.map((Y,He)=>a.jsxs("div",{className:"flex justify-between items-center gap-2 text-xs font-mono",children:[a.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[a.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:Er[He%Er.length]??"#3987e5"}}),a.jsx("span",{className:"truncate",children:Y.skillName}),a.jsx("span",{className:"text-base-content/50 shrink-0",children:Y.capabilityKind??"unknown"}),a.jsx("span",{className:"shrink-0 px-1 rounded border border-base-content/10",title:`evidence: ${Y.evidenceKind??"unknown"}`,children:Y.evidenceKind??"unknown"}),Y.status!==null&&Y.status!=="ok"&&a.jsx("span",{className:"shrink-0 text-warning",children:Y.status})]}),a.jsx("span",{className:"font-bold tabular-nums",children:Lt(Y.calls)})]},`${Y.skillName}-${Y.capabilityKind??"unknown"}-${Y.invocationKind}-${Y.evidenceKind??"unknown"}-${Y.status??"unknown"}`))})]}),Re.length>0&&a.jsxs("div",{children:[a.jsx("h5",{className:"font-bold text-xs mb-2 text-base-content/60",children:"Skill Call Trend"}),a.jsx(R1,{buckets:Re,series:rt,height:150})]})]}):a.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:a.jsx("span",{children:"No skill activity recorded for this window."})})]})]})}),RV=e=>e.map(t=>({id:t.id,label:t.label,color:t.color})),M1=h.memo(({item:e,maxTotal:t})=>{const n=e.freshInputTokens??(e.outputTokens?e.tokens-e.outputTokens:e.tokens),r=e.cacheReadTokens??0,s=e.outputTokens??0,i=t>0?t:1,o=l=>`${Math.round(l/i*1e3)/10}%`;return a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex justify-between text-xs font-mono",children:[a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:e.color}}),e.label]}),a.jsx("span",{children:Be(e.tokens)})]}),a.jsxs("div",{className:"w-full bg-base-300 h-3 rounded-full overflow-hidden flex",children:[n>0&&a.jsx("div",{className:"h-full",style:{width:o(n),background:"#3987e5"}}),s>0&&a.jsx("div",{className:"h-full",style:{width:o(s),background:"#f59e0b"}})]}),a.jsxs("div",{className:"flex justify-between text-[10px] text-base-content/60 font-mono",children:[a.jsxs("span",{children:["Fresh ",Be(n)," · Cached ",Be(r)," · Output ",Be(s)]}),a.jsxs("span",{children:["Total ",Be(n+r+s)]})]})]})}),F1=h.memo(({items:e})=>a.jsx("div",{className:"flex flex-col gap-2",children:e.map(t=>a.jsxs("div",{className:"flex flex-col gap-1 bg-base-300/40 p-2.5 rounded-lg border border-base-content/5",children:[a.jsxs("div",{className:"flex justify-between items-center text-xs",children:[a.jsxs("span",{className:"flex items-center gap-1.5 font-medium",children:[a.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:t.color}}),t.label]}),a.jsxs("span",{className:"font-mono font-bold text-cyan-400",children:[t.hitRatio,"%"]})]}),a.jsx("div",{className:"w-full bg-base-100 h-1.5 rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full rounded-full",style:{width:`${t.hitRatio}%`,background:t.color}})}),a.jsxs("div",{className:"flex justify-between text-[10px] text-base-content/60 font-mono",children:[a.jsxs("span",{children:["Saved: ",Be(t.savedTokens)]}),a.jsxs("span",{children:["Total Read: ",Be(t.totalRead)," · Billed: ",Be(t.billedTokens)]})]})]},t.id))})),DV=({blocks:e,start:t,end:n,onJumpToTime:r})=>{const s=h.useId(),{bins:i,maxBinTokens:o,maxBinOperations:l,startMs:c,endMs:u,hasValidRange:d}=h.useMemo(()=>{if(!t||!n||e.length===0)return{bins:[],maxBinTokens:0,maxBinOperations:0,startMs:0,endMs:0,hasValidRange:!1};const p=Date.parse(t),f=Date.parse(n);if(Number.isNaN(p)||Number.isNaN(f)||f<p)return{bins:[],maxBinTokens:0,maxBinOperations:0,startMs:0,endMs:0,hasValidRange:!1};const m=96,x=Math.max(1,f-p)/m,y=Array.from({length:m},(w,N)=>({index:N,timeMs:p+N*x,tokens:0,operations:0}));for(const w of e){if(!w.timestamp)continue;const N=Date.parse(w.timestamp);if(Number.isNaN(N)||N<p||N>f)continue;const _=Math.min(m-1,Math.max(0,Math.floor((N-p)/x))),k=y[_];k&&(k.tokens+=w.totalTokens,k.operations+=w.operationCount)}const E=Math.max(1,...y.map(w=>w.tokens)),A=Math.max(1,...y.map(w=>w.operations));return{bins:y,maxBinTokens:E,maxBinOperations:A,startMs:p,endMs:f,hasValidRange:!0}},[e,t,n]);return!d||i.length===0?null:a.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:[a.jsxs("div",{className:"flex items-center justify-between text-[11px] text-base-content/60 px-1",children:[a.jsxs("span",{children:["Timeline Activity (",i.length," bins)"]}),a.jsxs("span",{children:["Peak: ",Be(o)]})]}),a.jsx("div",{className:"relative h-10 w-full bg-base-300/60 rounded-lg overflow-hidden flex items-end p-1",children:a.jsx("svg",{viewBox:"0 0 96 32",preserveAspectRatio:"none",className:"w-full h-full text-primary/70","aria-hidden":"true",children:i.map(p=>{const f=p.operations>0?Math.max(2,Math.round(p.operations/l*30)):0,m=p.tokens>0?.35+p.tokens/o*.65:.25,b=32-f;return a.jsx("rect",{x:p.index,y:b,width:"0.85",height:f,fill:"currentColor",fillOpacity:m,"data-operations":p.operations,"data-tokens":p.tokens,className:"hover:text-cyan-400 transition-colors",children:a.jsx("title",{children:`${new Date(p.timeMs).toISOString()} · ${Be(p.tokens)} · ${p.operations} ops`})},p.index)})})}),a.jsx("label",{htmlFor:s,className:"sr-only",children:"Timeline scrub slider"}),a.jsx("input",{id:s,type:"range",min:c,max:u,defaultValue:c,"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 f=Number(p.currentTarget.value);Number.isFinite(f)&&r?.(new Date(f).toISOString())}})]})},Gs=(e,t)=>`${e}:${t}`,Ws=(e,t)=>JSON.stringify([e,t]),as=e=>e.replace(/[^a-zA-Z0-9_-]/g,"-"),ic=(e,t,n)=>e+t+n,OV=(e,t)=>{const n=e+t;return n>0?t/n*100:0},Cp=e=>e.length<=12?e:`${e.slice(0,8)}…${e.slice(-4)}`,LV=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],nA=e=>{if(!e)return"—";const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=LV[t.getUTCMonth()],r=t.getUTCDate(),s=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0");return`${n} ${r} ${s}:${i}`},_p=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"),s=String(t.getUTCSeconds()).padStart(2,"0");return`${n}:${r}:${s}`},P1=e=>`${Cp(e.id)} · ${e.source} · ${nA(e.start)} · ${Be(e.tokenLoad)}`,jV=e=>{const t=e.payload?.trim();return t&&t.length>0?t:e.title},B1=e=>e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)??e,$1=e=>e.kind==="assistant"||e.eventType==="message"&&e.kind!=="user",MV=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"}},FV=()=>a.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:[a.jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),a.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),PV=({promptTokens:e,fullText:t,tooltipId:n})=>{const[r,s]=h.useState(!1),i=e?.freshInputTokens??0,o=e?.cacheReadTokens??0,l=e?.outputTokens??0,c=ic(i,o,l),u=t.length>0?t.split(/\r?\n/).length:0,d=t.length;return a.jsxs("div",{className:"relative inline-flex items-center z-20",children:[a.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:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),onKeyDown:p=>{p.key==="Escape"&&s(!1)},children:a.jsx(FV,{})}),a.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:[a.jsx("div",{className:"font-bold text-base-content mb-1",children:"User Prompt Telemetry"}),a.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80",children:[a.jsx("span",{className:"text-base-content/60",children:"Lines / chars:"}),a.jsxs("span",{children:[u," lines (",d," chars)"]}),a.jsx("span",{className:"text-base-content/60",children:"📥 Fresh input:"}),a.jsx("span",{children:Be(i)}),a.jsx("span",{className:"text-base-content/60",children:"💾 Cache read:"}),a.jsx("span",{className:"text-cyan-400",children:Be(o)}),a.jsx("span",{className:"text-base-content/60",children:"📤 Output:"}),a.jsx("span",{children:Be(l)}),a.jsx("span",{className:"text-base-content/60 border-t border-base-content/10 pt-0.5",children:"⚡ Turn load:"}),a.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Be(c)})]})]})]})},U1=({agentId:e,model:t,timestamp:n,tooltipId:r,freshInputTokens:s=0,cacheReadTokens:i=0,outputTokens:o=0,sessionId:l})=>{const[c,u]=h.useState(!1),d=ic(s,i,o);return a.jsxs("div",{className:"relative inline-flex items-center z-20",children:[a.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:()=>u(!0),onMouseLeave:()=>u(!1),onFocus:()=>u(!0),onBlur:()=>u(!1),onKeyDown:p=>{p.key==="Escape"&&u(!1)},children:a.jsx(pr,{id:e})}),a.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 ${c?"block":"hidden"}`,children:[a.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:[a.jsx(pr,{id:e}),a.jsx("span",{className:"uppercase",children:e}),a.jsxs("span",{className:"text-base-content/50 font-normal truncate",children:["(",t,")"]})]}),a.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80 text-[10.5px]",children:[a.jsx("span",{className:"text-base-content/60",children:"Timestamp:"}),a.jsx("span",{className:"truncate",children:_p(n)}),l&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-base-content/60",children:"Session:"}),a.jsx("span",{className:"truncate font-bold text-primary",children:l})]})]}),a.jsxs("div",{className:"mt-1.5 pt-1.5 border-t border-base-content/10",children:[a.jsx("div",{className:"font-bold text-base-content/70 text-[10px] uppercase tracking-wider mb-0.5",children:"Token Breakdown"}),a.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-base-content/80 text-[10.5px]",children:[a.jsx("span",{className:"text-base-content/60",children:"📥 Fresh input:"}),a.jsx("span",{children:Be(s)}),a.jsx("span",{className:"text-base-content/60",children:"💾 Cache read:"}),a.jsx("span",{className:"text-cyan-400",children:Be(i)}),a.jsx("span",{className:"text-base-content/60",children:"📤 Output:"}),a.jsx("span",{children:Be(o)}),a.jsx("span",{className:"text-base-content/60 border-t border-base-content/10 pt-0.5",children:"⚡ Total:"}),a.jsx("span",{className:"font-bold border-t border-base-content/10 pt-0.5 text-primary",children:Be(d)})]})]})]})]})},rA=({data:e,loading:t,error:n,mode:r="session",sessionId:s,availableSessions:i=[],onSelectSession:o,onModeChange:l,consolidatedTaskWbs:c="",consolidatedRunId:u="",onConsolidatedScopeSubmit:d})=>{const p=e?.scope.sessionId,f=e?.scope.source,[m,b]=h.useState({}),[x,y]=h.useState(!0),[E,A]=h.useState(!0),[w,N]=h.useState(!0),[_,k]=h.useState(c),[S,v]=h.useState(u),O=p&&f?Ws(f,p):"consolidated",C=m[O]||{},M=P=>{b(oe=>({...oe,[O]:P(oe[O]||{})}))},B=(P,oe)=>{const re=Gs(P,oe);M(H=>({...H,[re]:!H[re]}))};if(t)return a.jsx("div",{className:"flex items-center justify-center p-16",children:a.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 a.jsx("div",{className:"p-4 rounded-lg bg-error/10 border border-error/20 text-error",children:a.jsxs("span",{children:["Failed to load timeline: ",n]})});if(!e)return a.jsx("div",{className:"p-4 rounded-lg bg-info/10 border border-info/20 text-info",children:a.jsx("span",{children:"No timeline data available."})});const{scope:R,blocks:z,truncated:W}=e,F=ic(R.tokens.freshInputTokens,R.tokens.cacheReadTokens,R.tokens.outputTokens),J=OV(R.tokens.freshInputTokens,R.tokens.cacheReadTokens),K=z.map(P=>{const oe=P.events.filter(re=>$1(re)?!x:re.kind==="unknown"||re.agent==="unknown"?!E:!(w&&!re.payload?.trim()&&(re.durationMs===null||re.durationMs===0)&&ic(re.freshInputTokens,re.cacheReadTokens,re.outputTokens)===0));return{...P,events:oe}}).filter(P=>P.events.length>0),X=K.flatMap(P=>P.events.filter(oe=>!!oe.payload?.trim()).map(oe=>Gs(P.key,oe.seq))),I=X.length>0&&X.every(P=>C[P]),V=()=>M(()=>I?{}:Object.fromEntries(X.map(P=>[P,!0]))),te=i.findIndex(P=>P.id===R.sessionId&&P.source===R.source),L=te>0?i[te-1]:void 0,ye=te>=0&&te<i.length-1?i[te+1]:void 0,xe=P=>{const oe=Date.parse(P),re=K.find(H=>{const Ce=H.timestamp?Date.parse(H.timestamp):Number.NaN;return Number.isFinite(Ce)&&Ce>=oe})??K.at(-1);re&&document.getElementById(`timeline-block-${as(re.key)}`)?.scrollIntoView({behavior:"smooth",block:"center"})};return a.jsxs("div",{className:"flex flex-col gap-6",children:[a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-5 flex flex-col gap-4",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[a.jsx("h3",{className:"text-base font-bold tracking-tight",children:"Conversation"}),a.jsxs("fieldset",{className:"inline-flex border border-base-content/20 rounded-lg p-0.5 bg-base-300 font-mono text-xs",children:[a.jsx("legend",{className:"sr-only",children:"Timeline mode"}),a.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"}),a.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"})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3",children:[r==="session"?a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"sr-only",children:"Session"}),a.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:R.source&&R.sessionId?Ws(R.source,R.sessionId):"",onChange:P=>{const oe=i.find(re=>Ws(re.source,re.id)===P.target.value);oe&&o?.(oe.source,oe.id)},children:i.length>0?i.map(P=>a.jsx("option",{value:Ws(P.source,P.id),children:P1(P)},Ws(P.source,P.id))):a.jsx("option",{value:R.source&&R.sessionId?Ws(R.source,R.sessionId):"",children:R.sessionId?P1({id:R.sessionId,source:R.source??"unknown",start:R.start??"",tokenLoad:F}):"No session selected"})})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button","aria-label":"Previous session",disabled:!L,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:()=>L&&o?.(L.source,L.id),children:"←"}),a.jsx("button",{type:"button","aria-label":"Next session",disabled:!ye,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:()=>ye&&o?.(ye.source,ye.id),children:"→"})]})]}):a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.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:[a.jsx("span",{className:"text-base-content/60",children:"Scope:"}),a.jsxs("span",{className:"font-semibold text-primary",children:[R.sessionCount," sessions"]})]}),a.jsxs("form",{className:"flex flex-wrap items-end gap-2",onSubmit:P=>{P.preventDefault(),d?.({taskWbs:_.trim(),runId:S.trim()})},children:[a.jsxs("label",{className:"flex flex-col gap-1 text-[10px] font-mono text-base-content/60",children:["Task WBS",a.jsx("input",{type:"text",value:_,onInput:P=>k(P.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"})]}),a.jsxs("label",{className:"flex flex-col gap-1 text-[10px] font-mono text-base-content/60",children:["Run ID",a.jsx("input",{type:"text",value:S,onInput:P=>v(P.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"})]}),a.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"})]})]}),a.jsx("button",{type:"button","aria-pressed":I,disabled:X.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:V,children:I?"Collapse all":"Expand all"}),a.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs font-mono text-base-content/80",children:[a.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[a.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:P=>y(P.target.checked)}),a.jsx("span",{children:"Hide assistant"})]}),a.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[a.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:E,onChange:P=>A(P.target.checked)}),a.jsx("span",{children:"Hide unknown"})]}),a.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer select-none",children:[a.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:w,onChange:P=>N(P.target.checked)}),a.jsx("span",{children:"Hide other empty"})]})]})]})]}),a.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:[a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:r==="session"?"SESSION":"SESSIONS"}),a.jsx("span",{className:"font-semibold truncate text-base-content mt-0.5",title:R.sessionId??`${R.sessionCount} sessions`,children:R.sessionId?Cp(R.sessionId):`${R.sessionCount} total`})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"AGENT"}),a.jsx("span",{className:"inline-flex items-center gap-1 font-semibold truncate text-base-content mt-0.5",children:R.source?a.jsxs(a.Fragment,{children:[a.jsx(pr,{id:R.source}),R.source]}):"multiple"})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"MODEL"}),a.jsxs("span",{className:"inline-flex items-center gap-1.5 truncate text-base-content mt-0.5",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-primary/70 shrink-0"}),R.model??"multiple"]})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"STARTED"}),a.jsx("span",{className:"truncate text-base-content/80 mt-0.5",children:nA(R.start)})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"DURATION"}),a.jsx("span",{className:"font-semibold truncate text-base-content mt-0.5",children:Wk(R.durationMs/6e4)})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"TOTAL TOKENS"}),a.jsx("span",{className:"font-bold text-primary truncate mt-0.5",children:Be(F)})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"CACHE READ"}),a.jsxs("span",{className:"font-semibold text-cyan-400 truncate mt-0.5",children:[J.toFixed(1),"%"]})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"OUTPUT TOKENS"}),a.jsx("span",{className:"truncate text-base-content/80 mt-0.5",children:Be(R.tokens.outputTokens)})]}),a.jsxs("div",{className:"flex flex-col bg-base-300/40 p-2 rounded-lg border border-base-content/5",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-base-content/60",children:"TOOL CALLS"}),a.jsx("span",{className:"truncate text-base-content font-bold mt-0.5",children:Lt(R.toolCallCount)})]})]}),a.jsx(DV,{blocks:K,start:R.start,end:R.end,onJumpToTime:xe})]}),W&&a.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:[a.jsx("span",{children:"ℹ️"}),a.jsx("span",{children:"Showing newest 5,000 events. Apply a narrower filter or time window to inspect earlier events."})]}),a.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:K.map(P=>{const oe=P.events.filter(H=>H.kind==="user"),re=P.events.filter(H=>H.kind!=="user");return a.jsxs("div",{id:`timeline-block-${as(P.key)}`,"data-testid":`timeline-block-${P.key}`,className:"flex flex-col gap-2.5",children:[r==="consolidated"&&a.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:[a.jsx(pr,{id:P.source}),a.jsx("span",{className:"font-bold text-base-content",children:P.source}),a.jsxs("span",{children:["· ",Cp(P.sessionId)]}),a.jsxs("span",{children:["· Turn #",P.turnIndex]}),P.correlationExactness&&a.jsx("span",{"data-testid":`timeline-exactness-${P.key}`,className:`px-1.5 py-0.2 rounded text-[10px] font-bold ${P.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:P.correlationExactness})]}),oe.map(H=>{const Ce=jV(H),me=H.payload?.trim()??"",he=B1(Ce),Ne=!!H.payload?.trim(),Ge=!!C[Gs(P.key,H.seq)],Z=as(`timeline-user-drawer-${P.key}-${H.seq}`),ke=as(`user-tt-${P.key}-${H.seq}`);return a.jsxs("div",{className:"relative flex flex-col sm:grid sm:grid-cols-[136px_minmax(0,1fr)] py-1","data-testid":`timeline-user-event-${P.key}-${H.seq}`,children:[a.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:P.timestamp?`Timestamp: ${_p(P.timestamp)}`:void 0,children:[a.jsxs("span",{className:"font-semibold text-primary truncate",children:["📥 ",Be(H.freshInputTokens)," in"]}),H.durationSource==="measured"&&H.durationMs!==null?a.jsxs("span",{"data-testid":`timeline-step-duration-${P.key}-${H.seq}`,className:H.durationMs>=5e3?"font-bold text-amber-400":"text-base-content/60",children:["⏱ ",sa(H.durationMs)]}):H.durationSource==="inferred"&&H.durationMs!==null?a.jsxs("span",{"data-testid":`timeline-step-duration-${P.key}-${H.seq}`,title:"Inferred from next event timestamp within session",className:"text-base-content/60 italic",children:["⏱ ~",sa(H.durationMs)]}):a.jsx("span",{"data-testid":`timeline-step-duration-${P.key}-${H.seq}`,title:"Unmeasured (gap > 10m or last event)",className:"text-base-content/40",children:"⏱ —"})]}),a.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"}),a.jsx("div",{className:"pl-6 sm:pl-5 min-w-0 flex justify-end",children:a.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:[a.jsxs("div",{className:"flex items-center justify-between gap-2 min-h-[32px]",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[a.jsx("span",{className:"relative z-10",children:a.jsx(PV,{promptTokens:H.promptTokens,fullText:me,tooltipId:ke})}),a.jsx("span",{className:"font-mono text-xs font-semibold text-base-content/90 truncate min-w-0",children:he})]}),a.jsx("div",{className:"flex items-center gap-2 shrink-0 font-mono text-[11px] text-base-content/60",children:Ne?a.jsx("button",{type:"button","aria-label":Ge?"Collapse full user prompt":"Expand full user prompt","aria-expanded":Ge,"aria-controls":Z,onClick:()=>B(P.key,H.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:a.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${Ge?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null})]}),Ge&&Ne&&a.jsx("div",{id:Z,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:yd(Ce)})]})})]},Gs(P.key,H.seq))}),re.map(H=>{const Ce=MV(H),me=!!C[Gs(P.key,H.seq)],he=!!H.payload?.trim(),Ne=as(`timeline-op-drawer-${P.key}-${H.seq}`),Ge=as(`agent-tt-${P.key}-${H.seq}`),Z=as(`tool-tt-${P.key}-${H.seq}`),ke=$1(H);return a.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-${P.key}-${H.seq}`,children:[a.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:P.timestamp?`Timestamp: ${_p(P.timestamp)}`:void 0,children:[a.jsx("span",{className:"font-semibold text-base-content/90 truncate",children:ke&&H.outputTokens>0?`📤 ${Be(H.outputTokens)} out`:`⚡ ${Be(H.tokens)} tok`}),H.durationSource==="measured"&&H.durationMs!==null?a.jsxs("span",{"data-testid":`timeline-step-duration-${P.key}-${H.seq}`,className:H.durationMs>=5e3?"font-bold text-amber-400":"text-base-content/60",children:["⏱ ",sa(H.durationMs)]}):H.durationSource==="inferred"&&H.durationMs!==null?a.jsxs("span",{"data-testid":`timeline-step-duration-${P.key}-${H.seq}`,title:"Inferred from next event timestamp within session",className:"text-base-content/60 italic",children:["⏱ ~",sa(H.durationMs)]}):a.jsx("span",{"data-testid":`timeline-step-duration-${P.key}-${H.seq}`,title:"Unmeasured (gap > 10m or last event)",className:"text-base-content/40",children:"⏱ —"})]}),a.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:Ce.color},"aria-hidden":"true"}),a.jsx("div",{className:"pl-6 sm:pl-5 min-w-0 flex justify-start",children:ke?a.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:[a.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2 min-h-[38px]",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[a.jsx("span",{className:"relative z-10",children:a.jsx(U1,{agentId:H.agent||P.source,model:H.model||P.model,timestamp:P.timestamp,tooltipId:Ge,freshInputTokens:H.freshInputTokens,cacheReadTokens:H.cacheReadTokens,outputTokens:H.outputTokens,sessionId:P.sessionId})}),a.jsx("span",{className:"font-mono text-xs text-base-content/60 truncate",children:H.model}),a.jsx("span",{className:"font-mono text-xs text-base-content/90 truncate min-w-0",children:B1(H.payload||H.title)})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 font-mono text-[11px] text-base-content/60",children:[a.jsxs("span",{children:["📤 ",Be(H.outputTokens)]}),he?a.jsx("button",{type:"button","aria-label":me?"Collapse response":"Expand response","aria-expanded":me,"aria-controls":Ne,onClick:()=>B(P.key,H.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:a.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${me?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null]})]}),me&&H.payload&&a.jsx("div",{id:Ne,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:yd(H.payload,H.toolName)})]}):a.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:Ce.color},children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 px-2.5 py-1.5 min-h-[38px]",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[a.jsx("span",{className:"relative z-10",children:a.jsx(U1,{agentId:H.agent||P.source,model:H.model||P.model,timestamp:P.timestamp,tooltipId:Ge,freshInputTokens:H.freshInputTokens,cacheReadTokens:H.cacheReadTokens,outputTokens:H.outputTokens,sessionId:P.sessionId})}),a.jsx("span",{className:"relative z-10",children:a.jsx(Gx,{item:{toolName:Ce.label,seq:H.seq,status:H.exitCode===0?"ok":H.exitCode!==null?"error":"ok",durationMs:H.durationMs,durationSource:H.durationSource,tokens:{billedTokens:H.tokens,freshInputTokens:H.freshInputTokens,cacheReadTokens:H.cacheReadTokens,outputTokens:H.outputTokens,cacheSavedTokens:0},argsRaw:H.payload,sessionId:P.sessionId??p,source:H.agent||P.source,model:H.model||P.model,ts:P.timestamp,errorText:H.exitCode!==null&&H.exitCode!==0?H.payload||`Exit code ${H.exitCode}`:null},categoryColor:Ce.color,testId:`timeline-tool-badge-${Z}`,tooltipId:Z,size:"xs"})}),H.title&&H.title.trim().length>0?a.jsx("span",{className:"font-mono text-xs font-semibold text-base-content/90 truncate min-w-0",title:H.title,children:H.title}):null]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 font-mono",children:[H.exitCode!==null&&a.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold relative z-10 ${H.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=",H.exitCode]}),he?a.jsx("button",{type:"button","aria-label":me?"Collapse operation payload":"Expand operation payload","aria-expanded":me,"aria-controls":Ne,onClick:()=>B(P.key,H.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:a.jsx("span",{className:`text-xs font-mono transition-transform duration-150 ${me?"rotate-90":""}`,"aria-hidden":"true",children:"›"})}):null]})]}),me&&H.payload&&a.jsx("div",{id:Ne,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:yd(H.payload,Ce.label)})]})})]},Gs(P.key,H.seq))})]},P.key)})})]})},ci=Tr,sA=({data:e,loading:t=!1,error:n=null,mode:r="session",onModeChange:s=()=>{},sessionId:i,sessionSource:o,availableSessions:l=[],onSelectSession:c=()=>{},toolNames:u=[],onToolNamesChange:d=()=>{},status:p="all",onStatusChange:f=()=>{},search:m="",onSearchChange:b=()=>{}})=>{const x=e?.items??[],y=e?.scope,E=h.useMemo(()=>{const N=new Set;for(const _ of x)N.add(_.toolName);return Array.from(N).sort()},[x]),A=N=>{u.includes(N)?d(u.filter(_=>_!==N)):d([...u,N])},w=u.length>0||p!=="all"||m.trim().length>0;return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsxs("div",{className:"bg-base-200 rounded-xl p-4 border border-base-content/10 flex flex-col gap-4 shadow-xs",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-base-content/10",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[a.jsxs("div",{className:"inline-flex bg-base-300 p-1 rounded-xl border border-base-content/5 text-xs font-mono",children:[a.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:()=>s("session"),children:"Single Session"}),a.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:()=>s("consolidated"),children:"Consolidated Stream"})]}),r==="session"&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[o&&a.jsx("span",{className:"w-5 h-5 flex items-center justify-center text-base-content/80",children:a.jsx(pr,{id:o})}),a.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:i?`${o??""}:${i}`:"",onChange:N=>{const _=N.target.value,[k,...S]=_.split(":");k&&S.length>0&&c(k,S.join(":"))},children:l.map(N=>a.jsxs("option",{value:`${N.source}:${N.id}`,children:["[",N.source,"] ",N.id.slice(0,16),"... (",N.model,")"]},`${N.source}:${N.id}`))})]})]}),r==="consolidated"&&a.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"})]}),a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3",children:[a.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[a.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Total Calls"}),a.jsx("div",{className:"mt-1",children:a.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-calls",children:y?.totalCalls??0})})]}),a.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[a.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Unique Tools"}),a.jsx("div",{className:"mt-1",children:a.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-unique",children:y?.uniqueTools??0})})]}),a.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[a.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Errors / Rate"}),a.jsx("div",{className:"mt-1",children:a.jsxs("span",{className:`text-lg font-bold font-mono ${(y?.errorCount??0)>0?"text-error":"text-success"}`,"data-testid":"tool-scope-errors",children:[y?.errorCount??0," (",Math.round((y?.errorRate??0)*100),"%)"]})})]}),a.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[a.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Mean Duration"}),a.jsxs("div",{className:"mt-1",children:[a.jsx("span",{className:"text-lg font-bold font-mono text-base-content","data-testid":"tool-scope-duration",children:y?.meanDurationMs?`${y.meanDurationMs} ms`:"—"}),(y?.durationUnmeasured??0)>0&&a.jsxs("span",{className:"text-[10px] text-base-content/50 ml-1 font-mono block",children:["(",y?.durationUnmeasured," unmeasured)"]})]})]}),a.jsxs("div",{className:"bg-base-300/60 rounded-xl p-3 border border-base-content/5 flex flex-col justify-between",children:[a.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-base-content/50",children:"Billed Tokens"}),a.jsx("div",{className:"mt-1",children:a.jsx("span",{className:"text-lg font-bold font-mono text-primary","data-testid":"tool-scope-tokens",children:y?ci(y.tokens.billedTokens):0})})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-base-content/10",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-base-content/60 font-semibold font-mono",children:"Status:"}),a.jsx("div",{className:"inline-flex bg-base-300 p-0.5 rounded-lg text-xs font-mono",children:["all","ok","error"].map(N=>a.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:()=>f(N),children:N.toUpperCase()},N))})]}),a.jsxs("div",{className:"flex-1 max-w-md relative",children:[a.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-xs opacity-40",children:"🔍"}),a.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:m,onChange:N=>b(N.target.value)}),m&&a.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:"✕"})]})]}),E.length>0&&a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-2 border-t border-base-content/5",children:[a.jsx("span",{className:"text-[11px] text-base-content/50 font-semibold font-mono",children:"Tools:"}),E.map(N=>{const _=u.includes(N);return a.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 ${_?"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:()=>A(N),children:N},N)}),u.length>0&&a.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 (",u.length,")"]})]})]}),e?.truncated&&a.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:[a.jsx("span",{children:"⚠️"}),a.jsxs("span",{children:["Showing the first ",x.length," tool calls. Refine your filters or search to narrow the scope."]})]}),n&&a.jsxs("div",{className:"bg-error/10 text-error border border-error/20 p-4 text-xs rounded-xl flex items-center gap-2",children:[a.jsx("span",{children:"⚠️"}),a.jsx("span",{children:n})]}),t&&x.length===0&&a.jsx("div",{className:"flex flex-col gap-2.5 animate-pulse",children:[1,2,3,4,5].map(N=>a.jsx("div",{className:"h-16 bg-base-200 rounded-xl border border-base-content/5"},N))}),!t&&!n&&x.length===0&&a.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:[a.jsx("span",{className:"text-3xl block mb-1",children:"🔍"}),a.jsx("p",{className:"text-sm font-semibold",children:"No tool calls found"}),a.jsx("p",{className:"text-xs max-w-sm",children:w?"No tool calls match your active filter criteria. Try clearing search or status filters.":"No tool invocations recorded for this scope."})]}),x.length>0&&a.jsx("div",{className:"flex flex-col gap-2 w-full",children:x.map(N=>{const _=`${N.sessionId}:${N.messageHash}:${N.toolSeq}`,k=sc[N.category]??sc.other,S=N.status==="error";return a.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:[a.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[a.jsx(TV,{agentId:N.source,model:N.model,timestamp:N.ts,freshInputTokens:N.tokens.freshInputTokens,cacheReadTokens:N.tokens.cacheReadTokens,outputTokens:N.tokens.outputTokens,sessionId:N.sessionId}),a.jsxs("span",{className:"text-xs font-mono text-base-content/40 font-bold min-w-[28px]",children:["#",N.seq]}),a.jsx(kV,{item:N,categoryColor:k}),a.jsx("span",{className:"text-xs font-mono text-base-content/80 truncate min-w-0 flex-1",title:N.argsRaw||N.argsDigest||"",children:EV(N)})]}),a.jsxs("div",{className:"flex items-center gap-3 shrink-0 text-xs font-mono",children:[a.jsx("span",{className:"text-base-content/70 tabular-nums",title:`Duration source: ${N.durationSource}`,children:N.durationMs!==null?`${N.durationMs} ms`:"—"}),a.jsxs("span",{className:"text-base-content/50 text-[11px] tabular-nums",title:`Tokens: ${ci(N.tokens.freshInputTokens)} fresh input, ${ci(N.tokens.cacheReadTokens)} cache read, ${ci(N.tokens.outputTokens)} output`,children:[ci(N.tokens.billedTokens)," tok"]}),a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border ${S?"bg-error/15 text-error border-error/30":"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"}`,children:[a.jsx("span",{className:"w-1 h-1 rounded-full bg-current"}),N.status]})]})]},_)})})]})},BV=[{id:"summary",label:"Summary",component:tA},{id:"timeline",label:"Timeline",component:rA},{id:"tool-using",label:"Tool Using",component:sA},{id:"sessions",label:"Sessions",component:Jk},{id:"insights",label:"Insights",component:Qk},{id:"sources",label:"Sources",component:eA}],il=(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()]},$V=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)??"…"}`,qs=e=>e instanceof Error?e.message:String(e),UV=()=>{const[e,t]=h.useState("summary"),[n,r]=h.useState({range:"4h",bucket:"auto",dimension:"model"}),[s,i]=h.useState("session"),[o,l]=h.useState(null),[c,u]=h.useState({taskWbs:"",runId:""}),[d,p]=h.useState("session"),[f,m]=h.useState([]),[b,x]=h.useState("all"),[y,E]=h.useState(""),[A,w]=h.useState(""),[N,_]=h.useState(1),[k,S]=h.useState("start"),[v,O]=h.useState("desc"),[C,M]=h.useState(void 0),[B,R]=h.useState(void 0),[z,W]=h.useState(void 0),[F,J]=h.useState(void 0),[K,X]=h.useState(void 0),[I,V]=h.useState(void 0),[te,L]=h.useState([]),[ye,xe]=h.useState(!1),[P,oe]=h.useState(!0),[re,H]=h.useState(null),[Ce,me]=h.useState(!0),[he,Ne]=h.useState(null),[Ge,Z]=h.useState(!0),[ke,Fe]=h.useState(null),[Re,rt]=h.useState(!1),[ae,pe]=h.useState(null),[De,Me]=h.useState(!1),[Le,ot]=h.useState(null),[dt,se]=h.useState(!1),[fe,je]=h.useState(null);h.useEffect(()=>{let ce=!0;const Ee=new AbortController;return oe(!0),H(null),me(!0),Ne(null),xt.history.getSummary(n,{signal:Ee.signal}).then(Ye=>{ce&&(Ye?.data?M(Ye.data):H("Failed to load summary"))}).catch(Ye=>{ce&&!Ee.signal.aborted&&H(qs(Ye))}).finally(()=>{ce&&!Ee.signal.aborted&&oe(!1)}),xt.history.getInsights(n,{signal:Ee.signal}).then(Ye=>{ce&&(Ye?.data?X(Ye.data):Ne("Failed to load insights"))}).catch(Ye=>{ce&&!Ee.signal.aborted&&Ne(qs(Ye))}).finally(()=>{ce&&!Ee.signal.aborted&&me(!1)}),()=>{ce=!1,Ee.abort()}},[n]),h.useEffect(()=>{let ce=!0;const Ee=new AbortController;return Z(!0),Fe(null),(async()=>{try{const Ye=await xt.history.getSources(void 0,{signal:Ee.signal});if(!ce)return;Ye?.data?V(Ye.data):Fe("Failed to load sources")}catch(Ye){ce&&!Ee.signal.aborted&&Fe(qs(Ye))}finally{ce&&!Ee.signal.aborted&&Z(!1)}})(),()=>{ce=!1,Ee.abort()}},[]),h.useEffect(()=>{if(e!=="timeline"&&e!=="tool-using")return;let ce=!0;return xe(!0),(async()=>{try{const Ee=await xt.history.getSessions({filter:n,page:1,pageSize:100,sortBy:"start",sortDir:"desc"});if(!ce)return;const Ye=(Ee?.data?.items??[]).map(ee=>({id:ee.id,source:ee.source,model:ee.model,start:ee.start,tokenLoad:ee.freshInputTokens+ee.cacheReadTokens+ee.outputTokens}));L(Ye);const Dt=Ye[0];Dt&&!o&&l({source:Dt.source,id:Dt.id})}catch{ce&&L([])}finally{ce&&xe(!1)}})(),()=>{ce=!1}},[e,n,o]),h.useEffect(()=>{if(e!=="sessions")return;let ce=!0;return rt(!0),pe(null),(async()=>{try{const Ee=await xt.history.getSessions({filter:n,page:N,pageSize:20,sortBy:k,sortDir:v});if(!ce)return;Ee?.data?J(Ee.data):pe("Failed to load sessions")}catch(Ee){ce&&pe(qs(Ee))}finally{ce&&rt(!1)}})(),()=>{ce=!1}},[e,n,N,k,v]),h.useEffect(()=>{if(e!=="timeline")return;if(s==="session"&&!o){const Ee=te[0];!ye&&Ee&&l({source:Ee.source,id:Ee.id});return}let ce=!0;return Me(!0),ot(null),(async()=>{try{const Ee=s==="session"&&o?await xt.history.getTimeline({mode:"session",source:o.source,sessionId:o.id}):await xt.history.getTimeline({mode:"consolidated",filter:n,...c.taskWbs?{taskWbs:c.taskWbs}:{},...c.runId?{runId:c.runId}:{}});if(!ce)return;Ee?.data?R(Ee.data):ot("Failed to load timeline")}catch(Ee){ce&&ot(qs(Ee))}finally{ce&&Me(!1)}})(),()=>{ce=!1}},[e,s,o,n,ye,te,c]),h.useEffect(()=>{const ce=setTimeout(()=>{w(y)},250);return()=>clearTimeout(ce)},[y]),h.useEffect(()=>{if(e!=="tool-using")return;if(d==="session"&&!o){const Ee=te[0];!ye&&Ee&&l({source:Ee.source,id:Ee.id});return}let ce=!0;return se(!0),je(null),(async()=>{try{const Ee=d==="session"&&o?{mode:"session",source:o.source,sessionId:o.id,toolNames:f.length>0?f:void 0,status:b,search:A||void 0}:{mode:"consolidated",filter:n,toolNames:f.length>0?f:void 0,status:b,search:A||void 0},Ye=await xt.history.getToolSequence(Ee);if(!ce)return;Ye?.data?W(Ye.data):je("Failed to load tool sequence")}catch(Ee){ce&&je(qs(Ee))}finally{ce&&se(!1)}})(),()=>{ce=!1}},[e,d,o,n,f,b,A,ye,te]);const Y=(ce,Ee)=>{l({source:ce,id:Ee}),i("session"),t("timeline")},He=(ce,Ee)=>{l({source:ce,id:Ee}),p("session")},Ue=(ce,Ee)=>{const Ye=Ee?{source:Ee,id:ce}:F?.items.find(Dt=>Dt.id===ce)??te.find(Dt=>Dt.id===ce);Ye&&Y(Ye.source,Ye.id)},at=async ce=>(await xt.history.triggerImport({mode:ce})).data,Nt=re?"—":P||C===void 0?"…":String(C.kpis.sessionsCount),At=fe?"—":dt||z===void 0?"…":String(z.scope.totalCalls),de=he?"—":Ce||K===void 0?"…":String(K.loops.length),_e=ke?"—":Ge||I===void 0?"…":String(I.agents.length),Ve={summary:null,timeline:null,"tool-using":At,sessions:Nt,insights:de,sources:_e},Pe=ke?"—":Ge?"…":I?.overview.lastImportedAt?new Date(I.overview.lastImportedAt).toLocaleString():"never imported",Je=h.useMemo(()=>K?{count:K.loops.length,redundantCalls:K.loops.reduce((ce,Ee)=>ce+Math.max(0,Ee.repeats-1),0),wastedTokens:K.loops.reduce((ce,Ee)=>ce+Ee.wastedTokens,0)}:void 0,[K]),Ct=h.useMemo(()=>il(I?.agents.map(ce=>({id:ce.id,label:ce.name,color:ce.color}))??[],n.sources),[I?.agents,n.sources]),Oe=h.useMemo(()=>il(C?.topModels.map(ce=>({id:ce.id,label:ce.label,color:ce.color}))??[],n.models),[C?.topModels,n.models]),Qe=h.useMemo(()=>il(C?.topTools.map(ce=>{const Ee=ce.id&&ce.id.trim()!==""?ce.id.trim():"unknown";return{id:Ee,label:Ee}})??[],n.tools?.map(ce=>ce&&ce.trim()!==""?ce.trim():"unknown")),[C?.topTools,n.tools]),qe=h.useMemo(()=>il(C?.skillsUsed.filter(ce=>ce.id&&ce.id.trim()!==""&&ce.id!=="unknown").map(ce=>({id:ce.id,label:ce.label,color:ce.color}))??[],n.skills?.filter(ce=>ce&&ce.trim()!==""&&ce!=="unknown")),[C?.skillsUsed,n.skills]),St=h.useMemo(()=>({rangeLabel:$V(n),sessionCount:re?null:P&&C===void 0?void 0:C?.kpis.sessionsCount,sourceCount:n.sources?.length??I?.agents.length}),[n,re,P,C,I?.agents.length]);return a.jsxs("div",{className:"flex flex-col gap-4 p-4 max-w-[1600px] mx-auto w-full",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rr,{id:"history",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Histories"}),a.jsx("p",{className:"text-xs text-base-content/60",children:"Transcript telemetry, session traces, and prompt cache analytics"}),a.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:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${ke?"bg-error":"bg-emerald-400 animate-pulse"}`,"aria-hidden":"true"}),"last import ",Pe]})]})]}),a.jsx("div",{className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:BV.map(ce=>a.jsxs("button",{type:"button",className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all ${e===ce.id?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,onClick:()=>t(ce.id),children:[ce.label,Ve[ce.id]!==null&&a.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-${ce.id}`,children:Ve[ce.id]})]},ce.id))})]}),e!=="sources"&&a.jsx(pV,{filter:n,onChange:r,sourceOptions:Ct,modelOptions:Oe,toolOptions:Qe,skillOptions:qe,scope:St}),a.jsxs("div",{className:"mt-2",children:[e==="summary"&&a.jsx(tA,{data:C,loading:P,error:re,dimension:n.dimension??"model",onDimensionChange:ce=>r(Ee=>({...Ee,dimension:ce})),bucket:n.bucket??"auto",onBucketChange:ce=>r(Ee=>({...Ee,bucket:ce})),loopSummary:Je}),e==="timeline"&&a.jsx(rA,{data:B,loading:De,error:Le,mode:s,sessionId:o?.id,sessionSource:o?.source,availableSessions:te,onSelectSession:Y,onModeChange:i,consolidatedTaskWbs:c.taskWbs,consolidatedRunId:c.runId,onConsolidatedScopeSubmit:u}),e==="tool-using"&&a.jsx(sA,{data:z,loading:dt,error:fe,mode:d,onModeChange:p,sessionId:o?.id,sessionSource:o?.source,availableSessions:te,onSelectSession:He,toolNames:f,onToolNamesChange:m,status:b,onStatusChange:x,search:y,onSearchChange:E}),e==="sessions"&&a.jsx(Jk,{data:F,loading:Re,error:ae,sortBy:k,sortDir:v,page:N,pageSize:20,onSortChange:ce=>{k===ce?O(Ee=>Ee==="asc"?"desc":"asc"):(S(ce),O("desc"))},onPageChange:_,onSelectSession:Y}),e==="insights"&&a.jsx(Qk,{data:K,loading:Ce,error:he,cacheHitTrend:C?.kpiTrend??[],onSelectSession:Ue}),e==="sources"&&a.jsx(eA,{data:I,loading:Ge,error:ke,onTriggerImport:at})]})]})},zV={id:"history",name:"History",icon:"📊",route:"history",component:UV,sidebarLabel:"Histories",description:"Imported agent sessions, token analytics, and tool-call forensics",order:20},HV=Object.freeze(Object.defineProperty({__proto__:null,module:zV},Symbol.toStringTag,{value:"Module"})),GV=["30s","5m","1h","4h","24h","7d","all"],WV={"30s":3e4,"5m":5*6e4,"1h":60*6e4,"4h":240*6e4,"24h":1440*6e4,"7d":10080*6e4,all:null};function Ns(e,t=Date.now()){const n=WV[e];if(n!=null)return new Date(t-n).toISOString()}function qV({timeRange:e,onTimeRangeChange:t}){return a.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:[a.jsx("legend",{className:"sr-only",children:"Time range presets"}),GV.map(n=>{const r=e===n;return a.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 VV(e){return e.selectedPrefixes.size>0||e.searchQuery.trim()!==""||e.searchScope!=="all"||e.severity!=="all"||e.tierFilter!=="all"||e.runId.trim()!==""}function Ip({label:e,value:t,onChange:n,options:r}){return a.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:[a.jsx("legend",{className:"sr-only",children:e}),r.map(s=>{const i=s.value===t;return a.jsxs("label",{className:`flex-1 text-[11px] text-center px-2 py-0.5 rounded cursor-pointer transition-all ${i?"bg-primary text-primary-content font-bold shadow-xs":"text-base-content/70 hover:bg-base-content/10"}`,children:[a.jsx("input",{type:"radio",name:`segmented-${e}`,value:s.value,checked:i,onChange:()=>n(s.value),className:"sr-only"}),s.label]},s.value)})]})}const YV="Retention: events capped at 10,000 rows per prefix · terminal jobs pruned after 30d",KV="Retention: decision logs keep the newest 10,000 invocations";function Wx({copy:e=YV}={}){return a.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:e,children:[a.jsx("span",{"aria-hidden":"true",children:"ℹ️"}),a.jsx("span",{children:e})]})}function ZV({filters:e,onFiltersChange:t,onClearFilters:n,prefixOptions:r,getPrefixColor:s,liveEnabled:i,onToggleLive:o,shownCount:l,totalCount:c,actions:u}){const d=h.useMemo(()=>{let m=0;return e.selectedPrefixes.size>0&&(m+=e.selectedPrefixes.size),e.searchQuery.trim()!==""&&(m+=1),e.severity!=="all"&&(m+=1),e.tierFilter!=="all"&&(m+=1),e.runId.trim()!==""&&(m+=1),m},[e]),p=VV(e),f=m=>{t(b=>{const x=new Set(b.selectedPrefixes);return x.has(m)?x.delete(m):x.add(m),{...b,selectedPrefixes:x}})};return a.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:a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("span",{"aria-live":"polite",className:"text-xs font-mono text-base-content/60 whitespace-nowrap","data-testid":"observability-result-count",children:[l," of ",c," shown"]}),a.jsxs("details",{className:"relative inline-block","data-testid":"observability-filter-disclosure",children:[a.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:[a.jsx("span",{children:"🔍 Filter"}),d>0&&a.jsx("span",{className:"px-1.5 py-0.2 rounded-full text-[10px] font-bold bg-primary text-primary-content",children:d})]}),a.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:[a.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-base-content/10",children:[a.jsx("span",{className:"text-xs font-bold uppercase tracking-wide text-base-content/70",children:"Filters"}),p&&a.jsx("button",{type:"button",onClick:n,className:"text-xs text-error hover:underline cursor-pointer","aria-label":"Clear all filters",children:"Clear all"})]}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("label",{htmlFor:"filter-search-input",className:"text-[11px] font-semibold text-base-content/60",children:"Search"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:e.searchScope,onChange:m=>t(b=>({...b,searchScope:m.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:[a.jsx("option",{value:"all",children:"all"}),a.jsx("option",{value:"name",children:"name"}),a.jsx("option",{value:"actor",children:"actor"}),a.jsx("option",{value:"payload",children:"payload"})]}),a.jsx(Vn,{id:"filter-search-input",size:"sm",variant:"bordered",placeholder:`Search ${e.searchScope}…`,value:e.searchQuery,onChange:m=>t(b=>({...b,searchQuery:m.target.value})),className:"flex-1 input-xs","aria-label":`Search ${e.searchScope}`})]})]}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Severity"}),a.jsx(Ip,{label:"Severity",value:e.severity,onChange:m=>t(b=>({...b,severity:m})),options:[{value:"all",label:"All"},{value:"info",label:"Info"},{value:"warning",label:"Warning"},{value:"error",label:"Error"}]})]}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Tier"}),a.jsx(Ip,{label:"Tier",value:e.tierFilter,onChange:m=>t(b=>({...b,tierFilter:m})),options:[{value:"all",label:"All"},{value:"default",label:"Default"},{value:"diagnostic",label:"Diagnostic"}]})]}),r.length>0&&a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"text-[11px] font-semibold text-base-content/60",children:"Prefix"}),a.jsxs("fieldset",{className:"flex flex-wrap items-center gap-1.5 border-0 p-0 m-0","aria-label":"Filter by prefix",children:[a.jsx("legend",{className:"sr-only",children:"Filter by prefix"}),r.map(m=>{const b=e.selectedPrefixes.has(m),x=s(m);return a.jsxs("button",{type:"button",role:"switch","aria-checked":b,"aria-label":`Prefix ${m}${b?" (selected)":""}`,onClick:()=>f(m),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:[m,".*"]},m)})]})]}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("label",{htmlFor:"filter-run-id-input",className:"text-[11px] font-semibold text-base-content/60",children:"Run ID"}),a.jsx(Vn,{id:"filter-run-id-input",size:"sm",variant:"bordered",placeholder:"Filter by run id…",value:e.runId,onChange:m=>t(b=>({...b,runId:m.target.value})),className:"w-full input-xs","aria-label":"Filter by run id"})]})]})]}),a.jsx(Wx,{}),a.jsx("button",{type:"button",onClick:o,className:`px-2.5 py-1 text-xs font-semibold rounded-lg border transition-all cursor-pointer flex items-center gap-1.5 ${i?"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":i?"Pause live event stream":"Resume live event stream","aria-pressed":i,children:a.jsx("span",{children:i?"⏸ Pause Live":"▶ Resume Live"})}),u]})})}const ma=[{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"}],XV=new Set(ma.map(e=>e.key)),Yr=["time","severity","event","summary","correlation","outcome","agent"],aA="spur:observability:columns:v1";function QV(e){if(!Array.isArray(e)||e.length===0)return[...Yr];const t=new Set;for(const n of e)typeof n=="string"&&XV.has(n)&&t.add(n);return t.size===0?[...Yr]:ma.filter(n=>t.has(n.key)).map(n=>n.key)}function JV(e){try{const t=e??(typeof window<"u"?window.localStorage:void 0);if(!t)return[...Yr];const n=t.getItem(aA);if(!n)return[...Yr];const r=JSON.parse(n);return QV(r)}catch{return[...Yr]}}function z1(e,t){try{const n=t??(typeof window<"u"?window.localStorage:void 0);if(!n)return;n.setItem(aA,JSON.stringify(e))}catch{}}function eY({visibleColumns:e,onVisibleColumnsChange:t}){const n=h.useMemo(()=>new Set(e),[e]),r=i=>{const o=new Set(n);if(o.has(i)){if(o.size<=1)return;o.delete(i)}else o.add(i);const l=ma.filter(c=>o.has(c.key)).map(c=>c.key);t(l),z1(l)},s=()=>{const i=[...Yr];t(i),z1(i)};return a.jsxs("details",{className:"relative inline-block","data-testid":"observability-column-customizer",children:[a.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:[a.jsx("span",{children:"📊 Columns"}),a.jsxs("span",{className:"text-[10px] text-base-content/60 font-mono",children:["(",e.length,"/",ma.length,")"]})]}),a.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:[a.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-base-content/10",children:[a.jsx("span",{className:"text-xs font-bold uppercase tracking-wide text-base-content/70",children:"Columns"}),a.jsx("button",{type:"button",onClick:s,className:"text-xs text-primary hover:underline cursor-pointer","aria-label":"Reset columns to default",children:"Reset defaults"})]}),a.jsxs("fieldset",{className:"flex flex-col gap-1.5 border-0 p-0 m-0","aria-label":"Visible columns",children:[a.jsx("legend",{className:"sr-only",children:"Select visible columns"}),ma.map(i=>{const o=n.has(i.key),l=o&&n.size===1,c=`observability-col-${i.key}`;return a.jsxs("label",{htmlFor:c,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:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Sx,{id:c,size:"xs",variant:"primary",checked:o,disabled:l,onChange:()=>r(i.key),"aria-label":i.label}),a.jsx("span",{className:"font-medium",children:i.label})]}),i.defaultVisible&&a.jsx("span",{className:"text-[10px] text-base-content/50 uppercase",children:"default"})]},i.key)})]})]})]})}const tY=()=>`${it()}/events/planning`,Rp=100;function Dp(e){const t=`${it()}/events/history`,n=[],r=e.limit??Rp;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 nY={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"},H1="text-spur-text-muted";function iA(e){return e?nY[e]??H1:H1}const Sd={selectedPrefixes:new Set,searchQuery:"",searchScope:"all",severity:"all",tierFilter:"all",runId:""};function rY(){const e=h.useRef([]),[t,n]=h.useState(0);h.useEffect(()=>{const s=window.setInterval(()=>{const i=Date.now()-6e4,o=e.current.filter(l=>l>=i);e.current=o,n(o.length)},1e3);return()=>window.clearInterval(s)},[]);const r=h.useCallback(()=>{const s=Date.now(),i=s-6e4,o=e.current.filter(l=>l>=i);o.push(s),e.current=o,n(o.length)},[]);return{rate:t,recordEvent:r}}function Op(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,s=typeof r=="string"?r:null,i=e.hasMore,o=typeof i=="boolean"?i:!1,l=[];for(const d of t){const p=sY(d);p&&l.push(p)}const c=e.catalog,u=Array.isArray(c)?aY(c):void 0;return{events:l,count:n,nextCursor:s,hasMore:o,...u?{catalog:u}:{}}}function sY(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,s=t.actor;if(s!==null&&typeof s!="string")return null;const i=t.payload,o=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,c=typeof t.entityId=="string"?t.entityId:t.entityId===null?null:void 0,u=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:s,...n?{prefix:n}:{},...r?{renderer:r}:{}};if(i===null)return{...d,payload:null,view:Ts(t.eventName,null),...oc(o,l,c,u)};if(typeof i!="object")return null;const p=i,f=p.schemaVersion===2?p:void 0;return{...d,payload:oA(p),...f?{envelope:f}:{},view:Ts(t.eventName,p),...oc(o,l,c,u)}}function oc(e,t,n,r){const s={};return e!==void 0&&(s.runId=e),t!==void 0&&(s.entityKind=t),n!==void 0&&(s.entityId=n),r!==void 0&&(s.sequence=r),s}function aY(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 s=typeof r.tier=="string"?r.tier:void 0,i={name:r.name,prefix:r.prefix,source:r.source,renderer:r.renderer,...s!==void 0?{tier:s}:{}};t.push(i)}return t}function iY(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,s=t.actor;if(s!==null&&typeof s!="string")return null;const i=t.payload;if(i!==null&&typeof i!="object")return null;const o=i,l=o?.schemaVersion===2?o:void 0,c=oA(o),u=t.runId??c?.runId,d=t.entityKind??c?.entityKind,p=t.entityId??c?.entityId,f=t.sequence??c?.sequence,m=typeof u=="string"?u:u===null?null:void 0,b=typeof d=="string"?d:d===null?null:void 0,x=typeof p=="string"?p:p===null?null:void 0,y=typeof f=="number"&&Number.isFinite(f)?f:f===null?null:void 0;return{eventName:t.eventName,occurredAt:t.occurredAt,actor:s,...n?{prefix:n}:{},...r?{renderer:r}:{},payload:c,...l?{envelope:l}:{},view:Ts(t.eventName,o),...oc(m,b,x,y)}}function Ts(e,t){const n=oY(e);if(t?.schemaVersion!==2)return n;const r=Pr(t.context),s=Pr(t.presentation),i=Pr(r?.project),o=Pr(r?.producer),l=Pr(r?.correlation);if(!r||!s||!i||!o||!l)return n;const c=s.severity==="info"||s.severity==="warning"||s.severity==="error"?s.severity:"warning",u=Array.isArray(s.fields)?s.fields.flatMap(A=>{const w=Pr(A),N=nn(w?.label,64),_=nn(w?.value,256);return N&&_?[{label:N,value:_}]:[]}).slice(0,8):[],d=[],p=(A,w)=>{const N=nn(w,128);N&&d.push({label:A,value:N})};p("Run",l.runId),p("Execution",l.executionId),p("Action",l.actionId),p("Entity",cY(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 f=nn(o.package,128)??"unavailable",m=nn(o.subsystem,128),b=lY(s.action),x=nn(s.actionLabel,128)??"unavailable",y=nn(s.agent,128),E=nn(s.correlators,512);return{severity:c,summary:nn(s.summary,512)??"unavailable",description:nn(s.description,512)??"Description unavailable.",fields:u,projectName:nn(i.name,128)??"unavailable",projectRoot:nn(i.root,256)??"unavailable",producer:m?`${f} / ${m}`:f,correlation:E??"unavailable",correlationFields:d,outcome:nn(s.outcome,128)??"unavailable",action:b,actionLabel:x,agent:y}}function oY(e){return{severity:"warning",summary:"unavailable",description:`Canonical context unavailable for ${nn(e,128)??"unknown"}.`,fields:[],projectName:"unavailable",projectRoot:"unavailable",producer:"unavailable",correlation:"unavailable",correlationFields:[],outcome:"unavailable",action:null,actionLabel:"unavailable",agent:null}}function lY(e){const t=Pr(e);if(!t||t.kind!=="command"&&t.kind!=="filter"&&t.kind!=="path")return null;const n=nn(t.label,128),r=nn(t.value,256);return n&&r?{label:n,kind:t.kind,value:r}:null}function nn(e,t){return typeof e!="string"||e.length===0?null:e.length<=t?e:`${e.slice(0,t-1)}…`}function cY(e,t){const n=nn(e,64),r=nn(t,128);return n&&r?`${n}:${r}`:n??r}const uY=["Entity","Run","Execution","Action","Job"];function dY(e,t){for(const n of uY){const r=t.correlationFields.find(s=>s.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 Pr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function oA(e){return e?.schemaVersion!==2?e:Pr(e.data)}const pY=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function G1(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=pY[t.getMonth()],r=t.getDate(),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0");return`${n} ${r} ${s}:${i}:${o}`}function Zr(e){return typeof e!="number"||!Number.isFinite(e)?null:e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}function wt(e){return e&&e!=="unavailable"?e:"-"}function fY(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 s=Ns(t);return s&&(n.since=s),n}function W1(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??Ts(e.eventName,e.payload??null)).severity!==t.severity)return!1;if(t.searchQuery.trim()!==""){const r=t.searchQuery.toLowerCase();let s=!1;if((t.searchScope==="name"||t.searchScope==="all")&&(s=s||e.eventName.toLowerCase().includes(r)),(t.searchScope==="actor"||t.searchScope==="all")&&(s=s||(e.actor?.toLowerCase().includes(r)??!1)),t.searchScope==="payload"&&e.payload&&(s=s||JSON.stringify(e.payload).toLowerCase().includes(r)),!s)return!1}return!(t.runId.trim()!==""&&e.runId!==t.runId.trim())}const qx={key:"time",direction:"desc"};function mY(e,t=qx){const n=e.map((r,s)=>({row:r,idx:s}));return n.sort((r,s)=>{let i=0;const o=r.row.view??Ts(r.row.eventName,r.row.payload??null),l=s.row.view??Ts(s.row.eventName,s.row.payload??null);switch(t.key){case"time":{const c=Date.parse(r.row.occurredAt),u=Date.parse(s.row.occurredAt),d=Number.isNaN(c)?-1/0:c,p=Number.isNaN(u)?-1/0:u;i=d-p;break}case"severity":{const c=u=>u==="info"?0:u==="warning"?1:2;i=c(o.severity)-c(l.severity);break}case"event":{i=r.row.eventName.localeCompare(s.row.eventName);break}case"summary":{i=(o.summary??"").localeCompare(l.summary??"");break}case"correlation":{i=(o.correlation??"").localeCompare(l.correlation??"");break}case"agent":{i=(o.agent??"").localeCompare(l.agent??"");break}case"outcome":{i=(o.outcome??"").localeCompare(l.outcome??"");break}default:i=0}return i!==0?t.direction==="asc"?i:-i:r.idx-s.idx}),n.map(r=>r.row)}function ps({value:e,label:t}){const[n,r]=h.useState("idle"),s=async i=>{i.preventDefault(),i.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:a.jsxs("button",{type:"button",onClick:s,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:[a.jsx("span",{"aria-hidden":"true",children:n==="copied"?"✓":n==="failed"?"!":"📋"}),a.jsx("span",{className:"sr-only","aria-live":"polite",children:n==="copied"?`${t} copied`:n==="failed"?`${t} copy failed`:""})]})}function hY({onLivenessChange:e,timeRange:t,navIntent:n}){const[r,s]=h.useState(()=>JV()),[i,o]=h.useState(qx),l=h.useCallback(P=>{o(oe=>oe.key===P?{key:P,direction:oe.direction==="asc"?"desc":"asc"}:{key:P,direction:"asc"})},[]),[c,u]=h.useState(!0),[d,p]=h.useState([]),[f,m]=h.useState([]),[b,x]=h.useState("idle"),[y,E]=h.useState(null),[A,w]=h.useState(null),[N,_]=h.useState(!1),[k,S]=h.useState(!1),[v,O]=h.useState(Sd),[C,M]=h.useState(Sd),[B,R]=h.useState("connecting"),{rate:z,recordEvent:W}=rY();h.useEffect(()=>{e?.({status:c?B:"paused",rate:z,lastEventAt:d[0]?.occurredAt??null})},[c,B,z,d,e]);const F=h.useMemo(()=>{const P=new Map;for(const oe of f)oe.tier&&P.set(oe.name,oe.tier);return P},[f]);h.useEffect(()=>{const P=window.setTimeout(()=>{M(v)},250);return()=>window.clearTimeout(P)},[v]),h.useEffect(()=>{if(n?.tab!=="system-events"||n.runId===void 0)return;const P=n.runId;O(oe=>oe.runId===P?oe:{...oe,runId:P}),M(oe=>oe.runId===P?oe:{...oe,runId:P})},[n]);const J=h.useMemo(()=>fY(C,t),[C,t]),K=h.useRef(0);h.useEffect(()=>{const P=++K.current,oe=new AbortController;return x("loading"),E(null),(async()=>{try{const re=await Xe(new Request(Dp({...J,limit:Rp}),{signal:oe.signal}));if(!re.ok){const me=await re.json().catch(()=>null),he=me?.code;throw he==="UNKNOWN_PREFIX"||he==="MALFORMED_CURSOR"?new Error(`${he}: ${me.error??re.status}`):new Error(`history fetch failed: ${re.status}`)}const H=await re.json(),Ce=Op(H);if(!Ce)throw new Error("history response failed schema validation");if(P!==K.current)return;p(Ce.events),Ce.catalog&&m(Ce.catalog),w(Ce.nextCursor),_(Ce.hasMore),x("loaded")}catch(re){if(oe.signal.aborted||P!==K.current)return;E(re instanceof Error?re.message:String(re)),x("error")}})(),()=>oe.abort()},[J]);const X=h.useCallback(async()=>{if(!(!N||k||A===null)){S(!0);try{const P=await Xe(new Request(Dp({...J,limit:Rp,cursor:A})));if(!P.ok)throw new Error(`history fetch failed: ${P.status}`);const oe=await P.json(),re=Op(oe);if(!re)throw new Error("history response failed schema validation");p(H=>{const Ce=new Set(H.map(he=>he.id)),me=re.events.filter(he=>!Ce.has(he.id));return[...H,...me]}),re.catalog&&m(re.catalog),w(re.nextCursor),_(re.hasMore)}catch(P){E(P instanceof Error?P.message:String(P))}finally{S(!1)}}},[N,k,A,J]),I=h.useRef(v);I.current=v;const V=h.useRef(F);V.current=F,h.useEffect(()=>{if(!c||typeof EventSource>"u")return;R("connecting");const P=new EventSource(tY());return P.onopen=()=>{R("live")},P.onerror=()=>{R("errored")},P.onmessage=oe=>{try{const re=JSON.parse(oe.data),H=iY(re);if(!H||H.eventName==="connected")return;const Ce=I.current,me=V.current;if(!W1({eventName:H.eventName,occurredAt:H.occurredAt,actor:H.actor,...H.prefix?{prefix:H.prefix}:{},payload:H.payload,view:H.view,...H.runId!==void 0?{runId:H.runId}:{}},Ce,me))return;const he={id:`live-${H.occurredAt}-${H.eventName}`,eventName:H.eventName,occurredAt:H.occurredAt,actor:H.actor,...H.prefix?{prefix:H.prefix}:{},...H.renderer?{renderer:H.renderer}:{},payload:H.payload,...H.envelope?{envelope:H.envelope}:{},view:H.view,...oc(H.runId,H.entityKind,H.entityId,H.sequence)};p(Ne=>[he,...Ne]),W()}catch{}},()=>P.close()},[c,W]);const te=h.useMemo(()=>Array.from(new Set([...f.map(P=>P.prefix),...d.map(P=>P.prefix??P.eventName.split(".")[0]??P.eventName)])).sort(),[f,d]),L=h.useCallback(()=>{O(Sd)},[]),ye=h.useMemo(()=>d.filter(P=>W1(P,v,F)),[d,v,F]),xe=h.useMemo(()=>mY(ye,i),[ye,i]);return b==="error"?a.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load event history: ",y]}):b==="idle"||b==="loading"?a.jsxs("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:[a.jsx(ln,{size:"sm"})," Loading event history…"]}):a.jsxs("div",{className:"flex flex-col gap-4","data-system-events-tab":!0,children:[a.jsx(ZV,{filters:v,onFiltersChange:O,onClearFilters:L,prefixOptions:te,getPrefixColor:iA,liveEnabled:c,onToggleLive:()=>u(P=>!P),shownCount:ye.length,totalCount:d.length,actions:a.jsx(eY,{visibleColumns:r,onVisibleColumnsChange:s})}),a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-sm border border-base-content/10 overflow-hidden flex flex-col",children:[xe.length===0?a.jsx("div",{className:"p-8 text-sm text-spur-text-muted italic text-center",children:d.length===0?"No system events yet. New events from the planning bus will appear here in real time.":"No events match the active filters."}):a.jsx(bY,{rows:xe,catalog:f,visibleColumns:r,sortState:i,onSortChange:l}),N&&a.jsx("div",{className:"px-4 py-2 border-t border-base-content/10 bg-base-200/50 shrink-0 flex justify-center",children:a.jsx("button",{type:"button",onClick:X,disabled:k,"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:k?"Loading…":"Load older"})})]})]})}function gY(e){const[t,n]=h.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches);return h.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),s=i=>n(i.matches);return r.addEventListener("change",s),n(r.matches),()=>r.removeEventListener("change",s)},[e]),t}function bY({rows:e,catalog:t,visibleColumns:n=Yr,sortState:r=qx,onSortChange:s=()=>{}}){const i=h.useMemo(()=>{const c=new Map;for(const u of t)u.tier&&c.set(u.name,u.tier);return c},[t]),o=gY("(max-width: 639px)"),l=h.useMemo(()=>new Map(ma.map(c=>[c.key,c])),[]);return a.jsx("section",{className:"overflow-x-auto min-w-0","data-system-events-tab":!0,"aria-label":"System events",children:a.jsxs("table",{className:`w-full ${o?"min-w-0":"min-w-[1000px]"} text-xs border-separate border-spacing-0 table-fixed`,children:[a.jsx("colgroup",{children:o?a.jsxs(a.Fragment,{children:[a.jsx("col",{className:"w-24"}),a.jsx("col",{className:"w-full"})]}):n.map(c=>a.jsx("col",{className:l.get(c)?.colWidth??"w-24"},c))}),a.jsx("thead",{className:"sticky top-0 z-10 bg-base-200",children:a.jsx("tr",{className:"text-left text-spur-text-muted uppercase tracking-wide text-[10px]",children:o?a.jsxs(a.Fragment,{children:[a.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:"Time"}),a.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:"Event"})]}):n.map(c=>{const u=l.get(c);if(!u)return null;const d=r.key===c,p=d?r.direction==="asc"?" ▲":" ▼":"",f=d?r.direction==="asc"?"ascending":"descending":"none";return u.sortable?a.jsx("th",{scope:"col","aria-sort":f,className:"font-semibold px-3 py-1.5 border-b border-spur-border select-none",children:a.jsxs("button",{type:"button",onClick:()=>s(c),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:[a.jsx("span",{children:u.label}),p&&a.jsx("span",{"aria-hidden":"true",children:p})]})},c):a.jsx("th",{scope:"col",className:"font-semibold px-3 py-1.5 border-b border-spur-border",children:u.label},c)})})}),a.jsx("tbody",{children:e.map(c=>a.jsx(xY,{event:c,tier:i.get(c.eventName)??"default",compact:o,visibleColumns:n},c.id))})]})})}const wd="system-events-payload-tooltip-pin";function vd({severity:e}){const t=h.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 a.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:[a.jsx("span",{"aria-hidden":"true",children:t.icon}),a.jsx("span",{children:e})]})}function xY({event:e,tier:t,compact:n,visibleColumns:r=Yr}){const s=e.prefix??e.eventName.split(".")[0]??e.eventName,i=h.useMemo(()=>e.view??Ts(e.eventName,e.payload??null),[e.eventName,e.payload,e.view]),o=iA(s),[l,c]=h.useState(!1),[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,b]=h.useState(null),x=h.useRef(null),y=h.useRef(null),E=h.useRef(0),A=h.useRef(null),w=wt(e.actor),N=u||p,_=h.useCallback(()=>{A.current!==null&&(clearTimeout(A.current),A.current=null)},[]),k=h.useCallback(()=>{f(!1),b(null)},[]),S=h.useCallback((R,z)=>{E.current=performance.now()+400,f(!0),d(!1),_();const W=Number.isFinite(R)&&R>0?R:8,F=Number.isFinite(z)&&z>0?z:8;b({x:W,y:F}),window.dispatchEvent(new CustomEvent(wd,{detail:{id:e.id}}))},[e.id,_]),v=h.useCallback((R,z,W)=>{const F=R.getBoundingClientRect(),J=z&&z>0?z:F.left,K=W&&W>0?W+4:F.bottom+6;S(J,K)},[S]);h.useEffect(()=>{const R=z=>{z.detail?.id!==e.id&&k()};return window.addEventListener(wd,R),()=>window.removeEventListener(wd,R)},[e.id,k]),h.useEffect(()=>{if(!p)return;const R=W=>{performance.now()<E.current||x.current?.contains(W.target)||y.current?.contains(W.target)||k()},z=W=>{W.key==="Escape"&&(k(),W.stopPropagation())};return document.addEventListener("pointerdown",R,!0),document.addEventListener("keydown",z,!0),()=>{document.removeEventListener("pointerdown",R,!0),document.removeEventListener("keydown",z,!0)}},[p,k]),h.useEffect(()=>()=>{_()},[_]);const O=h.useCallback(()=>c(R=>!R),[]),C=h.useCallback(R=>{if(R.key==="Escape"){if(p){k(),R.stopPropagation();return}c(!1),R.stopPropagation()}},[p,k]),M=N?a.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&&m?{top:m.y,left:m.x}:void 0,onMouseEnter:()=>{_(),d(!0)},onMouseLeave:()=>{p||(_(),A.current=setTimeout(()=>d(!1),150))},onFocusCapture:()=>d(!0),onBlurCapture:R=>{!p&&!R.currentTarget.contains(R.relatedTarget)&&d(!1)},onPointerDown:R=>{p&&R.stopPropagation()},children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[a.jsx("div",{className:"text-[11px] font-sans font-semibold text-[#c9d1d9] truncate","data-testid":"system-event-tooltip-title",children:dY(e,i)}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[!p&&a.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:R=>{R.stopPropagation(),R.preventDefault();const z=y.current;z?v(z):S(R.clientX,R.clientY)},children:"Pin"}),p&&a.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:R=>{R.stopPropagation(),k()},children:"close"})]})]}),a.jsx("p",{className:"mb-2 text-spur-text leading-relaxed","data-testid":"system-event-description",children:i.description}),a.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 max-h-80 overflow-y-auto",children:[a.jsx("dt",{className:"text-spur-text-muted",children:"Summary"}),a.jsx("dd",{className:"break-words",children:wt(i.summary)}),a.jsx("dt",{className:"text-spur-text-muted",children:"Severity"}),a.jsx("dd",{children:a.jsx(vd,{severity:i.severity})}),i.fields.map(R=>a.jsxs("div",{className:"contents",children:[a.jsx("dt",{className:"text-spur-text-muted",children:R.label}),a.jsx("dd",{className:"font-mono break-all",children:wt(R.value)})]},R.label+R.value)),a.jsx("dt",{className:"text-spur-text-muted",children:"Producer"}),a.jsx("dd",{className:"font-mono break-all",children:wt(i.producer)}),i.correlationFields.length>0?i.correlationFields.map(R=>a.jsxs("div",{className:"contents",children:[a.jsx("dt",{className:"text-spur-text-muted",children:R.label}),a.jsx("dd",{className:"font-mono break-all",children:wt(R.value)})]},`correlation-${R.label}`)):a.jsxs(a.Fragment,{children:[a.jsx("dt",{className:"text-spur-text-muted",children:"Correlation"}),a.jsx("dd",{className:"font-mono",children:"-"})]}),a.jsx("dt",{className:"text-spur-text-muted",children:"Outcome"}),a.jsx("dd",{className:"font-mono break-all",children:wt(i.outcome)})]}),i.action&&a.jsxs("div",{className:"mt-2 border-t border-[#30363d] pt-2","data-testid":"system-event-remediation",children:[a.jsx("div",{className:"text-spur-text-muted",children:i.action.label}),a.jsx("code",{className:"block mt-0.5 font-mono break-all select-text",children:i.action.value})]}),a.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,B=R=>{switch(R){case"time":return a.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-spur-text-muted whitespace-nowrap align-middle",children:G1(e.occurredAt)},"time");case"severity":return a.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 align-middle text-[10px]",children:a.jsx(vd,{severity:i.severity})},"severity");case"event":return a.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 relative align-middle min-w-0",children:a.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[a.jsx("button",{type:"button","aria-expanded":l,"aria-controls":`detail-${e.id}`,"aria-label":`${l?"Collapse":"Expand"} detail for ${e.eventName}`,onClick:O,onKeyDown:C,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?"▾":"▸"}),a.jsxs("div",{className:"relative min-w-0 max-w-full flex items-center gap-1",children:[a.jsx("button",{ref:y,type:"button",className:`font-mono font-semibold truncate block max-w-full text-left cursor-pointer bg-transparent border-0 p-0 ${o}`,"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:()=>{_(),d(!0)},onFocus:()=>{_(),d(!0)},onBlur:z=>{!p&&!x.current?.contains(z.relatedTarget)&&d(!1)},onMouseLeave:()=>{_(),A.current=setTimeout(()=>{p||d(!1)},200)},onClick:z=>{z.preventDefault(),z.stopPropagation(),!p&&v(z.currentTarget,z.clientX,z.clientY)},onKeyDown:z=>{if(z.key==="Enter"||z.key===" "){if(z.preventDefault(),p)return;v(z.currentTarget)}},children:e.eventName}),a.jsx(ps,{value:e.eventName,label:"event name"}),!p&&M]})]})},"event");case"summary":return a.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 text-spur-text align-middle truncate",title:wt(i.summary),children:wt(i.summary)},"summary");case"correlation":return a.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-[10px] text-spur-text-muted align-middle",children:a.jsxs("div",{className:"flex items-center gap-1 min-w-0",children:[a.jsx("span",{className:"truncate",title:wt(i.correlation),children:wt(i.correlation)}),i.correlation&&i.correlation!=="unavailable"&&a.jsx(ps,{value:i.correlation,label:"correlation"})]})},"correlation");case"outcome":return a.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:wt(i.outcome),children:wt(i.outcome)},"outcome");case"agent":return a.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:i.agent??"",children:i.agent??""},"agent");case"producer":return a.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:wt(i.producer),children:wt(i.producer)},"producer");case"action":return a.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:wt(i.actionLabel),children:wt(i.actionLabel)},"action");case"actor":return a.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:w,children:w},"actor")}};return a.jsxs(a.Fragment,{children:[a.jsx("tr",{className:"group hover:bg-base-200/60 transition-colors",style:{height:n?void 0:28},children:n?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 font-mono text-spur-text-muted whitespace-nowrap align-middle",children:G1(e.occurredAt)}),a.jsx("td",{className:"px-3 py-1 border-b border-spur-border/40 relative align-middle min-w-0",children:a.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[a.jsx("button",{type:"button","aria-expanded":l,"aria-controls":`detail-${e.id}`,"aria-label":`${l?"Collapse":"Expand"} detail for ${e.eventName}`,onClick:O,onKeyDown:C,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?"▾":"▸"}),a.jsxs("div",{className:"relative min-w-0 max-w-full flex items-center gap-1",children:[a.jsx("button",{ref:y,type:"button",className:`font-mono font-semibold truncate block max-w-full text-left cursor-pointer bg-transparent border-0 p-0 ${o}`,"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:()=>{_(),d(!0)},onFocus:()=>{_(),d(!0)},onBlur:R=>{!p&&!x.current?.contains(R.relatedTarget)&&d(!1)},onMouseLeave:()=>{_(),A.current=setTimeout(()=>{p||d(!1)},200)},onClick:R=>{R.preventDefault(),R.stopPropagation(),!p&&v(R.currentTarget,R.clientX,R.clientY)},onKeyDown:R=>{if(R.key==="Enter"||R.key===" "){if(R.preventDefault(),p)return;v(R.currentTarget)}},children:e.eventName}),a.jsx(ps,{value:e.eventName,label:"event name"}),!p&&M]})]}),a.jsxs("div",{className:"flex flex-col gap-0.5 text-[10px] text-spur-text-muted min-w-0",children:[a.jsx(vd,{severity:i.severity}),a.jsx("span",{className:"truncate text-spur-text",title:wt(i.summary),children:wt(i.summary)}),a.jsx("span",{className:"truncate",title:wt(i.producer),children:wt(i.producer)}),a.jsx("span",{className:"truncate",title:wt(i.correlation),children:wt(i.correlation)}),i.agent&&a.jsxs("span",{className:"truncate font-mono",title:i.agent,children:["agent: ",i.agent]}),a.jsxs("span",{className:"truncate",children:["outcome: ",wt(i.outcome)]}),a.jsxs("span",{className:"truncate",title:wt(i.actionLabel),children:["action: ",wt(i.actionLabel)]})]})]})})]}):r.map(R=>B(R))}),l&&a.jsx("tr",{children:a.jsx("td",{colSpan:n?2:r.length,className:"px-3 py-2 border-b border-spur-border/40 bg-base-300/40",children:a.jsxs("section",{id:`detail-${e.id}`,"aria-label":`Detail for ${e.eventName}`,onKeyDown:C,tabIndex:-1,className:"flex flex-col gap-2 text-[11px] text-spur-text max-w-full",children:[a.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 font-mono text-[10px]",children:[a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"project:"})," ",wt(i.projectName)]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"root:"})," ",wt(i.projectRoot)]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"producer:"})," ",wt(i.producer)]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"correlation:"})," ",wt(i.correlation)]}),e.runId&&a.jsxs("span",{className:"inline-flex items-center gap-1",children:[a.jsx("span",{className:"text-spur-text-muted",children:"runId:"})," ",e.runId," ",a.jsx(ps,{value:e.runId,label:"run ID"})]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"agent:"})," ",i.agent||"-"]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"actor:"})," ",w]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"prefix:"})," ",s]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"tier:"})," ",t]}),a.jsxs("span",{children:[a.jsx("span",{className:"text-spur-text-muted",children:"outcome:"})," ",wt(i.outcome)]})]}),i.fields.length>0&&a.jsx("dl",{className:"space-y-0.5",children:i.fields.map(R=>a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("dt",{className:"text-spur-text-muted shrink-0",children:[R.label,":"]}),a.jsx("dd",{className:"font-mono break-all",children:wt(R.value)})]},R.label+R.value))}),a.jsxs("div",{className:"border-t border-spur-border/40 pt-1",children:[a.jsx("div",{className:"text-spur-text-muted text-[10px] mb-0.5",children:"payload (redacted):"}),a.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):"-"})]}),a.jsx("button",{type:"button",onClick:()=>c(!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&&M&&typeof document<"u"?Ur.createPortal(M,document.body):null]})}function yY(e){switch(e){case"accepted":return"success";case"fallback":return"warning";default:return"error"}}function q1(e){if(e===null||e==="")return"—";try{return JSON.stringify(JSON.parse(e))}catch{return e}}function EY(e){if(e===null||e==="")return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function SY(e){if(e.confidence===null)return e.confidenceLevel;const t=e.minConfidence!==null?` (min ${e.minConfidence})`:"";return`${e.confidenceLevel} · ${e.confidence}${t}`}function wY({row:e,onClose:t,onNavigate:n}){const[r,s]=h.useState(null),[i,o]=h.useState(null),l=h.useRef(0);if(h.useEffect(()=>{if(!e){s(null),o(null);return}const f=x=>{x.key==="Escape"&&t()};window.addEventListener("keydown",f);const m=new AbortController,b=++l.current;return o(null),(async()=>{try{const x=await Xe(new Request(`${it()}/observability/decisions/${encodeURIComponent(e.id)}`,{signal:m.signal}));if(!x.ok)throw new Error(`HTTP ${x.status}`);const y=await x.json();if(m.signal.aborted||b!==l.current)return;s(y)}catch(x){if(m.signal.aborted||b!==l.current)return;o(x instanceof Error?x.message:String(x))}})(),()=>{window.removeEventListener("keydown",f),m.abort()}},[e,t]),!e)return null;const c=r??{...e,question:null,inputJson:null,phases:[]},u=c.runId,d=EY(c.inputJson),p=[{label:"Decision",value:c.decisionId},{label:"Outcome",value:c.outcome},{label:"Maker",value:c.makerName?`${c.makerName} (${c.makerSource??"?"})`:"—"},{label:"Caller",value:c.caller},{label:"Value",value:q1(c.value)},{label:"Fallback",value:q1(c.fallbackValue)},{label:"Source",value:c.source??"—"},{label:"Reason",value:c.reason??"—"},{label:"Confidence",value:SY(c)},{label:"Catalog layer",value:c.catalogLayer??"—"},{label:"Catalog source",value:c.catalogSource??"—"},{label:"Started At",value:new Date(c.startedAt).toLocaleString()},{label:"Duration",value:Zr(c.durationMs)??"—"},{label:"Input keys",value:c.inputKeys.length>0?c.inputKeys.join(", "):"—"}];return c.workflowName!==null&&p.push({label:"Workflow",value:c.workflowName}),c.nodeId!==null&&p.push({label:"Node",value:c.nodeId}),c.wbs!==null&&p.push({label:"WBS",value:c.wbs}),c.runId!==null&&p.push({label:"Run",value:c.runId}),c.decisionType!==null&&p.push({label:"Type",value:c.decisionType}),a.jsx("div",{className:"fixed inset-0 z-50 flex justify-end bg-black/60 backdrop-blur-xs",onClick:t,onKeyDown:f=>{f.key==="Escape"&&t()},role:"dialog","aria-modal":"true","aria-label":`Decision details for ${c.id}`,"data-testid":"decision-detail-drawer",children:a.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:f=>f.stopPropagation(),onKeyDown:f=>f.stopPropagation(),role:"document",children:[a.jsxs("div",{className:"px-5 py-4 border-b border-base-content/10 flex items-center justify-between bg-base-200/50",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tt,{variant:yY(c.outcome),size:"sm",children:c.outcome}),a.jsx("span",{className:"font-mono text-sm font-semibold text-base-content truncate max-w-xs",children:c.decisionId})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[n&&u!==null&&a.jsx(Ie,{variant:"outline",size:"xs","data-testid":"navigate-decision-run-events-btn",onClick:()=>n({tab:"system-events",runId:u}),children:"View run events"}),a.jsx(Ie,{variant:"ghost",size:"xs",onClick:t,"aria-label":"Close drawer","data-testid":"close-decision-drawer",children:"✕"})]})]}),a.jsxs("div",{className:"p-5 flex-1 overflow-y-auto space-y-5",children:[i&&a.jsxs("div",{className:"p-3 rounded-lg bg-warning/10 border border-warning/20 text-xs text-warning",role:"alert",children:["Detail fetch failed (",i,"); showing list data."]}),a.jsx("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:p.map(f=>a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:f.label}),a.jsx("span",{className:"font-semibold text-base-content break-words",children:f.value})]},f.label))}),c.error&&a.jsx("div",{className:"p-3 rounded-lg bg-error/10 border border-error/20 text-xs font-mono text-error break-words",children:c.error}),c.question&&a.jsxs("div",{children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60 mb-2",children:"Question"}),a.jsx("p",{className:"text-sm text-base-content bg-base-200/40 border border-base-content/10 rounded-lg p-3",children:c.question})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[a.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:["Input ",c.inputJson===null?"(metadata mode)":"(redacted)"]}),c.inputJson!==null&&a.jsx(ps,{value:d,label:"input JSON"})]}),c.inputJson===null?a.jsx("p",{className:"text-xs text-base-content/50",children:"Not recorded — decision log metadata mode."}):a.jsx("pre",{className:"text-xs font-mono bg-base-200/40 border border-base-content/10 rounded-lg p-3 overflow-x-auto whitespace-pre-wrap break-words","data-testid":"decision-detail-input",children:d})]}),a.jsxs("div",{children:[a.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60 mb-2",children:"Phases"}),c.phases.length===0?a.jsx("p",{className:"text-xs text-base-content/50",children:"No phase timings recorded."}):a.jsx("ul",{className:"space-y-1","data-testid":"decision-detail-phases",children:c.phases.map(f=>a.jsxs("li",{className:"flex items-center justify-between text-xs font-mono bg-base-200/40 border border-base-content/10 rounded-lg px-3 py-1.5",children:[a.jsx("span",{className:"font-semibold",children:f.phase}),a.jsx("span",{className:"text-base-content/60",children:Zr(f.durationMs)??`${f.durationMs}ms`})]},`${f.phase}-${f.startedAt}-${f.durationMs}`))})]})]})]})})}function lA(e){return`/board/observability?tab=trace&wbs=${encodeURIComponent(e)}`}function pee({wbs:e}){const t=mc(),n=lA(e);return a.jsxs(gl,{to:n,"data-task-run-evidence":e,className:"text-xs text-spur-accent underline",onKeyDown:r=>{r.key!=="Enter"&&r.key!==" "||(r.preventDefault(),t(n))},children:["Run evidence for ",e]})}const vY={notDone:"Not done",forcedDone:"Forced done",missingVerdict:"Missing verdict",syntheticVerdict:"Synthetic verdict",verdictNotPass:"Verdict not PASS",proofAbsent:"Proof absent",certifyingRunFailed:"Certifying run failed"};function NY({outcomes:e}){const t=e.verified,n=t?Object.entries(t.excludedReasons).filter(([,s])=>s>0):[],r=Object.entries(e.terminalReasonMix);return a.jsxs("section",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3","data-testid":"summary-outcomes","aria-labelledby":"summary-outcomes-heading",children:[a.jsx("h3",{id:"summary-outcomes-heading",className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Verified outcomes"}),a.jsxs("dl",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 text-sm",children:[a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Verified tasks"}),a.jsx("dd",{className:"font-mono","data-testid":"outcome-verified-tasks",children:t===null?"Verified outcomes unavailable":`${t.verifiedResults} of ${t.taskDenominator}`})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Corrections (tasks)"}),a.jsx("dd",{className:"font-mono","data-testid":"outcome-corrections",children:t===null?"—":t.correctionCount})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Retry exhausted (tasks)"}),a.jsx("dd",{className:"font-mono","data-testid":"outcome-retry-exhausted",children:t===null?"—":t.retryExhaustedCount})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Measured USD"}),a.jsx("dd",{className:"font-mono","data-testid":"outcome-measured-usd",children:e.measuredUsd===null?"Measured USD unavailable":e.measuredUsd})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Tokens"}),a.jsx("dd",{className:"font-mono","data-testid":"outcome-tokens",children:e.tokens===null?"—":e.tokens})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Cost coverage"}),a.jsxs("dd",{className:"font-mono","data-testid":"outcome-unknown-cost",children:[e.usdRows," of ",e.historyRows," history rows have persisted USD ·"," ",e.unknownUsdRows," unknown USD rows · ",e.unknownCostRunCount," runs with unknown cost"]})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Gate duration"}),a.jsxs("dd",{className:"font-mono","data-testid":"outcome-gate",children:[e.gateDurationMs===null?"Gate duration unavailable":`${e.gateDurationMs} ms`," ","· ",e.gateSampleCount," samples"]})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-xs text-base-content/60",children:"Terminal reasons"}),a.jsx("dd",{className:"font-mono","data-testid":"outcome-terminal-reasons",children:r.length===0?"No terminal runs":r.map(([s,i])=>`${s} ${i}`).join(", ")})]})]}),t!==null&&t.timeToVerified.count>0?a.jsxs("p",{className:"text-xs text-base-content/70","data-testid":"outcome-time-to-verified",children:["Mean time to verified ",t.timeToVerified.meanMs," ms"]}):null,n.length>0?a.jsx("ul",{className:"text-xs text-base-content/70","data-testid":"outcome-excluded",children:n.map(([s,i])=>a.jsxs("li",{children:[vY[s]??s,": ",i]},s))}):null,a.jsx("ul",{className:"flex flex-col gap-1 text-xs",children:e.evidence.map(s=>a.jsx("li",{"data-testid":`outcome-evidence-${s.runId}`,children:s.wbs!==null?a.jsxs(a.Fragment,{children:[a.jsxs(gl,{to:`/board/tasks/${encodeURIComponent(s.wbs)}`,children:["Task ",s.wbs]})," · ",a.jsxs(gl,{to:lA(s.wbs),children:["Trace ",s.runId]})]}):a.jsxs(gl,{to:"/board/observability?tab=trace",children:["Trace ",s.runId]})},s.runId))}),e.evidenceTruncated?a.jsx("p",{className:"text-xs text-base-content/70","data-testid":"outcome-evidence-truncated",children:"Evidence list truncated at 100; totals cover the full window."}):null]})}const TY={system:"#38bdf8",task:"#818cf8",feature:"#a78bfa",queue:"#f59e0b",scheduler:"#10b981",rule:"#ec4899",agent:"#06b6d4",history:"#64748b"},V1=["#38bdf8","#818cf8","#a78bfa","#f59e0b","#10b981","#ec4899","#06b6d4","#f43f5e","#64748b"];function ol(e){const t=TY[e];if(t)return t;let n=0;for(let s=0;s<e.length;s++)n=(n<<5)-n+e.charCodeAt(s),n|=0;const r=Math.abs(n)%V1.length;return V1[r]??"#38bdf8"}function kY(e){return e==null||!Number.isFinite(e)?"—":(e/1e3).toFixed(2)}const AY=(e,t)=>t===void 0||t===0?null:(e-t)/Math.abs(t)*100,CY=h.memo(({current:e,previous:t,invert:n=!1})=>{if(t===void 0)return a.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});if(t===0)return a.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=AY(e,t);if(r===null)return a.jsx("span",{className:"text-[10px] text-base-content/40",children:"No prior baseline"});const s=r>=0,i=n?!s:s;return a.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold font-mono ${i?"bg-emerald-500/15 text-emerald-400":"bg-error/15 text-error"}`,children:[s?"↑ +":"↓ ",Math.abs(r).toFixed(1),"% vs previous period"]})}),Gr=h.memo(({label:e,value:t,sub:n,trend:r,trendColor:s="#38bdf8",current:i,previous:o,invert:l,testId:c,extra:u})=>a.jsxs("div",{className:"bg-base-200 rounded-xl shadow-xs border border-base-content/10 p-4","data-testid":c,children:[a.jsxs("div",{className:"flex justify-between items-start gap-2",children:[a.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:e}),u]}),a.jsxs("div",{className:"flex items-end justify-between gap-2 mt-1",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold font-mono text-primary",children:t}),a.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[a.jsx(CY,{current:i,previous:o,invert:l}),a.jsx("span",{className:"text-xs text-base-content/60",children:n})]})]}),r&&r.length>1?a.jsx(Vk,{values:r,color:s,width:100,height:34}):null]})]}));function _Y(e){const t=h.useRef(0),[n,r]=h.useState(null),[s,i]=h.useState(null),[o,l]=h.useState(!0),[c,u]=h.useState(null),d=e.timeRange??"4h";h.useEffect(()=>{const S=++t.current,v=new AbortController;l(!0),u(null);async function O(){try{const C=Date.now(),M=Ns(d,C),B=new Date(C).toISOString();let R=`${it()}/observability/summary`;if(M){const I=new URLSearchParams({since:M,until:B});R+=`?${I.toString()}`}const z=Xe(new Request(R,{signal:v.signal}),1e4);let W=Promise.resolve(null);if(M){const I=new Date(M).getTime(),V=C-I,te=new Date(I-V).toISOString(),L=M,ye=new URLSearchParams({since:te,until:L,period:"previous"}),xe=`${it()}/observability/summary?${ye.toString()}`;W=Xe(new Request(xe,{signal:v.signal}),1e4).catch(()=>null)}const[F,J]=await Promise.all([z,W]);if(S!==t.current)return;if(!F.ok){const I=await F.text();throw new Error(`HTTP ${F.status}: ${I||F.statusText}`)}const K=await F.json();let X=null;if(J?.ok)try{X=await J.json()}catch{}if(S!==t.current)return;r(K),i(X),l(!1)}catch(C){if(v.signal.aborted||S!==t.current)return;u(C instanceof Error?C.message:String(C)),l(!1)}}return O(),()=>{v.abort()}},[d]);const{series:p,chartBuckets:f}=h.useMemo(()=>{const S=n?.eventVolumeBuckets??[],v={};for(const B of S)for(const[R,z]of Object.entries(B.byPrefix))v[R]=(v[R]??0)+z;const C=Object.keys(v).sort((B,R)=>(v[R]??0)-(v[B]??0)).map(B=>({id:B,label:B,color:ol(B)})),M=S.map(B=>({id:B.timestamp,label:Yi(B.timestamp),v:B.byPrefix}));return{series:C,chartBuckets:M}},[n?.eventVolumeBuckets]),{decisionSeries:m,decisionChartBuckets:b}=h.useMemo(()=>{const S=n?.decisionVolumeBuckets??[],v={};for(const B of S)for(const[R,z]of Object.entries(B.byDecision))v[R]=(v[R]??0)+z;const C=Object.keys(v).sort((B,R)=>(v[R]??0)-(v[B]??0)).map(B=>({id:B,label:B,color:ol(B)})),M=S.map(B=>{const R=B.total,z=B.byOutcome?.accepted??0,W=R>0?z/R*100:void 0;return{id:B.timestamp,label:Yi(B.timestamp),v:B.byDecision,lineValue:W}});return{decisionSeries:C,decisionChartBuckets:M}},[n?.decisionVolumeBuckets]),x=h.useMemo(()=>{const S={info:0,warning:0,error:0,unknown:0};for(const O of n?.eventVolumeBuckets??[])S.info+=O.bySeverity.info,S.warning+=O.bySeverity.warning,S.error+=O.bySeverity.error,S.unknown+=O.bySeverity.unknown;const v=S.info+S.warning+S.error+S.unknown;return{counts:S,sum:v}},[n?.eventVolumeBuckets]);if(o)return a.jsxs("div",{className:"flex flex-col gap-6 animate-pulse","data-testid":"observability-summary-tab","data-summary-tab":!0,children:[a.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(S=>a.jsx("div",{className:"h-24 bg-base-200/60 rounded-xl"},S))}),a.jsx("div",{className:"h-64 bg-base-200/60 rounded-xl"}),a.jsx("div",{className:"h-64 bg-base-200/60 rounded-xl"})]});if(c)return a.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:a.jsxs("span",{children:["Failed to load observability summary: ",c]})});const y=n?.kpis??{totalEvents:0,activeJobs:0,completedJobs:0,failedJobs:0,successRatePct:0,errorEventCount:0,warningEventCount:0},E=s?.kpis,A=n?.eventVolumeBuckets??[],w=A.map(S=>S.total),N=A.map(S=>S.bySeverity.error+S.bySeverity.warning),_=S=>{e.onNavigate?.({tab:"jobs",jobId:S})},k=(S,v)=>{e.onNavigate?.({tab:"system-events",eventName:S,runId:v})};return a.jsxs("div",{className:"flex flex-col gap-6","data-testid":"observability-summary-tab","data-summary-tab":!0,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsx(Gr,{label:"Total Events",value:Lt(y.totalEvents),sub:"events in window",trend:w,trendColor:"#38bdf8",current:y.totalEvents,previous:E?.totalEvents,testId:"kpi-card-total-events",extra:a.jsxs("div",{className:"flex flex-col items-end gap-1","data-testid":"severity-breakdown",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-x-2 text-[10px] text-base-content/70 font-mono",children:[a.jsxs("span",{className:"flex items-center gap-1",title:`Info: ${x.counts.info}`,children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-info inline-block"})," Info:"," ",x.counts.info.toLocaleString()]}),a.jsxs("span",{className:"flex items-center gap-1",title:`Warning: ${x.counts.warning}`,children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-warning inline-block"})," Warning:"," ",x.counts.warning.toLocaleString()]}),a.jsxs("span",{className:"flex items-center gap-1",title:`Error: ${x.counts.error}`,children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-error inline-block"})," Error:"," ",x.counts.error.toLocaleString()]}),a.jsxs("span",{className:"flex items-center gap-1",title:`Unknown: ${x.counts.unknown}`,children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-base-content/30 inline-block"})," ","Unknown: ",x.counts.unknown.toLocaleString()]})]}),a.jsx("div",{className:"w-36 h-1.5 rounded-full bg-base-300 overflow-hidden flex","data-testid":"severity-distribution-bar",children:x.sum>0?a.jsxs(a.Fragment,{children:[x.counts.info>0&&a.jsx("div",{style:{width:`${x.counts.info/x.sum*100}%`},className:"bg-info h-full",title:`Info: ${x.counts.info}`,"data-testid":"severity-bar-info"}),x.counts.warning>0&&a.jsx("div",{style:{width:`${x.counts.warning/x.sum*100}%`},className:"bg-warning h-full",title:`Warning: ${x.counts.warning}`,"data-testid":"severity-bar-warning"}),x.counts.error>0&&a.jsx("div",{style:{width:`${x.counts.error/x.sum*100}%`},className:"bg-error h-full",title:`Error: ${x.counts.error}`,"data-testid":"severity-bar-error"}),x.counts.unknown>0&&a.jsx("div",{style:{width:`${x.counts.unknown/x.sum*100}%`},className:"bg-base-content/20 h-full",title:`Unknown: ${x.counts.unknown}`,"data-testid":"severity-bar-unknown"})]}):a.jsx("div",{className:"w-full h-full bg-base-content/10"})})]})}),a.jsx(Gr,{label:"Active In-Flight Jobs",value:Lt(y.activeJobs),sub:"pending & processing",current:y.activeJobs,previous:E?.activeJobs,testId:"kpi-card-active-jobs"}),a.jsx(Gr,{label:"Success Rate",value:`${y.successRatePct}%`,sub:`${y.completedJobs} ok / ${y.failedJobs} fail`,current:y.successRatePct,previous:E?.successRatePct,testId:"kpi-card-success-rate"}),a.jsx(Gr,{label:"Errors & Warnings",value:`${y.errorEventCount} / ${y.warningEventCount}`,sub:"error / warning events",trend:N,trendColor:"#ef4444",current:y.errorEventCount+y.warningEventCount,previous:E?E.errorEventCount+E.warningEventCount:void 0,invert:!0,testId:"kpi-card-errors-warnings"})]}),n?.outcomes?a.jsx(NY,{outcomes:n.outcomes}):null,a.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[a.jsx("div",{className:"flex justify-between items-center",children:a.jsxs("div",{children:[a.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Event Volume Over Time"}),a.jsx("p",{className:"text-xs text-base-content/60 mt-0.5",children:"Distribution stacked by event prefix"})]})}),f.length>0&&p.length>0?a.jsx("div",{className:"mt-2","data-testid":"stacked-event-volume-chart",children:a.jsx(kp,{buckets:f,series:p,height:240})}):a.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."})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Decision Volume Over Time"}),a.jsx("p",{className:"text-xs text-base-content/60 mt-0.5",children:"Distribution stacked by decision with success rate overlay"})]}),a.jsx("div",{className:"flex items-center gap-2 text-xs","data-testid":"decision-success-rate-legend",children:a.jsxs("span",{className:"flex items-center gap-1.5 text-success font-medium",children:[a.jsx("span",{className:"w-2.5 h-0.5 bg-success inline-block rounded-full"}),"Success Rate (%)"]})})]}),b.length>0&&m.length>0?a.jsx("div",{className:"mt-2","data-testid":"stacked-decision-volume-chart",children:a.jsx(kp,{buckets:b,series:m,lineColor:"#10b981",lineLabel:"Success Rate",height:240})}):a.jsx("div",{className:"p-8 text-center text-xs text-base-content/50","data-testid":"empty-decision-chart-fallback",children:"No decision activity recorded in this time range."})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[a.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[a.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Top Event Types"}),a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"table table-xs w-full font-mono text-xs","data-testid":"top-event-types-table",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{children:"Event Name"}),a.jsx("th",{children:"Prefix"}),a.jsx("th",{className:"text-right",children:"Count"}),a.jsx("th",{className:"text-right",title:"Average duration in seconds",children:"Avg(Duration - s)"}),a.jsx("th",{className:"text-right",title:"Events with error severity",children:"Failures"}),a.jsx("th",{className:"text-right",children:"Latest"})]})}),a.jsxs("tbody",{children:[(n?.topEventTypes??[]).map(S=>a.jsxs("tr",{className:"hover:bg-base-300/40",children:[a.jsx("td",{className:"font-semibold text-base-content",children:S.name}),a.jsx("td",{children:a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-bold border",style:{color:ol(S.prefix),borderColor:ol(S.prefix)},children:S.prefix})}),a.jsx("td",{className:"text-right text-base-content/80 tabular-nums",children:S.count.toLocaleString()}),a.jsx("td",{className:"text-right text-base-content/80 tabular-nums","data-testid":`top-event-avg-${S.name}`,children:kY(S.avgDurationMs)}),a.jsx("td",{className:`text-right tabular-nums ${S.failureCount>0?"text-error font-semibold":"text-base-content/80"}`,"data-testid":`top-event-failures-${S.name}`,children:S.failureCount.toLocaleString()}),a.jsx("td",{className:"text-right text-base-content/50",children:new Date(S.latestAt).toLocaleTimeString()})]},S.name)),(!n||(n.topEventTypes??[]).length===0)&&a.jsx("tr",{children:a.jsx("td",{colSpan:6,className:"text-center text-base-content/40 py-4",children:"No events recorded"})})]})]})})]}),a.jsxs("div",{className:"bg-base-200 rounded-xl border border-base-content/10 p-4 flex flex-col gap-3",children:[a.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Recent Failures"}),a.jsxs("div",{className:"flex flex-col gap-2 max-h-[320px] overflow-y-auto","data-testid":"recent-failures-feed",children:[(n?.recentErrors??[]).map(S=>{const v=!!e.onNavigate,O=()=>{S.source==="job"?_(S.id):k(S.name,S.refId)},C=a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(tt,{size:"xs",variant:S.source==="job"?"warning":"error",children:S.source}),a.jsx("span",{className:"font-mono text-xs font-semibold text-base-content",children:S.name})]}),a.jsx("span",{className:"text-[11px] text-base-content/50 font-mono",children:new Date(S.occurredAt).toLocaleTimeString()})]}),a.jsx("p",{className:"text-xs text-error font-mono truncate",children:S.message})]});return v?a.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:O,"data-testid":`failure-row-${S.source}-${S.id}`,children:C},`${S.source}-${S.id}-${S.occurredAt}`):a.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-${S.source}-${S.id}`,children:C},`${S.source}-${S.id}-${S.occurredAt}`)}),(!n||(n.recentErrors??[]).length===0)&&a.jsx("div",{className:"p-8 text-center text-xs text-base-content/50",children:"No recent failures in this time range."})]})]})]})]})}function IY(e){switch(e){case"accepted":return"success";case"fallback":return"warning";default:return"error"}}function Y1(e){return`${Math.round(e*100)}%`}function RY(e){if(e===null||e==="")return"—";let t=e;try{t=JSON.stringify(JSON.parse(e))}catch{}return t.length>48?`${t.slice(0,48)}…`:t}const Nd=({label:e,value:t,options:n,onChange:r})=>a.jsxs(qr,{value:t,onChange:s=>r(s.target.value),size:"sm","aria-label":e,children:[a.jsxs("option",{value:"",children:[e,": all"]}),n.map(s=>a.jsx("option",{value:s,children:s},s))]}),DY=["cli","workflow","gate"];function OY({timeRange:e,onNavigate:t}){const[n,r]=h.useState(null),[s,i]=h.useState([]),[o,l]=h.useState(!0),[c,u]=h.useState(!1),[d,p]=h.useState(null),[f,m]=h.useState("all"),[b,x]=h.useState(""),[y,E]=h.useState(""),[A,w]=h.useState(""),[N,_]=h.useState(""),[k,S]=h.useState(null),[v,O]=h.useState(0),C=h.useRef(0),M=h.useRef(null),B=h.useRef(null),R=(K,X)=>{B.current=X,S(K)},z=h.useCallback(()=>{S(null),B.current?.focus()},[]),W=h.useMemo(()=>({timeRange:e,outcome:f,decisionId:b,maker:y,caller:A,runId:N,generation:v}),[e,f,b,y,A,N,v]);h.useEffect(()=>{const{timeRange:K,outcome:X,decisionId:I,maker:V,caller:te,runId:L}=W,ye=new AbortController,xe=++C.current;return l(!0),p(null),(async()=>{try{const P=new URLSearchParams,oe=Ns(K);oe&&P.set("since",oe),X!=="all"&&P.set("outcome",X),I!==""&&P.set("decision",I),V!==""&&P.set("maker",V),te!==""&&P.set("caller",te),L!==""&&P.set("run",L),P.set("limit","100");const re=await Xe(new Request(`${it()}/observability/decisions?${P.toString()}`,{signal:ye.signal}));if(!re.ok){const Ce=await re.text();throw new Error(`HTTP ${re.status}: ${Ce||re.statusText}`)}const H=await re.json();if(ye.signal.aborted||xe!==C.current)return;i(H.rows),r(H),M.current=H.nextCursor}catch(P){if(ye.signal.aborted||xe!==C.current)return;p(P instanceof Error?P.message:String(P))}finally{!ye.signal.aborted&&xe===C.current&&l(!1)}})(),()=>ye.abort()},[W]);const F=async()=>{if(M.current===null||c)return;const K=new AbortController;u(!0);try{const X=new URLSearchParams,I=Ns(e);I&&X.set("since",I),f!=="all"&&X.set("outcome",f),b!==""&&X.set("decision",b),y!==""&&X.set("maker",y),A!==""&&X.set("caller",A),N!==""&&X.set("run",N),X.set("limit","100"),X.set("before",M.current);const V=await Xe(new Request(`${it()}/observability/decisions?${X.toString()}`,{signal:K.signal}));if(!V.ok)throw new Error(`HTTP ${V.status}`);const te=await V.json();if(K.signal.aborted)return;i(L=>[...L,...te.rows]),M.current=te.nextCursor}catch(X){K.signal.aborted||p(X instanceof Error?X.message:String(X))}finally{K.signal.aborted||u(!1)}},J=n?.summary;return a.jsxs("div",{className:"flex flex-col gap-4","data-testid":"observability-decisions-tab",children:[a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Ip,{label:"Outcome",value:f,onChange:m,options:[{value:"all",label:"All"},{value:"accepted",label:"Accepted"},{value:"fallback",label:"Fallback"},{value:"rejected",label:"Rejected"}]}),a.jsx(Nd,{label:"Decision",value:b,options:n?.facets.decisionIds??[],onChange:x}),a.jsx(Nd,{label:"Maker",value:y,options:n?.facets.makers??[],onChange:E}),a.jsx(Nd,{label:"Caller",value:A,options:DY,onChange:w}),a.jsx(Vn,{type:"text",placeholder:"Run id","aria-label":"Filter by run id",value:N,onChange:K=>_(K.target.value),size:"xs",className:"w-40 font-mono"}),a.jsx(Ie,{variant:"ghost",size:"xs",disabled:o,onClick:()=>O(K=>K+1),"aria-label":"Refresh decisions","data-testid":"decisions-refresh-btn",children:"Refresh"})]}),a.jsx(Wx,{copy:KV})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4","data-testid":"decisions-kpi-strip",children:[a.jsx(Gr,{label:"Invocations",value:(J?.count??0).toLocaleString(),sub:"in window",current:0,previous:void 0,testId:"kpi-card-decision-invocations"}),a.jsx(Gr,{label:"Accepted",value:Y1(J?.acceptedRate??0),sub:"model answered",current:0,previous:void 0,testId:"kpi-card-decision-accepted-rate"}),a.jsx(Gr,{label:"Fallback",value:Y1(J?.fallbackRate??0),sub:"declared fallback used",current:0,previous:void 0,invert:!0,testId:"kpi-card-decision-fallback-rate"}),a.jsx(Gr,{label:"p95 Duration",value:J?.p95DurationMs!==null&&J?.p95DurationMs!==void 0?Zr(J.p95DurationMs)??"—":"—",sub:"per invocation",current:0,previous:void 0,testId:"kpi-card-decision-p95"})]}),a.jsxs("div",{className:"rounded-xl border border-base-content/10 bg-base-200/50 shadow-xs overflow-hidden flex flex-col",children:[a.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:[a.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/70",children:"Decision Invocations"}),a.jsxs("span",{className:"text-xs text-base-content/50 font-mono",children:["Showing ",s.length," of ",J?.count??0," row(s)"]})]}),d?a.jsxs("div",{className:"p-4 text-xs text-error",role:"alert","data-testid":"decisions-table-error",children:["Failed to load decisions: ",d]}):o&&s.length===0?a.jsx("div",{className:"flex items-center justify-center h-32 text-base-content/50 text-sm",children:a.jsx(ln,{size:"md"})}):s.length===0?a.jsxs("div",{className:"p-8 text-center text-sm text-base-content/50","data-testid":"decisions-empty",children:["No decision invocations recorded in this window.",a.jsxs("div",{className:"mt-1 text-xs",children:["Hint: run ",a.jsx("code",{className:"font-mono",children:"spur decision run"})," to record one."]})]}):a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"table table-sm","data-testid":"decisions-table",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-xs text-base-content/60 border-base-content/10",children:[a.jsx("th",{children:"Decision"}),a.jsx("th",{children:"Outcome"}),a.jsx("th",{children:"Value"}),a.jsx("th",{children:"Maker"}),a.jsx("th",{children:"Reason"}),a.jsx("th",{className:"text-right",children:"Duration"}),a.jsx("th",{children:"Started"})]})}),a.jsx("tbody",{children:s.map(K=>a.jsxs("tr",{tabIndex:0,"aria-haspopup":"dialog",className:"hover:bg-base-200/70 cursor-pointer border-base-content/10 focus:outline-none focus:bg-base-200/70",onClick:X=>R(K,X.currentTarget),onKeyDown:X=>{(X.key==="Enter"||X.key===" ")&&(X.preventDefault(),R(K,X.currentTarget))},"data-testid":"decision-row",children:[a.jsx("td",{className:"font-mono text-xs font-semibold",children:K.decisionId}),a.jsx("td",{children:a.jsx(tt,{variant:IY(K.outcome),size:"sm",children:K.outcome})}),a.jsx("td",{className:"font-mono text-xs max-w-[16rem] truncate",title:K.value??"",children:RY(K.value)}),a.jsx("td",{className:"text-xs",children:K.makerName??"—"}),a.jsx("td",{className:"text-xs text-base-content/60",children:K.reason??"—"}),a.jsx("td",{className:"text-right font-mono text-xs",children:Zr(K.durationMs)??"—"}),a.jsx("td",{className:"text-xs text-base-content/60 whitespace-nowrap",children:new Date(K.startedAt).toLocaleString()})]},K.id))})]})}),M.current!==null&&s.length>0&&a.jsx("div",{className:"p-3 border-t border-base-content/10 flex justify-center",children:a.jsx("button",{type:"button",className:"px-3 py-1.5 text-xs font-semibold rounded-lg border border-base-content/20 hover:bg-base-200 transition-colors cursor-pointer","data-testid":"load-older-decisions",onClick:()=>{F()},disabled:c,children:c?"Loading…":"Load older"})})]}),a.jsx(wY,{row:k,onClose:z,onNavigate:t})]})}function LY(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 jY(e){switch(e){case"completed":return"success";case"processing":return"info";case"failed":return"error";default:return"neutral"}}function MY({job:e,onClose:t,onNavigate:n}){const[r,s]=h.useState([]),[i,o]=h.useState(null),[l,c]=h.useState(!1),u=h.useRef(0);return h.useEffect(()=>{if(!e){s([]),o(null);return}const d=m=>{m.key==="Escape"&&t()};window.addEventListener("keydown",d);const p=new AbortController,f=++u.current;return c(!0),(async()=>{try{const m=Dp({prefix:"queue",since:e.queuedAt,limit:200}),b=await Xe(new Request(m,{signal:p.signal}));if(!b.ok)throw new Error(`HTTP ${b.status}`);const x=Op(await b.json());if(p.signal.aborted||f!==u.current)return;const y=(x?.events??[]).filter(A=>LY(A)===e.id);o(y.length);const E=y.map(A=>{const w=A.payload;return{id:A.id,eventName:A.eventName,occurredAt:A.occurredAt,error:typeof w?.error=="string"?w.error:void 0,attempt:typeof w?.attempt=="number"?w.attempt:void 0}});e.startedAt&&E.push({id:`synth-started-${e.id}`,eventName:"queue.job.started",occurredAt:e.startedAt,derived:!0}),E.sort((A,w)=>new Date(A.occurredAt).getTime()-new Date(w.occurredAt).getTime()),s(E)}catch{if(p.signal.aborted||f!==u.current)return;o(0);const m=[];e.startedAt&&m.push({id:`synth-started-${e.id}`,eventName:"queue.job.started",occurredAt:e.startedAt,derived:!0}),s(m)}finally{!p.signal.aborted&&f===u.current&&c(!1)}})(),()=>{window.removeEventListener("keydown",d),p.abort()}},[e,t]),e?a.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:a.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:[a.jsxs("div",{className:"px-5 py-4 border-b border-base-content/10 flex items-center justify-between bg-base-200/50",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tt,{variant:jY(e.status),size:"sm",children:e.status}),a.jsx("span",{className:"font-mono text-sm font-semibold text-base-content truncate max-w-xs",children:e.id})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[n&&a.jsx(Ie,{variant:"outline",size:"xs","data-testid":"navigate-system-events-btn",onClick:()=>n({tab:"system-events",runId:e.id}),children:"View in System Events"}),a.jsx(Ie,{variant:"ghost",size:"xs",onClick:t,"aria-label":"Close drawer","data-testid":"close-job-drawer",children:"✕"})]})]}),a.jsxs("div",{className:"p-5 flex-1 overflow-y-auto space-y-5",children:[a.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:[a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Type"}),a.jsx("span",{className:"font-semibold text-base-content",children:e.type})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Attempts"}),a.jsxs("span",{className:"text-base-content",children:[e.attempts," / ",e.maxRetries]})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Queued At"}),a.jsx("span",{className:"text-base-content",children:new Date(e.queuedAt).toLocaleString()})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Started At"}),a.jsx("span",{className:"text-base-content",children:e.startedAt?new Date(e.startedAt).toLocaleString():"—"})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Ended At"}),a.jsx("span",{className:"text-base-content",children:e.endedAt?new Date(e.endedAt).toLocaleString():"—"})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-base-content/50 block text-[10px] uppercase",children:"Duration"}),a.jsx("span",{className:"text-base-content",children:e.durationMs!==null?Zr(e.durationMs):"—"})]})]}),e.lastError&&a.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:[a.jsx("span",{className:"font-bold block mb-1",children:"Last Error:"}),e.lastError]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Payload"}),a.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?a.jsx("pre",{className:"whitespace-pre-wrap",children:JSON.stringify(e.payload,null,2)}):a.jsx("span",{className:"text-base-content/50 italic",children:"payload unavailable"})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/60",children:"Lifecycle Timeline"}),l&&a.jsx("span",{className:"text-[10px] text-base-content/50",children:"Loading…"})]}),i===0&&!l&&a.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"," ",a.jsx("code",{className:"font-mono text-base-content",children:"SPUR_DIAGNOSTIC_EVENTS=1"})," to capture them."]}),r.length>0&&a.jsx("div",{className:"space-y-2 font-mono text-xs","data-testid":"lifecycle-timeline-list",children:r.map(d=>a.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:[a.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[a.jsx("span",{className:"font-semibold text-base-content",children:d.eventName}),d.derived&&a.jsx(tt,{size:"xs",variant:"outline",children:"derived"}),d.attempt!==void 0&&a.jsxs(tt,{size:"xs",variant:"neutral",children:["attempt ",d.attempt]}),d.error&&a.jsx("span",{className:"text-error truncate max-w-xs",children:d.error})]}),a.jsx("span",{className:"text-[11px] text-base-content/50 shrink-0",children:new Date(d.occurredAt).toLocaleTimeString()})]},d.id))})]})]})]})}):null}function FY(e){switch(e){case"failed":return"failed";case"running":return"processing";case"completed":return"completed";default:return}}function PY(e){switch(e){case"completed":return"success";case"processing":return"info";case"failed":return"error";default:return"neutral"}}const BY=()=>{const[e,t]=h.useState(null),[n,r]=h.useState(null),[s,i]=h.useState(!0);return h.useEffect(()=>{const o=new AbortController;return(async()=>{try{const l=await Xe(new Request(`${it()}/jobs/schedules`,{signal:o.signal}));if(!l.ok)throw new Error(`HTTP ${l.status}`);const c=await l.json();if(o.signal.aborted)return;t(c.schedules)}catch(l){if(o.signal.aborted)return;r(l instanceof Error?l.message:String(l))}finally{o.signal.aborted||i(!1)}})(),()=>o.abort()},[]),a.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:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/70",children:"Active Schedules"}),e&&a.jsx(tt,{size:"xs",variant:"outline",children:e.length})]}),a.jsx("span",{className:"text-[11px] text-base-content/50",children:"Recurring background cron jobs"})]}),s?a.jsx("div",{className:"text-xs text-base-content/50 py-2",children:"Loading schedules…"}):n?a.jsxs("div",{className:"text-xs text-error/80 py-1","data-testid":"schedules-error",children:["Schedules unavailable: ",n]}):!e||e.length===0?a.jsx("div",{className:"text-xs text-base-content/50 py-2 italic",children:"No active schedules registered."}):a.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(o=>a.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-${o.name}`,children:[a.jsxs("div",{className:"flex items-center justify-between gap-1",children:[a.jsx("span",{className:"font-semibold text-base-content truncate",children:o.name}),a.jsx(tt,{size:"xs",variant:o.source==="builtin"?"neutral":"info",children:o.source})]}),a.jsxs("div",{className:"flex items-center justify-between text-[11px] text-base-content/60",children:[a.jsx("span",{children:o.cadence}),a.jsx("span",{className:"text-base-content/40",children:o.cron})]}),a.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:[a.jsx("span",{children:o.nextFireAt===null?"next run: cron (unknown)":`next: ${new Date(o.nextFireAt).toLocaleTimeString()}`}),a.jsx("span",{children:o.lastStatus==="none"?"never run":o.lastStatus})]})]},o.name))})]})};function $Y({timeRange:e,onNavigate:t}){const[n,r]=h.useState("all"),[s,i]=h.useState([]),[o,l]=h.useState({all:0,pending:0,processing:0,completed:0,failed:0}),[c,u]=h.useState(!1),[d,p]=h.useState(0),[f,m]=h.useState(!0),[b,x]=h.useState(null),[y,E]=h.useState(new Set),[A,w]=h.useState(null),N=h.useRef(0),_=h.useRef({timeRange:e,statusFilter:n});h.useEffect(()=>{const v=new AbortController,O=++N.current;return m(!0),x(null),(async()=>{try{const C=_.current.timeRange!==e||_.current.statusFilter!==n;C&&(_.current={timeRange:e,statusFilter:n});const M=C?0:d;C&&d!==0&&p(0);const B=Ns(e),R=new URLSearchParams,z=FY(n);z&&R.set("status",z),B&&R.set("since",B),R.set("limit","100"),R.set("offset",String(M));const W=await Xe(new Request(`${it()}/jobs?${R.toString()}`,{signal:v.signal}));if(!W.ok){const J=await W.text();throw new Error(`HTTP ${W.status}: ${J||W.statusText}`)}const F=await W.json();if(v.signal.aborted||O!==N.current)return;i(M===0?F.jobs:J=>[...J,...F.jobs]),l(F.countsByStatus),u(F.hasMore),m(!1)}catch(C){if(v.signal.aborted||O!==N.current)return;x(C instanceof Error?C.message:String(C)),m(!1)}})(),()=>v.abort()},[e,n,d]);const k=(v,O)=>{O.stopPropagation(),E(C=>{const M=new Set(C);return M.has(v)?M.delete(v):M.add(v),M})},S=[{id:"all",label:"All",count:o.all},{id:"failed",label:"Failed",count:o.failed},{id:"running",label:"Running",count:o.processing},{id:"completed",label:"Completed",count:o.completed}];return a.jsxs("div",{className:"flex flex-col gap-4","data-jobs-tab":!0,"data-testid":"observability-jobs-tab",children:[a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[a.jsx("div",{className:"flex items-center gap-1.5","data-testid":"job-status-chips",children:S.map(v=>{const O=n===v.id;return a.jsxs("button",{type:"button",onClick:()=>r(v.id),"data-testid":`status-chip-${v.id}`,className:`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-semibold rounded-full transition-colors cursor-pointer ${O?v.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:[a.jsx("span",{children:v.label}),a.jsx("span",{className:`px-1.5 py-0.2 text-[10px] rounded-full ${O?"bg-base-100/20":"bg-base-200 text-base-content/70"}`,children:v.count.toLocaleString()})]},v.id)})}),a.jsx(Wx,{})]}),o.failed>0&&a.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:[a.jsxs("span",{children:["⚠️ ",o.failed," ",o.failed===1?"job":"jobs"," failed in this window"]}),a.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"})]}),a.jsx(BY,{}),a.jsxs("div",{className:"rounded-xl border border-base-content/10 bg-base-200/50 shadow-xs overflow-hidden flex flex-col",children:[a.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:[a.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-base-content/70",children:"Queue Jobs"}),a.jsxs("span",{className:"text-xs text-base-content/50 font-mono",children:["Showing ",s.length," of ",o.all," job(s)"]})]}),b?a.jsxs("div",{className:"p-4 text-xs text-error",role:"alert","data-testid":"jobs-table-error",children:["Failed to load jobs: ",b]}):f&&s.length===0?a.jsxs("div",{className:"flex items-center justify-center h-32 text-base-content/50 text-sm",children:[a.jsx(ln,{size:"sm"})," Loading jobs…"]}):s.length===0?a.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."}):a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"table table-xs w-full font-mono text-xs","data-testid":"queue-jobs-table",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-base-content/10 text-base-content/60",children:[a.jsx("th",{children:"Status"}),a.jsx("th",{children:"Job Type"}),a.jsx("th",{children:"Enqueued At"}),a.jsx("th",{children:"Started At"}),a.jsx("th",{children:"Duration"}),a.jsx("th",{children:"Attempts"}),a.jsx("th",{children:"Error"})]})}),a.jsx("tbody",{children:s.map(v=>{const O=y.has(v.id);return a.jsxs("tr",{className:"hover:bg-base-300/40 cursor-pointer transition-colors",onClick:()=>w(v),"data-testid":`job-row-${v.id}`,children:[a.jsx("td",{children:a.jsx(tt,{size:"xs",variant:PY(v.status),children:v.status})}),a.jsx("td",{className:"font-semibold text-base-content",children:v.type}),a.jsx("td",{className:"text-base-content/60",children:new Date(v.queuedAt).toLocaleTimeString()}),a.jsx("td",{className:"text-base-content/60",children:v.startedAt?new Date(v.startedAt).toLocaleTimeString():"—"}),a.jsx("td",{className:"text-base-content/80",children:v.durationMs!==null?Zr(v.durationMs):"—"}),a.jsxs("td",{className:"text-base-content/60",children:[v.attempts," / ",v.maxRetries]}),a.jsx("td",{className:"max-w-xs",children:v.lastError?a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("div",{className:`text-error ${O?"whitespace-pre-wrap":"truncate"}`,"data-testid":`job-error-${v.id}`,children:v.lastError}),a.jsx("button",{type:"button",className:"text-[10px] text-base-content/60 hover:text-base-content underline self-start","data-testid":`expand-error-btn-${v.id}`,onClick:C=>k(v.id,C),children:O?"Hide":"Details"})]}):null})]},v.id)})})]})}),c&&a.jsx("div",{className:"p-3 border-t border-base-content/10 flex justify-center bg-base-200/30",children:a.jsx(Ie,{variant:"ghost",size:"xs",disabled:f,onClick:()=>p(v=>v+100),"data-testid":"jobs-load-more-btn",children:f?"Loading…":"Load more"})})]}),a.jsx(MY,{job:A,onClose:()=>w(null),onNavigate:t})]})}function K1(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 UY(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:K1(t.exact),estimated:K1(t.estimated),unmeasured:t.unmeasured}}function zY(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 HY(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 s=n,i=r,o=s.window;if(o===null||typeof o!="object")return null;const l=o;if(typeof l.since!="string"||typeof l.until!="string"||!Array.isArray(s.pairs)||!Array.isArray(i.roles))return null;const c=[];for(const d of s.pairs){const p=zY(d);p&&c.push(p)}const u=[];for(const d of i.roles){const p=UY(d);p&&u.push(p)}return{window:{since:l.since,until:l.until},pairs:c,roles:u}}function GY(e){switch(e){case"explicit":return"pinned";case"role":return"resolved";case"default":return"default";case null:return"—";default:return e}}const WY=new Intl.NumberFormat("en-US");function ia(e){return WY.format(e)}function Z1({label:e,totals:t}){return a.jsxs("div",{"data-token-bucket":e,className:"text-xs",children:[a.jsx(tt,{size:"xs",variant:e==="estimated"?"warning":"success",children:e}),a.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-0.5 mt-1",children:[a.jsx("dt",{className:"text-spur-text-muted",children:"input"}),a.jsx("dd",{className:"tabular-nums text-right",children:ia(t.inputTokens)}),a.jsx("dt",{className:"text-spur-text-muted",children:"cache read"}),a.jsx("dd",{className:"tabular-nums text-right",children:ia(t.cacheReadTokens)}),a.jsx("dt",{className:"text-spur-text-muted",children:"cache write"}),a.jsx("dd",{className:"tabular-nums text-right",children:ia(t.cacheCreationTokens)}),a.jsx("dt",{className:"text-spur-text-muted",children:"output"}),a.jsx("dd",{className:"tabular-nums text-right",children:ia(t.outputTokens)})]})]})}function qY({role:e}){const t=e.role??"—";return a.jsxs("div",{className:"bg-base-100 border border-spur-border rounded-md p-3","data-role-attribution":t,children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-sm font-semibold text-spur-text",children:t}),a.jsxs("span",{className:"text-[10px] text-spur-text-muted tabular-nums",children:["matched ",e.matchedRuns," of ",e.totalRuns," runs"]})]}),e.unmeasured?a.jsxs("div",{className:"mt-1 text-xs","data-unmeasured":!0,children:[a.jsx(tt,{size:"xs",variant:"ghost",children:"unmeasured"}),a.jsx("span",{className:"ml-1 text-spur-text-muted",children:"no token data recorded for this role — not a measured zero"})]}):a.jsxs("div",{className:"mt-2 flex flex-wrap gap-4",children:[e.exact?a.jsx(Z1,{label:"exact",totals:e.exact}):null,e.estimated?a.jsx(Z1,{label:"estimated",totals:e.estimated}):null]})]})}function VY({timeRange:e}){const[t,n]=h.useState(null),[r,s]=h.useState(null);if(h.useEffect(()=>{const o=new AbortController,l=Ns(e),c=it(),u=l?`${c}/observability/routing-summary?since=${encodeURIComponent(l)}`:`${c}/observability/routing-summary`;return(async()=>{try{const d=await Xe(new Request(u,{signal:o.signal}));if(!d.ok)throw new Error(`routing summary fetch failed: ${d.status}`);const p=HY(await d.json());if(!p)throw new Error("routing summary response failed schema validation");n(p)}catch(d){if(o.signal.aborted)return;s(d instanceof Error?d.message:String(d))}})(),()=>o.abort()},[e]),r)return a.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load routing summary: ",r]});if(t===null)return a.jsxs("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:[a.jsx(ln,{size:"sm"})," Loading routing summary…"]});const i=t.pairs.length===0&&t.roles.length===0;return a.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-routing-tab":!0,children:[a.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-base-200 shrink-0 flex items-baseline justify-between",children:[a.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Routing & token consumption"}),a.jsxs("span",{className:"text-[10px] text-spur-text-muted tabular-nums","data-covered-window":!0,children:["covered ",t.window.since," → ",t.window.until]})]}),i?a.jsx("div",{className:"flex-1 flex items-center justify-center p-4","data-routing-empty":!0,children:a.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."})}):a.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[t.pairs.length>0?a.jsxs("section",{className:"bg-base-100 border border-spur-border rounded-md","data-routing-table":!0,children:[a.jsxs("div",{className:"px-3 py-2 border-b border-spur-border",children:[a.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Role → executor"}),a.jsx("span",{className:"ml-2 text-[10px] text-spur-text-muted",children:"runs and escalations per pair; pinned and role-resolved counted separately"})]}),a.jsxs("table",{className:"table table-sm w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-[10px] uppercase text-spur-text-muted",children:[a.jsx("th",{children:"Role"}),a.jsx("th",{children:"Executor"}),a.jsx("th",{children:"Source"}),a.jsx("th",{className:"text-right",children:"Runs"}),a.jsx("th",{className:"text-right",children:"Escalations"})]})}),a.jsx("tbody",{children:t.pairs.map(o=>a.jsxs("tr",{children:[a.jsx("td",{className:"text-sm text-spur-text",children:o.role??"—"}),a.jsx("td",{className:"text-sm text-spur-text",children:o.executor}),a.jsx("td",{children:a.jsx(tt,{size:"xs",variant:o.source==="explicit"?"warning":"ghost",children:GY(o.source)})}),a.jsx("td",{className:"text-right tabular-nums text-spur-text",children:ia(o.runs)}),a.jsx("td",{className:"text-right tabular-nums text-spur-text",children:ia(o.escalations)})]},`${o.role??""}:${o.executor}:${o.source??""}`))})]}),a.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?a.jsxs("section",{"data-token-section":!0,children:[a.jsxs("div",{className:"px-1 pb-1.5",children:[a.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Token consumption by role"}),a.jsx("span",{className:"ml-2 text-[10px] text-spur-text-muted",children:"input, cache read, cache write, output — token totals only"})]}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:t.roles.map(o=>a.jsx(qY,{role:o},o.role??"pin"))})]}):null]})]})}const YY={backlog:["refine","start","cancel","deprecate"],todo:["plan","run","decompose","add-subtask","link-feature","block","cancel","deprecate"],wip:["run","add-subtask","link-feature","block","cancel","deprecate"],testing:["verify","complete","block","cancel","deprecate"],blocked:["refine","unblock","cancel","deprecate"],done:["reopen","deprecate"],deprecated:["undeprecate","cancel"],cancelled:[]},fee={refine:"Refine",plan:"Plan",run:"Run",verify:"Verify",decompose:"Decompose","add-subtask":"+ Subtask","link-feature":"Link Feature",start:"Start",complete:"Complete",reopen:"Reopen",block:"Block",unblock:"Unblock",cancel:"Cancel",deprecate:"Deprecate",undeprecate:"Un-deprecate"},mee={start:"todo",complete:"done",reopen:"wip",block:"blocked",unblock:"todo",cancel:"cancelled",deprecate:"deprecated",undeprecate:"todo"},KY="<input>",ZY=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,XY=/^\d{4}$/,QY=new Set(["body","content","message","prompt","query","response","value"]),JY={confirm:"--answer","hitl.confirm":"--answer",select:"--answer","hitl.select":"--answer",input:"--answer-text","hitl.input":"--answer-text"},eK=new Set(["failed","not-started","outcome-unknown","contract-violation"]),tK=new Set(["stale","missing","invalid"]);function nK(e){return e===null?!1:(YY[e]??[]).includes("run")}function Lp(e){if(Array.isArray(e))return e.map(t=>Lp(t));if(e!==null&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=QY.has(n)?"[redacted]":Lp(r);return t}return typeof e=="string"&&e.length>256?`${e.slice(0,256)}…`:e}function rK(e){if(e===null||typeof e!="object")return null;const t=e.links;if(!Array.isArray(t))return null;const n=[],r=[];for(const s of t){if(s===null||typeof s!="object")continue;const i=s;if(typeof i.runId!="string"||i.runId==="")continue;if(i.run===null){r.push(i.runId);continue}const o=mK(i.run);if(o===null||o.id!==i.runId){r.push(i.runId);continue}n.push(o)}return{runs:n,rejectedIds:r}}function sK(e,t){const n=e.states.find(c=>c.status==="failed"),r=e.currentState===null?void 0:e.states.find(c=>c.state===e.currentState),s=n??r??e.states[0];if(s===void 0)return null;const o=s.actions.find(c=>c.status==="failed")??s.actions[0],l=t.find(c=>c.node===s.state&&c.status==="failed"&&c.resultSummary!=null)??t.find(c=>c.node===s.state&&c.resultSummary!=null)??t.find(c=>c.node===s.state);return{state:s.state,actionKey:o?.actionKey??null,actionStatus:o?.status??l?.status??null,resultSummary:l?.resultSummary??null}}function aK(e){const t=fK(e.recordStatus,e.recordReason),n=pK(e.resultSummary);if(!ZY.test(e.runId))return{guidance:{kind:"inspection-only",traceCommand:null,reason:"Run id cannot be copied into a command. Inspection only."},evidence:t,proof:n,rejected:!1};const r=e.runStatus.toLowerCase(),s=`spur workflow trace ${e.runId}`;return r==="paused"?{guidance:oK(e,s),evidence:t,proof:n,rejected:cA(e)}:r==="failed"?{guidance:lK(e,s),evidence:t,proof:n,rejected:!1}:{guidance:{kind:"inspection-only",traceCommand:s,reason:"This run is not a failed or paused run with a recovery command. Inspection only."},evidence:t,proof:n,rejected:!1}}function iK(e){return XY.test(e)?`/sp:dev-run ${e} --auto`:null}function oK(e,t){if(cA(e))return{kind:"inspection-only",traceCommand:t,reason:"Work item belongs to a different run and was rejected. Inspection only."};if(cK(e)!==null)return{kind:"continue",command:Td(e.runId,"--answer-text"),inputLabel:"Input: receipt path for the paused work item."};const r=uK(e.resultSummary);return r==="--answer"?{kind:"continue",command:Td(e.runId,"--answer"),inputLabel:"Input: yes, no, or cancel. This label is not an answer."}:r==="--answer-text"?{kind:"continue",command:Td(e.runId,"--answer-text"),inputLabel:"Input: free text for the operator gate."}:{kind:"inspection-only",traceCommand:t,reason:"Paused run has no valid work item or operator-gate metadata. Inspection only."}}function lK(e,t){if(e.taskStatus===null)return{kind:"inspection-only",traceCommand:t,reason:"Task lifecycle is unknown. Inspection only."};if(!nK(e.taskStatus)||e.wbs===null)return{kind:"inspection-only",traceCommand:t,reason:"Task lifecycle does not permit retry. Inspection only."};const n=iK(e.wbs);return n===null?{kind:"inspection-only",traceCommand:t,reason:"Task lifecycle does not permit retry. Inspection only."}:{kind:"retry",traceCommand:t,retryCommand:n}}function Td(e,t){return`spur workflow continue ${e} ${t} ${KY}`}function cA(e){return uA(e.resultSummary).some(t=>t.runId!==e.runId)}function cK(e){return uA(e.resultSummary).find(t=>t.runId===e.runId&&t.state!=="")??null}function uK(e){for(const t of dK(e)){const n=JY[t];if(n!==void 0)return n}return null}function uA(e){const t=[];return Ki(e,n=>{const r=n.workItem;if(r===null||typeof r!="object"||Array.isArray(r))return;const s=r;typeof s.runId=="string"&&typeof s.state=="string"&&t.push({runId:s.runId,state:s.state})}),t}function dK(e){const t=[];return Ki(e,n=>{n.reason==="hitl-pause"&&typeof n.kind=="string"&&t.push(n.kind)}),t}function pK(e){let t=!1,n=!1;return Ki(e,r=>{typeof r.proof=="string"&&tK.has(r.proof)&&(t=!0),typeof r.outcome=="string"&&(eK.has(r.outcome)?t=!0:r.outcome==="done"&&(n=!0))}),t?{kind:"invalid",message:"Invalid proof cannot be reused as fresh evidence."}:n?{kind:"retained",message:"A retained receipt is not fresh evidence and cannot be reused."}:null}function fK(e,t){switch(e){case"record":return{provenanceUsable:!0,reusableAsFresh:!1,message:"Retained run record is usable provenance. It is not a fresh receipt and cannot be reused as evidence for a new attempt."};case"incomplete":return{provenanceUsable:!0,reusableAsFresh:!1,message:`Scratch record is incomplete (${t??"unspecified"}) and cannot be reused as fresh evidence. Retained run progress remains usable provenance.`};case"legacy":return{provenanceUsable:!0,reusableAsFresh:!1,message:"Legacy scratch record cannot be reused as fresh evidence. Retained run progress remains usable provenance."};case"oversized":return{provenanceUsable:!0,reusableAsFresh:!1,message:"Run record is oversized and cannot be reused as fresh evidence. Retained run progress remains usable provenance."};case"missing":return{provenanceUsable:!0,reusableAsFresh:!1,message:"Disposable scratch is expired or missing and cannot be reused as fresh evidence. Retained run progress remains usable provenance."};case"unread":return{provenanceUsable:!0,reusableAsFresh:!1,message:"Run record could not be read and cannot be reused as fresh evidence. Retained run progress remains usable provenance."}}}function Ki(e,t){if(Array.isArray(e)){for(const r of e)Ki(r,t);return}if(e===null||typeof e!="object")return;const n=e;t(n);for(const r of Object.values(n))Ki(r,t)}function mK(e){if(e===null||typeof e!="object")return null;const t=e;return typeof t.id!="string"||!ll(t.workflowName)||typeof t.status!="string"||!ll(t.mode)||!ll(t.agent)||typeof t.startedAt!="string"||!ll(t.completedAt)?null:{id:t.id,workflowName:t.workflowName,status:t.status,mode:t.mode,agent:t.agent,startedAt:t.startedAt,completedAt:t.completedAt}}function ll(e){return e===null||typeof e=="string"}const hK=["all","pending","running","paused","interrupted","done","failed","cancelled"],X1=50;function Wr(e){return typeof e=="string"}function cl(e){return e===null||typeof e=="string"}function gK(e){return e===null||typeof e=="number"&&Number.isFinite(e)}function bK(e){if(e===null||typeof e!="object")return null;const t=e;return!Wr(t.id)||!cl(t.workflowName)||!Wr(t.status)||!cl(t.mode)||!cl(t.agent)||!Wr(t.startedAt)||!cl(t.completedAt)?null:{id:t.id,workflowName:t.workflowName,status:t.status,mode:t.mode,agent:t.agent,startedAt:t.startedAt,completedAt:t.completedAt}}function Q1(e){if(e===null||typeof e!="object")return null;const t=e;if(!Array.isArray(t.runs)||typeof t.count!="number")return null;const n=[];for(const r of t.runs){const s=bK(r);s&&n.push(s)}return{runs:n,count:t.count,nextCursor:Wr(t.nextCursor)?t.nextCursor:null,hasMore:typeof t.hasMore=="boolean"?t.hasMore:!1}}function dA(e){if(e===null||typeof e!="object")return null;const t=e;return t.status==="missing"?{status:"missing"}:t.status==="oversized"?gK(t.sizeBytes)&&t.sizeBytes!==null?{status:"oversized",sizeBytes:t.sizeBytes}:null:t.status==="legacy"?Wr(t.content)?{status:"legacy",content:t.content}:null:t.status==="incomplete"?!Wr(t.markdown)||!Wr(t.reason)?null:{status:"incomplete",markdown:t.markdown,reason:t.reason}:t.status==="record"?!Wr(t.markdown)||t.state===null||typeof t.state!="object"||Array.isArray(t.state)?null:{status:"record",markdown:t.markdown,state:t.state}:null}const xK=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function _l(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=xK[t.getMonth()],r=t.getDate(),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0");return`${n} ${r} ${s}:${i}:${o}`}function oa(e){const t=e.toLowerCase();return t==="completed"||t==="done"||t==="succeeded"||t==="passed"?"success":t==="failed"||t==="error"||t==="cancelled"?"error":t==="running"||t==="active"||t==="processing"?"info":t==="paused"||t==="pending"||t==="waiting"||t==="interrupted"?"warning":"neutral"}function J1(e,t){const n=new URLSearchParams;return t.status!==void 0&&n.set("status",t.status),t.workflow!==void 0&&n.set("workflow",t.workflow),t.since!==void 0&&n.set("since",t.since),t.cursor!==void 0&&n.set("cursor",t.cursor),n.set("limit",String(t.limit)),`${e}/runs?${n.toString()}`}function yK(e){const t=`--since ${e.startedAt}`;return e.completedAt===null?`spur history analyze ${t}`:`spur history analyze ${t} --until ${e.completedAt}`}function EK(e,t=3){const n=[];for(const r of e.states)for(const s of r.actions)for(const i of s.attempts)i.durationMs!==null&&Number.isFinite(i.durationMs)&&n.push({actionRunId:i.actionRunId,durationMs:i.durationMs});return n.sort((r,s)=>s.durationMs-r.durationMs),new Set(n.slice(0,t).map(r=>r.actionRunId))}function SK(e){if(e.completedAt===null)return"running";const t=Date.parse(e.completedAt)-Date.parse(e.startedAt);return!Number.isFinite(t)||t<0?"running":Zr(t)??"running"}function wK(e){if(e===null||typeof e!="object")return[];const t=e.actions;if(!Array.isArray(t))return[];const n=[];for(const r of t){if(r===null||typeof r!="object")continue;const s=r;typeof s.node!="string"||typeof s.status!="string"||n.push({node:s.node,status:s.status,resultSummary:s.resultSummary??null})}return n}function vK(e,t){return t||e===null?{status:"unread"}:e.status==="incomplete"?{status:"incomplete",reason:e.reason}:{status:e.status}}function NK({timeRange:e,onNavigate:t}){const[n]=Ca(),r=n.get("wbs"),s=r!==null&&r!==""?r:null,[i,o]=h.useState("all"),[l,c]=h.useState(""),[u,d]=h.useState([]),[p,f]=h.useState([]),[m,b]=h.useState(null),[x,y]=h.useState(null),[E,A]=h.useState(!1),[w,N]=h.useState("loading"),[_,k]=h.useState(null),[S,v]=h.useState(!1),[O,C]=h.useState(null),[M,B]=h.useState(new Map),R=h.useRef(null),z=h.useMemo(()=>Ns(e),[e]),W=h.useMemo(()=>({...i!=="all"?{status:i}:{},...l!==""?{workflow:l}:{},...z!==void 0?{since:z}:{}}),[i,l,z]),F=h.useCallback(()=>{R.current?.abort();const P=new AbortController;R.current=P,N("loading"),k(null),(async()=>{try{const oe=J1(it(),{...W,limit:X1}),re=await Xe(new Request(oe,{signal:P.signal}));if(!re.ok)throw new Error(`runs fetch failed: ${re.status}`);const H=Q1(await re.json());if(!H)throw new Error("runs response failed schema validation");if(P.signal.aborted)return;d(H.runs),f([]),b(null),y(H.nextCursor),A(H.hasMore),N("ready")}catch(oe){if(P.signal.aborted)return;k(oe instanceof Error?oe.message:String(oe)),N("error")}})()},[W]),J=h.useCallback(()=>{if(s===null)return;R.current?.abort();const P=new AbortController;R.current=P,N("loading"),k(null);const oe=s;(async()=>{try{const re=it(),H=`${re}/runs/by-wbs/${encodeURIComponent(oe)}?limit=200`,Ce=/^\d{4}$/.test(oe)?`${re}/tasks/${oe}`:null,[me,he]=await Promise.all([Xe(new Request(H,{signal:P.signal})),Ce===null?Promise.resolve(null):Xe(new Request(Ce,{signal:P.signal})).catch(()=>null)]);if(!me.ok)throw new Error(`runs fetch failed: ${me.status}`);const Ne=rK(await me.json());if(!Ne)throw new Error("runs response failed schema validation");if(P.signal.aborted)return;let Ge=null;if(he?.ok)try{const Z=await he.json();Ge=typeof Z.data?.status=="string"?Z.data.status:null}catch{Ge=null}d(Ne.runs),f(Ne.rejectedIds),b(Ge),y(null),A(!1),N("ready")}catch(re){if(P.signal.aborted)return;k(re instanceof Error?re.message:String(re)),N("error")}})()},[s]),K=h.useCallback(()=>{s!==null?J():F()},[s,J,F]);h.useEffect(()=>{if(s===null)return F(),()=>R.current?.abort()},[s,F]),h.useEffect(()=>{if(s!==null)return J(),()=>R.current?.abort()},[s,J]);const X=h.useCallback(async()=>{if(!(x===null||!E||S)){v(!0);try{const P=J1(it(),{...W,cursor:x,limit:X1}),oe=await Xe(new Request(P));if(!oe.ok)throw new Error(`runs fetch failed: ${oe.status}`);const re=Q1(await oe.json());if(!re)throw new Error("runs response failed schema validation");d(H=>{const Ce=new Set(H.map(me=>me.id));return[...H,...re.runs.filter(me=>!Ce.has(me.id))]}),y(re.nextCursor),A(re.hasMore)}catch(P){k(P instanceof Error?P.message:String(P))}finally{v(!1)}}},[x,E,S,W]),I=h.useCallback(P=>{if(O===P){C(null);return}C(P),!M.has(P)&&(B(oe=>{const re=new Map(oe);return re.set(P,{projection:null,actions:[],recordOutcome:null,recordStatus:"unread",error:null,loading:!0}),re}),(async()=>{const oe=H=>{B(Ce=>{const me=new Map(Ce);return me.set(P,H),me})},re=it();try{const[H,Ce,me]=await Promise.all([Xe(new Request(`${re}/runs/${P}/progress`)),Xe(new Request(`${re}/runs/${P}`)),Xe(new Request(`${re}/observability/run-record/${P}`))]);let he=null,Ne=null;if(H.status===404)Ne="Run not found";else if(!H.ok)Ne=`run progress fetch failed: ${H.status}`;else try{const Re=zw.safeParse(await H.json());Re.success?he=Re.data:Ne="progress response failed schema validation"}catch(Re){Ne=Re instanceof Error?Re.message:String(Re)}let Ge=[];if(Ce.ok)try{Ge=wK(await Ce.json())}catch{Ge=[]}let Z=null,ke=!0;if(me.ok)try{Z=dA(await me.json()),ke=Z===null}catch{ke=!0}const Fe=vK(Z,ke);oe({projection:he,actions:Ge,recordOutcome:Z,recordStatus:Fe.status,recordReason:Fe.reason,error:Ne,loading:!1})}catch(H){oe({projection:null,actions:[],recordOutcome:null,recordStatus:"unread",error:H instanceof Error?H.message:String(H),loading:!1})}})())},[O,M]),V=h.useMemo(()=>{const P=new Set;for(const re of u)re.workflowName!==null&&re.workflowName!==""&&P.add(re.workflowName);const oe=Array.from(P).sort();return l!==""&&!oe.includes(l)&&oe.unshift(l),oe},[u,l]),te=h.useMemo(()=>s===null?u:u.filter(P=>!(i!=="all"&&P.status!==i||l!==""&&P.workflowName!==l)),[u,s,i,l]),L=te.find(P=>P.id===O)??null,ye=O===null?void 0:M.get(O),xe=h.useMemo(()=>ye?.projection?EK(ye.projection):new Set,[ye]);return w==="loading"&&u.length===0?a.jsxs("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm","data-trace-tab":!0,"data-trace-linked-wbs":s??void 0,children:[a.jsx(ln,{size:"sm"})," Loading runs…"]}):a.jsxs("div",{className:"flex flex-col gap-3","data-trace-tab":!0,"data-trace-linked-wbs":s??void 0,children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-3 bg-base-200 rounded-xl border border-base-content/10 p-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{htmlFor:"trace-status-filter",className:"text-xs font-semibold text-spur-text-muted",children:"Status"}),a.jsx("select",{id:"trace-status-filter",className:"bg-base-100 border border-base-content/20 rounded px-2 py-1 text-xs cursor-pointer",value:i,onChange:P=>o(P.target.value),children:hK.map(P=>a.jsx("option",{value:P,children:P},P))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{htmlFor:"trace-workflow-filter",className:"text-xs font-semibold text-spur-text-muted",children:"Workflow"}),a.jsxs("select",{id:"trace-workflow-filter",className:"bg-base-100 border border-base-content/20 rounded px-2 py-1 text-xs cursor-pointer",value:l,onChange:P=>c(P.target.value),children:[a.jsx("option",{value:"",children:"All workflows"}),V.map(P=>a.jsx("option",{value:P,children:P},P))]})]}),a.jsxs("span",{className:"text-xs text-spur-text-muted ml-auto",children:[te.length," run(s)"]})]}),_!==null&&a.jsxs("div",{className:"text-xs text-error",role:"alert",children:["Failed to load runs: ",_,a.jsx(Ie,{variant:"ghost",size:"xs",className:"ml-2",onClick:K,children:"Retry"})]}),p.length>0&&a.jsx("ul",{className:"flex flex-col gap-1","data-rejected-runs":!0,children:p.map(P=>a.jsxs("li",{"data-rejected-run":P,className:"text-xs text-warning",children:["Linked run ",P," was rejected and was not opened."]},P))}),te.length===0&&w==="ready"&&a.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-trace-empty":!0,children:s===null?"No workflow runs in this window":"No linked runs for this task"}),te.length>0&&a.jsx("ul",{className:"flex flex-col gap-1","data-trace-run-list":!0,children:te.map(P=>{const oe=P.id===O;return a.jsx("li",{children:a.jsx(yx,{variant:"compact",className:"bg-base-200 border border-base-content/10",children:a.jsxs(Ex,{className:"p-2 gap-1",children:[a.jsxs(TK,{expanded:oe,runId:P.id,onToggle:I,children:[a.jsx("span",{"aria-hidden":"true",children:oe?"▼":"▶"}),a.jsx("span",{className:"text-xs font-mono font-semibold",children:P.workflowName??"unknown"}),a.jsx(tt,{variant:oa(P.status),size:"xs",children:P.status}),a.jsx("span",{className:"text-[10px] text-spur-text-muted font-mono",children:_l(P.startedAt)}),a.jsx("span",{className:"text-[10px] text-spur-text-muted font-mono",children:SK(P)}),P.agent!==null&&a.jsx("span",{className:"text-[10px] text-spur-text-muted ml-auto",children:P.agent})]}),oe&&ye!==void 0&&a.jsxs("div",{className:"mt-2 pl-4 border-l-2 border-base-content/10",children:[ye.loading&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-spur-text-muted py-2",children:[a.jsx(ln,{size:"xs"})," Loading run detail…"]}),ye.error!==null&&a.jsx("div",{className:"text-xs text-error py-2",role:"alert","data-run-detail-error":!0,children:ye.error}),ye.projection!==null&&L!==null&&a.jsx(kK,{run:L,projection:ye.projection,slowestIds:xe,onNavigate:t,recordOutcome:ye.recordOutcome,recordFailed:ye.recordStatus==="unread"}),!ye.loading&&a.jsx(CK,{run:P,detail:ye,wbs:s,taskStatus:m})]})]})})},P.id)})}),s===null&&E&&a.jsx("div",{className:"flex justify-center",children:a.jsx(Ie,{variant:"outline",size:"xs",onClick:()=>{X()},disabled:S,children:"Load more"})})]})}function TK({expanded:e,runId:t,onToggle:n,children:r}){const s=h.useRef(!1);return a.jsx("button",{type:"button","aria-expanded":e,"data-run-id":t,"data-run-row":!0,className:"w-full text-left flex items-center gap-2 flex-wrap cursor-pointer",onKeyDown:i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),s.current=!0,n(t))},onClick:()=>{if(s.current){s.current=!1;return}n(t)},children:r})}function kK({run:e,projection:t,slowestIds:n,onNavigate:r,recordOutcome:s,recordFailed:i}){const o=yK(e);return a.jsxs("div",{className:"space-y-3","data-run-detail":!0,children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-[11px]","data-run-detail-header":!0,children:[a.jsx("span",{className:"font-mono font-semibold",children:t.workflow}),a.jsx(tt,{variant:oa(t.status),size:"xs",children:t.status}),t.currentState!==null&&a.jsxs("span",{className:"text-spur-text-muted",children:["current state:"," ",a.jsx("span",{className:"font-mono","data-current-state":!0,children:t.currentState})]}),t.definitionDigest!==null&&a.jsx("span",{className:"font-mono text-spur-text-muted",title:t.definitionDigest,children:t.definitionDigest.slice(0,12)})]}),t.states.length>0&&a.jsxs("div",{children:[a.jsx("div",{className:"text-[10px] uppercase text-spur-text-muted font-semibold mb-1",children:"States"}),a.jsx("ol",{className:"space-y-2",children:t.states.map(l=>a.jsxs("li",{"data-state":!0,className:"text-[11px] flex flex-col gap-1",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"font-mono font-semibold",children:l.state}),a.jsxs(tt,{variant:"outline",size:"xs",children:["visit ",l.visit]}),a.jsx(tt,{variant:oa(l.status),size:"xs",children:l.status})]}),a.jsx("ul",{className:"pl-4 space-y-1",children:l.actions.map(c=>a.jsxs("li",{className:"flex flex-col gap-0.5",children:[a.jsxs("span",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("span",{className:"font-mono",children:c.actionKey}),a.jsx(tt,{variant:"outline",size:"xs",children:c.kind}),a.jsx(tt,{variant:oa(c.status),size:"xs",children:c.status})]}),c.attempts.length>0&&a.jsx("ul",{className:"pl-4 space-y-0.5",children:c.attempts.map(u=>{const d=Zr(u.durationMs),p=n.has(u.actionRunId);return a.jsxs("li",{"data-attempt":u.actionRunId,"data-slowest":p?"true":void 0,className:`flex items-center gap-2 flex-wrap ${p?"text-warning font-semibold":"text-spur-text-muted"}`,children:[a.jsx(tt,{variant:oa(u.status),size:"xs",children:u.status}),d!==null&&a.jsx("span",{className:"font-mono",children:d}),u.provenance==="host-reported"&&a.jsx(tt,{variant:"info",size:"xs",children:"host-reported"}),u.estimated&&a.jsx(tt,{variant:"warning",size:"xs",children:"estimated"})]},u.actionRunId)})})]},c.actionKey))})]},`${l.state}:${l.visit}`))})]}),t.transitions.length>0&&a.jsxs("div",{children:[a.jsx("div",{className:"text-[10px] uppercase text-spur-text-muted font-semibold mb-1",children:"Transitions"}),a.jsx("ul",{className:"space-y-0.5",children:t.transitions.map(l=>a.jsxs("li",{className:"text-[11px] flex items-center gap-2 flex-wrap","data-transition":!0,children:[a.jsxs("span",{className:"font-mono",children:[l.from," → ",l.to]}),l.trigger!==null&&a.jsx("span",{className:"text-spur-text-muted",children:l.trigger}),a.jsx("span",{className:"text-[10px] text-spur-text-muted font-mono ml-auto",children:_l(l.at)})]},`${l.from}:${l.to}:${l.at}`))})]}),t.diagnostics.length>0&&a.jsxs("div",{"data-diagnostics":!0,children:[a.jsx("div",{className:"text-[10px] uppercase text-spur-text-muted font-semibold mb-1",children:"Diagnostics"}),a.jsx("ul",{className:"space-y-0.5",children:t.diagnostics.map(l=>a.jsxs("li",{className:"text-[11px] text-warning",children:[a.jsx("span",{className:"font-mono",children:l.code})," ",l.message]},`${l.code}:${l.message}`))})]}),a.jsx(AK,{runId:e.id,traceStatus:t.status,preloaded:s,preloadFailed:i}),a.jsxs("div",{className:"flex flex-col gap-1 border-t border-base-content/10 pt-2",children:[a.jsx("div",{children:a.jsx(Ie,{variant:"outline",size:"xs",onClick:()=>r?.({tab:"system-events",runId:e.id}),children:"System events for this run"})}),a.jsxs("div",{className:"text-[11px] flex items-center gap-2 flex-wrap",children:[a.jsx("span",{className:"text-spur-text-muted",children:"History window:"}),a.jsxs("span",{className:"font-mono","data-history-window":!0,children:[_l(e.startedAt)," →"," ",e.completedAt===null?"running":_l(e.completedAt)]}),a.jsx("code",{className:"font-mono text-[10px] text-spur-text-muted","data-history-command":!0,children:o}),a.jsx(ps,{value:o,label:"history analyze command"})]})]})]})}function AK({runId:e,traceStatus:t,preloaded:n=null,preloadFailed:r=!1}){const[s,i]=h.useState(n),[o,l]=h.useState(r?"error":"idle"),[c,u]=h.useState(r?"Run record could not be read.":null),d=h.useCallback(()=>{l("loading"),u(null),(async()=>{try{const p=await Xe(new Request(`${it()}/observability/run-record/${e}`)),f=await p.json().catch(()=>null);if(!p.ok){const b=f!==null&&typeof f=="object"?f.error:null;throw new Error(typeof b=="string"?b:`run record fetch failed: ${p.status}`)}const m=dA(f);if(!m)throw new Error("run record response failed schema validation");i(m),l("idle")}catch(p){u(p instanceof Error?p.message:String(p)),l("error")}})()},[e]);return a.jsxs("div",{"data-run-record":!0,children:[a.jsxs("div",{className:"text-[10px] uppercase text-spur-text-muted font-semibold mb-1",children:["Run Record"," ",a.jsxs("span",{className:"normal-case font-normal",children:["— status (DB trace):"," ",a.jsx(tt,{variant:oa(t),size:"xs",children:t})]})]}),o==="idle"&&s===null&&a.jsx(Ie,{variant:"outline",size:"xs",onClick:d,"aria-label":`View run record for run ${e}`,children:"View run record"}),o==="loading"&&a.jsxs("div",{className:"flex items-center gap-2 text-xs text-spur-text-muted py-1","aria-live":"polite","aria-busy":"true",children:[a.jsx(ln,{size:"xs"})," Loading run record…"]}),o==="error"&&a.jsxs("div",{className:"text-xs text-error py-1",role:"alert",children:["Failed to load run record: ",c,a.jsx(Ie,{variant:"ghost",size:"xs",className:"ml-2",onClick:d,children:"Retry"})]}),s!==null&&a.jsxs("div",{"aria-live":"polite",children:[s.status==="record"&&a.jsxs(a.Fragment,{children:[a.jsx("pre",{"data-run-record-text":!0,className:"text-[11px] bg-base-300 rounded p-2 overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap",children:s.markdown}),a.jsxs("details",{className:"text-[11px]",children:[a.jsx("summary",{className:"cursor-pointer text-spur-text-muted",children:"Machine state"}),a.jsx("pre",{className:"bg-base-300 rounded p-2 overflow-x-auto max-h-64 overflow-y-auto",children:JSON.stringify(s.state,null,2)})]})]}),s.status==="incomplete"&&a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:"text-xs text-warning py-1",children:["Run record is incomplete (",s.reason,"); the human log is shown, but completion is only proven by the DB trace."]}),a.jsx("pre",{"data-run-record-text":!0,className:"text-[11px] bg-base-300 rounded p-2 overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap",children:s.markdown})]}),s.status==="legacy"&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-xs text-spur-text-muted py-1",children:"Legacy .log record (re-redacted on read)."}),a.jsx("pre",{"data-run-record-text":!0,className:"text-[11px] bg-base-300 rounded p-2 overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap",children:s.content})]}),s.status==="oversized"&&a.jsxs("p",{className:"text-xs text-warning py-1",children:["Run record is too large to display (",s.sizeBytes," bytes)."]}),s.status==="missing"&&a.jsx("p",{className:"text-xs text-spur-text-muted italic py-1",children:"No run record found on disk."})]})]})}function CK({run:e,detail:t,wbs:n,taskStatus:r}){const s=t.projection===null?null:sK({currentState:t.projection.currentState,states:t.projection.states.map(l=>({state:l.state,status:l.status,actions:l.actions.map(c=>({actionKey:c.actionKey,status:c.status}))}))},t.actions),i=aK({runId:e.id,runStatus:e.status,wbs:n,taskStatus:r,resultSummary:t.actions.map(l=>l.resultSummary),recordStatus:t.recordStatus,recordReason:t.recordReason}),o=s?.resultSummary??null;return a.jsxs("div",{className:"mt-2 space-y-1 text-[11px]","data-recovery-guidance":i.guidance.kind,children:[s!==null&&a.jsxs("div",{"data-cause":!0,children:[a.jsx("span",{className:"font-mono",children:s.state}),s.actionKey!==null&&a.jsxs("span",{className:"font-mono",children:[" ",s.actionKey]}),s.actionStatus!==null&&a.jsxs("span",{children:[" ",s.actionStatus]})]}),o!==null&&a.jsx("pre",{className:"text-[10px] whitespace-pre-wrap","data-result-summary":!0,children:JSON.stringify(Lp(o))}),a.jsx("p",{"data-evidence-notice":!0,"data-reusable-as-fresh":"false",children:i.evidence.message}),i.proof!==null&&a.jsx("p",{"data-proof-notice":i.proof.kind,children:i.proof.message}),i.rejected&&a.jsx("p",{"data-recovery-rejected":"true",children:"Work item belongs to a different run and was rejected."}),i.guidance.kind==="continue"&&a.jsx(ul,{command:i.guidance.command,slot:"continue",label:"continue command",note:i.guidance.inputLabel}),i.guidance.kind==="retry"&&a.jsxs(a.Fragment,{children:[a.jsx(ul,{command:i.guidance.traceCommand,slot:"trace",label:"trace command"}),a.jsx(ul,{command:i.guidance.retryCommand,slot:"retry",label:"retry command"})]}),i.guidance.kind==="inspection-only"&&a.jsxs("div",{"data-inspection-only":!0,children:[a.jsx("p",{children:i.guidance.reason}),i.guidance.traceCommand!==null&&a.jsx(ul,{command:i.guidance.traceCommand,slot:"trace",label:"trace command"})]})]})}function ul({command:e,slot:t,label:n,note:r}){return a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("code",{className:"font-mono text-[10px]","data-recovery-command":t,children:e}),r!==void 0&&a.jsx("span",{"data-recovery-input":!0,children:r}),a.jsx(ps,{value:e,label:n})]})}const dl=[{id:"summary",label:"Summary",component:_Y},{id:"system-events",label:"System Events",component:hY},{id:"jobs",label:"Jobs",component:$Y},{id:"trace",label:"Trace",component:NK},{id:"routing",label:"Routing",component:VY},{id:"decisions",label:"Decisions",component:OY}];function _K(){const[e]=Ca(),t=e.get("tab"),[n,r]=h.useState(()=>t!==null&&dl.some(w=>w.id===t)?t:dl[0]?.id??""),[s,i]=h.useState("4h"),[o,l]=h.useState(null),[c,u]=h.useState({status:"connecting",rate:0,lastEventAt:null}),p=dl.find(w=>w.id===n)?.component,f=h.useCallback(w=>{u(w)},[]),m=h.useCallback(w=>{l(w),r(w.tab)},[]),b=h.useCallback(w=>{l(null),r(w)},[]),x=n==="system-events",y=x?c.status:"idle",E=x?c.status==="live"?`live tail · ${c.rate} evt/60s`:c.status==="connecting"?"connecting…":c.status==="paused"?"live tail paused":"stream error":"live tail idle",A=y==="live"?"bg-emerald-400 animate-pulse":y==="connecting"?"bg-amber-400":y==="errored"?"bg-error":"bg-base-content/40";return a.jsxs("div",{className:"flex flex-col gap-4 p-4 max-w-[1600px] mx-auto w-full","data-observability-shell":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rr,{id:"observability",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Observabilities"}),a.jsx("p",{className:"text-xs text-base-content/60",children:"System event streams, queue execution telemetry, and routing attribution"}),a.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:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${A}`,"aria-hidden":"true"}),E,x&&c.lastEventAt&&a.jsxs(a.Fragment,{children:[" · last ",a.jsx("time",{dateTime:c.lastEventAt,children:new Date(c.lastEventAt).toLocaleTimeString()})]})]})]})]}),a.jsx(qV,{timeRange:s,onTimeRangeChange:i}),a.jsx("div",{role:"tablist","aria-label":"Observability tabs",className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:dl.map(w=>{const N=w.id===n;return a.jsx("button",{type:"button",role:"tab","aria-selected":N,"aria-controls":`observability-tab-panel-${w.id}`,id:`observability-tab-${w.id}`,onClick:()=>b(w.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer ${N?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,children:w.label},w.id)})})]}),a.jsx("div",{role:"tabpanel",id:`observability-tab-panel-${n}`,"aria-labelledby":`observability-tab-${n}`,className:"mt-2 flex flex-col gap-4",children:p?a.jsx(p,{onLivenessChange:f,timeRange:s,onNavigate:m,navIntent:o}):null})]})}const IK={id:"observability",name:"Observabilities",icon:"📡",route:"observability",component:_K,sidebarLabel:"Observabilities",description:"Real-time system events, execution traces, and agent doctor telemetry",order:10},RK=Object.freeze(Object.defineProperty({__proto__:null,module:IK},Symbol.toStringTag,{value:"Module"}));function pA(e,t){const n=t.status,r=t instanceof Error?t.message:String(t);throw new Error(n===void 0?`${e}: ${r}`:`${e}: ${n}`)}async function DK(e){try{const t=await xt.planningDocuments.planList({signal:e});if(!Array.isArray(t.files))throw new Error("plan files: invalid response shape");return t.files}catch(t){pA("plan files fetch failed",t)}}async function OK(e,t){try{const n=await xt.planningDocuments.planShow({path:e},{signal:t});if(!n.ok||typeof n.content!="string")throw new Error("plan file: invalid response shape");return n}catch(n){pA("plan file fetch failed",n)}}function LK({files:e,selectedPath:t,onSelect:n}){const[r,s]=h.useState(""),i=h.useMemo(()=>{if(!r.trim())return e;const c=r.toLowerCase();return e.filter(u=>u.name.toLowerCase().includes(c)||u.title.toLowerCase().includes(c)||u.path.toLowerCase().includes(c))},[e,r]),o=h.useMemo(()=>i.filter(c=>c.category==="roadmap"),[i]),l=h.useMemo(()=>i.filter(c=>c.category==="plan"),[i]);return a.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-testid":"plan-file-list",children:[a.jsx("div",{className:"p-2 border-b border-spur-border bg-base-100/50 shrink-0",children:a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",value:r,onChange:c=>s(c.target.value),placeholder:"Filter plans...",className:"w-full text-xs px-2.5 py-1.5 pl-7 rounded border border-spur-border bg-base-100 text-spur-text placeholder:text-spur-text-muted/60 focus:outline-none focus:border-spur-accent","aria-label":"Filter plan documents"}),a.jsx("span",{className:"absolute left-2 top-1.5 text-xs text-spur-text-muted pointer-events-none",children:"🔍"}),r&&a.jsx("button",{type:"button",onClick:()=>s(""),className:"absolute right-2 top-1 text-xs text-spur-text-muted hover:text-spur-text p-0.5","aria-label":"Clear filter",children:"✕"})]})}),a.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-3",children:i.length===0?a.jsx("div",{className:"p-4 text-xs text-spur-text-muted italic text-center",children:r?`No documents match "${r}"`:"No plan documents found."}):a.jsxs(a.Fragment,{children:[o.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"px-2 py-1 text-[11px] font-bold uppercase tracking-wider text-spur-text-muted flex items-center justify-between",children:[a.jsx("span",{children:"Core Roadmap"}),a.jsx("span",{className:"text-[10px] font-mono",children:o.length})]}),a.jsx("div",{className:"space-y-0.5 mt-1",children:o.map(c=>{const u=t===c.path;return a.jsxs("button",{type:"button",onClick:()=>n(c.path),title:c.name,className:`w-full text-left px-2.5 py-1.5 rounded-md transition-colors flex items-center gap-2 cursor-pointer ${u?"bg-spur-accent/15 text-spur-accent font-semibold shadow-xs":"hover:bg-base-300 text-spur-text hover:text-spur-text"}`,children:[a.jsx("span",{className:"text-sm shrink-0",children:"🧭"}),a.jsx("span",{className:"flex-1 min-w-0 text-xs truncate font-medium",title:c.name,children:c.title})]},c.id)})})]}),l.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"px-2 py-1 text-[11px] font-bold uppercase tracking-wider text-spur-text-muted flex items-center justify-between",children:[a.jsx("span",{children:"Execution Plans"}),a.jsx("span",{className:"text-[10px] font-mono",children:l.length})]}),a.jsx("div",{className:"space-y-0.5 mt-1",children:l.map(c=>{const u=t===c.path;return a.jsxs("button",{type:"button",onClick:()=>n(c.path),title:c.name,className:`w-full text-left px-2.5 py-1.5 rounded-md transition-colors flex items-center gap-2 cursor-pointer ${u?"bg-spur-accent/15 text-spur-accent font-semibold shadow-xs":"hover:bg-base-300 text-spur-text hover:text-spur-text"}`,children:[a.jsx("span",{className:"text-xs shrink-0 text-spur-text-muted",children:"📄"}),a.jsx("span",{className:"flex-1 min-w-0 text-xs truncate",title:c.name,children:c.title})]},c.id)})})]})]})})]})}function jK(e){if(!e)return[];const t=e.split(/\r?\n/),n=[],r=new Map;let s=!1;for(const i of t){if(i.trim().startsWith("```")){s=!s;continue}if(s)continue;const l=i.match(/^(#{1,6})\s+(.+)$/);if(l?.[1]&&l[2]){const c=l[1].length,d=l[2].trim().replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim(),f=d.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-")||`heading-${n.length+1}`,m=r.get(f)??0;r.set(f,m+1);const b=m===0?f:`${f}-${m}`;n.push({id:b,text:d,level:c})}}return n}function MK(){const e=new Map;return{nextId(t){const r=t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-")||"heading",s=e.get(r)??0;return e.set(r,s+1),s===0?r:`${r}-${s}`}}}function FK({markdown:e,scrollContainerRef:t,onClose:n}){const r=h.useMemo(()=>jK(e),[e]),[s,i]=h.useState(null);h.useEffect(()=>{const l=t?.current;if(!l||r.length===0)return;const c=()=>{const u=l.getBoundingClientRect().top;let d=null;for(const p of r){const f=document.getElementById(p.id);f&&f.getBoundingClientRect().top-u<=100&&(d=p.id)}d&&i(d)};return l.addEventListener("scroll",c,{passive:!0}),c(),()=>l.removeEventListener("scroll",c)},[r,t]);const o=l=>{i(l);const c=document.getElementById(l);c&&c.scrollIntoView({behavior:"smooth",block:"start"})};return a.jsxs("aside",{id:"plan-toc-dock","aria-label":"Table of Contents",className:"w-64 lg:w-72 shrink-0 rounded-lg border border-spur-border bg-base-200 shadow-xs flex flex-col overflow-hidden 3xl:absolute 3xl:top-0 3xl:bottom-0 3xl:left-[calc(100%_+_12px)] 3xl:z-20 3xl:w-72 4xl:w-80 3xl:shadow-xl","data-testid":"plan-toc-dock",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border bg-base-300/60 shrink-0",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text flex items-center gap-1.5",children:[a.jsx("span",{children:"📑"})," Table of Contents"]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[r.length>0&&a.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-spur-accent/15 text-spur-accent font-semibold",children:r.length}),n&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent h-5 w-5 p-0 text-xs flex items-center justify-center cursor-pointer",onClick:n,"aria-label":"Close table of contents",title:"Close table of contents",children:"✕"})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-1.5 space-y-0.5",children:r.length===0?a.jsx("div",{className:"p-3 text-xs text-spur-text-muted italic",children:"No headings in document."}):r.map(l=>{const c=s===l.id;let u="pl-2 text-xs font-semibold";return l.level===2?u="pl-4 text-xs font-medium":l.level===3?u="pl-6 text-xs text-spur-text-muted":l.level>=4&&(u="pl-8 text-[11px] text-spur-text-muted"),a.jsx("button",{type:"button",onClick:()=>o(l.id),title:l.text,className:`w-full text-left py-1 pr-2 rounded transition-colors truncate block cursor-pointer ${u} ${c?"bg-spur-accent/15 text-spur-accent font-semibold":"hover:bg-base-300 hover:text-spur-text text-spur-text/80"}`,children:l.text},l.id)})})]})}function PK({source:e,className:t}){const n=Px(e),r=MK(),s=o=>{const l=`h${o}`;return({children:c,...u})=>{const p=Vi(c).trim().replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim(),f=r.nextId(p);return a.jsx(l,{id:f,className:"scroll-mt-6 group",...u,children:c})}},i={code:Bx,h1:s(1),h2:s(2),h3:s(3),h4:s(4),h5:s(5),h6:s(6)};return a.jsx("div",{className:`plan-markdown-container ${t??""}`,"data-testid":"plan-markdown-body",children:a.jsx(wa.Markdown,{source:n,wrapperElement:{"data-color-mode":"light"},...Ta,components:i})})}function BK(){const[e,t]=Ca(),[n,r]=h.useState(null),[s,i]=h.useState(()=>e.get("file")),o=h.useRef({}),[l,c]=h.useState({}),[u,d]=h.useState(!0),[p,f]=h.useState(!0),[m,b]=h.useState(!1),[x,y]=h.useState(!0),[E,A]=h.useState(!1),[w,N]=h.useState(null),[_,k]=h.useState(null),[S,v]=h.useState(!1),O=h.useRef(null),C=h.useRef(null),M=h.useCallback(async I=>{try{y(!0);const V=await DK(I);return r(V),N(null),V}catch(V){return I?.aborted||N(V instanceof Error?V.message:String(V)),null}finally{y(!1)}},[]),B=h.useCallback(async(I,V)=>{if(!o.current[I])try{A(!0),k(null);const te=await OK(I,V);o.current[I]=te,c(L=>({...L,[I]:te}))}catch(te){if(V?.aborted)return;k(te instanceof Error?te.message:String(te))}finally{A(!1)}},[]),R=e.get("file");h.useEffect(()=>{const I=new AbortController;return(async()=>{const V=await M(I.signal);if(V&&V.length>0){if(R&&V.some(L=>L.path===R))i(R);else if(!R){const L=V[0]?.path;L&&i(L)}}})(),()=>I.abort()},[M,R]),h.useEffect(()=>{R&&R!==s&&i(R)},[R,s]),h.useEffect(()=>{if(!s)return;const I=new AbortController;return B(s,I.signal),()=>I.abort()},[s,B]);const z=I=>{i(I),f(!0),t({file:I},{replace:!0}),O.current&&(O.current.scrollTop=0)},W=()=>{s&&(navigator.clipboard.writeText(s),v(!0),setTimeout(()=>v(!1),2e3))},F=s?l[s]:null,{frontmatterRaw:J,frontmatter:K,body:X}=h.useMemo(()=>F?.content?wk(F.content):{frontmatterRaw:null,frontmatter:null,body:""},[F?.content]);return w?a.jsxs("div",{className:"p-4 text-sm text-error",role:"alert",children:["Failed to load plan documents: ",w]}):x&&n===null?a.jsx("div",{className:"flex items-center justify-center h-full text-spur-text-muted text-sm",children:"Loading plan documents…"}):a.jsxs("div",{className:"relative h-full w-full p-4 overflow-hidden","data-plans-shell":!0,children:[a.jsxs("div",{className:"flex flex-col h-full w-full max-w-full 3xl:max-w-[1200px] 4xl:max-w-[1600px] mx-auto gap-3","data-plans-workspace":!0,children:[a.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-spur-border pb-3 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rr,{id:"plans",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight text-spur-text",children:"Plans"}),a.jsx("p",{className:"text-xs text-spur-text-muted",children:"Project roadmap, release commitments, and execution proposals"})]})]}),a.jsxs("div",{className:"flex items-center gap-1","data-plans-actions":!0,children:[a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>d(I=>!I),"aria-label":u?"Collapse plan file list":"Expand plan file list","aria-expanded":u,"aria-controls":"plan-files-dock",title:u?"Collapse plan file list":"Expand plan file list",children:u?"◧":"▶"}),s&&F?.content&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>f(I=>!I),"aria-label":p?"Collapse table of contents":"Expand table of contents","aria-expanded":p,"aria-controls":"plan-toc-dock",title:p?"Collapse table of contents":"Expand table of contents",children:p?"📑":"📖"}),a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent",onClick:()=>{(async()=>(await M(),s&&(c(I=>{const V={...I};return delete V[s],V}),B(s))))()},"aria-label":"Refresh plan documents",title:"Refresh plan documents",children:"🔄"})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-stretch gap-3 overflow-hidden 3xl:relative 3xl:block 3xl:overflow-visible",ref:C,children:[a.jsxs("div",{id:"plan-files-dock",hidden:!u,className:`${u?"flex":"hidden"} w-64 lg:w-72 shrink-0 flex-col overflow-hidden rounded-lg border border-spur-border bg-base-200 shadow-xs 3xl:absolute 3xl:right-[calc(100%_+_12px)] 3xl:top-0 3xl:bottom-0 3xl:z-20 3xl:w-72 4xl:w-80 3xl:shadow-xl`,"data-testid":"plan-files-dock",children:[a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-spur-border bg-base-300/60 shrink-0",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text flex items-center gap-1.5",children:[a.jsx("span",{children:"🧭"})," Plan Docs"]}),n&&n.length>0&&a.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-spur-accent/15 text-spur-accent font-semibold",children:n.length})]}),a.jsx("div",{className:"flex-1 overflow-hidden",children:n&&n.length>0?a.jsx(LK,{files:n,selectedPath:s,onSelect:z}):a.jsx("div",{className:"p-3 text-xs text-spur-text-muted italic",children:"No plan documents found."})})]}),a.jsx("div",{className:"flex-1 min-w-0 h-full overflow-hidden rounded-lg border border-spur-border bg-base-100 relative 3xl:w-full 3xl:flex-none","data-testid":"plan-workspace",children:a.jsx("div",{className:"w-full h-full overflow-y-auto",ref:O,children:s?a.jsxs("div",{className:"flex flex-col min-h-full",children:[a.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-6 py-3 border-b border-spur-border bg-base-100/90 backdrop-blur-xs",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-base-200 text-spur-text-muted border border-spur-border shrink-0",children:s}),F?.title&&a.jsx("h2",{className:"text-sm font-semibold text-spur-text truncate",children:F.title})]}),a.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-accent flex items-center gap-1 shrink-0",onClick:()=>b(!0),"aria-label":"View document metadata",title:"View document metadata","data-testid":"metadata-toggle",children:"ℹ Metadata"}),a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-spur-text-muted hover:text-spur-text shrink-0",onClick:W,"aria-label":"Copy file path",title:"Copy file path",children:S?"✓ Copied":"📋 Copy Path"})]})]}),a.jsx("div",{className:"p-6 md:p-8 flex-1","data-testid":"plan-body-container",children:E&&!F?a.jsx("div",{className:"flex items-center justify-center py-20 text-spur-text-muted text-sm",children:"Loading document content…"}):_?a.jsxs("div",{className:"p-4 text-sm text-error bg-error/10 rounded-md border border-error/20",children:["Failed to load document: ",_]}):F?a.jsx(PK,{source:X}):null})]}):a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-spur-text-muted gap-2",children:[a.jsx("span",{className:"text-3xl","aria-hidden":"true",children:"🧭"}),a.jsx("span",{className:"text-sm font-medium",children:"Select a plan document to view"})]})})}),s&&F?.content&&p&&a.jsx(FK,{markdown:X,scrollContainerRef:O,onClose:()=>f(!1)})]})]}),a.jsx(NT,{open:m,onClose:()=>b(!1),title:F?.title,filePath:s,frontmatterRaw:J,frontmatter:K})]})}const $K={id:"plans",name:"Plans",icon:"🧭",route:"plans",component:BK,sidebarLabel:"Plans",description:"Project roadmap, release commitments, and execution proposals",order:24},UK=Object.freeze(Object.defineProperty({__proto__:null,module:$K},Symbol.toStringTag,{value:"Module"})),Vs=50,zK=250,Tt={table:"table",page:"page",sort:"sort",dir:"dir",filterColumn:"fcol",filter:"f"};function HK(e){if(e===null)return 1;const t=Number.parseInt(e,10);return Number.isFinite(t)&&t>=1?t:1}function GK(e){return e==="desc"?"desc":"asc"}function kd(e){if(e===null)return null;const t=e.trim();return t===""?null:t}function WK(){return`${it()}/project/database/tables`}function Vx(e){return`${it()}/project/database/tables/${encodeURIComponent(e)}`}function qK(e,t){const n=new URL(`${Vx(e)}/rows`);return n.searchParams.set("page",String(t.page)),n.searchParams.set("pageSize",String(t.pageSize)),t.sort&&(n.searchParams.set("sort",t.sort),n.searchParams.set("dir",t.dir)),t.filterColumn&&t.filterValue&&(n.searchParams.set("filterColumn",t.filterColumn),n.searchParams.set("filter",t.filterValue)),n.toString()}function VK(e,t,n){const r=new URL(`${Vx(e)}/row`);return r.searchParams.set("offset",String(t)),n.sort&&(r.searchParams.set("sort",n.sort),r.searchParams.set("dir",n.dir)),n.filterColumn&&n.filterValue&&(r.searchParams.set("filterColumn",n.filterColumn),r.searchParams.set("filter",n.filterValue)),r.toString()}async function YK(e){try{return await e.json()}catch{return null}}async function KK(e,t){let n;try{n=await Xe(new Request(e,{signal:t}))}catch{return{ok:!1,state:"failed"}}if(n.status===404)return{ok:!1,state:(await YK(n))?.error==="unknown-table"?"unknown-table":"failed"};if(n.status===503)return{ok:!1,state:"unavailable"};if(!n.ok)return{ok:!1,state:"failed"};try{return{ok:!0,data:await n.json()}}catch{return{ok:!1,state:"failed"}}}function hu(e,t){const[n,r]=h.useState({state:"loading",data:null});return h.useEffect(()=>{if(e===null){r({state:"loading",data:null});return}const s=new AbortController;let i=!0;return r({state:"loading",data:null}),(async()=>{const o=await KK(e,s.signal);i&&r(o.ok?{state:"ready",data:o.data}:{state:o.state,data:null})})(),()=>{i=!1,s.abort()}},[e,t]),n}function ZK(e=0){const t=hu(WK(),e);return h.useMemo(()=>t.data&&t.data.tables.length===0?{state:"empty",data:t.data}:t,[t])}function XK(e,t=0){const n=e===null?null:Vx(e);return hu(n,t)}function QK(e,t,n=0){const r=e!==null&&t!==null?qK(e,t):null,s=hu(r,n);return h.useMemo(()=>s.data&&s.data.total===0?{state:"empty",data:s.data}:s,[s])}function JK(e,t,n,r=0){const s=e!==null&&t!==null&&n!==null?VK(e,t,n):null;return hu(s,r)}function bs(e){return e.toLocaleString("en-US")}function eZ(e,t,n){if(n===0)return"0 of 0";const r=Math.min(e,Math.ceil(n/t)),s=(r-1)*t+1,i=Math.min(r*t,n);return`${bs(s)}–${bs(i)} of ${bs(n)}`}function tZ(e){const t=e.trim();if(t==="")return null;try{return JSON.stringify(JSON.parse(t),null,2)}catch{return null}}function Ad(e,t){return Math.max(1,Math.ceil(e/t))}function fA(){return a.jsx(tt,{variant:"ghost",size:"xs",className:"opacity-60","data-database-null":!0,children:"NULL"})}function mA({bytes:e}){return a.jsx(tt,{variant:"ghost",size:"xs",className:"opacity-60 font-mono","data-database-blob":!0,children:`BLOB · ${bs(e)} B`})}function nZ({cell:e}){if(e.t==="null")return a.jsx(fA,{});if(e.t==="blob")return a.jsx(mA,{bytes:e.bytes});if(e.t==="num")return a.jsx("span",{className:"font-mono text-xs",children:String(e.v)});const t=e.truncated===!0?`${e.v} … [truncated — open the row for the full value]`:e.v;return a.jsx(ur,{tip:t,className:"w-full",children:a.jsx("span",{className:"block max-w-[28rem] truncate font-mono text-xs","data-database-text":!0,children:e.v})})}function rZ({cell:e}){if(e.t==="null")return a.jsx(fA,{});if(e.t==="blob")return a.jsx(mA,{bytes:e.bytes});if(e.t==="num")return a.jsx("span",{className:"font-mono text-xs",children:String(e.v)});const t=tZ(e.v);return t!==null?a.jsx("pre",{className:"font-mono text-[11px] whitespace-pre-wrap break-all","data-database-json":!0,children:t}):a.jsx("span",{className:"font-mono text-xs whitespace-pre-wrap break-all","data-database-text":!0,children:e.v})}const jp=7,sZ="spur:database:columns:v1:";function Yx(e){return`${sZ}${e}`}function eS(e,t=jp){if(e.length<=t)return e.map(i=>i.name);const n=e.filter(i=>i.pk).map(i=>i.name),r=e.filter(i=>!i.pk).map(i=>i.name),s=new Set(n);for(const i of r){if(s.size>=t)break;s.add(i)}return e.filter(i=>s.has(i.name)).map(i=>i.name)}function aZ(e,t,n){try{const r=n??(typeof window<"u"?window.localStorage:void 0);if(!r)return null;const s=r.getItem(Yx(e));if(!s)return null;const i=JSON.parse(s);if(!Array.isArray(i)||i.length===0)return null;const o=new Set(t),l=i.filter(c=>typeof c=="string"&&o.has(c));return l.length>0?l:null}catch{return null}}function tS(e,t,n){try{const r=n??(typeof window<"u"?window.localStorage:void 0);if(!r)return;r.setItem(Yx(e),JSON.stringify(t))}catch{}}function iZ(e,t){try{const n=t??(typeof window<"u"?window.localStorage:void 0);if(!n)return;n.removeItem(Yx(e))}catch{}}function oZ({open:e,onClose:t,schema:n}){return n?a.jsxs(wx,{open:e,onClose:t,className:"max-w-3xl w-full p-0 overflow-hidden bg-base-100 border border-base-content/15 shadow-2xl flex flex-col max-h-[85vh]","data-database-metadata-modal":!0,"aria-label":"Table metadata",children:[a.jsxs("div",{className:"px-5 py-3.5 border-b border-base-content/10 bg-base-200/50 flex items-center justify-between shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[a.jsx("span",{className:"flex items-center justify-center w-6 h-6 rounded bg-primary/15 text-primary font-bold text-xs shrink-0",children:"ℹ"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"text-sm font-semibold text-base-content leading-tight",children:"Table Metadata"}),a.jsx("p",{className:"text-xs text-base-content/60 truncate mt-0.5 font-mono",children:n.name})]})]}),a.jsx(Ie,{variant:"ghost",size:"xs",className:"text-base-content/60 hover:text-base-content h-6 w-6 p-0 text-xs flex items-center justify-center cursor-pointer",onClick:t,"aria-label":"Close metadata",title:"Close metadata",children:"✕"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-4 min-h-0",children:[a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs",children:[a.jsxs("div",{className:"p-2.5 rounded-lg bg-base-200/40 border border-base-content/10",children:[a.jsx("span",{className:"text-[10px] uppercase font-semibold text-base-content/60 block",children:"Table"}),a.jsx("span",{className:"font-mono text-xs font-semibold text-base-content truncate block",title:n.name,children:n.name})]}),a.jsxs("div",{className:"p-2.5 rounded-lg bg-base-200/40 border border-base-content/10",children:[a.jsx("span",{className:"text-[10px] uppercase font-semibold text-base-content/60 block",children:"Total Rows"}),a.jsx("span",{className:"font-mono text-xs text-base-content font-semibold",children:bs(n.rowCount)})]}),a.jsxs("div",{className:"p-2.5 rounded-lg bg-base-200/40 border border-base-content/10",children:[a.jsx("span",{className:"text-[10px] uppercase font-semibold text-base-content/60 block",children:"Columns"}),a.jsx("span",{className:"font-mono text-xs text-base-content font-semibold",children:n.columns.length})]}),a.jsxs("div",{className:"p-2.5 rounded-lg bg-base-200/40 border border-base-content/10",children:[a.jsx("span",{className:"text-[10px] uppercase font-semibold text-base-content/60 block",children:"Primary Key"}),a.jsx("span",{className:"font-mono text-xs text-base-content truncate block",children:n.columns.filter(r=>r.pk).map(r=>r.name).join(", ")||"none"})]})]}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-2",children:a.jsxs("span",{className:"text-xs font-semibold text-base-content/70 uppercase tracking-wide",children:["Fields (",n.columns.length,")"]})}),a.jsx("div",{className:"rounded-lg border border-base-content/10 overflow-hidden bg-base-100",children:a.jsxs("table",{className:"table table-xs w-full","data-database-columns":!0,children:[a.jsx("thead",{className:"bg-base-200/80 text-base-content/70",children:a.jsxs("tr",{children:[a.jsx("th",{className:"w-12 text-center font-mono text-[11px]",children:"#"}),a.jsx("th",{className:"font-mono text-[11px]",children:"Field Name"}),a.jsx("th",{className:"font-mono text-[11px]",children:"Data Type"}),a.jsx("th",{className:"text-[11px]",children:"Constraint"}),a.jsx("th",{className:"text-[11px] text-center w-16",children:"Key"})]})}),a.jsx("tbody",{className:"divide-y divide-base-content/10",children:n.columns.map((r,s)=>a.jsxs("tr",{className:"hover:bg-base-200/40",children:[a.jsx("td",{className:"text-center font-mono text-xs text-base-content/40",children:s+1}),a.jsx("td",{className:"font-mono text-xs font-semibold text-base-content",children:r.name}),a.jsx("td",{className:"font-mono text-xs text-base-content/70",children:r.type===""?a.jsx("span",{className:"text-base-content/40 italic",children:"—"}):r.type}),a.jsx("td",{children:r.notNull?a.jsx(tt,{variant:"ghost",size:"xs",className:"opacity-75 font-mono text-[10px]",children:"NOT NULL"}):a.jsx("span",{className:"text-xs text-base-content/40 font-mono",children:"NULL"})}),a.jsx("td",{className:"text-center",children:r.pk?a.jsx(tt,{variant:"primary",size:"xs",children:"PK"}):a.jsx("span",{className:"text-base-content/20 text-xs",children:"—"})})]},r.name))})]})})]})]}),a.jsx("div",{className:"px-5 py-3 border-t border-base-content/10 bg-base-200/40 flex items-center justify-end shrink-0",children:a.jsx(Ie,{variant:"ghost",size:"xs",onClick:t,"aria-label":"Close metadata",children:"Close"})})]}):null}function pl({state:e,children:t}){return a.jsx("div",{className:"flex h-full items-center justify-center p-8 text-center text-sm text-base-content/60","data-database-state":e,children:t})}function nS(e,t){switch(e){case"loading":return a.jsx(ln,{size:"md"});case"empty":return`Table ${t??""} has no rows.`;case"unknown-table":return`Table ${t??""} no longer exists. Pick another table from the list.`;case"unavailable":return"Database unavailable — the serve daemon is not attached to a project database.";case"failed":return"Request failed — could not read the database.";default:return null}}function lZ(){const[e,t]=Ca(),n=kd(e.get(Tt.table)),r=HK(e.get(Tt.page)),s=kd(e.get(Tt.sort)),i=GK(e.get(Tt.dir)),o=kd(e.get(Tt.filterColumn)),l=e.get(Tt.filter)??"",c=o!==null&&l!=="",[u,d]=h.useState(0),[p,f]=h.useState(""),[m,b]=h.useState(""),[x,y]=h.useState(null),[E,A]=h.useState(!1),w=h.useRef(null),[N,_]=h.useState(!1),[k,S]=h.useState(!1),v=h.useRef(null),[O,C]=h.useState(""),[M,B]=h.useState([]),[R,z]=h.useState(l);h.useEffect(()=>{const ae=setTimeout(()=>z(l),zK);return()=>clearTimeout(ae)},[l]),h.useEffect(()=>{if(!E)return;const ae=De=>{w.current&&!w.current.contains(De.target)&&A(!1)},pe=De=>{De.key==="Escape"&&A(!1)};return document.addEventListener("mousedown",ae),document.addEventListener("keydown",pe),()=>{document.removeEventListener("mousedown",ae),document.removeEventListener("keydown",pe)}},[E]),h.useEffect(()=>{if(!k)return;const ae=De=>{v.current&&!v.current.contains(De.target)&&S(!1)},pe=De=>{De.key==="Escape"&&S(!1)};return document.addEventListener("mousedown",ae),document.addEventListener("keydown",pe),()=>{document.removeEventListener("mousedown",ae),document.removeEventListener("keydown",pe)}},[k]);const W=h.useMemo(()=>{if(n===null)return null;const ae=o!==null&&R!=="";return{page:r,pageSize:Vs,sort:s,dir:i,filterColumn:ae?o:null,filterValue:ae?R:""}},[n,r,s,i,o,R]),F=ZK(u),J=XK(n,u),K=QK(n,W,u),X=JK(n,x,W,u);h.useEffect(()=>{if(K.data===null)return;const ae=Ad(K.data.total,Vs);r<=ae||t(pe=>{const De=new URLSearchParams(pe);return ae<=1?De.delete(Tt.page):De.set(Tt.page,String(ae)),De},{replace:!0})},[K.data,r,t]);const I=ae=>{y(null),t(pe=>{const De=new URLSearchParams(pe);return ae(De),De},{replace:!0})},V=ae=>{S(!1),C(""),_(!1),I(pe=>{pe.set(Tt.table,ae),pe.delete(Tt.page),pe.delete(Tt.sort),pe.delete(Tt.dir),pe.delete(Tt.filterColumn),pe.delete(Tt.filter)})},te=ae=>{I(pe=>{pe.get(Tt.sort)===ae?pe.set(Tt.dir,pe.get(Tt.dir)==="desc"?"asc":"desc"):(pe.set(Tt.sort,ae),pe.set(Tt.dir,"asc")),pe.delete(Tt.page)})},L=ae=>{I(pe=>{ae===""?(pe.delete(Tt.filterColumn),pe.delete(Tt.filter)):pe.set(Tt.filterColumn,ae),pe.delete(Tt.page)})},ye=ae=>{I(pe=>{ae===""?pe.delete(Tt.filter):pe.set(Tt.filter,ae),pe.delete(Tt.page)})},xe=ae=>{const pe=K.data?.total??0,De=Ad(pe,Vs),Me=Math.min(Math.max(1,ae),De);I(Le=>{Me<=1?Le.delete(Tt.page):Le.set(Tt.page,String(Me))})},P=h.useMemo(()=>{const ae=F.data?.tables??[],pe=p.trim().toLowerCase();return pe===""?ae:ae.filter(De=>De.toLowerCase().includes(pe))},[F.data,p]),oe=(()=>{const ae=[J.state,K.state];return ae.includes("unavailable")?"unavailable":ae.includes("unknown-table")?"unknown-table":ae.includes("failed")?"failed":null})(),re=J.state==="ready"&&J.data!==null,H=K.state==="ready"&&K.data!==null,Ce=K.data?.total??0,me=Ad(Ce,Vs),he=K.data?.columns??J.data?.columns.map(ae=>ae.name)??[];h.useEffect(()=>{if(!n||!J.data){B([]);return}const ae=J.data.columns,pe=ae.map(Me=>Me.name),De=aZ(n,pe);De!==null&&De.length>0?B(De):B(eS(ae,jp))},[n,J.data]);const Ne=h.useMemo(()=>{if(M.length>0){const ae=new Set(he),pe=M.filter(De=>ae.has(De));if(pe.length>0)return pe}return he},[M,he]),Ge=h.useMemo(()=>Ne.map(ae=>he.indexOf(ae)).filter(ae=>ae!==-1),[Ne,he]),Z=h.useMemo(()=>new Set(Ne),[Ne]),ke=h.useMemo(()=>{const ae=J.data?.columns??[],pe=O.trim().toLowerCase();return pe===""?ae:ae.filter(De=>De.name.toLowerCase().includes(pe))},[J.data?.columns,O]),Fe=ae=>{if(!n||!J.data)return;const pe=J.data.columns.map(Le=>Le.name),De=new Set(Ne);if(De.has(ae)){if(De.size<=1)return;De.delete(ae)}else De.add(ae);const Me=pe.filter(Le=>De.has(Le));B(Me),tS(n,Me)},Re=()=>{if(!n||!J.data)return;const ae=J.data.columns.map(pe=>pe.name);B(ae),tS(n,ae)},rt=()=>{if(!n||!J.data)return;const ae=eS(J.data.columns,jp);B(ae),iZ(n)};return a.jsxs("div",{className:"flex flex-col h-full min-h-0","data-database-view":!0,children:[a.jsx(yx,{variant:"bordered",className:"min-w-0 flex-1 overflow-hidden",children:a.jsxs(Ex,{className:"p-0 min-h-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2.5 border-b border-base-content/10 px-3 py-2 bg-base-100/60 shrink-0",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[a.jsxs("div",{ref:w,className:"relative",children:[a.jsxs("button",{type:"button","aria-haspopup":"listbox","aria-expanded":E,"aria-label":"Select table","data-database-table-select":!0,onClick:()=>A(ae=>!ae),className:"flex items-center gap-2 px-2.5 py-1 text-xs rounded border border-base-content/20 bg-base-100 hover:bg-base-200/80 transition-colors cursor-pointer text-left font-mono font-medium text-base-content",children:[a.jsxs("svg",{className:"h-3.5 w-3.5 text-base-content/60 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:[a.jsx("ellipse",{cx:"8",cy:"4",rx:"6",ry:"2.5"}),a.jsx("path",{d:"M2 4v4c0 1.38 2.69 2.5 6 2.5s6-1.12 6-2.5V4"}),a.jsx("path",{d:"M2 8v4c0 1.38 2.69 2.5 6 2.5s6-1.12 6-2.5V8"})]}),a.jsx("span",{className:"truncate max-w-[200px] sm:max-w-[320px]",children:n??"Select table…"}),a.jsx("svg",{className:`h-3 w-3 shrink-0 text-base-content/50 transition-transform ${E?"rotate-180":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M4 6l4 4 4-4"})})]}),E&&a.jsxs("div",{role:"dialog","aria-label":"Select table",className:"absolute left-0 top-full mt-1.5 z-50 w-72 sm:w-84 rounded-lg border border-base-content/15 bg-base-100 shadow-xl p-2 flex flex-col gap-2",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Vn,{size:"xs",placeholder:"Filter tables…","aria-label":"Filter tables",value:p,onChange:ae=>f(ae.target.value),onKeyDown:ae=>{const pe=P[0];ae.key==="Enter"&&pe&&(ae.preventDefault(),V(pe),A(!1),f(""))},"data-database-rail-filter":!0,autoFocus:!0}),p&&a.jsx("button",{type:"button",onClick:()=>f(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-base-content/40 hover:text-base-content cursor-pointer","aria-label":"Clear filter",children:"×"})]}),a.jsxs("div",{className:"max-h-64 overflow-y-auto min-h-0 flex flex-col gap-0.5","data-database-rail":!0,"data-database-rail-state":F.state,role:"listbox","aria-label":"Tables",children:[F.state==="loading"&&a.jsx("div",{className:"flex justify-center p-3",children:a.jsx(ln,{size:"sm"})}),F.state==="unavailable"&&a.jsx("p",{className:"p-2 text-xs text-base-content/60 text-center",children:"Database unavailable."}),F.state==="failed"&&a.jsx("p",{className:"p-2 text-xs text-base-content/60 text-center",children:"Could not load tables."}),F.state==="empty"&&a.jsx("p",{className:"p-2 text-xs text-base-content/60 text-center","data-database-rail-empty":!0,children:"This database has no tables."}),F.state==="ready"&&(P.length===0?a.jsx("p",{className:"p-2 text-xs text-base-content/60 text-center",children:"No tables match this filter."}):P.map(ae=>{const pe=ae===n;return a.jsxs("button",{type:"button",role:"option","aria-selected":pe,"data-database-table":ae,onClick:()=>{V(ae),A(!1),f("")},className:`flex items-center justify-between px-2.5 py-1.5 text-xs font-mono rounded text-left transition-colors cursor-pointer ${pe?"bg-primary text-primary-content font-bold":"text-base-content/80 hover:bg-base-content/10 hover:text-base-content"}`,children:[a.jsx("span",{className:"truncate",children:ae}),pe&&a.jsx("span",{className:"text-xs ml-2",children:"✓"})]},ae)}))]})]})]}),n!==null&&re&&J.data!==null&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"h-4 w-px bg-base-content/15 hidden sm:block"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(qr,{size:"xs","aria-label":"Filter column",value:o??"",onChange:ae=>L(ae.target.value),"data-database-filter-column":!0,children:[a.jsx("option",{value:"",children:"Filter column…"}),J.data.columns.map(ae=>a.jsx("option",{value:ae.name,children:ae.name},ae.name))]}),a.jsx(Vn,{size:"xs",placeholder:"contains…","aria-label":"Filter value",value:l,onChange:ae=>ye(ae.target.value),"data-database-filter-value":!0})]})]})]}),n!==null&&re&&J.data!==null&&a.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[a.jsxs("span",{className:"text-xs text-base-content/50 font-mono hidden md:inline",children:[bs(J.data.rowCount)," rows · ",J.data.columns.length," columns"]}),a.jsx("div",{className:"h-4 w-px bg-base-content/15 hidden md:block"}),a.jsxs(Ie,{size:"xs",variant:"outline",onClick:()=>_(!0),className:"flex items-center gap-1.5 font-medium cursor-pointer","aria-label":"Table metadata",title:"View table metadata","data-database-metadata-btn":!0,children:[a.jsxs("svg",{className:"w-3.5 h-3.5 text-base-content/70 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"8",cy:"8",r:"6"}),a.jsx("path",{d:"M8 7v4M8 5h.01"})]}),a.jsx("span",{children:"Metadata"})]}),a.jsxs("div",{ref:v,className:"relative",children:[a.jsxs(Ie,{size:"xs",variant:"outline",onClick:()=>{S(ae=>!ae),C("")},className:"flex items-center gap-1.5 font-medium cursor-pointer","aria-haspopup":"dialog","aria-expanded":k,"aria-label":"Customize visible columns",title:"Customize visible columns","data-database-columns-btn":!0,children:[a.jsxs("svg",{className:"w-3.5 h-3.5 text-base-content/70 shrink-0",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"1.5"}),a.jsx("path",{d:"M6.5 2v12M10.5 2v12"})]}),a.jsx("span",{children:"Columns"}),a.jsxs("span",{className:"font-mono text-[10px] px-1 py-0.2 rounded bg-base-200 text-base-content/70",children:[Ne.length,"/",J.data.columns.length]})]}),k&&a.jsxs("div",{role:"dialog","aria-label":"Customize columns","data-database-columns-dropdown":!0,className:"absolute right-0 top-full mt-1.5 z-50 w-72 rounded-lg border border-base-content/15 bg-base-100 shadow-xl p-3 flex flex-col gap-2.5",children:[a.jsxs("div",{className:"flex items-center justify-between pb-2 border-b border-base-content/10",children:[a.jsxs("span",{className:"text-xs font-bold uppercase tracking-wide text-base-content/70",children:["Visible Fields (",Ne.length,"/",J.data.columns.length,")"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",onClick:Re,className:"text-[11px] text-primary hover:underline cursor-pointer",children:"All"}),a.jsx("span",{className:"text-base-content/30 text-xs",children:"·"}),a.jsx("button",{type:"button",onClick:rt,className:"text-[11px] text-base-content/60 hover:text-base-content hover:underline cursor-pointer",children:"Default"})]})]}),J.data.columns.length>8&&a.jsxs("div",{className:"relative",children:[a.jsx(Vn,{size:"xs",placeholder:"Search fields…","aria-label":"Search fields",value:O,onChange:ae=>C(ae.target.value),autoFocus:!0}),O&&a.jsx("button",{type:"button",onClick:()=>C(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-base-content/40 hover:text-base-content cursor-pointer","aria-label":"Clear search",children:"×"})]}),a.jsx("div",{className:"max-h-64 overflow-y-auto flex flex-col gap-1 pr-1",children:ke.map(ae=>{const pe=Z.has(ae.name),De=pe&&Z.size===1,Me=`database-col-${ae.name}`;return a.jsxs("label",{htmlFor:Me,className:`flex items-center justify-between px-2 py-1 rounded text-xs transition-colors ${De?"opacity-60 cursor-not-allowed":"hover:bg-base-200 cursor-pointer text-base-content"}`,children:[a.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(Sx,{id:Me,size:"xs",variant:"primary",checked:pe,disabled:De,onChange:()=>Fe(ae.name),"aria-label":ae.name}),a.jsx("span",{className:"font-mono truncate",children:ae.name})]}),a.jsxs("span",{className:"flex items-center gap-1 shrink-0 ml-2",children:[ae.pk&&a.jsx(tt,{variant:"primary",size:"xs",children:"PK"}),a.jsx("span",{className:"text-[10px] text-base-content/40 font-mono",children:ae.type||"ANY"})]})]},ae.name)})})]})]})]})]}),n===null&&a.jsx(pl,{state:"prompt",children:a.jsx("p",{"data-database-prompt":!0,children:"Select a table to browse its rows."})}),n!==null&&oe!==null&&a.jsx(pl,{state:oe,children:a.jsxs("div",{className:"flex flex-col items-center gap-2",children:[nS(oe,n),oe==="failed"&&a.jsx(Ie,{size:"xs",variant:"outline",onClick:()=>d(ae=>ae+1),children:"Retry"})]})}),n!==null&&oe===null&&!re&&a.jsx(pl,{state:"loading",children:a.jsx(ln,{size:"md"})}),n!==null&&oe===null&&re&&J.data!==null&&a.jsxs(a.Fragment,{children:[K.state==="loading"&&a.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:a.jsx(ln,{size:"md"})}),K.state==="empty"&&a.jsx(pl,{state:"empty",children:a.jsxs("span",{children:["Table ",n," has no rows",c?" matching this filter":"","."]})}),H&&K.data!==null&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:a.jsxs("table",{className:"table table-sm","data-testid":"database-table",children:[a.jsx("thead",{className:"sticky top-0 z-10 bg-base-200",children:a.jsx("tr",{className:"text-xs text-base-content/60",children:Ne.map(ae=>{const pe=s===ae,De=pe?i==="desc"?"descending":"ascending":"none";return a.jsx("th",{scope:"col","aria-sort":De,className:"whitespace-nowrap",children:a.jsxs("button",{type:"button",onClick:()=>te(ae),"data-database-sort":ae,className:"flex items-center gap-1 font-mono text-xs font-semibold uppercase tracking-wide cursor-pointer",children:[a.jsx("span",{children:ae}),pe&&a.jsx("span",{"aria-hidden":"true",children:i==="desc"?"▼":"▲"})]})},ae)})})}),a.jsx("tbody",{children:K.data.rows.map((ae,pe)=>{const De=(r-1)*Vs+pe;return a.jsx("tr",{tabIndex:0,"aria-haspopup":"dialog","data-database-row":!0,className:"hover:bg-base-200/70 cursor-pointer focus:outline-none focus:bg-base-200/70",onClick:()=>y(De),onKeyDown:Me=>{(Me.key==="Enter"||Me.key===" ")&&(Me.preventDefault(),y(De))},children:Ge.map(Me=>a.jsx("td",{className:"align-middle max-w-[28rem]",children:ae[Me]?a.jsx(nZ,{cell:ae[Me]}):null},he[Me]??Me))},De)})})]})}),a.jsxs("footer",{className:"flex items-center justify-between gap-4 border-t border-base-content/10 px-2 py-2 text-xs text-base-content/70",children:[a.jsx("span",{"data-database-range":!0,children:eZ(r,Vs,Ce)}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{size:"xs",variant:"outline",disabled:r<=1,onClick:()=>xe(r-1),"data-database-prev":!0,children:"Prev"}),a.jsxs("span",{"data-database-page":!0,children:["Page ",r," of ",bs(me)]}),a.jsx(Ie,{size:"xs",variant:"outline",disabled:r>=me,onClick:()=>xe(r+1),"data-database-next":!0,children:"Next"}),a.jsx(Vn,{size:"xs",type:"number",min:1,className:"w-16","aria-label":"Go to page",placeholder:String(r),value:m,onChange:ae=>b(ae.target.value)}),a.jsx(Ie,{size:"xs",variant:"outline",onClick:()=>{const ae=Number.parseInt(m,10);Number.isFinite(ae)&&xe(ae),b("")},"data-database-go":!0,children:"Go"})]})]})]})]})]})}),a.jsxs(wx,{open:x!==null,onClose:()=>y(null),className:"max-w-3xl","data-database-detail":!0,"aria-label":"Row detail",children:[a.jsx("h3",{className:"text-sm font-bold",children:"Row detail"}),X.state==="loading"&&a.jsx("div",{className:"flex justify-center p-6",children:a.jsx(ln,{size:"md"})}),X.state!=="loading"&&X.state!=="ready"&&a.jsx("p",{className:"p-4 text-sm text-base-content/60","data-database-detail-state":X.state,children:nS(X.state,n)}),X.state==="ready"&&X.data!==null&&a.jsx("div",{className:"mt-2 max-h-[60vh] overflow-auto",children:a.jsx("dl",{className:"divide-y divide-base-content/10",children:X.data.columns.map((ae,pe)=>a.jsxs("div",{className:"grid grid-cols-[10rem_1fr] gap-3 py-2",children:[a.jsx("dt",{className:"font-mono text-xs font-semibold",children:ae}),a.jsx("dd",{className:"min-w-0",children:a.jsx(rZ,{cell:X.data?.row[pe]??{t:"null"}})})]},ae))})}),a.jsx("div",{className:"flex justify-end gap-2 pt-4",children:a.jsx(Ie,{size:"sm",onClick:()=>y(null),children:"Close"})})]}),a.jsx(oZ,{open:N,onClose:()=>_(!1),schema:J.data})]})}const hA={path:null,name:"",fleet:null,state:"loading"},gA=h.createContext(hA);function cZ({children:e}){const[t,n]=h.useState(hA);return h.useEffect(()=>{const r=new AbortController;let s=!1;return Xe(new Request(`${it()}/project`,{signal:r.signal})).then(async i=>i.ok?await i.json():null).then(i=>{if(s)return;if(!i?.path){n({path:null,name:"",fleet:null,state:"unresolvable"});return}const o=i.path;n(l=>({...l,path:o,name:i.name??"",state:"ready"}))}).catch(()=>{s||n({path:null,name:"",fleet:null,state:"unresolvable"})}),Xe(new Request(`${it()}/project/fleet`,{signal:r.signal})).then(async i=>i.ok?await i.json():null).then(i=>{s||i===null||n(o=>({...o,fleet:i}))}).catch(()=>{}),()=>{s=!0,r.abort()}},[]),a.jsx(gA.Provider,{value:t,children:e})}function Ms(){return h.useContext(gA)}const fl="operator",uZ=()=>`${it()}/events/planning`;function rS(e,t){return t.includes(e.id)?0:1}function dZ(e){const t=new Map;for(const r of e){const s=r.threadId||r.id,i=t.get(s);i===void 0?t.set(s,[r]):i.push(r)}return[...t.values()].map(r=>r.sort((s,i)=>s.createdAt-i.createdAt)).sort((r,s)=>(r[0]?.createdAt??0)-(s[0]?.createdAt??0))}function pZ(e,t){if(e===null||typeof e!="object")return{members:!1,thread:!1};const{eventName:n,payload:r}=e;if(typeof n!="string"||!n.startsWith("message."))return{members:!1,thread:!1};const s=r?.data??null,i=[s?.fromId,s?.toId].filter(o=>typeof o=="string");return{members:!0,thread:i.length===0||t!==null&&i.includes(t)}}function fZ(e,t){const n=new Set(e.map(r=>r.id));return[...e,...t.filter(r=>!n.has(r.id))]}function mZ(e){return e.status==="failed"?`failed${e.error?` — ${e.error}`:""}`:e.status}const hZ=xt.inbox;function gZ({client:e=hZ}={}){const t=Ms(),[n,r]=h.useState(null),[s,i]=h.useState(null),[o,l]=h.useState(null),[c,u]=h.useState(null),[d,p]=h.useState(!1),[f,m]=h.useState(null),[b,x]=h.useState(""),[y,E]=h.useState(null),[A,w]=h.useState(0),[N,_]=h.useState(0),k=h.useCallback(()=>{w(X=>X+1),_(X=>X+1)},[]),S=h.useRef(s);S.current=s;const v=h.useRef({project:null,member:null,oldestId:null}),O=h.useRef(0),C=h.useRef(!1),M=h.useRef(t.path);M.current!==t.path&&(M.current=t.path,O.current+=1);const B=h.useRef({project:t.path,member:s,generation:0});(B.current.project!==t.path||B.current.member!==s)&&(B.current={project:t.path,member:s,generation:B.current.generation+1}),h.useEffect(()=>()=>{B.current.generation+=1},[]);const R=h.useMemo(()=>(t.fleet?.members??[]).map(X=>X.instanceId),[t.fleet]);h.useEffect(()=>{t.path,r(null),i(null),l(null),u(null),m(null),x(""),E(null)},[t.path]),h.useEffect(()=>{if(t.path===null||typeof EventSource>"u")return;const X=new EventSource(uZ());return X.onmessage=I=>{try{const V=pZ(JSON.parse(I.data),S.current);V.members&&w(te=>te+1),V.thread&&_(te=>te+1)}catch{}},()=>X.close()},[t.path]),h.useEffect(()=>{if(t.path===null)return;let X=!1;return(async()=>{try{const I=await e.members({});if(X)return;r(I)}catch(I){X||E(I instanceof Error?I.message:"could not read the member list")}})(),()=>{X=!0}},[e,t.path,A]);const z=h.useMemo(()=>{const X=new Map(R.map(I=>[I,{id:I,queued:0,unread:0}]));for(const I of n??[])X.set(I.id,I);return[...X.values()].sort((I,V)=>rS(I,R)-rS(V,R)||I.id.localeCompare(V.id))},[n,R]);h.useEffect(()=>{i(X=>X??z[0]?.id??null)},[z]),h.useEffect(()=>{if(t.path===null||s===null)return;let X=!1;O.current+=1,C.current=!0,p(!0);const I=v.current.project===t.path&&v.current.member===s,V=I?v.current.oldestId:null;return I||(l(null),u(null),m(null)),(async()=>{try{let te=await e.list({member:s,direction:"both"});const L=[...te.messages];for(;V!==null&&te.nextCursor!==null&&!L.some(ye=>ye.id===V);){if(X)return;te=await e.list({member:s,direction:"both",cursor:te.nextCursor}),L.push(...te.messages)}X||(l(L),u(te.nextCursor),v.current={project:t.path,member:s,oldestId:V},E(null))}catch(te){X||E(te instanceof Error?te.message:"could not read this thread")}finally{X||(C.current=!1,p(!1))}})(),()=>{X=!0,O.current+=1}},[e,t.path,s,N]);const W=h.useCallback(async()=>{if(s===null||c===null||C.current)return;const X=O.current;C.current=!0,p(!0);try{const I=await e.list({member:s,direction:"both",cursor:c});if(X!==O.current||S.current!==s||M.current!==t.path)return;l(V=>fZ(V??[],I.messages)),u(I.nextCursor),v.current={project:t.path,member:s,oldestId:I.messages.at(-1)?.id??v.current.oldestId}}catch(I){X===O.current&&S.current===s&&E(I instanceof Error?I.message:"could not read older messages")}finally{X===O.current&&(C.current=!1,p(!1))}},[e,t.path,s,c]),F=h.useCallback(async()=>{const X=b.trim();if(X===""||s===null)return;const I=B.current.generation;try{if(f!==null?await e.reply({id:f.id,from:fl,body:X}):await e.send({to:s,...t.path!==null?{projectPath:t.path}:{},body:X}),B.current.generation!==I)return;x(V=>V===b?"":V),m(V=>V?.id===f?.id?null:V),k()}catch(V){B.current.generation===I&&E(V instanceof Error?V.message:"the message was not sent")}},[e,b,f,s,t.path,k]),J=h.useCallback(async X=>{const I=B.current.generation;try{await e.read({id:X.id,reader:fl}),B.current.generation===I&&k()}catch(V){B.current.generation===I&&E(V instanceof Error?V.message:"could not mark this message read")}},[e,k]),K=h.useMemo(()=>dZ(o??[]),[o]);return a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(180px, 240px) 1fr",gap:16},children:[a.jsxs("aside",{"aria-label":"Inbox members",children:[a.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:8},children:[a.jsx("h3",{style:{margin:0,fontSize:13,color:"var(--color-spur-text-muted)"},children:"Members"}),a.jsx("button",{type:"button",onClick:k,title:"Refetch the member list and thread",children:"Refresh"})]}),z.length===0?a.jsx("p",{style:{color:"var(--color-spur-text-faint)"},children:"No inbox addresses yet."}):a.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:z.map(X=>{const I=X.id===s;return a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>{X.id!==s&&(O.current+=1,i(X.id),l(null),u(null),m(null))},"aria-pressed":I,style:{width:"100%",textAlign:"left",padding:"6px 8px",marginBottom:2,borderRadius:6,border:"1px solid var(--color-spur-border)",background:I?"var(--color-spur-surface-2)":"transparent",color:"var(--color-spur-text)",cursor:"pointer"},children:[a.jsx("span",{style:{display:"block",fontSize:13},children:X.id}),a.jsxs("span",{style:{fontSize:11,color:"var(--color-spur-text-muted)"},children:[X.queued," queued · ",X.unread," unread"]})]})},X.id)})})]}),a.jsxs("section",{"aria-label":"Thread",children:[y!==null?a.jsx("p",{role:"alert",style:{color:"var(--color-spur-text-muted)"},children:y}):null,s!==null&&c!==null?a.jsx("button",{type:"button",disabled:d,onClick:()=>{W()},style:{marginBottom:8},children:"Load older"}):null,s===null?a.jsx("p",{style:{color:"var(--color-spur-text-faint)"},children:"Select a member to read its thread."}):K.length===0?a.jsxs("p",{style:{color:"var(--color-spur-text-faint)"},children:["No messages with ",s," yet."]}):K.map(X=>a.jsx("article",{style:{marginBottom:16},children:X.map(I=>{const V=I.fromId===fl,te=I.toId===fl&&I.readAt===null;return a.jsxs("div",{style:{border:"1px solid var(--color-spur-border)",borderRadius:8,padding:"8px 10px",marginBottom:6,background:V?"var(--color-spur-surface-2)":"var(--color-spur-surface)"},children:[a.jsxs("div",{style:{fontSize:11,color:"var(--color-spur-text-muted)"},children:[I.fromId," → ",I.toId," · ",mZ(I),te?" · unread":""]}),a.jsx("p",{style:{margin:"4px 0",whiteSpace:"pre-wrap"},children:I.body}),a.jsxs("div",{style:{display:"flex",gap:8},children:[V?null:a.jsx("button",{type:"button",onClick:()=>m(I),children:"Reply"}),te?a.jsx("button",{type:"button",onClick:()=>{J(I)},children:"Mark read"}):null]})]},I.id)})},X[0]?.threadId??X[0]?.id)),a.jsxs("form",{onSubmit:X=>{X.preventDefault(),F()},style:{display:"flex",flexDirection:"column",gap:6,marginTop:12},children:[f!==null?a.jsxs("span",{style:{fontSize:11,color:"var(--color-spur-text-muted)"},children:["Replying to ",f.fromId," ·"," ",a.jsx("button",{type:"button",onClick:()=>m(null),children:"cancel"})]}):null,a.jsx("textarea",{value:b,onChange:X=>x(X.target.value),placeholder:s===null?"Select a member first":`Message ${s} as operator`,disabled:s===null,rows:3,style:{width:"100%"}}),a.jsx("button",{type:"submit",disabled:s===null||b.trim()==="",children:f===null?"Send":"Reply"})]})]})]})}const bZ=100,xZ=()=>`${it()}/events/history?limit=${bZ}`,yZ=["agent.","message.","task.","supervisor.","process."];function EZ(e){return yZ.some(t=>e.startsWith(t))}function SZ(e){if(e===null||typeof e!="object")return null;const t=e;if(typeof t.eventName!="string"||typeof t.occurredAt!="string"||!EZ(t.eventName))return null;const n=t.payload!==null&&typeof t.payload=="object"?t.payload:null,r=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,...s?{memberLabel:s}:{},...r?{agentType:r}:{}}}function wZ(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 s=SZ(r);s&&n.push(s)}return n}const ml=1e3,Cd=[1e3,2e3,4e3,8e3,15e3],vZ=15e3;function NZ(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 TZ(e){return e<0?Cd[0]:e>=Cd.length?vZ:Cd[e]}function sS(e,t,n){if(t.seq===void 0){const s=[...e,t];return s.length>ml&&s.splice(0,s.length-ml),{frames:s,lastSeq:n}}if(t.seq<=n)return{frames:e,lastSeq:n};const r=[...e,t];return r.length>ml&&r.splice(0,r.length-ml),{frames:r,lastSeq:t.seq}}const kZ=(e,t)=>t!==void 0?`${it()}/processes/${encodeURIComponent(e)}/stream?sinceSeq=${t}`:`${it()}/processes/${encodeURIComponent(e)}/stream`,Kx=3e3;function Zx(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 s=r;if(typeof s.agentId!="string"||typeof s.status!="string"||typeof s.startedAt!="string"||typeof s.pid!="number")return null;const i=s.exitCode;if(i!==null&&typeof i!="number")return null;const o=s.session,l=o!==null&&typeof o=="object"&&(o.mode==="persistent"||o.mode==="resume"||o.mode==="one-shot")?{mode:o.mode,...typeof o.id=="string"&&o.id.length>0?{id:o.id}:{}}:void 0;n.push({agentId:s.agentId,pid:s.pid,status:s.status,startedAt:s.startedAt,exitCode:i,...l!==void 0?{session:l}:{}})}return n}function AZ(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 s=r;if(typeof s.id!="string"||typeof s.label!="string"||typeof s.command!="string"||!Array.isArray(s.args)||!s.args.every(i=>typeof i=="string")||s.pid!==null&&typeof s.pid!="number"||typeof s.status!="string"||typeof s.startedAt!="string"||s.exitedAt!==null&&typeof s.exitedAt!="string"||s.exitCode!==null&&typeof s.exitCode!="number"||typeof s.source!="string"||s.agentId!==null&&typeof s.agentId!="string")return null;n.push({id:s.id,label:s.label,command:s.command,args:s.args,pid:s.pid,status:s.status,startedAt:s.startedAt,exitedAt:s.exitedAt,exitCode:s.exitCode,source:s.source,agentId:s.agentId})}return n}const CZ=e=>`${it()}/processes/${encodeURIComponent(e)}/stdin`,_Z=()=>`${it()}/processes`;function IZ({agentId:e,sessionId:t}){const[n,r]=h.useState([]),[s,i]=h.useState("unknown"),[o,l]=h.useState(""),[c,u]=h.useState(null),[d,p]=h.useState(!1),f=h.useRef(-1),m=h.useRef(null),b=h.useRef(void 0),x=h.useRef(0),y=h.useRef(!0),E=h.useRef(null),A=h.useCallback(async S=>{try{const v=await Xe(new Request(_Z(),{signal:S}));if(!v.ok)return;const O=await v.json(),C=Zx(O);if(!C)return;const M=C.find(B=>B.agentId===e);M&&y.current&&i(M.status)}catch{}},[e]);h.useEffect(()=>{y.current=!0;let S=null;const v=()=>{S?.abort(),S=new AbortController,A(S.signal)};v();const O=setInterval(v,Kx);return()=>{y.current=!1,S?.abort(),clearInterval(O)}},[A]);const w=h.useCallback(()=>{if(!y.current)return;const S=new EventSource(kZ(e,f.current>-1?f.current:void 0));m.current=S,S.onmessage=v=>{try{const O=JSON.parse(v.data),C=NZ(O);if(!C)return;r(M=>{const B=sS(M,C,f.current);return f.current=B.lastSeq,B.frames}),x.current=0,p(!0)}catch{}},S.onerror=()=>{if(S.close(),m.current=null,p(!1),!y.current)return;const v=TZ(x.current);x.current+=1,b.current=setTimeout(w,v)}},[e]);h.useEffect(()=>(w(),()=>{y.current=!1,m.current?.close(),m.current=null,b.current&&clearTimeout(b.current)}),[w]),h.useEffect(()=>{E.current&&n.length>0&&(E.current.scrollTop=E.current.scrollHeight)},[n]);const N=h.useCallback(async()=>{const S=o;if(S.length===0)return;u(null);const v={stream:"meta",ts:new Date().toISOString(),line:`> ${S}`};r(O=>sS(O,v,f.current).frames);try{const O=await Xe(new Request(CZ(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({line:S})}));if(!O.ok){const M=(await O.json().catch(()=>null))?.error??`stdin POST failed: ${O.status}`;u(M);return}l("")}catch(O){u(O instanceof Error?O.message:String(O))}},[e,o]),_=s==="running",k=S=>{S.key==="Enter"&&_&&(S.preventDefault(),N())};return a.jsxs("div",{className:"flex flex-col h-full overflow-hidden","data-member-terminal":e,children:[a.jsxs("div",{className:"px-4 py-2 border-b border-spur-border bg-base-200 shrink-0 flex items-center gap-2",children:[a.jsx("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:"Terminal"}),a.jsx("span",{className:"font-mono text-xs text-spur-text-muted",children:e}),t&&a.jsxs("span",{className:"font-mono text-[10px] text-spur-text-muted hidden sm:inline","data-terminal-session":!0,title:`Session ID: ${t}`,children:["sess:",t.slice(0,8),"…"]}),a.jsx(tt,{variant:_?"success":"ghost",size:"xs","data-terminal-status":!0,children:s}),a.jsx("span",{className:"text-[10px] text-spur-text-muted","data-terminal-connected":!0,children:d?"connected":"reconnecting…"})]}),!_&&a.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 ",s," — input disabled."]}),a.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:n.length===0?a.jsxs("span",{className:"text-spur-text-muted italic",children:["Waiting for output from ",e,"…"]}):n.map((S,v)=>a.jsx("div",{className:S.stream==="stderr"?"text-error":S.stream==="meta"?"text-spur-text-muted italic":"text-spur-text","data-stream":S.stream,children:S.line},S.seq??`meta-${v}`))}),c&&a.jsx("div",{className:"px-4 py-1 text-xs text-error border-t border-spur-border",role:"alert","data-input-error":!0,children:c}),a.jsx("div",{className:"flex items-center gap-2 px-2 py-2 border-t border-spur-border bg-base-200 shrink-0",children:a.jsx("input",{type:"text",value:o,onChange:S=>l(S.target.value),onKeyDown:k,disabled:!_,placeholder:_?"Type a line and press Enter…":"Input disabled (member not running)",className:"flex-1 input input-sm font-mono","data-terminal-input":!0})})]})}const RZ="operator";function Xx(e){return e===void 0?null:e.id===void 0?e.mode:`${e.mode} · ${e.id.slice(0,8)}`}function aS(e,t){const{state:n,instanceId:r}=t.orchestrator;return n!=="bound-online"&&n!=="bound-offline"?!1:r!==void 0&&r===e.instanceId}function DZ(e,t){const n=new Map(t.map(s=>[s.agentId,s])),r=[];for(const s of e.members){const i=n.get(s.instanceId),o={status:iS(i),pid:i?.pid??null,startedAt:i?.startedAt??null,exitCode:i?.exitCode??null,session:i?.session??null},l=[];s.enabled===!1&&l.push("disabled"),s.capabilityState==="unavailable"&&l.push("executor-unavailable"),s.capabilityState==="unknown"&&l.push("capability-unknown"),e.capacity.missing.includes(s.instanceId)&&l.push("unresolved"),r.push({instanceId:s.instanceId,declared:s,observed:o,isOrchestrator:aS({instanceId:s.instanceId},e),issues:l})}for(const s of t)e.members.some(i=>i.instanceId===s.agentId)||s.agentId!==RZ&&r.push({instanceId:s.agentId,declared:null,observed:{status:iS(s),pid:s.pid,startedAt:s.startedAt,exitCode:s.exitCode,session:s.session??null},isOrchestrator:aS({instanceId:s.agentId},e),issues:["undeclared"]});return r.sort((s,i)=>s.isOrchestrator!==i.isOrchestrator?s.isOrchestrator?-1:1:s.instanceId<i.instanceId?-1:s.instanceId>i.instanceId?1:0),r}function iS(e){return e===void 0?"not-started":e.status==="running"?"running":"exited"}const bA=6e4,Mp=60*bA,oS=24*Mp;function OZ(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 s=Math.floor(r/oS),i=Math.floor(r%oS/Mp),o=Math.floor(r%Mp/bA);return s>0?`up ${s}d ${i}h`:i>0?`up ${i}h ${o}m`:`up ${o}m`}const LZ=(e,t)=>`${it()}/agents/${encodeURIComponent(e)}/${t}`;function jZ({entry:e,onClose:t,execution:n,fullCommand:r,className:s}){const i=Ms(),o=i.fleet?.path??i.path??"Unavailable",l=e.declared===null?"Unavailable":e.declared.model??"Executor default",c=e.declared?.role,u=i.fleet?.roles?.find(K=>K.name===c),d=u?.stages&&u.stages.length>0?u.stages:i.fleet?.stages?.filter(K=>K.role===c).map(K=>K.id)??[],p=e.declared?.executor??u?.electedExecutor??"Unavailable",f=e.observed.session??e.declared?.session,m=f?.id,[b,x]=h.useState(null),[y,E]=h.useState(null),[A,w]=h.useState(!1),[N,_]=h.useState(null),[k,S]=h.useState(!0),[v,O]=h.useState(!1),[C,M]=h.useState(!1),B=h.useRef(null);h.useEffect(()=>{if(!v)return;const K=X=>{B.current&&!B.current.contains(X.target)&&O(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[v]),h.useEffect(()=>{const K=X=>{X.key==="Escape"&&(v?O(!1):t())};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[t,v]),h.useEffect(()=>{let K=!1;return x(null),xt.inbox.list({member:e.instanceId,direction:"in"}).then(X=>{K||x(X.messages)}).catch(()=>{K||x([])}),()=>{K=!0}},[e.instanceId]),h.useEffect(()=>{let K=!1;return E(null),Xe(new Request(xZ())).then(async X=>X.ok?wZ(await X.json()):[]).then(X=>{K||E((X??[]).filter(I=>I.memberLabel===e.instanceId||I.actor===e.instanceId))}).catch(()=>{K||E([])}),()=>{K=!0}},[e.instanceId]);const R=e.issues.includes("executor-unavailable")||e.issues.includes("unresolved"),z=e.issues.includes("executor-unavailable")?"controls disabled — executor unavailable":e.issues.includes("unresolved")?"controls disabled — member unresolved":null,W=async K=>{w(!0),_(null);try{const X=await Xe(new Request(LZ(e.instanceId,K),{method:"POST"}));X.ok||_(`${K} failed: ${X.status}`)}catch(X){_(X instanceof Error?X.message:String(X))}finally{w(!1)}},F=e.observed.status==="running",J=[`Role: ${e.declared?.role??"member"}`,`Executor: ${p}`,`Model: ${l}`,`Status: ${e.observed.status}${e.observed.pid!==null?` — pid ${e.observed.pid}`:""}`,"Click to toggle agent details"].join(`
309
309
  `);return a.jsxs("div",{className:`flex flex-col bg-spur-surface overflow-hidden ${s??"h-full shrink-0 border-t border-spur-border"}`,"data-member-detail":!0,children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-spur-border shrink-0 relative",children:[a.jsxs("div",{className:"relative",children:[a.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-left group cursor-pointer focus:outline-none",onClick:()=>O(K=>!K),title:J,"aria-expanded":v,"aria-haspopup":"dialog",children:[a.jsx("span",{className:"text-sm font-semibold text-spur-text group-hover:text-spur-accent transition-colors",children:e.declared?.role??"member"}),a.jsxs("span",{className:"text-xs font-mono text-spur-text-muted",children:["(",e.instanceId,")"]}),e.isOrchestrator&&a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-spur-accent/20 text-spur-accent font-medium uppercase tracking-wide",children:"orchestrator"}),a.jsxs("span",{className:`text-[10px] px-1.5 py-0.5 rounded border transition-colors flex items-center gap-1 ${v?"bg-spur-accent/20 text-spur-accent border-spur-accent/40 font-medium":"bg-spur-surface-2 text-spur-text-muted group-hover:text-spur-text border-spur-border/70"}`,children:[a.jsx("span",{"aria-hidden":"true",children:"ℹ️"}),a.jsx("span",{children:"info"})]})]}),a.jsxs("div",{ref:B,role:"dialog","aria-label":"Agent member details",className:`absolute top-full left-0 mt-2 z-50 w-[420px] max-w-[90vw] p-3 rounded-xl bg-spur-surface border border-spur-border shadow-2xl text-xs flex flex-col gap-2 transition-all ${v?"opacity-100 visible pointer-events-auto translate-y-0":"opacity-0 invisible pointer-events-none -translate-y-1"}`,children:[a.jsxs("div",{className:"flex items-center justify-between pb-1.5 border-b border-spur-border",children:[a.jsxs("span",{className:"font-semibold text-spur-text",children:[e.declared?.role??"member"," (",e.instanceId,")"]}),a.jsx("button",{type:"button",className:"text-spur-text-muted hover:text-spur-text p-0.5 rounded cursor-pointer",onClick:()=>O(!1),"aria-label":"Close details popup",children:"✕"})]}),a.jsxs("span",{className:"text-spur-text-muted",children:["declared:"," ",a.jsx("span",{className:"text-spur-text",children:e.declared===null?"none":`${e.declared.enabled?"enabled":"disabled"} · capability ${e.declared.capabilityState}`})]}),a.jsxs("span",{className:"text-spur-text-muted",children:["observed:"," ",a.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.jsxs("span",{className:"text-spur-text-muted flex items-center justify-between","data-member-session":!0,children:[a.jsxs("span",{children:["session:"," ",a.jsx("span",{className:"font-mono text-spur-text",children:Xx(f)??"—"})]}),m&&a.jsx("button",{type:"button",className:"px-1.5 py-0.5 rounded text-[10px] bg-spur-surface-2 hover:bg-spur-surface-3 border border-spur-border text-spur-text cursor-pointer transition-colors",onClick:()=>{navigator.clipboard?.writeText(m),M(!0),setTimeout(()=>M(!1),1500)},title:`Copy session id: ${m}`,"data-copy-session-id":!0,children:C?"copied!":"copy id"})]}),a.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-1 pt-1 border-t border-spur-border",children:[a.jsx("dt",{className:"text-spur-text-muted",children:"Process Stream"}),a.jsxs("dd",{className:"font-mono text-spur-text break-all","data-member-stream-url":!0,children:["/api/processes/",e.instanceId,"/stream"]}),a.jsx("dt",{className:"text-spur-text-muted",children:"Role"}),a.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-role":!0,children:e.declared?.role??"member"}),a.jsx("dt",{className:"text-spur-text-muted",children:"Executor"}),a.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-executor":!0,children:p}),a.jsx("dt",{className:"text-spur-text-muted",children:"Model"}),a.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-model":!0,children:l}),d.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("dt",{className:"text-spur-text-muted",children:"Stages"}),a.jsx("dd",{className:"flex items-center gap-1 flex-wrap","data-member-stages":!0,children:d.map(K=>a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-base-200 text-spur-text-muted border border-spur-border/60",children:K},K))})]}),a.jsx("dt",{className:"text-spur-text-muted",children:"Working directory"}),a.jsx("dd",{className:"font-mono text-spur-text break-all","data-member-workdir":!0,children:o})]}),(r||n?.command)&&a.jsxs("div",{className:"mt-1 pt-1 border-t border-spur-border/50 text-xs",children:[a.jsx("span",{className:"text-spur-text-muted text-[11px]",children:"Command: "}),a.jsx("code",{className:"font-mono text-[11px] text-spur-text break-all bg-spur-surface-2 p-1 rounded border border-spur-border block",children:r??`${n?.command} ${(n?.args??[]).join(" ")}`})]})]})]}),a.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[z!==null&&a.jsx("span",{className:"text-xs text-spur-text-muted hidden sm:inline","data-lifecycle-reason":!0,children:z}),N!==null&&a.jsx("span",{className:"text-xs text-error",role:"alert","data-lifecycle-error":!0,children:N}),a.jsx("button",{type:"button",className:"px-2 py-0.5 rounded-lg text-xs bg-spur-accent text-white disabled:opacity-40 hover:opacity-90 transition-opacity cursor-pointer disabled:cursor-not-allowed font-medium",disabled:A||R||F,onClick:()=>{W("start")},"data-member-start":!0,children:"start"}),a.jsx("button",{type:"button",className:"px-2 py-0.5 rounded-lg text-xs bg-spur-surface-3 text-spur-text disabled:opacity-40 hover:bg-spur-surface-2 transition-colors border border-spur-border cursor-pointer disabled:cursor-not-allowed font-medium",disabled:A||R||!F,onClick:()=>{W("stop")},"data-member-stop":!0,children:"stop"}),a.jsxs("button",{type:"button",className:`px-2 py-0.5 rounded text-xs font-mono flex items-center gap-1 transition-colors border cursor-pointer ${k?"bg-spur-accent/20 text-spur-accent border-spur-accent/40":"bg-spur-surface-2 text-spur-text-muted hover:text-spur-text border-spur-border"}`,"aria-label":"Toggle stdout/stderr terminal","data-detail-toggle-terminal":!0,onClick:()=>S(K=>!K),title:"Toggle live stdout/stderr process stream",children:[a.jsx("span",{children:">_"}),a.jsx("span",{children:"Terminal"})]}),a.jsx("button",{type:"button",className:"px-2 py-0.5 rounded-lg text-xs text-spur-text-muted hover:text-spur-text cursor-pointer","aria-label":"Close member detail",onClick:t,"data-member-detail-close":!0,children:"close ✕"})]})]}),k&&a.jsxs("div",{className:"flex-1 min-h-[180px] border-b border-spur-border flex flex-col",children:[a.jsxs("div",{className:"px-3 py-1 bg-spur-surface-2 border-b border-spur-border text-[11px] font-mono text-spur-text-muted flex items-center justify-between shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:"stdout / stderr live stream"}),a.jsxs("span",{className:"text-[10px] px-1.5 py-0.2 rounded bg-spur-surface-3 text-spur-text-muted border border-spur-border/70 hidden sm:inline",children:["/api/processes/",e.instanceId,"/stream"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[f?.id&&a.jsxs("span",{className:"text-[10px] text-spur-text-muted hidden md:inline","data-stream-session-id":!0,children:["session: ",a.jsx("code",{className:"text-spur-accent font-mono",children:f.id})]}),a.jsx("span",{className:"text-[10px] text-spur-accent font-semibold",children:"SSE"})]})]}),a.jsx("div",{className:"flex-1 min-h-0",children:a.jsx(IZ,{agentId:e.instanceId,sessionId:f?.id},e.instanceId)})]}),a.jsxs("div",{className:"shrink-0 h-[35%] flex overflow-hidden",children:[a.jsxs("div",{className:"flex-1 overflow-y-auto p-2 border-r border-spur-border","data-member-messages":!0,children:[a.jsx("div",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide mb-1",children:"Messages"}),(b??[]).length===0&&a.jsx("div",{className:"text-xs text-spur-text-muted italic",children:b===null?"Loading…":"No inbox messages."}),(b??[]).slice(0,20).map(K=>a.jsxs("div",{className:"text-xs border-t border-spur-border py-1","data-member-message":K.id,children:[a.jsxs("span",{className:"font-mono text-spur-text-muted",children:[K.fromId??"system"," → ",K.toId]}),a.jsx("span",{className:"ml-1 px-1 rounded bg-spur-surface-3 text-spur-text",children:K.status}),a.jsx("span",{className:"ml-1 font-mono text-spur-text-muted",children:K.createdAt}),a.jsx("p",{className:"text-spur-text mt-0.5 whitespace-pre-wrap break-words",children:K.body})]},K.id))]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2","data-member-activity":!0,children:[a.jsx("div",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide mb-1",children:"Activity"}),(y??[]).length===0&&a.jsx("div",{className:"text-xs text-spur-text-muted italic",children:y===null?"Loading…":"No activity for this member."}),(y??[]).slice(0,20).map(K=>a.jsxs("div",{className:"text-xs border-t border-spur-border py-1","data-member-activity-row":K.eventName,children:[a.jsx("span",{className:"font-mono text-spur-text-muted",children:K.occurredAt})," ",a.jsx("span",{className:"text-spur-text",children:K.eventName})]},K.id))]})]})]})}const lS="spur:detail-width",MZ=()=>`${it()}/processes`;function FZ(e,t){const n=e.map(i=>({key:`sup:${i.agentId}`,label:i.agentId,agentId:i.agentId,pid:i.pid,status:i.status,startedAt:i.startedAt,source:"supervisor",exitCode:i.exitCode,session:i.session??null})),r=new Set(e.map(i=>i.agentId)),s=new Set(e.map(i=>i.pid).filter(i=>i!=null));for(const i of t)i.agentId&&r.has(i.agentId)||i.pid!=null&&s.has(i.pid)||n.push({key:`reg:${i.id}`,label:i.label||i.command,agentId:i.agentId??void 0,pid:i.pid,status:i.status,startedAt:i.startedAt,source:i.source,command:i.command,args:i.args,exitCode:i.exitCode,session:null});return n}function PZ(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;return!0})}function cS({filters:e,onFilters:t,totalCount:n,shownCount:r}){return a.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-2 text-xs","data-processes-filters":!0,children:[a.jsxs("label",{className:"flex items-center gap-1","data-processes-filter-running":!0,children:[a.jsx("input",{type:"checkbox",checked:e.runningOnly,onChange:s=>t({...e,runningOnly:s.target.checked}),"data-processes-filter-running-input":!0}),a.jsx("span",{children:"Running only"})]}),a.jsxs("label",{className:"flex items-center gap-1",children:[a.jsx("span",{children:"Source"}),a.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:[a.jsx("option",{value:"all",children:"all"}),a.jsx("option",{value:"supervisor",children:"supervisor"}),a.jsx("option",{value:"one-shot",children:"one-shot"}),a.jsx("option",{value:"other",children:"other"})]})]}),a.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"}),"data-processes-filter-clear":!0,children:"Clear"}),a.jsxs("span",{className:"text-spur-text-muted","data-processes-filter-count":!0,children:[r,"/",n," shown"]})]})}function BZ({pollMs:e=Kx}){const[t,n]=h.useState(null),[r,s]=h.useState(null),[i,o]=h.useState({runningOnly:!1,source:"all"}),l=h.useRef(!0),[c,u]=h.useState(()=>{const v=typeof window<"u"?Math.min(1728,window.innerWidth*.8):1728;if(typeof window>"u")return v;try{const O=Number.parseFloat(window.localStorage.getItem(lS)??"");if(Number.isFinite(O)&&O>0)return Math.min(O,window.innerWidth*.8)}catch{}return v});h.useEffect(()=>{document.documentElement.style.setProperty("--detail-w",`${c}px`)},[c]);const d=h.useCallback(async v=>{try{const O=await Xe(new Request(MZ(),{signal:v}));if(!O.ok)throw new Error(`processes fetch failed: ${O.status}`);const C=await O.json(),M=Zx(C),B=AZ(C)??[];if(!M)return;l.current&&(n({processes:M,executions:B}),s(null))}catch(O){if(v.aborted)return;l.current&&s(O instanceof Error?O.message:String(O))}},[]);h.useEffect(()=>{l.current=!0;let v=null;const O=()=>{v?.abort(),v=new AbortController,d(v.signal)};O();const C=setInterval(O,e);return()=>{l.current=!1,v?.abort(),clearInterval(C)}},[d,e]);const p=h.useMemo(()=>t?FZ(t.processes,t.executions):[],[t]),f=h.useMemo(()=>PZ(p,i),[p,i]),m=Ms(),[b,x]=h.useState(null),y=h.useRef(null),E=(v,O)=>{O&&(y.current=O),x(v)},A=h.useCallback(()=>{x(null),y.current?.focus()},[]),w=h.useMemo(()=>{if(!b)return null;const v=b.agentId??b.label,O=m.fleet?.members.find(M=>M.instanceId===v)??null,C=t?.processes.find(M=>M.agentId===v);return{instanceId:v,declared:O,observed:{status:b.status==="running"?"running":b.status==="exited"?"exited":"not-started",pid:b.pid,startedAt:b.startedAt,exitCode:b.exitCode??C?.exitCode??null,session:b.session??C?.session??null},isOrchestrator:m.fleet?.orchestrator.instanceId===v,issues:O?[]:["undeclared"]}},[b,m.fleet,t]),N=h.useMemo(()=>{if(!b||b.source==="supervisor")return null;const v=b.key.replace(/^reg:/,"");return t?.executions.find(O=>O.id===v)??null},[b,t]),_=h.useMemo(()=>{if(b)return b.command?`${b.command}${b.args&&b.args.length>0?` ${b.args.join(" ")}`:""}`:`spur agent run ${b.agentId??b.label}`},[b]);if(r&&(!t||p.length===0))return a.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 a.jsx("div",{className:"p-4","data-processes-tab-loading":!0,children:a.jsx(ln,{size:"sm"})});if(p.length===0)return a.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"," ",a.jsx("code",{className:"font-mono",children:"spur agent start"}),"."]});if(f.length===0)return a.jsxs("div",{className:"p-3 overflow-auto h-full","data-processes-tab":!0,"data-processes-tab-filtered-empty":!0,children:[a.jsx(cS,{filters:i,onFilters:o,totalCount:p.length,shownCount:0}),a.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 k=t.processes.length,S=Math.max(0,p.length-k);return a.jsxs("div",{className:"p-3 overflow-auto h-full relative","data-processes-tab":!0,children:[a.jsx(cS,{filters:i,onFilters:o,totalCount:p.length,shownCount:f.length}),a.jsxs("div",{className:"flex items-center gap-2 mb-2 text-xs text-spur-text-muted",children:[a.jsxs("span",{"data-processes-header":!0,children:["Process watch list (",p.length,k>0||S>0?` · ${k} supervised${S>0?` · ${S} other`:""}`:"",")"]}),a.jsx("span",{className:"italic",children:"— ProcessExecutor registry (ts-runtime)"})]}),a.jsxs("table",{className:"table table-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"Agent / Instance"}),a.jsx("th",{children:"Role"}),a.jsx("th",{children:"Stages"}),a.jsx("th",{children:"Executor"}),a.jsx("th",{children:"Session"}),a.jsx("th",{children:"Command"}),a.jsx("th",{children:"PID"}),a.jsx("th",{children:"Status"}),a.jsx("th",{children:"Started"}),a.jsx("th",{children:"Source"})]})}),a.jsx("tbody",{children:f.map(v=>{const O=v.status==="running",C=v.agentId??v.label,M=m.fleet?.members.find(xe=>xe.instanceId===C),B=m.fleet?.orchestrator.instanceId===C,R=M?.role??(v.agentId?"agent":"process"),z=m.fleet?.roles?.find(xe=>xe.name===R),W=z?.stages&&z.stages.length>0?z.stages:m.fleet?.stages?.filter(xe=>xe.role===R).map(xe=>xe.id)??[],F=M?.executor??z?.electedExecutor??(v.source==="supervisor"?"spur":null),J=m.fleet?.executors?.find(xe=>xe.name===F||xe.name===M?.executor),K=J?.agent??M?.executor??(v.source==="supervisor"?"spur":v.command??"cli"),X=M?.model??J?.model??"—",I=J?.tier??z?.tier,V=[`Agent: ${K||"—"}`,`Model: ${X||"—"}`,I?`Tier: ${I}`:""].filter(Boolean).join(`
310
- `),te=v.session??M?.session,L=Xx(te),ye=v.command?`${v.command}${v.args&&v.args.length>0?` ${v.args.join(" ")}`:""}`:`spur agent run ${C}`;return a.jsxs("tr",{"data-processes-row":v.key,"data-g6":"open-member","data-roster-entry":C,tabIndex:0,"aria-haspopup":"dialog",className:"hover:bg-spur-surface-2/40 cursor-pointer transition-colors focus:outline-none focus:bg-spur-surface-2/60",onClick:xe=>E(v,xe.currentTarget),onKeyDown:xe=>{(xe.key==="Enter"||xe.key===" ")&&(xe.preventDefault(),E(v,xe.currentTarget))},children:[a.jsx("td",{children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"font-mono text-xs font-semibold text-spur-text",children:v.label}),B&&a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-spur-accent/20 text-spur-accent tracking-wide uppercase",children:"lead"}),M?.lifecycle?.state==="blocked"&&a.jsx("span",{"data-member-needs-human":C,title:"This member reported blocked — it is waiting on a human (a permission prompt), so the strategy holds its work",className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-spur-warning/15 text-spur-warning tracking-wide uppercase",children:"needs human"})]})}),a.jsx("td",{children:a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[11px] font-mono font-medium bg-spur-accent/15 text-spur-accent",children:R})}),a.jsx("td",{children:W.length>0?a.jsx("div",{className:"flex items-center gap-1 flex-wrap max-w-[200px]",children:W.map(xe=>a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-base-200 text-spur-text-muted border border-spur-border/60",children:xe},xe))}):a.jsx("span",{className:"font-mono text-xs text-spur-text-muted/60",children:"—"})}),a.jsx("td",{children:a.jsx(ur,{position:"top",tip:V,className:"inline-flex! z-30 [&:before]:whitespace-pre-line! [&:before]:text-left! [&:before]:font-mono [&:before]:text-[11px] [&:before]:p-2 [&:before]:rounded-lg [&:before]:shadow-xl after:whitespace-pre-line after:text-left after:font-mono after:text-[11px]",children:a.jsx("span",{className:"font-mono text-xs font-semibold text-spur-text cursor-help hover:text-spur-accent transition-colors",title:V,"data-process-executor":F??"none",children:F??"—"})})}),a.jsx("td",{children:a.jsx("span",{className:"font-mono text-xs text-spur-text-muted",children:L??"—"})}),a.jsx("td",{className:"max-w-[240px]",children:a.jsx("span",{className:"font-mono text-xs text-spur-text-muted truncate block",title:ye,children:ye})}),a.jsx("td",{className:"font-mono text-xs text-spur-text-muted",children:v.pid??"—"}),a.jsx("td",{children:a.jsx(tt,{variant:O?"success":"ghost",size:"xs",children:v.status})}),a.jsx("td",{className:"text-xs text-spur-text-muted whitespace-nowrap",children:new Date(v.startedAt).toLocaleTimeString()}),a.jsx("td",{className:"text-xs text-spur-text-muted","data-process-source":v.source,children:v.source})]},v.key)})})]}),w&&a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button","aria-label":"Close process detail",className:"fixed inset-0 z-50 bg-black/50 border-0 p-0 cursor-default",onClick:A}),a.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Process 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:[a.jsx(ka,{targetVar:"--detail-w",onResizeEnd:v=>{const O=Math.max(576,Math.min(v,window.innerWidth*.8));u(O);try{window.localStorage.setItem(lS,String(O))}catch{}},direction:"horizontal",invert:!0}),a.jsx("div",{className:"flex-1 flex flex-col min-w-0 h-full overflow-hidden",children:a.jsx(jZ,{entry:w,onClose:A,execution:N,fullCommand:_,className:"h-full"})})]})]})]})}const $Z="fleet",Sr=[{id:"fleet",label:"Fleet",component:BZ},{id:"inbox",label:"Inbox",component:gZ},{id:"database",label:"Database",component:lZ}];function UZ(){const e=Ji(),t=mc();return{activeTab:(()=>{const s=e.pathname.split("/"),i=s.indexOf("projects"),o=i>=0?s[i+1]:void 0;return Sr.some(l=>l.id===o)?o:$Z})(),selectTab:s=>{const i=new URLSearchParams(e.search).toString();t(`/board/projects/${s}${i?`?${i}`:""}`,{replace:!0})}}}function zZ(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 xA(){const e=Ms(),{activeTab:t,selectTab:n}=UZ(),s=(Sr.find(l=>l.id===t)??Sr[0])?.component,i=zZ(e),o=l=>{if(l.key!=="ArrowRight"&&l.key!=="ArrowLeft")return;l.preventDefault();const c=Sr.findIndex(p=>p.id===t),u=l.key==="ArrowRight"?1:-1,d=Sr[(c+u+Sr.length)%Sr.length];d&&(l.currentTarget.querySelectorAll('[role="tab"]')[Sr.indexOf(d)]?.focus(),n(d.id))};return a.jsxs("div",{className:"projects flex flex-col h-full gap-4 p-4 max-w-[1600px] mx-auto w-full overflow-hidden","data-projects-shell":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3 shrink-0","data-projects-header":!0,"data-projects-state":i,children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rr,{id:"projects",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Projects"}),a.jsx("p",{className:"text-xs text-base-content/60",children:"Conversation and processes for this project"})]})]}),a.jsx("div",{role:"tablist","aria-label":"Projects tabs",onKeyDown:o,className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:Sr.map(l=>{const c=l.id===t;return a.jsx("button",{type:"button",role:"tab","aria-selected":c,"aria-controls":`projects-tab-panel-${l.id}`,id:`projects-tab-${l.id}`,onClick:()=>n(l.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer ${c?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,"data-projects-tab":l.id,children:l.label},l.id)})})]}),a.jsx("div",{role:"tabpanel",id:`projects-tab-panel-${t}`,"aria-labelledby":`projects-tab-${t}`,className:"flex-1 min-h-0 overflow-hidden",children:s?a.jsx(s,{}):null})]})}const HZ={id:"projects",name:"Projects",icon:"📁",route:"projects",component:xA,sidebarLabel:"Projects",description:"Conversation and processes for this project",order:45},GZ=Object.freeze(Object.defineProperty({__proto__:null,ProjectsShell:xA,module:HZ},Symbol.toStringTag,{value:"Module"}));function Fp(e){const{label:t,hits:n,skip:r}=e;return n===null?r===null?null:a.jsxs("section",{"aria-label":`${t} group`,className:"mb-4 text-sm opacity-70",children:[a.jsx("h3",{className:"font-medium mb-1",children:t}),a.jsxs("p",{children:["skipped: ",r.reason,r.hint!==void 0?` — ${r.hint}`:""]})]}):a.jsxs("section",{"aria-label":`${t} group`,className:"mb-4",children:[a.jsxs("h3",{className:"font-medium mb-1",children:[t," (",n.length,")"]}),n.length===0?a.jsx("p",{className:"text-sm opacity-70",children:"no matches"}):null,a.jsx("ol",{className:"flex flex-col gap-2",children:n.map(s=>a.jsx(WZ,{hit:s},`${s.path}:${s.startLine}`))})]})}function WZ(e){const{hit:t}=e,n=t.startLine===t.endLine?`${t.startLine}`:`${t.startLine}-${t.endLine}`;return a.jsxs("li",{className:"text-sm",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"font-mono",children:[t.path,":",n]}),t.matchedBy.length>1?a.jsx(tt,{variant:"info",children:t.matchedBy.join("+")}):null]}),a.jsx("pre",{className:"font-mono text-xs whitespace-pre-wrap mt-0.5",children:t.snippet})]})}function qZ(e){const{status:t}=e;return t===null?null:a.jsxs("div",{role:"status","aria-label":"search backend status",className:"flex flex-wrap items-center gap-2 text-xs mb-3",children:[a.jsxs(tt,{variant:t.rg.available?"success":"warning",children:["rg ",t.rg.available?t.rg.version??"available":"not installed"]}),a.jsxs(tt,{variant:t.zg.available&&t.zg.index==="ready"?"success":"warning",children:["zg ",t.zg.available?t.zg.version??"available":"not installed"," · index"," ",t.zg.index]}),t.zg.hint!==void 0?a.jsx("span",{className:"opacity-70",children:t.zg.hint}):null]})}const VZ=["auto","exact","fuzzy"],YZ=["all","docs","code"];function KZ(){const[e,t]=h.useState(""),[n,r]=h.useState("auto"),[s,i]=h.useState("all"),[o,l]=h.useState(!1),[c,u]=h.useState(null),[d,p]=h.useState(null),[f,m]=h.useState(null);h.useEffect(()=>{const E=new AbortController;return xt.search.status(void 0,{signal:E.signal}).then(A=>{A?.data&&m(A.data)}).catch(()=>{}),()=>E.abort()},[]);const b=()=>{const E=e.trim();E.length===0||o||(l(!0),u(null),xt.search.query({query:E,mode:n,scope:s,limit:20}).then(A=>{p(A?.data??null)}).catch(A=>{u(A instanceof Error?A.message:"search failed")}).finally(()=>{l(!1)}))},x=d?.skipped.find(E=>E.route==="exact")??null,y=d?.skipped.find(E=>E.route==="fuzzy")??null;return a.jsxs("div",{className:"p-4 max-w-4xl",children:[a.jsx("h2",{className:"text-lg font-medium mb-2",children:"Search"}),a.jsx("p",{className:"text-sm opacity-70 mb-3",children:"Exact and semantic search over docs and code"}),a.jsx(qZ,{status:f}),a.jsxs("form",{className:"flex items-center gap-2 mb-4",onSubmit:E=>{E.preventDefault(),b()},children:[a.jsx("label",{className:"sr-only",htmlFor:"search-query",children:"Search query"}),a.jsx(Vn,{id:"search-query",type:"text",placeholder:"Search docs and code…",value:e,onChange:E=>t(E.target.value),className:"flex-1"}),a.jsx("div",{role:"radiogroup","aria-label":"Search mode",className:"flex items-center gap-1",children:VZ.map(E=>a.jsx(Ie,{type:"button","aria-pressed":n===E,variant:n===E?"primary":"outline",onClick:()=>r(E),children:E},E))}),a.jsx("label",{className:"sr-only",htmlFor:"search-scope",children:"Search scope"}),a.jsx(qr,{id:"search-scope",value:s,onChange:E=>i(E.target.value),children:YZ.map(E=>a.jsx("option",{value:E,children:E},E))}),a.jsx(Ie,{type:"submit",variant:"primary",disabled:o||e.trim().length===0,children:o?"Searching…":"Search"})]}),c!==null?a.jsx("p",{className:"text-sm text-error mb-3",children:c}):null,o&&d===null?a.jsx(ln,{}):null,d!==null?a.jsxs(a.Fragment,{children:[a.jsx(Fp,{label:"Exact",hits:d.groups.exact,skip:x}),a.jsx(Fp,{label:"Fuzzy",hits:d.groups.fuzzy,skip:y}),d.groups.exact!==null&&d.groups.fuzzy!==null&&d.groups.exact.length===0&&d.groups.fuzzy.length===0?a.jsx("p",{className:"text-sm opacity-70",children:"no matches"}):null]}):null]})}const ZZ={id:"search",name:"Search",icon:"🔎",route:"search",component:KZ,sidebarLabel:"Search",description:"Exact and semantic search over docs and code",order:15},XZ=Object.freeze(Object.defineProperty({__proto__:null,HitGroup:Fp,module:ZZ},Symbol.toStringTag,{value:"Module"})),QZ=()=>`${it()}/project/fleet`,JZ=()=>`${it()}/processes`,eX=()=>`${it()}/project/executors/availability`,uS=[{name:"scribe",tier:"cheap",stages:["changelog"],isCustom:!1},{name:"coder",tier:"standard",stages:["implement","test","wrap"],isCustom:!1},{name:"reviewer",tier:"capable-1",stages:["verify","review","dogfood"],isCustom:!1},{name:"planner",tier:"capable-2",stages:["plan","refine","brainstorm"],isCustom:!1}],tX=[{id:"plan",alias:"/sp:dev-plan",description:"Intake and decompose feature into spec and tasks",role:"planner",tier:"capable-2",skill:"sp:super-planner"},{id:"refine",alias:"/sp:dev-refine",description:"Clarify task ambiguity and acceptance criteria",role:"planner",tier:"capable-2",skill:"sp:super-planner"},{id:"brainstorm",alias:"/sp:brainstorm",description:"Structured ideation with trade-offs and options",role:"planner",tier:"capable-2",skill:"sp:brainstorm"},{id:"implement",alias:"/sp:dev-run",description:"Transform requirements into production code",role:"coder",tier:"standard",skill:"sp:super-coder"},{id:"test",alias:"/sp:dev-unit",description:"Generate and extend unit and regression test suites",role:"coder",tier:"standard",skill:"sp:code-testing"},{id:"review",alias:"/sp:dev-review",description:"Multi-dimensional SECUA code review",role:"reviewer",tier:"capable-1",skill:"sp:super-reviewer"},{id:"verify",alias:"/sp:dev-verify",description:"Traceability and acceptance criteria verification",role:"reviewer",tier:"capable-1",skill:"sp:code-verification"},{id:"dogfood",alias:"/sp:dev-dogfood",description:"End-to-end dogfood verification with retry ledger",role:"reviewer",tier:"capable-1",skill:"sp:dogfood-testing"},{id:"wrap",alias:"/sp:dev-wrap",description:"Capture learnings, metrics, and documentation sync",role:"coder",tier:"standard",skill:"sp:doc-evolve"},{id:"changelog",alias:"/sp:dev-changelog",description:"Generate conventional release notes and summaries",role:"scribe",tier:"cheap",skill:"sp:dev-changelog"}];function dS(e){const t=new Map(e.map(n=>[n.name,n]));return tX.map(n=>{const r=t.get(n.role);return{...n,tier:r?.tier??n.tier,electedExecutor:r?.electedExecutor??null,candidateExecutors:r?.candidateExecutors??[]}})}function nX(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 _d={"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 rX(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 Qx(e){switch(e){case"cheap":return"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border border-emerald-500/20";case"standard":return"bg-blue-500/10 text-blue-700 dark:text-blue-400 border border-blue-500/20";case"capable-1":return"bg-purple-500/10 text-purple-700 dark:text-purple-400 border border-purple-500/20";case"capable-2":return"bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 border border-indigo-500/20";case"capable-3":return"bg-amber-500/10 text-amber-800 dark:text-amber-400 border border-amber-500/20";default:return"bg-spur-surface-3 text-spur-text-muted border border-spur-border"}}const pS={cheap:1,standard:2,"capable-1":3,"capable-2":4,"capable-3":5};function yA({pollMs:e=Kx}){const t=Ms(),[n,r]=h.useState(null),[s,i]=h.useState(uS),[o,l]=h.useState(()=>dS(uS)),[c,u]=h.useState([]),[d,p]=h.useState(null),[f,m]=h.useState(!1),[b,x]=h.useState(!1),[y,E]=h.useState(!1),[A,w]=h.useState("all"),[N,_]=h.useState(""),[k,S]=h.useState(""),[v,O]=h.useState(null),C=h.useRef(async()=>{});h.useEffect(()=>{let R=!1,z=null;const W=async()=>{if(z!==null)return;const J=new AbortController;z=J;const K=J.signal;try{const[X,I]=await Promise.all([Xe(new Request(QZ(),{signal:K})),Xe(new Request(JZ(),{signal:K})).catch(()=>null)]);if(R)return;if(!X.ok)throw new Error(`fleet feed HTTP ${X.status}`);const V=await X.json();if(R||!nX(V))return;const te=I?.ok?Zx(await I.json().catch(()=>null)):null;if(R)return;x(te===null),te!==null&&r(DZ(V,te)),V.roles&&V.roles.length>0&&i(V.roles),V.stages&&V.stages.length>0?l(V.stages):V.roles&&V.roles.length>0&&l(dS(V.roles)),u(V.executors??[]),p(V),E(V.orchestrator.state==="bound-offline"),m(!1)}catch{R||m(!0)}finally{z===J&&(z=null)}};C.current=W,W();const F=setInterval(()=>{W()},e);return()=>{R=!0,clearInterval(F),z?.abort()}},[e]);const M=h.useMemo(()=>{if(!N.trim())return c;const R=N.toLowerCase();return c.filter(z=>z.name.toLowerCase().includes(R)||z.agent.toLowerCase().includes(R)||!!z.model?.toLowerCase().includes(R)||z.tier.toLowerCase().includes(R))},[c,N]),B=h.useMemo(()=>{if(!k.trim())return o;const R=k.toLowerCase();return o.filter(z=>z.id.toLowerCase().includes(R)||z.role.toLowerCase().includes(R)||z.tier.toLowerCase().includes(R)||!!z.alias?.toLowerCase().includes(R)||!!z.skill?.toLowerCase().includes(R)||z.description.toLowerCase().includes(R))},[o,k]);return a.jsxs("div",{className:"flex flex-col h-full overflow-hidden bg-spur-bg","data-agents-view":!0,children:[a.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-6",children:[d===null&&!f&&a.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-roster-loading":!0,children:"Loading agent configuration…"}),f&&d===null&&a.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-roster-fetch-failed":!0,role:"alert",children:"Agent configuration unavailable — the fleet feed could not be read."}),d!==null&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-spur-border/50",children:[a.jsx("div",{className:"flex items-center gap-1.5 p-1 bg-spur-surface-2 rounded-xl border border-spur-border",children:[{id:"all",label:"All"},{id:"roles",label:"Roles",count:s.length},{id:"stages",label:"Stages",count:o.length},{id:"executors",label:"Executors",count:c.length},{id:"fleet",label:"Fleet",count:n?.length??0}].map(R=>a.jsxs("button",{type:"button",onClick:()=>w(R.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer flex items-center gap-1.5 ${A===R.id?"bg-spur-accent text-white shadow-sm":"text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-3"}`,"data-section-filter":R.id,children:[a.jsx("span",{children:R.label}),"count"in R&&a.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-mono transition-colors ${A===R.id?"bg-white/20 text-white":"bg-spur-surface-3 text-spur-text-muted"}`,children:R.count})]},R.id))}),A==="stages"&&o.length>0&&a.jsx("input",{type:"text",placeholder:"Filter stages by id, role, alias...",value:k,onChange:R=>S(R.target.value),className:"px-3 py-1.5 bg-spur-surface border border-spur-border rounded-lg text-xs text-spur-text placeholder:text-spur-text-muted/60 focus:outline-none focus:ring-1 focus:ring-spur-accent min-w-[240px]","data-stage-filter":!0}),A==="executors"&&c.length>0&&a.jsx("input",{type:"text",placeholder:"Filter executors by name, agent, model...",value:N,onChange:R=>_(R.target.value),className:"px-3 py-1.5 bg-spur-surface border border-spur-border rounded-lg text-xs text-spur-text placeholder:text-spur-text-muted/60 focus:outline-none focus:ring-1 focus:ring-spur-accent min-w-[240px]"})]}),(A==="all"||A==="roles")&&a.jsxs("section",{className:"space-y-3","data-roles-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Agent Roles"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"agent.roles"})]}),a.jsx("span",{className:"text-xs text-spur-text-muted",children:"Routing roles mapped to capability tiers and folded stages"})]}),a.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-roles-grid":!0,children:s.map(R=>a.jsx(aX,{role:R,executors:c},R.name))})]}),A==="all"&&a.jsx("hr",{className:"border-0 border-t border-spur-border/50 my-1"}),(A==="all"||A==="stages")&&a.jsxs("section",{className:"space-y-3","data-stages-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Pipeline Stages"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"pipeline.stages"}),o.length>0&&a.jsxs("span",{className:"text-xs text-spur-text-muted font-mono",children:["(",o.length," defined)"]})]}),a.jsx("span",{className:"text-xs text-spur-text-muted",children:"Pipeline execution stages from the perspective of agent executors and capability tiers"})]}),B.length===0?a.jsx("div",{className:"p-4 rounded-xl bg-spur-surface border border-spur-border text-xs text-spur-text-muted",children:o.length===0?"No pipeline stages defined.":"No stages match filter."}):a.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3","data-stages-grid":!0,children:B.map(R=>a.jsx(oX,{stage:R,executors:c},R.id))})]}),A==="all"&&a.jsx("hr",{className:"border-0 border-t border-spur-border/50 my-1"}),(A==="all"||A==="executors")&&a.jsxs("section",{className:"space-y-3","data-executors-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Agent Executors"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"agent.executors"}),c.length>0&&a.jsxs("span",{className:"text-xs text-spur-text-muted font-mono",children:["(",c.filter(R=>!R.disabled).length," active,"," ",c.filter(R=>R.disabled).length," disabled)"]})]}),a.jsx("span",{className:"text-xs text-spur-text-muted",children:"Execution profiles pairing CLI runtimes with models and capability tiers"})]}),M.length===0?a.jsx("div",{className:"p-4 rounded-xl bg-spur-surface border border-spur-border text-xs text-spur-text-muted",children:c.length===0?"No executor profiles defined in config.":"No executors match filter."}):a.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3","data-executors-grid":!0,children:M.map(R=>a.jsx(lX,{executor:R,onToggle:z=>O({executor:z,targetDisabled:!z.disabled})},R.name))})]}),A==="all"&&a.jsx("hr",{className:"border-0 border-t border-spur-border/50 my-1"}),(A==="all"||A==="fleet")&&a.jsxs("section",{className:"space-y-3","data-fleet-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Agent Fleet"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"agent.fleet"})]}),d&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[a.jsx("span",{className:`px-2 py-0.5 rounded-md font-medium text-[11px] ${d.enabled?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-spur-surface-2 border border-spur-border text-spur-text-muted"}`,children:d.enabled?"Fleet Enabled":"Fleet Disabled"}),d.strategy&&a.jsxs("span",{className:"px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-text text-[11px]",children:["strategy:"," ",a.jsx("strong",{className:"font-mono text-spur-accent",children:d.strategy.name})]}),a.jsxs("span",{className:"px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-text text-[11px]",children:["orchestrator:"," ",a.jsx("span",{className:"font-mono text-spur-text-muted",children:d.orchestrator.state})]})]})]}),n===null&&a.jsx("div",{className:"p-4 text-sm text-spur-text-muted bg-spur-surface border border-spur-border rounded-xl","data-roster-fetch-failed":b?"true":void 0,role:b?"alert":void 0,children:b?"Fleet roster unavailable — the process feed could not be read.":"Loading fleet roster…"}),n?.length===0&&a.jsxs("div",{className:"p-4 text-sm text-spur-text-muted italic bg-spur-surface border border-spur-border rounded-xl","data-roster-empty":!0,children:["No agents for this project — declare members under"," ",a.jsx("code",{className:"font-mono text-spur-accent",children:"agent.fleet"})," in"," ",a.jsx("code",{className:"font-mono text-spur-accent",children:`${t.path??"this project"}/.spur/config.yaml`}),"."]}),n!==null&&n.length>0&&a.jsx("div",{className:"grid gap-2 md:grid-cols-2 xl:grid-cols-3","data-roster-grid":!0,children:n.map(R=>a.jsx(cX,{entry:R,orchestratorOffline:y},R.instanceId))})]})]})]}),v!==null&&a.jsx(uX,{executor:v.executor,targetDisabled:v.targetDisabled,onClose:()=>O(null),onSuccess:()=>{const R=v;O(null),R&&u(z=>z.map(W=>W.name===R.executor.name?{...W,disabled:R.targetDisabled}:W)),C.current?.()}})]})}function EA({tier:e,electedExecutor:t,candidateExecutors:n,executors:r}){const s=e||"standard",i=r.filter(f=>(f.tier??"standard")===s),o=i.length>0?i:r.filter(f=>{const m=pS[s]??0;return(pS[f.tier??"standard"]??0)>=m}),l=t??o.find(f=>!f.disabled&&f.usable!==!1)?.name,c=l?o.find(f=>f.name===l)??r.find(f=>f.name===l):void 0,u=o.filter(f=>f.name!==l&&!f.disabled),d=o.filter(f=>f.name!==l&&f.disabled),p=[];c&&p.push({name:c.name,isDefault:!0,disabled:c.disabled,model:c.model,agent:c.agent});for(const f of u)p.push({name:f.name,isDefault:!1,disabled:!1,model:f.model,agent:f.agent});for(const f of d)p.push({name:f.name,isDefault:!1,disabled:!0,model:f.model,agent:f.agent});return p.length===0&&n&&n.length>0?n.map((f,m)=>{const b=r.find(x=>x.name===f);return{name:f,isDefault:f===t||m===0,disabled:b?.disabled??!1,agent:b?.agent,model:b?.model}}):p}function fS(e){return[`Agent: ${e.agent||"—"}`,`Model: ${e.model||"default"}`].join(`
310
+ `),te=v.session??M?.session,L=Xx(te),ye=v.command?`${v.command}${v.args&&v.args.length>0?` ${v.args.join(" ")}`:""}`:`spur agent run ${C}`;return a.jsxs("tr",{"data-processes-row":v.key,"data-g6":"open-member","data-roster-entry":C,tabIndex:0,"aria-haspopup":"dialog",className:"hover:bg-spur-surface-2/40 cursor-pointer transition-colors focus:outline-none focus:bg-spur-surface-2/60",onClick:xe=>E(v,xe.currentTarget),onKeyDown:xe=>{(xe.key==="Enter"||xe.key===" ")&&(xe.preventDefault(),E(v,xe.currentTarget))},children:[a.jsx("td",{children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"font-mono text-xs font-semibold text-spur-text",children:v.label}),B&&a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-spur-accent/20 text-spur-accent tracking-wide uppercase",children:"lead"}),M?.lifecycle?.state==="blocked"&&a.jsx("span",{"data-member-needs-human":C,title:"This member reported blocked — it is waiting on a human (a permission prompt), so the strategy holds its work",className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-spur-warning/15 text-spur-warning tracking-wide uppercase",children:"needs human"})]})}),a.jsx("td",{children:a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[11px] font-mono font-medium bg-spur-accent/15 text-spur-accent",children:R})}),a.jsx("td",{children:W.length>0?a.jsx("div",{className:"flex items-center gap-1 flex-wrap max-w-[200px]",children:W.map(xe=>a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-base-200 text-spur-text-muted border border-spur-border/60",children:xe},xe))}):a.jsx("span",{className:"font-mono text-xs text-spur-text-muted/60",children:"—"})}),a.jsx("td",{children:a.jsx(ur,{position:"top",tip:V,className:"inline-flex! z-30 [&:before]:whitespace-pre-line! [&:before]:text-left! [&:before]:font-mono [&:before]:text-[11px] [&:before]:p-2 [&:before]:rounded-lg [&:before]:shadow-xl after:whitespace-pre-line after:text-left after:font-mono after:text-[11px]",children:a.jsx("span",{className:"font-mono text-xs font-semibold text-spur-text cursor-help hover:text-spur-accent transition-colors",title:V,"data-process-executor":F??"none",children:F??"—"})})}),a.jsx("td",{children:a.jsx("span",{className:"font-mono text-xs text-spur-text-muted",children:L??"—"})}),a.jsx("td",{className:"max-w-[240px]",children:a.jsx("span",{className:"font-mono text-xs text-spur-text-muted truncate block",title:ye,children:ye})}),a.jsx("td",{className:"font-mono text-xs text-spur-text-muted",children:v.pid??"—"}),a.jsx("td",{children:a.jsx(tt,{variant:O?"success":"ghost",size:"xs",children:v.status})}),a.jsx("td",{className:"text-xs text-spur-text-muted whitespace-nowrap",children:new Date(v.startedAt).toLocaleTimeString()}),a.jsx("td",{className:"text-xs text-spur-text-muted","data-process-source":v.source,children:v.source})]},v.key)})})]}),w&&a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button","aria-label":"Close process detail",className:"fixed inset-0 z-50 bg-black/50 border-0 p-0 cursor-default",onClick:A}),a.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Process 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:[a.jsx(ka,{targetVar:"--detail-w",onResizeEnd:v=>{const O=Math.max(576,Math.min(v,window.innerWidth*.8));u(O);try{window.localStorage.setItem(lS,String(O))}catch{}},direction:"horizontal",invert:!0}),a.jsx("div",{className:"flex-1 flex flex-col min-w-0 h-full overflow-hidden",children:a.jsx(jZ,{entry:w,onClose:A,execution:N,fullCommand:_,className:"h-full"})})]})]})]})}const $Z="fleet",Sr=[{id:"fleet",label:"Fleet",component:BZ},{id:"inbox",label:"Inbox",component:gZ},{id:"database",label:"Database",component:lZ}];function UZ(){const e=Ji(),t=mc();return{activeTab:(()=>{const s=e.pathname.split("/"),i=s.indexOf("projects"),o=i>=0?s[i+1]:void 0;return Sr.some(l=>l.id===o)?o:$Z})(),selectTab:s=>{const i=new URLSearchParams(e.search).toString();t(`/board/projects/${s}${i?`?${i}`:""}`,{replace:!0})}}}function zZ(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 xA(){const e=Ms(),{activeTab:t,selectTab:n}=UZ(),s=(Sr.find(l=>l.id===t)??Sr[0])?.component,i=zZ(e),o=l=>{if(l.key!=="ArrowRight"&&l.key!=="ArrowLeft")return;l.preventDefault();const c=Sr.findIndex(p=>p.id===t),u=l.key==="ArrowRight"?1:-1,d=Sr[(c+u+Sr.length)%Sr.length];d&&(l.currentTarget.querySelectorAll('[role="tab"]')[Sr.indexOf(d)]?.focus(),n(d.id))};return a.jsxs("div",{className:"projects flex flex-col h-full gap-4 p-4 max-w-[1600px] mx-auto w-full overflow-hidden","data-projects-shell":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-b border-base-content/10 pb-3 shrink-0","data-projects-header":!0,"data-projects-state":i,children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Rr,{id:"projects",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Projects"}),a.jsx("p",{className:"text-xs text-base-content/60",children:"Conversation and processes for this project"})]})]}),a.jsx("div",{role:"tablist","aria-label":"Projects tabs",onKeyDown:o,className:"flex items-center gap-1 bg-base-300 p-1 rounded-xl",children:Sr.map(l=>{const c=l.id===t;return a.jsx("button",{type:"button",role:"tab","aria-selected":c,"aria-controls":`projects-tab-panel-${l.id}`,id:`projects-tab-${l.id}`,onClick:()=>n(l.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer ${c?"bg-primary text-primary-content font-bold shadow-sm":"text-base-content/70 hover:bg-base-content/10"}`,"data-projects-tab":l.id,children:l.label},l.id)})})]}),a.jsx("div",{role:"tabpanel",id:`projects-tab-panel-${t}`,"aria-labelledby":`projects-tab-${t}`,className:"flex-1 min-h-0 overflow-hidden",children:s?a.jsx(s,{}):null})]})}const HZ={id:"projects",name:"Projects",icon:"📁",route:"projects",component:xA,sidebarLabel:"Projects",description:"Conversation and processes for this project",order:45},GZ=Object.freeze(Object.defineProperty({__proto__:null,ProjectsShell:xA,module:HZ},Symbol.toStringTag,{value:"Module"}));function Fp(e){const{label:t,hits:n,skip:r}=e;return n===null?r===null?null:a.jsxs("section",{"aria-label":`${t} group`,className:"mb-4 text-sm opacity-70",children:[a.jsx("h3",{className:"font-medium mb-1",children:t}),a.jsxs("p",{children:["skipped: ",r.reason,r.hint!==void 0?` — ${r.hint}`:""]})]}):a.jsxs("section",{"aria-label":`${t} group`,className:"mb-4",children:[a.jsxs("h3",{className:"font-medium mb-1",children:[t," (",n.length,")"]}),n.length===0?a.jsx("p",{className:"text-sm opacity-70",children:"no matches"}):null,a.jsx("ol",{className:"flex flex-col gap-2",children:n.map(s=>a.jsx(WZ,{hit:s},`${s.path}:${s.startLine}`))})]})}function WZ(e){const{hit:t}=e,n=t.startLine===t.endLine?`${t.startLine}`:`${t.startLine}-${t.endLine}`;return a.jsxs("li",{className:"text-sm",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"font-mono",children:[t.path,":",n]}),t.matchedBy.length>1?a.jsx(tt,{variant:"info",children:t.matchedBy.join("+")}):null]}),a.jsx("pre",{className:"font-mono text-xs whitespace-pre-wrap mt-0.5",children:t.snippet})]})}function qZ(e){const{status:t}=e;return t===null?null:a.jsxs("div",{role:"status","aria-label":"search backend status",className:"flex flex-wrap items-center gap-2 text-xs mb-3",children:[a.jsxs(tt,{variant:t.rg.available?"success":"warning",children:["rg ",t.rg.available?t.rg.version??"available":"not installed"]}),a.jsxs(tt,{variant:t.zg.available&&t.zg.index==="ready"?"success":"warning",children:["zg ",t.zg.available?t.zg.version??"available":"not installed"," · index"," ",t.zg.index]}),t.zg.hint!==void 0?a.jsx("span",{className:"opacity-70",children:t.zg.hint}):null]})}const VZ=["auto","exact","fuzzy"],YZ=["all","docs","code"];function KZ(){const[e,t]=h.useState(""),[n,r]=h.useState("auto"),[s,i]=h.useState("all"),[o,l]=h.useState(!1),[c,u]=h.useState(null),[d,p]=h.useState(null),[f,m]=h.useState(null);h.useEffect(()=>{const E=new AbortController;return xt.search.status(void 0,{signal:E.signal}).then(A=>{A?.data&&m(A.data)}).catch(()=>{}),()=>E.abort()},[]);const b=()=>{const E=e.trim();E.length===0||o||(l(!0),u(null),xt.search.query({query:E,mode:n,scope:s,limit:20}).then(A=>{p(A?.data??null)}).catch(A=>{u(A instanceof Error?A.message:"search failed")}).finally(()=>{l(!1)}))},x=d?.skipped.find(E=>E.route==="exact")??null,y=d?.skipped.find(E=>E.route==="fuzzy")??null;return a.jsxs("div",{className:"p-4 max-w-4xl",children:[a.jsx("h2",{className:"text-lg font-medium mb-2",children:"Search"}),a.jsx("p",{className:"text-sm opacity-70 mb-3",children:"Exact and semantic search over docs and code"}),a.jsx(qZ,{status:f}),a.jsxs("form",{className:"flex items-center gap-2 mb-4",onSubmit:E=>{E.preventDefault(),b()},children:[a.jsx("label",{className:"sr-only",htmlFor:"search-query",children:"Search query"}),a.jsx(Vn,{id:"search-query",type:"text",placeholder:"Search docs and code…",value:e,onChange:E=>t(E.target.value),className:"flex-1"}),a.jsx("div",{role:"radiogroup","aria-label":"Search mode",className:"flex items-center gap-1",children:VZ.map(E=>a.jsx(Ie,{type:"button","aria-pressed":n===E,variant:n===E?"primary":"outline",onClick:()=>r(E),children:E},E))}),a.jsx("label",{className:"sr-only",htmlFor:"search-scope",children:"Search scope"}),a.jsx(qr,{id:"search-scope",value:s,onChange:E=>i(E.target.value),children:YZ.map(E=>a.jsx("option",{value:E,children:E},E))}),a.jsx(Ie,{type:"submit",variant:"primary",disabled:o||e.trim().length===0,children:o?"Searching…":"Search"})]}),c!==null?a.jsx("p",{className:"text-sm text-error mb-3",children:c}):null,o&&d===null?a.jsx(ln,{}):null,d!==null?a.jsxs(a.Fragment,{children:[a.jsx(Fp,{label:"Exact",hits:d.groups.exact,skip:x}),a.jsx(Fp,{label:"Fuzzy",hits:d.groups.fuzzy,skip:y}),d.groups.exact!==null&&d.groups.fuzzy!==null&&d.groups.exact.length===0&&d.groups.fuzzy.length===0?a.jsx("p",{className:"text-sm opacity-70",children:"no matches"}):null]}):null]})}const ZZ={id:"search",name:"Search",icon:"🔎",route:"search",component:KZ,sidebarLabel:"Search",description:"Exact and semantic search over docs and code",order:15},XZ=Object.freeze(Object.defineProperty({__proto__:null,HitGroup:Fp,module:ZZ},Symbol.toStringTag,{value:"Module"})),QZ=()=>`${it()}/project/fleet`,JZ=()=>`${it()}/processes`,eX=()=>`${it()}/project/executors/availability`,uS=[{name:"scribe",tier:"cheap",stages:["changelog"],isCustom:!1},{name:"coder",tier:"standard",stages:["implement","test","wrap"],isCustom:!1},{name:"reviewer",tier:"capable-1",stages:["verify","review","dogfood"],isCustom:!1},{name:"planner",tier:"capable-2",stages:["plan","refine","brainstorm"],isCustom:!1}],tX=[{id:"plan",alias:"/sp:dev-plan",description:"Intake and decompose feature into spec and tasks",role:"planner",tier:"capable-2",skill:"sp:spur-dev"},{id:"refine",alias:"/sp:dev-refine",description:"Clarify task ambiguity and acceptance criteria",role:"planner",tier:"capable-2",skill:"sp:spur-dev"},{id:"brainstorm",alias:"/sp:dev-brainstorm",description:"Structured ideation with trade-offs and options",role:"planner",tier:"capable-2",skill:"sp:brainstorm"},{id:"implement",alias:"/sp:dev-run",description:"Transform requirements into production code",role:"coder",tier:"standard",skill:"sp:code-implementation"},{id:"test",alias:"/sp:dev-unit",description:"Generate and extend unit and regression test suites",role:"coder",tier:"standard",skill:"sp:code-testing"},{id:"review",alias:"/sp:dev-review",description:"Multi-dimensional SECUA code review",role:"reviewer",tier:"capable-1",skill:"sp:code-verification"},{id:"verify",alias:"/sp:dev-verify",description:"Traceability and acceptance criteria verification",role:"reviewer",tier:"capable-1",skill:"sp:code-verification"},{id:"dogfood",alias:"/sp:dev-dogfood",description:"End-to-end dogfood verification with retry ledger",role:"reviewer",tier:"capable-1",skill:"sp:dogfood-testing"},{id:"wrap",alias:"/sp:dev-wrap",description:"Capture learnings, metrics, and documentation sync",role:"coder",tier:"standard",skill:"sp:spur-dev"},{id:"changelog",alias:"/sp:dev-changelog",description:"Generate conventional release notes and summaries",role:"scribe",tier:"cheap",skill:"inline"}];function dS(e){const t=new Map(e.map(n=>[n.name,n]));return tX.map(n=>{const r=t.get(n.role);return{...n,tier:r?.tier??n.tier,electedExecutor:r?.electedExecutor??null,candidateExecutors:r?.candidateExecutors??[]}})}function nX(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 _d={"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 rX(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 Qx(e){switch(e){case"cheap":return"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 border border-emerald-500/20";case"standard":return"bg-blue-500/10 text-blue-700 dark:text-blue-400 border border-blue-500/20";case"capable-1":return"bg-purple-500/10 text-purple-700 dark:text-purple-400 border border-purple-500/20";case"capable-2":return"bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 border border-indigo-500/20";case"capable-3":return"bg-amber-500/10 text-amber-800 dark:text-amber-400 border border-amber-500/20";default:return"bg-spur-surface-3 text-spur-text-muted border border-spur-border"}}const pS={cheap:1,standard:2,"capable-1":3,"capable-2":4,"capable-3":5};function yA({pollMs:e=Kx}){const t=Ms(),[n,r]=h.useState(null),[s,i]=h.useState(uS),[o,l]=h.useState(()=>dS(uS)),[c,u]=h.useState([]),[d,p]=h.useState(null),[f,m]=h.useState(!1),[b,x]=h.useState(!1),[y,E]=h.useState(!1),[A,w]=h.useState("all"),[N,_]=h.useState(""),[k,S]=h.useState(""),[v,O]=h.useState(null),C=h.useRef(async()=>{});h.useEffect(()=>{let R=!1,z=null;const W=async()=>{if(z!==null)return;const J=new AbortController;z=J;const K=J.signal;try{const[X,I]=await Promise.all([Xe(new Request(QZ(),{signal:K})),Xe(new Request(JZ(),{signal:K})).catch(()=>null)]);if(R)return;if(!X.ok)throw new Error(`fleet feed HTTP ${X.status}`);const V=await X.json();if(R||!nX(V))return;const te=I?.ok?Zx(await I.json().catch(()=>null)):null;if(R)return;x(te===null),te!==null&&r(DZ(V,te)),V.roles&&V.roles.length>0&&i(V.roles),V.stages&&V.stages.length>0?l(V.stages):V.roles&&V.roles.length>0&&l(dS(V.roles)),u(V.executors??[]),p(V),E(V.orchestrator.state==="bound-offline"),m(!1)}catch{R||m(!0)}finally{z===J&&(z=null)}};C.current=W,W();const F=setInterval(()=>{W()},e);return()=>{R=!0,clearInterval(F),z?.abort()}},[e]);const M=h.useMemo(()=>{if(!N.trim())return c;const R=N.toLowerCase();return c.filter(z=>z.name.toLowerCase().includes(R)||z.agent.toLowerCase().includes(R)||!!z.model?.toLowerCase().includes(R)||z.tier.toLowerCase().includes(R))},[c,N]),B=h.useMemo(()=>{if(!k.trim())return o;const R=k.toLowerCase();return o.filter(z=>z.id.toLowerCase().includes(R)||z.role.toLowerCase().includes(R)||z.tier.toLowerCase().includes(R)||!!z.alias?.toLowerCase().includes(R)||!!z.skill?.toLowerCase().includes(R)||z.description.toLowerCase().includes(R))},[o,k]);return a.jsxs("div",{className:"flex flex-col h-full overflow-hidden bg-spur-bg","data-agents-view":!0,children:[a.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-6",children:[d===null&&!f&&a.jsx("div",{className:"p-4 text-sm text-spur-text-muted italic","data-roster-loading":!0,children:"Loading agent configuration…"}),f&&d===null&&a.jsx("div",{className:"p-4 text-sm text-spur-text-muted","data-roster-fetch-failed":!0,role:"alert",children:"Agent configuration unavailable — the fleet feed could not be read."}),d!==null&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pb-3 border-b border-spur-border/50",children:[a.jsx("div",{className:"flex items-center gap-1.5 p-1 bg-spur-surface-2 rounded-xl border border-spur-border",children:[{id:"all",label:"All"},{id:"roles",label:"Roles",count:s.length},{id:"stages",label:"Stages",count:o.length},{id:"executors",label:"Executors",count:c.length},{id:"fleet",label:"Fleet",count:n?.length??0}].map(R=>a.jsxs("button",{type:"button",onClick:()=>w(R.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer flex items-center gap-1.5 ${A===R.id?"bg-spur-accent text-white shadow-sm":"text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-3"}`,"data-section-filter":R.id,children:[a.jsx("span",{children:R.label}),"count"in R&&a.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] font-mono transition-colors ${A===R.id?"bg-white/20 text-white":"bg-spur-surface-3 text-spur-text-muted"}`,children:R.count})]},R.id))}),A==="stages"&&o.length>0&&a.jsx("input",{type:"text",placeholder:"Filter stages by id, role, alias...",value:k,onChange:R=>S(R.target.value),className:"px-3 py-1.5 bg-spur-surface border border-spur-border rounded-lg text-xs text-spur-text placeholder:text-spur-text-muted/60 focus:outline-none focus:ring-1 focus:ring-spur-accent min-w-[240px]","data-stage-filter":!0}),A==="executors"&&c.length>0&&a.jsx("input",{type:"text",placeholder:"Filter executors by name, agent, model...",value:N,onChange:R=>_(R.target.value),className:"px-3 py-1.5 bg-spur-surface border border-spur-border rounded-lg text-xs text-spur-text placeholder:text-spur-text-muted/60 focus:outline-none focus:ring-1 focus:ring-spur-accent min-w-[240px]"})]}),(A==="all"||A==="roles")&&a.jsxs("section",{className:"space-y-3","data-roles-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Agent Roles"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"agent.roles"})]}),a.jsx("span",{className:"text-xs text-spur-text-muted",children:"Routing roles mapped to capability tiers and folded stages"})]}),a.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-roles-grid":!0,children:s.map(R=>a.jsx(aX,{role:R,executors:c},R.name))})]}),A==="all"&&a.jsx("hr",{className:"border-0 border-t border-spur-border/50 my-1"}),(A==="all"||A==="stages")&&a.jsxs("section",{className:"space-y-3","data-stages-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Pipeline Stages"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"pipeline.stages"}),o.length>0&&a.jsxs("span",{className:"text-xs text-spur-text-muted font-mono",children:["(",o.length," defined)"]})]}),a.jsx("span",{className:"text-xs text-spur-text-muted",children:"Pipeline execution stages from the perspective of agent executors and capability tiers"})]}),B.length===0?a.jsx("div",{className:"p-4 rounded-xl bg-spur-surface border border-spur-border text-xs text-spur-text-muted",children:o.length===0?"No pipeline stages defined.":"No stages match filter."}):a.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3","data-stages-grid":!0,children:B.map(R=>a.jsx(oX,{stage:R,executors:c},R.id))})]}),A==="all"&&a.jsx("hr",{className:"border-0 border-t border-spur-border/50 my-1"}),(A==="all"||A==="executors")&&a.jsxs("section",{className:"space-y-3","data-executors-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Agent Executors"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"agent.executors"}),c.length>0&&a.jsxs("span",{className:"text-xs text-spur-text-muted font-mono",children:["(",c.filter(R=>!R.disabled).length," active,"," ",c.filter(R=>R.disabled).length," disabled)"]})]}),a.jsx("span",{className:"text-xs text-spur-text-muted",children:"Execution profiles pairing CLI runtimes with models and capability tiers"})]}),M.length===0?a.jsx("div",{className:"p-4 rounded-xl bg-spur-surface border border-spur-border text-xs text-spur-text-muted",children:c.length===0?"No executor profiles defined in config.":"No executors match filter."}):a.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3","data-executors-grid":!0,children:M.map(R=>a.jsx(lX,{executor:R,onToggle:z=>O({executor:z,targetDisabled:!z.disabled})},R.name))})]}),A==="all"&&a.jsx("hr",{className:"border-0 border-t border-spur-border/50 my-1"}),(A==="all"||A==="fleet")&&a.jsxs("section",{className:"space-y-3","data-fleet-section":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-sm font-semibold tracking-tight text-spur-text",children:"Agent Fleet"}),a.jsx("code",{className:"text-[11px] font-mono px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-accent",children:"agent.fleet"})]}),d&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[a.jsx("span",{className:`px-2 py-0.5 rounded-md font-medium text-[11px] ${d.enabled?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-spur-surface-2 border border-spur-border text-spur-text-muted"}`,children:d.enabled?"Fleet Enabled":"Fleet Disabled"}),d.strategy&&a.jsxs("span",{className:"px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-text text-[11px]",children:["strategy:"," ",a.jsx("strong",{className:"font-mono text-spur-accent",children:d.strategy.name})]}),a.jsxs("span",{className:"px-2 py-0.5 rounded-md bg-spur-surface-2 border border-spur-border text-spur-text text-[11px]",children:["orchestrator:"," ",a.jsx("span",{className:"font-mono text-spur-text-muted",children:d.orchestrator.state})]})]})]}),n===null&&a.jsx("div",{className:"p-4 text-sm text-spur-text-muted bg-spur-surface border border-spur-border rounded-xl","data-roster-fetch-failed":b?"true":void 0,role:b?"alert":void 0,children:b?"Fleet roster unavailable — the process feed could not be read.":"Loading fleet roster…"}),n?.length===0&&a.jsxs("div",{className:"p-4 text-sm text-spur-text-muted italic bg-spur-surface border border-spur-border rounded-xl","data-roster-empty":!0,children:["No agents for this project — declare members under"," ",a.jsx("code",{className:"font-mono text-spur-accent",children:"agent.fleet"})," in"," ",a.jsx("code",{className:"font-mono text-spur-accent",children:`${t.path??"this project"}/.spur/config.yaml`}),"."]}),n!==null&&n.length>0&&a.jsx("div",{className:"grid gap-2 md:grid-cols-2 xl:grid-cols-3","data-roster-grid":!0,children:n.map(R=>a.jsx(cX,{entry:R,orchestratorOffline:y},R.instanceId))})]})]})]}),v!==null&&a.jsx(uX,{executor:v.executor,targetDisabled:v.targetDisabled,onClose:()=>O(null),onSuccess:()=>{const R=v;O(null),R&&u(z=>z.map(W=>W.name===R.executor.name?{...W,disabled:R.targetDisabled}:W)),C.current?.()}})]})}function EA({tier:e,electedExecutor:t,candidateExecutors:n,executors:r}){const s=e||"standard",i=r.filter(f=>(f.tier??"standard")===s),o=i.length>0?i:r.filter(f=>{const m=pS[s]??0;return(pS[f.tier??"standard"]??0)>=m}),l=t??o.find(f=>!f.disabled&&f.usable!==!1)?.name,c=l?o.find(f=>f.name===l)??r.find(f=>f.name===l):void 0,u=o.filter(f=>f.name!==l&&!f.disabled),d=o.filter(f=>f.name!==l&&f.disabled),p=[];c&&p.push({name:c.name,isDefault:!0,disabled:c.disabled,model:c.model,agent:c.agent});for(const f of u)p.push({name:f.name,isDefault:!1,disabled:!1,model:f.model,agent:f.agent});for(const f of d)p.push({name:f.name,isDefault:!1,disabled:!0,model:f.model,agent:f.agent});return p.length===0&&n&&n.length>0?n.map((f,m)=>{const b=r.find(x=>x.name===f);return{name:f,isDefault:f===t||m===0,disabled:b?.disabled??!1,agent:b?.agent,model:b?.model}}):p}function fS(e){return[`Agent: ${e.agent||"—"}`,`Model: ${e.model||"default"}`].join(`
311
311
  `)}const sX={scribe:"✍️",coder:"💻",reviewer:"🔍",planner:"📋"};function SA(e){return e.sourcePath??(e.sourceLayer==="project"?".spur/config.yaml":"~/.config/spur/config.yaml")}function wA({cand:e,kind:t}){const n=t==="role"?{"data-role-executor-item":e.name}:{"data-stage-executor-item":e.name};return a.jsx(ur,{position:"top",tip:fS(e),className:"inline-flex! z-30 [&:before]:whitespace-pre-line! [&:before]:text-left! [&:before]:font-mono [&:before]:text-[11px] [&:before]:p-2 [&:before]:rounded-lg [&:before]:shadow-xl after:whitespace-pre-line after:text-left after:font-mono after:text-[11px]",children:a.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[11px] font-mono inline-flex items-center gap-1 border transition-colors cursor-help ${e.isDefault?"bg-amber-500/15 border-amber-500/40 text-amber-800 dark:text-amber-300 font-semibold":e.disabled?"bg-spur-surface-2/40 border-spur-border/40 text-spur-text-muted/60 dark:text-spur-text-muted/50 line-through":"bg-spur-surface-2 border-spur-border/60 text-spur-text hover:border-spur-accent/30"}`,title:fS(e),...n,children:[a.jsx("span",{children:e.name}),e.isDefault&&a.jsx("span",{role:"img","aria-label":"default executor",children:"⭐"})]})})}function aX({role:e,executors:t=[]}){const n=sX[e.name.toLowerCase()]??"🤖",r=h.useMemo(()=>EA({tier:e.tier,electedExecutor:e.electedExecutor,candidateExecutors:e.candidateExecutors,executors:t}),[t,e.tier,e.electedExecutor,e.candidateExecutors]);return a.jsxs("div",{className:"p-3.5 bg-spur-surface border border-spur-border rounded-xl flex flex-col justify-between gap-3 hover:border-spur-accent/40 transition-colors shadow-sm","data-role-card":e.name,children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-base","aria-hidden":"true",children:n}),a.jsx("span",{className:"font-semibold text-sm capitalize text-spur-text",children:e.name})]}),a.jsx("span",{className:`text-[11px] font-mono px-2 py-0.5 rounded-md font-medium ${Qx(e.tier)}`,children:e.tier})]}),a.jsxs("div",{className:"mt-2.5",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider text-spur-text-muted font-medium mb-1",children:"Stages"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:e.stages.map(s=>a.jsx("span",{className:"px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border/60 text-[11px] font-mono text-spur-text",children:s},s))})]}),a.jsxs("div",{className:"mt-2.5",children:[a.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-spur-text-muted font-medium mb-1 flex items-center justify-between",children:[a.jsx("span",{children:"Executors"}),a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted/70",children:[r.length," in tier"]})]}),a.jsx("div",{className:"flex flex-wrap gap-1","data-role-executors":e.name,children:r.length>0?r.map(s=>a.jsx(wA,{cand:s,kind:"role"},s.name)):a.jsx("span",{className:"text-[11px] font-mono text-spur-text-muted italic",children:"none in tier"})})]})]}),a.jsx("div",{className:"pt-2 border-t border-spur-border/40 flex flex-col gap-1 text-[11px] text-spur-text-muted",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{children:"source"}),a.jsx("span",{className:"font-mono text-spur-text",children:e.isCustom?"project override":"built-in / global"})]})})]})}const iX={plan:"📋",refine:"🔧",brainstorm:"💡",implement:"💻",test:"🧪",review:"🔍",verify:"✅",dogfood:"🐶",wrap:"🎁",changelog:"📝"};function oX({stage:e,executors:t=[]}){const n=iX[e.id.toLowerCase()]??"⚙️",r=h.useMemo(()=>EA({tier:e.tier,electedExecutor:e.electedExecutor,candidateExecutors:e.candidateExecutors,executors:t}),[t,e.tier,e.electedExecutor,e.candidateExecutors]);return a.jsx("div",{className:"p-3.5 bg-spur-surface border border-spur-border rounded-xl flex flex-col justify-between gap-3 hover:border-spur-accent/40 transition-colors shadow-sm","data-stage-card":e.id,children:a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-base","aria-hidden":"true",children:n}),a.jsx("span",{className:"font-semibold text-sm font-mono text-spur-text",children:e.id}),e.alias&&a.jsx("code",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border text-spur-accent",children:e.alias})]}),a.jsx("span",{className:`text-[11px] font-mono px-2 py-0.5 rounded-md font-medium ${Qx(e.tier)}`,children:e.tier})]}),a.jsx("p",{className:"mt-2 text-xs text-spur-text-muted leading-relaxed line-clamp-2 min-h-[2.5rem]",children:e.description}),a.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-[11px]",children:[a.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border/60 font-medium text-spur-text",children:["role: ",a.jsx("strong",{className:"font-semibold",children:e.role})]}),e.skill&&a.jsx("span",{className:"px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border/40 font-mono text-[10px] text-spur-text-muted",title:`Reasoning skill: ${e.skill}`,children:e.skill})]}),a.jsxs("div",{className:"mt-2.5",children:[a.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-spur-text-muted font-medium mb-1 flex items-center justify-between",children:[a.jsx("span",{children:"Executors"}),a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted/70",children:[r.length," in tier"]})]}),a.jsx("div",{className:"flex flex-wrap gap-1","data-stage-executors":e.id,children:r.length>0?r.map(s=>a.jsx(wA,{cand:s,kind:"stage"},s.name)):a.jsx("span",{className:"text-[11px] font-mono text-spur-text-muted italic",children:"none in tier"})})]})]})})}function lX({executor:e,onToggle:t}){const n=e.executionCapabilities?.axes,r=n?Object.keys(n).filter(o=>n[o]?.state==="available"||n[o]?.state==="enforced"):[],s=!e.disabled,i=SA(e);return a.jsxs("div",{className:"p-3.5 bg-spur-surface border border-spur-border rounded-xl flex flex-col justify-between gap-3 hover:border-spur-accent/40 transition-colors shadow-sm","data-executor-card":e.name,children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"font-mono font-semibold text-sm text-spur-text",children:e.name}),a.jsx("span",{className:"px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border/60 text-[11px] font-mono text-spur-accent",children:e.agent})]}),a.jsx("span",{className:`text-[11px] font-mono px-2 py-0.5 rounded-md font-medium ${Qx(e.tier)}`,children:e.tier})]}),a.jsxs("div",{className:"mt-2 text-xs flex flex-wrap items-center justify-between gap-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5 truncate",children:[a.jsx("span",{className:"text-spur-text-muted",children:"model:"}),a.jsx("span",{className:"font-mono text-spur-text truncate",children:e.model??"default"})]}),e.version&&a.jsx("span",{className:"text-[10px] font-mono text-spur-text-muted/80 bg-spur-surface-2 px-1.5 py-0.5 rounded",children:e.version})]}),e.elected&&e.elected.length>0&&a.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[a.jsx("span",{className:"text-[10px] text-amber-700 dark:text-amber-400 font-medium",children:"Elected:"}),e.elected.map(o=>a.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 border border-amber-500/20 text-[10px] font-mono text-amber-800 dark:text-amber-300 flex items-center gap-0.5",children:[a.jsx("span",{children:"⭐"}),a.jsx("span",{children:o})]},o))]}),r.length>0&&a.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:r.map(o=>a.jsx("span",{className:"px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border/40 text-[10px] font-mono text-spur-text-muted",children:o},o))})]}),a.jsxs("div",{className:"pt-2 border-t border-spur-border/40 flex items-center justify-between text-xs gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("button",{type:"button",role:"switch","aria-checked":s,"aria-label":`Toggle ${e.name} status (currently ${s?"Ready":"Disabled"})`,onClick:o=>{o.stopPropagation(),t?.(e)},className:`group relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-spur-accent focus:ring-offset-1 focus:ring-offset-spur-surface ${s?"bg-emerald-500 border-emerald-500":"bg-spur-surface-3 border-spur-border"}`,"data-executor-toggle":e.name,children:[a.jsxs("span",{className:"sr-only",children:["Toggle ",e.name," availability"]}),a.jsx("span",{"aria-hidden":"true",className:`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow-sm ring-0 transition duration-200 ease-in-out ${s?"translate-x-4":"translate-x-0 bg-spur-text-muted/80"}`})]}),a.jsx("span",{className:`font-mono text-xs font-medium ${e.disabled?"text-amber-400":e.installed===!1?"text-rose-400":"text-emerald-400"}`,children:e.disabled?"Disabled":e.installed===!1?"CLI Missing":"Ready"})]}),a.jsxs("div",{className:"flex items-center gap-1.5 overflow-hidden",children:[e.sourceLayer&&a.jsx("span",{className:"px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border/60 text-[10px] font-mono text-spur-text-muted",title:`Declared in ${e.sourceLayer==="project"?"Project Config":"Global Config"}: ${i}`,children:e.sourceLayer}),e.disabled&&a.jsx("span",{className:"text-[11px] text-spur-text-muted truncate max-w-[120px]",title:e.disabledReason??e.disabledOwner??"disabled",children:e.disabledReason??e.disabledOwner??"disabled"})]})]})]})}function cX({entry:e,orchestratorOffline:t}){const n=rX(e,t),r=e.observed.status==="running"?OZ(e.observed.startedAt):null;return a.jsxs("div",{className:"text-left p-3.5 bg-spur-surface border border-spur-border rounded-xl shadow-sm transition-colors","data-roster-entry":e.instanceId,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{"data-roster-role":!0,className:"font-medium text-spur-text text-sm",children:e.declared?.role??"member"}),e.isOrchestrator&&a.jsx("span",{"data-roster-orchestrator":!0,className:"text-xs px-1 rounded bg-spur-accent/20 text-spur-accent",children:"orchestrator"})]}),a.jsxs("div",{className:"mt-1 text-xs text-spur-text-muted",children:["executor"," ",a.jsx("span",{"data-roster-executor":!0,className:"font-mono text-spur-text",children:e.declared?.executor??"—"})]}),a.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs",children:[a.jsxs("span",{"data-roster-declared":!0,children:[a.jsx("span",{className:"text-spur-text-muted",children:"declared:"})," ",a.jsx("span",{className:"text-spur-text",children:e.declared===null?"none":`${e.declared.enabled?"enabled":"disabled"} · capability ${e.declared.capabilityState}`})]}),a.jsxs("span",{"data-roster-observed":!0,children:[a.jsx("span",{className:"text-spur-text-muted",children:"observed:"})," ",a.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}`:""]})]})]}),r!==null&&a.jsx("div",{"data-roster-uptime":!0,className:"mt-1 text-xs text-spur-text-muted",children:r}),a.jsxs("div",{"data-roster-session":!0,className:"mt-1 text-xs text-spur-text-muted",children:["session"," ",a.jsx("span",{className:"font-mono text-spur-text",children:Xx(e.observed.session??e.declared?.session)??"—"})]}),e.issues.length>0&&a.jsx("div",{className:"mt-1 space-y-0.5",children:e.issues.map(s=>a.jsxs("div",{"data-roster-issue":s,className:"text-xs",children:[a.jsx("span",{"aria-hidden":"true",children:_d[s].icon})," ",a.jsx("span",{className:"text-spur-text",children:_d[s].label}),a.jsxs("span",{className:"text-spur-text-muted",children:[" — ",_d[s].action]})]},s))}),n.action!==null&&a.jsxs("div",{"data-roster-next-action":!0,className:"mt-1 text-xs text-spur-text-muted",children:["next: ",n.action]})]})}function uX({executor:e,targetDisabled:t,onClose:n,onSuccess:r}){const[s,i]=h.useState(!1),[o,l]=h.useState(null);h.useEffect(()=>{const p=f=>{f.key==="Escape"&&!s&&n()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,s]);const c=async()=>{i(!0),l(null);try{const p=await Xe(new Request(eX(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e.name,disabled:t,layer:e.sourceLayer})}));if(!p.ok){const f=await p.json().catch(()=>({}));throw new Error(f.error??`Request failed with status ${p.status}`)}r()}catch(p){l(p instanceof Error?p.message:String(p)),i(!1)}},u=e.sourceLayer==="project"?"Project Config":"Global Config",d=SA(e);return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm","data-modal-backdrop":!0,children:[a.jsx("button",{type:"button","aria-label":"Close modal backdrop",tabIndex:-1,className:"fixed inset-0 w-full h-full bg-transparent border-0 cursor-default",onClick:s?void 0:n}),a.jsxs("div",{className:"relative z-10 w-full max-w-md p-6 bg-spur-surface border border-spur-border rounded-2xl shadow-2xl space-y-4 text-spur-text",role:"dialog","aria-modal":"true","aria-labelledby":"executor-modal-title","data-executor-confirm-modal":!0,children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:`p-2.5 rounded-xl text-lg flex items-center justify-center ${t?"bg-amber-500/10 text-amber-400 border border-amber-500/20":"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"}`,"aria-hidden":"true",children:t?"⏸️":"⚡"}),a.jsxs("div",{children:[a.jsx("h3",{id:"executor-modal-title",className:"text-base font-semibold text-spur-text",children:t?"Disable Agent Executor":"Enable Agent Executor"}),a.jsxs("p",{className:"text-xs text-spur-text-muted mt-0.5",children:["Are you sure you want to change the status of"," ",a.jsx("code",{className:"px-1.5 py-0.5 rounded bg-spur-surface-2 border border-spur-border font-mono text-spur-accent font-semibold",children:e.name}),"?"]})]})]}),a.jsxs("div",{className:"p-3.5 rounded-xl bg-spur-surface-2 border border-spur-border/60 space-y-2.5 text-xs",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-spur-text-muted",children:"Target configuration:"}),a.jsx("span",{className:"font-mono font-medium text-spur-text",children:u})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-spur-text-muted shrink-0",children:"Config file:"}),a.jsx("code",{className:"font-mono text-spur-accent text-[11px] truncate max-w-[230px]",title:d,children:d})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-spur-text-muted",children:"Status transition:"}),a.jsxs("div",{className:"flex items-center gap-1.5 font-mono text-xs",children:[a.jsx("span",{className:e.disabled?"text-amber-400":"text-emerald-400",children:e.disabled?"Disabled":"Ready"}),a.jsx("span",{className:"text-spur-text-muted",children:"→"}),a.jsx("span",{className:`font-semibold ${t?"text-amber-400":"text-emerald-400"}`,children:t?"Disabled (OFF)":"Ready (ON)"})]})]}),a.jsx("div",{className:"pt-2 border-t border-spur-border/40 text-[11px] text-spur-text-muted leading-relaxed",children:t?a.jsxs("span",{children:["⚠️ Disabling will update your ",u.toLowerCase()," and exclude this executor from role elections and execution pipelines."]}):a.jsxs("span",{children:["✨ Enabling will update your ",u.toLowerCase()," and make this executor eligible for role elections and execution pipelines."]})})]}),o&&a.jsx("div",{className:"p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs",children:o}),a.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[a.jsx("button",{type:"button",onClick:n,disabled:s,className:"px-4 py-2 text-xs font-medium rounded-xl border border-spur-border bg-spur-surface-2 hover:bg-spur-surface-3 text-spur-text transition-colors disabled:opacity-50","data-modal-cancel":!0,children:"Cancel"}),a.jsx("button",{type:"button",onClick:c,disabled:s,className:`px-4 py-2 text-xs font-medium rounded-xl border transition-colors flex items-center gap-1.5 disabled:opacity-50 ${t?"bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 border-amber-500/40":"bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-300 border-emerald-500/40"}`,"data-modal-confirm":!0,children:s?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"w-3.5 h-3.5 border-2 border-current border-t-transparent rounded-full animate-spin"}),a.jsx("span",{children:"Updating..."})]}):a.jsx("span",{children:t?"Confirm Disable":"Confirm Enable"})})]})]})]})}function Id(e){let t=!1,n=!1;for(let r=0;r<e.length;r++){const s=e[r];if(s==="'"&&!n)t=!t;else if(s==='"'&&!t&&(r===0||(e[r-1]??"")!=="\\"))n=!n;else if(s==="#"&&!t&&!n&&(r===0||/\s/.test(e[r-1]??"")))return{content:e.slice(0,r),comment:e.slice(r)}}return{content:e}}function Rd(e,t){if(!e)return null;const n=e.trim();if(!n)return e;const r=e.match(/^\s*/),s=e.match(/\s*$/),i=r?r[0]:"",o=s?s[0]:"";let l=n;return n.startsWith('"')&&n.endsWith('"')&&n.length>=2||n.startsWith("'")&&n.endsWith("'")&&n.length>=2?l=a.jsx("span",{className:"text-emerald-400",children:n}):/^(true|false|yes|no|null|~)$/i.test(n)?l=a.jsx("span",{className:"text-purple-400 font-semibold",children:n}):/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(n)?l=a.jsx("span",{className:"text-amber-400 font-mono",children:n}):/^[&*][a-zA-Z0-9_-]+$/.test(n)?l=a.jsx("span",{className:"text-pink-400 font-semibold",children:n}):/^[|>][+-]?$/.test(n)?l=a.jsx("span",{className:"text-amber-300 font-bold",children:n}):/^!{1,2}[a-zA-Z0-9_-]+$/.test(n)?l=a.jsx("span",{className:"text-indigo-400 font-mono",children:n}):l=a.jsx("span",{className:"text-slate-200",children:n}),a.jsxs("span",{children:[i,l,o]},t)}function dX(e,t){const n=`line-${t}`;if(e.length===0)return" ";if(/^\s*(?:---|(?:\.\.\.))\s*$/.test(e))return a.jsx("span",{className:"text-slate-500 font-bold",children:e},n);const r=e.trimStart();if(r.startsWith("#")){const c=e.slice(0,e.length-r.length);return a.jsxs("span",{children:[c,a.jsx("span",{className:"text-slate-500 italic",children:r})]},n)}const s=e.match(/^(\s*(?:-\s+)?)(['"]?[a-zA-Z0-9_\-./@]+['"]?)\s*:(.*)$/);if(s){const c=s[1]??"",u=s[2]??"",d=s[3]??"",p=c.match(/^(\s*)(-\s+)(.*)$/);let f=c;p&&(f=a.jsxs("span",{children:[p[1],a.jsx("span",{className:"text-rose-400 font-bold",children:p[2]}),p[3]]}));const{content:m,comment:b}=Id(d);return a.jsxs("span",{children:[f,a.jsx("span",{className:"text-sky-400 font-semibold",children:u}),a.jsx("span",{className:"text-slate-400",children:":"}),m?Rd(m,`${n}-val`):null,b?a.jsx("span",{className:"text-slate-500 italic",children:b}):null]},n)}const i=e.match(/^(\s*-\s+)(.*)$/);if(i){const c=i[1]??"",u=i[2]??"",{content:d,comment:p}=Id(u),f=c.match(/^(\s*)(-\s+)/),m=f?a.jsxs("span",{children:[f[1],a.jsx("span",{className:"text-rose-400 font-bold",children:f[2]})]}):a.jsx("span",{className:"text-rose-400 font-bold",children:c});return a.jsxs("span",{children:[m,d?Rd(d,`${n}-val`):null,p?a.jsx("span",{className:"text-slate-500 italic",children:p}):null]},n)}const{content:o,comment:l}=Id(e);return a.jsxs("span",{children:[o?Rd(o,`${n}-val`):null,l?a.jsx("span",{className:"text-slate-500 italic",children:l}):null]},n)}function Jx({code:e="",filePath:t,maxHeight:n="calc(100vh - 280px)",className:r="",hideToolbar:s=!1}){const[i,o]=h.useState(!1),l=h.useMemo(()=>(e??"").split(`
312
312
  `).map((u,d)=>({id:`line-entry-${d+1}`,line:u,lineNum:d+1})),[e]),c=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),2e3)}catch{}};return a.jsxs("div",{className:`flex flex-col rounded-xl border border-spur-border bg-[#0d1117] text-[#e6edf3] shadow-md overflow-hidden ${r}`,"data-yaml-viewer":!0,children:[!s&&a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-[#161b22] border-b border-spur-border/70 text-xs shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2 font-mono text-spur-text-muted truncate",children:[a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-sky-500/10 text-sky-400 border border-sky-500/20",children:"YAML"}),t&&a.jsx("span",{className:"text-slate-300 truncate",title:t,children:t})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"text-[11px] text-slate-500 font-mono",children:[l.length," ",l.length===1?"line":"lines"]}),a.jsx("button",{type:"button",onClick:c,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium transition-colors bg-spur-surface-2 hover:bg-spur-surface-3 border border-spur-border text-slate-200 cursor-pointer","data-copy-button":!0,children:i?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-emerald-400",children:"✓"}),a.jsx("span",{className:"text-emerald-400",children:"Copied"})]}):a.jsxs(a.Fragment,{children:[a.jsxs("svg",{className:"w-3.5 h-3.5 text-slate-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[a.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),a.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),a.jsx("span",{children:"Copy"})]})})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-auto text-xs font-mono leading-relaxed",style:n&&n!=="none"?{maxHeight:n}:void 0,"data-yaml-code-container":!0,children:a.jsxs("div",{className:"flex min-w-full w-max py-2",children:[a.jsx("div",{className:"select-none text-slate-600 text-right pr-4 pl-3 shrink-0 border-r border-slate-800","aria-hidden":"true",children:l.map(u=>a.jsx("div",{className:"leading-6",children:u.lineNum},u.id))}),a.jsx("div",{className:"pl-4 pr-6 flex-1",children:l.map(u=>a.jsx("div",{className:"leading-6 whitespace-pre","data-code-line":!0,children:dX(u.line,u.lineNum-1)},u.id))})]})})]})}const pX=()=>`${it()}/project/configs`;function fX(e){if(e===0)return"0 B";if(e<1024)return`${e} B`;const t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(2)} MB`}const mX=[{id:"global",label:"🌐 Global Config",path:"~/.config/spur/config.yaml"},{id:"project",label:"📁 Project Config",path:".spur/config.yaml"}];function vA(){const[e,t]=h.useState("global"),[n,r]=h.useState(null),[s,i]=h.useState(!0),[o,l]=h.useState(null),c=h.useCallback(async()=>{i(!0),l(null);try{const d=await Xe(new Request(pX()));if(!d.ok)throw new Error(`Failed to load configuration files (${d.status})`);const p=await d.json();r(p)}catch(d){l(d instanceof Error?d.message:String(d))}finally{i(!1)}},[]);h.useEffect(()=>{c()},[c]);const u=n?.[e];return a.jsxs("div",{className:"flex flex-col h-full gap-4 overflow-y-auto pr-1","data-general-view":!0,children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-spur-border/60 pb-3 shrink-0",children:[a.jsx("div",{role:"tablist","aria-label":"Configuration file targets",className:"flex items-center gap-1.5 p-1 bg-spur-surface-2 border border-spur-border rounded-xl","data-config-subtabs":!0,children:mX.map(d=>{const p=e===d.id;return a.jsxs("button",{type:"button",role:"tab","aria-selected":p,"aria-controls":`config-subtab-panel-${d.id}`,id:`config-subtab-${d.id}`,onClick:()=>t(d.id),className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all cursor-pointer flex items-center gap-2 ${p?"bg-spur-accent text-white shadow-sm":"text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-3"}`,"data-subtab":d.id,children:[a.jsx("span",{children:d.label}),a.jsx("code",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-black/20 text-white/90",children:d.path})]},d.id)})}),a.jsxs("div",{className:"flex items-center gap-2.5",children:[u&&a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsxs("span",{className:`px-2 py-0.5 rounded-md font-medium text-[11px] flex items-center gap-1 ${u.exists?"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20":"bg-amber-500/10 text-amber-400 border border-amber-500/20"}`,"data-status-badge":!0,children:[a.jsx("span",{children:u.exists?"✓":"⚠️"}),a.jsx("span",{children:u.exists?"Found":"Not Created"})]}),u.exists&&a.jsx("span",{className:"font-mono text-spur-text-muted text-[11px]",children:fX(u.sizeBytes)})]}),a.jsxs("button",{type:"button",onClick:c,disabled:s,className:"px-2.5 py-1 text-xs font-medium rounded-lg border border-spur-border bg-spur-surface-2 hover:bg-spur-surface-3 text-spur-text transition-colors disabled:opacity-50 cursor-pointer flex items-center gap-1",title:"Reload configuration files from disk","data-reload-button":!0,children:[a.jsx("span",{className:s?"animate-spin":"",children:"↻"}),a.jsx("span",{children:"Refresh"})]})]})]}),o&&a.jsxs("div",{className:"p-3 text-xs rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-400 flex items-center justify-between","data-error-banner":!0,children:[a.jsx("span",{children:o}),a.jsx("button",{type:"button",onClick:c,className:"underline hover:text-rose-300 font-semibold cursor-pointer",children:"Retry"})]}),s&&!n&&a.jsxs("div",{className:"flex-1 flex items-center justify-center p-12 text-spur-text-muted text-sm gap-2",children:[a.jsx("span",{className:"w-4 h-4 border-2 border-spur-accent border-t-transparent rounded-full animate-spin"}),a.jsx("span",{children:"Loading configuration files..."})]}),u&&a.jsxs("div",{role:"tabpanel",id:`config-subtab-panel-${e}`,"aria-labelledby":`config-subtab-${e}`,className:"flex-1 min-h-0 space-y-2",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-3.5 py-2 rounded-xl bg-spur-surface-2 border border-spur-border/60 text-xs",children:[a.jsxs("div",{className:"flex items-center gap-2 truncate",children:[a.jsx("span",{className:"text-spur-text-muted shrink-0",children:"Path:"}),a.jsx("code",{className:"font-mono text-spur-accent truncate text-[11px]",title:u.path,children:u.path})]}),u.updatedAt&&a.jsxs("div",{className:"text-[11px] text-spur-text-muted shrink-0",children:["Updated: ",new Date(u.updatedAt).toLocaleString()]})]}),u.exists?a.jsx(Jx,{code:u.content,filePath:u.displayPath}):a.jsxs("div",{className:"p-8 text-center bg-spur-surface-2 border border-dashed border-spur-border rounded-xl space-y-3","data-missing-file-card":!0,children:[a.jsx("div",{className:"text-3xl",children:"⚠️"}),a.jsx("h3",{className:"text-sm font-semibold text-spur-text",children:"Configuration File Not Found"}),a.jsxs("p",{className:"text-xs text-spur-text-muted max-w-md mx-auto",children:["No configuration file exists at"," ",a.jsx("code",{className:"font-mono text-spur-accent px-1.5 py-0.5 rounded bg-spur-surface border border-spur-border",children:u.displayPath}),". You can initialize it using the Spur CLI."]}),a.jsx("div",{className:"pt-2",children:a.jsx("code",{className:"px-3 py-1.5 rounded-lg bg-spur-surface border border-spur-border font-mono text-xs text-spur-accent",children:e==="global"?"spur init --global":"spur init"})})]})]})]})}const hX=()=>`${it()}/project/workflows`,NA="spur:detail-width";function gX(){if(typeof window>"u")return 1728;const e=window.innerWidth*.8;try{const t=Number.parseFloat(window.localStorage.getItem(NA)??"");if(Number.isFinite(t)&&t>0)return Math.min(t,e)}catch{}return Math.min(1728,e)}const bX=[{label:"🤖 agent.run",style:"bg-[#e0e7ff] border-[#4f46e5] text-[#1e1b4b]",title:"Agent run (prompt / slash command)"},{label:"💻 shell",style:"bg-[#ecfdf5] border-[#059669] text-[#064e3b]",title:"Shell command execution"},{label:"👤 hitl",style:"bg-[#fdf4ff] border-[#9333ea] text-[#3b0764]",title:"Human-in-the-loop decision"},{label:"🔒 gate",style:"bg-[#e8e8f8] border-[#5b5bd6] text-[#1a1a5e]",title:"Structural gate or probe"}],xX=[{label:"Initial",dot:"bg-[#fff3cd] border-[#b8860b] rounded-full"},{label:"Done",dot:"bg-[#d4edda] border-[#1e7e34] rounded-full"},{label:"Failed",dot:"bg-[#f8d7da] border-[#c62828] rounded"}];function TA(){const[e,t]=h.useState([]),[n,r]=h.useState(""),[s,i]=h.useState(!0),[o,l]=h.useState(null),[c,u]=h.useState(!1),[d,p]=h.useState(1),[f,m]=h.useState("TD"),[b,x]=h.useState(!1),[y,E]=h.useState(gX);h.useEffect(()=>{typeof document<"u"&&document.documentElement.style.setProperty("--workflow-yaml-w",`${y}px`)},[y]),h.useEffect(()=>{if(!b)return;const S=v=>{v.key==="Escape"&&x(!1)};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[b]);const A=h.useCallback(async()=>{i(!0),l(null);try{const S=await Xe(new Request(hX()));if(!S.ok)throw new Error(`Failed to load workflows (${S.status})`);const O=(await S.json()).workflows??[];if(t(O),O.length>0){const C=O[0];C&&r(M=>O.some(R=>R.name===M)?M:C.name)}}catch(S){l(S instanceof Error?S.message:String(S))}finally{i(!1)}},[]);h.useEffect(()=>{A()},[A]);const w=h.useMemo(()=>e.find(S=>S.name===n)??e[0],[e,n]),N=h.useMemo(()=>{const S={registered:[],project:[],shared:[]};for(const v of e){const O=S[v.source];O?O.push(v):S[v.source]=[v]}return S},[e]),_=h.useMemo(()=>{if(!w?.mermaidDiagram)return"";let S=w.mermaidDiagram.trim();return S.startsWith("```")||(S=`\`\`\`mermaid
313
313
  ${S}
@@ -316,5 +316,5 @@ ${S}
316
316
  To pick up a draggable item, press the space bar.
317
317
  While dragging, use the arrow keys to move the item.
318
318
  Press space again to drop the item in its new position, or press escape to cancel.
319
- `},LX={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 jX(e){let{announcements:t=LX,container:n,hiddenTextDescribedById:r,screenReaderInstructions:s=OX}=e;const{announce:i,announcement:o}=IX(),l=xu("DndLiveRegion"),[c,u]=h.useState(!1);if(h.useEffect(()=>{u(!0)},[]),RX(h.useMemo(()=>({onDragStart(p){let{active:f}=p;i(t.onDragStart({active:f}))},onDragMove(p){let{active:f,over:m}=p;t.onDragMove&&i(t.onDragMove({active:f,over:m}))},onDragOver(p){let{active:f,over:m}=p;i(t.onDragOver({active:f,over:m}))},onDragEnd(p){let{active:f,over:m}=p;i(t.onDragEnd({active:f,over:m}))},onDragCancel(p){let{active:f,over:m}=p;i(t.onDragCancel({active:f,over:m}))}}),[i,t])),!c)return null;const d=st.createElement(st.Fragment,null,st.createElement(CX,{id:r,value:s.draggable}),st.createElement(_X,{id:l,announcement:o}));return n?Ur.createPortal(d,n):d}var Zt;(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"})(Zt||(Zt={}));function pc(){}function hS(e,t){return h.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function MX(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return h.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const Zn=Object.freeze({x:0,y:0});function FX(e,t){const n=dc(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 PX(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function BX(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function $X(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),s=Math.min(t.left+t.width,e.left+e.width),i=Math.min(t.top+t.height,e.top+e.height),o=s-r,l=i-n;if(r<s&&n<i){const c=t.width*t.height,u=e.width*e.height,d=o*l,p=d/(c+u-d);return Number(p.toFixed(4))}return 0}const UX=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=[];for(const i of r){const{id:o}=i,l=n.get(o);if(l){const c=$X(l,t);c>0&&s.push({id:o,data:{droppableContainer:i,value:c}})}}return s.sort(PX)};function zX(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function IA(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Zn}function HX(e){return function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),i=1;i<r;i++)s[i-1]=arguments[i];return s.reduce((o,l)=>({...o,top:o.top+e*l.y,bottom:o.bottom+e*l.y,left:o.left+e*l.x,right:o.right+e*l.x}),{...n})}}const GX=HX(1);function RA(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 WX(e,t,n){const r=RA(t);if(!r)return e;const{scaleX:s,scaleY:i,x:o,y:l}=r,c=e.left-o-(1-s)*parseFloat(n),u=e.top-l-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),d=s?e.width/s:e.width,p=i?e.height/i:e.height;return{width:d,height:p,top:u,right:c+d,bottom:u+p,left:c}}const qX={ignoreTransform:!1};function No(e,t){t===void 0&&(t=qX);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=Nn(e).getComputedStyle(e);u&&(n=WX(n,u,d))}const{top:r,left:s,width:i,height:o,bottom:l,right:c}=n;return{top:r,left:s,width:i,height:o,bottom:l,right:c}}function gS(e){return No(e,{ignoreTransform:!0})}function VX(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function YX(e,t){return t===void 0&&(t=Nn(e).getComputedStyle(e)),t.position==="fixed"}function KX(e,t){t===void 0&&(t=Nn(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(s=>{const i=t[s];return typeof i=="string"?n.test(i):!1})}function r0(e,t){const n=[];function r(s){if(t!=null&&n.length>=t||!s)return n;if(t0(s)&&s.scrollingElement!=null&&!n.includes(s.scrollingElement))return n.push(s.scrollingElement),n;if(!wo(s)||AA(s)||n.includes(s))return n;const i=Nn(e).getComputedStyle(s);return s!==e&&KX(s,i)&&n.push(s),YX(s,i)?n:r(s.parentNode)}return e?r(e):n}function DA(e){const[t]=r0(e,1);return t??null}function Od(e){return!gu||!e?null:Va(e)?e:e0(e)?t0(e)||e===Ya(e).scrollingElement?window:wo(e)?e:null:null}function OA(e){return Va(e)?e.scrollX:e.scrollLeft}function LA(e){return Va(e)?e.scrollY:e.scrollTop}function Pp(e){return{x:OA(e),y:LA(e)}}var rn;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(rn||(rn={}));function jA(e){return!gu||!e?!1:e===document.scrollingElement}function MA(e){const t={x:0,y:0},n=jA(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},s=e.scrollTop<=t.y,i=e.scrollLeft<=t.x,o=e.scrollTop>=r.y,l=e.scrollLeft>=r.x;return{isTop:s,isLeft:i,isBottom:o,isRight:l,maxScroll:r,minScroll:t}}const ZX={x:.2,y:.2};function XX(e,t,n,r,s){let{top:i,left:o,right:l,bottom:c}=n;r===void 0&&(r=10),s===void 0&&(s=ZX);const{isTop:u,isBottom:d,isLeft:p,isRight:f}=MA(e),m={x:0,y:0},b={x:0,y:0},x={height:t.height*s.y,width:t.width*s.x};return!u&&i<=t.top+x.height?(m.y=rn.Backward,b.y=r*Math.abs((t.top+x.height-i)/x.height)):!d&&c>=t.bottom-x.height&&(m.y=rn.Forward,b.y=r*Math.abs((t.bottom-x.height-c)/x.height)),!f&&l>=t.right-x.width?(m.x=rn.Forward,b.x=r*Math.abs((t.right-x.width-l)/x.width)):!p&&o<=t.left+x.width&&(m.x=rn.Backward,b.x=r*Math.abs((t.left+x.width-o)/x.width)),{direction:m,speed:b}}function QX(e){if(e===document.scrollingElement){const{innerWidth:i,innerHeight:o}=window;return{top:0,left:0,right:i,bottom:o,width:i,height:o}}const{top:t,left:n,right:r,bottom:s}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:s,width:e.clientWidth,height:e.clientHeight}}function FA(e){return e.reduce((t,n)=>ha(t,Pp(n)),Zn)}function JX(e){return e.reduce((t,n)=>t+OA(n),0)}function eQ(e){return e.reduce((t,n)=>t+LA(n),0)}function PA(e,t){if(t===void 0&&(t=No),!e)return;const{top:n,left:r,bottom:s,right:i}=t(e);DA(e)&&(s<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const tQ=[["x",["left","right"],JX],["y",["top","bottom"],eQ]];class s0{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=r0(n),s=FA(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,o,l]of tQ)for(const c of o)Object.defineProperty(this,c,{get:()=>{const u=l(r),d=s[i]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ri{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 s;(s=this.target)==null||s.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function nQ(e){const{EventTarget:t}=Nn(e);return e instanceof t?e:Ya(e)}function Ld(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 jn;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(jn||(jn={}));function bS(e){e.preventDefault()}function rQ(e){e.stopPropagation()}var It;(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"})(It||(It={}));const BA={start:[It.Space,It.Enter],cancel:[It.Esc],end:[It.Space,It.Enter,It.Tab]},sQ=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case It.Right:return{...n,x:n.x+25};case It.Left:return{...n,x:n.x-25};case It.Down:return{...n,y:n.y+25};case It.Up:return{...n,y:n.y-25}}};class a0{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 Ri(Ya(n)),this.windowListeners=new Ri(Nn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(jn.Resize,this.handleCancel),this.windowListeners.add(jn.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(jn.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&PA(r),n(Zn)}handleKeyDown(t){if(n0(t)){const{active:n,context:r,options:s}=this.props,{keyboardCodes:i=BA,coordinateGetter:o=sQ,scrollBehavior:l="smooth"}=s,{code:c}=t;if(i.end.includes(c)){this.handleEnd(t);return}if(i.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:Zn;this.referenceCoordinates||(this.referenceCoordinates=d);const p=o(t,{active:n,context:r.current,currentCoordinates:d});if(p){const f=uc(p,d),m={x:0,y:0},{scrollableAncestors:b}=r.current;for(const x of b){const y=t.code,{isTop:E,isRight:A,isLeft:w,isBottom:N,maxScroll:_,minScroll:k}=MA(x),S=QX(x),v={x:Math.min(y===It.Right?S.right-S.width/2:S.right,Math.max(y===It.Right?S.left:S.left+S.width/2,p.x)),y:Math.min(y===It.Down?S.bottom-S.height/2:S.bottom,Math.max(y===It.Down?S.top:S.top+S.height/2,p.y))},O=y===It.Right&&!A||y===It.Left&&!w,C=y===It.Down&&!N||y===It.Up&&!E;if(O&&v.x!==p.x){const M=x.scrollLeft+f.x,B=y===It.Right&&M<=_.x||y===It.Left&&M>=k.x;if(B&&!f.y){x.scrollTo({left:M,behavior:l});return}B?m.x=x.scrollLeft-M:m.x=y===It.Right?x.scrollLeft-_.x:x.scrollLeft-k.x,m.x&&x.scrollBy({left:-m.x,behavior:l});break}else if(C&&v.y!==p.y){const M=x.scrollTop+f.y,B=y===It.Down&&M<=_.y||y===It.Up&&M>=k.y;if(B&&!f.x){x.scrollTo({top:M,behavior:l});return}B?m.y=x.scrollTop-M:m.y=y===It.Down?x.scrollTop-_.y:x.scrollTop-k.y,m.y&&x.scrollBy({top:-m.y,behavior:l});break}}this.handleMove(t,ha(uc(p,this.referenceCoordinates),m))}}}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()}}a0.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=BA,onActivation:s}=t,{active:i}=n;const{code:o}=e.nativeEvent;if(r.start.includes(o)){const l=i.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),s?.({event:e.nativeEvent}),!0)}return!1}}];function xS(e){return!!(e&&"distance"in e)}function yS(e){return!!(e&&"delay"in e)}class i0{constructor(t,n,r){var s;r===void 0&&(r=nQ(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:i}=t,{target:o}=i;this.props=t,this.events=n,this.document=Ya(o),this.documentListeners=new Ri(this.document),this.listeners=new Ri(r),this.windowListeners=new Ri(Nn(o)),this.initialCoordinates=(s=dc(i))!=null?s:Zn,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(jn.Resize,this.handleCancel),this.windowListeners.add(jn.DragStart,bS),this.windowListeners.add(jn.VisibilityChange,this.handleCancel),this.windowListeners.add(jn.ContextMenu,bS),this.documentListeners.add(jn.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(yS(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(xS(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:s}=this.props;s(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(jn.Click,rQ,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(jn.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:s,props:i}=this,{onMove:o,options:{activationConstraint:l}}=i;if(!s)return;const c=(n=dc(t))!=null?n:Zn,u=uc(s,c);if(!r&&l){if(xS(l)){if(l.tolerance!=null&&Ld(u,l.tolerance))return this.handleCancel();if(Ld(u,l.distance))return this.handleStart()}if(yS(l)&&Ld(u,l.tolerance))return this.handleCancel();this.handlePending(l,u);return}t.cancelable&&t.preventDefault(),o(c)}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===It.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const aQ={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class o0 extends i0{constructor(t){const{event:n}=t,r=Ya(n.target);super(t,aQ,r)}}o0.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 iQ={move:{name:"mousemove"},end:{name:"mouseup"}};var Bp;(function(e){e[e.RightClick=2]="RightClick"})(Bp||(Bp={}));class oQ extends i0{constructor(t){super(t,iQ,Ya(t.event.target))}}oQ.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===Bp.RightClick?!1:(r?.({event:n}),!0)}}];const jd={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class lQ extends i0{constructor(t){super(t,jd)}static setup(){return window.addEventListener(jd.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(jd.move.name,t)};function t(){}}}lQ.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:s}=n;return s.length>1?!1:(r?.({event:n}),!0)}}];var Di;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Di||(Di={}));var fc;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(fc||(fc={}));function cQ(e){let{acceleration:t,activator:n=Di.Pointer,canScroll:r,draggingRect:s,enabled:i,interval:o=5,order:l=fc.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:p,threshold:f}=e;const m=dQ({delta:p,disabled:!i}),[b,x]=vX(),y=h.useRef({x:0,y:0}),E=h.useRef({x:0,y:0}),A=h.useMemo(()=>{switch(n){case Di.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case Di.DraggableRect:return s}},[n,s,c]),w=h.useRef(null),N=h.useCallback(()=>{const k=w.current;if(!k)return;const S=y.current.x*E.current.x,v=y.current.y*E.current.y;k.scrollBy(S,v)},[]),_=h.useMemo(()=>l===fc.TreeOrder?[...u].reverse():u,[l,u]);h.useEffect(()=>{if(!i||!u.length||!A){x();return}for(const k of _){if(r?.(k)===!1)continue;const S=u.indexOf(k),v=d[S];if(!v)continue;const{direction:O,speed:C}=XX(k,v,A,t,f);for(const M of["x","y"])m[M][O[M]]||(C[M]=0,O[M]=0);if(C.x>0||C.y>0){x(),w.current=k,b(N,o),y.current=C,E.current=O;return}}y.current={x:0,y:0},E.current={x:0,y:0},x()},[t,N,r,x,i,o,JSON.stringify(A),JSON.stringify(m),b,u,_,d,JSON.stringify(f)])}const uQ={x:{[rn.Backward]:!1,[rn.Forward]:!1},y:{[rn.Backward]:!1,[rn.Forward]:!1}};function dQ(e){let{delta:t,disabled:n}=e;const r=cc(t);return vo(s=>{if(n||!r||!s)return uQ;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[rn.Backward]:s.x[rn.Backward]||i.x===-1,[rn.Forward]:s.x[rn.Forward]||i.x===1},y:{[rn.Backward]:s.y[rn.Backward]||i.y===-1,[rn.Forward]:s.y[rn.Forward]||i.y===1}}},[n,t,r])}function pQ(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return vo(s=>{var i;return t==null?null:(i=r??s)!=null?i:null},[r,t])}function fQ(e,t){return h.useMemo(()=>e.reduce((n,r)=>{const{sensor:s}=r,i=s.activators.map(o=>({eventName:o.eventName,handler:t(o.handler,r)}));return[...n,...i]},[]),[e,t])}var Xi;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Xi||(Xi={}));var $p;(function(e){e.Optimized="optimized"})($p||($p={}));const ES=new Map;function mQ(e,t){let{dragging:n,dependencies:r,config:s}=t;const[i,o]=h.useState(null),{frequency:l,measure:c,strategy:u}=s,d=h.useRef(e),p=y(),f=Zi(p),m=h.useCallback(function(E){E===void 0&&(E=[]),!f.current&&o(A=>A===null?E:A.concat(E.filter(w=>!A.includes(w))))},[f]),b=h.useRef(null),x=vo(E=>{if(p&&!n)return ES;if(!E||E===ES||d.current!==e||i!=null){const A=new Map;for(let w of e){if(!w)continue;if(i&&i.length>0&&!i.includes(w.id)&&w.rect.current){A.set(w.id,w.rect.current);continue}const N=w.node.current,_=N?new s0(c(N),N):null;w.rect.current=_,_&&A.set(w.id,_)}return A}return E},[e,i,n,p,c]);return h.useEffect(()=>{d.current=e},[e]),h.useEffect(()=>{p||m()},[n,p]),h.useEffect(()=>{i&&i.length>0&&o(null)},[JSON.stringify(i)]),h.useEffect(()=>{p||typeof l!="number"||b.current!==null||(b.current=setTimeout(()=>{m(),b.current=null},l))},[l,p,m,...r]),{droppableRects:x,measureDroppableContainers:m,measuringScheduled:i!=null};function y(){switch(u){case Xi.Always:return!1;case Xi.BeforeDragging:return n;default:return!n}}}function l0(e,t){return vo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function hQ(e,t){return l0(e,t)}function gQ(e){let{callback:t,disabled:n}=e;const r=bu(t),s=h.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return h.useEffect(()=>()=>s?.disconnect(),[s]),s}function yu(e){let{callback:t,disabled:n}=e;const r=bu(t),s=h.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return h.useEffect(()=>()=>s?.disconnect(),[s]),s}function bQ(e){return new s0(No(e),e)}function SS(e,t,n){t===void 0&&(t=bQ);const[r,s]=h.useState(null);function i(){s(c=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=t(e);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const o=gQ({callback(c){if(e)for(const u of c){const{type:d,target:p}=u;if(d==="childList"&&p instanceof HTMLElement&&p.contains(e)){i();break}}}}),l=yu({callback:i});return _r(()=>{i(),e?(l?.observe(e),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[e]),r}function xQ(e){const t=l0(e);return IA(e,t)}const wS=[];function yQ(e){const t=h.useRef(e),n=vo(r=>e?r&&r!==wS&&e&&t.current&&e.parentNode===t.current.parentNode?r:r0(e):wS,[e]);return h.useEffect(()=>{t.current=e},[e]),n}function EQ(e){const[t,n]=h.useState(null),r=h.useRef(e),s=h.useCallback(i=>{const o=Od(i.target);o&&n(l=>l?(l.set(o,Pp(o)),new Map(l)):null)},[]);return h.useEffect(()=>{const i=r.current;if(e!==i){o(i);const l=e.map(c=>{const u=Od(c);return u?(u.addEventListener("scroll",s,{passive:!0}),[u,Pp(u)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),r.current=e}return()=>{o(e),o(i)};function o(l){l.forEach(c=>{const u=Od(c);u?.removeEventListener("scroll",s)})}},[s,e]),h.useMemo(()=>e.length?t?Array.from(t.values()).reduce((i,o)=>ha(i,o),Zn):FA(e):Zn,[e,t])}function vS(e,t){t===void 0&&(t=[]);const n=h.useRef(null);return h.useEffect(()=>{n.current=null},t),h.useEffect(()=>{const r=e!==Zn;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?uc(e,n.current):Zn}function SQ(e){h.useEffect(()=>{if(!gu)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 wQ(e,t){return h.useMemo(()=>e.reduce((n,r)=>{let{eventName:s,handler:i}=r;return n[s]=o=>{i(o,t)},n},{}),[e,t])}function $A(e){return h.useMemo(()=>e?VX(e):null,[e])}const NS=[];function vQ(e,t){t===void 0&&(t=No);const[n]=e,r=$A(n?Nn(n):null),[s,i]=h.useState(NS);function o(){i(()=>e.length?e.map(c=>jA(c)?r:new s0(t(c),c)):NS)}const l=yu({callback:o});return _r(()=>{l?.disconnect(),o(),e.forEach(c=>l?.observe(c))},[e]),s}function UA(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return wo(t)?t:e}function NQ(e){let{measure:t}=e;const[n,r]=h.useState(null),s=h.useCallback(u=>{for(const{target:d}of u)if(wo(d)){r(p=>{const f=t(d);return p?{...p,width:f.width,height:f.height}:f});break}},[t]),i=yu({callback:s}),o=h.useCallback(u=>{const d=UA(u);i?.disconnect(),d&&i?.observe(d),r(d?t(d):null)},[t,i]),[l,c]=lc(o);return h.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const TQ=[{sensor:o0,options:{}},{sensor:a0,options:{}}],kQ={current:{}},Il={draggable:{measure:gS},droppable:{measure:gS,strategy:Xi.WhileDragging,frequency:$p.Optimized},dragOverlay:{measure:No}};class Oi 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 AQ={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Oi,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:pc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Il,measureDroppableContainers:pc,windowRect:null,measuringScheduled:!1},zA={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:pc,draggableNodes:new Map,over:null,measureDroppableContainers:pc},To=h.createContext(zA),HA=h.createContext(AQ);function CQ(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Oi}}}function _Q(e,t){switch(t.type){case Zt.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Zt.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 Zt.DragEnd:case Zt.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Zt.RegisterDroppable:{const{element:n}=t,{id:r}=n,s=new Oi(e.droppable.containers);return s.set(r,n),{...e,droppable:{...e.droppable,containers:s}}}case Zt.SetDroppableDisabled:{const{id:n,key:r,disabled:s}=t,i=e.droppable.containers.get(n);if(!i||r!==i.key)return e;const o=new Oi(e.droppable.containers);return o.set(n,{...i,disabled:s}),{...e,droppable:{...e.droppable,containers:o}}}case Zt.UnregisterDroppable:{const{id:n,key:r}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const i=new Oi(e.droppable.containers);return i.delete(n),{...e,droppable:{...e.droppable,containers:i}}}default:return e}}function IQ(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:s}=h.useContext(To),i=cc(r),o=cc(n?.id);return h.useEffect(()=>{if(!t&&!r&&i&&o!=null){if(!n0(i)||document.activeElement===i.target)return;const l=s.get(o);if(!l)return;const{activatorNode:c,node:u}=l;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const p=kX(d);if(p){p.focus();break}}})}},[r,t,s,o,i]),null}function GA(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((s,i)=>i({transform:s,...r}),n):n}function RQ(e){return h.useMemo(()=>({draggable:{...Il.draggable,...e?.draggable},droppable:{...Il.droppable,...e?.droppable},dragOverlay:{...Il.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function DQ(e){let{activeNode:t,measure:n,initialRect:r,config:s=!0}=e;const i=h.useRef(!1),{x:o,y:l}=typeof s=="boolean"?{x:s,y:s}:s;_r(()=>{if(!o&&!l||!t){i.current=!1;return}if(i.current||!r)return;const u=t?.node.current;if(!u||u.isConnected===!1)return;const d=n(u),p=IA(d,r);if(o||(p.x=0),l||(p.y=0),i.current=!0,Math.abs(p.x)>0||Math.abs(p.y)>0){const f=DA(u);f&&f.scrollBy({top:p.y,left:p.x})}},[t,o,l,r,n])}const Eu=h.createContext({...Zn,scaleX:1,scaleY:1});var Br;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Br||(Br={}));const OQ=h.memo(function(t){var n,r,s,i;let{id:o,accessibility:l,autoScroll:c=!0,children:u,sensors:d=TQ,collisionDetection:p=UX,measuring:f,modifiers:m,...b}=t;const x=h.useReducer(_Q,void 0,CQ),[y,E]=x,[A,w]=DX(),[N,_]=h.useState(Br.Uninitialized),k=N===Br.Initialized,{draggable:{active:S,nodes:v,translate:O},droppable:{containers:C}}=y,M=S!=null?v.get(S):null,B=h.useRef({initial:null,translated:null}),R=h.useMemo(()=>{var Oe;return S!=null?{id:S,data:(Oe=M?.data)!=null?Oe:kQ,rect:B}:null},[S,M]),z=h.useRef(null),[W,F]=h.useState(null),[J,K]=h.useState(null),X=Zi(b,Object.values(b)),I=xu("DndDescribedBy",o),V=h.useMemo(()=>C.getEnabled(),[C]),te=RQ(f),{droppableRects:L,measureDroppableContainers:ye,measuringScheduled:xe}=mQ(V,{dragging:k,dependencies:[O.x,O.y],config:te.droppable}),P=pQ(v,S),oe=h.useMemo(()=>J?dc(J):null,[J]),re=Ct(),H=hQ(P,te.draggable.measure);DQ({activeNode:S!=null?v.get(S):null,config:re.layoutShiftCompensation,initialRect:H,measure:te.draggable.measure});const Ce=SS(P,te.draggable.measure,H),me=SS(P?P.parentElement:null),he=h.useRef({activatorEvent:null,active:null,activeNode:P,collisionRect:null,collisions:null,droppableRects:L,draggableNodes:v,draggingNode:null,draggingNodeRect:null,droppableContainers:C,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ne=C.getNodeFor((n=he.current.over)==null?void 0:n.id),Ge=NQ({measure:te.dragOverlay.measure}),Z=(r=Ge.nodeRef.current)!=null?r:P,ke=k?(s=Ge.rect)!=null?s:Ce:null,Fe=!!(Ge.nodeRef.current&&Ge.rect),Re=xQ(Fe?null:Ce),rt=$A(Z?Nn(Z):null),ae=yQ(k?Ne??P:null),pe=vQ(ae),De=GA(m,{transform:{x:O.x-Re.x,y:O.y-Re.y,scaleX:1,scaleY:1},activatorEvent:J,active:R,activeNodeRect:Ce,containerNodeRect:me,draggingNodeRect:ke,over:he.current.over,overlayNodeRect:Ge.rect,scrollableAncestors:ae,scrollableAncestorRects:pe,windowRect:rt}),Me=oe?ha(oe,O):null,Le=EQ(ae),ot=vS(Le),dt=vS(Le,[Ce]),se=ha(De,ot),fe=ke?GX(ke,De):null,je=R&&fe?p({active:R,collisionRect:fe,droppableRects:L,droppableContainers:V,pointerCoordinates:Me}):null,Y=BX(je,"id"),[He,Ue]=h.useState(null),at=Fe?De:ha(De,dt),Nt=zX(at,(i=He?.rect)!=null?i:null,Ce),At=h.useRef(null),de=h.useCallback((Oe,Qe)=>{let{sensor:qe,options:St}=Qe;if(z.current==null)return;const ce=v.get(z.current);if(!ce)return;const Ee=Oe.nativeEvent,Ye=new qe({active:z.current,activeNode:ce,event:Ee,options:St,context:he,onAbort(ee){if(!v.get(ee))return;const{onDragAbort:lt}=X.current,bt={id:ee};lt?.(bt),A({type:"onDragAbort",event:bt})},onPending(ee,We,lt,bt){if(!v.get(ee))return;const{onDragPending:xr}=X.current,nr={id:ee,constraint:We,initialCoordinates:lt,offset:bt};xr?.(nr),A({type:"onDragPending",event:nr})},onStart(ee){const We=z.current;if(We==null)return;const lt=v.get(We);if(!lt)return;const{onDragStart:bt}=X.current,In={activatorEvent:Ee,active:{id:We,data:lt.data,rect:B}};Ur.unstable_batchedUpdates(()=>{bt?.(In),_(Br.Initializing),E({type:Zt.DragStart,initialCoordinates:ee,active:We}),A({type:"onDragStart",event:In}),F(At.current),K(Ee)})},onMove(ee){E({type:Zt.DragMove,coordinates:ee})},onEnd:Dt(Zt.DragEnd),onCancel:Dt(Zt.DragCancel)});At.current=Ye;function Dt(ee){return async function(){const{active:lt,collisions:bt,over:In,scrollAdjustedTranslate:xr}=he.current;let nr=null;if(lt&&xr){const{cancelDrop:Hn}=X.current;nr={activatorEvent:Ee,active:lt,collisions:bt,delta:xr,over:In},ee===Zt.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(nr))&&(ee=Zt.DragCancel)}z.current=null,Ur.unstable_batchedUpdates(()=>{E({type:ee}),_(Br.Uninitialized),Ue(null),F(null),K(null),At.current=null;const Hn=ee===Zt.DragEnd?"onDragEnd":"onDragCancel";if(nr){const Ka=X.current[Hn];Ka?.(nr),A({type:Hn,event:nr})}})}}},[v]),_e=h.useCallback((Oe,Qe)=>(qe,St)=>{const ce=qe.nativeEvent,Ee=v.get(St);if(z.current!==null||!Ee||ce.dndKit||ce.defaultPrevented)return;const Ye={active:Ee};Oe(qe,Qe.options,Ye)===!0&&(ce.dndKit={capturedBy:Qe.sensor},z.current=St,de(qe,Qe))},[v,de]),Ve=fQ(d,_e);SQ(d),_r(()=>{Ce&&N===Br.Initializing&&_(Br.Initialized)},[Ce,N]),h.useEffect(()=>{const{onDragMove:Oe}=X.current,{active:Qe,activatorEvent:qe,collisions:St,over:ce}=he.current;if(!Qe||!qe)return;const Ee={active:Qe,activatorEvent:qe,collisions:St,delta:{x:se.x,y:se.y},over:ce};Ur.unstable_batchedUpdates(()=>{Oe?.(Ee),A({type:"onDragMove",event:Ee})})},[se.x,se.y]),h.useEffect(()=>{const{active:Oe,activatorEvent:Qe,collisions:qe,droppableContainers:St,scrollAdjustedTranslate:ce}=he.current;if(!Oe||z.current==null||!Qe||!ce)return;const{onDragOver:Ee}=X.current,Ye=St.get(Y),Dt=Ye&&Ye.rect.current?{id:Ye.id,rect:Ye.rect.current,data:Ye.data,disabled:Ye.disabled}:null,ee={active:Oe,activatorEvent:Qe,collisions:qe,delta:{x:ce.x,y:ce.y},over:Dt};Ur.unstable_batchedUpdates(()=>{Ue(Dt),Ee?.(ee),A({type:"onDragOver",event:ee})})},[Y]),_r(()=>{he.current={activatorEvent:J,active:R,activeNode:P,collisionRect:fe,collisions:je,droppableRects:L,draggableNodes:v,draggingNode:Z,draggingNodeRect:ke,droppableContainers:C,over:He,scrollableAncestors:ae,scrollAdjustedTranslate:se},B.current={initial:ke,translated:fe}},[R,P,je,fe,v,Z,ke,L,C,He,ae,se]),cQ({...re,delta:O,draggingRect:fe,pointerCoordinates:Me,scrollableAncestors:ae,scrollableAncestorRects:pe});const Pe=h.useMemo(()=>({active:R,activeNode:P,activeNodeRect:Ce,activatorEvent:J,collisions:je,containerNodeRect:me,dragOverlay:Ge,draggableNodes:v,droppableContainers:C,droppableRects:L,over:He,measureDroppableContainers:ye,scrollableAncestors:ae,scrollableAncestorRects:pe,measuringConfiguration:te,measuringScheduled:xe,windowRect:rt}),[R,P,Ce,J,je,me,Ge,v,C,L,He,ye,ae,pe,te,xe,rt]),Je=h.useMemo(()=>({activatorEvent:J,activators:Ve,active:R,activeNodeRect:Ce,ariaDescribedById:{draggable:I},dispatch:E,draggableNodes:v,over:He,measureDroppableContainers:ye}),[J,Ve,R,Ce,E,I,v,He,ye]);return st.createElement(_A.Provider,{value:w},st.createElement(To.Provider,{value:Je},st.createElement(HA.Provider,{value:Pe},st.createElement(Eu.Provider,{value:Nt},u)),st.createElement(IQ,{disabled:l?.restoreFocus===!1})),st.createElement(jX,{...l,hiddenTextDescribedById:I}));function Ct(){const Oe=W?.autoScrollEnabled===!1,Qe=typeof c=="object"?c.enabled===!1:c===!1,qe=k&&!Oe&&!Qe;return typeof c=="object"?{...c,enabled:qe}:{enabled:qe}}}),LQ=h.createContext(null),TS="button",jQ="Draggable";function MQ(e){let{id:t,data:n,disabled:r=!1,attributes:s}=e;const i=xu(jQ),{activators:o,activatorEvent:l,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:p,over:f}=h.useContext(To),{role:m=TS,roleDescription:b="draggable",tabIndex:x=0}=s??{},y=c?.id===t,E=h.useContext(y?Eu:LQ),[A,w]=lc(),[N,_]=lc(),k=wQ(o,t),S=Zi(n);_r(()=>(p.set(t,{id:t,key:i,node:A,activatorNode:N,data:S}),()=>{const O=p.get(t);O&&O.key===i&&p.delete(t)}),[p,t]);const v=h.useMemo(()=>({role:m,tabIndex:x,"aria-disabled":r,"aria-pressed":y&&m===TS?!0:void 0,"aria-roledescription":b,"aria-describedby":d.draggable}),[r,m,x,y,b,d.draggable]);return{active:c,activatorEvent:l,activeNodeRect:u,attributes:v,isDragging:y,listeners:r?void 0:k,node:A,over:f,setNodeRef:w,setActivatorNodeRef:_,transform:E}}function FQ(){return h.useContext(HA)}const PQ="Droppable",BQ={timeout:25};function $Q(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:s}=e;const i=xu(PQ),{active:o,dispatch:l,over:c,measureDroppableContainers:u}=h.useContext(To),d=h.useRef({disabled:n}),p=h.useRef(!1),f=h.useRef(null),m=h.useRef(null),{disabled:b,updateMeasurementsFor:x,timeout:y}={...BQ,...s},E=Zi(x??r),A=h.useCallback(()=>{if(!p.current){p.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(E.current)?E.current:[E.current]),m.current=null},y)},[y]),w=yu({callback:A,disabled:b||!o}),N=h.useCallback((v,O)=>{w&&(O&&(w.unobserve(O),p.current=!1),v&&w.observe(v))},[w]),[_,k]=lc(N),S=Zi(t);return h.useEffect(()=>{!w||!_.current||(w.disconnect(),p.current=!1,w.observe(_.current))},[_,w]),h.useEffect(()=>(l({type:Zt.RegisterDroppable,element:{id:r,key:i,disabled:n,node:_,rect:f,data:S}}),()=>l({type:Zt.UnregisterDroppable,key:i,id:r})),[r]),h.useEffect(()=>{n!==d.current.disabled&&(l({type:Zt.SetDroppableDisabled,id:r,key:i,disabled:n}),d.current.disabled=n)},[r,i,n,l]),{active:o,rect:f,isOver:c?.id===r,node:_,over:c,setNodeRef:k}}function UQ(e){let{animation:t,children:n}=e;const[r,s]=h.useState(null),[i,o]=h.useState(null),l=cc(n);return!n&&!r&&l&&s(l),_r(()=>{if(!i)return;const c=r?.key,u=r?.props.id;if(c==null||u==null){s(null);return}Promise.resolve(t(u,i)).then(()=>{s(null)})},[t,r,i]),st.createElement(st.Fragment,null,n,r?h.cloneElement(r,{ref:o}):null)}const zQ={x:0,y:0,scaleX:1,scaleY:1};function HQ(e){let{children:t}=e;return st.createElement(To.Provider,{value:zA},st.createElement(Eu.Provider,{value:zQ},t))}const GQ={position:"fixed",touchAction:"none"},WQ=e=>n0(e)?"transform 250ms ease":void 0,qQ=h.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:s,children:i,className:o,rect:l,style:c,transform:u,transition:d=WQ}=e;if(!l)return null;const p=s?u:{...u,scaleX:1,scaleY:1},f={...GQ,width:l.width,height:l.height,top:l.top,left:l.left,transform:Aa.Transform.toString(p),transformOrigin:s&&r?FX(r,l):void 0,transition:typeof d=="function"?d(r):d,...c};return st.createElement(n,{className:o,style:f,ref:t},i)}),VQ=e=>t=>{let{active:n,dragOverlay:r}=t;const s={},{styles:i,className:o}=e;if(i!=null&&i.active)for(const[l,c]of Object.entries(i.active))c!==void 0&&(s[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,c));if(i!=null&&i.dragOverlay)for(const[l,c]of Object.entries(i.dragOverlay))c!==void 0&&r.node.style.setProperty(l,c);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&r.node.classList.add(o.dragOverlay),function(){for(const[c,u]of Object.entries(s))n.node.style.setProperty(c,u);o!=null&&o.active&&n.node.classList.remove(o.active)}},YQ=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Aa.Transform.toString(t)},{transform:Aa.Transform.toString(n)}]},KQ={duration:250,easing:"ease",keyframes:YQ,sideEffects:VQ({styles:{active:{opacity:"0"}}})};function ZQ(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:s}=e;return bu((i,o)=>{if(t===null)return;const l=n.get(i);if(!l)return;const c=l.node.current;if(!c)return;const u=UA(o);if(!u)return;const{transform:d}=Nn(o).getComputedStyle(o),p=RA(d);if(!p)return;const f=typeof t=="function"?t:XQ(t);return PA(c,s.draggable.measure),f({active:{id:i,data:l.data,node:c,rect:s.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:o,rect:s.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:s,transform:p})})}function XQ(e){const{duration:t,easing:n,sideEffects:r,keyframes:s}={...KQ,...e};return i=>{let{active:o,dragOverlay:l,transform:c,...u}=i;if(!t)return;const d={x:l.rect.left-o.rect.left,y:l.rect.top-o.rect.top},p={scaleX:c.scaleX!==1?o.rect.width*c.scaleX/l.rect.width:1,scaleY:c.scaleY!==1?o.rect.height*c.scaleY/l.rect.height:1},f={x:c.x-d.x,y:c.y-d.y,...p},m=s({...u,active:o,dragOverlay:l,transform:{initial:c,final:f}}),[b]=m,x=m[m.length-1];if(JSON.stringify(b)===JSON.stringify(x))return;const y=r?.({active:o,dragOverlay:l,...u}),E=l.node.animate(m,{duration:t,easing:n,fill:"forwards"});return new Promise(A=>{E.onfinish=()=>{y?.(),A()}})}}let kS=0;function QQ(e){return h.useMemo(()=>{if(e!=null)return kS++,kS},[e])}const JQ=st.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:s,transition:i,modifiers:o,wrapperElement:l="div",className:c,zIndex:u=999}=e;const{activatorEvent:d,active:p,activeNodeRect:f,containerNodeRect:m,draggableNodes:b,droppableContainers:x,dragOverlay:y,over:E,measuringConfiguration:A,scrollableAncestors:w,scrollableAncestorRects:N,windowRect:_}=FQ(),k=h.useContext(Eu),S=QQ(p?.id),v=GA(o,{activatorEvent:d,active:p,activeNodeRect:f,containerNodeRect:m,draggingNodeRect:y.rect,over:E,overlayNodeRect:y.rect,scrollableAncestors:w,scrollableAncestorRects:N,transform:k,windowRect:_}),O=l0(f),C=ZQ({config:r,draggableNodes:b,droppableContainers:x,measuringConfiguration:A}),M=O?y.setRef:void 0;return st.createElement(HQ,null,st.createElement(UQ,{animation:C},p&&S?st.createElement(qQ,{key:S,id:p.id,ref:M,as:l,activatorEvent:d,adjustScale:t,className:c,transition:i,rect:O,style:{zIndex:u,...s},transform:v},n):null))}),eJ=6e4,tJ=10080*60*1e3,nJ={P1:"error",P2:"warning",P3:"neutral"},rJ={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",deprecated:"bg-spur-text-muted"};function sJ(e,t){const n=new Date(e).getTime(),r=t-n,s=Math.floor(r/1e3);if(s<60)return"just now";const i=Math.floor(s/60);if(i<60)return`${i}m ago`;const o=Math.floor(i/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:`${Math.floor(l/30)}mo ago`}function WA({task:e,onClick:t}){const{attributes:n,listeners:r,setNodeRef:s,transform:i,isDragging:o}=MQ({id:e.wbs,data:{task:e}}),[l,c]=h.useState(Date.now());h.useEffect(()=>{const m=setInterval(()=>c(Date.now()),eJ);return()=>clearInterval(m)},[]);const u=i?{transform:Aa.Transform.toString(i),zIndex:o?50:void 0}:void 0,{subtaskProgress:d}=Ux(),p=d.get(e.wbs),f=e.updatedAt?l-new Date(e.updatedAt).getTime()>tJ:!1;return a.jsx(yx,{variant:"compact",asChild:!0,className:`group bg-spur-surface-2 hover:bg-spur-surface-3 rounded-xl border border-spur-border hover:border-spur-accent/60 shadow-xs hover:shadow-md cursor-pointer transition-all duration-150 w-full text-left ${o?"opacity-30":""}`,children:a.jsx("button",{ref:s,type:"button",style:u,onClick:()=>t(e.wbs),...r,...n,"aria-roledescription":"draggable card",children:a.jsxs(Ex,{className:"p-3 gap-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-mono font-semibold text-spur-text",children:[a.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ring-1 ring-spur-surface-2 ${rJ[e.status]??"bg-spur-text-faint"}`,"data-status":e.status,"aria-hidden":"true"}),e.wbs]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[e.estimateHours!==void 0&&a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted flex items-center gap-0.5",title:`Estimated: ${e.estimateHours}h`,children:[a.jsx("span",{className:"text-spur-text-faint text-[9px]",children:"⏱"}),e.estimateHours,"h"]}),e.priority&&a.jsx(tt,{variant:nJ[e.priority]??"outline",size:"xs",className:"font-mono text-[10px] font-semibold",children:e.priority})]})]}),a.jsx("p",{className:"text-sm font-medium text-spur-text leading-snug line-clamp-2 group-hover:text-spur-accent transition-colors",children:e.name}),a.jsxs("div",{className:"flex gap-1.5 flex-wrap items-center pt-0.5",children:[p&&p.total>0&&a.jsxs("div",{className:"flex items-center gap-1.5 min-w-[3.5rem]","data-testid":"subtask-progress",title:"subtasks done/total",children:[a.jsx("div",{className:"h-1 flex-1 rounded-full bg-spur-border/60 overflow-hidden",children:a.jsx("div",{className:"h-full bg-spur-success",style:{width:`${Math.round(p.done/p.total*100)}%`}})}),a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted shrink-0",children:[p.done,"/",p.total]})]}),e.type&&e.type!=="task"&&a.jsx(tt,{variant:"outline",size:"xs",className:"text-[10px] font-mono border-spur-border text-spur-text-muted",children:e.type}),e.template&&e.template!=="feature-impl"&&a.jsx(tt,{variant:"outline",size:"xs",className:"text-[10px] font-mono border-spur-accent/40 text-spur-accent bg-spur-accent/5 font-medium",children:e.template}),e.featureId&&a.jsx(tt,{variant:"outline",size:"xs",className:"text-[10px] font-mono border-spur-border text-spur-text-muted",children:e.featureId}),e.dependencyCount!==void 0&&e.dependencyCount>0&&a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted flex items-center gap-0.5",title:`${e.dependencyCount} dependenc${e.dependencyCount===1?"y":"ies"}`,children:[a.jsx("span",{className:"text-spur-text-faint text-[9px]",children:"⛓"}),e.dependencyCount]}),e.updatedAt&&a.jsx("span",{className:`text-xs font-mono ml-auto ${f?"text-spur-text-faint":"text-spur-text-muted"}`,title:e.updatedAt,children:sJ(e.updatedAt,l)})]})]})})})}function aJ({status:e,label:t,tasks:n,onCardClick:r,sortDir:s,onSortToggle:i}){const{setNodeRef:o,isOver:l}=$Q({id:e,data:{status:e}});return a.jsxs("section",{ref:o,"aria-label":`${t} column`,className:`flex flex-col flex-1 min-w-[16rem] rounded-xl border transition-colors duration-200 overflow-hidden ${l?"bg-spur-surface/40 border-spur-accent shadow-lg ring-1 ring-spur-accent/30":"bg-transparent border-spur-border"}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-3.5 py-2.5 border-b border-spur-border shrink-0 bg-spur-surface",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:[ef(e)," ",t]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(tt,{variant:"ghost",size:"sm",className:"font-mono text-spur-text-muted bg-spur-surface-2 border border-spur-border/80 px-2 py-0.5",children:n.length}),i&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"h-6 w-6 p-0 flex items-center justify-center text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-2 rounded-md transition-colors",onClick:i,"aria-label":`Sort ${t} by WBS`,title:`Sort ${t}: ${s==="asc"?"WBS ↓":s==="desc"?"WBS ↑":"none"}`,children:s==="asc"?"↓":s==="desc"?"↑":"⇅"})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-2 min-h-[4rem]",children:[n.map(c=>a.jsx(WA,{task:c,onClick:r},c.wbs)),n.length===0&&a.jsx("div",{className:"flex items-center justify-center h-20 text-xs text-spur-text-muted italic border border-dashed border-spur-border/60 rounded-lg my-1 bg-spur-surface/30",children:"No tasks"})]})]})}const iJ=h.lazy(()=>Ak(()=>import("./TaskDetail.C3fD4iNx.js"),__vite__mapDeps([2,3,1,4,5]))),oJ=Pn,qA="docs/tasks",AS="spur:detail-width",lJ=new Set(["blocked","cancelled","deprecated"]);function cJ(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 VA(e){const{onSelectTask:t,filters:n,folder:r,hiddenColumns:s,onConnectionChange:i,onSyncChange:o}=e,[l,c]=h.useState({}),[u,d]=h.useState(qA),[p,f]=h.useState(null),[m,b]=h.useState(()=>{const V=typeof window<"u"?Math.min(1728,window.innerWidth*.8):1728;if(typeof window>"u")return V;try{const te=Number.parseFloat(window.localStorage.getItem(AS)??"");if(Number.isFinite(te)&&te>0)return Math.min(te,window.innerWidth*.8)}catch{}return V}),x=r??u,y=s??lJ,E=h.useCallback(()=>xt.task.list({folder:x}),[x]),{tasks:A,loading:w,error:N,connected:_,lastSyncAt:k,setTasks:S,store:v}=Ux(E),[O,C]=h.useState(null);h.useEffect(()=>{i?.(_)},[_,i]),h.useEffect(()=>{o?.(k)},[k,o]),h.useEffect(()=>{typeof xt.task.folders=="function"&&xt.task.folders({}).then(V=>{const{data:te,activeFolder:L}=V,ye=L??te?.[0]?.path;ye!==void 0&&d(ye)}).catch(()=>{})},[]),h.useEffect(()=>{document.documentElement.style.setProperty("--detail-w",`${m}px`)},[m]),h.useEffect(()=>{if(!p)return;const V=te=>{te.key==="Escape"&&f(null)};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[p]);const M=Ji();h.useEffect(()=>{const V=M.pathname.split("/"),te=V.indexOf("tasks"),L=te>=0?V[te+1]:void 0;L&&/^\d{4}$/.test(L)&&f(L)},[M.pathname]);const B=hS(o0,{activationConstraint:{distance:5}}),R=hS(a0),z=MX(B,R),W=cJ(A,n),F=V=>{c(te=>{const L={...te};return te[V]==="asc"?L[V]="desc":te[V]==="desc"?delete L[V]:L[V]="asc",L})},J=V=>{const te=W.filter(ye=>ye.status===V),L=l[V]??"desc";return[...te].sort((ye,xe)=>{const P=ye.wbs.localeCompare(xe.wbs);return L==="asc"?P:-P})},K=V=>A.find(te=>te.wbs===V),X=V=>{C(String(V.active.id))},I=V=>{C(null);const{active:te,over:L}=V;if(!L)return;const ye=String(te.id),xe=String(L.id),P=K(ye);if(!P||P.status===xe)return;const oe=[...A];S(re=>re.map(H=>H.wbs===ye?{...H,status:xe}:H)),xt.task.transition({wbs:ye,toStatus:xe}).catch(re=>{S(oe);const H=re instanceof Error?re.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:H}}))})};return w?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(ln,{size:"lg",className:"text-spur-accent"})}):N?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center text-spur-text-muted",children:[a.jsx("p",{className:"text-lg font-semibold",children:"Failed to load tasks"}),a.jsx("p",{className:"text-sm",children:N.message})]})}):a.jsx(Mk.Provider,{value:v,children:a.jsxs(OQ,{sensors:z,onDragStart:X,onDragEnd:I,children:[a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsx("div",{className:"flex gap-3 overflow-x-auto h-full p-4",children:oJ.filter(V=>!y.has(V)).map(V=>a.jsx(aJ,{status:V,label:V,tasks:J(V),onCardClick:te=>{f(te),t(te)},sortDir:l[V],onSortToggle:()=>F(V)},V))}),p&&a.jsxs(a.Fragment,{children:[a.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:()=>f(null)}),a.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:[a.jsx(ka,{targetVar:"--detail-w",onResizeEnd:V=>{const te=Math.max(576,Math.min(V,window.innerWidth*.8));b(te);try{window.localStorage.setItem(AS,String(te))}catch{}},direction:"horizontal",invert:!0}),a.jsx("div",{className:"flex flex-col flex-1 overflow-hidden",children:a.jsx("div",{className:"flex-1 overflow-y-auto","data-testid":"detail-body",children:(()=>{const V=A.find(te=>te.wbs===p);return V?a.jsx(h.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:"Loading detail..."}),children:a.jsx(iJ,{task:V,onClose:()=>f(null),onTransition:(te,L)=>{S(ye=>ye.map(xe=>xe.wbs===te?{...xe,status:L}:xe)),xt.task.transition({wbs:te,toStatus:L}).catch(ye=>{const xe=ye instanceof Error?ye.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:xe}}))})}})}):null})()})})]})]})]}),a.jsx(JQ,{dropAnimation:null,children:O?(()=>{const V=K(O);return V?a.jsx("div",{className:"opacity-90",children:a.jsx(WA,{task:V,onClick:()=>{}})}):null})():null})]})})}const Md=[{id:"kanban",label:"Kanban",component:VA}];function YA(){const[e,t]=Ca(),n=Ji(),r=mc(),s=h.useMemo(()=>{const c=n.pathname.split("/"),u=c.indexOf("tasks"),d=u>=0?c[u+1]:void 0;return d&&/^\d{4}$/.test(d)?d:e.get("selected")},[n.pathname,e]),i=h.useMemo(()=>{const c={},u=e.get("status"),d=e.get("feature"),p=e.get("parent"),f=e.get("assignee"),m=e.get("folder");return u!==null&&(c.status=u),d&&(c.featureId=d),p&&(c.parentWbs=p),f&&(c.assignee=f),m&&(c.folder=m),c},[e]);return{selected:s,filters:i,selectTask:c=>{const u=new URLSearchParams(e);u.delete("selected");const d=u.toString(),p=c?`/board/tasks/${c}`:"/board/tasks";r(`${p}${d?`?${d}`:""}`,{replace:!0})},setFilter:(c,u)=>{t(d=>{const p=new URLSearchParams(d);return c==="feature"&&p.delete("parent"),c==="parent"&&p.delete("feature"),u!==null?p.set(c,u):p.delete(c),p},{replace:!0})}}}function uJ(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 dJ(){const{selectTask:e,setFilter:t,filters:n}=YA(),[r,s]=h.useState(qA),[i,o]=h.useState([]),[l,c]=h.useState("kanban"),[u,d]=h.useState(!1),[p,f]=h.useState(""),[m,b]=h.useState(!1),[x,y]=h.useState(void 0),E=n.folder??r,A=new Set(n.status===void 0?Pn.filter(S=>S!=="blocked"&&S!=="cancelled"&&S!=="deprecated"):n.status.split(",").filter(S=>Pn.some(v=>v===S))),w=new Set(Pn.filter(S=>!A.has(S)));h.useEffect(()=>{f(n.featureId??n.parentWbs??"")},[n.featureId,n.parentWbs]),h.useEffect(()=>{typeof xt.task.folders=="function"&&xt.task.folders({}).then(S=>{const{data:v,activeFolder:O}=S,C=O??v?.[0]?.path;v&&o(v),C!==void 0&&s(C)}).catch(()=>{})},[]);const N=S=>{const v=new Set(A);v.has(S)?v.delete(S):v.add(S),t("status",Pn.filter(O=>v.has(O)).join(","))},_=S=>{S.preventDefault();const v=uJ(p);if(v.kind==="navigate"){e(v.wbs),f("");return}t(v.key,v.value||null)},k=(Md.find(S=>S.id===l)??Md[0]).component;return a.jsxs("div",{className:"task-kanban flex flex-col h-full",children:[a.jsx("header",{className:"mx-auto w-full max-w-[1600px] shrink-0 px-4 pt-3",children:a.jsxs("div",{className:"flex flex-nowrap items-center justify-between gap-4 border-b border-spur-border pb-3",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[a.jsx(Rr,{id:"tasks",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight text-spur-text",children:"Tasks"}),a.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-spur-border bg-spur-surface-2 px-2.5 py-0.5 text-xs text-spur-text-muted font-mono",role:"status","data-testid":"tasks-live-chip",children:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${m?"bg-spur-success":"bg-spur-error"}`,"aria-hidden":"true"}),"last sync ",x?new Date(x).toLocaleString():"—"]})]}),a.jsx("p",{className:"text-xs text-spur-text-muted mt-0.5",children:"Task corpus, kanban lanes, and phase filters"})]})]}),a.jsxs("div",{className:"flex min-w-0 flex-nowrap items-center gap-2.5 overflow-x-auto",children:[a.jsx(qr,{variant:"ghost",size:"xs",className:"text-xs shrink-0 w-44 bg-spur-surface-2 border border-spur-border rounded-lg text-spur-text",value:E,onChange:S=>t("folder",S.target.value),"aria-label":"Task phase folder",children:i.map(S=>a.jsx("option",{value:S.path,children:S.label?`${S.label} (${S.path})`:S.path},S.path))}),a.jsx("div",{className:"flex shrink-0 items-center gap-1 bg-spur-surface-2 border border-spur-border px-2 py-1 rounded-xl",children:Pn.map(S=>a.jsxs("label",{htmlFor:`tasks-status-${S}`,className:"flex items-center gap-1.5 px-1.5 py-0.5 rounded-md hover:bg-spur-surface-3 transition-colors cursor-pointer",children:[a.jsx(Sx,{id:`tasks-status-${S}`,size:"xs",checked:!w.has(S),onChange:()=>N(S)}),a.jsxs("span",{className:"text-[11px] font-medium text-spur-text-muted select-none",children:[ef(S)," ",S]})]},S))}),a.jsx("form",{onSubmit:_,className:"flex shrink-0 items-center",children:a.jsx(Vn,{"aria-label":"Filter by WBS or feature",type:"text",placeholder:"WBS or feature",variant:"bordered",size:"xs",className:"w-36 bg-spur-surface-2 border-spur-border text-spur-text",value:p,onChange:S=>f(S.target.value)})}),a.jsx(Ie,{variant:"primary",size:"sm",className:"shrink-0 font-medium",onClick:()=>d(!0),children:"+ New Task"}),a.jsx("div",{className:"flex shrink-0 items-center gap-1 bg-spur-surface-2 border border-spur-border p-1 rounded-xl",children:Md.map(S=>a.jsx("button",{type:"button",className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all ${l===S.id?"bg-primary text-primary-content font-bold shadow-sm":"text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-3"}`,onClick:()=>c(S.id),children:S.label},S.id))})]})]})}),a.jsx(Lk,{folder:E}),a.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:a.jsx(k,{onSelectTask:e,filters:n,folder:E,hiddenColumns:w,onConnectionChange:b,onSyncChange:y})}),a.jsx(Ok,{open:u,onClose:()=>d(!1),onCreated:()=>{},folder:E})]})}function pJ(e,t){xt.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 fJ(){const{filters:e,selectTask:t}=YA();return a.jsx("div",{className:"task-kanban flex flex-col h-full",children:a.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:a.jsx(VA,{onSelectTask:t,filters:e})})})}const mJ={id:"tasks",name:"Tasks",icon:"📋",route:"tasks",component:dJ,sidebarLabel:"Tasks",description:"Task kanban, lifecycle status, and per-task detail",order:40},hJ=Object.freeze(Object.defineProperty({__proto__:null,TaskKanbanView:fJ,module:mJ,transition:pJ},Symbol.toStringTag,{value:"Module"}));function KA(e){return e===null||typeof e!="object"?null:"module"in e&&CS(e.module)?e.module:"default"in e&&CS(e.default)?e.default:null}function CS(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 ZA(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 gJ(e){const t=[],n=e("./*/index.{ts,tsx}",{eager:!0});for(const r of Object.values(n)){const s=KA(r);s&&t.push(s)}return t.sort((r,s)=>r.id.localeCompare(s.id)),t.sort(ZA),t}function bJ(){try{return gJ(()=>Object.assign({"./designs/index.tsx":Mq,"./features/index.tsx":cV,"./history/index.tsx":HV,"./observability/index.tsx":RK,"./plans/index.tsx":UK,"./projects/index.tsx":GZ,"./search/index.tsx":XZ,"./settings/index.tsx":wX,"./task-kanban/index.tsx":hJ}))}catch(s){if(typeof require!="function")throw s}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 xJ(r,{readdirSync:(s,i)=>e.readdirSync(s,i),tryRequire:s=>require(s)})}function xJ(e,t){const n=require("node:path"),r=[];let s=[];try{s=t.readdirSync(e,{withFileTypes:!0})}catch{return r}const i=s.filter(o=>o.isDirectory()).map(o=>o.name).sort((o,l)=>o.localeCompare(l));for(const o of i)for(const l of["tsx","ts"]){const c=n.join(e,o,`index.${l}`);try{const u=t.tryRequire(c),d=KA(u);if(d){r.push(d);break}}catch{}}return r.sort(ZA),r}function XA(e,t){const n=new Set(t?.disabled??[]),r=e.slice(),s=new Set(n),i=t?.defaultModuleId;function o(){return r.filter(l=>!s.has(l.id))}return yJ(r),{get modules(){return o()},getModule(l){return o().find(c=>c.id===l)},get defaultModule(){const l=o();if(i){const c=l.find(u=>u.id===i);if(c)return c}return l[0]},disableModule(l){s.add(l)},enableModule(l){s.delete(l)},getEnabledModules(){return o().map(l=>l.id)}}}function yJ(e){const t=new Map,n=new Map;for(const r of e){const s=t.get(r.id);if(s!==void 0)throw new Error(`Duplicate module id "${r.id}" discovered in two sources: ${s} and ${hl(r)}`);t.set(r.id,hl(r));const i=n.get(r.route);if(i!==void 0)throw new Error(`Duplicate module route "${r.route}" discovered in two sources: ${i} and ${hl(r)}`);n.set(r.route,hl(r))}}function hl(e){return e.id}const c0=XA(bJ(),{disabled:Lj,defaultModuleId:jj}),Qi=c0;c0.modules;c0.defaultModule;const QA=h.createContext({registry:Qi,hostDiagnostics:[]});function EJ({value:e,children:t}){return a.jsx(QA.Provider,{value:e,children:t})}function JA(){return h.useContext(QA)}const Up="spur-board-layout-v3",_S="spur-board-layout-v2",IS="spur-board-layout",ir={version:3,sidebarWidth:240,rightPanelWidth:320,sidebarCollapsed:!0,rightPanelCollapsed:!0};function SJ(){try{const e=localStorage.getItem(Up);if(e){const s=JSON.parse(e);return{version:3,sidebarWidth:typeof s.sidebarWidth=="number"?s.sidebarWidth:ir.sidebarWidth,rightPanelWidth:typeof s.rightPanelWidth=="number"?s.rightPanelWidth:ir.rightPanelWidth,sidebarCollapsed:typeof s.sidebarCollapsed=="boolean"?s.sidebarCollapsed:ir.sidebarCollapsed,rightPanelCollapsed:typeof s.rightPanelCollapsed=="boolean"?s.rightPanelCollapsed:ir.rightPanelCollapsed}}const t=localStorage.getItem(_S),n=localStorage.getItem(IS),r=t||n;if(r){const s=JSON.parse(r),i={version:3,sidebarWidth:typeof s.sidebarWidth=="number"?s.sidebarWidth:ir.sidebarWidth,rightPanelWidth:typeof s.rightPanelWidth=="number"?s.rightPanelWidth:ir.rightPanelWidth,sidebarCollapsed:ir.sidebarCollapsed,rightPanelCollapsed:typeof s.rightPanelCollapsed=="boolean"?s.rightPanelCollapsed:ir.rightPanelCollapsed};try{localStorage.setItem(Up,JSON.stringify(i)),localStorage.removeItem(_S),localStorage.removeItem(IS)}catch{}return i}return{...ir}}catch{return{...ir}}}function wJ(e){try{localStorage.setItem(Up,JSON.stringify({...e,version:3}))}catch{}}const eC="spur.board.projects.draft.v1";function la(e){return{path:e,text:"",revision:0}}function vJ(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;const t=e;if(typeof t.path!="string"||typeof t.text!="string"||typeof t.revision!="number"||!Number.isFinite(t.revision))return null;const n={path:t.path,text:t.text,revision:t.revision};return t.pending!==void 0&&(n.pending=t.pending),n}function NJ(e){try{const t=globalThis.localStorage?.getItem(eC);if(t==null)return la(e);const n=vJ(JSON.parse(t));return n===null||n.path!==e?(Rl(la(e)),la(e)):n}catch{return la(e)}}function Rl(e){try{globalThis.localStorage?.setItem(eC,JSON.stringify(e))}catch{}}const TJ={draft:la(""),setText:()=>{},persistPending:()=>{},clearSubmitted:()=>{}},tC=h.createContext(TJ);function kJ(){return h.useContext(tC)}function AJ({children:e}){const n=Ms().path,[r,s]=h.useState(()=>la(""));h.useEffect(()=>{n!==null&&s(NJ(n))},[n]);const i=h.useMemo(()=>({draft:r,setText:o=>s(l=>{if(l.path!==n)return l;const c={...l,text:o,revision:l.revision+1};return Rl(c),c}),persistPending:o=>s(l=>{if(l.path!==r.path||l.revision!==r.revision)return l;const c={...l,pending:{requestKey:o,revision:l.revision}};return Rl(c),c}),clearSubmitted:(o,l)=>s(c=>{if(c.path!==l||c.revision!==o)return c;const u={path:c.path,text:"",revision:c.revision+1};return Rl(u),u})}),[r,n]);return a.jsx(tC.Provider,{value:i,children:e})}function CJ(){const[e,t]=h.useState([]);return h.useEffect(()=>{if(typeof window>"u")return;const n=r=>{const i=r.detail?.message||"An error occurred",o=`${Date.now()}-${Math.random().toString(36).slice(2,7)}`;t(l=>[...l,{id:o,message:i}]),setTimeout(()=>{t(l=>l.filter(c=>c.id!==o))},5e3)};return window.addEventListener("api-error",n),()=>{window.removeEventListener("api-error",n)}},[]),e.length===0?null:a.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=>a.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:[a.jsx("span",{className:"flex-1 break-words",children:n.message}),a.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(s=>s.id!==n.id)),"aria-label":"Close error toast",children:"×"})]},n.id))})}const _J="Enter",IJ=229;function RJ(e){return e.key===_J&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==IJ}const DJ=[{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"]}],OJ={sending:{icon:"…",label:"Sending",meaning:"the request is being stored",action:"wait for the mailbox",tone:"warn"},queued:{icon:"○",label:"Queued",meaning:"the orchestrator has not claimed it yet",action:"wait for the orchestrator",tone:"warn"},working:{icon:"◐",label:"In progress",meaning:"a member claimed it",action:"wait for the run to finish",tone:"warn"},delivered:{icon:"✓",label:"Delivered",meaning:"the member consumed the request",action:"read the reply in the Inbox tab",tone:"ok"},failed:{icon:"✕",label:"Failed",meaning:"delivery did not start or the run errored",action:"resend, or read the error in the Inbox tab",tone:"err"},unresolved:{icon:"!",label:"Unresolved",meaning:"the run left no verified outcome",action:"check the Inbox tab for the hold reason",tone:"warn"},absent:{icon:"·",label:"No receipt",meaning:"the request did not reach an inbox",action:"check the project binding and resend",tone:"warn"}};function LJ(e,t){return t?"sending":e===null?"absent":e.status==="failed"||["failed","errored","cancelled"].includes(e.runStatus??"")?"failed":e.runStatus==="running"?"working":e.reason!==null&&e.reason!==""?e.status==="delivered"?"unresolved":"working":e.status==="delivered"?"delivered":e.status==="claimed"?"working":"queued"}const jJ=[{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 MJ(e){if(!e)return!0;const{state:t,instanceId:n}=e.orchestrator;return t==="missing"||t==="unresolvable"||!n}function FJ({activeModule:e}){const[t,n]=h.useState(!1),[r,s]=h.useState(!1),[i,o]=h.useState(null),[l,c]=h.useState("auto"),[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,b]=h.useState(0),[x,y]=h.useState("all"),[E,A]=h.useState(DJ),w=h.useMemo(()=>{const Z=new Map;for(const Re of E){if(Array.isArray(Re.tags)){for(const rt of Re.tags)if(rt&&typeof rt=="string"){const ae=rt.trim().toLowerCase();Z.set(ae,(Z.get(ae)??0)+1)}}if(Re.category){const rt=Re.category.trim().toLowerCase();Z.set(rt,(Z.get(rt)??0)+1)}}const ke=["sp","cc","kk","wt","git","dev","sys","harness","builtin"];return["all",...Array.from(Z.keys()).sort((Re,rt)=>{const ae=ke.indexOf(Re),pe=ke.indexOf(rt);if(ae!==-1&&pe!==-1)return ae-pe;if(ae!==-1)return-1;if(pe!==-1)return 1;const De=(Z.get(rt)??0)-(Z.get(Re)??0);return De!==0?De:Re.localeCompare(rt)})]},[E]),N=Ms(),_=h.useRef({path:N.path,generation:0,inFlight:!1});_.current.path!==N.path&&(_.current={path:N.path,generation:_.current.generation+1,inFlight:!1}),h.useEffect(()=>()=>{_.current.generation+=1},[]);const{draft:k,setText:S,persistPending:v,clearSubmitted:O}=kJ(),C=N.fleet?.orchestrator?.instanceId,M=MJ(N.fleet),[B,R]=h.useState(null),[z,W]=h.useState(!1),[F,J]=h.useState(null),[K,X]=h.useState(0);h.useEffect(()=>{N.path,s(!1),o(null),R(null),W(!1),J(null)},[N.path]),h.useEffect(()=>{if(i===null)return;let Z=!1;return(async()=>{try{const ke=await xt.inbox.requests({messageId:i});if(Z)return;const Fe=ke.find(Re=>Re.messageId===i);Fe!==void 0&&R({status:Fe.status,reason:Fe.reason,runStatus:Fe.runStatus}),W(!1)}catch{Z||W(!0)}})(),()=>{Z=!0}},[i,K]),h.useEffect(()=>{if(typeof EventSource>"u")return;const Z=new EventSource(`${it()}/events/planning`);return Z.onmessage=ke=>{try{const Fe=JSON.parse(ke.data).eventName;typeof Fe=="string"&&Fe.startsWith("message.")&&X(Re=>Re+1)}catch{}},()=>Z.close()},[]);const I=LJ(B,r),V=OJ[I],te=r||i!==null,L=te?`${V.label} — Next: ${V.action}`:"";h.useEffect(()=>{if(i===null||N.path===null||B===null||["completed","exited","failed","errored","cancelled"].includes(B.runStatus??"")||B.status!=="queued"&&B.status!=="claimed"&&B.runStatus!=="running")return;const Z=setInterval(()=>X(ke=>ke+1),2e3);return()=>clearInterval(Z)},[i,N.path,B]);const ye=h.useRef(null);h.useEffect(()=>{let Z=!0;return(async()=>{try{const ke=await Xe(new Request(`${it()}/agent/commands`));if(ke.ok){const Fe=await ke.json();Z&&Array.isArray(Fe.commands)&&Fe.commands.length>0&&A(Fe.commands)}}catch{}})(),()=>{Z=!1}},[]),h.useEffect(()=>{if(!u)return;const Z=ke=>{ye.current&&!ye.current.contains(ke.target)&&d(!1)};return document.addEventListener("click",Z),()=>document.removeEventListener("click",Z)},[u]),h.useEffect(()=>{k.text.startsWith("/")&&f(!1)},[k.text]);const xe=k.text.trim().toLowerCase(),P=xe.startsWith("/")&&!p,oe=P?E.filter(Z=>{const ke=x==="all"||Array.isArray(Z.tags)&&Z.tags.map(rt=>rt.toLowerCase()).includes(x)||Z.category.toLowerCase()===x,Fe=xe.startsWith("/")?xe.slice(1):xe,Re=Z.name.toLowerCase().startsWith(xe)||Z.name.toLowerCase().includes(Fe)||!!Z.argumentHint?.toLowerCase().includes(Fe)||Z.description.toLowerCase().includes(Fe)||Array.isArray(Z.tags)&&Z.tags.some(rt=>rt.toLowerCase().includes(Fe));return ke&&Re}):[],re=P&&oe.length>0,H=Z=>{S(`${Z} `),f(!0),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},Ce=Z=>{const ke=k.text,Fe=ke.length>0&&!ke.endsWith(" ")?`${ke} ${Z}`:`${ke}${Z}`;S(Fe),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},me=()=>l==="auto"?C:N.fleet?.members?.find(ke=>ke.role===l||ke.instanceId===l)?.instanceId??C,he=async()=>{const Z=N.path,ke=me();if(Z===null||k.path!==Z||ke===void 0||_.current.inFlight)return;const Fe=++_.current.generation,Re=()=>_.current.path===Z&&_.current.generation===Fe,rt=k.text;if(rt.trim().length===0)return;_.current.inFlight=!0;const ae={text:rt,revision:k.revision},pe=k.pending!==void 0&&typeof k.pending.requestKey=="string"&&k.pending.requestKey.length>0&&k.pending.revision===k.revision?k.pending:void 0,De=pe!==void 0?pe.requestKey:crypto.randomUUID();v(De),J(null),s(!0),o(null),R(null),f(!0);try{const Me=await xt.inbox.send({...ke!==null?{to:ke}:{},body:ae.text,requestKey:De,...Z!==null?{projectPath:Z}:{}});if(!Re())return;R({status:Me.message.status,reason:null}),o(Me.message.id),O(ae.revision,Z)}catch(Me){Re()&&J(Me instanceof Error?Me.message:"the message was not sent")}finally{Re()&&(_.current.inFlight=!1,s(!1))}};if(!t)return a.jsxs(a.Fragment,{children:[a.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:L}),a.jsx(Ie,{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 Ne=N.fleet?.members&&N.fleet.members.length>0?[{id:"auto",label:"auto",desc:"Orchestrator auto-dispatch (default)"},...N.fleet.members.map(Z=>({id:Z.instanceId,label:Z.role||Z.instanceId,desc:`${Z.executor}${Z.model?` · ${Z.model}`:""}`}))]:jJ,Ge=k.text.trim().length===0||l==="auto"&&M;return a.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:[a.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:L}),re&&a.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:[a.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:[a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsx("span",{className:"font-mono text-spur-accent font-semibold text-[13px]",children:"/"}),a.jsx("span",{className:"font-mono text-[12px] font-medium text-spur-text",children:"Commands"}),a.jsxs("span",{className:"text-[11px] font-mono text-spur-text-muted",children:[oe.length," available"]})]}),a.jsx("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar max-w-[65%] py-0.5",role:"tablist",children:w.slice(0,10).map(Z=>a.jsx("button",{type:"button",role:"tab","aria-selected":x===Z,onClick:()=>y(Z),className:`px-2 py-0.5 rounded text-[11px] font-mono transition-colors shrink-0 cursor-pointer ${x===Z?"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:Z==="all"?"All":Z},Z))})]}),a.jsx("div",{className:"flex flex-col py-1.5 px-2 max-h-[260px] overflow-y-auto",role:"listbox",children:oe.map((Z,ke)=>{const Fe=ke===m;return a.jsxs("button",{type:"button",role:"option","aria-selected":Fe,onClick:()=>H(Z.name),title:Z.description,className:`flex items-center w-full text-left px-3 py-2 rounded-lg cursor-pointer transition-colors ${Fe?"bg-spur-surface text-spur-accent font-medium":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 font-mono text-[13px] min-w-0 truncate flex-1",children:[a.jsx("span",{className:Fe?"font-semibold text-spur-accent":"font-medium text-spur-text",children:Z.name}),Z.argumentHint?a.jsx("span",{className:`font-mono text-xs truncate ${Fe?"text-spur-text/80":"text-spur-text-muted"}`,children:Z.argumentHint}):a.jsx("span",{className:`font-sans text-xs italic truncate ${Fe?"text-spur-text/60":"text-spur-text-muted/60"}`,children:Z.description})]}),a.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-2",children:(Z.tags&&Z.tags.length>0?Z.tags.slice(0,2):[Z.category]).map(Re=>a.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:Re},Re))})]},Z.name)})}),a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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:"↑↓"}),a.jsx("span",{children:"navigate"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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"}),a.jsx("span",{children:"complete"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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:"↵"}),a.jsx("span",{children:"execute"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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"}),a.jsx("span",{children:"dismiss"})]})]}),a.jsxs("div",{className:"flex items-center gap-3 font-mono text-[11px]",children:[a.jsxs("button",{type:"button",onClick:()=>Ce("@"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Reference files",children:[a.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"@"}),a.jsx("span",{className:"group-hover:text-spur-text",children:"files"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("button",{type:"button",onClick:()=>Ce("#"),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:[a.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"#"}),a.jsx("span",{className:"group-hover:text-spur-text",children:"context"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("button",{type:"button",onClick:()=>Ce("!"),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:[a.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"!"}),a.jsx("span",{className:"group-hover:text-spur-text",children:"bash"})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-spur-text-muted font-mono text-sm select-none font-bold pl-1",children:">"}),a.jsxs("div",{className:"relative shrink-0",ref:ye,children:[a.jsxs("button",{type:"button",onClick:()=>d(Z=>!Z),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:[a.jsx("span",{className:"text-spur-text-muted font-sans text-[11px]",children:"to:"}),a.jsx("span",{className:"font-semibold",children:Ne.find(Z=>Z.id===l)?.label??l}),a.jsx("span",{className:"text-spur-text-muted text-[10px] group-hover:text-spur-text transition-colors",children:"▾"})]}),u&&a.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:[a.jsx("div",{className:"px-2.5 py-1 text-[10px] font-mono text-spur-text-muted uppercase tracking-wider",children:"Dispatch Target"}),Ne.map(Z=>a.jsxs("button",{type:"button",onClick:()=>{c(Z.id),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===Z.id?"bg-spur-accent/15 text-spur-accent font-semibold":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[a.jsxs("div",{className:"flex flex-col",children:[a.jsx("span",{className:"font-medium text-spur-text",children:Z.label}),a.jsx("span",{className:"text-[10px] text-spur-text-muted",children:Z.desc})]}),l===Z.id&&a.jsx("span",{className:"text-[12px]",children:"✓"})]},Z.id))]})]}),a.jsx(aG,{variant:"ghost",rows:1,value:k.text,onChange:Z=>S(Z.target.value),onKeyDown:Z=>{if(re&&oe.length>0){if(Z.key==="ArrowDown"){Z.preventDefault(),b(ke=>(ke+1)%oe.length);return}if(Z.key==="ArrowUp"){Z.preventDefault(),b(ke=>(ke-1+oe.length)%oe.length);return}if(Z.key==="Tab"){Z.preventDefault();const ke=oe[m];ke&&H(ke.name);return}if(Z.key==="Escape"){Z.preventDefault(),f(!0);return}}RJ(Z)&&(Ge||(Z.preventDefault(),he()))},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"}),a.jsx(Ie,{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"&&M&&a.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."}),F!==null&&a.jsxs("div",{role:"alert",className:"rounded-lg px-2.5 py-1 text-xs bg-spur-error/10 text-spur-error",children:["Not sent: ",F]}),te&&a.jsxs("div",{"data-receipt-state":I,role:"status",className:`rounded-lg px-2.5 py-1 text-xs ${V.tone==="err"?"bg-spur-error/10 text-spur-error":V.tone==="warn"?"bg-spur-warning/10 text-spur-warning":"bg-spur-success/10 text-spur-success"}`,children:[a.jsx("span",{"aria-hidden":"true",className:"mr-1",children:V.icon}),a.jsx("span",{className:"font-medium",children:V.label}),a.jsxs("span",{className:"text-spur-text-muted",children:[" ","— ",V.meaning," Next: ",V.action,"."]}),z&&a.jsx("span",{className:"text-spur-text-muted",children:" (results feed unavailable)"})]})]})}function PJ(e){return u0(e.host)?`${e.name} (${e.host?.trim()})`:e.name}function u0(e){const t=e?.trim().toLowerCase();return t!==void 0&&t!==""&&t!=="localhost"&&t!=="127.0.0.1"&&t!=="::1"}function BJ(e){return e.port<=0||!e.running&&!u0(e.host)?null:`http://${e.host?.trim()||"localhost"}:${e.port}/board`}async function $J(e,t){return Promise.all(e.map(async n=>!n.running&&n.port>0&&u0(n.host)?{...n,running:await t(`http://${n.host?.trim()}:${n.port}/api/health`)}:n))}async function UJ(e){try{return await Xe(new Request(e,{mode:"no-cors"}),1500),!0}catch{return!1}}function zJ({name:e}){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;const n=Math.abs(t)%8,s=["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],i=()=>{switch(n){case 0:return a.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:[a.jsx("path",{d:"M8 1.5l5.5 3.2v6.6L8 14.5l-5.5-3.2V4.7L8 1.5z"}),a.jsx("path",{d:"M8 1.5v13M2.5 4.7l5.5 3.3 5.5-3.3"})]});case 1:return a.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:[a.jsx("rect",{x:"2",y:"2.5",width:"12",height:"11",rx:"2"}),a.jsx("path",{d:"M5 6l2.5 2L5 10M8.5 10H11"})]});case 2:return a.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:[a.jsx("circle",{cx:"4.5",cy:"4",r:"1.5"}),a.jsx("circle",{cx:"4.5",cy:"12",r:"1.5"}),a.jsx("circle",{cx:"11.5",cy:"7",r:"1.5"}),a.jsx("path",{d:"M4.5 5.5v5M4.5 7.5a4 4 0 004-1"})]});case 3:return a.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:[a.jsx("path",{d:"M8 2l5.5 3-5.5 3-5.5-3L8 2z"}),a.jsx("path",{d:"M2.5 8l5.5 3 5.5-3M2.5 11l5.5 3 5.5-3"})]});case 4:return a.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:[a.jsx("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1.5"}),a.jsx("path",{d:"M6 1.5v2M10 1.5v2M6 12.5v2M10 12.5v2M1.5 6h2M1.5 10h2M12.5 6h2M12.5 10h2"})]});case 5:return a.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:a.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 a.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:a.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 a.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:[a.jsx("circle",{cx:"8",cy:"8",r:"6"}),a.jsx("path",{d:"M2 8h12M8 2a9 9 0 010 12 9 9 0 010-12z"})]})}};return a.jsx("span",{"data-testid":"project-avatar-icon",className:`flex h-7 w-7 items-center justify-center rounded border ${s}`,children:i()})}function RS({currentName:e,collapsed:t=!1}){const[n,r]=h.useState(!1),[s,i]=h.useState([]),[o,l]=h.useState(null),[c,u]=h.useState(null),d=h.useRef(null);h.useEffect(()=>{if(!n)return;const m=new AbortController;return Xe(new Request(`${it()}/projects`,{signal:m.signal})).then(async b=>{if(!b.ok)return;const y=(await b.json()).projects??[];i(y);const E=await $J(y,UJ);m.signal.aborted||i(E)}).catch(()=>{u("Failed to load projects")}),()=>m.abort()},[n]),h.useEffect(()=>{if(!n)return;const m=x=>{x.key==="Escape"&&r(!1)},b=x=>{d.current&&!d.current.contains(x.target)&&r(!1)};return document.addEventListener("keydown",m),document.addEventListener("mousedown",b),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",b)}},[n]);const p=async m=>{if(m.current){r(!1);return}const b=BJ(m);if(b){window.location.href=b;return}l(m.name);try{const x=await Xe(new Request(`${it()}/projects/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:m.name,path:m.path})}));if(!x.ok)throw new Error("Failed to start project");const y=await x.json();window.location.href=y.url||`http://${m.host??"localhost"}:${y.port}/board`}catch(x){u(x instanceof Error?x.message:"Start failed"),l(null)}},f=a.jsxs("button",{type:"button",onClick:()=>r(m=>!m),"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:[a.jsx("span",{className:`items-center justify-center ${n?"hidden":"flex group-hover:hidden"}`,children:a.jsx(zJ,{name:e})}),a.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:a.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:a.jsx("path",{d:"M4 6l4 4 4-4"})})})]});return a.jsxs("div",{className:`relative ${t?"flex items-center justify-center":"min-w-0 flex-1"}`,ref:d,children:[t?n?f:a.jsx(ur,{position:"right",tip:`Switch project: ${e}`,className:"block",children:f}):a.jsxs("button",{type:"button",onClick:()=>r(m=>!m),"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:[a.jsx("span",{className:"font-semibold truncate",children:e}),a.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:a.jsx("path",{d:"M4 6l4 4 4-4"})})]}),n&&a.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:[a.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"}),s.length===0?a.jsx("div",{className:"px-2 py-1.5 text-xs text-spur-text-muted",children:c||"No projects registered"}):s.map(m=>a.jsxs("button",{type:"button",role:"option","aria-selected":m.current,disabled:o===m.name,onClick:()=>p(m),"data-testid":`project-item-${m.name}`,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-xs text-left transition-colors ${m.current?"bg-spur-accent/15 text-spur-accent font-medium":"text-spur-text hover:bg-spur-border/30"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[a.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ${m.running?"bg-green-500":"bg-gray-400"}`,title:m.running?`Running on port ${m.port}`:"Stopped"}),a.jsx("span",{className:"truncate",children:PJ(m)})]}),o===m.name?a.jsx("span",{className:"text-[10px] text-spur-accent animate-pulse",children:"Starting..."}):m.current?a.jsx("span",{className:"text-[10px] font-semibold text-spur-accent",children:"current"}):m.running?a.jsxs("span",{className:"text-[10px] text-spur-text-muted",children:[":",m.port]}):a.jsx("span",{className:"text-[10px] text-spur-text-muted",children:"stopped"})]},m.path))]})]})}const nC="spur-theme";function HJ(){try{const e=localStorage.getItem(nC);if(e==="light"||e==="dark")return e}catch{}return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function GJ(e){document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(nC,e)}catch{}}function WJ(e){const t=e==="dark"?"light":"dark";return GJ(t),t}function DS(){const[e,t]=h.useState(HJ);h.useEffect(()=>{const s=window.matchMedia("(prefers-color-scheme: dark)"),i=o=>{if(!(()=>{try{return localStorage.getItem("spur-theme")}catch{return null}})()){const c=o.matches?"dark":"light";t(c),document.documentElement.setAttribute("data-theme",c)}};return s.addEventListener("change",i),()=>s.removeEventListener("change",i)},[]);const n=h.useCallback(()=>t(WJ),[]),r=e==="dark"?"Switch to light mode":"Switch to dark mode";return a.jsx(Ie,{variant:"ghost",size:"sm",onClick:n,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","aria-label":r,title:r,children:e==="dark"?a.jsx(AG,{className:"h-4 w-4 shrink-0",strokeWidth:1.8,"aria-hidden":"true"}):a.jsx(vG,{className:"h-4 w-4 shrink-0",strokeWidth:1.8,"aria-hidden":"true"})})}const qJ="Modules";function VJ(){const[e,t]=h.useState(qJ);return h.useEffect(()=>{const n=new AbortController;return Xe(new Request(`${it()}/project`,{signal:n.signal})).then(async r=>{if(!r.ok)return;const s=await r.json();s.name&&t(s.name)}).catch(()=>{}),()=>n.abort()},[]),e}function YJ({direction:e}){const t=e==="expand";return a.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:[a.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"}),a.jsx("line",{x1:"6",y1:"2",x2:"6",y2:"14"}),t?a.jsx("path",{d:"M9 6l2 2-2 2"}):a.jsx("path",{d:"M11 6l-2 2 2 2"})]})}function OS({collapsed:e,onToggle:t}){const n=e?"Expand sidebar":"Collapse sidebar";return a.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:a.jsx(YJ,{direction:e?"expand":"collapse"})})}function LS({collapsed:e}){const t=a.jsx(MS,{to:"/board/settings","aria-label":"Open settings",title:"Open settings","data-testid":"sidebar-settings",className:({isActive:n})=>`flex h-8 w-8 items-center justify-center rounded-md transition-colors ${n?"bg-spur-accent/20 text-spur-accent":"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:a.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:a.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"})})});return e?a.jsx(ur,{position:"right",tip:"Settings",className:"block",children:t}):t}function KJ({collapsed:e,onToggle:t,onMobileClose:n}){const r=VJ(),{registry:s}=JA();return a.jsxs("aside",{className:`flex flex-col bg-spur-surface border-r border-spur-border ${e?"overflow-visible":"overflow-hidden"}`,children:[a.jsx("div",{"data-spur-drag-region":"","data-testid":"desktop-drag-region",className:"h-0 w-full shrink-0","aria-hidden":"true"}),e?a.jsx("div",{className:"flex items-center justify-center border-b border-spur-border shrink-0 py-2",children:a.jsx(RS,{currentName:r,collapsed:!0})}):a.jsxs("div",{className:"flex items-center justify-between gap-1 p-3 border-b border-spur-border shrink-0",children:[a.jsx(RS,{currentName:r}),n&&a.jsx(Ie,{variant:"ghost",size:"sm",className:"text-spur-text-muted md:hidden",onClick:n,"aria-label":"Close navigation",children:"✕"})]}),a.jsx("nav",{className:`flex-1 ${e?"overflow-visible":"overflow-y-auto"}`,children:s.modules.filter(i=>i.id!=="settings").map(i=>{const o=i.sidebarLabel??i.name,l=a.jsxs(MS,{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:[a.jsx("span",{className:"flex h-5 w-5 items-center justify-center shrink-0",children:a.jsx(Rr,{id:i.id,icon:i.icon})}),!e&&a.jsx("span",{children:o})]},i.id);if(e){const c=i.description?`${o}
319
+ `},LX={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 jX(e){let{announcements:t=LX,container:n,hiddenTextDescribedById:r,screenReaderInstructions:s=OX}=e;const{announce:i,announcement:o}=IX(),l=xu("DndLiveRegion"),[c,u]=h.useState(!1);if(h.useEffect(()=>{u(!0)},[]),RX(h.useMemo(()=>({onDragStart(p){let{active:f}=p;i(t.onDragStart({active:f}))},onDragMove(p){let{active:f,over:m}=p;t.onDragMove&&i(t.onDragMove({active:f,over:m}))},onDragOver(p){let{active:f,over:m}=p;i(t.onDragOver({active:f,over:m}))},onDragEnd(p){let{active:f,over:m}=p;i(t.onDragEnd({active:f,over:m}))},onDragCancel(p){let{active:f,over:m}=p;i(t.onDragCancel({active:f,over:m}))}}),[i,t])),!c)return null;const d=st.createElement(st.Fragment,null,st.createElement(CX,{id:r,value:s.draggable}),st.createElement(_X,{id:l,announcement:o}));return n?Ur.createPortal(d,n):d}var Zt;(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"})(Zt||(Zt={}));function pc(){}function hS(e,t){return h.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function MX(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return h.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const Zn=Object.freeze({x:0,y:0});function FX(e,t){const n=dc(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 PX(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function BX(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function $X(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),s=Math.min(t.left+t.width,e.left+e.width),i=Math.min(t.top+t.height,e.top+e.height),o=s-r,l=i-n;if(r<s&&n<i){const c=t.width*t.height,u=e.width*e.height,d=o*l,p=d/(c+u-d);return Number(p.toFixed(4))}return 0}const UX=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=[];for(const i of r){const{id:o}=i,l=n.get(o);if(l){const c=$X(l,t);c>0&&s.push({id:o,data:{droppableContainer:i,value:c}})}}return s.sort(PX)};function zX(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function IA(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Zn}function HX(e){return function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),i=1;i<r;i++)s[i-1]=arguments[i];return s.reduce((o,l)=>({...o,top:o.top+e*l.y,bottom:o.bottom+e*l.y,left:o.left+e*l.x,right:o.right+e*l.x}),{...n})}}const GX=HX(1);function RA(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 WX(e,t,n){const r=RA(t);if(!r)return e;const{scaleX:s,scaleY:i,x:o,y:l}=r,c=e.left-o-(1-s)*parseFloat(n),u=e.top-l-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),d=s?e.width/s:e.width,p=i?e.height/i:e.height;return{width:d,height:p,top:u,right:c+d,bottom:u+p,left:c}}const qX={ignoreTransform:!1};function No(e,t){t===void 0&&(t=qX);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=Nn(e).getComputedStyle(e);u&&(n=WX(n,u,d))}const{top:r,left:s,width:i,height:o,bottom:l,right:c}=n;return{top:r,left:s,width:i,height:o,bottom:l,right:c}}function gS(e){return No(e,{ignoreTransform:!0})}function VX(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function YX(e,t){return t===void 0&&(t=Nn(e).getComputedStyle(e)),t.position==="fixed"}function KX(e,t){t===void 0&&(t=Nn(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(s=>{const i=t[s];return typeof i=="string"?n.test(i):!1})}function r0(e,t){const n=[];function r(s){if(t!=null&&n.length>=t||!s)return n;if(t0(s)&&s.scrollingElement!=null&&!n.includes(s.scrollingElement))return n.push(s.scrollingElement),n;if(!wo(s)||AA(s)||n.includes(s))return n;const i=Nn(e).getComputedStyle(s);return s!==e&&KX(s,i)&&n.push(s),YX(s,i)?n:r(s.parentNode)}return e?r(e):n}function DA(e){const[t]=r0(e,1);return t??null}function Od(e){return!gu||!e?null:Va(e)?e:e0(e)?t0(e)||e===Ya(e).scrollingElement?window:wo(e)?e:null:null}function OA(e){return Va(e)?e.scrollX:e.scrollLeft}function LA(e){return Va(e)?e.scrollY:e.scrollTop}function Pp(e){return{x:OA(e),y:LA(e)}}var rn;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(rn||(rn={}));function jA(e){return!gu||!e?!1:e===document.scrollingElement}function MA(e){const t={x:0,y:0},n=jA(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},s=e.scrollTop<=t.y,i=e.scrollLeft<=t.x,o=e.scrollTop>=r.y,l=e.scrollLeft>=r.x;return{isTop:s,isLeft:i,isBottom:o,isRight:l,maxScroll:r,minScroll:t}}const ZX={x:.2,y:.2};function XX(e,t,n,r,s){let{top:i,left:o,right:l,bottom:c}=n;r===void 0&&(r=10),s===void 0&&(s=ZX);const{isTop:u,isBottom:d,isLeft:p,isRight:f}=MA(e),m={x:0,y:0},b={x:0,y:0},x={height:t.height*s.y,width:t.width*s.x};return!u&&i<=t.top+x.height?(m.y=rn.Backward,b.y=r*Math.abs((t.top+x.height-i)/x.height)):!d&&c>=t.bottom-x.height&&(m.y=rn.Forward,b.y=r*Math.abs((t.bottom-x.height-c)/x.height)),!f&&l>=t.right-x.width?(m.x=rn.Forward,b.x=r*Math.abs((t.right-x.width-l)/x.width)):!p&&o<=t.left+x.width&&(m.x=rn.Backward,b.x=r*Math.abs((t.left+x.width-o)/x.width)),{direction:m,speed:b}}function QX(e){if(e===document.scrollingElement){const{innerWidth:i,innerHeight:o}=window;return{top:0,left:0,right:i,bottom:o,width:i,height:o}}const{top:t,left:n,right:r,bottom:s}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:s,width:e.clientWidth,height:e.clientHeight}}function FA(e){return e.reduce((t,n)=>ha(t,Pp(n)),Zn)}function JX(e){return e.reduce((t,n)=>t+OA(n),0)}function eQ(e){return e.reduce((t,n)=>t+LA(n),0)}function PA(e,t){if(t===void 0&&(t=No),!e)return;const{top:n,left:r,bottom:s,right:i}=t(e);DA(e)&&(s<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const tQ=[["x",["left","right"],JX],["y",["top","bottom"],eQ]];class s0{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=r0(n),s=FA(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,o,l]of tQ)for(const c of o)Object.defineProperty(this,c,{get:()=>{const u=l(r),d=s[i]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ri{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 s;(s=this.target)==null||s.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function nQ(e){const{EventTarget:t}=Nn(e);return e instanceof t?e:Ya(e)}function Ld(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 jn;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(jn||(jn={}));function bS(e){e.preventDefault()}function rQ(e){e.stopPropagation()}var It;(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"})(It||(It={}));const BA={start:[It.Space,It.Enter],cancel:[It.Esc],end:[It.Space,It.Enter,It.Tab]},sQ=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case It.Right:return{...n,x:n.x+25};case It.Left:return{...n,x:n.x-25};case It.Down:return{...n,y:n.y+25};case It.Up:return{...n,y:n.y-25}}};class a0{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 Ri(Ya(n)),this.windowListeners=new Ri(Nn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(jn.Resize,this.handleCancel),this.windowListeners.add(jn.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(jn.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&PA(r),n(Zn)}handleKeyDown(t){if(n0(t)){const{active:n,context:r,options:s}=this.props,{keyboardCodes:i=BA,coordinateGetter:o=sQ,scrollBehavior:l="smooth"}=s,{code:c}=t;if(i.end.includes(c)){this.handleEnd(t);return}if(i.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:Zn;this.referenceCoordinates||(this.referenceCoordinates=d);const p=o(t,{active:n,context:r.current,currentCoordinates:d});if(p){const f=uc(p,d),m={x:0,y:0},{scrollableAncestors:b}=r.current;for(const x of b){const y=t.code,{isTop:E,isRight:A,isLeft:w,isBottom:N,maxScroll:_,minScroll:k}=MA(x),S=QX(x),v={x:Math.min(y===It.Right?S.right-S.width/2:S.right,Math.max(y===It.Right?S.left:S.left+S.width/2,p.x)),y:Math.min(y===It.Down?S.bottom-S.height/2:S.bottom,Math.max(y===It.Down?S.top:S.top+S.height/2,p.y))},O=y===It.Right&&!A||y===It.Left&&!w,C=y===It.Down&&!N||y===It.Up&&!E;if(O&&v.x!==p.x){const M=x.scrollLeft+f.x,B=y===It.Right&&M<=_.x||y===It.Left&&M>=k.x;if(B&&!f.y){x.scrollTo({left:M,behavior:l});return}B?m.x=x.scrollLeft-M:m.x=y===It.Right?x.scrollLeft-_.x:x.scrollLeft-k.x,m.x&&x.scrollBy({left:-m.x,behavior:l});break}else if(C&&v.y!==p.y){const M=x.scrollTop+f.y,B=y===It.Down&&M<=_.y||y===It.Up&&M>=k.y;if(B&&!f.x){x.scrollTo({top:M,behavior:l});return}B?m.y=x.scrollTop-M:m.y=y===It.Down?x.scrollTop-_.y:x.scrollTop-k.y,m.y&&x.scrollBy({top:-m.y,behavior:l});break}}this.handleMove(t,ha(uc(p,this.referenceCoordinates),m))}}}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()}}a0.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=BA,onActivation:s}=t,{active:i}=n;const{code:o}=e.nativeEvent;if(r.start.includes(o)){const l=i.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),s?.({event:e.nativeEvent}),!0)}return!1}}];function xS(e){return!!(e&&"distance"in e)}function yS(e){return!!(e&&"delay"in e)}class i0{constructor(t,n,r){var s;r===void 0&&(r=nQ(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:i}=t,{target:o}=i;this.props=t,this.events=n,this.document=Ya(o),this.documentListeners=new Ri(this.document),this.listeners=new Ri(r),this.windowListeners=new Ri(Nn(o)),this.initialCoordinates=(s=dc(i))!=null?s:Zn,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(jn.Resize,this.handleCancel),this.windowListeners.add(jn.DragStart,bS),this.windowListeners.add(jn.VisibilityChange,this.handleCancel),this.windowListeners.add(jn.ContextMenu,bS),this.documentListeners.add(jn.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(yS(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(xS(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:s}=this.props;s(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(jn.Click,rQ,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(jn.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:s,props:i}=this,{onMove:o,options:{activationConstraint:l}}=i;if(!s)return;const c=(n=dc(t))!=null?n:Zn,u=uc(s,c);if(!r&&l){if(xS(l)){if(l.tolerance!=null&&Ld(u,l.tolerance))return this.handleCancel();if(Ld(u,l.distance))return this.handleStart()}if(yS(l)&&Ld(u,l.tolerance))return this.handleCancel();this.handlePending(l,u);return}t.cancelable&&t.preventDefault(),o(c)}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===It.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const aQ={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class o0 extends i0{constructor(t){const{event:n}=t,r=Ya(n.target);super(t,aQ,r)}}o0.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 iQ={move:{name:"mousemove"},end:{name:"mouseup"}};var Bp;(function(e){e[e.RightClick=2]="RightClick"})(Bp||(Bp={}));class oQ extends i0{constructor(t){super(t,iQ,Ya(t.event.target))}}oQ.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===Bp.RightClick?!1:(r?.({event:n}),!0)}}];const jd={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class lQ extends i0{constructor(t){super(t,jd)}static setup(){return window.addEventListener(jd.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(jd.move.name,t)};function t(){}}}lQ.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:s}=n;return s.length>1?!1:(r?.({event:n}),!0)}}];var Di;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Di||(Di={}));var fc;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(fc||(fc={}));function cQ(e){let{acceleration:t,activator:n=Di.Pointer,canScroll:r,draggingRect:s,enabled:i,interval:o=5,order:l=fc.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:p,threshold:f}=e;const m=dQ({delta:p,disabled:!i}),[b,x]=vX(),y=h.useRef({x:0,y:0}),E=h.useRef({x:0,y:0}),A=h.useMemo(()=>{switch(n){case Di.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case Di.DraggableRect:return s}},[n,s,c]),w=h.useRef(null),N=h.useCallback(()=>{const k=w.current;if(!k)return;const S=y.current.x*E.current.x,v=y.current.y*E.current.y;k.scrollBy(S,v)},[]),_=h.useMemo(()=>l===fc.TreeOrder?[...u].reverse():u,[l,u]);h.useEffect(()=>{if(!i||!u.length||!A){x();return}for(const k of _){if(r?.(k)===!1)continue;const S=u.indexOf(k),v=d[S];if(!v)continue;const{direction:O,speed:C}=XX(k,v,A,t,f);for(const M of["x","y"])m[M][O[M]]||(C[M]=0,O[M]=0);if(C.x>0||C.y>0){x(),w.current=k,b(N,o),y.current=C,E.current=O;return}}y.current={x:0,y:0},E.current={x:0,y:0},x()},[t,N,r,x,i,o,JSON.stringify(A),JSON.stringify(m),b,u,_,d,JSON.stringify(f)])}const uQ={x:{[rn.Backward]:!1,[rn.Forward]:!1},y:{[rn.Backward]:!1,[rn.Forward]:!1}};function dQ(e){let{delta:t,disabled:n}=e;const r=cc(t);return vo(s=>{if(n||!r||!s)return uQ;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[rn.Backward]:s.x[rn.Backward]||i.x===-1,[rn.Forward]:s.x[rn.Forward]||i.x===1},y:{[rn.Backward]:s.y[rn.Backward]||i.y===-1,[rn.Forward]:s.y[rn.Forward]||i.y===1}}},[n,t,r])}function pQ(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return vo(s=>{var i;return t==null?null:(i=r??s)!=null?i:null},[r,t])}function fQ(e,t){return h.useMemo(()=>e.reduce((n,r)=>{const{sensor:s}=r,i=s.activators.map(o=>({eventName:o.eventName,handler:t(o.handler,r)}));return[...n,...i]},[]),[e,t])}var Xi;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Xi||(Xi={}));var $p;(function(e){e.Optimized="optimized"})($p||($p={}));const ES=new Map;function mQ(e,t){let{dragging:n,dependencies:r,config:s}=t;const[i,o]=h.useState(null),{frequency:l,measure:c,strategy:u}=s,d=h.useRef(e),p=y(),f=Zi(p),m=h.useCallback(function(E){E===void 0&&(E=[]),!f.current&&o(A=>A===null?E:A.concat(E.filter(w=>!A.includes(w))))},[f]),b=h.useRef(null),x=vo(E=>{if(p&&!n)return ES;if(!E||E===ES||d.current!==e||i!=null){const A=new Map;for(let w of e){if(!w)continue;if(i&&i.length>0&&!i.includes(w.id)&&w.rect.current){A.set(w.id,w.rect.current);continue}const N=w.node.current,_=N?new s0(c(N),N):null;w.rect.current=_,_&&A.set(w.id,_)}return A}return E},[e,i,n,p,c]);return h.useEffect(()=>{d.current=e},[e]),h.useEffect(()=>{p||m()},[n,p]),h.useEffect(()=>{i&&i.length>0&&o(null)},[JSON.stringify(i)]),h.useEffect(()=>{p||typeof l!="number"||b.current!==null||(b.current=setTimeout(()=>{m(),b.current=null},l))},[l,p,m,...r]),{droppableRects:x,measureDroppableContainers:m,measuringScheduled:i!=null};function y(){switch(u){case Xi.Always:return!1;case Xi.BeforeDragging:return n;default:return!n}}}function l0(e,t){return vo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function hQ(e,t){return l0(e,t)}function gQ(e){let{callback:t,disabled:n}=e;const r=bu(t),s=h.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return h.useEffect(()=>()=>s?.disconnect(),[s]),s}function yu(e){let{callback:t,disabled:n}=e;const r=bu(t),s=h.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return h.useEffect(()=>()=>s?.disconnect(),[s]),s}function bQ(e){return new s0(No(e),e)}function SS(e,t,n){t===void 0&&(t=bQ);const[r,s]=h.useState(null);function i(){s(c=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=t(e);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const o=gQ({callback(c){if(e)for(const u of c){const{type:d,target:p}=u;if(d==="childList"&&p instanceof HTMLElement&&p.contains(e)){i();break}}}}),l=yu({callback:i});return _r(()=>{i(),e?(l?.observe(e),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[e]),r}function xQ(e){const t=l0(e);return IA(e,t)}const wS=[];function yQ(e){const t=h.useRef(e),n=vo(r=>e?r&&r!==wS&&e&&t.current&&e.parentNode===t.current.parentNode?r:r0(e):wS,[e]);return h.useEffect(()=>{t.current=e},[e]),n}function EQ(e){const[t,n]=h.useState(null),r=h.useRef(e),s=h.useCallback(i=>{const o=Od(i.target);o&&n(l=>l?(l.set(o,Pp(o)),new Map(l)):null)},[]);return h.useEffect(()=>{const i=r.current;if(e!==i){o(i);const l=e.map(c=>{const u=Od(c);return u?(u.addEventListener("scroll",s,{passive:!0}),[u,Pp(u)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),r.current=e}return()=>{o(e),o(i)};function o(l){l.forEach(c=>{const u=Od(c);u?.removeEventListener("scroll",s)})}},[s,e]),h.useMemo(()=>e.length?t?Array.from(t.values()).reduce((i,o)=>ha(i,o),Zn):FA(e):Zn,[e,t])}function vS(e,t){t===void 0&&(t=[]);const n=h.useRef(null);return h.useEffect(()=>{n.current=null},t),h.useEffect(()=>{const r=e!==Zn;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?uc(e,n.current):Zn}function SQ(e){h.useEffect(()=>{if(!gu)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 wQ(e,t){return h.useMemo(()=>e.reduce((n,r)=>{let{eventName:s,handler:i}=r;return n[s]=o=>{i(o,t)},n},{}),[e,t])}function $A(e){return h.useMemo(()=>e?VX(e):null,[e])}const NS=[];function vQ(e,t){t===void 0&&(t=No);const[n]=e,r=$A(n?Nn(n):null),[s,i]=h.useState(NS);function o(){i(()=>e.length?e.map(c=>jA(c)?r:new s0(t(c),c)):NS)}const l=yu({callback:o});return _r(()=>{l?.disconnect(),o(),e.forEach(c=>l?.observe(c))},[e]),s}function UA(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return wo(t)?t:e}function NQ(e){let{measure:t}=e;const[n,r]=h.useState(null),s=h.useCallback(u=>{for(const{target:d}of u)if(wo(d)){r(p=>{const f=t(d);return p?{...p,width:f.width,height:f.height}:f});break}},[t]),i=yu({callback:s}),o=h.useCallback(u=>{const d=UA(u);i?.disconnect(),d&&i?.observe(d),r(d?t(d):null)},[t,i]),[l,c]=lc(o);return h.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const TQ=[{sensor:o0,options:{}},{sensor:a0,options:{}}],kQ={current:{}},Il={draggable:{measure:gS},droppable:{measure:gS,strategy:Xi.WhileDragging,frequency:$p.Optimized},dragOverlay:{measure:No}};class Oi 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 AQ={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Oi,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:pc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Il,measureDroppableContainers:pc,windowRect:null,measuringScheduled:!1},zA={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:pc,draggableNodes:new Map,over:null,measureDroppableContainers:pc},To=h.createContext(zA),HA=h.createContext(AQ);function CQ(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Oi}}}function _Q(e,t){switch(t.type){case Zt.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Zt.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 Zt.DragEnd:case Zt.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Zt.RegisterDroppable:{const{element:n}=t,{id:r}=n,s=new Oi(e.droppable.containers);return s.set(r,n),{...e,droppable:{...e.droppable,containers:s}}}case Zt.SetDroppableDisabled:{const{id:n,key:r,disabled:s}=t,i=e.droppable.containers.get(n);if(!i||r!==i.key)return e;const o=new Oi(e.droppable.containers);return o.set(n,{...i,disabled:s}),{...e,droppable:{...e.droppable,containers:o}}}case Zt.UnregisterDroppable:{const{id:n,key:r}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const i=new Oi(e.droppable.containers);return i.delete(n),{...e,droppable:{...e.droppable,containers:i}}}default:return e}}function IQ(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:s}=h.useContext(To),i=cc(r),o=cc(n?.id);return h.useEffect(()=>{if(!t&&!r&&i&&o!=null){if(!n0(i)||document.activeElement===i.target)return;const l=s.get(o);if(!l)return;const{activatorNode:c,node:u}=l;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const p=kX(d);if(p){p.focus();break}}})}},[r,t,s,o,i]),null}function GA(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((s,i)=>i({transform:s,...r}),n):n}function RQ(e){return h.useMemo(()=>({draggable:{...Il.draggable,...e?.draggable},droppable:{...Il.droppable,...e?.droppable},dragOverlay:{...Il.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function DQ(e){let{activeNode:t,measure:n,initialRect:r,config:s=!0}=e;const i=h.useRef(!1),{x:o,y:l}=typeof s=="boolean"?{x:s,y:s}:s;_r(()=>{if(!o&&!l||!t){i.current=!1;return}if(i.current||!r)return;const u=t?.node.current;if(!u||u.isConnected===!1)return;const d=n(u),p=IA(d,r);if(o||(p.x=0),l||(p.y=0),i.current=!0,Math.abs(p.x)>0||Math.abs(p.y)>0){const f=DA(u);f&&f.scrollBy({top:p.y,left:p.x})}},[t,o,l,r,n])}const Eu=h.createContext({...Zn,scaleX:1,scaleY:1});var Br;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Br||(Br={}));const OQ=h.memo(function(t){var n,r,s,i;let{id:o,accessibility:l,autoScroll:c=!0,children:u,sensors:d=TQ,collisionDetection:p=UX,measuring:f,modifiers:m,...b}=t;const x=h.useReducer(_Q,void 0,CQ),[y,E]=x,[A,w]=DX(),[N,_]=h.useState(Br.Uninitialized),k=N===Br.Initialized,{draggable:{active:S,nodes:v,translate:O},droppable:{containers:C}}=y,M=S!=null?v.get(S):null,B=h.useRef({initial:null,translated:null}),R=h.useMemo(()=>{var Oe;return S!=null?{id:S,data:(Oe=M?.data)!=null?Oe:kQ,rect:B}:null},[S,M]),z=h.useRef(null),[W,F]=h.useState(null),[J,K]=h.useState(null),X=Zi(b,Object.values(b)),I=xu("DndDescribedBy",o),V=h.useMemo(()=>C.getEnabled(),[C]),te=RQ(f),{droppableRects:L,measureDroppableContainers:ye,measuringScheduled:xe}=mQ(V,{dragging:k,dependencies:[O.x,O.y],config:te.droppable}),P=pQ(v,S),oe=h.useMemo(()=>J?dc(J):null,[J]),re=Ct(),H=hQ(P,te.draggable.measure);DQ({activeNode:S!=null?v.get(S):null,config:re.layoutShiftCompensation,initialRect:H,measure:te.draggable.measure});const Ce=SS(P,te.draggable.measure,H),me=SS(P?P.parentElement:null),he=h.useRef({activatorEvent:null,active:null,activeNode:P,collisionRect:null,collisions:null,droppableRects:L,draggableNodes:v,draggingNode:null,draggingNodeRect:null,droppableContainers:C,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ne=C.getNodeFor((n=he.current.over)==null?void 0:n.id),Ge=NQ({measure:te.dragOverlay.measure}),Z=(r=Ge.nodeRef.current)!=null?r:P,ke=k?(s=Ge.rect)!=null?s:Ce:null,Fe=!!(Ge.nodeRef.current&&Ge.rect),Re=xQ(Fe?null:Ce),rt=$A(Z?Nn(Z):null),ae=yQ(k?Ne??P:null),pe=vQ(ae),De=GA(m,{transform:{x:O.x-Re.x,y:O.y-Re.y,scaleX:1,scaleY:1},activatorEvent:J,active:R,activeNodeRect:Ce,containerNodeRect:me,draggingNodeRect:ke,over:he.current.over,overlayNodeRect:Ge.rect,scrollableAncestors:ae,scrollableAncestorRects:pe,windowRect:rt}),Me=oe?ha(oe,O):null,Le=EQ(ae),ot=vS(Le),dt=vS(Le,[Ce]),se=ha(De,ot),fe=ke?GX(ke,De):null,je=R&&fe?p({active:R,collisionRect:fe,droppableRects:L,droppableContainers:V,pointerCoordinates:Me}):null,Y=BX(je,"id"),[He,Ue]=h.useState(null),at=Fe?De:ha(De,dt),Nt=zX(at,(i=He?.rect)!=null?i:null,Ce),At=h.useRef(null),de=h.useCallback((Oe,Qe)=>{let{sensor:qe,options:St}=Qe;if(z.current==null)return;const ce=v.get(z.current);if(!ce)return;const Ee=Oe.nativeEvent,Ye=new qe({active:z.current,activeNode:ce,event:Ee,options:St,context:he,onAbort(ee){if(!v.get(ee))return;const{onDragAbort:lt}=X.current,bt={id:ee};lt?.(bt),A({type:"onDragAbort",event:bt})},onPending(ee,We,lt,bt){if(!v.get(ee))return;const{onDragPending:xr}=X.current,nr={id:ee,constraint:We,initialCoordinates:lt,offset:bt};xr?.(nr),A({type:"onDragPending",event:nr})},onStart(ee){const We=z.current;if(We==null)return;const lt=v.get(We);if(!lt)return;const{onDragStart:bt}=X.current,In={activatorEvent:Ee,active:{id:We,data:lt.data,rect:B}};Ur.unstable_batchedUpdates(()=>{bt?.(In),_(Br.Initializing),E({type:Zt.DragStart,initialCoordinates:ee,active:We}),A({type:"onDragStart",event:In}),F(At.current),K(Ee)})},onMove(ee){E({type:Zt.DragMove,coordinates:ee})},onEnd:Dt(Zt.DragEnd),onCancel:Dt(Zt.DragCancel)});At.current=Ye;function Dt(ee){return async function(){const{active:lt,collisions:bt,over:In,scrollAdjustedTranslate:xr}=he.current;let nr=null;if(lt&&xr){const{cancelDrop:Hn}=X.current;nr={activatorEvent:Ee,active:lt,collisions:bt,delta:xr,over:In},ee===Zt.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(nr))&&(ee=Zt.DragCancel)}z.current=null,Ur.unstable_batchedUpdates(()=>{E({type:ee}),_(Br.Uninitialized),Ue(null),F(null),K(null),At.current=null;const Hn=ee===Zt.DragEnd?"onDragEnd":"onDragCancel";if(nr){const Ka=X.current[Hn];Ka?.(nr),A({type:Hn,event:nr})}})}}},[v]),_e=h.useCallback((Oe,Qe)=>(qe,St)=>{const ce=qe.nativeEvent,Ee=v.get(St);if(z.current!==null||!Ee||ce.dndKit||ce.defaultPrevented)return;const Ye={active:Ee};Oe(qe,Qe.options,Ye)===!0&&(ce.dndKit={capturedBy:Qe.sensor},z.current=St,de(qe,Qe))},[v,de]),Ve=fQ(d,_e);SQ(d),_r(()=>{Ce&&N===Br.Initializing&&_(Br.Initialized)},[Ce,N]),h.useEffect(()=>{const{onDragMove:Oe}=X.current,{active:Qe,activatorEvent:qe,collisions:St,over:ce}=he.current;if(!Qe||!qe)return;const Ee={active:Qe,activatorEvent:qe,collisions:St,delta:{x:se.x,y:se.y},over:ce};Ur.unstable_batchedUpdates(()=>{Oe?.(Ee),A({type:"onDragMove",event:Ee})})},[se.x,se.y]),h.useEffect(()=>{const{active:Oe,activatorEvent:Qe,collisions:qe,droppableContainers:St,scrollAdjustedTranslate:ce}=he.current;if(!Oe||z.current==null||!Qe||!ce)return;const{onDragOver:Ee}=X.current,Ye=St.get(Y),Dt=Ye&&Ye.rect.current?{id:Ye.id,rect:Ye.rect.current,data:Ye.data,disabled:Ye.disabled}:null,ee={active:Oe,activatorEvent:Qe,collisions:qe,delta:{x:ce.x,y:ce.y},over:Dt};Ur.unstable_batchedUpdates(()=>{Ue(Dt),Ee?.(ee),A({type:"onDragOver",event:ee})})},[Y]),_r(()=>{he.current={activatorEvent:J,active:R,activeNode:P,collisionRect:fe,collisions:je,droppableRects:L,draggableNodes:v,draggingNode:Z,draggingNodeRect:ke,droppableContainers:C,over:He,scrollableAncestors:ae,scrollAdjustedTranslate:se},B.current={initial:ke,translated:fe}},[R,P,je,fe,v,Z,ke,L,C,He,ae,se]),cQ({...re,delta:O,draggingRect:fe,pointerCoordinates:Me,scrollableAncestors:ae,scrollableAncestorRects:pe});const Pe=h.useMemo(()=>({active:R,activeNode:P,activeNodeRect:Ce,activatorEvent:J,collisions:je,containerNodeRect:me,dragOverlay:Ge,draggableNodes:v,droppableContainers:C,droppableRects:L,over:He,measureDroppableContainers:ye,scrollableAncestors:ae,scrollableAncestorRects:pe,measuringConfiguration:te,measuringScheduled:xe,windowRect:rt}),[R,P,Ce,J,je,me,Ge,v,C,L,He,ye,ae,pe,te,xe,rt]),Je=h.useMemo(()=>({activatorEvent:J,activators:Ve,active:R,activeNodeRect:Ce,ariaDescribedById:{draggable:I},dispatch:E,draggableNodes:v,over:He,measureDroppableContainers:ye}),[J,Ve,R,Ce,E,I,v,He,ye]);return st.createElement(_A.Provider,{value:w},st.createElement(To.Provider,{value:Je},st.createElement(HA.Provider,{value:Pe},st.createElement(Eu.Provider,{value:Nt},u)),st.createElement(IQ,{disabled:l?.restoreFocus===!1})),st.createElement(jX,{...l,hiddenTextDescribedById:I}));function Ct(){const Oe=W?.autoScrollEnabled===!1,Qe=typeof c=="object"?c.enabled===!1:c===!1,qe=k&&!Oe&&!Qe;return typeof c=="object"?{...c,enabled:qe}:{enabled:qe}}}),LQ=h.createContext(null),TS="button",jQ="Draggable";function MQ(e){let{id:t,data:n,disabled:r=!1,attributes:s}=e;const i=xu(jQ),{activators:o,activatorEvent:l,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:p,over:f}=h.useContext(To),{role:m=TS,roleDescription:b="draggable",tabIndex:x=0}=s??{},y=c?.id===t,E=h.useContext(y?Eu:LQ),[A,w]=lc(),[N,_]=lc(),k=wQ(o,t),S=Zi(n);_r(()=>(p.set(t,{id:t,key:i,node:A,activatorNode:N,data:S}),()=>{const O=p.get(t);O&&O.key===i&&p.delete(t)}),[p,t]);const v=h.useMemo(()=>({role:m,tabIndex:x,"aria-disabled":r,"aria-pressed":y&&m===TS?!0:void 0,"aria-roledescription":b,"aria-describedby":d.draggable}),[r,m,x,y,b,d.draggable]);return{active:c,activatorEvent:l,activeNodeRect:u,attributes:v,isDragging:y,listeners:r?void 0:k,node:A,over:f,setNodeRef:w,setActivatorNodeRef:_,transform:E}}function FQ(){return h.useContext(HA)}const PQ="Droppable",BQ={timeout:25};function $Q(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:s}=e;const i=xu(PQ),{active:o,dispatch:l,over:c,measureDroppableContainers:u}=h.useContext(To),d=h.useRef({disabled:n}),p=h.useRef(!1),f=h.useRef(null),m=h.useRef(null),{disabled:b,updateMeasurementsFor:x,timeout:y}={...BQ,...s},E=Zi(x??r),A=h.useCallback(()=>{if(!p.current){p.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(E.current)?E.current:[E.current]),m.current=null},y)},[y]),w=yu({callback:A,disabled:b||!o}),N=h.useCallback((v,O)=>{w&&(O&&(w.unobserve(O),p.current=!1),v&&w.observe(v))},[w]),[_,k]=lc(N),S=Zi(t);return h.useEffect(()=>{!w||!_.current||(w.disconnect(),p.current=!1,w.observe(_.current))},[_,w]),h.useEffect(()=>(l({type:Zt.RegisterDroppable,element:{id:r,key:i,disabled:n,node:_,rect:f,data:S}}),()=>l({type:Zt.UnregisterDroppable,key:i,id:r})),[r]),h.useEffect(()=>{n!==d.current.disabled&&(l({type:Zt.SetDroppableDisabled,id:r,key:i,disabled:n}),d.current.disabled=n)},[r,i,n,l]),{active:o,rect:f,isOver:c?.id===r,node:_,over:c,setNodeRef:k}}function UQ(e){let{animation:t,children:n}=e;const[r,s]=h.useState(null),[i,o]=h.useState(null),l=cc(n);return!n&&!r&&l&&s(l),_r(()=>{if(!i)return;const c=r?.key,u=r?.props.id;if(c==null||u==null){s(null);return}Promise.resolve(t(u,i)).then(()=>{s(null)})},[t,r,i]),st.createElement(st.Fragment,null,n,r?h.cloneElement(r,{ref:o}):null)}const zQ={x:0,y:0,scaleX:1,scaleY:1};function HQ(e){let{children:t}=e;return st.createElement(To.Provider,{value:zA},st.createElement(Eu.Provider,{value:zQ},t))}const GQ={position:"fixed",touchAction:"none"},WQ=e=>n0(e)?"transform 250ms ease":void 0,qQ=h.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:s,children:i,className:o,rect:l,style:c,transform:u,transition:d=WQ}=e;if(!l)return null;const p=s?u:{...u,scaleX:1,scaleY:1},f={...GQ,width:l.width,height:l.height,top:l.top,left:l.left,transform:Aa.Transform.toString(p),transformOrigin:s&&r?FX(r,l):void 0,transition:typeof d=="function"?d(r):d,...c};return st.createElement(n,{className:o,style:f,ref:t},i)}),VQ=e=>t=>{let{active:n,dragOverlay:r}=t;const s={},{styles:i,className:o}=e;if(i!=null&&i.active)for(const[l,c]of Object.entries(i.active))c!==void 0&&(s[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,c));if(i!=null&&i.dragOverlay)for(const[l,c]of Object.entries(i.dragOverlay))c!==void 0&&r.node.style.setProperty(l,c);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&r.node.classList.add(o.dragOverlay),function(){for(const[c,u]of Object.entries(s))n.node.style.setProperty(c,u);o!=null&&o.active&&n.node.classList.remove(o.active)}},YQ=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Aa.Transform.toString(t)},{transform:Aa.Transform.toString(n)}]},KQ={duration:250,easing:"ease",keyframes:YQ,sideEffects:VQ({styles:{active:{opacity:"0"}}})};function ZQ(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:s}=e;return bu((i,o)=>{if(t===null)return;const l=n.get(i);if(!l)return;const c=l.node.current;if(!c)return;const u=UA(o);if(!u)return;const{transform:d}=Nn(o).getComputedStyle(o),p=RA(d);if(!p)return;const f=typeof t=="function"?t:XQ(t);return PA(c,s.draggable.measure),f({active:{id:i,data:l.data,node:c,rect:s.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:o,rect:s.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:s,transform:p})})}function XQ(e){const{duration:t,easing:n,sideEffects:r,keyframes:s}={...KQ,...e};return i=>{let{active:o,dragOverlay:l,transform:c,...u}=i;if(!t)return;const d={x:l.rect.left-o.rect.left,y:l.rect.top-o.rect.top},p={scaleX:c.scaleX!==1?o.rect.width*c.scaleX/l.rect.width:1,scaleY:c.scaleY!==1?o.rect.height*c.scaleY/l.rect.height:1},f={x:c.x-d.x,y:c.y-d.y,...p},m=s({...u,active:o,dragOverlay:l,transform:{initial:c,final:f}}),[b]=m,x=m[m.length-1];if(JSON.stringify(b)===JSON.stringify(x))return;const y=r?.({active:o,dragOverlay:l,...u}),E=l.node.animate(m,{duration:t,easing:n,fill:"forwards"});return new Promise(A=>{E.onfinish=()=>{y?.(),A()}})}}let kS=0;function QQ(e){return h.useMemo(()=>{if(e!=null)return kS++,kS},[e])}const JQ=st.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:s,transition:i,modifiers:o,wrapperElement:l="div",className:c,zIndex:u=999}=e;const{activatorEvent:d,active:p,activeNodeRect:f,containerNodeRect:m,draggableNodes:b,droppableContainers:x,dragOverlay:y,over:E,measuringConfiguration:A,scrollableAncestors:w,scrollableAncestorRects:N,windowRect:_}=FQ(),k=h.useContext(Eu),S=QQ(p?.id),v=GA(o,{activatorEvent:d,active:p,activeNodeRect:f,containerNodeRect:m,draggingNodeRect:y.rect,over:E,overlayNodeRect:y.rect,scrollableAncestors:w,scrollableAncestorRects:N,transform:k,windowRect:_}),O=l0(f),C=ZQ({config:r,draggableNodes:b,droppableContainers:x,measuringConfiguration:A}),M=O?y.setRef:void 0;return st.createElement(HQ,null,st.createElement(UQ,{animation:C},p&&S?st.createElement(qQ,{key:S,id:p.id,ref:M,as:l,activatorEvent:d,adjustScale:t,className:c,transition:i,rect:O,style:{zIndex:u,...s},transform:v},n):null))}),eJ=6e4,tJ=10080*60*1e3,nJ={P1:"error",P2:"warning",P3:"neutral"},rJ={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",deprecated:"bg-spur-text-muted"};function sJ(e,t){const n=new Date(e).getTime(),r=t-n,s=Math.floor(r/1e3);if(s<60)return"just now";const i=Math.floor(s/60);if(i<60)return`${i}m ago`;const o=Math.floor(i/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:`${Math.floor(l/30)}mo ago`}function WA({task:e,onClick:t}){const{attributes:n,listeners:r,setNodeRef:s,transform:i,isDragging:o}=MQ({id:e.wbs,data:{task:e}}),[l,c]=h.useState(Date.now());h.useEffect(()=>{const m=setInterval(()=>c(Date.now()),eJ);return()=>clearInterval(m)},[]);const u=i?{transform:Aa.Transform.toString(i),zIndex:o?50:void 0}:void 0,{subtaskProgress:d}=Ux(),p=d.get(e.wbs),f=e.updatedAt?l-new Date(e.updatedAt).getTime()>tJ:!1;return a.jsx(yx,{variant:"compact",asChild:!0,className:`group bg-spur-surface-2 hover:bg-spur-surface-3 rounded-xl border border-spur-border hover:border-spur-accent/60 shadow-xs hover:shadow-md cursor-pointer transition-all duration-150 w-full text-left ${o?"opacity-30":""}`,children:a.jsx("button",{ref:s,type:"button",style:u,onClick:()=>t(e.wbs),...r,...n,"aria-roledescription":"draggable card",children:a.jsxs(Ex,{className:"p-3 gap-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-mono font-semibold text-spur-text",children:[a.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ring-1 ring-spur-surface-2 ${rJ[e.status]??"bg-spur-text-faint"}`,"data-status":e.status,"aria-hidden":"true"}),e.wbs]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[e.estimateHours!==void 0&&a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted flex items-center gap-0.5",title:`Estimated: ${e.estimateHours}h`,children:[a.jsx("span",{className:"text-spur-text-faint text-[9px]",children:"⏱"}),e.estimateHours,"h"]}),e.priority&&a.jsx(tt,{variant:nJ[e.priority]??"outline",size:"xs",className:"font-mono text-[10px] font-semibold",children:e.priority})]})]}),a.jsx("p",{className:"text-sm font-medium text-spur-text leading-snug line-clamp-2 group-hover:text-spur-accent transition-colors",children:e.name}),a.jsxs("div",{className:"flex gap-1.5 flex-wrap items-center pt-0.5",children:[p&&p.total>0&&a.jsxs("div",{className:"flex items-center gap-1.5 min-w-[3.5rem]","data-testid":"subtask-progress",title:"subtasks done/total",children:[a.jsx("div",{className:"h-1 flex-1 rounded-full bg-spur-border/60 overflow-hidden",children:a.jsx("div",{className:"h-full bg-spur-success",style:{width:`${Math.round(p.done/p.total*100)}%`}})}),a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted shrink-0",children:[p.done,"/",p.total]})]}),e.type&&e.type!=="task"&&a.jsx(tt,{variant:"outline",size:"xs",className:"text-[10px] font-mono border-spur-border text-spur-text-muted",children:e.type}),e.template&&e.template!=="feature-impl"&&a.jsx(tt,{variant:"outline",size:"xs",className:"text-[10px] font-mono border-spur-accent/40 text-spur-accent bg-spur-accent/5 font-medium",children:e.template}),e.featureId&&a.jsx(tt,{variant:"outline",size:"xs",className:"text-[10px] font-mono border-spur-border text-spur-text-muted",children:e.featureId}),e.dependencyCount!==void 0&&e.dependencyCount>0&&a.jsxs("span",{className:"text-[10px] font-mono text-spur-text-muted flex items-center gap-0.5",title:`${e.dependencyCount} dependenc${e.dependencyCount===1?"y":"ies"}`,children:[a.jsx("span",{className:"text-spur-text-faint text-[9px]",children:"⛓"}),e.dependencyCount]}),e.updatedAt&&a.jsx("span",{className:`text-xs font-mono ml-auto ${f?"text-spur-text-faint":"text-spur-text-muted"}`,title:e.updatedAt,children:sJ(e.updatedAt,l)})]})]})})})}function aJ({status:e,label:t,tasks:n,onCardClick:r,sortDir:s,onSortToggle:i}){const{setNodeRef:o,isOver:l}=$Q({id:e,data:{status:e}});return a.jsxs("section",{ref:o,"aria-label":`${t} column`,className:`flex flex-col flex-1 min-w-[16rem] rounded-xl border transition-colors duration-200 overflow-hidden ${l?"bg-spur-surface/40 border-spur-accent shadow-lg ring-1 ring-spur-accent/30":"bg-transparent border-spur-border"}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-3.5 py-2.5 border-b border-spur-border shrink-0 bg-spur-surface",children:[a.jsxs("span",{className:"text-xs font-semibold text-spur-text uppercase tracking-wide",children:[ef(e)," ",t]}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(tt,{variant:"ghost",size:"sm",className:"font-mono text-spur-text-muted bg-spur-surface-2 border border-spur-border/80 px-2 py-0.5",children:n.length}),i&&a.jsx(Ie,{variant:"ghost",size:"xs",className:"h-6 w-6 p-0 flex items-center justify-center text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-2 rounded-md transition-colors",onClick:i,"aria-label":`Sort ${t} by WBS`,title:`Sort ${t}: ${s==="asc"?"WBS ↓":s==="desc"?"WBS ↑":"none"}`,children:s==="asc"?"↓":s==="desc"?"↑":"⇅"})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-2 min-h-[4rem]",children:[n.map(c=>a.jsx(WA,{task:c,onClick:r},c.wbs)),n.length===0&&a.jsx("div",{className:"flex items-center justify-center h-20 text-xs text-spur-text-muted italic border border-dashed border-spur-border/60 rounded-lg my-1 bg-spur-surface/30",children:"No tasks"})]})]})}const iJ=h.lazy(()=>Ak(()=>import("./TaskDetail.DWXct9_X.js"),__vite__mapDeps([2,3,1,4,5]))),oJ=Pn,qA="docs/tasks",AS="spur:detail-width",lJ=new Set(["blocked","cancelled","deprecated"]);function cJ(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 VA(e){const{onSelectTask:t,filters:n,folder:r,hiddenColumns:s,onConnectionChange:i,onSyncChange:o}=e,[l,c]=h.useState({}),[u,d]=h.useState(qA),[p,f]=h.useState(null),[m,b]=h.useState(()=>{const V=typeof window<"u"?Math.min(1728,window.innerWidth*.8):1728;if(typeof window>"u")return V;try{const te=Number.parseFloat(window.localStorage.getItem(AS)??"");if(Number.isFinite(te)&&te>0)return Math.min(te,window.innerWidth*.8)}catch{}return V}),x=r??u,y=s??lJ,E=h.useCallback(()=>xt.task.list({folder:x}),[x]),{tasks:A,loading:w,error:N,connected:_,lastSyncAt:k,setTasks:S,store:v}=Ux(E),[O,C]=h.useState(null);h.useEffect(()=>{i?.(_)},[_,i]),h.useEffect(()=>{o?.(k)},[k,o]),h.useEffect(()=>{typeof xt.task.folders=="function"&&xt.task.folders({}).then(V=>{const{data:te,activeFolder:L}=V,ye=L??te?.[0]?.path;ye!==void 0&&d(ye)}).catch(()=>{})},[]),h.useEffect(()=>{document.documentElement.style.setProperty("--detail-w",`${m}px`)},[m]),h.useEffect(()=>{if(!p)return;const V=te=>{te.key==="Escape"&&f(null)};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[p]);const M=Ji();h.useEffect(()=>{const V=M.pathname.split("/"),te=V.indexOf("tasks"),L=te>=0?V[te+1]:void 0;L&&/^\d{4}$/.test(L)&&f(L)},[M.pathname]);const B=hS(o0,{activationConstraint:{distance:5}}),R=hS(a0),z=MX(B,R),W=cJ(A,n),F=V=>{c(te=>{const L={...te};return te[V]==="asc"?L[V]="desc":te[V]==="desc"?delete L[V]:L[V]="asc",L})},J=V=>{const te=W.filter(ye=>ye.status===V),L=l[V]??"desc";return[...te].sort((ye,xe)=>{const P=ye.wbs.localeCompare(xe.wbs);return L==="asc"?P:-P})},K=V=>A.find(te=>te.wbs===V),X=V=>{C(String(V.active.id))},I=V=>{C(null);const{active:te,over:L}=V;if(!L)return;const ye=String(te.id),xe=String(L.id),P=K(ye);if(!P||P.status===xe)return;const oe=[...A];S(re=>re.map(H=>H.wbs===ye?{...H,status:xe}:H)),xt.task.transition({wbs:ye,toStatus:xe}).catch(re=>{S(oe);const H=re instanceof Error?re.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:H}}))})};return w?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(ln,{size:"lg",className:"text-spur-accent"})}):N?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center text-spur-text-muted",children:[a.jsx("p",{className:"text-lg font-semibold",children:"Failed to load tasks"}),a.jsx("p",{className:"text-sm",children:N.message})]})}):a.jsx(Mk.Provider,{value:v,children:a.jsxs(OQ,{sensors:z,onDragStart:X,onDragEnd:I,children:[a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsx("div",{className:"flex gap-3 overflow-x-auto h-full p-4",children:oJ.filter(V=>!y.has(V)).map(V=>a.jsx(aJ,{status:V,label:V,tasks:J(V),onCardClick:te=>{f(te),t(te)},sortDir:l[V],onSortToggle:()=>F(V)},V))}),p&&a.jsxs(a.Fragment,{children:[a.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:()=>f(null)}),a.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:[a.jsx(ka,{targetVar:"--detail-w",onResizeEnd:V=>{const te=Math.max(576,Math.min(V,window.innerWidth*.8));b(te);try{window.localStorage.setItem(AS,String(te))}catch{}},direction:"horizontal",invert:!0}),a.jsx("div",{className:"flex flex-col flex-1 overflow-hidden",children:a.jsx("div",{className:"flex-1 overflow-y-auto","data-testid":"detail-body",children:(()=>{const V=A.find(te=>te.wbs===p);return V?a.jsx(h.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center h-32 text-spur-text-muted text-sm",children:"Loading detail..."}),children:a.jsx(iJ,{task:V,onClose:()=>f(null),onTransition:(te,L)=>{S(ye=>ye.map(xe=>xe.wbs===te?{...xe,status:L}:xe)),xt.task.transition({wbs:te,toStatus:L}).catch(ye=>{const xe=ye instanceof Error?ye.message:"Transition failed";typeof window<"u"&&window.dispatchEvent(new CustomEvent("api-error",{detail:{message:xe}}))})}})}):null})()})})]})]})]}),a.jsx(JQ,{dropAnimation:null,children:O?(()=>{const V=K(O);return V?a.jsx("div",{className:"opacity-90",children:a.jsx(WA,{task:V,onClick:()=>{}})}):null})():null})]})})}const Md=[{id:"kanban",label:"Kanban",component:VA}];function YA(){const[e,t]=Ca(),n=Ji(),r=mc(),s=h.useMemo(()=>{const c=n.pathname.split("/"),u=c.indexOf("tasks"),d=u>=0?c[u+1]:void 0;return d&&/^\d{4}$/.test(d)?d:e.get("selected")},[n.pathname,e]),i=h.useMemo(()=>{const c={},u=e.get("status"),d=e.get("feature"),p=e.get("parent"),f=e.get("assignee"),m=e.get("folder");return u!==null&&(c.status=u),d&&(c.featureId=d),p&&(c.parentWbs=p),f&&(c.assignee=f),m&&(c.folder=m),c},[e]);return{selected:s,filters:i,selectTask:c=>{const u=new URLSearchParams(e);u.delete("selected");const d=u.toString(),p=c?`/board/tasks/${c}`:"/board/tasks";r(`${p}${d?`?${d}`:""}`,{replace:!0})},setFilter:(c,u)=>{t(d=>{const p=new URLSearchParams(d);return c==="feature"&&p.delete("parent"),c==="parent"&&p.delete("feature"),u!==null?p.set(c,u):p.delete(c),p},{replace:!0})}}}function uJ(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 dJ(){const{selectTask:e,setFilter:t,filters:n}=YA(),[r,s]=h.useState(qA),[i,o]=h.useState([]),[l,c]=h.useState("kanban"),[u,d]=h.useState(!1),[p,f]=h.useState(""),[m,b]=h.useState(!1),[x,y]=h.useState(void 0),E=n.folder??r,A=new Set(n.status===void 0?Pn.filter(S=>S!=="blocked"&&S!=="cancelled"&&S!=="deprecated"):n.status.split(",").filter(S=>Pn.some(v=>v===S))),w=new Set(Pn.filter(S=>!A.has(S)));h.useEffect(()=>{f(n.featureId??n.parentWbs??"")},[n.featureId,n.parentWbs]),h.useEffect(()=>{typeof xt.task.folders=="function"&&xt.task.folders({}).then(S=>{const{data:v,activeFolder:O}=S,C=O??v?.[0]?.path;v&&o(v),C!==void 0&&s(C)}).catch(()=>{})},[]);const N=S=>{const v=new Set(A);v.has(S)?v.delete(S):v.add(S),t("status",Pn.filter(O=>v.has(O)).join(","))},_=S=>{S.preventDefault();const v=uJ(p);if(v.kind==="navigate"){e(v.wbs),f("");return}t(v.key,v.value||null)},k=(Md.find(S=>S.id===l)??Md[0]).component;return a.jsxs("div",{className:"task-kanban flex flex-col h-full",children:[a.jsx("header",{className:"mx-auto w-full max-w-[1600px] shrink-0 px-4 pt-3",children:a.jsxs("div",{className:"flex flex-nowrap items-center justify-between gap-4 border-b border-spur-border pb-3",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[a.jsx(Rr,{id:"tasks",size:"lg",className:"h-7 w-7 text-spur-accent","aria-hidden":"true"}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx("h1",{className:"text-xl font-bold tracking-tight text-spur-text",children:"Tasks"}),a.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-spur-border bg-spur-surface-2 px-2.5 py-0.5 text-xs text-spur-text-muted font-mono",role:"status","data-testid":"tasks-live-chip",children:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${m?"bg-spur-success":"bg-spur-error"}`,"aria-hidden":"true"}),"last sync ",x?new Date(x).toLocaleString():"—"]})]}),a.jsx("p",{className:"text-xs text-spur-text-muted mt-0.5",children:"Task corpus, kanban lanes, and phase filters"})]})]}),a.jsxs("div",{className:"flex min-w-0 flex-nowrap items-center gap-2.5 overflow-x-auto",children:[a.jsx(qr,{variant:"ghost",size:"xs",className:"text-xs shrink-0 w-44 bg-spur-surface-2 border border-spur-border rounded-lg text-spur-text",value:E,onChange:S=>t("folder",S.target.value),"aria-label":"Task phase folder",children:i.map(S=>a.jsx("option",{value:S.path,children:S.label?`${S.label} (${S.path})`:S.path},S.path))}),a.jsx("div",{className:"flex shrink-0 items-center gap-1 bg-spur-surface-2 border border-spur-border px-2 py-1 rounded-xl",children:Pn.map(S=>a.jsxs("label",{htmlFor:`tasks-status-${S}`,className:"flex items-center gap-1.5 px-1.5 py-0.5 rounded-md hover:bg-spur-surface-3 transition-colors cursor-pointer",children:[a.jsx(Sx,{id:`tasks-status-${S}`,size:"xs",checked:!w.has(S),onChange:()=>N(S)}),a.jsxs("span",{className:"text-[11px] font-medium text-spur-text-muted select-none",children:[ef(S)," ",S]})]},S))}),a.jsx("form",{onSubmit:_,className:"flex shrink-0 items-center",children:a.jsx(Vn,{"aria-label":"Filter by WBS or feature",type:"text",placeholder:"WBS or feature",variant:"bordered",size:"xs",className:"w-36 bg-spur-surface-2 border-spur-border text-spur-text",value:p,onChange:S=>f(S.target.value)})}),a.jsx(Ie,{variant:"primary",size:"sm",className:"shrink-0 font-medium",onClick:()=>d(!0),children:"+ New Task"}),a.jsx("div",{className:"flex shrink-0 items-center gap-1 bg-spur-surface-2 border border-spur-border p-1 rounded-xl",children:Md.map(S=>a.jsx("button",{type:"button",className:`px-3 py-1.5 text-xs font-semibold rounded-lg transition-all ${l===S.id?"bg-primary text-primary-content font-bold shadow-sm":"text-spur-text-muted hover:text-spur-text hover:bg-spur-surface-3"}`,onClick:()=>c(S.id),children:S.label},S.id))})]})]})}),a.jsx(Lk,{folder:E}),a.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:a.jsx(k,{onSelectTask:e,filters:n,folder:E,hiddenColumns:w,onConnectionChange:b,onSyncChange:y})}),a.jsx(Ok,{open:u,onClose:()=>d(!1),onCreated:()=>{},folder:E})]})}function pJ(e,t){xt.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 fJ(){const{filters:e,selectTask:t}=YA();return a.jsx("div",{className:"task-kanban flex flex-col h-full",children:a.jsx("div",{"data-kanban-board":!0,className:"flex-1 overflow-hidden",children:a.jsx(VA,{onSelectTask:t,filters:e})})})}const mJ={id:"tasks",name:"Tasks",icon:"📋",route:"tasks",component:dJ,sidebarLabel:"Tasks",description:"Task kanban, lifecycle status, and per-task detail",order:40},hJ=Object.freeze(Object.defineProperty({__proto__:null,TaskKanbanView:fJ,module:mJ,transition:pJ},Symbol.toStringTag,{value:"Module"}));function KA(e){return e===null||typeof e!="object"?null:"module"in e&&CS(e.module)?e.module:"default"in e&&CS(e.default)?e.default:null}function CS(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 ZA(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 gJ(e){const t=[],n=e("./*/index.{ts,tsx}",{eager:!0});for(const r of Object.values(n)){const s=KA(r);s&&t.push(s)}return t.sort((r,s)=>r.id.localeCompare(s.id)),t.sort(ZA),t}function bJ(){try{return gJ(()=>Object.assign({"./designs/index.tsx":Mq,"./features/index.tsx":cV,"./history/index.tsx":HV,"./observability/index.tsx":RK,"./plans/index.tsx":UK,"./projects/index.tsx":GZ,"./search/index.tsx":XZ,"./settings/index.tsx":wX,"./task-kanban/index.tsx":hJ}))}catch(s){if(typeof require!="function")throw s}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 xJ(r,{readdirSync:(s,i)=>e.readdirSync(s,i),tryRequire:s=>require(s)})}function xJ(e,t){const n=require("node:path"),r=[];let s=[];try{s=t.readdirSync(e,{withFileTypes:!0})}catch{return r}const i=s.filter(o=>o.isDirectory()).map(o=>o.name).sort((o,l)=>o.localeCompare(l));for(const o of i)for(const l of["tsx","ts"]){const c=n.join(e,o,`index.${l}`);try{const u=t.tryRequire(c),d=KA(u);if(d){r.push(d);break}}catch{}}return r.sort(ZA),r}function XA(e,t){const n=new Set(t?.disabled??[]),r=e.slice(),s=new Set(n),i=t?.defaultModuleId;function o(){return r.filter(l=>!s.has(l.id))}return yJ(r),{get modules(){return o()},getModule(l){return o().find(c=>c.id===l)},get defaultModule(){const l=o();if(i){const c=l.find(u=>u.id===i);if(c)return c}return l[0]},disableModule(l){s.add(l)},enableModule(l){s.delete(l)},getEnabledModules(){return o().map(l=>l.id)}}}function yJ(e){const t=new Map,n=new Map;for(const r of e){const s=t.get(r.id);if(s!==void 0)throw new Error(`Duplicate module id "${r.id}" discovered in two sources: ${s} and ${hl(r)}`);t.set(r.id,hl(r));const i=n.get(r.route);if(i!==void 0)throw new Error(`Duplicate module route "${r.route}" discovered in two sources: ${i} and ${hl(r)}`);n.set(r.route,hl(r))}}function hl(e){return e.id}const c0=XA(bJ(),{disabled:Lj,defaultModuleId:jj}),Qi=c0;c0.modules;c0.defaultModule;const QA=h.createContext({registry:Qi,hostDiagnostics:[]});function EJ({value:e,children:t}){return a.jsx(QA.Provider,{value:e,children:t})}function JA(){return h.useContext(QA)}const Up="spur-board-layout-v3",_S="spur-board-layout-v2",IS="spur-board-layout",ir={version:3,sidebarWidth:240,rightPanelWidth:320,sidebarCollapsed:!0,rightPanelCollapsed:!0};function SJ(){try{const e=localStorage.getItem(Up);if(e){const s=JSON.parse(e);return{version:3,sidebarWidth:typeof s.sidebarWidth=="number"?s.sidebarWidth:ir.sidebarWidth,rightPanelWidth:typeof s.rightPanelWidth=="number"?s.rightPanelWidth:ir.rightPanelWidth,sidebarCollapsed:typeof s.sidebarCollapsed=="boolean"?s.sidebarCollapsed:ir.sidebarCollapsed,rightPanelCollapsed:typeof s.rightPanelCollapsed=="boolean"?s.rightPanelCollapsed:ir.rightPanelCollapsed}}const t=localStorage.getItem(_S),n=localStorage.getItem(IS),r=t||n;if(r){const s=JSON.parse(r),i={version:3,sidebarWidth:typeof s.sidebarWidth=="number"?s.sidebarWidth:ir.sidebarWidth,rightPanelWidth:typeof s.rightPanelWidth=="number"?s.rightPanelWidth:ir.rightPanelWidth,sidebarCollapsed:ir.sidebarCollapsed,rightPanelCollapsed:typeof s.rightPanelCollapsed=="boolean"?s.rightPanelCollapsed:ir.rightPanelCollapsed};try{localStorage.setItem(Up,JSON.stringify(i)),localStorage.removeItem(_S),localStorage.removeItem(IS)}catch{}return i}return{...ir}}catch{return{...ir}}}function wJ(e){try{localStorage.setItem(Up,JSON.stringify({...e,version:3}))}catch{}}const eC="spur.board.projects.draft.v1";function la(e){return{path:e,text:"",revision:0}}function vJ(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;const t=e;if(typeof t.path!="string"||typeof t.text!="string"||typeof t.revision!="number"||!Number.isFinite(t.revision))return null;const n={path:t.path,text:t.text,revision:t.revision};return t.pending!==void 0&&(n.pending=t.pending),n}function NJ(e){try{const t=globalThis.localStorage?.getItem(eC);if(t==null)return la(e);const n=vJ(JSON.parse(t));return n===null||n.path!==e?(Rl(la(e)),la(e)):n}catch{return la(e)}}function Rl(e){try{globalThis.localStorage?.setItem(eC,JSON.stringify(e))}catch{}}const TJ={draft:la(""),setText:()=>{},persistPending:()=>{},clearSubmitted:()=>{}},tC=h.createContext(TJ);function kJ(){return h.useContext(tC)}function AJ({children:e}){const n=Ms().path,[r,s]=h.useState(()=>la(""));h.useEffect(()=>{n!==null&&s(NJ(n))},[n]);const i=h.useMemo(()=>({draft:r,setText:o=>s(l=>{if(l.path!==n)return l;const c={...l,text:o,revision:l.revision+1};return Rl(c),c}),persistPending:o=>s(l=>{if(l.path!==r.path||l.revision!==r.revision)return l;const c={...l,pending:{requestKey:o,revision:l.revision}};return Rl(c),c}),clearSubmitted:(o,l)=>s(c=>{if(c.path!==l||c.revision!==o)return c;const u={path:c.path,text:"",revision:c.revision+1};return Rl(u),u})}),[r,n]);return a.jsx(tC.Provider,{value:i,children:e})}function CJ(){const[e,t]=h.useState([]);return h.useEffect(()=>{if(typeof window>"u")return;const n=r=>{const i=r.detail?.message||"An error occurred",o=`${Date.now()}-${Math.random().toString(36).slice(2,7)}`;t(l=>[...l,{id:o,message:i}]),setTimeout(()=>{t(l=>l.filter(c=>c.id!==o))},5e3)};return window.addEventListener("api-error",n),()=>{window.removeEventListener("api-error",n)}},[]),e.length===0?null:a.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=>a.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:[a.jsx("span",{className:"flex-1 break-words",children:n.message}),a.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(s=>s.id!==n.id)),"aria-label":"Close error toast",children:"×"})]},n.id))})}const _J="Enter",IJ=229;function RJ(e){return e.key===_J&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==IJ}const DJ=[{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"]}],OJ={sending:{icon:"…",label:"Sending",meaning:"the request is being stored",action:"wait for the mailbox",tone:"warn"},queued:{icon:"○",label:"Queued",meaning:"the orchestrator has not claimed it yet",action:"wait for the orchestrator",tone:"warn"},working:{icon:"◐",label:"In progress",meaning:"a member claimed it",action:"wait for the run to finish",tone:"warn"},delivered:{icon:"✓",label:"Delivered",meaning:"the member consumed the request",action:"read the reply in the Inbox tab",tone:"ok"},failed:{icon:"✕",label:"Failed",meaning:"delivery did not start or the run errored",action:"resend, or read the error in the Inbox tab",tone:"err"},unresolved:{icon:"!",label:"Unresolved",meaning:"the run left no verified outcome",action:"check the Inbox tab for the hold reason",tone:"warn"},absent:{icon:"·",label:"No receipt",meaning:"the request did not reach an inbox",action:"check the project binding and resend",tone:"warn"}};function LJ(e,t){return t?"sending":e===null?"absent":e.status==="failed"||["failed","errored","cancelled"].includes(e.runStatus??"")?"failed":e.runStatus==="running"?"working":e.reason!==null&&e.reason!==""?e.status==="delivered"?"unresolved":"working":e.status==="delivered"?"delivered":e.status==="claimed"?"working":"queued"}const jJ=[{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 MJ(e){if(!e)return!0;const{state:t,instanceId:n}=e.orchestrator;return t==="missing"||t==="unresolvable"||!n}function FJ({activeModule:e}){const[t,n]=h.useState(!1),[r,s]=h.useState(!1),[i,o]=h.useState(null),[l,c]=h.useState("auto"),[u,d]=h.useState(!1),[p,f]=h.useState(!1),[m,b]=h.useState(0),[x,y]=h.useState("all"),[E,A]=h.useState(DJ),w=h.useMemo(()=>{const Z=new Map;for(const Re of E){if(Array.isArray(Re.tags)){for(const rt of Re.tags)if(rt&&typeof rt=="string"){const ae=rt.trim().toLowerCase();Z.set(ae,(Z.get(ae)??0)+1)}}if(Re.category){const rt=Re.category.trim().toLowerCase();Z.set(rt,(Z.get(rt)??0)+1)}}const ke=["sp","cc","kk","wt","git","dev","sys","harness","builtin"];return["all",...Array.from(Z.keys()).sort((Re,rt)=>{const ae=ke.indexOf(Re),pe=ke.indexOf(rt);if(ae!==-1&&pe!==-1)return ae-pe;if(ae!==-1)return-1;if(pe!==-1)return 1;const De=(Z.get(rt)??0)-(Z.get(Re)??0);return De!==0?De:Re.localeCompare(rt)})]},[E]),N=Ms(),_=h.useRef({path:N.path,generation:0,inFlight:!1});_.current.path!==N.path&&(_.current={path:N.path,generation:_.current.generation+1,inFlight:!1}),h.useEffect(()=>()=>{_.current.generation+=1},[]);const{draft:k,setText:S,persistPending:v,clearSubmitted:O}=kJ(),C=N.fleet?.orchestrator?.instanceId,M=MJ(N.fleet),[B,R]=h.useState(null),[z,W]=h.useState(!1),[F,J]=h.useState(null),[K,X]=h.useState(0);h.useEffect(()=>{N.path,s(!1),o(null),R(null),W(!1),J(null)},[N.path]),h.useEffect(()=>{if(i===null)return;let Z=!1;return(async()=>{try{const ke=await xt.inbox.requests({messageId:i});if(Z)return;const Fe=ke.find(Re=>Re.messageId===i);Fe!==void 0&&R({status:Fe.status,reason:Fe.reason,runStatus:Fe.runStatus}),W(!1)}catch{Z||W(!0)}})(),()=>{Z=!0}},[i,K]),h.useEffect(()=>{if(typeof EventSource>"u")return;const Z=new EventSource(`${it()}/events/planning`);return Z.onmessage=ke=>{try{const Fe=JSON.parse(ke.data).eventName;typeof Fe=="string"&&Fe.startsWith("message.")&&X(Re=>Re+1)}catch{}},()=>Z.close()},[]);const I=LJ(B,r),V=OJ[I],te=r||i!==null,L=te?`${V.label} — Next: ${V.action}`:"";h.useEffect(()=>{if(i===null||N.path===null||B===null||["completed","exited","failed","errored","cancelled"].includes(B.runStatus??"")||B.status!=="queued"&&B.status!=="claimed"&&B.runStatus!=="running")return;const Z=setInterval(()=>X(ke=>ke+1),2e3);return()=>clearInterval(Z)},[i,N.path,B]);const ye=h.useRef(null);h.useEffect(()=>{let Z=!0;return(async()=>{try{const ke=await Xe(new Request(`${it()}/agent/commands`));if(ke.ok){const Fe=await ke.json();Z&&Array.isArray(Fe.commands)&&Fe.commands.length>0&&A(Fe.commands)}}catch{}})(),()=>{Z=!1}},[]),h.useEffect(()=>{if(!u)return;const Z=ke=>{ye.current&&!ye.current.contains(ke.target)&&d(!1)};return document.addEventListener("click",Z),()=>document.removeEventListener("click",Z)},[u]),h.useEffect(()=>{k.text.startsWith("/")&&f(!1)},[k.text]);const xe=k.text.trim().toLowerCase(),P=xe.startsWith("/")&&!p,oe=P?E.filter(Z=>{const ke=x==="all"||Array.isArray(Z.tags)&&Z.tags.map(rt=>rt.toLowerCase()).includes(x)||Z.category.toLowerCase()===x,Fe=xe.startsWith("/")?xe.slice(1):xe,Re=Z.name.toLowerCase().startsWith(xe)||Z.name.toLowerCase().includes(Fe)||!!Z.argumentHint?.toLowerCase().includes(Fe)||Z.description.toLowerCase().includes(Fe)||Array.isArray(Z.tags)&&Z.tags.some(rt=>rt.toLowerCase().includes(Fe));return ke&&Re}):[],re=P&&oe.length>0,H=Z=>{S(`${Z} `),f(!0),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},Ce=Z=>{const ke=k.text,Fe=ke.length>0&&!ke.endsWith(" ")?`${ke} ${Z}`:`${ke}${Z}`;S(Fe),document.querySelector('[data-testid="agent-bar-input"]')?.focus()},me=()=>l==="auto"?C:N.fleet?.members?.find(ke=>ke.role===l||ke.instanceId===l)?.instanceId??C,he=async()=>{const Z=N.path,ke=me();if(Z===null||k.path!==Z||ke===void 0||_.current.inFlight)return;const Fe=++_.current.generation,Re=()=>_.current.path===Z&&_.current.generation===Fe,rt=k.text;if(rt.trim().length===0)return;_.current.inFlight=!0;const ae={text:rt,revision:k.revision},pe=k.pending!==void 0&&typeof k.pending.requestKey=="string"&&k.pending.requestKey.length>0&&k.pending.revision===k.revision?k.pending:void 0,De=pe!==void 0?pe.requestKey:crypto.randomUUID();v(De),J(null),s(!0),o(null),R(null),f(!0);try{const Me=await xt.inbox.send({...ke!==null?{to:ke}:{},body:ae.text,requestKey:De,...Z!==null?{projectPath:Z}:{}});if(!Re())return;R({status:Me.message.status,reason:null}),o(Me.message.id),O(ae.revision,Z)}catch(Me){Re()&&J(Me instanceof Error?Me.message:"the message was not sent")}finally{Re()&&(_.current.inFlight=!1,s(!1))}};if(!t)return a.jsxs(a.Fragment,{children:[a.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:L}),a.jsx(Ie,{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 Ne=N.fleet?.members&&N.fleet.members.length>0?[{id:"auto",label:"auto",desc:"Orchestrator auto-dispatch (default)"},...N.fleet.members.map(Z=>({id:Z.instanceId,label:Z.role||Z.instanceId,desc:`${Z.executor}${Z.model?` · ${Z.model}`:""}`}))]:jJ,Ge=k.text.trim().length===0||l==="auto"&&M;return a.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:[a.jsx("div",{role:"status","aria-live":"polite",className:"sr-only","data-agent-bar-live":!0,children:L}),re&&a.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:[a.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:[a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsx("span",{className:"font-mono text-spur-accent font-semibold text-[13px]",children:"/"}),a.jsx("span",{className:"font-mono text-[12px] font-medium text-spur-text",children:"Commands"}),a.jsxs("span",{className:"text-[11px] font-mono text-spur-text-muted",children:[oe.length," available"]})]}),a.jsx("div",{className:"flex items-center gap-1 overflow-x-auto no-scrollbar max-w-[65%] py-0.5",role:"tablist",children:w.slice(0,10).map(Z=>a.jsx("button",{type:"button",role:"tab","aria-selected":x===Z,onClick:()=>y(Z),className:`px-2 py-0.5 rounded text-[11px] font-mono transition-colors shrink-0 cursor-pointer ${x===Z?"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:Z==="all"?"All":Z},Z))})]}),a.jsx("div",{className:"flex flex-col py-1.5 px-2 max-h-[260px] overflow-y-auto",role:"listbox",children:oe.map((Z,ke)=>{const Fe=ke===m;return a.jsxs("button",{type:"button",role:"option","aria-selected":Fe,onClick:()=>H(Z.name),title:Z.description,className:`flex items-center w-full text-left px-3 py-2 rounded-lg cursor-pointer transition-colors ${Fe?"bg-spur-surface text-spur-accent font-medium":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 font-mono text-[13px] min-w-0 truncate flex-1",children:[a.jsx("span",{className:Fe?"font-semibold text-spur-accent":"font-medium text-spur-text",children:Z.name}),Z.argumentHint?a.jsx("span",{className:`font-mono text-xs truncate ${Fe?"text-spur-text/80":"text-spur-text-muted"}`,children:Z.argumentHint}):a.jsx("span",{className:`font-sans text-xs italic truncate ${Fe?"text-spur-text/60":"text-spur-text-muted/60"}`,children:Z.description})]}),a.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-2",children:(Z.tags&&Z.tags.length>0?Z.tags.slice(0,2):[Z.category]).map(Re=>a.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:Re},Re))})]},Z.name)})}),a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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:"↑↓"}),a.jsx("span",{children:"navigate"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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"}),a.jsx("span",{children:"complete"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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:"↵"}),a.jsx("span",{children:"execute"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.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"}),a.jsx("span",{children:"dismiss"})]})]}),a.jsxs("div",{className:"flex items-center gap-3 font-mono text-[11px]",children:[a.jsxs("button",{type:"button",onClick:()=>Ce("@"),className:"text-spur-text-muted hover:text-spur-accent cursor-pointer transition-colors flex items-center gap-0.5 group",title:"Reference files",children:[a.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"@"}),a.jsx("span",{className:"group-hover:text-spur-text",children:"files"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("button",{type:"button",onClick:()=>Ce("#"),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:[a.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"#"}),a.jsx("span",{className:"group-hover:text-spur-text",children:"context"})]}),a.jsx("span",{className:"text-spur-border",children:"•"}),a.jsxs("button",{type:"button",onClick:()=>Ce("!"),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:[a.jsx("span",{className:"font-semibold text-spur-accent group-hover:underline",children:"!"}),a.jsx("span",{className:"group-hover:text-spur-text",children:"bash"})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-spur-text-muted font-mono text-sm select-none font-bold pl-1",children:">"}),a.jsxs("div",{className:"relative shrink-0",ref:ye,children:[a.jsxs("button",{type:"button",onClick:()=>d(Z=>!Z),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:[a.jsx("span",{className:"text-spur-text-muted font-sans text-[11px]",children:"to:"}),a.jsx("span",{className:"font-semibold",children:Ne.find(Z=>Z.id===l)?.label??l}),a.jsx("span",{className:"text-spur-text-muted text-[10px] group-hover:text-spur-text transition-colors",children:"▾"})]}),u&&a.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:[a.jsx("div",{className:"px-2.5 py-1 text-[10px] font-mono text-spur-text-muted uppercase tracking-wider",children:"Dispatch Target"}),Ne.map(Z=>a.jsxs("button",{type:"button",onClick:()=>{c(Z.id),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===Z.id?"bg-spur-accent/15 text-spur-accent font-semibold":"hover:bg-base-200 text-spur-text-muted hover:text-spur-text"}`,children:[a.jsxs("div",{className:"flex flex-col",children:[a.jsx("span",{className:"font-medium text-spur-text",children:Z.label}),a.jsx("span",{className:"text-[10px] text-spur-text-muted",children:Z.desc})]}),l===Z.id&&a.jsx("span",{className:"text-[12px]",children:"✓"})]},Z.id))]})]}),a.jsx(aG,{variant:"ghost",rows:1,value:k.text,onChange:Z=>S(Z.target.value),onKeyDown:Z=>{if(re&&oe.length>0){if(Z.key==="ArrowDown"){Z.preventDefault(),b(ke=>(ke+1)%oe.length);return}if(Z.key==="ArrowUp"){Z.preventDefault(),b(ke=>(ke-1+oe.length)%oe.length);return}if(Z.key==="Tab"){Z.preventDefault();const ke=oe[m];ke&&H(ke.name);return}if(Z.key==="Escape"){Z.preventDefault(),f(!0);return}}RJ(Z)&&(Ge||(Z.preventDefault(),he()))},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"}),a.jsx(Ie,{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"&&M&&a.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."}),F!==null&&a.jsxs("div",{role:"alert",className:"rounded-lg px-2.5 py-1 text-xs bg-spur-error/10 text-spur-error",children:["Not sent: ",F]}),te&&a.jsxs("div",{"data-receipt-state":I,role:"status",className:`rounded-lg px-2.5 py-1 text-xs ${V.tone==="err"?"bg-spur-error/10 text-spur-error":V.tone==="warn"?"bg-spur-warning/10 text-spur-warning":"bg-spur-success/10 text-spur-success"}`,children:[a.jsx("span",{"aria-hidden":"true",className:"mr-1",children:V.icon}),a.jsx("span",{className:"font-medium",children:V.label}),a.jsxs("span",{className:"text-spur-text-muted",children:[" ","— ",V.meaning," Next: ",V.action,"."]}),z&&a.jsx("span",{className:"text-spur-text-muted",children:" (results feed unavailable)"})]})]})}function PJ(e){return u0(e.host)?`${e.name} (${e.host?.trim()})`:e.name}function u0(e){const t=e?.trim().toLowerCase();return t!==void 0&&t!==""&&t!=="localhost"&&t!=="127.0.0.1"&&t!=="::1"}function BJ(e){return e.port<=0||!e.running&&!u0(e.host)?null:`http://${e.host?.trim()||"localhost"}:${e.port}/board`}async function $J(e,t){return Promise.all(e.map(async n=>!n.running&&n.port>0&&u0(n.host)?{...n,running:await t(`http://${n.host?.trim()}:${n.port}/api/health`)}:n))}async function UJ(e){try{return await Xe(new Request(e,{mode:"no-cors"}),1500),!0}catch{return!1}}function zJ({name:e}){let t=0;for(let o=0;o<e.length;o++)t=(t<<5)-t+e.charCodeAt(o),t|=0;const n=Math.abs(t)%8,s=["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],i=()=>{switch(n){case 0:return a.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:[a.jsx("path",{d:"M8 1.5l5.5 3.2v6.6L8 14.5l-5.5-3.2V4.7L8 1.5z"}),a.jsx("path",{d:"M8 1.5v13M2.5 4.7l5.5 3.3 5.5-3.3"})]});case 1:return a.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:[a.jsx("rect",{x:"2",y:"2.5",width:"12",height:"11",rx:"2"}),a.jsx("path",{d:"M5 6l2.5 2L5 10M8.5 10H11"})]});case 2:return a.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:[a.jsx("circle",{cx:"4.5",cy:"4",r:"1.5"}),a.jsx("circle",{cx:"4.5",cy:"12",r:"1.5"}),a.jsx("circle",{cx:"11.5",cy:"7",r:"1.5"}),a.jsx("path",{d:"M4.5 5.5v5M4.5 7.5a4 4 0 004-1"})]});case 3:return a.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:[a.jsx("path",{d:"M8 2l5.5 3-5.5 3-5.5-3L8 2z"}),a.jsx("path",{d:"M2.5 8l5.5 3 5.5-3M2.5 11l5.5 3 5.5-3"})]});case 4:return a.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:[a.jsx("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1.5"}),a.jsx("path",{d:"M6 1.5v2M10 1.5v2M6 12.5v2M10 12.5v2M1.5 6h2M1.5 10h2M12.5 6h2M12.5 10h2"})]});case 5:return a.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:a.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 a.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:a.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 a.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:[a.jsx("circle",{cx:"8",cy:"8",r:"6"}),a.jsx("path",{d:"M2 8h12M8 2a9 9 0 010 12 9 9 0 010-12z"})]})}};return a.jsx("span",{"data-testid":"project-avatar-icon",className:`flex h-7 w-7 items-center justify-center rounded border ${s}`,children:i()})}function RS({currentName:e,collapsed:t=!1}){const[n,r]=h.useState(!1),[s,i]=h.useState([]),[o,l]=h.useState(null),[c,u]=h.useState(null),d=h.useRef(null);h.useEffect(()=>{if(!n)return;const m=new AbortController;return Xe(new Request(`${it()}/projects`,{signal:m.signal})).then(async b=>{if(!b.ok)return;const y=(await b.json()).projects??[];i(y);const E=await $J(y,UJ);m.signal.aborted||i(E)}).catch(()=>{u("Failed to load projects")}),()=>m.abort()},[n]),h.useEffect(()=>{if(!n)return;const m=x=>{x.key==="Escape"&&r(!1)},b=x=>{d.current&&!d.current.contains(x.target)&&r(!1)};return document.addEventListener("keydown",m),document.addEventListener("mousedown",b),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",b)}},[n]);const p=async m=>{if(m.current){r(!1);return}const b=BJ(m);if(b){window.location.href=b;return}l(m.name);try{const x=await Xe(new Request(`${it()}/projects/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:m.name,path:m.path})}));if(!x.ok)throw new Error("Failed to start project");const y=await x.json();window.location.href=y.url||`http://${m.host??"localhost"}:${y.port}/board`}catch(x){u(x instanceof Error?x.message:"Start failed"),l(null)}},f=a.jsxs("button",{type:"button",onClick:()=>r(m=>!m),"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:[a.jsx("span",{className:`items-center justify-center ${n?"hidden":"flex group-hover:hidden"}`,children:a.jsx(zJ,{name:e})}),a.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:a.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:a.jsx("path",{d:"M4 6l4 4 4-4"})})})]});return a.jsxs("div",{className:`relative ${t?"flex items-center justify-center":"min-w-0 flex-1"}`,ref:d,children:[t?n?f:a.jsx(ur,{position:"right",tip:`Switch project: ${e}`,className:"block",children:f}):a.jsxs("button",{type:"button",onClick:()=>r(m=>!m),"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:[a.jsx("span",{className:"font-semibold truncate",children:e}),a.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:a.jsx("path",{d:"M4 6l4 4 4-4"})})]}),n&&a.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:[a.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"}),s.length===0?a.jsx("div",{className:"px-2 py-1.5 text-xs text-spur-text-muted",children:c||"No projects registered"}):s.map(m=>a.jsxs("button",{type:"button",role:"option","aria-selected":m.current,disabled:o===m.name,onClick:()=>p(m),"data-testid":`project-item-${m.name}`,className:`flex w-full items-center justify-between rounded px-2 py-1.5 text-xs text-left transition-colors ${m.current?"bg-spur-accent/15 text-spur-accent font-medium":"text-spur-text hover:bg-spur-border/30"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[a.jsx("span",{className:`h-2 w-2 rounded-full shrink-0 ${m.running?"bg-green-500":"bg-gray-400"}`,title:m.running?`Running on port ${m.port}`:"Stopped"}),a.jsx("span",{className:"truncate",children:PJ(m)})]}),o===m.name?a.jsx("span",{className:"text-[10px] text-spur-accent animate-pulse",children:"Starting..."}):m.current?a.jsx("span",{className:"text-[10px] font-semibold text-spur-accent",children:"current"}):m.running?a.jsxs("span",{className:"text-[10px] text-spur-text-muted",children:[":",m.port]}):a.jsx("span",{className:"text-[10px] text-spur-text-muted",children:"stopped"})]},m.path))]})]})}const nC="spur-theme";function HJ(){try{const e=localStorage.getItem(nC);if(e==="light"||e==="dark")return e}catch{}return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function GJ(e){document.documentElement.setAttribute("data-theme",e);try{localStorage.setItem(nC,e)}catch{}}function WJ(e){const t=e==="dark"?"light":"dark";return GJ(t),t}function DS(){const[e,t]=h.useState(HJ);h.useEffect(()=>{const s=window.matchMedia("(prefers-color-scheme: dark)"),i=o=>{if(!(()=>{try{return localStorage.getItem("spur-theme")}catch{return null}})()){const c=o.matches?"dark":"light";t(c),document.documentElement.setAttribute("data-theme",c)}};return s.addEventListener("change",i),()=>s.removeEventListener("change",i)},[]);const n=h.useCallback(()=>t(WJ),[]),r=e==="dark"?"Switch to light mode":"Switch to dark mode";return a.jsx(Ie,{variant:"ghost",size:"sm",onClick:n,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","aria-label":r,title:r,children:e==="dark"?a.jsx(AG,{className:"h-4 w-4 shrink-0",strokeWidth:1.8,"aria-hidden":"true"}):a.jsx(vG,{className:"h-4 w-4 shrink-0",strokeWidth:1.8,"aria-hidden":"true"})})}const qJ="Modules";function VJ(){const[e,t]=h.useState(qJ);return h.useEffect(()=>{const n=new AbortController;return Xe(new Request(`${it()}/project`,{signal:n.signal})).then(async r=>{if(!r.ok)return;const s=await r.json();s.name&&t(s.name)}).catch(()=>{}),()=>n.abort()},[]),e}function YJ({direction:e}){const t=e==="expand";return a.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:[a.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"}),a.jsx("line",{x1:"6",y1:"2",x2:"6",y2:"14"}),t?a.jsx("path",{d:"M9 6l2 2-2 2"}):a.jsx("path",{d:"M11 6l-2 2 2 2"})]})}function OS({collapsed:e,onToggle:t}){const n=e?"Expand sidebar":"Collapse sidebar";return a.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:a.jsx(YJ,{direction:e?"expand":"collapse"})})}function LS({collapsed:e}){const t=a.jsx(MS,{to:"/board/settings","aria-label":"Open settings",title:"Open settings","data-testid":"sidebar-settings",className:({isActive:n})=>`flex h-8 w-8 items-center justify-center rounded-md transition-colors ${n?"bg-spur-accent/20 text-spur-accent":"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:a.jsx("svg",{className:"h-4 w-4 shrink-0",viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:a.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"})})});return e?a.jsx(ur,{position:"right",tip:"Settings",className:"block",children:t}):t}function KJ({collapsed:e,onToggle:t,onMobileClose:n}){const r=VJ(),{registry:s}=JA();return a.jsxs("aside",{className:`flex flex-col bg-spur-surface border-r border-spur-border ${e?"overflow-visible":"overflow-hidden"}`,children:[a.jsx("div",{"data-spur-drag-region":"","data-testid":"desktop-drag-region",className:"h-0 w-full shrink-0","aria-hidden":"true"}),e?a.jsx("div",{className:"flex items-center justify-center border-b border-spur-border shrink-0 py-2",children:a.jsx(RS,{currentName:r,collapsed:!0})}):a.jsxs("div",{className:"flex items-center justify-between gap-1 p-3 border-b border-spur-border shrink-0",children:[a.jsx(RS,{currentName:r}),n&&a.jsx(Ie,{variant:"ghost",size:"sm",className:"text-spur-text-muted md:hidden",onClick:n,"aria-label":"Close navigation",children:"✕"})]}),a.jsx("nav",{className:`flex-1 ${e?"overflow-visible":"overflow-y-auto"}`,children:s.modules.filter(i=>i.id!=="settings").map(i=>{const o=i.sidebarLabel??i.name,l=a.jsxs(MS,{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:[a.jsx("span",{className:"flex h-5 w-5 items-center justify-center shrink-0",children:a.jsx(Rr,{id:i.id,icon:i.icon})}),!e&&a.jsx("span",{children:o})]},i.id);if(e){const c=i.description?`${o}
320
320
  ${i.description}`:o;return a.jsx(ur,{position:"right",tip:c,className:"[&:before]:whitespace-pre-line block",children:l},i.id)}return l})}),a.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?a.jsxs(a.Fragment,{children:[a.jsx(DS,{}),a.jsx(LS,{collapsed:!0}),a.jsx(OS,{collapsed:!0,onToggle:t})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(DS,{}),a.jsx(LS,{})]}),a.jsx(OS,{collapsed:!1,onToggle:t})]})})]})}function ZJ({children:e,mobileHeader:t,framed:n=!1}){return a.jsxs("main",{className:"flex flex-col h-full overflow-hidden bg-spur-bg",children:[t,a.jsx("div",{className:n?"flex flex-1 min-h-0 flex-col overflow-hidden":"flex-1 min-h-0 overflow-auto",children:e})]})}function XJ({collapsed:e,onToggle:t,onMobileClose:n,children:r,actions:s}){return a.jsxs("aside",{className:"flex flex-col bg-spur-surface border-l border-spur-border overflow-hidden",children:[n&&a.jsx("div",{className:"hidden max-md:flex items-center justify-center py-2 shrink-0",children:a.jsx("div",{className:"w-10 h-1 rounded-full bg-spur-border"})}),a.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-spur-border shrink-0",children:[!e&&a.jsx("span",{className:"text-sm font-semibold text-spur-text",children:r?"Context":""}),a.jsx("div",{className:"flex items-center gap-1",children:s}),a.jsxs("div",{className:"flex items-center gap-1",children:[n&&a.jsx(Ie,{variant:"ghost",size:"sm",className:"text-spur-text-muted md:hidden",onClick:n,"aria-label":"Close panel",children:"✕"}),a.jsx(Ie,{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&&a.jsx("div",{className:"flex-1 overflow-y-auto p-3",children:r})]})}const QJ=h.createContext(void 0);function JJ(){const[e,t]=h.useState(()=>SJ()),[n,r]=h.useState(!1),[s,i]=h.useState(!1),o=Ji(),{registry:l,hostDiagnostics:c}=JA(),u=(()=>{const _=o.pathname.split("/"),k=_.indexOf("board"),S=k>=0?_[k+1]:void 0;if(!S)return;const v=S==="modules"&&_[k+2]?`modules/${_[k+2]}`:S;return l.modules.find(O=>O.route===v)})();h.useLayoutEffect(()=>{const _=document.documentElement;_.style.setProperty("--sidebar-w",`${e.sidebarWidth}px`),_.style.setProperty("--rightpanel-w",`${e.rightPanelWidth}px`)},[e.sidebarWidth,e.rightPanelWidth]);const d=h.useCallback(_=>wJ(_),[]),p=h.useCallback(()=>{t(_=>{const k={..._,sidebarCollapsed:!_.sidebarCollapsed};return d(k),k})},[d]),f=h.useCallback(()=>{t(_=>{const k={..._,rightPanelCollapsed:!_.rightPanelCollapsed};return d(k),k})},[d]),m=h.useCallback(_=>t(k=>{const S={...k,sidebarWidth:_};return d(S),S}),[d]),b=h.useCallback(_=>t(k=>{const S={...k,rightPanelWidth:_};return d(S),S}),[d]),x=h.useCallback(()=>{r(!1),i(!1)},[]),y=h.useCallback(_=>{_.key==="Escape"&&x()},[x]),E=u?.rightPanelComponent,A=u?.contributionType==="iframe";h.useLayoutEffect(()=>{E&&e.rightPanelCollapsed&&t(_=>({..._,rightPanelCollapsed:!1}))},[E,e.rightPanelCollapsed]);const w=a.jsxs("div",{className:"mobile-bar",children:[a.jsx(Ie,{variant:"ghost",size:"sm",className:"text-spur-text",onClick:()=>r(!0),"aria-label":"Open navigation",children:"☰"}),a.jsx("span",{className:"text-sm font-semibold text-spur-text",children:u?.name??"Spur"}),!A&&a.jsx(Ie,{variant:"ghost",size:"sm",className:"text-spur-text",onClick:()=>i(!0),"aria-label":"Open panel",children:"◧"})]}),N=n||s;return a.jsx(cZ,{children:a.jsxs(AJ,{children:[N&&a.jsx("div",{className:"fixed inset-0 z-40 bg-black/50 md:hidden",onClick:x,onKeyDown:y,"aria-hidden":"true"}),a.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(s),"data-framed-workspace":String(A),children:a.jsxs(QJ.Provider,{value:u,children:[a.jsx(KJ,{collapsed:e.sidebarCollapsed&&!n,onToggle:p,onMobileClose:x}),a.jsx(ka,{targetVar:"--sidebar-w",onResizeEnd:m}),a.jsxs(ZJ,{mobileHeader:w,framed:A,children:[a.jsx(Tj,{diagnostics:c}),a.jsx(bC,{})]}),!A&&a.jsxs(a.Fragment,{children:[a.jsx(ka,{targetVar:"--rightpanel-w",onResizeEnd:b}),a.jsx(XJ,{collapsed:e.rightPanelCollapsed,onToggle:f,onMobileClose:x,children:E?u&&u.contributionType==="react"?a.jsx(Xw,{moduleId:u.id,category:"panel",children:a.jsx(E,{})}):a.jsx(E,{}):null})]})]})}),!A&&a.jsx(FJ,{activeModule:u}),a.jsx(CJ,{})]})})}const eee=[{from:"workspace",to:"/board/projects"},{from:"teams",to:"/board/settings/agents"}];function zp(e){return e.contributionType==="react"||e.contributionType==="iframe"}function jS(e){const t=e.component;return zp(e)?a.jsx(Xw,{moduleId:e.id,children:a.jsx(t,{})}):a.jsx(t,{})}function tee(e){const t=e.defaultModule;return t&&!zp(t)?t:e.modules.find(n=>!zp(n))??t}function rC(e){const t=tee(e);return[{path:"/board",element:a.jsx(JJ,{}),children:[{index:!0,element:a.jsx(_o,{to:t?`/board/${t.route}`:"/board",replace:!0})},...eee.flatMap(n=>[{path:n.from,element:a.jsx(_o,{to:n.to,replace:!0})},{path:`${n.from}/*`,element:a.jsx(_o,{to:n.to,replace:!0})}]),...e.modules.flatMap(n=>[{path:n.route,element:jS(n)},{path:`${n.route}/*`,element:jS(n)}])]},{path:"/",element:a.jsx(_o,{to:t?`/board/${t.route}`:"/board",replace:!0})}]}rC(Qi);function nee(e=Qi){return xC(rC(e))}async function ree(e=()=>xt.board.modules()){const t=await e().catch(()=>null),n=await Oj(t,Qi.modules);try{return{registry:XA([...n.modules]),hostDiagnostics:n.hostDiagnostics}}catch(r){return{registry:Qi,hostDiagnostics:[...n.hostDiagnostics,{moduleId:"catalog",category:"catalog",message:r instanceof Error?r.message:String(r)}]}}}function hee(){const[e,t]=h.useState(null);return h.useEffect(()=>{let n=!0;return ree().then(r=>{n&&t({value:r,router:nee(r.registry)})}),()=>{n=!1}},[]),e?a.jsx(EJ,{value:e.value,children:a.jsx(yC,{router:e.router})}):null}export{Ie as B,Sx as C,ln as L,wa as M,qr as S,pee as T,Ak as _,xt as a,YY as b,fee as c,tt as d,Ck as e,mee as f,Pn as g,hee as h,ree as l,Ta as m,ef as t,Ux as u};