@rudderhq/server 0.7.1 → 0.7.2-canary.0

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 (81) hide show
  1. package/package.json +14 -14
  2. package/ui-dist/assets/{LibraryLiveSurface-CZED7oKj.js → LibraryLiveSurface-CcsYG18H.js} +1 -1
  3. package/ui-dist/assets/{abnfDiagram-VRR7QNED-BoPyIoAq.js → abnfDiagram-VRR7QNED-C34K70lu.js} +1 -1
  4. package/ui-dist/assets/{arc-DTYs4RCH.js → arc-BYztEqom.js} +1 -1
  5. package/ui-dist/assets/{architectureDiagram-ZJ3FMSHR-BGfp2S_3.js → architectureDiagram-ZJ3FMSHR-BQKKX-d7.js} +1 -1
  6. package/ui-dist/assets/{blockDiagram-677ZJIJ3-aW0EGIUf.js → blockDiagram-677ZJIJ3-DPfaIbqb.js} +1 -1
  7. package/ui-dist/assets/{c4Diagram-LMCZKHZV--1itKgA2.js → c4Diagram-LMCZKHZV-BnwCM567.js} +1 -1
  8. package/ui-dist/assets/channel-Bmzlyjow.js +1 -0
  9. package/ui-dist/assets/{chunk-2Q5K7J3B-ZIqIozPQ.js → chunk-2Q5K7J3B-CFviCRuZ.js} +1 -1
  10. package/ui-dist/assets/{chunk-32BRIVSS-DiwBEZVQ.js → chunk-32BRIVSS-FoIxWB1d.js} +1 -1
  11. package/ui-dist/assets/{chunk-5VM5RSS4-CLOrTmL8.js → chunk-5VM5RSS4-EbAfuwwN.js} +1 -1
  12. package/ui-dist/assets/{chunk-EX3LRPZG-D6xZzF47.js → chunk-EX3LRPZG-CsStqjdd.js} +1 -1
  13. package/ui-dist/assets/{chunk-JWPE2WC7-B9tYvTZl.js → chunk-JWPE2WC7-Dw5KEviU.js} +1 -1
  14. package/ui-dist/assets/{chunk-MOJQB5TN-D_qo-SzM.js → chunk-MOJQB5TN-BlHlEWfj.js} +1 -1
  15. package/ui-dist/assets/{chunk-RYQCIY6F-ChPHGc2P.js → chunk-RYQCIY6F-BWw7BE01.js} +1 -1
  16. package/ui-dist/assets/{chunk-V7JOEXUC-Dk6GbZYp.js → chunk-V7JOEXUC-CxRvHZbj.js} +1 -1
  17. package/ui-dist/assets/{chunk-VR4S4FIN-B6AREC1T.js → chunk-VR4S4FIN-DZa_KwY9.js} +1 -1
  18. package/ui-dist/assets/{chunk-XXDRQBXY-CUyO-JUr.js → chunk-XXDRQBXY-Cnimf5j2.js} +1 -1
  19. package/ui-dist/assets/classDiagram-OUVF2IWQ-VR7MKiEz.js +1 -0
  20. package/ui-dist/assets/classDiagram-v2-EOCWNBFH-VR7MKiEz.js +1 -0
  21. package/ui-dist/assets/{cose-bilkent-JH36ORCC-BCxIInLZ.js → cose-bilkent-JH36ORCC-COCPT6B8.js} +1 -1
  22. package/ui-dist/assets/{cynefin-VYW2F7L2-DqsnpnHA.js → cynefin-VYW2F7L2-C5CybQ7c.js} +1 -1
  23. package/ui-dist/assets/{cynefinDiagram-TSTJHNR4-BD7QQNLW.js → cynefinDiagram-TSTJHNR4-BDrPLGpv.js} +1 -1
  24. package/ui-dist/assets/{dagre-VKFMJZFB-DaE160f7.js → dagre-VKFMJZFB-DXxPiE9D.js} +1 -1
  25. package/ui-dist/assets/{diagram-FQU43EPY-DZ0c59y8.js → diagram-FQU43EPY-CdC2pj_S.js} +1 -1
  26. package/ui-dist/assets/{diagram-G47NLZAW-C_413g5E.js → diagram-G47NLZAW-sEOwPe0_.js} +1 -1
  27. package/ui-dist/assets/{diagram-NH7WQ7WH-D_o9pXB-.js → diagram-NH7WQ7WH-CwoTfWmv.js} +1 -1
  28. package/ui-dist/assets/{diagram-OA4YK3LP-BI2xMqiW.js → diagram-OA4YK3LP-Cksc-JQa.js} +1 -1
  29. package/ui-dist/assets/{diagram-WEI45ONY-hhM8R_14.js → diagram-WEI45ONY-1lHRkCse.js} +1 -1
  30. package/ui-dist/assets/{ebnfDiagram-CCIWWBDH-DfFgEtmG.js → ebnfDiagram-CCIWWBDH-BJ6dNjJ2.js} +1 -1
  31. package/ui-dist/assets/{erDiagram-Q63AITRT-CCw4ysHK.js → erDiagram-Q63AITRT-DVTmCmE1.js} +1 -1
  32. package/ui-dist/assets/{flowDiagram-23GEKE2U-CzC1SMmo.js → flowDiagram-23GEKE2U-B2A6w103.js} +1 -1
  33. package/ui-dist/assets/{ganttDiagram-NO4QXBWP-CbPJIrIw.js → ganttDiagram-NO4QXBWP-BoqdQOBD.js} +1 -1
  34. package/ui-dist/assets/{gitGraphDiagram-IHSO6WYX-jCxJ66_C.js → gitGraphDiagram-IHSO6WYX-BPWVpzXj.js} +1 -1
  35. package/ui-dist/assets/{graph-BfNZ9Jzj.js → graph-W8QGT1XQ.js} +1 -1
  36. package/ui-dist/assets/{index-BE1vSI6a.js → index-96_7QHQ5.js} +1 -1
  37. package/ui-dist/assets/{index-DmjAbzHq.js → index-9ogi82-q.js} +1 -1
  38. package/ui-dist/assets/{index-SkHIC7Ma.js → index-BT3SfQnV.js} +1 -1
  39. package/ui-dist/assets/{index-B3h9Vdxx.js → index-BYt_CWxk.js} +1 -1
  40. package/ui-dist/assets/{index-Ck-ZNQeD.js → index-C8VKPswh.js} +4 -4
  41. package/ui-dist/assets/{index-B8q4cbOz.js → index-CG59QbM3.js} +1 -1
  42. package/ui-dist/assets/{index-D_K-9VDs.js → index-CRe48ije.js} +1 -1
  43. package/ui-dist/assets/{index-BULll2e0.js → index-CaNgMg06.js} +1 -1
  44. package/ui-dist/assets/{index-Chop-Dpa.js → index-CjRwrGKt.js} +1 -1
  45. package/ui-dist/assets/{index-ByUFNj0O.js → index-Cjq0R1QI.js} +1 -1
  46. package/ui-dist/assets/{index-D00XdcOq.js → index-CrOrmmHY.js} +1 -1
  47. package/ui-dist/assets/{index-DiMDROQY.js → index-D5okPECv.js} +1 -1
  48. package/ui-dist/assets/{index-Bwo-C8W5.js → index-DFhr5xg9.js} +1 -1
  49. package/ui-dist/assets/{index-BKn4zRjf.js → index-DTqh4VW9.js} +1 -1
  50. package/ui-dist/assets/{index-BjxRqzZK.js → index-UkFXcg--.js} +1 -1
  51. package/ui-dist/assets/{infoDiagram-FWYZ7A6U-BkDimGw3.js → infoDiagram-FWYZ7A6U-CGKM1qd0.js} +1 -1
  52. package/ui-dist/assets/{ishikawaDiagram-FXEZZL3T-BAyUfn6x.js → ishikawaDiagram-FXEZZL3T-BMINXmgJ.js} +1 -1
  53. package/ui-dist/assets/{journeyDiagram-5HDEW3XC-DlbpTZHG.js → journeyDiagram-5HDEW3XC-lLpvO5ye.js} +1 -1
  54. package/ui-dist/assets/{kanban-definition-HUTT4EX6-Cd67S14K.js → kanban-definition-HUTT4EX6-B1o_jb4m.js} +1 -1
  55. package/ui-dist/assets/{layout-Dc4YEiCC.js → layout-CfhTVz4J.js} +1 -1
  56. package/ui-dist/assets/{linear-BhRsbD_5.js → linear-Cyfw5mer.js} +1 -1
  57. package/ui-dist/assets/{map-CEWybj6z.js → map-BJC9PnTS.js} +1 -1
  58. package/ui-dist/assets/{mermaid.core-CqqAFYNg.js → mermaid.core-FscMPm7s.js} +4 -4
  59. package/ui-dist/assets/{mindmap-definition-LN4V7U3C-CCb-XmEi.js → mindmap-definition-LN4V7U3C-DRgxKOO8.js} +1 -1
  60. package/ui-dist/assets/{pegDiagram-2B236MQR-CqUV14VZ.js → pegDiagram-2B236MQR-Dvz4qHu-.js} +1 -1
  61. package/ui-dist/assets/{pieDiagram-ENE6RG2P-Dn_M_GRM.js → pieDiagram-ENE6RG2P-Dk2JI7ZR.js} +1 -1
  62. package/ui-dist/assets/{quadrantDiagram-ABIIQ3AL-rAEhJDr2.js → quadrantDiagram-ABIIQ3AL-rDcmmQtb.js} +1 -1
  63. package/ui-dist/assets/{railroadDiagram-RFXS5EU6-iE2o_jkH.js → railroadDiagram-RFXS5EU6-DuGw7Ver.js} +1 -1
  64. package/ui-dist/assets/{requirementDiagram-TGXJPOKE-BFyKBR1h.js → requirementDiagram-TGXJPOKE-B9FO6PRO.js} +1 -1
  65. package/ui-dist/assets/{sankeyDiagram-HTMAVEWB-DRa_2YB6.js → sankeyDiagram-HTMAVEWB-Dvy9IKWr.js} +1 -1
  66. package/ui-dist/assets/{sequenceDiagram-DBY2YBRQ-BG8VIjD7.js → sequenceDiagram-DBY2YBRQ-BMNm3icE.js} +1 -1
  67. package/ui-dist/assets/{sizeCapture-X5ZJPWSS-CS1xlbzG.js → sizeCapture-X5ZJPWSS-D9g2vtWC.js} +1 -1
  68. package/ui-dist/assets/{stateDiagram-2N3HPSRC-BSl2RUJ1.js → stateDiagram-2N3HPSRC-kQ3-sJWr.js} +1 -1
  69. package/ui-dist/assets/stateDiagram-v2-6OUMAXLB-BYK8scZh.js +1 -0
  70. package/ui-dist/assets/{swimlanes-5IMT3BWC-BT8Hrm9J.js → swimlanes-5IMT3BWC-Cx_ksQRH.js} +2 -2
  71. package/ui-dist/assets/swimlanesDiagram-G3AALYLV-irU0aSS8.js +8 -0
  72. package/ui-dist/assets/{timeline-definition-FHXFAJF6-CfYIqEuQ.js → timeline-definition-FHXFAJF6-CyArjIWu.js} +1 -1
  73. package/ui-dist/assets/{vennDiagram-L72KCM5P-C8zBH7o9.js → vennDiagram-L72KCM5P-Bjdg_skC.js} +1 -1
  74. package/ui-dist/assets/{wardleyDiagram-EHGQE667-D5HyFfI9.js → wardleyDiagram-EHGQE667-BLV-S7cE.js} +1 -1
  75. package/ui-dist/assets/{xychartDiagram-FW5EYKEG-CGItJmLx.js → xychartDiagram-FW5EYKEG-BTtly2sn.js} +1 -1
  76. package/ui-dist/index.html +1 -1
  77. package/ui-dist/assets/channel-DLNwhPnC.js +0 -1
  78. package/ui-dist/assets/classDiagram-OUVF2IWQ-JsIc-rlc.js +0 -1
  79. package/ui-dist/assets/classDiagram-v2-EOCWNBFH-JsIc-rlc.js +0 -1
  80. package/ui-dist/assets/stateDiagram-v2-6OUMAXLB-DUVNSzI8.js +0 -1
  81. package/ui-dist/assets/swimlanesDiagram-G3AALYLV-DfLFj7sh.js +0 -8
@@ -1604,7 +1604,7 @@ Error generating stack: `+I.message+`
1604
1604
  `))),s=[])};for(const c of n){const d=c.match(/^[ \t]{0,3}(`{3,}|~{3,})/u);if(d){const u=(l=d[1])==null?void 0:l[0];if(!a){o(),a=u??null,r.push(c);continue}if(u===a){r.push(c),a=null;continue}}a?r.push(c):s.push(c)}return o(),r.join(`
1605
1605
  `)}function M$t(e,t,n){const r=[{length:0,link:-1,firstEnd:n.rawStart-1,next:new Map}];let s=0;for(let c=n.rawStart;c<n.rawEnd;c+=1){const d=r.length;r.push({length:r[s].length+1,link:0,firstEnd:c,next:new Map});let u=s;const f=e[c];for(;u>=0&&!r[u].next.has(f);)r[u].next.set(f,d),u=r[u].link;if(u>=0){const A=r[u].next.get(f);if(r[u].length+1===r[A].length)r[d].link=A;else{const m=r.length;for(r.push({length:r[u].length+1,link:r[A].link,firstEnd:r[A].firstEnd,next:new Map(r[A].next)});u>=0&&r[u].next.get(f)===A;)r[u].next.set(f,m),u=r[u].link;r[A].link=m,r[d].link=m}}s=d}let a=0,o=0,l=null;for(let c=n.renderedStart;c<n.renderedEnd;c+=1){const d=t[c];for(;a!==0&&!r[a].next.has(d);)a=r[a].link,o=Math.min(o,r[a].length);const u=r[a].next.get(d);if(u===void 0){a=0,o=0;continue}a=u,o+=1;const A=r[a].firstEnd-o+1,m=c-o+1;(!l||o>l.length||o===l.length&&(m<l.renderedStart||m===l.renderedStart&&A<l.rawStart))&&(l={rawStart:A,renderedStart:m,length:o})}return l}function E$t(e,t){const n=[],r=[{rawStart:0,rawEnd:e.length,renderedStart:0,renderedEnd:t.length}];for(;r.length>0;){const s=r.pop();let{rawStart:a,rawEnd:o,renderedStart:l,renderedEnd:c}=s,d=0;for(;a+d<o&&l+d<c&&e[a+d]===t[l+d];)d+=1;d>0&&(n.push({rawStart:a,renderedStart:l,length:d}),a+=d,l+=d);let u=0;for(;o-u>a&&c-u>l&&e[o-u-1]===t[c-u-1];)u+=1;if(u>0&&(o-=u,c-=u,n.push({rawStart:o,renderedStart:c,length:u})),a>=o||l>=c)continue;const f=M$t(e,t,{rawStart:a,rawEnd:o,renderedStart:l,renderedEnd:c});if(!f||f.length===0)continue;n.push(f),a<f.rawStart&&l<f.renderedStart&&r.push({rawStart:a,rawEnd:f.rawStart,renderedStart:l,renderedEnd:f.renderedStart});const A=f.rawStart+f.length,m=f.renderedStart+f.length;A<o&&m<c&&r.push({rawStart:A,rawEnd:o,renderedStart:m,renderedEnd:c})}return n.sort((s,a)=>s.renderedStart-a.renderedStart||s.rawStart-a.rawStart).reduce((s,a)=>{const o=s.at(-1);return o&&o.rawStart+o.length===a.rawStart&&o.renderedStart+o.length===a.renderedStart?o.length+=a.length:s.push({...a}),s},[])}function i5e(e,t,n,r,s){const a=n-t,o=s-r;if(o===0){e[r]=n;return}for(let l=0;l<=o;l+=1)e[r+l]=t+Math.round(l/o*a)}function D$t(e,t){const n=Array(t.length+1).fill(0);let r=0,s=0;for(const a of E$t(e,t)){i5e(n,r,a.rawStart,s,a.renderedStart);for(let o=0;o<=a.length;o+=1)n[a.renderedStart+o]=a.rawStart+o;r=a.rawStart+a.length,s=a.renderedStart+a.length}i5e(n,r,e.length,s,t.length),n[0]=0,n[t.length]=e.length;for(let a=1;a<n.length;a+=1)n[a]=Math.max(n[a-1],Math.min(e.length,n[a]));return{rawSource:e,renderedSource:t,renderedBoundaryToRaw:n}}const R$t={get:(e,t="preview")=>Re.get(`/website-metadata?url=${encodeURIComponent(e)}&purpose=${encodeURIComponent(t)}`)},L$t=256,z$t=600*1e3,p2=new Map,cL=new Map;function $$t(e){try{const t=new URL(e);return t.hash="",t.href}catch{return e}}function F$t(e,t){return JSON.stringify([$$t(e),t])}function B$t(e){const t=e.split(".");if(t.length!==4)return!1;const n=t.map(Number);if(n.some(o=>!Number.isInteger(o)||o<0||o>255))return!1;const[r,s,a]=n;return r===0||r===10||r===127||r===100&&s>=64&&s<=127||r===169&&s===254||r===172&&s>=16&&s<=31||r===192&&(s===0||s===168||s===0&&a===2)||r===198&&(s===18||s===19||s===51&&a===100)||r===203&&s===0&&a===113||r>=224}function Q$t(e,t=typeof window>"u"?null:window.location.origin){try{const n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||t&&n.origin===t)return!1;const r=n.hostname.replace(/^\[|\]$/gu,"").toLowerCase();return!(!r||r.includes(":")||r==="localhost"||r.endsWith(".localhost")||r.endsWith(".local")||r.endsWith(".lan")||r.endsWith(".home")||r.endsWith(".internal")||r.endsWith(".corp")||r.endsWith(".intranet")||!r.includes(".")&&!/^\d+(?:\.\d+){3}$/u.test(r)||B$t(r))}catch{return!1}}function U$t(e){const t=p2.get(e);return t?t.expiresAt<=Date.now()?(p2.delete(e),null):(p2.delete(e),p2.set(e,t),t.value):null}function V$t(e,t,n){const r=t==="authoring"?{...n,iconUrl:null}:n;for(p2.delete(e),p2.set(e,{expiresAt:Date.now()+z$t,value:r});p2.size>L$t;){const s=p2.keys().next().value;if(typeof s!="string")break;p2.delete(s)}return r}function TUe(e,t){if(!Q$t(e))return Promise.resolve({url:e,siteName:null,pageTitle:null,iconUrl:null});const n=F$t(e,t),r=U$t(n);if(r)return Promise.resolve(r);const s=cL.get(n);if(s)return s;const a=Promise.resolve().then(()=>R$t.get(e,t)).then(o=>V$t(n,t,o)).finally(()=>{cL.get(n)===a&&cL.delete(n)});return cL.set(n,a),a}function Ps({...e}){return i.jsx(_M,{"data-slot":"dialog",...e})}function _Ue({...e}){return i.jsx(fEe,{"data-slot":"dialog-trigger",...e})}function MUe({...e}){return i.jsx(MM,{"data-slot":"dialog-portal",...e})}function q$t({...e}){return i.jsx(pj,{"data-slot":"dialog-close",...e})}function K$t({className:e,...t}){return i.jsx(EM,{"data-slot":"dialog-overlay",className:K("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-[rgb(31_27_23/0.22)] duration-200 dark:bg-[rgb(10_11_14/0.46)]",e),...t})}function zs({className:e,children:t,onEscapeKeyDown:n,overlayClassName:r,showCloseButton:s=!0,...a}){return i.jsxs(MUe,{"data-slot":"dialog-portal",children:[i.jsx(K$t,{className:r}),i.jsxs(mj,{"data-slot":"dialog-content",className:K("glass-modal motion-modal fixed top-[max(0.75rem,env(safe-area-inset-top))] md:top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-1.5rem)] translate-x-[-50%] translate-y-0 gap-4 rounded-md border bg-card p-6 shadow-[0_32px_90px_-46px_rgb(20_20_20/0.34)] outline-none md:translate-y-[-50%] sm:max-w-lg dark:shadow-[0_36px_96px_-48px_rgb(0_0_0/0.58)]",e),onEscapeKeyDown:o=>{const l=o.target,c=l instanceof HTMLElement?l.closest('[data-editor-engine="codemirror-live-preview"]'):null;if(c!=null&&c.querySelector('[data-markdown-source-editor="true"][aria-expanded="true"]')){o.preventDefault();return}n==null||n(o)},...a,children:[t,s&&i.jsxs(pj,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[i.jsx(Is,{}),i.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function vi({className:e,...t}){return i.jsx("div",{"data-slot":"dialog-header",className:K("flex flex-col gap-2 text-center sm:text-left",e),...t})}function ga({className:e,showCloseButton:t=!1,children:n,...r}){return i.jsxs("div",{"data-slot":"dialog-footer",className:K("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...r,children:[n,t&&i.jsx(pj,{asChild:!0,children:i.jsx(le,{variant:"outline",children:"Close"})})]})}function ei({className:e,...t}){return i.jsx(DM,{"data-slot":"dialog-title",className:K("text-lg leading-none font-semibold",e),...t})}function Si({className:e,...t}){return i.jsx(AEe,{"data-slot":"dialog-description",className:K("text-muted-foreground text-sm",e),...t})}const W$t={info:4e3,success:3500,warn:8e3,error:1e4},Z$t=1500,H$t=15e3,X$t=5,G$t=3500,Y$t=2e4,$Ae=h.createContext(null);function J$t(e,t){const n=W$t[t];return typeof e!="number"||!Number.isFinite(e)?n:Math.max(Z$t,Math.min(H$t,Math.floor(e)))}function eFt(){return`toast_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function tFt({children:e}){const[t,n]=h.useState([]),r=h.useRef(new Map),s=h.useRef(new Map),a=h.useCallback(u=>{const f=r.current.get(u);f!==void 0&&(window.clearTimeout(f),r.current.delete(u))},[]),o=h.useCallback(u=>{a(u),n(f=>f.filter(A=>A.id!==u))},[a]),l=h.useCallback(()=>{for(const u of r.current.values())window.clearTimeout(u);r.current.clear(),n([])},[]),c=h.useCallback(u=>{var v,w;const f=Date.now(),A=u.tone??"info",m=J$t(u.ttlMs,A),g=u.dedupeKey??u.id??`${A}|${u.title}|${u.body??""}|${((v=u.action)==null?void 0:v.href)??((w=u.action)==null?void 0:w.label)??""}`;for(const[k,S]of s.current.entries())f-S>Y$t&&s.current.delete(k);const x=s.current.get(g);if(x&&f-x<G$t)return null;s.current.set(g,f);const y=u.id??eFt();if(a(y),n(k=>{const S={id:y,title:u.title,body:u.body,tone:A,ttlMs:m,persistent:u.persistent,icon:u.icon,action:u.action,createdAt:f},j=k.filter(C=>C.id!==y);return[S,...j].slice(0,X$t)}),!u.persistent){const k=window.setTimeout(()=>{o(y)},m);r.current.set(y,k)}return y},[a,o]);h.useEffect(()=>()=>{for(const u of r.current.values())window.clearTimeout(u);r.current.clear()},[]);const d=h.useMemo(()=>({toasts:t,pushToast:c,dismissToast:o,clearToasts:l}),[t,c,o,l]);return i.jsx($Ae.Provider,{value:d,children:e})}function ss(){const e=h.useContext($Ae);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Uj(){return h.useContext($Ae)}function Vj(e){return!!(e!=null&&e.toLowerCase().startsWith("image/"))}const nFt=/\.(?:avif|bmp|gif|ico|jpe?g|png|svg|webp)$/i;function Vk(e,t){const n=e==null?void 0:e.trim();if(n)return Vj(n);const r=t.split(/[?#]/u,1)[0]??t;return nFt.test(r)}function rFt(e){switch(e.toLowerCase().split(";")[0]){case"image/jpeg":case"image/jpg":return".jpg";case"image/gif":return".gif";case"image/webp":return".webp";case"image/svg+xml":return".svg";case"image/png":default:return".png"}}function EUe(e,t,n="image"){const r=e.trim()||n;return/\.[a-z0-9]{2,8}$/i.test(r)?r:`${r}${rFt(t)}`}async function sFt(e){const t=await e.arrayBuffer(),n=new Uint8Array(t);let r="";const s=32768;for(let a=0;a<n.length;a+=s)r+=String.fromCharCode(...n.subarray(a,a+s));return btoa(r)}async function DUe(e,t,n="image"){const r=e.type||"image/png";return{filename:EUe(t,r,n),contentType:r,base64:await sFt(e)}}async function FAe(e){const t=await fetch(e,{credentials:"include"});if(!t.ok)throw new Error(`Unable to load image (${t.status}).`);const n=await t.blob();if(!Vj(n.type))throw new Error("The selected asset is not an image.");return n}async function iFt(e){var n;const t=typeof ClipboardItem>"u"?null:ClipboardItem;if(!((n=navigator.clipboard)!=null&&n.write)||!t)throw new Error("Copy Image is only available in the desktop app or a clipboard-enabled browser.");await navigator.clipboard.write([new t({[e.type||"image/png"]:e})])}async function RUe(e,t){const n=await FAe(e),r=Pn();if(r!=null&&r.copyImage){await r.copyImage(await DUe(n,t));return}await iFt(n)}async function LUe(e,t){const n=Pn();if(!(n!=null&&n.showImageInFolder))throw new Error("Show in folder is available in the desktop app.");const r=await FAe(e);await n.showImageInFolder(await DUe(r,t))}function zUe(){var e;return!!((e=Pn())!=null&&e.showImageInFolder)}async function $Ue(e,t){const n=await FAe(e),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=EUe(t,n.type||"image/png"),document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(r)}const a5e=24,aFt=1440,oFt=48,o5e=8,lFt=8,cFt=32,dFt=4,uFt=8,fFt=32;function gie(e){return!!(e&&e.width>0&&e.height>0)}function cW(e){return{alt:e.alt,naturalSize:e.naturalWidth>0&&e.naturalHeight>0?{width:e.naturalWidth,height:e.naturalHeight}:null,src:e.currentSrc||e.src}}function dW(e,t,n=typeof window>"u"?"http://localhost":window.location.href){var s;const r=e==null?void 0:e.trim();if(r)return r;try{const o=(s=new URL(t,n).pathname.split("/").filter(Boolean).at(-1))==null?void 0:s.trim();if(o)return decodeURIComponent(o)}catch{}return"Image preview"}function AFt(e){const t=Math.max(0,Math.floor(e)),n=t>0?uFt+t*cFt+(t-1)*dFt:0;return o5e+n+(n>0?lFt:0)+fFt+o5e}function BAe(e,t){return{maxWidth:Math.max(0,Math.min(e-a5e,aFt)),maxHeight:Math.max(0,t-a5e)}}function hFt(e,t,n){const r=BAe(t,n);if(!gie(e)||r.maxWidth===0||r.maxHeight===0)return{width:0,height:0};const s=Math.min(r.maxWidth/e.width,r.maxHeight/e.height,1);return{width:Math.max(1,Math.floor(e.width*s)),height:Math.max(1,Math.floor(e.height*s))}}function mFt(e,t,n,r=2){const s=BAe(t,n);return{width:Math.min(s.maxWidth,Math.max(e.width,AFt(r))),height:Math.min(s.maxHeight,Math.max(e.height,oFt))}}const pFt=190,gFt=178;function FUe(e,t){return typeof window>"u"?{left:e,top:t}:{left:Math.min(e,Math.max(8,window.innerWidth-pFt)),top:Math.min(t,Math.max(8,window.innerHeight-gFt))}}function QAe(e,t,n){const r=cW(e);return{...r,name:dW(e.getAttribute("alt"),r.src),position:FUe(t,n)}}function xFt(e){return e instanceof Error?e.message:String(e)}function uW({name:e,onClose:t,onOpen:n,position:r,portalContainer:s,src:a,testId:o="markdown-image-context-menu"}){const l=Uj(),c=h.useRef(null),d=zUe();h.useEffect(()=>{const f=m=>{var g;(g=c.current)!=null&&g.contains(m.target)||t()},A=m=>{m.key==="Escape"&&t()};return document.addEventListener("pointerdown",f),document.addEventListener("keydown",A),()=>{document.removeEventListener("pointerdown",f),document.removeEventListener("keydown",A)}},[t]);const u=async(f,A,m)=>{t();try{await A(),m&&(l==null||l.pushToast({title:m,tone:"success"}))}catch(g){l==null||l.pushToast({title:f,body:xFt(g),tone:"error"})}};return typeof document>"u"?null:ma.createPortal(i.jsxs("div",{ref:c,"data-testid":o,role:"menu",className:`motion-chat-composer-menu-pop surface-overlay z-50 min-w-[190px] rounded-[var(--radius-lg)] border p-1.5 text-foreground shadow-[var(--shadow-lg)] ${s?"absolute":"fixed"}`,style:r,children:[n?i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>{t(),n()},children:[i.jsx(Ja,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Open Image"})]}):null,i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>u("Copy Image failed",()=>RUe(a,e),"Image copied"),children:[i.jsx(Al,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Copy Image"})]}),i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>u("Download Image failed",()=>$Ue(a,e)),children:[i.jsx(Tg,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Download Image"})]}),d?i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>u("Show in folder failed",()=>LUe(a,e)),children:[i.jsx(wo,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Show in folder"})]}):null]}),s??document.body)}function l5e(){return typeof window>"u"?{width:1440,height:900}:{width:window.innerWidth,height:window.innerHeight}}function bFt({preview:e,onOpenChange:t,testId:n,titleFallback:r}){const s=Uj(),a=h.useRef(null),[o,l]=h.useState((e==null?void 0:e.naturalSize)??null),[c,d]=h.useState(()=>l5e()),[u,f]=h.useState(null),A=zUe();h.useEffect(()=>{if(f(null),!e){l(null);return}if(l(gie(e.naturalSize)?e.naturalSize:null),!e.src||gie(e.naturalSize))return;const v=new window.Image;return v.onload=()=>{l({width:v.naturalWidth,height:v.naturalHeight})},v.onerror=()=>{l(null)},v.src=e.src,()=>{v.onload=null,v.onerror=null}},[e]),h.useEffect(()=>{if(!e||typeof window>"u")return;const v=()=>{d(l5e())};return v(),window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v)}},[e]);const m=h.useMemo(()=>o?hFt(o,c.width,c.height):null,[o,c.height,c.width]),g=h.useMemo(()=>BAe(c.width,c.height),[c.height,c.width]),x=h.useMemo(()=>mFt(m??{width:0,height:0},c.width,c.height,A?3:2),[A,m,c.height,c.width]),y=async(v,w,k)=>{if(e)try{await w(),k&&(s==null||s.pushToast({title:k,tone:"success"}))}catch(S){s==null||s.pushToast({title:v,body:S instanceof Error?S.message:String(S),tone:"error"})}};return i.jsx(Ps,{open:e!==null,onOpenChange:t,children:i.jsxs(zs,{ref:a,"aria-describedby":void 0,showCloseButton:!1,className:"rudder-markdown-editor-image-preview-panel top-[50%] w-fit translate-y-[-50%] border-0 bg-transparent p-0 shadow-none",style:{maxWidth:`${g.maxWidth}px`,width:`${x.width}px`},children:[i.jsx(ei,{className:"sr-only",children:(e==null?void 0:e.name)??r}),e?i.jsxs("div",{"data-testid":n,className:"rudder-markdown-editor-image-preview-media relative flex w-fit max-w-full items-center justify-center overflow-hidden",style:{width:`${x.width}px`,height:`${x.height}px`},children:[i.jsxs(q$t,{className:"absolute right-2 top-2 z-10 flex size-8 items-center justify-center rounded-sm bg-black/55 text-white shadow-[0_6px_18px_rgb(0_0_0/0.28)] transition-colors hover:bg-black/70 focus:outline-none focus:ring-2 focus:ring-white/80",children:[i.jsx(Is,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Close image preview"})]}),i.jsxs("div",{className:"absolute left-2 top-2 z-10 flex items-center gap-1 rounded-sm bg-black/55 p-1 text-white shadow-[0_6px_18px_rgb(0_0_0/0.28)]",children:[i.jsxs("button",{type:"button",className:"rudder-image-preview-action",title:"Copy Image",onClick:()=>y("Copy Image failed",()=>RUe(e.src,e.name),"Image copied"),children:[i.jsx(Al,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Copy Image"})]}),i.jsxs("button",{type:"button",className:"rudder-image-preview-action",title:"Download Image",onClick:()=>y("Download Image failed",()=>$Ue(e.src,e.name)),children:[i.jsx(Tg,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Download Image"})]}),A?i.jsxs("button",{type:"button",className:"rudder-image-preview-action",title:"Show in folder",onClick:()=>y("Show in folder failed",()=>LUe(e.src,e.name)),children:[i.jsx(wo,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Show in folder"})]}):null]}),i.jsx("img",{src:e.src,alt:e.alt,className:"chat-attachment-preview-image",style:m?{width:"100%",height:"100%"}:void 0,onContextMenu:v=>{var S;v.preventDefault(),v.stopPropagation();const w=QAe(v.currentTarget,v.clientX,v.clientY),k=(S=a.current)==null?void 0:S.getBoundingClientRect();f(k?{...w,position:{left:w.position.left-k.left,top:w.position.top-k.top}}:w)}}),u?i.jsx(uW,{name:u.name,onClose:()=>f(null),position:u.position,portalContainer:a.current,src:u.src,testId:"image-preview-context-menu"}):null]}):null]})})}const yFt={closeImagePreview:()=>{},openImagePreview:()=>{}},BUe=h.createContext(yFt);function vFt({children:e}){const t=br(),[n,r]=h.useState(null),s=h.useCallback(()=>r(null),[]),a=h.useCallback(l=>r(l),[]),o=h.useMemo(()=>({closeImagePreview:s,openImagePreview:a}),[s,a]);return h.useEffect(()=>{s()},[s,t.hash,t.pathname,t.search]),i.jsxs(BUe.Provider,{value:o,children:[e,i.jsx(bFt,{preview:n,onOpenChange:l=>{l||s()},testId:(n==null?void 0:n.testId)??"global-image-preview-dialog",titleFallback:(n==null?void 0:n.titleFallback)??"Image preview"})]})}function vE(){return h.useContext(BUe)}function kb({alt:e,className:t,name:n,previewTestId:r,previewTitleFallback:s,showInspectOverlay:a=!0,src:o,triggerClassName:l,wrapperClassName:c,...d}){const{openImagePreview:u}=vE(),f=h.useRef(null),[A,m]=h.useState(null),g=h.useCallback(()=>m(null),[]),x=()=>{const w=f.current;w&&u({...cW(w),name:n,testId:r,titleFallback:s})},y=w=>{w.preventDefault(),w.stopPropagation(),x()},v=w=>{w.preventDefault(),w.stopPropagation(),m(FUe(w.clientX,w.clientY))};return i.jsxs("span",{className:`rudder-inspectable-image${c?` ${c}`:""}`,children:[i.jsxs("button",{type:"button",className:`rudder-inspectable-image-trigger${l?` ${l}`:""}`,"aria-label":`Open image preview: ${n}`,title:"Open image preview",onClick:y,onDoubleClick:y,onContextMenu:v,children:[i.jsx("img",{...d,ref:f,src:o,alt:e??"",className:t,onContextMenu:v}),a?i.jsx("span",{className:"rudder-inspectable-image-overlay","aria-hidden":"true",children:i.jsx(Px,{className:"size-3.5"})}):null]}),A?i.jsx(uW,{name:n,onClose:g,onOpen:x,position:A,src:o}):null]})}const wFt=700;function kFt(e){if(!e||typeof window>"u")return null;try{const t=window.sessionStorage.getItem(e);if(t===null)return null;const n=Number.parseFloat(t);return Number.isFinite(n)?n:null}catch{return null}}function OFt(e,t){if(!(!e||typeof window>"u"))try{window.sessionStorage.setItem(e,String(t))}catch{}}function bs(e){const t=h.useRef(null),n=h.useRef(null);return h.useCallback(r=>{var o;if((o=t.current)==null||o.call(t),t.current=null,n.current&&(clearTimeout(n.current),n.current=null),!r)return;const s=kFt(e);s!==null&&requestAnimationFrame(()=>{r.scrollTop=s});const a=()=>{r.classList.add("is-scrolling"),OFt(e,r.scrollTop),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{r.classList.remove("is-scrolling"),n.current=null},wFt)};r.addEventListener("scroll",a,{passive:!0}),t.current=()=>{r.removeEventListener("scroll",a),n.current&&(clearTimeout(n.current),n.current=null),r.classList.remove("is-scrolling")}},[e])}const SFt="rudder.libraryEntryCache",c5e=300*1e3,jFt="rudder.selectedOrganizationId",JN=new Map;function QUe(e,t){return`${e}:library-entry:${t}`}function xie(){return Date.now()}function UUe(e){return!!(e&&e.expiresAt>xie())}function CFt(e,t){return`${SFt}.${e}.${t}`}function NFt(e){return typeof e=="string"&&e.trim().length>0?e:null}function PFt(e,t){var n;if(typeof window>"u")return null;try{const r=(n=window.sessionStorage)==null?void 0:n.getItem(CFt(e,t));if(!r)return null;const s=JSON.parse(r),a=NFt(s==null?void 0:s.currentPath);return a?{currentPath:a}:null}catch{return null}}function IFt(){var e;return typeof window>"u"||typeof((e=window.localStorage)==null?void 0:e.getItem)!="function"?null:window.localStorage.getItem(jFt)}function TFt(e,t){if(!e||!t)return null;const n=JN.get(QUe(e,t));return UUe(n)&&(n!=null&&n.entry)?n.entry:PFt(e,t)}function VUe(e,t){const n=QUe(e,t),r=JN.get(n);if(UUe(r)){if(r!=null&&r.entry)return Promise.resolve(r.entry);if(r!=null&&r.promise)return r.promise}const s=_n.getLibraryEntry(e,t).then(a=>(JN.set(n,{entry:a,expiresAt:xie()+c5e}),a)).catch(a=>{throw JN.delete(n),a});return JN.set(n,{promise:s,expiresAt:xie()+c5e}),s}function _Ft(e,t){!e||!t||VUe(e,t).catch(()=>{})}const MFt={backlog:"text-orange-500 dark:text-orange-400",todo:"text-muted-foreground",in_progress:"text-yellow-600 dark:text-yellow-400",in_review:"text-violet-600 dark:text-violet-400",done:"text-green-600 dark:text-green-400",cancelled:"text-neutral-500 dark:text-neutral-400",blocked:"text-red-600 dark:text-red-400"},EFt="text-muted-foreground",W9={backlog:"text-muted-foreground",todo:"text-blue-600 dark:text-blue-400",in_progress:"text-yellow-600 dark:text-yellow-400",in_review:"text-violet-600 dark:text-violet-400",done:"text-green-600 dark:text-green-400"},wE={active:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",running:"border-cyan-200/80 bg-cyan-100/85 text-cyan-800 dark:border-cyan-700/50 dark:bg-cyan-900/30 dark:text-cyan-200",paused:"border-orange-200/80 bg-orange-100/85 text-orange-800 dark:border-orange-700/50 dark:bg-orange-900/30 dark:text-orange-200",idle:"border-yellow-200/80 bg-yellow-100/85 text-yellow-800 dark:border-yellow-700/50 dark:bg-yellow-900/30 dark:text-yellow-200",archived:"border-[color:var(--border-soft)] bg-muted text-muted-foreground",planned:"border-[color:var(--border-soft)] bg-muted text-muted-foreground",achieved:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",completed:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",failed:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",timed_out:"border-orange-200/80 bg-orange-100/85 text-orange-800 dark:border-orange-700/50 dark:bg-orange-900/30 dark:text-orange-200",succeeded:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",error:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",terminated:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",pending:"border-yellow-200/80 bg-yellow-100/85 text-yellow-800 dark:border-yellow-700/50 dark:bg-yellow-900/30 dark:text-yellow-200",pending_approval:"border-amber-200/80 bg-amber-100/85 text-amber-800 dark:border-amber-700/50 dark:bg-amber-900/30 dark:text-amber-200",revision_requested:"border-amber-200/80 bg-amber-100/85 text-amber-800 dark:border-amber-700/50 dark:bg-amber-900/30 dark:text-amber-200",approved:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",rejected:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",backlog:"border-[color:var(--border-soft)] bg-muted text-muted-foreground",todo:"border-blue-200/80 bg-blue-100/85 text-blue-800 dark:border-blue-700/50 dark:bg-blue-900/30 dark:text-blue-200",in_progress:"border-yellow-200/80 bg-yellow-100/85 text-yellow-800 dark:border-yellow-700/50 dark:bg-yellow-900/30 dark:text-yellow-200",in_review:"border-violet-200/80 bg-violet-100/85 text-violet-800 dark:border-violet-700/50 dark:bg-violet-900/30 dark:text-violet-200",blocked:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",done:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",cancelled:"border-[color:var(--border-soft)] bg-muted text-muted-foreground"},kE="border-[color:var(--border-soft)] bg-muted text-muted-foreground",DFt={running:"bg-cyan-400 animate-pulse",active:"bg-green-400",paused:"bg-yellow-400",idle:"bg-yellow-400",pending_approval:"bg-amber-400",error:"bg-red-400",archived:"bg-neutral-400"},RFt="bg-neutral-400",dL={critical:"text-orange-600 dark:text-orange-400",high:"text-orange-500 dark:text-orange-400",medium:"text-orange-400 dark:text-orange-300/80",low:"text-orange-300 dark:text-orange-300/55"},mT={critical:{value:"critical",label:"Urgent",level:4,color:dL.critical,menuLabelClassName:"font-medium text-orange-700 dark:text-orange-300"},high:{value:"high",label:"High",level:3,color:dL.high,menuLabelClassName:"font-medium text-orange-600 dark:text-orange-300"},medium:{value:"medium",label:"Medium",level:2,color:dL.medium,menuLabelClassName:"font-medium text-foreground"},low:{value:"low",label:"Low",level:1,color:dL.low,menuLabelClassName:"font-medium text-muted-foreground"}},qUe=["critical","high","medium","low"],LFt=qUe.map(e=>mT[e]);function zFt(e){return e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function KUe(e){return mT[e]??mT.medium}function md(e){var t;return((t=mT[e])==null?void 0:t.label)??zFt(e)}function Lf({className:e,size:t="default",...n}){return i.jsx(X1t,{"data-slot":"avatar","data-size":t,className:K("group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6 data-[size=xs]:size-5",e),...n})}function $Ft({className:e,...t}){return i.jsx(G1t,{"data-slot":"avatar-image",className:K("aspect-square size-full",e),...t})}function zf({className:e,...t}){return i.jsx(Y1t,{"data-slot":"avatar-fallback",className:K("bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs group-data-[size=xs]/avatar:text-[10px]",e),...t})}function WUe({className:e,...t}){return i.jsx("div",{"data-slot":"avatar-group",className:K("*:data-[slot=avatar]:ring-background group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2",e),...t})}function ZUe({className:e,...t}){return i.jsx("div",{"data-slot":"avatar-group-count",className:K("bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",e),...t})}const FFt={xs:"text-sm",sm:"text-xs",default:"text-sm",lg:"text-sm"},BFt={xs:"h-3 w-3 text-[10px]",sm:"h-3 w-3 text-xs",default:"h-4 w-4 text-sm",lg:"h-4.5 w-4.5 text-base"};function _g({icon:e,role:t,fallbackSeed:n,className:r,style:s}){const o=$m(e)??SAe(t),l=zj(o)??kAe(n);if(l){const d=iQ(o);return i.jsx("img",{src:l,alt:"",className:K("inline-flex rounded-full object-cover",r),style:{background:d==="oreo"?void 0:U7(o).background,...OAe(o),...s},loading:"lazy"})}const c=jAe(o);return i.jsx(c,{className:r})}function vu({name:e,icon:t,role:n,size:r="default",className:s}){const a=$m(t)??SAe(n),o=zj(a)??kAe(e);return i.jsxs("span",{className:K("inline-flex gap-1.5",r==="xs"?"items-baseline gap-1":"items-center",r==="lg"&&"gap-2",s),children:[i.jsx(Lf,{size:r,className:r==="xs"?"relative -top-px":void 0,children:o?i.jsx(_g,{icon:a,fallbackSeed:e,className:"size-full"}):i.jsx(zf,{children:i.jsx(_g,{icon:a,className:BFt[r]})})}),i.jsx("span",{className:K("truncate",FFt[r]),children:e})]})}function ts({...e}){return i.jsx(oK,{"data-slot":"popover",...e})}function ys({...e}){return i.jsx(Abt,{"data-slot":"popover-trigger",...e})}function ns({className:e,align:t="center",sideOffset:n=4,disablePortal:r=!1,...s}){const a=i.jsx(CRe,{"data-slot":"popover-content",align:t,sideOffset:n,className:K("motion-surface-pop bg-popover text-popover-foreground z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...s});return r?a:i.jsx(lK,{children:a})}function cQ({...e}){return i.jsx(jRe,{"data-slot":"popover-anchor",...e})}const QFt=["h-1","h-1.5","h-2.5","h-3.5"],HUe="w-48 rounded-lg border-[color:var(--border-base)] bg-[color:var(--surface-overlay)] p-1.5 shadow-[var(--shadow-md)]";function fW({priority:e,className:t}){const n=KUe(e);return i.jsx("span",{"data-slot":"priority-bars-icon",className:K("inline-flex h-3.5 w-4 items-end gap-[2px]",n.color,t),"aria-hidden":"true",children:QFt.map((r,s)=>i.jsx("span",{className:K("w-[3px] rounded-[1px] bg-current",r,s>=n.level&&"opacity-25")},r))})}function XUe({priority:e,selected:t,onSelect:n}){const r=mT[e];return i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t,className:K("group flex h-8 w-full items-center justify-between gap-3 rounded-md px-2 text-left text-sm transition-colors hover:bg-[color:var(--surface-active)] focus-visible:bg-[color:var(--surface-active)] focus-visible:outline-none",t&&"bg-[color:color-mix(in_oklab,var(--surface-active)_72%,transparent)] text-foreground"),onClick:()=>n(e),children:[i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[i.jsx(fW,{priority:e,className:"shrink-0"}),i.jsx("span",{className:K("truncate",r.menuLabelClassName),children:r.label})]}),t?i.jsx(Zs,{"data-slot":"priority-menu-check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):i.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":"true"})]})}function ec({priority:e,onChange:t,className:n,showLabel:r}){const[s,a]=h.useState(!1),o=KUe(e),l=i.jsx("span",{className:K("inline-flex items-center justify-center shrink-0",t&&!r&&"cursor-pointer",n),children:i.jsx(fW,{priority:e})});if(!t)return r?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[l,i.jsx("span",{className:"text-sm",children:o.label})]}):l;const c=r?i.jsxs("button",{type:"button","aria-label":`Edit priority, current priority ${o.label}`,className:"-mx-1 inline-flex cursor-pointer items-center gap-1.5 rounded-md px-1 py-0.5 transition-colors hover:bg-[color:var(--surface-active)]",children:[l,i.jsx("span",{className:"text-sm",children:o.label})]}):l;return i.jsxs(ts,{open:s,onOpenChange:a,children:[i.jsx(ys,{asChild:!0,children:c}),i.jsx(ns,{className:HUe,align:"start",role:"menu","aria-label":"Issue priority",children:qUe.map(d=>{const u=d===e;return i.jsx(XUe,{priority:d,selected:u,onSelect:f=>{t(f),a(!1)}},d)})})]})}const UFt="linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",VFt=/^#[0-9a-fA-F]{6}$/,qFt=/^#[0-9a-fA-F]{3}$/,KFt=/^linear-gradient\(\s*(?:\d{1,3}deg|to\s+(?:top|bottom|left|right)(?:\s+(?:top|bottom|left|right))?)\s*,\s*#[0-9a-fA-F]{6}(?:\s+\d{1,3}%?)?\s*,\s*#[0-9a-fA-F]{6}(?:\s+\d{1,3}%?)?\s*\)$/;function WFt(e){const t=e.slice(1).toLowerCase();return`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`}function UAe(e,t=UFt){const n=e==null?void 0:e.trim();return n?VFt.test(n)?n.toLowerCase():qFt.test(n)?WFt(n):KFt.test(n)?n:t:t}function ZFt(e){return{background:UAe(e)}}function HFt(e){var r;const n=(r=UAe(e).match(/#[0-9a-fA-F]{6}/))==null?void 0:r[0];return(n==null?void 0:n.toLowerCase())??"#6366f1"}function VAe(e){return{"--project-color":UAe(e),"--project-accent-color":HFt(e)}}const XFt={xs:"h-4 w-4 rounded-[calc(var(--radius-sm)-3px)]",sm:"h-5 w-5 rounded-[calc(var(--radius-sm)-2px)]",md:"h-6 w-6 rounded-[calc(var(--radius-sm)-1px)]",lg:"h-9 w-9 rounded-[var(--radius-sm)]"},GFt={xs:"h-4 w-4",sm:"h-[18px] w-[18px]",md:"h-5 w-5",lg:"h-7 w-7"};function uo({color:e,icon:t,size:n="sm",className:r,iconClassName:s,label:a,testId:o}){const l=oW(t);return i.jsx("span",{"data-testid":o,className:K("inline-flex shrink-0 items-center justify-center text-[color:var(--project-accent-color)]",XFt[n],r),style:VAe(e),"aria-label":a,"aria-hidden":a?void 0:!0,children:i.jsx(l,{className:K(GFt[n],s),strokeWidth:2.3})})}const qAe=h.forwardRef(({projectColor:e,projectIcon:t,label:n,className:r,title:s,...a},o)=>i.jsx("button",{...a,ref:o,type:"button",className:K("inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] outline-none transition-[box-shadow,transform] hover:scale-[1.03] focus-visible:ring-2 focus-visible:ring-ring",r),"aria-label":n,title:s??n,children:i.jsx(uo,{color:e,icon:t,size:"lg"})}));qAe.displayName="ProjectIdentityTriggerButton";function GUe({color:e,icon:t,onColorChange:n,onIconChange:r,className:s}){const a=aW(t);return i.jsxs("div",{className:K("w-72 space-y-3 p-2",s),style:VAe(e),children:[i.jsx("div",{className:"grid grid-cols-6 gap-1.5","aria-label":"Project colors",children:EP.map(o=>{const l=o===e;return i.jsx("button",{type:"button",className:K("relative h-7 w-7 rounded-[calc(var(--radius-sm)-1px)] outline-none transition-[box-shadow,transform] hover:scale-[1.04] focus-visible:ring-2 focus-visible:ring-ring",l?"ring-2 ring-foreground ring-offset-1 ring-offset-background":"ring-1 ring-[color:color-mix(in_oklab,var(--border-base)_72%,transparent)]"),style:ZFt(o),"aria-label":"Select project color","aria-pressed":l,onClick:()=>n(o)},o)})}),i.jsx(YFt,{icon:a,onIconChange:r}),i.jsxs("div",{className:"flex items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] border border-border/70 bg-muted/35 px-2 py-1.5",children:[i.jsx(uo,{color:e,icon:a||kK,size:"lg"}),i.jsx("span",{className:"min-w-0 truncate text-xs text-muted-foreground",children:a})]})]})}function YFt({icon:e,selectedIcon:t,onIconChange:n,ariaLabel:r="Project icons"}){const s=t===null?null:aW(t??e);return i.jsx("div",{className:"grid grid-cols-6 gap-1.5","aria-label":r,children:HM.map(a=>{const o=oW(a),l=a===s;return i.jsxs("button",{type:"button",className:K("relative inline-flex h-9 w-9 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] border text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",l?"border-[color:color-mix(in_oklab,var(--project-accent-color)_54%,var(--border-base))] bg-muted/55 text-[color:var(--project-accent-color)]":"border-border/70 bg-transparent"),"aria-label":`Select ${a} project icon`,"aria-pressed":l,onClick:()=>n(a),children:[i.jsx(o,{className:"h-5 w-5",strokeWidth:2.2}),l?i.jsx(Zs,{className:"absolute h-2.5 w-2.5 translate-x-3 translate-y-3 text-[color:var(--project-accent-color)]"}):null]},a)})})}const YUe=["backlog","todo","in_progress","in_review","done","cancelled","blocked"],JFt="w-48 rounded-lg border-[color:var(--border-base)] bg-[color:var(--surface-overlay)] p-1.5 shadow-[var(--shadow-md)]";function bie(e){return e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function JUe({status:e,className:t,dataSlot:n="issue-status-icon"}){const r=MFt[e]??EFt,s=YUe.includes(e)?e:"default";return i.jsx("span",{"data-slot":n,"data-status":e,className:K("inline-flex h-4 w-4 shrink-0 items-center justify-center",r,t),"aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 16 16",className:"h-full w-full overflow-visible text-current",fill:"none",children:[s==="backlog"&&i.jsx("circle",{"data-slot":"status-backlog-ring",cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2",strokeDasharray:"1 3",strokeLinecap:"round"}),s==="todo"&&i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"}),s==="in_progress"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2",opacity:"0.22"}),i.jsx("path",{"data-slot":"status-progress-arc",d:"M8 2.5a5.5 5.5 0 0 1 5.5 5.5",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round"}),i.jsx("path",{d:"M13.5 8a5.5 5.5 0 0 1-5.5 5.5",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",opacity:"0.72"})]}),s==="in_review"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"}),i.jsx("circle",{"data-slot":"status-review-dot",cx:"8",cy:"8",r:"2",fill:"currentColor"})]}),s==="done"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"6.5",fill:"currentColor"}),i.jsx("path",{"data-slot":"status-done-check",d:"M4.75 8.25 7 10.5l4.25-5",stroke:"var(--background)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),s==="cancelled"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"6",fill:"currentColor",opacity:"0.16"}),i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"}),i.jsx("path",{"data-slot":"status-cancel-mark",d:"m5.25 5.25 5.5 5.5m0-5.5-5.5 5.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),s==="blocked"&&i.jsxs(i.Fragment,{children:[i.jsx("path",{d:"M5.1 2.25h5.8l3.05 3.05v5.4l-3.05 3.05H5.1L2.05 10.7V5.3Z",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round"}),i.jsx("path",{"data-slot":"status-blocked-mark",d:"m5.25 5.25 5.5 5.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),s==="default"&&i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"})]})})}function eBt({status:e,selected:t,onSelect:n}){return i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t,className:K("group flex h-8 w-full items-center justify-between gap-3 rounded-md px-2 text-left text-sm transition-colors hover:bg-[color:var(--surface-active)] focus-visible:bg-[color:var(--surface-active)] focus-visible:outline-none",t&&"bg-[color:color-mix(in_oklab,var(--surface-active)_72%,transparent)] text-foreground"),onClick:()=>n(e),children:[i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[i.jsx(JUe,{status:e}),i.jsx("span",{className:"truncate",children:bie(e)})]}),t?i.jsx(Zs,{"data-slot":"status-menu-check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):i.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":"true"})]})}function ni({status:e,onChange:t,className:n,showLabel:r,dataSlot:s}){const[a,o]=h.useState(!1),l=i.jsx(JUe,{status:e,className:n,dataSlot:s});if(!t)return r?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[l,i.jsx("span",{className:"text-sm",children:bie(e)})]}):l;const c=r?i.jsxs("button",{type:"button",className:"-mx-1 inline-flex cursor-pointer items-center gap-1.5 rounded-md px-1 py-0.5 transition-colors hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",children:[l,i.jsx("span",{className:"text-sm",children:bie(e)})]}):i.jsx("button",{type:"button",className:"inline-flex cursor-pointer items-center justify-center rounded-sm transition-colors hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",children:l});return i.jsxs(ts,{open:a,onOpenChange:o,children:[i.jsx(ys,{asChild:!0,children:c}),i.jsx(ns,{className:JFt,align:"start",role:"menu","aria-label":"Issue status",children:YUe.map(d=>i.jsx(eBt,{status:d,selected:d===e,onSelect:u=>{t(u),o(!1)}},d))})]})}const tBt=600*1e3,d5e=1e3,nBt=160,rBt=new Map,sBt=new Map;function iBt(){return IFt()}function vS(e){return e?e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase()):null}function eVe(e,t=220){const n=(e==null?void 0:e.replace(/\s+/g," ").trim())??"";return n?n.length>t?`${n.slice(0,t-1).trimEnd()}...`:n:null}function AW(e){const t=(e==null?void 0:e.trim())??"";if(!t)return null;const n=t.split(/\n\s*\n/u).map(s=>s.trim()).filter(Boolean),r=n.find(s=>!/^#{1,6}\s+/u.test(s))??n[0]??t;return eVe(r.replace(/^#{1,6}\s+/gm,""))}function tVe(e){return((e==null?void 0:e.split("/").filter(Boolean))??[]).at(-1)??e??"Library item"}function nVe(e){return e?e.length>8?e.slice(0,8):e:null}function rVe(e,t,n,r=tBt){const s=Date.now(),a=e.get(t);if(a&&a.expiresAt>s)return a.promise;const o=n().catch(l=>{throw e.delete(t),l});return e.set(t,{expiresAt:s+r,promise:o}),o}function sVe(e,t){return rVe(sBt,`${t}:agent:${e}`,()=>Nn.get(e,t))}function iVe(e,t){return e.kind==="issue"?`${t}:issue:${e.issueId}:${e.commentId??""}`:e.kind==="agent"?`${t}:agent:${e.agentId}`:e.kind==="project"?`${t}:project:${e.projectId}`:e.kind==="library_doc"?`${t}:library_doc:${e.documentId}`:e.kind==="library_entry"?`${t}:library_entry:${e.entryId}`:e.kind==="library_file"?`${t}:library_file:${e.filePath}`:`${t}:library_directory:${e.directoryPath}`}async function u5e(e,t){if(!e)return null;try{const n=await sVe(e,t);return{name:n.name,icon:n.icon,role:n.role}}catch{return{name:`agent ${nVe(e)}`,icon:null,role:null}}}async function aBt(e,t){var l,c;const[n,r]=await Promise.all([lr.getComment(e.issueId,e.commentId),lr.get(e.issueId).catch(()=>null)]),s=e.ref??"Issue",a=((l=r==null?void 0:r.title)==null?void 0:l.trim())||s,o=((c=n.body)==null?void 0:c.trim())||null;return{kind:"issue_comment",eyebrow:`${s} comment`,title:a,rows:[],summary:o?null:"No comment body.",body:o}}async function oBt(e,t){if(e.commentId)return aBt(e);const n=await lr.get(e.issueId),r=n.project,[s,a,o]=await Promise.all([u5e(n.assigneeAgentId,t),u5e(n.reviewerAgentId,t),r!=null&&r.color||r!=null&&r.icon?Promise.resolve(r):n.projectId&&!(r!=null&&r.name)?Mi.get(n.projectId,t).catch(()=>null):Promise.resolve(null)]),l=(r==null?void 0:r.name)??(o==null?void 0:o.name)??null,c=o??r??null;return{kind:"issue",eyebrow:n.identifier??e.ref??"Issue",title:n.title,status:n.status,rows:[{label:"Status",value:vS(n.status),issueStatus:n.status},{label:"Priority",value:md(n.priority),priority:n.priority},{label:"Project",value:l,project:l?{color:(c==null?void 0:c.color)??null,icon:(c==null?void 0:c.icon)??null}:void 0},{label:"Assignee",value:s==null?void 0:s.name,agent:s?{icon:s.icon,role:s.role}:void 0},{label:"Reviewer",value:a==null?void 0:a.name,agent:a?{icon:a.icon,role:a.role}:void 0}],summary:AW(n.description)}}function lBt(e){return{kind:"agent",eyebrow:"Agent",title:e.name,subtitle:e.title??vS(e.role),status:vS(e.status)??e.status,icon:e.icon,role:e.role,summary:eVe(e.capabilities)}}function cBt(e,t){return{kind:"agent",eyebrow:"Agent",title:t.replace(/^@(?=\S)/,"")||`Agent ${nVe(e.agentId)??""}`.trim(),subtitle:null,status:"",icon:e.icon,role:null,summary:null}}function dBt(e){var r;const t=e.goals.length>0?e.goals.map(s=>s.title).slice(0,2).join(", "):null,n=((r=e.primaryWorkspace)==null?void 0:r.cwd)??e.codebase.repoName??e.codebase.repoUrl??e.codebase.effectiveLocalFolder??null;return{kind:"project",eyebrow:"Project",title:e.name,color:e.color,icon:e.icon,rows:[{label:"Status",value:vS(e.status)},{label:"Goal",value:t},{label:"Context",value:n}],summary:AW(e.description)}}function uBt(e){return e.previewKind==="text"?AW(e.content)??(e.truncated?"Text preview is truncated.":null):e.previewKind==="image"?"Image file.":e.previewKind==="pdf"?"PDF file.":e.message??"Preview is not available for this file type."}function fBt(e){return{kind:"library",eyebrow:"Library document",title:e.title??"Untitled document",icon:"file",rows:[{label:"Revision",value:String(e.latestRevisionNumber)},{label:"Format",value:vS(e.format)}],summary:AW(e.body)}}function f5e(e,t){return{kind:"library",eyebrow:e.previewKind==="text"?"Library file":"Library asset",title:t??tVe(e.filePath),icon:"file",rows:[{label:"Path",value:e.filePath},{label:"Type",value:e.contentType}],summary:uBt(e)}}async function ABt(e,t,n){if(e.kind==="issue")return oBt(e,n);if(e.kind==="agent")return lBt(await sVe(e.agentId,n));if(e.kind==="project")return dBt(await Mi.get(e.projectId,n));if(e.kind==="library_doc")return fBt(await _n.getLibraryDocument(n,e.documentId));if(e.kind==="library_entry"){const r=await VUe(n,e.entryId);return r.status!=="active"||!r.currentPath?{kind:"library",eyebrow:"Library file",title:r.title||t,icon:"file",rows:[{label:"Path",value:r.currentPath??e.path},{label:"Status",value:vS(r.status)}],summary:"This Library reference is not currently readable."}:f5e(await _n.readWorkspaceFile(n,r.currentPath),r.title)}return e.kind==="library_file"?f5e(await _n.readWorkspaceFile(n,e.filePath),e.title):{kind:"library",eyebrow:"Library folder",title:e.title??tVe(e.directoryPath),icon:"folder",rows:[{label:"Path",value:e.directoryPath}],summary:"Open the folder to inspect its files."}}function hBt(e,t,n){return rVe(rBt,iVe(e,n),()=>ABt(e,t,n))}function mBt({row:e}){return e.issueStatus?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(ni,{status:e.issueStatus,className:"size-3.5"})}):e.priority?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(ec,{priority:e.priority,className:"h-3.5 w-4"})}):e.agent?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(_g,{icon:e.agent.icon,role:e.agent.role,fallbackSeed:e.value,className:"size-4 rounded-full"})}):e.project?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(uo,{color:e.project.color,icon:e.project.icon,size:"xs"})}):null}function A5e({rows:e}){const t=e.filter(n=>n.value);return t.length===0?null:i.jsx("span",{className:"rudder-entity-preview-rows",children:t.map(n=>i.jsxs("span",{className:"rudder-entity-preview-row",children:[i.jsx("span",{className:"rudder-entity-preview-row-label",children:n.label}),i.jsxs("span",{className:"rudder-entity-preview-row-value",children:[i.jsx(mBt,{row:n}),i.jsx("span",{className:"rudder-entity-preview-row-value-text",children:n.value})]})]},n.label))})}function pBt({preview:e}){if(e.kind==="agent")return i.jsx(_g,{icon:e.icon,role:e.role,fallbackSeed:e.title,className:"rudder-entity-preview-main-icon rudder-entity-preview-main-icon--agent"});if(e.kind==="issue")return i.jsx(ni,{status:e.status,className:"rudder-entity-preview-main-icon"});if(e.kind==="issue_comment")return i.jsx("span",{className:"rudder-entity-preview-main-icon rudder-entity-preview-main-icon--comment","data-slot":"issue-comment-preview-icon",children:i.jsx(dE,{className:"size-4","aria-hidden":"true"})});if(e.kind==="project")return i.jsx(uo,{color:e.color,icon:e.icon,size:"sm",className:"rudder-entity-preview-main-icon--project"});const t=e.icon==="folder"?wo:Fi;return i.jsx("span",{className:"rudder-entity-preview-main-icon rudder-entity-preview-main-icon--library",children:i.jsx(t,{className:"size-4","aria-hidden":"true"})})}function nY({preview:e}){return i.jsxs("span",{className:"rudder-entity-preview-head",children:[i.jsx(pBt,{preview:e}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"rudder-entity-preview-eyebrow",children:e.eyebrow}),i.jsx("span",{className:"rudder-entity-preview-title",children:e.title}),e.kind==="agent"&&e.subtitle?i.jsx("span",{className:"rudder-entity-preview-subtitle",children:e.subtitle}):null]})]})}const aVe={a:({node:e,href:t,children:n,...r})=>{const s=xBt(t);return s?i.jsx("a",{...r,href:s,target:s.startsWith("http")?"_blank":void 0,rel:"noreferrer",children:n}):i.jsx("span",{children:n})},img:({node:e,src:t,alt:n,...r})=>{const s=t??"";return i.jsx(kb,{...r,src:s,alt:n??"",name:dW(n,s),loading:"lazy",previewTestId:"entity-image-preview-dialog",previewTitleFallback:"Image preview"})}};function gBt(){return typeof window>"u"?null:cp(window.location.pathname)}function xBt(e){const t=e==null?void 0:e.trim();if(!t)return null;const n=ac(t);if(n)return Uc(Aw(n),gBt());if(t.startsWith("/")||t.startsWith("#")||!/^[a-z][a-z\d+.-]*:/iu.test(t)&&!t.startsWith("//"))return t;try{const r=new URL(t);if(r.protocol==="http:"||r.protocol==="https:")return t}catch{return null}return null}function bBt({body:e}){const t=bs(),n=zAe(e);return i.jsx("div",{ref:t,className:"rudder-entity-preview-comment-body scrollbar-auto-hide","data-testid":"issue-comment-preview-body",children:i.jsx(mAe,{remarkPlugins:[tW],components:aVe,urlTransform:r=>r,children:n})})}function rY({summary:e}){const t=bs(),n=zAe(e);return i.jsx("div",{ref:t,className:"rudder-entity-preview-summary scrollbar-auto-hide",children:i.jsx(mAe,{remarkPlugins:[tW],components:aVe,urlTransform:r=>r,children:n})})}function yBt({preview:e}){return e.kind==="agent"?i.jsxs(i.Fragment,{children:[i.jsx(nY,{preview:e}),i.jsx(A5e,{rows:[{label:"Status",value:e.status}]}),e.summary?i.jsx(rY,{summary:e.summary}):null]}):e.kind==="issue_comment"?i.jsxs(i.Fragment,{children:[i.jsx(nY,{preview:e}),e.body?i.jsx(bBt,{body:e.body}):null,e.summary?i.jsx(rY,{summary:e.summary}):null]}):i.jsxs(i.Fragment,{children:[i.jsx(nY,{preview:e}),i.jsx(A5e,{rows:e.rows}),e.summary?i.jsx(rY,{summary:e.summary}):null]})}function hW({mention:e,label:t,children:n}){const[r,s]=h.useState(!1),[a,o]=h.useState(!1),[l,c]=h.useState({status:"idle"}),d=h.useRef(null),u=h.useRef(null),f=h.useRef(null),A=h.useRef(null),m=h.useMemo(iBt,[]),g=h.useRef(e),x=h.useRef(t);g.current=e,x.current=t;const y=m?iVe(e,m):null;h.useEffect(()=>{e.kind==="library_entry"&&_Ft(m,e.entryId)},[e,m]);const v=()=>{u.current&&(clearTimeout(u.current),u.current=null)},w=()=>{f.current&&(clearTimeout(f.current),f.current=null)};h.useEffect(()=>{if(!r)return;if(!m){c({status:"error",message:"Preview unavailable outside an organization."});return}if(!y||d.current===y)return;d.current=y;let N=!1;const P=g.current,M=x.current;return P.kind==="agent"?c({status:"ready",preview:cBt(P,M)}):c({status:"loading"}),hBt(P,M,m).then(E=>{N||c({status:"ready",preview:E})}).catch(()=>{N||c({status:"error",message:"Preview unavailable."})}),()=>{N=!0}},[r,m,y]),h.useEffect(()=>()=>{u.current&&clearTimeout(u.current),f.current&&clearTimeout(f.current)},[]),h.useEffect(()=>{if(!a)return;const N=P=>{var T;const M=P.target;if(!(M instanceof Node))return;if((T=A.current)!=null&&T.contains(M)){w();return}if(Array.from(document.querySelectorAll(".rudder-entity-preview-card")).some(R=>{const _=R.getBoundingClientRect();return P.clientX>=_.left&&P.clientX<=_.right&&P.clientY>=_.top&&P.clientY<=_.bottom})){w();return}j()};return window.addEventListener("mousemove",N),()=>{window.removeEventListener("mousemove",N)}},[a]);const k=()=>{v(),w(),s(!0),o(!0)},S=()=>{v(),w(),u.current=setTimeout(()=>{u.current=null,k()},d5e)},j=()=>{if(v(),w(),!a){o(!1);return}f.current=setTimeout(()=>{f.current=null,o(!1)},nBt)},C=()=>{v(),w(),o(!1)};return i.jsx(Wc,{delayDuration:d5e,skipDelayDuration:0,children:i.jsxs(ra,{open:a,onOpenChange:N=>{N||v(),N?k():j()},children:[i.jsx(sa,{asChild:!0,children:i.jsx("span",{ref:A,className:"rudder-entity-preview-wrap",onMouseEnter:S,onMouseLeave:j,onFocusCapture:k,onBlurCapture:C,children:n})}),r?i.jsx(ia,{side:"bottom",align:"center",sideOffset:8,collisionPadding:16,className:K("rudder-entity-preview-card motion-entity-preview-pop",l.status==="loading"&&"rudder-entity-preview-card--loading"),onMouseEnter:k,onMouseLeave:j,children:l.status==="ready"?i.jsx(yBt,{preview:l.preview}):l.status==="error"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"rudder-entity-preview-eyebrow",children:t}),i.jsx("span",{className:"rudder-entity-preview-empty",children:l.message})]}):i.jsxs(i.Fragment,{children:[i.jsx(Fi,{className:"size-3.5","aria-hidden":"true"}),i.jsx("span",{children:"Loading preview..."})]})}):null]})})}const a3="data-chat-annotation-source",dQ="data-chat-annotation-block",hw="data-chat-annotation-ignore",OE="data-chat-annotation-text-ignore",oVe=new WeakMap;function vBt(e,t){oVe.set(e,t)}function wBt(e){return oVe.get(e)??null}const kBt=new Set(["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","End","Home"]);function KAe(e){return e instanceof KeyboardEvent&&e.type==="keyup"&&e.shiftKey&&kBt.has(e.key)}async function d4(e){const t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function p7(e,t){const n=e instanceof HTMLElement?e:e.parentElement;return(n==null?void 0:n.closest(`[${t}]`))??null}const OBt=new Set(["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","DIV","FIGCAPTION","FIGURE","FOOTER","H1","H2","H3","H4","H5","H6","HEADER","LI","MAIN","NAV","P","PRE","SECTION","TR"]);function WAe(e,t,n={value:0}){if(e instanceof Element&&(e.hasAttribute(hw)||e.hasAttribute(OE)))return"";if(e.nodeType===Node.TEXT_NODE){const s=e.textContent??"";return s&&t&&t.push({node:e,start:n.value,end:n.value+s.length}),n.value+=s.length,s}if(e instanceof HTMLBRElement)return n.value+=1,`
1606
1606
  `;const r=Array.from(e.childNodes).map(s=>WAe(s,t,n)).join("");return e instanceof HTMLElement&&OBt.has(e.tagName)&&r.length>0?(n.value+=1,`${r}
1607
- `):r}function J2(e){const t=e.cloneNode(!0);return WAe(t).replace(/^\n+|\n+$/gu,"")}function lVe(e){var a;const t=[],n=WAe(e,t),r=((a=n.match(/^\n+/u))==null?void 0:a[0].length)??0,s=n.replace(/^\n+|\n+$/gu,"").length;return t.map(o=>({...o,start:o.start-r,end:o.end-r})).filter(o=>o.end>0&&o.start<s).map(o=>({...o,start:Math.max(0,o.start),end:Math.min(s,o.end)}))}function cVe(e,t,n){const r=lVe(e);if(t.nodeType===Node.TEXT_NODE){const o=r.find(l=>l.node===t);return o?Math.max(o.start,Math.min(o.end,o.start+n)):null}if(!(t instanceof Element||t instanceof DocumentFragment))return null;const s=t.childNodes[n]??null;if(s){const o=r.find(l=>s===l.node||s.contains(l.node));if(o)return o.start}const a=n>0?t.childNodes[n-1]??null:null;if(a){const o=[...r].reverse().find(l=>a===l.node||a.contains(l.node));if(o)return o.end}return t===e&&n===0?0:t===e&&n===e.childNodes.length?J2(e).length:null}function dVe(e,t,n){const r=cVe(e,t,n);if(r!==null)return J2(e).slice(0,r);const s=document.createRange();s.selectNodeContents(e);try{s.setEnd(t,n)}catch{return null}return J2(s.cloneContents())}function uVe(e){return J2(e.cloneContents())}function SBt(e,t){var a;if(e[t]!=="&")return null;const n=(a=e.slice(t).match(/^&(?:#[xX][\da-fA-F]+|#\d+|[a-zA-Z][a-zA-Z\d]+);/u))==null?void 0:a[0];if(!n||typeof document>"u")return null;const r=document.createElement("textarea");r.innerHTML=n;const s=r.value;return s.length===1?{decoded:s,length:n.length}:null}function jBt(e){const t=Array(e.length).fill(!0),n=(r,s)=>{for(let a=r;a<s;a+=1)t[a]=!1};for(const r of e.matchAll(/!?\[[^\]\n]*\]\[[^\]\n]*\]/gu)){const s=r[0],a=r.index,o=s.indexOf("]");s.startsWith("!")?n(a,a+s.length):(n(a,a+1),o>=0&&n(a+o,a+s.length))}for(const r of e.matchAll(/!?\[[^\]\n]*\]\((?:\\.|[^)\n])*\)/gu)){const s=r[0],a=r.index,o=s.indexOf("]");o>=0&&n(a+o,a+s.length),n(a,a+(s.startsWith("!")?2:1))}for(const r of e.matchAll(/!\[[^\]\n]*\](?![\[(])/gu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/^[\t ]*\[[^\]\n]+\]:[^\n]*$/gmu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/<\/?[a-zA-Z][^>\n]*>/gu))n(r.index,r.index+r[0].length);return t}function SE(e,t,n=0){const r=[],s=$6t(t,e),a=jBt(t);let o=0;for(let l=0;l<e.length;l+=1){const c=e[l],d=Math.max(o,s.renderedBoundaryToRaw[l+1]-1);let u=-1,f=-1,A=Number.POSITIVE_INFINITY;const m=(g,x)=>{const y=Math.abs(g-d);(y<A||y===A&&(g>u||g===u&&x>f))&&(u=g,f=x,A=y)};for(let g=t.indexOf(c,o);g>=0&&!(a[g]&&(m(g,g+1),g>=d));g=t.indexOf(c,g+1));for(let g=t.indexOf("&",o);g>=0;g=t.indexOf("&",g+1)){const x=SBt(t,g);if(a[g]&&(x==null?void 0:x.decoded)===c&&(m(g,g+x.length),g>=d))break}if(u<0)return Array.from({length:e.length},(g,x)=>({start:n+s.renderedBoundaryToRaw[x],end:n+s.renderedBoundaryToRaw[x+1]}));r.push({start:n+u,end:n+f}),o=f}return r}function CBt(e,t){const n=e instanceof HTMLElement?e:e.parentElement,r=(n==null?void 0:n.closest("[data-markdown-source-start][data-markdown-source-end]"))??null;return r&&t.contains(r)?r:null}function fVe(e,t){const n=Number(e.dataset.markdownSourceStart),r=Number(e.dataset.markdownSourceEnd);return!Number.isInteger(n)||!Number.isInteger(r)||n<0||r<=n||r>t?null:{start:n,end:r}}function NBt(e,t,n){const r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(o){return p7(o,hw)||p7(o,OE)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let s=t,a=null;for(let o=r.nextNode();o;o=r.nextNode()){const l=o;a=l;const c=l.data.length;if(s<c||s===c&&n==="end")return{container:l,offset:s};s-=c}return s===0&&a?{container:a,offset:a.data.length}:null}function PBt(e,t,n,r){return Array.from(e.querySelectorAll("[data-markdown-source-start][data-markdown-source-end]")).map(a=>({element:a,bounds:fVe(a,t)})).filter(a=>!!a.bounds).filter(({bounds:a})=>r==="start"?a.start<=n&&n<a.end:a.start<n&&n<=a.end).sort((a,o)=>a.bounds.end-a.bounds.start-(o.bounds.end-o.bounds.start))[0]??null}function h5e(e,t,n,r){const s=PBt(e,t.length,n,r);if(!s)return null;const a=J2(s.element),o=SE(a,t.slice(s.bounds.start,s.bounds.end),s.bounds.start);if(!o)return null;const l=r==="start"?o.findIndex(c=>c.end>n):o.findLastIndex(c=>c.start<n)+1;return l<0?null:NBt(s.element,l,r)}function AVe(e){if(e.start<0||e.end<=e.start||e.end>e.source.length)return null;const t=h5e(e.sourceRoot,e.source,e.start,"start"),n=h5e(e.sourceRoot,e.source,e.end,"end");if(!t||!n)return null;const r=document.createRange();try{r.setStart(t.container,t.offset),r.setEnd(n.container,n.offset)}catch{return null}return r.collapsed?null:r}function IBt(e,t=document){return Array.from(t.querySelectorAll(`[${a3}]`)).find(r=>!r.isConnected||r.dataset.messageId!==e.sourceMessageId||r.dataset.annotationSurface!==e.surface?!1:e.surface==="assistant_body"?!0:r.dataset.transcriptKind===e.transcriptKind&&r.dataset.generationId===e.generationId&&Number(r.dataset.generationSeqStart)===e.generationSeqStart&&Number(r.dataset.generationSeqEnd)===e.generationSeqEnd)??null}function yie(e){const t=IBt(e.anchor,e.searchRoot);if(!t)return null;const n=AVe({sourceRoot:t,source:e.source,start:e.anchor.start,end:e.anchor.end});return n?{range:n,sourceRoot:t}:null}function m5e(e,t,n,r,s){var u,f;const a=CBt(n,e);if(!a)return null;const o=fVe(a,t.length);if(!o)return null;const l=dVe(a,n,r);if(l===null)return null;const c=J2(a),d=SE(c,t.slice(o.start,o.end),o.start);return d?s==="start"?l.length===d.length?o.end:((u=d[l.length])==null?void 0:u.start)??null:l.length===0?o.start:((f=d[l.length-1])==null?void 0:f.end)??null:null}function p5e(e){var x,y;const{range:t,sourceRoot:n}=e;if(t.collapsed||!n.contains(t.startContainer)||!n.contains(t.endContainer))return null;const r=n.getAttribute(a3),s=p7(t.startContainer,a3),a=p7(t.endContainer,a3);if(!r||s!==n||a!==n||Array.from(n.querySelectorAll(`[${hw}]`)).some(v=>{try{return t.intersectsNode(v)}catch{return!1}}))return null;if(e.surface==="process_transcript"){const v=p7(t.startContainer,dQ),w=p7(t.endContainer,dQ);if(!v||v!==w)return null}const l=uVe(t);if(!l)return null;const c=dVe(n,t.startContainer,t.startOffset);if(c===null)return null;const d=m5e(n,e.source,t.startContainer,t.startOffset,"start"),u=m5e(n,e.source,t.endContainer,t.endOffset,"end");let f=d??void 0,A=u??void 0;if(f===void 0||A===void 0){const v=J2(n),w=SE(v,e.source);if(!w)return null;const k=c.length,S=k+l.length;if(k<0||S>w.length||S<=k)return null;f??(f=(x=w[k])==null?void 0:x.start),A??(A=(y=w[S-1])==null?void 0:y.end)}if(f===void 0||A===void 0||A<=f)return null;for(;f<A&&new RegExp("\\p{White_Space}","u").test(e.source[f]??"")&&!l.startsWith(e.source[f]??"");)f+=1;for(;A>f&&new RegExp("\\p{White_Space}","u").test(e.source[A-1]??"")&&!l.endsWith(e.source[A-1]??"");)A-=1;const m=Math.min(160,Math.max(0,e.contextLength??160)),g={selectedText:l,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,sourceHash:e.sourceHash,start:f,end:A,prefix:e.source.slice(Math.max(0,f-m),f),suffix:e.source.slice(A,A+m)};return e.surface==="process_transcript"?{...g,surface:e.surface,transcriptKind:e.transcriptKind,generationId:e.generationId,generationSeqStart:e.generationSeqStart,generationSeqEnd:e.generationSeqEnd}:{...g,surface:e.surface}}function ZAe({label:e,preview:t,fallbackOpenHref:n,sourceAttributes:r,onOpen:s}){var x,y,v,w,k,S;const a=((x=t==null?void 0:t.displayName)==null?void 0:x.trim())||e,o=((y=t==null?void 0:t.description)==null?void 0:y.trim())||null,l=((v=t==null?void 0:t.categoryLabel)==null?void 0:v.trim())||null,c=((w=t==null?void 0:t.locationLabel)==null?void 0:w.trim())||null,d=((k=t==null?void 0:t.detailsHref)==null?void 0:k.trim())||null,u=(n==null?void 0:n.trim())||((S=t==null?void 0:t.openHref)==null?void 0:S.trim())||null,f=!!(o||l||c||d),A=bs(),m=s?u??d:d,g=m?i.jsx("a",{className:"rudder-skill-token","data-skill-token":"true",href:m,"aria-label":`${a} skill`,style:oQ(),...r,onClick:j=>s==null?void 0:s(j,m,a),children:e}):i.jsx("span",{className:"rudder-skill-token","data-skill-token":"true",tabIndex:f?0:void 0,"aria-label":f?`${a} skill`:void 0,style:oQ(),...r,children:e});return i.jsxs("span",{className:K("rudder-skill-token-wrap",f&&"rudder-skill-token-wrap--preview"),children:[g,f?i.jsxs("span",{ref:A,className:"rudder-skill-hover-card scrollbar-auto-hide",role:"tooltip",[OE]:"",children:[i.jsxs("span",{className:"flex items-start gap-3",children:[i.jsx("span",{className:"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-md)] bg-[#2f80ed]/10 text-[#2f80ed]",children:i.jsx(wc,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block break-words text-sm font-medium leading-5 text-foreground",children:a}),l||c?i.jsxs("span",{className:"mt-1.5 flex min-w-0 flex-wrap items-center gap-1.5",children:[l?i.jsx("span",{className:"inline-flex items-center rounded-[var(--radius-sm)] border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[11px] font-medium leading-none text-muted-foreground",children:l}):null,c?i.jsx("span",{className:"min-w-0 break-all text-[11px] leading-4 text-muted-foreground",children:c}):null]}):null,o?i.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted-foreground",children:o}):null]})]}),d?i.jsxs("a",{className:"rudder-skill-hover-card-action",href:d,children:[i.jsx("span",{children:"View details"}),i.jsx(bx,{className:"h-3.5 w-3.5","aria-hidden":!0})]}):null]}):null]})}let sY=null;function TBt(){return sY||(sY=Wt(()=>import("./mermaid.core-CqqAFYNg.js").then(e=>e.bo),[]).then(e=>e.default)),sY}function u4(e){return e==null?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(t=>u4(t)).join(""):h.isValidElement(e)?u4(e.props.children):""}function uL(e){return(e==null?void 0:e.trim().replace(/\/+$/u,"").toLowerCase())??""}function P0(e){const t=(e==null?void 0:e.trim())??"";if(!t)return"item";const n=t.split(/[-/]/u).find(Boolean);return n&&n.length>=6?n.slice(0,12):t.length>12?t.slice(0,12):t}function iY(e){return((e==null?void 0:e.trim().replace(/\/+$/u,""))??"").split("/").filter(Boolean).at(-1)??""}function aY(e){var t,n,r,s,a,o,l;return e.kind==="agent"?P0(e.agentId):e.kind==="project"?P0(e.projectId):e.kind==="automation"?((t=e.title)==null?void 0:t.trim())||P0(e.automationId):e.kind==="issue"?((n=e.ref)==null?void 0:n.trim())||P0(e.issueId):e.kind==="chat"?((r=e.title)==null?void 0:r.trim())||P0(e.conversationId):e.kind==="library_doc"?((s=e.title)==null?void 0:s.trim())||P0(e.documentId):e.kind==="library_entry"?((a=e.title)==null?void 0:a.trim())||iY(e.path)||P0(e.entryId):e.kind==="library_file"?((o=e.title)==null?void 0:o.trim())||iY(e.filePath)||P0(e.filePath):((l=e.title)==null?void 0:l.trim())||iY(e.directoryPath)||P0(e.directoryPath)}function _Bt(e){if(!/[&][#a-z\d]+;/iu.test(e)||typeof document>"u")return e;const t=document.createElement("textarea");return t.innerHTML=e,t.value}function oY(e){return _Bt(e).replace(/\s+/gu," ").trim()}function MBt(){return typeof window>"u"?null:cp(window.location.pathname)}function EBt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DBt(e){return e.replace(/([\\[\]])/g,"\\$1")}function RBt(e){return e.trim().replace(/^@+/u,"")}function LBt(e){return/^[^\s@,!?.]+$/u.test(e)}function lY(e,t,n){const r=e.indexOf(t,n);return r>=0?r:null}function zBt(e,t){let n=!1;for(let r=t;r<e.length;r+=1){const s=e[r];if(n){n=!1;continue}if(s==="\\"){n=!0;continue}if(s===")")return r}return null}function $Bt(e){var o;const t=[];let n=0,r=0;function s(l){l>r&&t.push({text:e.slice(r,l),protected:!1})}function a(l){s(n),t.push({text:e.slice(n,l),protected:!0}),n=l,r=l}for(;n<e.length;){const l=e[n];if(l==="`"){const d=((o=e.slice(n).match(/^`+/u))==null?void 0:o[0])??"`",u=lY(e,d,n+d.length);if(u!==null){a(u+d.length);continue}}const c=l==="["?n:l==="!"&&e[n+1]==="["?n+1:null;if(c!==null){const d=lY(e,"]",c+1);if(d!==null&&e[d+1]==="("){const u=zBt(e,d+2);if(u!==null){a(u+1);continue}}}if(l==="<"){const d=lY(e,">",n+1);if(d!==null){a(d+1);continue}}n+=1}return s(e.length),t}function FBt(e,t){if(!e.includes("@")||!(t!=null&&t.length))return e;const n=t.map(o=>({...o,name:RBt(o.name)})).filter(o=>o.name&&o.agentId&&LBt(o.name)).sort((o,l)=>l.name.length-o.name.length);if(n.length===0)return e;const r=new RegExp(`(^|[^\\w/[\\]\`])@(${n.map(o=>EBt(o.name)).join("|")})(?=$|[\\s@,!?.])`,"giu"),s=/^(```|~~~)/;let a=!1;return e.split(/(\n)/).map(o=>o===`
1607
+ `):r}function J2(e){const t=e.cloneNode(!0);return WAe(t).replace(/^\n+|\n+$/gu,"")}function lVe(e){var a;const t=[],n=WAe(e,t),r=((a=n.match(/^\n+/u))==null?void 0:a[0].length)??0,s=n.replace(/^\n+|\n+$/gu,"").length;return t.map(o=>({...o,start:o.start-r,end:o.end-r})).filter(o=>o.end>0&&o.start<s).map(o=>({...o,start:Math.max(0,o.start),end:Math.min(s,o.end)}))}function cVe(e,t,n){const r=lVe(e);if(t.nodeType===Node.TEXT_NODE){const o=r.find(l=>l.node===t);return o?Math.max(o.start,Math.min(o.end,o.start+n)):null}if(!(t instanceof Element||t instanceof DocumentFragment))return null;const s=t.childNodes[n]??null;if(s){const o=r.find(l=>s===l.node||s.contains(l.node));if(o)return o.start}const a=n>0?t.childNodes[n-1]??null:null;if(a){const o=[...r].reverse().find(l=>a===l.node||a.contains(l.node));if(o)return o.end}return t===e&&n===0?0:t===e&&n===e.childNodes.length?J2(e).length:null}function dVe(e,t,n){const r=cVe(e,t,n);if(r!==null)return J2(e).slice(0,r);const s=document.createRange();s.selectNodeContents(e);try{s.setEnd(t,n)}catch{return null}return J2(s.cloneContents())}function uVe(e){return J2(e.cloneContents())}function SBt(e,t){var a;if(e[t]!=="&")return null;const n=(a=e.slice(t).match(/^&(?:#[xX][\da-fA-F]+|#\d+|[a-zA-Z][a-zA-Z\d]+);/u))==null?void 0:a[0];if(!n||typeof document>"u")return null;const r=document.createElement("textarea");r.innerHTML=n;const s=r.value;return s.length===1?{decoded:s,length:n.length}:null}function jBt(e){const t=Array(e.length).fill(!0),n=(r,s)=>{for(let a=r;a<s;a+=1)t[a]=!1};for(const r of e.matchAll(/!?\[[^\]\n]*\]\[[^\]\n]*\]/gu)){const s=r[0],a=r.index,o=s.indexOf("]");s.startsWith("!")?n(a,a+s.length):(n(a,a+1),o>=0&&n(a+o,a+s.length))}for(const r of e.matchAll(/!?\[[^\]\n]*\]\((?:\\.|[^)\n])*\)/gu)){const s=r[0],a=r.index,o=s.indexOf("]");o>=0&&n(a+o,a+s.length),n(a,a+(s.startsWith("!")?2:1))}for(const r of e.matchAll(/!\[[^\]\n]*\](?![\[(])/gu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/^[\t ]*\[[^\]\n]+\]:[^\n]*$/gmu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/<\/?[a-zA-Z][^>\n]*>/gu))n(r.index,r.index+r[0].length);return t}function SE(e,t,n=0){const r=[],s=$6t(t,e),a=jBt(t);let o=0;for(let l=0;l<e.length;l+=1){const c=e[l],d=Math.max(o,s.renderedBoundaryToRaw[l+1]-1);let u=-1,f=-1,A=Number.POSITIVE_INFINITY;const m=(g,x)=>{const y=Math.abs(g-d);(y<A||y===A&&(g>u||g===u&&x>f))&&(u=g,f=x,A=y)};for(let g=t.indexOf(c,o);g>=0&&!(a[g]&&(m(g,g+1),g>=d));g=t.indexOf(c,g+1));for(let g=t.indexOf("&",o);g>=0;g=t.indexOf("&",g+1)){const x=SBt(t,g);if(a[g]&&(x==null?void 0:x.decoded)===c&&(m(g,g+x.length),g>=d))break}if(u<0)return Array.from({length:e.length},(g,x)=>({start:n+s.renderedBoundaryToRaw[x],end:n+s.renderedBoundaryToRaw[x+1]}));r.push({start:n+u,end:n+f}),o=f}return r}function CBt(e,t){const n=e instanceof HTMLElement?e:e.parentElement,r=(n==null?void 0:n.closest("[data-markdown-source-start][data-markdown-source-end]"))??null;return r&&t.contains(r)?r:null}function fVe(e,t){const n=Number(e.dataset.markdownSourceStart),r=Number(e.dataset.markdownSourceEnd);return!Number.isInteger(n)||!Number.isInteger(r)||n<0||r<=n||r>t?null:{start:n,end:r}}function NBt(e,t,n){const r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(o){return p7(o,hw)||p7(o,OE)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let s=t,a=null;for(let o=r.nextNode();o;o=r.nextNode()){const l=o;a=l;const c=l.data.length;if(s<c||s===c&&n==="end")return{container:l,offset:s};s-=c}return s===0&&a?{container:a,offset:a.data.length}:null}function PBt(e,t,n,r){return Array.from(e.querySelectorAll("[data-markdown-source-start][data-markdown-source-end]")).map(a=>({element:a,bounds:fVe(a,t)})).filter(a=>!!a.bounds).filter(({bounds:a})=>r==="start"?a.start<=n&&n<a.end:a.start<n&&n<=a.end).sort((a,o)=>a.bounds.end-a.bounds.start-(o.bounds.end-o.bounds.start))[0]??null}function h5e(e,t,n,r){const s=PBt(e,t.length,n,r);if(!s)return null;const a=J2(s.element),o=SE(a,t.slice(s.bounds.start,s.bounds.end),s.bounds.start);if(!o)return null;const l=r==="start"?o.findIndex(c=>c.end>n):o.findLastIndex(c=>c.start<n)+1;return l<0?null:NBt(s.element,l,r)}function AVe(e){if(e.start<0||e.end<=e.start||e.end>e.source.length)return null;const t=h5e(e.sourceRoot,e.source,e.start,"start"),n=h5e(e.sourceRoot,e.source,e.end,"end");if(!t||!n)return null;const r=document.createRange();try{r.setStart(t.container,t.offset),r.setEnd(n.container,n.offset)}catch{return null}return r.collapsed?null:r}function IBt(e,t=document){return Array.from(t.querySelectorAll(`[${a3}]`)).find(r=>!r.isConnected||r.dataset.messageId!==e.sourceMessageId||r.dataset.annotationSurface!==e.surface?!1:e.surface==="assistant_body"?!0:r.dataset.transcriptKind===e.transcriptKind&&r.dataset.generationId===e.generationId&&Number(r.dataset.generationSeqStart)===e.generationSeqStart&&Number(r.dataset.generationSeqEnd)===e.generationSeqEnd)??null}function yie(e){const t=IBt(e.anchor,e.searchRoot);if(!t)return null;const n=AVe({sourceRoot:t,source:e.source,start:e.anchor.start,end:e.anchor.end});return n?{range:n,sourceRoot:t}:null}function m5e(e,t,n,r,s){var u,f;const a=CBt(n,e);if(!a)return null;const o=fVe(a,t.length);if(!o)return null;const l=dVe(a,n,r);if(l===null)return null;const c=J2(a),d=SE(c,t.slice(o.start,o.end),o.start);return d?s==="start"?l.length===d.length?o.end:((u=d[l.length])==null?void 0:u.start)??null:l.length===0?o.start:((f=d[l.length-1])==null?void 0:f.end)??null:null}function p5e(e){var x,y;const{range:t,sourceRoot:n}=e;if(t.collapsed||!n.contains(t.startContainer)||!n.contains(t.endContainer))return null;const r=n.getAttribute(a3),s=p7(t.startContainer,a3),a=p7(t.endContainer,a3);if(!r||s!==n||a!==n||Array.from(n.querySelectorAll(`[${hw}]`)).some(v=>{try{return t.intersectsNode(v)}catch{return!1}}))return null;if(e.surface==="process_transcript"){const v=p7(t.startContainer,dQ),w=p7(t.endContainer,dQ);if(!v||v!==w)return null}const l=uVe(t);if(!l)return null;const c=dVe(n,t.startContainer,t.startOffset);if(c===null)return null;const d=m5e(n,e.source,t.startContainer,t.startOffset,"start"),u=m5e(n,e.source,t.endContainer,t.endOffset,"end");let f=d??void 0,A=u??void 0;if(f===void 0||A===void 0){const v=J2(n),w=SE(v,e.source);if(!w)return null;const k=c.length,S=k+l.length;if(k<0||S>w.length||S<=k)return null;f??(f=(x=w[k])==null?void 0:x.start),A??(A=(y=w[S-1])==null?void 0:y.end)}if(f===void 0||A===void 0||A<=f)return null;for(;f<A&&new RegExp("\\p{White_Space}","u").test(e.source[f]??"")&&!l.startsWith(e.source[f]??"");)f+=1;for(;A>f&&new RegExp("\\p{White_Space}","u").test(e.source[A-1]??"")&&!l.endsWith(e.source[A-1]??"");)A-=1;const m=Math.min(160,Math.max(0,e.contextLength??160)),g={selectedText:l,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,sourceHash:e.sourceHash,start:f,end:A,prefix:e.source.slice(Math.max(0,f-m),f),suffix:e.source.slice(A,A+m)};return e.surface==="process_transcript"?{...g,surface:e.surface,transcriptKind:e.transcriptKind,generationId:e.generationId,generationSeqStart:e.generationSeqStart,generationSeqEnd:e.generationSeqEnd}:{...g,surface:e.surface}}function ZAe({label:e,preview:t,fallbackOpenHref:n,sourceAttributes:r,onOpen:s}){var x,y,v,w,k,S;const a=((x=t==null?void 0:t.displayName)==null?void 0:x.trim())||e,o=((y=t==null?void 0:t.description)==null?void 0:y.trim())||null,l=((v=t==null?void 0:t.categoryLabel)==null?void 0:v.trim())||null,c=((w=t==null?void 0:t.locationLabel)==null?void 0:w.trim())||null,d=((k=t==null?void 0:t.detailsHref)==null?void 0:k.trim())||null,u=(n==null?void 0:n.trim())||((S=t==null?void 0:t.openHref)==null?void 0:S.trim())||null,f=!!(o||l||c||d),A=bs(),m=s?u??d:d,g=m?i.jsx("a",{className:"rudder-skill-token","data-skill-token":"true",href:m,"aria-label":`${a} skill`,style:oQ(),...r,onClick:j=>s==null?void 0:s(j,m,a),children:e}):i.jsx("span",{className:"rudder-skill-token","data-skill-token":"true",tabIndex:f?0:void 0,"aria-label":f?`${a} skill`:void 0,style:oQ(),...r,children:e});return i.jsxs("span",{className:K("rudder-skill-token-wrap",f&&"rudder-skill-token-wrap--preview"),children:[g,f?i.jsxs("span",{ref:A,className:"rudder-skill-hover-card scrollbar-auto-hide",role:"tooltip",[OE]:"",children:[i.jsxs("span",{className:"flex items-start gap-3",children:[i.jsx("span",{className:"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-md)] bg-[#2f80ed]/10 text-[#2f80ed]",children:i.jsx(wc,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block break-words text-sm font-medium leading-5 text-foreground",children:a}),l||c?i.jsxs("span",{className:"mt-1.5 flex min-w-0 flex-wrap items-center gap-1.5",children:[l?i.jsx("span",{className:"inline-flex items-center rounded-[var(--radius-sm)] border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[11px] font-medium leading-none text-muted-foreground",children:l}):null,c?i.jsx("span",{className:"min-w-0 break-all text-[11px] leading-4 text-muted-foreground",children:c}):null]}):null,o?i.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted-foreground",children:o}):null]})]}),d?i.jsxs("a",{className:"rudder-skill-hover-card-action",href:d,children:[i.jsx("span",{children:"View details"}),i.jsx(bx,{className:"h-3.5 w-3.5","aria-hidden":!0})]}):null]}):null]})}let sY=null;function TBt(){return sY||(sY=Wt(()=>import("./mermaid.core-FscMPm7s.js").then(e=>e.bo),[]).then(e=>e.default)),sY}function u4(e){return e==null?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(t=>u4(t)).join(""):h.isValidElement(e)?u4(e.props.children):""}function uL(e){return(e==null?void 0:e.trim().replace(/\/+$/u,"").toLowerCase())??""}function P0(e){const t=(e==null?void 0:e.trim())??"";if(!t)return"item";const n=t.split(/[-/]/u).find(Boolean);return n&&n.length>=6?n.slice(0,12):t.length>12?t.slice(0,12):t}function iY(e){return((e==null?void 0:e.trim().replace(/\/+$/u,""))??"").split("/").filter(Boolean).at(-1)??""}function aY(e){var t,n,r,s,a,o,l;return e.kind==="agent"?P0(e.agentId):e.kind==="project"?P0(e.projectId):e.kind==="automation"?((t=e.title)==null?void 0:t.trim())||P0(e.automationId):e.kind==="issue"?((n=e.ref)==null?void 0:n.trim())||P0(e.issueId):e.kind==="chat"?((r=e.title)==null?void 0:r.trim())||P0(e.conversationId):e.kind==="library_doc"?((s=e.title)==null?void 0:s.trim())||P0(e.documentId):e.kind==="library_entry"?((a=e.title)==null?void 0:a.trim())||iY(e.path)||P0(e.entryId):e.kind==="library_file"?((o=e.title)==null?void 0:o.trim())||iY(e.filePath)||P0(e.filePath):((l=e.title)==null?void 0:l.trim())||iY(e.directoryPath)||P0(e.directoryPath)}function _Bt(e){if(!/[&][#a-z\d]+;/iu.test(e)||typeof document>"u")return e;const t=document.createElement("textarea");return t.innerHTML=e,t.value}function oY(e){return _Bt(e).replace(/\s+/gu," ").trim()}function MBt(){return typeof window>"u"?null:cp(window.location.pathname)}function EBt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DBt(e){return e.replace(/([\\[\]])/g,"\\$1")}function RBt(e){return e.trim().replace(/^@+/u,"")}function LBt(e){return/^[^\s@,!?.]+$/u.test(e)}function lY(e,t,n){const r=e.indexOf(t,n);return r>=0?r:null}function zBt(e,t){let n=!1;for(let r=t;r<e.length;r+=1){const s=e[r];if(n){n=!1;continue}if(s==="\\"){n=!0;continue}if(s===")")return r}return null}function $Bt(e){var o;const t=[];let n=0,r=0;function s(l){l>r&&t.push({text:e.slice(r,l),protected:!1})}function a(l){s(n),t.push({text:e.slice(n,l),protected:!0}),n=l,r=l}for(;n<e.length;){const l=e[n];if(l==="`"){const d=((o=e.slice(n).match(/^`+/u))==null?void 0:o[0])??"`",u=lY(e,d,n+d.length);if(u!==null){a(u+d.length);continue}}const c=l==="["?n:l==="!"&&e[n+1]==="["?n+1:null;if(c!==null){const d=lY(e,"]",c+1);if(d!==null&&e[d+1]==="("){const u=zBt(e,d+2);if(u!==null){a(u+1);continue}}}if(l==="<"){const d=lY(e,">",n+1);if(d!==null){a(d+1);continue}}n+=1}return s(e.length),t}function FBt(e,t){if(!e.includes("@")||!(t!=null&&t.length))return e;const n=t.map(o=>({...o,name:RBt(o.name)})).filter(o=>o.name&&o.agentId&&LBt(o.name)).sort((o,l)=>l.name.length-o.name.length);if(n.length===0)return e;const r=new RegExp(`(^|[^\\w/[\\]\`])@(${n.map(o=>EBt(o.name)).join("|")})(?=$|[\\s@,!?.])`,"giu"),s=/^(```|~~~)/;let a=!1;return e.split(/(\n)/).map(o=>o===`
1608
1608
  `?o:s.test(o.trimStart())?(a=!a,o):a?o:$Bt(o).map(l=>l.protected?l.text:l.text.replace(r,(c,d,u)=>{const f=n.find(m=>m.name.toLowerCase()===u.toLowerCase());if(!f)return c;const A=KM(f.agentId,f.agentIcon);return`${d}[@${DBt(f.name)}](${A})`})).join("")).join("")}function BBt(e){const t=(e==null?void 0:e.trim())??"";if(!t)return!1;if(t.startsWith("//"))return!0;if(!/^[a-z][a-z\d+.-]*:/iu.test(t))return!1;try{const n=new URL(t);return typeof window<"u"&&(n.protocol==="http:"||n.protocol==="https:")&&n.origin===window.location.origin?!1:n.protocol==="http:"||n.protocol==="https:"||n.protocol==="mailto:"}catch{return!1}}function hVe(e){const t=(e==null?void 0:e.trim())??"";if(!t)return null;const n=t.startsWith("//")?`${typeof window>"u"?"https:":window.location.protocol}${t}`:t;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"||typeof window<"u"&&r.origin===window.location.origin?null:r}catch{return null}}function QBt(e){const t=e.trim();return/^(?:https?:\/\/|www\.|\/\/)/iu.test(t)}function UBt(e){const t=(e==null?void 0:e.trim())??"";return t.startsWith("//")||/^[a-z][a-z\d+.-]*:/iu.test(t)}function VBt(e){var n,r;const t=((r=(n=e.split(/[\\/]/u).at(-1))==null?void 0:n.toLowerCase().match(/\.([^.]+)$/u))==null?void 0:r[1])??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(t)?"image":["zip","tar","gz","tgz","bz2","xz","7z","rar"].includes(t)?"archive":["csv","tsv","xls","xlsx","ods"].includes(t)?"spreadsheet":["ts","tsx","js","jsx","mjs","cjs","py","rb","go","rs","java","kt","kts","c","cc","cpp","h","hpp","cs","swift","php","sh","bash","zsh","fish","html","css","scss","less","json","jsonc","yaml","yml","toml","xml","sql","vue","svelte"].includes(t)?"code":["md","mdx","txt","pdf","doc","docx","rtf"].includes(t)?"document":"file"}function qBt({filePath:e}){const t=VBt(e),n=t==="image"?gBe:t==="archive"?Vjt:t==="spreadsheet"?sCt:t==="code"?K6:t==="document"?Fi:bBe;return i.jsx(n,{className:"mr-1 inline-block size-[0.95em] align-[-0.12em]","data-local-file-icon":t,"aria-hidden":"true"})}const g5e=new Set(["agents","automations","dashboard","goals","inbox","issues","library","messenger","organization","projects","settings","skills"]);function KBt(e){return e.button===0&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey}function x5e(e,t){if(typeof window>"u")return null;try{const n=new URL(e,window.location.href);if(n.origin!==window.location.origin)return null;const r=n.pathname.split("/").filter(Boolean);return(r[0]&&g5e.has(r[0])?r[0]:r[1]&&g5e.has(r[1])?r[1]:null)?Uc(`${n.pathname}${n.search}${n.hash}`,t):null}catch{return null}}function b5e(e){if(!e||typeof window>"u")return null;try{const t=new URL(e,window.location.href);if(t.origin!==window.location.origin)return null;const n=t.pathname.split("/").filter(Boolean),r=n.findIndex(a=>a.toLowerCase()==="issues");if(r<0)return null;const s=n[r+1];return s?decodeURIComponent(s):null}catch{return null}}function sk(e,t){const n=e==null?void 0:e.trim().toLowerCase();return n?t.find(r=>{var o;if(r.kind!=="issue"||!r.issueId)return!1;const s=r.issueId.toLowerCase(),a=((o=r.issueIdentifier)==null?void 0:o.toLowerCase())??"";return s===n||a===n||n.length>=6&&s.startsWith(n)})??null:null}function y5e({mention:e,label:t,targetHref:n,sourceAttributes:r,onClick:s}){const a=PUe(e),o=i.jsx("a",{href:n,className:K("rudder-mention-chip rudder-mention-chip--issue",a.status&&"rudder-mention-chip--with-status-icon"),"data-mention-kind":"issue","data-mention-comment":a.commentId?"true":void 0,"data-mention-status":a.status??void 0,...r,onClick:s,children:t});return i.jsx(hW,{mention:a,label:t,children:o})}function WBt(e){if(typeof window>"u")return;const t=`${window.location.pathname}${window.location.search}${window.location.hash}`;e!==t&&(window.history.pushState(window.history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:window.history.state})))}const ZBt=600*1e3,HBt=256,J1=new Map;function v5e(e){const t=J1.get(e);return t?t.expiresAt<=Date.now()?(J1.delete(e),null):(J1.delete(e),J1.set(e,t),t.state):null}function cY(e,t){for(J1.delete(e),J1.set(e,{expiresAt:Date.now()+ZBt,state:t});J1.size>HBt;){const n=J1.keys().next().value;if(typeof n!="string")break;J1.delete(n)}}function XBt(e){let t;try{t=typeof e=="string"?new URL(e):e}catch{return null}const n=Q6(t);if(n)return n.iconDataUrl;const r=J1.get(t.href);return(r==null?void 0:r.state.status)==="ready"?r.state.iconUrl:null}function GBt(e){const t=e.href,n=Q6(e),[r,s]=h.useState(()=>n?{status:"ready",iconUrl:n.iconDataUrl}:v5e(t)??{status:"idle",iconUrl:null});return h.useEffect(()=>{if(n){const d={status:"ready",iconUrl:n.iconDataUrl};cY(t,d),s(d);return}const a=v5e(t);if(a&&a.status!=="loading"){s(a);return}cY(t,{status:"loading",iconUrl:null});let l=!1;return Promise.resolve(TUe(t,"preview")).then(d=>d!=null&&d.iconUrl?{status:"ready",iconUrl:d.iconUrl}:{status:"none",iconUrl:null}).catch(()=>({status:"error",iconUrl:null})).then(d=>{cY(t,d),l||s(d)}),()=>{l=!0}},[t,n]),r}function mW({url:e}){const t=GBt(e),n=Q6(e),[r,s]=h.useState(()=>new Set),a=t.status==="ready"&&!r.has(t.iconUrl)?t.iconUrl:null;return a?i.jsx("span",{className:"rudder-website-link-icon","aria-hidden":"true","data-website-icon":"metadata",children:i.jsx("img",{src:a,alt:"",className:"rudder-website-link-logo","aria-hidden":"true","data-website-icon":"metadata","data-dark-mode":n==null?void 0:n.darkMode,referrerPolicy:"no-referrer",onError:()=>s(o=>new Set(o).add(a))})}):i.jsx("span",{className:"rudder-website-link-icon","aria-hidden":"true","data-website-icon":"generic",children:i.jsx(up,{className:"rudder-website-link-generic","aria-hidden":"true"})})}function YBt(e){if(!h.isValidElement(e))return null;const t=e.props;return typeof t.className!="string"||!/\blanguage-mermaid\b/i.test(t.className)?null:u4(t.children).replace(/\n$/,"")}function w5e(e){return u4(e).replace(/\n$/,"")}function JBt(e){var r;if(!h.isValidElement(e))return null;const t=e.props;if(typeof t.className!="string")return null;const n=(r=t.className.match(/\blanguage-([^\s]+)/i))==null?void 0:r[1];return(n==null?void 0:n.toLowerCase())??null}function eQt(e){return e==="diff"||e==="patch"||e==="udiff"}function tQt(e){return/^(?:diff --git|index |new file mode |deleted file mode |old mode |new mode |rename from |rename to |similarity index )/.test(e)?"meta":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("+")?"add":e.startsWith("-")?"remove":"context"}function nQt({source:e,preProps:t,sourceAttributes:n}){const r=e.split(`
1609
1609
  `);return i.jsx("pre",{...t,...n,className:K(typeof t.className=="string"?t.className:null,"rudder-markdown-patch-block"),children:i.jsx("code",{children:r.map((s,a)=>{const o=tQt(s),l=o==="add"||o==="remove",c=l?s.slice(0,1):"",d=l?s.slice(1):s;return i.jsxs("span",{className:K("rudder-markdown-patch-line",`rudder-markdown-patch-line--${o}`),children:[i.jsx("span",{className:"rudder-markdown-patch-line-marker","aria-hidden":!c,children:c}),i.jsx("span",{className:"rudder-markdown-patch-line-content",children:d})]},`${a}-${o}`)})})})}async function rQt(e){var r,s;if((r=navigator.clipboard)!=null&&r.writeText){await navigator.clipboard.writeText(e);return}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();const n=(s=document.execCommand)==null?void 0:s.call(document,"copy");if(t.remove(),!n)throw new Error("Clipboard write failed.")}function sQt(e,t,n=0){var c,d;const r=e==null?void 0:e.position,s=(c=r==null?void 0:r.start)==null?void 0:c.offset,a=(d=r==null?void 0:r.end)==null?void 0:d.offset;if(typeof s!="number"||typeof a!="number")return{};const o=n+((t==null?void 0:t.renderedBoundaryToRaw[s])??s),l=n+((t==null?void 0:t.renderedBoundaryToRaw[a])??a);return{"data-markdown-source-start":String(o),"data-markdown-source-end":String(l),"data-markdown-rendered-source-start":String(s),"data-markdown-rendered-source-end":String(a)}}function k5e(e){const t=e instanceof HTMLElement?e:(e==null?void 0:e.parentElement)??null;return(t==null?void 0:t.closest("[data-markdown-rendered-source-start][data-markdown-rendered-source-end]"))??null}function iQt(e,t){const n=Number(t.dataset.markdownRenderedSourceStart),r=Number(t.dataset.markdownRenderedSourceEnd);return!Number.isFinite(n)||!Number.isFinite(r)||r<=n?null:e.slice(n,r)}function aQt(e,t,n){const r=k5e(t.anchorNode),s=k5e(t.focusNode);if(r&&r===s)return iQt(n,r);const a=t.getRangeAt(0),o=Array.from(e.querySelectorAll("[data-markdown-rendered-source-start][data-markdown-rendered-source-end]")).filter(f=>{try{return a.intersectsNode(f)}catch{return!1}}),c=o.filter(f=>!o.some(A=>A!==f&&A.contains(f))).map(f=>({start:Number(f.dataset.markdownRenderedSourceStart),end:Number(f.dataset.markdownRenderedSourceEnd)})).filter(f=>Number.isFinite(f.start)&&Number.isFinite(f.end)&&f.end>f.start);if(c.length===0)return null;const d=Math.min(...c.map(f=>f.start)),u=Math.max(...c.map(f=>f.end));return n.slice(d,u)}const oQt=h.memo(function({source:t,darkMode:n}){const r=h.useId().replace(/[^a-zA-Z0-9_-]/g,""),[s,a]=h.useState(null),[o,l]=h.useState(null);return h.useEffect(()=>{let c=!0;return a(null),l(null),TBt().then(async d=>{d.initialize({startOnLoad:!1,securityLevel:"strict",theme:n?"dark":"default",fontFamily:"inherit",suppressErrorRendering:!0});const u=await d.render(`rudder-mermaid-${r}`,t);c&&a(u.svg)}).catch(d=>{if(!c)return;const u=d instanceof Error&&d.message?d.message:"Failed to render Mermaid diagram.";l(u)}),()=>{c=!1}},[n,r,t]),i.jsx("div",{className:"rudder-mermaid",children:s?i.jsx("div",{dangerouslySetInnerHTML:{__html:s}}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:K("rudder-mermaid-status",o&&"rudder-mermaid-status-error"),children:o?`Unable to render Mermaid diagram: ${o}`:"Rendering Mermaid diagram..."}),i.jsx("pre",{className:"rudder-mermaid-source",children:i.jsx("code",{className:"language-mermaid",children:t})})]})})});function O5e({children:e,copyText:t,preProps:n,sourceAttributes:r,block:s}){const[a,o]=h.useState("idle"),l=h.useRef(void 0),c=a==="copied"?"Copied":a==="failed"?"Copy failed":"Copy code";h.useEffect(()=>()=>clearTimeout(l.current),[]);const d=h.useCallback(async()=>{clearTimeout(l.current);try{await rQt(t),o("copied")}catch{o("failed")}l.current=setTimeout(()=>o("idle"),1600)},[t]);return i.jsxs("div",{className:"rudder-code-block-copy-wrap",children:[s??i.jsx("pre",{...n,...r,children:e}),i.jsx(Wc,{delayDuration:120,children:i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx("button",{type:"button",className:"rudder-code-block-copy-button","aria-label":c,"data-copy-state":a,onClick:()=>void d(),children:a==="copied"?i.jsx(Zs,{className:"h-3.5 w-3.5","aria-hidden":"true"}):i.jsx(Al,{className:"h-3.5 w-3.5","aria-hidden":"true"})})}),i.jsx(ia,{side:"left",sideOffset:8,children:c})]})})]})}function Qo({children:e,className:t,resolveImageSrc:n,onLinkClick:r,agentMentions:s,skillReferences:a,enableImagePreview:o=!0,copyMarkdownOnCopy:l=!1,enableCodeBlockCopy:c=!1,sourceOffsetBase:d=0}){const{resolvedTheme:u}=RAe(),{mentions:f}=DAe(),A=new Map(f.filter(L=>L.kind==="agent").map(L=>[L.agentId??L.id.replace(/^agent:/,""),L])),m=new Map(f.filter(L=>L.kind==="project"&&L.projectId).map(L=>[L.projectId,L])),g=new Map(f.filter(L=>L.kind==="issue"&&L.issueId).map(L=>[L.issueId,L])),x=f.filter(L=>L.kind==="issue"&&L.issueId),y=new Map(f.filter(L=>L.kind==="automation"&&L.automationId).map(L=>[L.automationId,L])),v=new Map(f.filter(L=>L.kind==="chat"&&L.chatConversationId).map(L=>[L.chatConversationId,L])),w=new Map(f.filter(L=>L.kind==="library_doc"&&L.libraryDocumentId).map(L=>[L.libraryDocumentId,L])),k=new Map(f.filter(L=>L.kind==="library_file"&&L.libraryEntryId).map(L=>[L.libraryEntryId,L])),S=new Map(f.filter(L=>L.kind==="library_file"&&L.libraryFilePath).map(L=>[L.libraryFilePath,L])),j=new Map(f.filter(L=>L.kind==="library_directory"&&L.libraryDirectoryPath).map(L=>[L.libraryDirectoryPath,L])),C=new Map((a??[]).map(L=>[uL(L.href),L]).filter(([L])=>L.length>0)),N=new Map((a??[]).map(L=>[uL(L.label),L]).filter(([L])=>L.length>0)),P=MBt(),{normalizedChildren:M,sourceMap:E}=h.useMemo(()=>{const L=FBt(zAe(e),s);return{normalizedChildren:L,sourceMap:D$t(e,L)}},[s,e]),T=h.useCallback(L=>sQt(L,E,d),[E,d]),R=h.useCallback(({node:L,children:H,...X})=>i.jsx("li",{...X,...T(L),children:H}),[T]),_=L=>{if(!l)return;const H=window.getSelection();if(!H||H.rangeCount===0||H.isCollapsed||!L.currentTarget.contains(H.anchorNode)||!L.currentTarget.contains(H.focusNode))return;const X=aQt(L.currentTarget,H,M)??M;L.clipboardData.setData("text/plain",X),L.preventDefault()},D=(L,H,X,F)=>{if(r==null?void 0:r({event:L,href:H,label:X,sourceHref:F})){L.preventDefault();return}if(L.defaultPrevented||!KBt(L))return;const q=x5e(H,P);q&&(L.preventDefault(),WBt(q))},U=h.useCallback(({node:L,children:H,...X})=>{const F=YBt(H);if(F)return i.jsx(oQt,{source:F,darkMode:u==="dark"});const Q=T(L),q=JBt(H),B=eQt(q)?w5e(H):null;if(B!==null){const ee=i.jsx(nQt,{source:B,preProps:X,sourceAttributes:Q});return c?i.jsx(O5e,{copyText:B,preProps:{},sourceAttributes:{},block:ee}):ee}return c?i.jsx(O5e,{copyText:w5e(H),preProps:X,sourceAttributes:Q,children:H}):i.jsx("pre",{...X,...Q,children:H})},[c,u,T]),$={p:({node:L,children:H,...X})=>i.jsx("p",{...X,...T(L),children:H}),h1:({node:L,children:H,...X})=>i.jsx("h1",{...X,...T(L),children:H}),h2:({node:L,children:H,...X})=>i.jsx("h2",{...X,...T(L),children:H}),h3:({node:L,children:H,...X})=>i.jsx("h3",{...X,...T(L),children:H}),h4:({node:L,children:H,...X})=>i.jsx("h4",{...X,...T(L),children:H}),h5:({node:L,children:H,...X})=>i.jsx("h5",{...X,...T(L),children:H}),h6:({node:L,children:H,...X})=>i.jsx("h6",{...X,...T(L),children:H}),strong:({node:L,children:H,...X})=>i.jsx("strong",{...X,...T(L),children:H}),em:({node:L,children:H,...X})=>i.jsx("em",{...X,...T(L),children:H}),del:({node:L,children:H,...X})=>i.jsx("del",{...X,...T(L),children:H}),code:({node:L,children:H,...X})=>i.jsx("code",{...X,...T(L),children:H}),li:R,table:({node:L,children:H,...X})=>i.jsx("div",{className:"rudder-markdown-table-scroll",children:i.jsx("table",{...X,...T(L),children:H})}),pre:U,a:({node:L,href:H,children:X})=>{const F=H?ac(H):null;if(F){const ce=oY(fw(u4(X))),Oe=(()=>{var ae;if(F.kind==="agent")return{...F,icon:((ae=A.get(F.agentId))==null?void 0:ae.agentIcon)??F.icon};if(F.kind==="project"){const fe=m.get(F.projectId);return{...F,color:(fe==null?void 0:fe.projectColor)??F.color,icon:(fe==null?void 0:fe.projectIcon)??F.icon}}if(F.kind==="issue"){const fe=g.get(F.issueId)??sk(F.issueId,x)??sk(F.ref,x)??sk(b5e(H),x);return{...F,issueId:F.issueId,ref:(fe==null?void 0:fe.issueIdentifier)??F.ref,status:(fe==null?void 0:fe.issueStatus)??F.status}}return F})(),Fe=(()=>{var ae,fe,ve,Se,ze,ft,ie,me,we,Xe,ge;if(Oe.kind==="agent")return((ae=A.get(Oe.agentId))==null?void 0:ae.name)??ce;if(Oe.kind==="project")return((fe=m.get(Oe.projectId))==null?void 0:fe.name)??ce;if(Oe.kind==="issue"){const te=g.get(Oe.issueId)??sk(Oe.issueId,x)??sk(Oe.ref,x);return((te==null?void 0:te.name)??ce??((ve=Oe.ref)==null?void 0:ve.trim())??"")||((Se=Oe.ref)==null?void 0:Se.trim())||aY(Oe)}return Oe.kind==="automation"?((ze=y.get(Oe.automationId))==null?void 0:ze.name)??((ft=Oe.title)==null?void 0:ft.trim())??ce:Oe.kind==="chat"?((ie=v.get(Oe.conversationId))==null?void 0:ie.name)??ce:Oe.kind==="library_doc"?((me=w.get(Oe.documentId))==null?void 0:me.name)??ce:Oe.kind==="library_entry"?((we=k.get(Oe.entryId))==null?void 0:we.name)??ce:Oe.kind==="library_file"?((Xe=S.get(Oe.filePath))==null?void 0:Xe.name)??ce:Oe.kind==="library_directory"?((ge=j.get(Oe.directoryPath))==null?void 0:ge.name)??ce:ce})()||aY(Oe),ke=oY(Fe),Ne=Uc(Aw(Oe),P);if(Oe.kind==="issue")return i.jsx(y5e,{mention:Oe,label:ke,targetHref:Ne,sourceAttributes:T(L),onClick:ae=>{D(ae,Ne,ke)}});const xe=i.jsx("a",{href:Ne,className:K("rudder-mention-chip",`rudder-mention-chip--${Oe.kind}`,Oe.kind==="project"&&"rudder-project-mention-chip"),"data-mention-kind":Oe.kind,style:$j(Oe),...T(L),onClick:ae=>{D(ae,Ne,ke)},children:ke});return Oe.kind==="automation"||Oe.kind==="chat"?xe:i.jsx(hW,{mention:Oe,label:ke,children:xe})}const Q=nh(H,u4(X));if(Q){const ce=C.get(uL(Q.href))??N.get(uL(Q.label))??null,Oe=i3(ce==null?void 0:ce.label)||Q.label;return i.jsx(ZAe,{label:Oe,preview:ce,fallbackOpenHref:IAe(Q.href)??(ce==null?void 0:ce.openHref)??"#",sourceAttributes:T(L),onOpen:r?(Fe,ke,Ne)=>{D(Fe,ke,Ne,Q.href)}:void 0})}const q=u4(X),B=BBt(H),ee=hVe(H),se=IUe(H),re=B&&QBt(q),ne=H?x5e(H,P):null,Ae=sk(b5e(H),x);if(Ae&&ne){const ce={kind:"issue",issueId:Ae.issueId,ref:Ae.issueIdentifier??null,commentId:null,status:Ae.issueStatus??null},Oe=oY(Ae.name||q||aY(ce));return i.jsx(y5e,{mention:ce,label:Oe,targetHref:ne,sourceAttributes:T(L),onClick:Fe=>{D(Fe,ne,Oe)}})}const Y=ne&&!UBt(H)?ne:H;return ee?i.jsxs("a",{href:H,target:"_blank",rel:"noreferrer noopener",title:re?H:void 0,className:"rudder-website-link",...T(L),onClick:ce=>{H&&D(ce,H,q)},children:[i.jsx(mW,{url:ee}),i.jsx("span",{className:"rudder-website-link-label",children:X})]}):se?i.jsxs("a",{href:H,className:"rudder-local-file-link",...T(L),onClick:ce=>{H&&D(ce,H,q)},children:[i.jsx(qBt,{filePath:se}),X]}):i.jsx("a",{href:Y,target:B?"_blank":void 0,rel:B?"noreferrer noopener":"noreferrer",title:re?H:void 0,...T(L),onClick:ce=>{H&&D(ce,ne??H,q)},children:X})}};return $.img=({node:L,src:H,alt:X,...F})=>{const q=(H&&n?n(H):null)??H??"";return o&&q?i.jsx(kb,{...F,src:q,alt:X??"",name:(X==null?void 0:X.trim())||"Markdown image",previewTestId:"markdown-body-image-preview-dialog",previewTitleFallback:"Image preview"}):i.jsx("img",{...F,src:q,alt:X??""})},i.jsx(i.Fragment,{children:i.jsx("div",{className:K("rudder-markdown prose prose-sm max-w-none break-words overflow-hidden",u==="dark"&&"prose-invert",t),onCopyCapture:_,"data-copy-markdown-source":l?"true":void 0,children:i.jsx(mAe,{remarkPlugins:[tW],components:$,urlTransform:L=>L,children:M})})})}const Ks={listSavedViews:(e,t={})=>{const n=new URLSearchParams({visibility:t.visibility??"visible"});return t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset)),t.primaryRailPinned!==void 0&&n.set("primaryRailPinned",String(t.primaryRailPinned)),Re.get(`/orgs/${e}/messenger/saved-views?${n.toString()}`)},getSavedView:(e,t)=>Re.get(`/orgs/${e}/messenger/saved-views/${t}`),keepSavedView:(e,t)=>Re.post(`/orgs/${e}/messenger/saved-views/keep`,t),createSavedView:(e,t)=>Re.post(`/orgs/${e}/messenger/saved-views`,t),updateSavedView:(e,t,n)=>Re.patch(`/orgs/${e}/messenger/saved-views/${t}`,n),reorderSavedViews:(e,t)=>Re.patch(`/orgs/${e}/messenger/saved-views/reorder`,{ids:t}),deleteSavedView:(e,t)=>Re.delete(`/orgs/${e}/messenger/saved-views/${t}`),listThreads:e=>Re.get(`/orgs/${e}/messenger/threads`),listThreadPage:(e,t={})=>{const n=new URLSearchParams;t.cursor&&n.set("cursor",t.cursor),typeof t.limit=="number"&&n.set("limit",String(t.limit)),t.splitIssues&&n.set("splitIssues","true");const r=n.toString();return Re.get(`/orgs/${e}/messenger/threads${r?`?${r}`:""}`)},markThreadRead:(e,t,n)=>Re.post(`/orgs/${e}/messenger/threads/${encodeURIComponent(t)}/read`,n?{lastReadAt:n}:{}),dismissUnreads:e=>Re.post(`/orgs/${e}/messenger/unreads/dismiss`,{}),updateThreadUserState:(e,t,n)=>Re.post(`/orgs/${e}/messenger/threads/${encodeURIComponent(t)}/user-state`,n),getIssuesThread:(e,t={})=>{const n=new URLSearchParams;t.cursor&&n.set("cursor",t.cursor),typeof t.limit=="number"&&n.set("limit",String(t.limit));const r=n.toString();return Re.get(`/orgs/${e}/messenger/issues${r?`?${r}`:""}`)},getApprovalsThread:e=>Re.get(`/orgs/${e}/messenger/approvals`),getSystemThread:(e,t)=>Re.get(`/orgs/${e}/messenger/system/${t}`),listCustomGroups:e=>Re.get(`/orgs/${e}/messenger/groups`),createCustomGroup:(e,t)=>Re.post(`/orgs/${e}/messenger/groups`,t),createCustomGroupWithEntries:(e,t)=>Re.post(`/orgs/${e}/messenger/groups/merge`,t),updateCustomGroup:(e,t,n)=>Re.patch(`/orgs/${e}/messenger/groups/${t}`,n),regenerateCustomGroupTitle:(e,t)=>Re.post(`/orgs/${e}/messenger/groups/${t}/title/regenerate`,{}),separateCustomGroup:(e,t)=>Re.post(`/orgs/${e}/messenger/groups/${t}/separate`,{}),deleteCustomGroup:(e,t)=>Re.delete(`/orgs/${e}/messenger/groups/${t}`),reorderCustomGroups:(e,t)=>Re.patch(`/orgs/${e}/messenger/groups/reorder`,{groupIds:t}),assignCustomGroupEntry:(e,t,n)=>Re.post(`/orgs/${e}/messenger/groups/${t}/entries`,{itemKey:n}),removeCustomGroupEntry:(e,t)=>Re.delete(`/orgs/${e}/messenger/groups/entries/${encodeURIComponent(t)}`),reorderCustomGroupEntries:(e,t,n)=>Re.patch(`/orgs/${e}/messenger/groups/${t}/entries/reorder`,{itemKeys:n})},lQt=400,cQt=2e3;function pW(e){return e==="starting"||e==="stopping"?lQt:e==="running"?cQt:!1}function HAe(e,t){return e.desktopInstallationId===t.desktopInstallationId&&e.appPublicId===t.appPublicId&&e.localBindingId===t.localBindingId}function mVe(e){return["A Local App could not open in Rudder Desktop.",`Local App label (context only): ${e.trim().replace(/[\r\n]+/g," ").slice(0,160)||"this Local App"}`,"Help me diagnose the startup issue. Ask for any error details or logs you need; I will review them before sharing."].join(`
1610
1610
 
@@ -1688,7 +1688,7 @@ When you submit the join request, use:
1688
1688
  - \`agentRuntimeType: "openclaw_gateway"\`
1689
1689
  - \`agentDefaultsPayload.url\` 填你的 \`ws://\` 或 \`wss://\` gateway URL
1690
1690
  - \`agentDefaultsPayload.headers["x-openclaw-token"]\` 填你的 gateway token
1691
- - (兼容旧字段)\`agentDefaultsPayload.headers["x-openclaw-auth"]\``,"organizationSettings.packages.description":"在不同 Rudder 安装之间迁移组织配置与工作数据。","organizationSettings.packages.export":"导出","organizationSettings.packages.import":"导入","organizationSettings.danger.description":"归档这个 organization 后,它会从侧边栏中隐藏。这个状态会持久化到数据库。","organizationSettings.danger.confirm":"要归档 organization “{{name}}” 吗?它会从侧边栏中隐藏。","organizationSettings.danger.archiving":"归档中...","organizationSettings.danger.alreadyArchived":"已归档","organizationSettings.danger.archive":"归档 organization","organizationSettings.danger.failed":"归档 organization 失败","settings.eyebrow.system":"系统设置","settings.eyebrow.labs":"实验室","app.instanceSetupRequired":"需要完成实例初始化","app.bootstrapInvite.active":"当前还没有实例管理员。引导邀请已经激活。请查看 Rudder 启动日志中的首个管理员邀请链接,或运行下面的命令重新生成:","app.bootstrapInvite.inactive":"当前还没有实例管理员。请在 Rudder 运行环境中执行下面的命令生成首个管理员邀请链接:","app.failedToLoadAppState":"加载应用状态失败","app.addAnotherAgentToOrganization":"为 {{name}} 再添加一个智能体","app.createAnotherOrganization":"创建另一个组织","app.createFirstOrganization":"创建你的第一个组织","app.onboarding.addAgentDescription":"再次运行引导,为这个组织添加一个智能体和一个初始任务。","app.onboarding.createAnotherDescription":"再次运行引导,创建另一个组织并初始化它的第一个智能体。","app.onboarding.createFirstDescription":"从创建一个组织和你的第一个智能体开始。","app.addAgent":"添加智能体","app.startOnboarding":"开始引导","app.noCompaniesDescription":"从创建一个组织开始。","app.newOrganization":"新建组织","general.title":"通用","general.description":"这台设备上的核心应用偏好。","general.updateFailed":"更新通用设置失败。","general.loadLoading":"正在加载通用设置...","general.loadFailed":"加载通用设置失败。","general.language.title":"语言","general.language.description":"选择这个 Rudder 实例在控制台界面中使用的语言。","general.language.label":"界面语言","general.language.help":"这是实例级界面语言,会影响所有使用这个实例的用户看到的控制台外壳和设置页面。","general.language.option.en.label":"英语","general.language.option.en.description":"默认产品语言","general.language.option.zh-CN.label":"简体中文","general.language.option.zh-CN.description":"中文界面","general.language.preview.en.primary":"Hello","general.language.preview.en.secondary":"Board UI","general.language.preview.zh-CN.primary":"你好","general.language.preview.zh-CN.secondary":"控制台界面","general.basics.title":"基础","general.productTour.title":"工作台教程","general.productTour.description":"重新播放引导教程。","general.productTour.start":"开始教程","general.logs.title":"操作日志","general.logs.description":"调整界面中面向操作员展示的输出方式。","general.logs.censor.title":"对日志中的用户名做脱敏","general.logs.censor.description":"对日志中显示的主目录路径用户名做脱敏。","general.updates.title":"桌面应用","general.updates.description":"选择这台机器安装 Rudder Desktop 时使用哪个发布渠道。","general.updates.loadFailed":"加载桌面更新设置失败。","general.updates.updateFailed":"更新桌面更新设置失败。","general.updates.unavailable":"当前环境不支持桌面更新设置。","general.updates.canary.title":"接收桌面测试版更新","general.updates.canary.disabledDescription":"安装最新正式版;当测试版更新时也纳入检测。","general.updates.canary.enabledDescription":"这台机器会同时检查正式版和更新的测试版。","general.diagnostics.developer.title":"显示开发诊断信息","general.diagnostics.developer.description":"在 transcript 中显示 Rudder 内部运行时、workspace、session 和 adapter 诊断信息。","general.developer.title":"开发者","general.appearance.title":"外观","general.appearance.description":"选择这个设备上的 Rudder 外观。视觉风格遵循低眩光、克制的 Claude 风格界面。","general.appearance.colorMode":"颜色模式","general.appearance.light.label":"浅色","general.appearance.light.description":"暖色纸面风格","general.appearance.system.label":"自动","general.appearance.system.description":"跟随系统外观","general.appearance.dark.label":"深色","general.appearance.dark.description":"低眩光工作区","general.appearance.designStyle":"设计风格","general.appearance.defaultStyle.label":"Classic","general.appearance.defaultStyle.description":"平衡的低眩光界面","general.appearance.mira.label":"Compact","general.appearance.mira.description":"紧凑卡片与控件","general.appearance.luma.label":"Rudder","general.appearance.luma.description":"柔和宽松的控件","general.appearance.baseColor":"基础色","general.appearance.base.neutral.label":"Neutral","general.appearance.base.neutral.description":"平衡的中性灰界面","general.appearance.base.stone.label":"Stone","general.appearance.base.stone.description":"暖调石色界面","general.appearance.base.zinc.label":"Zinc","general.appearance.base.zinc.description":"冷调灰色界面","general.appearance.base.mauve.label":"Mauve","general.appearance.base.mauve.description":"低饱和玫瑰灰界面","general.appearance.base.olive.label":"Olive","general.appearance.base.olive.description":"低饱和橄榄色界面","general.appearance.base.mist.label":"Mist","general.appearance.base.mist.description":"柔和蓝灰界面","general.appearance.base.taupe.label":"Taupe","general.appearance.base.taupe.description":"暖调灰褐界面","general.appearance.themeColor":"主题色","general.appearance.theme.neutral.label":"Neutral","general.appearance.theme.neutral.description":"单色操作状态","general.appearance.theme.amber.label":"Amber","general.appearance.theme.amber.description":"琥珀色操作状态","general.appearance.theme.blue.label":"Blue","general.appearance.theme.blue.description":"蓝色操作状态","general.appearance.theme.cyan.label":"Cyan","general.appearance.theme.cyan.description":"青色操作状态","general.appearance.theme.emerald.label":"Rudder","general.appearance.theme.emerald.description":"Rudder 绿色操作状态","general.appearance.theme.fuchsia.label":"Fuchsia","general.appearance.theme.fuchsia.description":"紫红色操作状态","general.appearance.theme.green.label":"Green","general.appearance.theme.green.description":"绿色操作状态","general.appearance.theme.indigo.label":"Indigo","general.appearance.theme.indigo.description":"靛蓝色操作状态","general.appearance.theme.lime.label":"Lime","general.appearance.theme.lime.description":"青柠色操作状态","general.appearance.theme.orange.label":"Orange","general.appearance.theme.orange.description":"橙色操作状态","general.appearance.theme.pink.label":"Pink","general.appearance.theme.pink.description":"粉色操作状态","notifications.title":"通知","notifications.description":"管理这个 Rudder 实例的未读 inbox 提醒。","notifications.loadFailed":"加载通知设置失败。","notifications.updateFailed":"更新通知设置失败。","notifications.support.available":"可用","notifications.support.unavailable":"不可用","notifications.permission.title":"权限","notifications.permission.description":"通知权限由操作系统或浏览器掌控,所以 Rudder 需要同时展示当前状态和修复入口。","notifications.permission.requestFailed":"请求通知权限失败。","notifications.permission.openSettingsFailed":"打开通知设置失败。","notifications.permission.access.title":"通知访问权限","notifications.permission.access.summary":"权限:{{permission}}。提醒:{{notificationsSupport}}。","notifications.permission.access.summaryDesktop":"权限:{{permission}}。原生提醒:{{notificationsSupport}}。","notifications.permission.access.default":"Rudder 还没有请求通知权限,因此未读 inbox 提醒可能不会出现。","notifications.permission.access.denied.desktop":"通知权限已被操作系统拦截。请在系统通知设置中重新允许 Rudder,才能恢复 macOS 提醒。","notifications.permission.access.denied.browser":"通知权限已被浏览器拦截。请在浏览器站点通知设置中重新允许 Rudder,才能在 `pnpm dev` 里预览 inbox 提醒。","notifications.permission.access.requesting":"请求中...","notifications.permission.access.enable":"开启通知","notifications.permission.access.desktopHelp":"这里能触发原生通知,但真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.desktopHelpProd":"真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.openSettings":"打开通知设置","notifications.environment.title":"当前环境","notifications.environment.desktop":"当前运行在 Electron 桌面壳中。","notifications.environment.browser":"当前运行在浏览器预览模式中。","notifications.environment.desktopHelp":"这里可以使用原生系统通知来提示未读 inbox 变化。","notifications.environment.browserHelp":"浏览器模式可以通过 Web Notifications API 预览未读 inbox 提醒。","notifications.behavior.title":"行为","notifications.behavior.description":"选择 Rudder 是否提示未读 inbox 活动。","notifications.behavior.inbox.title":"Inbox 活动提醒","notifications.behavior.inbox.description":"当未读 inbox 数量增加时显示提醒。","notifications.behavior.inbox.toggle":"切换 inbox 通知","systemPermissions.title":"系统权限","systemPermissions.description":"管理本地自动化、文件访问和 inbox 提醒所需的系统权限。","systemPermissions.section.title":"权限","systemPermissions.section.description":"Rudder 会尽量打开对应系统设置;最终状态仍以操作系统为准。","systemPermissions.status.authorized":"已授权","systemPermissions.status.needsAccess":"需要授权","systemPermissions.status.blocked":"已阻止","systemPermissions.status.checking":"检查中","systemPermissions.status.desktopOnly":"仅桌面应用","systemPermissions.status.perApp":"按应用授权","systemPermissions.status.unknown":"未知","systemPermissions.status.unavailable":"不可用","systemPermissions.action.openSettings":"打开设置","systemPermissions.action.desktopOnly":"仅桌面可用","systemPermissions.action.browserManaged":"由浏览器管理","systemPermissions.openSettingsFailed":"打开系统设置失败。","systemPermissions.permission.fullDiskAccess.title":"完全磁盘访问权限","systemPermissions.permission.fullDiskAccess.description":"在需要更广文件访问时读取本地项目文件和工作区元数据。","systemPermissions.permission.accessibility.title":"辅助功能","systemPermissions.permission.accessibility.description":"让 Rudder 驱动的桌面自动化在需要时观察并控制应用界面。","systemPermissions.permission.automation.title":"自动化","systemPermissions.permission.automation.description":"macOS 会按目标应用分别授权自动化;可打开此面板查看具体应用条目。","systemPermissions.permission.notifications.title":"通知","systemPermissions.permission.notifications.description":"Rudder 通知的系统访问权限。Issue 和 chat 通知可以在下方分别控制。","systemPermissions.permission.notifications.inboxLabel":"Inbox 活动提醒","systemPermissions.notifications.title":"通知","systemPermissions.notifications.description":"系统通知权限可用后,选择 Rudder 哪些事件需要提醒你。","systemPermissions.notifications.system.title":"系统通知访问权限","systemPermissions.notifications.system.description":"如果 Rudder 通知被阻止或没有出现,可以打开系统通知设置检查。","systemPermissions.notifications.issue.title":"Issue 通知","systemPermissions.notifications.issue.description":"当 issue 被创建、更新、评论或重新打开时提醒。","systemPermissions.notifications.issue.toggle":"切换 issue 通知","systemPermissions.notifications.chat.title":"Chat 通知","systemPermissions.notifications.chat.description":"当 assistant chat 回复、提议 issue 或操作时提醒。","systemPermissions.notifications.chat.toggle":"切换 chat 通知","about.title":"关于","about.version.title":"版本","about.version.description":"这里显示当前机器上运行的 Rudder 构建版本。","about.version.current":"版本","about.desktop.title":"桌面应用","about.desktop.description":"这个壳层连接到与控制台、CLI 以及其他本地 Rudder 界面共用的同一份本地实例数据。","about.desktop.profile":"环境","about.desktop.instance":"实例 ID","about.desktop.runtime":"运行时","about.desktop.owner":"拥有者","about.desktop.instanceDataPath":"实例数据路径","about.actions.title":"操作","about.actions.description":"这些动作属于应用生命周期,不应该埋在通用偏好里。","about.notifications.description":"Inbox 提醒、角标行为和权限修复入口现在都集中在独立的通知设置页中管理。","about.notifications.open":"打开通知设置","about.updates.title":"检查更新","about.updates.description":"将当前桌面构建与所选 GitHub Release 策略做对比。","about.updates.check":"检查更新","about.updates.install":"更新","about.updates.download":"下载更新","about.updates.installing":"正在更新...","about.updates.channel.stable":"正式版","about.updates.channel.canary":"正式版 + Canary","about.updates.available.inline":"发现 {{channel}} 新版本:{{latestVersion}}。","about.updates.current.inline":"{{channel}} 当前已经是最新版本:{{currentVersion}}。","about.updates.unavailable.inline":"暂时无法完成 {{channel}} 版本对比。","about.updates.available.toastTitle":"发现新版本","about.updates.available.toastBody":"{{latestVersion}} 已可下载。","about.updates.installStarted.toastTitle":"已开始更新","about.updates.installStarted.toastBody":"Rudder 会在安装 {{latestVersion}} 后关闭并重新打开。","about.updates.installWaiting.toastTitle":"更新已排队","about.updates.installWaiting.toastBody":"安装包正在下载。Rudder 会在 {{totalRuns}} 个活跃运行结束后自动更新。","about.updates.installBlocked.toastTitle":"更新已暂停","about.updates.installUnavailable":"当前构建不支持应用内安装更新。","about.updates.installFailed":"无法开始更新。","about.updates.installFailedToastTitle":"无法开始更新","about.updates.progress.title":"正在更新到 {{version}}","about.updates.progress.readyTitle":"更新已准备好","about.updates.progress.completeTitle":"重启交接已完成","about.updates.progress.detailsTitle":"更新进度详情","about.updates.progress.failedTitle":"更新失败","about.updates.progress.retry":"重试","about.updates.progress.restartToUpdate":"退出并更新","about.updates.progress.updateWhenIdle":"空闲时更新","about.updates.progress.forceRestartToUpdate":"停止运行并立即更新","about.updates.progress.blockersTitle":"正在延迟更新的运行","about.updates.progress.blockerRun":"{{organization}} · {{agent}} · 运行 {{runId}}","about.updates.progress.automaticApply":"这些运行结束后,Rudder 会自动完成更新。","about.updates.progress.openReleases":"打开发布页","about.updates.progress.dismiss":"关闭更新状态","about.updates.progress.phase.starting":"正在开始更新...","about.updates.progress.phase.resolving_release":"正在解析发布版本...","about.updates.progress.phase.downloading_checksums":"正在下载校验文件...","about.updates.progress.phase.downloading_asset":"正在下载桌面安装包...","about.updates.progress.phase.verifying_checksum":"正在校验安装包...","about.updates.progress.phase.ready_to_install":"安装包已下载并校验完成,正在检查运行状态...","about.updates.progress.phase.waiting_for_active_runs":"正在等待运行结束...","about.updates.progress.phase.preparing_restart":"正在准备重启...","about.updates.progress.phase.closing":"Rudder 将关闭并重新打开以完成更新。","about.updates.progress.phase.complete":"Rudder Desktop 启动交接已完成。","about.updates.progress.phase.failed":"更新失败。","about.updates.current.toastTitle":"已经是最新版本","about.updates.current.toastBody":"当前桌面构建已经是 {{currentVersion}}。","about.updates.unavailable.toastTitle":"暂时无法检查更新","about.updates.unavailable.toastBody":"当前无法把这个构建与最新桌面版本进行对比。","about.updates.browserFallback.toastTitle":"已打开发布页","about.updates.browserFallback.toastBody":"桌面更新检查只能在打包后的应用内运行,因此已改为打开发布页面。","about.updates.failed":"检查更新失败。","about.updates.failedToastTitle":"检查更新失败","about.feedback.title":"发送反馈","about.feedback.description":"打开默认邮件应用,并创建一封发往 Rudder 维护者邮箱的草稿。","about.feedback.send":"发送反馈","about.feedback.toastTitle":"正在打开邮件应用","about.feedback.toastBody":"正在为 Rudder 维护者邮箱创建新邮件草稿。","about.feedback.failed":"打开反馈邮件草稿失败。","about.feedback.failedToastTitle":"发送反馈失败","profile.title":"个人资料与账号","profile.description":"管理你的操作员资料、Rudder Account 和已登录设备。","profile.loadLoading":"正在加载个人资料设置...","profile.loadFailed":"加载个人资料设置失败。","profile.updateFailed":"更新个人资料设置失败。","profile.toastSaved.title":"个人资料已保存","profile.toastSaved.body":"你的操作员资料已更新。","profile.toastSaveFailed.title":"保存个人资料失败","profile.about.title":"关于你","profile.about.description":"这里沿用类似 ChatGPT 的轻量个人上下文结构:一个偏好的称呼,加上一些可选的工作背景信息。","profile.nickname.label":"你的称呼","profile.nickname.placeholder":"Rudder 应该怎么称呼你?","profile.nickname.help":"如果填写了,内置聊天助手可以用它来称呼你。","profile.moreAboutYou.label":"更多关于你","profile.moreAboutYou.placeholder":"补充一些长期有效的背景信息,帮助内置聊天助手更好理解你的请求。","profile.moreAboutYou.help":"Rudder 只会把这段内容注入内置聊天助手。如果留空,则不会追加到聊天系统提示词中。","profile.import.helper.title":"从其他 AI 导入 memories","profile.import.helper.description":"把这段提示词复制到 ChatGPT、Claude 或其他 AI provider,再把导出的 memory 粘贴到下面。","profile.import.copyPrompt":"复制 memory 导入提示词","profile.import.copiedButton":"已复制","profile.import.copied.title":"提示词已复制","profile.import.copied.body":"把结果粘贴到“更多关于你”,再编辑并保存。","profile.import.copyFailed.title":"提示词未复制","profile.import.copyFailed.body":"请手动选中提示词文本并复制。","profile.save":"保存资料","profile.saving":"保存中...","productTour.checklist.title":"完成首次工作闭环","productTour.checklist.workspace":"读懂控制台","productTour.checklist.create":"创建小任务","productTour.checklist.issues":"使用 issue 结构","productTour.checklist.inspect":"检查工作输出","productTour.checklist.settings":"再次找到教程","productTour.stepCounter":"{{current}} / {{total}}","productTour.step.workspace.title":"Rudder 是 agent work 的控制台","productTour.step.workspace.body":"主导航把关键工作面放在一起:Messenger、Dashboard、Issues、Agents、Organization、Automations 和 Calendar。用它在行动、检查和 review 之间切换。","productTour.step.create.title":"从一个 agent 真能推进的小任务开始","productTour.step.create.body":"创建菜单是新 Chat、issue、agent 和 project 的入口。第一次闭环可以选择边界清楚、结果可 review 的小 Chat 或 issue。","productTour.step.issues.title":"Issue 增加明确的工作流结构","productTour.step.issues.body":"Issue 页面展示哪些工作在等待、执行、阻塞或完成。Chat 是并列的对话式路径;需要明确 owner、状态、优先级、依赖或 review 时,再使用 issue。","productTour.step.inspect.title":"先检查工作,再审批或继续推进","productTour.step.inspect.body":"Dashboard 会展示当前页面、详情、transcript、产出和审批入口。Rudder 应该让你清楚看到发生了什么,以及哪里需要你介入。","productTour.step.settings.title":"你可以从 Settings 重新播放教程","productTour.step.settings.body":"第一次导览结束后,Rudder 会保持安静。以后想重新查看时,打开系统设置,再进入通用即可再次运行。","productTour.back":"上一步","productTour.next":"下一步","productTour.finish":"完成","productTour.skip":"跳过教程","heartbeats.title":"心跳","heartbeats.description":"查看所有组织的定时心跳配置。你可以在这里看到哪些已调度、哪些只是已配置,并直接按行启停心跳。","heartbeats.loadLoading":"正在加载调度心跳...","heartbeats.loadFailed":"加载调度心跳失败。","heartbeats.updateFailed":"更新心跳失败。","heartbeats.disableAllFailed":"批量关闭所有心跳失败。","heartbeats.summary.scheduled":"已调度","heartbeats.summary.configuredInactive":"已配置未激活","heartbeats.summary.disabled":"已关闭","heartbeats.summary.organization":"个组织","heartbeats.summary.organizations":"个组织","heartbeats.disableAll":"全部关闭","heartbeats.disabling":"关闭中...","heartbeats.confirmDisableAll.one":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.confirmDisableAll.many":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.empty":"没有符合当前条件的调度心跳。","heartbeats.section.title":"已调度智能体","heartbeats.section.description":"按组织分组展示已启用心跳的智能体,方便你统一查看归属、频率与最近心跳状态。","heartbeats.table.agent":"智能体","heartbeats.table.role":"角色","heartbeats.table.scheduler":"调度状态","heartbeats.table.interval":"间隔","heartbeats.table.lastHeartbeat":"最近心跳","heartbeats.table.actions":"操作","heartbeats.scheduler.scheduled":"已调度","heartbeats.scheduler.configuredInactive":"已配置,未激活","heartbeats.scheduler.disabled":"已关闭","heartbeats.never":"从未","heartbeats.fullAgentConfig":"完整智能体配置","heartbeats.timerState":"定时心跳状态","heartbeats.on":"开","heartbeats.off":"关","chat.annotations.selectionUnavailable":"选区已不可用","chat.annotations.selectionUnavailableBody":"请重新选择回复中的文字后再试。","chat.annotations.couldNotAdd":"无法添加批注","chat.annotations.added":"已添加批注","chat.annotations.removed":"已移除批注"},yVe=["placeholder","title","aria-label"],vQt=["code","pre","script","style","textarea","[contenteditable='true']",".cm-editor",".cm-content",".mdxeditor","[data-i18n-ignore='true']"].join(", "),N5e=new WeakMap,P5e=new WeakMap;function vVe(e){return e?e.closest(vQt)!=null:!0}function wVe(e,t){const n=e.parentElement;if(!n||vVe(n))return;const r=e.textContent??"";let s=N5e.get(e);s?r!==s.rendered&&r!==s.source&&(s.source=r):(s={source:r,rendered:r},N5e.set(e,s));const a=yj(t,s.source);s.rendered=a,r!==a&&(e.textContent=a)}function kVe(e,t,n){if(!e.hasAttribute(t)||vVe(e))return;const r=e.getAttribute(t)??"";let s=P5e.get(e);s||(s=new Map,P5e.set(e,s));let a=s.get(t);a?r!==a.rendered&&r!==a.source&&(a.source=r):(a={source:r,rendered:r},s.set(t,a));const o=yj(n,a.source);a.rendered=o,r!==o&&e.setAttribute(t,o)}function vie(e,t){if(e.nodeType===Node.TEXT_NODE){wVe(e,t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;const n=e;for(const r of yVe)kVe(n,r,t);for(const r of Array.from(n.childNodes))vie(r,t)}function wQt({locale:e}){return h.useEffect(()=>{if(typeof document>"u")return;const t=document.body;if(!t)return;vie(t,e);const n=new MutationObserver(r=>{for(const s of r){if(s.type==="characterData"){wVe(s.target,e);continue}if(s.type==="attributes"){kVe(s.target,s.attributeName,e);continue}for(const a of Array.from(s.addedNodes))vie(a,e)}});return n.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:[...yVe]}),()=>n.disconnect()},[e]),null}const kQt={en:bVe,"zh-CN":yQt},OVe=h.createContext(null);function OQt(e,t){return t?e.replaceAll(/\{\{(\w+)\}\}/g,(n,r)=>{const s=t[r];return s==null?n:String(s)}):e}function eP(e,t,n){const r=kQt[e][t]??bVe[t];return OQt(r,n)}function SQt({children:e}){var a;const n=((a=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1}).data)==null?void 0:a.uiLocale)??"en";h.useEffect(()=>{typeof document>"u"||(document.documentElement.lang=n)},[n]);const r=h.useCallback((o,l)=>eP(n,o,l),[n]),s=h.useMemo(()=>({locale:n,t:r}),[n,r]);return i.jsxs(OVe.Provider,{value:s,children:[i.jsx(wQt,{locale:n}),e]})}function is(){const e=h.useContext(OVe);if(!e)throw new Error("useI18n must be used within I18nProvider");return e}const Mv="about:blank";function jQt(e){try{return new URL(e).hostname||e}catch{return e}}function CQt(e){const t=jQt(e.url);return e.code==="ERR_CONNECTION_REFUSED"?{summary:`${t} refused to connect.`,suggestions:["Checking the connection","Checking the proxy and firewall"]}:e.code==="ERR_NAME_NOT_RESOLVED"?{summary:`${t}'s server IP address could not be found.`,suggestions:["Checking the address","Checking the connection"]}:e.code==="ERR_TIMED_OUT"?{summary:`${t} took too long to respond.`,suggestions:["Checking the connection","Trying again later"]}:{summary:`The page at ${t} could not be loaded.`,suggestions:["Checking the address","Trying again later"]}}function NQt(e){var r;return!e||e.type==="keyUp"||!(((r=e.key)==null?void 0:r.toLowerCase())==="w"||e.code==="KeyW")||e.alt||e.shift?!1:navigator.platform.toLowerCase().includes("mac")?!!e.meta&&!e.control:!!e.control&&!e.meta}function AL(e){return`https://www.google.com/search?q=${encodeURIComponent(e)}`}function PQt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function IQt(e){try{return new URL(e).toString()}catch{return e.trim()}}function TQt(e){return decodeURIComponent(e.pathname).replace(/\/+$/g,"").split("/").filter(Boolean).at(-1)||"File"}function _Qt(e,t){try{const n=decodeURIComponent(t.pathname);return/^file:\/\/\//i.test(e)&&t.protocol==="file:"&&t.hostname===""&&n.startsWith("/")&&!/^\/[\\/]/.test(n)}catch{return!1}}function A5(e){const t=e.trim();if(!t||t===Mv)return"New tab";try{const n=new URL(t);return n.protocol==="file:"?TQt(n):n.hostname||n.protocol.replace(":","")||"Browser"}catch{return t}}function MQt(e){const t=e.trim();if(!t||/^about:blank$/i.test(t))return Mv;if(/^(https?|file):/i.test(t))try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"||_Qt(t,n)?n.toString():AL(t)}catch{return AL(t)}return/^(localhost|\d{1,3}(?:\.\d{1,3}){3})(:\d+)?(\/.*)?$/i.test(t)?`http://${t}`:/^[a-z][a-z0-9+.-]*:/i.test(t)||/\s/.test(t)?AL(t):t.includes(".")?`https://${t}`:AL(t)}function a6(e=Mv,t={newTab:!0}){return{kind:"browser",url:e,label:A5(e),tabId:PQt(),...t.favicon?{favicon:t.favicon}:{},...t.newTab===!1?{dedupeKey:IQt(e)}:{}}}const dY=[.25,.33,.5,.67,.75,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3,4,5],SVe="rudder.browser.side-panel-onboarding.dismissed.v1",jVe="rudder.browser.side-panel-onboarding.session-dismissed.v1",uY="rudder:browser-side-panel-onboarding-dismissed";function EQt(){if(typeof window>"u")return!0;try{if(window.localStorage.getItem(SVe)==="true")return!0}catch{}try{return window.sessionStorage.getItem(jVe)==="true"}catch{return!1}}function DQt(e){if(typeof e!="string")return null;const t=e.trim();if(!t||t.length>GM)return null;if(t.startsWith("data:image/"))return t;try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?t:null}catch{return null}}function CVe({active:e,canOpenNewTab:t,surface:n,target:r,targetKey:s,onOpenBrowserSettings:a,onOpenTarget:o,onReplaceTarget:l,onCloseTarget:c,onCycleTab:d,onWebContentsIdChange:u,onRegisterShortcutController:f}){const{t:A}=is(),m=h.useRef(null),g=h.useRef(null),x=h.useRef(!1),y=h.useRef(r.url),v=h.useRef(r.url),w=h.useRef(r),k=h.useRef(l),S=h.useRef(c),j=h.useRef(d),C=h.useRef(u),N=h.useRef(e),P=h.useRef(null),[M,E]=h.useState(null),T=h.useRef(1),[R,_]=h.useState(r.url===Mv?"":r.url),[D,U]=h.useState(r.url),[$,L]=h.useState(r.url),[H,X]=h.useState(!1),[F,Q]=h.useState({canGoBack:!1,canGoForward:!1}),[q,B]=h.useState(null),[ee,se]=h.useState(!1),[re,ne]=h.useState(()=>!EQt()),Ae=D===Mv,Y=q?CQt(q):null;v.current=D,w.current=r,k.current=l,S.current=c,j.current=d,C.current=u,N.current=e;const ce=h.useCallback((me,we)=>{const Xe=g.current;if(!x.current||!Xe||Xe.tagName.toLowerCase()!=="webview")return we;try{return me(Xe)}catch{return we}},[]),Oe=h.useCallback(me=>ce(we=>{var Xe;return((Xe=we.getURL)==null?void 0:Xe.call(we))??me},me),[ce]),Fe=h.useCallback(()=>{Q({canGoBack:ce(me=>{var we;return!!((we=me.canGoBack)!=null&&we.call(me))},!1),canGoForward:ce(me=>{var we;return!!((we=me.canGoForward)!=null&&we.call(me))},!1)})},[ce]),ke=h.useCallback(me=>{ce(Xe=>Xe.setZoomFactor?(Xe.setZoomFactor(me),!0):!1,!1)&&(T.current=me)},[ce]),Ne=h.useCallback(me=>{const we=T.current;let Xe=0,ge=Number.POSITIVE_INFINITY;dY.forEach((G,oe)=>{const Ze=Math.abs(G-we);Ze<ge&&(ge=Ze,Xe=oe)});const te=Math.max(0,Math.min(dY.length-1,Xe+me));ke(dY[te]??1)},[ke]),xe=h.useCallback(me=>{var we,Xe;if(e)switch(me){case"new_tab":t&&o(a6());return;case"focus_location":(we=m.current)==null||we.focus(),(Xe=m.current)==null||Xe.select();return;case"reload":Ae||ce(ge=>{var te;return(te=ge.reload)==null?void 0:te.call(ge)},void 0);return;case"reload_ignoring_cache":Ae||ce(ge=>{var te;return(te=ge.reloadIgnoringCache)==null?void 0:te.call(ge)},void 0);return;case"go_back":Ae||ce(ge=>{var te,G;(te=ge.canGoBack)!=null&&te.call(ge)&&((G=ge.goBack)==null||G.call(ge))},void 0);return;case"go_forward":Ae||ce(ge=>{var te,G;(te=ge.canGoForward)!=null&&te.call(ge)&&((G=ge.goForward)==null||G.call(ge))},void 0);return;case"zoom_in":Ae||Ne(1);return;case"zoom_out":Ae||Ne(-1);return;case"zoom_reset":Ae||ke(1)}},[e,ke,t,Ae,o,ce,Ne]);P.current=xe,h.useEffect(()=>(f(s,xe),()=>f(s,null)),[xe,f,s]);const ae=h.useCallback((me,we=A5(me))=>{const Xe=w.current.url!==me,ge={...w.current,url:me,label:we,favicon:Xe?void 0:w.current.favicon};v.current=me,w.current=ge,U(me),_(me===Mv?"":me),y.current=me,k.current(s,ge)},[s]);h.useEffect(()=>{const me=y.current!==r.url;y.current=r.url,v.current=r.url,w.current=r,U(r.url),_(r.url===Mv?"":r.url),me&&(L(r.url),B(null),se(!1)),x.current?Fe():Q({canGoBack:!1,canGoForward:!1})},[r.label,r.url,Fe]),h.useEffect(()=>{const me=M;if(!me||me.tagName.toLowerCase()!=="webview")return;const we=()=>{X(!0),B(null),se(!1)},Xe=it=>{const lt=!("isMainFrame"in it)||it.isMainFrame!==!1,Ue="url"in it&&typeof it.url=="string"?it.url:"";lt&&Ue&&Ue!==v.current&&ae(Ue,A5(Ue))},ge=()=>{X(!1);const it=Oe("");it&&it!==v.current&&ae(it,A5(it)),Fe()},te=it=>{const lt="url"in it&&typeof it.url=="string"?it.url:Oe("");lt&&ae(lt,A5(lt)),Fe()},G=it=>{const lt=Oe(v.current),Ue="title"in it&&typeof it.title=="string"&&it.title.trim()?it.title.trim():A5(lt),mt={...w.current,url:lt,label:Ue};w.current=mt,k.current(s,mt)},oe=it=>{const Ue=("favicons"in it&&Array.isArray(it.favicons)?it.favicons:[]).map(DQt).find(tt=>!!tt);if(!Ue||Ue===w.current.favicon)return;const mt={...w.current,favicon:Ue};w.current=mt,k.current(s,mt)},Ze=it=>{const lt="errorDescription"in it&&typeof it.errorDescription=="string"?it.errorDescription:"Could not load this page.",Ue="validatedURL"in it&&typeof it.validatedURL=="string"&&it.validatedURL?it.validatedURL:v.current;(!("isMainFrame"in it)||it.isMainFrame!==!1)&&lt!=="ERR_ABORTED"&&(X(!1),B({code:lt,url:Ue}),se(!1)),Fe()},Te=()=>{var lt,Ue;x.current=!0;const it=(lt=me.getWebContentsId)==null?void 0:lt.call(me);typeof it=="number"&&Number.isFinite(it)&&((Ue=C.current)==null||Ue.call(C,it)),T.current!==1&&ce(mt=>{var tt;return(tt=mt.setZoomFactor)==null?void 0:tt.call(mt,T.current)},void 0),Fe()},Be=it=>{var dt,at;const lt=it,Ue=lt.input;if(Ue&&Ue.type!=="keyUp"&&(Ue.key==="Tab"||Ue.code==="Tab")&&!!Ue.control&&!Ue.meta&&!Ue.alt&&N.current&&j.current){it.preventDefault(),j.current(Ue.shift?-1:1);return}if((dt=Pn())!=null&&dt.onBrowserShortcut)return;if(NQt(lt.input)){it.preventDefault(),S.current(w.current);return}if(!lt.input||!N.current)return;const tt=fze(lt.input,{isMac:navigator.platform.toLowerCase().includes("mac")});tt&&(it.preventDefault(),(at=P.current)==null||at.call(P,tt))};return me.addEventListener("dom-ready",Te),me.addEventListener("before-input-event",Be),me.addEventListener("did-start-loading",we),me.addEventListener("did-start-navigation",Xe),me.addEventListener("did-stop-loading",ge),me.addEventListener("did-navigate",te),me.addEventListener("did-navigate-in-page",te),me.addEventListener("page-title-updated",G),me.addEventListener("page-favicon-updated",oe),me.addEventListener("did-fail-load",Ze),Fe(),()=>{me.removeEventListener("dom-ready",Te),me.removeEventListener("before-input-event",Be),me.removeEventListener("did-start-loading",we),me.removeEventListener("did-start-navigation",Xe),me.removeEventListener("did-stop-loading",ge),me.removeEventListener("did-navigate",te),me.removeEventListener("did-navigate-in-page",te),me.removeEventListener("page-title-updated",G),me.removeEventListener("page-favicon-updated",oe),me.removeEventListener("did-fail-load",Ze)}},[ae,Oe,ce,s,Fe,M]);const fe=h.useCallback(me=>{g.current=me,x.current=!1,E(me),me||Q({canGoBack:!1,canGoForward:!1})},[]);h.useEffect(()=>()=>{var me;(me=C.current)==null||me.call(C,null)},[]),h.useEffect(()=>{const me=()=>ne(!1);return window.addEventListener(uY,me),()=>{window.removeEventListener(uY,me)}},[]);const ve=()=>{ne(!1);try{window.localStorage.setItem(SVe,"true")}catch{}try{window.sessionStorage.setItem(jVe,"true")}catch{}window.dispatchEvent(new Event(uY))},Se=h.useCallback(me=>{const we=MQt(me);B(null),se(!1),L(we),ae(we,A5(we))},[ae]),ze=h.useCallback(()=>{se(!1),ce(me=>{var we;(we=me.reload)==null||we.call(me)},void 0)},[ce]),ft=me=>{me.preventDefault();const Xe=new FormData(me.currentTarget).get("browser-url");Se(typeof Xe=="string"?Xe:R)},ie=()=>{var we;if(Ae)return;const me=Pn();if(me){((we=me.forceOpenExternal)==null?void 0:we.call(me,D))??me.openExternal(D);return}window.open(D,"_blank","noopener,noreferrer")};return i.jsxs("div",{className:"flex min-h-full flex-col bg-[color:var(--surface-elevated)]","data-testid":e?"chat-side-panel-browser-view":"chat-side-panel-browser-view-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",children:[i.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-[color:var(--border-soft)] bg-[color:var(--surface-elevated)] px-2 py-2","data-testid":"chat-side-panel-browser-toolbar",children:[i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Back",disabled:!F.canGoBack,onClick:()=>ce(me=>{var we;(we=me.goBack)==null||we.call(me)},void 0),children:i.jsx(Kx,{className:"h-3.5 w-3.5"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Forward",disabled:!F.canGoForward,onClick:()=>ce(me=>{var we;(we=me.goForward)==null||we.call(me)},void 0),children:i.jsx(Y4,{className:"h-3.5 w-3.5"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Reload",disabled:Ae,onClick:ze,children:i.jsx(M2,{className:K("h-3.5 w-3.5",H&&"animate-spin")})}),i.jsx("form",{className:"min-w-0 flex-1",onSubmit:ft,children:i.jsx(Kn,{ref:m,"aria-label":"Browser URL",name:"browser-url",value:R,onChange:me=>_(me.currentTarget.value),placeholder:"Enter a URL",className:"h-8 rounded-[var(--radius-md)] bg-[color:var(--surface-inset)] font-mono text-xs"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open new browser tab",title:t?"Open new browser tab":"Browser tab limit reached",disabled:!t,onClick:()=>o(a6()),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open browser page externally",disabled:Ae,onClick:ie,children:i.jsx(Ja,{className:"h-3.5 w-3.5"})})]}),i.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col bg-[color:var(--surface-inset)]","data-testid":"chat-side-panel-browser-content",children:[e&&n==="side_panel"&&re?i.jsx(xVe,{testId:"browser-side-panel-onboarding",className:"absolute right-3 top-3 z-20 w-[min(24rem,calc(100%-1.5rem))] shadow-[var(--shadow-lg)]",icon:i.jsx(Xfe,{"aria-hidden":"true"}),title:A("browser.onboarding.title"),description:A("browser.onboarding.description"),stackActions:!0,actions:i.jsxs(i.Fragment,{children:[a?i.jsx(le,{type:"button",variant:"outline",size:"sm",onClick:()=>{ve(),a()},children:A("browser.onboarding.settings")}):null,i.jsx(le,{type:"button",size:"sm",onClick:ve,children:A("browser.onboarding.dismiss")})]})}):null,Ae?i.jsx("div",{className:"flex min-h-[44vh] flex-1 items-center justify-center px-6 text-center","data-testid":"chat-side-panel-browser-start",children:i.jsxs("div",{className:"max-w-[18rem]",children:[i.jsx(up,{className:"mx-auto h-12 w-12 text-muted-foreground"}),i.jsx("h3",{className:"mt-4 text-base font-semibold text-foreground",children:"Start browsing"}),i.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Enter a URL to open a page."})]})}):i.jsxs("div",{className:"relative flex min-h-[52vh] flex-1",children:[h.createElement("webview",{ref:fe,src:$,className:K("min-h-[52vh] flex-1 bg-[color:var(--surface-elevated)]",q&&"invisible"),"data-testid":e?"chat-side-panel-browser-webview":"chat-side-panel-browser-webview-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",allowpopups:"true"}),q?i.jsx("div",{role:"alert","data-testid":"chat-side-panel-browser-error",className:"absolute inset-0 flex overflow-y-auto bg-[color:var(--surface-elevated)] px-8 py-10",children:i.jsxs("div",{className:"m-auto w-full max-w-[32rem]",children:[i.jsx(Xjt,{className:"h-12 w-12 text-muted-foreground","aria-hidden":"true"}),i.jsx("h3",{className:"mt-6 text-xl font-semibold text-foreground",children:"This site can't be reached"}),i.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:Y==null?void 0:Y.summary}),i.jsxs("div",{className:"mt-5 text-sm text-muted-foreground",children:[i.jsx("p",{children:"Try:"}),i.jsx("ul",{className:"mt-2 list-disc space-y-1 pl-6",children:Y==null?void 0:Y.suggestions.map(me=>i.jsx("li",{children:me},me))})]}),i.jsx("p",{className:"mt-5 font-mono text-xs text-muted-foreground",children:q.code}),ee?i.jsx("p",{className:"mt-4 break-all rounded-[var(--radius-md)] border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] px-3 py-2 font-mono text-xs text-muted-foreground",children:q.url}):null,i.jsxs("div",{className:"mt-7 flex items-center justify-between gap-3",children:[i.jsx(le,{type:"button",variant:"outline",size:"sm","aria-expanded":ee,onClick:()=>se(me=>!me),children:"Details"}),i.jsxs(le,{type:"button",size:"sm",onClick:ze,children:[i.jsx(M2,{className:"h-3.5 w-3.5"}),"Reload"]})]})]})}):null]})]})]})}function Df(e,t){return(e==null?void 0:e.trim())||t}function AQ(e,t){return e.split("/").filter(Boolean).at(-1)??t}function NVe(e){try{return new URL(e,"http://rudder.local")}catch{return null}}function PVe(e){return(e.searchParams.get("messageId")??e.searchParams.get("targetMessageId")??"").trim()||null}function RQt(e){const t=decodeURIComponent(e.hash.replace(/^#/,"")).trim();return t.startsWith("comment-")&&t.slice(8).trim()||null}function wie(e){return e.kind==="issue"?`issue:${e.issueId}:${e.commentId??""}`:e.kind==="issue_proposal"?`issue-proposal:${e.conversationId}:${e.messageId}`:e.kind==="automation"?`automation:${e.automationId}`:e.kind==="chat"?`chat:${e.conversationId}:${e.messageId??""}`:e.kind==="subagents"?`subagents:${e.conversationId}`:e.kind==="subagent"?`subagent:${e.threadId}`:e.kind==="side_chat"?e.conversationId?`side-chat:${e.conversationId}`:`side-chat:draft:${e.clientMutationId}`:e.kind==="run_feedback_chat"?`run-feedback-chat:${e.organizationId}:${e.agentId}`:e.kind==="library_document"?`library-document:${e.documentId}`:e.kind==="library_entry"?`library-entry:${e.entryId}:${e.path??""}`:e.kind==="library_file"?`library-file:${e.filePath}`:e.kind==="local_file"?`local-file:${e.filePath}`:e.kind==="organization_skill_file"?`organization-skill-file:${e.skillId}:${e.filePath}`:e.kind==="local_apps"?"local-apps":e.kind==="local_app"?`local-app:${encodeURIComponent(e.desktopInstallationId)}:${encodeURIComponent(e.appPublicId)}:${encodeURIComponent(e.localBindingId)}`:e.kind==="library_directory"?`library-directory:${e.directoryPath}`:e.kind==="browser"?`browser-tab:${e.tabId}`:`placeholder:${e.targetKind}`}function Kf(e){return e.kind==="automation"||e.kind==="library_document"||e.kind==="library_entry"||e.kind==="library_file"||e.kind==="library_directory"||e.kind==="browser"||e.kind==="local_app"}function ps(e){const t=wie(e);return e.kind==="browser"||!Kf(e)||!e.viewInstanceId?t:`${t}:view:${e.viewInstanceId}`}function LQt(e,t){var l,c,d;const n=NVe(e);if(!n||n.origin!=="http://rudder.local")return null;const r=n.pathname.split("/").filter(Boolean).map(u=>{try{return decodeURIComponent(u)}catch{return u}}),s=r.length>=2&&r.at(-2)==="issues"?(l=r.at(-1))==null?void 0:l.trim():"";if(s)return{kind:"issue",issueId:s,ref:(t==null?void 0:t.trim())||null,commentId:RQt(n),label:Df(t,"Issue")};const a=r.length>=2&&r.at(-2)==="automations"?(c=r.at(-1))==null?void 0:c.trim():"";if(a)return{kind:"automation",automationId:a,label:Df(t,n.searchParams.get("t")??n.searchParams.get("title")??"Automation")};const o=r.length>=2&&r.at(-2)==="chat"?(d=r.at(-1))==null?void 0:d.trim():"";if(o)return{kind:"chat",conversationId:o,messageId:PVe(n),label:Df(t,"Chat")};if(r.at(-1)==="library"){const u=(n.searchParams.get("skill")??"").trim();if(u)return{kind:"organization_skill_file",skillId:u,filePath:(n.searchParams.get("skillFile")??"SKILL.md").trim()||"SKILL.md",label:Df(t,"Skill")};const f=(n.searchParams.get("document")??n.searchParams.get("doc")??"").trim();if(f)return{kind:"library_document",documentId:f,label:Df(t,n.searchParams.get("t")??n.searchParams.get("title")??"Library document")};const A=(n.searchParams.get("path")??"").trim();if(A)return{kind:"library_file",filePath:A,label:Df(t,AQ(A,"Library file"))};const m=(n.searchParams.get("directory")??"").trim();if(m)return{kind:"library_directory",directoryPath:m,label:Df(t,AQ(m,"Library directory"))};const g=(n.searchParams.get("entry")??"").trim();if(g)return{kind:"library_entry",entryId:g,path:A||null,label:Df(t,g)}}return null}function zQt(e,t){const n=ac(e);if(!n)return LQt(e,t);if(n.kind==="issue")return{kind:"issue",issueId:n.issueId,ref:n.ref??(t==null?void 0:t.trim())??null,commentId:n.commentId,label:Df(t,n.ref??"Issue")};if(n.kind==="automation")return{kind:"automation",automationId:n.automationId,label:Df(t,n.title??"Automation")};if(n.kind==="chat"){const r=NVe(e);return{kind:"chat",conversationId:n.conversationId,messageId:r?PVe(r):null,label:Df(t,n.title??"Chat")}}return n.kind==="library_doc"?{kind:"library_document",documentId:n.documentId,label:Df(t,n.title??"Library document")}:n.kind==="library_entry"?{kind:"library_entry",entryId:n.entryId,path:n.path,label:Df(t,n.title??n.path??"Library entry")}:n.kind==="library_file"?{kind:"library_file",filePath:n.filePath,label:Df(t,n.title??AQ(n.filePath,"Library file"))}:n.kind==="library_directory"?{kind:"library_directory",directoryPath:n.directoryPath,label:Df(t,n.title??AQ(n.directoryPath,"Library directory"))}:null}const $Qt=h.lazy(async()=>({default:(await Wt(async()=>{const{AutomationDetail:e}=await Promise.resolve().then(()=>$Rn);return{AutomationDetail:e}},void 0)).AutomationDetail})),FQt=h.lazy(async()=>({default:(await Wt(async()=>{const{LibraryLiveSurface:e}=await import("./LibraryLiveSurface-CZED7oKj.js");return{LibraryLiveSurface:e}},[])).LibraryLiveSurface})),YAe=h.createContext(null);function hQ(e){var n;const t=((n=e.viewInstanceId)==null?void 0:n.trim())||(e.kind==="browser"?e.tabId.trim():"");if(!t)throw new Error(`${e.kind} live surface requires a viewInstanceId`);return t}function gT(e,t){return JSON.stringify([e.trim(),t.kind,hQ(t)])}function IVe(e){try{const t=JSON.parse(e);return Array.isArray(t)&&typeof t[0]=="string"?t[0]:""}catch{return""}}function fY(e,t){return e.kind===t.kind&&hQ(e)===hQ(t)}function kie(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,l)=>kie(o,t[l]));const n=e,r=t,s=Object.keys(n).filter(o=>n[o]!==void 0),a=Object.keys(r).filter(o=>r[o]!==void 0);return s.length===a.length&&s.every(o=>Object.hasOwn(r,o)&&kie(n[o],r[o]))}function TVe(e){return e.startsWith("main:")?"workbench":"side_panel"}function Oie(e){if(!_Ve(e))return!1;const t=e.element.getBoundingClientRect();return t.width>0&&t.height>0}function _Ve(e){return!!(e!=null&&e.active&&e.element.isConnected)}function BQt({children:e}){const t=h.useRef(new Map),n=h.useRef(new Map),[r,s]=h.useState(0),a=h.useCallback(()=>{s(T=>T+1)},[]),o=h.useCallback(T=>{const R=t.current.get(T.runtimeId);if(R&&!fY(R.target,T.target))return()=>{};const _=R??{interactionLocked:!1,leaseOwnerId:null,owners:new Map,renderSurface:T.renderSurface??null,runtimeId:T.runtimeId,shortcutController:null,target:T.target,webContentsId:null};return _.owners.set(T.ownerId,T),T.renderSurface&&(_.renderSurface=T.renderSurface),t.current.set(T.runtimeId,_),a(),()=>{const D=t.current.get(T.runtimeId);D&&(D.owners.delete(T.ownerId),D.leaseOwnerId===T.ownerId&&(D.leaseOwnerId=null),a())}},[a]),l=h.useCallback(T=>{const R=t.current.get(T.runtimeId);if(!R||!fY(R.target,T.target))return;const _=R.owners.get(T.ownerId);if(!_)return;const D=!kie(_.target,T.target);(_.active!==T.active||_.callbacks!==T.callbacks||_.element!==T.element||_.hostId!==T.hostId||_.renderSurface!==T.renderSurface||D)&&(R.owners.set(T.ownerId,T),D&&R.leaseOwnerId===T.ownerId&&!R.interactionLocked&&(R.target=T.target),T.renderSurface&&(R.renderSurface=T.renderSurface),a())},[a]),c=h.useCallback((T,R)=>{const _=t.current.get(T),D=_==null?void 0:_.owners.get(R);return!_||!Oie(D)?!1:(_.leaseOwnerId===R||(_.leaseOwnerId=R,a()),!0)},[a]),d=h.useCallback((T,R)=>{const _=t.current.get(T),D=_==null?void 0:_.owners.get(R);return!_||!_Ve(D)||_.leaseOwnerId&&_.leaseOwnerId!==R?!1:(_.leaseOwnerId===R||(_.leaseOwnerId=R,a()),!0)},[a]),u=h.useCallback(async(T,R,_=5e3)=>{var U;const D=Date.now();for(;Date.now()-D<=_;){const $=(U=t.current.get(T))==null?void 0:U.owners.get(R);if(Oie($))return!0;await new Promise(L=>{window.setTimeout(L,16)})}return!1},[]),f=h.useCallback((T,R)=>{const _=t.current.get(T);!_||_.interactionLocked===R||(_.interactionLocked=R,a())},[a]),A=h.useCallback((T,R)=>{const _=t.current.get(T);return!_||!fY(_.target,R)?!1:(_.target=R,a(),!0)},[a]),m=h.useCallback(T=>{const R=t.current.get(T);R&&(R.webContentsId!==null&&n.current.delete(R.webContentsId),t.current.delete(T),a())},[a]),g=h.useCallback((T,R)=>{const _=t.current.get(T);!_||_.webContentsId===R||(_.webContentsId!==null&&n.current.delete(_.webContentsId),_.webContentsId=R,R!==null&&n.current.set(R,T))},[]),x=h.useCallback(T=>{const R=n.current.get(T),_=R?t.current.get(R):null,D=_!=null&&_.leaseOwnerId?_.owners.get(_.leaseOwnerId):null;return!_||!D?null:{hostId:D.hostId,ownerId:D.ownerId,runtimeId:_.runtimeId,surface:TVe(D.ownerId),targetKind:_.target.kind}},[]),y=h.useCallback((T,R)=>{const _=n.current.get(T),D=_?t.current.get(_):null,U=D!=null&&D.leaseOwnerId?D.owners.get(D.leaseOwnerId):null;return U!=null&&U.callbacks.onOpenTarget?(U.callbacks.onOpenTarget(R),!0):!1},[]),v=h.useCallback(T=>{const R=t.current.get(T),_=R!=null&&R.leaseOwnerId?R.owners.get(R.leaseOwnerId):null;return!R||!(_!=null&&_.callbacks.onCloseTarget)?!1:(_.callbacks.onCloseTarget(R.target),!0)},[]),w=h.useCallback(T=>{const R=n.current.get(T);return R?v(R):!1},[v]),k=h.useCallback((T,R)=>{const _=t.current.get(T);!_||_.target.kind!=="browser"||(_.shortcutController=R)},[]),S=h.useCallback((T,R)=>{const _=t.current.get(T);return!_||_.target.kind!=="browser"||!_.leaseOwnerId||!_.shortcutController?!1:(_.shortcutController(R),!0)},[]),j=h.useCallback((T,R)=>{const _=n.current.get(T);return _?S(_,R):!1},[S]),C=h.useCallback(T=>Array.from(t.current.values()).filter(R=>R.target.kind==="browser"&&IVe(R.runtimeId)===T).length,[]),N=h.useCallback(T=>{var R;return((R=t.current.get(T))==null?void 0:R.target)??null},[]),P=h.useCallback(T=>t.current.has(T),[]),M=h.useCallback(()=>Array.from(t.current.values()),[]),E=h.useMemo(()=>({autoClaimSurface:d,claimSurface:c,closeTargetForGuest:w,closeTargetForRuntime:v,dispatchBrowserShortcutForGuest:j,dispatchBrowserShortcutForRuntime:S,disposeSurface:m,getGuestOwner:x,getLiveBrowserCount:C,getRuntimeTarget:N,hasSurface:P,listRecords:M,openTargetForGuest:y,registerBrowserShortcutController:k,registerOwner:o,registerWebContentsId:g,revision:r,setInteractionLocked:f,updateOwner:l,updateTarget:A,waitForOwner:u}),[d,c,w,v,j,S,m,x,C,N,P,M,y,k,o,g,r,f,l,A,u]);return i.jsx(YAe.Provider,{value:E,children:e})}function jE(){const e=h.useContext(YAe);if(!e)throw new Error("useLiveSurfaceRuntime must be used inside LiveSurfaceRuntimeProvider");return e}function JAe(){return h.useContext(YAe)}function MVe({active:e,autoClaim:t=!0,callbacks:n={},hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l,...c}){const{autoClaimSurface:d,registerOwner:u,updateOwner:f}=jE(),A=h.useRef(null),m=h.useRef(n);m.current=n;const g=h.useMemo(()=>({get annotationConversationId(){return m.current.annotationConversationId},get canOpenNewTab(){return m.current.canOpenNewTab},get savedViewId(){return m.current.savedViewId},onCloseTarget:x=>{var y,v;return(v=(y=m.current).onCloseTarget)==null?void 0:v.call(y,x)},onCycleTab:x=>{var y,v;return(v=(y=m.current).onCycleTab)==null?void 0:v.call(y,x)},onLocalAppTitleChange:x=>{var y,v;return(v=(y=m.current).onLocalAppTitleChange)==null?void 0:v.call(y,x)},onOpenBrowserSettings:()=>{var x,y;return(y=(x=m.current).onOpenBrowserSettings)==null?void 0:y.call(x)},onOpenTarget:x=>{var y,v;return(v=(y=m.current).onOpenTarget)==null?void 0:v.call(y,x)},onRegisterShortcutController:(x,y)=>{var v,w;return(w=(v=m.current).onRegisterShortcutController)==null?void 0:w.call(v,x,y)},onReplaceTarget:x=>{var y,v;return(v=(y=m.current).onReplaceTarget)==null?void 0:v.call(y,x)}}),[]);return h.useLayoutEffect(()=>{const x=A.current;if(x)return u({active:e,callbacks:g,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l})},[r,s,u,o]),h.useLayoutEffect(()=>{const x=A.current;if(!x)return;f({active:e,callbacks:g,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l}),e&&t&&d(o,s)},[e,t,d,r,s,a,o,g,l,f]),i.jsx("div",{...c,ref:A,"data-owner-id":s})}function QQt({record:e,owner:t,visible:n}){var f;const r=jE(),s=e.target,a=t==null?void 0:t.callbacks,o=t?TVe(t.ownerId):"side_panel",l=A=>{var m;(m=a==null?void 0:a.onCloseTarget)==null||m.call(a,A)},c=A=>{var m;(m=a==null?void 0:a.onOpenTarget)==null||m.call(a,A)},d=A=>{var m;(A.kind==="automation"||A.kind==="browser"||A.kind==="library_directory"||A.kind==="library_document"||A.kind==="library_entry"||A.kind==="library_file"||A.kind==="local_app")&&r.updateTarget(e.runtimeId,A),e.interactionLocked||(m=a==null?void 0:a.onReplaceTarget)==null||m.call(a,A)},u=(f=e.renderSurface)==null?void 0:f.call(e,{active:n,closeTarget:l,openTarget:c,replaceTarget:d,surface:o,target:s});return s.kind==="browser"?i.jsx(CVe,{active:n,canOpenNewTab:(a==null?void 0:a.canOpenNewTab)??!1,surface:o,target:s,targetKey:ps(s),onCloseTarget:l,onCycleTab:a==null?void 0:a.onCycleTab,onOpenBrowserSettings:a==null?void 0:a.onOpenBrowserSettings,onOpenTarget:c,onRegisterShortcutController:(A,m)=>{var g;r.registerBrowserShortcutController(e.runtimeId,m),(g=a==null?void 0:a.onRegisterShortcutController)==null||g.call(a,A,m)},onReplaceTarget:(A,m)=>d(m),onWebContentsIdChange:A=>{r.registerWebContentsId(e.runtimeId,A)}}):s.kind==="local_app"?i.jsx(gVe,{active:n,savedViewId:a==null?void 0:a.savedViewId,target:s,onTitleChange:a==null?void 0:a.onLocalAppTitleChange}):u!==void 0?i.jsx(i.Fragment,{children:u}):s.kind==="automation"?i.jsx(h.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx($Qt,{automationId:s.automationId,onClose:()=>l(s),surface:o})}):i.jsx(h.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx(FQt,{active:n,annotationConversationId:a==null?void 0:a.annotationConversationId,organizationId:IVe(e.runtimeId),onOpenTarget:c,surface:o,target:s})})}function UQt(){const e=jE(),t=e.listRecords(),[,n]=h.useState(0);return h.useEffect(()=>{const r=()=>n(a=>a+1);window.addEventListener("resize",r),window.addEventListener("scroll",r,!0);const s=typeof ResizeObserver>"u"?null:new ResizeObserver(r);for(const a of e.listRecords())for(const o of a.owners.values())s==null||s.observe(o.element);return()=>{window.removeEventListener("resize",r),window.removeEventListener("scroll",r,!0),s==null||s.disconnect()}},[e]),i.jsx("div",{className:"pointer-events-none fixed inset-0","data-testid":"live-surface-runtime-layer","aria-label":"Live workspace surfaces",children:t.map(r=>{const s=r.leaseOwnerId?r.owners.get(r.leaseOwnerId)??null:null,a=Oie(s),o=a?s.element.getBoundingClientRect():null,l=!a||r.interactionLocked;return i.jsx("div",{"data-testid":"live-surface-runtime-host","data-host-id":s==null?void 0:s.hostId,"data-owner-id":s==null?void 0:s.ownerId,"data-runtime-id":r.runtimeId,"data-target-kind":r.target.kind,"data-view-instance-id":hQ(r.target),"aria-hidden":!a,hidden:!a,inert:l?!0:void 0,className:`fixed flex min-h-0 flex-col overflow-hidden bg-[color:var(--surface-panel)] ${s!=null&&s.ownerId.startsWith("side:")?"rounded-[var(--desktop-workspace-radius)]":s!=null&&s.ownerId.startsWith("main:")?r.target.kind==="browser"?"rounded-[var(--desktop-workspace-radius)]":"rounded-b-[var(--desktop-workspace-radius)]":""}`,style:{height:o?`${o.height}px`:"0px",left:o?`${o.left}px`:"0px",pointerEvents:l?"none":"auto",top:o?`${o.top}px`:"0px",width:o?`${o.width}px`:"0px",zIndex:s!=null&&s.ownerId.startsWith("side:")?70:40},children:i.jsx(QQt,{record:r,owner:s,visible:a&&!r.interactionLocked})},r.runtimeId)})})}const W7=[{actionId:"commandPalette.open",label:"Open command palette",description:"Search and jump across Rudder.",scope:"Global",defaultBindings:[{key:"k",code:"KeyK",metaKey:!0},{key:"k",code:"KeyK",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"k",code:"KeyK",metaKey:!0}],nonMac:[{key:"k",code:"KeyK",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"settings.open",label:"Open settings",description:"Open System Settings.",scope:"Global",defaultBindings:[{key:",",metaKey:!0},{key:",",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:",",metaKey:!0}],nonMac:[{key:",",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"chat.create",label:"New chat",description:"Open the new chat composer.",scope:"Global",defaultBindings:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0},{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}],defaultBindingsByPlatform:{mac:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0}],nonMac:[{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}]},configurable:!0,disableable:!0},{actionId:"issue.create",label:"Create issue",description:"Open the new issue dialog.",scope:"Global",defaultBindings:[{key:"n",code:"KeyN",metaKey:!0},{key:"n",code:"KeyN",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"n",code:"KeyN",metaKey:!0}],nonMac:[{key:"n",code:"KeyN",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"sidebar.toggle",label:"Toggle sidebar",description:"Show or hide the workspace sidebar.",scope:"Global",defaultBindings:[{key:"["}],configurable:!0,disableable:!0},{actionId:"panel.toggle",label:"Toggle panel",description:"Show or hide the context panel.",scope:"Global",defaultBindings:[{key:"]"}],configurable:!0,disableable:!0},{actionId:"system.escapeBack",label:"Navigate back / close detail",description:"System Escape behavior is read-only in this version.",scope:"System",defaultBindings:[{key:"Escape"}],configurable:!1,disableable:!1}],VQt=new Set(W7.filter(e=>e.configurable).map(e=>e.actionId)),qQt=new Set(["Alt","Control","Meta","Shift"]),I5e=new Set(["meta+n","meta+shift+o"]);function CE(){var n,r,s;if(typeof navigator>"u")return"nonMac";const e=navigator,t=((r=(n=e.userAgentData)==null?void 0:n.platform)==null?void 0:r.trim())||((s=e.platform)==null?void 0:s.trim())||"";return/mac|iphone|ipad|ipod/i.test(t)?"mac":"nonMac"}function EVe(e,t=CE()){var n;return(((n=e.defaultBindingsByPlatform)==null?void 0:n[t])??e.defaultBindings).map(H6)}function DVe(e){return e.length===1?e.toLowerCase():e}function H6(e){return{key:DVe(e.key.trim()),...e.code?{code:e.code.trim()}:{},...e.metaKey?{metaKey:!0}:{},...e.ctrlKey?{ctrlKey:!0}:{},...e.altKey?{altKey:!0}:{},...e.shiftKey?{shiftKey:!0}:{}}}function Sie(e){const t=H6(e);return[t.metaKey?"meta":"",t.ctrlKey?"ctrl":"",t.altKey?"alt":"",t.shiftKey?"shift":"",t.key].filter(Boolean).join("+")}function RVe(e){if(!(e instanceof HTMLElement)||KQt(e))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable||!!e.closest('[contenteditable="true"], [contenteditable="plaintext-only"]')}function KQt(e){let t=e;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!0;const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!0;t=t.parentElement}return!1}function WQt(e){return qQt.has(e.key)?null:H6({key:e.key,code:e.code||void 0,metaKey:e.metaKey,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey})}function ZQt(e,t){const n=H6(t);return(n.code&&e.code?e.code===n.code:DVe(e.key)===n.key)&&e.metaKey===!!n.metaKey&&e.ctrlKey===!!n.ctrlKey&&e.altKey===!!n.altKey&&e.shiftKey===!!n.shiftKey}function ehe(e,t=CE()){const n={};for(const r of W7)VQt.has(r.actionId)&&(n[r.actionId]=EVe(r,t));for(const r of(e==null?void 0:e.shortcuts)??[]){const s=W7.find(a=>a.actionId===r.actionId);if(s!=null&&s.configurable){if(r.disabled===!0){n[r.actionId]=[];continue}if(r.bindings&&r.bindings.length>0){const a=r.bindings.map(H6);if(HQt(r.actionId,a))continue;n[r.actionId]=a}}}return n}function HQt(e,t){return e!=="chat.create"||t.length!==I5e.size?!1:t.every(n=>I5e.has(Sie(n)))}function qk(e,t,n,r){return n===void 0?!1:(ehe(n,r)[t]??[]).some(a=>ZQt(e,a))}function T5e(e,t=CE()){const n=H6(e),r=[];return n.ctrlKey&&r.push(t==="mac"?"⌃":"Ctrl"),n.altKey&&r.push(t==="mac"?"⌥":"Alt"),n.shiftKey&&r.push(t==="mac"?"⇧":"Shift"),n.metaKey&&r.push(t==="mac"?"⌘":"Meta"),r.push(XQt(n.key)),t==="mac"?r.join(""):r.join("+")}function XQt(e){return e===" "?"Space":e==="Escape"?"Esc":e.length===1?e.toUpperCase():e}function GQt(e){const t=H6(e),n=t.key.toLowerCase();return t.metaKey||t.ctrlKey?["l","r","w","q"].includes(n):!1}function YQt(e,t,n,r){const s=Sie(t),a=ehe(n,r);for(const[o,l]of Object.entries(a))if(o!==e&&l.some(c=>Sie(c)===s))return o;return null}function hL(e,t,n){const r=e.shortcuts.filter(s=>s.actionId!==t);return n&&r.push({actionId:t,...n}),{shortcuts:r}}const the=h.createContext(null),tP="global",QP=8;function Gw(e){return(e==null?void 0:e.trim())||tP}function S1(){return{activeKey:null,hasPanelState:!1,open:!1,tabs:[]}}function AY(e){return!!(e&&(e.hasPanelState||e.tabs.length>0||e.activeKey!==null))}function _5e(e){return e instanceof Element&&!!e.closest("[data-testid='messenger-main-workbench'],[data-testid='live-surface-runtime-host'][data-owner-id^='main:']")}function JQt(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`view-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function hY(e,t,n){if(!Kf(t))return t;if(t.kind==="browser")return{...t,viewInstanceId:t.viewInstanceId??t.tabId};if(!n&&t.viewInstanceId)return t;if(!n){const r=wie(t),s=e.find(a=>Kf(a)&&wie(a)===r);if(s&&s.kind!=="browser"&&"viewInstanceId"in s&&s.viewInstanceId)return{...t,viewInstanceId:s.viewInstanceId}}return{...t,viewInstanceId:JQt()}}function M5e(e,t){return{...e,tabId:t.tabId,viewInstanceId:t.viewInstanceId??t.tabId,savedViewRecovery:t.savedViewRecovery??e.savedViewRecovery}}function mY(e,t,n,r=!0){const s=ps(n),a=n.kind==="browser"&&n.dedupeKey?e.find(d=>d.kind==="browser"&&d.dedupeKey===n.dedupeKey):void 0;if(n.kind==="browser"&&(a==null?void 0:a.kind)==="browser"){const d=ps(a),u=M5e(n,a);return{activeKey:d,tabs:e.map(f=>ps(f)===d?u:f),openResult:{admitted:!0}}}const o=e.find(d=>ps(d)===s);if(o){const d=n.kind==="browser"&&o.kind==="browser"?M5e(n,o):n;return{activeKey:s,tabs:e.map(u=>ps(u)===s?d:u),openResult:{admitted:!0}}}const l=[...e,n];if(n.kind!=="browser")return{activeKey:s,tabs:l,openResult:{admitted:!0}};const c=e.filter(d=>d.kind==="browser").length;return r&&c<QP?{activeKey:s,tabs:l,openResult:{admitted:!0}}:{activeKey:t,tabs:e,openResult:{admitted:!1,reason:"browser_capacity"}}}function jie(e){var t;return((t=e.viewInstanceId)==null?void 0:t.trim())||e.tabId.trim()}function pY(e){const t=new Set;for(const n of Object.values(e))for(const r of n.tabs)r.kind==="browser"&&t.add(jie(r));return t}function eUt(e,t,n){const r=e.activeKey?e.tabs.findIndex(l=>ps(l)===e.activeKey):-1,s=e.tabs.filter(l=>l.kind!=="browser"||(n==null?void 0:n(t,l))==="preserve");if(s.length===e.tabs.length)return e;const a=e.activeKey!==null&&s.some(l=>ps(l)===e.activeKey),o=s[Math.min(Math.max(r,0),s.length-1)]??s.at(-1)??null;return{...e,activeKey:e.activeKey===null?null:a?e.activeKey:o?ps(o):null,tabs:s}}function tUt({children:e}){const t=h.useRef({[tP]:S1()}),n=h.useRef({[tP]:{}}),r=h.useRef(tP),[s,a]=h.useState(tP),[o,l]=h.useState(()=>S1()),[c,d]=h.useState(null),[u,f]=h.useState(!1),A=h.useRef(null),m=h.useRef(null),g=h.useCallback((B,ee)=>{const se=t.current[B]??S1(),re=ee(se);if(re!==se){const ne=new Map(se.tabs.map(ce=>[ps(ce),ce])),Ae=n.current[B]??{},Y={...Ae};for(const ce of re.tabs){const Oe=ps(ce),Fe=ne.get(Oe),ke=Ae[Oe]??0;Y[Oe]=Fe?Fe!==ce?ke+1:ke:Object.hasOwn(Ae,Oe)?ke+1:0}n.current={...n.current,[B]:Y}}return t.current={...t.current,[B]:re},B===r.current&&l(re),re},[]),x=h.useCallback(B=>{const ee=Gw(B);if(r.current===ee)return;const se=t.current[ee]??S1();r.current=ee,l(se),f(AY(se)&&se.open),a(re=>re===ee?re:ee)},[]),y=h.useCallback((B,ee)=>{let se={admitted:!0};return g(s,re=>{const ne=pY(t.current),Ae=B.kind!=="browser"||ne.has(jie(B))||(ee==null?void 0:ee.allowNewBrowserGuest)!==!1&&ne.size<QP,Y=mY(re.tabs,re.activeKey,hY(re.tabs,B,!1),Ae);return se=Y.openResult,{activeKey:Y.activeKey,hasPanelState:!0,open:!0,tabs:Y.tabs}}),f(!0),se},[s,g]),v=h.useCallback((B,ee)=>{let se={admitted:!0};return g(s,re=>{const ne=pY(t.current),Ae=B.kind!=="browser"||(ee==null?void 0:ee.allowNewBrowserGuest)!==!1&&ne.size<QP,Y=mY(re.tabs,re.activeKey,hY(re.tabs,B,!0),Ae);return se=Y.openResult,{activeKey:Y.activeKey,hasPanelState:!0,open:!0,tabs:Y.tabs}}),f(!0),se},[s,g]),w=h.useCallback((B,ee,se)=>{const re=Gw(B);let ne={admitted:!0};const Ae=g(re,Y=>{const ce=pY(t.current),Oe=ee.kind!=="browser"||ce.has(jie(ee))||(se==null?void 0:se.allowNewBrowserGuest)!==!1&&ce.size<QP,Fe=mY(Y.tabs,Y.activeKey,hY(Y.tabs,ee,!1),Oe);return ne=Fe.openResult,{activeKey:Fe.activeKey,hasPanelState:!0,open:!0,tabs:Fe.tabs}});return re===r.current&&(l(Ae),f(!0)),ne},[g]),k=h.useCallback(()=>{g(s,B=>({...B,hasPanelState:!0,open:!0})),f(!0)},[s,g]),S=h.useCallback(B=>{const ee=Gw(B),re={...t.current[ee]??S1(),hasPanelState:!0,open:!0};t.current={...t.current,[ee]:re},r.current=ee,a(ee),l(re),f(!0)},[]),j=h.useCallback(()=>{f(!0),g(s,B=>({...B,activeKey:null,hasPanelState:!0,open:!0}))},[s,g]),C=h.useCallback(()=>{d(null),g(s,B=>AY(B)?{...B,open:!1}:B),f(!1)},[s,g]),N=h.useCallback(()=>{d(null),g(s,()=>S1()),f(!1)},[s,g]),P=C,M=h.useCallback(()=>{d(null)},[]),E=h.useCallback((B,ee=r.current)=>{const se=B.trim(),re=Gw(ee);return!se||!re.startsWith("chat:")&&!re.startsWith("issue:")?!1:(d({organizationId:se,contextKey:re}),!0)},[]),T=h.useCallback((B,ee)=>{var ne,Ae;const se=Gw(B);return(((ne=t.current[se])==null?void 0:ne.tabs)??[]).some(Y=>ps(Y)===ee)?((Ae=n.current[se])==null?void 0:Ae[ee])??0:null},[]),R=h.useCallback((B,ee,se)=>{var Fe;const re=Gw(B),ne=t.current[re]??S1(),Ae=ne.tabs.findIndex(ke=>ps(ke)===ee);if(Ae<0)return{detached:!1,reason:"not_found",revision:null};const Y=((Fe=n.current[re])==null?void 0:Fe[ee])??0;if(se!==Y)return{detached:!1,reason:"revision_mismatch",revision:Y};const ce=ne.tabs[Ae],Oe=g(re,ke=>{const Ne=ke.tabs.filter(ae=>ps(ae)!==ee);if(Ne.length===0)return{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(ke.activeKey!==ee)return{...ke,tabs:Ne};const xe=Ne[Math.min(Ae,Ne.length-1)]??null;return{activeKey:xe?ps(xe):null,hasPanelState:!0,open:!0,tabs:Ne}});return re===r.current&&f(Oe.open),{detached:!0,revision:Y,target:ce}},[g]),_=h.useCallback(B=>{g(s,ee=>{const se=ee.tabs.findIndex(Ae=>ps(Ae)===B),re=ee.tabs.filter(Ae=>ps(Ae)!==B);if(re.length===0)return f(!1),{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(ee.activeKey!==B)return{...ee,tabs:re};const ne=re[Math.min(Math.max(se,0),re.length-1)]??re.at(-1)??null;return{activeKey:ne?ps(ne):null,hasPanelState:!0,open:!0,tabs:re}})},[s,g]),D=h.useCallback(B=>(A.current=B,()=>{A.current===B&&(A.current=null)}),[]),U=h.useCallback(B=>(m.current=B,()=>{m.current===B&&(m.current=null)}),[]),$=h.useCallback(B=>{const se=(t.current[r.current]??S1()).tabs.find(ne=>ps(ne)===B);if(!se)return;const re=A.current;if(re){re(se);return}_(B)},[_]),L=u&&!!o.activeKey;h.useEffect(()=>{const B=Pn(),ee=B==null?void 0:B.setSidePanelCloseShortcutActive;if(!ee)return;let se=!1,re=null;const ne=()=>{if(se)return;const Y=L&&!_5e(document.activeElement);re!==Y&&(re=Y,ee(Y).catch(()=>{}))},Ae=()=>queueMicrotask(ne);return document.addEventListener("focusin",Ae,!0),document.addEventListener("focusout",Ae,!0),ne(),()=>{se=!0,document.removeEventListener("focusin",Ae,!0),document.removeEventListener("focusout",Ae,!0)}},[L]),h.useEffect(()=>{const B=Pn(),ee=B==null?void 0:B.setSidePanelCloseShortcutActive;if(ee)return()=>{ee(!1).catch(()=>{})}},[]),h.useEffect(()=>{const B=Pn();if(B!=null&&B.onBrowserReset)return B.onBrowserReset(()=>{const ee=Object.fromEntries(Object.entries(t.current).map(([re,ne])=>[re,eUt(ne,re,m.current)]));t.current=ee;const se=ee[r.current]??S1();l(se),f(AY(se)&&se.open)})},[]),h.useEffect(()=>{if(!L)return;const B=Pn();if(B!=null&&B.onCloseSidePanelActiveTab)return B.onCloseSidePanelActiveTab(()=>{const ee=o.activeKey;ee&&$(ee)})},[o.activeKey,L,$]),h.useEffect(()=>{const B=Pn();if(B!=null&&B.onOpenEmptySidePanel)return B.onOpenEmptySidePanel(j)},[j]),h.useEffect(()=>{if(!u||!o.activeKey)return;const B=ee=>{_5e(ee.target)||ee.key.toLowerCase()!=="w"||(CE()==="mac"?!ee.metaKey||ee.ctrlKey:!ee.ctrlKey||ee.metaKey)||ee.altKey||ee.shiftKey||(ee.preventDefault(),ee.stopPropagation(),$(o.activeKey))};return document.addEventListener("keydown",B,!0),()=>document.removeEventListener("keydown",B,!0)},[o.activeKey,u,$]);const H=h.useCallback((B,ee,se)=>{const re=Gw(B);if(!(t.current[re]??S1()).tabs.some(Y=>ps(Y)===ee))return!1;const Ae=ps(se);return g(re,Y=>({...Y,activeKey:Y.activeKey===ee?Ae:Y.activeKey,tabs:Y.tabs.map(ce=>ps(ce)===ee?se:ce)})),!0},[g]),X=h.useCallback((B,ee)=>{H(s,B,ee)},[s,H]),F=h.useCallback((B,ee,se)=>{B!==ee&&g(s,re=>{const ne=re.tabs.findIndex(ke=>ps(ke)===B),Ae=re.tabs.findIndex(ke=>ps(ke)===ee);if(ne<0||Ae<0)return re;const Y=[...re.tabs],[ce]=Y.splice(ne,1);if(!ce)return re;const Fe=Y.findIndex(ke=>ps(ke)===ee)+(se==="after"?1:0);return Y.splice(Fe,0,ce),{...re,tabs:Y}})},[s,g]),Q=h.useCallback(B=>{g(s,ee=>({...ee,activeKey:B,hasPanelState:!0,open:!0}))},[s,g]),q=h.useMemo(()=>({activeKey:o.activeKey,clearCurrentContext:N,clearDisplayedContextHold:M,closePanel:P,closeTarget:_,contextKey:s,detachTargetForContext:R,displayedContextHold:c,getTargetRevisionForContext:T,hidePanel:C,holdDisplayedContext:E,open:u,openEmpty:j,openTarget:y,openTargetInNewTab:v,openTargetForContext:w,registerCloseRequestHandler:D,registerBrowserResetHandler:U,replaceTarget:X,replaceTargetForContext:H,reorderTarget:F,setActiveKey:Q,setContextKey:x,showPanel:k,showPanelForContext:S,tabs:o.tabs}),[N,M,P,_,s,o.activeKey,o.tabs,R,c,T,C,E,u,j,y,w,v,U,D,F,X,H,Q,x,k,S]);return i.jsx(the.Provider,{value:q,children:e})}function Ob(){const e=h.useContext(the);if(!e)throw new Error("useSidePanel must be used inside SidePanelProvider");return e}function nUt(){return h.useContext(the)}function rUt(e){try{const t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}async function sUt(e){var r;const{request:t}=e;if(!rUt(t.url))return"ignored";let n;try{n=await e.getSettings()}catch{return await e.forceOpenExternal(t.url),"default_browser"}return n.openLinksIn==="built_in"||t.source==="browser_popup"?(e.openBuiltIn(a6(t.url,{favicon:(r=e.resolveFavicon)==null?void 0:r.call(e,t.url),newTab:t.source==="browser_popup"})),"built_in"):(await e.forceOpenExternal(t.url),"default_browser")}const o3=8;function iUt(){return{activeViewInstanceId:null,tabOrder:[],tabsByViewInstanceId:{},runtimesById:{},promotionsById:{}}}function aUt(){return{organizations:{}}}function P5(e){return e.kind==="side"||e.kind==="transferring"||e.kind==="main"||e.kind==="parked"}function oUt(e,t){const n=e.organizations[t];return n?Object.values(n.runtimesById).filter(r=>r.targetKind==="browser"&&P5(r.host)).length:0}function lUt(e){return Object.values(e.runtimesById).filter(t=>t.targetKind==="browser"&&P5(t.host)).length}function cUt(e,t){return e.kind!==t.kind?!1:e.kind==="side"&&t.kind==="side"?e.contextKey===t.contextKey:e.kind==="main"&&t.kind==="main"?e.organizationId===t.organizationId:!0}function dUt(e){return{...e}}function LVe(e,t,n){if(!n.id||!n.viewInstanceId||n.target.viewInstanceId!==n.viewInstanceId||n.target.kind!==n.targetKind||n.host.kind==="main"&&n.host.organizationId!==t)return!1;const r=e.runtimesById[n.id];return r&&(r.viewInstanceId!==n.viewInstanceId||r.targetKind!==n.targetKind)||n.targetKind==="browser"&&P5(n.host)&&!((r==null?void 0:r.targetKind)==="browser"&&P5(r.host))&&lUt(e)>=o3?!1:!(P5(n.host)&&Object.values(e.runtimesById).some(o=>o.id!==n.id&&o.viewInstanceId===n.viewInstanceId&&P5(o.host)))}function Mg(e,t,n){if(!LVe(e,t,n))return e;const r=e.runtimesById[n.id];return r&&cUt(r.host,n.host)?e:{...e,runtimesById:{...e.runtimesById,[n.id]:{...n,organizationId:t,target:(r==null?void 0:r.target)??X6(n.target),host:dUt(n.host)}}}}function X6(e){return e.kind!=="browser"||!e.savedViewRecovery?{...e}:{...e,savedViewRecovery:{...e.savedViewRecovery,persistedMetadata:{...e.savedViewRecovery.persistedMetadata,target:{...e.savedViewRecovery.persistedMetadata.target}}}}}function zVe(e){return!!(e.viewInstanceId&&e.runtimeId&&e.originContextKey&&e.target.viewInstanceId===e.viewInstanceId)}function nhe(e,t){return Object.values(e.tabsByViewInstanceId).find(n=>n.savedViewId===t)??null}function Cie(e,t,n,r){if(!zVe(n)||r!==null&&!r)return{organization:e,outcome:"rejected"};const s=r?nhe(e,r):null;if(s&&s.viewInstanceId!==n.viewInstanceId)return e.activeViewInstanceId===s.viewInstanceId?{organization:e,outcome:"focused_existing_binding"}:{organization:{...e,activeViewInstanceId:s.viewInstanceId},outcome:"focused_existing_binding"};const a=e.tabsByViewInstanceId[n.viewInstanceId];if(a){const c=r!==null&&a.savedViewId!==null&&a.savedViewId!==r,d=r===null||a.savedViewId===r,u=e.activeViewInstanceId===n.viewInstanceId;return d&&u?{organization:e,outcome:"already_satisfied"}:{organization:{...e,activeViewInstanceId:n.viewInstanceId,tabsByViewInstanceId:r===null||d||c?e.tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n.viewInstanceId]:{...a,savedViewId:r}}},outcome:c?"binding_conflict":"already_satisfied"}}const o={id:n.runtimeId,viewInstanceId:n.viewInstanceId,targetKind:n.target.kind,target:n.target,host:{kind:"main",organizationId:t}};if(!LVe(e,t,o))return{organization:e,outcome:"rejected"};const l=Mg(e,t,o);return{organization:{...l,activeViewInstanceId:n.viewInstanceId,tabOrder:[...l.tabOrder,n.viewInstanceId],tabsByViewInstanceId:{...l.tabsByViewInstanceId,[n.viewInstanceId]:{organizationId:t,viewInstanceId:n.viewInstanceId,savedViewId:r,target:X6(n.target),originContextKey:n.originContextKey,runtimeId:n.runtimeId}}},outcome:"opened"}}function xl(e,t,n){if(!t)return e;const r=e.organizations[t]??iUt(),s=n(r);return s===r?e:{...e,organizations:{...e.organizations,[t]:s}}}function uUt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||!n||r.savedViewId===n||r.savedViewId!==null||nhe(e,n)?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:n}}}}function fUt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||r.savedViewId!==n?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:null}}}}function AUt(e,t,n){var u;const r=e.tabsByViewInstanceId[n];if(!r)return e;const s=e.tabOrder.indexOf(n),a=e.tabOrder.filter(f=>f!==n),{[n]:o,...l}=e.tabsByViewInstanceId,c=Mg(e,t,{id:r.runtimeId,viewInstanceId:r.viewInstanceId,targetKind:r.target.kind,target:((u=e.runtimesById[r.runtimeId])==null?void 0:u.target)??r.target,host:{kind:"disposed"}}),d=e.activeViewInstanceId===n?a[Math.min(Math.max(s,0),a.length-1)]??null:e.activeViewInstanceId;return{...c,activeViewInstanceId:d,tabOrder:a,tabsByViewInstanceId:l}}function hUt(e,t,n){const r=e.tabOrder.indexOf(t);if(r<0||!Number.isFinite(n))return e;const s=Math.max(0,Math.min(Math.trunc(n),e.tabOrder.length-1));if(r===s)return e;const a=[...e.tabOrder];return a.splice(r,1),a.splice(s,0,t),{...e,tabOrder:a}}function mUt(e){return{...e,target:X6(e.target)}}function xW(e){return Number.isInteger(e)&&e>=0}function pUt(e){return e.status==="pending"||e.status==="reconciling"||e.status==="claiming"||e.status==="detaching"}function gUt(e,t,n,r,s){if(!n||!s||!zVe(r)||!xW(r.sourceRevision)||e.promotionsById[n]||Object.values(e.promotionsById).some(l=>pUt(l)&&l.source.runtimeId===r.runtimeId))return e;const a=e.runtimesById[r.runtimeId];if(!a||a.viewInstanceId!==r.viewInstanceId||a.targetKind!==r.target.kind||a.host.kind!=="side"||a.host.contextKey!==r.originContextKey)return e;const o=Mg(e,t,{id:a.id,viewInstanceId:a.viewInstanceId,targetKind:a.targetKind,target:a.target,host:{kind:"transferring"}});return{...o,promotionsById:{...o.promotionsById,[n]:{id:n,organizationId:t,clientMutationId:s,status:"pending",source:mUt(r)}}}}function qj(e,t,n){const r=e.runtimesById[n.runtimeId];return r?Mg(e,t,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:{kind:"side",contextKey:n.originContextKey}}):e}function NE(e,t,n){const r=e.promotionsById[t];if(!r||r.status!=="pending"&&r.status!=="reconciling"&&r.status!=="claiming"||r.source.sourceRevision!==n)return null;const s=e.runtimesById[r.source.runtimeId];return!s||s.viewInstanceId!==r.source.viewInstanceId||s.targetKind!==r.source.target.kind||s.host.kind!=="transferring"?null:r}function xUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="server_failed"&&a.status!=="commit_unknown"||a.source.sourceRevision!==r||!xW(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=Mg(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"pending",source:{...a.source,sourceRevision:s}}}}}function bUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="commit_unknown"||a.source.sourceRevision!==r||!xW(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=Mg(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"reconciling",source:{...a.source,sourceRevision:s}}}}}function yUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="claim_failed"||a.source.sourceRevision!==r||!xW(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=Mg(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"claiming",savedViewId:a.savedViewId,source:{...a.source,sourceRevision:s}}}}}function vUt(e,t,n,r,s){const a=NE(e,n,s);return!a||a.status==="claiming"||!r?e:{...e,promotionsById:{...e.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"claiming",savedViewId:r}}}}function wUt(e,t,n,r,s){const a=NE(e,n,r);if(!a||a.status==="claiming")return e;const o=qj(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"server_failed",error:s}}}}function kUt(e,t,n,r,s){const a=NE(e,n,r);if(!a||a.status==="claiming")return e;const o=qj(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"commit_unknown",error:s}}}}function OUt(e,t,n,r,s,a){const o=NE(e,n,s);if(!o||o.status!=="claiming"||!r||o.savedViewId!==r)return e;const l=qj(e,t,o.source);return{...l,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function mQ(e,t){const{[t]:n,...r}=e.promotionsById;return{...e,promotionsById:r}}function SUt(e,t,n){const r=e.promotionsById[t];return!r||r.status!=="server_failed"&&r.status!=="commit_unknown"&&r.status!=="claim_failed"||r.source.sourceRevision!==n?e:mQ(e,t)}function jUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.source.sourceRevision!==s||a.source.savedViewId!==r&&(!("savedViewId"in a)||a.savedViewId!==r))return e;if(a.status==="detaching"){const o=BVe(e,t,n,r,s,"saved_view_removed");return mQ(o,n)}return mQ(qj(e,t,a.source),n)}function Z9(e,t,n,r,s){const a=qj(e,t,n.source);return{...a,promotionsById:{...a.promotionsById,[n.id]:{id:n.id,organizationId:t,clientMutationId:n.clientMutationId,source:n.source,status:"claim_failed",savedViewId:r,error:s}}}}function $Ve(e){return{...e,target:X6(e.target)}}function E5e(e,t,n,r){return{...e,promotionsById:{...e.promotionsById,[n.id]:{...n,organizationId:t,status:"detaching",rollback:r}}}}function CUt(e,t,n,r,s){var u;const a=NE(e,n,s);if(!a||a.status!=="claiming"||!r||a.savedViewId!==r)return e;const o={activeViewInstanceId:e.activeViewInstanceId,tab:e.tabsByViewInstanceId[a.source.viewInstanceId]?$Ve(e.tabsByViewInstanceId[a.source.viewInstanceId]):null},l=e.tabsByViewInstanceId[a.source.viewInstanceId],c=nhe(e,r);if(c&&c.viewInstanceId!==a.source.viewInstanceId){const f=e.activeViewInstanceId===c.viewInstanceId?e:{...e,activeViewInstanceId:c.viewInstanceId};return Z9(f,t,a,r,"saved_view_already_bound")}if(l!=null&&l.savedViewId&&l.savedViewId!==r){const f=e.activeViewInstanceId===l.viewInstanceId?e:{...e,activeViewInstanceId:l.viewInstanceId};return Z9(f,t,a,r,"saved_view_binding_conflict")}if(l){let f=e,A=l.runtimeId;if(l.runtimeId===a.source.runtimeId){const m=f.runtimesById[a.source.runtimeId];f=Mg(f,t,{id:m.id,viewInstanceId:m.viewInstanceId,targetKind:m.targetKind,target:m.target,host:{kind:"main",organizationId:t}})}else{const m=f.runtimesById[l.runtimeId];if(!m||m.viewInstanceId!==l.viewInstanceId||m.targetKind!==l.target.kind||P5(m.host))return Z9(e,t,a,r,"existing_tab_runtime_unavailable");const g=f.runtimesById[a.source.runtimeId];if(f=Mg(f,t,{id:g.id,viewInstanceId:g.viewInstanceId,targetKind:g.targetKind,target:g.target,host:{kind:"main",organizationId:t}}),((u=f.runtimesById[g.id])==null?void 0:u.host.kind)!=="main")return Z9(e,t,a,r,"existing_tab_runtime_unavailable");A=g.id}return f={...f,activeViewInstanceId:l.viewInstanceId,tabsByViewInstanceId:l.savedViewId===r&&l.runtimeId===A?f.tabsByViewInstanceId:{...f.tabsByViewInstanceId,[l.viewInstanceId]:{...l,savedViewId:r,runtimeId:A,target:X6(a.source.target),originContextKey:a.source.originContextKey}}},E5e(f,t,a,o)}const d=Cie(e,t,{viewInstanceId:a.source.viewInstanceId,runtimeId:a.source.runtimeId,target:a.source.target,originContextKey:a.source.originContextKey},r);return d.outcome!=="opened"?Z9(d.organization,t,a,r,d.outcome==="binding_conflict"?"saved_view_binding_conflict":"main_host_claim_rejected"):E5e(d.organization,t,a,o)}function FVe(e,t,n,r){const s=e.promotionsById[t];if(!s||s.status!=="detaching"||s.savedViewId!==n||s.source.sourceRevision!==r)return null;const a=e.runtimesById[s.source.runtimeId],o=e.tabsByViewInstanceId[s.source.viewInstanceId];return!a||a.viewInstanceId!==s.source.viewInstanceId||a.host.kind!=="main"||a.host.organizationId!==s.organizationId||!o||o.runtimeId!==a.id||o.savedViewId!==n?null:s}function NUt(e,t,n,r){const s=FVe(e,t,n,r);return s?mQ(e,s.id):e}function BVe(e,t,n,r,s,a){const o=FVe(e,n,r,s);if(!o)return e;const l=qj(e,t,o.source),c={...l.tabsByViewInstanceId};let d=l.tabOrder;return o.rollback.tab?c[o.source.viewInstanceId]=$Ve(o.rollback.tab):(delete c[o.source.viewInstanceId],d=d.filter(u=>u!==o.source.viewInstanceId)),{...l,activeViewInstanceId:o.rollback.activeViewInstanceId,tabOrder:d,tabsByViewInstanceId:c,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function PUt(e,t,n,r){const s=e.runtimesById[t];return!s||s.viewInstanceId!==n||r.viewInstanceId!==n||s.targetKind!==r.kind?e:{...e,runtimesById:{...e.runtimesById,[t]:{...s,target:X6(r)}}}}function IUt(e,t,n,r){const s=e.tabsByViewInstanceId[n],a=e.runtimesById[t];return!s||s.runtimeId!==t||s.target.kind!==r.kind||r.viewInstanceId!==n||!a||a.viewInstanceId!==n||a.targetKind!==r.kind?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n]:{...s,target:X6(r)}}}}function TUt(e,t){switch(t.type){case"saved-tab/open":return xl(e,t.organizationId,n=>Cie(n,t.organizationId,t.tab,t.savedViewId).organization);case"session-tab/create":return xl(e,t.organizationId,n=>Cie(n,t.organizationId,t.tab,null).organization);case"tab/focus":return xl(e,t.organizationId,n=>n.activeViewInstanceId===t.viewInstanceId||!n.tabsByViewInstanceId[t.viewInstanceId]?n:{...n,activeViewInstanceId:t.viewInstanceId});case"tab/reorder":return xl(e,t.organizationId,n=>hUt(n,t.viewInstanceId,t.toIndex));case"tab/bind-saved-view":return xl(e,t.organizationId,n=>uUt(n,t.viewInstanceId,t.savedViewId));case"tab/unbind-saved-view":return xl(e,t.organizationId,n=>fUt(n,t.viewInstanceId,t.savedViewId));case"tab/close":return xl(e,t.organizationId,n=>AUt(n,t.organizationId,t.viewInstanceId));case"tab/update-target":return xl(e,t.organizationId,n=>IUt(n,t.runtimeId,t.viewInstanceId,t.target));case"runtime/admit":return xl(e,t.organizationId,n=>Mg(n,t.organizationId,t.runtime));case"runtime/set-host":return xl(e,t.organizationId,n=>{const r=n.runtimesById[t.runtimeId];return r?Mg(n,t.organizationId,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:t.host}):n});case"runtime/update-target":return xl(e,t.organizationId,n=>PUt(n,t.runtimeId,t.viewInstanceId,t.target));case"promotion/start":return xl(e,t.organizationId,n=>gUt(n,t.organizationId,t.promotionId,t.source,t.clientMutationId));case"promotion/server-commit":return xl(e,t.organizationId,n=>vUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/claim":return xl(e,t.organizationId,n=>CUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-succeed":return xl(e,t.organizationId,n=>NUt(n,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-fail":return xl(e,t.organizationId,n=>BVe(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/server-fail":return xl(e,t.organizationId,n=>wUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/timeout":return xl(e,t.organizationId,n=>kUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/retry":return xl(e,t.organizationId,n=>xUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/reconcile":return xl(e,t.organizationId,n=>bUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/claim-fail":return xl(e,t.organizationId,n=>OUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/claim-retry":return xl(e,t.organizationId,n=>yUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/discard":return xl(e,t.organizationId,n=>SUt(n,t.promotionId,t.expectedSourceRevision));case"promotion/cancel-saved-view":return xl(e,t.organizationId,n=>jUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision))}}function QVe(){var n,r;const e=(n=document.activeElement)==null?void 0:n.closest("[data-runtime-id]");if(!e||e.hidden||e.hasAttribute("inert")||e.getAttribute("aria-hidden")==="true")return null;const t=e.dataset.runtimeId;return t?{runtimeId:t,owner:(r=e.dataset.ownerId)!=null&&r.startsWith("main:")?"main_workbench":"side_panel"}:null}function _Ut(){var e;return((e=QVe())==null?void 0:e.runtimeId)??null}function MUt(){const e=Vn(),t=JAe(),n=zFe(),{openTarget:r}=Ob(),s=Uj();return h.useEffect(()=>{const a=Pn();if(a!=null&&a.onOpenWebLink)return a.onOpenWebLink(o=>{sUt({request:o,getSettings:()=>e.fetchQuery({queryKey:V.instance.browserSettings,queryFn:()=>Ha.getBrowser(),staleTime:0}),openBuiltIn:l=>{var f;if(o.sourceWebContentsId){((t==null?void 0:t.openTargetForGuest(o.sourceWebContentsId,l))??!1)||console.warn("[rudder-ui] ignored Browser popup without a live guest owner",o.sourceWebContentsId);return}const c=((f=n==null?void 0:n.selectedOrganizationId)==null?void 0:f.trim())??"",d=!t||!c||t.getLiveBrowserCount(c)<o3;r(l,{allowNewBrowserGuest:d}).admitted||s==null||s.pushToast({title:"Browser tab limit reached",body:`Close a Browser tab to open another. Side Panel and Main share ${o3} live tabs.`,tone:"error"})},forceOpenExternal:l=>{var c;return((c=a.forceOpenExternal)==null?void 0:c.call(a,l))??a.openExternal(l)},resolveFavicon:XBt}).catch(l=>{console.warn("[rudder-ui] failed to route Desktop web link",l)})})},[t,r,n==null?void 0:n.selectedOrganizationId,e,s]),h.useEffect(()=>{const a=Pn();if(a!=null&&a.onBrowserShortcut)return a.onBrowserShortcut(o=>{if(!t)return;const l=o.sourceWebContentsId?null:_Ut();if(o.action==="close_tab"){o.sourceWebContentsId?t.closeTargetForGuest(o.sourceWebContentsId):l&&t.closeTargetForRuntime(l);return}o.sourceWebContentsId?t.dispatchBrowserShortcutForGuest(o.sourceWebContentsId,o.action):l&&t.dispatchBrowserShortcutForRuntime(l,o.action)})},[t]),h.useEffect(()=>{var f;const a=(f=Pn())==null?void 0:f.setBrowserSurfaceShortcutActive;if(!a||!t)return;let o=!1,l=!1,c;const d=()=>{var y;if(o)return;const A=QVe(),m=(A==null?void 0:A.runtimeId)??null,g=m?((y=t.getRuntimeTarget(m))==null?void 0:y.kind)==="browser":!1,x=A==null?void 0:A.owner;l===g&&x===c||(l=g,c=x,a(g,x).catch(()=>{}))},u=()=>queueMicrotask(d);return document.addEventListener("focusin",u,!0),document.addEventListener("focusout",u,!0),d(),()=>{o=!0,document.removeEventListener("focusin",u,!0),document.removeEventListener("focusout",u,!0),a(!1).catch(()=>{})}},[t]),null}const xT="https://docs.rudderhq.dev",UVe="https://discord.gg/ZcfWwPVkUz";function VVe({alt:e="",className:t,...n}){return i.jsx("img",{src:"/rudder-logo.png",alt:e,"aria-hidden":e?void 0:!0,className:K("inline-block shrink-0 rounded-full bg-white object-cover ring-1 ring-black/5 dark:ring-white/10",t),...n})}function EUt(){const[e,t]=h.useState(null),n=h.useRef(null);h.useEffect(()=>{const a=Pn();if(!(a!=null&&a.getReleaseNotes))return;let o=!1;return a.getReleaseNotes().then(l=>{o||l.status!=="available"||(n.current=l.notes,t(l.notes))}).catch(()=>{}),()=>{o=!0}},[]);async function r(){var o,l;const a=n.current;n.current=null,t(null),a&&await((l=(o=Pn())==null?void 0:o.markReleaseNotesShown)==null?void 0:l.call(o,a.version).catch(()=>{}))}async function s(){const a=Pn();if(a){await a.openExternal(xT).catch(()=>{});return}window.open(xT,"_blank","noopener,noreferrer")}return i.jsx(Ps,{open:e!==null,onOpenChange:a=>{a||r()},children:i.jsxs(zs,{className:"gap-0 overflow-hidden p-0 sm:max-w-[36rem]",showCloseButton:!1,children:[i.jsxs("div",{className:"flex items-start gap-3 border-b border-border/70 px-5 pb-4 pt-5",children:[i.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-[var(--radius-md)] border border-border bg-background shadow-sm",children:i.jsx(VVe,{alt:"Rudder",className:"h-6 w-6 ring-0"})}),i.jsxs(vi,{className:"min-w-0 gap-1 text-left",children:[i.jsx(ei,{className:"text-base leading-6",children:(e==null?void 0:e.title)??"What's new in Rudder"}),i.jsx(Si,{className:"text-sm leading-5",children:"Updates installed with this version."})]})]}),i.jsx("div",{className:"max-h-[min(62vh,34rem)] overflow-y-auto px-5 py-4",children:i.jsx("div",{className:"space-y-4",children:e==null?void 0:e.sections.map(a=>i.jsxs("section",{className:"space-y-2",children:[i.jsx("h2",{className:"text-sm font-semibold text-foreground",children:a.title}),i.jsx("ul",{className:"space-y-1.5 text-sm leading-5 text-muted-foreground",children:a.items.map(o=>i.jsxs("li",{className:"flex gap-2",children:[i.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-muted-foreground/70"}),i.jsx("span",{children:o})]},o))})]},a.title))})}),i.jsxs(ga,{className:"border-t border-border/70 px-5 py-4 sm:justify-between",children:[i.jsxs(le,{type:"button",variant:"outline",onClick:()=>void s(),children:[i.jsx(Ja,{className:"h-4 w-4"}),"Docs"]}),i.jsx(le,{type:"button",onClick:()=>void r(),children:"Continue"})]})]})})}function DUt(e){const[t="",...n]=e.split(/\n{2,}/);return{body:t.trim(),runDetail:n.join(`
1691
+ - (兼容旧字段)\`agentDefaultsPayload.headers["x-openclaw-auth"]\``,"organizationSettings.packages.description":"在不同 Rudder 安装之间迁移组织配置与工作数据。","organizationSettings.packages.export":"导出","organizationSettings.packages.import":"导入","organizationSettings.danger.description":"归档这个 organization 后,它会从侧边栏中隐藏。这个状态会持久化到数据库。","organizationSettings.danger.confirm":"要归档 organization “{{name}}” 吗?它会从侧边栏中隐藏。","organizationSettings.danger.archiving":"归档中...","organizationSettings.danger.alreadyArchived":"已归档","organizationSettings.danger.archive":"归档 organization","organizationSettings.danger.failed":"归档 organization 失败","settings.eyebrow.system":"系统设置","settings.eyebrow.labs":"实验室","app.instanceSetupRequired":"需要完成实例初始化","app.bootstrapInvite.active":"当前还没有实例管理员。引导邀请已经激活。请查看 Rudder 启动日志中的首个管理员邀请链接,或运行下面的命令重新生成:","app.bootstrapInvite.inactive":"当前还没有实例管理员。请在 Rudder 运行环境中执行下面的命令生成首个管理员邀请链接:","app.failedToLoadAppState":"加载应用状态失败","app.addAnotherAgentToOrganization":"为 {{name}} 再添加一个智能体","app.createAnotherOrganization":"创建另一个组织","app.createFirstOrganization":"创建你的第一个组织","app.onboarding.addAgentDescription":"再次运行引导,为这个组织添加一个智能体和一个初始任务。","app.onboarding.createAnotherDescription":"再次运行引导,创建另一个组织并初始化它的第一个智能体。","app.onboarding.createFirstDescription":"从创建一个组织和你的第一个智能体开始。","app.addAgent":"添加智能体","app.startOnboarding":"开始引导","app.noCompaniesDescription":"从创建一个组织开始。","app.newOrganization":"新建组织","general.title":"通用","general.description":"这台设备上的核心应用偏好。","general.updateFailed":"更新通用设置失败。","general.loadLoading":"正在加载通用设置...","general.loadFailed":"加载通用设置失败。","general.language.title":"语言","general.language.description":"选择这个 Rudder 实例在控制台界面中使用的语言。","general.language.label":"界面语言","general.language.help":"这是实例级界面语言,会影响所有使用这个实例的用户看到的控制台外壳和设置页面。","general.language.option.en.label":"英语","general.language.option.en.description":"默认产品语言","general.language.option.zh-CN.label":"简体中文","general.language.option.zh-CN.description":"中文界面","general.language.preview.en.primary":"Hello","general.language.preview.en.secondary":"Board UI","general.language.preview.zh-CN.primary":"你好","general.language.preview.zh-CN.secondary":"控制台界面","general.basics.title":"基础","general.productTour.title":"工作台教程","general.productTour.description":"重新播放引导教程。","general.productTour.start":"开始教程","general.logs.title":"操作日志","general.logs.description":"调整界面中面向操作员展示的输出方式。","general.logs.censor.title":"对日志中的用户名做脱敏","general.logs.censor.description":"对日志中显示的主目录路径用户名做脱敏。","general.updates.title":"桌面应用","general.updates.description":"选择这台机器安装 Rudder Desktop 时使用哪个发布渠道。","general.updates.loadFailed":"加载桌面更新设置失败。","general.updates.updateFailed":"更新桌面更新设置失败。","general.updates.unavailable":"当前环境不支持桌面更新设置。","general.updates.canary.title":"接收桌面测试版更新","general.updates.canary.disabledDescription":"安装最新正式版;当测试版更新时也纳入检测。","general.updates.canary.enabledDescription":"这台机器会同时检查正式版和更新的测试版。","general.diagnostics.developer.title":"显示开发诊断信息","general.diagnostics.developer.description":"在 transcript 中显示 Rudder 内部运行时、workspace、session 和 adapter 诊断信息。","general.developer.title":"开发者","general.appearance.title":"外观","general.appearance.description":"选择这个设备上的 Rudder 外观。视觉风格遵循低眩光、克制的 Claude 风格界面。","general.appearance.colorMode":"颜色模式","general.appearance.light.label":"浅色","general.appearance.light.description":"暖色纸面风格","general.appearance.system.label":"自动","general.appearance.system.description":"跟随系统外观","general.appearance.dark.label":"深色","general.appearance.dark.description":"低眩光工作区","general.appearance.designStyle":"设计风格","general.appearance.defaultStyle.label":"Classic","general.appearance.defaultStyle.description":"平衡的低眩光界面","general.appearance.mira.label":"Compact","general.appearance.mira.description":"紧凑卡片与控件","general.appearance.luma.label":"Rudder","general.appearance.luma.description":"柔和宽松的控件","general.appearance.baseColor":"基础色","general.appearance.base.neutral.label":"Neutral","general.appearance.base.neutral.description":"平衡的中性灰界面","general.appearance.base.stone.label":"Stone","general.appearance.base.stone.description":"暖调石色界面","general.appearance.base.zinc.label":"Zinc","general.appearance.base.zinc.description":"冷调灰色界面","general.appearance.base.mauve.label":"Mauve","general.appearance.base.mauve.description":"低饱和玫瑰灰界面","general.appearance.base.olive.label":"Olive","general.appearance.base.olive.description":"低饱和橄榄色界面","general.appearance.base.mist.label":"Mist","general.appearance.base.mist.description":"柔和蓝灰界面","general.appearance.base.taupe.label":"Taupe","general.appearance.base.taupe.description":"暖调灰褐界面","general.appearance.themeColor":"主题色","general.appearance.theme.neutral.label":"Neutral","general.appearance.theme.neutral.description":"单色操作状态","general.appearance.theme.amber.label":"Amber","general.appearance.theme.amber.description":"琥珀色操作状态","general.appearance.theme.blue.label":"Blue","general.appearance.theme.blue.description":"蓝色操作状态","general.appearance.theme.cyan.label":"Cyan","general.appearance.theme.cyan.description":"青色操作状态","general.appearance.theme.emerald.label":"Rudder","general.appearance.theme.emerald.description":"Rudder 绿色操作状态","general.appearance.theme.fuchsia.label":"Fuchsia","general.appearance.theme.fuchsia.description":"紫红色操作状态","general.appearance.theme.green.label":"Green","general.appearance.theme.green.description":"绿色操作状态","general.appearance.theme.indigo.label":"Indigo","general.appearance.theme.indigo.description":"靛蓝色操作状态","general.appearance.theme.lime.label":"Lime","general.appearance.theme.lime.description":"青柠色操作状态","general.appearance.theme.orange.label":"Orange","general.appearance.theme.orange.description":"橙色操作状态","general.appearance.theme.pink.label":"Pink","general.appearance.theme.pink.description":"粉色操作状态","notifications.title":"通知","notifications.description":"管理这个 Rudder 实例的未读 inbox 提醒。","notifications.loadFailed":"加载通知设置失败。","notifications.updateFailed":"更新通知设置失败。","notifications.support.available":"可用","notifications.support.unavailable":"不可用","notifications.permission.title":"权限","notifications.permission.description":"通知权限由操作系统或浏览器掌控,所以 Rudder 需要同时展示当前状态和修复入口。","notifications.permission.requestFailed":"请求通知权限失败。","notifications.permission.openSettingsFailed":"打开通知设置失败。","notifications.permission.access.title":"通知访问权限","notifications.permission.access.summary":"权限:{{permission}}。提醒:{{notificationsSupport}}。","notifications.permission.access.summaryDesktop":"权限:{{permission}}。原生提醒:{{notificationsSupport}}。","notifications.permission.access.default":"Rudder 还没有请求通知权限,因此未读 inbox 提醒可能不会出现。","notifications.permission.access.denied.desktop":"通知权限已被操作系统拦截。请在系统通知设置中重新允许 Rudder,才能恢复 macOS 提醒。","notifications.permission.access.denied.browser":"通知权限已被浏览器拦截。请在浏览器站点通知设置中重新允许 Rudder,才能在 `pnpm dev` 里预览 inbox 提醒。","notifications.permission.access.requesting":"请求中...","notifications.permission.access.enable":"开启通知","notifications.permission.access.desktopHelp":"这里能触发原生通知,但真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.desktopHelpProd":"真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.openSettings":"打开通知设置","notifications.environment.title":"当前环境","notifications.environment.desktop":"当前运行在 Electron 桌面壳中。","notifications.environment.browser":"当前运行在浏览器预览模式中。","notifications.environment.desktopHelp":"这里可以使用原生系统通知来提示未读 inbox 变化。","notifications.environment.browserHelp":"浏览器模式可以通过 Web Notifications API 预览未读 inbox 提醒。","notifications.behavior.title":"行为","notifications.behavior.description":"选择 Rudder 是否提示未读 inbox 活动。","notifications.behavior.inbox.title":"Inbox 活动提醒","notifications.behavior.inbox.description":"当未读 inbox 数量增加时显示提醒。","notifications.behavior.inbox.toggle":"切换 inbox 通知","systemPermissions.title":"系统权限","systemPermissions.description":"管理本地自动化、文件访问和 inbox 提醒所需的系统权限。","systemPermissions.section.title":"权限","systemPermissions.section.description":"Rudder 会尽量打开对应系统设置;最终状态仍以操作系统为准。","systemPermissions.status.authorized":"已授权","systemPermissions.status.needsAccess":"需要授权","systemPermissions.status.blocked":"已阻止","systemPermissions.status.checking":"检查中","systemPermissions.status.desktopOnly":"仅桌面应用","systemPermissions.status.perApp":"按应用授权","systemPermissions.status.unknown":"未知","systemPermissions.status.unavailable":"不可用","systemPermissions.action.openSettings":"打开设置","systemPermissions.action.desktopOnly":"仅桌面可用","systemPermissions.action.browserManaged":"由浏览器管理","systemPermissions.openSettingsFailed":"打开系统设置失败。","systemPermissions.permission.fullDiskAccess.title":"完全磁盘访问权限","systemPermissions.permission.fullDiskAccess.description":"在需要更广文件访问时读取本地项目文件和工作区元数据。","systemPermissions.permission.accessibility.title":"辅助功能","systemPermissions.permission.accessibility.description":"让 Rudder 驱动的桌面自动化在需要时观察并控制应用界面。","systemPermissions.permission.automation.title":"自动化","systemPermissions.permission.automation.description":"macOS 会按目标应用分别授权自动化;可打开此面板查看具体应用条目。","systemPermissions.permission.notifications.title":"通知","systemPermissions.permission.notifications.description":"Rudder 通知的系统访问权限。Issue 和 chat 通知可以在下方分别控制。","systemPermissions.permission.notifications.inboxLabel":"Inbox 活动提醒","systemPermissions.notifications.title":"通知","systemPermissions.notifications.description":"系统通知权限可用后,选择 Rudder 哪些事件需要提醒你。","systemPermissions.notifications.system.title":"系统通知访问权限","systemPermissions.notifications.system.description":"如果 Rudder 通知被阻止或没有出现,可以打开系统通知设置检查。","systemPermissions.notifications.issue.title":"Issue 通知","systemPermissions.notifications.issue.description":"当 issue 被创建、更新、评论或重新打开时提醒。","systemPermissions.notifications.issue.toggle":"切换 issue 通知","systemPermissions.notifications.chat.title":"Chat 通知","systemPermissions.notifications.chat.description":"当 assistant chat 回复、提议 issue 或操作时提醒。","systemPermissions.notifications.chat.toggle":"切换 chat 通知","about.title":"关于","about.version.title":"版本","about.version.description":"这里显示当前机器上运行的 Rudder 构建版本。","about.version.current":"版本","about.desktop.title":"桌面应用","about.desktop.description":"这个壳层连接到与控制台、CLI 以及其他本地 Rudder 界面共用的同一份本地实例数据。","about.desktop.profile":"环境","about.desktop.instance":"实例 ID","about.desktop.runtime":"运行时","about.desktop.owner":"拥有者","about.desktop.instanceDataPath":"实例数据路径","about.actions.title":"操作","about.actions.description":"这些动作属于应用生命周期,不应该埋在通用偏好里。","about.notifications.description":"Inbox 提醒、角标行为和权限修复入口现在都集中在独立的通知设置页中管理。","about.notifications.open":"打开通知设置","about.updates.title":"检查更新","about.updates.description":"将当前桌面构建与所选 GitHub Release 策略做对比。","about.updates.check":"检查更新","about.updates.install":"更新","about.updates.download":"下载更新","about.updates.installing":"正在更新...","about.updates.channel.stable":"正式版","about.updates.channel.canary":"正式版 + Canary","about.updates.available.inline":"发现 {{channel}} 新版本:{{latestVersion}}。","about.updates.current.inline":"{{channel}} 当前已经是最新版本:{{currentVersion}}。","about.updates.unavailable.inline":"暂时无法完成 {{channel}} 版本对比。","about.updates.available.toastTitle":"发现新版本","about.updates.available.toastBody":"{{latestVersion}} 已可下载。","about.updates.installStarted.toastTitle":"已开始更新","about.updates.installStarted.toastBody":"Rudder 会在安装 {{latestVersion}} 后关闭并重新打开。","about.updates.installWaiting.toastTitle":"更新已排队","about.updates.installWaiting.toastBody":"安装包正在下载。Rudder 会在 {{totalRuns}} 个活跃运行结束后自动更新。","about.updates.installBlocked.toastTitle":"更新已暂停","about.updates.installUnavailable":"当前构建不支持应用内安装更新。","about.updates.installFailed":"无法开始更新。","about.updates.installFailedToastTitle":"无法开始更新","about.updates.progress.title":"正在更新到 {{version}}","about.updates.progress.readyTitle":"更新已准备好","about.updates.progress.completeTitle":"重启交接已完成","about.updates.progress.detailsTitle":"更新进度详情","about.updates.progress.failedTitle":"更新失败","about.updates.progress.retry":"重试","about.updates.progress.restartToUpdate":"退出并更新","about.updates.progress.updateWhenIdle":"空闲时更新","about.updates.progress.forceRestartToUpdate":"停止运行并立即更新","about.updates.progress.blockersTitle":"正在延迟更新的运行","about.updates.progress.blockerRun":"{{organization}} · {{agent}} · 运行 {{runId}}","about.updates.progress.automaticApply":"这些运行结束后,Rudder 会自动完成更新。","about.updates.progress.openReleases":"打开发布页","about.updates.progress.dismiss":"关闭更新状态","about.updates.progress.phase.starting":"正在开始更新...","about.updates.progress.phase.resolving_release":"正在解析发布版本...","about.updates.progress.phase.downloading_checksums":"正在下载校验文件...","about.updates.progress.phase.downloading_asset":"正在下载桌面安装包...","about.updates.progress.phase.verifying_checksum":"正在校验安装包...","about.updates.progress.phase.ready_to_install":"安装包已下载并校验完成,正在检查运行状态...","about.updates.progress.phase.waiting_for_active_runs":"正在等待运行结束...","about.updates.progress.phase.preparing_restart":"正在准备重启...","about.updates.progress.phase.closing":"Rudder 将关闭并重新打开以完成更新。","about.updates.progress.phase.complete":"Rudder Desktop 启动交接已完成。","about.updates.progress.phase.failed":"更新失败。","about.updates.current.toastTitle":"已经是最新版本","about.updates.current.toastBody":"当前桌面构建已经是 {{currentVersion}}。","about.updates.unavailable.toastTitle":"暂时无法检查更新","about.updates.unavailable.toastBody":"当前无法把这个构建与最新桌面版本进行对比。","about.updates.browserFallback.toastTitle":"已打开发布页","about.updates.browserFallback.toastBody":"桌面更新检查只能在打包后的应用内运行,因此已改为打开发布页面。","about.updates.failed":"检查更新失败。","about.updates.failedToastTitle":"检查更新失败","about.feedback.title":"发送反馈","about.feedback.description":"打开默认邮件应用,并创建一封发往 Rudder 维护者邮箱的草稿。","about.feedback.send":"发送反馈","about.feedback.toastTitle":"正在打开邮件应用","about.feedback.toastBody":"正在为 Rudder 维护者邮箱创建新邮件草稿。","about.feedback.failed":"打开反馈邮件草稿失败。","about.feedback.failedToastTitle":"发送反馈失败","profile.title":"个人资料与账号","profile.description":"管理你的操作员资料、Rudder Account 和已登录设备。","profile.loadLoading":"正在加载个人资料设置...","profile.loadFailed":"加载个人资料设置失败。","profile.updateFailed":"更新个人资料设置失败。","profile.toastSaved.title":"个人资料已保存","profile.toastSaved.body":"你的操作员资料已更新。","profile.toastSaveFailed.title":"保存个人资料失败","profile.about.title":"关于你","profile.about.description":"这里沿用类似 ChatGPT 的轻量个人上下文结构:一个偏好的称呼,加上一些可选的工作背景信息。","profile.nickname.label":"你的称呼","profile.nickname.placeholder":"Rudder 应该怎么称呼你?","profile.nickname.help":"如果填写了,内置聊天助手可以用它来称呼你。","profile.moreAboutYou.label":"更多关于你","profile.moreAboutYou.placeholder":"补充一些长期有效的背景信息,帮助内置聊天助手更好理解你的请求。","profile.moreAboutYou.help":"Rudder 只会把这段内容注入内置聊天助手。如果留空,则不会追加到聊天系统提示词中。","profile.import.helper.title":"从其他 AI 导入 memories","profile.import.helper.description":"把这段提示词复制到 ChatGPT、Claude 或其他 AI provider,再把导出的 memory 粘贴到下面。","profile.import.copyPrompt":"复制 memory 导入提示词","profile.import.copiedButton":"已复制","profile.import.copied.title":"提示词已复制","profile.import.copied.body":"把结果粘贴到“更多关于你”,再编辑并保存。","profile.import.copyFailed.title":"提示词未复制","profile.import.copyFailed.body":"请手动选中提示词文本并复制。","profile.save":"保存资料","profile.saving":"保存中...","productTour.checklist.title":"完成首次工作闭环","productTour.checklist.workspace":"读懂控制台","productTour.checklist.create":"创建小任务","productTour.checklist.issues":"使用 issue 结构","productTour.checklist.inspect":"检查工作输出","productTour.checklist.settings":"再次找到教程","productTour.stepCounter":"{{current}} / {{total}}","productTour.step.workspace.title":"Rudder 是 agent work 的控制台","productTour.step.workspace.body":"主导航把关键工作面放在一起:Messenger、Dashboard、Issues、Agents、Organization、Automations 和 Calendar。用它在行动、检查和 review 之间切换。","productTour.step.create.title":"从一个 agent 真能推进的小任务开始","productTour.step.create.body":"创建菜单是新 Chat、issue、agent 和 project 的入口。第一次闭环可以选择边界清楚、结果可 review 的小 Chat 或 issue。","productTour.step.issues.title":"Issue 增加明确的工作流结构","productTour.step.issues.body":"Issue 页面展示哪些工作在等待、执行、阻塞或完成。Chat 是并列的对话式路径;需要明确 owner、状态、优先级、依赖或 review 时,再使用 issue。","productTour.step.inspect.title":"先检查工作,再审批或继续推进","productTour.step.inspect.body":"Dashboard 会展示当前页面、详情、transcript、产出和审批入口。Rudder 应该让你清楚看到发生了什么,以及哪里需要你介入。","productTour.step.settings.title":"你可以从 Settings 重新播放教程","productTour.step.settings.body":"第一次导览结束后,Rudder 会保持安静。以后想重新查看时,打开系统设置,再进入通用即可再次运行。","productTour.back":"上一步","productTour.next":"下一步","productTour.finish":"完成","productTour.skip":"跳过教程","heartbeats.title":"心跳","heartbeats.description":"查看所有组织的定时心跳配置。你可以在这里看到哪些已调度、哪些只是已配置,并直接按行启停心跳。","heartbeats.loadLoading":"正在加载调度心跳...","heartbeats.loadFailed":"加载调度心跳失败。","heartbeats.updateFailed":"更新心跳失败。","heartbeats.disableAllFailed":"批量关闭所有心跳失败。","heartbeats.summary.scheduled":"已调度","heartbeats.summary.configuredInactive":"已配置未激活","heartbeats.summary.disabled":"已关闭","heartbeats.summary.organization":"个组织","heartbeats.summary.organizations":"个组织","heartbeats.disableAll":"全部关闭","heartbeats.disabling":"关闭中...","heartbeats.confirmDisableAll.one":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.confirmDisableAll.many":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.empty":"没有符合当前条件的调度心跳。","heartbeats.section.title":"已调度智能体","heartbeats.section.description":"按组织分组展示已启用心跳的智能体,方便你统一查看归属、频率与最近心跳状态。","heartbeats.table.agent":"智能体","heartbeats.table.role":"角色","heartbeats.table.scheduler":"调度状态","heartbeats.table.interval":"间隔","heartbeats.table.lastHeartbeat":"最近心跳","heartbeats.table.actions":"操作","heartbeats.scheduler.scheduled":"已调度","heartbeats.scheduler.configuredInactive":"已配置,未激活","heartbeats.scheduler.disabled":"已关闭","heartbeats.never":"从未","heartbeats.fullAgentConfig":"完整智能体配置","heartbeats.timerState":"定时心跳状态","heartbeats.on":"开","heartbeats.off":"关","chat.annotations.selectionUnavailable":"选区已不可用","chat.annotations.selectionUnavailableBody":"请重新选择回复中的文字后再试。","chat.annotations.couldNotAdd":"无法添加批注","chat.annotations.added":"已添加批注","chat.annotations.removed":"已移除批注"},yVe=["placeholder","title","aria-label"],vQt=["code","pre","script","style","textarea","[contenteditable='true']",".cm-editor",".cm-content",".mdxeditor","[data-i18n-ignore='true']"].join(", "),N5e=new WeakMap,P5e=new WeakMap;function vVe(e){return e?e.closest(vQt)!=null:!0}function wVe(e,t){const n=e.parentElement;if(!n||vVe(n))return;const r=e.textContent??"";let s=N5e.get(e);s?r!==s.rendered&&r!==s.source&&(s.source=r):(s={source:r,rendered:r},N5e.set(e,s));const a=yj(t,s.source);s.rendered=a,r!==a&&(e.textContent=a)}function kVe(e,t,n){if(!e.hasAttribute(t)||vVe(e))return;const r=e.getAttribute(t)??"";let s=P5e.get(e);s||(s=new Map,P5e.set(e,s));let a=s.get(t);a?r!==a.rendered&&r!==a.source&&(a.source=r):(a={source:r,rendered:r},s.set(t,a));const o=yj(n,a.source);a.rendered=o,r!==o&&e.setAttribute(t,o)}function vie(e,t){if(e.nodeType===Node.TEXT_NODE){wVe(e,t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;const n=e;for(const r of yVe)kVe(n,r,t);for(const r of Array.from(n.childNodes))vie(r,t)}function wQt({locale:e}){return h.useEffect(()=>{if(typeof document>"u")return;const t=document.body;if(!t)return;vie(t,e);const n=new MutationObserver(r=>{for(const s of r){if(s.type==="characterData"){wVe(s.target,e);continue}if(s.type==="attributes"){kVe(s.target,s.attributeName,e);continue}for(const a of Array.from(s.addedNodes))vie(a,e)}});return n.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:[...yVe]}),()=>n.disconnect()},[e]),null}const kQt={en:bVe,"zh-CN":yQt},OVe=h.createContext(null);function OQt(e,t){return t?e.replaceAll(/\{\{(\w+)\}\}/g,(n,r)=>{const s=t[r];return s==null?n:String(s)}):e}function eP(e,t,n){const r=kQt[e][t]??bVe[t];return OQt(r,n)}function SQt({children:e}){var a;const n=((a=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1}).data)==null?void 0:a.uiLocale)??"en";h.useEffect(()=>{typeof document>"u"||(document.documentElement.lang=n)},[n]);const r=h.useCallback((o,l)=>eP(n,o,l),[n]),s=h.useMemo(()=>({locale:n,t:r}),[n,r]);return i.jsxs(OVe.Provider,{value:s,children:[i.jsx(wQt,{locale:n}),e]})}function is(){const e=h.useContext(OVe);if(!e)throw new Error("useI18n must be used within I18nProvider");return e}const Mv="about:blank";function jQt(e){try{return new URL(e).hostname||e}catch{return e}}function CQt(e){const t=jQt(e.url);return e.code==="ERR_CONNECTION_REFUSED"?{summary:`${t} refused to connect.`,suggestions:["Checking the connection","Checking the proxy and firewall"]}:e.code==="ERR_NAME_NOT_RESOLVED"?{summary:`${t}'s server IP address could not be found.`,suggestions:["Checking the address","Checking the connection"]}:e.code==="ERR_TIMED_OUT"?{summary:`${t} took too long to respond.`,suggestions:["Checking the connection","Trying again later"]}:{summary:`The page at ${t} could not be loaded.`,suggestions:["Checking the address","Trying again later"]}}function NQt(e){var r;return!e||e.type==="keyUp"||!(((r=e.key)==null?void 0:r.toLowerCase())==="w"||e.code==="KeyW")||e.alt||e.shift?!1:navigator.platform.toLowerCase().includes("mac")?!!e.meta&&!e.control:!!e.control&&!e.meta}function AL(e){return`https://www.google.com/search?q=${encodeURIComponent(e)}`}function PQt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function IQt(e){try{return new URL(e).toString()}catch{return e.trim()}}function TQt(e){return decodeURIComponent(e.pathname).replace(/\/+$/g,"").split("/").filter(Boolean).at(-1)||"File"}function _Qt(e,t){try{const n=decodeURIComponent(t.pathname);return/^file:\/\/\//i.test(e)&&t.protocol==="file:"&&t.hostname===""&&n.startsWith("/")&&!/^\/[\\/]/.test(n)}catch{return!1}}function A5(e){const t=e.trim();if(!t||t===Mv)return"New tab";try{const n=new URL(t);return n.protocol==="file:"?TQt(n):n.hostname||n.protocol.replace(":","")||"Browser"}catch{return t}}function MQt(e){const t=e.trim();if(!t||/^about:blank$/i.test(t))return Mv;if(/^(https?|file):/i.test(t))try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"||_Qt(t,n)?n.toString():AL(t)}catch{return AL(t)}return/^(localhost|\d{1,3}(?:\.\d{1,3}){3})(:\d+)?(\/.*)?$/i.test(t)?`http://${t}`:/^[a-z][a-z0-9+.-]*:/i.test(t)||/\s/.test(t)?AL(t):t.includes(".")?`https://${t}`:AL(t)}function a6(e=Mv,t={newTab:!0}){return{kind:"browser",url:e,label:A5(e),tabId:PQt(),...t.favicon?{favicon:t.favicon}:{},...t.newTab===!1?{dedupeKey:IQt(e)}:{}}}const dY=[.25,.33,.5,.67,.75,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3,4,5],SVe="rudder.browser.side-panel-onboarding.dismissed.v1",jVe="rudder.browser.side-panel-onboarding.session-dismissed.v1",uY="rudder:browser-side-panel-onboarding-dismissed";function EQt(){if(typeof window>"u")return!0;try{if(window.localStorage.getItem(SVe)==="true")return!0}catch{}try{return window.sessionStorage.getItem(jVe)==="true"}catch{return!1}}function DQt(e){if(typeof e!="string")return null;const t=e.trim();if(!t||t.length>GM)return null;if(t.startsWith("data:image/"))return t;try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?t:null}catch{return null}}function CVe({active:e,canOpenNewTab:t,surface:n,target:r,targetKey:s,onOpenBrowserSettings:a,onOpenTarget:o,onReplaceTarget:l,onCloseTarget:c,onCycleTab:d,onWebContentsIdChange:u,onRegisterShortcutController:f}){const{t:A}=is(),m=h.useRef(null),g=h.useRef(null),x=h.useRef(!1),y=h.useRef(r.url),v=h.useRef(r.url),w=h.useRef(r),k=h.useRef(l),S=h.useRef(c),j=h.useRef(d),C=h.useRef(u),N=h.useRef(e),P=h.useRef(null),[M,E]=h.useState(null),T=h.useRef(1),[R,_]=h.useState(r.url===Mv?"":r.url),[D,U]=h.useState(r.url),[$,L]=h.useState(r.url),[H,X]=h.useState(!1),[F,Q]=h.useState({canGoBack:!1,canGoForward:!1}),[q,B]=h.useState(null),[ee,se]=h.useState(!1),[re,ne]=h.useState(()=>!EQt()),Ae=D===Mv,Y=q?CQt(q):null;v.current=D,w.current=r,k.current=l,S.current=c,j.current=d,C.current=u,N.current=e;const ce=h.useCallback((me,we)=>{const Xe=g.current;if(!x.current||!Xe||Xe.tagName.toLowerCase()!=="webview")return we;try{return me(Xe)}catch{return we}},[]),Oe=h.useCallback(me=>ce(we=>{var Xe;return((Xe=we.getURL)==null?void 0:Xe.call(we))??me},me),[ce]),Fe=h.useCallback(()=>{Q({canGoBack:ce(me=>{var we;return!!((we=me.canGoBack)!=null&&we.call(me))},!1),canGoForward:ce(me=>{var we;return!!((we=me.canGoForward)!=null&&we.call(me))},!1)})},[ce]),ke=h.useCallback(me=>{ce(Xe=>Xe.setZoomFactor?(Xe.setZoomFactor(me),!0):!1,!1)&&(T.current=me)},[ce]),Ne=h.useCallback(me=>{const we=T.current;let Xe=0,ge=Number.POSITIVE_INFINITY;dY.forEach((G,oe)=>{const Ze=Math.abs(G-we);Ze<ge&&(ge=Ze,Xe=oe)});const te=Math.max(0,Math.min(dY.length-1,Xe+me));ke(dY[te]??1)},[ke]),xe=h.useCallback(me=>{var we,Xe;if(e)switch(me){case"new_tab":t&&o(a6());return;case"focus_location":(we=m.current)==null||we.focus(),(Xe=m.current)==null||Xe.select();return;case"reload":Ae||ce(ge=>{var te;return(te=ge.reload)==null?void 0:te.call(ge)},void 0);return;case"reload_ignoring_cache":Ae||ce(ge=>{var te;return(te=ge.reloadIgnoringCache)==null?void 0:te.call(ge)},void 0);return;case"go_back":Ae||ce(ge=>{var te,G;(te=ge.canGoBack)!=null&&te.call(ge)&&((G=ge.goBack)==null||G.call(ge))},void 0);return;case"go_forward":Ae||ce(ge=>{var te,G;(te=ge.canGoForward)!=null&&te.call(ge)&&((G=ge.goForward)==null||G.call(ge))},void 0);return;case"zoom_in":Ae||Ne(1);return;case"zoom_out":Ae||Ne(-1);return;case"zoom_reset":Ae||ke(1)}},[e,ke,t,Ae,o,ce,Ne]);P.current=xe,h.useEffect(()=>(f(s,xe),()=>f(s,null)),[xe,f,s]);const ae=h.useCallback((me,we=A5(me))=>{const Xe=w.current.url!==me,ge={...w.current,url:me,label:we,favicon:Xe?void 0:w.current.favicon};v.current=me,w.current=ge,U(me),_(me===Mv?"":me),y.current=me,k.current(s,ge)},[s]);h.useEffect(()=>{const me=y.current!==r.url;y.current=r.url,v.current=r.url,w.current=r,U(r.url),_(r.url===Mv?"":r.url),me&&(L(r.url),B(null),se(!1)),x.current?Fe():Q({canGoBack:!1,canGoForward:!1})},[r.label,r.url,Fe]),h.useEffect(()=>{const me=M;if(!me||me.tagName.toLowerCase()!=="webview")return;const we=()=>{X(!0),B(null),se(!1)},Xe=it=>{const lt=!("isMainFrame"in it)||it.isMainFrame!==!1,Ue="url"in it&&typeof it.url=="string"?it.url:"";lt&&Ue&&Ue!==v.current&&ae(Ue,A5(Ue))},ge=()=>{X(!1);const it=Oe("");it&&it!==v.current&&ae(it,A5(it)),Fe()},te=it=>{const lt="url"in it&&typeof it.url=="string"?it.url:Oe("");lt&&ae(lt,A5(lt)),Fe()},G=it=>{const lt=Oe(v.current),Ue="title"in it&&typeof it.title=="string"&&it.title.trim()?it.title.trim():A5(lt),mt={...w.current,url:lt,label:Ue};w.current=mt,k.current(s,mt)},oe=it=>{const Ue=("favicons"in it&&Array.isArray(it.favicons)?it.favicons:[]).map(DQt).find(tt=>!!tt);if(!Ue||Ue===w.current.favicon)return;const mt={...w.current,favicon:Ue};w.current=mt,k.current(s,mt)},Ze=it=>{const lt="errorDescription"in it&&typeof it.errorDescription=="string"?it.errorDescription:"Could not load this page.",Ue="validatedURL"in it&&typeof it.validatedURL=="string"&&it.validatedURL?it.validatedURL:v.current;(!("isMainFrame"in it)||it.isMainFrame!==!1)&&lt!=="ERR_ABORTED"&&(X(!1),B({code:lt,url:Ue}),se(!1)),Fe()},Te=()=>{var lt,Ue;x.current=!0;const it=(lt=me.getWebContentsId)==null?void 0:lt.call(me);typeof it=="number"&&Number.isFinite(it)&&((Ue=C.current)==null||Ue.call(C,it)),T.current!==1&&ce(mt=>{var tt;return(tt=mt.setZoomFactor)==null?void 0:tt.call(mt,T.current)},void 0),Fe()},Be=it=>{var dt,at;const lt=it,Ue=lt.input;if(Ue&&Ue.type!=="keyUp"&&(Ue.key==="Tab"||Ue.code==="Tab")&&!!Ue.control&&!Ue.meta&&!Ue.alt&&N.current&&j.current){it.preventDefault(),j.current(Ue.shift?-1:1);return}if((dt=Pn())!=null&&dt.onBrowserShortcut)return;if(NQt(lt.input)){it.preventDefault(),S.current(w.current);return}if(!lt.input||!N.current)return;const tt=fze(lt.input,{isMac:navigator.platform.toLowerCase().includes("mac")});tt&&(it.preventDefault(),(at=P.current)==null||at.call(P,tt))};return me.addEventListener("dom-ready",Te),me.addEventListener("before-input-event",Be),me.addEventListener("did-start-loading",we),me.addEventListener("did-start-navigation",Xe),me.addEventListener("did-stop-loading",ge),me.addEventListener("did-navigate",te),me.addEventListener("did-navigate-in-page",te),me.addEventListener("page-title-updated",G),me.addEventListener("page-favicon-updated",oe),me.addEventListener("did-fail-load",Ze),Fe(),()=>{me.removeEventListener("dom-ready",Te),me.removeEventListener("before-input-event",Be),me.removeEventListener("did-start-loading",we),me.removeEventListener("did-start-navigation",Xe),me.removeEventListener("did-stop-loading",ge),me.removeEventListener("did-navigate",te),me.removeEventListener("did-navigate-in-page",te),me.removeEventListener("page-title-updated",G),me.removeEventListener("page-favicon-updated",oe),me.removeEventListener("did-fail-load",Ze)}},[ae,Oe,ce,s,Fe,M]);const fe=h.useCallback(me=>{g.current=me,x.current=!1,E(me),me||Q({canGoBack:!1,canGoForward:!1})},[]);h.useEffect(()=>()=>{var me;(me=C.current)==null||me.call(C,null)},[]),h.useEffect(()=>{const me=()=>ne(!1);return window.addEventListener(uY,me),()=>{window.removeEventListener(uY,me)}},[]);const ve=()=>{ne(!1);try{window.localStorage.setItem(SVe,"true")}catch{}try{window.sessionStorage.setItem(jVe,"true")}catch{}window.dispatchEvent(new Event(uY))},Se=h.useCallback(me=>{const we=MQt(me);B(null),se(!1),L(we),ae(we,A5(we))},[ae]),ze=h.useCallback(()=>{se(!1),ce(me=>{var we;(we=me.reload)==null||we.call(me)},void 0)},[ce]),ft=me=>{me.preventDefault();const Xe=new FormData(me.currentTarget).get("browser-url");Se(typeof Xe=="string"?Xe:R)},ie=()=>{var we;if(Ae)return;const me=Pn();if(me){((we=me.forceOpenExternal)==null?void 0:we.call(me,D))??me.openExternal(D);return}window.open(D,"_blank","noopener,noreferrer")};return i.jsxs("div",{className:"flex min-h-full flex-col bg-[color:var(--surface-elevated)]","data-testid":e?"chat-side-panel-browser-view":"chat-side-panel-browser-view-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",children:[i.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-[color:var(--border-soft)] bg-[color:var(--surface-elevated)] px-2 py-2","data-testid":"chat-side-panel-browser-toolbar",children:[i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Back",disabled:!F.canGoBack,onClick:()=>ce(me=>{var we;(we=me.goBack)==null||we.call(me)},void 0),children:i.jsx(Kx,{className:"h-3.5 w-3.5"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Forward",disabled:!F.canGoForward,onClick:()=>ce(me=>{var we;(we=me.goForward)==null||we.call(me)},void 0),children:i.jsx(Y4,{className:"h-3.5 w-3.5"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Reload",disabled:Ae,onClick:ze,children:i.jsx(M2,{className:K("h-3.5 w-3.5",H&&"animate-spin")})}),i.jsx("form",{className:"min-w-0 flex-1",onSubmit:ft,children:i.jsx(Kn,{ref:m,"aria-label":"Browser URL",name:"browser-url",value:R,onChange:me=>_(me.currentTarget.value),placeholder:"Enter a URL",className:"h-8 rounded-[var(--radius-md)] bg-[color:var(--surface-inset)] font-mono text-xs"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open new browser tab",title:t?"Open new browser tab":"Browser tab limit reached",disabled:!t,onClick:()=>o(a6()),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open browser page externally",disabled:Ae,onClick:ie,children:i.jsx(Ja,{className:"h-3.5 w-3.5"})})]}),i.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col bg-[color:var(--surface-inset)]","data-testid":"chat-side-panel-browser-content",children:[e&&n==="side_panel"&&re?i.jsx(xVe,{testId:"browser-side-panel-onboarding",className:"absolute right-3 top-3 z-20 w-[min(24rem,calc(100%-1.5rem))] shadow-[var(--shadow-lg)]",icon:i.jsx(Xfe,{"aria-hidden":"true"}),title:A("browser.onboarding.title"),description:A("browser.onboarding.description"),stackActions:!0,actions:i.jsxs(i.Fragment,{children:[a?i.jsx(le,{type:"button",variant:"outline",size:"sm",onClick:()=>{ve(),a()},children:A("browser.onboarding.settings")}):null,i.jsx(le,{type:"button",size:"sm",onClick:ve,children:A("browser.onboarding.dismiss")})]})}):null,Ae?i.jsx("div",{className:"flex min-h-[44vh] flex-1 items-center justify-center px-6 text-center","data-testid":"chat-side-panel-browser-start",children:i.jsxs("div",{className:"max-w-[18rem]",children:[i.jsx(up,{className:"mx-auto h-12 w-12 text-muted-foreground"}),i.jsx("h3",{className:"mt-4 text-base font-semibold text-foreground",children:"Start browsing"}),i.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Enter a URL to open a page."})]})}):i.jsxs("div",{className:"relative flex min-h-[52vh] flex-1",children:[h.createElement("webview",{ref:fe,src:$,className:K("min-h-[52vh] flex-1 bg-[color:var(--surface-elevated)]",q&&"invisible"),"data-testid":e?"chat-side-panel-browser-webview":"chat-side-panel-browser-webview-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",allowpopups:"true"}),q?i.jsx("div",{role:"alert","data-testid":"chat-side-panel-browser-error",className:"absolute inset-0 flex overflow-y-auto bg-[color:var(--surface-elevated)] px-8 py-10",children:i.jsxs("div",{className:"m-auto w-full max-w-[32rem]",children:[i.jsx(Xjt,{className:"h-12 w-12 text-muted-foreground","aria-hidden":"true"}),i.jsx("h3",{className:"mt-6 text-xl font-semibold text-foreground",children:"This site can't be reached"}),i.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:Y==null?void 0:Y.summary}),i.jsxs("div",{className:"mt-5 text-sm text-muted-foreground",children:[i.jsx("p",{children:"Try:"}),i.jsx("ul",{className:"mt-2 list-disc space-y-1 pl-6",children:Y==null?void 0:Y.suggestions.map(me=>i.jsx("li",{children:me},me))})]}),i.jsx("p",{className:"mt-5 font-mono text-xs text-muted-foreground",children:q.code}),ee?i.jsx("p",{className:"mt-4 break-all rounded-[var(--radius-md)] border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] px-3 py-2 font-mono text-xs text-muted-foreground",children:q.url}):null,i.jsxs("div",{className:"mt-7 flex items-center justify-between gap-3",children:[i.jsx(le,{type:"button",variant:"outline",size:"sm","aria-expanded":ee,onClick:()=>se(me=>!me),children:"Details"}),i.jsxs(le,{type:"button",size:"sm",onClick:ze,children:[i.jsx(M2,{className:"h-3.5 w-3.5"}),"Reload"]})]})]})}):null]})]})]})}function Df(e,t){return(e==null?void 0:e.trim())||t}function AQ(e,t){return e.split("/").filter(Boolean).at(-1)??t}function NVe(e){try{return new URL(e,"http://rudder.local")}catch{return null}}function PVe(e){return(e.searchParams.get("messageId")??e.searchParams.get("targetMessageId")??"").trim()||null}function RQt(e){const t=decodeURIComponent(e.hash.replace(/^#/,"")).trim();return t.startsWith("comment-")&&t.slice(8).trim()||null}function wie(e){return e.kind==="issue"?`issue:${e.issueId}:${e.commentId??""}`:e.kind==="issue_proposal"?`issue-proposal:${e.conversationId}:${e.messageId}`:e.kind==="automation"?`automation:${e.automationId}`:e.kind==="chat"?`chat:${e.conversationId}:${e.messageId??""}`:e.kind==="subagents"?`subagents:${e.conversationId}`:e.kind==="subagent"?`subagent:${e.threadId}`:e.kind==="side_chat"?e.conversationId?`side-chat:${e.conversationId}`:`side-chat:draft:${e.clientMutationId}`:e.kind==="run_feedback_chat"?`run-feedback-chat:${e.organizationId}:${e.agentId}`:e.kind==="library_document"?`library-document:${e.documentId}`:e.kind==="library_entry"?`library-entry:${e.entryId}:${e.path??""}`:e.kind==="library_file"?`library-file:${e.filePath}`:e.kind==="local_file"?`local-file:${e.filePath}`:e.kind==="organization_skill_file"?`organization-skill-file:${e.skillId}:${e.filePath}`:e.kind==="local_apps"?"local-apps":e.kind==="local_app"?`local-app:${encodeURIComponent(e.desktopInstallationId)}:${encodeURIComponent(e.appPublicId)}:${encodeURIComponent(e.localBindingId)}`:e.kind==="library_directory"?`library-directory:${e.directoryPath}`:e.kind==="browser"?`browser-tab:${e.tabId}`:`placeholder:${e.targetKind}`}function Kf(e){return e.kind==="automation"||e.kind==="library_document"||e.kind==="library_entry"||e.kind==="library_file"||e.kind==="library_directory"||e.kind==="browser"||e.kind==="local_app"}function ps(e){const t=wie(e);return e.kind==="browser"||!Kf(e)||!e.viewInstanceId?t:`${t}:view:${e.viewInstanceId}`}function LQt(e,t){var l,c,d;const n=NVe(e);if(!n||n.origin!=="http://rudder.local")return null;const r=n.pathname.split("/").filter(Boolean).map(u=>{try{return decodeURIComponent(u)}catch{return u}}),s=r.length>=2&&r.at(-2)==="issues"?(l=r.at(-1))==null?void 0:l.trim():"";if(s)return{kind:"issue",issueId:s,ref:(t==null?void 0:t.trim())||null,commentId:RQt(n),label:Df(t,"Issue")};const a=r.length>=2&&r.at(-2)==="automations"?(c=r.at(-1))==null?void 0:c.trim():"";if(a)return{kind:"automation",automationId:a,label:Df(t,n.searchParams.get("t")??n.searchParams.get("title")??"Automation")};const o=r.length>=2&&r.at(-2)==="chat"?(d=r.at(-1))==null?void 0:d.trim():"";if(o)return{kind:"chat",conversationId:o,messageId:PVe(n),label:Df(t,"Chat")};if(r.at(-1)==="library"){const u=(n.searchParams.get("skill")??"").trim();if(u)return{kind:"organization_skill_file",skillId:u,filePath:(n.searchParams.get("skillFile")??"SKILL.md").trim()||"SKILL.md",label:Df(t,"Skill")};const f=(n.searchParams.get("document")??n.searchParams.get("doc")??"").trim();if(f)return{kind:"library_document",documentId:f,label:Df(t,n.searchParams.get("t")??n.searchParams.get("title")??"Library document")};const A=(n.searchParams.get("path")??"").trim();if(A)return{kind:"library_file",filePath:A,label:Df(t,AQ(A,"Library file"))};const m=(n.searchParams.get("directory")??"").trim();if(m)return{kind:"library_directory",directoryPath:m,label:Df(t,AQ(m,"Library directory"))};const g=(n.searchParams.get("entry")??"").trim();if(g)return{kind:"library_entry",entryId:g,path:A||null,label:Df(t,g)}}return null}function zQt(e,t){const n=ac(e);if(!n)return LQt(e,t);if(n.kind==="issue")return{kind:"issue",issueId:n.issueId,ref:n.ref??(t==null?void 0:t.trim())??null,commentId:n.commentId,label:Df(t,n.ref??"Issue")};if(n.kind==="automation")return{kind:"automation",automationId:n.automationId,label:Df(t,n.title??"Automation")};if(n.kind==="chat"){const r=NVe(e);return{kind:"chat",conversationId:n.conversationId,messageId:r?PVe(r):null,label:Df(t,n.title??"Chat")}}return n.kind==="library_doc"?{kind:"library_document",documentId:n.documentId,label:Df(t,n.title??"Library document")}:n.kind==="library_entry"?{kind:"library_entry",entryId:n.entryId,path:n.path,label:Df(t,n.title??n.path??"Library entry")}:n.kind==="library_file"?{kind:"library_file",filePath:n.filePath,label:Df(t,n.title??AQ(n.filePath,"Library file"))}:n.kind==="library_directory"?{kind:"library_directory",directoryPath:n.directoryPath,label:Df(t,n.title??AQ(n.directoryPath,"Library directory"))}:null}const $Qt=h.lazy(async()=>({default:(await Wt(async()=>{const{AutomationDetail:e}=await Promise.resolve().then(()=>$Rn);return{AutomationDetail:e}},void 0)).AutomationDetail})),FQt=h.lazy(async()=>({default:(await Wt(async()=>{const{LibraryLiveSurface:e}=await import("./LibraryLiveSurface-CcsYG18H.js");return{LibraryLiveSurface:e}},[])).LibraryLiveSurface})),YAe=h.createContext(null);function hQ(e){var n;const t=((n=e.viewInstanceId)==null?void 0:n.trim())||(e.kind==="browser"?e.tabId.trim():"");if(!t)throw new Error(`${e.kind} live surface requires a viewInstanceId`);return t}function gT(e,t){return JSON.stringify([e.trim(),t.kind,hQ(t)])}function IVe(e){try{const t=JSON.parse(e);return Array.isArray(t)&&typeof t[0]=="string"?t[0]:""}catch{return""}}function fY(e,t){return e.kind===t.kind&&hQ(e)===hQ(t)}function kie(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,l)=>kie(o,t[l]));const n=e,r=t,s=Object.keys(n).filter(o=>n[o]!==void 0),a=Object.keys(r).filter(o=>r[o]!==void 0);return s.length===a.length&&s.every(o=>Object.hasOwn(r,o)&&kie(n[o],r[o]))}function TVe(e){return e.startsWith("main:")?"workbench":"side_panel"}function Oie(e){if(!_Ve(e))return!1;const t=e.element.getBoundingClientRect();return t.width>0&&t.height>0}function _Ve(e){return!!(e!=null&&e.active&&e.element.isConnected)}function BQt({children:e}){const t=h.useRef(new Map),n=h.useRef(new Map),[r,s]=h.useState(0),a=h.useCallback(()=>{s(T=>T+1)},[]),o=h.useCallback(T=>{const R=t.current.get(T.runtimeId);if(R&&!fY(R.target,T.target))return()=>{};const _=R??{interactionLocked:!1,leaseOwnerId:null,owners:new Map,renderSurface:T.renderSurface??null,runtimeId:T.runtimeId,shortcutController:null,target:T.target,webContentsId:null};return _.owners.set(T.ownerId,T),T.renderSurface&&(_.renderSurface=T.renderSurface),t.current.set(T.runtimeId,_),a(),()=>{const D=t.current.get(T.runtimeId);D&&(D.owners.delete(T.ownerId),D.leaseOwnerId===T.ownerId&&(D.leaseOwnerId=null),a())}},[a]),l=h.useCallback(T=>{const R=t.current.get(T.runtimeId);if(!R||!fY(R.target,T.target))return;const _=R.owners.get(T.ownerId);if(!_)return;const D=!kie(_.target,T.target);(_.active!==T.active||_.callbacks!==T.callbacks||_.element!==T.element||_.hostId!==T.hostId||_.renderSurface!==T.renderSurface||D)&&(R.owners.set(T.ownerId,T),D&&R.leaseOwnerId===T.ownerId&&!R.interactionLocked&&(R.target=T.target),T.renderSurface&&(R.renderSurface=T.renderSurface),a())},[a]),c=h.useCallback((T,R)=>{const _=t.current.get(T),D=_==null?void 0:_.owners.get(R);return!_||!Oie(D)?!1:(_.leaseOwnerId===R||(_.leaseOwnerId=R,a()),!0)},[a]),d=h.useCallback((T,R)=>{const _=t.current.get(T),D=_==null?void 0:_.owners.get(R);return!_||!_Ve(D)||_.leaseOwnerId&&_.leaseOwnerId!==R?!1:(_.leaseOwnerId===R||(_.leaseOwnerId=R,a()),!0)},[a]),u=h.useCallback(async(T,R,_=5e3)=>{var U;const D=Date.now();for(;Date.now()-D<=_;){const $=(U=t.current.get(T))==null?void 0:U.owners.get(R);if(Oie($))return!0;await new Promise(L=>{window.setTimeout(L,16)})}return!1},[]),f=h.useCallback((T,R)=>{const _=t.current.get(T);!_||_.interactionLocked===R||(_.interactionLocked=R,a())},[a]),A=h.useCallback((T,R)=>{const _=t.current.get(T);return!_||!fY(_.target,R)?!1:(_.target=R,a(),!0)},[a]),m=h.useCallback(T=>{const R=t.current.get(T);R&&(R.webContentsId!==null&&n.current.delete(R.webContentsId),t.current.delete(T),a())},[a]),g=h.useCallback((T,R)=>{const _=t.current.get(T);!_||_.webContentsId===R||(_.webContentsId!==null&&n.current.delete(_.webContentsId),_.webContentsId=R,R!==null&&n.current.set(R,T))},[]),x=h.useCallback(T=>{const R=n.current.get(T),_=R?t.current.get(R):null,D=_!=null&&_.leaseOwnerId?_.owners.get(_.leaseOwnerId):null;return!_||!D?null:{hostId:D.hostId,ownerId:D.ownerId,runtimeId:_.runtimeId,surface:TVe(D.ownerId),targetKind:_.target.kind}},[]),y=h.useCallback((T,R)=>{const _=n.current.get(T),D=_?t.current.get(_):null,U=D!=null&&D.leaseOwnerId?D.owners.get(D.leaseOwnerId):null;return U!=null&&U.callbacks.onOpenTarget?(U.callbacks.onOpenTarget(R),!0):!1},[]),v=h.useCallback(T=>{const R=t.current.get(T),_=R!=null&&R.leaseOwnerId?R.owners.get(R.leaseOwnerId):null;return!R||!(_!=null&&_.callbacks.onCloseTarget)?!1:(_.callbacks.onCloseTarget(R.target),!0)},[]),w=h.useCallback(T=>{const R=n.current.get(T);return R?v(R):!1},[v]),k=h.useCallback((T,R)=>{const _=t.current.get(T);!_||_.target.kind!=="browser"||(_.shortcutController=R)},[]),S=h.useCallback((T,R)=>{const _=t.current.get(T);return!_||_.target.kind!=="browser"||!_.leaseOwnerId||!_.shortcutController?!1:(_.shortcutController(R),!0)},[]),j=h.useCallback((T,R)=>{const _=n.current.get(T);return _?S(_,R):!1},[S]),C=h.useCallback(T=>Array.from(t.current.values()).filter(R=>R.target.kind==="browser"&&IVe(R.runtimeId)===T).length,[]),N=h.useCallback(T=>{var R;return((R=t.current.get(T))==null?void 0:R.target)??null},[]),P=h.useCallback(T=>t.current.has(T),[]),M=h.useCallback(()=>Array.from(t.current.values()),[]),E=h.useMemo(()=>({autoClaimSurface:d,claimSurface:c,closeTargetForGuest:w,closeTargetForRuntime:v,dispatchBrowserShortcutForGuest:j,dispatchBrowserShortcutForRuntime:S,disposeSurface:m,getGuestOwner:x,getLiveBrowserCount:C,getRuntimeTarget:N,hasSurface:P,listRecords:M,openTargetForGuest:y,registerBrowserShortcutController:k,registerOwner:o,registerWebContentsId:g,revision:r,setInteractionLocked:f,updateOwner:l,updateTarget:A,waitForOwner:u}),[d,c,w,v,j,S,m,x,C,N,P,M,y,k,o,g,r,f,l,A,u]);return i.jsx(YAe.Provider,{value:E,children:e})}function jE(){const e=h.useContext(YAe);if(!e)throw new Error("useLiveSurfaceRuntime must be used inside LiveSurfaceRuntimeProvider");return e}function JAe(){return h.useContext(YAe)}function MVe({active:e,autoClaim:t=!0,callbacks:n={},hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l,...c}){const{autoClaimSurface:d,registerOwner:u,updateOwner:f}=jE(),A=h.useRef(null),m=h.useRef(n);m.current=n;const g=h.useMemo(()=>({get annotationConversationId(){return m.current.annotationConversationId},get canOpenNewTab(){return m.current.canOpenNewTab},get savedViewId(){return m.current.savedViewId},onCloseTarget:x=>{var y,v;return(v=(y=m.current).onCloseTarget)==null?void 0:v.call(y,x)},onCycleTab:x=>{var y,v;return(v=(y=m.current).onCycleTab)==null?void 0:v.call(y,x)},onLocalAppTitleChange:x=>{var y,v;return(v=(y=m.current).onLocalAppTitleChange)==null?void 0:v.call(y,x)},onOpenBrowserSettings:()=>{var x,y;return(y=(x=m.current).onOpenBrowserSettings)==null?void 0:y.call(x)},onOpenTarget:x=>{var y,v;return(v=(y=m.current).onOpenTarget)==null?void 0:v.call(y,x)},onRegisterShortcutController:(x,y)=>{var v,w;return(w=(v=m.current).onRegisterShortcutController)==null?void 0:w.call(v,x,y)},onReplaceTarget:x=>{var y,v;return(v=(y=m.current).onReplaceTarget)==null?void 0:v.call(y,x)}}),[]);return h.useLayoutEffect(()=>{const x=A.current;if(x)return u({active:e,callbacks:g,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l})},[r,s,u,o]),h.useLayoutEffect(()=>{const x=A.current;if(!x)return;f({active:e,callbacks:g,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l}),e&&t&&d(o,s)},[e,t,d,r,s,a,o,g,l,f]),i.jsx("div",{...c,ref:A,"data-owner-id":s})}function QQt({record:e,owner:t,visible:n}){var f;const r=jE(),s=e.target,a=t==null?void 0:t.callbacks,o=t?TVe(t.ownerId):"side_panel",l=A=>{var m;(m=a==null?void 0:a.onCloseTarget)==null||m.call(a,A)},c=A=>{var m;(m=a==null?void 0:a.onOpenTarget)==null||m.call(a,A)},d=A=>{var m;(A.kind==="automation"||A.kind==="browser"||A.kind==="library_directory"||A.kind==="library_document"||A.kind==="library_entry"||A.kind==="library_file"||A.kind==="local_app")&&r.updateTarget(e.runtimeId,A),e.interactionLocked||(m=a==null?void 0:a.onReplaceTarget)==null||m.call(a,A)},u=(f=e.renderSurface)==null?void 0:f.call(e,{active:n,closeTarget:l,openTarget:c,replaceTarget:d,surface:o,target:s});return s.kind==="browser"?i.jsx(CVe,{active:n,canOpenNewTab:(a==null?void 0:a.canOpenNewTab)??!1,surface:o,target:s,targetKey:ps(s),onCloseTarget:l,onCycleTab:a==null?void 0:a.onCycleTab,onOpenBrowserSettings:a==null?void 0:a.onOpenBrowserSettings,onOpenTarget:c,onRegisterShortcutController:(A,m)=>{var g;r.registerBrowserShortcutController(e.runtimeId,m),(g=a==null?void 0:a.onRegisterShortcutController)==null||g.call(a,A,m)},onReplaceTarget:(A,m)=>d(m),onWebContentsIdChange:A=>{r.registerWebContentsId(e.runtimeId,A)}}):s.kind==="local_app"?i.jsx(gVe,{active:n,savedViewId:a==null?void 0:a.savedViewId,target:s,onTitleChange:a==null?void 0:a.onLocalAppTitleChange}):u!==void 0?i.jsx(i.Fragment,{children:u}):s.kind==="automation"?i.jsx(h.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx($Qt,{automationId:s.automationId,onClose:()=>l(s),surface:o})}):i.jsx(h.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx(FQt,{active:n,annotationConversationId:a==null?void 0:a.annotationConversationId,organizationId:IVe(e.runtimeId),onOpenTarget:c,surface:o,target:s})})}function UQt(){const e=jE(),t=e.listRecords(),[,n]=h.useState(0);return h.useEffect(()=>{const r=()=>n(a=>a+1);window.addEventListener("resize",r),window.addEventListener("scroll",r,!0);const s=typeof ResizeObserver>"u"?null:new ResizeObserver(r);for(const a of e.listRecords())for(const o of a.owners.values())s==null||s.observe(o.element);return()=>{window.removeEventListener("resize",r),window.removeEventListener("scroll",r,!0),s==null||s.disconnect()}},[e]),i.jsx("div",{className:"pointer-events-none fixed inset-0","data-testid":"live-surface-runtime-layer","aria-label":"Live workspace surfaces",children:t.map(r=>{const s=r.leaseOwnerId?r.owners.get(r.leaseOwnerId)??null:null,a=Oie(s),o=a?s.element.getBoundingClientRect():null,l=!a||r.interactionLocked;return i.jsx("div",{"data-testid":"live-surface-runtime-host","data-host-id":s==null?void 0:s.hostId,"data-owner-id":s==null?void 0:s.ownerId,"data-runtime-id":r.runtimeId,"data-target-kind":r.target.kind,"data-view-instance-id":hQ(r.target),"aria-hidden":!a,hidden:!a,inert:l?!0:void 0,className:`fixed flex min-h-0 flex-col overflow-hidden bg-[color:var(--surface-panel)] ${s!=null&&s.ownerId.startsWith("side:")?"rounded-[var(--desktop-workspace-radius)]":s!=null&&s.ownerId.startsWith("main:")?r.target.kind==="browser"?"rounded-[var(--desktop-workspace-radius)]":"rounded-b-[var(--desktop-workspace-radius)]":""}`,style:{height:o?`${o.height}px`:"0px",left:o?`${o.left}px`:"0px",pointerEvents:l?"none":"auto",top:o?`${o.top}px`:"0px",width:o?`${o.width}px`:"0px",zIndex:s!=null&&s.ownerId.startsWith("side:")?70:40},children:i.jsx(QQt,{record:r,owner:s,visible:a&&!r.interactionLocked})},r.runtimeId)})})}const W7=[{actionId:"commandPalette.open",label:"Open command palette",description:"Search and jump across Rudder.",scope:"Global",defaultBindings:[{key:"k",code:"KeyK",metaKey:!0},{key:"k",code:"KeyK",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"k",code:"KeyK",metaKey:!0}],nonMac:[{key:"k",code:"KeyK",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"settings.open",label:"Open settings",description:"Open System Settings.",scope:"Global",defaultBindings:[{key:",",metaKey:!0},{key:",",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:",",metaKey:!0}],nonMac:[{key:",",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"chat.create",label:"New chat",description:"Open the new chat composer.",scope:"Global",defaultBindings:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0},{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}],defaultBindingsByPlatform:{mac:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0}],nonMac:[{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}]},configurable:!0,disableable:!0},{actionId:"issue.create",label:"Create issue",description:"Open the new issue dialog.",scope:"Global",defaultBindings:[{key:"n",code:"KeyN",metaKey:!0},{key:"n",code:"KeyN",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"n",code:"KeyN",metaKey:!0}],nonMac:[{key:"n",code:"KeyN",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"sidebar.toggle",label:"Toggle sidebar",description:"Show or hide the workspace sidebar.",scope:"Global",defaultBindings:[{key:"["}],configurable:!0,disableable:!0},{actionId:"panel.toggle",label:"Toggle panel",description:"Show or hide the context panel.",scope:"Global",defaultBindings:[{key:"]"}],configurable:!0,disableable:!0},{actionId:"system.escapeBack",label:"Navigate back / close detail",description:"System Escape behavior is read-only in this version.",scope:"System",defaultBindings:[{key:"Escape"}],configurable:!1,disableable:!1}],VQt=new Set(W7.filter(e=>e.configurable).map(e=>e.actionId)),qQt=new Set(["Alt","Control","Meta","Shift"]),I5e=new Set(["meta+n","meta+shift+o"]);function CE(){var n,r,s;if(typeof navigator>"u")return"nonMac";const e=navigator,t=((r=(n=e.userAgentData)==null?void 0:n.platform)==null?void 0:r.trim())||((s=e.platform)==null?void 0:s.trim())||"";return/mac|iphone|ipad|ipod/i.test(t)?"mac":"nonMac"}function EVe(e,t=CE()){var n;return(((n=e.defaultBindingsByPlatform)==null?void 0:n[t])??e.defaultBindings).map(H6)}function DVe(e){return e.length===1?e.toLowerCase():e}function H6(e){return{key:DVe(e.key.trim()),...e.code?{code:e.code.trim()}:{},...e.metaKey?{metaKey:!0}:{},...e.ctrlKey?{ctrlKey:!0}:{},...e.altKey?{altKey:!0}:{},...e.shiftKey?{shiftKey:!0}:{}}}function Sie(e){const t=H6(e);return[t.metaKey?"meta":"",t.ctrlKey?"ctrl":"",t.altKey?"alt":"",t.shiftKey?"shift":"",t.key].filter(Boolean).join("+")}function RVe(e){if(!(e instanceof HTMLElement)||KQt(e))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable||!!e.closest('[contenteditable="true"], [contenteditable="plaintext-only"]')}function KQt(e){let t=e;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!0;const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!0;t=t.parentElement}return!1}function WQt(e){return qQt.has(e.key)?null:H6({key:e.key,code:e.code||void 0,metaKey:e.metaKey,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey})}function ZQt(e,t){const n=H6(t);return(n.code&&e.code?e.code===n.code:DVe(e.key)===n.key)&&e.metaKey===!!n.metaKey&&e.ctrlKey===!!n.ctrlKey&&e.altKey===!!n.altKey&&e.shiftKey===!!n.shiftKey}function ehe(e,t=CE()){const n={};for(const r of W7)VQt.has(r.actionId)&&(n[r.actionId]=EVe(r,t));for(const r of(e==null?void 0:e.shortcuts)??[]){const s=W7.find(a=>a.actionId===r.actionId);if(s!=null&&s.configurable){if(r.disabled===!0){n[r.actionId]=[];continue}if(r.bindings&&r.bindings.length>0){const a=r.bindings.map(H6);if(HQt(r.actionId,a))continue;n[r.actionId]=a}}}return n}function HQt(e,t){return e!=="chat.create"||t.length!==I5e.size?!1:t.every(n=>I5e.has(Sie(n)))}function qk(e,t,n,r){return n===void 0?!1:(ehe(n,r)[t]??[]).some(a=>ZQt(e,a))}function T5e(e,t=CE()){const n=H6(e),r=[];return n.ctrlKey&&r.push(t==="mac"?"⌃":"Ctrl"),n.altKey&&r.push(t==="mac"?"⌥":"Alt"),n.shiftKey&&r.push(t==="mac"?"⇧":"Shift"),n.metaKey&&r.push(t==="mac"?"⌘":"Meta"),r.push(XQt(n.key)),t==="mac"?r.join(""):r.join("+")}function XQt(e){return e===" "?"Space":e==="Escape"?"Esc":e.length===1?e.toUpperCase():e}function GQt(e){const t=H6(e),n=t.key.toLowerCase();return t.metaKey||t.ctrlKey?["l","r","w","q"].includes(n):!1}function YQt(e,t,n,r){const s=Sie(t),a=ehe(n,r);for(const[o,l]of Object.entries(a))if(o!==e&&l.some(c=>Sie(c)===s))return o;return null}function hL(e,t,n){const r=e.shortcuts.filter(s=>s.actionId!==t);return n&&r.push({actionId:t,...n}),{shortcuts:r}}const the=h.createContext(null),tP="global",QP=8;function Gw(e){return(e==null?void 0:e.trim())||tP}function S1(){return{activeKey:null,hasPanelState:!1,open:!1,tabs:[]}}function AY(e){return!!(e&&(e.hasPanelState||e.tabs.length>0||e.activeKey!==null))}function _5e(e){return e instanceof Element&&!!e.closest("[data-testid='messenger-main-workbench'],[data-testid='live-surface-runtime-host'][data-owner-id^='main:']")}function JQt(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`view-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function hY(e,t,n){if(!Kf(t))return t;if(t.kind==="browser")return{...t,viewInstanceId:t.viewInstanceId??t.tabId};if(!n&&t.viewInstanceId)return t;if(!n){const r=wie(t),s=e.find(a=>Kf(a)&&wie(a)===r);if(s&&s.kind!=="browser"&&"viewInstanceId"in s&&s.viewInstanceId)return{...t,viewInstanceId:s.viewInstanceId}}return{...t,viewInstanceId:JQt()}}function M5e(e,t){return{...e,tabId:t.tabId,viewInstanceId:t.viewInstanceId??t.tabId,savedViewRecovery:t.savedViewRecovery??e.savedViewRecovery}}function mY(e,t,n,r=!0){const s=ps(n),a=n.kind==="browser"&&n.dedupeKey?e.find(d=>d.kind==="browser"&&d.dedupeKey===n.dedupeKey):void 0;if(n.kind==="browser"&&(a==null?void 0:a.kind)==="browser"){const d=ps(a),u=M5e(n,a);return{activeKey:d,tabs:e.map(f=>ps(f)===d?u:f),openResult:{admitted:!0}}}const o=e.find(d=>ps(d)===s);if(o){const d=n.kind==="browser"&&o.kind==="browser"?M5e(n,o):n;return{activeKey:s,tabs:e.map(u=>ps(u)===s?d:u),openResult:{admitted:!0}}}const l=[...e,n];if(n.kind!=="browser")return{activeKey:s,tabs:l,openResult:{admitted:!0}};const c=e.filter(d=>d.kind==="browser").length;return r&&c<QP?{activeKey:s,tabs:l,openResult:{admitted:!0}}:{activeKey:t,tabs:e,openResult:{admitted:!1,reason:"browser_capacity"}}}function jie(e){var t;return((t=e.viewInstanceId)==null?void 0:t.trim())||e.tabId.trim()}function pY(e){const t=new Set;for(const n of Object.values(e))for(const r of n.tabs)r.kind==="browser"&&t.add(jie(r));return t}function eUt(e,t,n){const r=e.activeKey?e.tabs.findIndex(l=>ps(l)===e.activeKey):-1,s=e.tabs.filter(l=>l.kind!=="browser"||(n==null?void 0:n(t,l))==="preserve");if(s.length===e.tabs.length)return e;const a=e.activeKey!==null&&s.some(l=>ps(l)===e.activeKey),o=s[Math.min(Math.max(r,0),s.length-1)]??s.at(-1)??null;return{...e,activeKey:e.activeKey===null?null:a?e.activeKey:o?ps(o):null,tabs:s}}function tUt({children:e}){const t=h.useRef({[tP]:S1()}),n=h.useRef({[tP]:{}}),r=h.useRef(tP),[s,a]=h.useState(tP),[o,l]=h.useState(()=>S1()),[c,d]=h.useState(null),[u,f]=h.useState(!1),A=h.useRef(null),m=h.useRef(null),g=h.useCallback((B,ee)=>{const se=t.current[B]??S1(),re=ee(se);if(re!==se){const ne=new Map(se.tabs.map(ce=>[ps(ce),ce])),Ae=n.current[B]??{},Y={...Ae};for(const ce of re.tabs){const Oe=ps(ce),Fe=ne.get(Oe),ke=Ae[Oe]??0;Y[Oe]=Fe?Fe!==ce?ke+1:ke:Object.hasOwn(Ae,Oe)?ke+1:0}n.current={...n.current,[B]:Y}}return t.current={...t.current,[B]:re},B===r.current&&l(re),re},[]),x=h.useCallback(B=>{const ee=Gw(B);if(r.current===ee)return;const se=t.current[ee]??S1();r.current=ee,l(se),f(AY(se)&&se.open),a(re=>re===ee?re:ee)},[]),y=h.useCallback((B,ee)=>{let se={admitted:!0};return g(s,re=>{const ne=pY(t.current),Ae=B.kind!=="browser"||ne.has(jie(B))||(ee==null?void 0:ee.allowNewBrowserGuest)!==!1&&ne.size<QP,Y=mY(re.tabs,re.activeKey,hY(re.tabs,B,!1),Ae);return se=Y.openResult,{activeKey:Y.activeKey,hasPanelState:!0,open:!0,tabs:Y.tabs}}),f(!0),se},[s,g]),v=h.useCallback((B,ee)=>{let se={admitted:!0};return g(s,re=>{const ne=pY(t.current),Ae=B.kind!=="browser"||(ee==null?void 0:ee.allowNewBrowserGuest)!==!1&&ne.size<QP,Y=mY(re.tabs,re.activeKey,hY(re.tabs,B,!0),Ae);return se=Y.openResult,{activeKey:Y.activeKey,hasPanelState:!0,open:!0,tabs:Y.tabs}}),f(!0),se},[s,g]),w=h.useCallback((B,ee,se)=>{const re=Gw(B);let ne={admitted:!0};const Ae=g(re,Y=>{const ce=pY(t.current),Oe=ee.kind!=="browser"||ce.has(jie(ee))||(se==null?void 0:se.allowNewBrowserGuest)!==!1&&ce.size<QP,Fe=mY(Y.tabs,Y.activeKey,hY(Y.tabs,ee,!1),Oe);return ne=Fe.openResult,{activeKey:Fe.activeKey,hasPanelState:!0,open:!0,tabs:Fe.tabs}});return re===r.current&&(l(Ae),f(!0)),ne},[g]),k=h.useCallback(()=>{g(s,B=>({...B,hasPanelState:!0,open:!0})),f(!0)},[s,g]),S=h.useCallback(B=>{const ee=Gw(B),re={...t.current[ee]??S1(),hasPanelState:!0,open:!0};t.current={...t.current,[ee]:re},r.current=ee,a(ee),l(re),f(!0)},[]),j=h.useCallback(()=>{f(!0),g(s,B=>({...B,activeKey:null,hasPanelState:!0,open:!0}))},[s,g]),C=h.useCallback(()=>{d(null),g(s,B=>AY(B)?{...B,open:!1}:B),f(!1)},[s,g]),N=h.useCallback(()=>{d(null),g(s,()=>S1()),f(!1)},[s,g]),P=C,M=h.useCallback(()=>{d(null)},[]),E=h.useCallback((B,ee=r.current)=>{const se=B.trim(),re=Gw(ee);return!se||!re.startsWith("chat:")&&!re.startsWith("issue:")?!1:(d({organizationId:se,contextKey:re}),!0)},[]),T=h.useCallback((B,ee)=>{var ne,Ae;const se=Gw(B);return(((ne=t.current[se])==null?void 0:ne.tabs)??[]).some(Y=>ps(Y)===ee)?((Ae=n.current[se])==null?void 0:Ae[ee])??0:null},[]),R=h.useCallback((B,ee,se)=>{var Fe;const re=Gw(B),ne=t.current[re]??S1(),Ae=ne.tabs.findIndex(ke=>ps(ke)===ee);if(Ae<0)return{detached:!1,reason:"not_found",revision:null};const Y=((Fe=n.current[re])==null?void 0:Fe[ee])??0;if(se!==Y)return{detached:!1,reason:"revision_mismatch",revision:Y};const ce=ne.tabs[Ae],Oe=g(re,ke=>{const Ne=ke.tabs.filter(ae=>ps(ae)!==ee);if(Ne.length===0)return{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(ke.activeKey!==ee)return{...ke,tabs:Ne};const xe=Ne[Math.min(Ae,Ne.length-1)]??null;return{activeKey:xe?ps(xe):null,hasPanelState:!0,open:!0,tabs:Ne}});return re===r.current&&f(Oe.open),{detached:!0,revision:Y,target:ce}},[g]),_=h.useCallback(B=>{g(s,ee=>{const se=ee.tabs.findIndex(Ae=>ps(Ae)===B),re=ee.tabs.filter(Ae=>ps(Ae)!==B);if(re.length===0)return f(!1),{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(ee.activeKey!==B)return{...ee,tabs:re};const ne=re[Math.min(Math.max(se,0),re.length-1)]??re.at(-1)??null;return{activeKey:ne?ps(ne):null,hasPanelState:!0,open:!0,tabs:re}})},[s,g]),D=h.useCallback(B=>(A.current=B,()=>{A.current===B&&(A.current=null)}),[]),U=h.useCallback(B=>(m.current=B,()=>{m.current===B&&(m.current=null)}),[]),$=h.useCallback(B=>{const se=(t.current[r.current]??S1()).tabs.find(ne=>ps(ne)===B);if(!se)return;const re=A.current;if(re){re(se);return}_(B)},[_]),L=u&&!!o.activeKey;h.useEffect(()=>{const B=Pn(),ee=B==null?void 0:B.setSidePanelCloseShortcutActive;if(!ee)return;let se=!1,re=null;const ne=()=>{if(se)return;const Y=L&&!_5e(document.activeElement);re!==Y&&(re=Y,ee(Y).catch(()=>{}))},Ae=()=>queueMicrotask(ne);return document.addEventListener("focusin",Ae,!0),document.addEventListener("focusout",Ae,!0),ne(),()=>{se=!0,document.removeEventListener("focusin",Ae,!0),document.removeEventListener("focusout",Ae,!0)}},[L]),h.useEffect(()=>{const B=Pn(),ee=B==null?void 0:B.setSidePanelCloseShortcutActive;if(ee)return()=>{ee(!1).catch(()=>{})}},[]),h.useEffect(()=>{const B=Pn();if(B!=null&&B.onBrowserReset)return B.onBrowserReset(()=>{const ee=Object.fromEntries(Object.entries(t.current).map(([re,ne])=>[re,eUt(ne,re,m.current)]));t.current=ee;const se=ee[r.current]??S1();l(se),f(AY(se)&&se.open)})},[]),h.useEffect(()=>{if(!L)return;const B=Pn();if(B!=null&&B.onCloseSidePanelActiveTab)return B.onCloseSidePanelActiveTab(()=>{const ee=o.activeKey;ee&&$(ee)})},[o.activeKey,L,$]),h.useEffect(()=>{const B=Pn();if(B!=null&&B.onOpenEmptySidePanel)return B.onOpenEmptySidePanel(j)},[j]),h.useEffect(()=>{if(!u||!o.activeKey)return;const B=ee=>{_5e(ee.target)||ee.key.toLowerCase()!=="w"||(CE()==="mac"?!ee.metaKey||ee.ctrlKey:!ee.ctrlKey||ee.metaKey)||ee.altKey||ee.shiftKey||(ee.preventDefault(),ee.stopPropagation(),$(o.activeKey))};return document.addEventListener("keydown",B,!0),()=>document.removeEventListener("keydown",B,!0)},[o.activeKey,u,$]);const H=h.useCallback((B,ee,se)=>{const re=Gw(B);if(!(t.current[re]??S1()).tabs.some(Y=>ps(Y)===ee))return!1;const Ae=ps(se);return g(re,Y=>({...Y,activeKey:Y.activeKey===ee?Ae:Y.activeKey,tabs:Y.tabs.map(ce=>ps(ce)===ee?se:ce)})),!0},[g]),X=h.useCallback((B,ee)=>{H(s,B,ee)},[s,H]),F=h.useCallback((B,ee,se)=>{B!==ee&&g(s,re=>{const ne=re.tabs.findIndex(ke=>ps(ke)===B),Ae=re.tabs.findIndex(ke=>ps(ke)===ee);if(ne<0||Ae<0)return re;const Y=[...re.tabs],[ce]=Y.splice(ne,1);if(!ce)return re;const Fe=Y.findIndex(ke=>ps(ke)===ee)+(se==="after"?1:0);return Y.splice(Fe,0,ce),{...re,tabs:Y}})},[s,g]),Q=h.useCallback(B=>{g(s,ee=>({...ee,activeKey:B,hasPanelState:!0,open:!0}))},[s,g]),q=h.useMemo(()=>({activeKey:o.activeKey,clearCurrentContext:N,clearDisplayedContextHold:M,closePanel:P,closeTarget:_,contextKey:s,detachTargetForContext:R,displayedContextHold:c,getTargetRevisionForContext:T,hidePanel:C,holdDisplayedContext:E,open:u,openEmpty:j,openTarget:y,openTargetInNewTab:v,openTargetForContext:w,registerCloseRequestHandler:D,registerBrowserResetHandler:U,replaceTarget:X,replaceTargetForContext:H,reorderTarget:F,setActiveKey:Q,setContextKey:x,showPanel:k,showPanelForContext:S,tabs:o.tabs}),[N,M,P,_,s,o.activeKey,o.tabs,R,c,T,C,E,u,j,y,w,v,U,D,F,X,H,Q,x,k,S]);return i.jsx(the.Provider,{value:q,children:e})}function Ob(){const e=h.useContext(the);if(!e)throw new Error("useSidePanel must be used inside SidePanelProvider");return e}function nUt(){return h.useContext(the)}function rUt(e){try{const t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}async function sUt(e){var r;const{request:t}=e;if(!rUt(t.url))return"ignored";let n;try{n=await e.getSettings()}catch{return await e.forceOpenExternal(t.url),"default_browser"}return n.openLinksIn==="built_in"||t.source==="browser_popup"?(e.openBuiltIn(a6(t.url,{favicon:(r=e.resolveFavicon)==null?void 0:r.call(e,t.url),newTab:t.source==="browser_popup"})),"built_in"):(await e.forceOpenExternal(t.url),"default_browser")}const o3=8;function iUt(){return{activeViewInstanceId:null,tabOrder:[],tabsByViewInstanceId:{},runtimesById:{},promotionsById:{}}}function aUt(){return{organizations:{}}}function P5(e){return e.kind==="side"||e.kind==="transferring"||e.kind==="main"||e.kind==="parked"}function oUt(e,t){const n=e.organizations[t];return n?Object.values(n.runtimesById).filter(r=>r.targetKind==="browser"&&P5(r.host)).length:0}function lUt(e){return Object.values(e.runtimesById).filter(t=>t.targetKind==="browser"&&P5(t.host)).length}function cUt(e,t){return e.kind!==t.kind?!1:e.kind==="side"&&t.kind==="side"?e.contextKey===t.contextKey:e.kind==="main"&&t.kind==="main"?e.organizationId===t.organizationId:!0}function dUt(e){return{...e}}function LVe(e,t,n){if(!n.id||!n.viewInstanceId||n.target.viewInstanceId!==n.viewInstanceId||n.target.kind!==n.targetKind||n.host.kind==="main"&&n.host.organizationId!==t)return!1;const r=e.runtimesById[n.id];return r&&(r.viewInstanceId!==n.viewInstanceId||r.targetKind!==n.targetKind)||n.targetKind==="browser"&&P5(n.host)&&!((r==null?void 0:r.targetKind)==="browser"&&P5(r.host))&&lUt(e)>=o3?!1:!(P5(n.host)&&Object.values(e.runtimesById).some(o=>o.id!==n.id&&o.viewInstanceId===n.viewInstanceId&&P5(o.host)))}function Mg(e,t,n){if(!LVe(e,t,n))return e;const r=e.runtimesById[n.id];return r&&cUt(r.host,n.host)?e:{...e,runtimesById:{...e.runtimesById,[n.id]:{...n,organizationId:t,target:(r==null?void 0:r.target)??X6(n.target),host:dUt(n.host)}}}}function X6(e){return e.kind!=="browser"||!e.savedViewRecovery?{...e}:{...e,savedViewRecovery:{...e.savedViewRecovery,persistedMetadata:{...e.savedViewRecovery.persistedMetadata,target:{...e.savedViewRecovery.persistedMetadata.target}}}}}function zVe(e){return!!(e.viewInstanceId&&e.runtimeId&&e.originContextKey&&e.target.viewInstanceId===e.viewInstanceId)}function nhe(e,t){return Object.values(e.tabsByViewInstanceId).find(n=>n.savedViewId===t)??null}function Cie(e,t,n,r){if(!zVe(n)||r!==null&&!r)return{organization:e,outcome:"rejected"};const s=r?nhe(e,r):null;if(s&&s.viewInstanceId!==n.viewInstanceId)return e.activeViewInstanceId===s.viewInstanceId?{organization:e,outcome:"focused_existing_binding"}:{organization:{...e,activeViewInstanceId:s.viewInstanceId},outcome:"focused_existing_binding"};const a=e.tabsByViewInstanceId[n.viewInstanceId];if(a){const c=r!==null&&a.savedViewId!==null&&a.savedViewId!==r,d=r===null||a.savedViewId===r,u=e.activeViewInstanceId===n.viewInstanceId;return d&&u?{organization:e,outcome:"already_satisfied"}:{organization:{...e,activeViewInstanceId:n.viewInstanceId,tabsByViewInstanceId:r===null||d||c?e.tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n.viewInstanceId]:{...a,savedViewId:r}}},outcome:c?"binding_conflict":"already_satisfied"}}const o={id:n.runtimeId,viewInstanceId:n.viewInstanceId,targetKind:n.target.kind,target:n.target,host:{kind:"main",organizationId:t}};if(!LVe(e,t,o))return{organization:e,outcome:"rejected"};const l=Mg(e,t,o);return{organization:{...l,activeViewInstanceId:n.viewInstanceId,tabOrder:[...l.tabOrder,n.viewInstanceId],tabsByViewInstanceId:{...l.tabsByViewInstanceId,[n.viewInstanceId]:{organizationId:t,viewInstanceId:n.viewInstanceId,savedViewId:r,target:X6(n.target),originContextKey:n.originContextKey,runtimeId:n.runtimeId}}},outcome:"opened"}}function xl(e,t,n){if(!t)return e;const r=e.organizations[t]??iUt(),s=n(r);return s===r?e:{...e,organizations:{...e.organizations,[t]:s}}}function uUt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||!n||r.savedViewId===n||r.savedViewId!==null||nhe(e,n)?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:n}}}}function fUt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||r.savedViewId!==n?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:null}}}}function AUt(e,t,n){var u;const r=e.tabsByViewInstanceId[n];if(!r)return e;const s=e.tabOrder.indexOf(n),a=e.tabOrder.filter(f=>f!==n),{[n]:o,...l}=e.tabsByViewInstanceId,c=Mg(e,t,{id:r.runtimeId,viewInstanceId:r.viewInstanceId,targetKind:r.target.kind,target:((u=e.runtimesById[r.runtimeId])==null?void 0:u.target)??r.target,host:{kind:"disposed"}}),d=e.activeViewInstanceId===n?a[Math.min(Math.max(s,0),a.length-1)]??null:e.activeViewInstanceId;return{...c,activeViewInstanceId:d,tabOrder:a,tabsByViewInstanceId:l}}function hUt(e,t,n){const r=e.tabOrder.indexOf(t);if(r<0||!Number.isFinite(n))return e;const s=Math.max(0,Math.min(Math.trunc(n),e.tabOrder.length-1));if(r===s)return e;const a=[...e.tabOrder];return a.splice(r,1),a.splice(s,0,t),{...e,tabOrder:a}}function mUt(e){return{...e,target:X6(e.target)}}function xW(e){return Number.isInteger(e)&&e>=0}function pUt(e){return e.status==="pending"||e.status==="reconciling"||e.status==="claiming"||e.status==="detaching"}function gUt(e,t,n,r,s){if(!n||!s||!zVe(r)||!xW(r.sourceRevision)||e.promotionsById[n]||Object.values(e.promotionsById).some(l=>pUt(l)&&l.source.runtimeId===r.runtimeId))return e;const a=e.runtimesById[r.runtimeId];if(!a||a.viewInstanceId!==r.viewInstanceId||a.targetKind!==r.target.kind||a.host.kind!=="side"||a.host.contextKey!==r.originContextKey)return e;const o=Mg(e,t,{id:a.id,viewInstanceId:a.viewInstanceId,targetKind:a.targetKind,target:a.target,host:{kind:"transferring"}});return{...o,promotionsById:{...o.promotionsById,[n]:{id:n,organizationId:t,clientMutationId:s,status:"pending",source:mUt(r)}}}}function qj(e,t,n){const r=e.runtimesById[n.runtimeId];return r?Mg(e,t,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:{kind:"side",contextKey:n.originContextKey}}):e}function NE(e,t,n){const r=e.promotionsById[t];if(!r||r.status!=="pending"&&r.status!=="reconciling"&&r.status!=="claiming"||r.source.sourceRevision!==n)return null;const s=e.runtimesById[r.source.runtimeId];return!s||s.viewInstanceId!==r.source.viewInstanceId||s.targetKind!==r.source.target.kind||s.host.kind!=="transferring"?null:r}function xUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="server_failed"&&a.status!=="commit_unknown"||a.source.sourceRevision!==r||!xW(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=Mg(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"pending",source:{...a.source,sourceRevision:s}}}}}function bUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="commit_unknown"||a.source.sourceRevision!==r||!xW(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=Mg(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"reconciling",source:{...a.source,sourceRevision:s}}}}}function yUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="claim_failed"||a.source.sourceRevision!==r||!xW(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=Mg(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"claiming",savedViewId:a.savedViewId,source:{...a.source,sourceRevision:s}}}}}function vUt(e,t,n,r,s){const a=NE(e,n,s);return!a||a.status==="claiming"||!r?e:{...e,promotionsById:{...e.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"claiming",savedViewId:r}}}}function wUt(e,t,n,r,s){const a=NE(e,n,r);if(!a||a.status==="claiming")return e;const o=qj(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"server_failed",error:s}}}}function kUt(e,t,n,r,s){const a=NE(e,n,r);if(!a||a.status==="claiming")return e;const o=qj(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"commit_unknown",error:s}}}}function OUt(e,t,n,r,s,a){const o=NE(e,n,s);if(!o||o.status!=="claiming"||!r||o.savedViewId!==r)return e;const l=qj(e,t,o.source);return{...l,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function mQ(e,t){const{[t]:n,...r}=e.promotionsById;return{...e,promotionsById:r}}function SUt(e,t,n){const r=e.promotionsById[t];return!r||r.status!=="server_failed"&&r.status!=="commit_unknown"&&r.status!=="claim_failed"||r.source.sourceRevision!==n?e:mQ(e,t)}function jUt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.source.sourceRevision!==s||a.source.savedViewId!==r&&(!("savedViewId"in a)||a.savedViewId!==r))return e;if(a.status==="detaching"){const o=BVe(e,t,n,r,s,"saved_view_removed");return mQ(o,n)}return mQ(qj(e,t,a.source),n)}function Z9(e,t,n,r,s){const a=qj(e,t,n.source);return{...a,promotionsById:{...a.promotionsById,[n.id]:{id:n.id,organizationId:t,clientMutationId:n.clientMutationId,source:n.source,status:"claim_failed",savedViewId:r,error:s}}}}function $Ve(e){return{...e,target:X6(e.target)}}function E5e(e,t,n,r){return{...e,promotionsById:{...e.promotionsById,[n.id]:{...n,organizationId:t,status:"detaching",rollback:r}}}}function CUt(e,t,n,r,s){var u;const a=NE(e,n,s);if(!a||a.status!=="claiming"||!r||a.savedViewId!==r)return e;const o={activeViewInstanceId:e.activeViewInstanceId,tab:e.tabsByViewInstanceId[a.source.viewInstanceId]?$Ve(e.tabsByViewInstanceId[a.source.viewInstanceId]):null},l=e.tabsByViewInstanceId[a.source.viewInstanceId],c=nhe(e,r);if(c&&c.viewInstanceId!==a.source.viewInstanceId){const f=e.activeViewInstanceId===c.viewInstanceId?e:{...e,activeViewInstanceId:c.viewInstanceId};return Z9(f,t,a,r,"saved_view_already_bound")}if(l!=null&&l.savedViewId&&l.savedViewId!==r){const f=e.activeViewInstanceId===l.viewInstanceId?e:{...e,activeViewInstanceId:l.viewInstanceId};return Z9(f,t,a,r,"saved_view_binding_conflict")}if(l){let f=e,A=l.runtimeId;if(l.runtimeId===a.source.runtimeId){const m=f.runtimesById[a.source.runtimeId];f=Mg(f,t,{id:m.id,viewInstanceId:m.viewInstanceId,targetKind:m.targetKind,target:m.target,host:{kind:"main",organizationId:t}})}else{const m=f.runtimesById[l.runtimeId];if(!m||m.viewInstanceId!==l.viewInstanceId||m.targetKind!==l.target.kind||P5(m.host))return Z9(e,t,a,r,"existing_tab_runtime_unavailable");const g=f.runtimesById[a.source.runtimeId];if(f=Mg(f,t,{id:g.id,viewInstanceId:g.viewInstanceId,targetKind:g.targetKind,target:g.target,host:{kind:"main",organizationId:t}}),((u=f.runtimesById[g.id])==null?void 0:u.host.kind)!=="main")return Z9(e,t,a,r,"existing_tab_runtime_unavailable");A=g.id}return f={...f,activeViewInstanceId:l.viewInstanceId,tabsByViewInstanceId:l.savedViewId===r&&l.runtimeId===A?f.tabsByViewInstanceId:{...f.tabsByViewInstanceId,[l.viewInstanceId]:{...l,savedViewId:r,runtimeId:A,target:X6(a.source.target),originContextKey:a.source.originContextKey}}},E5e(f,t,a,o)}const d=Cie(e,t,{viewInstanceId:a.source.viewInstanceId,runtimeId:a.source.runtimeId,target:a.source.target,originContextKey:a.source.originContextKey},r);return d.outcome!=="opened"?Z9(d.organization,t,a,r,d.outcome==="binding_conflict"?"saved_view_binding_conflict":"main_host_claim_rejected"):E5e(d.organization,t,a,o)}function FVe(e,t,n,r){const s=e.promotionsById[t];if(!s||s.status!=="detaching"||s.savedViewId!==n||s.source.sourceRevision!==r)return null;const a=e.runtimesById[s.source.runtimeId],o=e.tabsByViewInstanceId[s.source.viewInstanceId];return!a||a.viewInstanceId!==s.source.viewInstanceId||a.host.kind!=="main"||a.host.organizationId!==s.organizationId||!o||o.runtimeId!==a.id||o.savedViewId!==n?null:s}function NUt(e,t,n,r){const s=FVe(e,t,n,r);return s?mQ(e,s.id):e}function BVe(e,t,n,r,s,a){const o=FVe(e,n,r,s);if(!o)return e;const l=qj(e,t,o.source),c={...l.tabsByViewInstanceId};let d=l.tabOrder;return o.rollback.tab?c[o.source.viewInstanceId]=$Ve(o.rollback.tab):(delete c[o.source.viewInstanceId],d=d.filter(u=>u!==o.source.viewInstanceId)),{...l,activeViewInstanceId:o.rollback.activeViewInstanceId,tabOrder:d,tabsByViewInstanceId:c,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function PUt(e,t,n,r){const s=e.runtimesById[t];return!s||s.viewInstanceId!==n||r.viewInstanceId!==n||s.targetKind!==r.kind?e:{...e,runtimesById:{...e.runtimesById,[t]:{...s,target:X6(r)}}}}function IUt(e,t,n,r){const s=e.tabsByViewInstanceId[n],a=e.runtimesById[t];return!s||s.runtimeId!==t||s.target.kind!==r.kind||r.viewInstanceId!==n||!a||a.viewInstanceId!==n||a.targetKind!==r.kind?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n]:{...s,target:X6(r)}}}}function TUt(e,t){switch(t.type){case"saved-tab/open":return xl(e,t.organizationId,n=>Cie(n,t.organizationId,t.tab,t.savedViewId).organization);case"session-tab/create":return xl(e,t.organizationId,n=>Cie(n,t.organizationId,t.tab,null).organization);case"tab/focus":return xl(e,t.organizationId,n=>n.activeViewInstanceId===t.viewInstanceId||!n.tabsByViewInstanceId[t.viewInstanceId]?n:{...n,activeViewInstanceId:t.viewInstanceId});case"tab/reorder":return xl(e,t.organizationId,n=>hUt(n,t.viewInstanceId,t.toIndex));case"tab/bind-saved-view":return xl(e,t.organizationId,n=>uUt(n,t.viewInstanceId,t.savedViewId));case"tab/unbind-saved-view":return xl(e,t.organizationId,n=>fUt(n,t.viewInstanceId,t.savedViewId));case"tab/close":return xl(e,t.organizationId,n=>AUt(n,t.organizationId,t.viewInstanceId));case"tab/update-target":return xl(e,t.organizationId,n=>IUt(n,t.runtimeId,t.viewInstanceId,t.target));case"runtime/admit":return xl(e,t.organizationId,n=>Mg(n,t.organizationId,t.runtime));case"runtime/set-host":return xl(e,t.organizationId,n=>{const r=n.runtimesById[t.runtimeId];return r?Mg(n,t.organizationId,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:t.host}):n});case"runtime/update-target":return xl(e,t.organizationId,n=>PUt(n,t.runtimeId,t.viewInstanceId,t.target));case"promotion/start":return xl(e,t.organizationId,n=>gUt(n,t.organizationId,t.promotionId,t.source,t.clientMutationId));case"promotion/server-commit":return xl(e,t.organizationId,n=>vUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/claim":return xl(e,t.organizationId,n=>CUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-succeed":return xl(e,t.organizationId,n=>NUt(n,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-fail":return xl(e,t.organizationId,n=>BVe(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/server-fail":return xl(e,t.organizationId,n=>wUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/timeout":return xl(e,t.organizationId,n=>kUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/retry":return xl(e,t.organizationId,n=>xUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/reconcile":return xl(e,t.organizationId,n=>bUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/claim-fail":return xl(e,t.organizationId,n=>OUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/claim-retry":return xl(e,t.organizationId,n=>yUt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/discard":return xl(e,t.organizationId,n=>SUt(n,t.promotionId,t.expectedSourceRevision));case"promotion/cancel-saved-view":return xl(e,t.organizationId,n=>jUt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision))}}function QVe(){var n,r;const e=(n=document.activeElement)==null?void 0:n.closest("[data-runtime-id]");if(!e||e.hidden||e.hasAttribute("inert")||e.getAttribute("aria-hidden")==="true")return null;const t=e.dataset.runtimeId;return t?{runtimeId:t,owner:(r=e.dataset.ownerId)!=null&&r.startsWith("main:")?"main_workbench":"side_panel"}:null}function _Ut(){var e;return((e=QVe())==null?void 0:e.runtimeId)??null}function MUt(){const e=Vn(),t=JAe(),n=zFe(),{openTarget:r}=Ob(),s=Uj();return h.useEffect(()=>{const a=Pn();if(a!=null&&a.onOpenWebLink)return a.onOpenWebLink(o=>{sUt({request:o,getSettings:()=>e.fetchQuery({queryKey:V.instance.browserSettings,queryFn:()=>Ha.getBrowser(),staleTime:0}),openBuiltIn:l=>{var f;if(o.sourceWebContentsId){((t==null?void 0:t.openTargetForGuest(o.sourceWebContentsId,l))??!1)||console.warn("[rudder-ui] ignored Browser popup without a live guest owner",o.sourceWebContentsId);return}const c=((f=n==null?void 0:n.selectedOrganizationId)==null?void 0:f.trim())??"",d=!t||!c||t.getLiveBrowserCount(c)<o3;r(l,{allowNewBrowserGuest:d}).admitted||s==null||s.pushToast({title:"Browser tab limit reached",body:`Close a Browser tab to open another. Side Panel and Main share ${o3} live tabs.`,tone:"error"})},forceOpenExternal:l=>{var c;return((c=a.forceOpenExternal)==null?void 0:c.call(a,l))??a.openExternal(l)},resolveFavicon:XBt}).catch(l=>{console.warn("[rudder-ui] failed to route Desktop web link",l)})})},[t,r,n==null?void 0:n.selectedOrganizationId,e,s]),h.useEffect(()=>{const a=Pn();if(a!=null&&a.onBrowserShortcut)return a.onBrowserShortcut(o=>{if(!t)return;const l=o.sourceWebContentsId?null:_Ut();if(o.action==="close_tab"){o.sourceWebContentsId?t.closeTargetForGuest(o.sourceWebContentsId):l&&t.closeTargetForRuntime(l);return}o.sourceWebContentsId?t.dispatchBrowserShortcutForGuest(o.sourceWebContentsId,o.action):l&&t.dispatchBrowserShortcutForRuntime(l,o.action)})},[t]),h.useEffect(()=>{var f;const a=(f=Pn())==null?void 0:f.setBrowserSurfaceShortcutActive;if(!a||!t)return;let o=!1,l=!1,c;const d=()=>{var y;if(o)return;const A=QVe(),m=(A==null?void 0:A.runtimeId)??null,g=m?((y=t.getRuntimeTarget(m))==null?void 0:y.kind)==="browser":!1,x=A==null?void 0:A.owner;l===g&&x===c||(l=g,c=x,a(g,x).catch(()=>{}))},u=()=>queueMicrotask(d);return document.addEventListener("focusin",u,!0),document.addEventListener("focusout",u,!0),d(),()=>{o=!0,document.removeEventListener("focusin",u,!0),document.removeEventListener("focusout",u,!0),a(!1).catch(()=>{})}},[t]),null}const xT="https://docs.rudderhq.dev",UVe="https://discord.gg/ZcfWwPVkUz";function VVe({alt:e="",className:t,...n}){return i.jsx("img",{src:"/rudder-logo.png",alt:e,"aria-hidden":e?void 0:!0,className:K("inline-block shrink-0 rounded-full bg-white object-cover ring-1 ring-black/5 dark:ring-white/10",t),...n})}function EUt(){const[e,t]=h.useState(null),n=h.useRef(null);h.useEffect(()=>{const a=Pn();if(!(a!=null&&a.getReleaseNotes))return;let o=!1;return a.getReleaseNotes().then(l=>{o||l.status!=="available"||(n.current=l.notes,t(l.notes))}).catch(()=>{}),()=>{o=!0}},[]);async function r(){var o,l;const a=n.current;n.current=null,t(null),a&&await((l=(o=Pn())==null?void 0:o.markReleaseNotesShown)==null?void 0:l.call(o,a.version).catch(()=>{}))}async function s(){const a=Pn();if(a){await a.openExternal(xT).catch(()=>{});return}window.open(xT,"_blank","noopener,noreferrer")}return i.jsx(Ps,{open:e!==null,onOpenChange:a=>{a||r()},children:i.jsxs(zs,{className:"gap-0 overflow-hidden p-0 sm:max-w-[36rem]",showCloseButton:!1,children:[i.jsxs("div",{className:"flex items-start gap-3 border-b border-border/70 px-5 pb-4 pt-5",children:[i.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-[var(--radius-md)] border border-border bg-background shadow-sm",children:i.jsx(VVe,{alt:"Rudder",className:"h-6 w-6 ring-0"})}),i.jsxs(vi,{className:"min-w-0 gap-1 text-left",children:[i.jsx(ei,{className:"text-base leading-6",children:(e==null?void 0:e.title)??"What's new in Rudder"}),i.jsx(Si,{className:"text-sm leading-5",children:"Updates installed with this version."})]})]}),i.jsx("div",{className:"max-h-[min(62vh,34rem)] overflow-y-auto px-5 py-4",children:i.jsx("div",{className:"space-y-4",children:e==null?void 0:e.sections.map(a=>i.jsxs("section",{className:"space-y-2",children:[i.jsx("h2",{className:"text-sm font-semibold text-foreground",children:a.title}),i.jsx("ul",{className:"space-y-1.5 text-sm leading-5 text-muted-foreground",children:a.items.map(o=>i.jsxs("li",{className:"flex gap-2",children:[i.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-muted-foreground/70"}),i.jsx("span",{children:o})]},o))})]},a.title))})}),i.jsxs(ga,{className:"border-t border-border/70 px-5 py-4 sm:justify-between",children:[i.jsxs(le,{type:"button",variant:"outline",onClick:()=>void s(),children:[i.jsx(Ja,{className:"h-4 w-4"}),"Docs"]}),i.jsx(le,{type:"button",onClick:()=>void r(),children:"Continue"})]})]})})}function DUt(e){const[t="",...n]=e.split(/\n{2,}/);return{body:t.trim(),runDetail:n.join(`
1692
1692
 
1693
1693
  `).trim()}}function RUt(){const[e,t]=h.useState(null),[n,r]=h.useState(!1),s=h.useRef(null);h.useEffect(()=>{var d;const c=Pn();if(c!=null&&c.onDeferredUpdatePrompt)return(d=c.setDeferredUpdatePromptReady)==null||d.call(c,!0),c.onDeferredUpdatePrompt(u=>{s.current=u,t(u),r(!1)})},[]),h.useEffect(()=>()=>{var c,d;(d=(c=Pn())==null?void 0:c.setDeferredUpdatePromptReady)==null||d.call(c,!1)},[]);async function a(c){var f;const d=s.current;if(!d)return;const u=Pn();s.current=null,r(!0),t(null),await((f=u==null?void 0:u.respondDeferredUpdatePrompt)==null?void 0:f.call(u,d.promptId,c).catch(()=>{})),r(!1)}const{body:o,runDetail:l}=DUt((e==null?void 0:e.detail)??"");return i.jsx(Ps,{open:e!==null,onOpenChange:c=>{c||a("cancel")},children:i.jsxs(zs,{className:"gap-0 p-0 sm:max-w-[34rem]",showCloseButton:!1,children:[i.jsxs("div",{className:"flex items-start gap-3 px-5 pb-4 pt-5",children:[i.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-[var(--radius-md)] border border-amber-500/30 bg-amber-500/12 text-amber-600 dark:text-amber-300",children:i.jsx(Gf,{className:"h-5 w-5"})}),i.jsxs(vi,{className:"min-w-0 gap-2 text-left",children:[i.jsx(ei,{className:"text-base leading-6",children:e==null?void 0:e.message}),o?i.jsx(Si,{className:"text-sm leading-5",children:o}):null]})]}),l?i.jsx("div",{className:"mx-5 rounded-[var(--radius-md)] border border-border/70 bg-muted/35 px-3 py-2.5",children:i.jsx("p",{className:"whitespace-pre-wrap break-words text-xs font-medium leading-5 text-foreground",children:l})}):null,i.jsxs(ga,{className:"grid grid-cols-1 gap-2 px-5 pb-5 pt-4 sm:grid-cols-2 sm:justify-stretch",children:[i.jsx(le,{type:"button",variant:"outline",className:"h-auto min-h-10 min-w-0 whitespace-normal leading-5",disabled:n,onClick:()=>void a("cancel"),children:(e==null?void 0:e.cancelLabel)??"Cancel"}),i.jsx(le,{type:"button",variant:"outline",className:"h-auto min-h-10 min-w-0 whitespace-normal leading-5",disabled:n,onClick:()=>void a("force"),children:(e==null?void 0:e.forceLabel)??"Stop Runs and Update Now"}),i.jsx(le,{type:"button",className:"h-auto min-h-10 min-w-0 whitespace-normal leading-5 sm:col-span-2",disabled:n,onClick:()=>void a("wait"),children:(e==null?void 0:e.confirmLabel)??"Download and Update When Idle"})]})]})})}const qVe=h.createContext(null),LUt={progress:null,dismissProgress:()=>{}};function zUt({children:e}){const[t,n]=h.useState(null),[r,s]=h.useState(null);h.useEffect(()=>{var d,u;const l=Pn();if(!l)return;function c(f){n(f),f.phase==="complete"&&window.setTimeout(()=>{n(A=>(A==null?void 0:A.updateId)===f.updateId&&A.phase==="complete"?null:A)},4e3)}return(d=l.getUpdateProgress)==null||d.call(l).then(f=>{f&&c(f)}).catch(()=>{}),(u=l.onUpdateProgress)==null?void 0:u.call(l,f=>{c(f),s(A=>A===f.updateId&&f.phase!=="failed"?A:null)})},[]);const a=(t==null?void 0:t.updateId)===r?null:t,o=h.useMemo(()=>({progress:a,dismissProgress:()=>{t&&s(t.updateId)}}),[t,a]);return i.jsx(qVe.Provider,{value:o,children:e})}function KVe(){return h.useContext(qVe)??LUt}const D5e="https://github.com/Undertone0809/rudder/releases",R5e={starting:"about.updates.progress.phase.starting",resolving_release:"about.updates.progress.phase.resolving_release",downloading_checksums:"about.updates.progress.phase.downloading_checksums",downloading_asset:"about.updates.progress.phase.downloading_asset",verifying_checksum:"about.updates.progress.phase.verifying_checksum",ready_to_install:"about.updates.progress.phase.ready_to_install",waiting_for_active_runs:"about.updates.progress.phase.waiting_for_active_runs",preparing_restart:"about.updates.progress.phase.preparing_restart",closing:"about.updates.progress.phase.closing",complete:"about.updates.progress.phase.complete",failed:"about.updates.progress.phase.failed"};function L5e(e){if(typeof e!="number"||!Number.isFinite(e))return null;const t=["B","KB","MB","GB"];let n=Math.max(0,e),r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return r===0?`${Math.round(n)} ${t[r]}`:`${n.toFixed(1)} ${t[r]}`}function $Ut(e){return e==="failed"?"failed":e==="ready_to_install"||e==="closing"||e==="complete"?"ready":"active"}function FUt(){const{progress:e,dismissProgress:t}=KVe(),{t:n}=is(),[r,s]=h.useState(null),[a,o]=h.useState(!1);if(!e)return null;const l=e,c=$Ut(l.phase),d=L5e(l.transferredBytes),u=L5e(l.totalBytes),f=typeof l.percent=="number"?Math.max(0,Math.min(100,l.percent)):null,A=f!==null,m=f!==null?`${f}%`:d?u?`${d} / ${u}`:d:null,g=c==="active"&&!A,x=l.blockers??[],y=l.phase==="waiting_for_active_runs"&&x.length>0;async function v(){const S=Pn();S&&(s(null),await S.installUpdate(l.version))}async function w(S={}){const j=Pn();if(s(null),!(j!=null&&j.applyUpdate)){s(n("about.updates.installUnavailable"));return}o(!0);try{const C=await j.applyUpdate(l.updateId,S.force?{force:!0}:void 0);C.status!=="started"&&s(C.message||n("about.updates.installFailed"))}catch(C){s(C instanceof Error?C.message:n("about.updates.installFailed"))}finally{o(!1)}}async function k(){const S=Pn();S?await S.openExternal(D5e):window.open(D5e,"_blank","noopener,noreferrer")}return i.jsx("aside",{"aria-live":"polite",className:"pointer-events-none fixed bottom-[calc(1rem+5.75rem)] right-4 z-[1001] w-[min(calc(100vw-2rem),20rem)] md:bottom-4",children:i.jsx("div",{className:K("pointer-events-auto overflow-hidden rounded-[var(--radius-md)] border bg-popover text-popover-foreground shadow-[0_16px_40px_rgba(15,23,42,0.16)] backdrop-blur-xl dark:shadow-[0_16px_44px_rgba(0,0,0,0.45)]",c==="failed"?"border-destructive/35":"border-border/70"),children:i.jsxs("div",{className:"flex items-start gap-3 px-3.5 py-3",children:[i.jsx("span",{className:K("flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-sm)] bg-muted text-muted-foreground",c==="failed"&&"bg-destructive/10 text-destructive",c==="ready"&&"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"),children:c==="failed"?i.jsx(Gf,{className:"h-4 w-4"}):c==="ready"?i.jsx(dd,{className:"h-4 w-4"}):i.jsx(Tg,{className:"h-4 w-4"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsx("p",{className:"text-sm font-semibold leading-5",children:c==="failed"?n("about.updates.progress.failedTitle"):l.phase==="ready_to_install"?n("about.updates.progress.readyTitle"):l.phase==="complete"?n("about.updates.progress.completeTitle"):n("about.updates.progress.title",{version:l.version.startsWith("v")?l.version:`v${l.version}`})}),m?i.jsx("span",{className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:m}):null]}),i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-xs leading-4 text-muted-foreground",children:l.error??l.message??n(R5e[l.phase])}),y?i.jsxs("div",{className:"mt-2 rounded-[var(--radius-sm)] border border-amber-500/25 bg-amber-500/8 px-2.5 py-2",children:[i.jsx("p",{className:"text-[11px] font-semibold text-foreground",children:n("about.updates.progress.blockersTitle")}),i.jsxs("div",{className:"mt-1 grid gap-0.5",children:[x.slice(0,3).map(S=>i.jsx("p",{className:"break-words text-[11px] leading-4 text-muted-foreground",children:n("about.updates.progress.blockerRun",{organization:S.organizationName,agent:S.agentName,runId:S.runId.slice(0,8)})},S.runId)),x.length>3?i.jsxs("p",{className:"text-[11px] leading-4 text-muted-foreground",children:["+",x.length-3]}):null]}),i.jsx("p",{className:"mt-1 text-[11px] leading-4 text-muted-foreground",children:n("about.updates.progress.automaticApply")})]}):null,r?i.jsx("p",{className:"mt-2 rounded-[var(--radius-sm)] border border-destructive/25 bg-destructive/8 px-2.5 py-2 text-xs leading-4 text-destructive",children:r}):null,A?i.jsx("div",{className:"mt-2 h-1.5 overflow-hidden rounded-full bg-muted",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":f,children:i.jsx("div",{className:K("h-full rounded-full bg-emerald-700 transition-[width] duration-300",c==="failed"&&"bg-destructive"),style:{width:`${f}%`}})}):g?i.jsx("div",{className:"mt-2 h-1.5 overflow-hidden rounded-full bg-muted",role:"progressbar","aria-label":n(R5e[l.phase]),children:i.jsx("div",{className:"h-full w-2/5 rounded-full bg-emerald-700/70 animate-pulse"})}):null,l.phase==="ready_to_install"&&l.automaticApply!==!0?i.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:i.jsx(le,{type:"button",size:"sm",className:"h-8 px-3 text-xs",disabled:a,onClick:()=>void w(),children:n(a?"about.updates.installing":"about.updates.progress.restartToUpdate")})}):null,y?i.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:i.jsx(le,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",disabled:a,onClick:()=>void w({force:!0}),children:n(a?"about.updates.installing":"about.updates.progress.forceRestartToUpdate")})}):null,c==="failed"?i.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[i.jsx(le,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:()=>void v(),children:n("about.updates.progress.retry")}),i.jsx(le,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:()=>void k(),children:n("about.updates.progress.openReleases")})]}):null]}),i.jsx("button",{type:"button","aria-label":n("about.updates.progress.dismiss"),onClick:t,className:"-mr-1 -mt-1 shrink-0 rounded-[var(--radius-sm)] p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]})})})}const bo={list:e=>Re.get(`/plugins${e?`?status=${e}`:""}`),listAvailable:()=>Re.get("/plugins/available"),listExamples:()=>Re.get("/plugins/examples"),get:e=>Re.get(`/plugins/${e}`),install:e=>Re.post("/plugins/install",e),uninstall:(e,t)=>Re.delete(`/plugins/${e}${t?"?purge=true":""}`),enable:e=>Re.post(`/plugins/${e}/enable`,{}),disable:(e,t)=>Re.post(`/plugins/${e}/disable`,t?{reason:t}:{}),health:e=>Re.get(`/plugins/${e}/health`),dashboard:e=>Re.get(`/plugins/${e}/dashboard`),logs:(e,t)=>{const n=new URLSearchParams;t!=null&&t.limit&&n.set("limit",String(t.limit)),t!=null&&t.level&&n.set("level",t.level),t!=null&&t.since&&n.set("since",t.since);const r=n.toString();return Re.get(`/plugins/${e}/logs${r?`?${r}`:""}`)},upgrade:(e,t)=>Re.post(`/plugins/${e}/upgrade`,t?{version:t}:{}),listUiContributions:()=>Re.get("/plugins/ui-contributions"),getConfig:e=>Re.get(`/plugins/${e}/config`),saveConfig:(e,t)=>Re.post(`/plugins/${e}/config`,{configJson:t}),testConfig:(e,t)=>Re.post(`/plugins/${e}/config/test`,{configJson:t}),bridgeGetData:(e,t,n,r,s)=>Re.post(`/plugins/${e}/data/${encodeURIComponent(t)}`,{orgId:r??void 0,params:n,renderEnvironment:s??void 0}),bridgePerformAction:(e,t,n,r,s)=>Re.post(`/plugins/${e}/actions/${encodeURIComponent(t)}`,{orgId:r??void 0,params:n,renderEnvironment:s??void 0})},rhe=h.createContext(null);function bW(){const e=h.useContext(rhe);if(!e)throw new Error("Plugin bridge hook called outside of a <PluginBridgeContext.Provider>. Ensure the plugin component is rendered within a PluginBridgeScope.");return e}function WVe(e){if(e instanceof Nl&&e.body&&typeof e.body=="object"){const t=e.body;if(typeof t.code=="string"&&typeof t.message=="string")return{code:t.code,message:t.message,details:t.details};if(typeof t.error=="string")return{code:"UNKNOWN",message:t.error}}return{code:"UNKNOWN",message:e instanceof Error?e.message:String(e)}}function BUt(e){if(!e)return"";try{return JSON.stringify(e,Object.keys(e).sort())}catch{return""}}function ZVe(e){return e?{environment:e.environment,launcherId:e.launcherId,bounds:e.bounds}:null}function QUt(e){return e?JSON.stringify(e):""}function UUt(e,t){const{pluginId:n,hostContext:r}=bW(),s=r.orgId,a=ZVe(r.renderEnvironment),o=QUt(a),[l,c]=h.useState(null),[d,u]=h.useState(!0),[f,A]=h.useState(null),[m,g]=h.useState(0),x=BUt(t);h.useEffect(()=>{let v=!1,w=null,k=0;const S=2,j=["WORKER_UNAVAILABLE","TIMEOUT"];u(!0);const C=()=>{bo.bridgeGetData(n,e,t,s,a).then(N=>{v||(c(N.data),A(null),u(!1))}).catch(N=>{if(v)return;const P=WVe(N);if(j.includes(P.code)&&k<S){k+=1,w=setTimeout(()=>{w=null,v||C()},150*k);return}A(P),c(null),u(!1)})};return C(),()=>{v=!0,w&&clearTimeout(w)}},[n,e,x,m,s,o]);const y=h.useCallback(()=>{g(v=>v+1)},[]);return{data:l,loading:d,error:f,refresh:y}}function VUt(e){const t=bW(),n=h.useRef(t);return n.current=t,h.useCallback(async r=>{const{pluginId:s,hostContext:a}=n.current,o=a.orgId,l=ZVe(a.renderEnvironment);try{return(await bo.bridgePerformAction(s,e,r,o,l)).data}catch(c){throw WVe(c)}},[e])}function qUt(){const{hostContext:e}=bW();return e}function KUt(){const{pushToast:e}=ss();return h.useCallback(t=>e(t),[e])}function WUt(e,t){const{pluginId:n,hostContext:r}=bW(),s=(t==null?void 0:t.orgId)??r.orgId??void 0,[a,o]=h.useState([]),[l,c]=h.useState(null),[d,u]=h.useState(!!s),[f,A]=h.useState(!1),[m,g]=h.useState(null),x=h.useRef(null),y=h.useCallback(()=>{var v;(v=x.current)==null||v.close(),x.current=null,u(!1),A(!1)},[]);return h.useEffect(()=>{if(o([]),c(null),g(null),!s){y();return}const v=new URLSearchParams({orgId:s}),w=new EventSource(`/api/plugins/${encodeURIComponent(n)}/bridge/stream/${encodeURIComponent(e)}?${v.toString()}`,{withCredentials:!0});return x.current=w,u(!0),A(!1),w.onopen=()=>{u(!1),A(!0),g(null)},w.onmessage=k=>{try{const S=JSON.parse(k.data);o(j=>[...j,S]),c(S)}catch(S){g(S instanceof Error?S:new Error(String(S)))}},w.addEventListener("close",()=>{w.close(),x.current===w&&(x.current=null),u(!1),A(!1)}),w.onerror=()=>{u(!1),A(!1),g(new Error(`Failed to connect to plugin stream "${e}"`)),w.close(),x.current===w&&(x.current=null)},()=>{w.close(),x.current===w&&(x.current=null)}},[e,y,s,n]),{events:a,lastEvent:l,connecting:d,connected:f,error:m,close:y}}const yW=new Map;function vW(e,t){return`${e}:${t}`}function ZUt(e){return e==="detailTab"||e==="taskDetailView"||e==="contextMenuItem"||e==="commentAnnotation"||e==="commentContextMenuItem"||e==="projectSidebarItem"||e==="toolbarButton"}function HUt(e){return e instanceof Error&&e.message?e.message:"Unknown error"}function XUt(e,t,n){yW.set(vW(e,t),{kind:"react",component:n})}function GUt(e,t,n){yW.set(vW(e,t),{kind:"web-component",tagName:n})}function YUt(e){return yW.get(vW(e.pluginKey,e.exportName))??null}function z5e(e,t){return yW.get(vW(e,t))??null}const b5=new Map,nP=new Map;function she(e){const t=e.updatedAt??e.version??"0";return`${e.pluginId}:${t}`}function JUt(e){const t=encodeURIComponent(e.updatedAt??e.version??"0");return`/_plugins/${encodeURIComponent(e.pluginId)}/ui/${e.uiEntryFile}?v=${t}`}const gY={};function eVt(e,t){return t===void 0?e??{}:{...e??{},key:t}}function bm(e){if(gY[e])return gY[e];let t;switch(e){case"react":t=`
1694
1694
  const R = globalThis.__rudderPluginBridge__?.react;
@@ -1792,7 +1792,7 @@ When you submit the join request, use:
1792
1792
  constructor(\${params}) {
1793
1793
  \${}
1794
1794
  }
1795
- }`,{label:"class",detail:"definition",type:"keyword"}),zl('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),zl('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],det=oge.concat([zl("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),zl("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),zl("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),cOe=new _pe,uet=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function aN(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const Yun=["FunctionDeclaration"],Jun={FunctionDeclaration:aN("function"),ClassDeclaration:aN("class"),ClassExpression:()=>!0,EnumDeclaration:aN("constant"),TypeAliasDeclaration:aN("type"),NamespaceDeclaration:aN("namespace"),VariableDefinition(e,t){e.matchContext(Yun)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function fet(e,t){let n=cOe.get(t);if(n)return n;let r=[],s=!0;function a(o,l){let c=e.sliceString(o.from,o.to);r.push({label:c,type:l})}return t.cursor(Za.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let l=Jun[o.name];if(l&&l(o,a)||uet.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of fet(e,o.node))r.push(l);return!1}}),cOe.set(t,r),r}const MU=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,lge=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Aet(e){let t=Pa(e.state).resolveInner(e.pos,-1);if(lge.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&MU.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)uet.has(s.name)&&(r=r.concat(fet(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:MU}}function qJ(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,o;if((a==null?void 0:a.name)=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if((a==null?void 0:a.name)=="MemberExpression"&&((r=o=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(o)),t=a;else return null}}function het(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=Pa(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?qJ(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?qJ(t,n.parent,""):lge.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&MU.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?qJ(t,n,""):e.explicit?{path:[],name:""}:null}function efn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let o=Object.getPrototypeOf(e);if(!o)return r;e=o}}function tfn(e){let t=new Map;return n=>{let r=het(n);if(!r)return null;let s=e;for(let o of r.path)if(s=s[o],!s)return null;let a=t.get(s);return a||t.set(s,a=efn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:MU}}}const Hm=Lx.define({name:"javascript",parser:Gun.configure({props:[_b.add({IfStatement:aO({except:/^\s*({|else\b)/}),TryStatement:aO({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:aon,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:iO({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":aO({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),Mb.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":sD,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),met={test:e=>/^JSX/.test(e.name),facet:gZ({commentTokens:{block:{open:"{/*",close:"*/}"}}})},cge=Hm.configure({dialect:"ts"},"typescript"),dge=Hm.configure({dialect:"jsx",props:[Epe.add(e=>e.isTop?[met]:void 0)]}),uge=Hm.configure({dialect:"jsx ts",props:[Epe.add(e=>e.isTop?[met]:void 0)]},"typescript");let pet=e=>({label:e,type:"keyword"});const get="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(pet),nfn=get.concat(["declare","implements","private","protected","public"].map(pet));function EU(e={}){let t=e.jsx?e.typescript?uge:dge:e.typescript?cge:Hm,n=e.typescript?det.concat(nfn):oge.concat(get);return new Qg(t,[Hm.data.of({autocomplete:eJe(lge,Bpe(n))}),Hm.data.of({autocomplete:Aet}),e.jsx?xet:[]])}function rfn(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function dOe(e,t,n=e.length){for(let r=t==null?void 0:t.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const sfn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),xet=Fn.inputHandler.of((e,t,n,r,s)=>{if((sfn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Hm.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d;let{head:u}=c,f=Pa(o).resolveInner(u-1,-1),A;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(u-1,u)!=r||f.name=="JSXAttributeValue"&&f.to>u)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:u,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let m=f.parent,g=m.parent;if(g&&m.from==u-2&&((A=dOe(o.doc,g.firstChild,u))||((d=g.firstChild)===null||d===void 0?void 0:d.name)=="JSXFragmentTag")){let x=`${A}>`;return{range:Ht.cursor(u+x.length,-1),changes:{from:u,insert:x}}}}else if(r==">"){let m=rfn(f);if(m&&m.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(u,u+2))&&(A=dOe(o.doc,m,u)))return{range:c,changes:{from:u,insert:`</${A}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function ifn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:o}of Hm.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let d of e.verify(r.sliceDoc(a,o),t))s.push(afn(d,r.doc,c))}return s}}function uOe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function afn(e,t,n){let r=uOe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?uOe(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:o}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(d,u){d.dispatch({changes:{from:u+l,to:u+c,insert:o},scrollIntoView:!0})}}]}return s}const tz=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:xet,completionPath:het,esLint:ifn,javascript:EU,javascriptLanguage:Hm,jsxLanguage:dge,localCompletionSource:Aet,scopeCompletionSource:tfn,snippets:oge,tsxLanguage:uge,typescriptLanguage:cge,typescriptSnippets:det},Symbol.toStringTag,{value:"Module"})),oN=["_blank","_self","_top","_parent"],KJ=["ascii","utf-8","utf-16","latin1","latin1"],WJ=["get","post","put","delete"],ZJ=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],wh=["true","false"],Qr={},ofn={a:{attrs:{href:null,ping:null,type:null,media:null,target:oN,hreflang:null}},abbr:Qr,address:Qr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Qr,aside:Qr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Qr,base:{attrs:{href:null,target:oN}},bdi:Qr,bdo:Qr,blockquote:{attrs:{cite:null}},body:Qr,br:Qr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:ZJ,formmethod:WJ,formnovalidate:["novalidate"],formtarget:oN,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Qr,center:Qr,cite:Qr,code:Qr,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Qr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Qr,div:Qr,dl:Qr,dt:Qr,em:Qr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Qr,figure:Qr,footer:Qr,form:{attrs:{action:null,name:null,"accept-charset":KJ,autocomplete:["on","off"],enctype:ZJ,method:WJ,novalidate:["novalidate"],target:oN}},h1:Qr,h2:Qr,h3:Qr,h4:Qr,h5:Qr,h6:Qr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Qr,hgroup:Qr,hr:Qr,html:{attrs:{manifest:null}},i:Qr,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:ZJ,formmethod:WJ,formnovalidate:["novalidate"],formtarget:oN,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Qr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Qr,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Qr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:KJ,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Qr,noscript:Qr,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Qr,param:{attrs:{name:null,value:null}},pre:Qr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Qr,rt:Qr,ruby:Qr,samp:Qr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:KJ}},section:Qr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Qr,source:{attrs:{src:null,type:null,media:null}},span:Qr,strong:Qr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Qr,summary:Qr,sup:Qr,table:Qr,tbody:Qr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Qr,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Qr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Qr,time:{attrs:{datetime:null}},title:Qr,tr:Qr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Qr,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Qr},bet={accesskey:null,class:null,contenteditable:wh,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:wh,autocorrect:wh,autocapitalize:wh,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":wh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":wh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":wh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":wh,"aria-hidden":wh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":wh,"aria-multiselectable":wh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":wh,"aria-relevant":null,"aria-required":wh,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},yet="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of yet)bet[e]=null;let a_=class{constructor(t,n){this.tags={...ofn,...t},this.globalAttrs={...bet,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}};a_.default=new a_;function $S(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function FS(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function vet(e,t,n){let r=n.tags[$S(e,FS(t))];return(r==null?void 0:r.children)||n.allTags}function fge(e,t){let n=[];for(let r=FS(t);r&&!r.type.isTop;r=FS(r.parent)){let s=$S(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const wet=/^[:\-\.\w\u00b7-\uffff]*$/;function fOe(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",o=FS(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:vet(e.doc,o,t).map(l=>({label:l,type:"type"})).concat(fge(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function AOe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:fge(e.doc,t).map((a,o)=>({label:a,apply:a+s,type:"type",boost:99-o})),validFor:wet}}function lfn(e,t,n,r){let s=[],a=0;for(let o of vet(e.doc,n,t))s.push({label:"<"+o,type:"type"});for(let o of fge(e.doc,n))s.push({label:"</"+o+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function cfn(e,t,n,r,s){let a=FS(n),o=a?t.tags[$S(e.doc,a)]:null,l=o&&o.attrs?Object.keys(o.attrs):[],c=o&&o.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(d=>({label:d,type:"property"})),validFor:wet}}function dfn(e,t,n,r,s){var a;let o=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(o){let d=e.sliceDoc(o.from,o.to),u=t.globalAttrs[d];if(!u){let f=FS(n),A=f?t.tags[$S(e.doc,f)]:null;u=(A==null?void 0:A.attrs)&&A.attrs[d]}if(u){let f=e.sliceDoc(r,s).toLowerCase(),A='"',m='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,A="",m=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let g of u)l.push({label:g,apply:A+g+m,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function ket(e,t){let{state:n,pos:r}=t,s=Pa(n).resolveInner(r,-1),a=s.resolve(r);for(let o=r,l;a==s&&(l=s.childBefore(o));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,o=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?AOe(n,s,s.from,r):fOe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?fOe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?AOe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?cfn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?dfn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?lfn(n,e,s,r):null}function Oet(e){return ket(a_.default,e)}function jet(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new a_(t,n):a_.default;return s=>ket(r,s)}const ufn=Hm.parser.configure({top:"SingleExpression"}),Cet=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:cge.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:dge.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:uge.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:ufn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Hm.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:i_.parser}],Net=[{name:"style",parser:i_.parser.configure({top:"Styles"})}].concat(yet.map(e=>({name:e,parser:Hm.parser}))),Pet=Lx.define({name:"html",parser:yun.configure({props:[_b.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),Mb.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),WYe.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),AI=Pet.configure({wrap:oet(Cet,Net)});function Iet(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=oet((e.nestedLanguages||[]).concat(Cet),(e.nestedAttributes||[]).concat(Net)));let r=n?Pet.configure({wrap:n,dialect:t}):t?AI.configure({dialect:t}):AI;return new Qg(r,[AI.data.of({autocomplete:jet(e)}),e.autoCloseTags!==!1?Tet:[],EU().support,GJe().support])}const hOe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),Tet=Fn.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!AI.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d,u,f;let A=o.doc.sliceString(c.from-1,c.to)==r,{head:m}=c,g=Pa(o).resolveInner(m,-1),x;if(A&&r==">"&&g.name=="EndTag"){let y=g.parent;if(((u=(d=y.parent)===null||d===void 0?void 0:d.lastChild)===null||u===void 0?void 0:u.name)!="CloseTag"&&(x=$S(o.doc,y.parent,m))&&!hOe.has(x)){let v=m+(o.doc.sliceString(m,m+1)===">"?1:0),w=`</${x}>`;return{range:c,changes:{from:m,to:v,insert:w}}}}else if(A&&r=="/"&&g.name=="IncompleteCloseTag"){let y=g.parent;if(g.from==m-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(x=$S(o.doc,y,m))&&!hOe.has(x)){let v=m+(o.doc.sliceString(m,m+1)===">"?1:0),w=`${x}>`;return{range:Ht.cursor(m+w.length,-1),changes:{from:m,to:v,insert:w}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),ffn=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:Tet,html:Iet,htmlCompletionSource:Oet,htmlCompletionSourceWith:jet,htmlLanguage:AI},Symbol.toStringTag,{value:"Module"}));function Afn(e,t,n,r){const s=Ex(jl),a=Bh(CHe),o=ye.useRef(null),{lexicalNode:l}=Kae(),c=ye.useRef(!1),d=ye.useRef(!1),u=ye.useCallback(()=>{a({editorType:t,rootNode:l,editorRef:o.current})},[t,l,a]),f=ye.useCallback(A=>{var m,g,x,y,v,w;if(A.key==="ArrowDown"){const k=(g=(m=o.current)==null?void 0:m.getCodemirror())==null?void 0:g.state;if(k){const S=k.doc.length,j=k.selection.ranges[0].to;S===j&&(c.current?(s==null||s.update(()=>{var C,N;const P=vx(e);P.getNextSibling()?((N=(C=o.current)==null?void 0:C.getCodemirror())==null||N.contentDOM.blur(),P.selectNext()):P.insertAfter(Fo())}),c.current=!1):c.current=!0)}}else if(A.key==="ArrowUp"){const k=(y=(x=o.current)==null?void 0:x.getCodemirror())==null?void 0:y.state;k&&k.selection.ranges[0].from===0&&(d.current?(s==null||s.update(()=>{var j,C;const N=vx(e);N.getPreviousSibling()&&((C=(j=o.current)==null?void 0:j.getCodemirror())==null||C.contentDOM.blur(),N.selectPrevious())}),d.current=!1):d.current=!0)}else if(A.key==="Enter")A.stopPropagation();else if(A.key==="Backspace"||A.key==="Delete"){const k=(w=(v=o.current)==null?void 0:v.getCodemirror())==null?void 0:w.state;(k==null?void 0:k.doc.length)===0&&(s==null||s.update(()=>{vx(e).remove()}))}},[s,e]);return ye.useEffect(()=>{const A=o.current;return setTimeout(()=>{var m,g;(m=A==null?void 0:A.getCodemirror())==null||m.contentDOM.addEventListener("focus",u),(g=A==null?void 0:A.getCodemirror())==null||g.contentDOM.addEventListener("keydown",f)},300),()=>{var m,g;(m=A==null?void 0:A.getCodemirror())==null||m.contentDOM.removeEventListener("focus",u),(g=A==null?void 0:A.getCodemirror())==null||g.contentDOM.removeEventListener("keydown",f)}},[o,u,f,n]),ye.useEffect(()=>{r.subscribe(()=>{var A,m;(m=(A=o.current)==null?void 0:A.getCodemirror())==null||m.focus(),u()})},[r,o,e,u]),o}function bn(e){return new Qg(Lpe.define(e))}function vy(e){return Wt(()=>import("./index-B3h9Vdxx.js"),[]).then(t=>t.sql({dialect:t[e]}))}const hfn=[Ut.of({name:"C",extensions:["c","h","ino"],load(){return Wt(()=>import("./index-BE1vSI6a.js"),[]).then(e=>e.cpp())}}),Ut.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return Wt(()=>import("./index-BE1vSI6a.js"),[]).then(e=>e.cpp())}}),Ut.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return vy("Cassandra")}}),Ut.of({name:"CSS",extensions:["css"],load(){return Wt(()=>Promise.resolve().then(()=>Rdn),void 0).then(e=>e.css())}}),Ut.of({name:"Go",extensions:["go"],load(){return Wt(()=>import("./index-Chop-Dpa.js"),[]).then(e=>e.go())}}),Ut.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return Wt(()=>Promise.resolve().then(()=>ffn),void 0).then(e=>e.html())}}),Ut.of({name:"Java",extensions:["java"],load(){return Wt(()=>import("./index-BKn4zRjf.js"),[]).then(e=>e.java())}}),Ut.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript())}}),Ut.of({name:"Jinja",extensions:["j2","jinja","jinja2"],load(){return Wt(()=>import("./index-DmjAbzHq.js"),[]).then(e=>e.jinja())}}),Ut.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Wt(()=>Promise.resolve().then(()=>$Mn),void 0).then(e=>e.json())}}),Ut.of({name:"JSX",extensions:["jsx"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript({jsx:!0}))}}),Ut.of({name:"LESS",extensions:["less"],load(){return Wt(()=>import("./index-D00XdcOq.js"),[]).then(e=>e.less())}}),Ut.of({name:"Liquid",extensions:["liquid"],load(){return Wt(()=>import("./index-BULll2e0.js"),[]).then(e=>e.liquid())}}),Ut.of({name:"MariaDB SQL",load(){return vy("MariaSQL")}}),Ut.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Wt(()=>Promise.resolve().then(()=>rhn),void 0).then(e=>e.markdown())}}),Ut.of({name:"MS SQL",load(){return vy("MSSQL")}}),Ut.of({name:"MySQL",load(){return vy("MySQL")}}),Ut.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return Wt(()=>import("./index-SkHIC7Ma.js"),[]).then(e=>e.php())}}),Ut.of({name:"PLSQL",extensions:["pls"],load(){return vy("PLSQL")}}),Ut.of({name:"PostgreSQL",load(){return vy("PostgreSQL")}}),Ut.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return Wt(()=>Promise.resolve().then(()=>JEn),void 0).then(e=>e.python())}}),Ut.of({name:"Rust",extensions:["rs"],load(){return Wt(()=>import("./index-D_K-9VDs.js"),[]).then(e=>e.rust())}}),Ut.of({name:"Sass",extensions:["sass"],load(){return Wt(()=>import("./index-B8q4cbOz.js"),[]).then(e=>e.sass({indented:!0}))}}),Ut.of({name:"SCSS",extensions:["scss"],load(){return Wt(()=>import("./index-B8q4cbOz.js"),[]).then(e=>e.sass())}}),Ut.of({name:"SQL",extensions:["sql"],load(){return vy("StandardSQL")}}),Ut.of({name:"SQLite",load(){return vy("SQLite")}}),Ut.of({name:"TSX",extensions:["tsx"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),Ut.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript({typescript:!0}))}}),Ut.of({name:"WebAssembly",extensions:["wat","wast"],load(){return Wt(()=>import("./index-Bwo-C8W5.js"),[]).then(e=>e.wast())}}),Ut.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return Wt(()=>import("./index-ByUFNj0O.js"),[]).then(e=>e.xml())}}),Ut.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return Wt(()=>Promise.resolve().then(()=>TDn),void 0).then(e=>e.yaml())}}),Ut.of({name:"APL",extensions:["dyalog","apl"],load(){return Wt(()=>import("./apl-B4CMkyY2.js"),[]).then(e=>bn(e.apl))}}),Ut.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return Wt(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(e=>bn(e.asciiArmor))}}),Ut.of({name:"ASN.1",extensions:["asn","asn1"],load(){return Wt(()=>import("./asn1-EdZsLKOL.js"),[]).then(e=>bn(e.asn1({})))}}),Ut.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return Wt(()=>import("./asterisk-B-8jnY81.js"),[]).then(e=>bn(e.asterisk))}}),Ut.of({name:"Brainfuck",extensions:["b","bf"],load(){return Wt(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(e=>bn(e.brainfuck))}}),Ut.of({name:"Cobol",extensions:["cob","cpy"],load(){return Wt(()=>import("./cobol-CWcv1MsR.js"),[]).then(e=>bn(e.cobol))}}),Ut.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.csharp))}}),Ut.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return Wt(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>bn(e.clojure))}}),Ut.of({name:"ClojureScript",extensions:["cljs"],load(){return Wt(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>bn(e.clojure))}}),Ut.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return Wt(()=>import("./css-BnMrqG3P.js"),[]).then(e=>bn(e.gss))}}),Ut.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return Wt(()=>import("./cmake-BQqOBYOt.js"),[]).then(e=>bn(e.cmake))}}),Ut.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return Wt(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(e=>bn(e.coffeeScript))}}),Ut.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return Wt(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(e=>bn(e.commonLisp))}}),Ut.of({name:"Cypher",extensions:["cyp","cypher"],load(){return Wt(()=>import("./cypher-C_CwsFkJ.js"),[]).then(e=>bn(e.cypher))}}),Ut.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return Wt(()=>import("./python-BuPzkPfP.js"),[]).then(e=>bn(e.cython))}}),Ut.of({name:"Crystal",extensions:["cr"],load(){return Wt(()=>import("./crystal-SjHAIU92.js"),[]).then(e=>bn(e.crystal))}}),Ut.of({name:"D",extensions:["d"],load(){return Wt(()=>import("./d-pRatUO7H.js"),[]).then(e=>bn(e.d))}}),Ut.of({name:"Dart",extensions:["dart"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.dart))}}),Ut.of({name:"diff",extensions:["diff","patch"],load(){return Wt(()=>import("./diff-DbItnlRl.js"),[]).then(e=>bn(e.diff))}}),Ut.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return Wt(()=>import("./dockerfile-BKs6k2Af.js"),__vite__mapDeps([0,1])).then(e=>bn(e.dockerFile))}}),Ut.of({name:"DTD",extensions:["dtd"],load(){return Wt(()=>import("./dtd-DF_7sFjM.js"),[]).then(e=>bn(e.dtd))}}),Ut.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return Wt(()=>import("./dylan-DwRh75JA.js"),[]).then(e=>bn(e.dylan))}}),Ut.of({name:"EBNF",load(){return Wt(()=>import("./ebnf-CDyGwa7X.js"),[]).then(e=>bn(e.ebnf))}}),Ut.of({name:"ECL",extensions:["ecl"],load(){return Wt(()=>import("./ecl-Cabwm37j.js"),[]).then(e=>bn(e.ecl))}}),Ut.of({name:"edn",extensions:["edn"],load(){return Wt(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>bn(e.clojure))}}),Ut.of({name:"Eiffel",extensions:["e"],load(){return Wt(()=>import("./eiffel-CnydiIhH.js"),[]).then(e=>bn(e.eiffel))}}),Ut.of({name:"Elm",extensions:["elm"],load(){return Wt(()=>import("./elm-vLlmbW-K.js"),[]).then(e=>bn(e.elm))}}),Ut.of({name:"Erlang",extensions:["erl"],load(){return Wt(()=>import("./erlang-BNw1qcRV.js"),[]).then(e=>bn(e.erlang))}}),Ut.of({name:"Esper",load(){return Wt(()=>import("./sql-D0XecflT.js"),[]).then(e=>bn(e.esper))}}),Ut.of({name:"Factor",extensions:["factor"],load(){return Wt(()=>import("./factor-kuTfRLto.js"),__vite__mapDeps([2,1])).then(e=>bn(e.factor))}}),Ut.of({name:"FCL",load(){return Wt(()=>import("./fcl-Kvtd6kyn.js"),[]).then(e=>bn(e.fcl))}}),Ut.of({name:"Forth",extensions:["forth","fth","4th"],load(){return Wt(()=>import("./forth-Ffai-XNe.js"),[]).then(e=>bn(e.forth))}}),Ut.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return Wt(()=>import("./fortran-DYz_wnZ1.js"),[]).then(e=>bn(e.fortran))}}),Ut.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return Wt(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>bn(e.fSharp))}}),Ut.of({name:"Gas",extensions:["s"],load(){return Wt(()=>import("./gas-Bneqetm1.js"),[]).then(e=>bn(e.gas))}}),Ut.of({name:"Gherkin",extensions:["feature"],load(){return Wt(()=>import("./gherkin-heZmZLOM.js"),[]).then(e=>bn(e.gherkin))}}),Ut.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return Wt(()=>import("./groovy-D9Dt4D0W.js"),[]).then(e=>bn(e.groovy))}}),Ut.of({name:"Haskell",extensions:["hs"],load(){return Wt(()=>import("./haskell-Cw1EW3IL.js"),[]).then(e=>bn(e.haskell))}}),Ut.of({name:"Haxe",extensions:["hx"],load(){return Wt(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>bn(e.haxe))}}),Ut.of({name:"HXML",extensions:["hxml"],load(){return Wt(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>bn(e.hxml))}}),Ut.of({name:"HTTP",load(){return Wt(()=>import("./http-DBlCnlav.js"),[]).then(e=>bn(e.http))}}),Ut.of({name:"IDL",extensions:["pro"],load(){return Wt(()=>import("./idl-BEugSyMb.js"),[]).then(e=>bn(e.idl))}}),Ut.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return Wt(()=>import("./javascript-iXu5QeM3.js"),[]).then(e=>bn(e.jsonld))}}),Ut.of({name:"Julia",extensions:["jl"],load(){return Wt(()=>import("./julia-DuME0IfC.js"),[]).then(e=>bn(e.julia))}}),Ut.of({name:"Kotlin",extensions:["kt","kts"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.kotlin))}}),Ut.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return Wt(()=>import("./livescript-BwQOo05w.js"),[]).then(e=>bn(e.liveScript))}}),Ut.of({name:"Lua",extensions:["lua"],load(){return Wt(()=>import("./lua-BgMRiT3U.js"),[]).then(e=>bn(e.lua))}}),Ut.of({name:"mIRC",extensions:["mrc"],load(){return Wt(()=>import("./mirc-CjQqDB4T.js"),[]).then(e=>bn(e.mirc))}}),Ut.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return Wt(()=>import("./mathematica-DTrFuWx2.js"),[]).then(e=>bn(e.mathematica))}}),Ut.of({name:"Modelica",extensions:["mo"],load(){return Wt(()=>import("./modelica-Dc1JOy9r.js"),[]).then(e=>bn(e.modelica))}}),Ut.of({name:"MUMPS",extensions:["mps"],load(){return Wt(()=>import("./mumps-BT43cFF4.js"),[]).then(e=>bn(e.mumps))}}),Ut.of({name:"Mbox",extensions:["mbox"],load(){return Wt(()=>import("./mbox-CNhZ1qSd.js"),[]).then(e=>bn(e.mbox))}}),Ut.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return Wt(()=>import("./nginx-DdIZxoE0.js"),[]).then(e=>bn(e.nginx))}}),Ut.of({name:"NSIS",extensions:["nsh","nsi"],load(){return Wt(()=>import("./nsis-LdVXkNf5.js"),__vite__mapDeps([3,1])).then(e=>bn(e.nsis))}}),Ut.of({name:"NTriples",extensions:["nt","nq"],load(){return Wt(()=>import("./ntriples-BfvgReVJ.js"),[]).then(e=>bn(e.ntriples))}}),Ut.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.objectiveC))}}),Ut.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.objectiveCpp))}}),Ut.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return Wt(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>bn(e.oCaml))}}),Ut.of({name:"Octave",extensions:["m"],load(){return Wt(()=>import("./octave-Ck1zUtKM.js"),[]).then(e=>bn(e.octave))}}),Ut.of({name:"Oz",extensions:["oz"],load(){return Wt(()=>import("./oz-BzwKVEFT.js"),[]).then(e=>bn(e.oz))}}),Ut.of({name:"Pascal",extensions:["p","pas"],load(){return Wt(()=>import("./pascal--L3eBynH.js"),[]).then(e=>bn(e.pascal))}}),Ut.of({name:"Perl",extensions:["pl","pm"],load(){return Wt(()=>import("./perl-CdXCOZ3F.js"),[]).then(e=>bn(e.perl))}}),Ut.of({name:"Pig",extensions:["pig"],load(){return Wt(()=>import("./pig-CevX1Tat.js"),[]).then(e=>bn(e.pig))}}),Ut.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return Wt(()=>import("./powershell-CFHJl5sT.js"),[]).then(e=>bn(e.powerShell))}}),Ut.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return Wt(()=>import("./properties-C78fOPTZ.js"),[]).then(e=>bn(e.properties))}}),Ut.of({name:"ProtoBuf",extensions:["proto"],load(){return Wt(()=>import("./protobuf-ChK-085T.js"),[]).then(e=>bn(e.protobuf))}}),Ut.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return Wt(()=>import("./pug-DeIclll2.js"),__vite__mapDeps([4,5])).then(e=>bn(e.pug))}}),Ut.of({name:"Puppet",extensions:["pp"],load(){return Wt(()=>import("./puppet-DMA9R1ak.js"),[]).then(e=>bn(e.puppet))}}),Ut.of({name:"Q",extensions:["q"],load(){return Wt(()=>import("./q-pXgVlZs6.js"),[]).then(e=>bn(e.q))}}),Ut.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return Wt(()=>import("./r-B6wPVr8A.js"),[]).then(e=>bn(e.r))}}),Ut.of({name:"RPM Changes",load(){return Wt(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>bn(e.rpmChanges))}}),Ut.of({name:"RPM Spec",extensions:["spec"],load(){return Wt(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>bn(e.rpmSpec))}}),Ut.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return Wt(()=>import("./ruby-B2Rjki9n.js"),[]).then(e=>bn(e.ruby))}}),Ut.of({name:"SAS",extensions:["sas"],load(){return Wt(()=>import("./sas-B4kiWyti.js"),[]).then(e=>bn(e.sas))}}),Ut.of({name:"Scala",extensions:["scala"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.scala))}}),Ut.of({name:"Scheme",extensions:["scm","ss"],load(){return Wt(()=>import("./scheme-C41bIUwD.js"),[]).then(e=>bn(e.scheme))}}),Ut.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Wt(()=>import("./shell-CjFT_Tl9.js"),[]).then(e=>bn(e.shell))}}),Ut.of({name:"Sieve",extensions:["siv","sieve"],load(){return Wt(()=>import("./sieve-C3Gn_uJK.js"),[]).then(e=>bn(e.sieve))}}),Ut.of({name:"Smalltalk",extensions:["st"],load(){return Wt(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(e=>bn(e.smalltalk))}}),Ut.of({name:"Solr",load(){return Wt(()=>import("./solr-DehyRSwq.js"),[]).then(e=>bn(e.solr))}}),Ut.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return Wt(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>bn(e.sml))}}),Ut.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return Wt(()=>import("./sparql-DkYu6x3z.js"),[]).then(e=>bn(e.sparql))}}),Ut.of({name:"Spreadsheet",alias:["excel","formula"],load(){return Wt(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(e=>bn(e.spreadsheet))}}),Ut.of({name:"Squirrel",extensions:["nut"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.squirrel))}}),Ut.of({name:"Stylus",extensions:["styl"],load(){return Wt(()=>import("./stylus-B533Al4x.js"),[]).then(e=>bn(e.stylus))}}),Ut.of({name:"Swift",extensions:["swift"],load(){return Wt(()=>import("./swift-BzpIVaGY.js"),[]).then(e=>bn(e.swift))}}),Ut.of({name:"sTeX",load(){return Wt(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>bn(e.stex))}}),Ut.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return Wt(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>bn(e.stex))}}),Ut.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return Wt(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>bn(e.verilog))}}),Ut.of({name:"Tcl",extensions:["tcl"],load(){return Wt(()=>import("./tcl-DVfN8rqt.js"),[]).then(e=>bn(e.tcl))}}),Ut.of({name:"Textile",extensions:["textile"],load(){return Wt(()=>import("./textile-CnDTJFAw.js"),[]).then(e=>bn(e.textile))}}),Ut.of({name:"TiddlyWiki",load(){return Wt(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(e=>bn(e.tiddlyWiki))}}),Ut.of({name:"Tiki wiki",load(){return Wt(()=>import("./tiki-DGYXhP31.js"),[]).then(e=>bn(e.tiki))}}),Ut.of({name:"TOML",extensions:["toml"],load(){return Wt(()=>import("./toml-Bm5Em-hy.js"),[]).then(e=>bn(e.toml))}}),Ut.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return Wt(()=>import("./troff-wAsdV37c.js"),[]).then(e=>bn(e.troff))}}),Ut.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return Wt(()=>import("./ttcn-CfJYG6tj.js"),[]).then(e=>bn(e.ttcn))}}),Ut.of({name:"TTCN_CFG",extensions:["cfg"],load(){return Wt(()=>import("./ttcn-cfg-B9xdYoR4.js"),[]).then(e=>bn(e.ttcnCfg))}}),Ut.of({name:"Turtle",extensions:["ttl"],load(){return Wt(()=>import("./turtle-B1tBg_DP.js"),[]).then(e=>bn(e.turtle))}}),Ut.of({name:"Web IDL",extensions:["webidl"],load(){return Wt(()=>import("./webidl-ZXfAyPTL.js"),[]).then(e=>bn(e.webIDL))}}),Ut.of({name:"VB.NET",extensions:["vb"],load(){return Wt(()=>import("./vb-CmGdzxic.js"),[]).then(e=>bn(e.vb))}}),Ut.of({name:"VBScript",extensions:["vbs"],load(){return Wt(()=>import("./vbscript-BuJXcnF6.js"),[]).then(e=>bn(e.vbScript))}}),Ut.of({name:"Velocity",extensions:["vtl"],load(){return Wt(()=>import("./velocity-D8B20fx6.js"),[]).then(e=>bn(e.velocity))}}),Ut.of({name:"Verilog",extensions:["v"],load(){return Wt(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>bn(e.verilog))}}),Ut.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return Wt(()=>import("./vhdl-lSbBsy5d.js"),[]).then(e=>bn(e.vhdl))}}),Ut.of({name:"XQuery",extensions:["xy","xquery","xq","xqm","xqy"],load(){return Wt(()=>import("./xquery-DzFWVndE.js"),[]).then(e=>bn(e.xQuery))}}),Ut.of({name:"Yacas",extensions:["ys"],load(){return Wt(()=>import("./yacas-BJ4BC0dw.js"),[]).then(e=>bn(e.yacas))}}),Ut.of({name:"Z80",extensions:["z80"],load(){return Wt(()=>import("./z80-Hz9HOZM7.js"),[]).then(e=>bn(e.z80))}}),Ut.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return Wt(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>bn(e.mscgen))}}),Ut.of({name:"Xù",extensions:["xu"],load(){return Wt(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>bn(e.xu))}}),Ut.of({name:"MsGenny",extensions:["msgenny"],load(){return Wt(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>bn(e.msgenny))}}),Ut.of({name:"Vue",extensions:["vue"],load(){return Wt(()=>import("./index-BjxRqzZK.js"),[]).then(e=>e.vue())}}),Ut.of({name:"Angular Template",load(){return Wt(()=>import("./index-DiMDROQY.js"),[]).then(e=>e.angular())}})],mOe="#2e3440",Age="#3b4252",pOe="#434c5e",nz="#4c566a",gOe="#e5e9f0",Koe="#eceff4",HJ="#8fbcbb",xOe="#88c0d0",mfn="#81a1c1",$p="#5e81ac",pfn="#bf616a",dk="#d08770",XJ="#ebcb8b",bOe="#a3be8c",gfn="#b48ead",yOe="#d30102",hge=Koe,GJ=hge,xfn="#ffffff",YJ=Age,bfn=hge,vOe=Age,yfn=Fn.theme({"&":{color:mOe,backgroundColor:xfn},".cm-content":{caretColor:vOe},".cm-cursor, .cm-dropCursor":{borderLeftColor:vOe},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:bfn},".cm-panels":{backgroundColor:hge,color:nz},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${nz}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:gOe},".cm-activeLine":{backgroundColor:GJ},".cm-selectionMatch":{backgroundColor:gOe},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${nz}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:Koe},".cm-gutters":{backgroundColor:Koe,color:mOe,border:"none"},".cm-activeLineGutter":{backgroundColor:GJ},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:YJ},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:YJ,borderBottomColor:YJ},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:GJ,color:nz}}},{dark:!1}),vfn=a8.define([{tag:Le.keyword,color:$p},{tag:[Le.name,Le.deleted,Le.character,Le.propertyName,Le.macroName],color:dk},{tag:[Le.variableName],color:dk},{tag:[Le.function(Le.variableName)],color:$p},{tag:[Le.labelName],color:mfn},{tag:[Le.color,Le.constant(Le.name),Le.standard(Le.name)],color:$p},{tag:[Le.definition(Le.name),Le.separator],color:bOe},{tag:[Le.brace],color:HJ},{tag:[Le.annotation],color:yOe},{tag:[Le.number,Le.changed,Le.annotation,Le.modifier,Le.self,Le.namespace],color:xOe},{tag:[Le.typeName,Le.className],color:XJ},{tag:[Le.operator,Le.operatorKeyword],color:bOe},{tag:[Le.tagName],color:gfn},{tag:[Le.squareBracket],color:pfn},{tag:[Le.angleBracket],color:dk},{tag:[Le.attributeName],color:XJ},{tag:[Le.regexp],color:$p},{tag:[Le.quote],color:Age},{tag:[Le.string],color:dk},{tag:Le.link,color:HJ,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[Le.url,Le.escape,Le.special(Le.string)],color:dk},{tag:[Le.meta],color:xOe},{tag:[Le.comment],color:pOe,fontStyle:"italic"},{tag:Le.strong,fontWeight:"bold",color:$p},{tag:Le.emphasis,fontStyle:"italic",color:$p},{tag:Le.strikethrough,textDecoration:"line-through"},{tag:Le.heading,fontWeight:"bold",color:$p},{tag:Le.special(Le.heading1),fontWeight:"bold",color:$p},{tag:Le.heading1,fontWeight:"bold",color:$p},{tag:[Le.heading2,Le.heading3,Le.heading4],fontWeight:"bold",color:$p},{tag:[Le.heading5,Le.heading6],color:$p},{tag:[Le.atom,Le.bool,Le.special(Le.variableName)],color:dk},{tag:[Le.processingInstruction,Le.inserted],color:HJ},{tag:[Le.contentSeparator],color:XJ},{tag:Le.invalid,color:pOe,borderBottom:`1px dotted ${yOe}`}]),wfn=[yfn,yZ(vfn)],wOe=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class BS{constructor(t,n,r=0,s=t.length,a,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(wOe(l)):wOe,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return EA(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=dpe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=tx(t);let s=this.normalize(n);if(s.length)for(let a=0,o=r;;a++){let l=s.charCodeAt(a),c=this.match(l,o,this.bufferPos+this.bufferStart);if(a==s.length-1){if(c)return this.value=c,this;break}o==r&&a<n.length&&n.charCodeAt(a)==l&&o++}}}match(t,n,r){let s=null;for(let a=0;a<this.matches.length;a+=2){let o=this.matches[a],l=!1;this.query.charCodeAt(o)==t&&(o==this.query.length-1?s={from:this.matches[a+1],to:r}:(this.matches[a]++,l=!0)),l||(this.matches.splice(a,2),a-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(BS.prototype[Symbol.iterator]=function(){return this});const _et={from:-1,to:-1,match:/.*/.exec("")},mge="gm"+(/x/.unicode==null?"":"u");class Met{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=_et,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new Eet(t,n,r,s,a);this.re=new RegExp(n,mge+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let o=t.lineAt(s);this.curLineStart=o.from,this.matchPos=DU(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=DU(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const JJ=new WeakMap;class cO{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=JJ.get(t);if(!s||s.from>=r||s.to<=n){let l=new cO(n,t.sliceString(n,r));return JJ.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:o}=s;return o>n&&(a=t.sliceString(n,o)+a,o=n),s.to<r&&(a+=t.sliceString(s.to,r)),JJ.set(t,new cO(o,a)),new cO(n,a.slice(n-o,r-o))}}class Eet{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=_et,this.matchPos=DU(t,s),this.re=new RegExp(n,mge+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=cO.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=DU(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=cO.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Met.prototype[Symbol.iterator]=Eet.prototype[Symbol.iterator]=function(){return this});function kfn(e){try{return new RegExp(e,mge),!0}catch{return!1}}function DU(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const Ofn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=pan(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let o=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!o){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,d,u,f]=o,A=u?+u.slice(1):0,m=d?+d:l.number;if(d&&f){let y=m/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),m=Math.round(t.doc.lines*y)}else d&&c&&(m=m*(c=="-"?-1:1)+l.number);let g=t.doc.line(Math.max(1,Math.min(t.doc.lines,m))),x=Ht.cursor(g.from+Math.max(0,Math.min(A,g.length)));e.dispatch({effects:[r,Fn.scrollIntoView(x.from,{y:"center"})],selection:x})}),!0},Sfn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},jfn=cr.define({combine(e){return Xx(e,Sfn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function Cfn(e){return[_fn,Tfn]}const Nfn=gr.mark({class:"cm-selectionMatch"}),Pfn=gr.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function kOe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=Cl.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=Cl.Word)}function Ifn(e,t,n,r){return e(t.sliceDoc(n,n+1))==Cl.Word&&e(t.sliceDoc(r-1,r))==Cl.Word}const Tfn=Sc.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(jfn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return gr.none;let s=r.main,a,o=null;if(s.empty){if(!t.highlightWordAroundCursor)return gr.none;let c=n.wordAt(s.head);if(!c)return gr.none;o=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return gr.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),o=n.charCategorizer(s.head),!(kOe(o,n,s.from,s.to)&&Ifn(o,n,s.from,s.to)))return gr.none}else if(a=n.sliceDoc(s.from,s.to),!a)return gr.none}let l=[];for(let c of e.visibleRanges){let d=new BS(n.doc,a,c.from,c.to);for(;!d.next().done;){let{from:u,to:f}=d.value;if((!o||kOe(o,n,u,f))&&(s.empty&&u<=s.from&&f>=s.to?l.push(Pfn.range(u,f)):(u>=s.to||f<=s.from)&&l.push(Nfn.range(u,f)),l.length>t.maxMatches))return gr.none}}return gr.set(l)}},{decorations:e=>e.decorations}),_fn=Fn.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Mfn=({state:e,dispatch:t})=>{let{selection:n}=e,r=Ht.create(n.ranges.map(s=>e.wordAt(s.head)||Ht.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function Efn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let o=!1,l=new BS(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new BS(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),o=!0}else{if(o&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const Dfn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return Mfn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=Efn(e,r);return s?(t(e.update({selection:e.selection.addRange(Ht.range(s.from,s.to),!1),effects:Fn.scrollIntoView(s.to)})),!0):!1},wC=cr.define({combine(e){return Xx(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new Hfn(t),scrollToMatch:t=>Fn.scrollIntoView(t)})}});class Det{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||kfn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
1795
+ }`,{label:"class",detail:"definition",type:"keyword"}),zl('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),zl('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],det=oge.concat([zl("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),zl("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),zl("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),cOe=new _pe,uet=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function aN(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const Yun=["FunctionDeclaration"],Jun={FunctionDeclaration:aN("function"),ClassDeclaration:aN("class"),ClassExpression:()=>!0,EnumDeclaration:aN("constant"),TypeAliasDeclaration:aN("type"),NamespaceDeclaration:aN("namespace"),VariableDefinition(e,t){e.matchContext(Yun)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function fet(e,t){let n=cOe.get(t);if(n)return n;let r=[],s=!0;function a(o,l){let c=e.sliceString(o.from,o.to);r.push({label:c,type:l})}return t.cursor(Za.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let l=Jun[o.name];if(l&&l(o,a)||uet.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of fet(e,o.node))r.push(l);return!1}}),cOe.set(t,r),r}const MU=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,lge=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Aet(e){let t=Pa(e.state).resolveInner(e.pos,-1);if(lge.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&MU.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)uet.has(s.name)&&(r=r.concat(fet(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:MU}}function qJ(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,o;if((a==null?void 0:a.name)=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if((a==null?void 0:a.name)=="MemberExpression"&&((r=o=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(o)),t=a;else return null}}function het(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=Pa(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?qJ(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?qJ(t,n.parent,""):lge.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&MU.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?qJ(t,n,""):e.explicit?{path:[],name:""}:null}function efn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let o=Object.getPrototypeOf(e);if(!o)return r;e=o}}function tfn(e){let t=new Map;return n=>{let r=het(n);if(!r)return null;let s=e;for(let o of r.path)if(s=s[o],!s)return null;let a=t.get(s);return a||t.set(s,a=efn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:MU}}}const Hm=Lx.define({name:"javascript",parser:Gun.configure({props:[_b.add({IfStatement:aO({except:/^\s*({|else\b)/}),TryStatement:aO({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:aon,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:iO({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":aO({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),Mb.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":sD,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),met={test:e=>/^JSX/.test(e.name),facet:gZ({commentTokens:{block:{open:"{/*",close:"*/}"}}})},cge=Hm.configure({dialect:"ts"},"typescript"),dge=Hm.configure({dialect:"jsx",props:[Epe.add(e=>e.isTop?[met]:void 0)]}),uge=Hm.configure({dialect:"jsx ts",props:[Epe.add(e=>e.isTop?[met]:void 0)]},"typescript");let pet=e=>({label:e,type:"keyword"});const get="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(pet),nfn=get.concat(["declare","implements","private","protected","public"].map(pet));function EU(e={}){let t=e.jsx?e.typescript?uge:dge:e.typescript?cge:Hm,n=e.typescript?det.concat(nfn):oge.concat(get);return new Qg(t,[Hm.data.of({autocomplete:eJe(lge,Bpe(n))}),Hm.data.of({autocomplete:Aet}),e.jsx?xet:[]])}function rfn(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function dOe(e,t,n=e.length){for(let r=t==null?void 0:t.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const sfn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),xet=Fn.inputHandler.of((e,t,n,r,s)=>{if((sfn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Hm.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d;let{head:u}=c,f=Pa(o).resolveInner(u-1,-1),A;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(u-1,u)!=r||f.name=="JSXAttributeValue"&&f.to>u)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:u,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let m=f.parent,g=m.parent;if(g&&m.from==u-2&&((A=dOe(o.doc,g.firstChild,u))||((d=g.firstChild)===null||d===void 0?void 0:d.name)=="JSXFragmentTag")){let x=`${A}>`;return{range:Ht.cursor(u+x.length,-1),changes:{from:u,insert:x}}}}else if(r==">"){let m=rfn(f);if(m&&m.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(u,u+2))&&(A=dOe(o.doc,m,u)))return{range:c,changes:{from:u,insert:`</${A}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function ifn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:o}of Hm.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let d of e.verify(r.sliceDoc(a,o),t))s.push(afn(d,r.doc,c))}return s}}function uOe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function afn(e,t,n){let r=uOe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?uOe(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:o}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(d,u){d.dispatch({changes:{from:u+l,to:u+c,insert:o},scrollIntoView:!0})}}]}return s}const tz=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:xet,completionPath:het,esLint:ifn,javascript:EU,javascriptLanguage:Hm,jsxLanguage:dge,localCompletionSource:Aet,scopeCompletionSource:tfn,snippets:oge,tsxLanguage:uge,typescriptLanguage:cge,typescriptSnippets:det},Symbol.toStringTag,{value:"Module"})),oN=["_blank","_self","_top","_parent"],KJ=["ascii","utf-8","utf-16","latin1","latin1"],WJ=["get","post","put","delete"],ZJ=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],wh=["true","false"],Qr={},ofn={a:{attrs:{href:null,ping:null,type:null,media:null,target:oN,hreflang:null}},abbr:Qr,address:Qr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Qr,aside:Qr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Qr,base:{attrs:{href:null,target:oN}},bdi:Qr,bdo:Qr,blockquote:{attrs:{cite:null}},body:Qr,br:Qr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:ZJ,formmethod:WJ,formnovalidate:["novalidate"],formtarget:oN,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Qr,center:Qr,cite:Qr,code:Qr,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Qr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Qr,div:Qr,dl:Qr,dt:Qr,em:Qr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Qr,figure:Qr,footer:Qr,form:{attrs:{action:null,name:null,"accept-charset":KJ,autocomplete:["on","off"],enctype:ZJ,method:WJ,novalidate:["novalidate"],target:oN}},h1:Qr,h2:Qr,h3:Qr,h4:Qr,h5:Qr,h6:Qr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Qr,hgroup:Qr,hr:Qr,html:{attrs:{manifest:null}},i:Qr,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:ZJ,formmethod:WJ,formnovalidate:["novalidate"],formtarget:oN,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Qr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Qr,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Qr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:KJ,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Qr,noscript:Qr,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Qr,param:{attrs:{name:null,value:null}},pre:Qr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Qr,rt:Qr,ruby:Qr,samp:Qr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:KJ}},section:Qr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Qr,source:{attrs:{src:null,type:null,media:null}},span:Qr,strong:Qr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Qr,summary:Qr,sup:Qr,table:Qr,tbody:Qr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Qr,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Qr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Qr,time:{attrs:{datetime:null}},title:Qr,tr:Qr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Qr,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Qr},bet={accesskey:null,class:null,contenteditable:wh,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:wh,autocorrect:wh,autocapitalize:wh,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":wh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":wh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":wh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":wh,"aria-hidden":wh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":wh,"aria-multiselectable":wh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":wh,"aria-relevant":null,"aria-required":wh,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},yet="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of yet)bet[e]=null;let a_=class{constructor(t,n){this.tags={...ofn,...t},this.globalAttrs={...bet,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}};a_.default=new a_;function $S(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function FS(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function vet(e,t,n){let r=n.tags[$S(e,FS(t))];return(r==null?void 0:r.children)||n.allTags}function fge(e,t){let n=[];for(let r=FS(t);r&&!r.type.isTop;r=FS(r.parent)){let s=$S(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const wet=/^[:\-\.\w\u00b7-\uffff]*$/;function fOe(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",o=FS(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:vet(e.doc,o,t).map(l=>({label:l,type:"type"})).concat(fge(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function AOe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:fge(e.doc,t).map((a,o)=>({label:a,apply:a+s,type:"type",boost:99-o})),validFor:wet}}function lfn(e,t,n,r){let s=[],a=0;for(let o of vet(e.doc,n,t))s.push({label:"<"+o,type:"type"});for(let o of fge(e.doc,n))s.push({label:"</"+o+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function cfn(e,t,n,r,s){let a=FS(n),o=a?t.tags[$S(e.doc,a)]:null,l=o&&o.attrs?Object.keys(o.attrs):[],c=o&&o.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(d=>({label:d,type:"property"})),validFor:wet}}function dfn(e,t,n,r,s){var a;let o=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(o){let d=e.sliceDoc(o.from,o.to),u=t.globalAttrs[d];if(!u){let f=FS(n),A=f?t.tags[$S(e.doc,f)]:null;u=(A==null?void 0:A.attrs)&&A.attrs[d]}if(u){let f=e.sliceDoc(r,s).toLowerCase(),A='"',m='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,A="",m=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let g of u)l.push({label:g,apply:A+g+m,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function ket(e,t){let{state:n,pos:r}=t,s=Pa(n).resolveInner(r,-1),a=s.resolve(r);for(let o=r,l;a==s&&(l=s.childBefore(o));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,o=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?AOe(n,s,s.from,r):fOe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?fOe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?AOe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?cfn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?dfn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?lfn(n,e,s,r):null}function Oet(e){return ket(a_.default,e)}function jet(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new a_(t,n):a_.default;return s=>ket(r,s)}const ufn=Hm.parser.configure({top:"SingleExpression"}),Cet=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:cge.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:dge.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:uge.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:ufn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Hm.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:i_.parser}],Net=[{name:"style",parser:i_.parser.configure({top:"Styles"})}].concat(yet.map(e=>({name:e,parser:Hm.parser}))),Pet=Lx.define({name:"html",parser:yun.configure({props:[_b.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),Mb.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),WYe.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),AI=Pet.configure({wrap:oet(Cet,Net)});function Iet(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=oet((e.nestedLanguages||[]).concat(Cet),(e.nestedAttributes||[]).concat(Net)));let r=n?Pet.configure({wrap:n,dialect:t}):t?AI.configure({dialect:t}):AI;return new Qg(r,[AI.data.of({autocomplete:jet(e)}),e.autoCloseTags!==!1?Tet:[],EU().support,GJe().support])}const hOe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),Tet=Fn.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!AI.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d,u,f;let A=o.doc.sliceString(c.from-1,c.to)==r,{head:m}=c,g=Pa(o).resolveInner(m,-1),x;if(A&&r==">"&&g.name=="EndTag"){let y=g.parent;if(((u=(d=y.parent)===null||d===void 0?void 0:d.lastChild)===null||u===void 0?void 0:u.name)!="CloseTag"&&(x=$S(o.doc,y.parent,m))&&!hOe.has(x)){let v=m+(o.doc.sliceString(m,m+1)===">"?1:0),w=`</${x}>`;return{range:c,changes:{from:m,to:v,insert:w}}}}else if(A&&r=="/"&&g.name=="IncompleteCloseTag"){let y=g.parent;if(g.from==m-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(x=$S(o.doc,y,m))&&!hOe.has(x)){let v=m+(o.doc.sliceString(m,m+1)===">"?1:0),w=`${x}>`;return{range:Ht.cursor(m+w.length,-1),changes:{from:m,to:v,insert:w}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),ffn=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:Tet,html:Iet,htmlCompletionSource:Oet,htmlCompletionSourceWith:jet,htmlLanguage:AI},Symbol.toStringTag,{value:"Module"}));function Afn(e,t,n,r){const s=Ex(jl),a=Bh(CHe),o=ye.useRef(null),{lexicalNode:l}=Kae(),c=ye.useRef(!1),d=ye.useRef(!1),u=ye.useCallback(()=>{a({editorType:t,rootNode:l,editorRef:o.current})},[t,l,a]),f=ye.useCallback(A=>{var m,g,x,y,v,w;if(A.key==="ArrowDown"){const k=(g=(m=o.current)==null?void 0:m.getCodemirror())==null?void 0:g.state;if(k){const S=k.doc.length,j=k.selection.ranges[0].to;S===j&&(c.current?(s==null||s.update(()=>{var C,N;const P=vx(e);P.getNextSibling()?((N=(C=o.current)==null?void 0:C.getCodemirror())==null||N.contentDOM.blur(),P.selectNext()):P.insertAfter(Fo())}),c.current=!1):c.current=!0)}}else if(A.key==="ArrowUp"){const k=(y=(x=o.current)==null?void 0:x.getCodemirror())==null?void 0:y.state;k&&k.selection.ranges[0].from===0&&(d.current?(s==null||s.update(()=>{var j,C;const N=vx(e);N.getPreviousSibling()&&((C=(j=o.current)==null?void 0:j.getCodemirror())==null||C.contentDOM.blur(),N.selectPrevious())}),d.current=!1):d.current=!0)}else if(A.key==="Enter")A.stopPropagation();else if(A.key==="Backspace"||A.key==="Delete"){const k=(w=(v=o.current)==null?void 0:v.getCodemirror())==null?void 0:w.state;(k==null?void 0:k.doc.length)===0&&(s==null||s.update(()=>{vx(e).remove()}))}},[s,e]);return ye.useEffect(()=>{const A=o.current;return setTimeout(()=>{var m,g;(m=A==null?void 0:A.getCodemirror())==null||m.contentDOM.addEventListener("focus",u),(g=A==null?void 0:A.getCodemirror())==null||g.contentDOM.addEventListener("keydown",f)},300),()=>{var m,g;(m=A==null?void 0:A.getCodemirror())==null||m.contentDOM.removeEventListener("focus",u),(g=A==null?void 0:A.getCodemirror())==null||g.contentDOM.removeEventListener("keydown",f)}},[o,u,f,n]),ye.useEffect(()=>{r.subscribe(()=>{var A,m;(m=(A=o.current)==null?void 0:A.getCodemirror())==null||m.focus(),u()})},[r,o,e,u]),o}function bn(e){return new Qg(Lpe.define(e))}function vy(e){return Wt(()=>import("./index-BYt_CWxk.js"),[]).then(t=>t.sql({dialect:t[e]}))}const hfn=[Ut.of({name:"C",extensions:["c","h","ino"],load(){return Wt(()=>import("./index-96_7QHQ5.js"),[]).then(e=>e.cpp())}}),Ut.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return Wt(()=>import("./index-96_7QHQ5.js"),[]).then(e=>e.cpp())}}),Ut.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return vy("Cassandra")}}),Ut.of({name:"CSS",extensions:["css"],load(){return Wt(()=>Promise.resolve().then(()=>Rdn),void 0).then(e=>e.css())}}),Ut.of({name:"Go",extensions:["go"],load(){return Wt(()=>import("./index-CjRwrGKt.js"),[]).then(e=>e.go())}}),Ut.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return Wt(()=>Promise.resolve().then(()=>ffn),void 0).then(e=>e.html())}}),Ut.of({name:"Java",extensions:["java"],load(){return Wt(()=>import("./index-DTqh4VW9.js"),[]).then(e=>e.java())}}),Ut.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript())}}),Ut.of({name:"Jinja",extensions:["j2","jinja","jinja2"],load(){return Wt(()=>import("./index-9ogi82-q.js"),[]).then(e=>e.jinja())}}),Ut.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Wt(()=>Promise.resolve().then(()=>$Mn),void 0).then(e=>e.json())}}),Ut.of({name:"JSX",extensions:["jsx"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript({jsx:!0}))}}),Ut.of({name:"LESS",extensions:["less"],load(){return Wt(()=>import("./index-CrOrmmHY.js"),[]).then(e=>e.less())}}),Ut.of({name:"Liquid",extensions:["liquid"],load(){return Wt(()=>import("./index-CaNgMg06.js"),[]).then(e=>e.liquid())}}),Ut.of({name:"MariaDB SQL",load(){return vy("MariaSQL")}}),Ut.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Wt(()=>Promise.resolve().then(()=>rhn),void 0).then(e=>e.markdown())}}),Ut.of({name:"MS SQL",load(){return vy("MSSQL")}}),Ut.of({name:"MySQL",load(){return vy("MySQL")}}),Ut.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return Wt(()=>import("./index-BT3SfQnV.js"),[]).then(e=>e.php())}}),Ut.of({name:"PLSQL",extensions:["pls"],load(){return vy("PLSQL")}}),Ut.of({name:"PostgreSQL",load(){return vy("PostgreSQL")}}),Ut.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return Wt(()=>Promise.resolve().then(()=>JEn),void 0).then(e=>e.python())}}),Ut.of({name:"Rust",extensions:["rs"],load(){return Wt(()=>import("./index-CRe48ije.js"),[]).then(e=>e.rust())}}),Ut.of({name:"Sass",extensions:["sass"],load(){return Wt(()=>import("./index-CG59QbM3.js"),[]).then(e=>e.sass({indented:!0}))}}),Ut.of({name:"SCSS",extensions:["scss"],load(){return Wt(()=>import("./index-CG59QbM3.js"),[]).then(e=>e.sass())}}),Ut.of({name:"SQL",extensions:["sql"],load(){return vy("StandardSQL")}}),Ut.of({name:"SQLite",load(){return vy("SQLite")}}),Ut.of({name:"TSX",extensions:["tsx"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),Ut.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Wt(()=>Promise.resolve().then(()=>tz),void 0).then(e=>e.javascript({typescript:!0}))}}),Ut.of({name:"WebAssembly",extensions:["wat","wast"],load(){return Wt(()=>import("./index-DFhr5xg9.js"),[]).then(e=>e.wast())}}),Ut.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return Wt(()=>import("./index-Cjq0R1QI.js"),[]).then(e=>e.xml())}}),Ut.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return Wt(()=>Promise.resolve().then(()=>TDn),void 0).then(e=>e.yaml())}}),Ut.of({name:"APL",extensions:["dyalog","apl"],load(){return Wt(()=>import("./apl-B4CMkyY2.js"),[]).then(e=>bn(e.apl))}}),Ut.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return Wt(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(e=>bn(e.asciiArmor))}}),Ut.of({name:"ASN.1",extensions:["asn","asn1"],load(){return Wt(()=>import("./asn1-EdZsLKOL.js"),[]).then(e=>bn(e.asn1({})))}}),Ut.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return Wt(()=>import("./asterisk-B-8jnY81.js"),[]).then(e=>bn(e.asterisk))}}),Ut.of({name:"Brainfuck",extensions:["b","bf"],load(){return Wt(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(e=>bn(e.brainfuck))}}),Ut.of({name:"Cobol",extensions:["cob","cpy"],load(){return Wt(()=>import("./cobol-CWcv1MsR.js"),[]).then(e=>bn(e.cobol))}}),Ut.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.csharp))}}),Ut.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return Wt(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>bn(e.clojure))}}),Ut.of({name:"ClojureScript",extensions:["cljs"],load(){return Wt(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>bn(e.clojure))}}),Ut.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return Wt(()=>import("./css-BnMrqG3P.js"),[]).then(e=>bn(e.gss))}}),Ut.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return Wt(()=>import("./cmake-BQqOBYOt.js"),[]).then(e=>bn(e.cmake))}}),Ut.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return Wt(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(e=>bn(e.coffeeScript))}}),Ut.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return Wt(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(e=>bn(e.commonLisp))}}),Ut.of({name:"Cypher",extensions:["cyp","cypher"],load(){return Wt(()=>import("./cypher-C_CwsFkJ.js"),[]).then(e=>bn(e.cypher))}}),Ut.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return Wt(()=>import("./python-BuPzkPfP.js"),[]).then(e=>bn(e.cython))}}),Ut.of({name:"Crystal",extensions:["cr"],load(){return Wt(()=>import("./crystal-SjHAIU92.js"),[]).then(e=>bn(e.crystal))}}),Ut.of({name:"D",extensions:["d"],load(){return Wt(()=>import("./d-pRatUO7H.js"),[]).then(e=>bn(e.d))}}),Ut.of({name:"Dart",extensions:["dart"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.dart))}}),Ut.of({name:"diff",extensions:["diff","patch"],load(){return Wt(()=>import("./diff-DbItnlRl.js"),[]).then(e=>bn(e.diff))}}),Ut.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return Wt(()=>import("./dockerfile-BKs6k2Af.js"),__vite__mapDeps([0,1])).then(e=>bn(e.dockerFile))}}),Ut.of({name:"DTD",extensions:["dtd"],load(){return Wt(()=>import("./dtd-DF_7sFjM.js"),[]).then(e=>bn(e.dtd))}}),Ut.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return Wt(()=>import("./dylan-DwRh75JA.js"),[]).then(e=>bn(e.dylan))}}),Ut.of({name:"EBNF",load(){return Wt(()=>import("./ebnf-CDyGwa7X.js"),[]).then(e=>bn(e.ebnf))}}),Ut.of({name:"ECL",extensions:["ecl"],load(){return Wt(()=>import("./ecl-Cabwm37j.js"),[]).then(e=>bn(e.ecl))}}),Ut.of({name:"edn",extensions:["edn"],load(){return Wt(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>bn(e.clojure))}}),Ut.of({name:"Eiffel",extensions:["e"],load(){return Wt(()=>import("./eiffel-CnydiIhH.js"),[]).then(e=>bn(e.eiffel))}}),Ut.of({name:"Elm",extensions:["elm"],load(){return Wt(()=>import("./elm-vLlmbW-K.js"),[]).then(e=>bn(e.elm))}}),Ut.of({name:"Erlang",extensions:["erl"],load(){return Wt(()=>import("./erlang-BNw1qcRV.js"),[]).then(e=>bn(e.erlang))}}),Ut.of({name:"Esper",load(){return Wt(()=>import("./sql-D0XecflT.js"),[]).then(e=>bn(e.esper))}}),Ut.of({name:"Factor",extensions:["factor"],load(){return Wt(()=>import("./factor-kuTfRLto.js"),__vite__mapDeps([2,1])).then(e=>bn(e.factor))}}),Ut.of({name:"FCL",load(){return Wt(()=>import("./fcl-Kvtd6kyn.js"),[]).then(e=>bn(e.fcl))}}),Ut.of({name:"Forth",extensions:["forth","fth","4th"],load(){return Wt(()=>import("./forth-Ffai-XNe.js"),[]).then(e=>bn(e.forth))}}),Ut.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return Wt(()=>import("./fortran-DYz_wnZ1.js"),[]).then(e=>bn(e.fortran))}}),Ut.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return Wt(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>bn(e.fSharp))}}),Ut.of({name:"Gas",extensions:["s"],load(){return Wt(()=>import("./gas-Bneqetm1.js"),[]).then(e=>bn(e.gas))}}),Ut.of({name:"Gherkin",extensions:["feature"],load(){return Wt(()=>import("./gherkin-heZmZLOM.js"),[]).then(e=>bn(e.gherkin))}}),Ut.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return Wt(()=>import("./groovy-D9Dt4D0W.js"),[]).then(e=>bn(e.groovy))}}),Ut.of({name:"Haskell",extensions:["hs"],load(){return Wt(()=>import("./haskell-Cw1EW3IL.js"),[]).then(e=>bn(e.haskell))}}),Ut.of({name:"Haxe",extensions:["hx"],load(){return Wt(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>bn(e.haxe))}}),Ut.of({name:"HXML",extensions:["hxml"],load(){return Wt(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>bn(e.hxml))}}),Ut.of({name:"HTTP",load(){return Wt(()=>import("./http-DBlCnlav.js"),[]).then(e=>bn(e.http))}}),Ut.of({name:"IDL",extensions:["pro"],load(){return Wt(()=>import("./idl-BEugSyMb.js"),[]).then(e=>bn(e.idl))}}),Ut.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return Wt(()=>import("./javascript-iXu5QeM3.js"),[]).then(e=>bn(e.jsonld))}}),Ut.of({name:"Julia",extensions:["jl"],load(){return Wt(()=>import("./julia-DuME0IfC.js"),[]).then(e=>bn(e.julia))}}),Ut.of({name:"Kotlin",extensions:["kt","kts"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.kotlin))}}),Ut.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return Wt(()=>import("./livescript-BwQOo05w.js"),[]).then(e=>bn(e.liveScript))}}),Ut.of({name:"Lua",extensions:["lua"],load(){return Wt(()=>import("./lua-BgMRiT3U.js"),[]).then(e=>bn(e.lua))}}),Ut.of({name:"mIRC",extensions:["mrc"],load(){return Wt(()=>import("./mirc-CjQqDB4T.js"),[]).then(e=>bn(e.mirc))}}),Ut.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return Wt(()=>import("./mathematica-DTrFuWx2.js"),[]).then(e=>bn(e.mathematica))}}),Ut.of({name:"Modelica",extensions:["mo"],load(){return Wt(()=>import("./modelica-Dc1JOy9r.js"),[]).then(e=>bn(e.modelica))}}),Ut.of({name:"MUMPS",extensions:["mps"],load(){return Wt(()=>import("./mumps-BT43cFF4.js"),[]).then(e=>bn(e.mumps))}}),Ut.of({name:"Mbox",extensions:["mbox"],load(){return Wt(()=>import("./mbox-CNhZ1qSd.js"),[]).then(e=>bn(e.mbox))}}),Ut.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return Wt(()=>import("./nginx-DdIZxoE0.js"),[]).then(e=>bn(e.nginx))}}),Ut.of({name:"NSIS",extensions:["nsh","nsi"],load(){return Wt(()=>import("./nsis-LdVXkNf5.js"),__vite__mapDeps([3,1])).then(e=>bn(e.nsis))}}),Ut.of({name:"NTriples",extensions:["nt","nq"],load(){return Wt(()=>import("./ntriples-BfvgReVJ.js"),[]).then(e=>bn(e.ntriples))}}),Ut.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.objectiveC))}}),Ut.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.objectiveCpp))}}),Ut.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return Wt(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>bn(e.oCaml))}}),Ut.of({name:"Octave",extensions:["m"],load(){return Wt(()=>import("./octave-Ck1zUtKM.js"),[]).then(e=>bn(e.octave))}}),Ut.of({name:"Oz",extensions:["oz"],load(){return Wt(()=>import("./oz-BzwKVEFT.js"),[]).then(e=>bn(e.oz))}}),Ut.of({name:"Pascal",extensions:["p","pas"],load(){return Wt(()=>import("./pascal--L3eBynH.js"),[]).then(e=>bn(e.pascal))}}),Ut.of({name:"Perl",extensions:["pl","pm"],load(){return Wt(()=>import("./perl-CdXCOZ3F.js"),[]).then(e=>bn(e.perl))}}),Ut.of({name:"Pig",extensions:["pig"],load(){return Wt(()=>import("./pig-CevX1Tat.js"),[]).then(e=>bn(e.pig))}}),Ut.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return Wt(()=>import("./powershell-CFHJl5sT.js"),[]).then(e=>bn(e.powerShell))}}),Ut.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return Wt(()=>import("./properties-C78fOPTZ.js"),[]).then(e=>bn(e.properties))}}),Ut.of({name:"ProtoBuf",extensions:["proto"],load(){return Wt(()=>import("./protobuf-ChK-085T.js"),[]).then(e=>bn(e.protobuf))}}),Ut.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return Wt(()=>import("./pug-DeIclll2.js"),__vite__mapDeps([4,5])).then(e=>bn(e.pug))}}),Ut.of({name:"Puppet",extensions:["pp"],load(){return Wt(()=>import("./puppet-DMA9R1ak.js"),[]).then(e=>bn(e.puppet))}}),Ut.of({name:"Q",extensions:["q"],load(){return Wt(()=>import("./q-pXgVlZs6.js"),[]).then(e=>bn(e.q))}}),Ut.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return Wt(()=>import("./r-B6wPVr8A.js"),[]).then(e=>bn(e.r))}}),Ut.of({name:"RPM Changes",load(){return Wt(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>bn(e.rpmChanges))}}),Ut.of({name:"RPM Spec",extensions:["spec"],load(){return Wt(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>bn(e.rpmSpec))}}),Ut.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return Wt(()=>import("./ruby-B2Rjki9n.js"),[]).then(e=>bn(e.ruby))}}),Ut.of({name:"SAS",extensions:["sas"],load(){return Wt(()=>import("./sas-B4kiWyti.js"),[]).then(e=>bn(e.sas))}}),Ut.of({name:"Scala",extensions:["scala"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.scala))}}),Ut.of({name:"Scheme",extensions:["scm","ss"],load(){return Wt(()=>import("./scheme-C41bIUwD.js"),[]).then(e=>bn(e.scheme))}}),Ut.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Wt(()=>import("./shell-CjFT_Tl9.js"),[]).then(e=>bn(e.shell))}}),Ut.of({name:"Sieve",extensions:["siv","sieve"],load(){return Wt(()=>import("./sieve-C3Gn_uJK.js"),[]).then(e=>bn(e.sieve))}}),Ut.of({name:"Smalltalk",extensions:["st"],load(){return Wt(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(e=>bn(e.smalltalk))}}),Ut.of({name:"Solr",load(){return Wt(()=>import("./solr-DehyRSwq.js"),[]).then(e=>bn(e.solr))}}),Ut.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return Wt(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>bn(e.sml))}}),Ut.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return Wt(()=>import("./sparql-DkYu6x3z.js"),[]).then(e=>bn(e.sparql))}}),Ut.of({name:"Spreadsheet",alias:["excel","formula"],load(){return Wt(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(e=>bn(e.spreadsheet))}}),Ut.of({name:"Squirrel",extensions:["nut"],load(){return Wt(()=>import("./clike-B9uivgTg.js"),[]).then(e=>bn(e.squirrel))}}),Ut.of({name:"Stylus",extensions:["styl"],load(){return Wt(()=>import("./stylus-B533Al4x.js"),[]).then(e=>bn(e.stylus))}}),Ut.of({name:"Swift",extensions:["swift"],load(){return Wt(()=>import("./swift-BzpIVaGY.js"),[]).then(e=>bn(e.swift))}}),Ut.of({name:"sTeX",load(){return Wt(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>bn(e.stex))}}),Ut.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return Wt(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>bn(e.stex))}}),Ut.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return Wt(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>bn(e.verilog))}}),Ut.of({name:"Tcl",extensions:["tcl"],load(){return Wt(()=>import("./tcl-DVfN8rqt.js"),[]).then(e=>bn(e.tcl))}}),Ut.of({name:"Textile",extensions:["textile"],load(){return Wt(()=>import("./textile-CnDTJFAw.js"),[]).then(e=>bn(e.textile))}}),Ut.of({name:"TiddlyWiki",load(){return Wt(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(e=>bn(e.tiddlyWiki))}}),Ut.of({name:"Tiki wiki",load(){return Wt(()=>import("./tiki-DGYXhP31.js"),[]).then(e=>bn(e.tiki))}}),Ut.of({name:"TOML",extensions:["toml"],load(){return Wt(()=>import("./toml-Bm5Em-hy.js"),[]).then(e=>bn(e.toml))}}),Ut.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return Wt(()=>import("./troff-wAsdV37c.js"),[]).then(e=>bn(e.troff))}}),Ut.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return Wt(()=>import("./ttcn-CfJYG6tj.js"),[]).then(e=>bn(e.ttcn))}}),Ut.of({name:"TTCN_CFG",extensions:["cfg"],load(){return Wt(()=>import("./ttcn-cfg-B9xdYoR4.js"),[]).then(e=>bn(e.ttcnCfg))}}),Ut.of({name:"Turtle",extensions:["ttl"],load(){return Wt(()=>import("./turtle-B1tBg_DP.js"),[]).then(e=>bn(e.turtle))}}),Ut.of({name:"Web IDL",extensions:["webidl"],load(){return Wt(()=>import("./webidl-ZXfAyPTL.js"),[]).then(e=>bn(e.webIDL))}}),Ut.of({name:"VB.NET",extensions:["vb"],load(){return Wt(()=>import("./vb-CmGdzxic.js"),[]).then(e=>bn(e.vb))}}),Ut.of({name:"VBScript",extensions:["vbs"],load(){return Wt(()=>import("./vbscript-BuJXcnF6.js"),[]).then(e=>bn(e.vbScript))}}),Ut.of({name:"Velocity",extensions:["vtl"],load(){return Wt(()=>import("./velocity-D8B20fx6.js"),[]).then(e=>bn(e.velocity))}}),Ut.of({name:"Verilog",extensions:["v"],load(){return Wt(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>bn(e.verilog))}}),Ut.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return Wt(()=>import("./vhdl-lSbBsy5d.js"),[]).then(e=>bn(e.vhdl))}}),Ut.of({name:"XQuery",extensions:["xy","xquery","xq","xqm","xqy"],load(){return Wt(()=>import("./xquery-DzFWVndE.js"),[]).then(e=>bn(e.xQuery))}}),Ut.of({name:"Yacas",extensions:["ys"],load(){return Wt(()=>import("./yacas-BJ4BC0dw.js"),[]).then(e=>bn(e.yacas))}}),Ut.of({name:"Z80",extensions:["z80"],load(){return Wt(()=>import("./z80-Hz9HOZM7.js"),[]).then(e=>bn(e.z80))}}),Ut.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return Wt(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>bn(e.mscgen))}}),Ut.of({name:"Xù",extensions:["xu"],load(){return Wt(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>bn(e.xu))}}),Ut.of({name:"MsGenny",extensions:["msgenny"],load(){return Wt(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>bn(e.msgenny))}}),Ut.of({name:"Vue",extensions:["vue"],load(){return Wt(()=>import("./index-UkFXcg--.js"),[]).then(e=>e.vue())}}),Ut.of({name:"Angular Template",load(){return Wt(()=>import("./index-D5okPECv.js"),[]).then(e=>e.angular())}})],mOe="#2e3440",Age="#3b4252",pOe="#434c5e",nz="#4c566a",gOe="#e5e9f0",Koe="#eceff4",HJ="#8fbcbb",xOe="#88c0d0",mfn="#81a1c1",$p="#5e81ac",pfn="#bf616a",dk="#d08770",XJ="#ebcb8b",bOe="#a3be8c",gfn="#b48ead",yOe="#d30102",hge=Koe,GJ=hge,xfn="#ffffff",YJ=Age,bfn=hge,vOe=Age,yfn=Fn.theme({"&":{color:mOe,backgroundColor:xfn},".cm-content":{caretColor:vOe},".cm-cursor, .cm-dropCursor":{borderLeftColor:vOe},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:bfn},".cm-panels":{backgroundColor:hge,color:nz},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${nz}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:gOe},".cm-activeLine":{backgroundColor:GJ},".cm-selectionMatch":{backgroundColor:gOe},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${nz}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:Koe},".cm-gutters":{backgroundColor:Koe,color:mOe,border:"none"},".cm-activeLineGutter":{backgroundColor:GJ},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:YJ},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:YJ,borderBottomColor:YJ},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:GJ,color:nz}}},{dark:!1}),vfn=a8.define([{tag:Le.keyword,color:$p},{tag:[Le.name,Le.deleted,Le.character,Le.propertyName,Le.macroName],color:dk},{tag:[Le.variableName],color:dk},{tag:[Le.function(Le.variableName)],color:$p},{tag:[Le.labelName],color:mfn},{tag:[Le.color,Le.constant(Le.name),Le.standard(Le.name)],color:$p},{tag:[Le.definition(Le.name),Le.separator],color:bOe},{tag:[Le.brace],color:HJ},{tag:[Le.annotation],color:yOe},{tag:[Le.number,Le.changed,Le.annotation,Le.modifier,Le.self,Le.namespace],color:xOe},{tag:[Le.typeName,Le.className],color:XJ},{tag:[Le.operator,Le.operatorKeyword],color:bOe},{tag:[Le.tagName],color:gfn},{tag:[Le.squareBracket],color:pfn},{tag:[Le.angleBracket],color:dk},{tag:[Le.attributeName],color:XJ},{tag:[Le.regexp],color:$p},{tag:[Le.quote],color:Age},{tag:[Le.string],color:dk},{tag:Le.link,color:HJ,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[Le.url,Le.escape,Le.special(Le.string)],color:dk},{tag:[Le.meta],color:xOe},{tag:[Le.comment],color:pOe,fontStyle:"italic"},{tag:Le.strong,fontWeight:"bold",color:$p},{tag:Le.emphasis,fontStyle:"italic",color:$p},{tag:Le.strikethrough,textDecoration:"line-through"},{tag:Le.heading,fontWeight:"bold",color:$p},{tag:Le.special(Le.heading1),fontWeight:"bold",color:$p},{tag:Le.heading1,fontWeight:"bold",color:$p},{tag:[Le.heading2,Le.heading3,Le.heading4],fontWeight:"bold",color:$p},{tag:[Le.heading5,Le.heading6],color:$p},{tag:[Le.atom,Le.bool,Le.special(Le.variableName)],color:dk},{tag:[Le.processingInstruction,Le.inserted],color:HJ},{tag:[Le.contentSeparator],color:XJ},{tag:Le.invalid,color:pOe,borderBottom:`1px dotted ${yOe}`}]),wfn=[yfn,yZ(vfn)],wOe=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class BS{constructor(t,n,r=0,s=t.length,a,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(wOe(l)):wOe,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return EA(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=dpe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=tx(t);let s=this.normalize(n);if(s.length)for(let a=0,o=r;;a++){let l=s.charCodeAt(a),c=this.match(l,o,this.bufferPos+this.bufferStart);if(a==s.length-1){if(c)return this.value=c,this;break}o==r&&a<n.length&&n.charCodeAt(a)==l&&o++}}}match(t,n,r){let s=null;for(let a=0;a<this.matches.length;a+=2){let o=this.matches[a],l=!1;this.query.charCodeAt(o)==t&&(o==this.query.length-1?s={from:this.matches[a+1],to:r}:(this.matches[a]++,l=!0)),l||(this.matches.splice(a,2),a-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(BS.prototype[Symbol.iterator]=function(){return this});const _et={from:-1,to:-1,match:/.*/.exec("")},mge="gm"+(/x/.unicode==null?"":"u");class Met{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=_et,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new Eet(t,n,r,s,a);this.re=new RegExp(n,mge+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let o=t.lineAt(s);this.curLineStart=o.from,this.matchPos=DU(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=DU(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const JJ=new WeakMap;class cO{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=JJ.get(t);if(!s||s.from>=r||s.to<=n){let l=new cO(n,t.sliceString(n,r));return JJ.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:o}=s;return o>n&&(a=t.sliceString(n,o)+a,o=n),s.to<r&&(a+=t.sliceString(s.to,r)),JJ.set(t,new cO(o,a)),new cO(n,a.slice(n-o,r-o))}}class Eet{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=_et,this.matchPos=DU(t,s),this.re=new RegExp(n,mge+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=cO.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=DU(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=cO.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Met.prototype[Symbol.iterator]=Eet.prototype[Symbol.iterator]=function(){return this});function kfn(e){try{return new RegExp(e,mge),!0}catch{return!1}}function DU(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const Ofn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=pan(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let o=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!o){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,d,u,f]=o,A=u?+u.slice(1):0,m=d?+d:l.number;if(d&&f){let y=m/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),m=Math.round(t.doc.lines*y)}else d&&c&&(m=m*(c=="-"?-1:1)+l.number);let g=t.doc.line(Math.max(1,Math.min(t.doc.lines,m))),x=Ht.cursor(g.from+Math.max(0,Math.min(A,g.length)));e.dispatch({effects:[r,Fn.scrollIntoView(x.from,{y:"center"})],selection:x})}),!0},Sfn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},jfn=cr.define({combine(e){return Xx(e,Sfn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function Cfn(e){return[_fn,Tfn]}const Nfn=gr.mark({class:"cm-selectionMatch"}),Pfn=gr.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function kOe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=Cl.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=Cl.Word)}function Ifn(e,t,n,r){return e(t.sliceDoc(n,n+1))==Cl.Word&&e(t.sliceDoc(r-1,r))==Cl.Word}const Tfn=Sc.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(jfn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return gr.none;let s=r.main,a,o=null;if(s.empty){if(!t.highlightWordAroundCursor)return gr.none;let c=n.wordAt(s.head);if(!c)return gr.none;o=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return gr.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),o=n.charCategorizer(s.head),!(kOe(o,n,s.from,s.to)&&Ifn(o,n,s.from,s.to)))return gr.none}else if(a=n.sliceDoc(s.from,s.to),!a)return gr.none}let l=[];for(let c of e.visibleRanges){let d=new BS(n.doc,a,c.from,c.to);for(;!d.next().done;){let{from:u,to:f}=d.value;if((!o||kOe(o,n,u,f))&&(s.empty&&u<=s.from&&f>=s.to?l.push(Pfn.range(u,f)):(u>=s.to||f<=s.from)&&l.push(Nfn.range(u,f)),l.length>t.maxMatches))return gr.none}}return gr.set(l)}},{decorations:e=>e.decorations}),_fn=Fn.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Mfn=({state:e,dispatch:t})=>{let{selection:n}=e,r=Ht.create(n.ranges.map(s=>e.wordAt(s.head)||Ht.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function Efn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let o=!1,l=new BS(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new BS(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),o=!0}else{if(o&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const Dfn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return Mfn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=Efn(e,r);return s?(t(e.update({selection:e.selection.addRange(Ht.range(s.from,s.to),!1),effects:Fn.scrollIntoView(s.to)})),!0):!1},wC=cr.define({combine(e){return Xx(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new Hfn(t),scrollToMatch:t=>Fn.scrollIntoView(t)})}});class Det{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||kfn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
1796
1796
  `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new Bfn(this):new zfn(this)}getCursor(t,n=0,r){let s=t.doc?t:yo.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?Yk(this,s,n,r):Gk(this,s,n,r)}}class Ret{constructor(t){this.spec=t}}function Rfn(e,t,n){return(r,s,a,o)=>{if(n&&!n(r,s,a,o))return!1;let l=r>=o&&s<=o+a.length?a.slice(r-o,s-o):t.doc.sliceString(r,s);return e(l,t,r,s)}}function Gk(e,t,n,r){let s;return e.wholeWord&&(s=Lfn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=Rfn(e.test,t,s)),new BS(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function Lfn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(RU(s,n-a))!=Cl.Word||t(LU(s,n-a))!=Cl.Word)&&(t(LU(s,r-a))!=Cl.Word||t(RU(s,r-a))!=Cl.Word))}class zfn extends Ret{constructor(t){super(t)}nextMatch(t,n,r){let s=Gk(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=Gk(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),o=Gk(this.spec,t,a,s),l=null;for(;!o.nextOverlapping().done;)l=o.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=Gk(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=Gk(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function $fn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function Yk(e,t,n,r){let s;return e.wholeWord&&(s=Ffn(t.charCategorizer(t.selection.main.head))),e.test&&(s=$fn(e.test,t,s)),new Met(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function RU(e,t){return e.slice(Fd(e,t,!1),t)}function LU(e,t){return e.slice(t,Fd(e,t))}function Ffn(e){return(t,n,r)=>!r[0].length||(e(RU(r.input,r.index))!=Cl.Word||e(LU(r.input,r.index))!=Cl.Word)&&(e(LU(r.input,r.index+r[0].length))!=Cl.Word||e(RU(r.input,r.index+r[0].length))!=Cl.Word)}class Bfn extends Ret{nextMatch(t,n,r){let s=Yk(this.spec,t,r,t.doc.length).next();return s.done&&(s=Yk(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),o=Yk(this.spec,t,a,r),l=null;for(;!o.next().done;)l=o.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=Yk(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=Yk(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const o_=Ns.define(),pge=Ns.define(),f3=Wd.define({create(e){return new eee(Woe(e).create(),null)},update(e,t){for(let n of t.effects)n.is(o_)?e=new eee(n.value.create(),e.panel):n.is(pge)&&(e=new eee(e.query,n.value?gge:null));return e},provide:e=>XT.from(e,t=>t.panel)});class eee{constructor(t,n){this.query=t,this.panel=n}}const Qfn=gr.mark({class:"cm-searchMatch"}),Ufn=gr.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Vfn=Sc.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(f3))}update(e){let t=e.state.field(f3);(t!=e.startState.field(f3)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return gr.none;let{view:n}=this,r=new ob;for(let s=0,a=n.visibleRanges,o=a.length;s<o;s++){let{from:l,to:c}=a[s];for(;s<o-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(d,u)=>{let f=n.state.selection.ranges.some(A=>A.from==d&&A.to==u);r.add(d,u,f?Ufn:Qfn)})}return r.finish()}},{decorations:e=>e.decorations});function lD(e){return t=>{let n=t.state.field(f3,!1);return n&&n.query.spec.valid?e(t,n):$et(t)}}const zU=lD((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=Ht.single(r.from,r.to),a=e.state.facet(wC);return e.dispatch({selection:s,effects:[xge(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),zet(e),!0}),$U=lD((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=Ht.single(s.from,s.to),o=e.state.facet(wC);return e.dispatch({selection:a,effects:[xge(e,s),o.scrollToMatch(a.main,e)],userEvent:"select.search"}),zet(e),!0}),qfn=lD((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:Ht.create(n.map(r=>Ht.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),Kfn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],o=0;for(let l=new BS(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(o=a.length),a.push(Ht.range(l.value.from,l.value.to))}return t(e.update({selection:Ht.create(a,o),userEvent:"select.search.matches"})),!0},OOe=lD((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let o=a,l=[],c,d,u=[];o.from==r&&o.to==s&&(d=n.toText(t.getReplacement(o)),l.push({from:o.from,to:o.to,insert:d}),o=t.nextMatch(n,o.from,o.to),u.push(Fn.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let f=e.state.changes(l);return o&&(c=Ht.single(o.from,o.to).map(f),u.push(xge(e,o)),u.push(n.facet(wC).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:u,userEvent:"input.replace"}),!0}),Wfn=lD((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(s=>{let{from:a,to:o}=s;return{from:a,to:o,insert:t.getReplacement(s)}});if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Fn.announce.of(r),userEvent:"input.replace.all"}),!0});function gge(e){return e.state.facet(wC).createPanel(e)}function Woe(e,t){var n,r,s,a,o;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let d=e.facet(wC);return new Det({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:d.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:d.caseSensitive,literal:(s=t==null?void 0:t.literal)!==null&&s!==void 0?s:d.literal,regexp:(a=t==null?void 0:t.regexp)!==null&&a!==void 0?a:d.regexp,wholeWord:(o=t==null?void 0:t.wholeWord)!==null&&o!==void 0?o:d.wholeWord})}function Let(e){let t=Npe(e,gge);return t&&t.dom.querySelector("[main-field]")}function zet(e){let t=Let(e);t&&t==e.root.activeElement&&t.select()}const $et=e=>{let t=e.state.field(f3,!1);if(t&&t.panel){let n=Let(e);if(n&&n!=e.root.activeElement){let r=Woe(e.state,t.query.spec);r.valid&&e.dispatch({effects:o_.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[pge.of(!0),t?o_.of(Woe(e.state,t.query.spec)):Ns.appendConfig.of(Gfn)]});return!0},Fet=e=>{let t=e.state.field(f3,!1);if(!t||!t.panel)return!1;let n=Npe(e,gge);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:pge.of(!1)}),!0},Zfn=[{key:"Mod-f",run:$et,scope:"editor search-panel"},{key:"F3",run:zU,shift:$U,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:zU,shift:$U,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Fet,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Kfn},{key:"Mod-Alt-g",run:Ofn},{key:"Mod-d",run:Dfn,preventDefault:!0}];class Hfn{constructor(t){this.view=t;let n=this.query=t.state.field(f3).query.spec;this.commit=this.commit.bind(this),this.searchField=No("input",{value:n.search,placeholder:kh(t,"Find"),"aria-label":kh(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=No("input",{value:n.replace,placeholder:kh(t,"Replace"),"aria-label":kh(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=No("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=No("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=No("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,o){return No("button",{class:"cm-button",name:s,onclick:a,type:"button"},o)}this.dom=No("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>zU(t),[kh(t,"next")]),r("prev",()=>$U(t),[kh(t,"previous")]),r("select",()=>qfn(t),[kh(t,"all")]),No("label",null,[this.caseField,kh(t,"match case")]),No("label",null,[this.reField,kh(t,"regexp")]),No("label",null,[this.wordField,kh(t,"by word")]),...t.state.readOnly?[]:[No("br"),this.replaceField,r("replace",()=>OOe(t),[kh(t,"replace")]),r("replaceAll",()=>Wfn(t),[kh(t,"replace all")])],No("button",{name:"close",onclick:()=>Fet(t),"aria-label":kh(t,"close"),type:"button"},["×"])])}commit(){let t=new Det({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:o_.of(t)}))}keydown(t){Nin(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?$U:zU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),OOe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(o_)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(wC).top}}function kh(e,t){return e.state.phrase(t)}const rz=30,sz=/[\s\.,:;?!]/;function xge(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-rz),o=Math.min(s,n+rz),l=e.state.sliceDoc(a,o);if(a!=r.from){for(let c=0;c<rz;c++)if(!sz.test(l[c+1])&&sz.test(l[c])){l=l.slice(c);break}}if(o!=s){for(let c=l.length-1;c>l.length-rz;c--)if(!sz.test(l[c-1])&&sz.test(l[c])){l=l.slice(0,c);break}}return Fn.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const Xfn=Fn.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),Gfn=[f3,Zm.low(Vfn),Xfn];class SOe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class w5{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(l_).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((m,g)=>m.from-g.from||m.to-g.to),o=new ob,l=[],c=0,d=r.doc.iter(),u=0,f=r.doc.length;for(let m=0;;){let g=m==a.length?null:a[m];if(!g&&!l.length)break;let x,y;if(l.length)x=c,y=l.reduce((k,S)=>Math.min(k,S.to),g&&g.from>x?g.from:1e8);else{if(x=g.from,x>f)break;y=g.to,l.push(g),m++}for(;m<a.length;){let k=a[m];if(k.from==x&&(k.to>k.from||k.to==x))l.push(k),m++,y=Math.min(k.to,y);else{y=Math.min(k.from,y);break}}y=Math.min(y,f);let v=!1;if(l.some(k=>k.from==x&&(k.to==y||y==f))&&(v=x==y,!v&&y-x<10)){let k=x-(u+d.value.length);k>0&&(d.next(k),u=x);for(let S=x;;){if(S>=y){v=!0;break}if(!d.lineBreak&&u+d.value.length>S)break;S=u+d.value.length,u+=d.value.length,d.next()}}let w=dAn(l);if(v)o.add(x,x,gr.widget({widget:new aAn(w),diagnostics:l.slice()}));else{let k=l.reduce((S,j)=>j.markClass?S+" "+j.markClass:S,"");o.add(x,y,gr.mark({class:"cm-lintRange cm-lintRange-"+w+k,diagnostics:l.slice(),inclusiveEnd:l.some(S=>S.to>y)}))}if(c=y,c==f)break;for(let k=0;k<l.length;k++)l[k].to<=c&&l.splice(k--,1)}let A=o.finish();return new w5(A,n,U3(A))}}function U3(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:o})=>{if(!(t&&o.diagnostics.indexOf(t)<0))if(!r)r=new SOe(s,a,t||o.diagnostics[0]);else{if(o.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new SOe(r.from,a,r.diagnostic)}}),r}function Yfn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(l_).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(o=>o.is(Bet))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function Jfn(e,t){return e.field(Wh,!1)?t:t.concat(Ns.appendConfig.of(uAn))}const Bet=Ns.define(),bge=Ns.define(),Qet=Ns.define(),Wh=Wd.define({create(){return new w5(gr.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=U3(n,e.selected.diagnostic,a)||U3(n,null,a)}!n.size&&s&&t.state.facet(l_).autoPanel&&(s=null),e=new w5(n,s,r)}for(let n of t.effects)if(n.is(Bet)){let r=t.state.facet(l_).autoPanel?n.value.length?c_.open:null:e.panel;e=w5.init(n.value,r,t.state)}else n.is(bge)?e=new w5(e.diagnostics,n.value?c_.open:null,e.selected):n.is(Qet)&&(e=new w5(e.diagnostics,e.panel,n.value));return e},provide:e=>[XT.from(e,t=>t.panel),Fn.decorations.from(e,t=>t.diagnostics)]}),eAn=gr.mark({class:"cm-lintRange cm-lintRange-active"});function tAn(e,t,n){let{diagnostics:r}=e.state.field(Wh),s,a=-1,o=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,d,{spec:u})=>{if(t>=c&&t<=d&&(c==d||(t>c||n>0)&&(t<d||n<0)))return s=u.diagnostics,a=c,o=d,!1});let l=e.state.facet(l_).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:o,above:e.state.doc.lineAt(a).to<o,create(){return{dom:nAn(e,s)}}}:null}function nAn(e,t){return No("ul",{class:"cm-tooltip-lint"},t.map(n=>Vet(e,n,!1)))}const rAn=e=>{let t=e.state.field(Wh,!1);(!t||!t.panel)&&e.dispatch({effects:Jfn(e.state,[bge.of(!0)])});let n=Npe(e,c_.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},jOe=e=>{let t=e.state.field(Wh,!1);return!t||!t.panel?!1:(e.dispatch({effects:bge.of(!1)}),!0)},sAn=e=>{let t=e.state.field(Wh,!1);if(!t)return!1;let n=e.state.selection.main,r=U3(t.diagnostics,null,n.to+1);return!r&&(r=U3(t.diagnostics,null,0),!r||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},iAn=[{key:"Mod-Shift-m",run:rAn,preventDefault:!0},{key:"F8",run:sAn}],l_=cr.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Xx(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:COe,tooltipFilter:COe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function COe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function Uet(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function Vet(e,t,n){var r;let s=n?Uet(t.actions):[];return No("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},No("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,o)=>{let l=!1,c=m=>{if(m.preventDefault(),l)return;l=!0;let g=U3(e.state.field(Wh).diagnostics,t);g&&a.apply(e,g.from,g.to)},{name:d}=a,u=s[o]?d.indexOf(s[o]):-1,f=u<0?d:[d.slice(0,u),No("u",d.slice(u,u+1)),d.slice(u+1)],A=a.markClass?" "+a.markClass:"";return No("button",{type:"button",class:"cm-diagnosticAction"+A,onclick:c,onmousedown:c,"aria-label":` Action: ${d}${u<0?"":` (access key "${s[o]})"`}.`},f)}),t.source&&No("div",{class:"cm-diagnosticSource"},t.source))}class aAn extends Ap{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return No("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class NOe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Vet(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class c_{constructor(t){this.view=t,this.items=[];let n=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)jOe(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],o=Uet(a.actions);for(let l=0;l<o.length;l++)if(o[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=U3(this.view.state.field(Wh).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()}},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=No("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=No("div",{class:"cm-panel-lint"},this.list,No("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>jOe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Wh).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Wh),r=0,s=!1,a=null,o=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:d})=>{for(let u of d.diagnostics){if(o.has(u))continue;o.add(u);let f=-1,A;for(let m=r;m<this.items.length;m++)if(this.items[m].diagnostic==u){f=m;break}f<0?(A=new NOe(this.view,u),this.items.splice(r,0,A),s=!0):(A=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&A.diagnostic==n.diagnostic?A.dom.hasAttribute("aria-selected")||(A.dom.setAttribute("aria-selected","true"),a=A):A.dom.hasAttribute("aria-selected")&&A.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new NOe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let d=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/d:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/d)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Wh),r=U3(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Qet.of(r)})}static open(t){return new c_(t)}}function oAn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function iz(e){return oAn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const lAn=Fn.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:iz("#d11")},".cm-lintRange-warning":{backgroundImage:iz("orange")},".cm-lintRange-info":{backgroundImage:iz("#999")},".cm-lintRange-hint":{backgroundImage:iz("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function cAn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function dAn(e){let t="hint",n=1;for(let r of e){let s=cAn(r.severity);s>n&&(n=s,t=r.severity)}return t}const uAn=[Wh,Fn.decorations.compute([Wh],e=>{let{selected:t,panel:n}=e.field(Wh);return!t||!n||t.from==t.to?gr.none:gr.set([eAn.range(t.from,t.to)])}),han(tAn,{hideOn:Yfn}),lAn],yge=[OYe(),Pan(),qin(),fJe(),yon(),Ein(),$in(),yo.allowMultipleSelections.of(!0),lon(),yZ(Oon,{fallback:!0}),Ton(),kln(),Eln(),ran(),aan(),Gin(),Cfn(),db.of([...Cln,...QJe,...Zfn,...pJe,...pon,...cJe,...iAn])],fAn=ye.forwardRef(({title:e,children:t},n)=>{const r=Ex(r8);return ye.createElement(Fue,{delayDuration:100},ye.createElement(Bue,null,ye.createElement(Que,{ref:n,asChild:!0},ye.createElement("span",{className:Tn.tooltipTrigger},t)),ye.createElement(Uue,{container:r==null?void 0:r.current},ye.createElement(Vue,{className:Po(Tn.tooltipContent),sideOffset:10},e))))}),AAn=ye.forwardRef(({children:e,className:t,...n},r)=>ye.createElement(wLe,{...n,ref:r,className:Po(t,Tn.selectItem)},ye.createElement(kLe,null,e))),hAn=({title:e,placeholder:t,className:n})=>{const[r,s]=qg($g,Nb);return ye.createElement(fAn,{title:e},ye.createElement(pLe,{"aria-label":t,className:Po(Tn.selectTrigger,n),"data-toolbar-item":!0,disabled:r},ye.createElement(gLe,{placeholder:t}),ye.createElement(xLe,{className:Tn.selectDropdownArrow},s("arrow_drop_down"))))},mAn=({children:e,className:t=Tn.selectContainer})=>{const n=Ex(r8);return ye.createElement(bLe,{container:n==null?void 0:n.current},ye.createElement(yLe,{className:Po(t,"mdxeditor-select-content"),onCloseAutoFocus:r=>{r.preventDefault()},position:"popper"},ye.createElement(vLe,{"data-editor-dropdown":!0,style:{maxHeight:"var(--radix-select-content-available-height)"}},e)))},pAn=e=>ye.createElement(mLe,{value:e.value||"",onValueChange:e.onChange,disabled:e.disabled},ye.createElement(hAn,{title:e.triggerTitle,placeholder:e.placeholder}),ye.createElement(mAn,null,e.items.map((t,n)=>t==="separator"?ye.createElement(Jbt,{key:n}):ye.createElement(AAn,{key:n,value:t.value},t.label)))),qet=({language:e,nodeKey:t,code:n,focusEmitter:r})=>{const s=Pb(),{parentEditor:a,lexicalNode:o}=Kae(),[l,c,d,u,f]=qg($g,Goe,Yoe,Nb,Xoe),A=Afn(t,"codeblock",e,r),{setCode:m}=Kae(),g=ye.useRef(null),x=ye.useRef(null),y=ye.useRef(m);return y.current=m,A.current={getCodemirror:()=>g.current},ye.useEffect(()=>{const v=x.current;return(async()=>{const w=[...c,yge,wfn,OYe(),db.of([Wcn]),Fn.lineWrapping,Fn.updateListener.of(({state:k})=>{y.current(k.doc.toString())}),Fn.domEventHandlers({focus:()=>{a.update(()=>{fp(null)})}})];if(l&&w.push(yo.readOnly.of(!0)),e!==""&&d){const k=hfn.find(S=>S.name===e||S.alias.includes(e)||S.extensions.includes(e));if(k)try{const S=await k.load();w.push(S.extension)}catch{console.warn("failed to load language support for",e)}}v.innerHTML="",g.current=new Fn({parent:v,state:yo.create({doc:n,extensions:w})}),v.addEventListener("keydown",POe)})(),()=>{var w;(w=g.current)==null||w.destroy(),g.current=null,v.removeEventListener("keydown",POe)}},[l,e,...c]),ye.createElement("div",{className:Tn.codeMirrorWrapper},ye.createElement("div",{className:Tn.codeMirrorToolbar},ye.createElement(pAn,{disabled:l,value:f.keyMap[e]??e,onChange:v=>{a.update(()=>{o.setLanguage(v===Zoe?"":v),setTimeout(()=>{a.update(()=>{o.getLatest().select()})})})},triggerTitle:s("codeBlock.selectLanguage","Select code block language"),placeholder:s("codeBlock.inlineLanguage","Language"),items:f.items}),ye.createElement("button",{className:Tn.iconButton,type:"button",disabled:l,title:s("codeblock.delete","Delete code block"),onClick:v=>{v.preventDefault(),a.update(()=>{o.remove()})}},u("delete_small"))),ye.createElement("div",{ref:x}))};function POe(e){e.stopPropagation()}const Zoe="__EMPTY_VALUE__";function Hoe(e){var t;const n=[],r={};if(Array.isArray(e))for(const s of e){const a=((t=s.alias)==null?void 0:t[0])??s.name.toLowerCase();if(n.push({value:a,label:s.name}),r[a]=a,s.alias)for(const o of s.alias)r[o]=a;if(s.extensions)for(const o of s.extensions)r[o]=a;r[s.name.toLowerCase()]=a}else{const s={};for(const[a,o]of Object.entries(e))o in s||(s[o]=a,n.push({value:a||Zoe,label:o})),r[a]=s[o]||Zoe}return{items:n,keyMap:r}}const Xoe=hr(Hoe({js:"JavaScript",ts:"TypeScript",tsx:"TypeScript (React)",jsx:"JavaScript (React)",css:"CSS"})),gAn=Cc(e=>{e.link(e.pipe(gAn,_3(({language:t,code:n})=>({code:n,language:t,meta:""}))),XXe)}),Goe=hr([]),Yoe=hr(!0),xAn=Nu({update(e,t){e.pubIn({[Xoe]:Hoe((t==null?void 0:t.codeBlockLanguages)??{}),[Goe]:(t==null?void 0:t.codeMirrorExtensions)??[],[Yoe]:(t==null?void 0:t.autoLoadLanguageSupport)??!0})},init(e,t){const n=Hoe((t==null?void 0:t.codeBlockLanguages)??{});e.pubIn({[Xoe]:n,[Goe]:(t==null?void 0:t.codeMirrorExtensions)??[],[vrn]:bAn(n),[Yoe]:(t==null?void 0:t.autoLoadLanguageSupport)??!0})}});function bAn(e){return{match(t,n){return Object.hasOwn(e.keyMap,t??"")&&!n},priority:1,Editor:qet}}function yAn({url:e,title:t,text:n,onSubmit:r,onCancel:s,linkAutocompleteSuggestions:a,showLinkTitleField:o,showAnchorTextField:l}){const{register:c,handleSubmit:d,control:u,setValue:f,reset:A}=SXe({values:{url:e,title:t,text:n}}),m=Pb();return ye.createElement("form",{onSubmit:g=>{d(r)(g),g.stopPropagation(),g.preventDefault()},onReset:g=>{g.stopPropagation(),s()},onKeyDown:g=>{g.key==="Escape"&&(g.stopPropagation(),s())},className:Po(Tn.multiFieldForm,Tn.linkDialogEditForm)},ye.createElement("div",{className:Tn.formField},ye.createElement("label",{htmlFor:"link-url"},m("createLink.url","URL")),ye.createElement(UXe,{register:c,initialInputValue:e,inputName:"url",suggestions:a,setValue:f,control:u,placeholder:m("createLink.urlPlaceholder","Select or paste an URL"),autofocus:!0})),l?ye.createElement("div",{className:Tn.formField},ye.createElement("label",{htmlFor:"link-text",title:m("createLink.textTooltip","The text to be displayed for the link")},m("createLink.text","Anchor text")),ye.createElement("input",{id:"link-text",className:Tn.textInput,size:40,...c("text")})):null,o?ye.createElement("div",{className:Tn.formField},ye.createElement("label",{htmlFor:"link-title",title:m("createLink.titleTooltip","The link's title attribute, shown on hover")},m("createLink.title","Link title")),ye.createElement("input",{id:"link-title",className:Tn.textInput,size:40,...c("title")})):null,ye.createElement("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--spacing-2)"}},ye.createElement("button",{type:"submit",title:m("createLink.saveTooltip","Set URL"),"aria-label":m("createLink.saveTooltip","Set URL"),className:Po(Tn.primaryButton)},m("dialogControls.save","Save")),ye.createElement("button",{type:"reset",title:m("createLink.cancelTooltip","Cancel change"),"aria-label":m("createLink.cancelTooltip","Cancel change"),className:Po(Tn.secondaryButton)},m("dialogControls.cancel","Cancel"))))}const vAn=()=>{const[e,t,n,r,s,a,o]=qg(r8,jl,Nb,OA,Yet,Jet,ttt),l=Bh(Ket),c=Bh(Wet),d=Bh(Zet),u=Bh(Het),f=Bh(Xet);ye.useEffect(()=>{const v=()=>{t==null||t.getEditorState().read(()=>{l(!0)})};return window.addEventListener("resize",v),window.addEventListener("scroll",v),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v)}},[t,l]);const[A,m]=ye.useState(!1),g=Pb();if(r.type==="inactive")return null;const x=r.rectangle,y=r.type==="preview"&&r.url.startsWith("http");return ye.createElement(oK,{open:!0},ye.createElement(jRe,{"data-visible":r.type==="edit",className:Tn.linkDialogAnchor,style:{top:`${x.top}px`,left:`${x.left}px`,width:`${x.width}px`,height:`${x.height}px`}}),ye.createElement(lK,{container:e==null?void 0:e.current},ye.createElement(CRe,{className:Po(Tn.linkDialogPopoverContent),sideOffset:5,onOpenAutoFocus:v=>{v.preventDefault()},key:r.linkNodeKey},r.type==="edit"&&ye.createElement(yAn,{url:r.url,title:r.title,text:r.text,onSubmit:c,onCancel:d.bind(null),linkAutocompleteSuggestions:s,showLinkTitleField:o,showAnchorTextField:r.withAnchorText}),r.type==="preview"&&ye.createElement(ye.Fragment,null,ye.createElement("a",{className:Tn.linkDialogPreviewAnchor,href:r.url,...y?{target:"_blank",rel:"noreferrer"}:{},onClick:v=>{a!==null&&(v.preventDefault(),a(r.url))},title:y?g("linkPreview.open","Open {{url}} in new window",{url:r.url}):r.url},ye.createElement("span",null,r.url),y&&n("open_in_new")),ye.createElement(tee,{onClick:()=>{u()},title:g("linkPreview.edit","Edit link URL"),"aria-label":g("linkPreview.edit","Edit link URL")},n("edit")),ye.createElement(Fue,null,ye.createElement(Bue,{open:A},ye.createElement(Que,{asChild:!0},ye.createElement(tee,{title:g("linkPreview.copyToClipboard","Copy to clipboard"),"aria-label":g("linkPreview.copyToClipboard","Copy to clipboard"),onClick:()=>{window.navigator.clipboard.writeText(r.url).then(()=>{m(!0),setTimeout(()=>{m(!1)},1e3)})}},n(A?"check":"content_copy"))),ye.createElement(Uue,{container:e==null?void 0:e.current},ye.createElement(Vue,{className:Po(Tn.tooltipContent),sideOffset:5},g("linkPreview.copied","Copied!"),ye.createElement(uze,null))))),ye.createElement(tee,{title:g("linkPreview.remove","Remove link"),"aria-label":g("linkPreview.remove","Remove link"),onClick:()=>{f()}},n("link_off"))),ye.createElement(Nue,{className:Tn.popoverArrow}))))},tee=ye.forwardRef(({className:e,...t},n)=>ye.createElement("button",{className:Po(Tn.actionButton,e),ref:n,...t}));function Joe(e){if(!e)return null;const t=Aen(e);if(t===null)return null;const n=t.getParent();return $f(n)?n:$f(t)?t:null}const Ket=Cc(),OA=hr({type:"inactive"},e=>{e.pub(zT,t=>t.registerCommand(YW,()=>e.getValue(OA).type==="preview"?(e.pub(OA,{type:"inactive"}),!0):!1,Go)),e.sub(e.pipe($T),t=>{t!=="rich-text"&&e.pub(OA,{type:"inactive"})}),e.pub(zT,t=>t.registerCommand(jZe,n=>{if(n.key==="k"&&(eXe?n.metaKey:n.ctrlKey)&&!e.getValue($g)){const r=xr();return _r(r)?(e.pub(Get),n.stopPropagation(),n.preventDefault(),!0):!1}return!1},ET)),e.sub(e.pipe(Het,Ql(OA,jl)),([,t,n])=>{if(t.type==="preview")setTimeout(()=>{n==null||n.getEditorState().read(()=>{const r=vx(t.linkNodeKey),s=$f(r)?r.getTextContent().length>0&&r.getChildrenSize()<=1:!1,a=s&&r?r.getTextContent():"";e.pub(OA,{type:"edit",initialUrl:t.url,url:t.url,title:t.title,text:a,withAnchorText:s,linkNodeKey:t.linkNodeKey,rectangle:t.rectangle})})});else throw new Error("Cannot switch to edit mode when not in preview mode")}),e.sub(e.pipe(Wet,Ql(jl,OA,IS)),([t,n,r,s])=>{var a,o,l;const c=((a=t.text)==null?void 0:a.trim())??"",d=((o=t.url)==null?void 0:o.trim())??"",u=((l=t.title)==null?void 0:l.trim())??"";if(d!==""){if(s!=null&&s.isCollapsed()){const f=c||u||d;n==null||n.update(()=>{const A=Joe(s);if(A)if(ig(A)){const m=ab(d,{title:u});m.append(sp(c)),A.replace(m),m.select()}else A.setURL(d),A.setTitle(u),IOe(A.getFirstChild(),c);else{const m=ab(d,{title:u});m.append(sp(f)),fC([m]),m.select()}},{discrete:!0})}else n==null||n.update(()=>{IOe(s==null?void 0:s.anchor.getNode(),c)}),n==null||n.dispatchCommand(TS,{url:d,title:u});e.pub(OA,{type:"preview",linkNodeKey:r.linkNodeKey,rectangle:r.rectangle,title:u,url:d})}else r.type==="edit"&&r.initialUrl!==""&&(n==null||n.dispatchCommand(TS,null)),e.pub(OA,{type:"inactive"})}),e.link(e.pipe(Zet,Ql(OA,jl),_3(([,t,n])=>{if(t.type==="edit")return n==null||n.focus(),t.initialUrl===""?{type:"inactive"}:{type:"preview",url:t.initialUrl,linkNodeKey:t.linkNodeKey,rectangle:t.rectangle};throw new Error("Cannot cancel edit when not in edit mode")})),OA),e.link(e.pipe(e.combine(IS,Ket),Ql(jl,OA,$g),_3(([[t],n,r,s])=>{if(_r(t)&&n&&!s){const a=Joe(t);if(!t.isCollapsed())return{type:"inactive"};if(a){const o=GHe(n);return o?{type:"preview",url:a.getURL(),linkNodeKey:a.getKey(),title:a.getTitle(),rectangle:o}:{type:"inactive"}}else return{type:"inactive"}}else return{type:"inactive"}})),OA)}),Wet=Cc(),Zet=pw();pw();const Het=pw(),Xet=pw(e=>{e.sub(e.pipe(Xet,Ql(jl)),([,t])=>{t==null||t.dispatchCommand(TS,null)})}),Get=pw(e=>{e.sub(e.pipe(Get,Ql(IS,jl),$E(([,t])=>_r(t))),([,t,n])=>{n==null||n.focus(()=>{setTimeout(()=>{n.getEditorState().read(()=>{const r=Joe(t),s=GHe(n),a=(r==null?void 0:r.getURL())??"",o=(r==null?void 0:r.getURL())??"",l=(r==null?void 0:r.getTitle())??"",c=(r==null?void 0:r.getKey())??"",d=r?r.getTextContent().length>0&&r.getChildrenSize()<=1:!!(t!=null&&t.isCollapsed()),u=d&&r?r.getTextContent():"";e.pub(OA,{type:"edit",initialUrl:a,url:o,title:l,text:u,withAnchorText:d,linkNodeKey:c,rectangle:s})})})})})}),Yet=hr([]),Jet=hr(null),ett=hr(null,e=>{e.pub(zT,t=>{function n(r){const[s,a]=e.getValues([$g,ett]);!s||a===null||t.update(()=>{const o=g6(r.target);if(o!==null){const l=kg(o,c=>c instanceof Hg);l!==null&&a(r,l,l.getURL())}})}return t.registerRootListener((r,s)=>{r&&r.addEventListener("click",n),s&&s.removeEventListener("click",n)})})});function IOe(e,t){La(e)&&t&&(e.setTextContent(t),e.selectStart())}const ttt=hr(!0),wAn=Nu({init(e,t){e.pub(s8,(t==null?void 0:t.LinkDialog)??vAn),e.pub(Jet,(t==null?void 0:t.onClickLinkCallback)??null),e.pub(ett,(t==null?void 0:t.onReadOnlyClickLinkCallback)??null),e.pub(ttt,(t==null?void 0:t.showLinkTitleField)??!0)},update(e,t={}){e.pub(Yet,t.linkAutocompleteSuggestions??[])}});class FU{static create(t,n,r,s,a){let o=s+(s<<8)+t+(n<<4)|0;return new FU(t,n,r,o,a,[],[])}constructor(t,n,r,s,a,o,l){this.type=t,this.value=n,this.from=r,this.hash=s,this.end=a,this.children=o,this.positions=l,this.hashProp=[[$s.contextHash,s]]}addChild(t,n){t.prop($s.contextHash)!=this.hash&&(t=new Qi(t.type,t.children,t.positions,t.length,this.hashProp)),this.children.push(t),this.positions.push(n)}toTree(t,n=this.end){let r=this.children.length-1;return r>=0&&(n=Math.max(n,this.positions[r]+this.children[r].length+this.from)),new Qi(t.types[this.type],this.children,this.positions,n-this.from).balance({makeTree:(s,a,o)=>new Qi(qd.none,s,a,o,this.hashProp)})}}var $n;(function(e){e[e.Document=1]="Document",e[e.CodeBlock=2]="CodeBlock",e[e.FencedCode=3]="FencedCode",e[e.Blockquote=4]="Blockquote",e[e.HorizontalRule=5]="HorizontalRule",e[e.BulletList=6]="BulletList",e[e.OrderedList=7]="OrderedList",e[e.ListItem=8]="ListItem",e[e.ATXHeading1=9]="ATXHeading1",e[e.ATXHeading2=10]="ATXHeading2",e[e.ATXHeading3=11]="ATXHeading3",e[e.ATXHeading4=12]="ATXHeading4",e[e.ATXHeading5=13]="ATXHeading5",e[e.ATXHeading6=14]="ATXHeading6",e[e.SetextHeading1=15]="SetextHeading1",e[e.SetextHeading2=16]="SetextHeading2",e[e.HTMLBlock=17]="HTMLBlock",e[e.LinkReference=18]="LinkReference",e[e.Paragraph=19]="Paragraph",e[e.CommentBlock=20]="CommentBlock",e[e.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",e[e.Escape=22]="Escape",e[e.Entity=23]="Entity",e[e.HardBreak=24]="HardBreak",e[e.Emphasis=25]="Emphasis",e[e.StrongEmphasis=26]="StrongEmphasis",e[e.Link=27]="Link",e[e.Image=28]="Image",e[e.InlineCode=29]="InlineCode",e[e.HTMLTag=30]="HTMLTag",e[e.Comment=31]="Comment",e[e.ProcessingInstruction=32]="ProcessingInstruction",e[e.Autolink=33]="Autolink",e[e.HeaderMark=34]="HeaderMark",e[e.QuoteMark=35]="QuoteMark",e[e.ListMark=36]="ListMark",e[e.LinkMark=37]="LinkMark",e[e.EmphasisMark=38]="EmphasisMark",e[e.CodeMark=39]="CodeMark",e[e.CodeText=40]="CodeText",e[e.CodeInfo=41]="CodeInfo",e[e.LinkTitle=42]="LinkTitle",e[e.LinkLabel=43]="LinkLabel",e[e.URL=44]="URL"})($n||($n={}));class kAn{constructor(t,n){this.start=t,this.content=n,this.marks=[],this.parsers=[]}}class OAn{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let t=this.skipSpace(this.basePos);this.indent=this.countIndent(t,this.pos,this.indent),this.pos=t,this.next=t==this.text.length?-1:this.text.charCodeAt(t)}skipSpace(t){return hI(this.text,t)}reset(t){for(this.text=t,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(t){this.basePos=t,this.baseIndent=this.countIndent(t,this.pos,this.indent)}moveBaseColumn(t){this.baseIndent=t,this.basePos=this.findColumn(t)}addMarker(t){this.markers.push(t)}countIndent(t,n=0,r=0){for(let s=n;s<t;s++)r+=this.text.charCodeAt(s)==9?4-r%4:1;return r}findColumn(t){let n=0;for(let r=0;n<this.text.length&&r<t;n++)r+=this.text.charCodeAt(n)==9?4-r%4:1;return n}scrub(){if(!this.baseIndent)return this.text;let t="";for(let n=0;n<this.basePos;n++)t+=" ";return t+this.text.slice(this.basePos)}}function TOe(e,t,n){if(n.pos==n.text.length||e!=t.block&&n.indent>=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let r=(e.type==$n.OrderedList?kge:wge)(n,t,!1);return r>0&&(e.type!=$n.BulletList||vge(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}const ntt={[$n.Blockquote](e,t,n){return n.next!=62?!1:(n.markers.push(ya($n.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(mp(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0)},[$n.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[$n.OrderedList]:TOe,[$n.BulletList]:TOe,[$n.Document](){return!0}};function mp(e){return e==32||e==9||e==10||e==13}function hI(e,t=0){for(;t<e.length&&mp(e.charCodeAt(t));)t++;return t}function _Oe(e,t,n){for(;t>n&&mp(e.charCodeAt(t-1));)t--;return t}function rtt(e){if(e.next!=96&&e.next!=126)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;if(t<e.pos+3)return-1;if(e.next==96){for(let n=t;n<e.text.length;n++)if(e.text.charCodeAt(n)==96)return-1}return t}function stt(e){return e.next!=62?-1:e.text.charCodeAt(e.pos+1)==32?2:1}function vge(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let s=e.pos+1;s<e.text.length;s++){let a=e.text.charCodeAt(s);if(a==e.next)r++;else if(!mp(a))return-1}return n&&e.next==45&&ott(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(utt.SetextHeading)>-1||r<3?-1:1}function itt(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function wge(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||mp(e.text.charCodeAt(e.pos+1)))&&(!n||itt(t,$n.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function kge(e,t,n){let r=e.pos,s=e.next;for(;s>=48&&s<=57;){r++;if(r==e.text.length)return-1;s=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||s!=46&&s!=41||r<e.text.length-1&&!mp(e.text.charCodeAt(r+1))||n&&!itt(t,$n.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function att(e){if(e.next!=35)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==35;)t++;if(t<e.text.length&&e.text.charCodeAt(t)!=32)return-1;let n=t-e.pos;return n>6?-1:n}function ott(e){if(e.next!=45&&e.next!=61||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;let n=t;for(;t<e.text.length&&mp(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}const ele=/^[ \t]*$/,ltt=/-->/,ctt=/\?>/,tle=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,ltt],[/^\s*<\?/,ctt],[/^\s*<![A-Z]/,/>/],[/^\s*<!\[CDATA\[/,/\]\]>/],[/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i,ele],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,ele]];function dtt(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let s=0,a=tle.length-(n?1:0);s<a;s++)if(tle[s][0].test(r))return s;return-1}function MOe(e,t){let n=e.countIndent(t,e.pos,e.indent),r=e.countIndent(e.skipSpace(t),t,n);return r>=n+5?n+1:r}function wy(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==$n.CodeText?e[r].to=n:e.push(ya($n.CodeText,t,n))}const az={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),s=e.lineStart+r,a=e.lineStart+t.text.length,o=[],l=[];for(wy(o,s,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){wy(l,e.lineStart-1,e.lineStart);for(let c of t.markers)l.push(c)}else{if(t.indent<n)break;{if(l.length){for(let d of l)d.type==$n.CodeText?wy(o,d.from,d.to):o.push(d);l=[]}wy(o,e.lineStart-1,e.lineStart);for(let d of t.markers)o.push(d);a=e.lineStart+t.text.length;let c=e.lineStart+t.findColumn(t.baseIndent+4);c<a&&wy(o,c,a)}}return l.length&&(l=l.filter(c=>c.type!=$n.CodeText),l.length&&(t.markers=l.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-s).finish($n.CodeBlock,a-s),s),!0},FencedCode(e,t){let n=rtt(t);if(n<0)return!1;let r=e.lineStart+t.pos,s=t.next,a=n-t.pos,o=t.skipSpace(n),l=_Oe(t.text,t.text.length,o),c=[ya($n.CodeMark,r,r+a)];o<l&&c.push(ya($n.CodeInfo,e.lineStart+o,e.lineStart+l));for(let d=!0,u=!0,f=!1;e.nextLine()&&t.depth>=e.stack.length;d=!1){let A=t.pos;if(t.indent-t.baseIndent<4)for(;A<t.text.length&&t.text.charCodeAt(A)==s;)A++;if(A-t.pos>=a&&t.skipSpace(A)==t.text.length){for(let m of t.markers)c.push(m);u&&f&&wy(c,e.lineStart-1,e.lineStart),c.push(ya($n.CodeMark,e.lineStart+t.pos,e.lineStart+A)),e.nextLine();break}else{f=!0,d||(wy(c,e.lineStart-1,e.lineStart),u=!1);for(let x of t.markers)c.push(x);let m=e.lineStart+t.basePos,g=e.lineStart+t.text.length;m<g&&(wy(c,m,g),u=!1)}}return e.addNode(e.buffer.writeElements(c,-r).finish($n.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=stt(t);return n<0?!1:(e.startContext($n.Blockquote,t.pos),e.addNode($n.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(vge(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode($n.HorizontalRule,n),!0},BulletList(e,t){let n=wge(t,e,!1);if(n<0)return!1;e.block.type!=$n.BulletList&&e.startContext($n.BulletList,t.basePos,t.next);let r=MOe(t,t.pos+1);return e.startContext($n.ListItem,t.basePos,r-t.baseIndent),e.addNode($n.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=kge(t,e,!1);if(n<0)return!1;e.block.type!=$n.OrderedList&&e.startContext($n.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=MOe(t,t.pos+n);return e.startContext($n.ListItem,t.basePos,r-t.baseIndent),e.addNode($n.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=att(t);if(n<0)return!1;let r=t.pos,s=e.lineStart+r,a=_Oe(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!mp(t.text.charCodeAt(o-1)))&&(o=t.text.length);let l=e.buffer.write($n.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),s+n+1),-s);o<t.text.length&&l.write($n.HeaderMark,o-r,a-r);let c=l.finish($n.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(c,s),!0},HTMLBlock(e,t){let n=dtt(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,s=tle[n][1],a=[],o=s!=ele;for(;!s.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let d of t.markers)a.push(d)}o&&e.nextLine();let l=s==ltt?$n.CommentBlock:s==ctt?$n.ProcessingInstructionBlock:$n.HTMLBlock,c=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(l,c-r),r),!0},SetextHeading:void 0};class SAn{constructor(t){this.stage=0,this.elts=[],this.pos=0,this.start=t.start,this.advance(t.content)}nextLine(t,n,r){if(this.stage==-1)return!1;let s=r.content+`
1797
1797
  `+n.scrub(),a=this.advance(s);return a>-1&&a<s.length?this.complete(t,r,a):!1}finish(t,n){return(this.stage==2||this.stage==3)&&hI(n.content,this.pos)==n.content.length?this.complete(t,n,n.content.length):!1}complete(t,n,r){return t.addLeafElement(n,ya($n.LinkReference,this.start,this.start+r,this.elts)),!0}nextStage(t){return t?(this.pos=t.to-this.start,this.elts.push(t),this.stage++,!0):(t===!1&&(this.stage=-1),!1)}advance(t){for(;;){if(this.stage==-1)return-1;if(this.stage==0){if(!this.nextStage(ytt(t,this.pos,this.start,!0)))return-1;if(t.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(ya($n.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(xtt(t,hI(t,this.pos),this.start)))return-1}else if(this.stage==2){let n=hI(t,this.pos),r=0;if(n>this.pos){let s=btt(t,n,this.start);if(s){let a=nee(t,s.to-this.start);a>0&&(this.nextStage(s),r=a)}}return r||(r=nee(t,this.pos)),r>0&&r<t.length?r:-1}else return nee(t,this.pos)}}}function nee(e,t){for(;t<e.length;t++){let n=e.charCodeAt(t);if(n==10)break;if(!mp(n))return-1}return t}class jAn{nextLine(t,n,r){let s=n.depth<t.stack.length?-1:ott(n),a=n.next;if(s<0)return!1;let o=ya($n.HeaderMark,t.lineStart+n.pos,t.lineStart+s);return t.nextLine(),t.addLeafElement(r,ya(a==61?$n.SetextHeading1:$n.SetextHeading2,r.start,t.prevLineEnd(),[...t.parser.parseInline(r.content,r.start),o])),!0}finish(){return!1}}const utt={LinkReference(e,t){return t.content.charCodeAt(0)==91?new SAn(t):null},SetextHeading(){return new jAn}},CAn=[(e,t)=>att(t)>=0,(e,t)=>rtt(t)>=0,(e,t)=>stt(t)>=0,(e,t)=>wge(t,e,!0)>=0,(e,t)=>kge(t,e,!0)>=0,(e,t)=>vge(t,e,!0)>=0,(e,t)=>dtt(t,e,!0)>=0],NAn={text:"",end:0};class PAn{constructor(t,n,r,s){this.parser=t,this.input=n,this.ranges=s,this.line=new OAn,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=s[s.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=s[0].from,this.block=FU.create($n.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=r.length?new _An(r,n):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:t}=this;for(;;){for(let r=0;;){let s=t.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;r<t.markers.length&&(!s||t.markers[r].from<s.end);){let a=t.markers[r++];this.addNode(a.type,a.from,a.to)}if(!s)break;this.finishContext()}if(t.pos<t.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(t.basePos))return null;e:for(;;){for(let r of this.parser.blockParsers)if(r){let s=r(this,t);if(s!=!1){if(s==!0)return null;t.forward();continue e}}break}let n=new kAn(this.lineStart+t.pos,t.text.slice(t.pos));for(let r of this.parser.leafBlockParsers)if(r){let s=r(this,n);s&&n.parsers.push(s)}e:for(;this.nextLine()&&t.pos!=t.text.length;){if(t.indent<t.baseIndent+4){for(let r of this.parser.endLeafBlock)if(r(this,t,n))break e}for(let r of n.parsers)if(r.nextLine(this,t,n))return null;n.content+=`
1798
1798
  `+t.scrub();for(let r of t.markers)n.marks.push(r)}return this.finishLeaf(n),null}stopAt(t){if(this.stoppedAt!=null&&this.stoppedAt<t)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=t}reuseFragment(t){if(!this.fragments.moveTo(this.absoluteLineStart+t,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let n=this.fragments.takeNodes(this);return n?(this.absoluteLineStart+=n,this.lineStart=vtt(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(t=this.depth-1){return this.parser.nodeSet.types[this.stack[t].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(t){let n=NAn;if(n.end=t,t>=this.to)n.text="";else if(n.text=this.lineChunkAt(t),n.end+=n.text.length,this.ranges.length>1){let r=this.absoluteLineStart,s=this.rangeI;for(;this.ranges[s].to<n.end;){s++;let a=this.ranges[s].from,o=this.lineChunkAt(a);n.end=a+o.length,n.text=n.text.slice(0,this.ranges[s-1].to-r)+o,r=n.end-n.text.length}}return n}readLine(){let{line:t}=this,{text:n,end:r}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=r,t.reset(n);t.depth<this.stack.length;t.depth++){let s=this.stack[t.depth],a=this.parser.skipContextMarkup[s.type];if(!a)throw new Error("Unhandled block context "+$n[s.type]);let o=this.line.markers.length;if(!a(s,this,t)){this.line.markers.length>o&&(s.end=this.line.markers[this.line.markers.length-1].to),t.forward();break}t.forward()}}lineChunkAt(t){let n=this.input.chunk(t),r;if(this.input.lineChunks)r=n==`
@@ -1977,7 +1977,7 @@ ${Ie}`:Ie;return x&&wNe(x,De),De})}else if(g)for(const ue of ot)await g(ue)}fina
1977
1977
  `}${n}`}const Xzn=new Set([".md",".markdown",".mdown",".mdx",".txt",".text",".css",".csv",".html",".htm",".js",".json",".jsonl",".jsx",".log",".py",".toml",".ts",".tsx",".xml",".yaml",".yml"]),Gzn=new Set(["application/json","application/javascript","application/typescript","application/xml","application/x-yaml","text/csv","text/html","text/javascript","text/markdown","text/plain","text/xml","text/yaml"]),Yzn=new Set(["HEARTBEAT.MD","MEMORY.MD","SOUL.MD","TOOLS.MD"]),Jzn=new Set(["memory","skills"]),G0e="application/x-rudder-workspace-entry",e$n="[data-workspace-entry-path]";function C2(e){var t;return((t=e.displayLabel)==null?void 0:t.trim())||e.name}function OO(e){return`skills/${e.slug}`}function ede(e,t){return`${OO(e)}/${t.split("/").filter(Boolean).join("/")}`}function t$n(e){const t=e.split("/").filter(Boolean);return t.length===2&&t[0]==="skills"||t.length===4&&t[0]==="agents"&&t[2]==="skills"}function n$n(e){const t=e.split("/").filter(Boolean);return e==="skills"||t.length===3&&t[0]==="agents"&&t[2]==="skills"}function R6(e){const t=vl(e.workspaceEditPath);return!!(t&&t.startsWith(`${OO(e)}/`))}function r$n(e){const t=e.fileInventory.map(n=>vl(n.path)).filter(n=>!!n);return t.length>0?t:["SKILL.md"]}function s$n(e,t,n){const r=n??[],s=vl(e)??"";if(s==="skills"){const d=new Set(t.map(u=>u.path));return r.filter(u=>!R6(u)).map(u=>{var f;return{name:u.slug,displayLabel:((f=u.name)==null?void 0:f.trim())||u.slug,path:OO(u),isDirectory:!0,virtualSkillId:u.id,virtualSkillReadOnlyReason:u.editableReason,virtualSkillSourceLabel:u.sourceLabel}}).filter(u=>!d.has(u.path))}const a=r.find(d=>{if(R6(d))return!1;const u=OO(d);return s===u||s.startsWith(`${u}/`)});if(!a)return[];const o=OO(a),l=s===o?"":s.slice(o.length+1),c=new Map;for(const d of r$n(a)){if(l&&d!==l&&!d.startsWith(`${l}/`))continue;const u=l?d.slice(l.length+1):d,[f]=u.split("/");if(!f)continue;const A=l?`${l}/${f}`:f,m=u.includes("/"),g=`${o}/${A}`;c.set(g,{name:f,displayLabel:f,path:g,isDirectory:m,virtualSkillId:a.id,virtualSkillFilePath:m?null:A,virtualSkillReadOnlyReason:a.editableReason,virtualSkillSourceLabel:a.sourceLabel})}return[...c.values()].sort((d,u)=>Number(u.isDirectory)-Number(d.isDirectory)||C2(d).localeCompare(C2(u)))}function Y0e(e,t,n){if((vl(e)??"")==="")return!(n??[]).some(o=>!R6(o))||t.some(o=>o.path==="skills")?t:[...t,{name:"skills",displayLabel:"skills",path:"skills",isDirectory:!0}].sort((o,l)=>Number(l.isDirectory)-Number(o.isDirectory)||C2(o).localeCompare(C2(l)));const s=s$n(e,t,n);return s.length===0?t:[...t,...s].sort((a,o)=>Number(o.isDirectory)-Number(a.isDirectory)||C2(a).localeCompare(C2(o)))}function Tut(e){return`projects/${e.urlKey||e.id}`}function NH(e){return`${Tut(e)}/resources`}function _ut(e,t){return`${NH(e)}/${t.id}`}function i$n(e){const t=new Map;for(const n of e??[])t.set(Tut(n),{project:n,resources:[...n.resources].sort((r,s)=>r.sortOrder-s.sortOrder||r.resource.name.localeCompare(s.resource.name))});return t}function tde(e,t){if(!t)return null;for(const n of e){const r=n.resources.find(s=>s.id===t);if(r)return{project:n,attachment:r,path:_ut(n,r)}}return null}function cj(e){if(e==="agents")return!0;const t=e.split("/").filter(Boolean);return t.length===2&&t[0]==="agents"}function J0e(e){var n;const t=e.split("/").filter(Boolean);return t.length===3?t[0]==="agents"&&t[2]==="instructions":t.length===4&&t[0]==="agents"&&t[2]==="instructions"?Yzn.has(((n=t[3])==null?void 0:n.toUpperCase())??""):!1}function If(e){var n;const t=(e??"").split("/").filter(Boolean);return t.length===4&&t[0]==="agents"&&t[2]==="instructions"&&((n=t[3])==null?void 0:n.toUpperCase())==="HEARTBEAT.MD"}function e2e(e){var n;const t=e.split("/").filter(Boolean);return t.length>=3&&t[0]==="agents"&&Jzn.has(((n=t[2])==null?void 0:n.toLowerCase())??"")}function PH(e){var t;return((t=e.split("/").filter(Boolean)[0])==null?void 0:t.toLowerCase())==="skills"}function dj(e){return!cj(e)&&!PH(e)}function t2e(e){return!cj(e.path)&&!J0e(e.path)&&!e2e(e.path)&&!PH(e.path)}function n2e(e){return t2e(e)}function r2e(e){return!cj(e.path)&&!J0e(e.path)&&!e2e(e.path)&&!PH(e.path)}function s2e(e){return e.entityType==="orphaned_agent_workspace"&&cj(e.path)&&e.path!=="agents"?!0:!cj(e.path)&&!J0e(e.path)&&!e2e(e.path)&&!PH(e.path)&&!Mut(e.path)}function Mut(e){const t=e.split("/").filter(Boolean);return t.length===2&&t[0]==="projects"}function B_(e){const t=e.split("/").filter(Boolean);return t.pop(),t.join("/")}function F5(e,t,n){return e===t?n:e.startsWith(`${t}/`)?`${n}${e.slice(t.length)}`:e}function Q_(e,t){return!t2e(e)||!dj(t)||e.path===t||e.isDirectory&&t.startsWith(`${e.path}/`)?!1:B_(e.path)!==t}function i2e(e){return Array.from(e.types).includes(G0e)}function x3(e){return Array.from(e.types).includes("Files")||e.files.length>0}function a$n(e){var r;const t=((r=e.type.toLowerCase().split(";")[0])==null?void 0:r.trim())??"";if(t.startsWith("text/")||Gzn.has(t))return!0;const n=jw(e.name);return n!==null&&Xzn.has(n)}function a2e(e){const t=Array.from(e.files),n=t.filter(r=>U_(r.name)&&a$n(r));return{supported:n,unsupportedCount:t.length-n.length}}function Eut(e){return e.target instanceof HTMLElement&&!!e.target.closest(e$n)}function U_(e){const t=e.trim();return!!t&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")}function o2e(e,t){return e?`${e}/${t}`:t}function Xv(e,t){return e?`${e.replace(/\/+$/,"")}/${t}`:t}function Dut(e,t,n){return n?hvt(n,t,e):pvt(e,t)}function o$n(e,t){return`[${t.replace(/([\\[\]])/g,"\\$1")}](/library?directory=${encodeURIComponent(e)})`}function Rut(e){const t=C2(e);return e.isDirectory?o$n(e.path,t):Dut(e.path,t,e.libraryEntryId)}function e$(e){return e.split("/").filter(Boolean).at(-1)??e}function l$n(e,t,n,r){const s=e.split("/").filter(Boolean),a={label:r,path:"",isFile:!1,kind:"folder"};return s.length===0?[a]:[a,...s.map((o,l)=>{const c=s.slice(0,l+1).join("/"),d=n==="file"&&l===s.length-1;if(s[0]==="agents"&&l===1){const u=t.get(o);return{label:u?C2(u):o,path:c,isFile:d,kind:"agent_workspace",agentIcon:(u==null?void 0:u.agentIcon)??null,agentRole:(u==null?void 0:u.agentRole)??null}}return{label:o,path:c,isFile:d,kind:o==="agents"&&l===0?"agents_root":d?"file":"folder"}})]}function c$n(e,t){if(!t)return e;const n=OO(t);return e.map(r=>{var s;return r.path===n?{...r,label:((s=t.name)==null?void 0:s.trim())||t.slug}:r})}const d$n=["Install or import a skill into this Rudder organization.","","Source or command:","<paste a GitHub URL, local path, or skills.sh command here>","","After importing, verify it appears in Library / skills and explain whether it is editable or read-only."].join(`
1978
1978
  `);function Lut({open:e,orgId:t,onOpenChange:n}){const r=Yr(),s=Vn(),{pushToast:a}=ss(),[o,l]=h.useState(""),c=o.split(/\r?\n/).map(A=>A.trim()).filter(Boolean),d=h.useCallback(async()=>{t&&await Promise.all([s.invalidateQueries({queryKey:V.organizationSkills.list(t)}),s.invalidateQueries({queryKey:["organizations",t,"workspace-files"]})])},[t,s]),u=xt({mutationFn:async A=>{if(!t)throw new Error("Select an organization before importing skills.");return Promise.all(A.sources.map(m=>nf.importFromSource(t,m)))},onSuccess:A=>{d(),l(""),n(!1);const m=A.reduce((g,x)=>g+x.imported.length,0);a({title:m===1?"Skill imported":`${m} skills imported`,body:m>0?"The skills list has been refreshed.":"No new skills were imported.",tone:m>0?"success":"info"})},onError:A=>{a({title:A instanceof Error?A.message:"Failed to import skill",tone:"error"})}}),f=xt({mutationFn:async()=>{if(!t)throw new Error("Select an organization before scanning skills.");return nf.scanLocal(t)},onSuccess:A=>{d(),n(!1);const m=A.imported.length+A.updated.length;a({title:m===1?"Local skill synced":`${m} local skills synced`,body:A.warnings.length>0?A.warnings.join(", "):void 0,tone:A.warnings.length>0?"warn":"success"})},onError:A=>{a({title:A instanceof Error?A.message:"Failed to scan local skills",tone:"error"})}});return i.jsx(Ps,{open:e,onOpenChange:A=>{!A&&!u.isPending&&!f.isPending?n(!1):A&&n(!0)},children:i.jsxs(zs,{className:"!w-[min(40rem,calc(100vw-2rem))] !max-w-[calc(100vw-2rem)] gap-6 p-6 sm:!max-w-[40rem]",children:[i.jsxs(vi,{children:[i.jsx(ei,{children:"Add skill to Library"}),i.jsx(Si,{className:"max-w-[34rem]",children:"Import or move a skill into this organization. Workspace-backed skills become editable Library files; bundled or remote skills appear here as read-only references."})]}),i.jsx("div",{className:"space-y-5",children:i.jsxs("label",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-muted-foreground",children:"Skill source, one per line"}),i.jsx(Bl,{value:o,onChange:A=>l(A.target.value),placeholder:`https://github.com/org/repo/tree/main/.agents/skills/example
1979
1979
  /Users/me/.agents/skills/example
1980
- skills install example`,className:"field-sizing-fixed min-h-28 min-w-0 resize-y overflow-x-auto whitespace-pre-wrap break-all font-mono text-xs",disabled:u.isPending||f.isPending,autoFocus:!0})]})}),i.jsxs(ga,{className:"flex-col gap-3 border-t border-border/60 pt-4 sm:flex-row sm:items-center sm:justify-between",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:flex-1",children:[i.jsx(le,{type:"button",onClick:()=>u.mutate({sources:c}),disabled:!t||c.length===0||u.isPending||f.isPending,children:u.isPending?"Importing...":"Import skill"}),i.jsx(le,{type:"button",variant:"outline",onClick:()=>f.mutate(),disabled:!t||u.isPending||f.isPending,children:f.isPending?"Scanning...":"Scan local skills"}),i.jsx(le,{type:"button",variant:"outline","data-testid":"org-workspaces-skill-agent-install-button",onClick:()=>{n(!1),r(`/messenger/chat?prefill=${encodeURIComponent(d$n)}`)},children:"Ask Agent to install"})]}),i.jsx(le,{type:"button",variant:"ghost",className:"w-full sm:w-auto",onClick:()=>n(!1),disabled:u.isPending||f.isPending,children:"Close"})]})]})})}const zut="[data-workspace-entry-path]";function u$n(e){return JSON.stringify({path:e.path,isDirectory:e.isDirectory})}function f$n(e){var r;if(typeof e.dataTransfer.setDragImage!="function")return;const t=e.currentTarget.cloneNode(!0);if(!(t instanceof HTMLElement))return;(r=t.querySelector("[data-testid^='org-workspaces-entry-more-']"))==null||r.remove(),t.classList.remove("hover:bg-accent/60","hover:bg-accent/50","hover:text-foreground"),t.classList.add("rudder-workspace-tree-drag-image"),t.removeAttribute("data-workspace-entry-path"),t.removeAttribute("draggable");const n=e.currentTarget.getBoundingClientRect();t.style.position="fixed",t.style.top="-1000px",t.style.left="-1000px",t.style.width=`${Math.min(Math.max(n.width||220,190),300)}px`,t.style.paddingLeft="10px",t.style.opacity="1",t.style.pointerEvents="none",t.style.zIndex="-1",document.body.appendChild(t),e.dataTransfer.setDragImage(t,Math.min(e.clientX-n.left,26),Math.min(e.clientY-n.top,16)),window.setTimeout(()=>t.remove(),0)}function l2e(e){const t=e.dataTransfer.getData(G0e);if(!t)return null;try{const n=JSON.parse(t);return typeof n.path!="string"||typeof n.isDirectory!="boolean"?null:{path:n.path,isDirectory:n.isDirectory}}catch{return null}}function nq(e){const t=e.relatedTarget;return!(t instanceof Node)||!e.currentTarget.contains(t)}function c2e(e){var r;if(typeof document>"u")return;const t=Array.from(document.querySelectorAll(zut)).find(s=>s.dataset.workspaceEntryPath===e);if(!t)return;(r=t.scrollIntoView)==null||r.call(t,{block:"center"});const n=t.querySelector("button");n==null||n.focus({preventScroll:!0})}function A$n(){return typeof document>"u"?[]:Array.from(document.querySelectorAll(zut))}function yne(e,t,n){const r=A$n(),s=r.findIndex(l=>l.dataset.workspaceEntryPath===e);if(s<0)return;const a=r[s+t],o=a==null?void 0:a.dataset.workspaceEntryPath;o&&(n(o),c2e(o))}function h$n(e,t){const n=B_(e);n&&(t(n),c2e(n))}function m$n(e){switch(e){case"directory":return wo;case"file":return Fi;case"connector_object":return wc;case"url":default:return qm}}function p$n({group:e,selectedResourcePath:t,activeEntryPath:n,onSelectResource:r,onFocusEntry:s,onAddResources:a,onCopyResourceLocator:o,onOpenResource:l,onUnlinkResource:c,unlinkingResourceId:d,depth:u}){const f=NH(e.project),[A,m]=h.useState((t==null?void 0:t.startsWith(`${f}/`))??!1),g=n===f,[x,y]=h.useState(!1);return h.useEffect(()=>{t!=null&&t.startsWith(`${f}/`)&&m(!0)},[f,t]),i.jsx("ul",{className:"space-y-0.5",children:i.jsxs("li",{children:[i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm text-foreground transition-colors hover:bg-accent/60",g&&"bg-accent text-foreground"),style:{paddingLeft:`${u*14+8}px`},"data-workspace-entry-path":f,"data-testid":`org-workspaces-project-resources-folder-${e.project.id}`,onContextMenu:v=>{v.preventDefault(),v.stopPropagation(),s(f),y(!0)},children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{s(f),m(v=>!v)},onFocus:()=>s(f),"aria-expanded":A,"aria-selected":g,children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground",children:A?i.jsx(qr,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})}),i.jsx(wo,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:"resources"}),i.jsx("span",{className:"shrink-0 rounded-full border border-border bg-background px-1.5 py-0.5 text-[10px] text-muted-foreground",children:e.resources.length})]}),i.jsxs(Ei,{open:x,onOpenChange:y,children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":`More actions for ${e.project.name} resources`,"data-testid":`org-workspaces-project-resources-more-${e.project.id}`,onClick:v=>{v.stopPropagation(),s(f)},children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsx(Ri,{align:"end",sideOffset:6,className:"w-44",onClick:v=>v.stopPropagation(),children:i.jsxs(Xt,{onSelect:()=>a(e.project),children:[i.jsx(qm,{className:"h-3.5 w-3.5"}),"Add resources"]})})]})]}),A?i.jsx("ul",{className:"space-y-0.5",children:e.resources.map(v=>{const w=_ut(e.project,v),k=t===w,S=n===w,j=m$n(v.resource.kind),C=d===v.id;return i.jsx("li",{children:i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm transition-colors",k||S?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"),style:{paddingLeft:`${(u+1)*14+23}px`},"data-workspace-entry-path":w,"data-testid":`org-workspaces-project-resource-${v.id}`,children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{s(w),r(v.id)},onFocus:()=>s(w),"aria-selected":S||k,children:[i.jsx(j,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:v.resource.name})]}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":`More actions for ${v.resource.name}`,"data-testid":`org-workspaces-project-resource-more-${v.id}`,onClick:N=>{N.stopPropagation(),s(w)},children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",sideOffset:6,className:"w-48",onClick:N=>N.stopPropagation(),children:[i.jsxs(Xt,{onSelect:()=>l(v),children:[i.jsx(Ja,{className:"h-3.5 w-3.5"}),"Open resource"]}),i.jsxs(Xt,{onSelect:()=>o(v),children:[i.jsx(Al,{className:"h-3.5 w-3.5"}),"Copy locator"]}),i.jsx(Yo,{}),i.jsxs(Xt,{variant:"destructive",disabled:C,onSelect:()=>c(e.project,v),children:[C?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(YPt,{className:"h-3.5 w-3.5"}),"Unlink resource"]})]})]})]})},v.id)})}):null]})})}function g$n({orgId:e,directoryPath:t,organizationSkills:n,selectedFilePath:r,selectedSkillTreePath:s,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H}){const{data:X}=Me({queryKey:V.organizations.workspaceFiles(e,t),queryFn:()=>_n.listWorkspaceFiles(e,t),enabled:!!e,refetchOnWindowFocus:!1}),F=h.useMemo(()=>Y0e(t,(X==null?void 0:X.entries)??[],n),[X==null?void 0:X.entries,t,n]);return F.length===0?null:i.jsx("ul",{className:"space-y-0.5",children:F.map(Q=>i.jsx(d2e,{orgId:e,entry:Q,organizationSkills:n,selectedFilePath:r,selectedSkillTreePath:s,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H},Q.path))})}function d2e({orgId:e,entry:t,organizationSkills:n=[],selectedFilePath:r,selectedSkillTreePath:s=null,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H=0}){const[X,F]=h.useState(D.has(t.path)),[Q,q]=h.useState(!1),[B,ee]=h.useState(!1),se=C2(t),re=!!t.virtualSkillId,ne=t.entityType==="agent_workspace",Ae=t.path==="agents",Y=n$n(t.path),ce=t$n(t.path),Oe=Mut(t.path),Fe=cj(t.path),ke=L.get(t.path)??null,Ne=!re&&t.isDirectory&&dj(t.path),xe=!re&&n2e(t),ae=!re&&t2e(t),fe=!re&&r2e(t),ve=!re&&s2e(t),Se=!re&&t.isDirectory&&dj(t.path),ze=t.isDirectory?U:F_(U),ft=o===t.path||s===t.path||!o&&r===t.path,ie=l===t.path,me=Be=>{Be.preventDefault(),Be.stopPropagation(),f(t.path),q(!0)},we=Be=>{if(!ae){Be.preventDefault();return}Be.dataTransfer.effectAllowed="move",Be.dataTransfer.setData(G0e,u$n(t)),Be.dataTransfer.setData("text/plain",t.path),A(t.path),f$n(Be)},Xe=Be=>{if(!Se)return;const it=x3(Be.dataTransfer);!i2e(Be.dataTransfer)&&!it||(Be.preventDefault(),Be.dataTransfer.dropEffect=it?"copy":"move",ee(!0))},ge=Be=>{nq(Be)&&ee(!1)},te=Be=>{if(!Se)return;if(Be.preventDefault(),Be.stopPropagation(),ee(!1),x3(Be.dataTransfer)){const{supported:lt,unsupportedCount:Ue}=a2e(Be.dataTransfer);N(lt,t.path,Ue),F(!0);return}const it=l2e(Be);it&&Q_(it,t.path)&&(C(it,t.path),F(!0))},G=Be=>{if(!(Be.metaKey||Be.ctrlKey||Be.altKey)){if(Be.key==="ArrowDown"){Be.preventDefault(),yne(t.path,1,f);return}if(Be.key==="ArrowUp"){Be.preventDefault(),yne(t.path,-1,f);return}if(Be.key==="ArrowRight"&&t.isDirectory){Be.preventDefault(),f(t.path),X?window.requestAnimationFrame(()=>yne(t.path,1,f)):F(!0);return}if(Be.key==="ArrowLeft"){Be.preventDefault(),f(t.path),t.isDirectory&&X?F(!1):h$n(t.path,f);return}Be.key==="Enter"&&(Be.preventDefault(),f(t.path),t.isDirectory?F(it=>!it):t.virtualSkillId&&t.virtualSkillFilePath?d==null||d(t.virtualSkillId,t.virtualSkillFilePath,t.path):c(t.path))}},oe=i.jsxs(Ei,{open:Q,onOpenChange:q,children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":`More actions for ${se}`,"data-testid":`org-workspaces-entry-more-${t.path}`,onClick:Be=>Be.stopPropagation(),children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",sideOffset:6,className:"w-60 whitespace-nowrap will-change-[opacity,transform] data-[state=open]:duration-150 data-[state=open]:ease-out data-[state=closed]:duration-100 data-[state=closed]:ease-in",onClick:Be=>Be.stopPropagation(),onContextMenu:Be=>{Be.preventDefault(),Be.stopPropagation()},children:[i.jsxs(Xt,{onSelect:()=>g(t),children:[i.jsx(qm,{className:"h-3.5 w-3.5"}),"Copy link"]}),i.jsxs(Xt,{onSelect:()=>x(t),children:[i.jsx(Al,{className:"h-3.5 w-3.5"}),"Copy absolute path"]}),Fe?null:i.jsxs(i.Fragment,{children:[y||v||Ne?i.jsx(Yo,{}):null,y||v?ze.length>0&&v?i.jsxs(r6,{children:[i.jsxs(s6,{className:"h-9 rounded-[6px] px-2 text-sm","data-testid":`org-workspaces-entry-open-submenu-${t.path}`,children:[i.jsx(Ja,{className:"h-3.5 w-3.5"}),t.isDirectory?"Open folder":"Open In"]}),i.jsx(i6,{sideOffset:6,className:"w-60 whitespace-nowrap p-1",children:ze.map(Be=>i.jsxs(Xt,{className:"h-9 gap-2 rounded-[6px]",disabled:$!==null,"data-testid":`org-workspaces-entry-open-target-${t.path}-${Be.id}`,onSelect:()=>v(t,Be),children:[$===Be.id?i.jsx(hn,{className:"h-4 w-4 animate-spin"}):i.jsx(mb,{target:Be}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:Be.label}),i.jsx("span",{className:"text-[11px] capitalize text-muted-foreground",children:Be.kind})]},Be.id))})]}):y?i.jsxs(Xt,{onSelect:()=>y(t),children:[i.jsx(Ja,{className:"h-3.5 w-3.5"}),t.isDirectory?"Open folder":"Open In"]}):null:null,Ne?i.jsxs(i.Fragment,{children:[y||v?i.jsx(Yo,{}):null,i.jsxs(Xt,{onSelect:()=>w(t,"file"),children:[i.jsx(F7,{className:"h-3.5 w-3.5"}),"New file"]}),i.jsxs(Xt,{onSelect:()=>w(t,"folder"),children:[i.jsx(j3,{className:"h-3.5 w-3.5"}),"New folder"]})]}):null,xe||fe||ve?i.jsx(Yo,{}):null,xe?i.jsxs(Xt,{onSelect:()=>k(t),children:[i.jsx(cCt,{className:"h-3.5 w-3.5"}),"Create copy"]}):null,fe?i.jsxs(Xt,{onSelect:()=>S(t),children:[i.jsx(JA,{className:"h-3.5 w-3.5"}),"Rename"]}):null,ve?i.jsxs(Xt,{variant:"destructive",onSelect:()=>j(t),children:[i.jsx(yi,{className:"h-3.5 w-3.5"}),"Delete"]}):null]}),Fe&&ve?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{variant:"destructive",onSelect:()=>j(t),children:[i.jsx(yi,{className:"h-3.5 w-3.5"}),"Delete"]})]}):null]})]});if(h.useEffect(()=>{D.has(t.path)&&F(!0)},[t.path,D]),t.isDirectory)return i.jsxs("li",{children:[i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm text-foreground transition-[background-color,color,opacity,transform] duration-150",ie?"rudder-workspace-tree-entry--dragging text-muted-foreground":"hover:bg-accent/60",ft&&!ie&&"bg-accent text-foreground",B&&!ie&&"bg-[#2f80ed]/10 ring-1 ring-[#2f80ed]/30"),style:{paddingLeft:`${H*14+8}px`},"data-workspace-entry-path":t.path,"data-dragging-workspace-entry":ie?"true":void 0,draggable:ae,onDragStart:we,onDragEnd:()=>{ee(!1),m()},onDragOver:Xe,onDragLeave:ge,onDrop:te,onContextMenu:me,children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{f(t.path),F(Be=>!Be)},onFocus:()=>f(t.path),onKeyDown:G,"aria-expanded":X,"aria-selected":ft,children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground",children:X?i.jsx(qr,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})}),ne?i.jsx("span",{"data-testid":"org-workspaces-agent-icon",className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-muted-foreground",children:i.jsx(Il,{icon:t.agentIcon,role:t.agentRole,className:"h-3.5 w-3.5 text-[12px]"})}):Ae?i.jsx(C3,{"data-testid":"org-workspaces-agents-root-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):Y?i.jsx(wc,{"data-testid":"org-workspaces-skills-root-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):ce?i.jsx(dBe,{"data-testid":"org-workspaces-skill-folder-icon",className:"h-3.5 w-3.5 shrink-0 text-[#2f80ed]"}):Oe?ke?i.jsx(uo,{color:ke.project.color,icon:ke.project.icon,size:"xs",testId:"org-workspaces-project-icon"}):i.jsx(TBe,{"data-testid":"org-workspaces-project-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx(wo,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx("div",{className:"truncate font-medium",children:se})}),ne?i.jsx("span",{"aria-hidden":"true","data-testid":"org-workspaces-agent-badge",className:"inline-flex shrink-0 items-center gap-1 rounded-full border border-border bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Agent"}):null]}),t.path==="skills"?i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":"Add skill to Library","data-testid":"org-workspaces-skills-add-button",onClick:Be=>{Be.preventDefault(),Be.stopPropagation(),R==null||R()},children:i.jsx(Zr,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"Add skill"})]}):null,re?null:oe]}),X?i.jsxs(i.Fragment,{children:[i.jsx(g$n,{orgId:e,directoryPath:t.path,organizationSkills:n,selectedFilePath:r,selectedSkillTreePath:s,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H+1}),ke?i.jsx(p$n,{group:ke,selectedResourcePath:a,activeEntryPath:o,onSelectResource:u,onFocusEntry:f,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,unlinkingResourceId:_,depth:H+1}):null]}):null]});const Ze=r===t.path||s===t.path,Te=Qzn(t.path)?kBe:Wzn(t.path)?Kfe:Zzn(t.path)?qfe:Kzn(t.path)?Fi:K6;return i.jsx("li",{children:i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm transition-[background-color,color,opacity,transform] duration-150",ie?"rudder-workspace-tree-entry--dragging text-muted-foreground":Ze||ft?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"),style:{paddingLeft:`${H*14+23}px`},"data-workspace-entry-path":t.path,"data-dragging-workspace-entry":ie?"true":void 0,draggable:ae,onDragStart:we,onDragEnd:()=>{ee(!1),m()},onContextMenu:me,children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{f(t.path),t.virtualSkillId&&t.virtualSkillFilePath?d==null||d(t.virtualSkillId,t.virtualSkillFilePath,t.path):c(t.path)},onFocus:()=>f(t.path),onKeyDown:G,"aria-selected":ft||Ze,children:[i.jsx(Te,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:se})]}),re?null:oe]})})}const nde="rudder:workspace-flush-draft";function rde(){typeof window>"u"||window.dispatchEvent(new Event(nde))}function $ut(e){const t=Me({queryKey:e?V.projects.list(e):V.projects.list("__none__"),queryFn:()=>Mi.list(e),enabled:!!e,refetchOnWindowFocus:!1}),n=h.useMemo(()=>i$n(t.data),[t.data]);return{projects:t.data??[],groupsByLibraryPath:n,isLoading:t.isLoading}}async function Fut(e,t,n){const r=[],s=[];for(const a of n){const o=o2e(t,a.name);try{r.push(await _n.createWorkspaceFile(e,{filePath:o,content:await a.text()}))}catch(l){s.push({fileName:a.name,filePath:o,message:l instanceof Error?l.message:"Failed to import file"})}}return{imported:r,failed:s}}async function zI(e){var n;const t=Pn();if(t!=null&&t.copyText)await t.copyText(e);else if((n=navigator.clipboard)!=null&&n.writeText)await navigator.clipboard.writeText(e);else throw new Error("Clipboard is not available in this environment.")}function xo(e,t,n){const r=new URLSearchParams(e);n?r.set("path",n):r.delete("path"),r.delete("entry"),r.delete("doc"),r.delete("skill"),r.delete("skillFile"),n&&r.delete("directory"),r.delete("resource"),t(r,{replace:!0})}function But(e,t,n){const r=new URLSearchParams(e);r.set("resource",n),r.delete("doc"),r.delete("path"),r.delete("skill"),r.delete("skillFile"),r.delete("directory"),t(r,{replace:!0})}function Qut(e,t,n,r){const s=new URLSearchParams(e);s.set("skill",n),s.set("skillFile",r),s.delete("path"),s.delete("entry"),s.delete("doc"),s.delete("directory"),s.delete("resource"),t(s,{replace:!0})}function SPe(e,t,n){const r=new URLSearchParams(e);n?r.set("directory",n):r.delete("directory"),r.delete("path"),r.delete("entry"),r.delete("doc"),r.delete("skill"),r.delete("skillFile"),r.delete("resource"),t(r,{replace:!0})}function IH(e){return/^https?:\/\//i.test(e.trim())}function u2e(e,t){const n=e.resource.locator.trim();return!n||IH(n)?null:e.resource.sourceType==="library"?Xv(t,n):e.resource.kind==="file"||e.resource.kind==="directory"?n:null}function x$n({onCollapseSidebar:e}={}){var Je,_e,Ee,Ce,kt;const t=Vn(),n=Yr(),{pushToast:r}=ss(),{locale:s}=is(),{viewedOrganizationId:a}=th(),[o,l]=gd(),c=vl(o.get("entry")),d=c?null:vl(o.get("skill")),u=d?vl(o.get("skillFile"))??"SKILL.md":null,f=c||d?null:vl(o.get("path")),A=c||d?null:vl(o.get("resource")),m=c||d?null:vl(o.get("directory")),g=bs("org-workspaces:files-sidebar"),[x,y]=h.useState(null),[v,w]=h.useState(""),[k,S]=h.useState(null),[j,C]=h.useState(""),[N,P]=h.useState(null),[M,E]=h.useState(!1),[T,R]=h.useState(!1),[_,D]=h.useState(null),[U,$]=h.useState(f??m),L=Me({queryKey:V.organizations.workspaceFiles(a??"__none__",""),queryFn:()=>_n.listWorkspaceFiles(a,""),enabled:!!a,refetchOnWindowFocus:!1}),H=Me({queryKey:V.organizations.libraryEntry(a??"__none__",c??""),queryFn:()=>_n.getLibraryEntry(a,c),enabled:!!a&&!!c,refetchOnWindowFocus:!1}),F=Me({queryKey:V.organizationSkills.list(a??"__none__"),queryFn:()=>nf.list(a),enabled:!!a,refetchOnWindowFocus:!1}).data??[],Q=h.useMemo(()=>{var Qe;return Y0e("",((Qe=L.data)==null?void 0:Qe.entries)??[],F)},[F,(Je=L.data)==null?void 0:Je.entries]),q=F.find(Qe=>Qe.id===d)??null,B=q&&!R6(q)?q:null,ee=B&&u?ede(B,u):null,se=$ut(a),re=h.useMemo(()=>tde(se.projects,A),[se.projects,A]),ne=(re==null?void 0:re.path)??null,Ae=Kce(a),Y=!!(f||Ae.openFilePaths.length>0),ce=!!(f||ee||m),Oe=(_e=L.data)!=null&&_e.rootExists?L.data.rootPath:null,Fe=h.useMemo(()=>({name:"",path:"",isDirectory:!0,displayLabel:_i("library",s)}),[s]),[ke,Ne]=h.useState([]),[xe,ae]=h.useState(null),fe=h.useMemo(()=>f?kO(f):ee?kO(ee):ne?kO(ne):m?Vdt(m):new Set,[m,f,ne,ee]);h.useEffect(()=>{var Qe;if(d&&q&&R6(q)){const gt=vl(q.workspaceEditPath);gt&&xo(o,l,gt);return}if(c){((Qe=H.data)==null?void 0:Qe.status)==="active"&&H.data.currentPath?xo(o,l,H.data.currentPath):$(null);return}f?$(f):ee?$(ee):ne?$(ne):m&&$(m)},[(Ee=H.data)==null?void 0:Ee.currentPath,m,c,d,o,f,q,ne,ee,l]),h.useEffect(()=>{const Qe=()=>{R(!1),D(null)};return window.addEventListener("dragend",Qe),window.addEventListener("drop",Qe,!0),()=>{window.removeEventListener("dragend",Qe),window.removeEventListener("drop",Qe,!0)}},[]),h.useEffect(()=>{const Qe=Pn();let gt=!1;return typeof(Qe==null?void 0:Qe.listWorkspaceLaunchTargets)=="function"?Qe.listWorkspaceLaunchTargets().then(Nt=>{gt||Ne(Nt)}).catch(()=>{gt||Ne([])}):Ne([]),()=>{gt=!0}},[]);const ve=h.useCallback(async()=>{a&&await Promise.all([t.invalidateQueries({queryKey:["organizations",a,"workspace-files"]}),t.invalidateQueries({queryKey:["organizations",a,"workspace-file"]})])},[t,a]),Se=xt({mutationFn:Qe=>Mi.removeResourceAttachment(Qe.project.id,Qe.attachment.id,Qe.project.orgId),onSuccess:(Qe,gt)=>{t.invalidateQueries({queryKey:V.projects.list(gt.project.orgId)}),t.invalidateQueries({queryKey:V.projects.resources(gt.project.id)}),A===gt.attachment.id&&(xo(o,l,null),$(NH(gt.project))),r({title:"Resource unlinked",body:Qe.resource.name,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to unlink resource",tone:"error"})}}),ze=xt({mutationFn:async Qe=>{rde();const gt=o2e(Qe.parent.path,Qe.name.trim());return Qe.kind==="folder"?{kind:Qe.kind,result:await _n.createWorkspaceDirectory(a,{directoryPath:gt})}:{kind:Qe.kind,result:await _n.createWorkspaceFile(a,{filePath:gt,content:""})}},onSuccess:({kind:Qe,result:gt})=>{if(!a)return;ve(),y(null),w(""),Qe==="file"&&"filePath"in gt&&(t.setQueryData(V.organizations.workspaceFile(a,gt.filePath),gt),$(gt.filePath),xo(o,l,gt.filePath));const Nt="filePath"in gt?gt.filePath:gt.path;r({title:Qe==="file"?"File created":"Folder created",body:Nt,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to create workspace entry",tone:"error"})}}),ft=xt({mutationFn:async Qe=>(rde(),{...await Fut(a,Qe.destinationDirectoryPath,Qe.files),unsupportedCount:Qe.unsupportedCount??0}),onSuccess:({imported:Qe,failed:gt,unsupportedCount:Nt})=>{if(!a)return;if(Qe.length>0){ve();for(const Rn of Qe)t.setQueryData(V.organizations.workspaceFile(a,Rn.filePath),Rn)}const Gt=Qe.at(-1);Gt&&($(Gt.filePath),xo(o,l,Gt.filePath));const cn=[...gt.map(Rn=>`${Rn.fileName}: ${Rn.message}`),...Nt>0?[`${Nt} unsupported file${Nt===1?"":"s"}`]:[]].join(", ");if(Qe.length===0){r({title:"No files imported",body:cn||"Only text, Markdown, and code files can be imported.",tone:gt.length>0?"error":"warn"});return}r({title:gt.length>0||Nt>0?`Imported ${Qe.length} of ${Qe.length+gt.length+Nt} files`:Qe.length===1?"File imported":`${Qe.length} files imported`,body:cn?`${Qe.map(Rn=>Rn.filePath).join(", ")}. Failed: ${cn}`:Qe.map(Rn=>Rn.filePath).join(", "),tone:gt.length>0||Nt>0?"warn":"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to import files",tone:"error"})}}),ie=xt({mutationFn:Qe=>_n.renameWorkspaceEntry(a,Qe.entry.path,{name:Qe.name}),onSuccess:Qe=>{if(ve(),S(null),C(""),Qe.previousPath&&f){const gt=f===Qe.previousPath?Qe.path:f.startsWith(`${Qe.previousPath}/`)?`${Qe.path}${f.slice(Qe.previousPath.length)}`:f;gt!==f&&xo(o,l,gt)}Qe.previousPath&&U&&$(F5(U,Qe.previousPath,Qe.path)),r({title:"Workspace entry renamed",body:Qe.previousPath?`${Qe.previousPath} -> ${Qe.path}`:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to rename workspace entry",tone:"error"})}}),me=xt({mutationFn:Qe=>_n.moveWorkspaceEntry(a,Qe.entry.path,{destinationDirectoryPath:Qe.destinationDirectoryPath}),onSuccess:Qe=>{if(ve(),Qe.previousPath&&f){const gt=F5(f,Qe.previousPath,Qe.path);gt!==f&&xo(o,l,gt)}Qe.previousPath&&U&&$(F5(U,Qe.previousPath,Qe.path)),r({title:"Workspace entry moved",body:Qe.previousPath?`${Qe.previousPath} -> ${Qe.path}`:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to move workspace entry",tone:"error"})}}),we=xt({mutationFn:Qe=>_n.copyWorkspaceEntry(a,Qe.path),onSuccess:Qe=>{ve(),Qe.isDirectory?$(Qe.path):($(Qe.path),xo(o,l,Qe.path)),r({title:"Workspace entry copied",body:Qe.previousPath?`${Qe.previousPath} -> ${Qe.path}`:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to copy workspace entry",tone:"error"})}}),Xe=xt({mutationFn:Qe=>_n.deleteWorkspaceEntry(a,Qe.path),onSuccess:Qe=>{ve(),P(null),f&&(f===Qe.path||f.startsWith(`${Qe.path}/`))&&xo(o,l,null),U&&(U===Qe.path||U.startsWith(`${Qe.path}/`))&&$(B_(Qe.path)||null),r({title:"Workspace entry deleted",body:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to delete workspace entry",tone:"error"})}});async function ge(Qe){const gt=Rut(Qe);try{await zI(gt),r({title:"Library link copied",tone:"info"})}catch(Nt){r({title:"Failed to copy Library link",body:Nt instanceof Error?Nt.message:gt,tone:"error"})}}async function te(Qe){const gt=Xv(Oe,Qe.path);try{await zI(gt),r({title:"Absolute path copied",body:gt,tone:"info"})}catch(Nt){r({title:"Failed to copy absolute path",body:Nt instanceof Error?Nt.message:gt,tone:"error"})}}async function G(Qe){const gt=Xv(Oe,Qe.path),Nt=Pn();if(Nt!=null&&Nt.openPath)try{await Nt.openPath(gt),r({title:Qe.isDirectory?"Opened folder":"Opened in editor",body:gt,tone:"info"})}catch(Gt){r({title:Qe.isDirectory?"Failed to open folder":"Failed to open in editor",body:Gt instanceof Error?Gt.message:gt,tone:"error"})}}function oe(Qe){n(`/projects/${Qe.urlKey??Qe.id}/resources`)}async function Ze(Qe){var Gt;const gt=Qe.resource.locator,Nt=Pn();try{if(Nt!=null&&Nt.copyText)await Nt.copyText(gt);else if((Gt=navigator.clipboard)!=null&&Gt.writeText)await navigator.clipboard.writeText(gt);else throw new Error("Clipboard is not available in this environment.");r({title:"Resource locator copied",body:gt,tone:"info"})}catch(cn){r({title:"Failed to copy resource locator",body:cn instanceof Error?cn.message:gt,tone:"error"})}}async function Te(Qe){const gt=Qe.resource.locator.trim(),Nt=Pn();try{if(Qe.resource.kind==="url"||IH(gt)){Nt!=null&&Nt.openExternal?await Nt.openExternal(gt):window.open(gt,"_blank","noopener,noreferrer"),r({title:"Opened resource link",body:gt,tone:"info"});return}const Gt=u2e(Qe,Oe);if(!Gt||!(Nt!=null&&Nt.openPath))throw new Error("This resource cannot be opened from the current shell.");await Nt.openPath(Gt),r({title:"Opened resource",body:Gt,tone:"info"})}catch(Gt){r({title:"Failed to open resource",body:Gt instanceof Error?Gt.message:gt,tone:"error"})}}async function Be(Qe,gt,Nt="workspace"){const Gt=Pn();if(Gt!=null&&Gt.openWorkspace){ae(gt.id);try{await Gt.openWorkspace(Qe,gt.id),LI(gt.id),r({title:`Opened ${Nt} in ${gt.label}`,tone:"info"})}catch(cn){r({title:`Failed to open ${Nt}`,body:cn instanceof Error?cn.message:`Could not open the ${Nt} in ${gt.label}.`,tone:"error"})}finally{ae(null)}}}async function it(Qe,gt){if(Qe.isDirectory){if($5(gt))return;await Be(Xv(Oe,Qe.path),gt,"folder");return}if(!Oe)return;const Nt=Pn();if(typeof(Nt==null?void 0:Nt.openWorkspaceFileInIde)!="function")return;const Gt=$5(gt)?gt:F_([gt]).find(cn=>cn.id===gt.id);if(Gt){ae(Gt.id);try{await Nt.openWorkspaceFileInIde(Oe,Qe.path,Gt.id),Gt.workspaceTarget&&LI(Gt.workspaceTarget.id),r({title:Gt.id==="defaultApp"?"Opened file":`Opened file in ${Gt.label}`,body:Qe.path,tone:"info"})}catch(cn){r({title:"Failed to open file",body:cn instanceof Error?cn.message:`Could not open ${Qe.path} in ${Gt.label}.`,tone:"error"})}finally{ae(null)}}}function lt(Qe){xo(o,l,Qe)}function Ue(Qe,gt,Nt){$(Nt),Qut(o,l,Qe,gt)}function mt(Qe){But(o,l,Qe)}function tt(Qe,gt){!Qe.isDirectory||!dj(Qe.path)||(y({parent:Qe,kind:gt}),w(gt==="file"?"untitled.md":"new-folder"))}function dt(Qe){tt(Fe,Qe)}function at(Qe){r2e(Qe)&&(S(Qe),C(Qe.name))}function Pe(Qe){s2e(Qe)&&P(Qe)}function $e(Qe){n2e(Qe)&&we.mutate(Qe)}function ot(Qe,gt){R(!1),Q_(Qe,gt)&&me.mutate({entry:Qe,destinationDirectoryPath:gt})}function ue(Qe,gt,Nt=0){if(R(!1),Qe.length===0){Nt>0&&r({title:"No files imported",body:"Only text, Markdown, and code files can be imported.",tone:"warn"});return}ft.mutate({files:Qe,destinationDirectoryPath:gt,unsupportedCount:Nt})}function Ie(Qe){if(!(!i2e(Qe.dataTransfer)&&!x3(Qe.dataTransfer))){if(Eut(Qe)){R(!1);return}Qe.preventDefault(),Qe.dataTransfer.dropEffect=x3(Qe.dataTransfer)?"copy":"move",R(!0)}}function Ke(Qe){nq(Qe)&&R(!1)}function De(Qe){if(Qe.preventDefault(),R(!1),x3(Qe.dataTransfer)){const{supported:Nt,unsupportedCount:Gt}=a2e(Qe.dataTransfer);ue(Nt,"",Gt);return}const gt=l2e(Qe);!gt||!Q_(gt,"")||ot(gt,"")}return i.jsxs(i.Fragment,{children:[i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx("header",{"data-testid":"workspace-context-header","aria-label":_i("library",s),className:K("workspace-context-header rudder-doc-editor-sidebar-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4",Y&&!ce&&"rudder-doc-editor-sidebar-header--tabs-only",!Y&&ce&&"rudder-doc-editor-sidebar-header--breadcrumb-only",Y&&ce&&"rudder-doc-editor-sidebar-header--tabs-and-breadcrumb"),children:i.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1.5",children:[Oe?i.jsx(Wce,{rootPath:Oe,targets:ke,openingTargetId:qce(xe),onOpenTarget:(Qe,gt,Nt)=>{Be(Qe,gt,Nt)},contentAlign:"start",testId:"org-workspaces-sidebar-launcher",targetTestIdPrefix:"org-workspaces-sidebar-launch-target"}):null,i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>dt("file"),disabled:!Oe,"aria-label":"New file","data-testid":"org-workspaces-new-file-button",children:i.jsx(F7,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"New file"})]}),i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>dt("folder"),disabled:!Oe,"aria-label":"New folder","data-testid":"org-workspaces-new-folder-button",children:i.jsx(j3,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"New folder"})]}),e?i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e,"aria-label":"Hide Library sidebar","data-testid":"org-workspaces-hide-sidebar-button",children:i.jsx(ow,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"Hide Library sidebar"})]}):null]})}),i.jsx("section",{"data-testid":"org-workspaces-files-card","data-active-surface":ft.isPending?"workspace-import":void 0,className:K("flex min-h-0 flex-1 flex-col overflow-hidden border-t border-border transition-colors",T&&"bg-[#2f80ed]/5 ring-1 ring-inset ring-[#2f80ed]/25",ft.isPending&&"active-surface-ring"),onDragOver:Ie,onDragLeave:Ke,onDrop:De,children:i.jsx("div",{ref:g,"data-testid":"org-workspaces-files-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-auto",children:i.jsx("div",{className:"px-2 py-2",children:a?L.isLoading?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Loading files..."}):L.error?i.jsx("div",{className:"px-2 py-3 text-sm text-destructive",children:L.error.message}):(Ce=L.data)!=null&&Ce.rootExists?Q.length===0?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:L.data.message??"This folder is empty."}):i.jsx("ul",{className:"space-y-0.5",children:Q.map(Qe=>{var gt,Nt;return i.jsx(d2e,{orgId:a,entry:Qe,organizationSkills:F,selectedFilePath:f,selectedSkillTreePath:ee,selectedResourcePath:ne,activeEntryPath:U,draggedEntryPath:_,onSelectFile:lt,onSelectSkillFile:Ue,onSelectResource:mt,onFocusEntry:$,onDragStartEntry:D,onDragEndEntry:()=>D(null),onCopyLink:Gt=>void ge(Gt),onCopyAbsolutePath:Gt=>void te(Gt),onOpenEntry:(gt=Pn())!=null&&gt.openPath?Gt=>void G(Gt):void 0,onOpenEntryTarget:(Gt,cn)=>{it(Gt,cn)},onStartCreateEntry:tt,onCopyEntry:$e,onStartRename:at,onStartDelete:Pe,onMoveEntry:ot,onImportFiles:ue,onAddResources:oe,onCopyResourceLocator:Gt=>void Ze(Gt),onOpenResource:Gt=>void Te(Gt),onUnlinkResource:(Gt,cn)=>Se.mutate({project:Gt,attachment:cn}),onOpenSkillAddDialog:()=>E(!0),unlinkingResourceId:((Nt=Se.variables)==null?void 0:Nt.attachment.id)??null,expandedDirectories:fe,workspaceLaunchTargets:ke,openingWorkspaceTargetId:xe,projectResourceGroupsByLibraryPath:se.groupsByLibraryPath},Qe.path)})}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:((kt=L.data)==null?void 0:kt.message)??"The shared Library root is not available on this machine yet."}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Select an organization."})})})})]}),i.jsx(Ps,{open:x!==null,onOpenChange:Qe=>{!Qe&&!ze.isPending&&(y(null),w(""))},children:i.jsxs(zs,{children:[i.jsxs(vi,{children:[i.jsx(ei,{children:(x==null?void 0:x.kind)==="folder"?"New folder":"New file"}),i.jsxs(Si,{children:["Create inside ",(x==null?void 0:x.parent.path)??"this folder","."]})]}),i.jsxs("label",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-muted-foreground",children:"Name"}),i.jsx(Kn,{value:v,onChange:Qe=>w(Qe.target.value),onKeyDown:Qe=>{Qe.key!=="Enter"||!x||!U_(v)||(Qe.preventDefault(),ze.mutate({parent:x.parent,kind:x.kind,name:v}))},autoFocus:!0})]}),i.jsxs(ga,{children:[i.jsx(le,{type:"button",variant:"outline",onClick:()=>{y(null),w("")},disabled:ze.isPending,children:"Cancel"}),i.jsx(le,{type:"button",onClick:()=>{x&&ze.mutate({parent:x.parent,kind:x.kind,name:v})},disabled:!x||!U_(v)||ze.isPending,children:ze.isPending?"Creating...":(x==null?void 0:x.kind)==="folder"?"Create folder":"Create file"})]})]})}),i.jsx(Ps,{open:k!==null,onOpenChange:Qe=>{!Qe&&!ie.isPending&&(S(null),C(""))},children:i.jsxs(zs,{children:[i.jsxs(vi,{children:[i.jsx(ei,{children:"Rename entry"}),i.jsx(Si,{children:"Rename this workspace file or folder without changing its parent folder."})]}),i.jsxs("label",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-muted-foreground",children:"Name"}),i.jsx(Kn,{value:j,onChange:Qe=>C(Qe.target.value),onKeyDown:Qe=>{Qe.key!=="Enter"||!k||(Qe.preventDefault(),ie.mutate({entry:k,name:j}))},autoFocus:!0})]}),i.jsxs(ga,{children:[i.jsx(le,{type:"button",variant:"outline",onClick:()=>{S(null),C("")},disabled:ie.isPending,children:"Cancel"}),i.jsx(le,{type:"button",onClick:()=>{k&&ie.mutate({entry:k,name:j})},disabled:!k||j.trim().length===0||j.trim()===k.name||ie.isPending,children:ie.isPending?"Renaming...":"Rename"})]})]})}),i.jsx(Ps,{open:N!==null,onOpenChange:Qe=>{!Qe&&!Xe.isPending&&P(null)},children:i.jsxs(zs,{children:[i.jsxs(vi,{children:[i.jsx(ei,{children:(N==null?void 0:N.entityType)==="orphaned_agent_workspace"?"Delete deleted agent folder?":"Delete entry"}),i.jsx(Si,{children:(N==null?void 0:N.entityType)==="orphaned_agent_workspace"?`This folder is no longer linked to an active agent. This will permanently delete ${N.path} and everything inside it from the organization Library.`:`This will permanently delete ${(N==null?void 0:N.path)??"this entry"} from the organization Library.`})]}),i.jsxs(ga,{children:[i.jsx(le,{type:"button",variant:"outline",onClick:()=>P(null),disabled:Xe.isPending,children:"Cancel"}),i.jsx(le,{type:"button",variant:"destructive",onClick:()=>{N&&Xe.mutate(N)},disabled:!N||Xe.isPending,children:Xe.isPending?"Deleting...":"Delete"})]})]})}),i.jsx(Lut,{open:M,orgId:a,onOpenChange:E})]})}function b$n(e){const t=fl(e);return/^\/(?:dashboard\/calendar|calendar)(?:\/|$)/.test(t)?"calendar":"dashboard"}function Uut({className:e,compact:t=!1}){const n=br(),r=b$n(n.pathname);return i.jsxs("nav",{"aria-label":"Dashboard section","data-testid":"dashboard-calendar-switcher","data-mode":r,className:K("desktop-window-no-drag relative grid h-9 w-[232px] grid-cols-2 rounded-md border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] p-0.5 text-[13px] shadow-[0_8px_22px_-18px_rgba(15,23,42,0.42)]",e),children:[i.jsx("span",{"aria-hidden":"true",className:K("absolute left-0.5 top-0.5 h-8 w-[calc(50%-2px)] rounded-[calc(var(--radius-sm)-1px)] bg-foreground shadow-[0_8px_20px_-14px_rgba(15,23,42,0.75)] transition-transform duration-200 ease-out motion-reduce:transition-none",r==="calendar"&&"translate-x-full")}),i.jsxs(sn,{to:"/dashboard","aria-current":r==="dashboard"?"page":void 0,className:K("relative z-10 inline-flex min-w-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] font-medium transition-colors",t?"gap-1 px-1.5":"gap-1.5 px-2",r==="dashboard"?"text-background":"text-muted-foreground hover:text-foreground"),children:[t?null:i.jsx(yx,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:"Dashboard"})]}),i.jsxs(sn,{to:"/dashboard/calendar","aria-current":r==="calendar"?"page":void 0,className:K("relative z-10 inline-flex min-w-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] font-medium transition-colors",t?"gap-1 px-1.5":"gap-1.5 px-2",r==="calendar"?"text-background":"text-muted-foreground hover:text-foreground"),children:[t?null:i.jsx(rE,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:"Calendar"})]})]})}function sde({...e}){return i.jsx("nav",{"aria-label":"breadcrumb","data-slot":"breadcrumb",...e})}function ide({className:e,...t}){return i.jsx("ol",{"data-slot":"breadcrumb-list",className:K("text-muted-foreground m-0 flex list-none flex-wrap items-center gap-1.5 p-0 text-sm break-words sm:gap-2.5",e),...t})}function $I({className:e,...t}){return i.jsx("li",{"data-slot":"breadcrumb-item",className:K("inline-flex items-center gap-1.5",e),...t})}function rq({asChild:e,className:t,...n}){const r=e?eue:"a";return i.jsx(r,{"data-slot":"breadcrumb-link",className:K("hover:text-foreground transition-colors",t),...n})}function ade({className:e,...t}){return i.jsx("span",{"data-slot":"breadcrumb-page",role:"link","aria-disabled":"true","aria-current":"page",className:K("text-foreground font-normal",e),...t})}function sq({children:e,className:t,...n}){return i.jsx("li",{"data-slot":"breadcrumb-separator",role:"presentation","aria-hidden":"true",className:K("[&>svg]:size-3.5",t),...n,children:e??i.jsx(bi,{})})}function hc({className:e,...t}){return i.jsx(OEe,{"data-slot":"checkbox",className:K("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:i.jsx(jEe,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:i.jsx(Zs,{className:"size-3.5"})})})}function y$n(e){return e.defaultPrevented||e.key.toLowerCase()!=="f"||!e.metaKey&&!e.ctrlKey?!1:!e.altKey&&!e.shiftKey}function v$n({context:e}){const{slots:t}=Kj({slotTypes:["globalToolbarButton"],orgId:e.orgId}),{launchers:n}=xut({placementZones:["globalToolbarButton"],orgId:e.orgId,enabled:!!e.orgId});return t.length===0&&n.length===0?null:i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i.jsx(eb,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}),i.jsx(K0e,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"})]})}function w$n(e){return e.identifier??e.id.slice(0,8)}const ode=[{value:"title",label:"Title"},{value:"description",label:"Description"},{value:"comment",label:"Comments"}],k$n=new Set(ode.map(e=>e.value));function O$n(e){if(!e)return["title"];const t=e.split(",").map(n=>n.trim()).filter(n=>k$n.has(n));return t.length>0?t:["title"]}function S$n(e){return e.length===1&&e[0]==="title"?null:e.join(",")}function jPe({desktopChrome:e=!1,variant:t="shell"}={}){const{t:n}=is(),{breadcrumbs:r,headerActions:s}=Xi(),{sidebarOpen:a,setSidebarOpen:o,toggleSidebar:l,isMobile:c}=jc(),{selectedOrganizationId:d,selectedOrganization:u}=jr(),{openNewIssue:f,openNewProject:A}=ii(),m=br(),g=Yr(),[x,y]=h.useState(""),[v,w]=h.useState(!1),[k,S]=h.useState(["title"]),j=h.useRef(null),C=h.useRef(null),N=h.useMemo(()=>fl(m.pathname),[m.pathname]),P=h.useMemo(()=>new URLSearchParams(m.search).get("source")??"",[m.search]),M=h.useMemo(()=>/^\/issues(?:\/|$)/.test(N),[N]),E=h.useMemo(()=>/^\/issues\/[^/]+(?:\/|$)/.test(N),[N]),T=h.useMemo(()=>/^\/messenger\/issues\/[^/]+(?:\/|$)/.test(N),[N]),R=h.useMemo(()=>/^\/automations\/[^/]+(?:\/|$)/.test(N),[N]),_=M&&P==="linear",D=h.useMemo(()=>/^\/(?:dashboard|inbox|chat|messenger|issues|agents|library|projects|goals|automations|calendar)(?:\/|$)/.test(N),[N]),U=h.useMemo(()=>/^\/agents\/[^/]+(?:\/|$)/.test(N),[N]),$=h.useMemo(()=>/^\/dashboard\/calendar(?:\/|$)/.test(N)?null:/^\/dashboard(?:\/|$)/.test(N)?"Dashboard":/^\/messenger(?:\/|$)/.test(N)?"Messenger":/^\/inbox(?:\/|$)/.test(N)?"Inbox":/^\/issues(?:\/|$)/.test(N)?P==="linear"?"Linear Issues":E?"Issues":"Issue Tracker":/^\/chat(?:\/|$)/.test(N)?"Chat":/^\/projects(?:\/|$)/.test(N)?"Projects":/^\/agents(?:\/|$)/.test(N)?"Agents":/^\/goals(?:\/|$)/.test(N)?"Goals":/^\/automations(?:\/|$)/.test(N)?"Automations":/^\/calendar(?:\/|$)/.test(N)?"Calendar":null,[P,E,N]),{data:L}=Me({queryKey:V.projects.list(d??"__none__"),queryFn:async()=>(await Mi.list(d)).filter(ze=>!ze.archivedAt),enabled:!!d&&/^\/projects(?:\/|$)/.test(N)}),H=x.trim(),X=E&&!_&&v&&H.length>0,F=M&&!E&&!_&&v,Q=X||F,{data:q=[],isFetching:B}=Me({queryKey:V.issues.search(d??"__none__",H,void 0,k),queryFn:()=>lr.list(d,{q:H,searchFields:k}),enabled:!!d&&X}),ee=h.useMemo(()=>({orgId:d??null,orgPrefix:u?Oc(u):null}),[d,u]),se=i.jsx(v$n,{context:ee}),re=s||se?i.jsxs("div",{"data-testid":"workspace-main-header-actions",className:K("ml-auto flex shrink-0 items-center gap-2",e&&"desktop-window-no-drag"),children:[s?i.jsx("div",{className:"flex shrink-0 items-center gap-2",children:s}):null,se]}):null;h.useEffect(()=>{if(!M)return;const Se=new URLSearchParams(m.search),ze=Se.get("q")??"";y(ze),S(O$n(Se.get("searchFields"))),w(ze.trim().length>0&&E)},[E,M,m.search]),h.useEffect(()=>{if(!M)return;const Se=window.setTimeout(()=>{const ze=new URLSearchParams(m.search),ft=x.trim();(ze.get("q")??"")!==ft&&(ft?ze.set("q",ft):ze.delete("q"),g({pathname:m.pathname,search:ze.toString()?`?${ze.toString()}`:""},{replace:!0}))},250);return()=>window.clearTimeout(Se)},[M,x,m.pathname,m.search,g]);const ne=Se=>{var ze;w(!1),(ze=j.current)==null||ze.blur(),g(`/issues/${Se.identifier??Se.id}`)},Ae=Se=>{S(ze=>{const ft=ze.includes(Se)?ze.length===1?ze:ze.filter(we=>we!==Se):ode.map(we=>we.value).filter(we=>we===Se||ze.includes(we)),ie=new URLSearchParams(m.search),me=S$n(ft);return me?ie.set("searchFields",me):ie.delete("searchFields"),g({pathname:m.pathname,search:ie.toString()?`?${ie.toString()}`:""},{replace:!0}),ft})};h.useEffect(()=>{if(!v)return;const Se=ze=>{var ie;const ft=ze.target;ft instanceof Node&&((ie=C.current)!=null&&ie.contains(ft)||w(!1))};return document.addEventListener("pointerdown",Se),()=>document.removeEventListener("pointerdown",Se)},[v]),h.useEffect(()=>{if(!M)return;const Se=()=>{const ft=j.current;ft&&document.activeElement===ft&&ft.blur()},ze=ft=>{y$n(ft)&&(window.requestAnimationFrame(Se),window.setTimeout(Se,0))};return document.addEventListener("keydown",ze,!0),()=>document.removeEventListener("keydown",ze,!0)},[M]);const Y=c&&i.jsx(le,{variant:"ghost",size:"icon-sm",className:K("mr-2 shrink-0",e&&"desktop-window-no-drag"),onClick:l,"aria-label":n("common.openSidebar"),children:i.jsx(z9t,{className:"h-5 w-5"})}),ce=!c&&t==="card"&&a===!1?i.jsx(le,{variant:"ghost",size:"icon-sm",className:"desktop-window-no-drag shrink-0 text-muted-foreground hover:text-foreground",onClick:()=>o(!0),"aria-label":"Open context sidebar",title:"Open context sidebar",children:i.jsx(ow,{className:"h-4 w-4"})}):null,ke=t==="card"?"workspace-card-header workspace-main-header":"surface-shell",Ne=e?"desktop-chrome desktop-window-drag":"",xe=t==="card"&&/^\/messenger(?:\/|$)/.test(N)&&!T,ae=t==="card"&&U,fe=h.useMemo(()=>/^\/(?:library|resources)(?:\/|$)/.test(N)?"Shared Library for markdown notes, codebases, references, outputs, and reusable context that humans and agents can both work with.":/^\/workspaces(?:\/|$)/.test(N)?"Shared Library files, plans, and skill packages for this organization. Use this page for disk-backed context and editable files.":null,[N]),ve=h.useMemo(()=>/^\/(?:library|resources)(?:\/|$)/.test(N)||/^\/workspaces(?:\/|$)/.test(N)?"About Library":null,[N]);if((xe||ae)&&!ce)return null;if(xe||ae)return i.jsxs("div",{className:K(ke,"flex h-12 shrink-0 items-center px-4 md:px-4",Ne),children:[ce,i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}),re]});if($){const Se=(M&&E||T)&&r.length>1,ze=Se||R&&r.length>1,ft=/^\/projects(?:\/|$)/.test(N),ie=ft&&!/^\/projects\/[^/]+/.test(N),me=/^\/dashboard\/?$/.test(N);return i.jsxs("div",{className:K(ke,"flex shrink-0 items-center gap-3",t==="card"?X?"items-start px-4 py-3 md:px-4":"h-12 px-4 md:px-4":X?"items-start px-4 py-3 md:px-6":"h-14 px-4 md:px-6",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[Y,ce,me?i.jsx(Uut,{}):ze?i.jsx("div",{className:K("min-w-0 flex-1",e&&"desktop-window-no-drag"),children:i.jsx(sde,{className:"min-w-0 overflow-hidden","data-testid":Se?"issue-detail-breadcrumb":"primary-detail-breadcrumb",children:i.jsx(ide,{className:"flex-nowrap overflow-hidden",children:r.map((we,Xe)=>{const ge=Xe===r.length-1;return i.jsxs(h.Fragment,{children:[Xe>0&&i.jsx(sq,{className:"shrink-0"}),i.jsx($I,{className:ge?"min-w-0":"max-w-[180px] shrink-0",children:ge||!we.href?i.jsx(ade,{className:"truncate text-[13px] font-medium text-foreground",title:we.label,children:we.label}):i.jsx(rq,{asChild:!0,children:i.jsx(sn,{to:we.href,state:we.href.startsWith("/issues/")?m.state:void 0,className:"truncate",title:we.label,children:we.label})})})]},`${we.href??we.label}-${Xe}`)})})})}):i.jsx("div",{className:"min-w-0 shrink-0",children:i.jsx("h1",{className:"truncate text-[15px] font-semibold tracking-tight text-foreground",children:$})}),e&&!ze?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,M?i.jsxs("div",{className:K("hidden items-center gap-3 md:flex",e&&"desktop-window-no-drag"),children:[i.jsxs("div",{ref:C,className:"relative w-80",children:[i.jsx(Fl,{className:"pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Kn,{ref:j,value:x,onChange:we=>{y(we.target.value),w(E?we.target.value.trim().length>0:!_)},onClick:()=>w(E?H.length>0:!_),onFocus:()=>w(E?H.length>0:!_),onKeyDown:we=>{we.key==="Escape"&&v&&(we.preventDefault(),w(!1)),we.key==="Enter"&&Q&&q[0]&&(we.preventDefault(),ne(q[0]))},placeholder:_?"Search Linear issues...":"Search issues...",className:"h-9 border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] pl-8 text-sm","aria-label":"Search issues","aria-expanded":Q,"aria-controls":Q?"issue-search-menu":void 0}),X?i.jsx("div",{id:"issue-search-menu","data-testid":"breadcrumb-issue-result-menu",role:"listbox",className:K("relative z-50 mt-2 w-full overflow-hidden rounded-[var(--radius-sm)] border border-[color:var(--border-base)] bg-[color:var(--surface-panel)] py-1 shadow-lg",E?"xl:w-[26rem] xl:-translate-x-[calc(100%+0.5rem)]":null),children:B?i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:"Searching..."}):q.length>0?i.jsx("div",{className:"max-h-32 overflow-y-auto scrollbar-auto-hide",children:q.slice(0,8).map(we=>i.jsxs("button",{type:"button",role:"option",className:"flex w-full min-w-0 items-center gap-2 px-3 py-2 text-left text-sm hover:bg-[color:var(--surface-hover)] focus:bg-[color:var(--surface-hover)] focus:outline-none",onMouseDown:Xe=>Xe.preventDefault(),onClick:()=>ne(we),children:[i.jsx(ni,{status:we.status,className:"h-3.5 w-3.5"}),i.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:w$n(we)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",children:we.title}),i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:we.status})]},we.id))}):i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:"No matching issues."})}):F?i.jsxs("div",{id:"issue-search-menu","data-testid":"breadcrumb-issue-search-scope-menu",className:"absolute left-0 top-full z-[70] mt-2 w-full overflow-hidden rounded-[var(--radius-sm)] border border-[color:var(--border-base)] bg-[color:var(--surface-overlay)] shadow-[0_22px_60px_-34px_rgb(0_0_0/0.72)] dark:border-[color:var(--border-strong)]",children:[i.jsx("div",{className:"border-b border-[color:var(--border-soft)] px-3 py-2",children:i.jsx("div",{className:"text-xs font-medium text-foreground",children:"Search in"})}),i.jsx("div",{className:"space-y-0.5 p-1.5",children:ode.map(we=>i.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded-[calc(var(--radius-sm)-2px)] px-2 py-1.5 text-sm transition-colors hover:bg-[color:var(--surface-active)] focus-within:bg-[color:var(--surface-active)]",children:[i.jsx(hc,{checked:k.includes(we.value),onCheckedChange:()=>Ae(we.value)}),i.jsx("span",{children:we.label})]},we.value))})]}):null]}),_?null:i.jsxs(le,{size:"sm",className:"px-4",onClick:()=>f(),children:[i.jsx(Zr,{className:"mr-1.5 h-3.5 w-3.5"}),"Create Issue"]})]}):null,ft&&(!ie||((L==null?void 0:L.length)??0)>0)?i.jsxs(le,{size:"sm",className:K("hidden px-4 md:inline-flex",e&&"desktop-window-no-drag"),onClick:()=>A(),children:[i.jsx(Zr,{className:"mr-1.5 h-3.5 w-3.5"}),"Add Project"]}):null,re]})}if(r.length===0)return i.jsxs("div",{className:K(ke,"flex h-14 shrink-0 items-center justify-end px-4 md:px-6",t==="card"&&"md:px-5",t==="shell"&&!D&&"border-b panel-divider",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[ce,e?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,re]});if(r.length===1){const Se=r[0],ze=Se.sublabel&&Se.subhref;return i.jsxs("div",{className:K(ke,"flex shrink-0 items-center px-4 md:px-6",t==="card"&&"md:px-5",t==="shell"&&!D&&"border-b panel-divider",ze?"min-h-14 py-2":"h-14",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[Y,ce,i.jsxs("div",{className:"min-w-0 overflow-hidden flex-1",children:[t==="card"?null:i.jsx("div",{className:"text-[10px] font-medium text-muted-foreground/75",children:n("common.workspace")}),i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 pt-0.5",children:[i.jsx("h1",{className:"truncate text-sm font-semibold tracking-wide text-foreground leading-tight",children:Se.label}),fe?i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx("button",{type:"button",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":ve??"About organization context",children:i.jsx(Vfe,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{side:"bottom",sideOffset:8,className:"max-w-[320px] px-3 py-2 text-xs leading-5",children:fe})]}):null]}),ze?i.jsx(sn,{to:Se.subhref,className:"mt-0.5 block truncate text-left text-[11px] leading-snug text-muted-foreground underline-offset-4 hover:text-foreground hover:underline",children:Se.sublabel}):null]}),e?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,re]})}return i.jsxs("div",{className:K(ke,"flex h-14 shrink-0 items-center px-4 md:px-6",t==="card"&&"md:px-5",t==="shell"&&!D&&"border-b panel-divider",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[Y,ce,i.jsx("div",{className:"min-w-0 overflow-hidden flex-1",children:i.jsx(sde,{className:"min-w-0 overflow-hidden",children:i.jsx(ide,{className:"flex-nowrap",children:r.map((Se,ze)=>{const ft=ze===r.length-1;return i.jsxs(h.Fragment,{children:[ze>0&&i.jsx(sq,{}),i.jsx($I,{className:ft?"min-w-0":"shrink-0",children:ft||!Se.href?i.jsx(ade,{className:"truncate",children:Se.label}):i.jsx(rq,{asChild:!0,children:i.jsx(sn,{to:Se.href,children:Se.label})})})]},ze)})})})}),e?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,re]})}var CPe=1,j$n=.9,C$n=.8,N$n=.17,vne=.1,wne=.999,P$n=.9999,I$n=.99,T$n=/[\\\/_+.#"@\[\(\{&]/,_$n=/[\\\/_+.#"@\[\(\{&]/g,M$n=/[\s-]/,Vut=/[\s-]/g;function lde(e,t,n,r,s,a,o){if(a===t.length)return s===e.length?CPe:I$n;var l=`${s},${a}`;if(o[l]!==void 0)return o[l];for(var c=r.charAt(a),d=n.indexOf(c,s),u=0,f,A,m,g;d>=0;)f=lde(e,t,n,r,d+1,a+1,o),f>u&&(d===s?f*=CPe:T$n.test(e.charAt(d-1))?(f*=C$n,m=e.slice(s,d-1).match(_$n),m&&s>0&&(f*=Math.pow(wne,m.length))):M$n.test(e.charAt(d-1))?(f*=j$n,g=e.slice(s,d-1).match(Vut),g&&s>0&&(f*=Math.pow(wne,g.length))):(f*=N$n,s>0&&(f*=Math.pow(wne,d-s))),e.charAt(d)!==t.charAt(a)&&(f*=P$n)),(f<vne&&n.charAt(d-1)===r.charAt(a+1)||r.charAt(a+1)===r.charAt(a)&&n.charAt(d-1)!==r.charAt(a))&&(A=lde(e,t,n,r,d+1,a+2,o),A*vne>f&&(f=A*vne)),f>u&&(u=f),d=n.indexOf(c,d+1);return o[l]=u,u}function NPe(e){return e.toLowerCase().replace(Vut," ")}function E$n(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,lde(e,t,NPe(e),NPe(t),0,0,{})}var D$n=Symbol.for("react.lazy"),iq=Bq[" use ".trim().toString()];function R$n(e){return typeof e=="object"&&e!==null&&"then"in e}function qut(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===D$n&&"_payload"in e&&R$n(e._payload)}function L$n(e){const t=z$n(e),n=h.forwardRef((r,s)=>{let{children:a,...o}=r;qut(a)&&typeof iq=="function"&&(a=iq(a._payload));const l=h.Children.toArray(a),c=l.find(F$n);if(c){const d=c.props.children,u=l.map(f=>f===c?h.Children.count(d)>1?h.Children.only(null):h.isValidElement(d)?d.props.children:null:f);return i.jsx(t,{...o,ref:s,children:h.isValidElement(d)?h.cloneElement(d,void 0,u):null})}return i.jsx(t,{...o,ref:s,children:a})});return n.displayName=`${e}.Slot`,n}function z$n(e){const t=h.forwardRef((n,r)=>{let{children:s,...a}=n;if(qut(s)&&typeof iq=="function"&&(s=iq(s._payload)),h.isValidElement(s)){const o=Q$n(s),l=B$n(a,s.props);return s.type!==h.Fragment&&(l.ref=r?Sx(r,o):o),h.cloneElement(s,l)}return h.Children.count(s)>1?h.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var $$n=Symbol("radix.slottable");function F$n(e){return h.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$$n}function B$n(e,t){const n={...t};for(const r in t){const s=e[r],a=t[r];/^on[A-Z]/.test(r)?s&&a?n[r]=(...l)=>{const c=a(...l);return s(...l),c}:s&&(n[r]=s):r==="style"?n[r]={...s,...a}:r==="className"&&(n[r]=[s,a].filter(Boolean).join(" "))}return{...e,...n}}function Q$n(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var U$n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Cw=U$n.reduce((e,t)=>{const n=L$n(`Primitive.${t}`),r=h.forwardRef((s,a)=>{const{asChild:o,...l}=s,c=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(c,{...l,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),IN='[cmdk-group=""]',kne='[cmdk-group-items=""]',V$n='[cmdk-group-heading=""]',Kut='[cmdk-item=""]',PPe=`${Kut}:not([aria-disabled="true"])`,cde="cmdk-item-select",l7="data-value",q$n=(e,t,n)=>E$n(e,t,n),Wut=h.createContext(void 0),ED=()=>h.useContext(Wut),Zut=h.createContext(void 0),f2e=()=>h.useContext(Zut),Hut=h.createContext(void 0),Xut=h.forwardRef((e,t)=>{let n=c7(()=>{var q,B;return{search:"",value:(B=(q=e.value)!=null?q:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=c7(()=>new Set),s=c7(()=>new Map),a=c7(()=>new Map),o=c7(()=>new Set),l=Gut(e),{label:c,children:d,value:u,onValueChange:f,filter:A,shouldFilter:m,loop:g,disablePointerSelection:x=!1,vimBindings:y=!0,...v}=e,w=vc(),k=vc(),S=vc(),j=h.useRef(null),C=nFn();L6(()=>{if(u!==void 0){let q=u.trim();n.current.value=q,N.emit()}},[u]),L6(()=>{C(6,_)},[]);let N=h.useMemo(()=>({subscribe:q=>(o.current.add(q),()=>o.current.delete(q)),snapshot:()=>n.current,setState:(q,B,ee)=>{var se,re,ne,Ae;if(!Object.is(n.current[q],B)){if(n.current[q]=B,q==="search")R(),E(),C(1,T);else if(q==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Y=document.getElementById(S);Y?Y.focus():(se=document.getElementById(w))==null||se.focus()}if(C(7,()=>{var Y;n.current.selectedItemId=(Y=D())==null?void 0:Y.id,N.emit()}),ee||C(5,_),((re=l.current)==null?void 0:re.value)!==void 0){let Y=B??"";(Ae=(ne=l.current).onValueChange)==null||Ae.call(ne,Y);return}}N.emit()}},emit:()=>{o.current.forEach(q=>q())}}),[]),P=h.useMemo(()=>({value:(q,B,ee)=>{var se;B!==((se=a.current.get(q))==null?void 0:se.value)&&(a.current.set(q,{value:B,keywords:ee}),n.current.filtered.items.set(q,M(B,ee)),C(2,()=>{E(),N.emit()}))},item:(q,B)=>(r.current.add(q),B&&(s.current.has(B)?s.current.get(B).add(q):s.current.set(B,new Set([q]))),C(3,()=>{R(),E(),n.current.value||T(),N.emit()}),()=>{a.current.delete(q),r.current.delete(q),n.current.filtered.items.delete(q);let ee=D();C(4,()=>{R(),(ee==null?void 0:ee.getAttribute("id"))===q&&T(),N.emit()})}),group:q=>(s.current.has(q)||s.current.set(q,new Set),()=>{a.current.delete(q),s.current.delete(q)}),filter:()=>l.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>l.current.disablePointerSelection,listId:w,inputId:S,labelId:k,listInnerRef:j}),[]);function M(q,B){var ee,se;let re=(se=(ee=l.current)==null?void 0:ee.filter)!=null?se:q$n;return q?re(q,n.current.search,B):0}function E(){if(!n.current.search||l.current.shouldFilter===!1)return;let q=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(se=>{let re=s.current.get(se),ne=0;re.forEach(Ae=>{let Y=q.get(Ae);ne=Math.max(Y,ne)}),B.push([se,ne])});let ee=j.current;U().sort((se,re)=>{var ne,Ae;let Y=se.getAttribute("id"),ce=re.getAttribute("id");return((ne=q.get(ce))!=null?ne:0)-((Ae=q.get(Y))!=null?Ae:0)}).forEach(se=>{let re=se.closest(kne);re?re.appendChild(se.parentElement===re?se:se.closest(`${kne} > *`)):ee.appendChild(se.parentElement===ee?se:se.closest(`${kne} > *`))}),B.sort((se,re)=>re[1]-se[1]).forEach(se=>{var re;let ne=(re=j.current)==null?void 0:re.querySelector(`${IN}[${l7}="${encodeURIComponent(se[0])}"]`);ne==null||ne.parentElement.appendChild(ne)})}function T(){let q=U().find(ee=>ee.getAttribute("aria-disabled")!=="true"),B=q==null?void 0:q.getAttribute(l7);N.setState("value",B||void 0)}function R(){var q,B,ee,se;if(!n.current.search||l.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let ne of r.current){let Ae=(B=(q=a.current.get(ne))==null?void 0:q.value)!=null?B:"",Y=(se=(ee=a.current.get(ne))==null?void 0:ee.keywords)!=null?se:[],ce=M(Ae,Y);n.current.filtered.items.set(ne,ce),ce>0&&re++}for(let[ne,Ae]of s.current)for(let Y of Ae)if(n.current.filtered.items.get(Y)>0){n.current.filtered.groups.add(ne);break}n.current.filtered.count=re}function _(){var q,B,ee;let se=D();se&&(((q=se.parentElement)==null?void 0:q.firstChild)===se&&((ee=(B=se.closest(IN))==null?void 0:B.querySelector(V$n))==null||ee.scrollIntoView({block:"nearest"})),se.scrollIntoView({block:"nearest"}))}function D(){var q;return(q=j.current)==null?void 0:q.querySelector(`${Kut}[aria-selected="true"]`)}function U(){var q;return Array.from(((q=j.current)==null?void 0:q.querySelectorAll(PPe))||[])}function $(q){let B=U()[q];B&&N.setState("value",B.getAttribute(l7))}function L(q){var B;let ee=D(),se=U(),re=se.findIndex(Ae=>Ae===ee),ne=se[re+q];(B=l.current)!=null&&B.loop&&(ne=re+q<0?se[se.length-1]:re+q===se.length?se[0]:se[re+q]),ne&&N.setState("value",ne.getAttribute(l7))}function H(q){let B=D(),ee=B==null?void 0:B.closest(IN),se;for(;ee&&!se;)ee=q>0?eFn(ee,IN):tFn(ee,IN),se=ee==null?void 0:ee.querySelector(PPe);se?N.setState("value",se.getAttribute(l7)):L(q)}let X=()=>$(U().length-1),F=q=>{q.preventDefault(),q.metaKey?X():q.altKey?H(1):L(1)},Q=q=>{q.preventDefault(),q.metaKey?$(0):q.altKey?H(-1):L(-1)};return h.createElement(Cw.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:q=>{var B;(B=v.onKeyDown)==null||B.call(v,q);let ee=q.nativeEvent.isComposing||q.keyCode===229;if(!(q.defaultPrevented||ee))switch(q.key){case"n":case"j":{y&&q.ctrlKey&&F(q);break}case"ArrowDown":{F(q);break}case"p":case"k":{y&&q.ctrlKey&&Q(q);break}case"ArrowUp":{Q(q);break}case"Home":{q.preventDefault(),$(0);break}case"End":{q.preventDefault(),X();break}case"Enter":{q.preventDefault();let se=D();if(se){let re=new Event(cde);se.dispatchEvent(re)}}}}},h.createElement("label",{"cmdk-label":"",htmlFor:P.inputId,id:P.labelId,style:sFn},c),TH(e,q=>h.createElement(Zut.Provider,{value:N},h.createElement(Wut.Provider,{value:P},q))))}),K$n=h.forwardRef((e,t)=>{var n,r;let s=vc(),a=h.useRef(null),o=h.useContext(Hut),l=ED(),c=Gut(e),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:o==null?void 0:o.forceMount;L6(()=>{if(!d)return l.item(s,o==null?void 0:o.id)},[d]);let u=Yut(s,a,[e.value,e.children,a],e.keywords),f=f2e(),A=H3(C=>C.value&&C.value===u.current),m=H3(C=>d||l.filter()===!1?!0:C.search?C.filtered.items.get(s)>0:!0);h.useEffect(()=>{let C=a.current;if(!(!C||e.disabled))return C.addEventListener(cde,g),()=>C.removeEventListener(cde,g)},[m,e.onSelect,e.disabled]);function g(){var C,N;x(),(N=(C=c.current).onSelect)==null||N.call(C,u.current)}function x(){f.setState("value",u.current,!0)}if(!m)return null;let{disabled:y,value:v,onSelect:w,forceMount:k,keywords:S,...j}=e;return h.createElement(Cw.div,{ref:Sx(a,t),...j,id:s,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!A,"data-disabled":!!y,"data-selected":!!A,onPointerMove:y||l.getDisablePointerSelection()?void 0:x,onClick:y?void 0:g},e.children)}),W$n=h.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...a}=e,o=vc(),l=h.useRef(null),c=h.useRef(null),d=vc(),u=ED(),f=H3(m=>s||u.filter()===!1?!0:m.search?m.filtered.groups.has(o):!0);L6(()=>u.group(o),[]),Yut(o,l,[e.value,e.heading,c]);let A=h.useMemo(()=>({id:o,forceMount:s}),[s]);return h.createElement(Cw.div,{ref:Sx(l,t),...a,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&h.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),TH(e,m=>h.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},h.createElement(Hut.Provider,{value:A},m))))}),Z$n=h.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=h.useRef(null),a=H3(o=>!o.search);return!n&&!a?null:h.createElement(Cw.div,{ref:Sx(s,t),...r,"cmdk-separator":"",role:"separator"})}),H$n=h.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,a=f2e(),o=H3(d=>d.search),l=H3(d=>d.selectedItemId),c=ED();return h.useEffect(()=>{e.value!=null&&a.setState("search",e.value)},[e.value]),h.createElement(Cw.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":l,id:c.inputId,type:"text",value:s?e.value:o,onChange:d=>{s||a.setState("search",d.target.value),n==null||n(d.target.value)}})}),X$n=h.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,a=h.useRef(null),o=h.useRef(null),l=H3(d=>d.selectedItemId),c=ED();return h.useEffect(()=>{if(o.current&&a.current){let d=o.current,u=a.current,f,A=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=d.offsetHeight;u.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return A.observe(d),()=>{cancelAnimationFrame(f),A.unobserve(d)}}},[]),h.createElement(Cw.div,{ref:Sx(a,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":l,"aria-label":r,id:c.listId},TH(e,d=>h.createElement("div",{ref:Sx(o,c.listInnerRef),"cmdk-list-sizer":""},d)))}),G$n=h.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:a,container:o,...l}=e;return h.createElement(_M,{open:n,onOpenChange:r},h.createElement(MM,{container:o},h.createElement(EM,{"cmdk-overlay":"",className:s}),h.createElement(mj,{"aria-label":e.label,"cmdk-dialog":"",className:a},h.createElement(Xut,{ref:t,...l}))))}),Y$n=h.forwardRef((e,t)=>H3(n=>n.filtered.count===0)?h.createElement(Cw.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),J$n=h.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...a}=e;return h.createElement(Cw.div,{ref:t,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},TH(e,o=>h.createElement("div",{"aria-hidden":!0},o)))}),u8=Object.assign(Xut,{List:X$n,Item:K$n,Input:H$n,Group:W$n,Separator:Z$n,Dialog:G$n,Empty:Y$n,Loading:J$n});function eFn(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function tFn(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Gut(e){let t=h.useRef(e);return L6(()=>{t.current=e}),t}var L6=typeof window>"u"?h.useEffect:h.useLayoutEffect;function c7(e){let t=h.useRef();return t.current===void 0&&(t.current=e()),t}function H3(e){let t=f2e(),n=()=>e(t.snapshot());return h.useSyncExternalStore(t.subscribe,n,n)}function Yut(e,t,n,r=[]){let s=h.useRef(),a=ED();return L6(()=>{var o;let l=(()=>{var d;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(d=u.current.textContent)==null?void 0:d.trim():s.current}})(),c=r.map(d=>d.trim());a.value(e,l,c),(o=t.current)==null||o.setAttribute(l7,l),s.current=l}),s}var nFn=()=>{let[e,t]=h.useState(),n=c7(()=>new Map);return L6(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function rFn(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function TH({asChild:e,children:t},n){return e&&h.isValidElement(t)?h.cloneElement(rFn(t),{ref:t.ref},n(t.props.children)):n(t)}var sFn={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function Jut({className:e,...t}){return i.jsx(u8,{"data-slot":"command",className:K("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",e),...t})}function iFn({title:e="Command Palette",description:t="Search for a command to run...",children:n,className:r,contentStyle:s,showCloseButton:a=!0,...o}){return i.jsxs(Ps,{...o,children:[i.jsxs(vi,{className:"sr-only",children:[i.jsx(ei,{children:e}),i.jsx(Si,{children:t})]}),i.jsxs(zs,{className:K("overflow-hidden p-0",r),style:s,showCloseButton:!1,children:[i.jsx(Jut,{className:"[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:n}),a&&i.jsxs(pj,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-0 right-2 flex h-12 items-center rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[i.jsx(Is,{}),i.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function eft({className:e,inputPrefix:t,...n}){return i.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[i.jsx(Fl,{className:"size-4 shrink-0 opacity-50"}),t,i.jsx(u8.Input,{"data-slot":"command-input",className:K("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...n})]})}function tft({className:e,...t}){return i.jsx(u8.List,{"data-slot":"command-list",className:K("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function nft({...e}){return i.jsx(u8.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...e})}function vm({className:e,...t}){return i.jsx(u8.Group,{"data-slot":"command-group",className:K("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...t})}function qy({className:e,...t}){return i.jsx(u8.Separator,{"data-slot":"command-separator",className:K("bg-border -mx-1 h-px",e),...t})}function bl({className:e,...t}){return i.jsx(u8.Item,{"data-slot":"command-item",className:K("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}const A2e=[{scope:"issue",label:"Issues",aliases:["issue","issues"]},{scope:"library",label:"Library",aliases:["library","docs","doc"]},{scope:"chat",label:"Chats",aliases:["chat","chats"]},{scope:"agent",label:"Agents",aliases:["agent","agents"]},{scope:"project",label:"Projects",aliases:["project","projects"]},{scope:"skill",label:"Skills",aliases:["skill","skills"]}],rft=new Map(A2e.flatMap(e=>e.aliases.map(t=>[t,e.scope])));function IPe(e){return A2e.find(t=>t.scope===e)??null}function sft(e){return rft.get(e.trim().toLowerCase())??null}function aFn(e){var n;const t=e.trim().toLowerCase();return!t||/\s/.test(t)||rft.has(t)?null:((n=A2e.find(r=>r.aliases.some(s=>s.startsWith(t))))==null?void 0:n.scope)??null}function oFn(e){return/\s$/.test(e)?sft(e):null}function lFn(e,t){return e!==" "&&e!=="Tab"&&e!=="Enter"?null:sft(t)}const TPe=["title","description","comment"],TN=2,Sk=20,cFn=250,dFn=20;function t$(e,t){const n=e.trim().toLowerCase();return n?t.some(r=>r==null?void 0:r.toLowerCase().includes(n)):!0}function uFn(e){return`/library?${e.isDirectory?"directory":"path"}=${encodeURIComponent(e.path)}`}function fFn(){const[e,t]=h.useState(!1),[n,r]=h.useState(null),[s,a]=h.useState(""),[o,l]=h.useState("shortcut"),[c,d]=h.useState(!1),[u,f]=h.useState(!1),[A,m]=h.useState(null),[g,x]=h.useState(null),y=h.useRef(0),v=Yr(),{selectedOrganizationId:w}=jr(),{isMobile:k,setSidebarOpen:S}=jc(),j=s.trim(),[C,N]=h.useState(""),P=Me({queryKey:V.instance.shortcutSettings,queryFn:()=>Ha.getShortcuts(),retry:!1}),M=P.data===void 0?P.isError?null:void 0:P.data,T=(Me({queryKey:V.organizations.intelligenceProfiles(w??"__none__"),queryFn:()=>_n.listIntelligenceProfiles(w),enabled:!!w&&e}).data??[]).some(Ue=>(Ue==null?void 0:Ue.purpose)==="reasoning"&&Ue.status==="configured");h.useEffect(()=>{function Ue(mt){mt.defaultPrevented||mt.isComposing||RVe(mt.target)||qk(mt,"commandPalette.open",M)&&(mt.preventDefault(),l("shortcut"),t(!0),k&&S(!1))}return document.addEventListener("keydown",Ue),()=>document.removeEventListener("keydown",Ue)},[k,S,M]),h.useEffect(()=>{function Ue(mt){var dt;const tt=mt instanceof CustomEvent&&((dt=mt.detail)==null?void 0:dt.source)==="primary-rail"?"primary-rail":"shortcut";l(tt),t(!0),k&&S(!1)}return document.addEventListener("rudder:open-command-palette",Ue),()=>document.removeEventListener("rudder:open-command-palette",Ue)},[k,S]),h.useEffect(()=>{e||(r(null),a(""),N(""),d(!1),f(!1),m(null),x(null))},[e]),h.useEffect(()=>{y.current+=1,d(!1),f(!1),m(null),x(null)},[j]),h.useEffect(()=>{if(!e||j.length<TN){N("");return}const Ue=window.setTimeout(()=>{N(j)},cFn);return()=>window.clearTimeout(Ue)},[e,j]);const R=C.length>=TN?C:"",_=n?IPe(n):null,D=n?null:aFn(s),U=D?IPe(D):null,$=Me({queryKey:["issues",w,"command-palette","list",Sk],queryFn:()=>lr.list(w,{limit:Sk}),enabled:!!w&&e&&(n===null||n==="issue")}),L=$.data??[],H=Me({queryKey:["issues",w,"command-palette","search",R,TPe.join(","),Sk],queryFn:()=>lr.list(w,{q:R,searchFields:TPe,limit:Sk}),enabled:!!w&&e&&R.length>0&&(n===null||n==="issue")}),X=H.data??[],F=Me({queryKey:["chats",w,"command-palette","search","all",R,Sk],queryFn:()=>Xn.list(w,"all",{q:R,limit:Sk}),enabled:!!w&&e&&R.length>0&&(n===null||n==="chat")}),Q=F.data??[],q=Me({queryKey:V.organizations.workspaceMentionFiles(w,j),queryFn:()=>_n.listWorkspaceMentionFiles(w,{query:j,limit:dFn}),enabled:!!w&&e&&n==="library"&&j.length>0}),B=q.data??{entries:[]},ee=Me({queryKey:V.agents.list(w),queryFn:()=>Nn.list(w),enabled:!!w&&e}),se=ee.data??[],re=h.useMemo(()=>new Map(se.map(Ue=>[Ue.id,Ue])),[se]),ne=Me({queryKey:V.projects.list(w),queryFn:()=>Mi.list(w),enabled:!!w&&e}),Ae=ne.data??[],Y=h.useMemo(()=>Ae.filter(Ue=>!Ue.archivedAt),[Ae]),ce=Me({queryKey:V.organizationSkills.list(w),queryFn:()=>nf.list(w),enabled:!!w&&e&&(n===null||n==="skill")}),Oe=ce.data??[];function Fe(Ue){t(!1),v(Ue)}function ke(Ue){r(Ue),a("")}function Ne(){r(null),a("")}function xe(){if(!w||j.length<TN)return;const Ue=y.current+1;y.current=Ue,d(!0),f(!0),m(null),x(null),_n.aiSearch(w,{query:j,scope:n??void 0}).then(mt=>{y.current===Ue&&x(mt)}).catch(mt=>{y.current===Ue&&m(mt instanceof Error?mt.message:"AI Search failed")}).finally(()=>{y.current===Ue&&f(!1)})}function ae(Ue){if(!n){const mt=oFn(Ue);if(mt){ke(mt);return}}a(Ue)}function fe(Ue){if(!n){const mt=lFn(Ue.key,s);if(mt){Ue.preventDefault(),ke(mt);return}}n&&Ue.key==="Backspace"&&s.length===0&&(Ue.preventDefault(),Ne())}const ve=h.useMemo(()=>n!==null&&n!=="issue"?[]:R.length>0?X:j.length>0?L.filter(Ue=>t$(j,[Ue.identifier,Ue.title])):L,[L,X,R,j,n]),Se=n===null||n==="chat"?Q:[],ze=n==="library"&&j.length>0?B.entries:[],ft=h.useMemo(()=>se.filter(Ue=>t$(j,[Ue.name,Ue.role,Ue.title,Ue.urlKey])),[se,j]),ie=n===null||n==="agent"?ft:[],me=h.useMemo(()=>Y.filter(Ue=>t$(j,[Ue.name,Ue.description,Ue.urlKey,Ue.status])),[Y,j]),we=n===null||n==="project"?me:[],Xe=h.useMemo(()=>Oe.filter(Ue=>t$(j,[Ue.name,Ue.description,Ue.key,Ue.slug,Ue.sourceLabel,Ue.sourcePath,Ue.sourceLocator])),[j,Oe]),ge=n===null||n==="skill"?Xe:[],te=_?`Search ${_.label}...`:"Search issues, chats, agents, projects, skills, library...",G=_?`No ${_.label.toLowerCase()} results found.`:"No results found.",oe=j.length>0?H:$,Ze=!!(w&&e)&&((n===null||n==="issue")&&oe.isFetching&&oe.data===void 0||(n===null||n==="chat")&&j.length>0&&F.isFetching&&F.data===void 0||n==="library"&&j.length>0&&q.isFetching&&q.data===void 0||(n===null||n==="agent")&&ee.isFetching&&ee.data===void 0||(n===null||n==="project")&&ne.isFetching&&ne.data===void 0||(n===null||n==="skill")&&ce.isFetching&&ce.data===void 0),Te=!!(w&&e)&&((n===null||n==="issue")&&oe.isFetching||(n===null||n==="chat")&&j.length>0&&F.isFetching||n==="library"&&j.length>0&&q.isFetching||(n===null||n==="agent")&&ee.isFetching||(n===null||n==="project")&&ne.isFetching||(n===null||n==="skill")&&ce.isFetching),Be=ve.length>0||Se.length>0||ze.length>0||ie.length>0||we.length>0||ge.length>0,it=n!==null&&n!=="issue"&&n!=="chat"?!0:j.length<TN||R===j,lt=T&&j.length>=TN&&it&&!Te&&!Be&&!c;return i.jsxs(iFn,{open:e,onOpenChange:Ue=>{t(Ue),Ue&&k&&S(!1)},contentStyle:k?void 0:{left:"50vw",top:"50vh"},className:["command-palette-content glass-popover command-palette-glass sm:max-w-2xl",o==="primary-rail"?"command-palette-content--from-rail":null,Ze?"command-palette-content--searching":null].filter(Boolean).join(" "),children:[i.jsx(eft,{placeholder:te,value:s,onValueChange:ae,onKeyDown:fe,inputPrefix:_?i.jsxs("span",{className:"inline-flex h-6 shrink-0 items-center gap-1 rounded-sm border bg-muted px-2 text-xs font-medium text-muted-foreground",children:[_.label,i.jsx("button",{type:"button","aria-label":`Clear ${_.label} search scope`,className:"-mr-1 inline-flex h-4 w-4 items-center justify-center rounded-sm hover:bg-background hover:text-foreground",onMouseDown:Ue=>Ue.preventDefault(),onClick:Ne,children:i.jsx(Is,{className:"h-3 w-3"})})]}):void 0,className:"pr-8"}),i.jsxs(tft,{children:[!(n==="library"&&j.length===0)&&i.jsx(nft,{children:Ze?i.jsxs("span",{className:"inline-flex items-center justify-center gap-2 text-muted-foreground",children:[i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}),"Searching..."]}):u?i.jsxs("span",{className:"inline-flex items-center justify-center gap-2 text-muted-foreground",children:[i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}),"Searching..."]}):A?i.jsx("span",{className:"text-destructive",children:A}):c&&(g==null?void 0:g.results.length)===0?"Found 0 results":G}),lt&&i.jsxs(bl,{value:`ai search ${j}`,onSelect:xe,children:[i.jsx(Hh,{className:"mr-2 h-4 w-4 text-amber-500"}),i.jsx("span",{children:"AI Search"})]}),c&&(g||A)&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsxs("div",{className:"flex items-center justify-between gap-3 px-2 py-2 text-sm",children:[i.jsx("span",{className:"font-medium",children:"AI Search"}),g&&i.jsxs("span",{className:"text-muted-foreground",children:["Found ",g.results.length," result",g.results.length===1?"":"s"]})]}),i.jsxs(vm,{children:[((g==null?void 0:g.results)??[]).map(Ue=>i.jsxs(bl,{value:`${j} ${Ue.title} ${Ue.preview??""} ${Ue.reason??""}`,onSelect:()=>Fe(Ue.href),children:[i.jsx(Hh,{className:"mr-2 h-4 w-4 text-amber-500"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.title}),(Ue.reason??Ue.preview)&&i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:Ue.reason??Ue.preview})]}),i.jsx("span",{className:"ml-2 hidden text-xs capitalize text-muted-foreground sm:inline",children:Ue.kind.replace("_"," ")})]},Ue.key)),A&&i.jsxs(bl,{value:`retry ai search ${j}`,onSelect:xe,children:[i.jsx(Hh,{className:"mr-2 h-4 w-4"}),"Try AI Search again"]})]})]}),U&&i.jsx(vm,{heading:"Scope",children:i.jsxs(bl,{value:`${s} search in ${U.label}`,onSelect:()=>ke(U.scope),children:[i.jsx("span",{className:"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border text-[10px] text-muted-foreground",children:"/"}),i.jsxs("span",{className:"flex-1",children:["Search in ",U.label]})]})}),n===null&&i.jsxs(vm,{heading:"Pages",children:[i.jsxs(bl,{value:"dashboard",onSelect:()=>Fe("/dashboard"),children:[i.jsx(yx,{className:"mr-2 h-4 w-4"}),"Dashboard"]}),i.jsxs(bl,{value:"messenger chat conversations",onSelect:()=>Fe("/messenger"),children:[i.jsx(pa,{className:"mr-2 h-4 w-4"}),"Messenger"]}),i.jsxs(bl,{value:"issues",onSelect:()=>Fe("/issues"),children:[i.jsx(qh,{className:"mr-2 h-4 w-4"}),"Issues"]}),i.jsxs(bl,{value:"projects",onSelect:()=>Fe("/projects"),children:[i.jsx(e6,{className:"mr-2 h-4 w-4"}),"Projects"]}),i.jsxs(bl,{value:"goals targets",onSelect:()=>Fe("/goals"),children:[i.jsx(ud,{className:"mr-2 h-4 w-4"}),"Goals"]}),i.jsxs(bl,{value:"heartbeats activity runs",onSelect:()=>Fe("/heartbeats"),children:[i.jsx(Cx,{className:"mr-2 h-4 w-4"}),"Heartbeats"]}),i.jsxs(bl,{value:"agents",onSelect:()=>Fe("/agents"),children:[i.jsx(Ul,{className:"mr-2 h-4 w-4"}),"Agents"]}),i.jsxs(bl,{value:"skills",onSelect:()=>Fe(MAe),children:[i.jsx(wc,{className:"mr-2 h-4 w-4 text-[#2f80ed]"}),"Skills"]}),i.jsxs(bl,{value:"costs billing spend",onSelect:()=>Fe("/costs"),children:[i.jsx(Nx,{className:"mr-2 h-4 w-4"}),"Costs"]}),i.jsxs(bl,{value:"activity history",onSelect:()=>Fe("/activity"),children:[i.jsx(lT,{className:"mr-2 h-4 w-4"}),"Activity"]})]}),n==="library"&&j.length===0&&i.jsx(vm,{heading:"Library",children:i.jsx("div",{className:"px-2 py-6 text-center text-sm text-muted-foreground",children:"Type to search Library"})}),ve.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Issues",children:ve.slice(0,10).map(Ue=>i.jsxs(bl,{value:j.length>0?`${j} ${Ue.identifier??""} ${Ue.title}`:`${Ue.identifier??""} ${Ue.title}`,onSelect:()=>Fe(`/issues/${Ue.identifier??Ue.id}`),children:[i.jsx(ni,{status:Ue.status,className:"mr-2"}),i.jsx("span",{className:"text-muted-foreground mr-2 font-mono text-xs",children:Ue.identifier??Ue.id.slice(0,8)}),i.jsx("span",{className:"flex-1 truncate",children:Ue.title}),Ue.assigneeAgentId&&(()=>{const mt=re.get(Ue.assigneeAgentId);return mt?i.jsx(vu,{name:mt.name,icon:mt.icon,role:mt.role,size:"sm",className:"ml-2 hidden sm:inline-flex"}):null})()]},Ue.id))})]}),j.length>0&&Se.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Chats",children:Se.slice(0,10).map(Ue=>{const mt=Ue.searchPreview??Ue.latestReplyPreview??Ue.summary,tt=Bi(Ue.lastMessageAt??Ue.updatedAt,{compactDate:!0});return i.jsxs(bl,{value:`${j} ${Ue.title} ${mt??""}`,onSelect:()=>Fe(`/messenger/chat/${Ue.id}`),children:[i.jsx(Yfe,{className:"mr-2 h-4 w-4"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.title}),mt&&i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:mt})]}),i.jsx("span",{className:"ml-2 hidden text-xs text-muted-foreground sm:inline",children:tt})]},Ue.id)})})]}),ze.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Library",children:ze.slice(0,10).map(Ue=>{const mt=Ue.isDirectory?wo:Fi;return i.jsxs(bl,{value:`${j} ${Ue.displayLabel??Ue.name} ${Ue.path}`,onSelect:()=>Fe(uFn(Ue)),children:[i.jsx(mt,{className:"mr-2 h-4 w-4"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.displayLabel??Ue.name}),i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:Ue.path})]}),i.jsx("span",{className:"ml-2 hidden text-xs text-muted-foreground sm:inline",children:Ue.isDirectory?"Folder":"File"})]},`${Ue.isDirectory?"directory":"file"}:${Ue.path}`)})})]}),ie.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Agents",children:ie.slice(0,10).map(Ue=>i.jsxs(bl,{value:`${Ue.name} ${Ue.role} ${Ue.title??""} ${Ue.urlKey}`,onSelect:()=>Fe(BA(Ue)),children:[i.jsx(Ul,{className:"mr-2 h-4 w-4"}),Ue.name,i.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:Ue.role})]},Ue.id))})]}),we.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Projects",children:we.slice(0,10).map(Ue=>i.jsxs(bl,{value:`${Ue.name} ${Ue.description??""} ${Ue.urlKey} ${Ue.status}`,onSelect:()=>Fe(nT(Ue)),children:[i.jsx(uo,{color:Ue.color,icon:Ue.icon,size:"sm",className:"mr-2"}),Ue.name]},Ue.id))})]}),ge.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Skills",children:ge.slice(0,10).map(Ue=>i.jsxs(bl,{value:`${Ue.name} ${Ue.description??""} ${Ue.key} ${Ue.slug} ${Ue.sourceLabel??""}`,onSelect:()=>Fe(Bj(Ue.id)),children:[i.jsx(wc,{className:"mr-2 h-4 w-4 text-[#2f80ed]"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.name}),Ue.description?i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:Ue.description}):null]}),i.jsx("span",{className:"ml-2 hidden text-xs text-muted-foreground sm:inline",children:Ue.sourceLabel??Ue.sourceBadge})]},Ue.id))})]})]})]})}function AFn(e){if(!e)return null;const t=new Date(e).getTime();if(Number.isNaN(t))return null;const n=Date.now()-t;if(n<6e4)return"just now";const r=Math.round(n/6e4);if(r<60)return`${r}m ago`;const s=Math.round(r/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}function hFn(e){return e.envFileChanged&&e.reason==="backend_changes_and_pending_migrations"?"Environment configuration changed and migrations are pending.":e.envFileChanged?"Environment configuration changed since this server booted.":e.reason==="backend_changes_and_pending_migrations"?"Backend files changed and migrations are pending.":e.reason==="pending_migrations"?"Pending migrations need a fresh boot.":"Backend files changed since this server booted."}function mFn(e,t){const n=AFn(e.lastChangedAt),r=[],s=Pn();if(n&&r.push(`Updated ${n}.`),r.push("Restart pnpm dev after the active work is safe to interrupt."),e.changedPathsSample.length>0){const a=e.changedPathsSample.slice(0,2).join(", "),o=e.changedPathCount>2?` +${e.changedPathCount-2} more`:"";r.push(`Changed: ${a}${o}.`)}if(e.pendingMigrations.length>0){const a=e.pendingMigrations.slice(0,2).join(", "),o=e.pendingMigrations.length>2?` +${e.pendingMigrations.length-2} more`:"";r.push(`Pending migrations: ${a}${o}.`)}return{id:E_,title:"Restart required",body:`${hFn(e)} ${r.join(" ")}`.trim(),tone:"warn",persistent:!0,...s?{action:{label:"Restart Rudder",onClick:async()=>{try{await s.restart()}catch(a){throw t({title:"Could not restart Rudder",body:a instanceof Error?a.message:"Try restarting Rudder manually.",tone:"error"}),a}}}}:{}}}function pFn(e){return JSON.stringify({reason:e.reason,lastChangedAt:e.lastChangedAt,changedPathCount:e.changedPathCount,changedPathsSample:e.changedPathsSample,envFileChanged:e.envFileChanged,pendingMigrations:e.pendingMigrations,lastRestartAt:e.lastRestartAt})}function gFn({devServer:e}){const{dismissToast:t,pushToast:n}=ss(),r=h.useRef(null),s=e!=null&&e.enabled&&e.restartRequired?pFn(e):null;return h.useEffect(()=>{if(!e||!s){t(E_),r.current=null;return}return r.current&&t(r.current),r.current=n({...mFn(e,n),dedupeKey:`dev-restart:${s}`}),()=>{t(E_),r.current=null}},[s,t,n]),null}function xFn({visible:e}){const{t}=is(),n=br(),{selectedOrganizationId:r}=jr(),{openNewIssue:s}=ii(),a=ihe(r),o=h.useMemo(()=>[{type:"link",to:"/messenger",label:"Messenger",icon:pa,badge:a.inbox,badgeTone:"danger"},{type:"link",to:"/issues",label:t("common.issues"),icon:qh},{type:"action",label:t("common.create"),icon:zBe,onClick:()=>s()},{type:"link",to:"/agents",label:t("common.agents"),icon:FBe}],[s,a.inbox,t]);return i.jsx("nav",{className:K("fixed bottom-0 left-0 right-0 z-30 border-t border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85 transition-transform duration-200 ease-out md:hidden pb-[env(safe-area-inset-bottom)]",e?"translate-y-0":"translate-y-full"),"aria-label":t("common.mobileNavigation"),children:i.jsx("div",{className:"grid h-16 grid-cols-4 px-1",children:o.map(l=>{if(l.type==="action"){const d=l.icon,u=/\/issues\/new(?:\/|$)/.test(n.pathname);return i.jsxs("button",{type:"button",onClick:l.onClick,className:K("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-[10px] font-medium transition-colors",u?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[i.jsx(d,{className:"h-[18px] w-[18px]"}),i.jsx("span",{className:"truncate",children:l.label})]},l.label)}const c=l.icon;return i.jsx(Pj,{to:l.to,className:({isActive:d})=>K("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-[10px] font-medium transition-colors",d?"text-foreground":"text-muted-foreground hover:text-foreground"),children:({isActive:d})=>i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"relative",children:[i.jsx(c,{className:K("h-[18px] w-[18px]",d&&"stroke-[2.3]")}),l.badge!=null&&l.badge>0&&i.jsx("span",{className:K("absolute -right-2 -top-2 rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none",l.badgeTone==="danger"?"bg-red-500 text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]":"bg-primary text-primary-foreground"),children:l.badge>99?"99+":l.badge})]}),i.jsx("span",{className:"truncate",children:l.label})]})},l.label)})})})}function h2e({className:e}){return i.jsxs(i.Fragment,{children:[i.jsx("img",{src:"/brands/opencode-logo-light-square.svg",alt:"OpenCode",className:K("dark:hidden",e)}),i.jsx("img",{src:"/brands/opencode-logo-dark-square.svg",alt:"OpenCode",className:K("hidden dark:block",e)})]})}const bFn=[{value:"claude_local",label:"Claude Code",icon:Hh,desc:"Local Claude agent",recommended:!0},{value:"codex_local",label:"Codex",icon:VK,desc:"Local Codex agent",recommended:!0},{value:"gemini_local",label:"Gemini CLI",icon:Wfe,desc:"Local Gemini agent"},{value:"opencode_local",label:"OpenCode",icon:h2e,desc:"Local multi-provider agent"},{value:"pi_local",label:"Pi",icon:AE,desc:"Local Pi agent"},{value:"cursor",label:"Cursor",icon:IBe,desc:"Local Cursor agent"},{value:"openclaw_gateway",label:"OpenClaw Gateway",icon:Ul,desc:"Invoke OpenClaw via gateway protocol"}];function yFn(){const{newAgentOpen:e,closeNewAgent:t,openNewIssue:n}=ii(),{selectedOrganizationId:r}=jr(),s=Yr(),[a,o]=h.useState(!1),{data:l}=Me({queryKey:V.agents.list(r),queryFn:()=>Nn.list(r),enabled:!!r&&e}),c=(l??[]).find(A=>A.role==="ceo");function d(){t(),n({assigneeAgentId:c==null?void 0:c.id,title:"Create a new agent",description:"(type in what kind of agent you want here)"})}function u(){o(!0)}function f(A){t(),o(!1),s(`/agents/new?agentRuntimeType=${encodeURIComponent(A)}`)}return i.jsx(Ps,{open:e,onOpenChange:A=>{A||(o(!1),t())},children:i.jsxs(zs,{showCloseButton:!1,className:"sm:max-w-md p-0 gap-0 overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[i.jsx("span",{className:"text-sm text-muted-foreground",children:"Add a new agent"}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{o(!1),t()},children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]}),i.jsx("div",{className:"p-6 space-y-6",children:a?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-2",children:[i.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",onClick:()=>o(!1),children:[i.jsx(Kx,{className:"h-3.5 w-3.5"}),"Back"]}),i.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose your runtime type for advanced setup."})]}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:bFn.map(A=>i.jsxs("button",{className:K("flex flex-col items-center gap-1.5 rounded-md border border-border p-3 text-xs transition-colors hover:bg-accent/50 relative"),onClick:()=>f(A.value),children:[A.recommended&&i.jsx("span",{className:"absolute -top-1.5 right-1.5 bg-green-500 text-white text-[9px] font-semibold px-1.5 py-0.5 rounded-full leading-none",children:"Recommended"}),i.jsx(A.icon,{className:"h-4 w-4"}),i.jsx("span",{className:"font-medium",children:A.label}),i.jsx("span",{className:"text-muted-foreground text-[10px]",children:A.desc})]},A.value))})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"text-center space-y-3",children:[i.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-accent",children:i.jsx(Hh,{className:"h-6 w-6 text-foreground"})}),i.jsx("p",{className:"text-sm text-muted-foreground",children:"We recommend letting your CEO handle agent setup — they can choose the right role, permissions, skills, and runtime."})]}),i.jsxs(le,{className:"w-full",size:"lg",onClick:d,children:[i.jsx(Ul,{className:"h-4 w-4 mr-2"}),"Ask Agent"]}),i.jsx("div",{className:"text-center",children:i.jsx("button",{className:"text-xs text-muted-foreground hover:text-foreground underline underline-offset-2 transition-colors",onClick:u,children:"I want advanced configuration myself"})})]})})]})})}const f8={uploadImage:async(e,t,n)=>{const r=await t.arrayBuffer(),s=new File([r],t.name,{type:t.type}),a=new FormData;return n&&n.trim().length>0&&a.append("namespace",n.trim()),a.append("file",s),Re.postForm(`/orgs/${e}/assets/images`,a)},uploadOrganizationLogo:async(e,t)=>{const n=await t.arrayBuffer(),r=new File([n],t.name,{type:t.type}),s=new FormData;return s.append("file",r),Re.postForm(`/orgs/${e}/logo`,s)}},_Pe={organization:"Organization",team:"Team",agent:"Agent",task:"Task"};function vFn(){const{newGoalOpen:e,newGoalDefaults:t,closeNewGoal:n}=ii(),{selectedOrganizationId:r,selectedOrganization:s}=jr(),a=Vn(),[o,l]=h.useState(""),[c,d]=h.useState(""),[u,f]=h.useState("planned"),[A,m]=h.useState("task"),[g,x]=h.useState(""),[y,v]=h.useState(!1),[w,k]=h.useState(0),[S,j]=h.useState(!1),[C,N]=h.useState(!1),[P,M]=h.useState(!1),E=h.useRef(null),T=g||t.parentId||"",{data:R}=Me({queryKey:V.goals.list(r),queryFn:()=>LA.list(r),enabled:!!r&&e}),_=xt({mutationFn:X=>LA.create(r,X),onSuccess:()=>{a.invalidateQueries({queryKey:V.goals.list(r)}),U(),n()}}),D=xt({mutationFn:async X=>{if(!r)throw new Error("No organization selected");return f8.uploadImage(r,X,"goals/drafts")}});function U(){k(X=>X+1),l(""),d(""),f("planned"),m("task"),x(""),v(!1)}function $(){!r||!o.trim()||_.mutate({title:o.trim(),description:g0e(c),status:u,level:A,...T?{parentId:T}:{}})}function L(X){X.key==="Enter"&&(X.metaKey||X.ctrlKey)&&(X.preventDefault(),$())}const H=(R??[]).find(X=>X.id===T);return i.jsx(Ps,{open:e,onOpenChange:X=>{X||(U(),n())},children:i.jsxs(zs,{showCloseButton:!1,className:K("p-0 gap-0",y?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:L,children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s&&i.jsx("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:s.name.slice(0,3).toUpperCase()}),i.jsx("span",{className:"text-muted-foreground/60",children:"›"}),i.jsx("span",{children:t.parentId?"New sub-goal":"New goal"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>v(!y),children:y?i.jsx(uE,{className:"h-3.5 w-3.5"}):i.jsx(n3,{className:"h-3.5 w-3.5"})}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{U(),n()},children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),i.jsx("div",{className:"px-4 pt-4 pb-2 shrink-0",children:i.jsx("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:o,onChange:X=>l(X.target.value),onKeyDown:X=>{var F;X.key==="Tab"&&!X.shiftKey&&(X.preventDefault(),(F=E.current)==null||F.focus())},autoFocus:!0})}),i.jsx("div",{className:"px-4 pb-2",children:i.jsx(ku,{ref:E,engine:"codemirror",documentIdentity:`new-goal:${w}`,value:c,onChange:d,placeholder:"Add description...",bordered:!1,contentClassName:K("text-sm text-muted-foreground",y?"min-h-[220px]":"min-h-[120px]"),imageUploadHandler:async X=>(await D.mutateAsync(X)).contentPath})}),i.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[i.jsxs(ts,{open:S,onOpenChange:j,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:i.jsx(Qs,{status:u})})}),i.jsx(ns,{className:"w-40 p-1",align:"start",children:wK.map(X=>i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",X===u&&"bg-accent"),onClick:()=>{f(X),j(!1)},children:X},X))})]}),i.jsxs(ts,{open:C,onOpenChange:N,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[i.jsx(CBe,{className:"h-3 w-3 text-muted-foreground"}),_Pe[A]??A]})}),i.jsx(ns,{className:"w-40 p-1",align:"start",children:Jue.map(X=>i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",X===A&&"bg-accent"),onClick:()=>{m(X),N(!1)},children:_Pe[X]??X},X))})]}),i.jsxs(ts,{open:P,onOpenChange:M,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[i.jsx(ud,{className:"h-3 w-3 text-muted-foreground"}),H?H.title:"Parent goal"]})}),i.jsxs(ns,{className:"w-48 p-1",align:"start",children:[i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!T&&"bg-accent"),onClick:()=>{x(""),M(!1)},children:"No parent"}),(R??[]).map(X=>i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",X.id===T&&"bg-accent"),onClick:()=>{x(X.id),M(!1)},children:X.title},X.id))]})]})]}),i.jsx("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:i.jsx(le,{size:"sm",disabled:!o.trim()||_.isPending,onClick:$,children:_.isPending?"Creating…":t.parentId?"Create sub-goal":"Create goal"})})]})})}function wFn(e){const t=/^#?([0-9a-f]{3,6})$/i.exec(e.trim());if(!t)return null;let n=t[1];return n.length===3&&(n=n.split("").map(r=>`${r}${r}`).join("")),n.length!==6?null:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16)}}function One(e){const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Sne(e,t,n){return .2126*One(e)+.7152*One(t)+.0722*One(n)}function MPe(e,t){const n=Math.max(e,t),r=Math.min(e,t);return(n+.05)/(r+.05)}const EPe="#f8fafc",kFn="#111827";function DPe(e){const t=wFn(e);if(!t)return EPe;const n=Sne(t.r,t.g,t.b),r=Sne(248,250,252),s=Sne(17,24,39);return MPe(n,r)>=MPe(n,s)?EPe:kFn}function dde(e){const t=e.trim();return t.includes("/")&&t.slice(0,t.indexOf("/")).trim()||null}function jne(e,t="other"){return dde(e)??t}function OFn(e){const t=e.trim();return t.includes("/")?t.slice(t.indexOf("/")+1).trim():t}const m2e="rudder:issue-draft",p2e="rudder:issue-autosave",ift="rudder:issue-drafts",V_="rudder:issue-draft-changed",aft="rudder:new-issue-preferences";function A8(){try{return globalThis.localStorage??null}catch{return null}}function g2e(){var e;try{(e=globalThis.dispatchEvent)==null||e.call(globalThis,new Event(V_))}catch{}}function uc(e){return typeof e=="string"?e.trim():""}function N2(e){return e?!!(uc(e.title)||uc(e.description)||uc(e.projectId)||uc(e.assigneeValue)||uc(e.assigneeId)||uc(e.reviewerValue)||uc(e.goalId)||uc(e.priority)&&uc(e.priority)!=="medium"||uc(e.status)&&uc(e.status)!=="todo"||Array.isArray(e.labelIds)&&e.labelIds.length>0||uc(e.projectWorkspaceId)||uc(e.assigneeModelOverride)||uc(e.assigneeThinkingEffort)||e.assigneeChrome):!1}function SFn(){var e,t;try{return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}catch{return`draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}}function jFn(e){try{const t=A8(),n=(t==null?void 0:t.getItem(p2e))??(t==null?void 0:t.getItem(m2e));if(!n)return null;const r=JSON.parse(n);return e&&r.orgId&&r.orgId!==e?null:N2(r)?r:null}catch{return null}}function CFn(e){if(!N2(e))return;const t=A8();t==null||t.setItem(p2e,JSON.stringify(e)),t==null||t.removeItem(m2e),g2e()}function RPe(){const e=A8();e==null||e.removeItem(p2e),e==null||e.removeItem(m2e),g2e()}function oft(){var e;try{const t=(e=A8())==null?void 0:e.getItem(aft);if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};const r={};for(const[s,a]of Object.entries(n)){if(!s||!a||typeof a!="object"||Array.isArray(a))continue;const o=a;r[s]={assigneeValue:uc(o.assigneeValue),reviewerValue:uc(o.reviewerValue),projectId:uc(o.projectId),updatedAt:uc(o.updatedAt)||new Date(0).toISOString()}}return r}catch{return{}}}function NFn(e){return e?oft()[e]??null:null}function PFn(e,t){if(!e)return;const n=A8();if(!n)return;const r={...oft(),[e]:{assigneeValue:uc(t.assigneeValue),reviewerValue:uc(t.reviewerValue),projectId:uc(t.projectId),updatedAt:new Date().toISOString()}};n.setItem(aft,JSON.stringify(r))}function _H(){var e;try{const t=(e=A8())==null?void 0:e.getItem(ift);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.filter(N2):[]}catch{return[]}}function x2e(e){var t;(t=A8())==null||t.setItem(ift,JSON.stringify(e)),g2e()}function LPe(e){return JSON.stringify({orgId:e.orgId??null,title:e.title,description:e.description,status:e.status,priority:e.priority,labelIds:e.labelIds??[],assigneeValue:e.assigneeValue??"",assigneeId:e.assigneeId??"",reviewerValue:e.reviewerValue??"",projectId:e.projectId??"",goalId:e.goalId??"",projectWorkspaceId:e.projectWorkspaceId??"",assigneeModelOverride:e.assigneeModelOverride??"",assigneeThinkingEffort:e.assigneeThinkingEffort??"",assigneeChrome:!!e.assigneeChrome,useIsolatedExecutionWorkspace:!!e.useIsolatedExecutionWorkspace})}function lft(e){return _H().filter(t=>!e||!t.orgId||t.orgId===e).sort((t,n)=>Date.parse(n.updatedAt)-Date.parse(t.updatedAt))}function IFn(e,t){return e?lft(t).find(n=>n.id===e)??null:null}function TFn(e){if(!N2(e))return null;const t=new Date().toISOString(),n={...e,id:SFn(),createdAt:t,updatedAt:t};return x2e([n,..._H()]),n}function _Fn(e,t){if(!e||!N2(t))return null;const n=_H(),r=n.findIndex(l=>l.id===e);if(r===-1)return null;const s=n[r];if(LPe(s)===LPe(t))return s;const a={...t,id:e,createdAt:s.createdAt,updatedAt:new Date().toISOString()},o=[...n];return o[r]=a,x2e(o),a}function ude(e){e&&x2e(_H().filter(t=>t.id!==e))}function MFn(e){const t=e.title.trim()||"Untitled issue draft";return{id:e.id,title:t,description:e.description.trim(),assigneeValue:e.assigneeValue,assigneeId:e.assigneeId,projectId:e.projectId,status:e.status||"todo",priority:e.priority,createdAt:e.createdAt,updatedAt:e.updatedAt}}function aq(e){return lft(e).map(MFn)}function zPe(e){const t=!!(e.defaults.assigneeAgentId||e.defaults.assigneeUserId),n=!!(e.defaults.reviewerAgentId||e.defaults.reviewerUserId);return{status:e.defaults.status??e.draft.status??"todo",priority:e.defaults.priority??e.draft.priority??"",projectId:e.defaultProjectId||e.draft.projectId,goalId:e.defaults.goalId??e.draft.goalId??"",labelIds:e.defaults.labelIds??e.draft.labelIds??[],assigneeValue:t?e.defaultAssigneeValue:e.draft.assigneeValue??e.draft.assigneeId??"",reviewerValue:n?e.defaultReviewerValue:e.draft.reviewerValue??""}}function EFn(e){var o,l,c;const t=(o=e.explicitProjectId)==null?void 0:o.trim();if(t)return t;const n=(l=new URLSearchParams(e.search??"").get("projectId"))==null?void 0:l.trim();if(n&&e.projects.some(d=>d.id===n))return n;const s=fl(e.pathname).match(/^\/projects\/([^/?#]+)/);if(!(s!=null&&s[1]))return"";const a=decodeURIComponent(s[1]).trim();return a?((c=e.projects.find(d=>d.id===a||S3(d)===a))==null?void 0:c.id)??"":""}function DFn(e){var c,d;const t=e.organizations.find(u=>u.id===e.orgId),n=t?Oc(t).trim():"",r=u=>n?`/${n}${u}`:u,s=((c=e.openContextLocation)==null?void 0:c.pathname)??r("/issues"),a=fl(s),o=/^\/issues(?:\/|$)/.test(a),l=e.issue.identifier??e.issue.id;return o?{destination:"issues",detailHref:r(`/issues/${l}`),breadcrumbLabel:"Issues",breadcrumbHref:`${r(a)}${((d=e.openContextLocation)==null?void 0:d.search)??""}`}:{destination:"messenger",detailHref:r(`/messenger/issues/${l}`),breadcrumbLabel:"Messenger",breadcrumbHref:r("/messenger/issues")}}function RFn(e){return{title:e.title.trim(),description:g0e(e.description),...e.parentId?{parentId:e.parentId}:{},status:e.status,priority:e.priority||"medium",...e.assigneeAgentId?{assigneeAgentId:e.assigneeAgentId}:{},...e.assigneeUserId?{assigneeUserId:e.assigneeUserId}:{},...e.reviewerAgentId?{reviewerAgentId:e.reviewerAgentId}:{},...e.reviewerUserId?{reviewerUserId:e.reviewerUserId}:{},...e.projectId?{projectId:e.projectId}:{},goalId:e.goalId||null,...e.labelIds.length>0?{labelIds:e.labelIds}:{},...e.projectWorkspaceId?{projectWorkspaceId:e.projectWorkspaceId}:{},...e.assigneeAgentRuntimeOverrides?{assigneeAgentRuntimeOverrides:e.assigneeAgentRuntimeOverrides}:{}}}const LFn=800,cft=new Set(["claude_local","codex_local","opencode_local"]),zFn="image/*,application/pdf,text/plain,text/markdown,application/json,text/csv,text/html,.md,.markdown",Cne="h-auto min-h-12 w-full py-2",n$={claude_local:[{value:"",label:"Default"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],opencode_local:[{value:"",label:"Default"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"max",label:"Max"}]};function $Fn(e){const t=e.agentRuntimeType??null;if(!t||!cft.has(t))return null;const n={};e.modelOverride&&(n.model=e.modelOverride),e.thinkingEffortOverride&&(t==="codex_local"?n.modelReasoningEffort=e.thinkingEffortOverride:t==="opencode_local"?n.variant=e.thinkingEffortOverride:t==="claude_local"?n.effort=e.thinkingEffortOverride:t==="opencode_local"&&(n.variant=e.thinkingEffortOverride)),t==="claude_local"&&e.chrome&&(n.chrome=!0);const r={};return Object.keys(n).length>0&&(r.agentRuntimeConfig=n),Object.keys(r).length>0?r:null}function $Pe(e){return e.size<1024?`${e.size} B`:e.size<1024*1024?`${(e.size/1024).toFixed(1)} KB`:`${(e.size/(1024*1024)).toFixed(1)} MB`}const Nne=[{value:"backlog",label:"Backlog",color:W9.backlog},{value:"todo",label:"Todo",color:W9.todo},{value:"in_progress",label:"In Progress",color:W9.in_progress},{value:"in_review",label:"In Review",color:W9.in_review},{value:"done",label:"Done",color:W9.done}],FPe=LFt;function _N(e){var t,n,r,s,a,o,l,c;return e?((t=e.codebase)==null?void 0:t.scope)==="organization"||((n=e.codebase)==null?void 0:n.scope)==="none"?((r=e.executionWorkspacePolicy)==null?void 0:r.defaultProjectWorkspaceId)??"":((s=e.executionWorkspacePolicy)==null?void 0:s.defaultProjectWorkspaceId)??((o=(a=e.workspaces)==null?void 0:a.find(d=>d.isPrimary))==null?void 0:o.id)??((c=(l=e.workspaces)==null?void 0:l[0])==null?void 0:c.id)??"":""}function FFn(){var Vo,yd,Pc,eo,$a,_s;const{newIssueOpen:e,newIssueDefaults:t,closeNewIssue:n}=ii(),{organizations:r,selectedOrganizationId:s,selectedOrganization:a}=jr(),o=Vn(),{pushToast:l}=ss(),c=br(),d=Yr(),[u,f]=h.useState(""),[A,m]=h.useState(""),[g,x]=h.useState("todo"),[y,v]=h.useState(""),[w,k]=h.useState([]),[S,j]=h.useState(""),[C,N]=h.useState(""),[P,M]=h.useState(""),[E,T]=h.useState(""),[R,_]=h.useState(""),[D,U]=h.useState(""),[$,L]=h.useState(!1),[H,X]=h.useState(""),[F,Q]=h.useState(""),[q,B]=h.useState(!1),[ee,se]=h.useState(!1),[re,ne]=h.useState(null),[Ae,Y]=h.useState([]),[ce,Oe]=h.useState(!1),[Fe,ke]=h.useState(null),[Ne,xe]=h.useState(0),[ae,fe]=h.useState(null),ve=h.useRef(null),Se=h.useRef(null),ze=h.useRef(null),ft=h.useRef(null),ie=re??s,me=r.find(et=>et.id===ie)??a,we=t.draftId??null,[Xe,ge]=h.useState(!1),[te,G]=h.useState(!1),[oe,Ze]=h.useState(!1),[Te,Be]=h.useState(!1),[it,lt]=h.useState(!1),Ue=h.useRef(null),mt=h.useRef(null),tt=h.useRef(null),dt=h.useRef(null),{data:at}=Me({queryKey:V.agents.list(ie),queryFn:()=>Nn.list(ie),enabled:!!ie&&e}),{data:Pe}=Me({queryKey:V.projects.list(ie),queryFn:()=>Mi.list(ie),enabled:!!ie&&e}),{data:$e}=Me({queryKey:V.goals.list(ie),queryFn:()=>LA.list(ie),enabled:!!ie&&e}),{data:ot}=Me({queryKey:V.issues.list(ie),queryFn:()=>lr.list(ie),enabled:!!ie&&e}),{data:ue}=Me({queryKey:V.issues.labels(ie),queryFn:()=>lr.listLabels(ie),enabled:!!ie&&e}),{data:Ie}=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),Ke=((Vo=Ie==null?void 0:Ie.user)==null?void 0:Vo.id)??((yd=Ie==null?void 0:Ie.session)==null?void 0:yd.userId)??null,De=h.useMemo(()=>(Pe??[]).filter(et=>!et.archivedAt),[Pe]),{orderedProjects:Je}=RE({projects:De,orgId:ie,userId:Ke}),_e=h.useMemo(()=>Nm(C),[C]),Ee=_e.assigneeAgentId,Ce=_e.assigneeUserId,kt=h.useMemo(()=>Nm(P),[P]),Qe=kt.assigneeAgentId,gt=kt.assigneeUserId,Nt=Ee?(at??[]).find(et=>et.id===Ee)??null:null,Gt=Qe?(at??[]).find(et=>et.id===Qe)??null:null,cn=(Nt==null?void 0:Nt.agentRuntimeType)??null,Rn=typeof(Nt==null?void 0:Nt.agentRuntimeConfig.model)=="string"?Nt.agentRuntimeConfig.model:"",nt=H||Rn,Qt=!!(cn&&cft.has(cn)),{data:st}=Me({queryKey:V.organizationSkills.list(ie??"__none__"),queryFn:()=>nf.list(ie),enabled:!!ie&&e&&!!Ee}),{data:Rt}=Me({queryKey:V.agents.skills(Ee??"__none__"),queryFn:()=>Nn.skills(Ee,ie),enabled:!!ie&&e&&!!Ee}),{data:Cn}=Me({queryKey:V.organizations.libraryDocuments(ie??"__none__"),queryFn:()=>_n.listLibraryDocuments(ie),enabled:!!ie&&e}),[zn,fs]=h.useState(null),as=(zn==null?void 0:zn.trim())??"",{data:sr}=Me({queryKey:["organizations",ie??"__none__","workspace-mention-files",as],queryFn:()=>_n.listWorkspaceMentionFiles(ie,{query:as,limit:as?50:200}),enabled:!!ie&&e});h.useEffect(()=>{if(!e){ze.current=null;return}ze.current||(ze.current={pathname:c.pathname,search:c.search})},[c.pathname,c.search,e]);const Kr=h.useMemo(()=>Qj({agent:Nt,orgUrlKey:(me==null?void 0:me.urlKey)??(a==null?void 0:a.urlKey)??"organization",organizationSkills:st,skillSnapshot:Rt}),[st,Rt,Nt,me==null?void 0:me.urlKey,a==null?void 0:a.urlKey]),yr=h.useMemo(()=>yE({agents:at,projects:Je,issues:ot,libraryDocuments:Cn,libraryFiles:sr==null?void 0:sr.entries,skillMentionOptions:Kr,currentUserId:Ke}),[at,ot,Ke,Cn,sr==null?void 0:sr.entries,Je,Kr]),{data:ht}=Me({queryKey:ie&&cn?V.agents.adapterModels(ie,cn):["agents","none","adapter-models",cn??"none"],queryFn:()=>Nn.adapterModels(ie,cn),enabled:!!ie&&e&&Qt}),Vt=h.useCallback(()=>{ve.current&&clearTimeout(ve.current),ve.current=null,Se.current=null},[]),We=h.useCallback(()=>{ve.current&&clearTimeout(ve.current),ve.current=null;const et=Se.current;if(Se.current=null,!!et){if(et.savedDraftId){_Fn(et.savedDraftId,et.draft);return}CFn(et.draft)}},[]),Tt=xt({mutationFn:async({orgId:et,stagedFiles:Hn,...dr})=>{const ca=await lr.create(et,dr),wi=[];for(const Ni of Hn)try{await lr.uploadAttachment(et,ca.id,Ni.file)}catch{wi.push(Ni.file.name)}return{issue:ca,orgId:et,failures:wi}},onSuccess:async({issue:et,orgId:Hn,failures:dr})=>{o.invalidateQueries({queryKey:V.issues.list(Hn)}),o.invalidateQueries({queryKey:V.issues.listTouchedByMe(Hn)}),o.invalidateQueries({queryKey:V.issues.listUnreadTouchedByMe(Hn)}),o.invalidateQueries({queryKey:V.sidebarBadges(Hn)}),o.setQueryData(V.issues.detail(et.identifier??et.id),et),o.setQueryData(V.issues.detail(et.id),et),Vt(),PFn(Hn,{assigneeValue:C,reviewerValue:P,projectId:E});const ca=et.identifier??et.id,wi=DFn({issue:et,orgId:Hn,organizations:r,openContextLocation:ze.current});dr.length>0&&l({title:`Created ${ca} with upload warnings`,body:`${dr.length} staged ${dr.length===1?"file":"files"} could not be added.`,tone:"warn",action:{label:`Open ${ca}`,href:wi.detailHref}}),fe(ca),await new Promise(vd=>setTimeout(vd,340)),RPe(),ude(Fe),pt(),n();const Ni=document;Ni.startViewTransition?await Ni.startViewTransition(()=>{d(wi.detailHref,{state:eq(wi.breadcrumbLabel,wi.breadcrumbHref)})}).finished.catch(()=>{}):d(wi.detailHref,{state:eq(wi.breadcrumbLabel,wi.breadcrumbHref)})}}),Mn=xt({mutationFn:et=>lr.createLabel(ie,et),onSuccess:async et=>{ie&&(await o.invalidateQueries({queryKey:V.issues.labels(ie)}),k(Hn=>[...new Set([...Hn,et.id])]),j(""))}}),tr=xt({mutationFn:async et=>{if(!ie)throw new Error("No organization selected");return f8.uploadImage(ie,et,"issues/drafts")}}),Ln=h.useCallback((et,Hn=null)=>{ve.current&&clearTimeout(ve.current),Se.current={draft:et,savedDraftId:Hn},ve.current=setTimeout(We,LFn)},[We]);h.useEffect(()=>{e&&N2({title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q})&&Ln({orgId:ie,title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q},Fe)},[u,A,g,y,w,C,P,E,R,D,H,F,q,ie,e,Fe,Ln]),h.useEffect(()=>{if(!e)return;ne(s);const et=ze.current??{pathname:c.pathname,search:c.search},Hn=EFn({explicitProjectId:t.projectId,pathname:et.pathname,search:et.search,projects:Je}),dr=NFn(s),ca=dr!=null&&dr.projectId&&Je.some(ai=>ai.id===dr.projectId)?dr.projectId:"",wi=Hn||ca,Ni=_v(t),vd=_v({assigneeAgentId:t.reviewerAgentId,assigneeUserId:t.reviewerUserId}),r1=Ni||(dr==null?void 0:dr.assigneeValue)||"",mf=vd||(dr==null?void 0:dr.reviewerValue)||"",el=IFn(we,s),_l=el??(we?null:jFn(s));if(ke(el?el.id:null),el&&N2(el)){const ai=zPe({defaults:{},draft:el,defaultProjectId:Hn,defaultAssigneeValue:Ni,defaultReviewerValue:vd}),tl=ai.projectId,wd=Je.find(pf=>pf.id===tl);f(el.title),m(el.description),x(ai.status),v(ai.priority),k(ai.labelIds),j(""),N(ai.assigneeValue),M(ai.reviewerValue),T(tl),_(ai.goalId),U(el.projectWorkspaceId??_N(wd)),X(el.assigneeModelOverride??""),Q(el.assigneeThinkingEffort??""),B(el.assigneeChrome??!1)}else if(t.title){f(t.title),m(t.description??""),x(t.status??"todo"),v(t.priority??""),k(t.labelIds??[]),j("");const ai=Je.find(tl=>tl.id===wi);T(wi),_(t.goalId??""),U(_N(ai)),N(r1),M(mf),X(""),Q(""),B(!1)}else if(_l&&N2(_l)){const ai=zPe({defaults:t,draft:_l,defaultProjectId:Hn,defaultAssigneeValue:Ni,defaultReviewerValue:vd}),tl=ai.projectId,wd=Je.find(pf=>pf.id===tl);f(_l.title),m(_l.description),x(ai.status),v(ai.priority),k(ai.labelIds),j(""),N(ai.assigneeValue),M(ai.reviewerValue),T(tl),_(ai.goalId),U(_l.projectWorkspaceId??_N(wd)),X(_l.assigneeModelOverride??""),Q(_l.assigneeThinkingEffort??""),B(_l.assigneeChrome??!1)}else{const ai=Je.find(tl=>tl.id===wi);f(""),m(""),x(t.status??"todo"),v(t.priority??""),k(t.labelIds??[]),j(""),T(wi),_(t.goalId??""),U(_N(ai)),N(r1),M(mf),X(""),Q(""),B(!1)}},[e,t,Je,we,s]),h.useEffect(()=>{if(!e){ft.current=null;return}const et=ft.current;et!==null&&et!==Ee&&(X(""),Q(""),B(!1)),ft.current=Ee},[e,Ee]),h.useEffect(()=>{if(!Qt){L(!1),X(""),Q(""),B(!1);return}(cn==="codex_local"?M_("Default",TV(nt)):cn==="opencode_local"?n$.opencode_local:n$.claude_local).some(Hn=>Hn.value===F)||Q("")},[Qt,cn,F,nt]),h.useEffect(()=>()=>{We()},[We]);function pt(){xe(et=>et+1),f(""),m(""),x("todo"),v(""),k([]),j(""),N(""),M(""),T(""),_(""),U(""),L(!1),X(""),Q(""),B(!1),se(!1),ne(null),Y([]),Oe(!1),lt(!1),ke(null),fe(null)}function vt(){We(),n()}function jt(et){et!==ie&&(ne(et),N(""),M(""),T(""),_(""),U(""),k([]),j(""),X(""),Q(""),B(!1))}function Zt(){TFn({orgId:ie,title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q})&&(Vt(),ude(Fe),RPe(),l({title:"Saved to Draft Issues",body:"Open Draft Issues from the Issues sidebar to continue it.",tone:"success"}),pt(),n())}function kr(){if(!ie||!oc||Tt.isPending||ae)return;fe(null);const et=$Fn({agentRuntimeType:cn,modelOverride:H,thinkingEffortOverride:F,chrome:q});Tt.mutate({orgId:ie,stagedFiles:Ae,...RFn({title:u,description:A,parentId:t.parentId,status:g,priority:y,assigneeAgentId:Ee,assigneeUserId:Ce,reviewerAgentId:Qe,reviewerUserId:gt,projectId:E,goalId:R,labelIds:w,projectWorkspaceId:D,assigneeAgentRuntimeOverrides:et})})}function xs(et){et.key==="Enter"&&(et.metaKey||et.ctrlKey)&&(et.preventDefault(),kr())}function la(et){et.length!==0&&Y(Hn=>{const dr=[...Hn];for(const ca of et)dr.push({id:`${ca.name}:${ca.size}:${ca.lastModified}`,file:ca,kind:"attachment"});return dr})}function Ss(et){la(Array.from(et.target.files??[])),mt.current&&(mt.current.value="")}function bt(et){et.dataTransfer.types.includes("Files")&&(et.preventDefault(),Oe(!0))}function Jt(et){et.dataTransfer.types.includes("Files")&&(et.preventDefault(),et.dataTransfer.dropEffect="copy",Oe(!0))}function nr(et){et.currentTarget.contains(et.relatedTarget)||Oe(!1)}function Er(et){et.dataTransfer.files.length&&(et.preventDefault(),Oe(!1),la(Array.from(et.dataTransfer.files)))}function cs(et){Y(Hn=>Hn.filter(dr=>dr.id!==et))}const ds=Nne.find(et=>et.value===g)??Nne[1],Or=FPe.find(et=>et.value===y),Dr=h.useMemo(()=>(ue??[]).filter(et=>w.includes(et.id)),[ue,w]),Ts=g3(S),Ui=h.useMemo(()=>(ue??[]).filter(et=>Ts?et.name.toLowerCase().includes(Ts.toLowerCase()):!0),[ue,Ts]),fo=h.useMemo(()=>Cct(ue??[],Ts),[ue,Ts]),On=Ts.length>0&&Ui.length===0&&!fo,Ye=x0e(Ts),Mt=Dr.length>0?i.jsxs(i.Fragment,{children:[i.jsx(Kse,{className:"h-3 w-3"}),i.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[Dr.slice(0,2).map(et=>i.jsx(C4,{label:et},et.id)),Dr.length>2?i.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["+",Dr.length-2]}):null]})]}):i.jsxs(i.Fragment,{children:[i.jsx(Kse,{className:"h-3 w-3"}),"Labels"]}),An=h.useCallback(()=>{!ie||!On||Mn.isPending||Mn.mutate({name:Ts,color:Ye})},[Mn,Ye,ie,Ts,On]),vn=Je.find(et=>et.id===E),fr=($e??[]).find(et=>et.id===R)??null,mr=cn==="claude_local"?"Claude options":cn==="codex_local"?"Codex options":cn==="opencode_local"?"OpenCode options":"Agent options",Ge=cn==="codex_local"?M_("Default",TV(nt)):cn==="opencode_local"?n$.opencode_local:n$.claude_local,tn=h.useMemo(()=>TD(),[e]),Gn=h.useMemo(()=>[...mie(Ke),...__((at??[]).filter(et=>et.status!=="terminated"),tn).map(et=>({id:_v({assigneeAgentId:et.id}),label:et.name,searchText:`${et.name} ${et.role} ${et.title??""}`}))],[at,Ke,tn]),Wr=h.useMemo(()=>[...mie(Ke),...__((at??[]).filter(et=>et.status!=="terminated"),tn).map(et=>({id:_v({assigneeAgentId:et.id}),label:et.name,searchText:`${et.name} ${et.role} ${et.title??""}`}))],[at,Ke,tn]),mn=h.useMemo(()=>Je.map(et=>({id:et.id,label:et.name,searchText:et.description??""})),[Je]),Bn=h.useMemo(()=>($e??[]).map(et=>({id:et.id,label:et.title,searchText:`${et.title} ${et.description??""} ${et.level} ${et.status}`})),[$e]),Ci=N2({title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q}),Vi=Tt.error instanceof Error?Tt.error.message:"Failed to create issue. Try again.",Vr=Tt.isPending||!!ae,oc=u.trim().length>0,Ao=bs(),ml=!!t.parentId,ho=t.parentIssue,vs=((Pc=ho==null?void 0:ho.identifier)==null?void 0:Pc.trim())||((eo=ho==null?void 0:ho.id)==null?void 0:eo.slice(0,8))||(($a=t.parentId)==null?void 0:$a.slice(0,8))||null,aA=((_s=ho==null?void 0:ho.title)==null?void 0:_s.trim())||null,hf=Ae.filter(et=>et.kind==="document"),Gi=Ae.filter(et=>et.kind==="attachment"),bd=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search labels...",value:S,onChange:et=>j(et.target.value),onKeyDown:et=>{et.key!=="Enter"||!On||(et.preventDefault(),An())},autoFocus:!0}),i.jsxs("div",{ref:Ao,className:"scrollbar-auto-hide max-h-44 overflow-y-auto overscroll-contain space-y-0.5",children:[Ui.map(et=>{const Hn=w.includes(et.id);return i.jsxs("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",Hn&&"bg-accent"),onClick:()=>k(dr=>dr.includes(et.id)?dr.filter(ca=>ca!==et.id):[...dr,et.id]),children:[i.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:et.color}}),i.jsx("span",{className:"truncate",children:et.name})]},et.id)}),On?i.jsxs(i.Fragment,{children:[Ui.length>0?i.jsx("div",{className:"my-1 border-t border-border"}):null,i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",disabled:Mn.isPending,onClick:An,children:[i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border border-border/70 text-muted-foreground",children:i.jsx(Zr,{className:"h-2.5 w-2.5"})}),i.jsx("span",{className:"truncate",children:Mn.isPending?"Creating...":`Create label "${Ts}"`}),i.jsx("span",{className:"ml-auto h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:Ye},"aria-hidden":"true"})]})]}):null]})]}),lc=h.useCallback(et=>{T(et);const Hn=Je.find(dr=>dr.id===et);U(_N(Hn))},[Je]),Qn=h.useMemo(()=>{const et=RC(cn??"",ht);return(cn==="codex_local"?et:[...et].sort((dr,ca)=>{const wi=jne(dr.id),Ni=jne(ca.id),vd=wi.localeCompare(Ni);return vd!==0?vd:dr.id.localeCompare(ca.id)})).map(dr=>({id:dr.id,label:dr.label,searchText:`${dr.id} ${jne(dr.id)}`}))},[cn,ht]);return i.jsx(Ps,{open:e,onOpenChange:et=>{!et&&!Vr&&vt()},children:i.jsxs(zs,{showCloseButton:!1,"aria-describedby":void 0,className:K("motion-new-issue-dialog p-0 gap-0 flex flex-col max-h-[calc(100dvh-2rem)]",ee?"sm:max-w-[1040px]":"sm:max-w-[920px]",ae&&"motion-new-issue-dialog--created"),"data-redirecting":ae?"true":void 0,onKeyDown:xs,onEscapeKeyDown:et=>{Vr&&et.preventDefault()},onPointerDownOutside:et=>{if(Vr){et.preventDefault();return}const Hn=et.detail.originalEvent.target;Hn!=null&&Hn.closest("[data-radix-popper-content-wrapper]")&&et.preventDefault()},children:[i.jsx(ei,{className:"sr-only",children:ml?"New sub-issue":"New issue"}),ae?i.jsxs("div",{className:"motion-new-issue-created-banner absolute left-1/2 top-4 z-10 inline-flex -translate-x-1/2 items-center gap-2 rounded-md border border-[color:color-mix(in_oklab,var(--accent-base)_42%,var(--border))] bg-[color:color-mix(in_oklab,var(--accent-soft)_82%,var(--surface-elevated))] px-3 py-1.5 text-xs font-medium text-foreground shadow-[var(--shadow-sm)]",role:"status","aria-live":"polite",children:[i.jsx(dd,{className:"h-3.5 w-3.5 text-[color:var(--accent-base)]"}),i.jsxs("span",{children:["Created ",ae,". Opening issue..."]})]}):null,i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i.jsxs(ts,{open:it,onOpenChange:lt,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:K("px-1.5 py-0.5 rounded text-xs font-semibold cursor-pointer hover:opacity-80 transition-opacity",!(me!=null&&me.brandColor)&&"bg-muted"),style:me!=null&&me.brandColor?{backgroundColor:me.brandColor,color:DPe(me.brandColor)}:void 0,children:((me==null?void 0:me.name)??"").slice(0,3).toUpperCase()})}),i.jsx(ns,{className:"w-48 p-1",align:"start",children:r.filter(et=>et.status!=="archived").map(et=>i.jsxs("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",et.id===ie&&"bg-accent"),onClick:()=>{jt(et.id),lt(!1)},children:[i.jsx("span",{className:K("px-1 py-0.5 rounded text-[10px] font-semibold leading-none",!et.brandColor&&"bg-muted"),style:et.brandColor?{backgroundColor:et.brandColor,color:DPe(et.brandColor)}:void 0,children:et.name.slice(0,3).toUpperCase()}),i.jsx("span",{className:"truncate",children:et.name})]},et.id))})]}),i.jsx("span",{className:"text-muted-foreground/60",children:"›"}),i.jsx("span",{children:ml?"New sub-issue":"New issue"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>se(!ee),disabled:Vr,children:ee?i.jsx(uE,{className:"h-3.5 w-3.5"}):i.jsx(n3,{className:"h-3.5 w-3.5"})}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:vt,disabled:Vr,children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),ml?i.jsx("div",{"data-slot":"new-issue-parent-context",className:"border-b border-border/60 px-4 py-2.5 shrink-0",children:i.jsxs("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden text-xs text-muted-foreground",children:[i.jsx(l4,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"shrink-0 font-medium",children:"Parent"}),vs?i.jsx("span",{className:"w-20 shrink-0 truncate whitespace-nowrap rounded-sm border border-border bg-muted/30 px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground",children:vs}):null,aA?i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground/80",children:aA}):null]})}):null,i.jsx("div",{className:"px-4 pt-4 pb-2 shrink-0",children:i.jsx("textarea",{className:"w-full text-lg font-semibold bg-transparent outline-none resize-none overflow-hidden placeholder:text-muted-foreground/50",placeholder:"Issue title",rows:1,value:u,onChange:et=>{f(et.target.value),et.target.style.height="auto",et.target.style.height=`${et.target.scrollHeight}px`},readOnly:Vr,onKeyDown:et=>{var Hn,dr,ca,wi;et.key==="Enter"&&!et.metaKey&&!et.ctrlKey&&!et.nativeEvent.isComposing&&(et.preventDefault(),(Hn=Ue.current)==null||Hn.focus()),et.key==="Tab"&&!et.shiftKey&&(et.preventDefault(),C?E?(dr=Ue.current)==null||dr.focus():(ca=dt.current)==null||ca.focus():(wi=tt.current)==null||wi.focus())},autoFocus:!0})}),i.jsx("div",{className:"px-4 pb-3 shrink-0",children:i.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:"Assignee"}),i.jsx(dg,{ref:tt,value:C,options:Gn,placeholder:"Assignee",disablePortal:!0,noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",variant:"field",className:Cne,onChange:et=>{const Hn=Nm(et);Hn.assigneeAgentId&&ij(Hn.assigneeAgentId),N(et)},onConfirm:()=>{var et,Hn;E?(et=Ue.current)==null||et.focus():(Hn=dt.current)==null||Hn.focus()},renderTriggerValue:et=>et?Nt?i.jsx(Wv,{agent:Nt,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label}):i.jsx("span",{className:"text-muted-foreground",children:"No assignee"}),renderOption:et=>{if(!et.id)return i.jsx("span",{className:"truncate",children:et.label});const Hn=Nm(et.id).assigneeAgentId?(at??[]).find(dr=>dr.id===Nm(et.id).assigneeAgentId):null;return Hn?i.jsx(Wv,{agent:Hn,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label})}})]}),i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:"Project"}),i.jsx(dg,{ref:dt,value:E,options:mn,placeholder:"Project",disablePortal:!0,noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",variant:"field",className:Cne,onChange:lc,onConfirm:()=>{var et;(et=Ue.current)==null||et.focus()},renderTriggerValue:et=>et&&vn?i.jsxs(i.Fragment,{children:[i.jsx(uo,{color:vn.color,icon:vn.icon,size:"xs"}),i.jsx("span",{className:"truncate",children:et.label})]}):i.jsx("span",{className:"text-muted-foreground",children:"No project"}),renderOption:et=>{if(!et.id)return i.jsx("span",{className:"truncate",children:et.label});const Hn=Je.find(dr=>dr.id===et.id);return i.jsxs(i.Fragment,{children:[i.jsx(uo,{color:Hn==null?void 0:Hn.color,icon:Hn==null?void 0:Hn.icon,size:"xs"}),i.jsx("span",{className:"truncate",children:et.label})]})}})]}),i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:"Reviewer"}),i.jsx(dg,{value:P,options:Wr,placeholder:"Reviewer",disablePortal:!0,noneLabel:"No reviewer",searchPlaceholder:"Search reviewers...",emptyMessage:"No reviewers found.",variant:"field",className:Cne,onChange:et=>{const Hn=Nm(et);Hn.assigneeAgentId&&ij(Hn.assigneeAgentId),M(et)},onConfirm:()=>{var et;(et=Ue.current)==null||et.focus()},renderTriggerValue:et=>et?Gt?i.jsx(Wv,{agent:Gt,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label}):i.jsx("span",{className:"text-muted-foreground",children:"No reviewer"}),renderOption:et=>{if(!et.id)return i.jsx("span",{className:"truncate",children:et.label});const Hn=Nm(et.id).assigneeAgentId?(at??[]).find(dr=>dr.id===Nm(et.id).assigneeAgentId):null;return Hn?i.jsx(Wv,{agent:Hn,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label})}})]})]})}),Qt&&i.jsxs("div",{className:"px-4 pb-2 shrink-0",children:[i.jsxs("button",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors",onClick:()=>L(et=>!et),children:[$?i.jsx(qr,{className:"h-3 w-3"}):i.jsx(bi,{className:"h-3 w-3"}),mr]}),$&&i.jsxs("div",{className:"mt-2 rounded-md border border-border p-3 bg-muted/20 space-y-3",children:[i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"text-xs text-muted-foreground",children:"Model"}),i.jsx(dg,{value:H,options:Qn,placeholder:"Default model",disablePortal:!0,noneLabel:"Default model",searchPlaceholder:"Search models...",emptyMessage:"No models found.",onChange:X})]}),i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"text-xs text-muted-foreground",children:"Thinking effort"}),i.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:Ge.map(et=>i.jsx("button",{className:K("px-2 py-1 rounded-md text-xs border border-border hover:bg-accent/50 transition-colors",F===et.value&&"bg-accent"),onClick:()=>Q(et.value),children:et.label},et.value||"default"))})]}),cn==="claude_local"&&i.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border px-2 py-1.5",children:[i.jsx("div",{className:"text-xs text-muted-foreground",children:"Enable Chrome (--chrome)"}),i.jsx(GA,{checked:q,size:"sm",tone:"success","aria-label":"Enable Chrome",onClick:()=>B(et=>!et)})]})]})]}),i.jsxs("div",{className:"px-4 pb-2 overflow-y-auto min-h-0 border-t border-border/60 pt-3",onDragEnter:bt,onDragOver:Jt,onDragLeave:nr,onDrop:Er,children:[i.jsx("div",{className:K("rounded-md transition-colors",ce&&"bg-accent/20"),children:i.jsx(ku,{ref:Ue,engine:"codemirror",documentIdentity:`new-issue:${ie??"none"}:${Fe??Ne}`,value:A,onChange:m,placeholder:"Add description...",bordered:!1,mentions:yr,onMentionQueryChange:fs,contentClassName:"text-sm text-muted-foreground pb-12 min-h-[88px]",imageUploadHandler:async et=>(await tr.mutateAsync(et)).contentPath})}),Ae.length>0?i.jsxs("div",{className:"mt-4 space-y-3 rounded-lg border border-border/70 p-3",children:[hf.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Documents"}),i.jsx("div",{className:"space-y-2",children:hf.map(et=>i.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"rounded-full border border-border px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:et.documentKey}),i.jsx("span",{className:"truncate text-sm",children:et.file.name})]}),i.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx(Fi,{className:"h-3.5 w-3.5"}),i.jsx("span",{children:et.title||et.file.name}),i.jsx("span",{children:"•"}),i.jsx("span",{children:$Pe(et.file)})]})]}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"shrink-0 text-muted-foreground",onClick:()=>cs(et.id),disabled:Vr,title:"Remove document",children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]},et.id))})]}):null,Gi.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Attachments"}),i.jsx("div",{className:"space-y-2",children:Gi.map(et=>i.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(tf,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate text-sm",children:et.file.name})]}),i.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[et.file.type||"application/octet-stream"," • ",$Pe(et.file)]})]}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"shrink-0 text-muted-foreground",onClick:()=>cs(et.id),disabled:Vr,title:"Remove attachment",children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]},et.id))})]}):null]}):null]}),i.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap shrink-0",children:[i.jsxs(ts,{open:Xe,onOpenChange:ge,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[i.jsx(qh,{className:K("h-3 w-3",ds.color)}),ds.label]})}),i.jsx(ns,{className:"w-36 p-1",align:"start",children:Nne.map(et=>i.jsxs("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",et.value===g&&"bg-accent"),onClick:()=>{x(et.value),ge(!1)},children:[i.jsx(qh,{className:K("h-3 w-3",et.color)}),et.label]},et.value))})]}),i.jsxs(ts,{open:te,onOpenChange:G,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:Or?i.jsxs(i.Fragment,{children:[i.jsx(fW,{priority:Or.value,className:"h-3.5 w-4"}),Or.label]}):i.jsxs(i.Fragment,{children:[i.jsx(PBe,{className:"h-3 w-3 text-muted-foreground"}),"Priority"]})})}),i.jsx(ns,{className:HUe,align:"start",role:"menu","aria-label":"Issue priority",children:FPe.map(et=>i.jsx(XUe,{priority:et.value,selected:et.value===y,onSelect:Hn=>{v(Hn),G(!1)}},et.value))})]}),i.jsxs(ts,{open:oe,onOpenChange:Ze,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:K("inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",Dr.length>0?"text-foreground":"text-muted-foreground"),disabled:Vr,children:Mt})}),i.jsx(ns,{className:"w-56 p-1",align:"start",disablePortal:!0,children:bd})]}),i.jsx(dg,{value:R,options:Bn,placeholder:"Goal",disablePortal:!0,noneLabel:"No goal",searchPlaceholder:"Search goals...",emptyMessage:"No goals found.",className:K("border-border bg-transparent px-2 py-1 [font-size:0.75rem] hover:bg-accent/50",fr?"text-foreground":"text-muted-foreground"),contentClassName:"w-56",onChange:_,onConfirm:()=>{var et;(et=Ue.current)==null||et.focus()},renderTriggerValue:et=>et&&fr?i.jsxs(i.Fragment,{children:[i.jsx(ud,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"max-w-40 truncate",children:et.label})]}):i.jsxs(i.Fragment,{children:[i.jsx(ud,{className:"h-3 w-3 shrink-0"}),"Goal"]}),renderOption:et=>et.id?i.jsxs(i.Fragment,{children:[i.jsx(ud,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:et.label})]}):i.jsx("span",{className:"truncate",children:et.label})}),i.jsx("input",{ref:mt,type:"file",accept:zFn,className:"hidden",onChange:Ss,multiple:!0}),i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground",onClick:()=>{var et;return(et=mt.current)==null?void 0:et.click()},disabled:Vr,children:[i.jsx(tf,{className:"h-3 w-3"}),"Upload"]}),i.jsxs(ts,{open:Te,onOpenChange:Be,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:"inline-flex items-center justify-center rounded-md border border-border p-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground",children:i.jsx(hl,{className:"h-3 w-3"})})}),i.jsxs(ns,{className:"w-44 p-1",align:"start",children:[i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",children:[i.jsx(UB,{className:"h-3 w-3"}),"Start date"]}),i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",children:[i.jsx(UB,{className:"h-3 w-3"}),"Due date"]})]})]})]}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-t border-border shrink-0",children:[Fe?i.jsxs("div",{className:"inline-flex min-h-8 items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx(dd,{className:"h-3.5 w-3.5"}),"Saved to Draft Issues"]}):i.jsx(le,{variant:"ghost",size:"sm",className:K("text-muted-foreground disabled:opacity-100",!Ci&&"disabled:border-border/40 disabled:bg-muted/20 disabled:text-muted-foreground/70"),onClick:Zt,disabled:Vr||!Ci,children:"Save Draft"}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"min-h-5 text-right",children:ae?i.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-[color:var(--accent-base)]",children:[i.jsx(dd,{className:"h-3 w-3"}),"Opening issue..."]}):Tt.isPending?i.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx(hn,{className:"h-3 w-3 animate-spin"}),ml?"Creating sub-issue...":"Creating issue..."]}):Tt.isError?i.jsx("span",{className:"text-xs text-destructive",children:Vi}):null}),i.jsx(le,{size:"sm",className:K("min-w-[8.5rem] disabled:opacity-100",!oc&&"disabled:border-border disabled:bg-muted disabled:text-muted-foreground disabled:ring-1 disabled:ring-inset disabled:ring-border/80 disabled:shadow-none"),disabled:!oc||Vr,onClick:kr,"aria-busy":Vr,children:i.jsxs("span",{className:"inline-flex items-center justify-center gap-1.5",children:[ae?i.jsx(dd,{className:"h-3.5 w-3.5"}):Tt.isPending?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):null,i.jsx("span",{children:ae?"Opening...":Tt.isPending?"Creating...":ml?"Create sub-issue":"Create Issue"})]})})]})]})]})})}const dft=[{value:"directory",label:"Directory"},{value:"file",label:"File"},{value:"url",label:"URL"},{value:"connector_object",label:"Connector object"}],BFn=[{value:"external",label:"External"},{value:"library",label:"Library"}];function P2(e){var t;return((t=dft.find(n=>n.value===e))==null?void 0:t.label)??e.replace(/_/g," ")}function b3(e){var t;return((t=BFn.find(n=>n.value===e))==null?void 0:t.label)??"External"}function BPe(e){return e==="directory"||e==="file"}function QFn(e){switch(e){case"directory":return"~/projects/rudder or https://linear.app/acme/project/...";case"file":return"~/projects/rudder/README.md or /Users/you/projects/rudder/README.md";case"connector_object":return"linear://project/123 or github://repo/acme/rudder";case"url":default:return"https://linear.app/acme/project/..."}}function uft(e){const t=e.trim();if(!t)return"";const n=t.replace(/\\/g,"/").replace(/\/+$/,""),r=n.split("/").filter(Boolean).pop()??n;try{return decodeURIComponent(r)}catch{return r}}function q_({kind:e,value:t,onChange:n,onPickedPath:r,disabled:s=!1,className:a,inputClassName:o,buttonClassName:l}){const[c,d]=h.useState(!1),u=Pn(),f=BPe(e)&&u!==null;async function A(){if(!(!u||!BPe(e)||c)){d(!0);try{const m=await u.pickPath({kind:e,title:e==="directory"?"Choose directory":"Choose file",buttonLabel:e==="directory"?"Choose directory":"Choose file",defaultPath:t.trim()||void 0});if(m.canceled||!m.path)return;n(m.path),r==null||r(m.path)}finally{d(!1)}}}return i.jsxs("div",{className:K("grid gap-2 sm:grid-cols-[minmax(0,1fr)_auto]",a),children:[i.jsx(Kn,{value:t,onChange:m=>n(m.target.value),placeholder:QFn(e),disabled:s||c,className:o}),f?i.jsxs(le,{type:"button",variant:"outline",size:"sm",onClick:()=>{A()},disabled:s||c,className:K("shrink-0",l),"aria-label":e==="directory"?"Browse for directory":"Browse for file",children:[c?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(yb,{className:"h-3.5 w-3.5"}),"Browse…"]}):null]})}const UFn=[{value:"backlog",label:"Backlog"},{value:"planned",label:"Planned"},{value:"in_progress",label:"In Progress"},{value:"completed",label:"Completed"},{value:"cancelled",label:"Cancelled"}],MN="w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_98%,transparent)] px-2.5 py-1.5 text-sm shadow-none outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50";function QPe(){return EP[Math.floor(Math.random()*EP.length)]??EP[0]}function Pne(e){return e.kind==="existing"?`existing:${e.resourceId}`:`new:${e.id}`}function VFn(){return{kind:"new",id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:"",resourceKind:"directory",sourceType:"external",locator:"",description:"",role:"working_set",note:""}}const qFn=/^[a-z][a-z0-9+.-]*:/i;function r$(e,t="file"){const n=e.trim();if(!n||qFn.test(n)||n.startsWith("/")||n.startsWith("\\")||n.startsWith("~")||n.includes("\\"))return!1;const r=n.split("/");return!r.every(s=>s.length>0&&s!=="."&&s!=="..")||r[0]!=="projects"?!1:t==="directory"?r.length>=2:r.length>=3}function KFn(e){return e.trim().split("/").filter(Boolean).at(-1)??e.trim()}function WFn(){const{newProjectOpen:e,closeNewProject:t}=ii(),{selectedOrganizationId:n,selectedOrganization:r}=jr(),{locale:s}=is(),a=Vn(),o=Yr(),[l,c]=h.useState(""),[d,u]=h.useState(""),[f,A]=h.useState("in_progress"),[m,g]=h.useState(QPe),[x,y]=h.useState("folder"),[v,w]=h.useState([]),[k,S]=h.useState(""),[j,C]=h.useState(!1),[N,P]=h.useState([]),[M,E]=h.useState(0),[T,R]=h.useState(!1),[_,D]=h.useState(!1),[U,$]=h.useState(!1),[L,H]=h.useState(""),[X,F]=h.useState(""),Q=h.useRef(null),q=bs("new-project:add-resources"),{data:B}=Me({queryKey:V.goals.list(n),queryFn:()=>LA.list(n),enabled:!!n&&e}),{data:ee}=Me({queryKey:V.organizations.resources(n??"__none__"),queryFn:()=>_n.listResources(n),enabled:!!n&&e}),{data:se}=Me({queryKey:V.organizations.workspaceMentionFiles(n??"__none__",L),queryFn:()=>_n.listWorkspaceMentionFiles(n,{query:L,limit:24}),enabled:!!n&&e&&U}),re=xt({mutationFn:Te=>Mi.create(n,Te)}),ne=xt({mutationFn:async Te=>{if(!n)throw new Error("No organization selected");return f8.uploadImage(n,Te,"projects/drafts")}});function Ae(){E(Te=>Te+1),c(""),u(""),A("in_progress"),g(QPe()),y("folder"),w([]),S(""),C(!1),P([]),H(""),F("")}const Y=new Map((ee??[]).map(Te=>[Te.id,Te])),ce=new Map((ee??[]).filter(Te=>Te.sourceType==="library").map(Te=>[Te.locator,Te])),Oe=new Set(N.filter(Te=>Te.kind==="existing").map(Te=>Te.resourceId)),Fe=new Set(N.flatMap(Te=>{if(Te.kind==="new"&&Te.sourceType==="library")return[Te.locator];if(Te.kind==="existing"){const Be=Y.get(Te.resourceId);return(Be==null?void 0:Be.sourceType)==="library"?[Be.locator]:[]}return[]})),ke=(ee??[]).filter(Te=>!Oe.has(Te.id)),Ne=X.trim().toLowerCase(),xe=Ne?ke.filter(Te=>[Te.name,Te.locator,Te.description??"",b3(Te.sourceType),P2(Te.kind)].some(Be=>Be.toLowerCase().includes(Ne))):ke,fe=(Array.isArray(se==null?void 0:se.entries)?se.entries:[]).filter(Te=>r$(Te.path,Te.isDirectory?"directory":"file")&&!Fe.has(Te.path)),ve=L.trim(),Se=r$(ve)&&!Fe.has(ve)&&!fe.some(Te=>Te.path===ve),ze=N.some(Te=>Te.kind==="new"&&(!Te.name.trim()||!Te.locator.trim()||Te.sourceType==="library"&&!r$(Te.locator,Te.resourceKind)));function ft(Te,Be){P(it=>it.map(lt=>Pne(lt)===Te?Be(lt):lt))}function ie(Te){P(Be=>Be.filter(it=>Pne(it)!==Te))}function me(Te){P(Be=>Be.some(it=>it.kind==="existing"&&it.resourceId===Te.id)?Be:[...Be,{kind:"existing",resourceId:Te.id,role:"reference",note:""}]),$(!1)}function we(Te){const Be=ce.get(Te.path);if(Be){me(Be);return}P(it=>[...it,{kind:"new",id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:Te.displayLabel??Te.name,resourceKind:Te.isDirectory?"directory":"file",sourceType:"library",locator:Te.path,description:"",role:Te.isDirectory?"working_set":"reference",note:""}]),$(!1)}function Xe(Te){const Be=Te.trim();if(!r$(Be))return;const it=ce.get(Be);if(it){me(it);return}P(lt=>[...lt,{kind:"new",id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:KFn(Be),resourceKind:"file",sourceType:"library",locator:Be,description:"",role:"reference",note:""}]),$(!1),H("")}function ge(){P(Te=>[...Te,VFn()]),$(!1)}async function te(){if(!n||!l.trim()||ze)return;const Te=N.filter(it=>it.kind==="existing").map((it,lt)=>({resourceId:it.resourceId,role:it.role,note:it.note.trim()||void 0,sortOrder:lt})),Be=N.filter(it=>it.kind==="new").map((it,lt)=>({name:it.name.trim(),kind:it.resourceKind,sourceType:it.sourceType,locator:it.locator.trim(),description:it.description.trim()||void 0,role:it.role,note:it.note.trim()||void 0,sortOrder:Te.length+lt}));try{const it=await re.mutateAsync({name:l.trim(),description:g0e(d),status:f,color:m,icon:x,...v.length>0?{goalIds:v}:{},...k?{targetDate:k}:{},...Te.length>0?{resourceAttachments:Te}:{},...Be.length>0?{newResources:Be}:{}});a.invalidateQueries({queryKey:V.projects.list(n)}),a.invalidateQueries({queryKey:V.projects.detail(it.id)}),a.invalidateQueries({queryKey:V.organizations.resources(n)}),Ae(),t(),o(`/issues?projectId=${encodeURIComponent(it.id)}`)}catch{}}function G(Te){Te.key==="Enter"&&(Te.metaKey||Te.ctrlKey)&&(Te.preventDefault(),te())}const oe=(B??[]).filter(Te=>v.includes(Te.id)),Ze=(B??[]).filter(Te=>!v.includes(Te.id));return i.jsx(Ps,{open:e,onOpenChange:Te=>{Te||(Ae(),t())},children:i.jsxs(zs,{showCloseButton:!1,className:K("flex max-h-[min(860px,calc(100vh-2rem))] flex-col gap-0 overflow-visible p-0",j?"sm:max-w-3xl":"sm:max-w-xl"),onKeyDown:G,children:[i.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border px-4 py-2.5",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[r&&i.jsx("span",{className:"rounded-[calc(var(--radius-sm)-1px)] bg-muted px-1.5 py-0.5 text-xs font-medium",children:r.name.slice(0,3).toUpperCase()}),i.jsx("span",{className:"text-muted-foreground/60",children:"›"}),i.jsx("span",{children:"New project"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>C(!j),children:j?i.jsx(uE,{className:"h-3.5 w-3.5"}):i.jsx(n3,{className:"h-3.5 w-3.5"})}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{Ae(),t()},children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),i.jsxs("div",{"data-testid":"new-project-dialog-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto overscroll-contain",children:[i.jsx("div",{className:"shrink-0 px-4 pb-2 pt-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(ts,{children:[i.jsx(ys,{asChild:!0,children:i.jsx(qAe,{projectColor:m,projectIcon:x,label:"Choose project identity","data-testid":"new-project-identity-trigger"})}),i.jsx(ns,{align:"start",className:"w-auto p-0",children:i.jsx(GUe,{color:m,icon:x,onColorChange:g,onIconChange:y})})]}),i.jsx("input",{className:"min-w-0 flex-1 bg-transparent text-lg font-semibold outline-none placeholder:text-muted-foreground/50",placeholder:"Project name",value:l,onChange:Te=>c(Te.target.value),onKeyDown:Te=>{var Be;Te.key==="Tab"&&!Te.shiftKey&&(Te.preventDefault(),(Be=Q.current)==null||Be.focus())},autoFocus:!0})]})}),i.jsx("div",{className:"px-4 pb-2",children:i.jsx(ku,{ref:Q,engine:"codemirror",documentIdentity:`new-project:${M}`,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:K("text-sm text-muted-foreground",j?"min-h-[200px]":"min-h-[120px]"),imageUploadHandler:async Te=>(await ne.mutateAsync(Te)).contentPath})}),i.jsxs("div",{className:"space-y-3 border-t border-border px-4 py-3",children:[i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"text-sm font-medium",children:"Project Context"}),i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx("button",{type:"button",className:"inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":"About project context",children:i.jsx(Vfe,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{side:"top",sideOffset:8,className:"max-w-[260px] px-3 py-2 text-xs leading-5",children:_i("projectContextHelp",s)})]})]}),i.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:i.jsxs(ts,{open:U,onOpenChange:Te=>{$(Te),Te||(H(""),F(""))},children:[i.jsx(ys,{asChild:!0,children:i.jsxs(le,{type:"button",size:"xs",className:"h-7 rounded-[calc(var(--radius-sm)-1px)] px-2",disabled:!n,children:[i.jsx(Zr,{className:"mr-1.5 h-3 w-3"}),"Add resources"]})}),i.jsxs(ns,{className:"z-[60] flex max-h-[min(420px,calc(100dvh-2rem),var(--radix-popover-content-available-height))] w-[min(20rem,calc(100vw-2rem))] flex-col overflow-hidden p-1",align:"end",collisionPadding:16,disablePortal:!0,sideOffset:8,children:[i.jsxs("button",{type:"button",className:"flex w-full shrink-0 items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:ge,children:[i.jsx(qm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{children:[i.jsx("span",{className:"block text-xs font-medium",children:"Create external resource"}),i.jsx("span",{className:"block text-[11px] text-muted-foreground",children:"Add a URL, local path, repo path, or connector reference."})]})]}),i.jsx("div",{className:"mx-2 my-1 h-px shrink-0 bg-border"}),i.jsx("div",{className:"px-2 pb-1.5 pt-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:_i("addFromLibrary",s)}),i.jsx("div",{className:"px-2 pb-2",children:i.jsx("input",{value:L,onChange:Te=>H(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"&&Se&&(Te.preventDefault(),Xe(ve))},className:"h-7 w-full rounded-[calc(var(--radius-sm)-1px)] border border-border bg-background px-2 text-xs outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",placeholder:_i("searchLibraryPlaceholder",s)})}),i.jsxs("div",{ref:q,"data-testid":"new-project-add-resources-popover-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1",children:[fe.length===0?i.jsx("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:L.trim()?_i("noMatchingLibraryFiles",s):_i("noLibraryFiles",s)}):fe.map(Te=>{const Be=Te.isDirectory?wo:Fi;return i.jsxs("button",{type:"button",className:"flex w-full items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:()=>we(Te),children:[i.jsx(Be,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:Te.displayLabel??Te.name}),i.jsx("span",{className:"block truncate font-mono text-[11px] text-muted-foreground",children:Te.path})]})]},Te.path)}),Se?i.jsxs("button",{type:"button",className:"mt-1 flex w-full items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:()=>Xe(ve),children:[i.jsx(Fi,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:_i("useThisLibraryPath",s)}),i.jsx("span",{className:"block truncate font-mono text-[11px] text-muted-foreground",children:ve})]})]}):null,i.jsx("div",{className:"my-1 h-px bg-border"}),i.jsx("div",{className:"px-2 pb-1.5 pt-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:"Existing resources"}),i.jsx("div",{className:"px-2 pb-2",children:i.jsx("input",{value:X,onChange:Te=>F(Te.target.value),className:"h-7 w-full rounded-[calc(var(--radius-sm)-1px)] border border-border bg-background px-2 text-xs outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",placeholder:"Search existing resources"})}),xe.length===0?i.jsx("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:X.trim()?"No matching resources.":"No unattached resources available."}):xe.map(Te=>i.jsxs("button",{type:"button",className:"flex w-full items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:()=>me(Te),children:[i.jsx(qm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:Te.name}),i.jsxs("span",{className:"block truncate text-[11px] text-muted-foreground",children:[b3(Te.sourceType)," · ",P2(Te.kind)," · ",Te.locator]})]})]},Te.id))]})]})]})})]}),N.length>0?i.jsx("div",{className:"space-y-3",children:N.map(Te=>{const Be=Pne(Te),it=Te.kind==="existing"?Y.get(Te.resourceId)??null:null;return i.jsxs("div",{className:"space-y-3 rounded-[var(--radius-sm)] border border-border/80 bg-[color:color-mix(in_oklab,var(--surface-inset)_52%,var(--surface-elevated))] px-3 py-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"space-y-0.5 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2 text-sm font-medium",children:Te.kind==="existing"?i.jsxs(i.Fragment,{children:[i.jsx(qm,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:(it==null?void 0:it.name)??"Missing resource"})]}):Te.sourceType==="library"?i.jsxs(i.Fragment,{children:[i.jsx(lE,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:Te.name.trim()||Te.locator})]}):i.jsxs(i.Fragment,{children:[i.jsx(wo,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{children:Te.name.trim()||"New resource"})]})}),i.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:Te.kind==="existing"?it?`${b3(it.sourceType)} · ${P2(it.kind)} · ${it.locator}`:"This resource is no longer available.":Te.sourceType==="library"?`Library · ${P2(Te.resourceKind)} · ${Te.locator}`:"Created as an external resource and attached to this project on submit."})]}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>ie(Be),children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]}),Te.kind==="new"&&Te.sourceType==="external"?i.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Name"}),i.jsx("input",{value:Te.name,onChange:lt=>ft(Be,Ue=>({...Ue,name:lt.target.value})),className:MN,placeholder:"Rudder repo"})]}),i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Kind"}),i.jsx("select",{value:Te.resourceKind,onChange:lt=>ft(Be,Ue=>({...Ue,resourceKind:lt.target.value})),className:K(MN,"h-8"),children:dft.map(lt=>i.jsx("option",{value:lt.value,children:lt.label},lt.value))})]}),i.jsxs("label",{className:"space-y-1 md:col-span-2",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Locator"}),i.jsx(q_,{kind:Te.resourceKind,value:Te.locator,onChange:lt=>ft(Be,Ue=>({...Ue,locator:lt})),onPickedPath:lt=>ft(Be,Ue=>{const mt=Ue;return{...mt,locator:lt,name:mt.name.trim()?mt.name:uft(lt)}}),inputClassName:K(MN,"h-8"),buttonClassName:"h-8 rounded-[calc(var(--radius-sm)-1px)]"})]}),i.jsxs("label",{className:"space-y-1 md:col-span-2",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Description"}),i.jsx("textarea",{value:Te.description,onChange:lt=>ft(Be,Ue=>({...Ue,description:lt.target.value})),className:K(MN,"min-h-[72px] resize-y py-2"),placeholder:"What this resource contains and when agents should use it."})]})]}):null,i.jsxs("label",{className:"block space-y-1",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Project note"}),i.jsx("input",{value:Te.note,onChange:lt=>ft(Be,Ue=>({...Ue,note:lt.target.value})),className:MN,placeholder:"Optional guidance specific to this project"})]}),Te.kind==="new"&&(!Te.name.trim()||!Te.locator.trim())?i.jsx("p",{className:"text-[11px] text-amber-600 dark:text-amber-300",children:"New resources need both a name and a locator before you can create the project."}):null]},Be)})}):null]})]}),i.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-1.5 border-t border-border px-4 py-2",children:[i.jsxs(ts,{open:T,onOpenChange:R,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{type:"button",className:"inline-flex items-center rounded-[calc(var(--radius-sm)-1px)] transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:i.jsx(Qs,{status:f})})}),i.jsx(ns,{className:"w-40 p-1",align:"start",children:UFn.map(Te=>i.jsx("button",{className:K("flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-xs hover:bg-accent/50",Te.value===f&&"bg-accent"),onClick:()=>{A(Te.value),R(!1)},children:Te.label},Te.value))})]}),oe.map(Te=>i.jsxs("span",{className:"inline-flex items-center gap-1 rounded-[calc(var(--radius-sm)-1px)] border border-border px-2 py-1 text-xs",children:[i.jsx(ud,{className:"h-3 w-3 text-muted-foreground"}),i.jsx("span",{className:"max-w-[160px] truncate",children:Te.title}),i.jsx("button",{className:"text-muted-foreground hover:text-foreground",onClick:()=>w(Be=>Be.filter(it=>it!==Te.id)),"aria-label":`Remove goal ${Te.title}`,type:"button",children:i.jsx(Is,{className:"h-3 w-3"})})]},Te.id)),i.jsxs(ts,{open:_,onOpenChange:D,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] border border-border px-2 py-1 text-xs transition-colors hover:bg-accent/50 disabled:opacity-60",disabled:oe.length>0&&Ze.length===0,children:[oe.length>0?i.jsx(Zr,{className:"h-3 w-3 text-muted-foreground"}):i.jsx(ud,{className:"h-3 w-3 text-muted-foreground"}),oe.length>0?"+ Goal":"Goal"]})}),i.jsxs(ns,{className:"w-56 p-1",align:"start",children:[oe.length===0&&i.jsx("button",{className:"flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-xs text-muted-foreground hover:bg-accent/50",onClick:()=>D(!1),children:"No goal"}),Ze.map(Te=>i.jsx("button",{className:"flex w-full items-center gap-2 truncate rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-xs hover:bg-accent/50",onClick:()=>{w(Be=>[...Be,Te.id]),D(!1)},children:Te.title},Te.id)),oe.length>0&&Ze.length===0&&i.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All goals already selected."})]})]}),i.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] border border-border px-2 py-1 text-xs",children:[i.jsx(UB,{className:"h-3 w-3 text-muted-foreground"}),i.jsx("input",{type:"date",className:"bg-transparent outline-none text-xs w-24",value:k,onChange:Te=>S(Te.target.value),placeholder:"Target date"})]})]}),i.jsxs("div",{className:"flex shrink-0 items-center justify-between border-t border-border px-4 py-2.5",children:[re.isError?i.jsx("p",{className:"text-xs text-destructive",children:"Failed to create project."}):i.jsx("span",{className:"text-xs text-muted-foreground",children:N.length>0?`${N.length} context item${N.length===1?"":"s"} queued`:""}),i.jsx(le,{size:"sm",disabled:!l.trim()||re.isPending||ze,onClick:()=>void te(),children:re.isPending?"Creating…":"Create project"})]})]})})}function fde(){if(typeof Notification>"u")return"unsupported";const e=Notification.permission;return e==="granted"||e==="denied"||e==="default"?e:"unsupported"}async function fft(){if(typeof Notification>"u"||typeof Notification.requestPermission!="function")return"unsupported";if(Notification.permission==="granted"||Notification.permission==="denied")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"||e==="denied"||e==="default"?e:"unsupported"}const UPe="rudder:issue-navigation",ZFn=new Set(["assigned","pinned","starred","recent"]);function Aft(e){return e?`${UPe}:${e}`:UPe}function hft(e){const t=typeof(e==null?void 0:e.scope)=="string"&&ZFn.has(e.scope)?e.scope==="starred"?"pinned":e.scope:void 0,n=typeof(e==null?void 0:e.projectId)=="string"&&e.projectId.trim().length>0?e.projectId:void 0;return{scope:t,projectId:n}}function HFn(e){const t=hft(e),n=new URLSearchParams;t.projectId?n.set("projectId",t.projectId):t.scope&&n.set("scope",t.scope);const r=n.toString();return r?`/issues?${r}`:"/issues"}function XFn(e){if(typeof window>"u")return"/issues";try{const t=window.localStorage.getItem(Aft(e));if(!t)return"/issues";const n=JSON.parse(t);return HFn(n)}catch{return"/issues"}}function GFn(e,t){if(!(typeof window>"u"))try{const n=hft(t);window.localStorage.setItem(Aft(e),JSON.stringify(n))}catch{}}const Ade="rudder:messenger-scroll-to-unread";let oq=0,hde=0;function VPe(){return oq>hde?oq:0}function Ine(e){hde=Math.max(hde,e)}function YFn(){if(typeof document>"u")return;oq+=1;const e=()=>{document.dispatchEvent(new CustomEvent(Ade,{detail:{requestId:oq}}))};if(e(),typeof requestAnimationFrame=="function"){requestAnimationFrame(e);return}setTimeout(e,0)}const JFn={desktopInboxNotifications:!0},eBn="/rudder-logo.png";function tBn(e){return/^\/(?:messenger|chat)(?:\/|$)/.test(e)}function nBn(e){if(!e||typeof window>"u")return null;const t=window.navigator.userAgent;return/Mac/i.test(t)?"macos":/Windows/i.test(t)?"windows":"other"}const Tne=["h-9 w-9 translate-x-[var(--primary-rail-item-shift,0.25rem)] rounded-lg border shadow-[0_6px_18px_-16px_rgba(15,23,42,0.55)] backdrop-blur-[22px]","border-[color:color-mix(in_oklab,var(--sidebar-border)_76%,white)]","bg-[color:color-mix(in_oklab,var(--sidebar)_72%,white)]","text-[color:color-mix(in_oklab,var(--sidebar-foreground)_88%,var(--sidebar))]","dark:border-white/20 dark:bg-white/10 dark:text-white/78"].join(" ");function qPe({to:e,label:t,icon:n,tourTarget:r,badge:s,badgeTone:a="default",badgeTestId:o,active:l,onDoubleClick:c,onContextMenu:d,localAppIdentity:u,end:f}){return i.jsxs(Pj,{to:e,end:f,"aria-current":l?"page":void 0,"data-tour-target":r,"data-tour-spotlight":r?"compact-rail":void 0,onDoubleClick:c,onContextMenu:d,className:({isActive:A})=>K("relative z-10 flex min-h-[56px] w-[var(--primary-rail-item-width,66px)] translate-x-[var(--primary-rail-item-shift,0.25rem)] flex-col items-center justify-center gap-1 rounded-[var(--radius-sm)] px-1 py-2 text-[9px] font-medium leading-[1.05] transition-colors",l??A?"text-white":["text-[color:color-mix(in_oklab,var(--sidebar-foreground)_86%,var(--sidebar))]","hover:bg-[color:color-mix(in_oklab,var(--sidebar)_58%,white)]","hover:text-[color:var(--sidebar-foreground)]","dark:text-white/74 dark:hover:bg-white/[0.07] dark:hover:text-white"].join(" ")),children:[i.jsxs("span",{className:"relative",children:[u?i.jsx(Z6,{className:"h-[17px] w-[17px] rounded-[4px]",identity:u,testId:"primary-rail-local-app-icon"}):i.jsx(n,{className:"h-[17px] w-[17px]"}),s!=null&&s>0?i.jsx("span",{"data-testid":o,className:K("absolute -right-2 -top-2 rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none",a==="danger"?"bg-red-500 text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]":"bg-primary text-primary-foreground"),children:s>99?"99+":s}):null]}),i.jsx("span",{className:"block w-full min-w-0 truncate text-center",title:t,children:t})]})}function rBn({onOpenSettings:e,onWarmSettings:t}){var ce,Oe,Fe;const{t:n,locale:r}=is(),{openNewIssue:s,openNewAgent:a,openNewProject:o}=ii(),{setSidebarOpen:l}=jc(),{selectedOrganizationId:c}=jr(),d=Vn(),u=ihe(c),[f,A]=h.useState(null),m=Me({queryKey:V.instance.notificationSettings,queryFn:()=>Ha.getNotifications(),staleTime:Do}),x=((Oe=(ce=Me({queryKey:V.health,queryFn:()=>rA.get(),staleTime:Do}).data)==null?void 0:ce.features)==null?void 0:Oe.experimentalSitesEnabled)===!0,y=Me({queryKey:V.messenger.primaryRailPins(c??"__none__"),queryFn:()=>Ks.listSavedViews(c,{visibility:"visible",primaryRailPinned:!0,limit:100}),enabled:!!(c&&x)}),v=br(),w=Yr(),k=fl(v.pathname),S=tBn(k),j=Pn()!==null,C=nBn(j),N=h.useRef(null),P=h.useRef(c),M=h.useRef(!1),E=/^\/(?:dashboard|calendar|org|projects|heartbeats|goals|skills|costs|activity)(?:\/|$)/.test(k),T=XFn(c),R=Yw(c,"messenger","/messenger"),_=Yw(c,"issues",T),D=Yw(c,"agents","/agents"),U=Yw(c,"library","/library"),$=Yw(c,"organization","/dashboard"),L=Yw(c,"automations","/automations"),H=Yw(c,"apps","/apps"),X=[{key:"messenger",to:R,label:"Messenger",icon:pa,badge:u.inbox,badgeTone:"danger",badgeTestId:"rail-badge-messenger",active:/^\/(?:messenger|chat)(?:\/|$)/.test(k)},{key:"issues",to:_,label:"Issue",icon:xS,active:/^\/issues(?:\/|$)/.test(k)},{key:"agents",to:D,label:"Agents",icon:iIt,active:/^\/agents(?:\/|$)/.test(k)},{key:"library",to:U,label:r==="zh-CN"?"文档":"Library",icon:lE,active:/^\/(?:library|resources|workspaces)(?:\/|$)/.test(k)},...x?[{key:"apps",to:H,label:"Apps",icon:sA,active:/^\/apps(?:\/|$)/.test(k)&&!/^\/apps\/saved\/[^/]+(?:\/|$)/.test(k)}]:[],{key:"organization",to:$,label:"Organization",icon:rNt,active:E},{key:"automations",to:L,label:"Automations",icon:cw,active:/^\/automations(?:\/|$)/.test(k)}],F=x?(((Fe=y.data)==null?void 0:Fe.items)??[]).filter(ke=>ke.targetPayload.kind==="local_app").map(ke=>({key:`saved-view:${ke.id}`,to:Rce(ke.id),label:ke.title,icon:pa,localAppIdentity:ke.targetPayload,active:k===Rce(ke.id)})):[],Q=X.findIndex(ke=>ke.active),q=F.findIndex(ke=>ke.active),B=Q>=0?Q:q>=0?X.length+q:-1,ee=B>=0?{"--motion-rail-active-index":B,"--motion-rail-active-offset":q>=0?`calc(${B} * (var(--motion-rail-item-height) + var(--motion-rail-item-gap)) + 0.6875rem)`:`calc(${B} * (var(--motion-rail-item-height) + var(--motion-rail-item-gap)))`}:void 0,se=h.useCallback(()=>{(u.inbox??0)<=0||(l(!0),YFn())},[u.inbox,l]),re=xt({mutationFn:async()=>c?Ks.dismissUnreads(c):{dismissedCount:0,dismissedThreadKeys:[]},onSuccess:async()=>{c&&await Promise.all([d.invalidateQueries({queryKey:V.sidebarBadges(c)}),d.invalidateQueries({queryKey:V.messenger.threadPreview(c)}),d.invalidateQueries({queryKey:V.messenger.threads(c)}),d.invalidateQueries({queryKey:V.messenger.threadPages(c)}),d.invalidateQueries({queryKey:V.messenger.customGroups(c)}),d.invalidateQueries({queryKey:V.messenger.issues(c)}),d.invalidateQueries({queryKey:V.messenger.approvals(c)}),d.invalidateQueries({queryKey:["messenger",c,"system"]}),d.invalidateQueries({queryKey:["chats",c]})])}}),ne=h.useCallback(ke=>{ke.preventDefault(),A({left:ke.clientX,top:ke.clientY})},[]),Ae=h.useCallback(()=>{!c||re.isPending||re.mutate()},[re,c]);h.useEffect(()=>{if(m.isLoading)return;P.current!==c&&(P.current=c,N.current=null);const ke=Pn();let Ne=!1;const xe=ke,ae=m.data??JFn;async function fe(){const ve=Math.max(0,u.inbox??0);xe&&await xe.setBadgeCount(ae.desktopInboxNotifications?ve:0).catch(ie=>{console.warn("[rudder-ui] failed to sync desktop dock badge count",ie)});let Se=fde();if(xe===null&&u.isReady&&ve>0&&Se==="default"&&!M.current&&ae.desktopInboxNotifications&&!S&&(M.current=!0,Se=await fft()),Ne)return;const ft=N.current;if(ft!=null&&u.isReady&&ve>ft&&ae.desktopInboxNotifications&&!S){const{title:ie,body:me}=u.notificationContent;if(xe)await xe.showNotification({title:ie,body:me}).catch(we=>{console.warn("[rudder-ui] failed to trigger desktop inbox notification",we)});else if(Se==="granted"&&typeof Notification<"u")try{const we=new Notification(ie,{body:me,icon:eBn});we.onclick=()=>window.focus()}catch(we){console.warn("[rudder-ui] failed to trigger browser inbox notification",we)}}u.isReady&&(N.current=ve)}return fe(),()=>{Ne=!0}},[u.inbox,u.isReady,u.notificationContent,m.data,m.isLoading,c,S]);function Y(){document.dispatchEvent(new CustomEvent("rudder:open-command-palette",{detail:{source:"primary-rail"}}))}return i.jsxs("aside",{"data-testid":"primary-rail","data-tour-target":"primary-rail","data-desktop-shell":j?"true":void 0,"data-desktop-platform":C??void 0,className:K("my-2 flex h-[calc(100%-1rem)] shrink-0 flex-col items-center py-1.5 text-[color:color-mix(in_oklab,var(--foreground)_78%,white)]",C==="windows"?"ml-1 mr-1 w-[52px] [--primary-rail-item-shift:0px] [--primary-rail-item-width:52px]":j?"ml-3 mr-1 w-[40px]":"ml-2 mr-3 px-5 w-[50px]"),children:[i.jsxs("div",{className:"flex w-full flex-col items-center gap-4",children:[i.jsx("div",{className:"translate-x-[var(--primary-rail-item-shift,0.25rem)]",children:i.jsx(che,{compact:!0})}),i.jsx(le,{variant:"ghost",size:"icon-sm",className:Tne,onClick:Y,title:n("common.search"),"aria-label":n("common.search"),children:i.jsx(Fl,{className:"h-4 w-4"})}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{variant:"ghost",size:"icon-sm",className:K(Tne,"rail-create-menu-trigger"),"data-tour-target":"create-menu",title:n("common.create"),"aria-label":n("common.create"),children:i.jsx(Zr,{className:"h-4 w-4"})})}),i.jsxs(Ri,{side:"right",align:"start",className:"rail-create-menu-content morph-popover morph-popover--from-left glass-popover w-48 text-foreground",children:[i.jsxs(Xt,{onClick:()=>w("/messenger/chat"),children:[i.jsx(F9t,{className:"h-4 w-4"}),"Create new chat"]}),i.jsxs(Xt,{onClick:()=>s(),children:[i.jsx(xS,{className:"h-4 w-4"}),"Create new issue"]}),i.jsxs(Xt,{onClick:()=>a(),children:[i.jsx(Ul,{className:"h-4 w-4"}),"Create new agent"]}),i.jsxs(Xt,{onClick:()=>o(),children:[i.jsx(oE,{className:"h-4 w-4"}),"Create new project"]})]})]})]}),i.jsxs("nav",{className:"motion-rail-nav scrollbar-auto-hide mt-2.5 flex min-h-0 w-[calc(var(--primary-rail-item-width,66px)+var(--primary-rail-item-shift,0.25rem)+var(--primary-rail-item-shift,0.25rem)+0.625rem)] flex-1 flex-col items-center gap-0.5 overflow-y-auto",style:ee,"data-active-index":B>=0?B:void 0,"aria-label":"Primary navigation",children:[B>=0?i.jsx("span",{"data-testid":"primary-rail-active-indicator",className:"motion-rail-active-indicator","aria-hidden":"true"}):null,X.map(ke=>i.jsx(qPe,{to:ke.to,label:ke.label,icon:ke.icon,tourTarget:ke.key==="issues"?"issues-nav":void 0,badge:ke.badge,badgeTone:ke.badgeTone,badgeTestId:ke.badgeTestId,active:ke.active,onDoubleClick:ke.key==="messenger"?se:void 0,onContextMenu:ke.key==="messenger"?ne:void 0,localAppIdentity:ke.localAppIdentity,end:ke.key==="apps"?!0:void 0},ke.key)),F.length>0?i.jsx("span",{className:"my-1 h-px w-7 shrink-0 bg-white/10","aria-hidden":"true"}):null,F.map(ke=>i.jsx(qPe,{to:ke.to,label:ke.label,icon:ke.icon,active:ke.active,localAppIdentity:ke.localAppIdentity},ke.key))]}),i.jsxs(Ei,{open:f!==null,onOpenChange:ke=>{ke||A(null)},children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-hidden":"true",tabIndex:-1,className:"fixed h-px w-px opacity-0",style:{left:(f==null?void 0:f.left)??-1e3,top:(f==null?void 0:f.top)??-1e3}})}),i.jsx(Ri,{side:"right",align:"start",className:"glass-popover w-52 text-foreground",onContextMenu:ke=>ke.preventDefault(),children:i.jsxs(Xt,{disabled:!c||re.isPending||(u.inbox??0)<=0,onClick:Ae,children:[i.jsx(cT,{className:"h-4 w-4"}),"Dismiss Unreads"]})})]}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",className:K("settings-entry-button flex items-center justify-center transition-[transform,background-color,border-color,box-shadow,color]",Tne),onPointerEnter:t,onFocus:t,onClick:e,"aria-label":n("common.systemSettings"),title:n("common.systemSettings"),"data-settings-trigger":"true",children:i.jsx(Ix,{className:"h-4 w-4"})})]})}const mft="rudder.productTour.completed.v1",b2e="rudder.productTour.pendingAfterSetup.v1",Ty=[{id:"workspace",target:"[data-tour-target='primary-rail']",checklistKey:"productTour.checklist.workspace",titleKey:"productTour.step.workspace.title",bodyKey:"productTour.step.workspace.body"},{id:"create",target:"[data-tour-target='create-menu']",checklistKey:"productTour.checklist.create",titleKey:"productTour.step.create.title",bodyKey:"productTour.step.create.body"},{id:"issues",target:"[data-tour-target='issues-nav']",checklistKey:"productTour.checklist.issues",titleKey:"productTour.step.issues.title",bodyKey:"productTour.step.issues.body"},{id:"inspect",target:"[data-tour-target='workspace-main']",checklistKey:"productTour.checklist.inspect",titleKey:"productTour.step.inspect.title",bodyKey:"productTour.step.inspect.body"},{id:"settings",target:"[data-settings-trigger='true']",checklistKey:"productTour.checklist.settings",titleKey:"productTour.step.settings.title",bodyKey:"productTour.step.settings.body"}],jk=16,sBn=96,iBn=48,d7=220,Ck=214,aBn=52,oBn=232,C7=16;function pft(){return typeof document>"u"?!1:document.documentElement.classList.contains("desktop-shell-macos")}function gft(){return pft()?{left:sBn,top:iBn,right:jk,bottom:jk}:{left:jk,top:jk,right:jk,bottom:jk}}function lBn(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(mft)==="true"}catch{return!0}}function xft(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(b2e)==="true"}catch{return!1}}function cBn(){if(!(typeof window>"u"))try{window.localStorage.setItem(b2e,"true")}catch{}}function dBn(){if(!(typeof window>"u"))try{window.localStorage.setItem(mft,"true"),window.localStorage.removeItem(b2e)}catch{}}function KPe(){const e=Math.min(520,Math.max(260,window.innerWidth*.48)),t=Math.min(220,Math.max(130,window.innerHeight*.26));return{left:Math.round((window.innerWidth-e)/2),top:Math.round((window.innerHeight-t)/2),width:Math.round(e),height:Math.round(t)}}function uBn(e){const t=document.querySelector(e);if(!t)return KPe();const n=t.getBoundingClientRect();if(n.width<=0||n.height<=0)return KPe();const r=t.dataset.tourSpotlight==="compact-rail",s=r?Math.min(n.width,aBn):n.width,a=r?n.left+(n.width-s)/2:n.left,o=r?4:6;return{left:Math.max(8,Math.round(a-o)),top:Math.max(8,Math.round(n.top-o)),width:Math.round(s+o*2),height:Math.round(n.height+o*2)}}function CP(e,t,n){return Math.max(t,Math.min(n,e))}function fBn(e,t,n=8){return e.left<t.left+t.width+n&&e.left+e.width+n>t.left&&e.top<t.top+t.height+n&&e.top+e.height+n>t.top}function ABn(e){const t=gft(),n=Math.min(360,Math.max(292,window.innerWidth-32)),r=Math.max(t.left,window.innerWidth-n-t.right),s=e.left+e.width+C7+n<=window.innerWidth-t.right,a=e.left-C7-n>=t.left,o=s?e.left+e.width+C7:a?e.left-C7-n:Math.max(t.left,Math.min(r,e.left)),l=Math.max(t.top,Math.min(window.innerHeight-250-t.bottom,e.top));return{width:n,left:o,top:l,height:oBn}}function hBn(e){const t=gft();if(pft())return{top:t.top,right:t.right};const n=Math.max(t.left,window.innerWidth-d7-t.right),r=Math.max(t.top,window.innerHeight-Ck-t.bottom),s=Math.max(t.top,20),a=[{left:n,top:s,width:d7,height:Ck},{left:Math.max(t.left,20),top:s,width:d7,height:Ck},{left:CP(e.left,t.left,n),top:CP(e.top+e.height+C7,t.top,r),width:d7,height:Ck},{left:CP(e.left,t.left,n),top:CP(e.top-Ck-C7,t.top,r),width:d7,height:Ck}],o=a.find(l=>!fBn(l,e))??a[0];return{left:Math.round(o.left),top:Math.round(o.top)}}function mBn(){const{t:e}=is(),{productTourOpen:t,closeProductTour:n}=ii(),r=Yr(),[s,a]=h.useState(0),[o,l]=h.useState(null),c=h.useRef(null),d=h.useRef(!1),u=Ty[s]??Ty[0],f=s===Ty.length-1,A=h.useCallback(()=>{l(uBn(u.target))},[u.target]);h.useEffect(()=>{t&&(a(0),d.current=!1)},[t]),h.useEffect(()=>{if(!t)return;A();const v=window.requestAnimationFrame(A);return window.addEventListener("resize",A),window.addEventListener("scroll",A,!0),()=>{window.cancelAnimationFrame(v),window.removeEventListener("resize",A),window.removeEventListener("scroll",A,!0)}},[t,A]),h.useEffect(()=>{var v;t&&((v=c.current)==null||v.focus())},[t,s]);const m=h.useMemo(()=>o?ABn(o):null,[o]),g=h.useMemo(()=>m?hBn(m):null,[m]),x=h.useCallback(()=>{const v=xft();dBn(),n(),v&&!d.current&&r("/issues")},[n,r]),y=h.useCallback(v=>{const w=CP(v,0,Ty.length-1);(Ty[w]??Ty[0]).id==="issues"&&(d.current=!0,r("/issues")),a(w)},[r]);return!t||!o||!m||!g?null:i.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-labelledby":"product-tour-title",tabIndex:-1,className:"fixed inset-0 z-[90] outline-none",onKeyDown:v=>{v.key==="Escape"&&(v.preventDefault(),x())},children:[i.jsx("div",{"aria-hidden":"true","data-testid":"product-tour-spotlight",className:"pointer-events-none fixed rounded-[10px] border-2 border-[color:color-mix(in_oklab,var(--accent-base)_72%,white)] shadow-[0_0_0_9999px_rgb(18_17_15/0.68),0_0_0_5px_color-mix(in_oklab,var(--accent-base)_18%,transparent)]",style:{left:o.left,top:o.top,width:o.width,height:o.height}}),i.jsxs("aside",{"data-testid":"product-tour-checklist",className:"fixed hidden rounded-[var(--radius-md)] border border-[color:color-mix(in_oklab,var(--border-strong)_72%,transparent)] bg-popover/98 p-3 text-popover-foreground shadow-[var(--shadow-lg)] backdrop-blur md:block",style:{...g,width:d7},children:[i.jsx("div",{className:"mb-2 text-[13px] font-semibold text-foreground",children:e("productTour.checklist.title")}),i.jsx("div",{className:"space-y-0.5",children:Ty.map((v,w)=>i.jsxs("div",{className:K("grid min-h-8 grid-cols-[18px_minmax(0,1fr)] items-center gap-2 border-t border-[color:color-mix(in_oklab,var(--border-soft)_76%,transparent)] py-1.5 text-[12px]",w===0&&"border-t-0",w===s?"text-foreground":"text-muted-foreground"),children:[w<s?i.jsx(Zs,{className:"h-3.5 w-3.5 rounded-full bg-[color:var(--accent-base)] p-0.5 text-primary-foreground"}):i.jsx(sE,{className:K("h-3.5 w-3.5",w===s&&"text-[color:var(--accent-strong)]")}),i.jsx("span",{children:e(v.checklistKey)})]},v.id))})]}),i.jsxs("section",{"data-testid":"product-tour-callout",className:"fixed rounded-[var(--radius-md)] border border-[color:color-mix(in_oklab,var(--border-strong)_74%,transparent)] bg-popover/98 p-3.5 text-popover-foreground shadow-[var(--shadow-lg)] backdrop-blur",style:{left:m.left,top:m.top,width:m.width},children:[i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"mb-1 text-[11px] text-muted-foreground",children:e("productTour.stepCounter",{current:s+1,total:Ty.length})}),i.jsx("h2",{id:"product-tour-title",className:"text-[15px] font-semibold leading-5 text-foreground",children:e(u.titleKey)})]}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",className:"-mr-1 -mt-1 text-muted-foreground",onClick:x,"aria-label":e("productTour.skip"),title:e("productTour.skip"),children:i.jsx(Is,{className:"h-4 w-4"})})]}),i.jsx("p",{className:"mt-2 text-[13px] leading-5 text-muted-foreground",children:e(u.bodyKey)}),i.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[i.jsxs(le,{type:"button",variant:"outline",size:"sm",className:"h-8",disabled:s===0,onClick:()=>y(s-1),children:[i.jsx(Tj,{className:"h-4 w-4"}),e("productTour.back")]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-8",onClick:x,children:e("productTour.skip")}),i.jsxs(le,{type:"button",size:"sm",className:"h-8",onClick:()=>{if(f){x();return}y(s+1)},children:[e(f?"productTour.finish":"productTour.next"),f?i.jsx(Zs,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})]})]})]})]})]})}function y2e(e){return`/${e.trim()}/organization/settings`}function pBn(e){const t=Pn();if(t){(t.forceOpenExternal??t.openExternal)(e);return}window.open(e,"_blank","noopener,noreferrer")}function gBn({href:e,label:t,variant:n}){return i.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",onClick:r=>{r.preventDefault(),pBn(e)},className:IE({variant:n,active:!1}),children:[i.jsx(nE,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"flex-1 truncate",children:t}),i.jsx(Ja,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80","aria-hidden":"true"})]})}function mde({showOrganizationSwitcher:e=!0,showBackButton:t=!0,variant:n="panel"}){const r=bs("rudder:sidebar-scroll:settings"),{t:s}=is(),a=Yr(),o=br(),{isMobile:l,setSidebarOpen:c}=jc(),{organizations:d}=jr(),{viewedOrganizationId:u}=th(),{data:f}=Me({queryKey:V.access.currentBoardAccess,queryFn:()=>bc.getCurrentBoardAccess(),retry:!1}),{data:A}=Me({queryKey:V.plugins.all,queryFn:()=>bo.list()}),{data:m}=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1}),g=(f==null?void 0:f.isInstanceAdmin)===!0,x=(m==null?void 0:m.deploymentMode)==="local_trusted",y=Hj(o.state),v=n==="modal",[w,k]=h.useState(!v),S=h.useMemo(()=>v&&!w?[]:GVe(d.filter(C=>C.status!=="archived")),[v,d,w]);h.useEffect(()=>{if(!v){k(!0);return}k(!1);const C=window.setTimeout(()=>k(!0),250);return()=>window.clearTimeout(C)},[v]);function j(C){a(y2e(Oc(C)),y?{state:y}:void 0),l&&c(!1)}return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:K("flex min-h-0 shrink-0 flex-col",v?"settings-modal-sidebar h-full w-[min(84vw,240px)] md:w-[184px]":"workspace-context-sidebar w-[248px]"),children:[v?null:i.jsxs("div",{className:"flex shrink-0 flex-col gap-2 border-b panel-divider px-3 py-3",children:[i.jsxs("div",{className:"flex items-center gap-2 px-2.5 text-muted-foreground",children:[i.jsx(Ix,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"text-[13px] font-semibold tracking-[-0.01em] text-foreground",children:s("common.systemSettings")})]}),e?i.jsx(che,{}):null,t?i.jsx(le,{variant:"ghost",className:"h-9 w-full justify-start gap-2 rounded-[var(--radius-md)] px-2.5 text-[13px] font-medium text-muted-foreground hover:text-foreground",asChild:!0,children:i.jsxs(sn,{to:Qc,children:[i.jsx(Kx,{className:"h-4 w-4"}),s("common.backToWorkspace")]})}):null]}),i.jsxs("nav",{ref:r,className:K("scrollbar-auto-hide flex min-h-0 flex-1 flex-col overflow-y-auto",v?"gap-4 px-3 py-5":"gap-5 px-3 py-3"),children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.personal")}),i.jsx(sd,{to:"/instance/settings/profile",state:y,label:s("common.profile"),icon:wBe,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/shortcuts",state:y,label:s("common.shortcuts"),icon:jBe,end:!0,variant:v?"compact":"default"})]}),g?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.desktopApp")}),i.jsx(sd,{to:"/instance/settings/general",state:y,label:s("common.general"),icon:Ej,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/appearance",state:y,label:s("general.appearance.title"),icon:ZK,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/experimental",state:y,label:s("common.experimental"),icon:lBe,end:!0,variant:v?"compact":"default"}),x?i.jsx(sd,{to:"/instance/settings/browser",state:y,label:s("common.browser"),icon:up,end:!0,variant:v?"compact":"default"}):null,i.jsx(sd,{to:"/instance/settings/notifications",state:y,label:s("common.systemPermissions"),icon:Tx,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/privacy",state:y,label:s("common.privacyTelemetry"),icon:Tx,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/about",state:y,label:s("common.about"),icon:Xfe,end:!0,variant:v?"compact":"default"})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.runtime")}),i.jsx(sd,{to:"/instance/settings/heartbeats",state:y,label:s("common.heartbeats"),icon:Cx,end:!0,variant:v?"compact":"default"})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.integrations")}),i.jsx(sd,{to:"/instance/settings/plugins",state:y,label:s("common.plugins"),icon:uT,variant:v?"compact":"default"}),(A??[]).length>0?i.jsx("div",{className:"ml-4 mt-1 flex flex-col gap-1 border-l border-[color:color-mix(in_oklab,var(--border-soft)_78%,transparent)] pl-4",children:(A??[]).map(C=>i.jsx(Pj,{to:`/instance/settings/plugins/${C.id}`,state:y,className:({isActive:N})=>K("rounded-[calc(var(--radius-sm)+2px)] px-2 py-1.5 text-xs transition-colors",N?"bg-[color:color-mix(in_oklab,var(--surface-active)_48%,transparent)] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_24%,transparent)] hover:text-foreground"),children:C.manifestJson.displayName??C.packageName},C.id))}):null]})]}):null,i.jsx("div",{className:K("flex flex-col gap-1 border-t border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] pt-3",!v&&!w&&"mt-auto"),children:i.jsx(gBn,{href:xT,label:s("common.docs"),variant:v?"compact":"default"})}),w&&S.length>0?i.jsxs("div",{className:K("flex flex-col gap-1 pt-2",!v&&"mt-auto"),children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.yourOrganizations")}),i.jsx("div",{className:"flex flex-col gap-1",children:S.map(C=>{const N=C.id===u;return i.jsxs("button",{type:"button",onClick:()=>j(C),"aria-label":C.name,className:K("flex w-full items-center gap-2.5 rounded-[calc(var(--radius-md)-2px)] px-3 py-2 text-left transition-colors",N?"bg-[color:var(--surface-active)] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_24%,transparent)] hover:text-foreground"),"aria-pressed":N,children:[i.jsx(UP,{organizationName:C.name,logoUrl:C.logoUrl,brandColor:C.brandColor,className:"h-5 w-5 shrink-0 rounded-md text-[10px]"}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-medium",title:C.name,children:C.name}),N?i.jsx(Zs,{className:"h-3.5 w-3.5 shrink-0 text-[color:var(--accent-strong)]"}):null]},C.id)})})]}):null]})]})}function xBn(e){var n,r,s,a;const t=new URLSearchParams({start:e.start,end:e.end});return(n=e.agentIds)!=null&&n.length&&t.set("agentIds",e.agentIds.join(",")),(r=e.sourceIds)!=null&&r.length&&t.set("sourceIds",e.sourceIds.join(",")),(s=e.eventKinds)!=null&&s.length&&t.set("eventKinds",e.eventKinds.join(",")),(a=e.statuses)!=null&&a.length&&t.set("statuses",e.statuses.join(",")),t.toString()}const su={sources:e=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/sources`),createSource:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/sources`,t),updateSource:(e,t,n)=>Re.patch(`/orgs/${encodeURIComponent(e)}/calendar/sources/${encodeURIComponent(t)}`,n),deleteSource:(e,t)=>Re.delete(`/orgs/${encodeURIComponent(e)}/calendar/sources/${encodeURIComponent(t)}`),events:(e,t)=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/events?${xBn(t)}`),getEvent:(e,t)=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/events/${encodeURIComponent(t)}`),createEvent:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/events`,t),updateEvent:(e,t,n)=>Re.patch(`/orgs/${encodeURIComponent(e)}/calendar/events/${encodeURIComponent(t)}`,n),deleteEvent:(e,t)=>Re.delete(`/orgs/${encodeURIComponent(e)}/calendar/events/${encodeURIComponent(t)}`),googleConfig:e=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/google/config`),updateGoogleConfig:(e,t)=>Re.patch(`/orgs/${encodeURIComponent(e)}/calendar/google/config`,t),connectGoogle:e=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/google/connect`,{}),syncGoogle:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/google/sync`,{sourceId:t??null})};function bBn({agent:e,orgId:t,triggerTestId:n,triggerClassName:r,visibilityClassName:s,onActionComplete:a}){const[o,l]=h.useState(!1),c=Vn(),d=Yr(),{openNewIssue:u}=ii(),{pushToast:f}=ss(),A=e.status==="terminated",m=e.status==="paused",g=async()=>{await Promise.all([c.invalidateQueries({queryKey:V.agents.list(t)}),c.invalidateQueries({queryKey:V.org(t)}),c.invalidateQueries({queryKey:V.agentRuns(t)}),c.invalidateQueries({queryKey:V.liveRuns(t)})])},x=xt({mutationFn:()=>Nn.invoke(e.id,t),onSuccess:async j=>{await g(),a==null||a(),f({title:"Heartbeat started",tone:"success",action:{label:"Open run",href:`/agents/${e3(e)}/runs/${j.id}`}})},onError:j=>{f({title:"Failed to run heartbeat",body:j instanceof Error?j.message:void 0,tone:"error"})}}),y=xt({mutationFn:()=>m?Nn.resume(e.id,t):Nn.pause(e.id,t),onSuccess:async()=>{await g(),a==null||a(),f({title:m?"Agent resumed":"Agent paused",tone:"success"})},onError:j=>{f({title:m?"Failed to resume agent":"Failed to pause agent",body:j instanceof Error?j.message:void 0,tone:"error"})}}),v=()=>{u({assigneeAgentId:e.id}),a==null||a()},w=()=>{a==null||a(),d({pathname:"/messenger/chat",search:`?agentId=${encodeURIComponent(e.id)}`})},k=async()=>{try{await navigator.clipboard.writeText(e.name),a==null||a(),f({title:"Copied agent name",tone:"success"})}catch(j){f({title:"Failed to copy agent name",body:j instanceof Error?j.message:void 0,tone:"error"})}},S=x.isPending||y.isPending;return i.jsxs(Ei,{open:o,onOpenChange:l,children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-label":`More actions for ${e.name}`,"data-testid":n??`agent-row-actions-${e.id}`,className:K("flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",o||S?"opacity-100":s??"opacity-100 md:opacity-0 md:group-hover/agent-row:opacity-100 md:group-focus-within/agent-row:opacity-100",r),onClick:j=>{j.preventDefault(),j.stopPropagation()},children:S?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay w-48 text-foreground",children:[i.jsxs(Xt,{onSelect:v,children:[i.jsx(Zr,{className:"h-4 w-4"}),"Create task"]}),i.jsxs(Xt,{onSelect:w,disabled:A,children:[i.jsx(pa,{className:"h-4 w-4"}),"Chat with agent"]}),i.jsx(Yo,{}),i.jsxs(Xt,{onSelect:()=>x.mutate(),disabled:x.isPending||A,children:[i.jsx(BCt,{className:"h-4 w-4"}),"Run heartbeat"]}),i.jsxs(Xt,{onSelect:()=>y.mutate(),disabled:y.isPending||A,children:[m?i.jsx(zA,{className:"h-4 w-4"}):i.jsx(HK,{className:"h-4 w-4"}),m?"Resume agent":"Pause agent"]}),i.jsx(Yo,{}),i.jsxs(Xt,{onSelect:()=>void k(),children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy agent name"]})]})]})}function WPe(e,t=""){return`/projects/${encodeURIComponent(e)}/app-builder${t}`}function s$(e,t,n=""){return`/app-builder/${encodeURIComponent(t)}${n}?orgId=${encodeURIComponent(e)}`}const Fh={list:e=>Re.get(`/orgs/${encodeURIComponent(e)}/app-builder`),async get(e){try{return await Re.get(WPe(e))}catch(t){if(t instanceof Nl&&t.status===404)return null;throw t}},create:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/app-builder`,t),createForProject:(e,t)=>Re.post(WPe(e),t),updateBuild:(e,t,n)=>Re.patch(s$(e,t,"/build"),n),attachConversation:(e,t,n)=>Re.patch(s$(e,t,"/conversation"),{conversationId:n}),bindLocalRuntime:(e,t,n)=>Re.put(s$(e,t,"/local-binding"),n),clearLocalRuntime:(e,t)=>Re.delete(s$(e,t,"/local-binding"))};let ZPe=0;const K_=new Map,lq=new Set,yBn=1e4;function v2e(e,t){return`${e}:${t}`}function vBn(e,t){ZPe+=1,K_.set(v2e(e,t),{createdAt:Date.now(),version:ZPe}),lq.forEach(n=>n())}function wBn(e,t){const n=v2e(e,t),r=K_.get(n);return r?Date.now()-r.createdAt<=yBn?r.version:(K_.delete(n),0):0}function kBn(e,t,n){var s;const r=v2e(e,t);((s=K_.get(r))==null?void 0:s.version)===n&&(K_.delete(r),lq.forEach(a=>a()))}function OBn(e){return lq.add(e),()=>lq.delete(e)}function pde(e){return`/apps/view/${encodeURIComponent(e)}`}function N7(e,t,n){return`${e}:${t}:${n}`}function bft(e){const n=fl(e).match(/^\/apps\/view\/([^/]+)$/);if(!(n!=null&&n[1]))return"home";try{return decodeURIComponent(n[1])}catch{return"home"}}function SBn(e){return e==="preparing"?"Preparing":e==="building"?"Building":e==="verifying"?"Verifying":e==="ready"?"Ready":"Needs attention"}function yft(e){var g;const{organizations:t,selectedOrganizationId:n}=jr(),r=(g=Pn())==null?void 0:g.localApps,s=Me({queryKey:V.appBuilder.organization(n??"__none__"),queryFn:()=>Fh.list(n),enabled:!!(n&&e)}),a=RFe({queries:t.filter(x=>x.id!==n).map(x=>({queryKey:V.appBuilder.organization(x.id),queryFn:()=>Fh.list(x.id),enabled:e}))}),o=Me({queryKey:V.localApps.definitions,queryFn:()=>r.list(),enabled:!!(r!=null&&r.supported&&e)}),l=h.useMemo(()=>new Map((o.data??[]).map(x=>[N7(x.desktopInstallationId,x.appPublicId,x.localBindingId),x])),[o.data]),c=h.useMemo(()=>(s.data??[]).map(x=>({kind:"managed",key:`managed:${x.id}`,app:x,definition:x.desktopInstallationId&&x.appPublicId&&x.localBindingId?l.get(N7(x.desktopInstallationId,x.appPublicId,x.localBindingId))??null:null})),[s.data,l]),d=h.useMemo(()=>new Set([...s.data??[],...a.flatMap(x=>x.data??[])].flatMap(x=>x.desktopInstallationId&&x.appPublicId&&x.localBindingId?[N7(x.desktopInstallationId,x.appPublicId,x.localBindingId)]:[])),[s.data,a]),u=!!(e&&s.isSuccess&&!s.isFetching&&a.every(x=>x.isSuccess&&!x.isFetching)),f=!!(u&&(!(r!=null&&r.supported)||o.isSuccess&&!o.isFetching)),A=h.useMemo(()=>u?(o.data??[]).filter(x=>!d.has(N7(x.desktopInstallationId,x.appPublicId,x.localBindingId))).map(x=>({kind:"local",key:`local:${x.id}`,definition:x})):[],[o.data,u,d]),m=h.useMemo(()=>[...c,...A],[A,c]);return{appsQuery:s,definitionsQuery:o,entries:m,localApps:r,registryReady:f}}const jBn=["Use $app-builder to create or improve a Rudder App.","Help me clarify what this local web app should do before building it."].join(" ");function CBn({entry:e,className:t}){return e.definition?i.jsx(Z6,{className:t,iconDataUrl:e.definition.iconDataUrl}):i.jsx("span",{className:K("flex items-center justify-center rounded-[var(--radius-sm)] bg-[color:color-mix(in_oklab,var(--accent-base)_18%,transparent)] text-[color:var(--accent-base)]",t),children:i.jsx(sA,{className:"h-3.5 w-3.5","aria-hidden":!0})})}function NBn({entry:e,onSettings:t}){var k;const n=Yr(),r=Vn(),{pushToast:s}=ss(),a=Pn(),o=a==null?void 0:a.localApps,l=a==null?void 0:a.appBuilder,c=e.definition,[d,u]=h.useState(null),f=Me({queryKey:V.localApps.status((c==null?void 0:c.localBindingId)??e.key),queryFn:()=>o.status(c.id),enabled:!!(o!=null&&o.supported&&c),refetchInterval:S=>{var j;return pW((j=S.state.data)==null?void 0:j.status)}}),A=xt({mutationFn:()=>o.stop(c.id),onMutate:()=>{c&&r.setQueryData(V.localApps.status(c.localBindingId),S=>S&&{...S,status:"stopping"})},onSuccess:S=>{c&&r.setQueryData(V.localApps.status(c.localBindingId),S)},onError:()=>{c&&r.invalidateQueries({queryKey:V.localApps.status(c.localBindingId)})}}),m=xt({mutationFn:async S=>{if(e.kind!=="managed"||!c||!(l!=null&&l.supported))throw new Error("App data controls are unavailable on this device.");const j={projectId:e.app.orgId,appDirectory:e.app.sourceRoot,binding:{desktopInstallationId:c.desktopInstallationId,definitionId:c.id,appPublicId:c.appPublicId,localBindingId:c.localBindingId}};if(S==="backup"){const N=await l.snapshot(j);(await l.exportSnapshot({...j,snapshotId:N.id})).canceled||(u(N.id),s({title:"App data backup exported",tone:"success"}));return}if(S==="import"){const N=await l.importData(j);N.canceled||(u(N.rollbackSnapshot.id),s({title:"App data imported",body:"The previous data is available as a restore point.",tone:"success"}));return}if(!d)throw new Error("Create a backup or import data first.");const C=await l.restoreSnapshot({...j,snapshotId:d});u(C.safetySnapshot.id),s({title:"App data restored",body:"A safety snapshot was kept.",tone:"success"})},onError:S=>{s({title:"App data operation failed",body:S instanceof Error?S.message:void 0,tone:"error"})},onSettled:()=>{c&&r.invalidateQueries({queryKey:V.localApps.status(c.localBindingId)})}}),g=(k=f.data)==null?void 0:k.status,x=g==="running",y=g==="starting"||g==="running"||g==="stopping"||g==="orphaned_unverified"||f.isPending||m.isPending,v=async S=>{if(!c||!o)return;const j=await o.attestedTarget(c.id);if(!j){s({title:"App link unavailable",body:"Open the App and wait for it to finish starting.",tone:"error"});return}const{src:C}=XAe(j);if(S==="copy"){await(a==null?void 0:a.copyText(C)),s({title:"App link copied",tone:"success"});return}const N=(a==null?void 0:a.forceOpenExternal)??(a==null?void 0:a.openExternal);await(N==null?void 0:N(C))},w=e.kind==="managed"?e.app.name:e.definition.title;return i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground opacity-0 transition-[background-color,color,opacity] hover:bg-[color:var(--surface-elevated)] hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100 data-[state=open]:opacity-100 motion-reduce:transition-none","aria-label":`More options for ${w}`,"data-testid":`apps-more-${e.key}`,children:i.jsx(hl,{className:"h-4 w-4","aria-hidden":!0})})}),i.jsxs(Ri,{align:"start",side:"right",className:"surface-overlay min-w-48 text-foreground",children:[c?i.jsxs(Xt,{onSelect:()=>t(c,y),children:[i.jsx(Ix,{"aria-hidden":!0}),"App settings"]}):null,c||e.kind==="managed"?i.jsxs(Xt,{onSelect:()=>{if(c){a==null||a.openPath(c.cwd).catch(S=>{s({title:"Could not open App source",body:S instanceof Error?S.message:void 0,tone:"error"})});return}e.kind==="managed"&&n(`/library?directory=${encodeURIComponent(e.app.sourceRoot)}`)},children:[i.jsx(qB,{"aria-hidden":!0}),"Open source"]}):null,e.kind==="managed"&&e.app.conversationId?i.jsxs(Xt,{onSelect:()=>n(`/messenger/chat/${e.app.conversationId}`),children:[i.jsx(pa,{"aria-hidden":!0}),"Continue in Chat"]}):null,c?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{disabled:!x,onSelect:()=>void v("copy"),"data-testid":`apps-copy-link-${e.key}`,children:[i.jsx(Al,{"aria-hidden":!0}),"Copy App link"]}),i.jsxs(Xt,{disabled:!x,onSelect:()=>void v("external"),children:[i.jsx(Ja,{"aria-hidden":!0}),"Open in browser"]}),e.kind==="managed"&&(l!=null&&l.supported)?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{disabled:m.isPending,onSelect:()=>m.mutate("backup"),children:[i.jsx(Tg,{"aria-hidden":!0}),"Back up data"]}),i.jsxs(Xt,{disabled:m.isPending,onSelect:()=>m.mutate("import"),children:[i.jsx(bS,{"aria-hidden":!0}),"Import data"]}),i.jsxs(Xt,{disabled:!d||m.isPending,onSelect:()=>m.mutate("restore"),children:[i.jsx(_2,{"aria-hidden":!0}),"Restore previous data"]})]}):null,i.jsx(Yo,{}),i.jsxs(Xt,{disabled:!y||A.isPending,onSelect:()=>A.mutate(),children:[i.jsx(vb,{"aria-hidden":!0}),"Stop App"]})]}):null]})]})}function PBn(){var k,S;const{isMobile:e,setSidebarOpen:t}=jc(),{selectedOrganizationId:n}=jr(),r=Yr(),s=br(),a=Vn(),[o,l]=h.useState(""),[c,d]=h.useState(null),f=((S=(k=Me({queryKey:V.health,queryFn:()=>rA.get()}).data)==null?void 0:k.features)==null?void 0:S.experimentalSitesEnabled)===!0,{entries:A,localApps:m}=yft(f),g=bft(s.pathname),x=A.filter(j=>(j.kind==="managed"?j.app.name:j.definition.title).toLowerCase().includes(o.trim().toLowerCase())),y=xt({mutationFn:()=>m.discover(),onSuccess:j=>{j.canceled||d({definition:j.draft,editId:null,editable:!0})}}),v=xt({mutationFn:j=>c!=null&&c.editId?m.update(c.editId,j):m.create(j),onSuccess:j=>{a.setQueryData(V.localApps.definitions,C=>{const N=C??[];return N.some(P=>P.id===j.id)?N.map(P=>P.id===j.id?j:P):[...N,j]}),d(null),r(pde(`local:${j.id}`))}}),w=xt({mutationFn:()=>m.stop(c.editId),onSuccess:j=>{!c||!("localBindingId"in c.definition)||(a.setQueryData(V.localApps.status(c.definition.localBindingId),j),d(C=>C&&{...C,editable:!0}))}});return i.jsxs(i.Fragment,{children:[i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx(sA,{className:"h-4 w-4 shrink-0 text-[color:var(--accent-base)]","aria-hidden":!0}),i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:"Apps"})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",size:"icon-sm",variant:"ghost",title:"Add an App","aria-label":"Add an App",disabled:!f,"data-testid":"apps-add",children:i.jsx(Zr,{className:"h-4 w-4","aria-hidden":!0})})}),i.jsxs(Ri,{align:"start",className:"surface-overlay w-80 max-w-[calc(100vw-1.5rem)] text-foreground",children:[i.jsxs(Xt,{className:"items-start gap-3 px-3 py-2.5","data-testid":"apps-build-with-agent",onSelect:()=>r(`/messenger/chat?prefill=${encodeURIComponent(jBn)}`),children:[i.jsx(Hh,{className:"mt-0.5","aria-hidden":!0}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-sm font-medium",children:"Build with Agent"}),i.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"Create or improve a web App with App Builder."})]})]}),i.jsxs(Xt,{className:"items-start gap-3 px-3 py-2.5",disabled:!(m!=null&&m.supported)||y.isPending,"data-testid":"apps-add-local-project",onSelect:()=>y.mutate(),children:[y.isPending?i.jsx(hn,{className:"mt-0.5 animate-spin motion-reduce:animate-none","aria-hidden":!0}):i.jsx(qB,{className:"mt-0.5","aria-hidden":!0}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-sm font-medium",children:"Add local web project"}),i.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"Load a Next.js, React, Vue, or other web project from this computer."})]})]})]})]}),e?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>t(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]})]}),i.jsx("div",{className:"p-3 pb-2",children:i.jsxs("div",{className:"relative",children:[i.jsx(Fl,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),i.jsx(Kn,{type:"search",value:o,onChange:j=>l(j.target.value),className:"h-8 pl-8 text-xs",placeholder:"Search Apps","aria-label":"Search Apps"})]})}),i.jsxs("nav",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-2 pb-3","aria-label":"Apps",children:[i.jsxs("button",{type:"button",className:K("flex h-9 w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2.5 text-left text-sm transition-[background-color,color] duration-150 motion-reduce:transition-none",g==="home"?"bg-[color:var(--surface-active)] font-medium text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_55%,transparent)] hover:text-foreground"),onClick:()=>r("/apps"),children:[i.jsx(Hfe,{className:"h-4 w-4","aria-hidden":!0}),"Home"]}),i.jsxs("div",{className:"mb-1.5 mt-4 flex items-center justify-between px-2.5",children:[i.jsx("span",{className:"text-[11px] font-medium text-muted-foreground/76",children:"Registered"}),i.jsx("span",{className:"text-[10px] tabular-nums text-muted-foreground",children:A.length})]}),x.length?i.jsx("div",{className:"space-y-0.5",children:x.map(j=>{const C=j.kind==="managed"?j.app.name:j.definition.title,N=j.key===g,P=j.kind==="managed"&&!j.definition?SBn(j.app.buildStatus):"On this device";return i.jsxs("div",{className:K("group motion-list-enter flex w-full items-center rounded-[calc(var(--radius-sm)-1px)] transition-[background-color,color] duration-150 motion-reduce:transition-none",N?"bg-[color:var(--surface-active)] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_55%,transparent)] hover:text-foreground"),children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2.5 px-2 py-2 text-left",onClick:()=>{n&&j.definition&&vBn(n,j.key),r(pde(j.key))},"data-testid":`apps-entry-${j.key}`,children:[i.jsx(CBn,{entry:j,className:"h-7 w-7 shrink-0"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:C}),i.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:P})]})]}),i.jsx("div",{className:"pr-1",children:i.jsx(NBn,{entry:j,onSettings:(M,E)=>{v.reset(),w.reset(),d({definition:M,editId:M.id,editable:!E})}})})]},j.key)})}):i.jsxs("div",{className:"mx-2 mt-3 rounded-[var(--radius-sm)] border border-dashed border-[color:var(--border-soft)] px-3 py-5 text-center",children:[i.jsx(qB,{className:"mx-auto h-5 w-5 text-muted-foreground","aria-hidden":!0}),i.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:o?"No matching Apps.":"Create or load your first App."})]})]})]}),c?i.jsx(gW,{definition:c.definition,edit:!!c.editId,editable:c.editable,error:v.error??w.error,open:!0,pending:v.isPending,requestEditPending:w.isPending,onCancel:()=>{v.reset(),w.reset(),d(null)},onRequestEdit:()=>w.mutate(),onSubmit:j=>v.mutate(j)}):null,y.error?i.jsxs("div",{className:"fixed bottom-5 right-5 z-50 flex max-w-sm items-start gap-3 rounded-[var(--radius-lg)] border border-destructive/30 bg-[color:var(--surface-overlay)] p-4 text-sm text-destructive shadow-lg",role:"alert",children:[i.jsx(Kc,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":!0}),i.jsx("span",{children:y.error instanceof Error?y.error.message:"Could not load this App."})]}):null]})}const W_=["slate","teal","sky","indigo","amber","rose","red","orange"],vft="::",IBn=new Set(HM),DD={slate:{bg:"#eef1ef",bgDark:"#313633",bgHover:"#e0e5e2",bgHoverDark:"#3b423e",border:"#d1d8d3",borderDark:"#545d58",text:"#26302a",textDark:"#f0f4f1",entryText:"#26302a",entryTextDark:"#eef2ef",swatch:"#242827"},teal:{bg:"#dff4ed",bgDark:"#143f36",bgHover:"#ccebe2",bgHoverDark:"#185247",border:"#a9d9cc",borderDark:"#2a7668",text:"#126454",textDark:"#d9fff5",entryText:"#173c35",entryTextDark:"#effffb",swatch:"#08a88a"},sky:{bg:"#dff1fb",bgDark:"#13394c",bgHover:"#c9e8f8",bgHoverDark:"#174b64",border:"#a9d7ee",borderDark:"#28708f",text:"#096287",textDark:"#dff7ff",entryText:"#153747",entryTextDark:"#f0fbff",swatch:"#0c8fca"},indigo:{bg:"#e6e5f8",bgDark:"#2d2c58",bgHover:"#d8d6f1",bgHoverDark:"#393873",border:"#c1bee6",borderDark:"#5b58a8",text:"#4c4695",textDark:"#f0efff",entryText:"#302e56",entryTextDark:"#f4f3ff",swatch:"#6259b5"},amber:{bg:"#f7edc2",bgDark:"#4a3914",bgHover:"#eee0a8",bgHoverDark:"#604a18",border:"#deca80",borderDark:"#9b7b2c",text:"#885900",textDark:"#ffeec2",entryText:"#4b3812",entryTextDark:"#fff8e5",swatch:"#f2a900"},rose:{bg:"#f3d5da",bgDark:"#4d252d",bgHover:"#eac3ca",bgHoverDark:"#63303a",border:"#dba8b2",borderDark:"#9b5664",text:"#7f2634",textDark:"#ffe9ee",entryText:"#51242c",entryTextDark:"#fff4f6",swatch:"#df6f83"},red:{bg:"#f0cdd1",bgDark:"#542126",bgHover:"#e7bac0",bgHoverDark:"#6a2a30",border:"#d59aa3",borderDark:"#a34d58",text:"#84242e",textDark:"#ffe8eb",entryText:"#552126",entryTextDark:"#fff1f2",swatch:"#d24b58"},orange:{bg:"#f4ddce",bgDark:"#552e1d",bgHover:"#edcbb7",bgHoverDark:"#6d3b25",border:"#dda98c",borderDark:"#a8623d",text:"#793816",textDark:"#ffeadf",entryText:"#512b1c",entryTextDark:"#fff4ee",swatch:"#ec6c3b"}};function TBn(e){return W_.includes(e)}function cq(e){const t=e==null?void 0:e.trim();if(!t)return{glyph:"folder",color:null};const[n,r]=t.split(vft);return{glyph:(n==null?void 0:n.trim())||"folder",color:TBn(r)?r:null}}function _ne(e,t){const n=e.trim()||"folder";return t?`${n}${vft}${t}`:n}function FI(e){const t=cq(e.icon);return t.color?t.color:W_[Math.abs(e.sortOrder??e.id.length)%W_.length]??"slate"}function _Bn(e){const t=DD[FI(e)];return{"--messenger-group-bg":t.bg,"--messenger-group-bg-dark":t.bgDark,"--messenger-group-bg-hover":t.bgHover,"--messenger-group-bg-hover-dark":t.bgHoverDark,"--messenger-group-border":t.border,"--messenger-group-border-dark":t.borderDark,"--messenger-group-text":t.text,"--messenger-group-text-dark":t.textDark,"--messenger-group-entry-text":t.entryText,"--messenger-group-entry-text-dark":t.entryTextDark}}function w2e(e){const{glyph:t}=cq(e);return t.trim()||null}function MH(e){return IBn.has((e??"").trim().toLowerCase())}function MBn(e){var n;const t=(n=w2e(e))==null?void 0:n.toLowerCase();return MH(t)?t:kK}function wft(e){return VAe(DD[e??"slate"].swatch)}function EBn(e){return!MH(e)&&/[^\x00-\x7F]/.test(e)}function RD({icon:e,color:t}){const n=w2e(e);if(!n||MH(n)){const r=t??FI({id:n??kK,icon:e??null,sortOrder:0});return i.jsx(uo,{color:DD[r].swatch,icon:MBn(e),size:"xs",className:"h-4 w-4",iconClassName:"h-4 w-4 text-[color:var(--project-accent-color)]",testId:"messenger-custom-group-icon"})}return EBn(n)?i.jsx("span",{"aria-hidden":!0,className:"inline-flex h-4 min-w-4 shrink-0 items-center justify-center text-[14px] leading-none",children:n}):i.jsx("span",{"aria-hidden":!0,className:"inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] bg-[color:color-mix(in_oklab,var(--surface-active)_72%,transparent)] px-0.5 text-[10px] font-semibold leading-none text-muted-foreground",children:n.slice(0,2)})}function kft({icon:e,ariaLabel:t,onIconChange:n}){const r=w2e(e);return i.jsx("div",{className:"space-y-1.5","aria-label":t,children:i.jsxs("div",{className:"grid grid-cols-6 gap-1.5","aria-label":`${t} options`,children:[HM.map(s=>{const a=oW(s),o=r&&MH(r)?s===r:!1;return i.jsx("button",{type:"button",className:K("relative inline-flex h-9 w-9 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] border text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",o?"border-[color:color-mix(in_oklab,var(--project-accent-color)_54%,var(--border-base))] bg-muted/55 text-[color:var(--project-accent-color)]":"border-border/70 bg-transparent"),"aria-label":`Select ${s} project icon`,"aria-pressed":o,onClick:()=>n(s),children:i.jsx(a,{className:"h-5 w-5",strokeWidth:2.2})},s)}),u3t.map(s=>{const a=s===r;return i.jsx("button",{type:"button",className:K("relative inline-flex h-9 w-9 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] border text-[18px] leading-none outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",a?"border-[color:color-mix(in_oklab,var(--project-accent-color)_54%,var(--border-base))] bg-muted/55":"border-border/70 bg-transparent"),"aria-label":`Select ${s} group emoji`,"aria-pressed":a,onClick:()=>n(s),children:i.jsx("span",{"aria-hidden":!0,children:s})},s)})]})})}function DBn({name:e,icon:t,color:n,pending:r,onNameChange:s,onIconChange:a,onColorChange:o,onCancel:l,onSubmit:c}){return i.jsxs("form",{"data-testid":"messenger-custom-group-editor",className:"p-2.5",onSubmit:d=>{d.preventDefault(),c()},children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx(RD,{icon:t,color:n}),i.jsx("div",{className:"min-w-0 flex-1 text-[12px] font-semibold text-foreground",children:"New group"})]}),i.jsx("input",{autoFocus:!0,"aria-label":"Group name",value:e,onChange:d=>s(d.currentTarget.value),className:"h-8 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-page)] px-2.5 text-[13px] outline-none transition-[border-color,box-shadow] focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30"}),i.jsx("div",{className:"mt-1.5 rounded-[calc(var(--radius-sm)-1px)] border border-[color:color-mix(in_oklab,var(--border-soft)_74%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-page)_72%,transparent)] p-1.5",style:wft(n),children:i.jsx(kft,{icon:t,ariaLabel:"Group icons",onIconChange:a})}),i.jsx("div",{className:"mt-2 flex items-center gap-1.5","aria-label":"Group color",children:W_.map(d=>{const u=DD[d];return i.jsx("button",{type:"button","aria-label":`Use ${d} group color`,"aria-pressed":n===d,className:K("inline-flex h-6 w-6 items-center justify-center rounded-full border transition-[border-color,box-shadow,transform] hover:scale-105",n===d?"border-[color:var(--border-strong)] shadow-[0_0_0_2px_var(--surface-elevated),0_0_0_4px_color-mix(in_oklab,var(--border-strong)_70%,transparent)]":"border-transparent"),style:{backgroundColor:u.swatch},onClick:()=>o(d)},d)})}),i.jsxs("div",{className:"mt-2.5 flex justify-end gap-1.5",children:[i.jsx("button",{type:"button",className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[12px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground",onClick:l,children:"Cancel"}),i.jsx("button",{type:"submit",disabled:r||!e.trim(),className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] bg-[color:var(--accent-strong)] px-2.5 text-[12px] font-semibold text-white transition-opacity disabled:cursor-not-allowed disabled:opacity-50",children:"Create"})]})]})}function RBn({name:e,pending:t,onNameChange:n,onCancel:r,onSubmit:s}){return i.jsxs("form",{"data-testid":"messenger-custom-group-rename",className:"mx-3 mt-2 rounded-md border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_96%,transparent)] p-2.5 shadow-sm",onSubmit:a=>{a.preventDefault(),s()},children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx(xg,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),i.jsx("div",{className:"min-w-0 flex-1 text-[12px] font-semibold text-foreground",children:"Rename group"})]}),i.jsx("input",{autoFocus:!0,"aria-label":"Group name",value:e,onChange:a=>n(a.currentTarget.value),className:"h-8 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-page)] px-2.5 text-[13px] outline-none transition-[border-color,box-shadow] focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30"}),i.jsxs("div",{className:"mt-2.5 flex justify-end gap-1.5",children:[i.jsx("button",{type:"button",className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[12px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground",onClick:r,children:"Cancel"}),i.jsx("button",{type:"submit",disabled:t||!e.trim(),className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] bg-[color:var(--accent-strong)] px-2.5 text-[12px] font-semibold text-white transition-opacity disabled:cursor-not-allowed disabled:opacity-50",children:"Save"})]})]})}class Oft{constructor(){Cs(this,"activeByChatId",new Map);Cs(this,"listenersByChatId",new Map);Cs(this,"getSnapshot",t=>this.activeByChatId.get(t)===!0);Cs(this,"subscribe",(t,n)=>{const r=this.listenersByChatId.get(t)??new Set;return r.add(n),this.listenersByChatId.set(t,r),()=>{r.delete(n),r.size===0&&this.listenersByChatId.delete(t)}})}setActive(t,n){if(this.getSnapshot(t)!==n){n?this.activeByChatId.set(t,!0):this.activeByChatId.delete(t);for(const r of this.listenersByChatId.get(t)??[])r()}}}const LBn=new Set,Sft={activeChatIds:LBn,streamDrafts:{},sendInFlightByChatId:{},isChatGenerationActive:()=>!1,setChatSendInFlight:()=>{},setStreamDraftForChat:()=>{},setStreamAbortController:()=>{},abortChatStream:()=>{}},jft=h.createContext(Sft),Cft=h.createContext(Sft),zBn=new Oft,Nft=h.createContext(zBn);function $Bn({children:e}){const t=PD(),[n,r]=h.useState({}),[s,a]=h.useState({}),o=h.useRef(n),l=h.useRef(null);l.current||(l.current=new Oft);const c=l.current,d=h.useRef({}),u=h.useRef(null),f=h.useRef(null),A=h.useRef(0),m=h.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null),r(o.current)},[]),g=h.useCallback(N=>{if(N){m();return}if(u.current!==null)return;const P=Date.now()<A.current;u.current=window.setTimeout(()=>{u.current=null,P?h.startTransition(()=>r(o.current)):r(o.current)},P?200:50)},[m]);h.useEffect(()=>{const N=()=>{A.current=Date.now()+120,f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{f.current=null,m()},120)};return window.addEventListener("scroll",N,{capture:!0,passive:!0}),window.addEventListener("wheel",N,{capture:!0,passive:!0}),()=>{window.removeEventListener("scroll",N,!0),window.removeEventListener("wheel",N,!0),u.current!==null&&window.clearTimeout(u.current),f.current!==null&&window.clearTimeout(f.current)}},[m]);const x=h.useMemo(()=>new Set(Object.keys(n)),[n]),y=h.useCallback((N,P)=>{a(M=>Yvn(M,N,P))},[]),v=h.useCallback((N,P)=>{const M=o.current,E=M[N]??null,T=typeof P=="function"?P(E):P,R=Jvn(M,N,T);if(R===M)return;if(o.current=R,c.setActive(N,T!==null),((E==null?void 0:E.state)!==(T==null?void 0:T.state)||E===null!=(T===null))&&t.updateSummary(`chat:${N}`,{status:(T==null?void 0:T.state)??(E?"completed":null)}),T===null&&E){u.current!==null&&(window.clearTimeout(u.current),u.current=null),r(M),window.setTimeout(()=>r(o.current),0);return}const _=T===null||T.state==="failed"||T.state==="stopped";g(_)},[t,g,c]),w=h.useCallback((N,P)=>{if(P){d.current={...d.current,[N]:P};return}if(!(N in d.current))return;const{[N]:M,...E}=d.current;d.current=E},[]),k=h.useCallback(N=>{var P;(P=d.current[N])==null||P.abort()},[]),S=h.useCallback(N=>!!(N&&c.getSnapshot(N)),[c]),j=h.useMemo(()=>({abortChatStream:k,isChatGenerationActive:S,setChatSendInFlight:y,setStreamDraftForChat:v,setStreamAbortController:w}),[k,S,y,w,v]),C=h.useMemo(()=>({activeChatIds:x,streamDrafts:n,sendInFlightByChatId:s,isChatGenerationActive:S,setChatSendInFlight:y,setStreamDraftForChat:v,setStreamAbortController:w,abortChatStream:k}),[k,x,S,s,y,w,v,n]);return i.jsx(Nft.Provider,{value:c,children:i.jsx(Cft.Provider,{value:j,children:i.jsx(jft.Provider,{value:C,children:e})})})}function Pft(){return h.useContext(jft)}function Ift(){return h.useContext(Cft)}function FBn(e){const t=h.useContext(Nft);return h.useSyncExternalStore(n=>t.subscribe(e,n),()=>t.getSnapshot(e),()=>t.getSnapshot(e))}function Z_(e){switch(e){case"chat":return"Chat";case"issues":return"Issues";case"approvals":return"Approvals";case"failed-runs":return"Failed runs";case"budget-alerts":return"Budget alerts";case"join-requests":return"Join requests";default:return e}}const HPe=1e3,BBn=120;function EH({dragHandleProps:e,label:t,compact:n=!1}){return e?i.jsx("button",{type:"button",...e.attributes,...e.listeners,"aria-label":t,title:t,className:K("shrink-0 cursor-grab touch-none rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/55 opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 active:cursor-grabbing group-hover:opacity-100 group-focus-within:opacity-100",n?"mt-0 flex h-5 w-4 items-center justify-center":"mt-0.5 flex h-6 w-4 items-center justify-center"),children:i.jsx(vBe,{className:"h-3.5 w-3.5","aria-hidden":!0})}):null}function QBn(e){switch(e){case"chat":return pa;case"issues":return xS;case"approvals":return Tx;case"failed-runs":return UK;case"budget-alerts":return Nx;case"join-requests":return Jfe;default:return Gf}}function oo(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function XPe(e){return qf(e.latestReplyPreview)||qf(e.summary)||(e.primaryIssue?`${e.primaryIssue.identifier??e.primaryIssue.id} · ${e.primaryIssue.title}`:null)||"Start the conversation"}function YF(e){return o6(e)}function GPe(e){return LP(e,{max:80})??e}function Tft({threadKey:e,eyebrow:t,title:n,description:r,metadata:s,suppressed:a=!1,children:o}){const[l,c]=h.useState(!1),d=h.useRef(null),u=h.useRef(null),f=h.useRef(a),A=h.useRef(!1),m=h.useRef(!1),g=h.useRef(!1),x=h.useRef(!1),y=(s==null?void 0:s.filter(E=>!!(E!=null&&E.trim())))??[];f.current=a;const v=E=>{E.current&&clearTimeout(E.current),E.current=null},w=()=>{v(d),v(u),!(f.current||A.current)&&c(!0)},k=()=>{v(d),v(u),!(f.current||A.current)&&(d.current=setTimeout(w,HPe))},S=()=>{k()},j=()=>{if(f.current){g.current=!0;return}!A.current||!m.current||(A.current=!1,m.current=!1,k())},C=()=>{v(d),v(u),u.current=setTimeout(()=>c(!1),BBn)},N=()=>{A.current&&(!f.current||g.current)&&(m.current=!0),C()},P=()=>{!f.current&&A.current&&(x.current=!0),C()},M=()=>{!f.current&&x.current&&(A.current=!1,x.current=!1),w()};return h.useEffect(()=>{a&&(A.current=!0,m.current=!1,g.current=!1,x.current=!1,v(d),v(u),c(!1))},[a]),h.useEffect(()=>()=>{v(d),v(u)},[]),i.jsx(Wc,{delayDuration:HPe,skipDelayDuration:0,children:i.jsxs(ra,{open:l&&!a,children:[i.jsx(sa,{asChild:!0,onMouseEnter:S,onMouseMove:j,onMouseLeave:N,onFocusCapture:M,onBlurCapture:P,children:o}),i.jsxs(ia,{side:"right",align:"start",sideOffset:8,collisionPadding:16,"data-testid":`messenger-thread-preview-${oo(e)}`,className:"motion-entity-preview-pop z-[70] w-[min(22rem,calc(100vw-2rem))] space-y-2 rounded-[var(--radius-md)] border border-border/80 bg-[color:var(--surface-overlay)] px-3.5 py-3 text-left text-foreground shadow-[var(--shadow-lg)]",onMouseEnter:w,onMouseLeave:C,children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:t}),i.jsx("div",{className:"break-words text-[13px] font-semibold leading-5 text-foreground",children:n}),r?i.jsx("div",{className:"line-clamp-6 whitespace-pre-wrap break-words text-[12px] leading-5 text-foreground/78",children:r}):null,y.length>0?i.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 border-t border-border/60 pt-2 text-[11px] text-muted-foreground",children:y.map(E=>i.jsx("span",{children:E},E))}):null]})]})})}function _ft({icon:e,unreadCount:t,needsAttention:n,density:r="comfortable",shape:s="circle",testId:a}){const o=r==="compact";return i.jsxs("span",{className:K("relative flex shrink-0 items-center justify-center border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)] text-[color:var(--accent-strong)]",o?"h-7 w-7":"mt-0.5 h-10 w-10",s==="rounded"?"rounded-[calc(var(--radius-sm)+1px)]":"rounded-full"),children:[i.jsx(e,{className:K(o?"h-3.5 w-3.5":"h-4.5 w-4.5")}),t>0?i.jsx("span",{"data-testid":a,className:"absolute -right-1.5 -top-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-[color:var(--surface-elevated)] bg-red-500 px-1 text-[10px] font-semibold leading-none text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]",children:t>99?"99+":t}):n?i.jsx("span",{"data-testid":a,className:"absolute -right-0.5 -top-0.5 h-3.5 w-3.5 rounded-full border-2 border-[color:var(--surface-elevated)] bg-red-500"}):null]})}function UBn({agent:e,agentId:t,unreadCount:n,needsAttention:r,density:s,testId:a}){if(!e&&!t)return i.jsx(_ft,{icon:pa,unreadCount:n,needsAttention:r,density:s,shape:"rounded",testId:`${a}-unread-badge`});const o=s==="compact";return i.jsxs("span",{"data-testid":a,title:e!=null&&e.name?`Chat agent: ${e.name}`:"Chat agent",className:K("relative flex shrink-0 items-center justify-center overflow-visible rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)]",o?"h-7 w-7":"mt-0.5 h-10 w-10"),children:[i.jsx(_g,{icon:e==null?void 0:e.icon,role:e==null?void 0:e.role,fallbackSeed:(e==null?void 0:e.id)??t,className:"h-full w-full rounded-full"}),n>0?i.jsx("span",{"data-testid":`${a}-unread-badge`,className:"absolute -right-1.5 -top-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-[color:var(--surface-elevated)] bg-red-500 px-1 text-[10px] font-semibold leading-none text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]",children:n>99?"99+":n}):r?i.jsx("span",{"data-testid":`${a}-unread-badge`,className:"absolute -right-0.5 -top-0.5 h-3.5 w-3.5 rounded-full border-2 border-[color:var(--surface-elevated)] bg-red-500"}):null]})}function VBn({status:e,unreadCount:t,needsAttention:n,density:r="comfortable",testId:s}){const a=r==="compact";return i.jsxs("span",{title:`Issue status: ${e.replace(/_/g," ")}`,className:K("relative flex shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)]",a?"h-7 w-7":"mt-0.5 h-10 w-10"),children:[i.jsx(ni,{status:e,className:K(a?"h-3.5 w-3.5":"h-4.5 w-4.5")}),t>0?i.jsx("span",{"data-testid":s,className:"absolute -right-1.5 -top-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-[color:var(--surface-elevated)] bg-red-500 px-1 text-[10px] font-semibold leading-none text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]",children:t>99?"99+":t}):n?i.jsx("span",{"data-testid":s,className:"absolute -right-0.5 -top-0.5 h-3.5 w-3.5 rounded-full border-2 border-[color:var(--surface-elevated)] bg-red-500"}):null]})}function qBn({conversation:e,agent:t,agentId:n,sourceBadge:r,href:s,active:a,generating:o,density:l,renaming:c,renameDraft:d,onRenameDraftChange:u,onCommitRename:f,onCancelRename:A,onStartRename:m,onRegenerateTitle:g,titleGenerating:x=!1,onFork:y,onArchive:v,onDelete:w,archiveDeleteAllowed:k=!0,onTogglePin:S,onToggleUnread:j,onCopyConversationLink:C,customGroups:N,customGroupId:P,customGroupPending:M,onMoveToCustomGroup:E,onRemoveFromCustomGroup:T,onCreateCustomGroup:R,dragHandleProps:_,dragging:D,onSelect:U}){const $=FBn(e.id),L=o??$,H=Bi(e.lastMessageAt??e.updatedAt,{compactDate:!0}),[X,F]=h.useState(!1),Q=h.useRef(null),q=h.useRef(null),B=h.useRef(!1),ee=l==="compact",se=ee?"right-1.5":"right-2",re=ee?"right-7":"right-8";return h.useEffect(()=>{(L||x)&&F(!1)},[L,x]),i.jsx(Tft,{threadKey:`chat:${e.id}`,eyebrow:"Chat",title:SW(e.title)?YF(e):e.title,description:XPe(e),metadata:[t!=null&&t.name?`Agent: ${t.name}`:null,H],suppressed:X,children:i.jsxs("div",{ref:Q,"data-testid":`messenger-thread-${oo(`chat:${e.id}`)}`,"data-messenger-thread-key":`chat:${e.id}`,className:K("group relative flex [contain-intrinsic-size:auto_44px] [content-visibility:auto] rounded-[calc(var(--radius-md)-2px)] border transition-[background-color,border-color,color]",P?"mx-0":"mx-1.5",ee?K("items-center gap-2 py-1.5",P?"px-1.5":"px-2"):K("items-start gap-3 py-2.5",P?"px-2":"px-3"),a?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]",P&&"text-[color:var(--messenger-group-entry-text)] dark:text-[color:var(--messenger-group-entry-text-dark)]",D&&"shadow-sm ring-1 ring-border/70"),children:[i.jsx(EH,{dragHandleProps:_,label:`Drag ${YF(e)}`,compact:ee}),i.jsx(UBn,{agent:t,agentId:n,unreadCount:e.unreadCount,needsAttention:e.needsAttention,density:l,testId:`messenger-thread-${oo(`chat:${e.id}`)}-agent-avatar`}),c?i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx("input",{autoFocus:!0,value:d,onChange:ne=>u(ne.target.value),onBlur:f,onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),f()),ne.key==="Escape"&&(ne.preventDefault(),A())},className:"min-h-0 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-elevated)] px-3 py-2 text-sm outline-none"})}):i.jsxs(i.Fragment,{children:[i.jsx(sn,{to:s,onClick:()=>U(s),className:"block min-w-0 flex-1",children:i.jsxs("div",{className:K("grid min-w-0 gap-x-2",ee?"grid-cols-[minmax(0,1fr)_2.75rem] items-center":"grid-cols-[minmax(0,1fr)_3rem] items-start"),children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:K("flex items-center gap-2 text-[13px] leading-tight",P?e.isUnread?"font-semibold text-current":"font-medium text-current/88":e.isUnread?"font-semibold text-foreground":"font-medium text-foreground/92"),children:[i.jsx("span",{className:"truncate",children:YF(e)}),r?i.jsx("span",{"data-testid":`messenger-source-badge-${oo(`chat:${e.id}`)}`,className:"inline-flex shrink-0 items-center rounded-[calc(var(--radius-sm)-2px)] border border-sky-500/35 bg-sky-500/15 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-sky-700 dark:text-sky-300",children:r.label}):null,x?i.jsxs("span",{"data-testid":`messenger-title-generating-${oo(`chat:${e.id}`)}`,className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-[color:color-mix(in_oklab,var(--surface-active)_76%,transparent)] px-1.5 py-0.5 text-[10px] font-semibold text-muted-foreground","aria-label":"Generating chat title",children:[i.jsx(hn,{className:"h-2.5 w-2.5 animate-spin","aria-hidden":!0}),"Naming"]}):null]}),ee?null:i.jsx("div",{className:K("mt-0.5 truncate text-[12px]",P?e.isUnread?"text-current/78":"text-current/62":e.isUnread?"text-foreground/76":"text-muted-foreground"),children:XPe(e)})]}),i.jsx("span",{"data-testid":`messenger-time-${oo(`chat:${e.id}`)}`,className:K("block shrink-0 whitespace-nowrap text-right text-[10px] leading-none tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",ee?"w-11":"mt-0.5 w-12",(X||L||x)&&"opacity-0"),children:H})]})}),L?i.jsx("span",{"data-testid":`messenger-generating-${oo(`chat:${e.id}`)}`,"aria-label":"Chat reply in progress",className:K("pointer-events-none absolute top-1/2 z-10 inline-flex -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",ee?"right-1.5 h-5 w-5":"right-2 h-6 w-6",X&&"opacity-0"),children:i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin",strokeWidth:2.25,"aria-hidden":!0})}):null,x?i.jsx("span",{"data-testid":`messenger-title-spinner-${oo(`chat:${e.id}`)}`,"aria-label":"Generating chat title",className:K("pointer-events-none absolute top-1/2 z-10 inline-flex -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition-opacity duration-150",ee?"right-1.5 h-5 w-5":"right-2 h-6 w-6"),children:i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin",strokeWidth:2.25,"aria-hidden":!0})}):null,e.isPinned?i.jsx("button",{type:"button","data-testid":`messenger-pin-toggle-${oo(`chat:${e.id}`)}`,className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-[color:var(--accent-strong)] opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-[color:var(--accent-strong)] focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",se,(X||L||x)&&"pointer-events-none opacity-0"),"aria-label":"Unpin chat",title:"Unpin chat",onClick:S,children:i.jsx(Jh,{className:"h-3.5 w-3.5",strokeWidth:2.25})}):null,i.jsxs(Ei,{open:X,onOpenChange:F,children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{ref:q,type:"button",className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-muted-foreground transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",e.isPinned?re:se,X?"opacity-100":"opacity-0",x&&"pointer-events-none opacity-0"),"aria-label":"Chat actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"messenger-thread-actions-menu morph-popover morph-popover--from-right surface-overlay text-foreground",onCloseAutoFocus:ne=>{B.current&&(ne.preventDefault(),B.current=!1)},children:[m?i.jsxs(Xt,{onClick:m,children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename"]}):null,g?i.jsxs(Xt,{disabled:x,onClick:g,children:[x?i.jsx(hn,{className:"h-4 w-4 animate-spin"}):i.jsx(KA,{className:"h-4 w-4"}),"Regenerate title"]}):null,i.jsx(Xt,{onClick:S,children:e.isPinned?i.jsxs(i.Fragment,{children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}):i.jsxs(i.Fragment,{children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]})}),i.jsx(Xt,{onClick:j,children:e.isUnread?i.jsxs(i.Fragment,{children:[i.jsx(NBe,{className:"h-4 w-4"}),"Mark as Read"]}):i.jsxs(i.Fragment,{children:[i.jsx(cE,{className:"h-4 w-4"}),"Mark as Unread"]})}),i.jsxs(Xt,{onClick:C,children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy Chat Link"]}),i.jsxs(Xt,{disabled:L,onClick:y,children:[i.jsx(WB,{className:"h-4 w-4"}),"Fork"]}),N&&!M?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{onClick:()=>{!Q.current||!q.current||(B.current=!0,R==null||R(Q.current,q.current))},children:[i.jsx(j3,{className:"h-4 w-4"}),"New group"]}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(aE,{className:"h-4 w-4"}),"Move to group"]}),i.jsxs(i6,{className:"morph-popover morph-popover--from-left surface-overlay text-foreground",children:[P?i.jsx(Xt,{onClick:T,children:"Move out of group"}):null,N.length>0?N.map(ne=>i.jsxs(Xt,{disabled:ne.id===P,onClick:()=>E==null?void 0:E(ne.id),children:[i.jsx(RD,{icon:ne.icon}),ne.name]},ne.id)):i.jsx(Xt,{disabled:!0,children:"No groups"})]})]})]}):null,k?i.jsxs(i.Fragment,{children:[i.jsxs(Xt,{onClick:v,children:[i.jsx(G4,{className:"h-4 w-4"}),"Archive"]}),i.jsxs(Xt,{variant:"destructive",onClick:w,title:L?"Stops the active reply before deleting this chat.":void 0,children:[i.jsx(yi,{className:"h-4 w-4"}),"Delete"]})]}):null]})]})]})]})})}function KBn({thread:e,active:t,density:n,preserveUnreadEmphasis:r=!1,onTogglePin:s,onHideIssue:a,customGroups:o,customGroupId:l,customGroupPending:c,onMoveToCustomGroup:d,onRemoveFromCustomGroup:u,onCreateCustomGroup:f,dragHandleProps:A,dragging:m,onSelect:g}){var F,Q,q,B,ee,se,re;const x=/^(issue|run):/.test(e.threadKey)?e.threadKey:null,y=dTn(x),v=QBn(e.kind),w=qf(e.preview)||qf(e.subtitle)||Z_(e.kind),k=n==="compact",[S,j]=h.useState(!1),C=h.useRef(null),N=h.useRef(null),P=h.useRef(!1),M=k?"right-1.5":"right-2",E=k?"right-7":"right-8",T=((F=e.metadata)==null?void 0:F.splitIssue)===!0,R=((Q=e.metadata)==null?void 0:Q.splitIssue)===!0&&!!a,_=T||R||!!o,D=((q=e.metadata)==null?void 0:q.splitIssue)===!0&&typeof e.metadata.status=="string"?(y==null?void 0:y.status)??e.metadata.status:null,U=(y==null?void 0:y.unreadCount)??e.unreadCount,$=(y==null?void 0:y.needsAttention)??e.needsAttention,L=(y==null?void 0:y.latestActivityAt)??e.latestActivityAt,H=t||r||U>0,X=((B=e.metadata)==null?void 0:B.splitIssue)===!0&&typeof e.metadata.activeExecutionRunId=="string"?e.metadata.activeExecutionRunId:null;return h.useEffect(()=>{X&&j(!1)},[X]),i.jsx(Tft,{threadKey:e.threadKey,eyebrow:((ee=e.metadata)==null?void 0:ee.splitIssue)===!0?typeof e.metadata.issueIdentifier=="string"?e.metadata.issueIdentifier:"Issue":Z_(e.kind),title:e.title,description:((se=e.metadata)==null?void 0:se.splitIssue)===!0&&typeof e.metadata.description=="string"?e.metadata.description:w,metadata:((re=e.metadata)==null?void 0:re.splitIssue)===!0?[D?`Status: ${D.replace(/_/g," ")}`:null,typeof e.metadata.priority=="string"?`Priority: ${e.metadata.priority}`:null,L?Bi(new Date(L),{compactDate:!0}):null]:[L?Bi(new Date(L),{compactDate:!0}):null],suppressed:S,children:i.jsxs("div",{ref:C,"data-testid":`messenger-thread-${oo(e.threadKey)}`,"data-messenger-thread-key":e.threadKey,className:K("group relative flex [contain-intrinsic-size:auto_44px] [content-visibility:auto] rounded-[calc(var(--radius-md)-2px)] border transition-[background-color,border-color,color]",l?"mx-0":"mx-1.5",k?K("items-center gap-2 py-1.5",l?"px-1.5":"px-2"):K("items-start gap-3 py-2.5",l?"px-2":"px-3"),t?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]",l&&"text-[color:var(--messenger-group-entry-text)] dark:text-[color:var(--messenger-group-entry-text-dark)]",m&&"opacity-80 shadow-sm ring-1 ring-border/70"),children:[i.jsx(EH,{dragHandleProps:A,label:`Drag ${GPe(e.title)}`,compact:k}),i.jsxs(sn,{to:e.href,onClick:()=>g(e),className:K("flex min-w-0 flex-1",k?"items-center gap-2":"items-start gap-3"),children:[D?i.jsx(VBn,{status:D,unreadCount:U,needsAttention:$,density:n,testId:`${oo(e.threadKey)}-unread-badge`}):i.jsx(_ft,{icon:v,unreadCount:U,needsAttention:$,density:n,testId:`${oo(e.threadKey)}-unread-badge`}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsxs("span",{className:K("grid min-w-0 gap-x-2",k?"grid-cols-[minmax(0,1fr)_2.75rem] items-center":"grid-cols-[minmax(0,1fr)_3rem] items-start"),children:[i.jsx("span",{className:K("flex min-w-0 items-center gap-2 text-[13px] leading-tight",H?"font-semibold text-foreground":"font-medium text-foreground/92"),children:i.jsx("span",{className:"truncate",children:GPe(e.title)})}),i.jsx("span",{"data-testid":`messenger-time-${oo(e.threadKey)}`,className:K("block shrink-0 whitespace-nowrap text-right text-[10px] leading-none tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",k?"w-11":"mt-0.5 w-12",(S||X)&&"opacity-0"),children:L?Bi(new Date(L),{compactDate:!0}):"No activity"})]}),k?null:i.jsx("span",{className:K("mt-0.5 block truncate text-[12px]",H?"text-foreground/76":"text-muted-foreground"),children:w})]})]}),X?i.jsx("span",{"data-testid":`messenger-active-run-${oo(e.threadKey)}`,"aria-label":"Issue run in progress",title:"Issue run in progress",className:K("pointer-events-none absolute top-1/2 z-10 inline-flex -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",k?"right-1.5 h-5 w-5":"right-2 h-6 w-6",S&&"opacity-0"),children:i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin",strokeWidth:2.25,"aria-hidden":!0})}):null,T&&e.isPinned?i.jsx("button",{type:"button","data-testid":`messenger-pin-toggle-${oo(e.threadKey)}`,className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-[color:var(--accent-strong)] opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-[color:var(--accent-strong)] focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",M,(S||X)&&"pointer-events-none opacity-0"),"aria-label":"Unpin thread",title:"Unpin thread",onClick:s,children:i.jsx(Jh,{className:"h-3.5 w-3.5",strokeWidth:2.25})}):null,_?i.jsxs(Ei,{open:S,onOpenChange:j,children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{ref:N,type:"button",className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-muted-foreground transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",T&&e.isPinned?E:M,S?"opacity-100":"opacity-0"),"aria-label":"Thread actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"messenger-thread-actions-menu morph-popover morph-popover--from-right surface-overlay text-foreground",onCloseAutoFocus:ne=>{P.current&&(ne.preventDefault(),P.current=!1)},children:[T?i.jsx(Xt,{onClick:s,children:e.isPinned?i.jsxs(i.Fragment,{children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}):i.jsxs(i.Fragment,{children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]})}):null,R?i.jsxs(Xt,{onClick:a,children:[i.jsx(J4,{className:"h-4 w-4"}),"Hide"]}):null,o&&!c?i.jsxs(i.Fragment,{children:[T||R?i.jsx(Yo,{}):null,i.jsxs(Xt,{onClick:()=>{!C.current||!N.current||(P.current=!0,f==null||f(C.current,N.current))},children:[i.jsx(j3,{className:"h-4 w-4"}),"New group"]}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(aE,{className:"h-4 w-4"}),"Move to group"]}),i.jsxs(i6,{className:"morph-popover morph-popover--from-left surface-overlay text-foreground",children:[l?i.jsx(Xt,{onClick:u,children:"Move out of group"}):null,o.length>0?o.map(ne=>i.jsxs(Xt,{disabled:ne.id===l,onClick:()=>d==null?void 0:d(ne.id),children:[i.jsx(RD,{icon:ne.icon}),ne.name]},ne.id)):i.jsx(Xt,{disabled:!0,children:"No groups"})]})]})]}):null]})]}):null]})})}function WBn(e){if(!e||e.length>GM)return null;if(/^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(e))return e;try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?e:null}catch{return null}}function ZBn(e){return e.replace(/(?:https?:\/\/|file:\/\/\/|(?:data|javascript):)[^\s<>"']+/gi,r=>{if(/^file:/i.test(r))return"Local file";if(/^(?:data|javascript):/i.test(r))return"Web page";try{return new URL(r).host||"Web page"}catch{return"Web page"}}).replace(/\/\/((?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z0-9-]{2,})(?::\d+)?)(?:[/?#][^\s<>"']*)?/gi,"$1").replace(/\b((?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z0-9-]{2,})(?::\d+)?)(?:[/?#][^\s<>"']*)?/gi,"$1")}function gde(e){const t="item"in e?e.item.savedView:e,n=t.title.trim();if(t.targetPayload.kind!=="browser")return n||"Saved View";try{const s=new URL(n);if(s.protocol==="http:"||s.protocol==="https:")return s.hostname||"Web page"}catch{}const r=ZBn(n).trim();if(r)return r;try{return new URL(t.targetPayload.url).hostname||"Web page"}catch{return"Web page"}}function HBn({savedView:e}){var o;const t=e.targetPayload.kind,n=t==="browser"?WBn(e.favicon):null,r=t==="browser"?(o=Q6(e.targetPayload.url))==null?void 0:o.darkMode:void 0,[s,a]=h.useState(!1);return h.useEffect(()=>{a(!1)},[n]),t==="browser"&&n&&!s?i.jsx("img",{alt:"",className:K("h-4 w-4 rounded-[3px] object-contain",r==="invert"&&"dark:invert"),"data-dark-mode":r,"data-testid":"messenger-saved-view-browser-favicon",referrerPolicy:"no-referrer",src:n,onError:()=>a(!0)}):t==="browser"?i.jsx(up,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-browser-fallback-icon","aria-hidden":!0}):t==="automation"?i.jsx(n6,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-automation-icon","aria-hidden":!0}):t==="local_app"?i.jsx(Z6,{className:"h-3.5 w-3.5 rounded-[3px]",identity:e.targetPayload,testId:"messenger-saved-view-local-app-icon"}):t==="library_directory"?i.jsx(wo,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-folder-icon","aria-hidden":!0}):t==="library_document"?i.jsx(NSt,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-document-icon","aria-hidden":!0}):i.jsx(bBe,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-file-icon","aria-hidden":!0})}function Mne({active:e=!1,currentGroupId:t,density:n,dragHandleProps:r,dragging:s=!1,entry:a,itemKey:o,savedView:l,groups:c,onMove:d,onMoveOutOfGroup:u,onRemove:f,placementPending:A=!1}){const m=(a==null?void 0:a.item.savedView)??l;if(!m)return null;const g=(a==null?void 0:a.itemKey)??o??`saved-view:${m.id}`,x=(a==null?void 0:a.id)??`loose-${m.id}`,y=c.filter(S=>S.id!==t),v=n==="compact",w=m.targetPayload.kind==="browser",k=gde(m);return i.jsxs("div",{"data-testid":`messenger-saved-view-${x.replace(/[^a-zA-Z0-9_-]/g,"-")}`,"data-messenger-saved-view-id":m.id,"data-active":e?"true":"false","aria-busy":A||void 0,"aria-label":k,title:k,className:K("group relative flex min-w-0 [contain-intrinsic-size:auto_44px] [content-visibility:auto] rounded-[calc(var(--radius-md)-2px)] border text-[color:var(--messenger-group-entry-text)] transition-[background-color,border-color,color] dark:text-[color:var(--messenger-group-entry-text-dark)]",v?"items-center gap-2 px-1.5 py-1.5":"items-start gap-3 px-2 py-2.5",e?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]",s&&"opacity-80 shadow-sm ring-1 ring-border/70"),children:[i.jsx(EH,{compact:v,dragHandleProps:A?void 0:r,label:`Drag ${k}`}),i.jsxs(sn,{to:aj(m.id),"aria-current":e?"page":void 0,"aria-label":k,title:k,className:K("flex min-w-0 flex-1 pr-7 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",v?"items-center gap-2":"items-start gap-3"),children:[i.jsx("span",{className:K("flex shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_88%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_82%,transparent)] text-current/75",v?"h-7 w-7":"mt-0.5 h-10 w-10"),children:i.jsx(HBn,{savedView:m})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-[13px] font-medium leading-tight text-current/88",children:k}),!v&&!w&&m.subtitle?i.jsx("span",{className:"mt-0.5 block truncate text-[12px] text-current/62",children:m.subtitle}):null]})]}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-label":`Saved View actions for ${k}`,disabled:A,className:K("absolute top-1/2 right-1.5 z-10 flex -translate-y-1/2 items-center justify-center rounded-md p-1 text-current/65 opacity-0 transition-[opacity,background-color,color] hover:bg-white/40 hover:text-current focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 group-hover:opacity-100 group-focus-within:opacity-100 data-[state=open]:opacity-100 dark:hover:bg-white/10",v?"h-5 w-5":"h-6 w-6"),children:i.jsx(hl,{className:"h-3.5 w-3.5","aria-hidden":!0})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay text-foreground",children:[i.jsxs(r6,{children:[i.jsxs(s6,{disabled:y.length===0&&!t,children:[i.jsx(aE,{className:"h-4 w-4"}),"Move to group"]}),i.jsxs(i6,{className:"surface-overlay text-foreground",children:[t&&u?i.jsx(Xt,{onClick:()=>u(g),children:"Move out of group"}):null,y.map(S=>i.jsxs(Xt,{onClick:()=>d(S.id,g),children:[i.jsx(RD,{icon:S.icon}),S.name]},S.id))]})]}),i.jsxs(Xt,{className:"text-destructive focus:text-destructive",onClick:()=>f(m.id),children:[i.jsx(yi,{className:"h-4 w-4"}),"Remove from Messenger"]})]})]})]})}const xde="rudder:messenger:discord-cta:v1",Mft="rudder:messenger:discord-cta:eligible:v1",YPe=360*60*60*1e3;function XBn(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Mft)==="eligible"}catch{return!1}}function GBn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(xde);if(!e)return null;if(e==="dismissed"){const n=Date.now();return window.localStorage.setItem(xde,String(n)),n}const t=Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function YBn(){return i.jsx("svg",{"data-testid":"discord-logo",viewBox:"0 0 16 16",fill:"currentColor",className:"size-4","aria-hidden":!0,children:i.jsx("path",{d:"M13.545 2.907a13.227 13.227 0 0 0-3.257-1.011c-.14.25-.3.58-.408.845a12.003 12.003 0 0 0-3.658 0 8.238 8.238 0 0 0-.419-.845 13.301 13.301 0 0 0-3.26 1.012C.514 5.953-.034 8.927.241 11.872a13.582 13.582 0 0 0 4.001 2.02 9.594 9.594 0 0 0 .987-1.35 8.169 8.169 0 0 1-1.555-.76c.131-.095.259-.195.382-.297a9.705 9.705 0 0 0 8.005 0c.124.102.252.202.382.297-.497.29-1.017.544-1.56.759a9.653 9.653 0 0 0 .988 1.35 13.57 13.57 0 0 0 4.001-2.02c.323-3.415-.551-6.362-2.327-8.964ZM5.369 10.075c-.956 0-1.747-.868-1.747-1.934 0-1.065.775-1.934 1.747-1.934.978 0 1.764.87 1.747 1.934 0 1.066-.775 1.934-1.747 1.934Zm5.263 0c-.956 0-1.747-.868-1.747-1.934 0-1.065.775-1.934 1.747-1.934.978 0 1.764.87 1.747 1.934 0 1.066-.769 1.934-1.747 1.934Z"})})}function JBn(e){var n;const t=Pn();t&&(e.preventDefault(),(n=t.forceOpenExternal)==null||n.call(t,UVe))}function eQn(){var d;const{selectedOrganizationId:e}=jr(),[t,n]=h.useState(XBn),[r,s]=h.useState(GBn),o=((d=Me({queryKey:V.agentRuns(e??"__none__",void 0,Nie),queryFn:()=>zo.list(e,void 0,Nie),enabled:!!e&&!t}).data)==null?void 0:d.some(u=>u.status==="succeeded"))??!1;h.useEffect(()=>{if(!(t||!o)){try{window.localStorage.setItem(Mft,"eligible")}catch{}n(!0)}},[t,o]),h.useEffect(()=>{if(r===null)return;const u=YPe-(Date.now()-r);if(u<=0){s(null);return}const f=window.setTimeout(()=>s(null),u);return()=>window.clearTimeout(f)},[r]);const l=()=>{const u=Date.now();try{window.localStorage.setItem(xde,String(u))}catch{}s(u)},c=r===null||Date.now()-r>=YPe;return!t&&!o||!c?null:i.jsx("div",{"data-testid":"messenger-discord-cta",className:"shrink-0 border-t border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] px-2 py-2.5",children:i.jsxs("div",{className:"group relative",children:[i.jsxs("a",{href:UVe,target:"_blank",rel:"noopener noreferrer",onClick:JBn,className:"flex min-h-[68px] items-center gap-2.5 rounded-[calc(var(--radius-md)-1px)] border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_52%,transparent)] px-3 py-2.5 pr-9 text-left transition-[background-color,border-color,transform] duration-150 hover:border-[color:color-mix(in_oklab,var(--border-strong)_78%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] active:translate-y-px focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30","aria-label":"Join our Discord — chat with the team and other builders",children:[i.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)+1px)] bg-[color:color-mix(in_oklab,#7289da_15%,transparent)] text-[#7289da]",children:i.jsx(YBn,{})}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-[12px] font-semibold leading-4 text-foreground",children:"Join our Discord"}),i.jsx("span",{className:"mt-0.5 block text-[11px] leading-4 text-muted-foreground",children:"Chat with the team and other builders."})]})]}),i.jsx("button",{type:"button",onClick:l,className:"absolute right-1.5 top-1.5 flex size-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground/70 transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30","aria-label":"Dismiss Discord invitation",title:"Dismiss",children:i.jsx(Is,{className:"size-3.5","aria-hidden":!0})})]})})}const tQn=40;function k2e(e){if(!/^\/messenger(?:\/|$)/.test(e))return{kind:"root"};if(/^\/messenger\/workbench(?:\/|$)/.test(e))return{kind:"workbench"};if(/^\/messenger\/chat\/[^/]+(?:\/|$)/.test(e)){const n=e.match(/^\/messenger\/chat\/([^/]+)(?:\/|$)/);return{kind:"chat",conversationId:n==null?void 0:n[1]}}if(/^\/messenger\/chat(?:\/|$)/.test(e))return{kind:"chat"};if(/^\/messenger\/saved\/[^/]+(?:\/|$)/.test(e)){const n=e.match(/^\/messenger\/saved\/([^/]+)(?:\/|$)/);return{kind:"saved_view",savedViewId:(n==null?void 0:n[1])??""}}if(/^\/messenger\/issues\/[^/]+(?:\/|$)/.test(e)){const n=e.match(/^\/messenger\/issues\/([^/]+)(?:\/|$)/);return{kind:"issue",issueId:(n==null?void 0:n[1])??""}}if(/^\/messenger\/issues(?:\/|$)/.test(e))return{kind:"issues"};if(/^\/messenger\/approvals(?:\/|$)/.test(e))return{kind:"approvals"};const t=e.match(/^\/messenger\/system\/([^/]+)(?:\/|$)/);if(t){const n=t[1];if(n==="failed-runs"||n==="budget-alerts"||n==="join-requests")return{kind:"system",threadKind:n}}return{kind:"root"}}function LD(e={}){var m,g,x,y,v,w;const t=br(),{selectedOrganizationId:n}=jr(),r=k2e(fl(t.pathname)),{data:s}=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),a=((m=s==null?void 0:s.user)==null?void 0:m.id)??((g=s==null?void 0:s.session)==null?void 0:g.userId)??null,o=MK({queryKey:V.messenger.threadPages(n??"__none__",!!e.splitIssues),initialPageParam:null,queryFn:({pageParam:k})=>Ks.listThreadPage(n,{cursor:k,limit:tQn,splitIssues:e.splitIssues}),getNextPageParam:k=>k.pageInfo.hasMore?k.pageInfo.nextCursor:void 0,enabled:!!n}),l=Me({queryKey:V.messenger.issues(n??"__none__"),queryFn:()=>Ks.getIssuesThread(n),enabled:!!n&&r.kind==="issues"}),c=Me({queryKey:V.messenger.approvals(n??"__none__"),queryFn:()=>Ks.getApprovalsThread(n),enabled:!!n&&r.kind==="approvals"}),d=r.kind==="system"?r.threadKind:"__none__",u=Me({queryKey:V.messenger.system(n??"__none__",d),queryFn:()=>Ks.getSystemThread(n,d),enabled:!!n&&r.kind==="system"}),f=h.useMemo(()=>o.error instanceof Error?o.error:l.error instanceof Error?l.error:c.error instanceof Error?c.error:u.error instanceof Error?u.error:null,[c.error,l.error,u.error,o.error]),A=h.useMemo(()=>{var k;return((k=o.data)==null?void 0:k.pages.flatMap(S=>S.items))??[]},[(x=o.data)==null?void 0:x.pages]);return{currentUserId:a,selectedOrganizationId:n,threadSummaries:A,hasMoreThreadSummaries:!!o.hasNextPage,isFetchingMoreThreadSummaries:o.isFetchingNextPage,loadMoreThreadSummaries:()=>o.fetchNextPage(),issueThreadDetail:((y=l.data)==null?void 0:y.detail)??null,approvalThreadDetail:((v=c.data)==null?void 0:v.detail)??null,systemThreadDetail:((w=u.data)==null?void 0:w.detail)??null,isLoading:o.isLoading||l.isLoading||c.isLoading||u.isLoading,error:f}}const Eft="rudder.messengerLastPaths";function Dft(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Eft);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function nQn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Eft,JSON.stringify(e))}catch{}}function Rft(e){var n;const t=((n=e==null?void 0:e.split("?")[0])==null?void 0:n.split("#")[0])??"";return/^\/messenger\/chat(?:\/[^/]+)?$/.test(t)||t==="/messenger/issues"||/^\/messenger\/issues\/[^/]+$/.test(t)||t==="/messenger/approvals"||/^\/messenger\/system\/(failed-runs|budget-alerts|join-requests)$/.test(t)?t:null}function O2e(e,t){const n=Rft(t);if(!n)return;const r=Dft();r[e]=n,nQn(r)}function Lft(e){return Rft(Dft()[e])}function rQn(e,t){const n=e.match(/^\/messenger\/chat\/([^/]+)$/);return n?t.length===0?!1:t.some(r=>r.threadKey===`chat:${n[1]}`||r.href===e):!0}function sQn(e){const t=Lft(e.orgId);return t&&rQn(t,e.threadSummaries)?t:"/messenger/chat"}const zft="rudder.messengerThreadOrganizationByOrg",$ft="rudder.messengerThreadDensityByOrg",Fft="rudder.messengerSplitIssueNotificationsByOrg",Bft="rudder.messengerCollapsedProjectGroupsByOrg",bde="rudder.messengerCollapsedThreadGroupsByOrg",Qft="rudder.messengerProjectGroupOrder",yde="rudder.messengerThreadGroupOrder",Uft="rudder.messengerDefaultThreadOrder",Vft="rudder.messengerHiddenIssueThreads",iQn="rudder.projectOrder",aQn=["local-board","anonymous"],qft="latest",oQn="compact",lQn=!0;function H_(e){return e==="project"||e==="agent"||e==="kind"}function S2e(e){return H_(e)||e==="custom"}function i5(e){return H_(e)||e==="custom"}function LC(e,t){if(!(!e||typeof window>"u"))try{const n=window.localStorage.getItem(t);return(n?JSON.parse(n):{})[e]}catch{return}}function zD(e,t,n){if(!(typeof window>"u"))try{const r=window.localStorage.getItem(t),s=r?JSON.parse(r):{};window.localStorage.setItem(t,JSON.stringify({...s,[e]:n}))}catch{}}function Ene(e){const t=LC(e,zft);return t==="latest"||t==="project"||t==="agent"||t==="kind"||t==="attention"||t==="custom"?t:qft}function JPe(e,t){zD(e,zft,t)}function eIe(e){const t=LC(e,$ft);return t==="comfortable"||t==="compact"?t:oQn}function cQn(e,t){zD(e,$ft,t)}function tIe(e){const t=LC(e,Fft);return typeof t=="boolean"?t:lQn}function dQn(e,t){zD(e,Fft,t)}function uQn(e){const t=LC(e,Bft);return new Set(DH(t))}function fQn(e,t){zD(e,Bft,Array.from(t))}function Dne(e,t){if(!S2e(t))return new Set;if(t==="project")return uQn(e);const n=LC(e,bde),r=n&&typeof n=="object"&&!Array.isArray(n)?n[t]:void 0;return new Set(DH(r))}function nIe(e,t,n){if(!S2e(t))return;if(t==="project"){fQn(e,n);return}const r=LC(e,bde),s=r&&typeof r=="object"&&!Array.isArray(r)?r:{};zD(e,bde,{...s,[t]:Array.from(n)})}function DH(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function $D(e){return(e==null?void 0:e.trim())||"anonymous"}function EN(e){try{return Array.isArray(JSON.parse(e))&&JSON.parse(e).every(t=>typeof t=="string")}catch{return!1}}function AQn(e){try{const t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(n=>typeof n=="string")}catch{return!1}}function hQn(e,t,n=window.localStorage){const r=$D(t);if(r==="anonymous"||r==="local-board")return[];const s=[],a=[{prefix:iQn,suffix:`${e}`,valid:EN},{prefix:Qft,suffix:`${e}`,valid:EN},{prefix:yde,suffix:`agent:${e}`,valid:EN},{prefix:yde,suffix:`kind:${e}`,valid:EN},{prefix:Uft,suffix:`${e}`,valid:EN},{prefix:Vft,suffix:`${e}`,valid:AQn}];for(const o of a){const l=`${o.prefix}:${o.suffix}:${r}`;if(n.getItem(l)===null)for(const c of aQn){const d=n.getItem(`${o.prefix}:${o.suffix}:${c}`);if(!(d===null||!o.valid(d))){try{n.setItem(l,d),s.push(l)}catch{}break}}}return s}function mQn(e,t){var r,s;const n=((r=t==null?void 0:t.user)==null?void 0:r.id)??((s=t==null?void 0:t.session)==null?void 0:s.userId)??null;return h.useEffect(()=>{!e||!n||hQn(e,n)},[e,n]),n}function pQn(e,t){return`${Qft}:${e}:${$D(t)}`}function gQn(e,t,n){return n==="project"?pQn(e,t):`${yde}:${n}:${e}:${$D(t)}`}function xQn(e,t){return`${Uft}:${e}:${$D(t)}`}function bQn(e,t){return`${Vft}:${e}:${$D(t)}`}function Nk(e){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(e);return t?DH(JSON.parse(t)):[]}catch{return[]}}function Pk(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(DH(t)))}catch{}}function Rne(e){if(typeof window>"u")return{};try{const t=window.localStorage.getItem(e),n=t?JSON.parse(t):{};return Object.fromEntries(Object.entries(n).filter(r=>r[0].length>0&&typeof r[1]=="string"))}catch{return{}}}function yQn(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}const rIe=new Set(["channel","channelLabel","channelType","externalSource","from","imProvider","integration","integrationLabel","integrationType","origin","originKind","platform","platformType","provider","source","sourceKind","sourceLabel","sourceName","sourceType"]),vQn=new Set(["channel","context","external","integration","metadata","origin","platform","provider","source"]);function sIe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kft(e,t=0){if(t>3||!sIe(e))return[];const n=[];for(const[r,s]of Object.entries(e)){if(rIe.has(r)&&typeof s=="string"){n.push(s);continue}(rIe.has(r)||vQn.has(r))&&sIe(s)&&n.push(...Kft(s,t+1))}return n}function j2e(...e){return e.flatMap(n=>Kft(n)).some(n=>n.trim().toLowerCase().includes("feishu"))?{key:"feishu",label:"Feishu"}:null}const C2e="project:pinned";function wQn(e,t){if(t.length===0)return e;const n=new Map(e.map(l=>[l.key,l])),r=t.map(l=>n.get(l)??null).filter(l=>!!l);if(r.length===0)return e;const s=new Set(r.map(l=>l.key)),a=e.findIndex(l=>s.has(l.key));return[...e.slice(0,a).filter(l=>!s.has(l.key)),...r,...e.slice(a).filter(l=>!s.has(l.key))]}function Lne(e,t){const n=BI(e.threadKey);return!n||!t.has(n)?e:{...e,metadata:{...e.metadata,isProcessing:!0}}}function BI(e){return e.startsWith("chat:")?e.slice(5):null}function i$(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function zne(e,t,n){var x;if(e.kind!=="chat")return null;const r=BI(e.threadKey);if(!r)return null;const s=e.metadata??{},a=i$(s.preferredAgentId),o=i$(s.routedAgentId),l=i$(s.runtimeAgentId),c=i$(s.latestUserMessagePreview),d=typeof e.isPinned=="boolean"?e.isPinned:!!(n!=null&&n.isPinned),u=j2e(n,s),f=(n==null?void 0:n.sourceMetadata)??((u==null?void 0:u.key)==="feishu"?{source:"agent_integration",provider:"feishu"}:null),A=(n==null?void 0:n.mutability)??((u==null?void 0:u.key)==="feishu"?"external_bound_chat":"native_chat");if(n)return{...n,mutability:A,sourceMetadata:f,title:e.title.includes("…")?n.title:e.title,preferredAgentId:n.preferredAgentId??a,routedAgentId:n.routedAgentId??o,chatRuntime:{...n.chatRuntime,runtimeAgentId:((x=n.chatRuntime)==null?void 0:x.runtimeAgentId)??l},lastReadAt:e.lastReadAt??n.lastReadAt,unreadCount:e.unreadCount,isUnread:e.unreadCount>0,needsAttention:e.needsAttention,isPinned:d};const m=e.latestActivityAt?new Date(e.latestActivityAt):new Date,g=e.preview??e.subtitle??null;return{id:r,orgId:t,status:"active",mutability:A,title:e.title,summary:null,latestReplyPreview:g,latestUserMessagePreview:c,userMessageCount:0,preferredAgentId:a,routedAgentId:o,primaryIssueId:null,forkedFromConversationId:null,forkedFromMessageId:null,forkRootConversationId:null,primaryIssue:null,issueCreationMode:"manual_approval",planMode:!1,createdByUserId:null,lastMessageAt:m,lastReadAt:e.lastReadAt,isPinned:d,isUnread:e.unreadCount>0,unreadCount:e.unreadCount,needsAttention:e.needsAttention,resolvedAt:null,contextLinks:[],chatRuntime:{sourceType:"unconfigured",sourceLabel:"Agent unavailable",runtimeAgentId:l,agentRuntimeType:null,model:null,available:!1,error:null},sourceMetadata:f,createdAt:m,updatedAt:m}}function p5(e){return e!=null&&e.length?e.flatMap(t=>[...t.entries,...p5(t.childSections)]):[]}function Wft(e){return e!=null&&e.length?e.flatMap(t=>[t,...Wft(t.childSections)]):[]}function _4(e){return e.startsWith("project:")&&e!=="project:none"&&e!==C2e?e.slice(8):null}function kQn(e){return _4(e)?null:`messenger-section:${e}`}function OQn(e){return _4(e)??kQn(e)??e}function Zft(e){return e.startsWith("messenger-section:")?e.slice(18):e.startsWith("project:")?e:`project:${e}`}function SQn(e,t){return e==="project"?OQn(t):t}function Hft(e,t){return e==="project"?Zft(t):t}function dq(e){return`custom-group:${e}`}function Cd(e){return e.startsWith("custom-group:")?e.slice(13):null}function jQn(e,t,n=[]){if(e.length===0)return e;const r=e.filter(A=>A.isPinned),s=e.filter(A=>!A.isPinned),a=new Map(t.map((A,m)=>[A,m])),o=[],l=[];for(const A of s)_4(A.key)?o.push(A):l.push(A);o.sort((A,m)=>{const g=_4(A.key),x=_4(m.key),y=g?a.get(g):void 0,v=x?a.get(x):void 0;return y!==void 0||v!==void 0?(y??Number.MAX_SAFE_INTEGER)-(v??Number.MAX_SAFE_INTEGER):(A.label??"").localeCompare(m.label??"")});const c=[...o,...l];if(n.length===0)return[...r,...c];const d=new Map(n.map((A,m)=>[Zft(A),m])),u=new Map(c.map((A,m)=>[A.key,m])),f=[...c].sort((A,m)=>{const g=d.get(A.key),x=d.get(m.key);return g!==void 0||x!==void 0?(g??Number.MAX_SAFE_INTEGER)-(x??Number.MAX_SAFE_INTEGER):(u.get(A.key)??0)-(u.get(m.key)??0)});return[...r,...f]}function CQn(e,t,n,r=[]){if(!H_(t))return e;if(t==="project")return jQn(e,n,r);if(r.length===0)return e;const s=new Map(r.map((o,l)=>[Hft(t,o),l])),a=new Map(e.map((o,l)=>[o.key,l]));return[...e].sort((o,l)=>{const c=s.get(o.key),d=s.get(l.key);return c!==void 0||d!==void 0?(c??Number.MAX_SAFE_INTEGER)-(d??Number.MAX_SAFE_INTEGER):(a.get(o.key)??0)-(a.get(l.key)??0)})}function G1(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.trim()?n.trim():null}function Xft(e){var t;return((t=e.chatRuntime)==null?void 0:t.runtimeAgentId)??e.routedAgentId??e.preferredAgentId??null}function Gft(e,t){return e?t.get(e)??null:null}function NQn(e,t){var o,l,c;const n=((o=e==null?void 0:e.contextLinks)==null?void 0:o.find(d=>d.entityType==="project"))??null,r=typeof(n==null?void 0:n.entityId)=="string"&&n.entityId.trim()?n.entityId.trim():null,s=Gft(r,t),a=(s==null?void 0:s.name)||((l=n==null?void 0:n.entity)==null?void 0:l.label)||((c=n==null?void 0:n.entity)==null?void 0:c.identifier)||(n?"Unknown project":"No project");return r?{key:`project:${r}`,label:a,sortLabel:a,projectIcon:s==null?void 0:s.icon,projectColor:s==null?void 0:s.color}:{key:"project:none",label:a}}function PQn(e,t){var o;if(((o=e.metadata)==null?void 0:o.splitIssue)!==!0)return null;const n=e.metadata,r=G1(n,"projectId"),s=Gft(r,t),a=(s==null?void 0:s.name)??G1(n,"projectName")??(r?"Unknown project":"No project");return r?{key:`project:${r}`,label:a,sortLabel:a,projectIcon:s==null?void 0:s.icon,projectColor:s==null?void 0:s.color}:{key:"project:none",label:a}}function IQn(e,t){var n,r;if(e.thread.kind==="chat"){const s=e.conversation?Xft(e.conversation):null;if(!s)return{key:"agent:unavailable",label:"Agent unavailable"};const a=t.get(s);if(!a)return{key:"agent:unavailable",label:"Agent unavailable"};const o=a.name;return{key:`agent:${s}`,label:o,sortLabel:o}}if(((n=e.thread.metadata)==null?void 0:n.splitIssue)===!0){const s=e.thread.metadata,a=G1(s,"assigneeAgentId")??G1(s,"agentId")??G1(s,"runtimeAgentId")??G1(s,"preferredAgentId");if(!a)return{key:"agent:unassigned",label:"Unassigned"};const o=((r=t.get(a))==null?void 0:r.name)??G1(s,"assigneeAgentName")??G1(s,"agentName")??"Unknown agent";return{key:`agent:${a}`,label:o,sortLabel:o}}return{key:"system",label:"System"}}function M4(e){var t;return typeof e.thread.isPinned=="boolean"?e.thread.isPinned:!!((t=e.conversation)!=null&&t.isPinned)}function TQn(e){const t=new Set;return e.filter(n=>t.has(n.threadKey)?!1:(t.add(n.threadKey),!0))}function Yft(e){const t=new Set;return e.filter(n=>t.has(n.thread.threadKey)?!1:(t.add(n.thread.threadKey),!0))}function iIe(e){var t;return((t=e.metadata)==null?void 0:t.splitIssue)!==!0?null:[e.latestActivityAt?new Date(e.latestActivityAt).toISOString():"none",G1(e.metadata,"status")??"unknown",G1(e.metadata,"activeExecutionRunId")??"idle",String(e.unreadCount),e.needsAttention?"attention":"settled"].join("|")}function _Qn(e,t){var r,s;return((r=e.metadata)==null?void 0:r.splitIssue)!==!0?!1:e.metadata.issueId===t||e.metadata.issueIdentifier===t?!0:(((s=e.href.split("?")[0])==null?void 0:s.split("#")[0])??e.href)===`/messenger/issues/${t}`}function vde(e){var n,r;const t=e.thread.latestActivityAt??((n=e.conversation)==null?void 0:n.lastMessageAt)??((r=e.conversation)==null?void 0:r.updatedAt)??null;return t?new Date(t).getTime():Number.NEGATIVE_INFINITY}function uq(e,t){if(M4(e)!==M4(t))return M4(e)?-1:1;const n=vde(t)-vde(e);return n!==0?n:e.thread.title.localeCompare(t.thread.title)}function aIe(e){return e.entries.reduce((t,n)=>Math.max(t,vde(n)),Number.NEGATIVE_INFINITY)}function MQn(e,t){var r,s;if(!!e.isPinned!=!!t.isPinned)return e.isPinned?-1:1;const n=aIe(t)-aIe(e);return n!==0?n:(e.label??((r=e.entries[0])==null?void 0:r.thread.title)??e.key).localeCompare(t.label??((s=t.entries[0])==null?void 0:s.thread.title)??t.key)}function oIe(e,t){const n=new Map(e.map(o=>[o.key,o])),r=t.map(o=>n.get(o)??null).filter(o=>!!o);if(r.length===0)return e;const s=new Set(r.map(o=>o.key)),a=e.findIndex(o=>s.has(o.key));return a===-1?e:[...e.slice(0,a).filter(o=>!s.has(o.key)),...r,...e.slice(a).filter(o=>!s.has(o.key))]}function EQn(e,t){if(t.length===0)return e;const n=e.filter(s=>s.isPinned),r=e.filter(s=>!s.isPinned);return[...oIe(n,t),...oIe(r,t)]}function DQn(e,t){if(t.length===0)return e;const n=new Map(e.map(o=>[o.thread.threadKey,o])),r=t.map(o=>n.get(o)??null).filter(o=>!!o);if(r.length===0)return e;const s=new Set(r.map(o=>o.thread.threadKey)),a=e.findIndex(o=>s.has(o.thread.threadKey));return a===-1?e:[...e.slice(0,a).filter(o=>!s.has(o.thread.threadKey)),...r,...e.slice(a).filter(o=>!s.has(o.thread.threadKey))]}function RQn(e,t,n){const r=new Set(t.flatMap(f=>f.entries.map(A=>A.thread.threadKey))),s=t.map(f=>({key:dq(f.id),label:f.name,icon:f.icon,isPinned:f.pinned,entries:f.entries.map(A=>({...A,customGroupId:f.id}))})),a=e.filter(f=>!r.has(f.thread.threadKey)).map(f=>({...f,customGroupId:null})).sort(uq),o=Yft([...s.flatMap(f=>f.entries),...a]),l=DQn(o.filter(f=>M4(f)&&f.customGroupId===null).sort(uq),n),c=a.filter(f=>!M4(f)).map(f=>({key:f.thread.threadKey,label:null,entries:[f]})),d=EQn([...s,...c].sort(MQn),n.length>0?n:s.map(f=>f.key)),u=[...d.filter(f=>f.isPinned),...l.length>0?[{key:"custom:pinned:loose",label:null,entries:l}]:[]];return[...u.length>0?[{key:"custom:pinned",label:"Pinned",entries:[],childSections:u}]:[],...d.filter(f=>!f.isPinned)]}function LQn(e,t,n){const r=new Set,s=t.map(c=>({key:dq(c.id),label:c.name,icon:c.icon,isPinned:c.pinned,entries:c.entries.filter(d=>r.has(d.thread.threadKey)?!1:(r.add(d.thread.threadKey),!0)).map(d=>({...d,customGroupId:c.id}))})),a=Yft(e).filter(c=>!r.has(c.thread.threadKey)).map(c=>({...c,customGroupId:null})),o=Jft(a,"project",new Map,n,c=>c),l=(c,d,u,f)=>{if(f.length===0)return;const A=o.findIndex(g=>g.key===c);if(A===-1){const g={key:c,label:d,isPinned:u,entries:[],childSections:f};u?o.unshift(g):o.push(g);return}const m=o[A];m&&(o[A]={...m,childSections:[...f,...m.childSections??[]]})};return l(C2e,"Pinned",!0,s.filter(c=>c.isPinned)),l("project:none","No project",!1,s.filter(c=>!c.isPinned)),o}function zQn(e,t,n){const r=[...e];if(t<0||t>=r.length||n<0||n>=r.length)return r;const[s]=r.splice(t,1);return s===void 0||r.splice(n,0,s),r}function a$(e,t,n,r){const s=zQn(e,n,r),a=Math.min(n,r),o=Math.max(n,r),l=new Set(s.slice(a,o+1)),c=new Set(e),d=new Set(t);return[...t.filter(u=>!c.has(u)),...s.filter(u=>l.has(u)||d.has(u))]}function o$(e,t){const n=new Map;for(const r of e){const s=t(r),a=n.get(s.key);a?a.entries.push(r):n.set(s.key,{group:s,entries:[r]})}return Array.from(n.values()).sort((r,s)=>{if(r.group.key==="attention:needs")return-1;if(s.group.key==="attention:needs"||r.group.key==="project:none")return 1;if(s.group.key==="project:none")return-1;if(r.group.key==="system")return 1;if(s.group.key==="system")return-1;const a=r.group.key==="agent:unavailable"||r.group.key==="agent:unassigned",o=s.group.key==="agent:unavailable"||s.group.key==="agent:unassigned";return a&&!o?1:o&&!a?-1:(r.group.sortLabel??r.group.label).localeCompare(s.group.sortLabel??s.group.label)}).map(({group:r,entries:s})=>({key:r.key,label:r.label,projectIcon:r.projectIcon,projectColor:r.projectColor,entries:[...s].sort(uq)}))}function Jft(e,t,n,r,s){const a=[...e].sort(uq);if(t==="project"){const o=a.filter(M4),l=o$(a.filter(c=>!M4(c)),c=>{const d=PQn(c.thread,r);return d||(c.thread.kind!=="chat"?{key:"system",label:"System"}:NQn(c.conversation,r))});return o.length>0?[{key:C2e,label:"Pinned",isPinned:!0,entries:o},...l]:l}return t==="agent"?o$(a,o=>IQn(o,n)):t==="kind"?o$(a,o=>({key:`kind:${o.thread.kind}`,label:s(o.thread.kind)})):o$(a,o=>o.thread.unreadCount>0||o.thread.needsAttention?{key:"attention:needs",label:"Needs attention"}:{key:"attention:other",label:"Other threads"})}function wde(e){return e.entries.filter(n=>n.thread.unreadCount>0||n.thread.needsAttention).length+(e.childSections??[]).reduce((n,r)=>n+wde(r),0)}function lIe(e,t){const n=t.get(e.threadKey);return!n||n!==(e.latestActivityAt??"none")||e.unreadCount===0&&!e.needsAttention?e:{...e,unreadCount:0,needsAttention:!1}}function JF(e){return e.item.type==="thread"}function l$(e){return e.item.type==="saved_view"}function _y(e){var t;return(t=e.itemKey)!=null&&t.trim()?e.itemKey:JF(e)?e.threadKey:e.item.itemKey}function cIe(e){return e.dataset.messengerSavedViewId?`saved-view:${e.dataset.messengerSavedViewId}`:e.dataset.messengerThreadKey??null}function $Qn({children:e,collapsed:t,onCollapsedChange:n}){const[r,s]=h.useState({collapsed:t,generation:0}),a=h.useRef(null),o=h.useRef(t),l=h.useRef(t),c=h.useRef(0),d=h.useRef(0),u=h.useRef(null),f=h.useRef(null),A=h.useCallback(x=>{const y=a.current;if(!y)return;const v=y.querySelector("[data-messenger-group-trigger]"),w=y.querySelector("[data-messenger-group-content]");y.dataset.collapsed=x?"true":"false",v==null||v.setAttribute("aria-expanded",x?"false":"true"),w&&(x?(w.setAttribute("aria-hidden","true"),w.setAttribute("inert","")):(w.removeAttribute("aria-hidden"),w.removeAttribute("inert")),w.style.gridTemplateRows=x?"0fr":"1fr",w.style.opacity=x?"0":"1",w.style.marginTop=x?"0px":"0.25rem")},[]),m=h.useCallback((x,y)=>{u.current!==null&&cancelAnimationFrame(u.current),f.current!==null&&clearTimeout(f.current),u.current=requestAnimationFrame(()=>{u.current=null,f.current=setTimeout(()=>{f.current=null,c.current===y&&s({collapsed:x,generation:y})},0)})},[]);h.useEffect(()=>{if(d.current!==0)return;const x=c.current+1;c.current=x,o.current=t,l.current=t,s({collapsed:t,generation:x})},[t]),h.useEffect(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),f.current!==null&&clearTimeout(f.current)},[]),h.useLayoutEffect(()=>{var y;const x=(y=a.current)==null?void 0:y.querySelector("[data-messenger-group-content]");x&&(x.style.removeProperty("grid-template-rows"),x.style.removeProperty("opacity"),x.style.removeProperty("margin-top"))},[r.generation]);const g=x=>{const y=!o.current,v=c.current+1;c.current=v,d.current=v,o.current=y,A(y),m(y,v),n(y).then(()=>{l.current=y,d.current===v&&(d.current=0)},()=>{if(d.current!==v)return;d.current=0;const w=l.current,k=c.current+1;c.current=k,o.current=w,A(w),m(w,k)})};return e(r.collapsed,g,a)}const Ik=6,FQn=10,$ne=50,BQn=24,QQn=32,c$=8,UQn=40,VQn=48,qQn=1200,Fne=[120,300,700],eAt=[{value:"latest",label:"Latest activity"},{value:"project",label:"Project"},{value:"agent",label:"Agent"},{value:"kind",label:"Thread type"},{value:"attention",label:"Needs attention"}];function KQn(e){return new Promise(t=>{globalThis.setTimeout(t,e)})}function tAt(e){if(e)return`translate3d(${Math.round(e.x)}px, ${Math.round(e.y)}px, 0)`}function d$(e){var a,o,l,c,d,u;if(typeof KeyboardEvent<"u"&&e.activatorEvent instanceof KeyboardEvent){if(e.activatorEvent.shiftKey)return null;const f=(o=(a=e.active.rect)==null?void 0:a.current)==null?void 0:o.initial,A=(l=e.over)==null?void 0:l.rect;if(!f||!A)return"before";const m=f.top+f.height/2,g=A.top+A.height/2;return m<g?"after":"before"}const t=(d=(c=e.active.rect)==null?void 0:c.current)==null?void 0:d.translated,n=(u=e.over)==null?void 0:u.rect;if(!t||!n)return null;const r=t.top+t.height/2,s=Math.max(8,n.height*.25);return r<=n.top+s?"before":r>=n.bottom-s?"after":null}const WQn=e=>{const t=pqt(e);if(t.length>0)return t;const n=gqe(e);return n.length>0?n:EE(e)},ZQn={droppable:{strategy:kS.WhileDragging,frequency:OQ.Optimized}};function eB({placement:e,tone:t="accent"}){return e?i.jsx("div",{"data-testid":`messenger-insertion-line-${e}`,className:K("pointer-events-none absolute left-2 right-2 h-0.5 rounded-full",e==="before"?"-top-1":"-bottom-1",t==="group"?"bg-[color:color-mix(in_oklab,var(--messenger-group-text)_58%,transparent)]":"bg-[color:var(--accent-strong)]")}):null}function HQn(e){return e.replace(/\\/g,"\\\\").replace(/]/g,"\\]")}function XQn(e){return`[${HQn(o6(e).trim()||"Chat")}](${vj(e.id)})`}function GQn({title:e,description:t}){const{isMobile:n,setSidebarOpen:r}=jc();return i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome desktop-window-drag flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:e}),t?i.jsx("p",{className:"mt-0.5 truncate text-[12px] text-muted-foreground",children:t}):null]}),n?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>r(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]})}function YQn(e){return e==="failed-runs"||e==="budget-alerts"||e==="join-requests"}function nAt(e){var t;return e==="custom"?"Latest activity":((t=eAt.find(n=>n.value===e))==null?void 0:t.label)??"Latest activity"}function JQn({loading:e,onVisible:t,testId:n}){const r=h.useRef(null);return h.useEffect(()=>{const s=r.current;if(!s||e||typeof IntersectionObserver>"u")return;const a=s.closest("nav");if(!a)return;const o=new IntersectionObserver(l=>{l.some(c=>c.isIntersecting)&&t()},{root:a,rootMargin:"0px 0px 320px 0px"});return o.observe(s),()=>o.disconnect()},[e,t]),i.jsx("div",{ref:r,"data-testid":n,className:"flex min-h-7 items-center px-2 text-[11px] text-muted-foreground","aria-live":"polite",children:e?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[i.jsx(hn,{className:"h-3 w-3 animate-spin","aria-hidden":!0}),"Loading"]}):null})}function eUn({rule:e,density:t,splitIssueNotifications:n,onRuleChange:r,onDensityChange:s,onSplitIssueNotificationsChange:a}){const o=e!==qft&&e!=="custom",l=t==="compact",c=[o?nAt(e):null].filter(Boolean);return i.jsxs("div",{className:"group/section flex items-center justify-between px-3.5 pt-3.5",children:[i.jsxs("div",{className:"min-w-0 truncate text-[11px] font-semibold text-muted-foreground/72",children:["Threads",c.length>0?i.jsxs("span",{className:"text-muted-foreground",children:[" · ",c.join(" · ")]}):null]}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","data-testid":"messenger-thread-organization-trigger",className:K("flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",o?"opacity-100":"opacity-0 group-hover/section:opacity-100 group-focus-within/section:opacity-100"),"aria-label":"Organize threads",children:i.jsx(Mj,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"morph-popover morph-popover--from-right surface-overlay w-48 text-foreground",children:[i.jsx(pT,{className:"text-xs text-muted-foreground",children:"View"}),i.jsx(uQ,{checked:l,onCheckedChange:d=>s(d?"compact":"comfortable"),children:"Compact mode"}),i.jsx(uQ,{checked:n,onCheckedChange:d=>a(!!d),children:"Split issue notifications"}),i.jsx(Yo,{}),i.jsx(pT,{className:"text-xs text-muted-foreground",children:"Organize by"}),i.jsx(GAe,{value:e,onValueChange:d=>r(d),children:eAt.map(d=>i.jsx(fQ,{value:d.value,children:d.label},d.value))})]})]})]})}function dIe({id:e,children:t}){const{attributes:n,listeners:r,setNodeRef:s,transform:a,transition:o,isDragging:l}=nC({id:e}),{measureNow:c,measuredRect:d,setMeasuredNodeRef:u}=rAt(s);return h.useEffect(()=>{l&&c()},[l,c]),i.jsx("div",{ref:u,style:{height:l&&d?d.height:void 0,width:l&&d?d.width:void 0,transform:tAt(a),transition:o,willChange:l?"transform":void 0,zIndex:l?10:void 0},className:K("flex min-h-9 shrink-0 touch-none flex-col gap-1 rounded-[calc(var(--radius-md)-2px)]",l&&"bg-[color:color-mix(in_oklab,var(--surface-active)_56%,transparent)] opacity-90 shadow-sm ring-1 ring-border/70"),children:t({attributes:n,listeners:r},l)})}function Bne({id:e,insertionPlacement:t,disabled:n=!1,children:r}){const{attributes:s,listeners:a,setNodeRef:o,transform:l,transition:c,isDragging:d}=nC({id:e,disabled:n}),{measureNow:u,measuredRect:f,setMeasuredNodeRef:A}=rAt(o);return h.useEffect(()=>{d&&u()},[d,u]),i.jsxs("div",{ref:A,style:{height:d&&f?f.height:void 0,width:d&&f?f.width:void 0,transform:tAt(l),transition:c,willChange:d?"transform":void 0,zIndex:d?20:void 0},className:K("relative touch-none",d&&"z-20"),children:[i.jsx(eB,{placement:t??null}),r({attributes:s,listeners:a},d)]})}function rAt(e){const[t,n]=h.useState(null),[r,s]=h.useState(null),a=h.useCallback(c=>{if(!c)return;const d=c.getBoundingClientRect(),u=Math.round(d.height),f=Math.round(d.width);u<=0||f<=0||s(A=>(A==null?void 0:A.height)===u&&A.width===f?A:{height:u,width:f})},[]),o=h.useCallback(c=>{e(c),n(c),a(c)},[e,a]),l=h.useCallback(()=>{a(t)},[t,a]);return h.useEffect(()=>{if(!t||(a(t),typeof ResizeObserver>"u"))return;const c=new ResizeObserver(()=>a(t));return c.observe(t),()=>c.disconnect()},[t,a]),{measureNow:l,measuredRect:r,setMeasuredNodeRef:o}}function tUn(){var wp,kp,Kl,dm,Xd,r0,Bb,cc,um;const{pushToast:e}=ss(),t=br(),n=Yr(),r=fl(t.pathname),s=new URLSearchParams(t.search).get("perfBaseline")==="1",{selectedOrganizationId:a}=jr(),[o,l]=h.useState(()=>tIe(a)),c=LD({splitIssues:o}),d=v0e(),u=w0e(),{isMobile:f,setSidebarOpen:A}=jc(),{confirm:m}=ii(),{abortChatStream:g,isChatGenerationActive:x,setChatSendInFlight:y,setStreamDraftForChat:v}=Ift(),{activeChatIds:w}=Pft(),k=Vn(),S=k2e(r),j=h.useRef(null),C=bs("rudder:sidebar-scroll:messenger"),N=bs(),P=h.useRef(null),M=h.useRef(null),E=h.useRef(null),T=h.useRef(!0),R=h.useRef(null),_=h.useRef(null),D=h.useRef(0),U=h.useRef(null),$=h.useRef(new Map),L=h.useRef(new Set),[H,X]=h.useState(()=>new Set),[F,Q]=h.useState(0),[q,B]=h.useState({}),ee=h.useRef({}),[se,re]=h.useState(null),[ne,Ae]=h.useState(""),[Y,ce]=h.useState({}),[Oe,Fe]=h.useState(()=>new Set),[ke,Ne]=h.useState(null),[xe,ae]=h.useState(null),[fe,ve]=h.useState(""),[Se,ze]=h.useState("folder"),[ft,ie]=h.useState("amber"),[me,we]=h.useState({}),[Xe,ge]=h.useState(()=>new Set),[te,G]=h.useState(null),[oe,Ze]=h.useState(null),[Te,Be]=h.useState(null),[it,lt]=h.useState(()=>new Map),[Ue,mt]=h.useState(null),tt=h.useRef(null),dt=h.useRef(null),at=h.useRef(null),Pe=h.useRef(null),$e=h.useRef(null),ot=h.useRef({}),ue=h.useRef(null),Ie=h.useRef(c.selectedOrganizationId),Ke=h.useRef(r);Ie.current=c.selectedOrganizationId,Ke.current=r;const[De,Je]=h.useState(0),[_e,Ee]=h.useState(()=>Ene(c.selectedOrganizationId)),[Ce,kt]=h.useState(()=>eIe(c.selectedOrganizationId)),[Qe,gt]=h.useState(()=>Dne(c.selectedOrganizationId,_e)),[Nt,Gt]=h.useState({}),cn=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),Rn=mQn(c.selectedOrganizationId,cn.data),nt=h.useMemo(()=>c.selectedOrganizationId?vhe(c.selectedOrganizationId,Rn):null,[Rn,c.selectedOrganizationId]),Qt=h.useMemo(()=>!c.selectedOrganizationId||!H_(_e)?null:gQn(c.selectedOrganizationId,Rn,_e),[Rn,c.selectedOrganizationId,_e]),st=h.useMemo(()=>c.selectedOrganizationId?bQn(c.selectedOrganizationId,Rn):null,[Rn,c.selectedOrganizationId]),Rt=h.useMemo(()=>c.selectedOrganizationId?xQn(c.selectedOrganizationId,Rn):null,[Rn,c.selectedOrganizationId]),[Cn,zn]=h.useState(()=>nt?H7(nt):[]),[fs,as]=h.useState(()=>Qt?Nk(Qt):[]),[sr,Kr]=h.useState(()=>Rt?Nk(Rt):[]),[yr,ht]=h.useState(()=>st?Rne(st):{}),Vt=Yj(Mx(mw,{activationConstraint:{distance:5}}),Mx(eC,{coordinateGetter:_W})),We=h.useCallback(de=>{tt.current!==de&&(tt.current=de,G(de))},[]),Tt=h.useCallback(de=>{dt.current!==de&&(dt.current=de,Ze(de))},[]),Mn=h.useCallback(de=>{at.current!==de&&(at.current=de,Be(de))},[]),tr=h.useCallback(()=>{Pe.current&&(clearTimeout(Pe.current),Pe.current=null,$e.current=null)},[]),Ln=h.useCallback(de=>{mt(de),ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{ue.current=null,mt(He=>He===de?null:He)},qQn)},[]),pt=h.useCallback(()=>{tr(),We(null),Tt(null),Mn(null)},[tr,Mn,Tt,We]),vt=h.useCallback(de=>{We(String(de.active.id)),Tt(null),Mn(null)},[Mn,Tt,We]);h.useEffect(()=>{Ee(Ene(c.selectedOrganizationId)),kt(eIe(c.selectedOrganizationId)),l(tIe(c.selectedOrganizationId));const de=Ene(c.selectedOrganizationId);gt(Dne(c.selectedOrganizationId,de)),Gt({}),ce({}),lt(new Map),mt(null),Q(0),B({}),ue.current&&(clearTimeout(ue.current),ue.current=null)},[c.selectedOrganizationId]),h.useEffect(()=>{gt(Dne(c.selectedOrganizationId,_e)),Gt({})},[c.selectedOrganizationId,_e]),h.useEffect(()=>{if(!nt){zn([]);return}zn(H7(nt));const de=wt=>{wt.key===nt&&zn(H7(nt))},He=wt=>{const Dt=wt.detail;!Dt||Dt.storageKey!==nt||zn(Dt.orderedIds)};return window.addEventListener("storage",de),window.addEventListener(kT,He),()=>{window.removeEventListener("storage",de),window.removeEventListener(kT,He)}},[nt]),h.useEffect(()=>{if(!Qt){as([]);return}as(Nk(Qt));const de=He=>{He.key===Qt&&as(Nk(Qt))};return window.addEventListener("storage",de),()=>window.removeEventListener("storage",de)},[Qt]),h.useEffect(()=>{if(!Rt){Kr([]);return}Kr(Nk(Rt));const de=He=>{He.key===Rt&&Kr(Nk(Rt))};return window.addEventListener("storage",de),()=>window.removeEventListener("storage",de)},[Rt]),h.useEffect(()=>{if(!st){ht({});return}ht(Rne(st));const de=He=>{He.key===st&&ht(Rne(st))};return window.addEventListener("storage",de),()=>window.removeEventListener("storage",de)},[st]),h.useEffect(()=>{c.selectedOrganizationId&&Qf(k,c.selectedOrganizationId)},[c.selectedOrganizationId,k,o]);const jt=_e==="project"||_e==="agent",Zt=80,kr=Me({queryKey:V.chats.listPreview(c.selectedOrganizationId??"__none__","all",Zt),queryFn:()=>Xn.list(c.selectedOrganizationId,"all",{limit:Zt}),enabled:!!c.selectedOrganizationId&&jt}),xs=Me({queryKey:V.agents.list(c.selectedOrganizationId??"__none__"),queryFn:()=>Nn.list(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId}),la=Me({queryKey:V.projects.list(c.selectedOrganizationId??"__none__"),queryFn:()=>Mi.list(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId&&_e==="project"}),Ss=Me({queryKey:V.organizations.intelligenceProfiles(c.selectedOrganizationId??"__none__"),queryFn:()=>_n.listIntelligenceProfiles(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId}),bt=Me({queryKey:V.messenger.customGroups(c.selectedOrganizationId??"__none__"),queryFn:()=>Ks.listCustomGroups(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId}),Jt=Me({queryKey:V.messenger.savedViews(c.selectedOrganizationId??"__none__","visible",$ne,F),queryFn:()=>Ks.listSavedViews(c.selectedOrganizationId,{visibility:"visible",limit:$ne,offset:F}),enabled:!!c.selectedOrganizationId});h.useEffect(()=>{Object.keys(me).length!==0&&we(de=>{var Dt;let He=!1;const wt={...de};for(const en of((Dt=bt.data)==null?void 0:Dt.groups)??[])en.id in wt&&wt[en.id]===en.icon&&(delete wt[en.id],He=!0);return He?wt:de})},[(wp=bt.data)==null?void 0:wp.groups,me]);const nr=h.useMemo(()=>{const de=new Map;for(const He of kr.data??[])de.set(He.id,He);return de},[kr.data]),Er=h.useMemo(()=>{const de=new Map;for(const He of xs.data??[])de.set(He.id,He);return de},[xs.data]),cs=h.useMemo(()=>{const de=new Map;for(const He of la.data??[])de.set(He.id,He);return de},[la.data]),ds=h.useMemo(()=>(Ss.data??[]).some(He=>(He==null?void 0:He.purpose)==="lightweight"&&He.status==="configured"),[Ss.data]),Or=((kp=bt.data)==null?void 0:kp.groups)??[],Dr=bt.data!==void 0,Ts=h.useMemo(()=>{var He;const de=new Map;for(const wt of Object.keys(q).map(Number).sort((Dt,en)=>Dt-en))for(const Dt of q[wt]??[])Dt.orgId===c.selectedOrganizationId&&de.set(Dt.id,Dt);for(const wt of((He=Jt.data)==null?void 0:He.items)??[])wt.orgId===c.selectedOrganizationId&&de.set(wt.id,wt);return Array.from(de.values()).sort((wt,Dt)=>wt.sortOrder-Dt.sortOrder)},[q,c.selectedOrganizationId,(Kl=Jt.data)==null?void 0:Kl.items]),Ui=h.useMemo(()=>new Set(Or.flatMap(de=>de.entries).filter(l$).map(de=>de.item.savedView.id)),[Or]),fo=h.useMemo(()=>Dr?Ts.filter(de=>!Ui.has(de.id)):[],[Dr,Ui,Ts]),Ye=_e==="latest"||_e==="custom"?"custom":_e;h.useEffect(()=>tr,[tr,Ye,c.selectedOrganizationId]),h.useEffect(()=>()=>{ue.current&&(clearTimeout(ue.current),ue.current=null)},[]);const Mt=h.useMemo(()=>{const de=new Map;for(const He of Or)de.set(dq(He.id),He);return de},[Or]),An=h.useMemo(()=>{const de=c.threadSummaries.filter(He=>{const wt=iIe(He);return wt?yr[He.threadKey]!==wt:!0});return TQn(de).map(He=>lIe(He,it))},[yr,it,c.threadSummaries]);h.useEffect(()=>{it.size!==0&&lt(de=>{const He=new Map(de),wt=new Map;for(const Dt of c.threadSummaries)wt.set(Dt.threadKey,[...wt.get(Dt.threadKey)??[],Dt]);for(const Dt of Or)for(const en of Dt.entries)JF(en)&&wt.set(en.threadKey,[...wt.get(en.threadKey)??[],en.thread]);for(const[Dt,en]of de){const gn=wt.get(Dt)??[];if(gn.length===0)continue;const yn=gn.filter(Sn=>(Sn.latestActivityAt??"none")===en);if(yn.length===0){He.delete(Dt);continue}yn.some(Sn=>Sn.unreadCount>0||Sn.needsAttention)||He.delete(Dt)}return He.size===de.size?de:He})},[Or,it.size,c.threadSummaries]);const vn=h.useMemo(()=>{const de=o?An.filter(Sn=>Sn.threadKey!=="issues"):An,He=Or.map(Sn=>({id:Sn.id,name:Sn.name,icon:Sn.icon,pinned:!!Sn.pinnedAt,entries:Sn.entries.filter(JF).map(pr=>{const Fr=BI(pr.threadKey),xa=Fr?Y[Fr]:void 0,oi=Lne(lIe(pr.thread,it),w),to=xa?{...oi,title:xa}:oi;return{thread:to,conversation:c.selectedOrganizationId?zne(to,c.selectedOrganizationId,nr.get(Fr??"")??null):null,customGroupId:Sn.id}})}));if(Ye==="custom"){const Sn=de.map(pr=>{const Fr=Lne(pr,w),xa=BI(Fr.threadKey),oi=xa?nr.get(xa)??null:null,to=xa?Y[xa]:void 0,Xc=to?{...Fr,title:to}:Fr;return{thread:Xc,conversation:c.selectedOrganizationId?zne(Xc,c.selectedOrganizationId,oi):null,customGroupId:null}});return RQn(Sn,He,sr)}const wt=de.map(Sn=>{const pr=Lne(Sn,w),Fr=BI(pr.threadKey),xa=Fr?nr.get(Fr)??null:null,oi=Fr?Y[Fr]:void 0,to=oi?{...pr,title:oi}:pr;return{thread:to,conversation:c.selectedOrganizationId?zne(to,c.selectedOrganizationId,xa):null}}),Dt=Ye==="project"?LQn(wt,He,cs):Jft(wt,Ye,Er,cs,Z_),en=new Set(Or.filter(Sn=>Sn.entries.some(l$)).map(Sn=>Sn.id)),gn=He.filter(Sn=>en.has(Sn.id)).map(Sn=>({key:dq(Sn.id),label:Sn.name,icon:Sn.icon,isPinned:Sn.pinned,entries:[]})),yn=Ye==="agent"||Ye==="kind"||Ye==="attention"?[...Dt,...gn]:Dt;return i5(Ye)?CQn(yn,Ye,Cn,fs):yn},[w,Er,nr,Or,sr,Ye,it,c.selectedOrganizationId,Y,Cn,cs,fs,o,An]),fr=h.useMemo(()=>{const de=new Map;for(const He of Or)for(const wt of He.entries)JF(wt)&&de.set(wt.threadKey,He.id);if(Ye==="custom")for(const He of vn)for(const wt of p5([He]))wt.customGroupId===null&&de.set(wt.thread.threadKey,null);return de},[Or,Ye,vn]),mr=h.useMemo(()=>{const de=new Map(fr);for(const He of Or)for(const wt of He.entries)de.set(_y(wt),He.id);for(const He of fo)de.set(`saved-view:${He.id}`,null);return de},[fr,Or,fo]),Ge=h.useMemo(()=>{const de=new Map;for(const He of Or)for(const wt of He.entries)l$(wt)&&de.set(_y(wt),{entry:wt,groupId:He.id,savedView:wt.item.savedView});for(const He of fo)de.set(`saved-view:${He.id}`,{entry:null,groupId:null,savedView:He});return de},[Or,fo]),tn=h.useMemo(()=>{const de=gn=>{const yn=Ge.get(gn);if(yn)return`Saved View ${gde(yn.savedView)}`;const Sn=Mt.get(gn);return Sn?`Messenger group ${Sn.name}`:"Messenger item"},He=gn=>{if(!gn)return"the Messenger list";const yn=Cd(gn)??mr.get(gn)??null,Sn=yn?Or.find(pr=>pr.id===yn):null;return Sn?`Messenger group ${Sn.name}`:"a Messenger item"},wt=(gn,yn)=>{var Fr;const Sn=Ge.get(gn);if(!Sn)return yn&&yn!==gn?"valid":"invalid";if(H.has(gn))return"busy";if(!yn||yn===gn)return"invalid";const pr=Cd(yn);if(pr)return pr===Sn.groupId?"invalid":"valid";if(mr.has(yn)){if(mr.get(yn)!==null||Ge.has(yn))return"valid";const xa=(Fr=p5(vn).find(oi=>oi.thread.threadKey===yn))==null?void 0:Fr.thread.kind;return xa==="chat"||xa==="issues"?"valid":"invalid"}return"invalid"};return{announcements:{onDragStart:({active:gn})=>`Picked up ${de(String(gn.id))}.`,onDragOver:({active:gn,over:yn})=>`Moving ${de(String(gn.id))} over ${He(yn?String(yn.id):null)}.`,onDragEnd:({active:gn,over:yn})=>{const Sn=String(gn.id),pr=wt(Sn,yn?String(yn.id):null);if(pr==="busy")return`${de(Sn)} already has a move in progress.`;if(pr==="invalid")return`Move canceled for ${de(Sn)}. That is not a valid destination.`;const Fr=Ge.get(Sn),xa=yn?String(yn.id):null,oi=xa?p5(vn).find(to=>to.thread.threadKey===xa):null;return(Fr==null?void 0:Fr.groupId)===null&&(oi==null?void 0:oi.customGroupId)===null&&(oi.thread.kind==="chat"||oi.thread.kind==="issues")?d$({active:gn,over:yn})?`Reorder requested for ${de(Sn)}.`:`Group requested for ${de(Sn)}.`:`Move requested for ${de(Sn)}. Messenger will announce when the server saves the change.`},onDragCancel:({active:gn})=>`Move canceled for ${de(String(gn.id))}.`},screenReaderInstructions:{draggable:"Press Space to pick up a Messenger item. Use the arrow keys to choose a destination, then press Space again to reorder. Hold Shift while picking up to group with a loose Chat or Issue. Press Escape to cancel."}}},[mr,Mt,Or,vn,H,Ge]),Gn=h.useMemo(()=>{var wt;if(!te)return null;const de=Ge.get(te);if(de)return gde(de.savedView);const He=Mt.get(te);return He?He.name:((wt=p5(vn).find(Dt=>Dt.thread.threadKey===te))==null?void 0:wt.thread.title)??"Messenger item"},[Mt,te,vn,Ge]),Wr=h.useCallback((de,He)=>{if(Ye!=="custom"||!He||de===He)return null;if(!mr.has(de))return Cd(de)&&Cd(He)?"reorder-group":null;const Dt=mr.get(de)??null,en=mr.has(He)?mr.get(He)??null:void 0,gn=Cd(He)??en;return Ge.has(de)&&en===null?Dt?"move-out-of-group":"reorder-entry":Dt&&en===null?"move-out-of-group":gn&&Dt!==gn?"move-into-group":Dt&&en&&Dt===en||Dt===null&&en===null?"reorder-entry":null},[mr,Ye,Ge]),mn=h.useMemo(()=>{const de=[],He=i5(Ye),wt=(Dt,en)=>{for(const gn of Dt??[]){const yn=He?[...en,gn.key]:[];for(const[Sn,pr]of gn.entries.entries())pr.thread.unreadCount>0&&de.push({threadKey:pr.thread.threadKey,groupKey:He?gn.key:null,sectionPath:yn,entryIndex:He?Sn:null});wt(gn.childSections,yn)}};return wt(vn,[]),de},[Ye,vn]),Bn=h.useMemo(()=>{if(De<=0||mn.length===0)return null;const de=_.current,He=de?mn.findIndex(wt=>wt.threadKey===de):-1;return He===mn.length-1&&c.hasMoreThreadSummaries?null:mn[(He+1)%mn.length]??null},[c.hasMoreThreadSummaries,De,mn]),Ci=De>0&&D.current!==De&&c.hasMoreThreadSummaries&&!c.isFetchingMoreThreadSummaries&&!c.isLoading&&(mn.length===0||!!_.current&&mn.findIndex(de=>de.threadKey===_.current)===mn.length-1);(dm=mn[0])==null||dm.threadKey;const Vi=h.useCallback(de=>{P.current=de,C(de)},[C]),Vr=h.useMemo(()=>{var de;return S.kind==="chat"&&S.conversationId?`chat:${S.conversationId}`:S.kind==="issue"?((de=An.find(He=>_Qn(He,S.issueId)))==null?void 0:de.threadKey)??`issue:${S.issueId}`:S.kind==="issues"?"issues":S.kind==="approvals"?"approvals":S.kind==="system"?S.threadKind:null},[S,An]),oc=S.kind==="saved_view"?S.savedViewId:null,Ao=h.useMemo(()=>{const de=vn.map(Dt=>({key:Dt.key,kind:"section",section:Dt})),He=fo.map(Dt=>({key:`saved-view:${Dt.id}`,kind:"saved-view",savedView:Dt})),wt=[...de,...He];return Ye==="custom"?wQn(wt,sr):wt},[sr,Ye,fo,vn]),ml=h.useCallback(de=>{const He=te?VQn:UQn,wt=Math.max(0,de.startIndex-He),Dt=Math.min(de.count-1,de.endIndex+He),en=Math.floor(wt/c$)*c$,gn=Math.min(de.count-1,Math.ceil((Dt+1)/c$)*c$-1);return Array.from({length:gn-en+1},(yn,Sn)=>en+Sn)},[te]),ho=wct({count:Ao.length,getScrollElement:()=>P.current,estimateSize:()=>Ce==="compact"?42:58,getItemKey:de=>{var He;return((He=Ao[de])==null?void 0:He.key)??de},overscan:0,rangeExtractor:ml,directDomUpdates:!0,directDomUpdatesMode:"transform",useFlushSync:!1}),vs=ho.getVirtualItems(),aA=h.useMemo(()=>Ao.filter(de=>de.kind==="saved-view"?Ye==="custom":(Ye!=="custom"||de.section.key!=="custom:pinned")&&(Ye!=="project"||!de.section.isPinned)).map(de=>de.key),[Ye,Ao]),hf=h.useMemo(()=>{if(!i5(Ye)||!Vr)return new Map;const de=new Map;for(const He of Wft(vn)){const wt=He.entries.findIndex(Dt=>Dt.thread.threadKey===Vr);wt!==-1&&de.set(He.key,wt+1)}return de},[Vr,Ye,vn]),Gi=h.useMemo(()=>An.find(de=>de.threadKey===Vr)??null,[Vr,An]),bd=h.useMemo(()=>S.kind==="issue"?!!Gi:S.kind==="issues"?!!c.issueThreadDetail:S.kind==="approvals"?!!c.approvalThreadDetail:S.kind==="system"?!!c.systemThreadDetail:!1,[Gi,c.approvalThreadDetail,c.issueThreadDetail,c.systemThreadDetail,S]),lc=h.useMemo(()=>{var de,He,wt;return S.kind==="issue"?(Gi==null?void 0:Gi.latestActivityAt)??null:S.kind==="issues"?((de=c.issueThreadDetail)==null?void 0:de.latestActivityAt)??null:S.kind==="approvals"?((He=c.approvalThreadDetail)==null?void 0:He.latestActivityAt)??null:S.kind==="system"?((wt=c.systemThreadDetail)==null?void 0:wt.latestActivityAt)??null:(Gi==null?void 0:Gi.latestActivityAt)??null},[Gi==null?void 0:Gi.latestActivityAt,(Xd=c.approvalThreadDetail)==null?void 0:Xd.latestActivityAt,(r0=c.issueThreadDetail)==null?void 0:r0.latestActivityAt,(Bb=c.systemThreadDetail)==null?void 0:Bb.latestActivityAt,S]),Qn=()=>{f&&A(!1)},Vo=de=>{c.selectedOrganizationId&&O2e(c.selectedOrganizationId,de),Qn()},yd=de=>{const He=c.selectedOrganizationId;if(Vo(de.href),!He||de.unreadCount===0&&!de.needsAttention)return;const wt=de.latestActivityAt??null,Dt=`${He}:${de.threadKey}:${wt??"none"}`;j.current!==Dt&&(j.current=Dt,Ln(de.threadKey),lt(en=>{const gn=wt instanceof Date?wt.toISOString():wt??"none";if(en.get(de.threadKey)===gn)return en;const yn=new Map(en);return yn.set(de.threadKey,gn),yn}),_ie(k,He,de.threadKey,wt),Ks.markThreadRead(He,de.threadKey,wt?new Date(wt).toISOString():null).then(async()=>{await Qf(k,He),await k.invalidateQueries({queryKey:V.sidebarBadges(He)}),de.kind==="issues"&&await k.invalidateQueries({queryKey:V.messenger.issues(He)}),de.kind==="approvals"&&await k.invalidateQueries({queryKey:V.messenger.approvals(He)}),YQn(de.kind)&&await k.invalidateQueries({queryKey:V.messenger.system(He,de.kind)})}).catch(()=>{j.current=null,lt(en=>{if(!en.has(de.threadKey))return en;const gn=new Map(en);return gn.delete(de.threadKey),gn}),Qf(k,He)}))},Pc=de=>{Ee(de),c.selectedOrganizationId&&JPe(c.selectedOrganizationId,de)},eo=de=>{kt(de),c.selectedOrganizationId&&cQn(c.selectedOrganizationId,de)},$a=de=>{l(de),c.selectedOrganizationId&&dQn(c.selectedOrganizationId,de)},_s=h.useCallback(de=>L.current.has(de)?!1:(L.current.add(de),X(new Set(L.current)),!0),[]),et=h.useCallback(de=>{L.current.delete(de),X(new Set(L.current))},[]),Hn=async()=>{c.selectedOrganizationId&&await k.invalidateQueries({queryKey:V.messenger.customGroups(c.selectedOrganizationId)})},dr=h.useCallback(async de=>{const He=new Set([0,F,...Object.keys(q).map(Number)]);await Promise.all([k.invalidateQueries({queryKey:V.messenger.customGroups(de)}),...Array.from(He).map(wt=>k.invalidateQueries({queryKey:V.messenger.savedViews(de,"visible",$ne,wt)}))]),Ie.current===de&&(B({}),Q(0))},[q,k,F]),ca=xt({mutationFn:async({name:de,icon:He,threadKey:wt})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to create a Messenger group");return Ks.createCustomGroupWithEntries(c.selectedOrganizationId,{autoGenerateName:!1,icon:He,itemKeys:[wt],name:de})},onSuccess:async()=>{c.selectedOrganizationId&&Pc("latest"),await Hn()}}),wi=xt({mutationFn:({groupId:de,data:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to update a Messenger group");return Ks.updateCustomGroup(c.selectedOrganizationId,de,He)},onSuccess:Hn}),Ni=h.useCallback((de,He)=>{const wt=c.selectedOrganizationId;if(!wt)return Promise.reject(new Error("Organization is required to update a Messenger group"));const en=(ot.current[de]??Promise.resolve()).catch(()=>{}).then(async()=>{await Ks.updateCustomGroup(wt,de,{collapsed:He})});return ot.current[de]=en,en.then(async()=>{ot.current[de]===en&&(delete ot.current[de],await Hn())},gn=>{ot.current[de]===en&&(delete ot.current[de],Hn()),e({title:"Could not update group",body:gn instanceof Error?gn.message:"Please try again.",tone:"error"})}),en},[c.selectedOrganizationId,e,Hn]),vd=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to regenerate a Messenger group title");return Ks.regenerateCustomGroupTitle(c.selectedOrganizationId,de)},onMutate:de=>{ge(He=>{const wt=new Set(He);return wt.add(de),wt})},onSettled:async(de,He,wt)=>{ge(Dt=>{const en=new Set(Dt);return en.delete(wt),en}),await Hn()}}),r1=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to separate a Messenger group");return Ks.separateCustomGroup(c.selectedOrganizationId,de)},onSuccess:async()=>{c.selectedOrganizationId&&await dr(c.selectedOrganizationId)},onError:de=>{e({title:"Could not separate Messenger group",body:de instanceof Error?de.message:"Try again.",tone:"error"})}}),mf=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to reorder Messenger groups");return Ks.reorderCustomGroups(c.selectedOrganizationId,de)},onSuccess:Hn}),el=xt({mutationFn:({groupId:de,itemKeys:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to reorder Messenger group entries");return Ks.reorderCustomGroupEntries(c.selectedOrganizationId,de,He)},onSuccess:Hn}),_l=xt({mutationFn:({groupId:de,itemKey:He,itemKeys:wt,organizationId:Dt})=>Ks.reorderCustomGroupEntries(Dt,de,wt),onSuccess:async(de,{organizationId:He})=>{await dr(He),e({title:"Saved View moved",body:"The Messenger group order was updated.",tone:"success"})},onError:de=>{e({title:"Could not move Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{itemKey:wt})=>{et(wt)}}),ai=xt({mutationFn:({groupId:de,threadKey:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to move a Messenger thread");return Ks.assignCustomGroupEntry(c.selectedOrganizationId,de,He)},onSuccess:async()=>{Pc("latest"),await Hn()}}),tl=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to move a Messenger thread");return Ks.removeCustomGroupEntry(c.selectedOrganizationId,de)},onSuccess:Hn}),wd=xt({mutationFn:({groupId:de,itemKey:He,organizationId:wt})=>Ks.assignCustomGroupEntry(wt,de,He),onSuccess:async(de,{organizationId:He})=>{await dr(He),e({title:"Saved View moved",body:"The Messenger group was updated.",tone:"success"})},onError:de=>{e({title:"Could not move Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{itemKey:wt})=>{et(wt)}}),pf=h.useCallback((de,He)=>{const wt=c.selectedOrganizationId;!wt||!_s(He)||wd.mutate({groupId:de,itemKey:He,organizationId:wt})},[_s,c.selectedOrganizationId,wd]),Hc=xt({mutationFn:({itemKey:de,organizationId:He,nextOrderKeys:wt,orderStorageKey:Dt})=>Ks.removeCustomGroupEntry(He,de),onSuccess:async(de,{nextOrderKeys:He,orderStorageKey:wt,organizationId:Dt})=>{await dr(Dt),He&&wt&&Ie.current===Dt&&(Kr(He),Pk(wt,He)),e({title:"Saved View moved",body:"The Saved View is now in the Messenger sidebar.",tone:"success"})},onError:de=>{e({title:"Could not move Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{itemKey:wt})=>{et(wt)}}),bp=h.useCallback(de=>{const He=c.selectedOrganizationId;!He||!_s(de)||Hc.mutate({itemKey:de,organizationId:He})},[_s,c.selectedOrganizationId,Hc]),Lb=xt({mutationFn:({anchorItemKey:de,itemKeys:He,name:wt,organizationId:Dt,savedViewItemKey:en})=>Ks.createCustomGroupWithEntries(Dt,{anchorItemKey:de,autoGenerateName:!1,itemKeys:He,name:wt}),onSuccess:async(de,{organizationId:He})=>{JPe(He,"latest"),Ie.current===He&&Ee("latest"),await dr(He),e({title:"Saved View grouped",body:"Created or reused the Chat or Issue group.",tone:"success"})},onError:de=>{e({title:"Could not group Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{savedViewItemKey:wt})=>{et(wt)}}),yp=h.useCallback(de=>{const He=Array.from(document.querySelectorAll("[data-messenger-thread-key],[data-messenger-saved-view-id]")),wt=He.findIndex(en=>en.dataset.messengerSavedViewId===de);if(wt===-1)return null;const Dt=He[wt+1]??He[wt-1]??null;return Dt?cIe(Dt):null},[]),s1=h.useCallback(async({focusItemKey:de,organizationId:He,savedViewId:wt})=>{var en;u==null||u.finalizeSavedViewRemoval(He,wt);const Dt=d.getState().organizations[He];for(const gn of Object.values((Dt==null?void 0:Dt.tabsByViewInstanceId)??{}))gn.savedViewId===wt&&d.unbindSavedViewForOrganization(He,gn.viewInstanceId,wt);if(Ie.current===He&&Ke.current===aj(wt)&&n("/messenger/workbench",{replace:!0}),VVt(k,He,wt),await dr(He),await k.invalidateQueries({queryKey:V.messenger.primaryRailPins(He)}),de&&Ie.current===He){const gn=Array.from(document.querySelectorAll("[data-messenger-thread-key],[data-messenger-saved-view-id]")).find(yn=>cIe(yn)===de);(en=(gn==null?void 0:gn.querySelector("a[href]"))??(gn==null?void 0:gn.querySelector("button,[tabindex]"))??gn)==null||en.focus()}e({title:"Removed from Messenger",body:"The open Main tab remains available for this session.",tone:"success"})},[d,n,e,k,dr,u]),gf=xt({mutationFn:async({organizationId:de,savedViewId:He,focusItemKey:wt})=>(await Ks.deleteSavedView(de,He),{focusItemKey:wt,organizationId:de,savedViewId:He}),onMutate:({organizationId:de,savedViewId:He})=>{u==null||u.setSavedViewRemovalPending(de,He,!0)},onSuccess:s1,onError:async(de,{focusItemKey:He,organizationId:wt,savedViewId:Dt})=>{let en=de instanceof Nl&&de.status===404,gn=!1;if(!en)try{await Ks.getSavedView(wt,Dt),gn=!0}catch(yn){en=yn instanceof Nl&&yn.status===404}if(en){await s1({focusItemKey:He,organizationId:wt,savedViewId:Dt});return}gn&&(u==null||u.setSavedViewRemovalPending(wt,Dt,!1)),e({title:gn?"Could not remove Saved View":"Could not confirm Saved View removal",body:gn?de instanceof Error?de.message:"Try again.":"The move remains paused. Retry Remove to reconcile it.",tone:"error"})}}),om=h.useCallback(de=>{const He=c.selectedOrganizationId;He&&gf.mutate({focusItemKey:yp(de),organizationId:He,savedViewId:de})},[c.selectedOrganizationId,yp,gf]),xf=h.useCallback(de=>{const He=de.over?String(de.over.id):null;Tt(He);const wt=String(de.active.id);let Dt=Wr(wt,He);const en=Ge.get(wt),gn=He?p5(vn).find(pr=>pr.thread.threadKey===He):null;if((en==null?void 0:en.groupId)===null&&(gn==null?void 0:gn.customGroupId)===null&&(gn.thread.kind==="chat"||gn.thread.kind==="issues")&&(Dt=d$(de)?"reorder-entry":"move-into-group"),Mn(Dt),Dt!=="move-into-group"||!He||Ye!=="custom"){tr();return}const yn=Cd(He)??mr.get(He)??null,Sn=yn?Or.find(pr=>pr.id===yn):null;if(!Sn||!Sn.collapsed){tr();return}$e.current===Sn.id&&Pe.current||(tr(),$e.current=Sn.id,Pe.current=setTimeout(()=>{Pe.current=null,$e.current=null,Ni(Sn.id,!1)},500))},[tr,mr,Or,Ye,vn,Wr,Ge,Ni,Mn,Tt]),kd=de=>{const He=Mt.get(de);if(He){Ni(He.id,!He.collapsed);return}S2e(Ye)&&gt(wt=>{const Dt=new Set(wt);return Dt.has(de)?Dt.delete(de):Dt.add(de),c.selectedOrganizationId&&nIe(c.selectedOrganizationId,Ye,Dt),Dt})},lm=h.useCallback(de=>{var oi,to,Xc,Gc;pt();const{active:He,over:wt}=de;if(!wt||He.id===wt.id||!i5(Ye))return;const Dt=c.selectedOrganizationId;if(!Dt)return;if(Ye==="custom"){const he=String(He.id),rt=String(wt.id),Pt=Ge.get(he)??null;if(Pt){const Rr=Ao.filter(Oa=>Oa.key!=="custom:pinned").map(Oa=>Oa.key),ua=Oa=>{if(!Rt)return null;const Ba=Rr.includes(he)?Rr:[...Rr,he],Od=Ba.indexOf(he),dc=Ba.filter(Io=>Io!==he).indexOf(rt);if(Od===-1||dc===-1)return null;const Op=Math.min(Ba.length-1,dc+(Oa==="after"?1:0));return a$(Ba,sr,Od,Op)},Xs=Oa=>{!Rt||!Oa||(Kr(Oa),Pk(Rt,Oa))},mo=Cd(rt),ka=mr.has(rt)?mr.get(rt)??null:void 0,Yc=mo??ka;if(ka===null&&fr.has(rt)){const Oa=p5(vn).find(Od=>Od.thread.threadKey===rt),Ba=d$(de);if(Oa&&(Oa.thread.kind==="chat"||Oa.thread.kind==="issues")&&Ba===null&&_s(he)){Lb.mutate({anchorItemKey:rt,itemKeys:[rt,he],name:Oa.thread.title.trim()||"New group",organizationId:Dt,savedViewItemKey:he});return}if(!Oa||Ba===null)return}if(Yc&&Yc!==Pt.groupId&&_s(he)){wd.mutate({groupId:Yc,itemKey:he,organizationId:Dt});return}if(Yc&&Yc===Pt.groupId){const Oa=Or.find(dc=>dc.id===Pt.groupId),Ba=(Oa==null?void 0:Oa.entries.slice().sort((dc,Op)=>dc.sortOrder-Op.sortOrder).map(_y))??[],Od=Ba.indexOf(he),Mu=Ba.indexOf(rt);Od!==-1&&Mu!==-1&&Od!==Mu&&_s(he)&&_l.mutate({groupId:Pt.groupId,itemKey:he,itemKeys:g2(Ba,Od,Mu),organizationId:Dt});return}if(ka===null){const Oa=d$(de),Ba=Rr.indexOf(he),Od=Rr.indexOf(rt),Mu=Oa??(Pt.groupId||Ba<Od?"after":"before"),dc=ua(Mu);Pt.groupId&&_s(he)?Hc.mutate({itemKey:he,nextOrderKeys:dc??void 0,orderStorageKey:Rt,organizationId:Dt}):Pt.groupId||Xs(dc)}return}const Yt=Ao.filter(Rr=>Rr.key!=="custom:pinned").map(Rr=>Rr.key),ur=((to=(oi=vn.find(Rr=>Rr.key==="custom:pinned"))==null?void 0:oi.childSections)==null?void 0:to.flatMap(Rr=>Rr.entries.map(ua=>ua.thread.threadKey)))??[],Hr=(Rr,ua,Xs)=>{if(!Rt)return;const mo=a$(Rr,sr,ua,Xs);Kr(mo),Pk(Rt,mo)},Wl=fr.has(he),fm=fr.has(rt),Gd=fr.get(he)??null,uh=fm?fr.get(rt)??null:void 0,_u=Cd(rt)??uh,Ml=Cd(he),El=Cd(rt);if(Ml&&El){const Rr=Or.find(ka=>ka.id===Ml),ua=Or.find(ka=>ka.id===El);if(!Rr||!ua||!!Rr.pinnedAt!=!!ua.pinnedAt)return;const Xs=Rr.pinnedAt?((Gc=(Xc=vn.find(ka=>ka.key==="custom:pinned"))==null?void 0:Xc.childSections)==null?void 0:Gc.map(ka=>ka.key).filter(ka=>!!Cd(ka)))??[]:vn.map(ka=>ka.key).filter(ka=>!!Cd(ka)),mo=Xs.indexOf(he),Zl=Xs.indexOf(rt);if(mo!==-1&&Zl!==-1){const ka=g2(Xs,mo,Zl);if(Rt){const Yc=a$(Xs,sr,mo,Zl);Kr(Yc),Pk(Rt,Yc)}mf.mutate(ka.map(Cd).filter(Yc=>!!Yc))}return}if(Wl&&fm&&Gd===null&&uh===null&&he!==rt){const Rr=ur.includes(he)&&ur.includes(rt)?ur:Yt,ua=Rr.indexOf(he),Xs=Rr.indexOf(rt);ua!==-1&&Xs!==-1&&Hr(Rr,ua,Xs);return}if(Wl&&fm&&Gd&&uh===null&&he!==rt){const Rr=Yt.indexOf(rt);if(Rr!==-1){const ua=Yt.includes(he)?Yt:[...Yt.slice(0,Rr),he,...Yt.slice(Rr)],Xs=ua.indexOf(he),mo=ua.indexOf(rt);Xs!==-1&&mo!==-1&&Hr(ua,Xs,mo)}tl.mutate(he);return}if(Wl&&_u!==void 0){const Rr=fr.get(he)??null;if(Rr!==_u){if(!_u){const ua=Yt.indexOf(rt);if(ua!==-1){const Xs=Yt.includes(he)?Yt:[...Yt.slice(0,ua),he,...Yt.slice(ua)],mo=Xs.indexOf(he),Zl=Xs.indexOf(rt);mo!==-1&&Zl!==-1&&Hr(Xs,mo,Zl)}}_u?ai.mutate({groupId:_u,threadKey:he}):tl.mutate(he);return}if(Rr===null){const ua=Yt.indexOf(he),Xs=Yt.indexOf(rt);ua!==-1&&Xs!==-1&&Hr(Yt,ua,Xs);return}}if(Gd&&uh&&Gd===uh){const Rr=Or.find(Zl=>Zl.id===Gd),ua=(Rr==null?void 0:Rr.entries.slice().sort((Zl,ka)=>Zl.sortOrder-ka.sortOrder).map(_y))??[],Xs=ua.indexOf(he),mo=ua.indexOf(rt);Xs!==-1&&mo!==-1&&el.mutate({groupId:Gd,itemKeys:g2(ua,Xs,mo)});return}}const en=Ye==="custom"?vn.filter(he=>he.key!=="custom:pinned").map(he=>he.key):vn.filter(he=>Ye!=="project"||!he.isPinned).map(he=>he.key),gn=en.indexOf(He.id),yn=en.indexOf(wt.id);if(gn===-1||yn===-1)return;if(Ye==="custom"){const he=g2(en,gn,yn);if(Rt){const Pt=a$(en,sr,gn,yn);Kr(Pt),Pk(Rt,Pt)}const rt=he.map(Cd).filter(Pt=>!!Pt);rt.length>0&&mf.mutate(rt);return}if(!Qt||!H_(Ye))return;const Sn=g2(en,gn,yn).map(he=>SQn(Ye,he));if(as(Sn),Pk(Qt,Sn),Ye!=="project")return;const pr=Sn.map(he=>Hft(Ye,he)).map(he=>_4(he)).filter(he=>!!he),Fr=new Set(pr),xa=[...pr,...Cn.filter(he=>!Fr.has(he))];zn(xa),nt&&whe(nt,xa)},[ai,_s,Lb,mr,fr,Or,sr,Rt,Ye,Qt,c.selectedOrganizationId,wd,vn,Cn,nt,Hc,tl,el,mf,_l,pt,Ge,Ao]),Pu=(de,He)=>{var wt;if(He<de.entries.length){Gt(Dt=>({...Dt,[de.key]:Math.min(de.entries.length,He+FQn)}));return}Mt.has(de.key)||c.hasMoreThreadSummaries&&!c.isFetchingMoreThreadSummaries&&((wt=c.loadMoreThreadSummaries)==null||wt.call(c))},bf=de=>{Gt(He=>({...He,[de]:Ik}))},vp=()=>{const de=Jt.data,He=de==null?void 0:de.pageInfo.nextOffset;!(de!=null&&de.pageInfo.hasMore)||He===null||He===void 0||(B(wt=>({...wt,[de.pageInfo.offset]:de.items})),Q(He))},zb=de=>{const He=iIe(de);!He||!st||ht(wt=>{const Dt={...wt,[de.threadKey]:He};return yQn(st,Dt),Dt})},oA=(de,He,wt)=>{M.current=de,E.current=He,T.current=!0,ae(null),Ne({mode:"create",threadKey:wt}),ve(""),ze("folder"),ie("amber")},da=h.useCallback(()=>{Ne(null),ve(""),ze("folder"),ie("amber")},[]),lA=()=>{if(!(ke!=null&&ke.threadKey))return;const de=fe.trim();if(!de)return;const He=_ne(Se,ft);ca.mutate({name:de,icon:He||null,threadKey:ke.threadKey}),da()},Fa=(de,He,wt)=>{window.setTimeout(()=>{de.isConnected&&He.isConnected&&oA(de,He,wt)},0)};h.useEffect(()=>{if(!ke)return;const de=M.current,He=P.current;if(!(de!=null&&de.isConnected)||!(He!=null&&He.contains(de)))return;const wt=()=>{const Dt=de.getBoundingClientRect(),en=He.getBoundingClientRect();Dt.bottom>en.top&&Dt.top<en.bottom||(T.current=!1,da())};return He.addEventListener("scroll",wt,{passive:!0}),()=>He.removeEventListener("scroll",wt)},[da,ke]);const $b=de=>{Ne(null),ae({group:de,name:de.name})},e0=()=>{ae(null)},Iu=()=>{if(!xe)return;const de=xe.name.trim();de&&(wi.mutate({groupId:xe.group.id,data:{name:de}}),e0())},Zd=(de,He)=>{const wt=c.selectedOrganizationId;if(!wt)return;const gn=(ee.current[de]??Promise.resolve()).catch(()=>{}).then(async()=>{try{await Ks.updateCustomGroup(wt,de,{icon:He}),await Hn()}catch{we(Sn=>{if(Sn[de]!==He)return Sn;const pr={...Sn};return delete pr[de],pr})}}).finally(()=>{ee.current[de]===gn&&delete ee.current[de]});ee.current[de]=gn},Hd=(de,He)=>{const wt=me[de.id]??de.icon,en=cq(wt).color??FI(de),gn=_ne(He,en)||null;we(yn=>({...yn,[de.id]:gn})),Zd(de.id,gn)},lh=(de,He)=>{const wt=me[de.id]??de.icon,Dt=cq(wt),en=_ne(Dt.glyph,He)||null;we(gn=>({...gn,[de.id]:en})),Zd(de.id,en)},i1=async de=>{await m({title:"Separate items",description:`Move the items in "${de.name}" back into the main list? The Messenger threads will stay intact.`,confirmLabel:"Separate items",tone:"default"})&&r1.mutate(de.id)},a1=(de,He,wt=!1)=>{var Sn,pr;const{thread:Dt,conversation:en}=de,gn=Vr===Dt.threadKey,yn=Ue===Dt.threadKey;if(Dt.kind==="chat"&&en){const Fr=Xft(en),xa=!Dv(en);return i.jsx(qBn,{conversation:en,agent:Fr?Er.get(Fr)??null:null,agentId:Fr,sourceBadge:j2e(en,Dt.metadata),href:Dt.href,active:gn,generating:((Sn=Dt.metadata)==null?void 0:Sn.isProcessing)===!0||typeof((pr=Dt.metadata)==null?void 0:pr.activeGenerationId)=="string"&&Dt.metadata.activeGenerationId.length>0,density:Ce,renaming:se===en.id,renameDraft:ne,onRenameDraftChange:Ae,onCommitRename:yf,onCancelRename:()=>{Ae(""),re(null)},onStartRename:()=>{re(en.id),Ae(en.title)},onRegenerateTitle:ds?()=>ut.mutate(en.id):void 0,titleGenerating:Oe.has(en.id),onFork:()=>h8.mutate(en.id),onArchive:()=>{c.selectedOrganizationId&&fqe(k,c.selectedOrganizationId,en.id),ch.mutate({chatId:en.id,data:{status:"archived"}})},onDelete:async()=>{await m({title:"Delete chat",description:`Delete "${YF(en)}"? This cannot be undone.`,confirmLabel:"Delete",tone:"destructive"})&&Nw.mutate({chatId:en.id,generating:x(en.id)})},archiveDeleteAllowed:xa,onTogglePin:()=>{c.selectedOrganizationId&&uqe(k,c.selectedOrganizationId,en.id,!en.isPinned),dh.mutate({chatId:en.id,pinned:!en.isPinned})},onToggleUnread:()=>{dh.mutate({chatId:en.id,unread:!en.isUnread})},onCopyConversationLink:()=>void n0(en),customGroups:Or,customGroupId:de.customGroupId,customGroupPending:de.customGroupId?!Or.some(oi=>oi.id===de.customGroupId):!1,onMoveToCustomGroup:oi=>ai.mutate({groupId:oi,threadKey:Dt.threadKey}),onRemoveFromCustomGroup:()=>tl.mutate(Dt.threadKey),onCreateCustomGroup:(oi,to)=>Fa(oi,to,Dt.threadKey),dragHandleProps:He,dragging:wt,onSelect:Vo},Dt.threadKey)}return i.jsx(KBn,{thread:Dt,active:gn,density:Ce,preserveUnreadEmphasis:yn,onTogglePin:()=>{c.selectedOrganizationId&&dqe(k,c.selectedOrganizationId,Dt.threadKey,!Dt.isPinned),cm.mutate({threadKey:Dt.threadKey,pinned:!Dt.isPinned})},onHideIssue:()=>zb(Dt),customGroups:Or,customGroupId:de.customGroupId,customGroupPending:de.customGroupId?!Or.some(Fr=>Fr.id===de.customGroupId):!1,onMoveToCustomGroup:Fr=>ai.mutate({groupId:Fr,threadKey:Dt.threadKey}),onRemoveFromCustomGroup:()=>tl.mutate(Dt.threadKey),onCreateCustomGroup:(Fr,xa)=>Fa(Fr,xa,Dt.threadKey),dragHandleProps:He,dragging:wt,onSelect:yd},Dt.threadKey)},o1=(de,He,wt=!1)=>{const Dt=`saved-view:${de.id}`;return i.jsx(Mne,{active:oc===de.id,currentGroupId:null,density:Ce,dragHandleProps:He,dragging:wt,itemKey:Dt,savedView:de,groups:Or,onMove:pf,onRemove:om,placementPending:H.has(Dt)})},Tu=(de,He,wt=!1)=>{var Io,l1;const Dt=i5(Ye),en=Ye==="agent"&&de.key.startsWith("agent:")?de.key.slice(6):null,gn=en?Er.get(en)??null:null,yn=Mt.get(de.key)??null,Sn=!!(yn&&Xe.has(yn.id)),pr=yn,Fr=yn?yn.collapsed:Dt&&Qe.has(de.key),xa=te?mr.get(te):void 0,oi=oe===de.key||de.entries.some(Jn=>Jn.thread.threadKey===oe)||!!(yn!=null&&yn.entries.some(Jn=>_y(Jn)===oe)),to=Ye==="custom"&&!!pr&&!!te&&xa!==void 0&&xa!==(yn==null?void 0:yn.id)&&Te==="move-into-group"&&oi,Xc=Ye==="custom"&&!yn&&de.label===null&&oi&&te!==de.key&&Te==="move-out-of-group",Gc=Jn=>{if(!te||oe!==Jn||Te!=="reorder-entry")return null;if(!yn&&de.label===null&&de.entries.length===1){const pl=vn.filter(Tc=>Tc.key!=="custom:pinned").map(Tc=>Tc.key),Jc=pl.indexOf(te),vf=pl.indexOf(Jn);return Jc===-1||vf===-1||Jc===vf?null:Jc<vf?"after":"before"}const Pi=de.entries.map(pl=>pl.thread.threadKey),To=Pi.indexOf(te),qo=Pi.indexOf(Jn);return To===-1||qo===-1||To===qo?null:To<qo?"after":"before"},he=(()=>{var Jc,vf;if(!te||oe!==de.key||Te!=="reorder-group")return null;const Jn=Cd(te),Pi=Jn?Or.find(Tc=>Tc.id===Jn):null,To=Pi!=null&&Pi.pinnedAt?((vf=(Jc=vn.find(Tc=>Tc.key==="custom:pinned"))==null?void 0:Jc.childSections)==null?void 0:vf.map(Tc=>Tc.key).filter(Tc=>!!Cd(Tc)))??[]:vn.filter(Tc=>Tc.key!=="custom:pinned").map(Tc=>Tc.key),qo=To.indexOf(te),pl=To.indexOf(de.key);return qo===-1||pl===-1||qo===pl?null:qo<pl?"after":"before"})(),rt=Dt?Math.max(Nt[de.key]??Ik,hf.get(de.key)??Ik):de.entries.length,Pt=Dt?de.entries.slice(0,rt):de.entries,Yt=Dt&&rt<de.entries.length,ur=Dt&&!yn&&!!c.hasMoreThreadSummaries&&rt>=de.entries.length&&de.entries.length>=Ik,Hr=!Fr&&(Yt||ur||!!(c.isFetchingMoreThreadSummaries&&ur)),Wl=!Fr&&Dt&&rt>Ik,fm=Dt?`messenger-thread-section-${oo(de.key)}-content`:void 0,Gd=Ye==="custom"&&de.key==="custom:pinned",uh=Ye==="custom"&&de.key==="custom:pinned:loose",_u=Gd,Ml=Ye==="custom"&&(!!yn||Gd||uh)&&(yn?yn.entries.length>0:Pt.length>0),El=Ye==="custom"&&!yn&&(de.label===null||Gd)&&Pt.length===1,Rr=Ye==="custom"?((Io=de.childSections)==null?void 0:Io.filter(Jn=>!!Cd(Jn.key)).map(Jn=>Jn.key))??[]:[],ua=(l1=de.childSections)!=null&&l1.length?i.jsx(l3,{items:Rr,strategy:WP,children:i.jsx("div",{className:"flex flex-col gap-1",children:de.childSections.map(Jn=>Rr.includes(Jn.key)?i.jsx(dIe,{id:Jn.key,children:(Pi,To)=>Tu(Jn,Pi,To)},Jn.key):i.jsx("div",{className:"flex shrink-0 flex-col gap-1",children:Tu(Jn)},Jn.key))})}):null,Xs=new Map(Pt.map(Jn=>[Jn.thread.threadKey,Jn])),mo=Jn=>Ml?i.jsx(Bne,{id:Jn.thread.threadKey,insertionPlacement:Gc(Jn.thread.threadKey),children:(Pi,To)=>a1(Jn,Pi,To)},Jn.thread.threadKey):i.jsxs("div",{className:"relative",children:[i.jsx(eB,{placement:Gc(Jn.thread.threadKey)}),a1(Jn,El?He:void 0)]},Jn.thread.threadKey),ka=(yn==null?void 0:yn.entries.slice().sort((Jn,Pi)=>Jn.sortOrder-Pi.sortOrder))??[],Yc=yn?ka.map(Jn=>{if(l$(Jn)){const To=_y(Jn),qo=H.has(To),pl=i.jsx(Mne,{active:oc===Jn.item.savedView.id,currentGroupId:yn.id,density:Ce,entry:Jn,groups:Or,onMove:pf,onMoveOutOfGroup:bp,onRemove:om,placementPending:qo});return Ml?i.jsx(Bne,{id:To,disabled:qo,children:(Jc,vf)=>i.jsx(Mne,{active:oc===Jn.item.savedView.id,currentGroupId:yn.id,density:Ce,dragHandleProps:Jc,dragging:vf,entry:Jn,groups:Or,onMove:pf,onMoveOutOfGroup:bp,onRemove:om,placementPending:qo})},To):i.jsx("div",{children:pl},To)}const Pi=Xs.get(Jn.threadKey);return Pi?mo(Pi):null}):Pt.map(mo),Oa=yn?ka.map(_y):Pt.map(Jn=>Jn.thread.threadKey),Ba=Yc.flatMap((Jn,Pi)=>Jn==null?[]:[{key:Oa[Pi]??`${de.key}:${Pi}`,node:Jn}]),Od=Bn!=null&&Bn.sectionPath.includes(de.key)?Bn.threadKey:null,Mu=Ba.length>30?i.jsx(m0e,{items:Ba,getItemKey:Jn=>Jn.key,estimateSize:()=>Ce==="compact"?34:42,itemGap:4,overscan:te?QQn:BQn,preventScrollBlanking:!0,scrollElementRef:P,targetKey:Od,onTargetMounted:Jn=>{var To;if(!Bn||Jn!==Bn.threadKey||De<=0)return;const Pi=Array.from(((To=P.current)==null?void 0:To.querySelectorAll("[data-messenger-thread-key]"))??[]).find(qo=>qo.dataset.messengerThreadKey===Jn);Pi&&(Pi.scrollIntoView({block:"nearest",behavior:"smooth"}),_.current=Jn,D.current=De,Ine(De),U.current=null)},testId:`messenger-section-virtual-entries-${oo(de.key)}`,children:Jn=>Jn.node}):Ba.map(Jn=>i.jsx("div",{children:Jn.node},Jn.key)),dc=Ml?i.jsx(l3,{items:yn?ka.map(_y):Pt.map(Jn=>Jn.thread.threadKey),strategy:WP,children:Mu}):Mu,Op=i.jsxs(i.Fragment,{children:[ua,i.jsx("div",{className:"flex flex-col gap-1",children:dc}),Hr||Wl?i.jsxs("div",{"data-messenger-scroll-coverage-row":!0,className:"mx-1.5 flex items-center gap-1.5 px-2 py-1",children:[Hr?i.jsx(JQn,{testId:`messenger-thread-section-${oo(de.key)}-auto-loader`,loading:!!(c.isFetchingMoreThreadSummaries&&ur),onVisible:()=>Pu(de,rt)}):null,Wl?i.jsx("button",{type:"button","data-testid":`messenger-thread-section-${oo(de.key)}-collapse`,className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[11px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",onClick:()=>bf(de.key),children:"Collapse"}):null]}):null]});if(de.label&&pr){const Jn=wde(de);return i.jsx($Qn,{collapsed:pr.collapsed,onCollapsedChange:Pi=>Ni(pr.id,Pi),children:(Pi,To,qo)=>i.jsxs("div",{ref:qo,"data-testid":`messenger-thread-section-${oo(de.key)}`,"data-messenger-scroll-coverage-surface":!0,"data-collapsed":Pi?"true":"false","data-drag-move-target":to?"true":void 0,"data-drag-intent":to?"move-into-group":void 0,className:K("group/custom-group relative mx-0.5 rounded-[calc(var(--radius-md)-1px)] border p-1 text-[color:var(--messenger-group-text)] transition-[background-color,border-color,box-shadow] duration-150 dark:text-[color:var(--messenger-group-text-dark)]",Pi&&!to?"border-transparent bg-transparent shadow-none hover:border-[color:var(--messenger-group-border)] hover:bg-[color:var(--messenger-group-bg-hover)] has-[:focus-visible]:border-[color:var(--messenger-group-border)] has-[:focus-visible]:bg-[color:var(--messenger-group-bg-hover)] dark:border-transparent dark:bg-transparent dark:hover:border-[color:var(--messenger-group-border-dark)] dark:hover:bg-[color:var(--messenger-group-bg-hover-dark)] dark:has-[:focus-visible]:border-[color:var(--messenger-group-border-dark)] dark:has-[:focus-visible]:bg-[color:var(--messenger-group-bg-hover-dark)]":"border-[color:var(--messenger-group-border)] bg-[color:var(--messenger-group-bg)] shadow-[0_8px_20px_-18px_rgba(15,23,42,0.45)] hover:bg-[color:var(--messenger-group-bg-hover)] dark:border-[color:var(--messenger-group-border-dark)] dark:bg-[color:var(--messenger-group-bg-dark)] dark:hover:bg-[color:var(--messenger-group-bg-hover-dark)]",to&&"ring-2 ring-[color:color-mix(in_oklab,var(--messenger-group-text)_34%,transparent)]"),style:_Bn(pr),children:[i.jsx(eB,{placement:he,tone:"group"}),i.jsxs("div",{"data-messenger-scroll-coverage-row":!0,className:"flex min-h-8 items-center gap-1.5",children:[i.jsx(EH,{dragHandleProps:He,label:`Drag group ${de.label}`,compact:!0}),i.jsxs("button",{type:"button","data-messenger-group-trigger":!0,"aria-expanded":!Pi,className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-[calc(var(--radius-sm)-2px)] px-0.5 text-left text-[12px] font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",onClick:To,children:[Pi?i.jsx(bi,{className:"h-3 w-3 shrink-0","aria-hidden":!0}):i.jsx(qr,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),i.jsx(RD,{icon:pr.icon,color:FI(pr)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:de.label}),Sn?i.jsxs("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-title-generating`,className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-white/35 px-1.5 py-0.5 text-[10px] font-semibold text-current/75","aria-label":"Generating group title",children:[i.jsx(hn,{className:"h-2.5 w-2.5 animate-spin","aria-hidden":!0}),"Naming"]}):null,Jn>0?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-attention-count`,className:"shrink-0 rounded-full bg-white/45 px-1.5 py-0.5 text-[10px] font-semibold",children:Jn}):null]}),to?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-drop-intent`,className:"shrink-0 rounded-full bg-white/45 px-1.5 py-0.5 text-[10px] font-semibold text-current/80",children:"Move into group"}):null,yn?i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-label":"Group actions",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-current/70 opacity-0 transition-[opacity,background-color,color] hover:bg-white/45 hover:text-current focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 group-hover/custom-group:opacity-100 group-focus-within/custom-group:opacity-100 data-[state=open]:opacity-100",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"messenger-thread-actions-menu morph-popover morph-popover--from-right surface-overlay text-foreground",children:[i.jsxs(Xt,{onClick:()=>$b(yn),children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename..."]}),i.jsxs(Xt,{disabled:Sn,onClick:()=>vd.mutate(yn.id),children:[Sn?i.jsx(hn,{className:"h-4 w-4 animate-spin"}):i.jsx(KA,{className:"h-4 w-4"}),"Regenerate title"]}),i.jsx(Xt,{onClick:()=>wi.mutate({groupId:yn.id,data:{pinned:!yn.pinnedAt}}),children:yn.pinnedAt?i.jsxs(i.Fragment,{children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}):i.jsxs(i.Fragment,{children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]})}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(wo,{className:"h-4 w-4"}),"Change icon"]}),i.jsx(i6,{className:"morph-popover morph-popover--from-left surface-overlay w-auto p-2 text-foreground",style:wft(FI({id:yn.id,icon:me[yn.id]??yn.icon,sortOrder:yn.sortOrder})),children:i.jsx(kft,{icon:me[yn.id]??yn.icon,ariaLabel:"Group icons",onIconChange:pl=>Hd(yn,pl)})})]}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(ZK,{className:"h-4 w-4"}),"Pick color"]}),i.jsx(i6,{className:"morph-popover morph-popover--from-left surface-overlay text-foreground",children:W_.map(pl=>{const Jc=DD[pl];return i.jsxs(Xt,{onClick:()=>lh(yn,pl),children:[i.jsx("span",{className:"inline-flex h-3.5 w-3.5 rounded-full border border-[color:color-mix(in_oklab,var(--border-strong)_42%,transparent)]",style:{backgroundColor:Jc.swatch},"aria-hidden":!0}),pl[0].toUpperCase()+pl.slice(1)]},pl)})})]}),i.jsx(Yo,{}),i.jsxs(Xt,{onClick:()=>void i1(yn),children:[i.jsx(aE,{className:"h-4 w-4"}),"Separate items"]})]})]}):null]}),i.jsx("div",{"data-testid":fm,"data-messenger-group-content":!0,className:K("grid",Pi||wt?"mt-0 grid-rows-[0fr] opacity-0":"mt-1 grid-rows-[1fr] opacity-100"),"aria-hidden":Pi||wt?"true":void 0,inert:Pi||wt?!0:void 0,children:i.jsx("div",{className:"min-h-0 overflow-hidden",children:Op})})]})})}return!de.label&&Xc?i.jsxs("div",{"data-drag-drop-target":"true","data-drag-intent":"move-out-of-group",className:"relative rounded-[calc(var(--radius-md)-1px)] ring-2 ring-[color:color-mix(in_oklab,var(--accent-strong)_30%,transparent)] ring-offset-1 ring-offset-[color:var(--surface-page)] transition-[background-color,border-color] duration-150",children:[i.jsx("div",{className:"pointer-events-none absolute -top-1 left-3 right-3 h-0.5 rounded-full bg-[color:var(--accent-strong)]"}),i.jsx("div",{"data-testid":`messenger-thread-section-${oo(de.key)}-drop-intent`,className:"pointer-events-none absolute right-2 top-1 z-10 rounded-full bg-[color:color-mix(in_oklab,var(--surface-elevated)_94%,transparent)] px-1.5 py-0.5 text-[10px] font-semibold text-[color:var(--accent-strong)] shadow-sm",children:"Move out of group"}),Op]}):i.jsxs(i.Fragment,{children:[de.label&&!_u?Dt?(()=>{const Jn=wde(de);return i.jsxs("button",{type:"button",...He==null?void 0:He.attributes,...He==null?void 0:He.listeners,"data-testid":`messenger-thread-section-${oo(de.key)}`,"aria-expanded":!Fr,className:"relative mx-1.5 flex min-h-8 items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] px-1.5 py-1.5 text-left text-[11px] font-semibold text-muted-foreground/72 transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_54%,transparent)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",onClick:()=>kd(de.key),children:[i.jsx(eB,{placement:he}),Fr?i.jsx(bi,{className:"h-3 w-3 shrink-0","aria-hidden":!0}):i.jsx(qr,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),_4(de.key)&&de.projectIcon?i.jsx(uo,{color:de.projectColor,icon:de.projectIcon,size:"xs",iconClassName:"h-3.5 w-3.5",testId:`messenger-thread-section-${oo(de.key)}-project-icon`}):null,gn?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-agent-avatar`,"aria-hidden":"true",className:"flex h-4 w-4 shrink-0 items-center justify-center overflow-hidden rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)]",children:i.jsx(_g,{icon:gn==null?void 0:gn.icon,role:gn==null?void 0:gn.role,fallbackSeed:gn.id,className:"h-full w-full rounded-full"})}):null,i.jsx("span",{className:"min-w-0 flex-1 truncate",children:de.label}),Jn>0?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-attention-count`,className:"shrink-0 rounded-full bg-[color:color-mix(in_oklab,var(--accent-info)_16%,transparent)] px-1.5 py-0.5 text-[10px] font-semibold text-[color:var(--accent-info)]",children:Jn}):null]})})():i.jsx("div",{"data-testid":`messenger-thread-section-${oo(de.key)}`,className:"px-3 pb-1 pt-2 text-[11px] font-semibold text-muted-foreground/72",children:de.label}):null,i.jsx("div",{"data-testid":_u?`messenger-thread-section-${oo(de.key)}`:fm,className:K("grid transition-[grid-template-rows,opacity,margin-top] duration-200 ease-out",Fr?"mt-0 grid-rows-[0fr] opacity-0":_u?"mt-0 grid-rows-[1fr] opacity-100":"mt-1 grid-rows-[1fr] opacity-100"),"aria-hidden":Fr?"true":void 0,inert:Fr?!0:void 0,children:i.jsx("div",{className:"min-h-0 overflow-hidden",children:Op})})]})},cA=de=>de.kind==="saved-view"?aA.includes(de.key)?i.jsx(Bne,{id:de.key,disabled:H.has(de.key),children:(He,wt)=>o1(de.savedView,He,wt)}):o1(de.savedView):aA.includes(de.key)?i.jsx(dIe,{id:de.key,children:(He,wt)=>Tu(de.section,He,wt)}):i.jsx("div",{className:"flex shrink-0 flex-col gap-1",children:Tu(de.section)}),t0=de=>de.kind==="saved-view"?o1(de.savedView):i.jsx("div",{className:"flex shrink-0 flex-col gap-1",children:Tu(de.section)}),Ic=async de=>{c.selectedOrganizationId&&(await Promise.all([Qf(k,c.selectedOrganizationId),k.invalidateQueries({queryKey:V.chats.list(c.selectedOrganizationId,"all")}),k.invalidateQueries({queryKey:V.chats.list(c.selectedOrganizationId,"active")})]),de&&await Promise.all([k.invalidateQueries({queryKey:V.chats.detail(c.selectedOrganizationId,de)}),k.invalidateQueries({queryKey:V.chats.messages(c.selectedOrganizationId,de)})]))},ch=xt({mutationFn:({chatId:de,data:He})=>Xn.update(de,He),onSuccess:async de=>{de.status==="archived"&&S.kind==="chat"&&S.conversationId===de.id&&n("/messenger"),re(He=>He===de.id?null:He),await Ic(de.id)},onError:async(de,He)=>{await Ic(He.chatId)}}),Fb=xt({mutationFn:({chatId:de,title:He})=>Xn.update(de,{title:He}),onMutate:async({chatId:de,title:He})=>{c.selectedOrganizationId&&(ce(wt=>({...wt,[de]:He})),await cqe(k,c.selectedOrganizationId),f4(k,c.selectedOrganizationId,de,He))},onSuccess:async de=>{c.selectedOrganizationId&&f4(k,c.selectedOrganizationId,de.id,de.title),await Ic(de.id),ce(He=>{if(!(de.id in He))return He;const wt={...He};return delete wt[de.id],wt})},onError:async(de,He)=>{await Ic(He.chatId),ce(wt=>{if(!(He.chatId in wt))return wt;const Dt={...wt};return delete Dt[He.chatId],Dt})}}),Nw=xt({mutationFn:async({chatId:de,generating:He})=>{He&&(g(de),await Xn.stopMessageStream(de).catch(()=>{}),v(de,null),y(de,!1));let wt=null;for(let Dt=0;Dt<=Fne.length;Dt+=1)try{return He?await Xn.remove(de,{cancelActive:!0}):await Xn.remove(de)}catch(en){if(wt=en,!(He&&en instanceof Nl&&en.status===409)||Dt>=Fne.length)throw en;await KQn(Fne[Dt])}throw wt},onSuccess:async de=>{S.kind==="chat"&&S.conversationId===de.id&&n("/messenger/chat"),await Ic(de.id)}}),dh=xt({mutationFn:({chatId:de,pinned:He,unread:wt})=>Xn.updateUserState(de,{pinned:He,unread:wt}),onSuccess:async de=>{await Ic(de.id)},onError:async(de,He)=>{await Ic(He.chatId)}}),ut=xt({mutationFn:de=>Xn.regenerateTitle(de),onMutate:de=>{Fe(He=>{const wt=new Set(He);return wt.add(de),wt})},onSuccess:async de=>{c.selectedOrganizationId&&f4(k,c.selectedOrganizationId,de.id,de.title)},onSettled:async(de,He,wt)=>{Fe(Dt=>{const en=new Set(Dt);return en.delete(wt),en}),await Ic(wt)}}),h8=xt({mutationFn:de=>Xn.fork(de,{}),onSuccess:async de=>{await Promise.all([Ic(de.id),c.selectedOrganizationId?k.invalidateQueries({queryKey:V.messenger.customGroups(c.selectedOrganizationId)}):Promise.resolve()]),n(`/messenger/chat/${de.id}`)},onError:async(de,He)=>{await Ic(He)}}),cm=xt({mutationFn:({threadKey:de,pinned:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to update Messenger thread state");return Ks.updateThreadUserState(c.selectedOrganizationId,de,{pinned:He})},onSuccess:async()=>{await Ic()},onError:async()=>{await Ic()}}),yf=()=>{const de=ne.trim();if(!se||!de){re(null);return}re(null),Fb.mutate({chatId:se,title:de})},n0=async de=>{try{await navigator.clipboard.writeText(XQn(de))}catch{}};return h.useEffect(()=>{if(!c.selectedOrganizationId||!Vr||S.kind==="chat"||!Gi||Gi.unreadCount===0&&!Gi.needsAttention||!bd)return;const de=c.selectedOrganizationId,He=lc??Gi.latestActivityAt??"none",wt=`${de}:${Vr}:${He}`;j.current!==wt&&(j.current=wt,lt(Dt=>{const en=Gi.latestActivityAt instanceof Date?Gi.latestActivityAt.toISOString():Gi.latestActivityAt??"none";if(Dt.get(Vr)===en)return Dt;const gn=new Map(Dt);return gn.set(Vr,en),gn}),_ie(k,de,Vr,lc),Ks.markThreadRead(de,Vr,lc?new Date(lc).toISOString():null).then(async()=>{await Qf(k,de),await k.invalidateQueries({queryKey:V.sidebarBadges(de)}),S.kind==="issues"&&await k.invalidateQueries({queryKey:V.messenger.issues(de)}),S.kind==="approvals"&&await k.invalidateQueries({queryKey:V.messenger.approvals(de)}),S.kind==="system"&&await k.invalidateQueries({queryKey:V.messenger.system(de,S.threadKind)})}).catch(()=>{j.current=null,lt(Dt=>{if(!Dt.has(Vr))return Dt;const en=new Map(Dt);return en.delete(Vr),en})}))},[Gi,bd,Vr,lc,c.selectedOrganizationId,k,S]),h.useEffect(()=>{if(typeof document>"u")return;const de=()=>{const wt=VPe();wt>0&&Je(wt)},He=VPe();return He>0&&Je(He),document.addEventListener(Ade,de),()=>{document.removeEventListener(Ade,de)}},[]),h.useEffect(()=>{_.current=null},[c.selectedOrganizationId,o,_e]),h.useEffect(()=>{mn.length>0||(_.current=null)},[mn.length]),h.useEffect(()=>{if(!Ci)return;const de={requestId:De,loadedCount:An.length},He=U.current;He&&He.requestId===de.requestId&&He.loadedCount===de.loadedCount||(U.current=de,c.loadMoreThreadSummaries())},[c.loadMoreThreadSummaries,Ci,De,An.length]),h.useEffect(()=>{De<=0||D.current!==De&&(Bn||Ci||c.isFetchingMoreThreadSummaries||c.isLoading||c.hasMoreThreadSummaries||mn.length>0||(D.current=De,Ine(De),U.current=null))},[c.hasMoreThreadSummaries,c.isFetchingMoreThreadSummaries,c.isLoading,Ci,De,Bn,mn.length]),h.useEffect(()=>{if(!Bn||De<=0||D.current===De)return;const de=Bn.sectionPath.filter(Sn=>Qe.has(Sn));if(de.length>0){gt(Sn=>{if(!de.some(Fr=>Sn.has(Fr)))return Sn;const pr=new Set(Sn);for(const Fr of de)pr.delete(Fr);return c.selectedOrganizationId&&i5(Ye)&&nIe(c.selectedOrganizationId,Ye,pr),pr});return}const He=Bn.sectionPath.map(Sn=>Mt.get(Sn)??null).find(Sn=>Sn==null?void 0:Sn.collapsed)??null;if(He){$.current.get(He.id)!==De&&($.current.set(He.id,De),Ni(He.id,!1));return}for(const Sn of Bn.sectionPath){const pr=Cd(Sn);pr&&$.current.delete(pr)}if(Bn.groupKey&&Bn.entryIndex!==null){const Sn=Bn.entryIndex+1,pr=Nt[Bn.groupKey]??Ik;if(Sn>pr){Gt(Fr=>({...Fr,[Bn.groupKey]:Sn}));return}}const wt=Bn.sectionPath[0]??null;if(wt){const Sn=Ao.findIndex(pr=>pr.key===wt);Sn!==-1&&ho.scrollToIndex(Sn,{align:"center"})}let Dt=!1,en=0,gn=0;const yn=()=>{if(Dt)return;const Sn=P.current;if(!Sn)return;const pr=Array.from(Sn.querySelectorAll("[data-messenger-thread-key]")).find(Fr=>Fr.dataset.messengerThreadKey===Bn.threadKey);if(pr==null||pr.scrollIntoView({block:"nearest",behavior:"smooth"}),pr){_.current=Bn.threadKey,D.current=De,Ine(De),U.current=null;return}gn+=1,gn<=12&&(en=requestAnimationFrame(yn))};return en=requestAnimationFrame(yn),()=>{Dt=!0,cancelAnimationFrame(en)}},[Qe,Mt,ho,Ye,c.selectedOrganizationId,Ao,De,Bn,Ni,Nt]),h.useEffect(()=>{const de=R.current,He=P.current;if(!de||!He||!c.hasMoreThreadSummaries||c.isFetchingMoreThreadSummaries||c.isLoading||typeof IntersectionObserver>"u")return;const wt=new IntersectionObserver(Dt=>{!Dt.some(gn=>gn.isIntersecting)||!c.hasMoreThreadSummaries||c.isFetchingMoreThreadSummaries||c.loadMoreThreadSummaries()},{root:He,rootMargin:"720px 0px 960px 0px"});return wt.observe(de),()=>wt.disconnect()},[c.hasMoreThreadSummaries,c.isFetchingMoreThreadSummaries,c.isLoading,c.loadMoreThreadSummaries,An.length]),c.selectedOrganizationId?i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(GQn,{title:"Messenger",description:Ye==="custom"?void 0:`Threads organized by ${nAt(Ye).toLowerCase()}`}),i.jsx(eUn,{rule:_e,density:Ce,splitIssueNotifications:o,onRuleChange:Pc,onDensityChange:eo,onSplitIssueNotificationsChange:$a}),i.jsxs(ts,{open:!!ke,onOpenChange:de=>{de||da()},children:[i.jsx(cQ,{virtualRef:M}),ke?i.jsx(ns,{ref:N,side:f?"bottom":"right",align:"center",sideOffset:8,collisionPadding:12,hideWhenDetached:!0,onInteractOutside:()=>{T.current=!1},onCloseAutoFocus:de=>{var He;de.preventDefault(),T.current&&((He=E.current)!=null&&He.isConnected)&&E.current.focus()},"aria-label":"Create Messenger group","data-testid":"messenger-custom-group-popover",className:"scrollbar-auto-hide surface-overlay z-[70] max-h-[min(34rem,var(--radix-popover-content-available-height))] w-[min(25rem,calc(100vw-2rem))] overflow-y-auto p-0 text-foreground",children:i.jsx(DBn,{name:fe,icon:Se,color:ft,pending:ca.isPending||wi.isPending,onNameChange:ve,onIconChange:ze,onColorChange:ie,onCancel:da,onSubmit:lA})}):null]}),xe?i.jsx(RBn,{name:xe.name,pending:wi.isPending,onNameChange:de=>ae(He=>He&&{...He,name:de}),onCancel:e0,onSubmit:Iu}):null,i.jsxs("nav",{ref:Vi,className:"scrollbar-auto-hide mt-2 flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto px-1.5 pb-3.5",children:[i.jsxs(sn,{to:"/messenger/chat",onClick:()=>Vo("/messenger/chat"),className:K("mx-0.5 flex items-center rounded-[calc(var(--radius-md)-2px)] border border-transparent text-sm transition-[background-color,border-color,color]",Ce==="compact"?"gap-2 px-2 py-1.5":"gap-3 px-3 py-2.5",S.kind==="chat"&&!S.conversationId?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))] font-medium text-foreground":"text-foreground/78 hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground"),children:[i.jsx("span",{className:K("flex shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)+1px)] border border-[color:color-mix(in_oklab,var(--border-soft)_88%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_82%,transparent)] text-[color:var(--accent-strong)]",Ce==="compact"?"h-7 w-7":"h-10 w-10"),children:i.jsx(Zr,{className:K(Ce==="compact"?"h-3.5 w-3.5":"h-4.5 w-4.5")})}),i.jsx("span",{className:"truncate text-[13px] font-medium leading-tight",children:"New chat"})]}),c.isLoading&&An.length===0?i.jsx("div",{className:"space-y-1 px-1.5",children:Array.from({length:5}).map((de,He)=>i.jsx("div",{className:K("animate-pulse rounded-[calc(var(--radius-md)-2px)] border border-transparent bg-[color:color-mix(in_oklab,var(--surface-elevated)_60%,transparent)]",Ce==="compact"?"h-10":"h-[72px]")},He))}):null,i5(Ye)?i.jsx(i.Fragment,{children:i.jsxs(tC,{accessibility:tn,sensors:Vt,collisionDetection:WQn,measuring:ZQn,onDragStart:vt,onDragOver:xf,onDragCancel:pt,onDragEnd:lm,children:[i.jsx(l3,{items:aA,strategy:WP,children:s?i.jsx("div",{"data-testid":"messenger-directory-baseline",className:"flex flex-col gap-1",children:Ao.map(de=>i.jsx("div",{children:cA(de)},de.key))}):i.jsx("div",{ref:ho.containerRef,"data-testid":"messenger-virtual-directory",style:{position:"relative",width:"100%"},children:vs.map(de=>{const He=Ao[de.index];return He?i.jsx("div",{ref:ho.measureElement,"data-index":de.index,style:{left:0,position:"absolute",top:0,width:"100%"},children:cA(He)},He.key):null})})}),i.jsx(Eqe,{dropAnimation:null,children:Gn?i.jsx("div",{"data-testid":"messenger-drag-overlay",className:"surface-overlay max-w-[18rem] rounded-[var(--radius-md)] border border-[color:var(--border-strong)] px-3 py-2 text-sm font-medium text-foreground shadow-[var(--shadow-lg)]",children:i.jsx("span",{className:"block truncate",children:Gn})}):null})]})}):s?i.jsx("div",{"data-testid":"messenger-directory-baseline",className:"flex flex-col gap-1",children:Ao.map(de=>i.jsx("div",{children:t0(de)},de.key))}):i.jsx("div",{ref:ho.containerRef,"data-testid":"messenger-virtual-directory",style:{position:"relative",width:"100%"},children:vs.map(de=>{const He=Ao[de.index];return He?i.jsx("div",{ref:ho.measureElement,"data-index":de.index,style:{left:0,position:"absolute",top:0,width:"100%"},children:t0(He)},He.key):null})}),(um=(cc=Jt.data)==null?void 0:cc.pageInfo)!=null&&um.hasMore?i.jsx("div",{className:"flex min-h-9 items-center justify-center px-3 py-1",children:i.jsx("button",{type:"button","data-testid":"messenger-saved-view-page-load-more",className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[11px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 disabled:cursor-not-allowed disabled:opacity-60",disabled:Jt.isFetching,onClick:vp,children:Jt.isFetching?"Loading Saved Views":"Load more Saved Views"})}):null,c.hasMoreThreadSummaries||c.isFetchingMoreThreadSummaries?i.jsx("div",{ref:R,"data-testid":"messenger-thread-page-sentinel",className:"flex min-h-10 items-center justify-center px-3 py-2 text-[12px] text-muted-foreground",children:c.isFetchingMoreThreadSummaries?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Loading more threads"]}):null}):null]}),i.jsx(eQn,{})]}):null}function nUn(e,t){return e==="assigned"&&t?{assigneeUserId:"me",includeAutomationExecutions:!0}:e==="reviewing"&&t?{reviewerUserId:"me",includeAutomationExecutions:!0}:e==="pinned"&&t?{followedByUserId:"me",includeAutomationExecutions:!0}:e==="following"&&t?{involvedUserId:"me",includeAutomationExecutions:!0}:{includeAutomationExecutions:!0}}function rUn(e,t){return t?e.createdByUserId===t||e.assigneeUserId===t||e.reviewerUserId===t:!1}const uIe=5,sAt="rudder.linear",sUn="linear-catalog",iUn="linear";function aUn(e){const t=e==null?void 0:e.find(r=>r.pluginKey===sAt);if(!t)return null;const n=t.slots.find(r=>r.type==="page");return n?{pluginId:t.pluginId,routePath:n.routePath||iUn}:null}function oUn(e){const t=new URLSearchParams;return t.set("source","linear"),e.kind==="team"?t.set("linearTeamId",e.id):(e.teamId&&t.set("linearTeamId",e.teamId),t.set("linearProjectId",e.id)),`/issues?${t.toString()}`}function Q1({children:e,action:t,testId:n,collapsed:r,onToggle:s}){const a=typeof r=="boolean"&&s;return i.jsxs("div",{"data-testid":n,className:"group flex items-center justify-between px-3.5 pt-3.5 text-[11px] font-medium tracking-normal text-muted-foreground/76",children:[i.jsx("span",{children:e}),t||a?i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t,a?i.jsx("button",{type:"button",onClick:s,"aria-label":`${r?"Expand":"Collapse"} ${e}`,title:r?"Expand":"Collapse","data-testid":n?`${n}-toggle`:void 0,className:K("inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/72 transition-[opacity,background-color,color]","hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] hover:text-foreground","opacity-100 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100",r&&"md:opacity-100"),children:r?i.jsx(bi,{className:"h-3.5 w-3.5"}):i.jsx(qr,{className:"h-3.5 w-3.5"})}):null]}):null]})}function DN({title:e,description:t,children:n}){const{isMobile:r,setSidebarOpen:s}=jc();return i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsx("div",{className:"min-w-0 flex-1",children:n??i.jsxs(i.Fragment,{children:[i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:e}),i.jsx("p",{className:"mt-0.5 truncate text-[12px] text-muted-foreground",children:t})]})}),r?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>s(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]})}function lUn(e){return/^\/issues(?:\/|$)/.test(e)||/^\/linear(?:\/|$)/.test(e)?{title:"Issues",description:"Views and project slices"}:/^\/chat(?:\/|$)/.test(e)?{title:"Chats",description:"Recent conversations"}:/^\/calendar(?:\/|$)/.test(e)?{title:"Calendar",description:"Sources and filters"}:/^\/(?:dashboard|org|projects|library|resources|workspaces|heartbeats|goals|skills|costs|activity)(?:\/|$)/.test(e)?{title:"Org",description:"Organization surfaces"}:{title:"Agents",description:""}}function fIe(e){return e==="planned"?"Planned":e==="in_progress"?"Running runs":e==="actual"?"Run history":e==="external"?"External calendar":e==="projected"?"Projected heartbeats":e==="cancelled"?"Cancelled":e}const u$=["border-blue-400 bg-blue-500","border-emerald-400 bg-emerald-500","border-amber-400 bg-amber-500","border-rose-400 bg-rose-500","border-cyan-400 bg-cyan-500","border-violet-400 bg-violet-500"],cUn=["M","T","W","T","F","S","S"];function iAt(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate(),0,0,0,0)}function aAt(e,t){const n=new Date(e);return n.setDate(n.getDate()+t),n}function tB(e){const t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function dUn(e){const t=new Date(e.getFullYear(),e.getMonth(),1),n=t.getDay();return iAt(aAt(t,n===0?-6:1-n))}function uUn(e){return new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric"}).format(e)}function fUn(e){return e>=8?"bg-emerald-700 text-white":e>=5?"bg-emerald-600 text-white":e>=3?"bg-emerald-500/80 text-white":e>=1?"bg-emerald-500/35 text-emerald-950 dark:text-emerald-50":""}function AIe(e,t,n){e(r=>{const s=new Set(r);return n?s.delete(t):s.add(t),s})}function AUn({cursor:e,setCursor:t,completedIssueCountByDay:n}){const r=dUn(e),s=Array.from({length:42},(l,c)=>aAt(r,c)),a=tB(new Date),o=tB(e);return i.jsxs("section",{className:"px-3.5 pt-3","data-testid":"calendar-mini-month",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("button",{type:"button",className:"inline-flex min-w-0 items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] px-1.5 py-1 text-left text-sm font-medium text-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",onClick:()=>t(l=>new Date(l.getFullYear(),l.getMonth(),1)),children:[i.jsx(qr,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:uUn(e)})]}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{type:"button","aria-label":"Previous month",className:"inline-flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground",onClick:()=>t(l=>new Date(l.getFullYear(),l.getMonth()-1,1)),children:i.jsx(Tj,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","aria-label":"Next month",className:"inline-flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground",onClick:()=>t(l=>new Date(l.getFullYear(),l.getMonth()+1,1)),children:i.jsx(bi,{className:"h-4 w-4"})})]})]}),i.jsxs("div",{className:"mt-3 grid grid-cols-7 gap-y-1 text-center",children:[cUn.map((l,c)=>i.jsx("div",{className:"text-[10px] font-medium text-muted-foreground/72",children:l},`${l}-${c}`)),s.map(l=>{const c=tB(l),d=l.getMonth()!==e.getMonth(),u=c===o,f=c===a,A=n.get(c)??0,m=A>0&&!f&&!u;return i.jsx("button",{type:"button","aria-label":`${c}${A>0?`, ${A} completed agent issue${A===1?"":"s"}`:""}`,title:A>0?`${A} completed agent issue${A===1?"":"s"}`:void 0,className:K("mx-auto flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-xs transition-[background-color,color,box-shadow]",d&&!f?"text-muted-foreground/45":"text-foreground/88",m&&fUn(A),f&&"bg-primary text-primary-foreground shadow-sm ring-2 ring-background",!f&&u&&"bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,var(--surface-active))] text-foreground ring-1 ring-primary/65",!f&&!u&&"hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)]"),onClick:()=>t(iAt(l)),children:l.getDate()},c)})]})]})}function hIe({label:e,visible:t,onToggle:n,icon:r,colorClass:s,agent:a}){const o=t?Px:J4;return i.jsxs("button",{type:"button","aria-pressed":t,"aria-label":`${t?"Hide":"Show"} ${e}`,onClick:n,className:K("group mx-1.5 flex min-h-9 w-[calc(100%-0.75rem)] items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-3 py-2 text-left text-sm transition-[background-color,color]","text-foreground/88 hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",!t&&"text-muted-foreground"),children:[a?i.jsx("span",{"data-testid":`calendar-agent-avatar-${a.id}`,className:K("inline-flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted ring-1 ring-border/80",!t&&"opacity-40 grayscale"),title:a.name,children:i.jsx(Il,{icon:a.icon,role:a.role,className:"h-full w-full"})}):s?i.jsx("span",{className:K("h-2.5 w-2.5 shrink-0 rounded-sm border",s,!t&&"opacity-35 grayscale")}):r?i.jsx(r,{className:K("h-3.5 w-3.5 shrink-0 text-muted-foreground",!t&&"opacity-45")}):null,i.jsx("span",{className:"min-w-0 flex-1 truncate",title:e,children:e}),i.jsx("span",{className:K("inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover:opacity-100 group-focus-visible:opacity-100",!t&&"text-muted-foreground/70"),children:i.jsx(o,{className:"h-3.5 w-3.5"})})]})}function hUn(e){const t=e.match(/\/(?:messenger\/chat|chat)\/([^/]+)\/?/);return(t==null?void 0:t[1])??null}function mIe({to:e,icon:t,label:n,active:r,slidingActiveIndicator:s=!1,testId:a}){return i.jsxs(sn,{to:e,"data-testid":a,className:K("relative z-10 mx-1.5 flex items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border border-transparent px-3 py-2 text-sm transition-[background-color,border-color,color]",s&&"min-h-[var(--motion-context-item-height)]",s?r?"font-medium text-foreground":"text-foreground/78 hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground":r?"border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_92%,var(--surface-active))] font-medium text-foreground":"text-foreground/78 hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground"),children:[i.jsx(t,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"truncate",children:n})]})}function mUn(e){return e>=0?{"--motion-context-active-index":e}:void 0}function u7({activeIndex:e,ariaLabel:t,className:n,scrollRef:r,indicatorTestId:s,testId:a,children:o}){return i.jsxs("nav",{ref:r,className:K("motion-context-nav",n),style:mUn(e),"data-active-index":e>=0?e:void 0,"data-testid":a,"aria-label":t,children:[e>=0?i.jsx("span",{"data-testid":s,className:"motion-context-active-indicator","aria-hidden":"true"}):null,o]})}function pIe({count:e}){return i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-1.5 pl-2",children:[i.jsxs("span",{className:"relative flex h-2 w-2",children:[i.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-blue-400 opacity-75"}),i.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-500"})]}),i.jsxs("span",{className:"text-[11px] font-medium text-blue-600 dark:text-blue-400",children:[e," live"]})]})}function pUn({visibleProjects:e,activeProjectRef:t,closeMobileSidebar:n,onNewProject:r,scrollRef:s}){const a=e.findIndex(o=>t===S3(o));return i.jsxs(i.Fragment,{children:[i.jsx(Q1,{testId:"workspace-projects-section",action:i.jsx("button",{type:"button",onClick:r,"aria-label":"New project",title:"Create project",className:K("inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/72 transition-[opacity,background-color,color]","hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] hover:text-foreground","opacity-100 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100"),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})}),children:"Projects"}),i.jsx(u7,{activeIndex:a,ariaLabel:"Projects",className:"motion-context-nav--project-card-list scrollbar-auto-hide mt-2 min-h-0 flex-1 overflow-y-auto pb-3.5",scrollRef:s,indicatorTestId:"project-sidebar-active-indicator",testId:"workspace-projects-scroll",children:e.map(o=>{const l=S3(o),c=t===l;return i.jsxs(sn,{to:`/projects/${l}/configuration`,onClick:n,className:K("relative z-10 mx-1.5 min-h-[var(--motion-context-item-height)] rounded-[calc(var(--radius-sm)-1px)] px-3.5 py-2.5 transition-colors",c?"font-medium text-foreground":"text-foreground/88 hover:bg-[color:color-mix(in_oklab,var(--surface-active)_54%,transparent)]"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(uo,{color:o.color,icon:o.icon,size:"sm",testId:`workspace-project-color-${o.id}`}),i.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:o.name})]}),i.jsx("div",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:o.description||"Project"})]},o.id)})})]})}function gIe({issues:e,activeIssueRef:t,closeMobileSidebar:n,onOpenIssue:r,collapsed:s,onToggleCollapsed:a,sectionLabel:o,ariaLabel:l,sectionTestId:c,listTestId:d,rowTestIdPrefix:u,toggleTestId:f,scrollActivityKey:A,followedIssueIds:m,pinningIssueId:g,issuePinDisabled:x,onToggleIssuePin:y}){const[v,w]=h.useState(!1),k=bs(A);if(e.length===0)return null;const S=v?e.length:uIe,j=e.slice(0,S);return i.jsxs("section",{"aria-label":l,className:"mt-1",children:[i.jsx(Q1,{testId:c,collapsed:s,onToggle:a,children:o}),s?null:i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:v?k:void 0,"data-testid":d,className:K("mt-2 space-y-0.5",v&&"scrollbar-auto-hide max-h-72 overflow-y-auto pr-1"),children:j.map(C=>{const N=C.identifier??C.id,P=t===N||t===C.id,M=m.has(C.id),E=M?"Unpin issue":"Pin issue",T=M?lw:Jh,R=g===C.id;return i.jsxs("div",{"data-testid":`${u}-${C.id}`,"aria-current":P?"page":void 0,className:K("group/issue-sidebar-row relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center rounded-[calc(var(--radius-sm)-1px)] border border-transparent text-sm transition-[background-color,border-color,color]",P?"border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_92%,var(--surface-active))] font-medium text-foreground":"text-muted-foreground hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),children:[i.jsxs(sn,{to:eE(C),onClick:()=>{r==null||r(C),n()},"aria-current":P?"page":void 0,className:"flex min-w-0 flex-1 items-center gap-2.5 self-stretch px-3 py-2 pr-9 text-inherit",children:[i.jsx("span",{className:"flex h-5 w-4 shrink-0 items-center justify-center",children:i.jsx(ni,{status:C.status})}),i.jsxs("span",{className:"flex min-h-5 min-w-0 flex-1 items-center gap-1.5",children:[i.jsx("span",{className:"shrink-0 font-mono text-[11px] leading-5 text-muted-foreground/78",children:N}),i.jsx("span",{className:"shrink-0 leading-5 text-muted-foreground/55",children:"·"}),i.jsx("span",{className:"min-w-0 truncate leading-5",children:C.title})]})]}),i.jsx("button",{type:"button","data-testid":`${u}-${C.id}-pin-toggle`,"aria-label":`${E} ${N}`,title:E,disabled:x||R,className:K("absolute right-1.5 top-1/2 z-10 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-md p-1 opacity-100 transition-[opacity,background-color,color] duration-150","hover:bg-[color:var(--surface-page)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--ring)] disabled:pointer-events-none disabled:opacity-35","md:opacity-0 md:group-hover/issue-sidebar-row:opacity-100 md:group-focus-within/issue-sidebar-row:opacity-100",M?"text-[color:var(--accent-strong)] hover:text-[color:var(--accent-strong)]":"text-muted-foreground hover:text-foreground"),onClick:_=>{_.preventDefault(),_.stopPropagation(),y(C)},children:i.jsx(T,{className:"h-3.5 w-3.5",strokeWidth:2.25})})]},C.id)})}),e.length>uIe?i.jsxs("button",{type:"button",onClick:()=>w(C=>!C),"data-testid":f,className:"mx-1.5 mt-1 flex min-h-8 w-[calc(100%-0.75rem)] items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-3 py-1.5 text-left text-xs font-medium text-muted-foreground transition-colors hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground",children:[v?i.jsx(BK,{className:"h-3.5 w-3.5"}):i.jsx(qr,{className:"h-3.5 w-3.5"}),i.jsx("span",{children:v?"Show less":"Show all"})]}):null]})]})}function gUn(){var We,Tt,Mn,tr,Ln;const e=br(),t=Yr(),n=fl(e.pathname),r=h.useMemo(()=>new URLSearchParams(e.search),[e.search]),s=h.useMemo(()=>lUn(n),[n]),a=/^\/messenger(?:\/|$)/.test(n),o=/^\/apps(?:\/|$)/.test(n),l=/^\/(?:dashboard\/calendar|calendar)(?:\/|$)/.test(n),c=/^\/linear(?:\/|$)/.test(n),d=/^\/issues(?:\/|$)/.test(n)||c,u=/^\/(?:dashboard|org|projects|library|resources|heartbeats|workspaces|goals|skills|costs|activity)(?:\/|$)/.test(n),f=/^\/chat(?:\/|$)/.test(n),A=!o&&!a&&!d&&!l&&!u&&!f,{selectedOrganizationId:m}=jr(),{isMobile:g,setSidebarOpen:x}=jc(),{pushToast:y}=ss(),{openNewAgent:v,openNewProject:w}=ii(),k=Vn(),[S,j]=h.useState({}),[C,N]=h.useState(null),P=h.useCallback(pt=>S[pt]===!0,[S]),M=h.useCallback(pt=>{j(vt=>({...vt,[pt]:!vt[pt]}))},[]),E=bs("rudder:sidebar-scroll:calendar"),T=bs("rudder:sidebar-scroll:issues"),R=bs("rudder:sidebar-scroll:workspace-projects"),_=bs("rudder:sidebar-scroll:chat"),D=bs("rudder:sidebar-scroll:agents"),{cursor:U,setCursor:$,hiddenAgentIds:L,setHiddenAgentIds:H,hiddenSourceIds:X,setHiddenSourceIds:F,myCalendarVisible:Q,setMyCalendarVisible:q,visibleStatuses:B,setVisibleStatuses:ee,setGoogleCalendarModalOpen:se}=qqe(),{data:re}=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),{data:ne}=Me({queryKey:V.projects.list(m??"__none__"),queryFn:()=>Mi.list(m),enabled:!!m}),{data:Ae}=Me({queryKey:V.agents.list(m??"__none__"),queryFn:()=>Nn.list(m),enabled:!!m}),{data:Y}=Me({queryKey:V.chats.listPreview(m??"__none__","active",40),queryFn:()=>Xn.list(m,"active",{limit:40}),enabled:!!m}),{data:ce}=Me({queryKey:V.calendar.sources(m??"__none__"),queryFn:()=>su.sources(m),enabled:!!m&&l}),Oe=xt({mutationFn:({sourceId:pt,status:vt})=>su.updateSource(m,pt,{status:vt}),onSuccess:async()=>{m&&await Promise.all([k.invalidateQueries({queryKey:V.calendar.sources(m)}),k.invalidateQueries({queryKey:["calendar",m]})])},onError:pt=>{y({title:"Failed to update calendar source",body:pt instanceof Error?pt.message:void 0,tone:"error"})}}),{data:Fe}=Me({queryKey:V.liveRuns(m??"__none__"),queryFn:()=>zo.liveRunsForCompany(m),enabled:!!m&&(A||d),refetchInterval:1e4}),{data:ke}=Me({queryKey:V.issues.listPreview(m??"__none__",80),queryFn:()=>lr.list(m,{limit:80}),enabled:!!m&&d}),{follows:Ne,followedIssueIds:xe,isLoading:ae,toggleFollowIssue:fe}=Z0e(m&&d?m:null),{data:ve}=Me({queryKey:V.plugins.uiContributions,queryFn:()=>bo.listUiContributions(),enabled:!!m&&d}),{data:Se}=Me({queryKey:["calendar",m??"__none__","completed-issue-heatmap"],queryFn:()=>lr.list(m,{status:"done"}),enabled:!!m&&l}),ze=((We=re==null?void 0:re.user)==null?void 0:We.id)??((Tt=re==null?void 0:re.session)==null?void 0:Tt.userId)??null,ft=new URLSearchParams(e.search).get("scope")??"",ie=ft==="recent"?"":ft,me=new URLSearchParams(e.search).get("source")??"",we=new URLSearchParams(e.search).get("projectId")??"",Xe=new URLSearchParams(e.search).get("linearProjectId")??"",ge=new URLSearchParams(e.search).get("linearTeamId")??"",te=hUn(e.pathname),G=((Mn=e.pathname.match(/\/agents\/([^/]+)/))==null?void 0:Mn[1])??null,oe=((tr=e.pathname.match(/\/projects\/([^/]+)/))==null?void 0:tr[1])??null,Ze=((Ln=e.pathname.match(/\/issues\/([^/]+)/))==null?void 0:Ln[1])??null,Te=h.useMemo(()=>(ne??[]).filter(pt=>!pt.archivedAt),[ne]),Be=h.useMemo(()=>aUn(ve),[ve]),{data:it}=Me({queryKey:["plugins",sAt,"catalog",m??"__none__",(Be==null?void 0:Be.pluginId)??"__none__"],queryFn:async()=>(await bo.bridgeGetData(Be.pluginId,sUn,{orgId:m},m)).data,enabled:!!m&&!!(Be!=null&&Be.pluginId)&&d}),lt=h.useMemo(()=>{const pt=[...(it==null?void 0:it.projects)??[]].sort((kr,xs)=>kr.name.localeCompare(xs.name)),vt=[...(it==null?void 0:it.teams)??[]].sort((kr,xs)=>kr.name.localeCompare(xs.name));if(vt.length===0)return pt.map(kr=>({...kr,kind:"project"}));const jt=[],Zt=new Set;for(const kr of vt){jt.push({...kr,kind:"team"});for(const xs of pt)(xs.teamIds??[]).includes(kr.id)&&(Zt.add(xs.id),jt.push({id:xs.id,name:xs.name,kind:"project",teamId:kr.id}))}for(const kr of pt)Zt.has(kr.id)||jt.push({...kr,kind:"project"});return jt},[it==null?void 0:it.projects,it==null?void 0:it.teams]),Ue=h.useMemo(()=>(Ae??[]).filter(pt=>pt.status!=="terminated").sort((pt,vt)=>pt.name.localeCompare(vt.name)),[Ae]),mt=h.useMemo(()=>{const pt=new Map;for(const vt of Fe??[])pt.set(vt.agentId,(pt.get(vt.agentId)??0)+1);return pt},[Fe]),tt=h.useMemo(()=>{const pt=new Map;for(const jt of ke??[])jt.projectId&&pt.set(jt.id,jt.projectId);const vt=new Map;for(const jt of Fe??[]){if(!jt.issueId)continue;const Zt=pt.get(jt.issueId);Zt&&vt.set(Zt,(vt.get(Zt)??0)+1)}return vt},[ke,Fe]),[dt,at]=h.useState(null),[Pe,$e]=h.useState(""),[ot,ue]=h.useState(!0),[Ie,Ke]=h.useState(()=>aq(m)),[De,Je]=h.useState(()=>j7(m)),_e=h.useMemo(()=>DLn(De,ke??[]),[ke,De]),Ee=h.useMemo(()=>{const pt=new Map((ke??[]).map(vt=>[vt.id,vt]));return Ne.map(vt=>pt.get(vt.issueId)??vt.issue)},[ke,Ne]),Ce=h.useMemo(()=>ze?(ke??[]).filter(pt=>rUn(pt,ze)).length:0,[ke,ze]),kt=[{key:"all",to:"/issues",icon:sE,label:"All Issues",active:me!=="linear"&&ie===""&&!we},...Ie.length>0?[{key:"drafts",to:"/issues?scope=drafts",icon:xg,label:`Draft Issues (${Ie.length})`,active:ie==="drafts",testId:"issue-draft-sidebar-entry"}]:[],{key:"following",to:`/issues${ze?"?scope=following":""}`,icon:C3,label:`Following${Ce>0?` (${Ce})`:""}`,active:ie==="following"}],Qe=kt.findIndex(pt=>pt.active),gt=Te.findIndex(pt=>{const vt=S3(pt);return we===pt.id||oe===vt}),Nt=[{key:"dashboard",to:"/dashboard",icon:yx,label:"Dashboard",active:/^\/dashboard(?:\/|$)/.test(n)},{key:"heartbeats",to:"/heartbeats",icon:Cx,label:"Heartbeats",active:/^\/heartbeats(?:\/|$)/.test(n)},{key:"goals",to:"/goals",icon:ud,label:"Goals",active:/^\/goals(?:\/|$)/.test(n)},{key:"skills",to:MAe,icon:wc,label:"Skills",active:/^\/skills(?:\/|$)/.test(n)||/^\/library(?:\/|$)/.test(n)&&(r.get("directory")==="skills"||r.has("skill"))},{key:"costs",to:"/costs",icon:Nx,label:"Costs",active:/^\/costs(?:\/|$)/.test(n)},{key:"activity",to:"/activity",icon:lT,label:"Activity",active:/^\/activity(?:\/|$)/.test(n)}],Gt=Nt.findIndex(pt=>pt.active),cn=Ue.findIndex(pt=>G===pt.urlKey||G===pt.id),Rn=(ce??[]).filter(pt=>pt.type==="google_calendar").sort((pt,vt)=>{const jt=(pt.externalCalendarId==="primary"?0:1)-(vt.externalCalendarId==="primary"?0:1);return jt!==0?jt:pt.name.localeCompare(vt.name)}),nt=Rn.filter(pt=>pt.status==="active"),Qt=Rn.some(pt=>pt.status==="active"&&!X.has(pt.id)),st=h.useMemo(()=>{const pt=new Map;for(const vt of Se??[]){if(!vt.completedAt||!vt.assigneeAgentId)continue;const jt=tB(vt.completedAt);pt.set(jt,(pt.get(jt)??0)+1)}return pt},[Se]);h.useEffect(()=>{Je(j7(m))},[e.key,m]),h.useEffect(()=>{if(typeof window>"u")return;const pt=()=>{Je(j7(m))};return window.addEventListener(Jce,pt),window.addEventListener("storage",pt),()=>{window.removeEventListener(Jce,pt),window.removeEventListener("storage",pt)}},[m]),h.useEffect(()=>{const pt=()=>{Ke(aq(m))};if(pt(),!(typeof window>"u"))return window.addEventListener(V_,pt),window.addEventListener("storage",pt),()=>{window.removeEventListener(V_,pt),window.removeEventListener("storage",pt)}},[m]);const Rt=()=>{g&&x(!1)},Cn=pt=>{m&&Je(X0e(m,pt.id,j7(m)))},zn=h.useCallback(async pt=>{if(C||ae)return;const vt=!xe.has(pt.id);N(pt.id);try{await fe(pt.id),y({title:vt?"Issue pinned":"Issue unpinned",tone:"success"})}catch(jt){y({title:vt?"Could not pin issue":"Could not unpin issue",body:jt instanceof Error?jt.message:void 0,tone:"error"})}finally{N(null)}},[xe,ae,C,y,fe]),fs=async pt=>{m&&(await k.invalidateQueries({queryKey:V.chats.list(m,"active")}),pt&&(await k.invalidateQueries({queryKey:V.chats.detail(m,pt)}),await k.invalidateQueries({queryKey:V.chats.messages(m,pt)})))},as=xt({mutationFn:({chatId:pt,data:vt})=>Xn.update(pt,vt),onSuccess:async pt=>{pt.status==="archived"&&pt.id===te&&t("/messenger"),at(vt=>vt===pt.id?null:vt),await fs(pt.id)},onError:pt=>{y({title:"Failed to update chat",body:pt instanceof Error?pt.message:void 0,tone:"error"})}}),sr=xt({mutationFn:({chatId:pt,pinned:vt})=>Xn.updateUserState(pt,{pinned:vt}),onSuccess:async pt=>{await fs(pt.id)},onError:pt=>{y({title:"Failed to update chat state",body:pt instanceof Error?pt.message:void 0,tone:"error"})}}),Kr=()=>{const pt=Pe.trim();if(!dt||!pt){at(null);return}as.mutate({chatId:dt,data:{title:pt}})},yr=async pt=>{try{await navigator.clipboard.writeText(pt),y({title:"Chat ID copied",tone:"success"})}catch{y({title:"Could not copy chat ID",tone:"error"})}},ht=()=>{const pt=!Qt,vt=pt?Rn:nt;F(jt=>{const Zt=new Set(jt);for(const kr of vt)pt?Zt.delete(kr.id):Zt.add(kr.id);return Zt});for(const jt of vt)Oe.mutate({sourceId:jt.id,status:pt?"active":"paused"})},Vt=pt=>{const vt=!(pt.status==="active"&&!X.has(pt.id));AIe(F,pt.id,vt),Oe.mutate({sourceId:pt.id,status:vt?"active":"paused"})};if(o)return i.jsx(PBn,{});if(a)return i.jsx(tUn,{});if(l)return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description,children:i.jsx(Uut,{compact:!0,className:"w-full"})}),i.jsxs("div",{ref:E,className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto pb-3.5",children:[i.jsx(AUn,{cursor:U,setCursor:$,completedIssueCountByDay:st}),i.jsx(Q1,{action:i.jsx("button",{type:"button","aria-label":"Import Google Calendar",className:"inline-flex h-6 w-6 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100",onClick:()=>se(!0),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})}),children:"Calendars"}),i.jsxs("div",{className:"mt-2 space-y-0.5",children:[i.jsx(hIe,{label:"My Calendar",visible:Q,onToggle:()=>q(pt=>!pt),icon:C3}),i.jsxs("div",{className:"group mx-1.5 flex min-h-9 items-center gap-1 rounded-[calc(var(--radius-sm)-1px)] px-1.5 py-1 text-sm text-foreground/88 transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",children:[i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground hover:bg-[color:var(--surface-page)] hover:text-foreground","aria-label":ot?"Collapse Google Calendar calendars":"Expand Google Calendar calendars",onClick:()=>ue(pt=>!pt),children:ot?i.jsx(qr,{className:"h-3.5 w-3.5"}):i.jsx(bi,{className:"h-3.5 w-3.5"})}),i.jsxs("button",{type:"button","data-testid":"calendar-google-row",className:"flex min-w-0 flex-1 items-center gap-2 rounded-[calc(var(--radius-sm)-2px)] px-1.5 py-1 text-left",onClick:()=>se(!0),children:[i.jsx(rE,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Google Calendar"})]}),i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100 disabled:cursor-not-allowed disabled:opacity-30","aria-label":`${Qt?"Hide":"Show"} Google Calendar`,disabled:Rn.length===0||Oe.isPending,onClick:ht,children:Qt?i.jsx(Px,{className:"h-3.5 w-3.5"}):i.jsx(J4,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100","aria-label":"Google Calendar settings",onClick:()=>se(!0),children:i.jsx(XK,{className:"h-3.5 w-3.5"})})]}),ot&&Rn.length>0?i.jsx("div",{className:"ml-9 mr-2 space-y-0.5","data-testid":"calendar-google-source-list",children:Rn.map((pt,vt)=>{const jt=pt.status==="active"&&!X.has(pt.id),Zt=jt?Px:J4;return i.jsxs("button",{type:"button","data-testid":`calendar-google-source-row-${pt.id}`,disabled:Oe.isPending,"aria-label":`${jt?"Disable":"Enable"} ${pt.name}`,className:K("group/source flex min-h-7 w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1 text-left text-xs text-foreground/82 hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] disabled:cursor-not-allowed disabled:opacity-60",!jt&&"text-muted-foreground"),onClick:()=>Vt(pt),children:[i.jsx("span",{className:K("h-2 w-2 shrink-0 rounded-sm border",u$[vt%u$.length],!jt&&"opacity-35 grayscale")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:pt.name,children:pt.name}),pt.status!=="active"?i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:"Off"}):null,i.jsx("span",{className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover/source:opacity-100 group-focus-visible/source:opacity-100",children:i.jsx(Zt,{className:"h-3 w-3"})})]},pt.id)})}):null]}),i.jsx(Q1,{children:"Agents"}),i.jsx("div",{className:"mt-2 space-y-0.5",children:Ue.map((pt,vt)=>i.jsx(hIe,{label:V7(pt),visible:!L.has(pt.id),onToggle:()=>AIe(H,pt.id,L.has(pt.id)),colorClass:u$[vt%u$.length],agent:pt},pt.id))}),i.jsx(Q1,{children:"Timeline"}),i.jsx("div",{className:"mt-2 space-y-0.5","data-testid":"calendar-status-filters",children:VKt.map(pt=>i.jsxs("label",{className:"mx-1.5 flex min-h-8 items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-3 py-1.5 text-sm text-foreground/88 hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",children:[i.jsx(hc,{checked:B.has(pt),onCheckedChange:vt=>{ee(jt=>{const Zt=new Set(jt);return vt===!0?Zt.add(pt):Zt.delete(pt),Zt})},"aria-label":`Show ${fIe(pt)} events`}),i.jsx("span",{className:"truncate",children:fIe(pt)})]},pt))})]})]});if(d)return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsx(Q1,{collapsed:P("issues"),onToggle:()=>M("issues"),children:"Issues"}),P("issues")?null:i.jsx(u7,{activeIndex:Qe,ariaLabel:"Issue navigation",className:"mt-2",indicatorTestId:"issue-sidebar-active-indicator",children:kt.map(pt=>i.jsx(mIe,{to:pt.to,icon:pt.icon,label:pt.label,active:pt.active,testId:pt.testId,slidingActiveIndicator:!0},pt.key))}),i.jsxs("div",{ref:T,"data-testid":"issue-sidebar-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto pb-3.5",children:[i.jsx(gIe,{issues:Ee,activeIssueRef:Ze,closeMobileSidebar:Rt,collapsed:P("pinned"),onToggleCollapsed:()=>M("pinned"),sectionLabel:`Pinned (${Ee.length})`,ariaLabel:"Pinned issues",sectionTestId:"issue-pinned-section",listTestId:"issue-pinned-list",rowTestIdPrefix:"issue-pinned-row",toggleTestId:"issue-pinned-toggle",scrollActivityKey:"rudder:sidebar-scroll:pinned-issues",followedIssueIds:xe,pinningIssueId:C,issuePinDisabled:ae,onToggleIssuePin:pt=>void zn(pt)}),i.jsx(gIe,{issues:_e,activeIssueRef:Ze,closeMobileSidebar:Rt,onOpenIssue:Cn,collapsed:P("recent"),onToggleCollapsed:()=>M("recent"),sectionLabel:`Recently Viewed (${_e.length})`,ariaLabel:"Recently viewed issues",sectionTestId:"issue-recent-section",listTestId:"issue-recent-list",rowTestIdPrefix:"issue-recent-row",toggleTestId:"issue-recent-toggle",scrollActivityKey:"rudder:sidebar-scroll:recent-issues",followedIssueIds:xe,pinningIssueId:C,issuePinDisabled:ae,onToggleIssuePin:pt=>void zn(pt)}),i.jsx(Q1,{testId:"workspace-projects-section",collapsed:P("projects"),onToggle:()=>M("projects"),children:"Projects"}),P("projects")?null:i.jsx(u7,{activeIndex:gt,ariaLabel:"Issue project slices",className:"mt-2",indicatorTestId:"issue-project-sidebar-active-indicator",children:Te.map(pt=>{const vt=S3(pt),jt=we===pt.id||oe===vt,Zt=tt.get(pt.id)??0;return i.jsxs(sn,{to:`/issues?projectId=${pt.id}`,onClick:Rt,"data-testid":`issue-project-row-${pt.id}`,className:K("relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border border-transparent px-3 py-2 text-sm transition-[background-color,border-color,color]",jt?"font-medium text-foreground":"text-muted-foreground hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),children:[i.jsx(uo,{color:pt.color,icon:pt.icon,size:"xs",testId:`issue-project-color-${pt.id}`}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:pt.name}),Zt>0?i.jsx(pIe,{count:Zt}):null]},pt.id)})}),lt.length>0?i.jsxs(i.Fragment,{children:[i.jsx(Q1,{testId:"issue-linear-section",collapsed:P("linear"),onToggle:()=>M("linear"),children:"Linear"}),P("linear")?null:i.jsx(u7,{activeIndex:-1,ariaLabel:"Linear issue source slices",className:"mt-2",children:lt.map(pt=>{const vt=pt.kind==="project"?Xe===pt.id&&(!pt.teamId||ge===pt.teamId):me==="linear"&&ge===pt.id&&!Xe;return i.jsxs(sn,{to:oUn(pt),onClick:Rt,"data-testid":`issue-linear-${pt.kind}-${pt.id}`,"aria-current":vt?"page":void 0,className:K("relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border border-transparent px-3 py-2 text-sm transition-[background-color,border-color,color]",pt.kind==="project"&&pt.teamId?"ml-6 min-h-8 py-1.5 text-xs":"",vt?"border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_92%,var(--surface-active))] font-medium text-foreground":"text-muted-foreground hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),children:[i.jsx("span",{className:"h-2.5 w-2.5 shrink-0 rounded-[calc(var(--radius-sm)-4px)] border border-[color:color-mix(in_oklab,var(--muted-foreground)_54%,transparent)] bg-[color:color-mix(in_oklab,var(--muted-foreground)_18%,transparent)]"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:pt.name})]},`${pt.kind}-${pt.id}`)})})]}):null]})]});if(u)return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsx(Q1,{children:"Org"}),i.jsx(u7,{activeIndex:Gt,ariaLabel:"Organization surfaces",className:"mt-2",indicatorTestId:"org-sidebar-active-indicator",children:Nt.map(pt=>i.jsx(mIe,{to:pt.to,icon:pt.icon,label:pt.label,active:pt.active,slidingActiveIndicator:!0},pt.key))}),i.jsx(pUn,{visibleProjects:Te,activeProjectRef:oe,closeMobileSidebar:Rt,onNewProject:w,scrollRef:R})]})]});if(f){if(!te&&((Y==null?void 0:Y.length)??0)===0)return null;const pt=(Y??[]).filter(jt=>jt.isPinned),vt=(Y??[]).filter(jt=>!jt.isPinned);return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar chat-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsxs("nav",{ref:_,"data-testid":"chat-sidebar-scroll",className:"scrollbar-auto-hide flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto px-1.5 py-2.5",children:[i.jsxs(sn,{to:"/messenger/chat",onClick:Rt,className:K("flex items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border px-3 py-2.5 text-sm transition-[background-color,border-color,color]",te?"border-transparent text-foreground/88 hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)] hover:text-foreground":"surface-active border-[color:var(--border-strong)] text-[color:var(--accent-strong)]"),children:[i.jsx(pa,{className:"h-4 w-4 shrink-0"}),i.jsx("div",{className:"truncate font-medium",children:"New Chat"})]}),pt.length>0?i.jsx("div",{className:"px-2 pb-1 pt-2 text-[10px] font-semibold tracking-[0.08em] text-muted-foreground/72",children:"Pinned"}):null,pt.map(jt=>i.jsx(Tie,{date:jt.lastMessageAt??jt.updatedAt,children:i.jsx("div",{"data-testid":`chat-sidebar-conversation-${jt.id}`,className:K("group relative rounded-[calc(var(--radius-sm)-1px)] border px-3 py-1.5 transition-[background-color,border-color,color]",te===jt.id?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_86%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]"),children:dt===jt.id?i.jsx("input",{autoFocus:!0,value:Pe,onChange:Zt=>$e(Zt.target.value),onBlur:Kr,onKeyDown:Zt=>{Zt.key==="Enter"&&(Zt.preventDefault(),Kr()),Zt.key==="Escape"&&(Zt.preventDefault(),at(null))},className:"min-h-0 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-elevated)] px-3 py-2 text-sm outline-none"}):i.jsxs(i.Fragment,{children:[i.jsx(sn,{to:`/messenger/chat/${jt.id}`,onClick:Rt,className:"block min-w-0 pr-12",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium leading-tight text-foreground",children:[i.jsx("span",{className:"truncate",children:o6(jt)}),jt.isUnread?i.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 rounded-full bg-red-500","aria-label":"Unread chat"}):null]})}),i.jsx("span",{className:"whitespace-nowrap text-[11px] tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",children:Bi(jt.lastMessageAt??jt.updatedAt)})]})}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Chat actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay text-foreground",children:[Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{at(jt.id),$e(jt.title)},children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename"]}),i.jsxs(Xt,{onClick:()=>{sr.mutate({chatId:jt.id,pinned:!1})},children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}),i.jsxs(Xt,{onClick:()=>void yr(jt.id),children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy chat ID"]}),Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{as.mutate({chatId:jt.id,data:{status:"archived"}})},children:[i.jsx(G4,{className:"h-4 w-4"}),"Archive"]})]})]})]})})},jt.id)),vt.length>0?i.jsx("div",{className:"px-2 pb-1 pt-2 text-[10px] font-semibold tracking-[0.08em] text-muted-foreground/72",children:"Recent"}):null,vt.map(jt=>i.jsx(Tie,{date:jt.lastMessageAt??jt.updatedAt,children:i.jsx("div",{"data-testid":`chat-sidebar-conversation-${jt.id}`,className:K("group relative rounded-[calc(var(--radius-sm)-1px)] border px-3 py-1.5 transition-[background-color,border-color,color]",te===jt.id?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_86%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]"),children:dt===jt.id?i.jsx("input",{autoFocus:!0,value:Pe,onChange:Zt=>$e(Zt.target.value),onBlur:Kr,onKeyDown:Zt=>{Zt.key==="Enter"&&(Zt.preventDefault(),Kr()),Zt.key==="Escape"&&(Zt.preventDefault(),at(null))},className:"min-h-0 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-elevated)] px-3 py-2 text-sm outline-none"}):i.jsxs(i.Fragment,{children:[i.jsx(sn,{to:`/messenger/chat/${jt.id}`,onClick:Rt,className:"block min-w-0 pr-12",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium leading-tight text-foreground",children:[i.jsx("span",{className:"truncate",children:o6(jt)}),jt.isUnread?i.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 rounded-full bg-red-500","aria-label":"Unread chat"}):null]})}),i.jsx("span",{className:"whitespace-nowrap text-[11px] tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",children:Bi(jt.lastMessageAt??jt.updatedAt)})]})}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Chat actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay text-foreground",children:[Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{at(jt.id),$e(jt.title)},children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename"]}),i.jsxs(Xt,{onClick:()=>{sr.mutate({chatId:jt.id,pinned:!0})},children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]}),i.jsxs(Xt,{onClick:()=>void yr(jt.id),children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy chat ID"]}),Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{as.mutate({chatId:jt.id,data:{status:"archived"}})},children:[i.jsx(G4,{className:"h-4 w-4"}),"Archive"]})]})]})]})})},jt.id))]})]})}return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsx(Q1,{testId:"agents-team-section",action:i.jsx("div",{className:"flex items-center",children:i.jsx("button",{type:"button",onClick:v,"aria-label":"New agent",className:K("inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/72 transition-[opacity,background-color,color]","hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] hover:text-foreground","opacity-100 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100"),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})})}),children:"Team"}),i.jsx(u7,{activeIndex:cn,ariaLabel:"Agent team",className:"motion-context-nav--agent-list scrollbar-auto-hide mt-2 min-h-0 flex-1 overflow-y-auto pb-3.5",scrollRef:D,indicatorTestId:"agent-sidebar-active-indicator",testId:"agent-sidebar-scroll",children:Ue.map(pt=>{const vt=mt.get(pt.id)??0,jt=G===pt.urlKey||G===pt.id,Zt=rqe(pt);return i.jsxs("div",{"data-testid":`agent-sidebar-row-${pt.id}`,className:K("group/agent-sidebar-row relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center rounded-[calc(var(--radius-sm)-1px)] text-sm transition-colors",jt?"font-medium text-foreground":"text-foreground/80 hover:bg-[color:color-mix(in_oklab,var(--surface-active)_54%,transparent)]"),children:[i.jsxs(sn,{to:BA(pt),onClick:Rt,className:"flex min-w-0 flex-1 items-center gap-3 self-stretch py-2.5 pl-3.5 pr-1 no-underline text-inherit",children:[i.jsx(Il,{icon:pt.icon,role:pt.role,className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"flex-1 truncate",title:V7(pt),children:V7(pt)}),Zt?i.jsx("span",{title:`Agent status: ${Zt}`,className:K("ml-auto inline-flex h-5 shrink-0 items-center rounded-[calc(var(--radius-sm)-1px)] border px-1.5 text-[10px] font-medium leading-none whitespace-nowrap",wE[Zt]??kE),children:Zt}):null,vt>0?i.jsx(pIe,{count:vt}):null]}),i.jsx(bBn,{agent:pt,orgId:m??pt.orgId,triggerTestId:`agent-sidebar-actions-${pt.id}`,triggerClassName:"mr-2 h-6 w-6",visibilityClassName:"opacity-100 md:opacity-0 md:group-hover/agent-sidebar-row:opacity-100 md:group-focus-within/agent-sidebar-row:opacity-100",onActionComplete:Rt})]},pt.id)})})]})}function xUn(e){const t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length-1;r+=1)n.push(t.slice(0,r+1).join("/"));return new Set(n)}function bUn(e){return e?new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(new Date(e)):"Running"}function yUn(e){return`${e} ${e===1?"file":"files"}`}function xIe(e){return(e==null?void 0:e.status)==="succeeded"||(e==null?void 0:e.status)==="restored"}function vUn(e){return e.status==="running"?"Backup still running.":e.status==="failed"?e.error?`Backup failed: ${e.error}`:"Backup failed before writing files.":"Backup files are not available."}function wUn(e,t,n){const r=new URLSearchParams(e);r.set("file",n),t(r,{replace:!0})}function kUn({orgId:e,backupId:t,directoryPath:n,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o}){const{data:l}=Me({queryKey:V.organizations.workspaceBackupFiles(e,t,n),queryFn:()=>_n.listWorkspaceBackupFiles(e,t,n),enabled:!!e&&!!t,refetchOnWindowFocus:!1}),c=(l==null?void 0:l.entries)??[];return c.length===0?null:i.jsx("ul",{className:"space-y-0.5",children:c.map(d=>i.jsx(oAt,{orgId:e,backupId:t,entry:d,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o},d.path))})}function oAt({orgId:e,backupId:t,entry:n,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o=0}){const[l,c]=h.useState(a.has(n.path));if(h.useEffect(()=>{a.has(n.path)&&c(!0)},[n.path,a]),n.isDirectory)return i.jsxs("li",{children:[i.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-left text-sm text-foreground/88 transition-colors hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",style:{paddingLeft:`${o*14+8}px`},onClick:()=>c(u=>!u),"aria-expanded":l,children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground",children:l?i.jsx(qr,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})}),i.jsx(wo,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:n.name})]}),l?i.jsx(kUn,{orgId:e,backupId:t,directoryPath:n.path,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o+1}):null]});const d=r===n.path;return i.jsx("li",{children:i.jsxs("button",{type:"button",className:K("flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-left text-sm transition-colors",d?"bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),style:{paddingLeft:`${o*14+23}px`},onClick:()=>s(n.path),children:[i.jsx(K6,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:n.name})]})})}function OUn(){var m,g,x,y;const{isMobile:e,setSidebarOpen:t}=jc(),{viewedOrganizationId:n}=th(),[r,s]=gd(),a=r.get("backup"),o=r.get("file"),l=Me({queryKey:V.organizations.workspaceBackups(n??"__none__"),queryFn:()=>_n.listWorkspaceBackups(n),enabled:!!n,refetchOnWindowFocus:!1}),c=((m=l.data)==null?void 0:m.backups)??[],d=c.find(v=>v.id===a)??c.find(xIe)??c[0]??null,u=xIe(d),f=Me({queryKey:V.organizations.workspaceBackupFiles(n??"__none__",(d==null?void 0:d.id)??"__none__",""),queryFn:()=>_n.listWorkspaceBackupFiles(n,d.id,""),enabled:!!n&&!!d&&u,refetchOnWindowFocus:!1}),A=h.useMemo(()=>o?xUn(o):new Set,[o]);return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:"Files"}),i.jsx("p",{className:"mt-0.5 truncate text-[12px] text-muted-foreground",children:d?`${yUn(d.fileCount)} · ${bUn(d.finishedAt??d.createdAt)}`:"Select a backup version"})]}),e?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>t(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]}),i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-auto px-1.5 py-2",children:l.isLoading?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Loading backups..."}):l.error?i.jsx("div",{className:"px-2 py-3 text-sm text-destructive",children:l.error.message}):d?u?f.isLoading?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Loading files..."}):f.error?i.jsx("div",{className:"px-2 py-3 text-sm text-destructive",children:f.error.message}):((g=f.data)==null?void 0:g.entries.length)===0?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:((x=f.data)==null?void 0:x.message)??"This backup is empty."}):i.jsx("ul",{className:"space-y-0.5",children:(((y=f.data)==null?void 0:y.entries)??[]).map(v=>i.jsx(oAt,{orgId:n,backupId:d.id,entry:v,selectedFilePath:o,onSelectFile:w=>wUn(r,s,w),expandedDirectories:A},v.path))}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:vUn(d)}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"No workspace backups yet."})})]})}function f$(e){var r;if(typeof document>"u")return null;const t=document.querySelector(`meta[name="${e}"]`),n=(r=t==null?void 0:t.getAttribute("content"))==null?void 0:r.trim();return n||null}function kde(e){if(!e)return null;const t=e.startsWith("#")?e.slice(1):e;return/^[0-9a-fA-F]{3}$/.test(t)?`#${t.split("").map(n=>`${n}${n}`).join("").toLowerCase()}`:/^[0-9a-fA-F]{6}$/.test(t)?`#${t.toLowerCase()}`:null}function SUn(e){const t=kde(e)??"#000000";return{r:Number.parseInt(t.slice(1,3),16),g:Number.parseInt(t.slice(3,5),16),b:Number.parseInt(t.slice(5,7),16)}}function Qne(e){const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function jUn(e){const{r:t,g:n,b:r}=SUn(e),s=.2126*Qne(t)+.7152*Qne(n)+.0722*Qne(r),a=1.05/(s+.05),o=(s+.05)/.05;return a>=o?"#f8fafc":"#111827"}function CUn(){if(f$("rudder-worktree-enabled")!=="true")return null;const e=f$("rudder-worktree-name"),t=kde(f$("rudder-worktree-color"));return!e||!t?null:{enabled:!0,name:e,color:t,textColor:kde(f$("rudder-worktree-text-color"))??jUn(t)}}function NUn(){const e=CUn();return e?i.jsx("div",{className:"relative overflow-hidden border-b px-3 py-1.5 text-[11px] font-medium tracking-[0.2em] uppercase",style:{backgroundColor:e.color,color:e.textColor,borderColor:`${e.textColor}22`,boxShadow:`inset 0 -1px 0 ${e.textColor}18`,backgroundImage:`linear-gradient(90deg, ${e.textColor}14, transparent 28%, transparent 72%, ${e.textColor}12), repeating-linear-gradient(135deg, transparent 0 10px, ${e.textColor}08 10px 20px)`},children:i.jsxs("div",{className:"flex items-center gap-2 overflow-hidden whitespace-nowrap",children:[i.jsx("span",{className:"shrink-0 opacity-70",children:"Worktree"}),i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-70","aria-hidden":"true"}),i.jsx("span",{className:"truncate font-semibold tracking-[0.12em]",children:e.name})]})}):null}function PUn({onMove:e,onStop:t,pointerId:n,resizeHandle:r}){let s=!0;const a=document.body.style.cursor,o=document.body.style.userSelect,l=()=>{if(s){if(s=!1,window.removeEventListener("pointermove",e),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l),window.removeEventListener("mousemove",e),window.removeEventListener("mouseup",l),window.removeEventListener("blur",l),r.removeEventListener("lostpointercapture",c),n!==null)try{r.hasPointerCapture(n)&&r.releasePointerCapture(n)}catch{}document.body.style.cursor=a,document.body.style.userSelect=o,t()}},c=d=>{(n===null||d.pointerId===n)&&l()};if(document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("pointermove",e),window.addEventListener("pointerup",l,{once:!0}),window.addEventListener("pointercancel",l,{once:!0}),window.addEventListener("mousemove",e),window.addEventListener("mouseup",l,{once:!0}),window.addEventListener("blur",l,{once:!0}),r.addEventListener("lostpointercapture",c),n!==null)try{r.setPointerCapture(n)}catch{}return{isActive:()=>s,stop:l}}const lAt="rudder.lastInstanceSettingsPath",cAt="rudder.lastWorkspacePath",dAt="rudder.workspace.contextWidth",nB="rudder.workspace.sidePanelWidth.v2",rB=420,N2e=340,Ode=292,IUn=N2e-Ode,P2e=4,TUn=10,uAt={apps:268,chat:318,messenger:332,issues:248,calendar:268,projects:268,agents:268,org:248,backups:332},fAt={apps:{min:236,max:360},chat:{min:280,max:420},messenger:{min:280,max:420},issues:{min:220,max:340,maxViewportFraction:1/3},calendar:{min:236,max:360},projects:{min:236,max:360},agents:{min:236,max:360},org:{min:220,max:340},backups:{min:280,max:420}};function bIe(e,t="authenticated"){const n=lWt();if(typeof window>"u")return n;try{return oKe(window.localStorage.getItem(lAt),e,t)}catch{return n}}function _Un(){if(typeof window>"u")return Qc;try{const e=window.localStorage.getItem(cAt);if(!e)return Qc;const t=fl(e);return t.startsWith("/instance/")||t.startsWith("/organization/settings")||EK(t)?Qc:t}catch{return Qc}}function MUn(e){return`${e.pathname}${e.search}${e.hash}`}function EUn(){var t;if(typeof window>"u")return!1;const e=(t=window.history.state)==null?void 0:t.idx;return typeof e=="number"&&e>0}function AAt({children:e,onClose:t}){const{t:n}=is(),{isMobile:r}=jc(),s=br(),[a,o]=h.useState(!1),l=bs("workspace-main:settings-modal"),c=h.useRef(null),d=h.useRef(null),u=h.useRef(null),f=h.useRef(null),A=h.useRef(typeof document<"u"&&document.activeElement instanceof HTMLElement?document.activeElement:null),m=h.useCallback(()=>{const g=Array.from(document.querySelectorAll('[data-settings-trigger="true"]')).find(v=>v.getClientRects().length>0&&!v.closest("[inert]")),x=A.current,y=x&&x!==document.body&&x!==document.documentElement&&x.isConnected&&!x.closest("[inert]")?x:g;y==null||y.focus({preventScroll:!0})},[]);return h.useEffect(()=>{const g=new Map,x=window.requestAnimationFrame(()=>{const y=u.current,v=f.current;if(!y||!v)return;let w=v;for(;w.parentElement;){for(const k of Array.from(w.parentElement.children))!(k instanceof HTMLElement)||g.has(k)||k===w||k===y||k.contains(v)||k.contains(y)||(g.set(k,{inert:k.inert,ariaHidden:k.getAttribute("aria-hidden")}),k.inert=!0,k.setAttribute("aria-hidden","true"));if(w=w.parentElement,w===document.body)break}});return()=>{window.cancelAnimationFrame(x);for(const[y,v]of g)y.inert=v.inert,v.ariaHidden===null?y.removeAttribute("aria-hidden"):y.setAttribute("aria-hidden",v.ariaHidden)}},[]),h.useEffect(()=>{r&&o(!1)},[r,s.pathname]),h.useEffect(()=>{var g,x;r&&(a?(g=c.current)==null||g.focus():(x=d.current)==null||x.focus())},[r,a]),i.jsx(_M,{open:!0,onOpenChange:g=>{g||t()},children:i.jsxs(MM,{children:[i.jsx(EM,{ref:u,"data-testid":"settings-modal-backdrop",className:"settings-modal-backdrop fixed inset-0 z-50"}),i.jsxs(mj,{"data-testid":"settings-modal-shell",ref:f,"aria-describedby":void 0,tabIndex:-1,className:"settings-modal-shell fixed left-1/2 top-1/2 z-50 flex min-h-0 w-[calc(100%-1rem)] max-w-[1440px] -translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-[10px] sm:w-[calc(100%-2rem)]",onOpenAutoFocus:g=>{var x;r&&(g.preventDefault(),(x=d.current)==null||x.focus({preventScroll:!0}))},onCloseAutoFocus:g=>{g.preventDefault(),m()},onEscapeKeyDown:g=>{!r||!a||(g.preventDefault(),o(!1))},children:[i.jsx(DM,{className:"sr-only",children:n("common.systemSettings")}),r&&a?i.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 z-10 bg-foreground/10 backdrop-blur-[1px]",onClick:()=>o(!1)}):null,i.jsxs("div",{id:"settings-modal-navigation","data-testid":"settings-modal-navigation","aria-hidden":r&&!a,inert:r&&!a?!0:void 0,className:K("z-20 flex h-full min-h-0 shrink-0",r?"absolute inset-y-0 left-0 transition-transform duration-200 ease-out motion-reduce:transition-none":"relative",r&&!a&&"pointer-events-none -translate-x-full"),onClickCapture:g=>{r&&g.target.closest("a")&&o(!1)},children:[r&&a?i.jsx(le,{ref:c,variant:"ghost",size:"icon-sm",className:"absolute right-1 top-1 z-10 size-8 rounded-full text-muted-foreground",onClick:()=>o(!1),"aria-label":`${n("common.closeSidebar")} (${n("common.systemSettings")})`,title:n("common.closeSidebar"),children:i.jsx(Is,{className:"h-4 w-4"})}):null,i.jsx(mde,{showBackButton:!1,variant:"modal"})]}),i.jsxs("section",{className:"settings-modal-main flex min-h-0 min-w-0 flex-1 flex-col",inert:r&&a?!0:void 0,children:[i.jsxs("div",{className:"flex h-14 shrink-0 items-center justify-between px-3 sm:px-5",children:[r?i.jsx(le,{ref:d,variant:"ghost",size:"icon-sm",className:"size-8 rounded-full text-muted-foreground",onClick:()=>o(!0),"aria-expanded":a,"aria-controls":"settings-modal-navigation","aria-label":n("common.openSidebar"),title:n("common.openSidebar"),children:i.jsx(ow,{className:"h-4 w-4"})}):i.jsx("span",{}),i.jsx(le,{variant:"ghost",size:"icon-sm",className:"size-8 rounded-full text-muted-foreground",onClick:t,"aria-label":n("common.closeSettings"),title:n("common.closeSettings"),children:i.jsx(Is,{className:"h-4 w-4"})})]}),i.jsx("main",{id:"main-content",tabIndex:-1,ref:l,className:"scrollbar-auto-hide min-w-0 flex-1 overflow-auto",children:e})]})]})]})})}function DUn(){return typeof window>"u"||!("desktopShell"in window)||!window.desktopShell?!1:/Mac/i.test(window.navigator.userAgent)}function RUn(e){return/^\/apps(?:\/|$)/.test(e)?"apps":/^\/workspaces\/backups(?:\/|$)/.test(e)?"backups":/^\/chat(?:\/|$)/.test(e)?"chat":/^\/messenger(?:\/|$)/.test(e)?"messenger":/^\/issues(?:\/|$)/.test(e)?"issues":/^\/(?:dashboard\/calendar|calendar)(?:\/|$)/.test(e)?"calendar":/^\/projects(?:\/|$)/.test(e)?"org":/^\/agents(?:\/|$)/.test(e)?"agents":/^\/(?:dashboard|org|library|resources|heartbeats|workspaces|goals|skills|costs|activity)(?:\/|$)/.test(e)?"org":null}function LUn(e){return/^\/apps(?:\/|$)/.test(e)||/^\/(?:library|resources|workspaces)(?:\/|$)/.test(e)&&!/^\/workspaces\/backups(?:\/|$)/.test(e)||/^\/automations(?:\/|$)/.test(e)||/^\/chat(?:\/|$)/.test(e)||/^\/messenger\/chat(?:\/|$)/.test(e)||/^\/messenger\/(?:workbench|saved)(?:\/|$)/.test(e)?!0:e==="/messenger"}function A$(e){try{return decodeURIComponent(e)}catch{return e}}function zUn(e){var n,r;const t=((r=(n=e.split("?")[0])==null?void 0:n.split("#")[0])==null?void 0:r.split("/").filter(Boolean))??[];return t[0]==="messenger"&&t[1]==="chat"&&t[2]?`chat:${A$(t[2])}`:t[0]==="messenger"&&t[1]==="issues"&&t[2]?`issue:${A$(t[2])}`:t[0]==="chat"&&t[1]?`chat:${A$(t[1])}`:t[0]==="agents"&&t[1]&&t[2]==="runs"?`agent-runs:${A$(t[1])}`:null}function $Un(e,t){return zUn(e)??(t?`organization:${t}:global`:"global")}function FUn(e,t,n){var o;const r=$Un(e,t),s=/^\/messenger\/(?:workbench(?:\/|$)|saved\/[^/]+(?:\/|$))/.test(((o=e.split("?")[0])==null?void 0:o.split("#")[0])??e),a=(n==null?void 0:n.contextKey.startsWith("chat:"))||(n==null?void 0:n.contextKey.startsWith("issue:"));return(s||r===(n==null?void 0:n.contextKey))&&a&&(n==null?void 0:n.organizationId)===t?{contextKey:n.contextKey,preserveHold:!0}:{contextKey:r,preserveHold:!1}}function X_(){return typeof window>"u"?null:window.innerWidth}function BUn(){const[e,t]=h.useState(X_);return h.useEffect(()=>{if(typeof window>"u")return;const n=()=>t(X_());return n(),window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),e}function QUn(e,t=X_()){const{max:n,maxViewportFraction:r}=fAt[e];return!r||t===null||!Number.isFinite(t)?n:Math.max(n,Math.floor(t*r))}function fq(e,t,n=X_()){const{min:r}=fAt[e],s=QUn(e,n);return Math.min(s,Math.max(r,Math.round(t)))}function yIe(e){const t=uAt[e];if(typeof window>"u")return t;try{const n=window.localStorage.getItem(`${dAt}.${e}`),r=n?Number.parseInt(n,10):Number.NaN;return Number.isFinite(r)?fq(e,r):t}catch{return t}}function I2e(e){const t=Math.max(0,e-P2e),n=t*(2/3);return{availableWidth:t,dockedMinWidth:Math.min(N2e,t/2),dockedMaxWidth:n}}function Aq(e,t=null){const n=Math.round(e);if(t===null||!Number.isFinite(t))return Math.max(N2e,n);const r=I2e(t);return Math.min(r.dockedMaxWidth,Math.max(r.dockedMinWidth,n))}function UUn(e,t,n){return fq(e,t*n,n)}function VUn(e,t){return Aq(e*t,t)}function Une(e){return Aq((e-P2e)/2,e)}function qUn(e,t){const{availableWidth:n}=I2e(t),r=n-e;return e>2*r}function KUn(e){if(e===null||!Number.isFinite(e))return Ode;const{dockedMinWidth:t}=I2e(e);return Math.max(0,Math.min(Ode,t-IUn))}function WUn(e,t,n,r){const s=Number.isFinite(n)&&Number.isFinite(r)&&n>0&&r>0?n/r:1;return e-t/s}function B5(e,t=X_()){return t===null||!Number.isFinite(t)||t<=0?null:e/t}function ZUn(e){return Math.round(e)}function HUn(){if(typeof window>"u")return rB;try{const e=window.localStorage.getItem(nB),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)?ZUn(t):rB}catch{return rB}}function XUn({contextReady:e,expanded:t,onExpandedChange:n,selectedOrganizationId:r}){const s=Ob(),a=h.useRef(null),[o,l]=h.useState(null),c=h.useRef(typeof window<"u"&&window.localStorage.getItem(nB)!==null),d=h.useRef(c.current),[u,f]=h.useState(!c.current),[A,m]=h.useState(HUn),g=h.useRef(null),[x,y]=h.useState(!1),v=h.useRef(s.open),w=h.useRef(!1),k=h.useRef(!1),S=h.useRef(null);h.useEffect(()=>{if(!(typeof window>"u"||!d.current))try{window.localStorage.setItem(nB,String(A))}catch{}},[A]),h.useLayoutEffect(()=>{var $;const _=($=a.current)==null?void 0:$.parentElement;if(!_)return;const D=()=>l(_.offsetWidth);D();const U=new ResizeObserver(D);return U.observe(_),()=>U.disconnect()},[]),h.useEffect(()=>{if(c.current||o===null)return;const _=Une(o);g.current=B5(_,o),m(_)},[o]),h.useLayoutEffect(()=>{const _=v.current;if(v.current=s.open,!_&&s.open){const U=window.requestAnimationFrame(()=>{var $;($=document.querySelector("[data-testid='chat-side-panel-collapse']"))==null||$.focus()});return()=>window.cancelAnimationFrame(U)}if(!_||s.open||!w.current)return;w.current=!1;const D=window.requestAnimationFrame(()=>{var L;const U=document.querySelector("[data-testid='chat-side-panel-trigger']"),$=document.querySelector("[data-testid='global-side-panel-trigger']");(L=U??$)==null||L.focus()});return()=>window.cancelAnimationFrame(D)},[s.open]),h.useEffect(()=>{if(o===null||u)return;const _=g.current;if(_===null){const D=Aq(A,o);g.current=B5(D,o),m(D);return}m(VUn(_,o))},[u,o]);const j=h.useCallback(_=>{const D=Aq(_,o);return g.current=o===null?null:B5(D,o),m(D),D},[o]),C=h.useCallback(()=>{f(!0),c.current=!1,d.current=!1;try{window.localStorage.removeItem(nB)}catch{}const _=o===null?rB:Une(o);return j(_)},[j,o]),N=u&&o!==null?Une(o):A;h.useEffect(()=>()=>{var _;(_=S.current)==null||_.call(S)},[]);const P=h.useCallback(_=>{var Ae,Y;if(!s.open||k.current)return;_.preventDefault(),k.current=!0,f(!1),c.current=!0,d.current=!0;const D=_.clientX,U=_.currentTarget,$=(Ae=a.current)==null?void 0:Ae.parentElement,L=((Y=$==null?void 0:$.querySelector("[data-testid='chat-side-panel']"))==null?void 0:Y.offsetWidth)??null,H=($==null?void 0:$.offsetWidth)??o,X=($==null?void 0:$.getBoundingClientRect().width)??H,F=KUn(H),Q=L!==null&&L>0?L:N,q="pointerId"in _?_.pointerId:null;let B=Q,ee=!1;j(Q),y(!0);let se=()=>{};const ne=PUn({resizeHandle:U,pointerId:q,onMove:ce=>{const Oe=ce.clientX-D;if(B=WUn(Q,Oe,X??H??0,H??0),H!==null&&qUn(B,H)){se(),n(!0);return}if(B<=F){ee=!0,se(),s.hidePanel(),C();return}j(B)},onStop:()=>{S.current=null,k.current=!1,y(!1),!ee&&B<=F&&(s.hidePanel(),C())}});se=ne.stop,S.current=ne.isActive()?se:null},[N,n,C,j,s,o]),M=e&&s.open,E=e&&s.open&&t,T=M?E?o??N:N:0,R=M&&!E;return i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:a,className:"hidden","aria-hidden":"true"}),M?null:i.jsx("div",{className:"group absolute inset-y-1 right-0 z-20 w-1","data-testid":"side-panel-hover-edge",children:i.jsx(le,{type:"button",variant:"outline",size:"icon","data-testid":"global-side-panel-trigger",className:"pointer-events-none absolute right-[3px] top-1/2 h-11 w-7 -translate-y-1/2 rounded-l-[calc(var(--radius-sm)-1px)] rounded-r-none border-r-0 bg-[color:var(--surface-elevated)] text-muted-foreground opacity-0 shadow-[var(--shadow-sm)] transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100 hover:bg-[color:var(--surface-active)] hover:text-foreground",onClick:s.showPanel,"aria-label":"Open Side Panel",title:"Open Side Panel",children:i.jsx(dT,{className:"h-4 w-4"})})},"trigger"),i.jsxs("div",{"data-testid":"side-panel-resizer","aria-hidden":!R,className:K("motion-resize workspace-column-resizer group relative z-20 flex shrink-0 touch-none select-none items-stretch justify-center",R?"cursor-col-resize opacity-100":"pointer-events-none opacity-0",x&&"is-resizing"),style:{width:R?P2e:0},onPointerDown:P,onMouseDown:P,role:R?"separator":void 0,"aria-orientation":"vertical","aria-label":R?"Resize Side Panel":void 0,children:[i.jsx("span",{"data-testid":"side-panel-resizer-hit-target",className:"absolute inset-y-0 left-1/2 -translate-x-1/2",style:{width:TUn},"aria-hidden":"true"}),i.jsx("div",{className:"workspace-column-resizer-line"})]},"resizer"),x?i.jsx("div",{"data-testid":"side-panel-resize-shield",className:"fixed inset-0 z-[200] cursor-col-resize","aria-hidden":"true"}):null,i.jsx("div",{className:K("motion-resize relative flex min-h-0 shrink-0 overflow-hidden",E&&"z-30",x&&"transition-none"),"data-testid":E?"side-panel-expanded-overlay":"side-panel-stable-host","data-side-panel-state":E?"expanded":M?"docked":"closed",style:{width:T},"aria-hidden":!M,inert:M?void 0:!0,onFocusCapture:()=>{w.current=!0},onBlurCapture:_=>{s.open&&!_.currentTarget.contains(_.relatedTarget)&&(w.current=!1)},children:i.jsx(Iut,{contextReady:e,selectedOrganizationId:r,expanded:E,onClose:()=>{t&&(n(!1),C()),s.hidePanel()},onToggleExpanded:()=>{t?(n(!1),C()):n(!0)}})},"panel")]})}function GUn({contextKey:e,preserveHold:t}){const{clearDisplayedContextHold:n,setContextKey:r}=Ob();return h.useLayoutEffect(()=>{t||n(),r(e)},[n,e,t,r]),null}function YUn({onOpen:e}){return i.jsx("div",{"data-testid":"workspace-sidebar-reopen-zone",className:"group absolute inset-y-0 left-0 z-30 flex w-8 items-center",children:i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"outline",size:"icon","data-testid":"workspace-sidebar-reopen-button",className:"desktop-window-no-drag pointer-events-none h-10 w-7 shrink-0 -translate-x-1/2 rounded-l-none rounded-r-[calc(var(--radius-sm)-1px)] border-l-0 bg-[color:var(--surface-elevated)] text-muted-foreground opacity-0 shadow-[var(--shadow-sm)] transition-[background-color,color,opacity,transform] duration-[var(--motion-duration-fast)] ease-[var(--motion-ease-standard)] group-hover:pointer-events-auto group-hover:translate-x-0 group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:translate-x-0 group-focus-within:opacity-100 hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none",onClick:e,"aria-label":"Open workspace sidebar",title:"Open workspace sidebar",children:i.jsx(ow,{className:"h-4 w-4","aria-hidden":"true"})})}),i.jsx(ia,{side:"right",children:"Open workspace sidebar"})]})})}function vIe(){const{t:e}=is(),t=Vn(),{sidebarOpen:n,setSidebarOpen:r,toggleSidebar:s,isMobile:a}=jc(),{openNewIssue:o,openOnboarding:l,onboardingOpen:c,productTourOpen:d,openProductTour:u}=ii(),{togglePanelVisible:f}=MW(),{contextKey:A,displayedContextHold:m,open:g}=Ob(),{organizations:x,loading:y,selectedOrganization:v,selectedOrganizationId:w,selectionSource:k,setSelectedOrganizationId:S}=jr(),{pushToast:j}=ss(),{orgPrefix:C}=Uo(),N=Yr(),P=br(),M=B7t(),E=h.useRef([]),T=h.useMemo(()=>DUn(),[]),R=P.pathname.startsWith("/instance/"),_=h.useMemo(()=>fl(P.pathname),[P.pathname]),D=h.useMemo(()=>`${_}${P.search}${P.hash}`,[P.hash,P.search,_]),U=h.useMemo(()=>RUn(_),[_]),$=h.useMemo(()=>!/^\/apps\/saved\/[^/]+(?:\/|$)/.test(_)&&/^\/(?:apps|chat|messenger|issues|calendar|dashboard|agents|projects|org|library|resources|heartbeats|workspaces|goals|skills|costs|activity)(?:\/|$)/.test(_),[_]),L=h.useMemo(()=>/^\/workspaces\/backups(?:\/|$)/.test(_),[_]),H=h.useMemo(()=>/^\/(?:library|resources|workspaces)(?:\/|$)/.test(_)&&!/^\/workspaces\/backups(?:\/|$)/.test(_),[_]),X=h.useMemo(()=>/^\/chat(?:\/|$)/.test(_),[_]);h.useMemo(()=>/^\/messenger(?:\/|$)/.test(_),[_]);const F=h.useMemo(()=>LUn(_),[_]),Q=h.useMemo(()=>/^\/projects(?:\/|$)/.test(_),[_]),q=h.useMemo(()=>/\/chat\/[^/]+/.test(_),[_]),B=h.useMemo(()=>/^\/organization\/settings(?:\/|$)/.test(_),[_]),ee=h.useMemo(()=>Zj(P.state),[P.state]),se=h.useMemo(()=>wW(P),[P]),re=R||B,ne=h.useRef(!1),Ae=h.useRef(!1),Y=h.useRef(0),ce=BUn(),[Oe,Fe]=h.useState(!0),[ke,Ne]=h.useState(()=>U?yIe(U):uAt.issues),xe=h.useRef(B5(ke)),[ae,fe]=h.useState(!1),[ve,Se]=h.useState(!1),ze=bs(`workspace-main:${_}`),{data:ft}=Me({queryKey:V.access.currentBoardAccess,queryFn:()=>bc.getCurrentBoardAccess(),retry:!1}),ie=(ft==null?void 0:ft.isInstanceAdmin)===!0,[me,we]=h.useState(()=>bIe(!1)),Xe=h.useMemo(()=>C?aw({organizations:x,organizationPrefix:C}):null,[x,C]),ge=FUn(_,Xe==null?void 0:Xe.id,m),te=A===ge.contextKey,G=te?Xe==null?void 0:Xe.id:null,oe=te&&g&&ve,Ze=!!C&&!y&&x.length>0&&!Xe,{data:Te}=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1,refetchInterval:gt=>{var Gt;const Nt=gt.state.data;return(Gt=Nt==null?void 0:Nt.devServer)!=null&&Gt.enabled?2e3:!1},refetchIntervalInBackground:!0}),{data:Be}=Me({queryKey:V.chats.listPreview(w??"__none__","active",40),queryFn:()=>Xn.list(w,"active",{limit:40}),enabled:X&&!!w}),{data:it}=Me({queryKey:V.projects.list(w??"__none__"),queryFn:async()=>(await Mi.list(w)).filter(Nt=>!Nt.archivedAt),enabled:Q&&!!w}),lt=h.useMemo(()=>$?X?q||((Be==null?void 0:Be.length)??0)>0:!0:!1,[Be==null?void 0:Be.length,q,X,$]),Ue=h.useMemo(()=>lt?!Q||!(/^\/projects(?:\/|$)/.test(_)&&!/^\/projects\/[^/]+/.test(_))?!0:((it==null?void 0:it.length)??0)>0:!1,[Q,_,lt,it==null?void 0:it.length]);h.useEffect(()=>{y||ne.current||(Te==null?void 0:Te.deploymentMode)!=="authenticated"&&x.length===0&&(ne.current=!0,l())},[x,y,l,Te==null?void 0:Te.deploymentMode]),h.useEffect(()=>{Ae.current||d||c||y||x.length===0||re||_==="/onboarding"||lBn()||!xft()||(Ae.current=!0,u({source:"auto"}))},[re,c,u,x.length,y,d,_]),h.useEffect(()=>{if(!C||y||x.length===0)return;if(!Xe){const Nt=(w?x.find(Gt=>Gt.id===w):null)??x[0]??null;Nt&&w!==Nt.id&&S(Nt.id,{source:"route_sync"});return}const gt=Oc(Xe);if(C.toLowerCase()!==gt.toLowerCase()){const Nt=P.pathname.replace(/^\/[^/]+/,"");N(`/${gt}${Nt}${P.search}`,{replace:!0});return}AWt({selectionSource:k,selectedOrganizationId:w,routeOrganizationId:Xe.id})&&S(Xe.id,{source:"route_sync"})},[C,x,y,Xe,P.pathname,P.search,N,k,w,S]);const mt=f;oWt(),h.useLayoutEffect(()=>{Se(!1)},[Xe==null?void 0:Xe.id]),h.useLayoutEffect(()=>{te||Se(!1)},[te]),h.useLayoutEffect(()=>{g||Se(!1)},[g]),h.useEffect(()=>{mWt(Xe==null?void 0:Xe.id,D)},[Xe==null?void 0:Xe.id,D]),h.useEffect(()=>{if(!a){Fe(!0);return}Y.current=0,Fe(!0)},[a]),h.useEffect(()=>{if(!a)return;const gt=30,Nt=50,Gt=75;let cn=0,Rn=0,nt=!1;const Qt=Rt=>{const Cn=Rt.touches[0];cn=Cn.clientX,Rn=Cn.clientY;const zn=Rt.target instanceof Element?Rt.target:null;nt=!!(zn!=null&&zn.closest('[data-slot="dialog-content"], [data-slot="dialog-overlay"], [data-testid="chat-side-panel"]'))},st=Rt=>{if(nt){nt=!1;return}const Cn=Rt.changedTouches[0],zn=Cn.clientX-cn;if(!(Math.abs(Cn.clientY-Rn)>Gt)){if(!n&&cn<gt&&zn>Nt){r(!0);return}n&&zn<-Nt&&r(!1)}};return document.addEventListener("touchstart",Qt,{passive:!0}),document.addEventListener("touchend",st,{passive:!0}),()=>{document.removeEventListener("touchstart",Qt),document.removeEventListener("touchend",st)}},[a,n,r]);const tt=h.useCallback(gt=>{const Nt=gt-Y.current;gt<=24?Fe(!0):Nt>8?Fe(!1):Nt<-8&&Fe(!0),Y.current=gt},[]);h.useEffect(()=>{if(!a){Fe(!0),Y.current=0;return}const gt=()=>{tt(window.scrollY||document.documentElement.scrollTop||0)};return gt(),window.addEventListener("scroll",gt,{passive:!0}),()=>{window.removeEventListener("scroll",gt)}},[a,tt]),h.useEffect(()=>{const gt=document.body.style.overflow;return document.body.style.overflow=a?"visible":"hidden",()=>{document.body.style.overflow=gt}},[a]),h.useEffect(()=>{we(bIe(ie,(Te==null?void 0:Te.deploymentMode)??"authenticated"))},[ie,Te==null?void 0:Te.deploymentMode]),h.useEffect(()=>{if(!U)return;const gt=yIe(U);xe.current=B5(gt),Ne(gt)},[U]),h.useEffect(()=>{if(!U||ce===null||!Number.isFinite(ce))return;const gt=xe.current;if(gt===null){xe.current=B5(ke,ce);return}Ne(UUn(U,gt,ce))},[ce,U]),h.useEffect(()=>{if(U)try{window.localStorage.setItem(`${dAt}.${U}`,String(fq(U,ke)))}catch{}},[ke,U]),h.useEffect(()=>{if(re)return;const gt=fl(`${P.pathname}${P.search}${P.hash}`);if(!EK(gt))try{window.localStorage.setItem(cAt,gt)}catch{}},[re,P.hash,P.pathname,P.search]),h.useEffect(()=>{if(!re)return;const gt=oKe(`${P.pathname}${P.search}${P.hash}`,ie,(Te==null?void 0:Te.deploymentMode)??"authenticated");we(gt);try{window.localStorage.setItem(lAt,gt)}catch{}},[ie,Te==null?void 0:Te.deploymentMode,re,P.hash,P.pathname,P.search]);const dt=!a&&!re,at=dt&&Ue,Pe=dt,$e=!a&&re,ot=dt?F?"p-0":"px-2 py-1.5 md:px-3.5 md:py-2.5 lg:px-5 lg:py-3":"px-2.5 py-1.5 md:px-3 md:py-2 lg:px-4 lg:py-2.5",ue=h.useCallback(()=>{yWt(t,{target:me,organizationId:w})},[t,w,me]),Ie=h.useCallback(()=>{const gt=`${P.pathname}${P.search}${P.hash}`;ohe(gt),N(me,se?{state:se}:void 0),ue(),a&&r(!1)},[a,P.hash,P.pathname,P.search,N,ue,r,se,me]);h.useEffect(()=>{const gt=MUn(P),Nt=E.current;if(Nt.length===0){Nt.push(gt);return}const Gt=Nt.lastIndexOf(gt);if(M==="POP"){Gt>=0?Nt.splice(Gt+1):Nt.push(gt);return}if(M==="REPLACE"){Nt[Nt.length-1]=gt;return}Nt[Nt.length-1]!==gt&&Nt.push(gt),Nt.length>50&&Nt.splice(0,Nt.length-50)},[P,M]);const Ke=h.useCallback(()=>{const gt=E.current;if(gt.length<2)return EUn()?(N(-1),!0):!1;const Nt=fWt(gt),Gt=Nt>=0?gt[Nt]:null;return Gt?(gt.splice(Nt+1),N(Gt),!0):!1},[N]),De=h.useCallback(()=>{if(!w){j({title:"Select an organization first",body:"A new chat must belong to an organization.",tone:"error"});return}N("/messenger/chat")},[N,j,w]),Je=Me({queryKey:V.instance.shortcutSettings,queryFn:()=>Ha.getShortcuts(),retry:!1}),_e=Je.data===void 0?Je.isError?null:void 0:Je.data,Ee=_e!==void 0;tWt({onNewChat:De,onNewIssue:()=>o(),onToggleSidebar:s,onTogglePanel:mt,onOpenSettings:()=>Ie(),onNavigateBack:Ke,shortcutSettings:_e});const Ce=T?"h-full flex-1 pl-2.5 pb-1 pr-1 pt-0.5 md:pl-3 md:pb-1.5 md:pr-1.5 md:pt-0.5":"h-full flex-1 pl-0 pb-1 pr-1 pt-0.5 md:pb-1.5 md:pr-1.5 md:pt-1";function kt(){yT(),N(ee??_Un(),{replace:!0})}const Qe=h.useCallback(gt=>{if(!U||a)return;gt.preventDefault();const Nt=gt.clientX,Gt=ke,cn={cursor:document.body.style.cursor,userSelect:document.body.style.userSelect};document.body.style.cursor="col-resize",document.body.style.userSelect="none",fe(!0);const Rn=Qt=>{const st=Qt.clientX-Nt,Rt=fq(U,Gt+st);xe.current=B5(Rt),Ne(Rt)},nt=()=>{document.body.style.cursor=cn.cursor,document.body.style.userSelect=cn.userSelect,fe(!1),window.removeEventListener("pointermove",Rn),window.removeEventListener("pointerup",nt)};window.addEventListener("pointermove",Rn),window.addEventListener("pointerup",nt,{once:!0})},[ke,a,U]);return i.jsx(HKt,{navigateBack:Ke,children:i.jsxs("div",{"data-shortcut-settings-ready":Ee?"true":"false",className:K("app-shell-backdrop text-foreground pt-[env(safe-area-inset-top)]",a?"min-h-dvh":"flex h-dvh flex-col overflow-hidden"),children:[i.jsx("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-[200] focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:e("common.skipToMainContent")}),i.jsx(NUn,{}),i.jsx(gFn,{devServer:Te==null?void 0:Te.devServer}),i.jsxs(e$t,{children:[i.jsx(GUn,{contextKey:ge.contextKey,preserveHold:ge.preserveHold}),i.jsxs(ZKt,{children:[i.jsxs("div",{className:K("min-h-0 flex-1",a?"w-full":"flex overflow-hidden"),children:[a&&n&&i.jsx("button",{type:"button",className:"fixed inset-0 z-40 bg-[rgb(23_17_11/0.28)] backdrop-blur-sm",onClick:()=>r(!1),"aria-label":e("common.closeSidebar")}),a?i.jsxs("div",{className:K("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-[env(safe-area-inset-top)] transition-transform duration-100 ease-out",n?"translate-x-0":"-translate-x-full"),children:[i.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:R?i.jsx(mde,{}):B?i.jsx(mde,{}):i.jsx(UKt,{})}),i.jsx("div",{className:"editorial-dock px-3 py-3",children:i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("a",{href:xT,target:"_blank",rel:"noopener noreferrer",className:"flex min-w-0 flex-1 items-center gap-2.5 rounded-full px-3 py-2 text-[13px] font-medium text-muted-foreground transition-colors hover:bg-[color:var(--surface-active)] hover:text-foreground",children:[i.jsx(nE,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"truncate",children:e("common.documentation")})]}),(Te==null?void 0:Te.version)&&i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx("span",{className:"px-2 text-xs text-muted-foreground shrink-0 cursor-default",children:"v"})}),i.jsxs(ia,{children:["v",Te.version]})]}),re?i.jsx(le,{variant:"ghost",size:"icon-sm",className:"text-muted-foreground shrink-0",asChild:!0,children:i.jsx(sn,{to:Qc,"aria-label":e("common.backToWorkspace"),title:e("common.backToWorkspace"),onClick:()=>{a&&r(!1)},children:i.jsx(Kx,{className:"h-4 w-4"})})}):i.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",className:"settings-entry-button shrink-0 text-muted-foreground",onPointerEnter:ue,onFocus:ue,onClick:Ie,"aria-label":e("common.systemSettings"),title:e("common.systemSettings"),"data-settings-trigger":"true",children:i.jsx(Ix,{className:"h-4 w-4"})})]})})]}):i.jsx("div",{className:K("flex h-full min-h-0 shrink-0",T&&"pt-[var(--desktop-sidebar-top-clearance)]"),children:re?null:i.jsx(rBn,{onOpenSettings:Ie,onWarmSettings:ue})}),i.jsxs("div",{className:K("flex min-w-0 flex-col",a?"w-full":Ce),children:[!a&&T?i.jsx("div",{className:"desktop-window-drag h-[var(--desktop-content-top-gap)] shrink-0"}):null,$e?i.jsx(AAt,{onClose:kt,children:Ze?i.jsx(T4,{scope:"invalid_organization_prefix",requestedPrefix:C??(v==null?void 0:v.issuePrefix)}):i.jsx(zP,{})}):i.jsxs("div",{"data-testid":a?void 0:"workspace-shell",className:K("flex min-h-0 min-w-0 flex-1 flex-col",a?"w-full":"workspace-shell overflow-hidden",!a&&H&&"workspace-shell--library-transparent"),children:[Pe?null:i.jsx("div",{className:K(a&&"sticky top-0 z-20 bg-background/80 backdrop-blur-xl supports-[backdrop-filter]:bg-background/65"),children:i.jsx(jPe,{desktopChrome:T})}),i.jsx("div",{className:K(a?"block":"flex min-h-0 min-w-0 flex-1"),children:dt?i.jsxs("div",{className:K("relative flex min-h-0 min-w-0 flex-1","px-[3px] pb-[3px] pt-[1px] md:px-1 md:pb-1 md:pt-0.5"),children:[at?i.jsxs(i.Fragment,{children:[i.jsx("div",{"data-testid":"workspace-context-card","aria-hidden":!n,inert:n?void 0:!0,className:K("flex min-h-0 shrink-0 overflow-hidden","workspace-context-card",!ae&&"transition-[width,opacity,border-color] duration-200 ease-out motion-reduce:transition-none",n?"opacity-100":"pointer-events-none border-0 border-transparent opacity-0"),style:{width:n?ke:0},children:L?i.jsx(OUn,{}):H?i.jsx(x$n,{onCollapseSidebar:()=>r(!1)}):i.jsx(gUn,{})}),i.jsx("div",{"data-testid":"workspace-column-resizer","aria-hidden":!n,className:K("workspace-column-resizer group flex shrink-0 cursor-col-resize items-stretch justify-center transition-[width,opacity] duration-200 ease-out motion-reduce:transition-none",n?"w-2 opacity-100 md:w-[9px]":"w-0 overflow-hidden opacity-0",ae&&"is-resizing"),onPointerDown:Qe,role:n?"separator":void 0,"aria-orientation":"vertical","aria-label":"Resize workspace columns",children:i.jsx("div",{className:"workspace-column-resizer-line"})})]}):null,at&&!n&&F?i.jsx(YUn,{onOpen:()=>r(!0)}):null,i.jsxs("div",{className:"workspace-main-panel-stack relative flex min-h-0 min-w-0 flex-1","data-testid":"workspace-main-panel-stack",children:[i.jsxs("div",{"data-testid":"workspace-main-card","data-tour-target":"workspace-main","aria-hidden":oe||void 0,inert:oe?!0:void 0,className:K("flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden","workspace-main-card",F&&"workspace-main-card--frameless",oe&&"pointer-events-none border-0 [box-shadow:none]"),children:[F?null:i.jsx("div",{"data-testid":"workspace-main-header",className:"shrink-0",children:i.jsx(jPe,{desktopChrome:T,variant:"card"})}),i.jsx("main",{id:"main-content",tabIndex:-1,ref:ze,className:K("scrollbar-auto-hide min-w-0 flex-1",ot,a?"overflow-visible pb-[calc(5rem+env(safe-area-inset-bottom))]":F?"overflow-hidden":"overflow-auto"),children:Ze?i.jsx(T4,{scope:"invalid_organization_prefix",requestedPrefix:C??(v==null?void 0:v.issuePrefix)}):i.jsx(zP,{})})]}),i.jsx(XUn,{contextReady:te,expanded:ve,selectedOrganizationId:G,onExpandedChange:Se})]})]}):i.jsx("main",{id:"main-content","data-tour-target":"workspace-main",tabIndex:-1,ref:ze,className:K("scrollbar-auto-hide min-w-0 flex-1",ot,a?"overflow-visible pb-[calc(5rem+env(safe-area-inset-bottom))]":"overflow-auto"),children:Ze?i.jsx(T4,{scope:"invalid_organization_prefix",requestedPrefix:C??(v==null?void 0:v.issuePrefix)}):i.jsx(zP,{})})})]})]})]}),a&&i.jsx(xFn,{visible:Oe}),i.jsx(fFn,{}),i.jsx(FFn,{}),i.jsx(WFn,{}),i.jsx(vFn,{}),i.jsx(yFn,{}),a?i.jsx(Iut,{contextReady:te,selectedOrganizationId:G}):null]})]})]})})}function oh({width:e="default",className:t,children:n,...r}){return i.jsx("div",{...r,"data-slot":"settings-page","data-width":e,className:K("mx-auto flex w-full flex-col gap-7 px-4 pb-10 sm:px-7",e==="default"&&"max-w-[52rem]",e==="wide"&&"max-w-[64rem]",e==="full"&&"max-w-none",t),children:n})}function am({eyebrow:e,icon:t,title:n,description:r,action:s}){return i.jsxs("header",{"data-slot":"settings-page-header",className:"flex flex-col gap-2",children:[e?i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground/72",children:e}):null,i.jsxs("div",{className:"grid grid-cols-1 items-start gap-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:gap-5",children:[i.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[t?i.jsx(t,{className:"mt-0.5 size-5 shrink-0 text-muted-foreground"}):null,i.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[i.jsx("h1",{className:"font-display text-[1.4rem] font-semibold leading-tight text-foreground sm:text-[1.55rem]",children:n}),r?i.jsx("div",{className:"max-w-3xl text-[13px] leading-5 text-muted-foreground",children:r}):null]})]}),s?i.jsx("div",{className:"flex shrink-0 items-center sm:justify-end",children:s}):null]})]})}function Wa({variant:e="default",children:t,className:n,...r}){return i.jsx("div",{...r,"data-slot":"settings-group","data-variant":e,className:K("overflow-hidden rounded-lg border border-[color:var(--border-soft)] [&>[data-slot=settings-actions]]:border-t [&>[data-slot=settings-actions]]:border-[color:var(--border-soft)] [&>[data-slot=settings-item]+[data-slot=settings-item]]:border-t [&>[data-slot=settings-item]+[data-slot=settings-item]]:border-[color:var(--border-soft)]",e==="feature"?"bg-[color:var(--surface-elevated)]":"bg-[color:color-mix(in_oklab,var(--surface-inset)_84%,var(--surface-elevated))]",n),children:t})}function ja({icon:e,title:t,description:n,action:r,headingLevel:s=3,className:a}){const o=s===2?"h2":"h3";return i.jsxs("div",{"data-slot":"settings-item",className:K("grid min-h-[4.25rem] grid-cols-1 items-center gap-3 px-4 py-3.5 sm:grid-cols-[minmax(0,1fr)_auto] sm:gap-5",a),children:[i.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e?i.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center text-muted-foreground",children:i.jsx(e,{className:"size-5"})}):null,i.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[i.jsx(o,{className:"text-[14px] font-medium leading-5 text-foreground",children:t}),n?i.jsx("div",{className:"max-w-[38rem] text-[13px] leading-5 text-muted-foreground",children:n}):null]})]}),r?i.jsx("div",{className:"flex w-full shrink-0 items-center justify-start sm:w-auto sm:justify-end",children:r}):null]})}function hi({title:e,description:t,children:n,className:r}){return i.jsxs("section",{"data-slot":"settings-section",className:K("flex flex-col gap-3",r),children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("h2",{className:"text-[15px] font-semibold text-foreground",children:e}),t?i.jsx("p",{className:"max-w-3xl text-[13px] leading-5 text-muted-foreground",children:t}):null]}),n]})}function v2({label:e,description:t,htmlFor:n,icon:r,children:s,className:a}){const o=i.jsxs(i.Fragment,{children:[r?i.jsx(r,{className:"size-4 shrink-0 text-muted-foreground"}):null,e]});return i.jsxs("div",{"data-slot":"settings-item",className:K("flex flex-col gap-3 px-4 py-4",a),children:[i.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[n?i.jsx("label",{htmlFor:n,className:"flex items-center gap-2 text-[14px] font-medium leading-5 text-foreground",children:o}):i.jsx("div",{className:"flex items-center gap-2 text-[14px] font-medium leading-5 text-foreground",children:o}),t?i.jsx("div",{className:"max-w-[42rem] text-[13px] leading-5 text-muted-foreground",children:t}):null]}),s]})}function hq({children:e,className:t}){return i.jsx("div",{"data-slot":"settings-actions",className:K("flex flex-wrap items-center justify-end gap-2 px-4 py-3",t),children:e})}function NP({children:e,className:t}){return i.jsx("div",{"data-slot":"settings-choice-grid",className:K("flex flex-wrap gap-2.5",t),children:e})}function U2({checked:e,className:t,...n}){return i.jsx(GA,{checked:e,size:"md",tone:"accent",className:K(t),...n})}function U1({label:e,description:t,selected:n=!1,preview:r,className:s,...a}){return i.jsxs("button",{type:"button","data-slot":"settings-choice-card","aria-pressed":n,className:K("group flex min-w-[var(--settings-choice-min-width)] flex-col gap-[var(--settings-choice-gap)] rounded-lg border px-[var(--settings-choice-padding-x)] py-[var(--settings-choice-padding-y)] text-left text-[length:var(--settings-choice-label-size)] outline-none transition-[border-color,background-color,box-shadow,transform] hover:bg-[color:var(--surface-elevated)] active:translate-y-px focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/45",n?"border-[color:color-mix(in_oklab,var(--accent-base)_74%,var(--border-strong))] bg-[color:var(--surface-elevated)] shadow-[0_0_0_1px_color-mix(in_oklab,var(--accent-base)_28%,transparent)]":"border-[color:var(--border-soft)] bg-[color:color-mix(in_oklab,var(--surface-inset)_84%,var(--surface-elevated))]",s),...a,children:[i.jsx("div",{className:"overflow-hidden rounded-[var(--settings-choice-preview-radius)]",children:r}),i.jsxs("div",{className:"flex flex-col gap-0.5",children:[i.jsx("div",{className:"font-medium text-foreground",children:e}),t?i.jsx("div",{className:"text-[length:var(--settings-choice-description-size)] leading-4 text-muted-foreground",children:t}):null]})]})}function n1({dense:e=!1,className:t}){return i.jsxs(oh,{"data-testid":"settings-page-skeleton",className:K("gap-7",t),"aria-hidden":"true",children:[i.jsxs("div",{className:"flex flex-col gap-3",children:[i.jsx(un,{className:"h-4 w-28"}),i.jsx(un,{className:"h-9 w-52"}),i.jsx(un,{className:"h-4 w-full max-w-xl"})]}),i.jsxs("div",{className:K("flex flex-col",e?"gap-3":"gap-4"),children:[i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(un,{className:"h-4 w-36"}),i.jsx(un,{className:"h-3 w-full max-w-lg"})]}),i.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] p-4",children:[i.jsx(un,{className:"h-10 w-full"}),i.jsx(un,{className:"h-10 w-full"}),e?null:i.jsx(un,{className:"h-24 w-full"})]})]}),i.jsxs("div",{className:"flex flex-col gap-4",children:[i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(un,{className:"h-4 w-32"}),i.jsx(un,{className:"h-3 w-full max-w-md"})]}),i.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(un,{className:"h-4 w-44"}),i.jsx(un,{className:"h-3 w-64 max-w-full"})]}),i.jsx(un,{className:"h-7 w-12 rounded-full"})]}),e?null:i.jsx(un,{className:"h-10 w-40"})]})]})]})}function wIe({children:e}){var s;const t=br(),n=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1});if(n.isLoading)return i.jsx(n1,{dense:!0});const r=Ohe(Rie,!0,((s=n.data)==null?void 0:s.deploymentMode)??"authenticated");if(r!==Rie){const a=Hj(t.state);return i.jsx(Ai,{to:r,replace:!0,state:a})}return e}const JUn={seedGettingStarted:(e,t={})=>Re.post(`/orgs/${e}/onboarding/getting-started`,t)},G_={list:e=>Re.get(`/orgs/${e}/secrets`),providers:e=>Re.get(`/orgs/${e}/secret-providers`),create:(e,t)=>Re.post(`/orgs/${e}/secrets`,t),rotate:(e,t)=>Re.post(`/secrets/${e}/rotate`,t),update:(e,t)=>Re.patch(`/secrets/${e}`,t),remove:e=>Re.delete(`/secrets/${e}`)};function hAt(e){var n,r;const t=e.split("/").filter(Boolean);return t.length===1?((n=t[0])==null?void 0:n.toLowerCase())==="onboarding":t.length===2?((r=t[1])==null?void 0:r.toLowerCase())==="onboarding":!1}function eVn(e){const{pathname:t,orgPrefix:n,organizations:r}=e;if(!hAt(t))return null;const s=t.split("/").filter(Boolean)[0],a=n??((s==null?void 0:s.toLowerCase())==="onboarding"?void 0:s);if(!a)return{initialStep:1};const o=aw({organizations:r,organizationPrefix:a});return o?{initialStep:2,orgId:o.id}:{initialStep:1}}function mAt(e){return!e.hasOrganizations&&!hAt(e.pathname)}function pAt({label:e,hint:t,models:n,value:r,onChange:s,open:a,onOpenChange:o,allowDefault:l,allowClear:c=!1,allowCustom:d=!1,required:u,groupByProvider:f,preserveModelOrder:A=!1,emptyLabel:m,searchPlaceholder:g="Search models...",emptyMessage:x="No models found.",triggerTestId:y,disabled:v=!1}){const[w,k]=h.useState(""),S=n.find(M=>M.id===r),j=w.trim(),C=h.useMemo(()=>n.filter(M=>{if(!w.trim())return!0;const E=w.toLowerCase(),T=dde(M.id)??"";return M.id.toLowerCase().includes(E)||M.label.toLowerCase().includes(E)||T.toLowerCase().includes(E)}),[n,w]),N=d&&j.length>0&&!n.some(M=>M.id===j),P=h.useMemo(()=>{if(!f)return[{provider:"models",entries:A?C:[...C].sort((E,T)=>E.id.localeCompare(T.id))}];const M=new Map;for(const E of C){const T=dde(E.id)??"other",R=M.get(T)??[];R.push(E),M.set(T,R)}return Array.from(M.entries()).sort(([E],[T])=>E.localeCompare(T)).map(([E,T])=>({provider:E,entries:[...T].sort((R,_)=>R.id.localeCompare(_.id))}))},[C,f,A]);return i.jsx(mi,{label:e,hint:t,children:i.jsxs(ts,{open:v?!1:a,onOpenChange:M=>{v||(o(M),M||k(""))},children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between min-w-0","data-testid":y,disabled:v,children:[i.jsx("span",{className:K("truncate text-left",!r&&"text-muted-foreground"),children:S?S.label:r||m||(u?"Select model (required)":"Select model")}),i.jsx(qr,{className:"h-3 w-3 text-muted-foreground"})]})}),i.jsxs(ns,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:g,value:w,onChange:M=>k(M.target.value),autoFocus:!0}),i.jsxs("div",{className:"max-h-[240px] overflow-y-auto",children:[l&&i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!r&&"bg-accent"),onClick:()=>{s(""),o(!1)},children:"Default"}),c&&i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!r&&"bg-accent"),onClick:()=>{s(""),o(!1)},children:"No fallback model"}),N&&i.jsx("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:()=>{s(j),o(!1)},children:i.jsxs("span",{className:"block w-full text-left truncate",title:j,children:['Use "',j,'"']})}),P.map(M=>i.jsxs("div",{className:"mb-1 last:mb-0",children:[f&&i.jsxs("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:[M.provider," (",M.entries.length,")"]}),M.entries.map(E=>i.jsx("button",{className:K("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",E.id===r&&"bg-accent"),onClick:()=>{s(E.id),o(!1)},children:i.jsx("span",{className:"block w-full text-left truncate",title:E.id,children:f?OFn(E.id):E.label})},E.id))]},M.provider)),C.length===0&&!N&&i.jsx("p",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:x})]})]})]})})}function gAt({value:e,options:t,label:n="Thinking effort",hint:r=Ma.thinkingEffort,onChange:s,open:a,onOpenChange:o,disabled:l=!1}){const c=t.find(d=>d.id===e)??t[0];return i.jsx(mi,{label:n,hint:r,children:i.jsxs(ts,{open:l?!1:a,onOpenChange:d=>{l||o(d)},children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",disabled:l,children:[i.jsx("span",{className:K(!e&&"text-muted-foreground"),children:(c==null?void 0:c.label)??"Auto"}),i.jsx(qr,{className:"h-3 w-3 text-muted-foreground"})]})}),i.jsx(ns,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:t.map(d=>i.jsxs("button",{className:K("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",d.id===e&&"bg-accent"),onClick:()=>{s(d.id),o(!1)},children:[i.jsx("span",{children:d.label}),d.id?i.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:d.id}):null]},d.id||"auto"))})]})})}const kIe=[" ",".","·","▪","▫","○"],tVn=24,nVn=1e3/tVn,h$=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function OIe(e){const t=document.createElement("span");t.textContent="M",t.style.cssText="position:absolute;visibility:hidden;white-space:pre;font-size:11px;font-family:monospace;line-height:1;",e.appendChild(t);const n=t.getBoundingClientRect();return e.removeChild(t),{w:n.width,h:n.height}}function rVn(e){let t=0;for(const n of e)t=Math.max(t,n.length);return{width:t,height:e.length}}function xAt(){const e=h.useRef(null),t=h.useRef(null);return h.useEffect(()=>{if(!e.current)return;const n=e.current,r=window.matchMedia("(prefers-reduced-motion: reduce)");let s=document.visibilityState!=="hidden",a=!1,o=0,l=0,c=0,d=0,u=7,f=11,A=new Float32Array(0),m=new Float32Array(0),g=new Float32Array(0),x=new Uint16Array(0),y=[],v="";function w(_){const D=Math.max(0,Math.min(.999,_)),U=Math.floor(D*kIe.length);return kIe[U]??" "}function k(){const _=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,u))),D=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,f)));if(_===c&&D===d)return;c=_,d=D;const U=c*d;A=new Float32Array(U),m=new Float32Array(c),g=new Float32Array(d),x=new Uint16Array(U),y=y.filter($=>$.x>-$.width-2&&$.x<c+2&&$.y>-$.height-2&&$.y<d+2),v=""}function S(){if(c<=0||d<=0){n.textContent="";return}const _=Array.from({length:d},()=>Array.from({length:c},()=>" "));for(let L=0;L<d;L++)for(let H=0;H<c;H++){const X=(Math.sin(H*.11+L*.04)+Math.cos(L*.08-H*.02))*.18+.22;_[L][H]=w(X)}const D=18,U=13;for(let L=1;L<d-9;L+=U){const H=Math.floor(L/U)%2===0?2:10;for(let X=H;X<c-10;X+=D){const F=h$[(X+L)%h$.length];for(let Q=0;Q<F.length;Q++){const q=F[Q];for(let B=0;B<q.length;B++){const ee=q[B]??" ";if(ee===" ")continue;const se=L+Q,re=X+B;se<0||se>=d||re<0||re>=c||(_[se][re]=ee)}}}}const $=_.map(L=>L.join("")).join(`
1980
+ skills install example`,className:"field-sizing-fixed min-h-28 min-w-0 resize-y overflow-x-auto whitespace-pre-wrap break-all font-mono text-xs",disabled:u.isPending||f.isPending,autoFocus:!0})]})}),i.jsxs(ga,{className:"flex-col gap-3 border-t border-border/60 pt-4 sm:flex-row sm:items-center sm:justify-between",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:flex-1",children:[i.jsx(le,{type:"button",onClick:()=>u.mutate({sources:c}),disabled:!t||c.length===0||u.isPending||f.isPending,children:u.isPending?"Importing...":"Import skill"}),i.jsx(le,{type:"button",variant:"outline",onClick:()=>f.mutate(),disabled:!t||u.isPending||f.isPending,children:f.isPending?"Scanning...":"Scan local skills"}),i.jsx(le,{type:"button",variant:"outline","data-testid":"org-workspaces-skill-agent-install-button",onClick:()=>{n(!1),r(`/messenger/chat?prefill=${encodeURIComponent(d$n)}`)},children:"Ask Agent to install"})]}),i.jsx(le,{type:"button",variant:"ghost",className:"w-full sm:w-auto",onClick:()=>n(!1),disabled:u.isPending||f.isPending,children:"Close"})]})]})})}const zut="[data-workspace-entry-path]";function u$n(e){return JSON.stringify({path:e.path,isDirectory:e.isDirectory})}function f$n(e){var r;if(typeof e.dataTransfer.setDragImage!="function")return;const t=e.currentTarget.cloneNode(!0);if(!(t instanceof HTMLElement))return;(r=t.querySelector("[data-testid^='org-workspaces-entry-more-']"))==null||r.remove(),t.classList.remove("hover:bg-accent/60","hover:bg-accent/50","hover:text-foreground"),t.classList.add("rudder-workspace-tree-drag-image"),t.removeAttribute("data-workspace-entry-path"),t.removeAttribute("draggable");const n=e.currentTarget.getBoundingClientRect();t.style.position="fixed",t.style.top="-1000px",t.style.left="-1000px",t.style.width=`${Math.min(Math.max(n.width||220,190),300)}px`,t.style.paddingLeft="10px",t.style.opacity="1",t.style.pointerEvents="none",t.style.zIndex="-1",document.body.appendChild(t),e.dataTransfer.setDragImage(t,Math.min(e.clientX-n.left,26),Math.min(e.clientY-n.top,16)),window.setTimeout(()=>t.remove(),0)}function l2e(e){const t=e.dataTransfer.getData(G0e);if(!t)return null;try{const n=JSON.parse(t);return typeof n.path!="string"||typeof n.isDirectory!="boolean"?null:{path:n.path,isDirectory:n.isDirectory}}catch{return null}}function nq(e){const t=e.relatedTarget;return!(t instanceof Node)||!e.currentTarget.contains(t)}function c2e(e){var r;if(typeof document>"u")return;const t=Array.from(document.querySelectorAll(zut)).find(s=>s.dataset.workspaceEntryPath===e);if(!t)return;(r=t.scrollIntoView)==null||r.call(t,{block:"center"});const n=t.querySelector("button");n==null||n.focus({preventScroll:!0})}function A$n(){return typeof document>"u"?[]:Array.from(document.querySelectorAll(zut))}function yne(e,t,n){const r=A$n(),s=r.findIndex(l=>l.dataset.workspaceEntryPath===e);if(s<0)return;const a=r[s+t],o=a==null?void 0:a.dataset.workspaceEntryPath;o&&(n(o),c2e(o))}function h$n(e,t){const n=B_(e);n&&(t(n),c2e(n))}function m$n(e){switch(e){case"directory":return wo;case"file":return Fi;case"connector_object":return wc;case"url":default:return qm}}function p$n({group:e,selectedResourcePath:t,activeEntryPath:n,onSelectResource:r,onFocusEntry:s,onAddResources:a,onCopyResourceLocator:o,onOpenResource:l,onUnlinkResource:c,unlinkingResourceId:d,depth:u}){const f=NH(e.project),[A,m]=h.useState((t==null?void 0:t.startsWith(`${f}/`))??!1),g=n===f,[x,y]=h.useState(!1);return h.useEffect(()=>{t!=null&&t.startsWith(`${f}/`)&&m(!0)},[f,t]),i.jsx("ul",{className:"space-y-0.5",children:i.jsxs("li",{children:[i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm text-foreground transition-colors hover:bg-accent/60",g&&"bg-accent text-foreground"),style:{paddingLeft:`${u*14+8}px`},"data-workspace-entry-path":f,"data-testid":`org-workspaces-project-resources-folder-${e.project.id}`,onContextMenu:v=>{v.preventDefault(),v.stopPropagation(),s(f),y(!0)},children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{s(f),m(v=>!v)},onFocus:()=>s(f),"aria-expanded":A,"aria-selected":g,children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground",children:A?i.jsx(qr,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})}),i.jsx(wo,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:"resources"}),i.jsx("span",{className:"shrink-0 rounded-full border border-border bg-background px-1.5 py-0.5 text-[10px] text-muted-foreground",children:e.resources.length})]}),i.jsxs(Ei,{open:x,onOpenChange:y,children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":`More actions for ${e.project.name} resources`,"data-testid":`org-workspaces-project-resources-more-${e.project.id}`,onClick:v=>{v.stopPropagation(),s(f)},children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsx(Ri,{align:"end",sideOffset:6,className:"w-44",onClick:v=>v.stopPropagation(),children:i.jsxs(Xt,{onSelect:()=>a(e.project),children:[i.jsx(qm,{className:"h-3.5 w-3.5"}),"Add resources"]})})]})]}),A?i.jsx("ul",{className:"space-y-0.5",children:e.resources.map(v=>{const w=_ut(e.project,v),k=t===w,S=n===w,j=m$n(v.resource.kind),C=d===v.id;return i.jsx("li",{children:i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm transition-colors",k||S?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"),style:{paddingLeft:`${(u+1)*14+23}px`},"data-workspace-entry-path":w,"data-testid":`org-workspaces-project-resource-${v.id}`,children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{s(w),r(v.id)},onFocus:()=>s(w),"aria-selected":S||k,children:[i.jsx(j,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:v.resource.name})]}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":`More actions for ${v.resource.name}`,"data-testid":`org-workspaces-project-resource-more-${v.id}`,onClick:N=>{N.stopPropagation(),s(w)},children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",sideOffset:6,className:"w-48",onClick:N=>N.stopPropagation(),children:[i.jsxs(Xt,{onSelect:()=>l(v),children:[i.jsx(Ja,{className:"h-3.5 w-3.5"}),"Open resource"]}),i.jsxs(Xt,{onSelect:()=>o(v),children:[i.jsx(Al,{className:"h-3.5 w-3.5"}),"Copy locator"]}),i.jsx(Yo,{}),i.jsxs(Xt,{variant:"destructive",disabled:C,onSelect:()=>c(e.project,v),children:[C?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(YPt,{className:"h-3.5 w-3.5"}),"Unlink resource"]})]})]})]})},v.id)})}):null]})})}function g$n({orgId:e,directoryPath:t,organizationSkills:n,selectedFilePath:r,selectedSkillTreePath:s,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H}){const{data:X}=Me({queryKey:V.organizations.workspaceFiles(e,t),queryFn:()=>_n.listWorkspaceFiles(e,t),enabled:!!e,refetchOnWindowFocus:!1}),F=h.useMemo(()=>Y0e(t,(X==null?void 0:X.entries)??[],n),[X==null?void 0:X.entries,t,n]);return F.length===0?null:i.jsx("ul",{className:"space-y-0.5",children:F.map(Q=>i.jsx(d2e,{orgId:e,entry:Q,organizationSkills:n,selectedFilePath:r,selectedSkillTreePath:s,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H},Q.path))})}function d2e({orgId:e,entry:t,organizationSkills:n=[],selectedFilePath:r,selectedSkillTreePath:s=null,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H=0}){const[X,F]=h.useState(D.has(t.path)),[Q,q]=h.useState(!1),[B,ee]=h.useState(!1),se=C2(t),re=!!t.virtualSkillId,ne=t.entityType==="agent_workspace",Ae=t.path==="agents",Y=n$n(t.path),ce=t$n(t.path),Oe=Mut(t.path),Fe=cj(t.path),ke=L.get(t.path)??null,Ne=!re&&t.isDirectory&&dj(t.path),xe=!re&&n2e(t),ae=!re&&t2e(t),fe=!re&&r2e(t),ve=!re&&s2e(t),Se=!re&&t.isDirectory&&dj(t.path),ze=t.isDirectory?U:F_(U),ft=o===t.path||s===t.path||!o&&r===t.path,ie=l===t.path,me=Be=>{Be.preventDefault(),Be.stopPropagation(),f(t.path),q(!0)},we=Be=>{if(!ae){Be.preventDefault();return}Be.dataTransfer.effectAllowed="move",Be.dataTransfer.setData(G0e,u$n(t)),Be.dataTransfer.setData("text/plain",t.path),A(t.path),f$n(Be)},Xe=Be=>{if(!Se)return;const it=x3(Be.dataTransfer);!i2e(Be.dataTransfer)&&!it||(Be.preventDefault(),Be.dataTransfer.dropEffect=it?"copy":"move",ee(!0))},ge=Be=>{nq(Be)&&ee(!1)},te=Be=>{if(!Se)return;if(Be.preventDefault(),Be.stopPropagation(),ee(!1),x3(Be.dataTransfer)){const{supported:lt,unsupportedCount:Ue}=a2e(Be.dataTransfer);N(lt,t.path,Ue),F(!0);return}const it=l2e(Be);it&&Q_(it,t.path)&&(C(it,t.path),F(!0))},G=Be=>{if(!(Be.metaKey||Be.ctrlKey||Be.altKey)){if(Be.key==="ArrowDown"){Be.preventDefault(),yne(t.path,1,f);return}if(Be.key==="ArrowUp"){Be.preventDefault(),yne(t.path,-1,f);return}if(Be.key==="ArrowRight"&&t.isDirectory){Be.preventDefault(),f(t.path),X?window.requestAnimationFrame(()=>yne(t.path,1,f)):F(!0);return}if(Be.key==="ArrowLeft"){Be.preventDefault(),f(t.path),t.isDirectory&&X?F(!1):h$n(t.path,f);return}Be.key==="Enter"&&(Be.preventDefault(),f(t.path),t.isDirectory?F(it=>!it):t.virtualSkillId&&t.virtualSkillFilePath?d==null||d(t.virtualSkillId,t.virtualSkillFilePath,t.path):c(t.path))}},oe=i.jsxs(Ei,{open:Q,onOpenChange:q,children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":`More actions for ${se}`,"data-testid":`org-workspaces-entry-more-${t.path}`,onClick:Be=>Be.stopPropagation(),children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",sideOffset:6,className:"w-60 whitespace-nowrap will-change-[opacity,transform] data-[state=open]:duration-150 data-[state=open]:ease-out data-[state=closed]:duration-100 data-[state=closed]:ease-in",onClick:Be=>Be.stopPropagation(),onContextMenu:Be=>{Be.preventDefault(),Be.stopPropagation()},children:[i.jsxs(Xt,{onSelect:()=>g(t),children:[i.jsx(qm,{className:"h-3.5 w-3.5"}),"Copy link"]}),i.jsxs(Xt,{onSelect:()=>x(t),children:[i.jsx(Al,{className:"h-3.5 w-3.5"}),"Copy absolute path"]}),Fe?null:i.jsxs(i.Fragment,{children:[y||v||Ne?i.jsx(Yo,{}):null,y||v?ze.length>0&&v?i.jsxs(r6,{children:[i.jsxs(s6,{className:"h-9 rounded-[6px] px-2 text-sm","data-testid":`org-workspaces-entry-open-submenu-${t.path}`,children:[i.jsx(Ja,{className:"h-3.5 w-3.5"}),t.isDirectory?"Open folder":"Open In"]}),i.jsx(i6,{sideOffset:6,className:"w-60 whitespace-nowrap p-1",children:ze.map(Be=>i.jsxs(Xt,{className:"h-9 gap-2 rounded-[6px]",disabled:$!==null,"data-testid":`org-workspaces-entry-open-target-${t.path}-${Be.id}`,onSelect:()=>v(t,Be),children:[$===Be.id?i.jsx(hn,{className:"h-4 w-4 animate-spin"}):i.jsx(mb,{target:Be}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:Be.label}),i.jsx("span",{className:"text-[11px] capitalize text-muted-foreground",children:Be.kind})]},Be.id))})]}):y?i.jsxs(Xt,{onSelect:()=>y(t),children:[i.jsx(Ja,{className:"h-3.5 w-3.5"}),t.isDirectory?"Open folder":"Open In"]}):null:null,Ne?i.jsxs(i.Fragment,{children:[y||v?i.jsx(Yo,{}):null,i.jsxs(Xt,{onSelect:()=>w(t,"file"),children:[i.jsx(F7,{className:"h-3.5 w-3.5"}),"New file"]}),i.jsxs(Xt,{onSelect:()=>w(t,"folder"),children:[i.jsx(j3,{className:"h-3.5 w-3.5"}),"New folder"]})]}):null,xe||fe||ve?i.jsx(Yo,{}):null,xe?i.jsxs(Xt,{onSelect:()=>k(t),children:[i.jsx(cCt,{className:"h-3.5 w-3.5"}),"Create copy"]}):null,fe?i.jsxs(Xt,{onSelect:()=>S(t),children:[i.jsx(JA,{className:"h-3.5 w-3.5"}),"Rename"]}):null,ve?i.jsxs(Xt,{variant:"destructive",onSelect:()=>j(t),children:[i.jsx(yi,{className:"h-3.5 w-3.5"}),"Delete"]}):null]}),Fe&&ve?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{variant:"destructive",onSelect:()=>j(t),children:[i.jsx(yi,{className:"h-3.5 w-3.5"}),"Delete"]})]}):null]})]});if(h.useEffect(()=>{D.has(t.path)&&F(!0)},[t.path,D]),t.isDirectory)return i.jsxs("li",{children:[i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm text-foreground transition-[background-color,color,opacity,transform] duration-150",ie?"rudder-workspace-tree-entry--dragging text-muted-foreground":"hover:bg-accent/60",ft&&!ie&&"bg-accent text-foreground",B&&!ie&&"bg-[#2f80ed]/10 ring-1 ring-[#2f80ed]/30"),style:{paddingLeft:`${H*14+8}px`},"data-workspace-entry-path":t.path,"data-dragging-workspace-entry":ie?"true":void 0,draggable:ae,onDragStart:we,onDragEnd:()=>{ee(!1),m()},onDragOver:Xe,onDragLeave:ge,onDrop:te,onContextMenu:me,children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{f(t.path),F(Be=>!Be)},onFocus:()=>f(t.path),onKeyDown:G,"aria-expanded":X,"aria-selected":ft,children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground",children:X?i.jsx(qr,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})}),ne?i.jsx("span",{"data-testid":"org-workspaces-agent-icon",className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-muted-foreground",children:i.jsx(Il,{icon:t.agentIcon,role:t.agentRole,className:"h-3.5 w-3.5 text-[12px]"})}):Ae?i.jsx(C3,{"data-testid":"org-workspaces-agents-root-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):Y?i.jsx(wc,{"data-testid":"org-workspaces-skills-root-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):ce?i.jsx(dBe,{"data-testid":"org-workspaces-skill-folder-icon",className:"h-3.5 w-3.5 shrink-0 text-[#2f80ed]"}):Oe?ke?i.jsx(uo,{color:ke.project.color,icon:ke.project.icon,size:"xs",testId:"org-workspaces-project-icon"}):i.jsx(TBe,{"data-testid":"org-workspaces-project-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx(wo,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx("div",{className:"truncate font-medium",children:se})}),ne?i.jsx("span",{"aria-hidden":"true","data-testid":"org-workspaces-agent-badge",className:"inline-flex shrink-0 items-center gap-1 rounded-full border border-border bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Agent"}):null]}),t.path==="skills"?i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100 focus-visible:opacity-100","aria-label":"Add skill to Library","data-testid":"org-workspaces-skills-add-button",onClick:Be=>{Be.preventDefault(),Be.stopPropagation(),R==null||R()},children:i.jsx(Zr,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"Add skill"})]}):null,re?null:oe]}),X?i.jsxs(i.Fragment,{children:[i.jsx(g$n,{orgId:e,directoryPath:t.path,organizationSkills:n,selectedFilePath:r,selectedSkillTreePath:s,selectedResourcePath:a,activeEntryPath:o,draggedEntryPath:l,onSelectFile:c,onSelectSkillFile:d,onSelectResource:u,onFocusEntry:f,onDragStartEntry:A,onDragEndEntry:m,onCopyLink:g,onCopyAbsolutePath:x,onOpenEntry:y,onOpenEntryTarget:v,onStartCreateEntry:w,onCopyEntry:k,onStartRename:S,onStartDelete:j,onMoveEntry:C,onImportFiles:N,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,onOpenSkillAddDialog:R,unlinkingResourceId:_,expandedDirectories:D,workspaceLaunchTargets:U,openingWorkspaceTargetId:$,projectResourceGroupsByLibraryPath:L,depth:H+1}),ke?i.jsx(p$n,{group:ke,selectedResourcePath:a,activeEntryPath:o,onSelectResource:u,onFocusEntry:f,onAddResources:P,onCopyResourceLocator:M,onOpenResource:E,onUnlinkResource:T,unlinkingResourceId:_,depth:H+1}):null]}):null]});const Ze=r===t.path||s===t.path,Te=Qzn(t.path)?kBe:Wzn(t.path)?Kfe:Zzn(t.path)?qfe:Kzn(t.path)?Fi:K6;return i.jsx("li",{children:i.jsxs("div",{className:K("group flex w-full items-center rounded-md pr-1 text-sm transition-[background-color,color,opacity,transform] duration-150",ie?"rudder-workspace-tree-entry--dragging text-muted-foreground":Ze||ft?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"),style:{paddingLeft:`${H*14+23}px`},"data-workspace-entry-path":t.path,"data-dragging-workspace-entry":ie?"true":void 0,draggable:ae,onDragStart:we,onDragEnd:()=>{ee(!1),m()},onContextMenu:me,children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-0 pr-2 text-left",onClick:()=>{f(t.path),t.virtualSkillId&&t.virtualSkillFilePath?d==null||d(t.virtualSkillId,t.virtualSkillFilePath,t.path):c(t.path)},onFocus:()=>f(t.path),onKeyDown:G,"aria-selected":ft||Ze,children:[i.jsx(Te,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:se})]}),re?null:oe]})})}const nde="rudder:workspace-flush-draft";function rde(){typeof window>"u"||window.dispatchEvent(new Event(nde))}function $ut(e){const t=Me({queryKey:e?V.projects.list(e):V.projects.list("__none__"),queryFn:()=>Mi.list(e),enabled:!!e,refetchOnWindowFocus:!1}),n=h.useMemo(()=>i$n(t.data),[t.data]);return{projects:t.data??[],groupsByLibraryPath:n,isLoading:t.isLoading}}async function Fut(e,t,n){const r=[],s=[];for(const a of n){const o=o2e(t,a.name);try{r.push(await _n.createWorkspaceFile(e,{filePath:o,content:await a.text()}))}catch(l){s.push({fileName:a.name,filePath:o,message:l instanceof Error?l.message:"Failed to import file"})}}return{imported:r,failed:s}}async function zI(e){var n;const t=Pn();if(t!=null&&t.copyText)await t.copyText(e);else if((n=navigator.clipboard)!=null&&n.writeText)await navigator.clipboard.writeText(e);else throw new Error("Clipboard is not available in this environment.")}function xo(e,t,n){const r=new URLSearchParams(e);n?r.set("path",n):r.delete("path"),r.delete("entry"),r.delete("doc"),r.delete("skill"),r.delete("skillFile"),n&&r.delete("directory"),r.delete("resource"),t(r,{replace:!0})}function But(e,t,n){const r=new URLSearchParams(e);r.set("resource",n),r.delete("doc"),r.delete("path"),r.delete("skill"),r.delete("skillFile"),r.delete("directory"),t(r,{replace:!0})}function Qut(e,t,n,r){const s=new URLSearchParams(e);s.set("skill",n),s.set("skillFile",r),s.delete("path"),s.delete("entry"),s.delete("doc"),s.delete("directory"),s.delete("resource"),t(s,{replace:!0})}function SPe(e,t,n){const r=new URLSearchParams(e);n?r.set("directory",n):r.delete("directory"),r.delete("path"),r.delete("entry"),r.delete("doc"),r.delete("skill"),r.delete("skillFile"),r.delete("resource"),t(r,{replace:!0})}function IH(e){return/^https?:\/\//i.test(e.trim())}function u2e(e,t){const n=e.resource.locator.trim();return!n||IH(n)?null:e.resource.sourceType==="library"?Xv(t,n):e.resource.kind==="file"||e.resource.kind==="directory"?n:null}function x$n({onCollapseSidebar:e}={}){var Je,_e,Ee,Ce,kt;const t=Vn(),n=Yr(),{pushToast:r}=ss(),{locale:s}=is(),{viewedOrganizationId:a}=th(),[o,l]=gd(),c=vl(o.get("entry")),d=c?null:vl(o.get("skill")),u=d?vl(o.get("skillFile"))??"SKILL.md":null,f=c||d?null:vl(o.get("path")),A=c||d?null:vl(o.get("resource")),m=c||d?null:vl(o.get("directory")),g=bs("org-workspaces:files-sidebar"),[x,y]=h.useState(null),[v,w]=h.useState(""),[k,S]=h.useState(null),[j,C]=h.useState(""),[N,P]=h.useState(null),[M,E]=h.useState(!1),[T,R]=h.useState(!1),[_,D]=h.useState(null),[U,$]=h.useState(f??m),L=Me({queryKey:V.organizations.workspaceFiles(a??"__none__",""),queryFn:()=>_n.listWorkspaceFiles(a,""),enabled:!!a,refetchOnWindowFocus:!1}),H=Me({queryKey:V.organizations.libraryEntry(a??"__none__",c??""),queryFn:()=>_n.getLibraryEntry(a,c),enabled:!!a&&!!c,refetchOnWindowFocus:!1}),F=Me({queryKey:V.organizationSkills.list(a??"__none__"),queryFn:()=>nf.list(a),enabled:!!a,refetchOnWindowFocus:!1}).data??[],Q=h.useMemo(()=>{var Qe;return Y0e("",((Qe=L.data)==null?void 0:Qe.entries)??[],F)},[F,(Je=L.data)==null?void 0:Je.entries]),q=F.find(Qe=>Qe.id===d)??null,B=q&&!R6(q)?q:null,ee=B&&u?ede(B,u):null,se=$ut(a),re=h.useMemo(()=>tde(se.projects,A),[se.projects,A]),ne=(re==null?void 0:re.path)??null,Ae=Kce(a),Y=!!(f||Ae.openFilePaths.length>0),ce=!!(f||ee||m),Oe=(_e=L.data)!=null&&_e.rootExists?L.data.rootPath:null,Fe=h.useMemo(()=>({name:"",path:"",isDirectory:!0,displayLabel:_i("library",s)}),[s]),[ke,Ne]=h.useState([]),[xe,ae]=h.useState(null),fe=h.useMemo(()=>f?kO(f):ee?kO(ee):ne?kO(ne):m?Vdt(m):new Set,[m,f,ne,ee]);h.useEffect(()=>{var Qe;if(d&&q&&R6(q)){const gt=vl(q.workspaceEditPath);gt&&xo(o,l,gt);return}if(c){((Qe=H.data)==null?void 0:Qe.status)==="active"&&H.data.currentPath?xo(o,l,H.data.currentPath):$(null);return}f?$(f):ee?$(ee):ne?$(ne):m&&$(m)},[(Ee=H.data)==null?void 0:Ee.currentPath,m,c,d,o,f,q,ne,ee,l]),h.useEffect(()=>{const Qe=()=>{R(!1),D(null)};return window.addEventListener("dragend",Qe),window.addEventListener("drop",Qe,!0),()=>{window.removeEventListener("dragend",Qe),window.removeEventListener("drop",Qe,!0)}},[]),h.useEffect(()=>{const Qe=Pn();let gt=!1;return typeof(Qe==null?void 0:Qe.listWorkspaceLaunchTargets)=="function"?Qe.listWorkspaceLaunchTargets().then(Nt=>{gt||Ne(Nt)}).catch(()=>{gt||Ne([])}):Ne([]),()=>{gt=!0}},[]);const ve=h.useCallback(async()=>{a&&await Promise.all([t.invalidateQueries({queryKey:["organizations",a,"workspace-files"]}),t.invalidateQueries({queryKey:["organizations",a,"workspace-file"]})])},[t,a]),Se=xt({mutationFn:Qe=>Mi.removeResourceAttachment(Qe.project.id,Qe.attachment.id,Qe.project.orgId),onSuccess:(Qe,gt)=>{t.invalidateQueries({queryKey:V.projects.list(gt.project.orgId)}),t.invalidateQueries({queryKey:V.projects.resources(gt.project.id)}),A===gt.attachment.id&&(xo(o,l,null),$(NH(gt.project))),r({title:"Resource unlinked",body:Qe.resource.name,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to unlink resource",tone:"error"})}}),ze=xt({mutationFn:async Qe=>{rde();const gt=o2e(Qe.parent.path,Qe.name.trim());return Qe.kind==="folder"?{kind:Qe.kind,result:await _n.createWorkspaceDirectory(a,{directoryPath:gt})}:{kind:Qe.kind,result:await _n.createWorkspaceFile(a,{filePath:gt,content:""})}},onSuccess:({kind:Qe,result:gt})=>{if(!a)return;ve(),y(null),w(""),Qe==="file"&&"filePath"in gt&&(t.setQueryData(V.organizations.workspaceFile(a,gt.filePath),gt),$(gt.filePath),xo(o,l,gt.filePath));const Nt="filePath"in gt?gt.filePath:gt.path;r({title:Qe==="file"?"File created":"Folder created",body:Nt,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to create workspace entry",tone:"error"})}}),ft=xt({mutationFn:async Qe=>(rde(),{...await Fut(a,Qe.destinationDirectoryPath,Qe.files),unsupportedCount:Qe.unsupportedCount??0}),onSuccess:({imported:Qe,failed:gt,unsupportedCount:Nt})=>{if(!a)return;if(Qe.length>0){ve();for(const Rn of Qe)t.setQueryData(V.organizations.workspaceFile(a,Rn.filePath),Rn)}const Gt=Qe.at(-1);Gt&&($(Gt.filePath),xo(o,l,Gt.filePath));const cn=[...gt.map(Rn=>`${Rn.fileName}: ${Rn.message}`),...Nt>0?[`${Nt} unsupported file${Nt===1?"":"s"}`]:[]].join(", ");if(Qe.length===0){r({title:"No files imported",body:cn||"Only text, Markdown, and code files can be imported.",tone:gt.length>0?"error":"warn"});return}r({title:gt.length>0||Nt>0?`Imported ${Qe.length} of ${Qe.length+gt.length+Nt} files`:Qe.length===1?"File imported":`${Qe.length} files imported`,body:cn?`${Qe.map(Rn=>Rn.filePath).join(", ")}. Failed: ${cn}`:Qe.map(Rn=>Rn.filePath).join(", "),tone:gt.length>0||Nt>0?"warn":"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to import files",tone:"error"})}}),ie=xt({mutationFn:Qe=>_n.renameWorkspaceEntry(a,Qe.entry.path,{name:Qe.name}),onSuccess:Qe=>{if(ve(),S(null),C(""),Qe.previousPath&&f){const gt=f===Qe.previousPath?Qe.path:f.startsWith(`${Qe.previousPath}/`)?`${Qe.path}${f.slice(Qe.previousPath.length)}`:f;gt!==f&&xo(o,l,gt)}Qe.previousPath&&U&&$(F5(U,Qe.previousPath,Qe.path)),r({title:"Workspace entry renamed",body:Qe.previousPath?`${Qe.previousPath} -> ${Qe.path}`:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to rename workspace entry",tone:"error"})}}),me=xt({mutationFn:Qe=>_n.moveWorkspaceEntry(a,Qe.entry.path,{destinationDirectoryPath:Qe.destinationDirectoryPath}),onSuccess:Qe=>{if(ve(),Qe.previousPath&&f){const gt=F5(f,Qe.previousPath,Qe.path);gt!==f&&xo(o,l,gt)}Qe.previousPath&&U&&$(F5(U,Qe.previousPath,Qe.path)),r({title:"Workspace entry moved",body:Qe.previousPath?`${Qe.previousPath} -> ${Qe.path}`:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to move workspace entry",tone:"error"})}}),we=xt({mutationFn:Qe=>_n.copyWorkspaceEntry(a,Qe.path),onSuccess:Qe=>{ve(),Qe.isDirectory?$(Qe.path):($(Qe.path),xo(o,l,Qe.path)),r({title:"Workspace entry copied",body:Qe.previousPath?`${Qe.previousPath} -> ${Qe.path}`:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to copy workspace entry",tone:"error"})}}),Xe=xt({mutationFn:Qe=>_n.deleteWorkspaceEntry(a,Qe.path),onSuccess:Qe=>{ve(),P(null),f&&(f===Qe.path||f.startsWith(`${Qe.path}/`))&&xo(o,l,null),U&&(U===Qe.path||U.startsWith(`${Qe.path}/`))&&$(B_(Qe.path)||null),r({title:"Workspace entry deleted",body:Qe.path,tone:"success"})},onError:Qe=>{r({title:Qe instanceof Error?Qe.message:"Failed to delete workspace entry",tone:"error"})}});async function ge(Qe){const gt=Rut(Qe);try{await zI(gt),r({title:"Library link copied",tone:"info"})}catch(Nt){r({title:"Failed to copy Library link",body:Nt instanceof Error?Nt.message:gt,tone:"error"})}}async function te(Qe){const gt=Xv(Oe,Qe.path);try{await zI(gt),r({title:"Absolute path copied",body:gt,tone:"info"})}catch(Nt){r({title:"Failed to copy absolute path",body:Nt instanceof Error?Nt.message:gt,tone:"error"})}}async function G(Qe){const gt=Xv(Oe,Qe.path),Nt=Pn();if(Nt!=null&&Nt.openPath)try{await Nt.openPath(gt),r({title:Qe.isDirectory?"Opened folder":"Opened in editor",body:gt,tone:"info"})}catch(Gt){r({title:Qe.isDirectory?"Failed to open folder":"Failed to open in editor",body:Gt instanceof Error?Gt.message:gt,tone:"error"})}}function oe(Qe){n(`/projects/${Qe.urlKey??Qe.id}/resources`)}async function Ze(Qe){var Gt;const gt=Qe.resource.locator,Nt=Pn();try{if(Nt!=null&&Nt.copyText)await Nt.copyText(gt);else if((Gt=navigator.clipboard)!=null&&Gt.writeText)await navigator.clipboard.writeText(gt);else throw new Error("Clipboard is not available in this environment.");r({title:"Resource locator copied",body:gt,tone:"info"})}catch(cn){r({title:"Failed to copy resource locator",body:cn instanceof Error?cn.message:gt,tone:"error"})}}async function Te(Qe){const gt=Qe.resource.locator.trim(),Nt=Pn();try{if(Qe.resource.kind==="url"||IH(gt)){Nt!=null&&Nt.openExternal?await Nt.openExternal(gt):window.open(gt,"_blank","noopener,noreferrer"),r({title:"Opened resource link",body:gt,tone:"info"});return}const Gt=u2e(Qe,Oe);if(!Gt||!(Nt!=null&&Nt.openPath))throw new Error("This resource cannot be opened from the current shell.");await Nt.openPath(Gt),r({title:"Opened resource",body:Gt,tone:"info"})}catch(Gt){r({title:"Failed to open resource",body:Gt instanceof Error?Gt.message:gt,tone:"error"})}}async function Be(Qe,gt,Nt="workspace"){const Gt=Pn();if(Gt!=null&&Gt.openWorkspace){ae(gt.id);try{await Gt.openWorkspace(Qe,gt.id),LI(gt.id),r({title:`Opened ${Nt} in ${gt.label}`,tone:"info"})}catch(cn){r({title:`Failed to open ${Nt}`,body:cn instanceof Error?cn.message:`Could not open the ${Nt} in ${gt.label}.`,tone:"error"})}finally{ae(null)}}}async function it(Qe,gt){if(Qe.isDirectory){if($5(gt))return;await Be(Xv(Oe,Qe.path),gt,"folder");return}if(!Oe)return;const Nt=Pn();if(typeof(Nt==null?void 0:Nt.openWorkspaceFileInIde)!="function")return;const Gt=$5(gt)?gt:F_([gt]).find(cn=>cn.id===gt.id);if(Gt){ae(Gt.id);try{await Nt.openWorkspaceFileInIde(Oe,Qe.path,Gt.id),Gt.workspaceTarget&&LI(Gt.workspaceTarget.id),r({title:Gt.id==="defaultApp"?"Opened file":`Opened file in ${Gt.label}`,body:Qe.path,tone:"info"})}catch(cn){r({title:"Failed to open file",body:cn instanceof Error?cn.message:`Could not open ${Qe.path} in ${Gt.label}.`,tone:"error"})}finally{ae(null)}}}function lt(Qe){xo(o,l,Qe)}function Ue(Qe,gt,Nt){$(Nt),Qut(o,l,Qe,gt)}function mt(Qe){But(o,l,Qe)}function tt(Qe,gt){!Qe.isDirectory||!dj(Qe.path)||(y({parent:Qe,kind:gt}),w(gt==="file"?"untitled.md":"new-folder"))}function dt(Qe){tt(Fe,Qe)}function at(Qe){r2e(Qe)&&(S(Qe),C(Qe.name))}function Pe(Qe){s2e(Qe)&&P(Qe)}function $e(Qe){n2e(Qe)&&we.mutate(Qe)}function ot(Qe,gt){R(!1),Q_(Qe,gt)&&me.mutate({entry:Qe,destinationDirectoryPath:gt})}function ue(Qe,gt,Nt=0){if(R(!1),Qe.length===0){Nt>0&&r({title:"No files imported",body:"Only text, Markdown, and code files can be imported.",tone:"warn"});return}ft.mutate({files:Qe,destinationDirectoryPath:gt,unsupportedCount:Nt})}function Ie(Qe){if(!(!i2e(Qe.dataTransfer)&&!x3(Qe.dataTransfer))){if(Eut(Qe)){R(!1);return}Qe.preventDefault(),Qe.dataTransfer.dropEffect=x3(Qe.dataTransfer)?"copy":"move",R(!0)}}function Ke(Qe){nq(Qe)&&R(!1)}function De(Qe){if(Qe.preventDefault(),R(!1),x3(Qe.dataTransfer)){const{supported:Nt,unsupportedCount:Gt}=a2e(Qe.dataTransfer);ue(Nt,"",Gt);return}const gt=l2e(Qe);!gt||!Q_(gt,"")||ot(gt,"")}return i.jsxs(i.Fragment,{children:[i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx("header",{"data-testid":"workspace-context-header","aria-label":_i("library",s),className:K("workspace-context-header rudder-doc-editor-sidebar-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4",Y&&!ce&&"rudder-doc-editor-sidebar-header--tabs-only",!Y&&ce&&"rudder-doc-editor-sidebar-header--breadcrumb-only",Y&&ce&&"rudder-doc-editor-sidebar-header--tabs-and-breadcrumb"),children:i.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1.5",children:[Oe?i.jsx(Wce,{rootPath:Oe,targets:ke,openingTargetId:qce(xe),onOpenTarget:(Qe,gt,Nt)=>{Be(Qe,gt,Nt)},contentAlign:"start",testId:"org-workspaces-sidebar-launcher",targetTestIdPrefix:"org-workspaces-sidebar-launch-target"}):null,i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>dt("file"),disabled:!Oe,"aria-label":"New file","data-testid":"org-workspaces-new-file-button",children:i.jsx(F7,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"New file"})]}),i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>dt("folder"),disabled:!Oe,"aria-label":"New folder","data-testid":"org-workspaces-new-folder-button",children:i.jsx(j3,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"New folder"})]}),e?i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e,"aria-label":"Hide Library sidebar","data-testid":"org-workspaces-hide-sidebar-button",children:i.jsx(ow,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{children:"Hide Library sidebar"})]}):null]})}),i.jsx("section",{"data-testid":"org-workspaces-files-card","data-active-surface":ft.isPending?"workspace-import":void 0,className:K("flex min-h-0 flex-1 flex-col overflow-hidden border-t border-border transition-colors",T&&"bg-[#2f80ed]/5 ring-1 ring-inset ring-[#2f80ed]/25",ft.isPending&&"active-surface-ring"),onDragOver:Ie,onDragLeave:Ke,onDrop:De,children:i.jsx("div",{ref:g,"data-testid":"org-workspaces-files-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-auto",children:i.jsx("div",{className:"px-2 py-2",children:a?L.isLoading?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Loading files..."}):L.error?i.jsx("div",{className:"px-2 py-3 text-sm text-destructive",children:L.error.message}):(Ce=L.data)!=null&&Ce.rootExists?Q.length===0?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:L.data.message??"This folder is empty."}):i.jsx("ul",{className:"space-y-0.5",children:Q.map(Qe=>{var gt,Nt;return i.jsx(d2e,{orgId:a,entry:Qe,organizationSkills:F,selectedFilePath:f,selectedSkillTreePath:ee,selectedResourcePath:ne,activeEntryPath:U,draggedEntryPath:_,onSelectFile:lt,onSelectSkillFile:Ue,onSelectResource:mt,onFocusEntry:$,onDragStartEntry:D,onDragEndEntry:()=>D(null),onCopyLink:Gt=>void ge(Gt),onCopyAbsolutePath:Gt=>void te(Gt),onOpenEntry:(gt=Pn())!=null&&gt.openPath?Gt=>void G(Gt):void 0,onOpenEntryTarget:(Gt,cn)=>{it(Gt,cn)},onStartCreateEntry:tt,onCopyEntry:$e,onStartRename:at,onStartDelete:Pe,onMoveEntry:ot,onImportFiles:ue,onAddResources:oe,onCopyResourceLocator:Gt=>void Ze(Gt),onOpenResource:Gt=>void Te(Gt),onUnlinkResource:(Gt,cn)=>Se.mutate({project:Gt,attachment:cn}),onOpenSkillAddDialog:()=>E(!0),unlinkingResourceId:((Nt=Se.variables)==null?void 0:Nt.attachment.id)??null,expandedDirectories:fe,workspaceLaunchTargets:ke,openingWorkspaceTargetId:xe,projectResourceGroupsByLibraryPath:se.groupsByLibraryPath},Qe.path)})}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:((kt=L.data)==null?void 0:kt.message)??"The shared Library root is not available on this machine yet."}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Select an organization."})})})})]}),i.jsx(Ps,{open:x!==null,onOpenChange:Qe=>{!Qe&&!ze.isPending&&(y(null),w(""))},children:i.jsxs(zs,{children:[i.jsxs(vi,{children:[i.jsx(ei,{children:(x==null?void 0:x.kind)==="folder"?"New folder":"New file"}),i.jsxs(Si,{children:["Create inside ",(x==null?void 0:x.parent.path)??"this folder","."]})]}),i.jsxs("label",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-muted-foreground",children:"Name"}),i.jsx(Kn,{value:v,onChange:Qe=>w(Qe.target.value),onKeyDown:Qe=>{Qe.key!=="Enter"||!x||!U_(v)||(Qe.preventDefault(),ze.mutate({parent:x.parent,kind:x.kind,name:v}))},autoFocus:!0})]}),i.jsxs(ga,{children:[i.jsx(le,{type:"button",variant:"outline",onClick:()=>{y(null),w("")},disabled:ze.isPending,children:"Cancel"}),i.jsx(le,{type:"button",onClick:()=>{x&&ze.mutate({parent:x.parent,kind:x.kind,name:v})},disabled:!x||!U_(v)||ze.isPending,children:ze.isPending?"Creating...":(x==null?void 0:x.kind)==="folder"?"Create folder":"Create file"})]})]})}),i.jsx(Ps,{open:k!==null,onOpenChange:Qe=>{!Qe&&!ie.isPending&&(S(null),C(""))},children:i.jsxs(zs,{children:[i.jsxs(vi,{children:[i.jsx(ei,{children:"Rename entry"}),i.jsx(Si,{children:"Rename this workspace file or folder without changing its parent folder."})]}),i.jsxs("label",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-muted-foreground",children:"Name"}),i.jsx(Kn,{value:j,onChange:Qe=>C(Qe.target.value),onKeyDown:Qe=>{Qe.key!=="Enter"||!k||(Qe.preventDefault(),ie.mutate({entry:k,name:j}))},autoFocus:!0})]}),i.jsxs(ga,{children:[i.jsx(le,{type:"button",variant:"outline",onClick:()=>{S(null),C("")},disabled:ie.isPending,children:"Cancel"}),i.jsx(le,{type:"button",onClick:()=>{k&&ie.mutate({entry:k,name:j})},disabled:!k||j.trim().length===0||j.trim()===k.name||ie.isPending,children:ie.isPending?"Renaming...":"Rename"})]})]})}),i.jsx(Ps,{open:N!==null,onOpenChange:Qe=>{!Qe&&!Xe.isPending&&P(null)},children:i.jsxs(zs,{children:[i.jsxs(vi,{children:[i.jsx(ei,{children:(N==null?void 0:N.entityType)==="orphaned_agent_workspace"?"Delete deleted agent folder?":"Delete entry"}),i.jsx(Si,{children:(N==null?void 0:N.entityType)==="orphaned_agent_workspace"?`This folder is no longer linked to an active agent. This will permanently delete ${N.path} and everything inside it from the organization Library.`:`This will permanently delete ${(N==null?void 0:N.path)??"this entry"} from the organization Library.`})]}),i.jsxs(ga,{children:[i.jsx(le,{type:"button",variant:"outline",onClick:()=>P(null),disabled:Xe.isPending,children:"Cancel"}),i.jsx(le,{type:"button",variant:"destructive",onClick:()=>{N&&Xe.mutate(N)},disabled:!N||Xe.isPending,children:Xe.isPending?"Deleting...":"Delete"})]})]})}),i.jsx(Lut,{open:M,orgId:a,onOpenChange:E})]})}function b$n(e){const t=fl(e);return/^\/(?:dashboard\/calendar|calendar)(?:\/|$)/.test(t)?"calendar":"dashboard"}function Uut({className:e,compact:t=!1}){const n=br(),r=b$n(n.pathname);return i.jsxs("nav",{"aria-label":"Dashboard section","data-testid":"dashboard-calendar-switcher","data-mode":r,className:K("desktop-window-no-drag relative grid h-9 w-[232px] grid-cols-2 rounded-md border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] p-0.5 text-[13px] shadow-[0_8px_22px_-18px_rgba(15,23,42,0.42)]",e),children:[i.jsx("span",{"aria-hidden":"true",className:K("absolute left-0.5 top-0.5 h-8 w-[calc(50%-2px)] rounded-[calc(var(--radius-sm)-1px)] bg-foreground shadow-[0_8px_20px_-14px_rgba(15,23,42,0.75)] transition-transform duration-200 ease-out motion-reduce:transition-none",r==="calendar"&&"translate-x-full")}),i.jsxs(sn,{to:"/dashboard","aria-current":r==="dashboard"?"page":void 0,className:K("relative z-10 inline-flex min-w-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] font-medium transition-colors",t?"gap-1 px-1.5":"gap-1.5 px-2",r==="dashboard"?"text-background":"text-muted-foreground hover:text-foreground"),children:[t?null:i.jsx(yx,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:"Dashboard"})]}),i.jsxs(sn,{to:"/dashboard/calendar","aria-current":r==="calendar"?"page":void 0,className:K("relative z-10 inline-flex min-w-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] font-medium transition-colors",t?"gap-1 px-1.5":"gap-1.5 px-2",r==="calendar"?"text-background":"text-muted-foreground hover:text-foreground"),children:[t?null:i.jsx(rE,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:"Calendar"})]})]})}function sde({...e}){return i.jsx("nav",{"aria-label":"breadcrumb","data-slot":"breadcrumb",...e})}function ide({className:e,...t}){return i.jsx("ol",{"data-slot":"breadcrumb-list",className:K("text-muted-foreground m-0 flex list-none flex-wrap items-center gap-1.5 p-0 text-sm break-words sm:gap-2.5",e),...t})}function $I({className:e,...t}){return i.jsx("li",{"data-slot":"breadcrumb-item",className:K("inline-flex items-center gap-1.5",e),...t})}function rq({asChild:e,className:t,...n}){const r=e?eue:"a";return i.jsx(r,{"data-slot":"breadcrumb-link",className:K("hover:text-foreground transition-colors",t),...n})}function ade({className:e,...t}){return i.jsx("span",{"data-slot":"breadcrumb-page",role:"link","aria-disabled":"true","aria-current":"page",className:K("text-foreground font-normal",e),...t})}function sq({children:e,className:t,...n}){return i.jsx("li",{"data-slot":"breadcrumb-separator",role:"presentation","aria-hidden":"true",className:K("[&>svg]:size-3.5",t),...n,children:e??i.jsx(bi,{})})}function hc({className:e,...t}){return i.jsx(OEe,{"data-slot":"checkbox",className:K("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:i.jsx(jEe,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:i.jsx(Zs,{className:"size-3.5"})})})}function y$n(e){return e.defaultPrevented||e.key.toLowerCase()!=="f"||!e.metaKey&&!e.ctrlKey?!1:!e.altKey&&!e.shiftKey}function v$n({context:e}){const{slots:t}=Kj({slotTypes:["globalToolbarButton"],orgId:e.orgId}),{launchers:n}=xut({placementZones:["globalToolbarButton"],orgId:e.orgId,enabled:!!e.orgId});return t.length===0&&n.length===0?null:i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i.jsx(eb,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}),i.jsx(K0e,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"})]})}function w$n(e){return e.identifier??e.id.slice(0,8)}const ode=[{value:"title",label:"Title"},{value:"description",label:"Description"},{value:"comment",label:"Comments"}],k$n=new Set(ode.map(e=>e.value));function O$n(e){if(!e)return["title"];const t=e.split(",").map(n=>n.trim()).filter(n=>k$n.has(n));return t.length>0?t:["title"]}function S$n(e){return e.length===1&&e[0]==="title"?null:e.join(",")}function jPe({desktopChrome:e=!1,variant:t="shell"}={}){const{t:n}=is(),{breadcrumbs:r,headerActions:s}=Xi(),{sidebarOpen:a,setSidebarOpen:o,toggleSidebar:l,isMobile:c}=jc(),{selectedOrganizationId:d,selectedOrganization:u}=jr(),{openNewIssue:f,openNewProject:A}=ii(),m=br(),g=Yr(),[x,y]=h.useState(""),[v,w]=h.useState(!1),[k,S]=h.useState(["title"]),j=h.useRef(null),C=h.useRef(null),N=h.useMemo(()=>fl(m.pathname),[m.pathname]),P=h.useMemo(()=>new URLSearchParams(m.search).get("source")??"",[m.search]),M=h.useMemo(()=>/^\/issues(?:\/|$)/.test(N),[N]),E=h.useMemo(()=>/^\/issues\/[^/]+(?:\/|$)/.test(N),[N]),T=h.useMemo(()=>/^\/messenger\/issues\/[^/]+(?:\/|$)/.test(N),[N]),R=h.useMemo(()=>/^\/automations\/[^/]+(?:\/|$)/.test(N),[N]),_=M&&P==="linear",D=h.useMemo(()=>/^\/(?:dashboard|inbox|chat|messenger|issues|agents|library|projects|goals|automations|calendar)(?:\/|$)/.test(N),[N]),U=h.useMemo(()=>/^\/agents\/[^/]+(?:\/|$)/.test(N),[N]),$=h.useMemo(()=>/^\/dashboard\/calendar(?:\/|$)/.test(N)?null:/^\/dashboard(?:\/|$)/.test(N)?"Dashboard":/^\/messenger(?:\/|$)/.test(N)?"Messenger":/^\/inbox(?:\/|$)/.test(N)?"Inbox":/^\/issues(?:\/|$)/.test(N)?P==="linear"?"Linear Issues":E?"Issues":"Issue Tracker":/^\/chat(?:\/|$)/.test(N)?"Chat":/^\/projects(?:\/|$)/.test(N)?"Projects":/^\/agents(?:\/|$)/.test(N)?"Agents":/^\/goals(?:\/|$)/.test(N)?"Goals":/^\/automations(?:\/|$)/.test(N)?"Automations":/^\/calendar(?:\/|$)/.test(N)?"Calendar":null,[P,E,N]),{data:L}=Me({queryKey:V.projects.list(d??"__none__"),queryFn:async()=>(await Mi.list(d)).filter(ze=>!ze.archivedAt),enabled:!!d&&/^\/projects(?:\/|$)/.test(N)}),H=x.trim(),X=E&&!_&&v&&H.length>0,F=M&&!E&&!_&&v,Q=X||F,{data:q=[],isFetching:B}=Me({queryKey:V.issues.search(d??"__none__",H,void 0,k),queryFn:()=>lr.list(d,{q:H,searchFields:k}),enabled:!!d&&X}),ee=h.useMemo(()=>({orgId:d??null,orgPrefix:u?Oc(u):null}),[d,u]),se=i.jsx(v$n,{context:ee}),re=s||se?i.jsxs("div",{"data-testid":"workspace-main-header-actions",className:K("ml-auto flex shrink-0 items-center gap-2",e&&"desktop-window-no-drag"),children:[s?i.jsx("div",{className:"flex shrink-0 items-center gap-2",children:s}):null,se]}):null;h.useEffect(()=>{if(!M)return;const Se=new URLSearchParams(m.search),ze=Se.get("q")??"";y(ze),S(O$n(Se.get("searchFields"))),w(ze.trim().length>0&&E)},[E,M,m.search]),h.useEffect(()=>{if(!M)return;const Se=window.setTimeout(()=>{const ze=new URLSearchParams(m.search),ft=x.trim();(ze.get("q")??"")!==ft&&(ft?ze.set("q",ft):ze.delete("q"),g({pathname:m.pathname,search:ze.toString()?`?${ze.toString()}`:""},{replace:!0}))},250);return()=>window.clearTimeout(Se)},[M,x,m.pathname,m.search,g]);const ne=Se=>{var ze;w(!1),(ze=j.current)==null||ze.blur(),g(`/issues/${Se.identifier??Se.id}`)},Ae=Se=>{S(ze=>{const ft=ze.includes(Se)?ze.length===1?ze:ze.filter(we=>we!==Se):ode.map(we=>we.value).filter(we=>we===Se||ze.includes(we)),ie=new URLSearchParams(m.search),me=S$n(ft);return me?ie.set("searchFields",me):ie.delete("searchFields"),g({pathname:m.pathname,search:ie.toString()?`?${ie.toString()}`:""},{replace:!0}),ft})};h.useEffect(()=>{if(!v)return;const Se=ze=>{var ie;const ft=ze.target;ft instanceof Node&&((ie=C.current)!=null&&ie.contains(ft)||w(!1))};return document.addEventListener("pointerdown",Se),()=>document.removeEventListener("pointerdown",Se)},[v]),h.useEffect(()=>{if(!M)return;const Se=()=>{const ft=j.current;ft&&document.activeElement===ft&&ft.blur()},ze=ft=>{y$n(ft)&&(window.requestAnimationFrame(Se),window.setTimeout(Se,0))};return document.addEventListener("keydown",ze,!0),()=>document.removeEventListener("keydown",ze,!0)},[M]);const Y=c&&i.jsx(le,{variant:"ghost",size:"icon-sm",className:K("mr-2 shrink-0",e&&"desktop-window-no-drag"),onClick:l,"aria-label":n("common.openSidebar"),children:i.jsx(z9t,{className:"h-5 w-5"})}),ce=!c&&t==="card"&&a===!1?i.jsx(le,{variant:"ghost",size:"icon-sm",className:"desktop-window-no-drag shrink-0 text-muted-foreground hover:text-foreground",onClick:()=>o(!0),"aria-label":"Open context sidebar",title:"Open context sidebar",children:i.jsx(ow,{className:"h-4 w-4"})}):null,ke=t==="card"?"workspace-card-header workspace-main-header":"surface-shell",Ne=e?"desktop-chrome desktop-window-drag":"",xe=t==="card"&&/^\/messenger(?:\/|$)/.test(N)&&!T,ae=t==="card"&&U,fe=h.useMemo(()=>/^\/(?:library|resources)(?:\/|$)/.test(N)?"Shared Library for markdown notes, codebases, references, outputs, and reusable context that humans and agents can both work with.":/^\/workspaces(?:\/|$)/.test(N)?"Shared Library files, plans, and skill packages for this organization. Use this page for disk-backed context and editable files.":null,[N]),ve=h.useMemo(()=>/^\/(?:library|resources)(?:\/|$)/.test(N)||/^\/workspaces(?:\/|$)/.test(N)?"About Library":null,[N]);if((xe||ae)&&!ce)return null;if(xe||ae)return i.jsxs("div",{className:K(ke,"flex h-12 shrink-0 items-center px-4 md:px-4",Ne),children:[ce,i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}),re]});if($){const Se=(M&&E||T)&&r.length>1,ze=Se||R&&r.length>1,ft=/^\/projects(?:\/|$)/.test(N),ie=ft&&!/^\/projects\/[^/]+/.test(N),me=/^\/dashboard\/?$/.test(N);return i.jsxs("div",{className:K(ke,"flex shrink-0 items-center gap-3",t==="card"?X?"items-start px-4 py-3 md:px-4":"h-12 px-4 md:px-4":X?"items-start px-4 py-3 md:px-6":"h-14 px-4 md:px-6",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[Y,ce,me?i.jsx(Uut,{}):ze?i.jsx("div",{className:K("min-w-0 flex-1",e&&"desktop-window-no-drag"),children:i.jsx(sde,{className:"min-w-0 overflow-hidden","data-testid":Se?"issue-detail-breadcrumb":"primary-detail-breadcrumb",children:i.jsx(ide,{className:"flex-nowrap overflow-hidden",children:r.map((we,Xe)=>{const ge=Xe===r.length-1;return i.jsxs(h.Fragment,{children:[Xe>0&&i.jsx(sq,{className:"shrink-0"}),i.jsx($I,{className:ge?"min-w-0":"max-w-[180px] shrink-0",children:ge||!we.href?i.jsx(ade,{className:"truncate text-[13px] font-medium text-foreground",title:we.label,children:we.label}):i.jsx(rq,{asChild:!0,children:i.jsx(sn,{to:we.href,state:we.href.startsWith("/issues/")?m.state:void 0,className:"truncate",title:we.label,children:we.label})})})]},`${we.href??we.label}-${Xe}`)})})})}):i.jsx("div",{className:"min-w-0 shrink-0",children:i.jsx("h1",{className:"truncate text-[15px] font-semibold tracking-tight text-foreground",children:$})}),e&&!ze?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,M?i.jsxs("div",{className:K("hidden items-center gap-3 md:flex",e&&"desktop-window-no-drag"),children:[i.jsxs("div",{ref:C,className:"relative w-80",children:[i.jsx(Fl,{className:"pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Kn,{ref:j,value:x,onChange:we=>{y(we.target.value),w(E?we.target.value.trim().length>0:!_)},onClick:()=>w(E?H.length>0:!_),onFocus:()=>w(E?H.length>0:!_),onKeyDown:we=>{we.key==="Escape"&&v&&(we.preventDefault(),w(!1)),we.key==="Enter"&&Q&&q[0]&&(we.preventDefault(),ne(q[0]))},placeholder:_?"Search Linear issues...":"Search issues...",className:"h-9 border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] pl-8 text-sm","aria-label":"Search issues","aria-expanded":Q,"aria-controls":Q?"issue-search-menu":void 0}),X?i.jsx("div",{id:"issue-search-menu","data-testid":"breadcrumb-issue-result-menu",role:"listbox",className:K("relative z-50 mt-2 w-full overflow-hidden rounded-[var(--radius-sm)] border border-[color:var(--border-base)] bg-[color:var(--surface-panel)] py-1 shadow-lg",E?"xl:w-[26rem] xl:-translate-x-[calc(100%+0.5rem)]":null),children:B?i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:"Searching..."}):q.length>0?i.jsx("div",{className:"max-h-32 overflow-y-auto scrollbar-auto-hide",children:q.slice(0,8).map(we=>i.jsxs("button",{type:"button",role:"option",className:"flex w-full min-w-0 items-center gap-2 px-3 py-2 text-left text-sm hover:bg-[color:var(--surface-hover)] focus:bg-[color:var(--surface-hover)] focus:outline-none",onMouseDown:Xe=>Xe.preventDefault(),onClick:()=>ne(we),children:[i.jsx(ni,{status:we.status,className:"h-3.5 w-3.5"}),i.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:w$n(we)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",children:we.title}),i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:we.status})]},we.id))}):i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:"No matching issues."})}):F?i.jsxs("div",{id:"issue-search-menu","data-testid":"breadcrumb-issue-search-scope-menu",className:"absolute left-0 top-full z-[70] mt-2 w-full overflow-hidden rounded-[var(--radius-sm)] border border-[color:var(--border-base)] bg-[color:var(--surface-overlay)] shadow-[0_22px_60px_-34px_rgb(0_0_0/0.72)] dark:border-[color:var(--border-strong)]",children:[i.jsx("div",{className:"border-b border-[color:var(--border-soft)] px-3 py-2",children:i.jsx("div",{className:"text-xs font-medium text-foreground",children:"Search in"})}),i.jsx("div",{className:"space-y-0.5 p-1.5",children:ode.map(we=>i.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded-[calc(var(--radius-sm)-2px)] px-2 py-1.5 text-sm transition-colors hover:bg-[color:var(--surface-active)] focus-within:bg-[color:var(--surface-active)]",children:[i.jsx(hc,{checked:k.includes(we.value),onCheckedChange:()=>Ae(we.value)}),i.jsx("span",{children:we.label})]},we.value))})]}):null]}),_?null:i.jsxs(le,{size:"sm",className:"px-4",onClick:()=>f(),children:[i.jsx(Zr,{className:"mr-1.5 h-3.5 w-3.5"}),"Create Issue"]})]}):null,ft&&(!ie||((L==null?void 0:L.length)??0)>0)?i.jsxs(le,{size:"sm",className:K("hidden px-4 md:inline-flex",e&&"desktop-window-no-drag"),onClick:()=>A(),children:[i.jsx(Zr,{className:"mr-1.5 h-3.5 w-3.5"}),"Add Project"]}):null,re]})}if(r.length===0)return i.jsxs("div",{className:K(ke,"flex h-14 shrink-0 items-center justify-end px-4 md:px-6",t==="card"&&"md:px-5",t==="shell"&&!D&&"border-b panel-divider",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[ce,e?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,re]});if(r.length===1){const Se=r[0],ze=Se.sublabel&&Se.subhref;return i.jsxs("div",{className:K(ke,"flex shrink-0 items-center px-4 md:px-6",t==="card"&&"md:px-5",t==="shell"&&!D&&"border-b panel-divider",ze?"min-h-14 py-2":"h-14",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[Y,ce,i.jsxs("div",{className:"min-w-0 overflow-hidden flex-1",children:[t==="card"?null:i.jsx("div",{className:"text-[10px] font-medium text-muted-foreground/75",children:n("common.workspace")}),i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 pt-0.5",children:[i.jsx("h1",{className:"truncate text-sm font-semibold tracking-wide text-foreground leading-tight",children:Se.label}),fe?i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx("button",{type:"button",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":ve??"About organization context",children:i.jsx(Vfe,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{side:"bottom",sideOffset:8,className:"max-w-[320px] px-3 py-2 text-xs leading-5",children:fe})]}):null]}),ze?i.jsx(sn,{to:Se.subhref,className:"mt-0.5 block truncate text-left text-[11px] leading-snug text-muted-foreground underline-offset-4 hover:text-foreground hover:underline",children:Se.sublabel}):null]}),e?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,re]})}return i.jsxs("div",{className:K(ke,"flex h-14 shrink-0 items-center px-4 md:px-6",t==="card"&&"md:px-5",t==="shell"&&!D&&"border-b panel-divider",t==="shell"&&e&&"h-auto min-h-[calc(3.5rem+var(--desktop-titlebar-top-gap))] pl-[var(--desktop-traffic-lights-offset)] pr-3 pt-[var(--desktop-titlebar-top-gap)] md:pr-4",Ne),children:[Y,ce,i.jsx("div",{className:"min-w-0 overflow-hidden flex-1",children:i.jsx(sde,{className:"min-w-0 overflow-hidden",children:i.jsx(ide,{className:"flex-nowrap",children:r.map((Se,ze)=>{const ft=ze===r.length-1;return i.jsxs(h.Fragment,{children:[ze>0&&i.jsx(sq,{}),i.jsx($I,{className:ft?"min-w-0":"shrink-0",children:ft||!Se.href?i.jsx(ade,{className:"truncate",children:Se.label}):i.jsx(rq,{asChild:!0,children:i.jsx(sn,{to:Se.href,children:Se.label})})})]},ze)})})})}),e?i.jsx("div",{className:"desktop-window-drag hidden min-h-full flex-1 md:block"}):null,re]})}var CPe=1,j$n=.9,C$n=.8,N$n=.17,vne=.1,wne=.999,P$n=.9999,I$n=.99,T$n=/[\\\/_+.#"@\[\(\{&]/,_$n=/[\\\/_+.#"@\[\(\{&]/g,M$n=/[\s-]/,Vut=/[\s-]/g;function lde(e,t,n,r,s,a,o){if(a===t.length)return s===e.length?CPe:I$n;var l=`${s},${a}`;if(o[l]!==void 0)return o[l];for(var c=r.charAt(a),d=n.indexOf(c,s),u=0,f,A,m,g;d>=0;)f=lde(e,t,n,r,d+1,a+1,o),f>u&&(d===s?f*=CPe:T$n.test(e.charAt(d-1))?(f*=C$n,m=e.slice(s,d-1).match(_$n),m&&s>0&&(f*=Math.pow(wne,m.length))):M$n.test(e.charAt(d-1))?(f*=j$n,g=e.slice(s,d-1).match(Vut),g&&s>0&&(f*=Math.pow(wne,g.length))):(f*=N$n,s>0&&(f*=Math.pow(wne,d-s))),e.charAt(d)!==t.charAt(a)&&(f*=P$n)),(f<vne&&n.charAt(d-1)===r.charAt(a+1)||r.charAt(a+1)===r.charAt(a)&&n.charAt(d-1)!==r.charAt(a))&&(A=lde(e,t,n,r,d+1,a+2,o),A*vne>f&&(f=A*vne)),f>u&&(u=f),d=n.indexOf(c,d+1);return o[l]=u,u}function NPe(e){return e.toLowerCase().replace(Vut," ")}function E$n(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,lde(e,t,NPe(e),NPe(t),0,0,{})}var D$n=Symbol.for("react.lazy"),iq=Bq[" use ".trim().toString()];function R$n(e){return typeof e=="object"&&e!==null&&"then"in e}function qut(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===D$n&&"_payload"in e&&R$n(e._payload)}function L$n(e){const t=z$n(e),n=h.forwardRef((r,s)=>{let{children:a,...o}=r;qut(a)&&typeof iq=="function"&&(a=iq(a._payload));const l=h.Children.toArray(a),c=l.find(F$n);if(c){const d=c.props.children,u=l.map(f=>f===c?h.Children.count(d)>1?h.Children.only(null):h.isValidElement(d)?d.props.children:null:f);return i.jsx(t,{...o,ref:s,children:h.isValidElement(d)?h.cloneElement(d,void 0,u):null})}return i.jsx(t,{...o,ref:s,children:a})});return n.displayName=`${e}.Slot`,n}function z$n(e){const t=h.forwardRef((n,r)=>{let{children:s,...a}=n;if(qut(s)&&typeof iq=="function"&&(s=iq(s._payload)),h.isValidElement(s)){const o=Q$n(s),l=B$n(a,s.props);return s.type!==h.Fragment&&(l.ref=r?Sx(r,o):o),h.cloneElement(s,l)}return h.Children.count(s)>1?h.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var $$n=Symbol("radix.slottable");function F$n(e){return h.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$$n}function B$n(e,t){const n={...t};for(const r in t){const s=e[r],a=t[r];/^on[A-Z]/.test(r)?s&&a?n[r]=(...l)=>{const c=a(...l);return s(...l),c}:s&&(n[r]=s):r==="style"?n[r]={...s,...a}:r==="className"&&(n[r]=[s,a].filter(Boolean).join(" "))}return{...e,...n}}function Q$n(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var U$n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Cw=U$n.reduce((e,t)=>{const n=L$n(`Primitive.${t}`),r=h.forwardRef((s,a)=>{const{asChild:o,...l}=s,c=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(c,{...l,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),IN='[cmdk-group=""]',kne='[cmdk-group-items=""]',V$n='[cmdk-group-heading=""]',Kut='[cmdk-item=""]',PPe=`${Kut}:not([aria-disabled="true"])`,cde="cmdk-item-select",l7="data-value",q$n=(e,t,n)=>E$n(e,t,n),Wut=h.createContext(void 0),ED=()=>h.useContext(Wut),Zut=h.createContext(void 0),f2e=()=>h.useContext(Zut),Hut=h.createContext(void 0),Xut=h.forwardRef((e,t)=>{let n=c7(()=>{var q,B;return{search:"",value:(B=(q=e.value)!=null?q:e.defaultValue)!=null?B:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=c7(()=>new Set),s=c7(()=>new Map),a=c7(()=>new Map),o=c7(()=>new Set),l=Gut(e),{label:c,children:d,value:u,onValueChange:f,filter:A,shouldFilter:m,loop:g,disablePointerSelection:x=!1,vimBindings:y=!0,...v}=e,w=vc(),k=vc(),S=vc(),j=h.useRef(null),C=nFn();L6(()=>{if(u!==void 0){let q=u.trim();n.current.value=q,N.emit()}},[u]),L6(()=>{C(6,_)},[]);let N=h.useMemo(()=>({subscribe:q=>(o.current.add(q),()=>o.current.delete(q)),snapshot:()=>n.current,setState:(q,B,ee)=>{var se,re,ne,Ae;if(!Object.is(n.current[q],B)){if(n.current[q]=B,q==="search")R(),E(),C(1,T);else if(q==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Y=document.getElementById(S);Y?Y.focus():(se=document.getElementById(w))==null||se.focus()}if(C(7,()=>{var Y;n.current.selectedItemId=(Y=D())==null?void 0:Y.id,N.emit()}),ee||C(5,_),((re=l.current)==null?void 0:re.value)!==void 0){let Y=B??"";(Ae=(ne=l.current).onValueChange)==null||Ae.call(ne,Y);return}}N.emit()}},emit:()=>{o.current.forEach(q=>q())}}),[]),P=h.useMemo(()=>({value:(q,B,ee)=>{var se;B!==((se=a.current.get(q))==null?void 0:se.value)&&(a.current.set(q,{value:B,keywords:ee}),n.current.filtered.items.set(q,M(B,ee)),C(2,()=>{E(),N.emit()}))},item:(q,B)=>(r.current.add(q),B&&(s.current.has(B)?s.current.get(B).add(q):s.current.set(B,new Set([q]))),C(3,()=>{R(),E(),n.current.value||T(),N.emit()}),()=>{a.current.delete(q),r.current.delete(q),n.current.filtered.items.delete(q);let ee=D();C(4,()=>{R(),(ee==null?void 0:ee.getAttribute("id"))===q&&T(),N.emit()})}),group:q=>(s.current.has(q)||s.current.set(q,new Set),()=>{a.current.delete(q),s.current.delete(q)}),filter:()=>l.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>l.current.disablePointerSelection,listId:w,inputId:S,labelId:k,listInnerRef:j}),[]);function M(q,B){var ee,se;let re=(se=(ee=l.current)==null?void 0:ee.filter)!=null?se:q$n;return q?re(q,n.current.search,B):0}function E(){if(!n.current.search||l.current.shouldFilter===!1)return;let q=n.current.filtered.items,B=[];n.current.filtered.groups.forEach(se=>{let re=s.current.get(se),ne=0;re.forEach(Ae=>{let Y=q.get(Ae);ne=Math.max(Y,ne)}),B.push([se,ne])});let ee=j.current;U().sort((se,re)=>{var ne,Ae;let Y=se.getAttribute("id"),ce=re.getAttribute("id");return((ne=q.get(ce))!=null?ne:0)-((Ae=q.get(Y))!=null?Ae:0)}).forEach(se=>{let re=se.closest(kne);re?re.appendChild(se.parentElement===re?se:se.closest(`${kne} > *`)):ee.appendChild(se.parentElement===ee?se:se.closest(`${kne} > *`))}),B.sort((se,re)=>re[1]-se[1]).forEach(se=>{var re;let ne=(re=j.current)==null?void 0:re.querySelector(`${IN}[${l7}="${encodeURIComponent(se[0])}"]`);ne==null||ne.parentElement.appendChild(ne)})}function T(){let q=U().find(ee=>ee.getAttribute("aria-disabled")!=="true"),B=q==null?void 0:q.getAttribute(l7);N.setState("value",B||void 0)}function R(){var q,B,ee,se;if(!n.current.search||l.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let re=0;for(let ne of r.current){let Ae=(B=(q=a.current.get(ne))==null?void 0:q.value)!=null?B:"",Y=(se=(ee=a.current.get(ne))==null?void 0:ee.keywords)!=null?se:[],ce=M(Ae,Y);n.current.filtered.items.set(ne,ce),ce>0&&re++}for(let[ne,Ae]of s.current)for(let Y of Ae)if(n.current.filtered.items.get(Y)>0){n.current.filtered.groups.add(ne);break}n.current.filtered.count=re}function _(){var q,B,ee;let se=D();se&&(((q=se.parentElement)==null?void 0:q.firstChild)===se&&((ee=(B=se.closest(IN))==null?void 0:B.querySelector(V$n))==null||ee.scrollIntoView({block:"nearest"})),se.scrollIntoView({block:"nearest"}))}function D(){var q;return(q=j.current)==null?void 0:q.querySelector(`${Kut}[aria-selected="true"]`)}function U(){var q;return Array.from(((q=j.current)==null?void 0:q.querySelectorAll(PPe))||[])}function $(q){let B=U()[q];B&&N.setState("value",B.getAttribute(l7))}function L(q){var B;let ee=D(),se=U(),re=se.findIndex(Ae=>Ae===ee),ne=se[re+q];(B=l.current)!=null&&B.loop&&(ne=re+q<0?se[se.length-1]:re+q===se.length?se[0]:se[re+q]),ne&&N.setState("value",ne.getAttribute(l7))}function H(q){let B=D(),ee=B==null?void 0:B.closest(IN),se;for(;ee&&!se;)ee=q>0?eFn(ee,IN):tFn(ee,IN),se=ee==null?void 0:ee.querySelector(PPe);se?N.setState("value",se.getAttribute(l7)):L(q)}let X=()=>$(U().length-1),F=q=>{q.preventDefault(),q.metaKey?X():q.altKey?H(1):L(1)},Q=q=>{q.preventDefault(),q.metaKey?$(0):q.altKey?H(-1):L(-1)};return h.createElement(Cw.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:q=>{var B;(B=v.onKeyDown)==null||B.call(v,q);let ee=q.nativeEvent.isComposing||q.keyCode===229;if(!(q.defaultPrevented||ee))switch(q.key){case"n":case"j":{y&&q.ctrlKey&&F(q);break}case"ArrowDown":{F(q);break}case"p":case"k":{y&&q.ctrlKey&&Q(q);break}case"ArrowUp":{Q(q);break}case"Home":{q.preventDefault(),$(0);break}case"End":{q.preventDefault(),X();break}case"Enter":{q.preventDefault();let se=D();if(se){let re=new Event(cde);se.dispatchEvent(re)}}}}},h.createElement("label",{"cmdk-label":"",htmlFor:P.inputId,id:P.labelId,style:sFn},c),TH(e,q=>h.createElement(Zut.Provider,{value:N},h.createElement(Wut.Provider,{value:P},q))))}),K$n=h.forwardRef((e,t)=>{var n,r;let s=vc(),a=h.useRef(null),o=h.useContext(Hut),l=ED(),c=Gut(e),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:o==null?void 0:o.forceMount;L6(()=>{if(!d)return l.item(s,o==null?void 0:o.id)},[d]);let u=Yut(s,a,[e.value,e.children,a],e.keywords),f=f2e(),A=H3(C=>C.value&&C.value===u.current),m=H3(C=>d||l.filter()===!1?!0:C.search?C.filtered.items.get(s)>0:!0);h.useEffect(()=>{let C=a.current;if(!(!C||e.disabled))return C.addEventListener(cde,g),()=>C.removeEventListener(cde,g)},[m,e.onSelect,e.disabled]);function g(){var C,N;x(),(N=(C=c.current).onSelect)==null||N.call(C,u.current)}function x(){f.setState("value",u.current,!0)}if(!m)return null;let{disabled:y,value:v,onSelect:w,forceMount:k,keywords:S,...j}=e;return h.createElement(Cw.div,{ref:Sx(a,t),...j,id:s,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!A,"data-disabled":!!y,"data-selected":!!A,onPointerMove:y||l.getDisablePointerSelection()?void 0:x,onClick:y?void 0:g},e.children)}),W$n=h.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...a}=e,o=vc(),l=h.useRef(null),c=h.useRef(null),d=vc(),u=ED(),f=H3(m=>s||u.filter()===!1?!0:m.search?m.filtered.groups.has(o):!0);L6(()=>u.group(o),[]),Yut(o,l,[e.value,e.heading,c]);let A=h.useMemo(()=>({id:o,forceMount:s}),[s]);return h.createElement(Cw.div,{ref:Sx(l,t),...a,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&h.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),TH(e,m=>h.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},h.createElement(Hut.Provider,{value:A},m))))}),Z$n=h.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=h.useRef(null),a=H3(o=>!o.search);return!n&&!a?null:h.createElement(Cw.div,{ref:Sx(s,t),...r,"cmdk-separator":"",role:"separator"})}),H$n=h.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,a=f2e(),o=H3(d=>d.search),l=H3(d=>d.selectedItemId),c=ED();return h.useEffect(()=>{e.value!=null&&a.setState("search",e.value)},[e.value]),h.createElement(Cw.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":l,id:c.inputId,type:"text",value:s?e.value:o,onChange:d=>{s||a.setState("search",d.target.value),n==null||n(d.target.value)}})}),X$n=h.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,a=h.useRef(null),o=h.useRef(null),l=H3(d=>d.selectedItemId),c=ED();return h.useEffect(()=>{if(o.current&&a.current){let d=o.current,u=a.current,f,A=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=d.offsetHeight;u.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return A.observe(d),()=>{cancelAnimationFrame(f),A.unobserve(d)}}},[]),h.createElement(Cw.div,{ref:Sx(a,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":l,"aria-label":r,id:c.listId},TH(e,d=>h.createElement("div",{ref:Sx(o,c.listInnerRef),"cmdk-list-sizer":""},d)))}),G$n=h.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:a,container:o,...l}=e;return h.createElement(_M,{open:n,onOpenChange:r},h.createElement(MM,{container:o},h.createElement(EM,{"cmdk-overlay":"",className:s}),h.createElement(mj,{"aria-label":e.label,"cmdk-dialog":"",className:a},h.createElement(Xut,{ref:t,...l}))))}),Y$n=h.forwardRef((e,t)=>H3(n=>n.filtered.count===0)?h.createElement(Cw.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),J$n=h.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...a}=e;return h.createElement(Cw.div,{ref:t,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},TH(e,o=>h.createElement("div",{"aria-hidden":!0},o)))}),u8=Object.assign(Xut,{List:X$n,Item:K$n,Input:H$n,Group:W$n,Separator:Z$n,Dialog:G$n,Empty:Y$n,Loading:J$n});function eFn(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function tFn(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Gut(e){let t=h.useRef(e);return L6(()=>{t.current=e}),t}var L6=typeof window>"u"?h.useEffect:h.useLayoutEffect;function c7(e){let t=h.useRef();return t.current===void 0&&(t.current=e()),t}function H3(e){let t=f2e(),n=()=>e(t.snapshot());return h.useSyncExternalStore(t.subscribe,n,n)}function Yut(e,t,n,r=[]){let s=h.useRef(),a=ED();return L6(()=>{var o;let l=(()=>{var d;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(d=u.current.textContent)==null?void 0:d.trim():s.current}})(),c=r.map(d=>d.trim());a.value(e,l,c),(o=t.current)==null||o.setAttribute(l7,l),s.current=l}),s}var nFn=()=>{let[e,t]=h.useState(),n=c7(()=>new Map);return L6(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function rFn(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function TH({asChild:e,children:t},n){return e&&h.isValidElement(t)?h.cloneElement(rFn(t),{ref:t.ref},n(t.props.children)):n(t)}var sFn={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function Jut({className:e,...t}){return i.jsx(u8,{"data-slot":"command",className:K("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",e),...t})}function iFn({title:e="Command Palette",description:t="Search for a command to run...",children:n,className:r,contentStyle:s,showCloseButton:a=!0,...o}){return i.jsxs(Ps,{...o,children:[i.jsxs(vi,{className:"sr-only",children:[i.jsx(ei,{children:e}),i.jsx(Si,{children:t})]}),i.jsxs(zs,{className:K("overflow-hidden p-0",r),style:s,showCloseButton:!1,children:[i.jsx(Jut,{className:"[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:n}),a&&i.jsxs(pj,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-0 right-2 flex h-12 items-center rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[i.jsx(Is,{}),i.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function eft({className:e,inputPrefix:t,...n}){return i.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[i.jsx(Fl,{className:"size-4 shrink-0 opacity-50"}),t,i.jsx(u8.Input,{"data-slot":"command-input",className:K("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...n})]})}function tft({className:e,...t}){return i.jsx(u8.List,{"data-slot":"command-list",className:K("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",e),...t})}function nft({...e}){return i.jsx(u8.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...e})}function vm({className:e,...t}){return i.jsx(u8.Group,{"data-slot":"command-group",className:K("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...t})}function qy({className:e,...t}){return i.jsx(u8.Separator,{"data-slot":"command-separator",className:K("bg-border -mx-1 h-px",e),...t})}function bl({className:e,...t}){return i.jsx(u8.Item,{"data-slot":"command-item",className:K("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}const A2e=[{scope:"issue",label:"Issues",aliases:["issue","issues"]},{scope:"library",label:"Library",aliases:["library","docs","doc"]},{scope:"chat",label:"Chats",aliases:["chat","chats"]},{scope:"agent",label:"Agents",aliases:["agent","agents"]},{scope:"project",label:"Projects",aliases:["project","projects"]},{scope:"skill",label:"Skills",aliases:["skill","skills"]}],rft=new Map(A2e.flatMap(e=>e.aliases.map(t=>[t,e.scope])));function IPe(e){return A2e.find(t=>t.scope===e)??null}function sft(e){return rft.get(e.trim().toLowerCase())??null}function aFn(e){var n;const t=e.trim().toLowerCase();return!t||/\s/.test(t)||rft.has(t)?null:((n=A2e.find(r=>r.aliases.some(s=>s.startsWith(t))))==null?void 0:n.scope)??null}function oFn(e){return/\s$/.test(e)?sft(e):null}function lFn(e,t){return e!==" "&&e!=="Tab"&&e!=="Enter"?null:sft(t)}const TPe=["title","description","comment"],TN=2,Sk=20,cFn=250,dFn=20;function t$(e,t){const n=e.trim().toLowerCase();return n?t.some(r=>r==null?void 0:r.toLowerCase().includes(n)):!0}function uFn(e){return`/library?${e.isDirectory?"directory":"path"}=${encodeURIComponent(e.path)}`}function fFn(){const[e,t]=h.useState(!1),[n,r]=h.useState(null),[s,a]=h.useState(""),[o,l]=h.useState("shortcut"),[c,d]=h.useState(!1),[u,f]=h.useState(!1),[A,m]=h.useState(null),[g,x]=h.useState(null),y=h.useRef(0),v=Yr(),{selectedOrganizationId:w}=jr(),{isMobile:k,setSidebarOpen:S}=jc(),j=s.trim(),[C,N]=h.useState(""),P=Me({queryKey:V.instance.shortcutSettings,queryFn:()=>Ha.getShortcuts(),retry:!1}),M=P.data===void 0?P.isError?null:void 0:P.data,T=(Me({queryKey:V.organizations.intelligenceProfiles(w??"__none__"),queryFn:()=>_n.listIntelligenceProfiles(w),enabled:!!w&&e}).data??[]).some(Ue=>(Ue==null?void 0:Ue.purpose)==="reasoning"&&Ue.status==="configured");h.useEffect(()=>{function Ue(mt){mt.defaultPrevented||mt.isComposing||RVe(mt.target)||qk(mt,"commandPalette.open",M)&&(mt.preventDefault(),l("shortcut"),t(!0),k&&S(!1))}return document.addEventListener("keydown",Ue),()=>document.removeEventListener("keydown",Ue)},[k,S,M]),h.useEffect(()=>{function Ue(mt){var dt;const tt=mt instanceof CustomEvent&&((dt=mt.detail)==null?void 0:dt.source)==="primary-rail"?"primary-rail":"shortcut";l(tt),t(!0),k&&S(!1)}return document.addEventListener("rudder:open-command-palette",Ue),()=>document.removeEventListener("rudder:open-command-palette",Ue)},[k,S]),h.useEffect(()=>{e||(r(null),a(""),N(""),d(!1),f(!1),m(null),x(null))},[e]),h.useEffect(()=>{y.current+=1,d(!1),f(!1),m(null),x(null)},[j]),h.useEffect(()=>{if(!e||j.length<TN){N("");return}const Ue=window.setTimeout(()=>{N(j)},cFn);return()=>window.clearTimeout(Ue)},[e,j]);const R=C.length>=TN?C:"",_=n?IPe(n):null,D=n?null:aFn(s),U=D?IPe(D):null,$=Me({queryKey:["issues",w,"command-palette","list",Sk],queryFn:()=>lr.list(w,{limit:Sk}),enabled:!!w&&e&&(n===null||n==="issue")}),L=$.data??[],H=Me({queryKey:["issues",w,"command-palette","search",R,TPe.join(","),Sk],queryFn:()=>lr.list(w,{q:R,searchFields:TPe,limit:Sk}),enabled:!!w&&e&&R.length>0&&(n===null||n==="issue")}),X=H.data??[],F=Me({queryKey:["chats",w,"command-palette","search","all",R,Sk],queryFn:()=>Xn.list(w,"all",{q:R,limit:Sk}),enabled:!!w&&e&&R.length>0&&(n===null||n==="chat")}),Q=F.data??[],q=Me({queryKey:V.organizations.workspaceMentionFiles(w,j),queryFn:()=>_n.listWorkspaceMentionFiles(w,{query:j,limit:dFn}),enabled:!!w&&e&&n==="library"&&j.length>0}),B=q.data??{entries:[]},ee=Me({queryKey:V.agents.list(w),queryFn:()=>Nn.list(w),enabled:!!w&&e}),se=ee.data??[],re=h.useMemo(()=>new Map(se.map(Ue=>[Ue.id,Ue])),[se]),ne=Me({queryKey:V.projects.list(w),queryFn:()=>Mi.list(w),enabled:!!w&&e}),Ae=ne.data??[],Y=h.useMemo(()=>Ae.filter(Ue=>!Ue.archivedAt),[Ae]),ce=Me({queryKey:V.organizationSkills.list(w),queryFn:()=>nf.list(w),enabled:!!w&&e&&(n===null||n==="skill")}),Oe=ce.data??[];function Fe(Ue){t(!1),v(Ue)}function ke(Ue){r(Ue),a("")}function Ne(){r(null),a("")}function xe(){if(!w||j.length<TN)return;const Ue=y.current+1;y.current=Ue,d(!0),f(!0),m(null),x(null),_n.aiSearch(w,{query:j,scope:n??void 0}).then(mt=>{y.current===Ue&&x(mt)}).catch(mt=>{y.current===Ue&&m(mt instanceof Error?mt.message:"AI Search failed")}).finally(()=>{y.current===Ue&&f(!1)})}function ae(Ue){if(!n){const mt=oFn(Ue);if(mt){ke(mt);return}}a(Ue)}function fe(Ue){if(!n){const mt=lFn(Ue.key,s);if(mt){Ue.preventDefault(),ke(mt);return}}n&&Ue.key==="Backspace"&&s.length===0&&(Ue.preventDefault(),Ne())}const ve=h.useMemo(()=>n!==null&&n!=="issue"?[]:R.length>0?X:j.length>0?L.filter(Ue=>t$(j,[Ue.identifier,Ue.title])):L,[L,X,R,j,n]),Se=n===null||n==="chat"?Q:[],ze=n==="library"&&j.length>0?B.entries:[],ft=h.useMemo(()=>se.filter(Ue=>t$(j,[Ue.name,Ue.role,Ue.title,Ue.urlKey])),[se,j]),ie=n===null||n==="agent"?ft:[],me=h.useMemo(()=>Y.filter(Ue=>t$(j,[Ue.name,Ue.description,Ue.urlKey,Ue.status])),[Y,j]),we=n===null||n==="project"?me:[],Xe=h.useMemo(()=>Oe.filter(Ue=>t$(j,[Ue.name,Ue.description,Ue.key,Ue.slug,Ue.sourceLabel,Ue.sourcePath,Ue.sourceLocator])),[j,Oe]),ge=n===null||n==="skill"?Xe:[],te=_?`Search ${_.label}...`:"Search issues, chats, agents, projects, skills, library...",G=_?`No ${_.label.toLowerCase()} results found.`:"No results found.",oe=j.length>0?H:$,Ze=!!(w&&e)&&((n===null||n==="issue")&&oe.isFetching&&oe.data===void 0||(n===null||n==="chat")&&j.length>0&&F.isFetching&&F.data===void 0||n==="library"&&j.length>0&&q.isFetching&&q.data===void 0||(n===null||n==="agent")&&ee.isFetching&&ee.data===void 0||(n===null||n==="project")&&ne.isFetching&&ne.data===void 0||(n===null||n==="skill")&&ce.isFetching&&ce.data===void 0),Te=!!(w&&e)&&((n===null||n==="issue")&&oe.isFetching||(n===null||n==="chat")&&j.length>0&&F.isFetching||n==="library"&&j.length>0&&q.isFetching||(n===null||n==="agent")&&ee.isFetching||(n===null||n==="project")&&ne.isFetching||(n===null||n==="skill")&&ce.isFetching),Be=ve.length>0||Se.length>0||ze.length>0||ie.length>0||we.length>0||ge.length>0,it=n!==null&&n!=="issue"&&n!=="chat"?!0:j.length<TN||R===j,lt=T&&j.length>=TN&&it&&!Te&&!Be&&!c;return i.jsxs(iFn,{open:e,onOpenChange:Ue=>{t(Ue),Ue&&k&&S(!1)},contentStyle:k?void 0:{left:"50vw",top:"50vh"},className:["command-palette-content glass-popover command-palette-glass sm:max-w-2xl",o==="primary-rail"?"command-palette-content--from-rail":null,Ze?"command-palette-content--searching":null].filter(Boolean).join(" "),children:[i.jsx(eft,{placeholder:te,value:s,onValueChange:ae,onKeyDown:fe,inputPrefix:_?i.jsxs("span",{className:"inline-flex h-6 shrink-0 items-center gap-1 rounded-sm border bg-muted px-2 text-xs font-medium text-muted-foreground",children:[_.label,i.jsx("button",{type:"button","aria-label":`Clear ${_.label} search scope`,className:"-mr-1 inline-flex h-4 w-4 items-center justify-center rounded-sm hover:bg-background hover:text-foreground",onMouseDown:Ue=>Ue.preventDefault(),onClick:Ne,children:i.jsx(Is,{className:"h-3 w-3"})})]}):void 0,className:"pr-8"}),i.jsxs(tft,{children:[!(n==="library"&&j.length===0)&&i.jsx(nft,{children:Ze?i.jsxs("span",{className:"inline-flex items-center justify-center gap-2 text-muted-foreground",children:[i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}),"Searching..."]}):u?i.jsxs("span",{className:"inline-flex items-center justify-center gap-2 text-muted-foreground",children:[i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}),"Searching..."]}):A?i.jsx("span",{className:"text-destructive",children:A}):c&&(g==null?void 0:g.results.length)===0?"Found 0 results":G}),lt&&i.jsxs(bl,{value:`ai search ${j}`,onSelect:xe,children:[i.jsx(Hh,{className:"mr-2 h-4 w-4 text-amber-500"}),i.jsx("span",{children:"AI Search"})]}),c&&(g||A)&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsxs("div",{className:"flex items-center justify-between gap-3 px-2 py-2 text-sm",children:[i.jsx("span",{className:"font-medium",children:"AI Search"}),g&&i.jsxs("span",{className:"text-muted-foreground",children:["Found ",g.results.length," result",g.results.length===1?"":"s"]})]}),i.jsxs(vm,{children:[((g==null?void 0:g.results)??[]).map(Ue=>i.jsxs(bl,{value:`${j} ${Ue.title} ${Ue.preview??""} ${Ue.reason??""}`,onSelect:()=>Fe(Ue.href),children:[i.jsx(Hh,{className:"mr-2 h-4 w-4 text-amber-500"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.title}),(Ue.reason??Ue.preview)&&i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:Ue.reason??Ue.preview})]}),i.jsx("span",{className:"ml-2 hidden text-xs capitalize text-muted-foreground sm:inline",children:Ue.kind.replace("_"," ")})]},Ue.key)),A&&i.jsxs(bl,{value:`retry ai search ${j}`,onSelect:xe,children:[i.jsx(Hh,{className:"mr-2 h-4 w-4"}),"Try AI Search again"]})]})]}),U&&i.jsx(vm,{heading:"Scope",children:i.jsxs(bl,{value:`${s} search in ${U.label}`,onSelect:()=>ke(U.scope),children:[i.jsx("span",{className:"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border text-[10px] text-muted-foreground",children:"/"}),i.jsxs("span",{className:"flex-1",children:["Search in ",U.label]})]})}),n===null&&i.jsxs(vm,{heading:"Pages",children:[i.jsxs(bl,{value:"dashboard",onSelect:()=>Fe("/dashboard"),children:[i.jsx(yx,{className:"mr-2 h-4 w-4"}),"Dashboard"]}),i.jsxs(bl,{value:"messenger chat conversations",onSelect:()=>Fe("/messenger"),children:[i.jsx(pa,{className:"mr-2 h-4 w-4"}),"Messenger"]}),i.jsxs(bl,{value:"issues",onSelect:()=>Fe("/issues"),children:[i.jsx(qh,{className:"mr-2 h-4 w-4"}),"Issues"]}),i.jsxs(bl,{value:"projects",onSelect:()=>Fe("/projects"),children:[i.jsx(e6,{className:"mr-2 h-4 w-4"}),"Projects"]}),i.jsxs(bl,{value:"goals targets",onSelect:()=>Fe("/goals"),children:[i.jsx(ud,{className:"mr-2 h-4 w-4"}),"Goals"]}),i.jsxs(bl,{value:"heartbeats activity runs",onSelect:()=>Fe("/heartbeats"),children:[i.jsx(Cx,{className:"mr-2 h-4 w-4"}),"Heartbeats"]}),i.jsxs(bl,{value:"agents",onSelect:()=>Fe("/agents"),children:[i.jsx(Ul,{className:"mr-2 h-4 w-4"}),"Agents"]}),i.jsxs(bl,{value:"skills",onSelect:()=>Fe(MAe),children:[i.jsx(wc,{className:"mr-2 h-4 w-4 text-[#2f80ed]"}),"Skills"]}),i.jsxs(bl,{value:"costs billing spend",onSelect:()=>Fe("/costs"),children:[i.jsx(Nx,{className:"mr-2 h-4 w-4"}),"Costs"]}),i.jsxs(bl,{value:"activity history",onSelect:()=>Fe("/activity"),children:[i.jsx(lT,{className:"mr-2 h-4 w-4"}),"Activity"]})]}),n==="library"&&j.length===0&&i.jsx(vm,{heading:"Library",children:i.jsx("div",{className:"px-2 py-6 text-center text-sm text-muted-foreground",children:"Type to search Library"})}),ve.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Issues",children:ve.slice(0,10).map(Ue=>i.jsxs(bl,{value:j.length>0?`${j} ${Ue.identifier??""} ${Ue.title}`:`${Ue.identifier??""} ${Ue.title}`,onSelect:()=>Fe(`/issues/${Ue.identifier??Ue.id}`),children:[i.jsx(ni,{status:Ue.status,className:"mr-2"}),i.jsx("span",{className:"text-muted-foreground mr-2 font-mono text-xs",children:Ue.identifier??Ue.id.slice(0,8)}),i.jsx("span",{className:"flex-1 truncate",children:Ue.title}),Ue.assigneeAgentId&&(()=>{const mt=re.get(Ue.assigneeAgentId);return mt?i.jsx(vu,{name:mt.name,icon:mt.icon,role:mt.role,size:"sm",className:"ml-2 hidden sm:inline-flex"}):null})()]},Ue.id))})]}),j.length>0&&Se.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Chats",children:Se.slice(0,10).map(Ue=>{const mt=Ue.searchPreview??Ue.latestReplyPreview??Ue.summary,tt=Bi(Ue.lastMessageAt??Ue.updatedAt,{compactDate:!0});return i.jsxs(bl,{value:`${j} ${Ue.title} ${mt??""}`,onSelect:()=>Fe(`/messenger/chat/${Ue.id}`),children:[i.jsx(Yfe,{className:"mr-2 h-4 w-4"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.title}),mt&&i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:mt})]}),i.jsx("span",{className:"ml-2 hidden text-xs text-muted-foreground sm:inline",children:tt})]},Ue.id)})})]}),ze.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Library",children:ze.slice(0,10).map(Ue=>{const mt=Ue.isDirectory?wo:Fi;return i.jsxs(bl,{value:`${j} ${Ue.displayLabel??Ue.name} ${Ue.path}`,onSelect:()=>Fe(uFn(Ue)),children:[i.jsx(mt,{className:"mr-2 h-4 w-4"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.displayLabel??Ue.name}),i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:Ue.path})]}),i.jsx("span",{className:"ml-2 hidden text-xs text-muted-foreground sm:inline",children:Ue.isDirectory?"Folder":"File"})]},`${Ue.isDirectory?"directory":"file"}:${Ue.path}`)})})]}),ie.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Agents",children:ie.slice(0,10).map(Ue=>i.jsxs(bl,{value:`${Ue.name} ${Ue.role} ${Ue.title??""} ${Ue.urlKey}`,onSelect:()=>Fe(BA(Ue)),children:[i.jsx(Ul,{className:"mr-2 h-4 w-4"}),Ue.name,i.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:Ue.role})]},Ue.id))})]}),we.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Projects",children:we.slice(0,10).map(Ue=>i.jsxs(bl,{value:`${Ue.name} ${Ue.description??""} ${Ue.urlKey} ${Ue.status}`,onSelect:()=>Fe(nT(Ue)),children:[i.jsx(uo,{color:Ue.color,icon:Ue.icon,size:"sm",className:"mr-2"}),Ue.name]},Ue.id))})]}),ge.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(qy,{}),i.jsx(vm,{heading:"Skills",children:ge.slice(0,10).map(Ue=>i.jsxs(bl,{value:`${Ue.name} ${Ue.description??""} ${Ue.key} ${Ue.slug} ${Ue.sourceLabel??""}`,onSelect:()=>Fe(Bj(Ue.id)),children:[i.jsx(wc,{className:"mr-2 h-4 w-4 text-[#2f80ed]"}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate",children:Ue.name}),Ue.description?i.jsx("span",{className:"truncate text-xs text-muted-foreground",children:Ue.description}):null]}),i.jsx("span",{className:"ml-2 hidden text-xs text-muted-foreground sm:inline",children:Ue.sourceLabel??Ue.sourceBadge})]},Ue.id))})]})]})]})}function AFn(e){if(!e)return null;const t=new Date(e).getTime();if(Number.isNaN(t))return null;const n=Date.now()-t;if(n<6e4)return"just now";const r=Math.round(n/6e4);if(r<60)return`${r}m ago`;const s=Math.round(r/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}function hFn(e){return e.envFileChanged&&e.reason==="backend_changes_and_pending_migrations"?"Environment configuration changed and migrations are pending.":e.envFileChanged?"Environment configuration changed since this server booted.":e.reason==="backend_changes_and_pending_migrations"?"Backend files changed and migrations are pending.":e.reason==="pending_migrations"?"Pending migrations need a fresh boot.":"Backend files changed since this server booted."}function mFn(e,t){const n=AFn(e.lastChangedAt),r=[],s=Pn();if(n&&r.push(`Updated ${n}.`),r.push("Restart pnpm dev after the active work is safe to interrupt."),e.changedPathsSample.length>0){const a=e.changedPathsSample.slice(0,2).join(", "),o=e.changedPathCount>2?` +${e.changedPathCount-2} more`:"";r.push(`Changed: ${a}${o}.`)}if(e.pendingMigrations.length>0){const a=e.pendingMigrations.slice(0,2).join(", "),o=e.pendingMigrations.length>2?` +${e.pendingMigrations.length-2} more`:"";r.push(`Pending migrations: ${a}${o}.`)}return{id:E_,title:"Restart required",body:`${hFn(e)} ${r.join(" ")}`.trim(),tone:"warn",persistent:!0,...s?{action:{label:"Restart Rudder",onClick:async()=>{try{await s.restart()}catch(a){throw t({title:"Could not restart Rudder",body:a instanceof Error?a.message:"Try restarting Rudder manually.",tone:"error"}),a}}}}:{}}}function pFn(e){return JSON.stringify({reason:e.reason,lastChangedAt:e.lastChangedAt,changedPathCount:e.changedPathCount,changedPathsSample:e.changedPathsSample,envFileChanged:e.envFileChanged,pendingMigrations:e.pendingMigrations,lastRestartAt:e.lastRestartAt})}function gFn({devServer:e}){const{dismissToast:t,pushToast:n}=ss(),r=h.useRef(null),s=e!=null&&e.enabled&&e.restartRequired?pFn(e):null;return h.useEffect(()=>{if(!e||!s){t(E_),r.current=null;return}return r.current&&t(r.current),r.current=n({...mFn(e,n),dedupeKey:`dev-restart:${s}`}),()=>{t(E_),r.current=null}},[s,t,n]),null}function xFn({visible:e}){const{t}=is(),n=br(),{selectedOrganizationId:r}=jr(),{openNewIssue:s}=ii(),a=ihe(r),o=h.useMemo(()=>[{type:"link",to:"/messenger",label:"Messenger",icon:pa,badge:a.inbox,badgeTone:"danger"},{type:"link",to:"/issues",label:t("common.issues"),icon:qh},{type:"action",label:t("common.create"),icon:zBe,onClick:()=>s()},{type:"link",to:"/agents",label:t("common.agents"),icon:FBe}],[s,a.inbox,t]);return i.jsx("nav",{className:K("fixed bottom-0 left-0 right-0 z-30 border-t border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85 transition-transform duration-200 ease-out md:hidden pb-[env(safe-area-inset-bottom)]",e?"translate-y-0":"translate-y-full"),"aria-label":t("common.mobileNavigation"),children:i.jsx("div",{className:"grid h-16 grid-cols-4 px-1",children:o.map(l=>{if(l.type==="action"){const d=l.icon,u=/\/issues\/new(?:\/|$)/.test(n.pathname);return i.jsxs("button",{type:"button",onClick:l.onClick,className:K("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-[10px] font-medium transition-colors",u?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[i.jsx(d,{className:"h-[18px] w-[18px]"}),i.jsx("span",{className:"truncate",children:l.label})]},l.label)}const c=l.icon;return i.jsx(Pj,{to:l.to,className:({isActive:d})=>K("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-[10px] font-medium transition-colors",d?"text-foreground":"text-muted-foreground hover:text-foreground"),children:({isActive:d})=>i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"relative",children:[i.jsx(c,{className:K("h-[18px] w-[18px]",d&&"stroke-[2.3]")}),l.badge!=null&&l.badge>0&&i.jsx("span",{className:K("absolute -right-2 -top-2 rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none",l.badgeTone==="danger"?"bg-red-500 text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]":"bg-primary text-primary-foreground"),children:l.badge>99?"99+":l.badge})]}),i.jsx("span",{className:"truncate",children:l.label})]})},l.label)})})})}function h2e({className:e}){return i.jsxs(i.Fragment,{children:[i.jsx("img",{src:"/brands/opencode-logo-light-square.svg",alt:"OpenCode",className:K("dark:hidden",e)}),i.jsx("img",{src:"/brands/opencode-logo-dark-square.svg",alt:"OpenCode",className:K("hidden dark:block",e)})]})}const bFn=[{value:"claude_local",label:"Claude Code",icon:Hh,desc:"Local Claude agent",recommended:!0},{value:"codex_local",label:"Codex",icon:VK,desc:"Local Codex agent",recommended:!0},{value:"gemini_local",label:"Gemini CLI",icon:Wfe,desc:"Local Gemini agent"},{value:"opencode_local",label:"OpenCode",icon:h2e,desc:"Local multi-provider agent"},{value:"pi_local",label:"Pi",icon:AE,desc:"Local Pi agent"},{value:"cursor",label:"Cursor",icon:IBe,desc:"Local Cursor agent"},{value:"openclaw_gateway",label:"OpenClaw Gateway",icon:Ul,desc:"Invoke OpenClaw via gateway protocol"}];function yFn(){const{newAgentOpen:e,closeNewAgent:t,openNewIssue:n}=ii(),{selectedOrganizationId:r}=jr(),s=Yr(),[a,o]=h.useState(!1),{data:l}=Me({queryKey:V.agents.list(r),queryFn:()=>Nn.list(r),enabled:!!r&&e}),c=(l??[]).find(A=>A.role==="ceo");function d(){t(),n({assigneeAgentId:c==null?void 0:c.id,title:"Create a new agent",description:"(type in what kind of agent you want here)"})}function u(){o(!0)}function f(A){t(),o(!1),s(`/agents/new?agentRuntimeType=${encodeURIComponent(A)}`)}return i.jsx(Ps,{open:e,onOpenChange:A=>{A||(o(!1),t())},children:i.jsxs(zs,{showCloseButton:!1,className:"sm:max-w-md p-0 gap-0 overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[i.jsx("span",{className:"text-sm text-muted-foreground",children:"Add a new agent"}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{o(!1),t()},children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]}),i.jsx("div",{className:"p-6 space-y-6",children:a?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-2",children:[i.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",onClick:()=>o(!1),children:[i.jsx(Kx,{className:"h-3.5 w-3.5"}),"Back"]}),i.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose your runtime type for advanced setup."})]}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:bFn.map(A=>i.jsxs("button",{className:K("flex flex-col items-center gap-1.5 rounded-md border border-border p-3 text-xs transition-colors hover:bg-accent/50 relative"),onClick:()=>f(A.value),children:[A.recommended&&i.jsx("span",{className:"absolute -top-1.5 right-1.5 bg-green-500 text-white text-[9px] font-semibold px-1.5 py-0.5 rounded-full leading-none",children:"Recommended"}),i.jsx(A.icon,{className:"h-4 w-4"}),i.jsx("span",{className:"font-medium",children:A.label}),i.jsx("span",{className:"text-muted-foreground text-[10px]",children:A.desc})]},A.value))})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"text-center space-y-3",children:[i.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-accent",children:i.jsx(Hh,{className:"h-6 w-6 text-foreground"})}),i.jsx("p",{className:"text-sm text-muted-foreground",children:"We recommend letting your CEO handle agent setup — they can choose the right role, permissions, skills, and runtime."})]}),i.jsxs(le,{className:"w-full",size:"lg",onClick:d,children:[i.jsx(Ul,{className:"h-4 w-4 mr-2"}),"Ask Agent"]}),i.jsx("div",{className:"text-center",children:i.jsx("button",{className:"text-xs text-muted-foreground hover:text-foreground underline underline-offset-2 transition-colors",onClick:u,children:"I want advanced configuration myself"})})]})})]})})}const f8={uploadImage:async(e,t,n)=>{const r=await t.arrayBuffer(),s=new File([r],t.name,{type:t.type}),a=new FormData;return n&&n.trim().length>0&&a.append("namespace",n.trim()),a.append("file",s),Re.postForm(`/orgs/${e}/assets/images`,a)},uploadOrganizationLogo:async(e,t)=>{const n=await t.arrayBuffer(),r=new File([n],t.name,{type:t.type}),s=new FormData;return s.append("file",r),Re.postForm(`/orgs/${e}/logo`,s)}},_Pe={organization:"Organization",team:"Team",agent:"Agent",task:"Task"};function vFn(){const{newGoalOpen:e,newGoalDefaults:t,closeNewGoal:n}=ii(),{selectedOrganizationId:r,selectedOrganization:s}=jr(),a=Vn(),[o,l]=h.useState(""),[c,d]=h.useState(""),[u,f]=h.useState("planned"),[A,m]=h.useState("task"),[g,x]=h.useState(""),[y,v]=h.useState(!1),[w,k]=h.useState(0),[S,j]=h.useState(!1),[C,N]=h.useState(!1),[P,M]=h.useState(!1),E=h.useRef(null),T=g||t.parentId||"",{data:R}=Me({queryKey:V.goals.list(r),queryFn:()=>LA.list(r),enabled:!!r&&e}),_=xt({mutationFn:X=>LA.create(r,X),onSuccess:()=>{a.invalidateQueries({queryKey:V.goals.list(r)}),U(),n()}}),D=xt({mutationFn:async X=>{if(!r)throw new Error("No organization selected");return f8.uploadImage(r,X,"goals/drafts")}});function U(){k(X=>X+1),l(""),d(""),f("planned"),m("task"),x(""),v(!1)}function $(){!r||!o.trim()||_.mutate({title:o.trim(),description:g0e(c),status:u,level:A,...T?{parentId:T}:{}})}function L(X){X.key==="Enter"&&(X.metaKey||X.ctrlKey)&&(X.preventDefault(),$())}const H=(R??[]).find(X=>X.id===T);return i.jsx(Ps,{open:e,onOpenChange:X=>{X||(U(),n())},children:i.jsxs(zs,{showCloseButton:!1,className:K("p-0 gap-0",y?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:L,children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s&&i.jsx("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:s.name.slice(0,3).toUpperCase()}),i.jsx("span",{className:"text-muted-foreground/60",children:"›"}),i.jsx("span",{children:t.parentId?"New sub-goal":"New goal"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>v(!y),children:y?i.jsx(uE,{className:"h-3.5 w-3.5"}):i.jsx(n3,{className:"h-3.5 w-3.5"})}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{U(),n()},children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),i.jsx("div",{className:"px-4 pt-4 pb-2 shrink-0",children:i.jsx("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:o,onChange:X=>l(X.target.value),onKeyDown:X=>{var F;X.key==="Tab"&&!X.shiftKey&&(X.preventDefault(),(F=E.current)==null||F.focus())},autoFocus:!0})}),i.jsx("div",{className:"px-4 pb-2",children:i.jsx(ku,{ref:E,engine:"codemirror",documentIdentity:`new-goal:${w}`,value:c,onChange:d,placeholder:"Add description...",bordered:!1,contentClassName:K("text-sm text-muted-foreground",y?"min-h-[220px]":"min-h-[120px]"),imageUploadHandler:async X=>(await D.mutateAsync(X)).contentPath})}),i.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[i.jsxs(ts,{open:S,onOpenChange:j,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:i.jsx(Qs,{status:u})})}),i.jsx(ns,{className:"w-40 p-1",align:"start",children:wK.map(X=>i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",X===u&&"bg-accent"),onClick:()=>{f(X),j(!1)},children:X},X))})]}),i.jsxs(ts,{open:C,onOpenChange:N,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[i.jsx(CBe,{className:"h-3 w-3 text-muted-foreground"}),_Pe[A]??A]})}),i.jsx(ns,{className:"w-40 p-1",align:"start",children:Jue.map(X=>i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",X===A&&"bg-accent"),onClick:()=>{m(X),N(!1)},children:_Pe[X]??X},X))})]}),i.jsxs(ts,{open:P,onOpenChange:M,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[i.jsx(ud,{className:"h-3 w-3 text-muted-foreground"}),H?H.title:"Parent goal"]})}),i.jsxs(ns,{className:"w-48 p-1",align:"start",children:[i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!T&&"bg-accent"),onClick:()=>{x(""),M(!1)},children:"No parent"}),(R??[]).map(X=>i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",X.id===T&&"bg-accent"),onClick:()=>{x(X.id),M(!1)},children:X.title},X.id))]})]})]}),i.jsx("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:i.jsx(le,{size:"sm",disabled:!o.trim()||_.isPending,onClick:$,children:_.isPending?"Creating…":t.parentId?"Create sub-goal":"Create goal"})})]})})}function wFn(e){const t=/^#?([0-9a-f]{3,6})$/i.exec(e.trim());if(!t)return null;let n=t[1];return n.length===3&&(n=n.split("").map(r=>`${r}${r}`).join("")),n.length!==6?null:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16)}}function One(e){const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Sne(e,t,n){return .2126*One(e)+.7152*One(t)+.0722*One(n)}function MPe(e,t){const n=Math.max(e,t),r=Math.min(e,t);return(n+.05)/(r+.05)}const EPe="#f8fafc",kFn="#111827";function DPe(e){const t=wFn(e);if(!t)return EPe;const n=Sne(t.r,t.g,t.b),r=Sne(248,250,252),s=Sne(17,24,39);return MPe(n,r)>=MPe(n,s)?EPe:kFn}function dde(e){const t=e.trim();return t.includes("/")&&t.slice(0,t.indexOf("/")).trim()||null}function jne(e,t="other"){return dde(e)??t}function OFn(e){const t=e.trim();return t.includes("/")?t.slice(t.indexOf("/")+1).trim():t}const m2e="rudder:issue-draft",p2e="rudder:issue-autosave",ift="rudder:issue-drafts",V_="rudder:issue-draft-changed",aft="rudder:new-issue-preferences";function A8(){try{return globalThis.localStorage??null}catch{return null}}function g2e(){var e;try{(e=globalThis.dispatchEvent)==null||e.call(globalThis,new Event(V_))}catch{}}function uc(e){return typeof e=="string"?e.trim():""}function N2(e){return e?!!(uc(e.title)||uc(e.description)||uc(e.projectId)||uc(e.assigneeValue)||uc(e.assigneeId)||uc(e.reviewerValue)||uc(e.goalId)||uc(e.priority)&&uc(e.priority)!=="medium"||uc(e.status)&&uc(e.status)!=="todo"||Array.isArray(e.labelIds)&&e.labelIds.length>0||uc(e.projectWorkspaceId)||uc(e.assigneeModelOverride)||uc(e.assigneeThinkingEffort)||e.assigneeChrome):!1}function SFn(){var e,t;try{return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}catch{return`draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}}function jFn(e){try{const t=A8(),n=(t==null?void 0:t.getItem(p2e))??(t==null?void 0:t.getItem(m2e));if(!n)return null;const r=JSON.parse(n);return e&&r.orgId&&r.orgId!==e?null:N2(r)?r:null}catch{return null}}function CFn(e){if(!N2(e))return;const t=A8();t==null||t.setItem(p2e,JSON.stringify(e)),t==null||t.removeItem(m2e),g2e()}function RPe(){const e=A8();e==null||e.removeItem(p2e),e==null||e.removeItem(m2e),g2e()}function oft(){var e;try{const t=(e=A8())==null?void 0:e.getItem(aft);if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};const r={};for(const[s,a]of Object.entries(n)){if(!s||!a||typeof a!="object"||Array.isArray(a))continue;const o=a;r[s]={assigneeValue:uc(o.assigneeValue),reviewerValue:uc(o.reviewerValue),projectId:uc(o.projectId),updatedAt:uc(o.updatedAt)||new Date(0).toISOString()}}return r}catch{return{}}}function NFn(e){return e?oft()[e]??null:null}function PFn(e,t){if(!e)return;const n=A8();if(!n)return;const r={...oft(),[e]:{assigneeValue:uc(t.assigneeValue),reviewerValue:uc(t.reviewerValue),projectId:uc(t.projectId),updatedAt:new Date().toISOString()}};n.setItem(aft,JSON.stringify(r))}function _H(){var e;try{const t=(e=A8())==null?void 0:e.getItem(ift);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.filter(N2):[]}catch{return[]}}function x2e(e){var t;(t=A8())==null||t.setItem(ift,JSON.stringify(e)),g2e()}function LPe(e){return JSON.stringify({orgId:e.orgId??null,title:e.title,description:e.description,status:e.status,priority:e.priority,labelIds:e.labelIds??[],assigneeValue:e.assigneeValue??"",assigneeId:e.assigneeId??"",reviewerValue:e.reviewerValue??"",projectId:e.projectId??"",goalId:e.goalId??"",projectWorkspaceId:e.projectWorkspaceId??"",assigneeModelOverride:e.assigneeModelOverride??"",assigneeThinkingEffort:e.assigneeThinkingEffort??"",assigneeChrome:!!e.assigneeChrome,useIsolatedExecutionWorkspace:!!e.useIsolatedExecutionWorkspace})}function lft(e){return _H().filter(t=>!e||!t.orgId||t.orgId===e).sort((t,n)=>Date.parse(n.updatedAt)-Date.parse(t.updatedAt))}function IFn(e,t){return e?lft(t).find(n=>n.id===e)??null:null}function TFn(e){if(!N2(e))return null;const t=new Date().toISOString(),n={...e,id:SFn(),createdAt:t,updatedAt:t};return x2e([n,..._H()]),n}function _Fn(e,t){if(!e||!N2(t))return null;const n=_H(),r=n.findIndex(l=>l.id===e);if(r===-1)return null;const s=n[r];if(LPe(s)===LPe(t))return s;const a={...t,id:e,createdAt:s.createdAt,updatedAt:new Date().toISOString()},o=[...n];return o[r]=a,x2e(o),a}function ude(e){e&&x2e(_H().filter(t=>t.id!==e))}function MFn(e){const t=e.title.trim()||"Untitled issue draft";return{id:e.id,title:t,description:e.description.trim(),assigneeValue:e.assigneeValue,assigneeId:e.assigneeId,projectId:e.projectId,status:e.status||"todo",priority:e.priority,createdAt:e.createdAt,updatedAt:e.updatedAt}}function aq(e){return lft(e).map(MFn)}function zPe(e){const t=!!(e.defaults.assigneeAgentId||e.defaults.assigneeUserId),n=!!(e.defaults.reviewerAgentId||e.defaults.reviewerUserId);return{status:e.defaults.status??e.draft.status??"todo",priority:e.defaults.priority??e.draft.priority??"",projectId:e.defaultProjectId||e.draft.projectId,goalId:e.defaults.goalId??e.draft.goalId??"",labelIds:e.defaults.labelIds??e.draft.labelIds??[],assigneeValue:t?e.defaultAssigneeValue:e.draft.assigneeValue??e.draft.assigneeId??"",reviewerValue:n?e.defaultReviewerValue:e.draft.reviewerValue??""}}function EFn(e){var o,l,c;const t=(o=e.explicitProjectId)==null?void 0:o.trim();if(t)return t;const n=(l=new URLSearchParams(e.search??"").get("projectId"))==null?void 0:l.trim();if(n&&e.projects.some(d=>d.id===n))return n;const s=fl(e.pathname).match(/^\/projects\/([^/?#]+)/);if(!(s!=null&&s[1]))return"";const a=decodeURIComponent(s[1]).trim();return a?((c=e.projects.find(d=>d.id===a||S3(d)===a))==null?void 0:c.id)??"":""}function DFn(e){var c,d;const t=e.organizations.find(u=>u.id===e.orgId),n=t?Oc(t).trim():"",r=u=>n?`/${n}${u}`:u,s=((c=e.openContextLocation)==null?void 0:c.pathname)??r("/issues"),a=fl(s),o=/^\/issues(?:\/|$)/.test(a),l=e.issue.identifier??e.issue.id;return o?{destination:"issues",detailHref:r(`/issues/${l}`),breadcrumbLabel:"Issues",breadcrumbHref:`${r(a)}${((d=e.openContextLocation)==null?void 0:d.search)??""}`}:{destination:"messenger",detailHref:r(`/messenger/issues/${l}`),breadcrumbLabel:"Messenger",breadcrumbHref:r("/messenger/issues")}}function RFn(e){return{title:e.title.trim(),description:g0e(e.description),...e.parentId?{parentId:e.parentId}:{},status:e.status,priority:e.priority||"medium",...e.assigneeAgentId?{assigneeAgentId:e.assigneeAgentId}:{},...e.assigneeUserId?{assigneeUserId:e.assigneeUserId}:{},...e.reviewerAgentId?{reviewerAgentId:e.reviewerAgentId}:{},...e.reviewerUserId?{reviewerUserId:e.reviewerUserId}:{},...e.projectId?{projectId:e.projectId}:{},goalId:e.goalId||null,...e.labelIds.length>0?{labelIds:e.labelIds}:{},...e.projectWorkspaceId?{projectWorkspaceId:e.projectWorkspaceId}:{},...e.assigneeAgentRuntimeOverrides?{assigneeAgentRuntimeOverrides:e.assigneeAgentRuntimeOverrides}:{}}}const LFn=800,cft=new Set(["claude_local","codex_local","opencode_local"]),zFn="image/*,application/pdf,text/plain,text/markdown,application/json,text/csv,text/html,.md,.markdown",Cne="h-auto min-h-12 w-full py-2",n$={claude_local:[{value:"",label:"Default"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}],opencode_local:[{value:"",label:"Default"},{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"max",label:"Max"}]};function $Fn(e){const t=e.agentRuntimeType??null;if(!t||!cft.has(t))return null;const n={};e.modelOverride&&(n.model=e.modelOverride),e.thinkingEffortOverride&&(t==="codex_local"?n.modelReasoningEffort=e.thinkingEffortOverride:t==="opencode_local"?n.variant=e.thinkingEffortOverride:t==="claude_local"?n.effort=e.thinkingEffortOverride:t==="opencode_local"&&(n.variant=e.thinkingEffortOverride)),t==="claude_local"&&e.chrome&&(n.chrome=!0);const r={};return Object.keys(n).length>0&&(r.agentRuntimeConfig=n),Object.keys(r).length>0?r:null}function $Pe(e){return e.size<1024?`${e.size} B`:e.size<1024*1024?`${(e.size/1024).toFixed(1)} KB`:`${(e.size/(1024*1024)).toFixed(1)} MB`}const Nne=[{value:"backlog",label:"Backlog",color:W9.backlog},{value:"todo",label:"Todo",color:W9.todo},{value:"in_progress",label:"In Progress",color:W9.in_progress},{value:"in_review",label:"In Review",color:W9.in_review},{value:"done",label:"Done",color:W9.done}],FPe=LFt;function _N(e){var t,n,r,s,a,o,l,c;return e?((t=e.codebase)==null?void 0:t.scope)==="organization"||((n=e.codebase)==null?void 0:n.scope)==="none"?((r=e.executionWorkspacePolicy)==null?void 0:r.defaultProjectWorkspaceId)??"":((s=e.executionWorkspacePolicy)==null?void 0:s.defaultProjectWorkspaceId)??((o=(a=e.workspaces)==null?void 0:a.find(d=>d.isPrimary))==null?void 0:o.id)??((c=(l=e.workspaces)==null?void 0:l[0])==null?void 0:c.id)??"":""}function FFn(){var Vo,yd,Pc,eo,$a,_s;const{newIssueOpen:e,newIssueDefaults:t,closeNewIssue:n}=ii(),{organizations:r,selectedOrganizationId:s,selectedOrganization:a}=jr(),o=Vn(),{pushToast:l}=ss(),c=br(),d=Yr(),[u,f]=h.useState(""),[A,m]=h.useState(""),[g,x]=h.useState("todo"),[y,v]=h.useState(""),[w,k]=h.useState([]),[S,j]=h.useState(""),[C,N]=h.useState(""),[P,M]=h.useState(""),[E,T]=h.useState(""),[R,_]=h.useState(""),[D,U]=h.useState(""),[$,L]=h.useState(!1),[H,X]=h.useState(""),[F,Q]=h.useState(""),[q,B]=h.useState(!1),[ee,se]=h.useState(!1),[re,ne]=h.useState(null),[Ae,Y]=h.useState([]),[ce,Oe]=h.useState(!1),[Fe,ke]=h.useState(null),[Ne,xe]=h.useState(0),[ae,fe]=h.useState(null),ve=h.useRef(null),Se=h.useRef(null),ze=h.useRef(null),ft=h.useRef(null),ie=re??s,me=r.find(et=>et.id===ie)??a,we=t.draftId??null,[Xe,ge]=h.useState(!1),[te,G]=h.useState(!1),[oe,Ze]=h.useState(!1),[Te,Be]=h.useState(!1),[it,lt]=h.useState(!1),Ue=h.useRef(null),mt=h.useRef(null),tt=h.useRef(null),dt=h.useRef(null),{data:at}=Me({queryKey:V.agents.list(ie),queryFn:()=>Nn.list(ie),enabled:!!ie&&e}),{data:Pe}=Me({queryKey:V.projects.list(ie),queryFn:()=>Mi.list(ie),enabled:!!ie&&e}),{data:$e}=Me({queryKey:V.goals.list(ie),queryFn:()=>LA.list(ie),enabled:!!ie&&e}),{data:ot}=Me({queryKey:V.issues.list(ie),queryFn:()=>lr.list(ie),enabled:!!ie&&e}),{data:ue}=Me({queryKey:V.issues.labels(ie),queryFn:()=>lr.listLabels(ie),enabled:!!ie&&e}),{data:Ie}=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),Ke=((Vo=Ie==null?void 0:Ie.user)==null?void 0:Vo.id)??((yd=Ie==null?void 0:Ie.session)==null?void 0:yd.userId)??null,De=h.useMemo(()=>(Pe??[]).filter(et=>!et.archivedAt),[Pe]),{orderedProjects:Je}=RE({projects:De,orgId:ie,userId:Ke}),_e=h.useMemo(()=>Nm(C),[C]),Ee=_e.assigneeAgentId,Ce=_e.assigneeUserId,kt=h.useMemo(()=>Nm(P),[P]),Qe=kt.assigneeAgentId,gt=kt.assigneeUserId,Nt=Ee?(at??[]).find(et=>et.id===Ee)??null:null,Gt=Qe?(at??[]).find(et=>et.id===Qe)??null:null,cn=(Nt==null?void 0:Nt.agentRuntimeType)??null,Rn=typeof(Nt==null?void 0:Nt.agentRuntimeConfig.model)=="string"?Nt.agentRuntimeConfig.model:"",nt=H||Rn,Qt=!!(cn&&cft.has(cn)),{data:st}=Me({queryKey:V.organizationSkills.list(ie??"__none__"),queryFn:()=>nf.list(ie),enabled:!!ie&&e&&!!Ee}),{data:Rt}=Me({queryKey:V.agents.skills(Ee??"__none__"),queryFn:()=>Nn.skills(Ee,ie),enabled:!!ie&&e&&!!Ee}),{data:Cn}=Me({queryKey:V.organizations.libraryDocuments(ie??"__none__"),queryFn:()=>_n.listLibraryDocuments(ie),enabled:!!ie&&e}),[zn,fs]=h.useState(null),as=(zn==null?void 0:zn.trim())??"",{data:sr}=Me({queryKey:["organizations",ie??"__none__","workspace-mention-files",as],queryFn:()=>_n.listWorkspaceMentionFiles(ie,{query:as,limit:as?50:200}),enabled:!!ie&&e});h.useEffect(()=>{if(!e){ze.current=null;return}ze.current||(ze.current={pathname:c.pathname,search:c.search})},[c.pathname,c.search,e]);const Kr=h.useMemo(()=>Qj({agent:Nt,orgUrlKey:(me==null?void 0:me.urlKey)??(a==null?void 0:a.urlKey)??"organization",organizationSkills:st,skillSnapshot:Rt}),[st,Rt,Nt,me==null?void 0:me.urlKey,a==null?void 0:a.urlKey]),yr=h.useMemo(()=>yE({agents:at,projects:Je,issues:ot,libraryDocuments:Cn,libraryFiles:sr==null?void 0:sr.entries,skillMentionOptions:Kr,currentUserId:Ke}),[at,ot,Ke,Cn,sr==null?void 0:sr.entries,Je,Kr]),{data:ht}=Me({queryKey:ie&&cn?V.agents.adapterModels(ie,cn):["agents","none","adapter-models",cn??"none"],queryFn:()=>Nn.adapterModels(ie,cn),enabled:!!ie&&e&&Qt}),Vt=h.useCallback(()=>{ve.current&&clearTimeout(ve.current),ve.current=null,Se.current=null},[]),We=h.useCallback(()=>{ve.current&&clearTimeout(ve.current),ve.current=null;const et=Se.current;if(Se.current=null,!!et){if(et.savedDraftId){_Fn(et.savedDraftId,et.draft);return}CFn(et.draft)}},[]),Tt=xt({mutationFn:async({orgId:et,stagedFiles:Hn,...dr})=>{const ca=await lr.create(et,dr),wi=[];for(const Ni of Hn)try{await lr.uploadAttachment(et,ca.id,Ni.file)}catch{wi.push(Ni.file.name)}return{issue:ca,orgId:et,failures:wi}},onSuccess:async({issue:et,orgId:Hn,failures:dr})=>{o.invalidateQueries({queryKey:V.issues.list(Hn)}),o.invalidateQueries({queryKey:V.issues.listTouchedByMe(Hn)}),o.invalidateQueries({queryKey:V.issues.listUnreadTouchedByMe(Hn)}),o.invalidateQueries({queryKey:V.sidebarBadges(Hn)}),o.setQueryData(V.issues.detail(et.identifier??et.id),et),o.setQueryData(V.issues.detail(et.id),et),Vt(),PFn(Hn,{assigneeValue:C,reviewerValue:P,projectId:E});const ca=et.identifier??et.id,wi=DFn({issue:et,orgId:Hn,organizations:r,openContextLocation:ze.current});dr.length>0&&l({title:`Created ${ca} with upload warnings`,body:`${dr.length} staged ${dr.length===1?"file":"files"} could not be added.`,tone:"warn",action:{label:`Open ${ca}`,href:wi.detailHref}}),fe(ca),await new Promise(vd=>setTimeout(vd,340)),RPe(),ude(Fe),pt(),n();const Ni=document;Ni.startViewTransition?await Ni.startViewTransition(()=>{d(wi.detailHref,{state:eq(wi.breadcrumbLabel,wi.breadcrumbHref)})}).finished.catch(()=>{}):d(wi.detailHref,{state:eq(wi.breadcrumbLabel,wi.breadcrumbHref)})}}),Mn=xt({mutationFn:et=>lr.createLabel(ie,et),onSuccess:async et=>{ie&&(await o.invalidateQueries({queryKey:V.issues.labels(ie)}),k(Hn=>[...new Set([...Hn,et.id])]),j(""))}}),tr=xt({mutationFn:async et=>{if(!ie)throw new Error("No organization selected");return f8.uploadImage(ie,et,"issues/drafts")}}),Ln=h.useCallback((et,Hn=null)=>{ve.current&&clearTimeout(ve.current),Se.current={draft:et,savedDraftId:Hn},ve.current=setTimeout(We,LFn)},[We]);h.useEffect(()=>{e&&N2({title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q})&&Ln({orgId:ie,title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q},Fe)},[u,A,g,y,w,C,P,E,R,D,H,F,q,ie,e,Fe,Ln]),h.useEffect(()=>{if(!e)return;ne(s);const et=ze.current??{pathname:c.pathname,search:c.search},Hn=EFn({explicitProjectId:t.projectId,pathname:et.pathname,search:et.search,projects:Je}),dr=NFn(s),ca=dr!=null&&dr.projectId&&Je.some(ai=>ai.id===dr.projectId)?dr.projectId:"",wi=Hn||ca,Ni=_v(t),vd=_v({assigneeAgentId:t.reviewerAgentId,assigneeUserId:t.reviewerUserId}),r1=Ni||(dr==null?void 0:dr.assigneeValue)||"",mf=vd||(dr==null?void 0:dr.reviewerValue)||"",el=IFn(we,s),_l=el??(we?null:jFn(s));if(ke(el?el.id:null),el&&N2(el)){const ai=zPe({defaults:{},draft:el,defaultProjectId:Hn,defaultAssigneeValue:Ni,defaultReviewerValue:vd}),tl=ai.projectId,wd=Je.find(pf=>pf.id===tl);f(el.title),m(el.description),x(ai.status),v(ai.priority),k(ai.labelIds),j(""),N(ai.assigneeValue),M(ai.reviewerValue),T(tl),_(ai.goalId),U(el.projectWorkspaceId??_N(wd)),X(el.assigneeModelOverride??""),Q(el.assigneeThinkingEffort??""),B(el.assigneeChrome??!1)}else if(t.title){f(t.title),m(t.description??""),x(t.status??"todo"),v(t.priority??""),k(t.labelIds??[]),j("");const ai=Je.find(tl=>tl.id===wi);T(wi),_(t.goalId??""),U(_N(ai)),N(r1),M(mf),X(""),Q(""),B(!1)}else if(_l&&N2(_l)){const ai=zPe({defaults:t,draft:_l,defaultProjectId:Hn,defaultAssigneeValue:Ni,defaultReviewerValue:vd}),tl=ai.projectId,wd=Je.find(pf=>pf.id===tl);f(_l.title),m(_l.description),x(ai.status),v(ai.priority),k(ai.labelIds),j(""),N(ai.assigneeValue),M(ai.reviewerValue),T(tl),_(ai.goalId),U(_l.projectWorkspaceId??_N(wd)),X(_l.assigneeModelOverride??""),Q(_l.assigneeThinkingEffort??""),B(_l.assigneeChrome??!1)}else{const ai=Je.find(tl=>tl.id===wi);f(""),m(""),x(t.status??"todo"),v(t.priority??""),k(t.labelIds??[]),j(""),T(wi),_(t.goalId??""),U(_N(ai)),N(r1),M(mf),X(""),Q(""),B(!1)}},[e,t,Je,we,s]),h.useEffect(()=>{if(!e){ft.current=null;return}const et=ft.current;et!==null&&et!==Ee&&(X(""),Q(""),B(!1)),ft.current=Ee},[e,Ee]),h.useEffect(()=>{if(!Qt){L(!1),X(""),Q(""),B(!1);return}(cn==="codex_local"?M_("Default",TV(nt)):cn==="opencode_local"?n$.opencode_local:n$.claude_local).some(Hn=>Hn.value===F)||Q("")},[Qt,cn,F,nt]),h.useEffect(()=>()=>{We()},[We]);function pt(){xe(et=>et+1),f(""),m(""),x("todo"),v(""),k([]),j(""),N(""),M(""),T(""),_(""),U(""),L(!1),X(""),Q(""),B(!1),se(!1),ne(null),Y([]),Oe(!1),lt(!1),ke(null),fe(null)}function vt(){We(),n()}function jt(et){et!==ie&&(ne(et),N(""),M(""),T(""),_(""),U(""),k([]),j(""),X(""),Q(""),B(!1))}function Zt(){TFn({orgId:ie,title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q})&&(Vt(),ude(Fe),RPe(),l({title:"Saved to Draft Issues",body:"Open Draft Issues from the Issues sidebar to continue it.",tone:"success"}),pt(),n())}function kr(){if(!ie||!oc||Tt.isPending||ae)return;fe(null);const et=$Fn({agentRuntimeType:cn,modelOverride:H,thinkingEffortOverride:F,chrome:q});Tt.mutate({orgId:ie,stagedFiles:Ae,...RFn({title:u,description:A,parentId:t.parentId,status:g,priority:y,assigneeAgentId:Ee,assigneeUserId:Ce,reviewerAgentId:Qe,reviewerUserId:gt,projectId:E,goalId:R,labelIds:w,projectWorkspaceId:D,assigneeAgentRuntimeOverrides:et})})}function xs(et){et.key==="Enter"&&(et.metaKey||et.ctrlKey)&&(et.preventDefault(),kr())}function la(et){et.length!==0&&Y(Hn=>{const dr=[...Hn];for(const ca of et)dr.push({id:`${ca.name}:${ca.size}:${ca.lastModified}`,file:ca,kind:"attachment"});return dr})}function Ss(et){la(Array.from(et.target.files??[])),mt.current&&(mt.current.value="")}function bt(et){et.dataTransfer.types.includes("Files")&&(et.preventDefault(),Oe(!0))}function Jt(et){et.dataTransfer.types.includes("Files")&&(et.preventDefault(),et.dataTransfer.dropEffect="copy",Oe(!0))}function nr(et){et.currentTarget.contains(et.relatedTarget)||Oe(!1)}function Er(et){et.dataTransfer.files.length&&(et.preventDefault(),Oe(!1),la(Array.from(et.dataTransfer.files)))}function cs(et){Y(Hn=>Hn.filter(dr=>dr.id!==et))}const ds=Nne.find(et=>et.value===g)??Nne[1],Or=FPe.find(et=>et.value===y),Dr=h.useMemo(()=>(ue??[]).filter(et=>w.includes(et.id)),[ue,w]),Ts=g3(S),Ui=h.useMemo(()=>(ue??[]).filter(et=>Ts?et.name.toLowerCase().includes(Ts.toLowerCase()):!0),[ue,Ts]),fo=h.useMemo(()=>Cct(ue??[],Ts),[ue,Ts]),On=Ts.length>0&&Ui.length===0&&!fo,Ye=x0e(Ts),Mt=Dr.length>0?i.jsxs(i.Fragment,{children:[i.jsx(Kse,{className:"h-3 w-3"}),i.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[Dr.slice(0,2).map(et=>i.jsx(C4,{label:et},et.id)),Dr.length>2?i.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["+",Dr.length-2]}):null]})]}):i.jsxs(i.Fragment,{children:[i.jsx(Kse,{className:"h-3 w-3"}),"Labels"]}),An=h.useCallback(()=>{!ie||!On||Mn.isPending||Mn.mutate({name:Ts,color:Ye})},[Mn,Ye,ie,Ts,On]),vn=Je.find(et=>et.id===E),fr=($e??[]).find(et=>et.id===R)??null,mr=cn==="claude_local"?"Claude options":cn==="codex_local"?"Codex options":cn==="opencode_local"?"OpenCode options":"Agent options",Ge=cn==="codex_local"?M_("Default",TV(nt)):cn==="opencode_local"?n$.opencode_local:n$.claude_local,tn=h.useMemo(()=>TD(),[e]),Gn=h.useMemo(()=>[...mie(Ke),...__((at??[]).filter(et=>et.status!=="terminated"),tn).map(et=>({id:_v({assigneeAgentId:et.id}),label:et.name,searchText:`${et.name} ${et.role} ${et.title??""}`}))],[at,Ke,tn]),Wr=h.useMemo(()=>[...mie(Ke),...__((at??[]).filter(et=>et.status!=="terminated"),tn).map(et=>({id:_v({assigneeAgentId:et.id}),label:et.name,searchText:`${et.name} ${et.role} ${et.title??""}`}))],[at,Ke,tn]),mn=h.useMemo(()=>Je.map(et=>({id:et.id,label:et.name,searchText:et.description??""})),[Je]),Bn=h.useMemo(()=>($e??[]).map(et=>({id:et.id,label:et.title,searchText:`${et.title} ${et.description??""} ${et.level} ${et.status}`})),[$e]),Ci=N2({title:u,description:A,status:g,priority:y,labelIds:w,assigneeValue:C,reviewerValue:P,projectId:E,goalId:R,projectWorkspaceId:D,assigneeModelOverride:H,assigneeThinkingEffort:F,assigneeChrome:q}),Vi=Tt.error instanceof Error?Tt.error.message:"Failed to create issue. Try again.",Vr=Tt.isPending||!!ae,oc=u.trim().length>0,Ao=bs(),ml=!!t.parentId,ho=t.parentIssue,vs=((Pc=ho==null?void 0:ho.identifier)==null?void 0:Pc.trim())||((eo=ho==null?void 0:ho.id)==null?void 0:eo.slice(0,8))||(($a=t.parentId)==null?void 0:$a.slice(0,8))||null,aA=((_s=ho==null?void 0:ho.title)==null?void 0:_s.trim())||null,hf=Ae.filter(et=>et.kind==="document"),Gi=Ae.filter(et=>et.kind==="attachment"),bd=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search labels...",value:S,onChange:et=>j(et.target.value),onKeyDown:et=>{et.key!=="Enter"||!On||(et.preventDefault(),An())},autoFocus:!0}),i.jsxs("div",{ref:Ao,className:"scrollbar-auto-hide max-h-44 overflow-y-auto overscroll-contain space-y-0.5",children:[Ui.map(et=>{const Hn=w.includes(et.id);return i.jsxs("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",Hn&&"bg-accent"),onClick:()=>k(dr=>dr.includes(et.id)?dr.filter(ca=>ca!==et.id):[...dr,et.id]),children:[i.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:et.color}}),i.jsx("span",{className:"truncate",children:et.name})]},et.id)}),On?i.jsxs(i.Fragment,{children:[Ui.length>0?i.jsx("div",{className:"my-1 border-t border-border"}):null,i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",disabled:Mn.isPending,onClick:An,children:[i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border border-border/70 text-muted-foreground",children:i.jsx(Zr,{className:"h-2.5 w-2.5"})}),i.jsx("span",{className:"truncate",children:Mn.isPending?"Creating...":`Create label "${Ts}"`}),i.jsx("span",{className:"ml-auto h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:Ye},"aria-hidden":"true"})]})]}):null]})]}),lc=h.useCallback(et=>{T(et);const Hn=Je.find(dr=>dr.id===et);U(_N(Hn))},[Je]),Qn=h.useMemo(()=>{const et=RC(cn??"",ht);return(cn==="codex_local"?et:[...et].sort((dr,ca)=>{const wi=jne(dr.id),Ni=jne(ca.id),vd=wi.localeCompare(Ni);return vd!==0?vd:dr.id.localeCompare(ca.id)})).map(dr=>({id:dr.id,label:dr.label,searchText:`${dr.id} ${jne(dr.id)}`}))},[cn,ht]);return i.jsx(Ps,{open:e,onOpenChange:et=>{!et&&!Vr&&vt()},children:i.jsxs(zs,{showCloseButton:!1,"aria-describedby":void 0,className:K("motion-new-issue-dialog p-0 gap-0 flex flex-col max-h-[calc(100dvh-2rem)]",ee?"sm:max-w-[1040px]":"sm:max-w-[920px]",ae&&"motion-new-issue-dialog--created"),"data-redirecting":ae?"true":void 0,onKeyDown:xs,onEscapeKeyDown:et=>{Vr&&et.preventDefault()},onPointerDownOutside:et=>{if(Vr){et.preventDefault();return}const Hn=et.detail.originalEvent.target;Hn!=null&&Hn.closest("[data-radix-popper-content-wrapper]")&&et.preventDefault()},children:[i.jsx(ei,{className:"sr-only",children:ml?"New sub-issue":"New issue"}),ae?i.jsxs("div",{className:"motion-new-issue-created-banner absolute left-1/2 top-4 z-10 inline-flex -translate-x-1/2 items-center gap-2 rounded-md border border-[color:color-mix(in_oklab,var(--accent-base)_42%,var(--border))] bg-[color:color-mix(in_oklab,var(--accent-soft)_82%,var(--surface-elevated))] px-3 py-1.5 text-xs font-medium text-foreground shadow-[var(--shadow-sm)]",role:"status","aria-live":"polite",children:[i.jsx(dd,{className:"h-3.5 w-3.5 text-[color:var(--accent-base)]"}),i.jsxs("span",{children:["Created ",ae,". Opening issue..."]})]}):null,i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i.jsxs(ts,{open:it,onOpenChange:lt,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:K("px-1.5 py-0.5 rounded text-xs font-semibold cursor-pointer hover:opacity-80 transition-opacity",!(me!=null&&me.brandColor)&&"bg-muted"),style:me!=null&&me.brandColor?{backgroundColor:me.brandColor,color:DPe(me.brandColor)}:void 0,children:((me==null?void 0:me.name)??"").slice(0,3).toUpperCase()})}),i.jsx(ns,{className:"w-48 p-1",align:"start",children:r.filter(et=>et.status!=="archived").map(et=>i.jsxs("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",et.id===ie&&"bg-accent"),onClick:()=>{jt(et.id),lt(!1)},children:[i.jsx("span",{className:K("px-1 py-0.5 rounded text-[10px] font-semibold leading-none",!et.brandColor&&"bg-muted"),style:et.brandColor?{backgroundColor:et.brandColor,color:DPe(et.brandColor)}:void 0,children:et.name.slice(0,3).toUpperCase()}),i.jsx("span",{className:"truncate",children:et.name})]},et.id))})]}),i.jsx("span",{className:"text-muted-foreground/60",children:"›"}),i.jsx("span",{children:ml?"New sub-issue":"New issue"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>se(!ee),disabled:Vr,children:ee?i.jsx(uE,{className:"h-3.5 w-3.5"}):i.jsx(n3,{className:"h-3.5 w-3.5"})}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:vt,disabled:Vr,children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),ml?i.jsx("div",{"data-slot":"new-issue-parent-context",className:"border-b border-border/60 px-4 py-2.5 shrink-0",children:i.jsxs("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden text-xs text-muted-foreground",children:[i.jsx(l4,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"shrink-0 font-medium",children:"Parent"}),vs?i.jsx("span",{className:"w-20 shrink-0 truncate whitespace-nowrap rounded-sm border border-border bg-muted/30 px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground",children:vs}):null,aA?i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground/80",children:aA}):null]})}):null,i.jsx("div",{className:"px-4 pt-4 pb-2 shrink-0",children:i.jsx("textarea",{className:"w-full text-lg font-semibold bg-transparent outline-none resize-none overflow-hidden placeholder:text-muted-foreground/50",placeholder:"Issue title",rows:1,value:u,onChange:et=>{f(et.target.value),et.target.style.height="auto",et.target.style.height=`${et.target.scrollHeight}px`},readOnly:Vr,onKeyDown:et=>{var Hn,dr,ca,wi;et.key==="Enter"&&!et.metaKey&&!et.ctrlKey&&!et.nativeEvent.isComposing&&(et.preventDefault(),(Hn=Ue.current)==null||Hn.focus()),et.key==="Tab"&&!et.shiftKey&&(et.preventDefault(),C?E?(dr=Ue.current)==null||dr.focus():(ca=dt.current)==null||ca.focus():(wi=tt.current)==null||wi.focus())},autoFocus:!0})}),i.jsx("div",{className:"px-4 pb-3 shrink-0",children:i.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:"Assignee"}),i.jsx(dg,{ref:tt,value:C,options:Gn,placeholder:"Assignee",disablePortal:!0,noneLabel:"No assignee",searchPlaceholder:"Search assignees...",emptyMessage:"No assignees found.",variant:"field",className:Cne,onChange:et=>{const Hn=Nm(et);Hn.assigneeAgentId&&ij(Hn.assigneeAgentId),N(et)},onConfirm:()=>{var et,Hn;E?(et=Ue.current)==null||et.focus():(Hn=dt.current)==null||Hn.focus()},renderTriggerValue:et=>et?Nt?i.jsx(Wv,{agent:Nt,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label}):i.jsx("span",{className:"text-muted-foreground",children:"No assignee"}),renderOption:et=>{if(!et.id)return i.jsx("span",{className:"truncate",children:et.label});const Hn=Nm(et.id).assigneeAgentId?(at??[]).find(dr=>dr.id===Nm(et.id).assigneeAgentId):null;return Hn?i.jsx(Wv,{agent:Hn,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label})}})]}),i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:"Project"}),i.jsx(dg,{ref:dt,value:E,options:mn,placeholder:"Project",disablePortal:!0,noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",variant:"field",className:Cne,onChange:lc,onConfirm:()=>{var et;(et=Ue.current)==null||et.focus()},renderTriggerValue:et=>et&&vn?i.jsxs(i.Fragment,{children:[i.jsx(uo,{color:vn.color,icon:vn.icon,size:"xs"}),i.jsx("span",{className:"truncate",children:et.label})]}):i.jsx("span",{className:"text-muted-foreground",children:"No project"}),renderOption:et=>{if(!et.id)return i.jsx("span",{className:"truncate",children:et.label});const Hn=Je.find(dr=>dr.id===et.id);return i.jsxs(i.Fragment,{children:[i.jsx(uo,{color:Hn==null?void 0:Hn.color,icon:Hn==null?void 0:Hn.icon,size:"xs"}),i.jsx("span",{className:"truncate",children:et.label})]})}})]}),i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:"Reviewer"}),i.jsx(dg,{value:P,options:Wr,placeholder:"Reviewer",disablePortal:!0,noneLabel:"No reviewer",searchPlaceholder:"Search reviewers...",emptyMessage:"No reviewers found.",variant:"field",className:Cne,onChange:et=>{const Hn=Nm(et);Hn.assigneeAgentId&&ij(Hn.assigneeAgentId),M(et)},onConfirm:()=>{var et;(et=Ue.current)==null||et.focus()},renderTriggerValue:et=>et?Gt?i.jsx(Wv,{agent:Gt,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label}):i.jsx("span",{className:"text-muted-foreground",children:"No reviewer"}),renderOption:et=>{if(!et.id)return i.jsx("span",{className:"truncate",children:et.label});const Hn=Nm(et.id).assigneeAgentId?(at??[]).find(dr=>dr.id===Nm(et.id).assigneeAgentId):null;return Hn?i.jsx(Wv,{agent:Hn,agentAvatarStyle:"bare"}):i.jsx("span",{className:"truncate",children:et.label})}})]})]})}),Qt&&i.jsxs("div",{className:"px-4 pb-2 shrink-0",children:[i.jsxs("button",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors",onClick:()=>L(et=>!et),children:[$?i.jsx(qr,{className:"h-3 w-3"}):i.jsx(bi,{className:"h-3 w-3"}),mr]}),$&&i.jsxs("div",{className:"mt-2 rounded-md border border-border p-3 bg-muted/20 space-y-3",children:[i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"text-xs text-muted-foreground",children:"Model"}),i.jsx(dg,{value:H,options:Qn,placeholder:"Default model",disablePortal:!0,noneLabel:"Default model",searchPlaceholder:"Search models...",emptyMessage:"No models found.",onChange:X})]}),i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"text-xs text-muted-foreground",children:"Thinking effort"}),i.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:Ge.map(et=>i.jsx("button",{className:K("px-2 py-1 rounded-md text-xs border border-border hover:bg-accent/50 transition-colors",F===et.value&&"bg-accent"),onClick:()=>Q(et.value),children:et.label},et.value||"default"))})]}),cn==="claude_local"&&i.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border px-2 py-1.5",children:[i.jsx("div",{className:"text-xs text-muted-foreground",children:"Enable Chrome (--chrome)"}),i.jsx(GA,{checked:q,size:"sm",tone:"success","aria-label":"Enable Chrome",onClick:()=>B(et=>!et)})]})]})]}),i.jsxs("div",{className:"px-4 pb-2 overflow-y-auto min-h-0 border-t border-border/60 pt-3",onDragEnter:bt,onDragOver:Jt,onDragLeave:nr,onDrop:Er,children:[i.jsx("div",{className:K("rounded-md transition-colors",ce&&"bg-accent/20"),children:i.jsx(ku,{ref:Ue,engine:"codemirror",documentIdentity:`new-issue:${ie??"none"}:${Fe??Ne}`,value:A,onChange:m,placeholder:"Add description...",bordered:!1,mentions:yr,onMentionQueryChange:fs,contentClassName:"text-sm text-muted-foreground pb-12 min-h-[88px]",imageUploadHandler:async et=>(await tr.mutateAsync(et)).contentPath})}),Ae.length>0?i.jsxs("div",{className:"mt-4 space-y-3 rounded-lg border border-border/70 p-3",children:[hf.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Documents"}),i.jsx("div",{className:"space-y-2",children:hf.map(et=>i.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"rounded-full border border-border px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground",children:et.documentKey}),i.jsx("span",{className:"truncate text-sm",children:et.file.name})]}),i.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx(Fi,{className:"h-3.5 w-3.5"}),i.jsx("span",{children:et.title||et.file.name}),i.jsx("span",{children:"•"}),i.jsx("span",{children:$Pe(et.file)})]})]}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"shrink-0 text-muted-foreground",onClick:()=>cs(et.id),disabled:Vr,title:"Remove document",children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]},et.id))})]}):null,Gi.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Attachments"}),i.jsx("div",{className:"space-y-2",children:Gi.map(et=>i.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(tf,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate text-sm",children:et.file.name})]}),i.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[et.file.type||"application/octet-stream"," • ",$Pe(et.file)]})]}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"shrink-0 text-muted-foreground",onClick:()=>cs(et.id),disabled:Vr,title:"Remove attachment",children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]},et.id))})]}):null]}):null]}),i.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap shrink-0",children:[i.jsxs(ts,{open:Xe,onOpenChange:ge,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[i.jsx(qh,{className:K("h-3 w-3",ds.color)}),ds.label]})}),i.jsx(ns,{className:"w-36 p-1",align:"start",children:Nne.map(et=>i.jsxs("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",et.value===g&&"bg-accent"),onClick:()=>{x(et.value),ge(!1)},children:[i.jsx(qh,{className:K("h-3 w-3",et.color)}),et.label]},et.value))})]}),i.jsxs(ts,{open:te,onOpenChange:G,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:Or?i.jsxs(i.Fragment,{children:[i.jsx(fW,{priority:Or.value,className:"h-3.5 w-4"}),Or.label]}):i.jsxs(i.Fragment,{children:[i.jsx(PBe,{className:"h-3 w-3 text-muted-foreground"}),"Priority"]})})}),i.jsx(ns,{className:HUe,align:"start",role:"menu","aria-label":"Issue priority",children:FPe.map(et=>i.jsx(XUe,{priority:et.value,selected:et.value===y,onSelect:Hn=>{v(Hn),G(!1)}},et.value))})]}),i.jsxs(ts,{open:oe,onOpenChange:Ze,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:K("inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",Dr.length>0?"text-foreground":"text-muted-foreground"),disabled:Vr,children:Mt})}),i.jsx(ns,{className:"w-56 p-1",align:"start",disablePortal:!0,children:bd})]}),i.jsx(dg,{value:R,options:Bn,placeholder:"Goal",disablePortal:!0,noneLabel:"No goal",searchPlaceholder:"Search goals...",emptyMessage:"No goals found.",className:K("border-border bg-transparent px-2 py-1 [font-size:0.75rem] hover:bg-accent/50",fr?"text-foreground":"text-muted-foreground"),contentClassName:"w-56",onChange:_,onConfirm:()=>{var et;(et=Ue.current)==null||et.focus()},renderTriggerValue:et=>et&&fr?i.jsxs(i.Fragment,{children:[i.jsx(ud,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"max-w-40 truncate",children:et.label})]}):i.jsxs(i.Fragment,{children:[i.jsx(ud,{className:"h-3 w-3 shrink-0"}),"Goal"]}),renderOption:et=>et.id?i.jsxs(i.Fragment,{children:[i.jsx(ud,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:et.label})]}):i.jsx("span",{className:"truncate",children:et.label})}),i.jsx("input",{ref:mt,type:"file",accept:zFn,className:"hidden",onChange:Ss,multiple:!0}),i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground",onClick:()=>{var et;return(et=mt.current)==null?void 0:et.click()},disabled:Vr,children:[i.jsx(tf,{className:"h-3 w-3"}),"Upload"]}),i.jsxs(ts,{open:Te,onOpenChange:Be,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{className:"inline-flex items-center justify-center rounded-md border border-border p-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground",children:i.jsx(hl,{className:"h-3 w-3"})})}),i.jsxs(ns,{className:"w-44 p-1",align:"start",children:[i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",children:[i.jsx(UB,{className:"h-3 w-3"}),"Start date"]}),i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",children:[i.jsx(UB,{className:"h-3 w-3"}),"Due date"]})]})]})]}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-t border-border shrink-0",children:[Fe?i.jsxs("div",{className:"inline-flex min-h-8 items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx(dd,{className:"h-3.5 w-3.5"}),"Saved to Draft Issues"]}):i.jsx(le,{variant:"ghost",size:"sm",className:K("text-muted-foreground disabled:opacity-100",!Ci&&"disabled:border-border/40 disabled:bg-muted/20 disabled:text-muted-foreground/70"),onClick:Zt,disabled:Vr||!Ci,children:"Save Draft"}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"min-h-5 text-right",children:ae?i.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-[color:var(--accent-base)]",children:[i.jsx(dd,{className:"h-3 w-3"}),"Opening issue..."]}):Tt.isPending?i.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx(hn,{className:"h-3 w-3 animate-spin"}),ml?"Creating sub-issue...":"Creating issue..."]}):Tt.isError?i.jsx("span",{className:"text-xs text-destructive",children:Vi}):null}),i.jsx(le,{size:"sm",className:K("min-w-[8.5rem] disabled:opacity-100",!oc&&"disabled:border-border disabled:bg-muted disabled:text-muted-foreground disabled:ring-1 disabled:ring-inset disabled:ring-border/80 disabled:shadow-none"),disabled:!oc||Vr,onClick:kr,"aria-busy":Vr,children:i.jsxs("span",{className:"inline-flex items-center justify-center gap-1.5",children:[ae?i.jsx(dd,{className:"h-3.5 w-3.5"}):Tt.isPending?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):null,i.jsx("span",{children:ae?"Opening...":Tt.isPending?"Creating...":ml?"Create sub-issue":"Create Issue"})]})})]})]})]})})}const dft=[{value:"directory",label:"Directory"},{value:"file",label:"File"},{value:"url",label:"URL"},{value:"connector_object",label:"Connector object"}],BFn=[{value:"external",label:"External"},{value:"library",label:"Library"}];function P2(e){var t;return((t=dft.find(n=>n.value===e))==null?void 0:t.label)??e.replace(/_/g," ")}function b3(e){var t;return((t=BFn.find(n=>n.value===e))==null?void 0:t.label)??"External"}function BPe(e){return e==="directory"||e==="file"}function QFn(e){switch(e){case"directory":return"~/projects/rudder or https://linear.app/acme/project/...";case"file":return"~/projects/rudder/README.md or /Users/you/projects/rudder/README.md";case"connector_object":return"linear://project/123 or github://repo/acme/rudder";case"url":default:return"https://linear.app/acme/project/..."}}function uft(e){const t=e.trim();if(!t)return"";const n=t.replace(/\\/g,"/").replace(/\/+$/,""),r=n.split("/").filter(Boolean).pop()??n;try{return decodeURIComponent(r)}catch{return r}}function q_({kind:e,value:t,onChange:n,onPickedPath:r,disabled:s=!1,className:a,inputClassName:o,buttonClassName:l}){const[c,d]=h.useState(!1),u=Pn(),f=BPe(e)&&u!==null;async function A(){if(!(!u||!BPe(e)||c)){d(!0);try{const m=await u.pickPath({kind:e,title:e==="directory"?"Choose directory":"Choose file",buttonLabel:e==="directory"?"Choose directory":"Choose file",defaultPath:t.trim()||void 0});if(m.canceled||!m.path)return;n(m.path),r==null||r(m.path)}finally{d(!1)}}}return i.jsxs("div",{className:K("grid gap-2 sm:grid-cols-[minmax(0,1fr)_auto]",a),children:[i.jsx(Kn,{value:t,onChange:m=>n(m.target.value),placeholder:QFn(e),disabled:s||c,className:o}),f?i.jsxs(le,{type:"button",variant:"outline",size:"sm",onClick:()=>{A()},disabled:s||c,className:K("shrink-0",l),"aria-label":e==="directory"?"Browse for directory":"Browse for file",children:[c?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(yb,{className:"h-3.5 w-3.5"}),"Browse…"]}):null]})}const UFn=[{value:"backlog",label:"Backlog"},{value:"planned",label:"Planned"},{value:"in_progress",label:"In Progress"},{value:"completed",label:"Completed"},{value:"cancelled",label:"Cancelled"}],MN="w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_98%,transparent)] px-2.5 py-1.5 text-sm shadow-none outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50";function QPe(){return EP[Math.floor(Math.random()*EP.length)]??EP[0]}function Pne(e){return e.kind==="existing"?`existing:${e.resourceId}`:`new:${e.id}`}function VFn(){return{kind:"new",id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:"",resourceKind:"directory",sourceType:"external",locator:"",description:"",role:"working_set",note:""}}const qFn=/^[a-z][a-z0-9+.-]*:/i;function r$(e,t="file"){const n=e.trim();if(!n||qFn.test(n)||n.startsWith("/")||n.startsWith("\\")||n.startsWith("~")||n.includes("\\"))return!1;const r=n.split("/");return!r.every(s=>s.length>0&&s!=="."&&s!=="..")||r[0]!=="projects"?!1:t==="directory"?r.length>=2:r.length>=3}function KFn(e){return e.trim().split("/").filter(Boolean).at(-1)??e.trim()}function WFn(){const{newProjectOpen:e,closeNewProject:t}=ii(),{selectedOrganizationId:n,selectedOrganization:r}=jr(),{locale:s}=is(),a=Vn(),o=Yr(),[l,c]=h.useState(""),[d,u]=h.useState(""),[f,A]=h.useState("in_progress"),[m,g]=h.useState(QPe),[x,y]=h.useState("folder"),[v,w]=h.useState([]),[k,S]=h.useState(""),[j,C]=h.useState(!1),[N,P]=h.useState([]),[M,E]=h.useState(0),[T,R]=h.useState(!1),[_,D]=h.useState(!1),[U,$]=h.useState(!1),[L,H]=h.useState(""),[X,F]=h.useState(""),Q=h.useRef(null),q=bs("new-project:add-resources"),{data:B}=Me({queryKey:V.goals.list(n),queryFn:()=>LA.list(n),enabled:!!n&&e}),{data:ee}=Me({queryKey:V.organizations.resources(n??"__none__"),queryFn:()=>_n.listResources(n),enabled:!!n&&e}),{data:se}=Me({queryKey:V.organizations.workspaceMentionFiles(n??"__none__",L),queryFn:()=>_n.listWorkspaceMentionFiles(n,{query:L,limit:24}),enabled:!!n&&e&&U}),re=xt({mutationFn:Te=>Mi.create(n,Te)}),ne=xt({mutationFn:async Te=>{if(!n)throw new Error("No organization selected");return f8.uploadImage(n,Te,"projects/drafts")}});function Ae(){E(Te=>Te+1),c(""),u(""),A("in_progress"),g(QPe()),y("folder"),w([]),S(""),C(!1),P([]),H(""),F("")}const Y=new Map((ee??[]).map(Te=>[Te.id,Te])),ce=new Map((ee??[]).filter(Te=>Te.sourceType==="library").map(Te=>[Te.locator,Te])),Oe=new Set(N.filter(Te=>Te.kind==="existing").map(Te=>Te.resourceId)),Fe=new Set(N.flatMap(Te=>{if(Te.kind==="new"&&Te.sourceType==="library")return[Te.locator];if(Te.kind==="existing"){const Be=Y.get(Te.resourceId);return(Be==null?void 0:Be.sourceType)==="library"?[Be.locator]:[]}return[]})),ke=(ee??[]).filter(Te=>!Oe.has(Te.id)),Ne=X.trim().toLowerCase(),xe=Ne?ke.filter(Te=>[Te.name,Te.locator,Te.description??"",b3(Te.sourceType),P2(Te.kind)].some(Be=>Be.toLowerCase().includes(Ne))):ke,fe=(Array.isArray(se==null?void 0:se.entries)?se.entries:[]).filter(Te=>r$(Te.path,Te.isDirectory?"directory":"file")&&!Fe.has(Te.path)),ve=L.trim(),Se=r$(ve)&&!Fe.has(ve)&&!fe.some(Te=>Te.path===ve),ze=N.some(Te=>Te.kind==="new"&&(!Te.name.trim()||!Te.locator.trim()||Te.sourceType==="library"&&!r$(Te.locator,Te.resourceKind)));function ft(Te,Be){P(it=>it.map(lt=>Pne(lt)===Te?Be(lt):lt))}function ie(Te){P(Be=>Be.filter(it=>Pne(it)!==Te))}function me(Te){P(Be=>Be.some(it=>it.kind==="existing"&&it.resourceId===Te.id)?Be:[...Be,{kind:"existing",resourceId:Te.id,role:"reference",note:""}]),$(!1)}function we(Te){const Be=ce.get(Te.path);if(Be){me(Be);return}P(it=>[...it,{kind:"new",id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:Te.displayLabel??Te.name,resourceKind:Te.isDirectory?"directory":"file",sourceType:"library",locator:Te.path,description:"",role:Te.isDirectory?"working_set":"reference",note:""}]),$(!1)}function Xe(Te){const Be=Te.trim();if(!r$(Be))return;const it=ce.get(Be);if(it){me(it);return}P(lt=>[...lt,{kind:"new",id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:KFn(Be),resourceKind:"file",sourceType:"library",locator:Be,description:"",role:"reference",note:""}]),$(!1),H("")}function ge(){P(Te=>[...Te,VFn()]),$(!1)}async function te(){if(!n||!l.trim()||ze)return;const Te=N.filter(it=>it.kind==="existing").map((it,lt)=>({resourceId:it.resourceId,role:it.role,note:it.note.trim()||void 0,sortOrder:lt})),Be=N.filter(it=>it.kind==="new").map((it,lt)=>({name:it.name.trim(),kind:it.resourceKind,sourceType:it.sourceType,locator:it.locator.trim(),description:it.description.trim()||void 0,role:it.role,note:it.note.trim()||void 0,sortOrder:Te.length+lt}));try{const it=await re.mutateAsync({name:l.trim(),description:g0e(d),status:f,color:m,icon:x,...v.length>0?{goalIds:v}:{},...k?{targetDate:k}:{},...Te.length>0?{resourceAttachments:Te}:{},...Be.length>0?{newResources:Be}:{}});a.invalidateQueries({queryKey:V.projects.list(n)}),a.invalidateQueries({queryKey:V.projects.detail(it.id)}),a.invalidateQueries({queryKey:V.organizations.resources(n)}),Ae(),t(),o(`/issues?projectId=${encodeURIComponent(it.id)}`)}catch{}}function G(Te){Te.key==="Enter"&&(Te.metaKey||Te.ctrlKey)&&(Te.preventDefault(),te())}const oe=(B??[]).filter(Te=>v.includes(Te.id)),Ze=(B??[]).filter(Te=>!v.includes(Te.id));return i.jsx(Ps,{open:e,onOpenChange:Te=>{Te||(Ae(),t())},children:i.jsxs(zs,{showCloseButton:!1,className:K("flex max-h-[min(860px,calc(100vh-2rem))] flex-col gap-0 overflow-visible p-0",j?"sm:max-w-3xl":"sm:max-w-xl"),onKeyDown:G,children:[i.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border px-4 py-2.5",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[r&&i.jsx("span",{className:"rounded-[calc(var(--radius-sm)-1px)] bg-muted px-1.5 py-0.5 text-xs font-medium",children:r.name.slice(0,3).toUpperCase()}),i.jsx("span",{className:"text-muted-foreground/60",children:"›"}),i.jsx("span",{children:"New project"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>C(!j),children:j?i.jsx(uE,{className:"h-3.5 w-3.5"}):i.jsx(n3,{className:"h-3.5 w-3.5"})}),i.jsx(le,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>{Ae(),t()},children:i.jsx("span",{className:"text-lg leading-none",children:"×"})})]})]}),i.jsxs("div",{"data-testid":"new-project-dialog-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto overscroll-contain",children:[i.jsx("div",{className:"shrink-0 px-4 pb-2 pt-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(ts,{children:[i.jsx(ys,{asChild:!0,children:i.jsx(qAe,{projectColor:m,projectIcon:x,label:"Choose project identity","data-testid":"new-project-identity-trigger"})}),i.jsx(ns,{align:"start",className:"w-auto p-0",children:i.jsx(GUe,{color:m,icon:x,onColorChange:g,onIconChange:y})})]}),i.jsx("input",{className:"min-w-0 flex-1 bg-transparent text-lg font-semibold outline-none placeholder:text-muted-foreground/50",placeholder:"Project name",value:l,onChange:Te=>c(Te.target.value),onKeyDown:Te=>{var Be;Te.key==="Tab"&&!Te.shiftKey&&(Te.preventDefault(),(Be=Q.current)==null||Be.focus())},autoFocus:!0})]})}),i.jsx("div",{className:"px-4 pb-2",children:i.jsx(ku,{ref:Q,engine:"codemirror",documentIdentity:`new-project:${M}`,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:K("text-sm text-muted-foreground",j?"min-h-[200px]":"min-h-[120px]"),imageUploadHandler:async Te=>(await ne.mutateAsync(Te)).contentPath})}),i.jsxs("div",{className:"space-y-3 border-t border-border px-4 py-3",children:[i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"text-sm font-medium",children:"Project Context"}),i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx("button",{type:"button",className:"inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":"About project context",children:i.jsx(Vfe,{className:"h-3.5 w-3.5"})})}),i.jsx(ia,{side:"top",sideOffset:8,className:"max-w-[260px] px-3 py-2 text-xs leading-5",children:_i("projectContextHelp",s)})]})]}),i.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:i.jsxs(ts,{open:U,onOpenChange:Te=>{$(Te),Te||(H(""),F(""))},children:[i.jsx(ys,{asChild:!0,children:i.jsxs(le,{type:"button",size:"xs",className:"h-7 rounded-[calc(var(--radius-sm)-1px)] px-2",disabled:!n,children:[i.jsx(Zr,{className:"mr-1.5 h-3 w-3"}),"Add resources"]})}),i.jsxs(ns,{className:"z-[60] flex max-h-[min(420px,calc(100dvh-2rem),var(--radix-popover-content-available-height))] w-[min(20rem,calc(100vw-2rem))] flex-col overflow-hidden p-1",align:"end",collisionPadding:16,disablePortal:!0,sideOffset:8,children:[i.jsxs("button",{type:"button",className:"flex w-full shrink-0 items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:ge,children:[i.jsx(qm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{children:[i.jsx("span",{className:"block text-xs font-medium",children:"Create external resource"}),i.jsx("span",{className:"block text-[11px] text-muted-foreground",children:"Add a URL, local path, repo path, or connector reference."})]})]}),i.jsx("div",{className:"mx-2 my-1 h-px shrink-0 bg-border"}),i.jsx("div",{className:"px-2 pb-1.5 pt-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:_i("addFromLibrary",s)}),i.jsx("div",{className:"px-2 pb-2",children:i.jsx("input",{value:L,onChange:Te=>H(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"&&Se&&(Te.preventDefault(),Xe(ve))},className:"h-7 w-full rounded-[calc(var(--radius-sm)-1px)] border border-border bg-background px-2 text-xs outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",placeholder:_i("searchLibraryPlaceholder",s)})}),i.jsxs("div",{ref:q,"data-testid":"new-project-add-resources-popover-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1",children:[fe.length===0?i.jsx("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:L.trim()?_i("noMatchingLibraryFiles",s):_i("noLibraryFiles",s)}):fe.map(Te=>{const Be=Te.isDirectory?wo:Fi;return i.jsxs("button",{type:"button",className:"flex w-full items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:()=>we(Te),children:[i.jsx(Be,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:Te.displayLabel??Te.name}),i.jsx("span",{className:"block truncate font-mono text-[11px] text-muted-foreground",children:Te.path})]})]},Te.path)}),Se?i.jsxs("button",{type:"button",className:"mt-1 flex w-full items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:()=>Xe(ve),children:[i.jsx(Fi,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:_i("useThisLibraryPath",s)}),i.jsx("span",{className:"block truncate font-mono text-[11px] text-muted-foreground",children:ve})]})]}):null,i.jsx("div",{className:"my-1 h-px bg-border"}),i.jsx("div",{className:"px-2 pb-1.5 pt-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:"Existing resources"}),i.jsx("div",{className:"px-2 pb-2",children:i.jsx("input",{value:X,onChange:Te=>F(Te.target.value),className:"h-7 w-full rounded-[calc(var(--radius-sm)-1px)] border border-border bg-background px-2 text-xs outline-none transition-[border-color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",placeholder:"Search existing resources"})}),xe.length===0?i.jsx("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:X.trim()?"No matching resources.":"No unattached resources available."}):xe.map(Te=>i.jsxs("button",{type:"button",className:"flex w-full items-start gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-2 text-left hover:bg-accent/50",onClick:()=>me(Te),children:[i.jsx(qm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:Te.name}),i.jsxs("span",{className:"block truncate text-[11px] text-muted-foreground",children:[b3(Te.sourceType)," · ",P2(Te.kind)," · ",Te.locator]})]})]},Te.id))]})]})]})})]}),N.length>0?i.jsx("div",{className:"space-y-3",children:N.map(Te=>{const Be=Pne(Te),it=Te.kind==="existing"?Y.get(Te.resourceId)??null:null;return i.jsxs("div",{className:"space-y-3 rounded-[var(--radius-sm)] border border-border/80 bg-[color:color-mix(in_oklab,var(--surface-inset)_52%,var(--surface-elevated))] px-3 py-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"space-y-0.5 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2 text-sm font-medium",children:Te.kind==="existing"?i.jsxs(i.Fragment,{children:[i.jsx(qm,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:(it==null?void 0:it.name)??"Missing resource"})]}):Te.sourceType==="library"?i.jsxs(i.Fragment,{children:[i.jsx(lE,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:Te.name.trim()||Te.locator})]}):i.jsxs(i.Fragment,{children:[i.jsx(wo,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{children:Te.name.trim()||"New resource"})]})}),i.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:Te.kind==="existing"?it?`${b3(it.sourceType)} · ${P2(it.kind)} · ${it.locator}`:"This resource is no longer available.":Te.sourceType==="library"?`Library · ${P2(Te.resourceKind)} · ${Te.locator}`:"Created as an external resource and attached to this project on submit."})]}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:()=>ie(Be),children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]}),Te.kind==="new"&&Te.sourceType==="external"?i.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Name"}),i.jsx("input",{value:Te.name,onChange:lt=>ft(Be,Ue=>({...Ue,name:lt.target.value})),className:MN,placeholder:"Rudder repo"})]}),i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Kind"}),i.jsx("select",{value:Te.resourceKind,onChange:lt=>ft(Be,Ue=>({...Ue,resourceKind:lt.target.value})),className:K(MN,"h-8"),children:dft.map(lt=>i.jsx("option",{value:lt.value,children:lt.label},lt.value))})]}),i.jsxs("label",{className:"space-y-1 md:col-span-2",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Locator"}),i.jsx(q_,{kind:Te.resourceKind,value:Te.locator,onChange:lt=>ft(Be,Ue=>({...Ue,locator:lt})),onPickedPath:lt=>ft(Be,Ue=>{const mt=Ue;return{...mt,locator:lt,name:mt.name.trim()?mt.name:uft(lt)}}),inputClassName:K(MN,"h-8"),buttonClassName:"h-8 rounded-[calc(var(--radius-sm)-1px)]"})]}),i.jsxs("label",{className:"space-y-1 md:col-span-2",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Description"}),i.jsx("textarea",{value:Te.description,onChange:lt=>ft(Be,Ue=>({...Ue,description:lt.target.value})),className:K(MN,"min-h-[72px] resize-y py-2"),placeholder:"What this resource contains and when agents should use it."})]})]}):null,i.jsxs("label",{className:"block space-y-1",children:[i.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Project note"}),i.jsx("input",{value:Te.note,onChange:lt=>ft(Be,Ue=>({...Ue,note:lt.target.value})),className:MN,placeholder:"Optional guidance specific to this project"})]}),Te.kind==="new"&&(!Te.name.trim()||!Te.locator.trim())?i.jsx("p",{className:"text-[11px] text-amber-600 dark:text-amber-300",children:"New resources need both a name and a locator before you can create the project."}):null]},Be)})}):null]})]}),i.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-1.5 border-t border-border px-4 py-2",children:[i.jsxs(ts,{open:T,onOpenChange:R,children:[i.jsx(ys,{asChild:!0,children:i.jsx("button",{type:"button",className:"inline-flex items-center rounded-[calc(var(--radius-sm)-1px)] transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",children:i.jsx(Qs,{status:f})})}),i.jsx(ns,{className:"w-40 p-1",align:"start",children:UFn.map(Te=>i.jsx("button",{className:K("flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-xs hover:bg-accent/50",Te.value===f&&"bg-accent"),onClick:()=>{A(Te.value),R(!1)},children:Te.label},Te.value))})]}),oe.map(Te=>i.jsxs("span",{className:"inline-flex items-center gap-1 rounded-[calc(var(--radius-sm)-1px)] border border-border px-2 py-1 text-xs",children:[i.jsx(ud,{className:"h-3 w-3 text-muted-foreground"}),i.jsx("span",{className:"max-w-[160px] truncate",children:Te.title}),i.jsx("button",{className:"text-muted-foreground hover:text-foreground",onClick:()=>w(Be=>Be.filter(it=>it!==Te.id)),"aria-label":`Remove goal ${Te.title}`,type:"button",children:i.jsx(Is,{className:"h-3 w-3"})})]},Te.id)),i.jsxs(ts,{open:_,onOpenChange:D,children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] border border-border px-2 py-1 text-xs transition-colors hover:bg-accent/50 disabled:opacity-60",disabled:oe.length>0&&Ze.length===0,children:[oe.length>0?i.jsx(Zr,{className:"h-3 w-3 text-muted-foreground"}):i.jsx(ud,{className:"h-3 w-3 text-muted-foreground"}),oe.length>0?"+ Goal":"Goal"]})}),i.jsxs(ns,{className:"w-56 p-1",align:"start",children:[oe.length===0&&i.jsx("button",{className:"flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-xs text-muted-foreground hover:bg-accent/50",onClick:()=>D(!1),children:"No goal"}),Ze.map(Te=>i.jsx("button",{className:"flex w-full items-center gap-2 truncate rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-xs hover:bg-accent/50",onClick:()=>{w(Be=>[...Be,Te.id]),D(!1)},children:Te.title},Te.id)),oe.length>0&&Ze.length===0&&i.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"All goals already selected."})]})]}),i.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] border border-border px-2 py-1 text-xs",children:[i.jsx(UB,{className:"h-3 w-3 text-muted-foreground"}),i.jsx("input",{type:"date",className:"bg-transparent outline-none text-xs w-24",value:k,onChange:Te=>S(Te.target.value),placeholder:"Target date"})]})]}),i.jsxs("div",{className:"flex shrink-0 items-center justify-between border-t border-border px-4 py-2.5",children:[re.isError?i.jsx("p",{className:"text-xs text-destructive",children:"Failed to create project."}):i.jsx("span",{className:"text-xs text-muted-foreground",children:N.length>0?`${N.length} context item${N.length===1?"":"s"} queued`:""}),i.jsx(le,{size:"sm",disabled:!l.trim()||re.isPending||ze,onClick:()=>void te(),children:re.isPending?"Creating…":"Create project"})]})]})})}function fde(){if(typeof Notification>"u")return"unsupported";const e=Notification.permission;return e==="granted"||e==="denied"||e==="default"?e:"unsupported"}async function fft(){if(typeof Notification>"u"||typeof Notification.requestPermission!="function")return"unsupported";if(Notification.permission==="granted"||Notification.permission==="denied")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"||e==="denied"||e==="default"?e:"unsupported"}const UPe="rudder:issue-navigation",ZFn=new Set(["assigned","pinned","starred","recent"]);function Aft(e){return e?`${UPe}:${e}`:UPe}function hft(e){const t=typeof(e==null?void 0:e.scope)=="string"&&ZFn.has(e.scope)?e.scope==="starred"?"pinned":e.scope:void 0,n=typeof(e==null?void 0:e.projectId)=="string"&&e.projectId.trim().length>0?e.projectId:void 0;return{scope:t,projectId:n}}function HFn(e){const t=hft(e),n=new URLSearchParams;t.projectId?n.set("projectId",t.projectId):t.scope&&n.set("scope",t.scope);const r=n.toString();return r?`/issues?${r}`:"/issues"}function XFn(e){if(typeof window>"u")return"/issues";try{const t=window.localStorage.getItem(Aft(e));if(!t)return"/issues";const n=JSON.parse(t);return HFn(n)}catch{return"/issues"}}function GFn(e,t){if(!(typeof window>"u"))try{const n=hft(t);window.localStorage.setItem(Aft(e),JSON.stringify(n))}catch{}}const Ade="rudder:messenger-scroll-to-unread";let oq=0,hde=0;function VPe(){return oq>hde?oq:0}function Ine(e){hde=Math.max(hde,e)}function YFn(){if(typeof document>"u")return;oq+=1;const e=()=>{document.dispatchEvent(new CustomEvent(Ade,{detail:{requestId:oq}}))};if(e(),typeof requestAnimationFrame=="function"){requestAnimationFrame(e);return}setTimeout(e,0)}const JFn={desktopInboxNotifications:!0},eBn="/rudder-logo.png";function tBn(e){return/^\/(?:messenger|chat)(?:\/|$)/.test(e)}function nBn(e){if(!e||typeof window>"u")return null;const t=window.navigator.userAgent;return/Mac/i.test(t)?"macos":/Windows/i.test(t)?"windows":"other"}const Tne=["h-9 w-9 translate-x-[var(--primary-rail-item-shift,0.25rem)] rounded-lg border shadow-[0_6px_18px_-16px_rgba(15,23,42,0.55)] backdrop-blur-[22px]","border-[color:color-mix(in_oklab,var(--sidebar-border)_76%,white)]","bg-[color:color-mix(in_oklab,var(--sidebar)_72%,white)]","text-[color:color-mix(in_oklab,var(--sidebar-foreground)_88%,var(--sidebar))]","dark:border-white/20 dark:bg-white/10 dark:text-white/78"].join(" ");function qPe({to:e,label:t,icon:n,tourTarget:r,badge:s,badgeTone:a="default",badgeTestId:o,active:l,onDoubleClick:c,onContextMenu:d,localAppIdentity:u,end:f}){return i.jsxs(Pj,{to:e,end:f,"aria-current":l?"page":void 0,"data-tour-target":r,"data-tour-spotlight":r?"compact-rail":void 0,onDoubleClick:c,onContextMenu:d,className:({isActive:A})=>K("relative z-10 flex min-h-[56px] w-[var(--primary-rail-item-width,66px)] translate-x-[var(--primary-rail-item-shift,0.25rem)] flex-col items-center justify-center gap-1 rounded-[var(--radius-sm)] px-1 py-2 text-[9px] font-medium leading-[1.05] transition-colors",l??A?"text-white":["text-[color:color-mix(in_oklab,var(--sidebar-foreground)_86%,var(--sidebar))]","hover:bg-[color:color-mix(in_oklab,var(--sidebar)_58%,white)]","hover:text-[color:var(--sidebar-foreground)]","dark:text-white/74 dark:hover:bg-white/[0.07] dark:hover:text-white"].join(" ")),children:[i.jsxs("span",{className:"relative",children:[u?i.jsx(Z6,{className:"h-[17px] w-[17px] rounded-[4px]",identity:u,testId:"primary-rail-local-app-icon"}):i.jsx(n,{className:"h-[17px] w-[17px]"}),s!=null&&s>0?i.jsx("span",{"data-testid":o,className:K("absolute -right-2 -top-2 rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none",a==="danger"?"bg-red-500 text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]":"bg-primary text-primary-foreground"),children:s>99?"99+":s}):null]}),i.jsx("span",{className:"block w-full min-w-0 truncate text-center",title:t,children:t})]})}function rBn({onOpenSettings:e,onWarmSettings:t}){var ce,Oe,Fe;const{t:n,locale:r}=is(),{openNewIssue:s,openNewAgent:a,openNewProject:o}=ii(),{setSidebarOpen:l}=jc(),{selectedOrganizationId:c}=jr(),d=Vn(),u=ihe(c),[f,A]=h.useState(null),m=Me({queryKey:V.instance.notificationSettings,queryFn:()=>Ha.getNotifications(),staleTime:Do}),x=((Oe=(ce=Me({queryKey:V.health,queryFn:()=>rA.get(),staleTime:Do}).data)==null?void 0:ce.features)==null?void 0:Oe.experimentalSitesEnabled)===!0,y=Me({queryKey:V.messenger.primaryRailPins(c??"__none__"),queryFn:()=>Ks.listSavedViews(c,{visibility:"visible",primaryRailPinned:!0,limit:100}),enabled:!!(c&&x)}),v=br(),w=Yr(),k=fl(v.pathname),S=tBn(k),j=Pn()!==null,C=nBn(j),N=h.useRef(null),P=h.useRef(c),M=h.useRef(!1),E=/^\/(?:dashboard|calendar|org|projects|heartbeats|goals|skills|costs|activity)(?:\/|$)/.test(k),T=XFn(c),R=Yw(c,"messenger","/messenger"),_=Yw(c,"issues",T),D=Yw(c,"agents","/agents"),U=Yw(c,"library","/library"),$=Yw(c,"organization","/dashboard"),L=Yw(c,"automations","/automations"),H=Yw(c,"apps","/apps"),X=[{key:"messenger",to:R,label:"Messenger",icon:pa,badge:u.inbox,badgeTone:"danger",badgeTestId:"rail-badge-messenger",active:/^\/(?:messenger|chat)(?:\/|$)/.test(k)},{key:"issues",to:_,label:"Issue",icon:xS,active:/^\/issues(?:\/|$)/.test(k)},{key:"agents",to:D,label:"Agents",icon:iIt,active:/^\/agents(?:\/|$)/.test(k)},{key:"library",to:U,label:r==="zh-CN"?"文档":"Library",icon:lE,active:/^\/(?:library|resources|workspaces)(?:\/|$)/.test(k)},...x?[{key:"apps",to:H,label:"Apps",icon:sA,active:/^\/apps(?:\/|$)/.test(k)&&!/^\/apps\/saved\/[^/]+(?:\/|$)/.test(k)}]:[],{key:"organization",to:$,label:"Organization",icon:rNt,active:E},{key:"automations",to:L,label:"Automations",icon:cw,active:/^\/automations(?:\/|$)/.test(k)}],F=x?(((Fe=y.data)==null?void 0:Fe.items)??[]).filter(ke=>ke.targetPayload.kind==="local_app").map(ke=>({key:`saved-view:${ke.id}`,to:Rce(ke.id),label:ke.title,icon:pa,localAppIdentity:ke.targetPayload,active:k===Rce(ke.id)})):[],Q=X.findIndex(ke=>ke.active),q=F.findIndex(ke=>ke.active),B=Q>=0?Q:q>=0?X.length+q:-1,ee=B>=0?{"--motion-rail-active-index":B,"--motion-rail-active-offset":q>=0?`calc(${B} * (var(--motion-rail-item-height) + var(--motion-rail-item-gap)) + 0.6875rem)`:`calc(${B} * (var(--motion-rail-item-height) + var(--motion-rail-item-gap)))`}:void 0,se=h.useCallback(()=>{(u.inbox??0)<=0||(l(!0),YFn())},[u.inbox,l]),re=xt({mutationFn:async()=>c?Ks.dismissUnreads(c):{dismissedCount:0,dismissedThreadKeys:[]},onSuccess:async()=>{c&&await Promise.all([d.invalidateQueries({queryKey:V.sidebarBadges(c)}),d.invalidateQueries({queryKey:V.messenger.threadPreview(c)}),d.invalidateQueries({queryKey:V.messenger.threads(c)}),d.invalidateQueries({queryKey:V.messenger.threadPages(c)}),d.invalidateQueries({queryKey:V.messenger.customGroups(c)}),d.invalidateQueries({queryKey:V.messenger.issues(c)}),d.invalidateQueries({queryKey:V.messenger.approvals(c)}),d.invalidateQueries({queryKey:["messenger",c,"system"]}),d.invalidateQueries({queryKey:["chats",c]})])}}),ne=h.useCallback(ke=>{ke.preventDefault(),A({left:ke.clientX,top:ke.clientY})},[]),Ae=h.useCallback(()=>{!c||re.isPending||re.mutate()},[re,c]);h.useEffect(()=>{if(m.isLoading)return;P.current!==c&&(P.current=c,N.current=null);const ke=Pn();let Ne=!1;const xe=ke,ae=m.data??JFn;async function fe(){const ve=Math.max(0,u.inbox??0);xe&&await xe.setBadgeCount(ae.desktopInboxNotifications?ve:0).catch(ie=>{console.warn("[rudder-ui] failed to sync desktop dock badge count",ie)});let Se=fde();if(xe===null&&u.isReady&&ve>0&&Se==="default"&&!M.current&&ae.desktopInboxNotifications&&!S&&(M.current=!0,Se=await fft()),Ne)return;const ft=N.current;if(ft!=null&&u.isReady&&ve>ft&&ae.desktopInboxNotifications&&!S){const{title:ie,body:me}=u.notificationContent;if(xe)await xe.showNotification({title:ie,body:me}).catch(we=>{console.warn("[rudder-ui] failed to trigger desktop inbox notification",we)});else if(Se==="granted"&&typeof Notification<"u")try{const we=new Notification(ie,{body:me,icon:eBn});we.onclick=()=>window.focus()}catch(we){console.warn("[rudder-ui] failed to trigger browser inbox notification",we)}}u.isReady&&(N.current=ve)}return fe(),()=>{Ne=!0}},[u.inbox,u.isReady,u.notificationContent,m.data,m.isLoading,c,S]);function Y(){document.dispatchEvent(new CustomEvent("rudder:open-command-palette",{detail:{source:"primary-rail"}}))}return i.jsxs("aside",{"data-testid":"primary-rail","data-tour-target":"primary-rail","data-desktop-shell":j?"true":void 0,"data-desktop-platform":C??void 0,className:K("my-2 flex h-[calc(100%-1rem)] shrink-0 flex-col items-center py-1.5 text-[color:color-mix(in_oklab,var(--foreground)_78%,white)]",C==="windows"?"ml-1 mr-1 w-[52px] [--primary-rail-item-shift:0px] [--primary-rail-item-width:52px]":j?"ml-3 mr-1 w-[40px]":"ml-2 mr-3 px-5 w-[50px]"),children:[i.jsxs("div",{className:"flex w-full flex-col items-center gap-4",children:[i.jsx("div",{className:"translate-x-[var(--primary-rail-item-shift,0.25rem)]",children:i.jsx(che,{compact:!0})}),i.jsx(le,{variant:"ghost",size:"icon-sm",className:Tne,onClick:Y,title:n("common.search"),"aria-label":n("common.search"),children:i.jsx(Fl,{className:"h-4 w-4"})}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{variant:"ghost",size:"icon-sm",className:K(Tne,"rail-create-menu-trigger"),"data-tour-target":"create-menu",title:n("common.create"),"aria-label":n("common.create"),children:i.jsx(Zr,{className:"h-4 w-4"})})}),i.jsxs(Ri,{side:"right",align:"start",className:"rail-create-menu-content morph-popover morph-popover--from-left glass-popover w-48 text-foreground",children:[i.jsxs(Xt,{onClick:()=>w("/messenger/chat"),children:[i.jsx(F9t,{className:"h-4 w-4"}),"Create new chat"]}),i.jsxs(Xt,{onClick:()=>s(),children:[i.jsx(xS,{className:"h-4 w-4"}),"Create new issue"]}),i.jsxs(Xt,{onClick:()=>a(),children:[i.jsx(Ul,{className:"h-4 w-4"}),"Create new agent"]}),i.jsxs(Xt,{onClick:()=>o(),children:[i.jsx(oE,{className:"h-4 w-4"}),"Create new project"]})]})]})]}),i.jsxs("nav",{className:"motion-rail-nav scrollbar-auto-hide mt-2.5 flex min-h-0 w-[calc(var(--primary-rail-item-width,66px)+var(--primary-rail-item-shift,0.25rem)+var(--primary-rail-item-shift,0.25rem)+0.625rem)] flex-1 flex-col items-center gap-0.5 overflow-y-auto",style:ee,"data-active-index":B>=0?B:void 0,"aria-label":"Primary navigation",children:[B>=0?i.jsx("span",{"data-testid":"primary-rail-active-indicator",className:"motion-rail-active-indicator","aria-hidden":"true"}):null,X.map(ke=>i.jsx(qPe,{to:ke.to,label:ke.label,icon:ke.icon,tourTarget:ke.key==="issues"?"issues-nav":void 0,badge:ke.badge,badgeTone:ke.badgeTone,badgeTestId:ke.badgeTestId,active:ke.active,onDoubleClick:ke.key==="messenger"?se:void 0,onContextMenu:ke.key==="messenger"?ne:void 0,localAppIdentity:ke.localAppIdentity,end:ke.key==="apps"?!0:void 0},ke.key)),F.length>0?i.jsx("span",{className:"my-1 h-px w-7 shrink-0 bg-white/10","aria-hidden":"true"}):null,F.map(ke=>i.jsx(qPe,{to:ke.to,label:ke.label,icon:ke.icon,active:ke.active,localAppIdentity:ke.localAppIdentity},ke.key))]}),i.jsxs(Ei,{open:f!==null,onOpenChange:ke=>{ke||A(null)},children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-hidden":"true",tabIndex:-1,className:"fixed h-px w-px opacity-0",style:{left:(f==null?void 0:f.left)??-1e3,top:(f==null?void 0:f.top)??-1e3}})}),i.jsx(Ri,{side:"right",align:"start",className:"glass-popover w-52 text-foreground",onContextMenu:ke=>ke.preventDefault(),children:i.jsxs(Xt,{disabled:!c||re.isPending||(u.inbox??0)<=0,onClick:Ae,children:[i.jsx(cT,{className:"h-4 w-4"}),"Dismiss Unreads"]})})]}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",className:K("settings-entry-button flex items-center justify-center transition-[transform,background-color,border-color,box-shadow,color]",Tne),onPointerEnter:t,onFocus:t,onClick:e,"aria-label":n("common.systemSettings"),title:n("common.systemSettings"),"data-settings-trigger":"true",children:i.jsx(Ix,{className:"h-4 w-4"})})]})}const mft="rudder.productTour.completed.v1",b2e="rudder.productTour.pendingAfterSetup.v1",Ty=[{id:"workspace",target:"[data-tour-target='primary-rail']",checklistKey:"productTour.checklist.workspace",titleKey:"productTour.step.workspace.title",bodyKey:"productTour.step.workspace.body"},{id:"create",target:"[data-tour-target='create-menu']",checklistKey:"productTour.checklist.create",titleKey:"productTour.step.create.title",bodyKey:"productTour.step.create.body"},{id:"issues",target:"[data-tour-target='issues-nav']",checklistKey:"productTour.checklist.issues",titleKey:"productTour.step.issues.title",bodyKey:"productTour.step.issues.body"},{id:"inspect",target:"[data-tour-target='workspace-main']",checklistKey:"productTour.checklist.inspect",titleKey:"productTour.step.inspect.title",bodyKey:"productTour.step.inspect.body"},{id:"settings",target:"[data-settings-trigger='true']",checklistKey:"productTour.checklist.settings",titleKey:"productTour.step.settings.title",bodyKey:"productTour.step.settings.body"}],jk=16,sBn=96,iBn=48,d7=220,Ck=214,aBn=52,oBn=232,C7=16;function pft(){return typeof document>"u"?!1:document.documentElement.classList.contains("desktop-shell-macos")}function gft(){return pft()?{left:sBn,top:iBn,right:jk,bottom:jk}:{left:jk,top:jk,right:jk,bottom:jk}}function lBn(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(mft)==="true"}catch{return!0}}function xft(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(b2e)==="true"}catch{return!1}}function cBn(){if(!(typeof window>"u"))try{window.localStorage.setItem(b2e,"true")}catch{}}function dBn(){if(!(typeof window>"u"))try{window.localStorage.setItem(mft,"true"),window.localStorage.removeItem(b2e)}catch{}}function KPe(){const e=Math.min(520,Math.max(260,window.innerWidth*.48)),t=Math.min(220,Math.max(130,window.innerHeight*.26));return{left:Math.round((window.innerWidth-e)/2),top:Math.round((window.innerHeight-t)/2),width:Math.round(e),height:Math.round(t)}}function uBn(e){const t=document.querySelector(e);if(!t)return KPe();const n=t.getBoundingClientRect();if(n.width<=0||n.height<=0)return KPe();const r=t.dataset.tourSpotlight==="compact-rail",s=r?Math.min(n.width,aBn):n.width,a=r?n.left+(n.width-s)/2:n.left,o=r?4:6;return{left:Math.max(8,Math.round(a-o)),top:Math.max(8,Math.round(n.top-o)),width:Math.round(s+o*2),height:Math.round(n.height+o*2)}}function CP(e,t,n){return Math.max(t,Math.min(n,e))}function fBn(e,t,n=8){return e.left<t.left+t.width+n&&e.left+e.width+n>t.left&&e.top<t.top+t.height+n&&e.top+e.height+n>t.top}function ABn(e){const t=gft(),n=Math.min(360,Math.max(292,window.innerWidth-32)),r=Math.max(t.left,window.innerWidth-n-t.right),s=e.left+e.width+C7+n<=window.innerWidth-t.right,a=e.left-C7-n>=t.left,o=s?e.left+e.width+C7:a?e.left-C7-n:Math.max(t.left,Math.min(r,e.left)),l=Math.max(t.top,Math.min(window.innerHeight-250-t.bottom,e.top));return{width:n,left:o,top:l,height:oBn}}function hBn(e){const t=gft();if(pft())return{top:t.top,right:t.right};const n=Math.max(t.left,window.innerWidth-d7-t.right),r=Math.max(t.top,window.innerHeight-Ck-t.bottom),s=Math.max(t.top,20),a=[{left:n,top:s,width:d7,height:Ck},{left:Math.max(t.left,20),top:s,width:d7,height:Ck},{left:CP(e.left,t.left,n),top:CP(e.top+e.height+C7,t.top,r),width:d7,height:Ck},{left:CP(e.left,t.left,n),top:CP(e.top-Ck-C7,t.top,r),width:d7,height:Ck}],o=a.find(l=>!fBn(l,e))??a[0];return{left:Math.round(o.left),top:Math.round(o.top)}}function mBn(){const{t:e}=is(),{productTourOpen:t,closeProductTour:n}=ii(),r=Yr(),[s,a]=h.useState(0),[o,l]=h.useState(null),c=h.useRef(null),d=h.useRef(!1),u=Ty[s]??Ty[0],f=s===Ty.length-1,A=h.useCallback(()=>{l(uBn(u.target))},[u.target]);h.useEffect(()=>{t&&(a(0),d.current=!1)},[t]),h.useEffect(()=>{if(!t)return;A();const v=window.requestAnimationFrame(A);return window.addEventListener("resize",A),window.addEventListener("scroll",A,!0),()=>{window.cancelAnimationFrame(v),window.removeEventListener("resize",A),window.removeEventListener("scroll",A,!0)}},[t,A]),h.useEffect(()=>{var v;t&&((v=c.current)==null||v.focus())},[t,s]);const m=h.useMemo(()=>o?ABn(o):null,[o]),g=h.useMemo(()=>m?hBn(m):null,[m]),x=h.useCallback(()=>{const v=xft();dBn(),n(),v&&!d.current&&r("/issues")},[n,r]),y=h.useCallback(v=>{const w=CP(v,0,Ty.length-1);(Ty[w]??Ty[0]).id==="issues"&&(d.current=!0,r("/issues")),a(w)},[r]);return!t||!o||!m||!g?null:i.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-labelledby":"product-tour-title",tabIndex:-1,className:"fixed inset-0 z-[90] outline-none",onKeyDown:v=>{v.key==="Escape"&&(v.preventDefault(),x())},children:[i.jsx("div",{"aria-hidden":"true","data-testid":"product-tour-spotlight",className:"pointer-events-none fixed rounded-[10px] border-2 border-[color:color-mix(in_oklab,var(--accent-base)_72%,white)] shadow-[0_0_0_9999px_rgb(18_17_15/0.68),0_0_0_5px_color-mix(in_oklab,var(--accent-base)_18%,transparent)]",style:{left:o.left,top:o.top,width:o.width,height:o.height}}),i.jsxs("aside",{"data-testid":"product-tour-checklist",className:"fixed hidden rounded-[var(--radius-md)] border border-[color:color-mix(in_oklab,var(--border-strong)_72%,transparent)] bg-popover/98 p-3 text-popover-foreground shadow-[var(--shadow-lg)] backdrop-blur md:block",style:{...g,width:d7},children:[i.jsx("div",{className:"mb-2 text-[13px] font-semibold text-foreground",children:e("productTour.checklist.title")}),i.jsx("div",{className:"space-y-0.5",children:Ty.map((v,w)=>i.jsxs("div",{className:K("grid min-h-8 grid-cols-[18px_minmax(0,1fr)] items-center gap-2 border-t border-[color:color-mix(in_oklab,var(--border-soft)_76%,transparent)] py-1.5 text-[12px]",w===0&&"border-t-0",w===s?"text-foreground":"text-muted-foreground"),children:[w<s?i.jsx(Zs,{className:"h-3.5 w-3.5 rounded-full bg-[color:var(--accent-base)] p-0.5 text-primary-foreground"}):i.jsx(sE,{className:K("h-3.5 w-3.5",w===s&&"text-[color:var(--accent-strong)]")}),i.jsx("span",{children:e(v.checklistKey)})]},v.id))})]}),i.jsxs("section",{"data-testid":"product-tour-callout",className:"fixed rounded-[var(--radius-md)] border border-[color:color-mix(in_oklab,var(--border-strong)_74%,transparent)] bg-popover/98 p-3.5 text-popover-foreground shadow-[var(--shadow-lg)] backdrop-blur",style:{left:m.left,top:m.top,width:m.width},children:[i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"mb-1 text-[11px] text-muted-foreground",children:e("productTour.stepCounter",{current:s+1,total:Ty.length})}),i.jsx("h2",{id:"product-tour-title",className:"text-[15px] font-semibold leading-5 text-foreground",children:e(u.titleKey)})]}),i.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",className:"-mr-1 -mt-1 text-muted-foreground",onClick:x,"aria-label":e("productTour.skip"),title:e("productTour.skip"),children:i.jsx(Is,{className:"h-4 w-4"})})]}),i.jsx("p",{className:"mt-2 text-[13px] leading-5 text-muted-foreground",children:e(u.bodyKey)}),i.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[i.jsxs(le,{type:"button",variant:"outline",size:"sm",className:"h-8",disabled:s===0,onClick:()=>y(s-1),children:[i.jsx(Tj,{className:"h-4 w-4"}),e("productTour.back")]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-8",onClick:x,children:e("productTour.skip")}),i.jsxs(le,{type:"button",size:"sm",className:"h-8",onClick:()=>{if(f){x();return}y(s+1)},children:[e(f?"productTour.finish":"productTour.next"),f?i.jsx(Zs,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})]})]})]})]})]})}function y2e(e){return`/${e.trim()}/organization/settings`}function pBn(e){const t=Pn();if(t){(t.forceOpenExternal??t.openExternal)(e);return}window.open(e,"_blank","noopener,noreferrer")}function gBn({href:e,label:t,variant:n}){return i.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",onClick:r=>{r.preventDefault(),pBn(e)},className:IE({variant:n,active:!1}),children:[i.jsx(nE,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"flex-1 truncate",children:t}),i.jsx(Ja,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80","aria-hidden":"true"})]})}function mde({showOrganizationSwitcher:e=!0,showBackButton:t=!0,variant:n="panel"}){const r=bs("rudder:sidebar-scroll:settings"),{t:s}=is(),a=Yr(),o=br(),{isMobile:l,setSidebarOpen:c}=jc(),{organizations:d}=jr(),{viewedOrganizationId:u}=th(),{data:f}=Me({queryKey:V.access.currentBoardAccess,queryFn:()=>bc.getCurrentBoardAccess(),retry:!1}),{data:A}=Me({queryKey:V.plugins.all,queryFn:()=>bo.list()}),{data:m}=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1}),g=(f==null?void 0:f.isInstanceAdmin)===!0,x=(m==null?void 0:m.deploymentMode)==="local_trusted",y=Hj(o.state),v=n==="modal",[w,k]=h.useState(!v),S=h.useMemo(()=>v&&!w?[]:GVe(d.filter(C=>C.status!=="archived")),[v,d,w]);h.useEffect(()=>{if(!v){k(!0);return}k(!1);const C=window.setTimeout(()=>k(!0),250);return()=>window.clearTimeout(C)},[v]);function j(C){a(y2e(Oc(C)),y?{state:y}:void 0),l&&c(!1)}return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:K("flex min-h-0 shrink-0 flex-col",v?"settings-modal-sidebar h-full w-[min(84vw,240px)] md:w-[184px]":"workspace-context-sidebar w-[248px]"),children:[v?null:i.jsxs("div",{className:"flex shrink-0 flex-col gap-2 border-b panel-divider px-3 py-3",children:[i.jsxs("div",{className:"flex items-center gap-2 px-2.5 text-muted-foreground",children:[i.jsx(Ix,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"text-[13px] font-semibold tracking-[-0.01em] text-foreground",children:s("common.systemSettings")})]}),e?i.jsx(che,{}):null,t?i.jsx(le,{variant:"ghost",className:"h-9 w-full justify-start gap-2 rounded-[var(--radius-md)] px-2.5 text-[13px] font-medium text-muted-foreground hover:text-foreground",asChild:!0,children:i.jsxs(sn,{to:Qc,children:[i.jsx(Kx,{className:"h-4 w-4"}),s("common.backToWorkspace")]})}):null]}),i.jsxs("nav",{ref:r,className:K("scrollbar-auto-hide flex min-h-0 flex-1 flex-col overflow-y-auto",v?"gap-4 px-3 py-5":"gap-5 px-3 py-3"),children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.personal")}),i.jsx(sd,{to:"/instance/settings/profile",state:y,label:s("common.profile"),icon:wBe,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/shortcuts",state:y,label:s("common.shortcuts"),icon:jBe,end:!0,variant:v?"compact":"default"})]}),g?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.desktopApp")}),i.jsx(sd,{to:"/instance/settings/general",state:y,label:s("common.general"),icon:Ej,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/appearance",state:y,label:s("general.appearance.title"),icon:ZK,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/experimental",state:y,label:s("common.experimental"),icon:lBe,end:!0,variant:v?"compact":"default"}),x?i.jsx(sd,{to:"/instance/settings/browser",state:y,label:s("common.browser"),icon:up,end:!0,variant:v?"compact":"default"}):null,i.jsx(sd,{to:"/instance/settings/notifications",state:y,label:s("common.systemPermissions"),icon:Tx,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/privacy",state:y,label:s("common.privacyTelemetry"),icon:Tx,end:!0,variant:v?"compact":"default"}),i.jsx(sd,{to:"/instance/settings/about",state:y,label:s("common.about"),icon:Xfe,end:!0,variant:v?"compact":"default"})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.runtime")}),i.jsx(sd,{to:"/instance/settings/heartbeats",state:y,label:s("common.heartbeats"),icon:Cx,end:!0,variant:v?"compact":"default"})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.integrations")}),i.jsx(sd,{to:"/instance/settings/plugins",state:y,label:s("common.plugins"),icon:uT,variant:v?"compact":"default"}),(A??[]).length>0?i.jsx("div",{className:"ml-4 mt-1 flex flex-col gap-1 border-l border-[color:color-mix(in_oklab,var(--border-soft)_78%,transparent)] pl-4",children:(A??[]).map(C=>i.jsx(Pj,{to:`/instance/settings/plugins/${C.id}`,state:y,className:({isActive:N})=>K("rounded-[calc(var(--radius-sm)+2px)] px-2 py-1.5 text-xs transition-colors",N?"bg-[color:color-mix(in_oklab,var(--surface-active)_48%,transparent)] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_24%,transparent)] hover:text-foreground"),children:C.manifestJson.displayName??C.packageName},C.id))}):null]})]}):null,i.jsx("div",{className:K("flex flex-col gap-1 border-t border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] pt-3",!v&&!w&&"mt-auto"),children:i.jsx(gBn,{href:xT,label:s("common.docs"),variant:v?"compact":"default"})}),w&&S.length>0?i.jsxs("div",{className:K("flex flex-col gap-1 pt-2",!v&&"mt-auto"),children:[i.jsx("div",{className:K("px-3 font-medium text-muted-foreground/78",v?"text-[11px]":"text-[12px]"),children:s("common.yourOrganizations")}),i.jsx("div",{className:"flex flex-col gap-1",children:S.map(C=>{const N=C.id===u;return i.jsxs("button",{type:"button",onClick:()=>j(C),"aria-label":C.name,className:K("flex w-full items-center gap-2.5 rounded-[calc(var(--radius-md)-2px)] px-3 py-2 text-left transition-colors",N?"bg-[color:var(--surface-active)] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_24%,transparent)] hover:text-foreground"),"aria-pressed":N,children:[i.jsx(UP,{organizationName:C.name,logoUrl:C.logoUrl,brandColor:C.brandColor,className:"h-5 w-5 shrink-0 rounded-md text-[10px]"}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-medium",title:C.name,children:C.name}),N?i.jsx(Zs,{className:"h-3.5 w-3.5 shrink-0 text-[color:var(--accent-strong)]"}):null]},C.id)})})]}):null]})]})}function xBn(e){var n,r,s,a;const t=new URLSearchParams({start:e.start,end:e.end});return(n=e.agentIds)!=null&&n.length&&t.set("agentIds",e.agentIds.join(",")),(r=e.sourceIds)!=null&&r.length&&t.set("sourceIds",e.sourceIds.join(",")),(s=e.eventKinds)!=null&&s.length&&t.set("eventKinds",e.eventKinds.join(",")),(a=e.statuses)!=null&&a.length&&t.set("statuses",e.statuses.join(",")),t.toString()}const su={sources:e=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/sources`),createSource:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/sources`,t),updateSource:(e,t,n)=>Re.patch(`/orgs/${encodeURIComponent(e)}/calendar/sources/${encodeURIComponent(t)}`,n),deleteSource:(e,t)=>Re.delete(`/orgs/${encodeURIComponent(e)}/calendar/sources/${encodeURIComponent(t)}`),events:(e,t)=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/events?${xBn(t)}`),getEvent:(e,t)=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/events/${encodeURIComponent(t)}`),createEvent:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/events`,t),updateEvent:(e,t,n)=>Re.patch(`/orgs/${encodeURIComponent(e)}/calendar/events/${encodeURIComponent(t)}`,n),deleteEvent:(e,t)=>Re.delete(`/orgs/${encodeURIComponent(e)}/calendar/events/${encodeURIComponent(t)}`),googleConfig:e=>Re.get(`/orgs/${encodeURIComponent(e)}/calendar/google/config`),updateGoogleConfig:(e,t)=>Re.patch(`/orgs/${encodeURIComponent(e)}/calendar/google/config`,t),connectGoogle:e=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/google/connect`,{}),syncGoogle:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/calendar/google/sync`,{sourceId:t??null})};function bBn({agent:e,orgId:t,triggerTestId:n,triggerClassName:r,visibilityClassName:s,onActionComplete:a}){const[o,l]=h.useState(!1),c=Vn(),d=Yr(),{openNewIssue:u}=ii(),{pushToast:f}=ss(),A=e.status==="terminated",m=e.status==="paused",g=async()=>{await Promise.all([c.invalidateQueries({queryKey:V.agents.list(t)}),c.invalidateQueries({queryKey:V.org(t)}),c.invalidateQueries({queryKey:V.agentRuns(t)}),c.invalidateQueries({queryKey:V.liveRuns(t)})])},x=xt({mutationFn:()=>Nn.invoke(e.id,t),onSuccess:async j=>{await g(),a==null||a(),f({title:"Heartbeat started",tone:"success",action:{label:"Open run",href:`/agents/${e3(e)}/runs/${j.id}`}})},onError:j=>{f({title:"Failed to run heartbeat",body:j instanceof Error?j.message:void 0,tone:"error"})}}),y=xt({mutationFn:()=>m?Nn.resume(e.id,t):Nn.pause(e.id,t),onSuccess:async()=>{await g(),a==null||a(),f({title:m?"Agent resumed":"Agent paused",tone:"success"})},onError:j=>{f({title:m?"Failed to resume agent":"Failed to pause agent",body:j instanceof Error?j.message:void 0,tone:"error"})}}),v=()=>{u({assigneeAgentId:e.id}),a==null||a()},w=()=>{a==null||a(),d({pathname:"/messenger/chat",search:`?agentId=${encodeURIComponent(e.id)}`})},k=async()=>{try{await navigator.clipboard.writeText(e.name),a==null||a(),f({title:"Copied agent name",tone:"success"})}catch(j){f({title:"Failed to copy agent name",body:j instanceof Error?j.message:void 0,tone:"error"})}},S=x.isPending||y.isPending;return i.jsxs(Ei,{open:o,onOpenChange:l,children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-label":`More actions for ${e.name}`,"data-testid":n??`agent-row-actions-${e.id}`,className:K("flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",o||S?"opacity-100":s??"opacity-100 md:opacity-0 md:group-hover/agent-row:opacity-100 md:group-focus-within/agent-row:opacity-100",r),onClick:j=>{j.preventDefault(),j.stopPropagation()},children:S?i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay w-48 text-foreground",children:[i.jsxs(Xt,{onSelect:v,children:[i.jsx(Zr,{className:"h-4 w-4"}),"Create task"]}),i.jsxs(Xt,{onSelect:w,disabled:A,children:[i.jsx(pa,{className:"h-4 w-4"}),"Chat with agent"]}),i.jsx(Yo,{}),i.jsxs(Xt,{onSelect:()=>x.mutate(),disabled:x.isPending||A,children:[i.jsx(BCt,{className:"h-4 w-4"}),"Run heartbeat"]}),i.jsxs(Xt,{onSelect:()=>y.mutate(),disabled:y.isPending||A,children:[m?i.jsx(zA,{className:"h-4 w-4"}):i.jsx(HK,{className:"h-4 w-4"}),m?"Resume agent":"Pause agent"]}),i.jsx(Yo,{}),i.jsxs(Xt,{onSelect:()=>void k(),children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy agent name"]})]})]})}function WPe(e,t=""){return`/projects/${encodeURIComponent(e)}/app-builder${t}`}function s$(e,t,n=""){return`/app-builder/${encodeURIComponent(t)}${n}?orgId=${encodeURIComponent(e)}`}const Fh={list:e=>Re.get(`/orgs/${encodeURIComponent(e)}/app-builder`),async get(e){try{return await Re.get(WPe(e))}catch(t){if(t instanceof Nl&&t.status===404)return null;throw t}},create:(e,t)=>Re.post(`/orgs/${encodeURIComponent(e)}/app-builder`,t),createForProject:(e,t)=>Re.post(WPe(e),t),updateBuild:(e,t,n)=>Re.patch(s$(e,t,"/build"),n),attachConversation:(e,t,n)=>Re.patch(s$(e,t,"/conversation"),{conversationId:n}),bindLocalRuntime:(e,t,n)=>Re.put(s$(e,t,"/local-binding"),n),clearLocalRuntime:(e,t)=>Re.delete(s$(e,t,"/local-binding"))};let ZPe=0;const K_=new Map,lq=new Set,yBn=1e4;function v2e(e,t){return`${e}:${t}`}function vBn(e,t){ZPe+=1,K_.set(v2e(e,t),{createdAt:Date.now(),version:ZPe}),lq.forEach(n=>n())}function wBn(e,t){const n=v2e(e,t),r=K_.get(n);return r?Date.now()-r.createdAt<=yBn?r.version:(K_.delete(n),0):0}function kBn(e,t,n){var s;const r=v2e(e,t);((s=K_.get(r))==null?void 0:s.version)===n&&(K_.delete(r),lq.forEach(a=>a()))}function OBn(e){return lq.add(e),()=>lq.delete(e)}function pde(e){return`/apps/view/${encodeURIComponent(e)}`}function N7(e,t,n){return`${e}:${t}:${n}`}function bft(e){const n=fl(e).match(/^\/apps\/view\/([^/]+)$/);if(!(n!=null&&n[1]))return"home";try{return decodeURIComponent(n[1])}catch{return"home"}}function SBn(e){return e==="preparing"?"Preparing":e==="building"?"Building":e==="verifying"?"Verifying":e==="ready"?"Ready":"Needs attention"}function yft(e){var g;const{organizations:t,selectedOrganizationId:n}=jr(),r=(g=Pn())==null?void 0:g.localApps,s=Me({queryKey:V.appBuilder.organization(n??"__none__"),queryFn:()=>Fh.list(n),enabled:!!(n&&e)}),a=RFe({queries:t.filter(x=>x.id!==n).map(x=>({queryKey:V.appBuilder.organization(x.id),queryFn:()=>Fh.list(x.id),enabled:e}))}),o=Me({queryKey:V.localApps.definitions,queryFn:()=>r.list(),enabled:!!(r!=null&&r.supported&&e)}),l=h.useMemo(()=>new Map((o.data??[]).map(x=>[N7(x.desktopInstallationId,x.appPublicId,x.localBindingId),x])),[o.data]),c=h.useMemo(()=>(s.data??[]).map(x=>({kind:"managed",key:`managed:${x.id}`,app:x,definition:x.desktopInstallationId&&x.appPublicId&&x.localBindingId?l.get(N7(x.desktopInstallationId,x.appPublicId,x.localBindingId))??null:null})),[s.data,l]),d=h.useMemo(()=>new Set([...s.data??[],...a.flatMap(x=>x.data??[])].flatMap(x=>x.desktopInstallationId&&x.appPublicId&&x.localBindingId?[N7(x.desktopInstallationId,x.appPublicId,x.localBindingId)]:[])),[s.data,a]),u=!!(e&&s.isSuccess&&!s.isFetching&&a.every(x=>x.isSuccess&&!x.isFetching)),f=!!(u&&(!(r!=null&&r.supported)||o.isSuccess&&!o.isFetching)),A=h.useMemo(()=>u?(o.data??[]).filter(x=>!d.has(N7(x.desktopInstallationId,x.appPublicId,x.localBindingId))).map(x=>({kind:"local",key:`local:${x.id}`,definition:x})):[],[o.data,u,d]),m=h.useMemo(()=>[...c,...A],[A,c]);return{appsQuery:s,definitionsQuery:o,entries:m,localApps:r,registryReady:f}}const jBn=["Use $app-builder to create or improve a Rudder App.","Help me clarify what this local web app should do before building it."].join(" ");function CBn({entry:e,className:t}){return e.definition?i.jsx(Z6,{className:t,iconDataUrl:e.definition.iconDataUrl}):i.jsx("span",{className:K("flex items-center justify-center rounded-[var(--radius-sm)] bg-[color:color-mix(in_oklab,var(--accent-base)_18%,transparent)] text-[color:var(--accent-base)]",t),children:i.jsx(sA,{className:"h-3.5 w-3.5","aria-hidden":!0})})}function NBn({entry:e,onSettings:t}){var k;const n=Yr(),r=Vn(),{pushToast:s}=ss(),a=Pn(),o=a==null?void 0:a.localApps,l=a==null?void 0:a.appBuilder,c=e.definition,[d,u]=h.useState(null),f=Me({queryKey:V.localApps.status((c==null?void 0:c.localBindingId)??e.key),queryFn:()=>o.status(c.id),enabled:!!(o!=null&&o.supported&&c),refetchInterval:S=>{var j;return pW((j=S.state.data)==null?void 0:j.status)}}),A=xt({mutationFn:()=>o.stop(c.id),onMutate:()=>{c&&r.setQueryData(V.localApps.status(c.localBindingId),S=>S&&{...S,status:"stopping"})},onSuccess:S=>{c&&r.setQueryData(V.localApps.status(c.localBindingId),S)},onError:()=>{c&&r.invalidateQueries({queryKey:V.localApps.status(c.localBindingId)})}}),m=xt({mutationFn:async S=>{if(e.kind!=="managed"||!c||!(l!=null&&l.supported))throw new Error("App data controls are unavailable on this device.");const j={projectId:e.app.orgId,appDirectory:e.app.sourceRoot,binding:{desktopInstallationId:c.desktopInstallationId,definitionId:c.id,appPublicId:c.appPublicId,localBindingId:c.localBindingId}};if(S==="backup"){const N=await l.snapshot(j);(await l.exportSnapshot({...j,snapshotId:N.id})).canceled||(u(N.id),s({title:"App data backup exported",tone:"success"}));return}if(S==="import"){const N=await l.importData(j);N.canceled||(u(N.rollbackSnapshot.id),s({title:"App data imported",body:"The previous data is available as a restore point.",tone:"success"}));return}if(!d)throw new Error("Create a backup or import data first.");const C=await l.restoreSnapshot({...j,snapshotId:d});u(C.safetySnapshot.id),s({title:"App data restored",body:"A safety snapshot was kept.",tone:"success"})},onError:S=>{s({title:"App data operation failed",body:S instanceof Error?S.message:void 0,tone:"error"})},onSettled:()=>{c&&r.invalidateQueries({queryKey:V.localApps.status(c.localBindingId)})}}),g=(k=f.data)==null?void 0:k.status,x=g==="running",y=g==="starting"||g==="running"||g==="stopping"||g==="orphaned_unverified"||f.isPending||m.isPending,v=async S=>{if(!c||!o)return;const j=await o.attestedTarget(c.id);if(!j){s({title:"App link unavailable",body:"Open the App and wait for it to finish starting.",tone:"error"});return}const{src:C}=XAe(j);if(S==="copy"){await(a==null?void 0:a.copyText(C)),s({title:"App link copied",tone:"success"});return}const N=(a==null?void 0:a.forceOpenExternal)??(a==null?void 0:a.openExternal);await(N==null?void 0:N(C))},w=e.kind==="managed"?e.app.name:e.definition.title;return i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground opacity-0 transition-[background-color,color,opacity] hover:bg-[color:var(--surface-elevated)] hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100 data-[state=open]:opacity-100 motion-reduce:transition-none","aria-label":`More options for ${w}`,"data-testid":`apps-more-${e.key}`,children:i.jsx(hl,{className:"h-4 w-4","aria-hidden":!0})})}),i.jsxs(Ri,{align:"start",side:"right",className:"surface-overlay min-w-48 text-foreground",children:[c?i.jsxs(Xt,{onSelect:()=>t(c,y),children:[i.jsx(Ix,{"aria-hidden":!0}),"App settings"]}):null,c||e.kind==="managed"?i.jsxs(Xt,{onSelect:()=>{if(c){a==null||a.openPath(c.cwd).catch(S=>{s({title:"Could not open App source",body:S instanceof Error?S.message:void 0,tone:"error"})});return}e.kind==="managed"&&n(`/library?directory=${encodeURIComponent(e.app.sourceRoot)}`)},children:[i.jsx(qB,{"aria-hidden":!0}),"Open source"]}):null,e.kind==="managed"&&e.app.conversationId?i.jsxs(Xt,{onSelect:()=>n(`/messenger/chat/${e.app.conversationId}`),children:[i.jsx(pa,{"aria-hidden":!0}),"Continue in Chat"]}):null,c?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{disabled:!x,onSelect:()=>void v("copy"),"data-testid":`apps-copy-link-${e.key}`,children:[i.jsx(Al,{"aria-hidden":!0}),"Copy App link"]}),i.jsxs(Xt,{disabled:!x,onSelect:()=>void v("external"),children:[i.jsx(Ja,{"aria-hidden":!0}),"Open in browser"]}),e.kind==="managed"&&(l!=null&&l.supported)?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{disabled:m.isPending,onSelect:()=>m.mutate("backup"),children:[i.jsx(Tg,{"aria-hidden":!0}),"Back up data"]}),i.jsxs(Xt,{disabled:m.isPending,onSelect:()=>m.mutate("import"),children:[i.jsx(bS,{"aria-hidden":!0}),"Import data"]}),i.jsxs(Xt,{disabled:!d||m.isPending,onSelect:()=>m.mutate("restore"),children:[i.jsx(_2,{"aria-hidden":!0}),"Restore previous data"]})]}):null,i.jsx(Yo,{}),i.jsxs(Xt,{disabled:!y||A.isPending,onSelect:()=>A.mutate(),children:[i.jsx(vb,{"aria-hidden":!0}),"Stop App"]})]}):null]})]})}function PBn(){var k,S;const{isMobile:e,setSidebarOpen:t}=jc(),{selectedOrganizationId:n}=jr(),r=Yr(),s=br(),a=Vn(),[o,l]=h.useState(""),[c,d]=h.useState(null),f=((S=(k=Me({queryKey:V.health,queryFn:()=>rA.get()}).data)==null?void 0:k.features)==null?void 0:S.experimentalSitesEnabled)===!0,{entries:A,localApps:m}=yft(f),g=bft(s.pathname),x=A.filter(j=>(j.kind==="managed"?j.app.name:j.definition.title).toLowerCase().includes(o.trim().toLowerCase())),y=xt({mutationFn:()=>m.discover(),onSuccess:j=>{j.canceled||d({definition:j.draft,editId:null,editable:!0})}}),v=xt({mutationFn:j=>c!=null&&c.editId?m.update(c.editId,j):m.create(j),onSuccess:j=>{a.setQueryData(V.localApps.definitions,C=>{const N=C??[];return N.some(P=>P.id===j.id)?N.map(P=>P.id===j.id?j:P):[...N,j]}),d(null),r(pde(`local:${j.id}`))}}),w=xt({mutationFn:()=>m.stop(c.editId),onSuccess:j=>{!c||!("localBindingId"in c.definition)||(a.setQueryData(V.localApps.status(c.definition.localBindingId),j),d(C=>C&&{...C,editable:!0}))}});return i.jsxs(i.Fragment,{children:[i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx(sA,{className:"h-4 w-4 shrink-0 text-[color:var(--accent-base)]","aria-hidden":!0}),i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:"Apps"})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx(le,{type:"button",size:"icon-sm",variant:"ghost",title:"Add an App","aria-label":"Add an App",disabled:!f,"data-testid":"apps-add",children:i.jsx(Zr,{className:"h-4 w-4","aria-hidden":!0})})}),i.jsxs(Ri,{align:"start",className:"surface-overlay w-80 max-w-[calc(100vw-1.5rem)] text-foreground",children:[i.jsxs(Xt,{className:"items-start gap-3 px-3 py-2.5","data-testid":"apps-build-with-agent",onSelect:()=>r(`/messenger/chat?prefill=${encodeURIComponent(jBn)}`),children:[i.jsx(Hh,{className:"mt-0.5","aria-hidden":!0}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-sm font-medium",children:"Build with Agent"}),i.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"Create or improve a web App with App Builder."})]})]}),i.jsxs(Xt,{className:"items-start gap-3 px-3 py-2.5",disabled:!(m!=null&&m.supported)||y.isPending,"data-testid":"apps-add-local-project",onSelect:()=>y.mutate(),children:[y.isPending?i.jsx(hn,{className:"mt-0.5 animate-spin motion-reduce:animate-none","aria-hidden":!0}):i.jsx(qB,{className:"mt-0.5","aria-hidden":!0}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-sm font-medium",children:"Add local web project"}),i.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"Load a Next.js, React, Vue, or other web project from this computer."})]})]})]})]}),e?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>t(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]})]}),i.jsx("div",{className:"p-3 pb-2",children:i.jsxs("div",{className:"relative",children:[i.jsx(Fl,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),i.jsx(Kn,{type:"search",value:o,onChange:j=>l(j.target.value),className:"h-8 pl-8 text-xs",placeholder:"Search Apps","aria-label":"Search Apps"})]})}),i.jsxs("nav",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-2 pb-3","aria-label":"Apps",children:[i.jsxs("button",{type:"button",className:K("flex h-9 w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2.5 text-left text-sm transition-[background-color,color] duration-150 motion-reduce:transition-none",g==="home"?"bg-[color:var(--surface-active)] font-medium text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_55%,transparent)] hover:text-foreground"),onClick:()=>r("/apps"),children:[i.jsx(Hfe,{className:"h-4 w-4","aria-hidden":!0}),"Home"]}),i.jsxs("div",{className:"mb-1.5 mt-4 flex items-center justify-between px-2.5",children:[i.jsx("span",{className:"text-[11px] font-medium text-muted-foreground/76",children:"Registered"}),i.jsx("span",{className:"text-[10px] tabular-nums text-muted-foreground",children:A.length})]}),x.length?i.jsx("div",{className:"space-y-0.5",children:x.map(j=>{const C=j.kind==="managed"?j.app.name:j.definition.title,N=j.key===g,P=j.kind==="managed"&&!j.definition?SBn(j.app.buildStatus):"On this device";return i.jsxs("div",{className:K("group motion-list-enter flex w-full items-center rounded-[calc(var(--radius-sm)-1px)] transition-[background-color,color] duration-150 motion-reduce:transition-none",N?"bg-[color:var(--surface-active)] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-active)_55%,transparent)] hover:text-foreground"),children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2.5 px-2 py-2 text-left",onClick:()=>{n&&j.definition&&vBn(n,j.key),r(pde(j.key))},"data-testid":`apps-entry-${j.key}`,children:[i.jsx(CBn,{entry:j,className:"h-7 w-7 shrink-0"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-xs font-medium",children:C}),i.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:P})]})]}),i.jsx("div",{className:"pr-1",children:i.jsx(NBn,{entry:j,onSettings:(M,E)=>{v.reset(),w.reset(),d({definition:M,editId:M.id,editable:!E})}})})]},j.key)})}):i.jsxs("div",{className:"mx-2 mt-3 rounded-[var(--radius-sm)] border border-dashed border-[color:var(--border-soft)] px-3 py-5 text-center",children:[i.jsx(qB,{className:"mx-auto h-5 w-5 text-muted-foreground","aria-hidden":!0}),i.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:o?"No matching Apps.":"Create or load your first App."})]})]})]}),c?i.jsx(gW,{definition:c.definition,edit:!!c.editId,editable:c.editable,error:v.error??w.error,open:!0,pending:v.isPending,requestEditPending:w.isPending,onCancel:()=>{v.reset(),w.reset(),d(null)},onRequestEdit:()=>w.mutate(),onSubmit:j=>v.mutate(j)}):null,y.error?i.jsxs("div",{className:"fixed bottom-5 right-5 z-50 flex max-w-sm items-start gap-3 rounded-[var(--radius-lg)] border border-destructive/30 bg-[color:var(--surface-overlay)] p-4 text-sm text-destructive shadow-lg",role:"alert",children:[i.jsx(Kc,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":!0}),i.jsx("span",{children:y.error instanceof Error?y.error.message:"Could not load this App."})]}):null]})}const W_=["slate","teal","sky","indigo","amber","rose","red","orange"],vft="::",IBn=new Set(HM),DD={slate:{bg:"#eef1ef",bgDark:"#313633",bgHover:"#e0e5e2",bgHoverDark:"#3b423e",border:"#d1d8d3",borderDark:"#545d58",text:"#26302a",textDark:"#f0f4f1",entryText:"#26302a",entryTextDark:"#eef2ef",swatch:"#242827"},teal:{bg:"#dff4ed",bgDark:"#143f36",bgHover:"#ccebe2",bgHoverDark:"#185247",border:"#a9d9cc",borderDark:"#2a7668",text:"#126454",textDark:"#d9fff5",entryText:"#173c35",entryTextDark:"#effffb",swatch:"#08a88a"},sky:{bg:"#dff1fb",bgDark:"#13394c",bgHover:"#c9e8f8",bgHoverDark:"#174b64",border:"#a9d7ee",borderDark:"#28708f",text:"#096287",textDark:"#dff7ff",entryText:"#153747",entryTextDark:"#f0fbff",swatch:"#0c8fca"},indigo:{bg:"#e6e5f8",bgDark:"#2d2c58",bgHover:"#d8d6f1",bgHoverDark:"#393873",border:"#c1bee6",borderDark:"#5b58a8",text:"#4c4695",textDark:"#f0efff",entryText:"#302e56",entryTextDark:"#f4f3ff",swatch:"#6259b5"},amber:{bg:"#f7edc2",bgDark:"#4a3914",bgHover:"#eee0a8",bgHoverDark:"#604a18",border:"#deca80",borderDark:"#9b7b2c",text:"#885900",textDark:"#ffeec2",entryText:"#4b3812",entryTextDark:"#fff8e5",swatch:"#f2a900"},rose:{bg:"#f3d5da",bgDark:"#4d252d",bgHover:"#eac3ca",bgHoverDark:"#63303a",border:"#dba8b2",borderDark:"#9b5664",text:"#7f2634",textDark:"#ffe9ee",entryText:"#51242c",entryTextDark:"#fff4f6",swatch:"#df6f83"},red:{bg:"#f0cdd1",bgDark:"#542126",bgHover:"#e7bac0",bgHoverDark:"#6a2a30",border:"#d59aa3",borderDark:"#a34d58",text:"#84242e",textDark:"#ffe8eb",entryText:"#552126",entryTextDark:"#fff1f2",swatch:"#d24b58"},orange:{bg:"#f4ddce",bgDark:"#552e1d",bgHover:"#edcbb7",bgHoverDark:"#6d3b25",border:"#dda98c",borderDark:"#a8623d",text:"#793816",textDark:"#ffeadf",entryText:"#512b1c",entryTextDark:"#fff4ee",swatch:"#ec6c3b"}};function TBn(e){return W_.includes(e)}function cq(e){const t=e==null?void 0:e.trim();if(!t)return{glyph:"folder",color:null};const[n,r]=t.split(vft);return{glyph:(n==null?void 0:n.trim())||"folder",color:TBn(r)?r:null}}function _ne(e,t){const n=e.trim()||"folder";return t?`${n}${vft}${t}`:n}function FI(e){const t=cq(e.icon);return t.color?t.color:W_[Math.abs(e.sortOrder??e.id.length)%W_.length]??"slate"}function _Bn(e){const t=DD[FI(e)];return{"--messenger-group-bg":t.bg,"--messenger-group-bg-dark":t.bgDark,"--messenger-group-bg-hover":t.bgHover,"--messenger-group-bg-hover-dark":t.bgHoverDark,"--messenger-group-border":t.border,"--messenger-group-border-dark":t.borderDark,"--messenger-group-text":t.text,"--messenger-group-text-dark":t.textDark,"--messenger-group-entry-text":t.entryText,"--messenger-group-entry-text-dark":t.entryTextDark}}function w2e(e){const{glyph:t}=cq(e);return t.trim()||null}function MH(e){return IBn.has((e??"").trim().toLowerCase())}function MBn(e){var n;const t=(n=w2e(e))==null?void 0:n.toLowerCase();return MH(t)?t:kK}function wft(e){return VAe(DD[e??"slate"].swatch)}function EBn(e){return!MH(e)&&/[^\x00-\x7F]/.test(e)}function RD({icon:e,color:t}){const n=w2e(e);if(!n||MH(n)){const r=t??FI({id:n??kK,icon:e??null,sortOrder:0});return i.jsx(uo,{color:DD[r].swatch,icon:MBn(e),size:"xs",className:"h-4 w-4",iconClassName:"h-4 w-4 text-[color:var(--project-accent-color)]",testId:"messenger-custom-group-icon"})}return EBn(n)?i.jsx("span",{"aria-hidden":!0,className:"inline-flex h-4 min-w-4 shrink-0 items-center justify-center text-[14px] leading-none",children:n}):i.jsx("span",{"aria-hidden":!0,className:"inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] bg-[color:color-mix(in_oklab,var(--surface-active)_72%,transparent)] px-0.5 text-[10px] font-semibold leading-none text-muted-foreground",children:n.slice(0,2)})}function kft({icon:e,ariaLabel:t,onIconChange:n}){const r=w2e(e);return i.jsx("div",{className:"space-y-1.5","aria-label":t,children:i.jsxs("div",{className:"grid grid-cols-6 gap-1.5","aria-label":`${t} options`,children:[HM.map(s=>{const a=oW(s),o=r&&MH(r)?s===r:!1;return i.jsx("button",{type:"button",className:K("relative inline-flex h-9 w-9 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] border text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",o?"border-[color:color-mix(in_oklab,var(--project-accent-color)_54%,var(--border-base))] bg-muted/55 text-[color:var(--project-accent-color)]":"border-border/70 bg-transparent"),"aria-label":`Select ${s} project icon`,"aria-pressed":o,onClick:()=>n(s),children:i.jsx(a,{className:"h-5 w-5",strokeWidth:2.2})},s)}),u3t.map(s=>{const a=s===r;return i.jsx("button",{type:"button",className:K("relative inline-flex h-9 w-9 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] border text-[18px] leading-none outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",a?"border-[color:color-mix(in_oklab,var(--project-accent-color)_54%,var(--border-base))] bg-muted/55":"border-border/70 bg-transparent"),"aria-label":`Select ${s} group emoji`,"aria-pressed":a,onClick:()=>n(s),children:i.jsx("span",{"aria-hidden":!0,children:s})},s)})]})})}function DBn({name:e,icon:t,color:n,pending:r,onNameChange:s,onIconChange:a,onColorChange:o,onCancel:l,onSubmit:c}){return i.jsxs("form",{"data-testid":"messenger-custom-group-editor",className:"p-2.5",onSubmit:d=>{d.preventDefault(),c()},children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx(RD,{icon:t,color:n}),i.jsx("div",{className:"min-w-0 flex-1 text-[12px] font-semibold text-foreground",children:"New group"})]}),i.jsx("input",{autoFocus:!0,"aria-label":"Group name",value:e,onChange:d=>s(d.currentTarget.value),className:"h-8 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-page)] px-2.5 text-[13px] outline-none transition-[border-color,box-shadow] focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30"}),i.jsx("div",{className:"mt-1.5 rounded-[calc(var(--radius-sm)-1px)] border border-[color:color-mix(in_oklab,var(--border-soft)_74%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-page)_72%,transparent)] p-1.5",style:wft(n),children:i.jsx(kft,{icon:t,ariaLabel:"Group icons",onIconChange:a})}),i.jsx("div",{className:"mt-2 flex items-center gap-1.5","aria-label":"Group color",children:W_.map(d=>{const u=DD[d];return i.jsx("button",{type:"button","aria-label":`Use ${d} group color`,"aria-pressed":n===d,className:K("inline-flex h-6 w-6 items-center justify-center rounded-full border transition-[border-color,box-shadow,transform] hover:scale-105",n===d?"border-[color:var(--border-strong)] shadow-[0_0_0_2px_var(--surface-elevated),0_0_0_4px_color-mix(in_oklab,var(--border-strong)_70%,transparent)]":"border-transparent"),style:{backgroundColor:u.swatch},onClick:()=>o(d)},d)})}),i.jsxs("div",{className:"mt-2.5 flex justify-end gap-1.5",children:[i.jsx("button",{type:"button",className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[12px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground",onClick:l,children:"Cancel"}),i.jsx("button",{type:"submit",disabled:r||!e.trim(),className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] bg-[color:var(--accent-strong)] px-2.5 text-[12px] font-semibold text-white transition-opacity disabled:cursor-not-allowed disabled:opacity-50",children:"Create"})]})]})}function RBn({name:e,pending:t,onNameChange:n,onCancel:r,onSubmit:s}){return i.jsxs("form",{"data-testid":"messenger-custom-group-rename",className:"mx-3 mt-2 rounded-md border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_96%,transparent)] p-2.5 shadow-sm",onSubmit:a=>{a.preventDefault(),s()},children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx(xg,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),i.jsx("div",{className:"min-w-0 flex-1 text-[12px] font-semibold text-foreground",children:"Rename group"})]}),i.jsx("input",{autoFocus:!0,"aria-label":"Group name",value:e,onChange:a=>n(a.currentTarget.value),className:"h-8 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-page)] px-2.5 text-[13px] outline-none transition-[border-color,box-shadow] focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30"}),i.jsxs("div",{className:"mt-2.5 flex justify-end gap-1.5",children:[i.jsx("button",{type:"button",className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[12px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground",onClick:r,children:"Cancel"}),i.jsx("button",{type:"submit",disabled:t||!e.trim(),className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] bg-[color:var(--accent-strong)] px-2.5 text-[12px] font-semibold text-white transition-opacity disabled:cursor-not-allowed disabled:opacity-50",children:"Save"})]})]})}class Oft{constructor(){Cs(this,"activeByChatId",new Map);Cs(this,"listenersByChatId",new Map);Cs(this,"getSnapshot",t=>this.activeByChatId.get(t)===!0);Cs(this,"subscribe",(t,n)=>{const r=this.listenersByChatId.get(t)??new Set;return r.add(n),this.listenersByChatId.set(t,r),()=>{r.delete(n),r.size===0&&this.listenersByChatId.delete(t)}})}setActive(t,n){if(this.getSnapshot(t)!==n){n?this.activeByChatId.set(t,!0):this.activeByChatId.delete(t);for(const r of this.listenersByChatId.get(t)??[])r()}}}const LBn=new Set,Sft={activeChatIds:LBn,streamDrafts:{},sendInFlightByChatId:{},isChatGenerationActive:()=>!1,setChatSendInFlight:()=>{},setStreamDraftForChat:()=>{},setStreamAbortController:()=>{},abortChatStream:()=>{}},jft=h.createContext(Sft),Cft=h.createContext(Sft),zBn=new Oft,Nft=h.createContext(zBn);function $Bn({children:e}){const t=PD(),[n,r]=h.useState({}),[s,a]=h.useState({}),o=h.useRef(n),l=h.useRef(null);l.current||(l.current=new Oft);const c=l.current,d=h.useRef({}),u=h.useRef(null),f=h.useRef(null),A=h.useRef(0),m=h.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null),r(o.current)},[]),g=h.useCallback(N=>{if(N){m();return}if(u.current!==null)return;const P=Date.now()<A.current;u.current=window.setTimeout(()=>{u.current=null,P?h.startTransition(()=>r(o.current)):r(o.current)},P?200:50)},[m]);h.useEffect(()=>{const N=()=>{A.current=Date.now()+120,f.current!==null&&window.clearTimeout(f.current),f.current=window.setTimeout(()=>{f.current=null,m()},120)};return window.addEventListener("scroll",N,{capture:!0,passive:!0}),window.addEventListener("wheel",N,{capture:!0,passive:!0}),()=>{window.removeEventListener("scroll",N,!0),window.removeEventListener("wheel",N,!0),u.current!==null&&window.clearTimeout(u.current),f.current!==null&&window.clearTimeout(f.current)}},[m]);const x=h.useMemo(()=>new Set(Object.keys(n)),[n]),y=h.useCallback((N,P)=>{a(M=>Yvn(M,N,P))},[]),v=h.useCallback((N,P)=>{const M=o.current,E=M[N]??null,T=typeof P=="function"?P(E):P,R=Jvn(M,N,T);if(R===M)return;if(o.current=R,c.setActive(N,T!==null),((E==null?void 0:E.state)!==(T==null?void 0:T.state)||E===null!=(T===null))&&t.updateSummary(`chat:${N}`,{status:(T==null?void 0:T.state)??(E?"completed":null)}),T===null&&E){u.current!==null&&(window.clearTimeout(u.current),u.current=null),r(M),window.setTimeout(()=>r(o.current),0);return}const _=T===null||T.state==="failed"||T.state==="stopped";g(_)},[t,g,c]),w=h.useCallback((N,P)=>{if(P){d.current={...d.current,[N]:P};return}if(!(N in d.current))return;const{[N]:M,...E}=d.current;d.current=E},[]),k=h.useCallback(N=>{var P;(P=d.current[N])==null||P.abort()},[]),S=h.useCallback(N=>!!(N&&c.getSnapshot(N)),[c]),j=h.useMemo(()=>({abortChatStream:k,isChatGenerationActive:S,setChatSendInFlight:y,setStreamDraftForChat:v,setStreamAbortController:w}),[k,S,y,w,v]),C=h.useMemo(()=>({activeChatIds:x,streamDrafts:n,sendInFlightByChatId:s,isChatGenerationActive:S,setChatSendInFlight:y,setStreamDraftForChat:v,setStreamAbortController:w,abortChatStream:k}),[k,x,S,s,y,w,v,n]);return i.jsx(Nft.Provider,{value:c,children:i.jsx(Cft.Provider,{value:j,children:i.jsx(jft.Provider,{value:C,children:e})})})}function Pft(){return h.useContext(jft)}function Ift(){return h.useContext(Cft)}function FBn(e){const t=h.useContext(Nft);return h.useSyncExternalStore(n=>t.subscribe(e,n),()=>t.getSnapshot(e),()=>t.getSnapshot(e))}function Z_(e){switch(e){case"chat":return"Chat";case"issues":return"Issues";case"approvals":return"Approvals";case"failed-runs":return"Failed runs";case"budget-alerts":return"Budget alerts";case"join-requests":return"Join requests";default:return e}}const HPe=1e3,BBn=120;function EH({dragHandleProps:e,label:t,compact:n=!1}){return e?i.jsx("button",{type:"button",...e.attributes,...e.listeners,"aria-label":t,title:t,className:K("shrink-0 cursor-grab touch-none rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/55 opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 active:cursor-grabbing group-hover:opacity-100 group-focus-within:opacity-100",n?"mt-0 flex h-5 w-4 items-center justify-center":"mt-0.5 flex h-6 w-4 items-center justify-center"),children:i.jsx(vBe,{className:"h-3.5 w-3.5","aria-hidden":!0})}):null}function QBn(e){switch(e){case"chat":return pa;case"issues":return xS;case"approvals":return Tx;case"failed-runs":return UK;case"budget-alerts":return Nx;case"join-requests":return Jfe;default:return Gf}}function oo(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function XPe(e){return qf(e.latestReplyPreview)||qf(e.summary)||(e.primaryIssue?`${e.primaryIssue.identifier??e.primaryIssue.id} · ${e.primaryIssue.title}`:null)||"Start the conversation"}function YF(e){return o6(e)}function GPe(e){return LP(e,{max:80})??e}function Tft({threadKey:e,eyebrow:t,title:n,description:r,metadata:s,suppressed:a=!1,children:o}){const[l,c]=h.useState(!1),d=h.useRef(null),u=h.useRef(null),f=h.useRef(a),A=h.useRef(!1),m=h.useRef(!1),g=h.useRef(!1),x=h.useRef(!1),y=(s==null?void 0:s.filter(E=>!!(E!=null&&E.trim())))??[];f.current=a;const v=E=>{E.current&&clearTimeout(E.current),E.current=null},w=()=>{v(d),v(u),!(f.current||A.current)&&c(!0)},k=()=>{v(d),v(u),!(f.current||A.current)&&(d.current=setTimeout(w,HPe))},S=()=>{k()},j=()=>{if(f.current){g.current=!0;return}!A.current||!m.current||(A.current=!1,m.current=!1,k())},C=()=>{v(d),v(u),u.current=setTimeout(()=>c(!1),BBn)},N=()=>{A.current&&(!f.current||g.current)&&(m.current=!0),C()},P=()=>{!f.current&&A.current&&(x.current=!0),C()},M=()=>{!f.current&&x.current&&(A.current=!1,x.current=!1),w()};return h.useEffect(()=>{a&&(A.current=!0,m.current=!1,g.current=!1,x.current=!1,v(d),v(u),c(!1))},[a]),h.useEffect(()=>()=>{v(d),v(u)},[]),i.jsx(Wc,{delayDuration:HPe,skipDelayDuration:0,children:i.jsxs(ra,{open:l&&!a,children:[i.jsx(sa,{asChild:!0,onMouseEnter:S,onMouseMove:j,onMouseLeave:N,onFocusCapture:M,onBlurCapture:P,children:o}),i.jsxs(ia,{side:"right",align:"start",sideOffset:8,collisionPadding:16,"data-testid":`messenger-thread-preview-${oo(e)}`,className:"motion-entity-preview-pop z-[70] w-[min(22rem,calc(100vw-2rem))] space-y-2 rounded-[var(--radius-md)] border border-border/80 bg-[color:var(--surface-overlay)] px-3.5 py-3 text-left text-foreground shadow-[var(--shadow-lg)]",onMouseEnter:w,onMouseLeave:C,children:[i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground",children:t}),i.jsx("div",{className:"break-words text-[13px] font-semibold leading-5 text-foreground",children:n}),r?i.jsx("div",{className:"line-clamp-6 whitespace-pre-wrap break-words text-[12px] leading-5 text-foreground/78",children:r}):null,y.length>0?i.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 border-t border-border/60 pt-2 text-[11px] text-muted-foreground",children:y.map(E=>i.jsx("span",{children:E},E))}):null]})]})})}function _ft({icon:e,unreadCount:t,needsAttention:n,density:r="comfortable",shape:s="circle",testId:a}){const o=r==="compact";return i.jsxs("span",{className:K("relative flex shrink-0 items-center justify-center border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)] text-[color:var(--accent-strong)]",o?"h-7 w-7":"mt-0.5 h-10 w-10",s==="rounded"?"rounded-[calc(var(--radius-sm)+1px)]":"rounded-full"),children:[i.jsx(e,{className:K(o?"h-3.5 w-3.5":"h-4.5 w-4.5")}),t>0?i.jsx("span",{"data-testid":a,className:"absolute -right-1.5 -top-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-[color:var(--surface-elevated)] bg-red-500 px-1 text-[10px] font-semibold leading-none text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]",children:t>99?"99+":t}):n?i.jsx("span",{"data-testid":a,className:"absolute -right-0.5 -top-0.5 h-3.5 w-3.5 rounded-full border-2 border-[color:var(--surface-elevated)] bg-red-500"}):null]})}function UBn({agent:e,agentId:t,unreadCount:n,needsAttention:r,density:s,testId:a}){if(!e&&!t)return i.jsx(_ft,{icon:pa,unreadCount:n,needsAttention:r,density:s,shape:"rounded",testId:`${a}-unread-badge`});const o=s==="compact";return i.jsxs("span",{"data-testid":a,title:e!=null&&e.name?`Chat agent: ${e.name}`:"Chat agent",className:K("relative flex shrink-0 items-center justify-center overflow-visible rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)]",o?"h-7 w-7":"mt-0.5 h-10 w-10"),children:[i.jsx(_g,{icon:e==null?void 0:e.icon,role:e==null?void 0:e.role,fallbackSeed:(e==null?void 0:e.id)??t,className:"h-full w-full rounded-full"}),n>0?i.jsx("span",{"data-testid":`${a}-unread-badge`,className:"absolute -right-1.5 -top-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-[color:var(--surface-elevated)] bg-red-500 px-1 text-[10px] font-semibold leading-none text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]",children:n>99?"99+":n}):r?i.jsx("span",{"data-testid":`${a}-unread-badge`,className:"absolute -right-0.5 -top-0.5 h-3.5 w-3.5 rounded-full border-2 border-[color:var(--surface-elevated)] bg-red-500"}):null]})}function VBn({status:e,unreadCount:t,needsAttention:n,density:r="comfortable",testId:s}){const a=r==="compact";return i.jsxs("span",{title:`Issue status: ${e.replace(/_/g," ")}`,className:K("relative flex shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)]",a?"h-7 w-7":"mt-0.5 h-10 w-10"),children:[i.jsx(ni,{status:e,className:K(a?"h-3.5 w-3.5":"h-4.5 w-4.5")}),t>0?i.jsx("span",{"data-testid":s,className:"absolute -right-1.5 -top-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-[color:var(--surface-elevated)] bg-red-500 px-1 text-[10px] font-semibold leading-none text-white shadow-[0_4px_12px_-6px_rgba(220,38,38,0.85)]",children:t>99?"99+":t}):n?i.jsx("span",{"data-testid":s,className:"absolute -right-0.5 -top-0.5 h-3.5 w-3.5 rounded-full border-2 border-[color:var(--surface-elevated)] bg-red-500"}):null]})}function qBn({conversation:e,agent:t,agentId:n,sourceBadge:r,href:s,active:a,generating:o,density:l,renaming:c,renameDraft:d,onRenameDraftChange:u,onCommitRename:f,onCancelRename:A,onStartRename:m,onRegenerateTitle:g,titleGenerating:x=!1,onFork:y,onArchive:v,onDelete:w,archiveDeleteAllowed:k=!0,onTogglePin:S,onToggleUnread:j,onCopyConversationLink:C,customGroups:N,customGroupId:P,customGroupPending:M,onMoveToCustomGroup:E,onRemoveFromCustomGroup:T,onCreateCustomGroup:R,dragHandleProps:_,dragging:D,onSelect:U}){const $=FBn(e.id),L=o??$,H=Bi(e.lastMessageAt??e.updatedAt,{compactDate:!0}),[X,F]=h.useState(!1),Q=h.useRef(null),q=h.useRef(null),B=h.useRef(!1),ee=l==="compact",se=ee?"right-1.5":"right-2",re=ee?"right-7":"right-8";return h.useEffect(()=>{(L||x)&&F(!1)},[L,x]),i.jsx(Tft,{threadKey:`chat:${e.id}`,eyebrow:"Chat",title:SW(e.title)?YF(e):e.title,description:XPe(e),metadata:[t!=null&&t.name?`Agent: ${t.name}`:null,H],suppressed:X,children:i.jsxs("div",{ref:Q,"data-testid":`messenger-thread-${oo(`chat:${e.id}`)}`,"data-messenger-thread-key":`chat:${e.id}`,className:K("group relative flex [contain-intrinsic-size:auto_44px] [content-visibility:auto] rounded-[calc(var(--radius-md)-2px)] border transition-[background-color,border-color,color]",P?"mx-0":"mx-1.5",ee?K("items-center gap-2 py-1.5",P?"px-1.5":"px-2"):K("items-start gap-3 py-2.5",P?"px-2":"px-3"),a?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]",P&&"text-[color:var(--messenger-group-entry-text)] dark:text-[color:var(--messenger-group-entry-text-dark)]",D&&"shadow-sm ring-1 ring-border/70"),children:[i.jsx(EH,{dragHandleProps:_,label:`Drag ${YF(e)}`,compact:ee}),i.jsx(UBn,{agent:t,agentId:n,unreadCount:e.unreadCount,needsAttention:e.needsAttention,density:l,testId:`messenger-thread-${oo(`chat:${e.id}`)}-agent-avatar`}),c?i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx("input",{autoFocus:!0,value:d,onChange:ne=>u(ne.target.value),onBlur:f,onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),f()),ne.key==="Escape"&&(ne.preventDefault(),A())},className:"min-h-0 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-elevated)] px-3 py-2 text-sm outline-none"})}):i.jsxs(i.Fragment,{children:[i.jsx(sn,{to:s,onClick:()=>U(s),className:"block min-w-0 flex-1",children:i.jsxs("div",{className:K("grid min-w-0 gap-x-2",ee?"grid-cols-[minmax(0,1fr)_2.75rem] items-center":"grid-cols-[minmax(0,1fr)_3rem] items-start"),children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:K("flex items-center gap-2 text-[13px] leading-tight",P?e.isUnread?"font-semibold text-current":"font-medium text-current/88":e.isUnread?"font-semibold text-foreground":"font-medium text-foreground/92"),children:[i.jsx("span",{className:"truncate",children:YF(e)}),r?i.jsx("span",{"data-testid":`messenger-source-badge-${oo(`chat:${e.id}`)}`,className:"inline-flex shrink-0 items-center rounded-[calc(var(--radius-sm)-2px)] border border-sky-500/35 bg-sky-500/15 px-1.5 py-0.5 text-[10px] font-semibold leading-none text-sky-700 dark:text-sky-300",children:r.label}):null,x?i.jsxs("span",{"data-testid":`messenger-title-generating-${oo(`chat:${e.id}`)}`,className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-[color:color-mix(in_oklab,var(--surface-active)_76%,transparent)] px-1.5 py-0.5 text-[10px] font-semibold text-muted-foreground","aria-label":"Generating chat title",children:[i.jsx(hn,{className:"h-2.5 w-2.5 animate-spin","aria-hidden":!0}),"Naming"]}):null]}),ee?null:i.jsx("div",{className:K("mt-0.5 truncate text-[12px]",P?e.isUnread?"text-current/78":"text-current/62":e.isUnread?"text-foreground/76":"text-muted-foreground"),children:XPe(e)})]}),i.jsx("span",{"data-testid":`messenger-time-${oo(`chat:${e.id}`)}`,className:K("block shrink-0 whitespace-nowrap text-right text-[10px] leading-none tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",ee?"w-11":"mt-0.5 w-12",(X||L||x)&&"opacity-0"),children:H})]})}),L?i.jsx("span",{"data-testid":`messenger-generating-${oo(`chat:${e.id}`)}`,"aria-label":"Chat reply in progress",className:K("pointer-events-none absolute top-1/2 z-10 inline-flex -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",ee?"right-1.5 h-5 w-5":"right-2 h-6 w-6",X&&"opacity-0"),children:i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin",strokeWidth:2.25,"aria-hidden":!0})}):null,x?i.jsx("span",{"data-testid":`messenger-title-spinner-${oo(`chat:${e.id}`)}`,"aria-label":"Generating chat title",className:K("pointer-events-none absolute top-1/2 z-10 inline-flex -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition-opacity duration-150",ee?"right-1.5 h-5 w-5":"right-2 h-6 w-6"),children:i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin",strokeWidth:2.25,"aria-hidden":!0})}):null,e.isPinned?i.jsx("button",{type:"button","data-testid":`messenger-pin-toggle-${oo(`chat:${e.id}`)}`,className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-[color:var(--accent-strong)] opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-[color:var(--accent-strong)] focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",se,(X||L||x)&&"pointer-events-none opacity-0"),"aria-label":"Unpin chat",title:"Unpin chat",onClick:S,children:i.jsx(Jh,{className:"h-3.5 w-3.5",strokeWidth:2.25})}):null,i.jsxs(Ei,{open:X,onOpenChange:F,children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{ref:q,type:"button",className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-muted-foreground transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",e.isPinned?re:se,X?"opacity-100":"opacity-0",x&&"pointer-events-none opacity-0"),"aria-label":"Chat actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"messenger-thread-actions-menu morph-popover morph-popover--from-right surface-overlay text-foreground",onCloseAutoFocus:ne=>{B.current&&(ne.preventDefault(),B.current=!1)},children:[m?i.jsxs(Xt,{onClick:m,children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename"]}):null,g?i.jsxs(Xt,{disabled:x,onClick:g,children:[x?i.jsx(hn,{className:"h-4 w-4 animate-spin"}):i.jsx(KA,{className:"h-4 w-4"}),"Regenerate title"]}):null,i.jsx(Xt,{onClick:S,children:e.isPinned?i.jsxs(i.Fragment,{children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}):i.jsxs(i.Fragment,{children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]})}),i.jsx(Xt,{onClick:j,children:e.isUnread?i.jsxs(i.Fragment,{children:[i.jsx(NBe,{className:"h-4 w-4"}),"Mark as Read"]}):i.jsxs(i.Fragment,{children:[i.jsx(cE,{className:"h-4 w-4"}),"Mark as Unread"]})}),i.jsxs(Xt,{onClick:C,children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy Chat Link"]}),i.jsxs(Xt,{disabled:L,onClick:y,children:[i.jsx(WB,{className:"h-4 w-4"}),"Fork"]}),N&&!M?i.jsxs(i.Fragment,{children:[i.jsx(Yo,{}),i.jsxs(Xt,{onClick:()=>{!Q.current||!q.current||(B.current=!0,R==null||R(Q.current,q.current))},children:[i.jsx(j3,{className:"h-4 w-4"}),"New group"]}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(aE,{className:"h-4 w-4"}),"Move to group"]}),i.jsxs(i6,{className:"morph-popover morph-popover--from-left surface-overlay text-foreground",children:[P?i.jsx(Xt,{onClick:T,children:"Move out of group"}):null,N.length>0?N.map(ne=>i.jsxs(Xt,{disabled:ne.id===P,onClick:()=>E==null?void 0:E(ne.id),children:[i.jsx(RD,{icon:ne.icon}),ne.name]},ne.id)):i.jsx(Xt,{disabled:!0,children:"No groups"})]})]})]}):null,k?i.jsxs(i.Fragment,{children:[i.jsxs(Xt,{onClick:v,children:[i.jsx(G4,{className:"h-4 w-4"}),"Archive"]}),i.jsxs(Xt,{variant:"destructive",onClick:w,title:L?"Stops the active reply before deleting this chat.":void 0,children:[i.jsx(yi,{className:"h-4 w-4"}),"Delete"]})]}):null]})]})]})]})})}function KBn({thread:e,active:t,density:n,preserveUnreadEmphasis:r=!1,onTogglePin:s,onHideIssue:a,customGroups:o,customGroupId:l,customGroupPending:c,onMoveToCustomGroup:d,onRemoveFromCustomGroup:u,onCreateCustomGroup:f,dragHandleProps:A,dragging:m,onSelect:g}){var F,Q,q,B,ee,se,re;const x=/^(issue|run):/.test(e.threadKey)?e.threadKey:null,y=dTn(x),v=QBn(e.kind),w=qf(e.preview)||qf(e.subtitle)||Z_(e.kind),k=n==="compact",[S,j]=h.useState(!1),C=h.useRef(null),N=h.useRef(null),P=h.useRef(!1),M=k?"right-1.5":"right-2",E=k?"right-7":"right-8",T=((F=e.metadata)==null?void 0:F.splitIssue)===!0,R=((Q=e.metadata)==null?void 0:Q.splitIssue)===!0&&!!a,_=T||R||!!o,D=((q=e.metadata)==null?void 0:q.splitIssue)===!0&&typeof e.metadata.status=="string"?(y==null?void 0:y.status)??e.metadata.status:null,U=(y==null?void 0:y.unreadCount)??e.unreadCount,$=(y==null?void 0:y.needsAttention)??e.needsAttention,L=(y==null?void 0:y.latestActivityAt)??e.latestActivityAt,H=t||r||U>0,X=((B=e.metadata)==null?void 0:B.splitIssue)===!0&&typeof e.metadata.activeExecutionRunId=="string"?e.metadata.activeExecutionRunId:null;return h.useEffect(()=>{X&&j(!1)},[X]),i.jsx(Tft,{threadKey:e.threadKey,eyebrow:((ee=e.metadata)==null?void 0:ee.splitIssue)===!0?typeof e.metadata.issueIdentifier=="string"?e.metadata.issueIdentifier:"Issue":Z_(e.kind),title:e.title,description:((se=e.metadata)==null?void 0:se.splitIssue)===!0&&typeof e.metadata.description=="string"?e.metadata.description:w,metadata:((re=e.metadata)==null?void 0:re.splitIssue)===!0?[D?`Status: ${D.replace(/_/g," ")}`:null,typeof e.metadata.priority=="string"?`Priority: ${e.metadata.priority}`:null,L?Bi(new Date(L),{compactDate:!0}):null]:[L?Bi(new Date(L),{compactDate:!0}):null],suppressed:S,children:i.jsxs("div",{ref:C,"data-testid":`messenger-thread-${oo(e.threadKey)}`,"data-messenger-thread-key":e.threadKey,className:K("group relative flex [contain-intrinsic-size:auto_44px] [content-visibility:auto] rounded-[calc(var(--radius-md)-2px)] border transition-[background-color,border-color,color]",l?"mx-0":"mx-1.5",k?K("items-center gap-2 py-1.5",l?"px-1.5":"px-2"):K("items-start gap-3 py-2.5",l?"px-2":"px-3"),t?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]",l&&"text-[color:var(--messenger-group-entry-text)] dark:text-[color:var(--messenger-group-entry-text-dark)]",m&&"opacity-80 shadow-sm ring-1 ring-border/70"),children:[i.jsx(EH,{dragHandleProps:A,label:`Drag ${GPe(e.title)}`,compact:k}),i.jsxs(sn,{to:e.href,onClick:()=>g(e),className:K("flex min-w-0 flex-1",k?"items-center gap-2":"items-start gap-3"),children:[D?i.jsx(VBn,{status:D,unreadCount:U,needsAttention:$,density:n,testId:`${oo(e.threadKey)}-unread-badge`}):i.jsx(_ft,{icon:v,unreadCount:U,needsAttention:$,density:n,testId:`${oo(e.threadKey)}-unread-badge`}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsxs("span",{className:K("grid min-w-0 gap-x-2",k?"grid-cols-[minmax(0,1fr)_2.75rem] items-center":"grid-cols-[minmax(0,1fr)_3rem] items-start"),children:[i.jsx("span",{className:K("flex min-w-0 items-center gap-2 text-[13px] leading-tight",H?"font-semibold text-foreground":"font-medium text-foreground/92"),children:i.jsx("span",{className:"truncate",children:GPe(e.title)})}),i.jsx("span",{"data-testid":`messenger-time-${oo(e.threadKey)}`,className:K("block shrink-0 whitespace-nowrap text-right text-[10px] leading-none tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",k?"w-11":"mt-0.5 w-12",(S||X)&&"opacity-0"),children:L?Bi(new Date(L),{compactDate:!0}):"No activity"})]}),k?null:i.jsx("span",{className:K("mt-0.5 block truncate text-[12px]",H?"text-foreground/76":"text-muted-foreground"),children:w})]})]}),X?i.jsx("span",{"data-testid":`messenger-active-run-${oo(e.threadKey)}`,"aria-label":"Issue run in progress",title:"Issue run in progress",className:K("pointer-events-none absolute top-1/2 z-10 inline-flex -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",k?"right-1.5 h-5 w-5":"right-2 h-6 w-6",S&&"opacity-0"),children:i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin",strokeWidth:2.25,"aria-hidden":!0})}):null,T&&e.isPinned?i.jsx("button",{type:"button","data-testid":`messenger-pin-toggle-${oo(e.threadKey)}`,className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-[color:var(--accent-strong)] opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-[color:var(--accent-strong)] focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",M,(S||X)&&"pointer-events-none opacity-0"),"aria-label":"Unpin thread",title:"Unpin thread",onClick:s,children:i.jsx(Jh,{className:"h-3.5 w-3.5",strokeWidth:2.25})}):null,_?i.jsxs(Ei,{open:S,onOpenChange:j,children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{ref:N,type:"button",className:K("absolute top-1/2 z-10 -translate-y-1/2 rounded-md p-1 text-muted-foreground transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",T&&e.isPinned?E:M,S?"opacity-100":"opacity-0"),"aria-label":"Thread actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"messenger-thread-actions-menu morph-popover morph-popover--from-right surface-overlay text-foreground",onCloseAutoFocus:ne=>{P.current&&(ne.preventDefault(),P.current=!1)},children:[T?i.jsx(Xt,{onClick:s,children:e.isPinned?i.jsxs(i.Fragment,{children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}):i.jsxs(i.Fragment,{children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]})}):null,R?i.jsxs(Xt,{onClick:a,children:[i.jsx(J4,{className:"h-4 w-4"}),"Hide"]}):null,o&&!c?i.jsxs(i.Fragment,{children:[T||R?i.jsx(Yo,{}):null,i.jsxs(Xt,{onClick:()=>{!C.current||!N.current||(P.current=!0,f==null||f(C.current,N.current))},children:[i.jsx(j3,{className:"h-4 w-4"}),"New group"]}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(aE,{className:"h-4 w-4"}),"Move to group"]}),i.jsxs(i6,{className:"morph-popover morph-popover--from-left surface-overlay text-foreground",children:[l?i.jsx(Xt,{onClick:u,children:"Move out of group"}):null,o.length>0?o.map(ne=>i.jsxs(Xt,{disabled:ne.id===l,onClick:()=>d==null?void 0:d(ne.id),children:[i.jsx(RD,{icon:ne.icon}),ne.name]},ne.id)):i.jsx(Xt,{disabled:!0,children:"No groups"})]})]})]}):null]})]}):null]})})}function WBn(e){if(!e||e.length>GM)return null;if(/^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(e))return e;try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?e:null}catch{return null}}function ZBn(e){return e.replace(/(?:https?:\/\/|file:\/\/\/|(?:data|javascript):)[^\s<>"']+/gi,r=>{if(/^file:/i.test(r))return"Local file";if(/^(?:data|javascript):/i.test(r))return"Web page";try{return new URL(r).host||"Web page"}catch{return"Web page"}}).replace(/\/\/((?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z0-9-]{2,})(?::\d+)?)(?:[/?#][^\s<>"']*)?/gi,"$1").replace(/\b((?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z0-9-]{2,})(?::\d+)?)(?:[/?#][^\s<>"']*)?/gi,"$1")}function gde(e){const t="item"in e?e.item.savedView:e,n=t.title.trim();if(t.targetPayload.kind!=="browser")return n||"Saved View";try{const s=new URL(n);if(s.protocol==="http:"||s.protocol==="https:")return s.hostname||"Web page"}catch{}const r=ZBn(n).trim();if(r)return r;try{return new URL(t.targetPayload.url).hostname||"Web page"}catch{return"Web page"}}function HBn({savedView:e}){var o;const t=e.targetPayload.kind,n=t==="browser"?WBn(e.favicon):null,r=t==="browser"?(o=Q6(e.targetPayload.url))==null?void 0:o.darkMode:void 0,[s,a]=h.useState(!1);return h.useEffect(()=>{a(!1)},[n]),t==="browser"&&n&&!s?i.jsx("img",{alt:"",className:K("h-4 w-4 rounded-[3px] object-contain",r==="invert"&&"dark:invert"),"data-dark-mode":r,"data-testid":"messenger-saved-view-browser-favicon",referrerPolicy:"no-referrer",src:n,onError:()=>a(!0)}):t==="browser"?i.jsx(up,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-browser-fallback-icon","aria-hidden":!0}):t==="automation"?i.jsx(n6,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-automation-icon","aria-hidden":!0}):t==="local_app"?i.jsx(Z6,{className:"h-3.5 w-3.5 rounded-[3px]",identity:e.targetPayload,testId:"messenger-saved-view-local-app-icon"}):t==="library_directory"?i.jsx(wo,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-folder-icon","aria-hidden":!0}):t==="library_document"?i.jsx(NSt,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-document-icon","aria-hidden":!0}):i.jsx(bBe,{className:"h-3.5 w-3.5","data-testid":"messenger-saved-view-file-icon","aria-hidden":!0})}function Mne({active:e=!1,currentGroupId:t,density:n,dragHandleProps:r,dragging:s=!1,entry:a,itemKey:o,savedView:l,groups:c,onMove:d,onMoveOutOfGroup:u,onRemove:f,placementPending:A=!1}){const m=(a==null?void 0:a.item.savedView)??l;if(!m)return null;const g=(a==null?void 0:a.itemKey)??o??`saved-view:${m.id}`,x=(a==null?void 0:a.id)??`loose-${m.id}`,y=c.filter(S=>S.id!==t),v=n==="compact",w=m.targetPayload.kind==="browser",k=gde(m);return i.jsxs("div",{"data-testid":`messenger-saved-view-${x.replace(/[^a-zA-Z0-9_-]/g,"-")}`,"data-messenger-saved-view-id":m.id,"data-active":e?"true":"false","aria-busy":A||void 0,"aria-label":k,title:k,className:K("group relative flex min-w-0 [contain-intrinsic-size:auto_44px] [content-visibility:auto] rounded-[calc(var(--radius-md)-2px)] border text-[color:var(--messenger-group-entry-text)] transition-[background-color,border-color,color] dark:text-[color:var(--messenger-group-entry-text-dark)]",v?"items-center gap-2 px-1.5 py-1.5":"items-start gap-3 px-2 py-2.5",e?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]",s&&"opacity-80 shadow-sm ring-1 ring-border/70"),children:[i.jsx(EH,{compact:v,dragHandleProps:A?void 0:r,label:`Drag ${k}`}),i.jsxs(sn,{to:aj(m.id),"aria-current":e?"page":void 0,"aria-label":k,title:k,className:K("flex min-w-0 flex-1 pr-7 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",v?"items-center gap-2":"items-start gap-3"),children:[i.jsx("span",{className:K("flex shrink-0 items-center justify-center rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_88%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_82%,transparent)] text-current/75",v?"h-7 w-7":"mt-0.5 h-10 w-10"),children:i.jsx(HBn,{savedView:m})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-[13px] font-medium leading-tight text-current/88",children:k}),!v&&!w&&m.subtitle?i.jsx("span",{className:"mt-0.5 block truncate text-[12px] text-current/62",children:m.subtitle}):null]})]}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-label":`Saved View actions for ${k}`,disabled:A,className:K("absolute top-1/2 right-1.5 z-10 flex -translate-y-1/2 items-center justify-center rounded-md p-1 text-current/65 opacity-0 transition-[opacity,background-color,color] hover:bg-white/40 hover:text-current focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 group-hover:opacity-100 group-focus-within:opacity-100 data-[state=open]:opacity-100 dark:hover:bg-white/10",v?"h-5 w-5":"h-6 w-6"),children:i.jsx(hl,{className:"h-3.5 w-3.5","aria-hidden":!0})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay text-foreground",children:[i.jsxs(r6,{children:[i.jsxs(s6,{disabled:y.length===0&&!t,children:[i.jsx(aE,{className:"h-4 w-4"}),"Move to group"]}),i.jsxs(i6,{className:"surface-overlay text-foreground",children:[t&&u?i.jsx(Xt,{onClick:()=>u(g),children:"Move out of group"}):null,y.map(S=>i.jsxs(Xt,{onClick:()=>d(S.id,g),children:[i.jsx(RD,{icon:S.icon}),S.name]},S.id))]})]}),i.jsxs(Xt,{className:"text-destructive focus:text-destructive",onClick:()=>f(m.id),children:[i.jsx(yi,{className:"h-4 w-4"}),"Remove from Messenger"]})]})]})]})}const xde="rudder:messenger:discord-cta:v1",Mft="rudder:messenger:discord-cta:eligible:v1",YPe=360*60*60*1e3;function XBn(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Mft)==="eligible"}catch{return!1}}function GBn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(xde);if(!e)return null;if(e==="dismissed"){const n=Date.now();return window.localStorage.setItem(xde,String(n)),n}const t=Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function YBn(){return i.jsx("svg",{"data-testid":"discord-logo",viewBox:"0 0 16 16",fill:"currentColor",className:"size-4","aria-hidden":!0,children:i.jsx("path",{d:"M13.545 2.907a13.227 13.227 0 0 0-3.257-1.011c-.14.25-.3.58-.408.845a12.003 12.003 0 0 0-3.658 0 8.238 8.238 0 0 0-.419-.845 13.301 13.301 0 0 0-3.26 1.012C.514 5.953-.034 8.927.241 11.872a13.582 13.582 0 0 0 4.001 2.02 9.594 9.594 0 0 0 .987-1.35 8.169 8.169 0 0 1-1.555-.76c.131-.095.259-.195.382-.297a9.705 9.705 0 0 0 8.005 0c.124.102.252.202.382.297-.497.29-1.017.544-1.56.759a9.653 9.653 0 0 0 .988 1.35 13.57 13.57 0 0 0 4.001-2.02c.323-3.415-.551-6.362-2.327-8.964ZM5.369 10.075c-.956 0-1.747-.868-1.747-1.934 0-1.065.775-1.934 1.747-1.934.978 0 1.764.87 1.747 1.934 0 1.066-.775 1.934-1.747 1.934Zm5.263 0c-.956 0-1.747-.868-1.747-1.934 0-1.065.775-1.934 1.747-1.934.978 0 1.764.87 1.747 1.934 0 1.066-.769 1.934-1.747 1.934Z"})})}function JBn(e){var n;const t=Pn();t&&(e.preventDefault(),(n=t.forceOpenExternal)==null||n.call(t,UVe))}function eQn(){var d;const{selectedOrganizationId:e}=jr(),[t,n]=h.useState(XBn),[r,s]=h.useState(GBn),o=((d=Me({queryKey:V.agentRuns(e??"__none__",void 0,Nie),queryFn:()=>zo.list(e,void 0,Nie),enabled:!!e&&!t}).data)==null?void 0:d.some(u=>u.status==="succeeded"))??!1;h.useEffect(()=>{if(!(t||!o)){try{window.localStorage.setItem(Mft,"eligible")}catch{}n(!0)}},[t,o]),h.useEffect(()=>{if(r===null)return;const u=YPe-(Date.now()-r);if(u<=0){s(null);return}const f=window.setTimeout(()=>s(null),u);return()=>window.clearTimeout(f)},[r]);const l=()=>{const u=Date.now();try{window.localStorage.setItem(xde,String(u))}catch{}s(u)},c=r===null||Date.now()-r>=YPe;return!t&&!o||!c?null:i.jsx("div",{"data-testid":"messenger-discord-cta",className:"shrink-0 border-t border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] px-2 py-2.5",children:i.jsxs("div",{className:"group relative",children:[i.jsxs("a",{href:UVe,target:"_blank",rel:"noopener noreferrer",onClick:JBn,className:"flex min-h-[68px] items-center gap-2.5 rounded-[calc(var(--radius-md)-1px)] border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_52%,transparent)] px-3 py-2.5 pr-9 text-left transition-[background-color,border-color,transform] duration-150 hover:border-[color:color-mix(in_oklab,var(--border-strong)_78%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] active:translate-y-px focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30","aria-label":"Join our Discord — chat with the team and other builders",children:[i.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)+1px)] bg-[color:color-mix(in_oklab,#7289da_15%,transparent)] text-[#7289da]",children:i.jsx(YBn,{})}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-[12px] font-semibold leading-4 text-foreground",children:"Join our Discord"}),i.jsx("span",{className:"mt-0.5 block text-[11px] leading-4 text-muted-foreground",children:"Chat with the team and other builders."})]})]}),i.jsx("button",{type:"button",onClick:l,className:"absolute right-1.5 top-1.5 flex size-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground/70 transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30","aria-label":"Dismiss Discord invitation",title:"Dismiss",children:i.jsx(Is,{className:"size-3.5","aria-hidden":!0})})]})})}const tQn=40;function k2e(e){if(!/^\/messenger(?:\/|$)/.test(e))return{kind:"root"};if(/^\/messenger\/workbench(?:\/|$)/.test(e))return{kind:"workbench"};if(/^\/messenger\/chat\/[^/]+(?:\/|$)/.test(e)){const n=e.match(/^\/messenger\/chat\/([^/]+)(?:\/|$)/);return{kind:"chat",conversationId:n==null?void 0:n[1]}}if(/^\/messenger\/chat(?:\/|$)/.test(e))return{kind:"chat"};if(/^\/messenger\/saved\/[^/]+(?:\/|$)/.test(e)){const n=e.match(/^\/messenger\/saved\/([^/]+)(?:\/|$)/);return{kind:"saved_view",savedViewId:(n==null?void 0:n[1])??""}}if(/^\/messenger\/issues\/[^/]+(?:\/|$)/.test(e)){const n=e.match(/^\/messenger\/issues\/([^/]+)(?:\/|$)/);return{kind:"issue",issueId:(n==null?void 0:n[1])??""}}if(/^\/messenger\/issues(?:\/|$)/.test(e))return{kind:"issues"};if(/^\/messenger\/approvals(?:\/|$)/.test(e))return{kind:"approvals"};const t=e.match(/^\/messenger\/system\/([^/]+)(?:\/|$)/);if(t){const n=t[1];if(n==="failed-runs"||n==="budget-alerts"||n==="join-requests")return{kind:"system",threadKind:n}}return{kind:"root"}}function LD(e={}){var m,g,x,y,v,w;const t=br(),{selectedOrganizationId:n}=jr(),r=k2e(fl(t.pathname)),{data:s}=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),a=((m=s==null?void 0:s.user)==null?void 0:m.id)??((g=s==null?void 0:s.session)==null?void 0:g.userId)??null,o=MK({queryKey:V.messenger.threadPages(n??"__none__",!!e.splitIssues),initialPageParam:null,queryFn:({pageParam:k})=>Ks.listThreadPage(n,{cursor:k,limit:tQn,splitIssues:e.splitIssues}),getNextPageParam:k=>k.pageInfo.hasMore?k.pageInfo.nextCursor:void 0,enabled:!!n}),l=Me({queryKey:V.messenger.issues(n??"__none__"),queryFn:()=>Ks.getIssuesThread(n),enabled:!!n&&r.kind==="issues"}),c=Me({queryKey:V.messenger.approvals(n??"__none__"),queryFn:()=>Ks.getApprovalsThread(n),enabled:!!n&&r.kind==="approvals"}),d=r.kind==="system"?r.threadKind:"__none__",u=Me({queryKey:V.messenger.system(n??"__none__",d),queryFn:()=>Ks.getSystemThread(n,d),enabled:!!n&&r.kind==="system"}),f=h.useMemo(()=>o.error instanceof Error?o.error:l.error instanceof Error?l.error:c.error instanceof Error?c.error:u.error instanceof Error?u.error:null,[c.error,l.error,u.error,o.error]),A=h.useMemo(()=>{var k;return((k=o.data)==null?void 0:k.pages.flatMap(S=>S.items))??[]},[(x=o.data)==null?void 0:x.pages]);return{currentUserId:a,selectedOrganizationId:n,threadSummaries:A,hasMoreThreadSummaries:!!o.hasNextPage,isFetchingMoreThreadSummaries:o.isFetchingNextPage,loadMoreThreadSummaries:()=>o.fetchNextPage(),issueThreadDetail:((y=l.data)==null?void 0:y.detail)??null,approvalThreadDetail:((v=c.data)==null?void 0:v.detail)??null,systemThreadDetail:((w=u.data)==null?void 0:w.detail)??null,isLoading:o.isLoading||l.isLoading||c.isLoading||u.isLoading,error:f}}const Eft="rudder.messengerLastPaths";function Dft(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Eft);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function nQn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Eft,JSON.stringify(e))}catch{}}function Rft(e){var n;const t=((n=e==null?void 0:e.split("?")[0])==null?void 0:n.split("#")[0])??"";return/^\/messenger\/chat(?:\/[^/]+)?$/.test(t)||t==="/messenger/issues"||/^\/messenger\/issues\/[^/]+$/.test(t)||t==="/messenger/approvals"||/^\/messenger\/system\/(failed-runs|budget-alerts|join-requests)$/.test(t)?t:null}function O2e(e,t){const n=Rft(t);if(!n)return;const r=Dft();r[e]=n,nQn(r)}function Lft(e){return Rft(Dft()[e])}function rQn(e,t){const n=e.match(/^\/messenger\/chat\/([^/]+)$/);return n?t.length===0?!1:t.some(r=>r.threadKey===`chat:${n[1]}`||r.href===e):!0}function sQn(e){const t=Lft(e.orgId);return t&&rQn(t,e.threadSummaries)?t:"/messenger/chat"}const zft="rudder.messengerThreadOrganizationByOrg",$ft="rudder.messengerThreadDensityByOrg",Fft="rudder.messengerSplitIssueNotificationsByOrg",Bft="rudder.messengerCollapsedProjectGroupsByOrg",bde="rudder.messengerCollapsedThreadGroupsByOrg",Qft="rudder.messengerProjectGroupOrder",yde="rudder.messengerThreadGroupOrder",Uft="rudder.messengerDefaultThreadOrder",Vft="rudder.messengerHiddenIssueThreads",iQn="rudder.projectOrder",aQn=["local-board","anonymous"],qft="latest",oQn="compact",lQn=!0;function H_(e){return e==="project"||e==="agent"||e==="kind"}function S2e(e){return H_(e)||e==="custom"}function i5(e){return H_(e)||e==="custom"}function LC(e,t){if(!(!e||typeof window>"u"))try{const n=window.localStorage.getItem(t);return(n?JSON.parse(n):{})[e]}catch{return}}function zD(e,t,n){if(!(typeof window>"u"))try{const r=window.localStorage.getItem(t),s=r?JSON.parse(r):{};window.localStorage.setItem(t,JSON.stringify({...s,[e]:n}))}catch{}}function Ene(e){const t=LC(e,zft);return t==="latest"||t==="project"||t==="agent"||t==="kind"||t==="attention"||t==="custom"?t:qft}function JPe(e,t){zD(e,zft,t)}function eIe(e){const t=LC(e,$ft);return t==="comfortable"||t==="compact"?t:oQn}function cQn(e,t){zD(e,$ft,t)}function tIe(e){const t=LC(e,Fft);return typeof t=="boolean"?t:lQn}function dQn(e,t){zD(e,Fft,t)}function uQn(e){const t=LC(e,Bft);return new Set(DH(t))}function fQn(e,t){zD(e,Bft,Array.from(t))}function Dne(e,t){if(!S2e(t))return new Set;if(t==="project")return uQn(e);const n=LC(e,bde),r=n&&typeof n=="object"&&!Array.isArray(n)?n[t]:void 0;return new Set(DH(r))}function nIe(e,t,n){if(!S2e(t))return;if(t==="project"){fQn(e,n);return}const r=LC(e,bde),s=r&&typeof r=="object"&&!Array.isArray(r)?r:{};zD(e,bde,{...s,[t]:Array.from(n)})}function DH(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function $D(e){return(e==null?void 0:e.trim())||"anonymous"}function EN(e){try{return Array.isArray(JSON.parse(e))&&JSON.parse(e).every(t=>typeof t=="string")}catch{return!1}}function AQn(e){try{const t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(n=>typeof n=="string")}catch{return!1}}function hQn(e,t,n=window.localStorage){const r=$D(t);if(r==="anonymous"||r==="local-board")return[];const s=[],a=[{prefix:iQn,suffix:`${e}`,valid:EN},{prefix:Qft,suffix:`${e}`,valid:EN},{prefix:yde,suffix:`agent:${e}`,valid:EN},{prefix:yde,suffix:`kind:${e}`,valid:EN},{prefix:Uft,suffix:`${e}`,valid:EN},{prefix:Vft,suffix:`${e}`,valid:AQn}];for(const o of a){const l=`${o.prefix}:${o.suffix}:${r}`;if(n.getItem(l)===null)for(const c of aQn){const d=n.getItem(`${o.prefix}:${o.suffix}:${c}`);if(!(d===null||!o.valid(d))){try{n.setItem(l,d),s.push(l)}catch{}break}}}return s}function mQn(e,t){var r,s;const n=((r=t==null?void 0:t.user)==null?void 0:r.id)??((s=t==null?void 0:t.session)==null?void 0:s.userId)??null;return h.useEffect(()=>{!e||!n||hQn(e,n)},[e,n]),n}function pQn(e,t){return`${Qft}:${e}:${$D(t)}`}function gQn(e,t,n){return n==="project"?pQn(e,t):`${yde}:${n}:${e}:${$D(t)}`}function xQn(e,t){return`${Uft}:${e}:${$D(t)}`}function bQn(e,t){return`${Vft}:${e}:${$D(t)}`}function Nk(e){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(e);return t?DH(JSON.parse(t)):[]}catch{return[]}}function Pk(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(DH(t)))}catch{}}function Rne(e){if(typeof window>"u")return{};try{const t=window.localStorage.getItem(e),n=t?JSON.parse(t):{};return Object.fromEntries(Object.entries(n).filter(r=>r[0].length>0&&typeof r[1]=="string"))}catch{return{}}}function yQn(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}const rIe=new Set(["channel","channelLabel","channelType","externalSource","from","imProvider","integration","integrationLabel","integrationType","origin","originKind","platform","platformType","provider","source","sourceKind","sourceLabel","sourceName","sourceType"]),vQn=new Set(["channel","context","external","integration","metadata","origin","platform","provider","source"]);function sIe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kft(e,t=0){if(t>3||!sIe(e))return[];const n=[];for(const[r,s]of Object.entries(e)){if(rIe.has(r)&&typeof s=="string"){n.push(s);continue}(rIe.has(r)||vQn.has(r))&&sIe(s)&&n.push(...Kft(s,t+1))}return n}function j2e(...e){return e.flatMap(n=>Kft(n)).some(n=>n.trim().toLowerCase().includes("feishu"))?{key:"feishu",label:"Feishu"}:null}const C2e="project:pinned";function wQn(e,t){if(t.length===0)return e;const n=new Map(e.map(l=>[l.key,l])),r=t.map(l=>n.get(l)??null).filter(l=>!!l);if(r.length===0)return e;const s=new Set(r.map(l=>l.key)),a=e.findIndex(l=>s.has(l.key));return[...e.slice(0,a).filter(l=>!s.has(l.key)),...r,...e.slice(a).filter(l=>!s.has(l.key))]}function Lne(e,t){const n=BI(e.threadKey);return!n||!t.has(n)?e:{...e,metadata:{...e.metadata,isProcessing:!0}}}function BI(e){return e.startsWith("chat:")?e.slice(5):null}function i$(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function zne(e,t,n){var x;if(e.kind!=="chat")return null;const r=BI(e.threadKey);if(!r)return null;const s=e.metadata??{},a=i$(s.preferredAgentId),o=i$(s.routedAgentId),l=i$(s.runtimeAgentId),c=i$(s.latestUserMessagePreview),d=typeof e.isPinned=="boolean"?e.isPinned:!!(n!=null&&n.isPinned),u=j2e(n,s),f=(n==null?void 0:n.sourceMetadata)??((u==null?void 0:u.key)==="feishu"?{source:"agent_integration",provider:"feishu"}:null),A=(n==null?void 0:n.mutability)??((u==null?void 0:u.key)==="feishu"?"external_bound_chat":"native_chat");if(n)return{...n,mutability:A,sourceMetadata:f,title:e.title.includes("…")?n.title:e.title,preferredAgentId:n.preferredAgentId??a,routedAgentId:n.routedAgentId??o,chatRuntime:{...n.chatRuntime,runtimeAgentId:((x=n.chatRuntime)==null?void 0:x.runtimeAgentId)??l},lastReadAt:e.lastReadAt??n.lastReadAt,unreadCount:e.unreadCount,isUnread:e.unreadCount>0,needsAttention:e.needsAttention,isPinned:d};const m=e.latestActivityAt?new Date(e.latestActivityAt):new Date,g=e.preview??e.subtitle??null;return{id:r,orgId:t,status:"active",mutability:A,title:e.title,summary:null,latestReplyPreview:g,latestUserMessagePreview:c,userMessageCount:0,preferredAgentId:a,routedAgentId:o,primaryIssueId:null,forkedFromConversationId:null,forkedFromMessageId:null,forkRootConversationId:null,primaryIssue:null,issueCreationMode:"manual_approval",planMode:!1,createdByUserId:null,lastMessageAt:m,lastReadAt:e.lastReadAt,isPinned:d,isUnread:e.unreadCount>0,unreadCount:e.unreadCount,needsAttention:e.needsAttention,resolvedAt:null,contextLinks:[],chatRuntime:{sourceType:"unconfigured",sourceLabel:"Agent unavailable",runtimeAgentId:l,agentRuntimeType:null,model:null,available:!1,error:null},sourceMetadata:f,createdAt:m,updatedAt:m}}function p5(e){return e!=null&&e.length?e.flatMap(t=>[...t.entries,...p5(t.childSections)]):[]}function Wft(e){return e!=null&&e.length?e.flatMap(t=>[t,...Wft(t.childSections)]):[]}function _4(e){return e.startsWith("project:")&&e!=="project:none"&&e!==C2e?e.slice(8):null}function kQn(e){return _4(e)?null:`messenger-section:${e}`}function OQn(e){return _4(e)??kQn(e)??e}function Zft(e){return e.startsWith("messenger-section:")?e.slice(18):e.startsWith("project:")?e:`project:${e}`}function SQn(e,t){return e==="project"?OQn(t):t}function Hft(e,t){return e==="project"?Zft(t):t}function dq(e){return`custom-group:${e}`}function Cd(e){return e.startsWith("custom-group:")?e.slice(13):null}function jQn(e,t,n=[]){if(e.length===0)return e;const r=e.filter(A=>A.isPinned),s=e.filter(A=>!A.isPinned),a=new Map(t.map((A,m)=>[A,m])),o=[],l=[];for(const A of s)_4(A.key)?o.push(A):l.push(A);o.sort((A,m)=>{const g=_4(A.key),x=_4(m.key),y=g?a.get(g):void 0,v=x?a.get(x):void 0;return y!==void 0||v!==void 0?(y??Number.MAX_SAFE_INTEGER)-(v??Number.MAX_SAFE_INTEGER):(A.label??"").localeCompare(m.label??"")});const c=[...o,...l];if(n.length===0)return[...r,...c];const d=new Map(n.map((A,m)=>[Zft(A),m])),u=new Map(c.map((A,m)=>[A.key,m])),f=[...c].sort((A,m)=>{const g=d.get(A.key),x=d.get(m.key);return g!==void 0||x!==void 0?(g??Number.MAX_SAFE_INTEGER)-(x??Number.MAX_SAFE_INTEGER):(u.get(A.key)??0)-(u.get(m.key)??0)});return[...r,...f]}function CQn(e,t,n,r=[]){if(!H_(t))return e;if(t==="project")return jQn(e,n,r);if(r.length===0)return e;const s=new Map(r.map((o,l)=>[Hft(t,o),l])),a=new Map(e.map((o,l)=>[o.key,l]));return[...e].sort((o,l)=>{const c=s.get(o.key),d=s.get(l.key);return c!==void 0||d!==void 0?(c??Number.MAX_SAFE_INTEGER)-(d??Number.MAX_SAFE_INTEGER):(a.get(o.key)??0)-(a.get(l.key)??0)})}function G1(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.trim()?n.trim():null}function Xft(e){var t;return((t=e.chatRuntime)==null?void 0:t.runtimeAgentId)??e.routedAgentId??e.preferredAgentId??null}function Gft(e,t){return e?t.get(e)??null:null}function NQn(e,t){var o,l,c;const n=((o=e==null?void 0:e.contextLinks)==null?void 0:o.find(d=>d.entityType==="project"))??null,r=typeof(n==null?void 0:n.entityId)=="string"&&n.entityId.trim()?n.entityId.trim():null,s=Gft(r,t),a=(s==null?void 0:s.name)||((l=n==null?void 0:n.entity)==null?void 0:l.label)||((c=n==null?void 0:n.entity)==null?void 0:c.identifier)||(n?"Unknown project":"No project");return r?{key:`project:${r}`,label:a,sortLabel:a,projectIcon:s==null?void 0:s.icon,projectColor:s==null?void 0:s.color}:{key:"project:none",label:a}}function PQn(e,t){var o;if(((o=e.metadata)==null?void 0:o.splitIssue)!==!0)return null;const n=e.metadata,r=G1(n,"projectId"),s=Gft(r,t),a=(s==null?void 0:s.name)??G1(n,"projectName")??(r?"Unknown project":"No project");return r?{key:`project:${r}`,label:a,sortLabel:a,projectIcon:s==null?void 0:s.icon,projectColor:s==null?void 0:s.color}:{key:"project:none",label:a}}function IQn(e,t){var n,r;if(e.thread.kind==="chat"){const s=e.conversation?Xft(e.conversation):null;if(!s)return{key:"agent:unavailable",label:"Agent unavailable"};const a=t.get(s);if(!a)return{key:"agent:unavailable",label:"Agent unavailable"};const o=a.name;return{key:`agent:${s}`,label:o,sortLabel:o}}if(((n=e.thread.metadata)==null?void 0:n.splitIssue)===!0){const s=e.thread.metadata,a=G1(s,"assigneeAgentId")??G1(s,"agentId")??G1(s,"runtimeAgentId")??G1(s,"preferredAgentId");if(!a)return{key:"agent:unassigned",label:"Unassigned"};const o=((r=t.get(a))==null?void 0:r.name)??G1(s,"assigneeAgentName")??G1(s,"agentName")??"Unknown agent";return{key:`agent:${a}`,label:o,sortLabel:o}}return{key:"system",label:"System"}}function M4(e){var t;return typeof e.thread.isPinned=="boolean"?e.thread.isPinned:!!((t=e.conversation)!=null&&t.isPinned)}function TQn(e){const t=new Set;return e.filter(n=>t.has(n.threadKey)?!1:(t.add(n.threadKey),!0))}function Yft(e){const t=new Set;return e.filter(n=>t.has(n.thread.threadKey)?!1:(t.add(n.thread.threadKey),!0))}function iIe(e){var t;return((t=e.metadata)==null?void 0:t.splitIssue)!==!0?null:[e.latestActivityAt?new Date(e.latestActivityAt).toISOString():"none",G1(e.metadata,"status")??"unknown",G1(e.metadata,"activeExecutionRunId")??"idle",String(e.unreadCount),e.needsAttention?"attention":"settled"].join("|")}function _Qn(e,t){var r,s;return((r=e.metadata)==null?void 0:r.splitIssue)!==!0?!1:e.metadata.issueId===t||e.metadata.issueIdentifier===t?!0:(((s=e.href.split("?")[0])==null?void 0:s.split("#")[0])??e.href)===`/messenger/issues/${t}`}function vde(e){var n,r;const t=e.thread.latestActivityAt??((n=e.conversation)==null?void 0:n.lastMessageAt)??((r=e.conversation)==null?void 0:r.updatedAt)??null;return t?new Date(t).getTime():Number.NEGATIVE_INFINITY}function uq(e,t){if(M4(e)!==M4(t))return M4(e)?-1:1;const n=vde(t)-vde(e);return n!==0?n:e.thread.title.localeCompare(t.thread.title)}function aIe(e){return e.entries.reduce((t,n)=>Math.max(t,vde(n)),Number.NEGATIVE_INFINITY)}function MQn(e,t){var r,s;if(!!e.isPinned!=!!t.isPinned)return e.isPinned?-1:1;const n=aIe(t)-aIe(e);return n!==0?n:(e.label??((r=e.entries[0])==null?void 0:r.thread.title)??e.key).localeCompare(t.label??((s=t.entries[0])==null?void 0:s.thread.title)??t.key)}function oIe(e,t){const n=new Map(e.map(o=>[o.key,o])),r=t.map(o=>n.get(o)??null).filter(o=>!!o);if(r.length===0)return e;const s=new Set(r.map(o=>o.key)),a=e.findIndex(o=>s.has(o.key));return a===-1?e:[...e.slice(0,a).filter(o=>!s.has(o.key)),...r,...e.slice(a).filter(o=>!s.has(o.key))]}function EQn(e,t){if(t.length===0)return e;const n=e.filter(s=>s.isPinned),r=e.filter(s=>!s.isPinned);return[...oIe(n,t),...oIe(r,t)]}function DQn(e,t){if(t.length===0)return e;const n=new Map(e.map(o=>[o.thread.threadKey,o])),r=t.map(o=>n.get(o)??null).filter(o=>!!o);if(r.length===0)return e;const s=new Set(r.map(o=>o.thread.threadKey)),a=e.findIndex(o=>s.has(o.thread.threadKey));return a===-1?e:[...e.slice(0,a).filter(o=>!s.has(o.thread.threadKey)),...r,...e.slice(a).filter(o=>!s.has(o.thread.threadKey))]}function RQn(e,t,n){const r=new Set(t.flatMap(f=>f.entries.map(A=>A.thread.threadKey))),s=t.map(f=>({key:dq(f.id),label:f.name,icon:f.icon,isPinned:f.pinned,entries:f.entries.map(A=>({...A,customGroupId:f.id}))})),a=e.filter(f=>!r.has(f.thread.threadKey)).map(f=>({...f,customGroupId:null})).sort(uq),o=Yft([...s.flatMap(f=>f.entries),...a]),l=DQn(o.filter(f=>M4(f)&&f.customGroupId===null).sort(uq),n),c=a.filter(f=>!M4(f)).map(f=>({key:f.thread.threadKey,label:null,entries:[f]})),d=EQn([...s,...c].sort(MQn),n.length>0?n:s.map(f=>f.key)),u=[...d.filter(f=>f.isPinned),...l.length>0?[{key:"custom:pinned:loose",label:null,entries:l}]:[]];return[...u.length>0?[{key:"custom:pinned",label:"Pinned",entries:[],childSections:u}]:[],...d.filter(f=>!f.isPinned)]}function LQn(e,t,n){const r=new Set,s=t.map(c=>({key:dq(c.id),label:c.name,icon:c.icon,isPinned:c.pinned,entries:c.entries.filter(d=>r.has(d.thread.threadKey)?!1:(r.add(d.thread.threadKey),!0)).map(d=>({...d,customGroupId:c.id}))})),a=Yft(e).filter(c=>!r.has(c.thread.threadKey)).map(c=>({...c,customGroupId:null})),o=Jft(a,"project",new Map,n,c=>c),l=(c,d,u,f)=>{if(f.length===0)return;const A=o.findIndex(g=>g.key===c);if(A===-1){const g={key:c,label:d,isPinned:u,entries:[],childSections:f};u?o.unshift(g):o.push(g);return}const m=o[A];m&&(o[A]={...m,childSections:[...f,...m.childSections??[]]})};return l(C2e,"Pinned",!0,s.filter(c=>c.isPinned)),l("project:none","No project",!1,s.filter(c=>!c.isPinned)),o}function zQn(e,t,n){const r=[...e];if(t<0||t>=r.length||n<0||n>=r.length)return r;const[s]=r.splice(t,1);return s===void 0||r.splice(n,0,s),r}function a$(e,t,n,r){const s=zQn(e,n,r),a=Math.min(n,r),o=Math.max(n,r),l=new Set(s.slice(a,o+1)),c=new Set(e),d=new Set(t);return[...t.filter(u=>!c.has(u)),...s.filter(u=>l.has(u)||d.has(u))]}function o$(e,t){const n=new Map;for(const r of e){const s=t(r),a=n.get(s.key);a?a.entries.push(r):n.set(s.key,{group:s,entries:[r]})}return Array.from(n.values()).sort((r,s)=>{if(r.group.key==="attention:needs")return-1;if(s.group.key==="attention:needs"||r.group.key==="project:none")return 1;if(s.group.key==="project:none")return-1;if(r.group.key==="system")return 1;if(s.group.key==="system")return-1;const a=r.group.key==="agent:unavailable"||r.group.key==="agent:unassigned",o=s.group.key==="agent:unavailable"||s.group.key==="agent:unassigned";return a&&!o?1:o&&!a?-1:(r.group.sortLabel??r.group.label).localeCompare(s.group.sortLabel??s.group.label)}).map(({group:r,entries:s})=>({key:r.key,label:r.label,projectIcon:r.projectIcon,projectColor:r.projectColor,entries:[...s].sort(uq)}))}function Jft(e,t,n,r,s){const a=[...e].sort(uq);if(t==="project"){const o=a.filter(M4),l=o$(a.filter(c=>!M4(c)),c=>{const d=PQn(c.thread,r);return d||(c.thread.kind!=="chat"?{key:"system",label:"System"}:NQn(c.conversation,r))});return o.length>0?[{key:C2e,label:"Pinned",isPinned:!0,entries:o},...l]:l}return t==="agent"?o$(a,o=>IQn(o,n)):t==="kind"?o$(a,o=>({key:`kind:${o.thread.kind}`,label:s(o.thread.kind)})):o$(a,o=>o.thread.unreadCount>0||o.thread.needsAttention?{key:"attention:needs",label:"Needs attention"}:{key:"attention:other",label:"Other threads"})}function wde(e){return e.entries.filter(n=>n.thread.unreadCount>0||n.thread.needsAttention).length+(e.childSections??[]).reduce((n,r)=>n+wde(r),0)}function lIe(e,t){const n=t.get(e.threadKey);return!n||n!==(e.latestActivityAt??"none")||e.unreadCount===0&&!e.needsAttention?e:{...e,unreadCount:0,needsAttention:!1}}function JF(e){return e.item.type==="thread"}function l$(e){return e.item.type==="saved_view"}function _y(e){var t;return(t=e.itemKey)!=null&&t.trim()?e.itemKey:JF(e)?e.threadKey:e.item.itemKey}function cIe(e){return e.dataset.messengerSavedViewId?`saved-view:${e.dataset.messengerSavedViewId}`:e.dataset.messengerThreadKey??null}function $Qn({children:e,collapsed:t,onCollapsedChange:n}){const[r,s]=h.useState({collapsed:t,generation:0}),a=h.useRef(null),o=h.useRef(t),l=h.useRef(t),c=h.useRef(0),d=h.useRef(0),u=h.useRef(null),f=h.useRef(null),A=h.useCallback(x=>{const y=a.current;if(!y)return;const v=y.querySelector("[data-messenger-group-trigger]"),w=y.querySelector("[data-messenger-group-content]");y.dataset.collapsed=x?"true":"false",v==null||v.setAttribute("aria-expanded",x?"false":"true"),w&&(x?(w.setAttribute("aria-hidden","true"),w.setAttribute("inert","")):(w.removeAttribute("aria-hidden"),w.removeAttribute("inert")),w.style.gridTemplateRows=x?"0fr":"1fr",w.style.opacity=x?"0":"1",w.style.marginTop=x?"0px":"0.25rem")},[]),m=h.useCallback((x,y)=>{u.current!==null&&cancelAnimationFrame(u.current),f.current!==null&&clearTimeout(f.current),u.current=requestAnimationFrame(()=>{u.current=null,f.current=setTimeout(()=>{f.current=null,c.current===y&&s({collapsed:x,generation:y})},0)})},[]);h.useEffect(()=>{if(d.current!==0)return;const x=c.current+1;c.current=x,o.current=t,l.current=t,s({collapsed:t,generation:x})},[t]),h.useEffect(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),f.current!==null&&clearTimeout(f.current)},[]),h.useLayoutEffect(()=>{var y;const x=(y=a.current)==null?void 0:y.querySelector("[data-messenger-group-content]");x&&(x.style.removeProperty("grid-template-rows"),x.style.removeProperty("opacity"),x.style.removeProperty("margin-top"))},[r.generation]);const g=x=>{const y=!o.current,v=c.current+1;c.current=v,d.current=v,o.current=y,A(y),m(y,v),n(y).then(()=>{l.current=y,d.current===v&&(d.current=0)},()=>{if(d.current!==v)return;d.current=0;const w=l.current,k=c.current+1;c.current=k,o.current=w,A(w),m(w,k)})};return e(r.collapsed,g,a)}const Ik=6,FQn=10,$ne=50,BQn=24,QQn=32,c$=8,UQn=40,VQn=48,qQn=1200,Fne=[120,300,700],eAt=[{value:"latest",label:"Latest activity"},{value:"project",label:"Project"},{value:"agent",label:"Agent"},{value:"kind",label:"Thread type"},{value:"attention",label:"Needs attention"}];function KQn(e){return new Promise(t=>{globalThis.setTimeout(t,e)})}function tAt(e){if(e)return`translate3d(${Math.round(e.x)}px, ${Math.round(e.y)}px, 0)`}function d$(e){var a,o,l,c,d,u;if(typeof KeyboardEvent<"u"&&e.activatorEvent instanceof KeyboardEvent){if(e.activatorEvent.shiftKey)return null;const f=(o=(a=e.active.rect)==null?void 0:a.current)==null?void 0:o.initial,A=(l=e.over)==null?void 0:l.rect;if(!f||!A)return"before";const m=f.top+f.height/2,g=A.top+A.height/2;return m<g?"after":"before"}const t=(d=(c=e.active.rect)==null?void 0:c.current)==null?void 0:d.translated,n=(u=e.over)==null?void 0:u.rect;if(!t||!n)return null;const r=t.top+t.height/2,s=Math.max(8,n.height*.25);return r<=n.top+s?"before":r>=n.bottom-s?"after":null}const WQn=e=>{const t=pqt(e);if(t.length>0)return t;const n=gqe(e);return n.length>0?n:EE(e)},ZQn={droppable:{strategy:kS.WhileDragging,frequency:OQ.Optimized}};function eB({placement:e,tone:t="accent"}){return e?i.jsx("div",{"data-testid":`messenger-insertion-line-${e}`,className:K("pointer-events-none absolute left-2 right-2 h-0.5 rounded-full",e==="before"?"-top-1":"-bottom-1",t==="group"?"bg-[color:color-mix(in_oklab,var(--messenger-group-text)_58%,transparent)]":"bg-[color:var(--accent-strong)]")}):null}function HQn(e){return e.replace(/\\/g,"\\\\").replace(/]/g,"\\]")}function XQn(e){return`[${HQn(o6(e).trim()||"Chat")}](${vj(e.id)})`}function GQn({title:e,description:t}){const{isMobile:n,setSidebarOpen:r}=jc();return i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome desktop-window-drag flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:e}),t?i.jsx("p",{className:"mt-0.5 truncate text-[12px] text-muted-foreground",children:t}):null]}),n?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>r(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]})}function YQn(e){return e==="failed-runs"||e==="budget-alerts"||e==="join-requests"}function nAt(e){var t;return e==="custom"?"Latest activity":((t=eAt.find(n=>n.value===e))==null?void 0:t.label)??"Latest activity"}function JQn({loading:e,onVisible:t,testId:n}){const r=h.useRef(null);return h.useEffect(()=>{const s=r.current;if(!s||e||typeof IntersectionObserver>"u")return;const a=s.closest("nav");if(!a)return;const o=new IntersectionObserver(l=>{l.some(c=>c.isIntersecting)&&t()},{root:a,rootMargin:"0px 0px 320px 0px"});return o.observe(s),()=>o.disconnect()},[e,t]),i.jsx("div",{ref:r,"data-testid":n,className:"flex min-h-7 items-center px-2 text-[11px] text-muted-foreground","aria-live":"polite",children:e?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[i.jsx(hn,{className:"h-3 w-3 animate-spin","aria-hidden":!0}),"Loading"]}):null})}function eUn({rule:e,density:t,splitIssueNotifications:n,onRuleChange:r,onDensityChange:s,onSplitIssueNotificationsChange:a}){const o=e!==qft&&e!=="custom",l=t==="compact",c=[o?nAt(e):null].filter(Boolean);return i.jsxs("div",{className:"group/section flex items-center justify-between px-3.5 pt-3.5",children:[i.jsxs("div",{className:"min-w-0 truncate text-[11px] font-semibold text-muted-foreground/72",children:["Threads",c.length>0?i.jsxs("span",{className:"text-muted-foreground",children:[" · ",c.join(" · ")]}):null]}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","data-testid":"messenger-thread-organization-trigger",className:K("flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",o?"opacity-100":"opacity-0 group-hover/section:opacity-100 group-focus-within/section:opacity-100"),"aria-label":"Organize threads",children:i.jsx(Mj,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"morph-popover morph-popover--from-right surface-overlay w-48 text-foreground",children:[i.jsx(pT,{className:"text-xs text-muted-foreground",children:"View"}),i.jsx(uQ,{checked:l,onCheckedChange:d=>s(d?"compact":"comfortable"),children:"Compact mode"}),i.jsx(uQ,{checked:n,onCheckedChange:d=>a(!!d),children:"Split issue notifications"}),i.jsx(Yo,{}),i.jsx(pT,{className:"text-xs text-muted-foreground",children:"Organize by"}),i.jsx(GAe,{value:e,onValueChange:d=>r(d),children:eAt.map(d=>i.jsx(fQ,{value:d.value,children:d.label},d.value))})]})]})]})}function dIe({id:e,children:t}){const{attributes:n,listeners:r,setNodeRef:s,transform:a,transition:o,isDragging:l}=nC({id:e}),{measureNow:c,measuredRect:d,setMeasuredNodeRef:u}=rAt(s);return h.useEffect(()=>{l&&c()},[l,c]),i.jsx("div",{ref:u,style:{height:l&&d?d.height:void 0,width:l&&d?d.width:void 0,transform:tAt(a),transition:o,willChange:l?"transform":void 0,zIndex:l?10:void 0},className:K("flex min-h-9 shrink-0 touch-none flex-col gap-1 rounded-[calc(var(--radius-md)-2px)]",l&&"bg-[color:color-mix(in_oklab,var(--surface-active)_56%,transparent)] opacity-90 shadow-sm ring-1 ring-border/70"),children:t({attributes:n,listeners:r},l)})}function Bne({id:e,insertionPlacement:t,disabled:n=!1,children:r}){const{attributes:s,listeners:a,setNodeRef:o,transform:l,transition:c,isDragging:d}=nC({id:e,disabled:n}),{measureNow:u,measuredRect:f,setMeasuredNodeRef:A}=rAt(o);return h.useEffect(()=>{d&&u()},[d,u]),i.jsxs("div",{ref:A,style:{height:d&&f?f.height:void 0,width:d&&f?f.width:void 0,transform:tAt(l),transition:c,willChange:d?"transform":void 0,zIndex:d?20:void 0},className:K("relative touch-none",d&&"z-20"),children:[i.jsx(eB,{placement:t??null}),r({attributes:s,listeners:a},d)]})}function rAt(e){const[t,n]=h.useState(null),[r,s]=h.useState(null),a=h.useCallback(c=>{if(!c)return;const d=c.getBoundingClientRect(),u=Math.round(d.height),f=Math.round(d.width);u<=0||f<=0||s(A=>(A==null?void 0:A.height)===u&&A.width===f?A:{height:u,width:f})},[]),o=h.useCallback(c=>{e(c),n(c),a(c)},[e,a]),l=h.useCallback(()=>{a(t)},[t,a]);return h.useEffect(()=>{if(!t||(a(t),typeof ResizeObserver>"u"))return;const c=new ResizeObserver(()=>a(t));return c.observe(t),()=>c.disconnect()},[t,a]),{measureNow:l,measuredRect:r,setMeasuredNodeRef:o}}function tUn(){var wp,kp,Kl,dm,Xd,r0,Bb,cc,um;const{pushToast:e}=ss(),t=br(),n=Yr(),r=fl(t.pathname),s=new URLSearchParams(t.search).get("perfBaseline")==="1",{selectedOrganizationId:a}=jr(),[o,l]=h.useState(()=>tIe(a)),c=LD({splitIssues:o}),d=v0e(),u=w0e(),{isMobile:f,setSidebarOpen:A}=jc(),{confirm:m}=ii(),{abortChatStream:g,isChatGenerationActive:x,setChatSendInFlight:y,setStreamDraftForChat:v}=Ift(),{activeChatIds:w}=Pft(),k=Vn(),S=k2e(r),j=h.useRef(null),C=bs("rudder:sidebar-scroll:messenger"),N=bs(),P=h.useRef(null),M=h.useRef(null),E=h.useRef(null),T=h.useRef(!0),R=h.useRef(null),_=h.useRef(null),D=h.useRef(0),U=h.useRef(null),$=h.useRef(new Map),L=h.useRef(new Set),[H,X]=h.useState(()=>new Set),[F,Q]=h.useState(0),[q,B]=h.useState({}),ee=h.useRef({}),[se,re]=h.useState(null),[ne,Ae]=h.useState(""),[Y,ce]=h.useState({}),[Oe,Fe]=h.useState(()=>new Set),[ke,Ne]=h.useState(null),[xe,ae]=h.useState(null),[fe,ve]=h.useState(""),[Se,ze]=h.useState("folder"),[ft,ie]=h.useState("amber"),[me,we]=h.useState({}),[Xe,ge]=h.useState(()=>new Set),[te,G]=h.useState(null),[oe,Ze]=h.useState(null),[Te,Be]=h.useState(null),[it,lt]=h.useState(()=>new Map),[Ue,mt]=h.useState(null),tt=h.useRef(null),dt=h.useRef(null),at=h.useRef(null),Pe=h.useRef(null),$e=h.useRef(null),ot=h.useRef({}),ue=h.useRef(null),Ie=h.useRef(c.selectedOrganizationId),Ke=h.useRef(r);Ie.current=c.selectedOrganizationId,Ke.current=r;const[De,Je]=h.useState(0),[_e,Ee]=h.useState(()=>Ene(c.selectedOrganizationId)),[Ce,kt]=h.useState(()=>eIe(c.selectedOrganizationId)),[Qe,gt]=h.useState(()=>Dne(c.selectedOrganizationId,_e)),[Nt,Gt]=h.useState({}),cn=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),Rn=mQn(c.selectedOrganizationId,cn.data),nt=h.useMemo(()=>c.selectedOrganizationId?vhe(c.selectedOrganizationId,Rn):null,[Rn,c.selectedOrganizationId]),Qt=h.useMemo(()=>!c.selectedOrganizationId||!H_(_e)?null:gQn(c.selectedOrganizationId,Rn,_e),[Rn,c.selectedOrganizationId,_e]),st=h.useMemo(()=>c.selectedOrganizationId?bQn(c.selectedOrganizationId,Rn):null,[Rn,c.selectedOrganizationId]),Rt=h.useMemo(()=>c.selectedOrganizationId?xQn(c.selectedOrganizationId,Rn):null,[Rn,c.selectedOrganizationId]),[Cn,zn]=h.useState(()=>nt?H7(nt):[]),[fs,as]=h.useState(()=>Qt?Nk(Qt):[]),[sr,Kr]=h.useState(()=>Rt?Nk(Rt):[]),[yr,ht]=h.useState(()=>st?Rne(st):{}),Vt=Yj(Mx(mw,{activationConstraint:{distance:5}}),Mx(eC,{coordinateGetter:_W})),We=h.useCallback(de=>{tt.current!==de&&(tt.current=de,G(de))},[]),Tt=h.useCallback(de=>{dt.current!==de&&(dt.current=de,Ze(de))},[]),Mn=h.useCallback(de=>{at.current!==de&&(at.current=de,Be(de))},[]),tr=h.useCallback(()=>{Pe.current&&(clearTimeout(Pe.current),Pe.current=null,$e.current=null)},[]),Ln=h.useCallback(de=>{mt(de),ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{ue.current=null,mt(He=>He===de?null:He)},qQn)},[]),pt=h.useCallback(()=>{tr(),We(null),Tt(null),Mn(null)},[tr,Mn,Tt,We]),vt=h.useCallback(de=>{We(String(de.active.id)),Tt(null),Mn(null)},[Mn,Tt,We]);h.useEffect(()=>{Ee(Ene(c.selectedOrganizationId)),kt(eIe(c.selectedOrganizationId)),l(tIe(c.selectedOrganizationId));const de=Ene(c.selectedOrganizationId);gt(Dne(c.selectedOrganizationId,de)),Gt({}),ce({}),lt(new Map),mt(null),Q(0),B({}),ue.current&&(clearTimeout(ue.current),ue.current=null)},[c.selectedOrganizationId]),h.useEffect(()=>{gt(Dne(c.selectedOrganizationId,_e)),Gt({})},[c.selectedOrganizationId,_e]),h.useEffect(()=>{if(!nt){zn([]);return}zn(H7(nt));const de=wt=>{wt.key===nt&&zn(H7(nt))},He=wt=>{const Dt=wt.detail;!Dt||Dt.storageKey!==nt||zn(Dt.orderedIds)};return window.addEventListener("storage",de),window.addEventListener(kT,He),()=>{window.removeEventListener("storage",de),window.removeEventListener(kT,He)}},[nt]),h.useEffect(()=>{if(!Qt){as([]);return}as(Nk(Qt));const de=He=>{He.key===Qt&&as(Nk(Qt))};return window.addEventListener("storage",de),()=>window.removeEventListener("storage",de)},[Qt]),h.useEffect(()=>{if(!Rt){Kr([]);return}Kr(Nk(Rt));const de=He=>{He.key===Rt&&Kr(Nk(Rt))};return window.addEventListener("storage",de),()=>window.removeEventListener("storage",de)},[Rt]),h.useEffect(()=>{if(!st){ht({});return}ht(Rne(st));const de=He=>{He.key===st&&ht(Rne(st))};return window.addEventListener("storage",de),()=>window.removeEventListener("storage",de)},[st]),h.useEffect(()=>{c.selectedOrganizationId&&Qf(k,c.selectedOrganizationId)},[c.selectedOrganizationId,k,o]);const jt=_e==="project"||_e==="agent",Zt=80,kr=Me({queryKey:V.chats.listPreview(c.selectedOrganizationId??"__none__","all",Zt),queryFn:()=>Xn.list(c.selectedOrganizationId,"all",{limit:Zt}),enabled:!!c.selectedOrganizationId&&jt}),xs=Me({queryKey:V.agents.list(c.selectedOrganizationId??"__none__"),queryFn:()=>Nn.list(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId}),la=Me({queryKey:V.projects.list(c.selectedOrganizationId??"__none__"),queryFn:()=>Mi.list(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId&&_e==="project"}),Ss=Me({queryKey:V.organizations.intelligenceProfiles(c.selectedOrganizationId??"__none__"),queryFn:()=>_n.listIntelligenceProfiles(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId}),bt=Me({queryKey:V.messenger.customGroups(c.selectedOrganizationId??"__none__"),queryFn:()=>Ks.listCustomGroups(c.selectedOrganizationId),enabled:!!c.selectedOrganizationId}),Jt=Me({queryKey:V.messenger.savedViews(c.selectedOrganizationId??"__none__","visible",$ne,F),queryFn:()=>Ks.listSavedViews(c.selectedOrganizationId,{visibility:"visible",limit:$ne,offset:F}),enabled:!!c.selectedOrganizationId});h.useEffect(()=>{Object.keys(me).length!==0&&we(de=>{var Dt;let He=!1;const wt={...de};for(const en of((Dt=bt.data)==null?void 0:Dt.groups)??[])en.id in wt&&wt[en.id]===en.icon&&(delete wt[en.id],He=!0);return He?wt:de})},[(wp=bt.data)==null?void 0:wp.groups,me]);const nr=h.useMemo(()=>{const de=new Map;for(const He of kr.data??[])de.set(He.id,He);return de},[kr.data]),Er=h.useMemo(()=>{const de=new Map;for(const He of xs.data??[])de.set(He.id,He);return de},[xs.data]),cs=h.useMemo(()=>{const de=new Map;for(const He of la.data??[])de.set(He.id,He);return de},[la.data]),ds=h.useMemo(()=>(Ss.data??[]).some(He=>(He==null?void 0:He.purpose)==="lightweight"&&He.status==="configured"),[Ss.data]),Or=((kp=bt.data)==null?void 0:kp.groups)??[],Dr=bt.data!==void 0,Ts=h.useMemo(()=>{var He;const de=new Map;for(const wt of Object.keys(q).map(Number).sort((Dt,en)=>Dt-en))for(const Dt of q[wt]??[])Dt.orgId===c.selectedOrganizationId&&de.set(Dt.id,Dt);for(const wt of((He=Jt.data)==null?void 0:He.items)??[])wt.orgId===c.selectedOrganizationId&&de.set(wt.id,wt);return Array.from(de.values()).sort((wt,Dt)=>wt.sortOrder-Dt.sortOrder)},[q,c.selectedOrganizationId,(Kl=Jt.data)==null?void 0:Kl.items]),Ui=h.useMemo(()=>new Set(Or.flatMap(de=>de.entries).filter(l$).map(de=>de.item.savedView.id)),[Or]),fo=h.useMemo(()=>Dr?Ts.filter(de=>!Ui.has(de.id)):[],[Dr,Ui,Ts]),Ye=_e==="latest"||_e==="custom"?"custom":_e;h.useEffect(()=>tr,[tr,Ye,c.selectedOrganizationId]),h.useEffect(()=>()=>{ue.current&&(clearTimeout(ue.current),ue.current=null)},[]);const Mt=h.useMemo(()=>{const de=new Map;for(const He of Or)de.set(dq(He.id),He);return de},[Or]),An=h.useMemo(()=>{const de=c.threadSummaries.filter(He=>{const wt=iIe(He);return wt?yr[He.threadKey]!==wt:!0});return TQn(de).map(He=>lIe(He,it))},[yr,it,c.threadSummaries]);h.useEffect(()=>{it.size!==0&&lt(de=>{const He=new Map(de),wt=new Map;for(const Dt of c.threadSummaries)wt.set(Dt.threadKey,[...wt.get(Dt.threadKey)??[],Dt]);for(const Dt of Or)for(const en of Dt.entries)JF(en)&&wt.set(en.threadKey,[...wt.get(en.threadKey)??[],en.thread]);for(const[Dt,en]of de){const gn=wt.get(Dt)??[];if(gn.length===0)continue;const yn=gn.filter(Sn=>(Sn.latestActivityAt??"none")===en);if(yn.length===0){He.delete(Dt);continue}yn.some(Sn=>Sn.unreadCount>0||Sn.needsAttention)||He.delete(Dt)}return He.size===de.size?de:He})},[Or,it.size,c.threadSummaries]);const vn=h.useMemo(()=>{const de=o?An.filter(Sn=>Sn.threadKey!=="issues"):An,He=Or.map(Sn=>({id:Sn.id,name:Sn.name,icon:Sn.icon,pinned:!!Sn.pinnedAt,entries:Sn.entries.filter(JF).map(pr=>{const Fr=BI(pr.threadKey),xa=Fr?Y[Fr]:void 0,oi=Lne(lIe(pr.thread,it),w),to=xa?{...oi,title:xa}:oi;return{thread:to,conversation:c.selectedOrganizationId?zne(to,c.selectedOrganizationId,nr.get(Fr??"")??null):null,customGroupId:Sn.id}})}));if(Ye==="custom"){const Sn=de.map(pr=>{const Fr=Lne(pr,w),xa=BI(Fr.threadKey),oi=xa?nr.get(xa)??null:null,to=xa?Y[xa]:void 0,Xc=to?{...Fr,title:to}:Fr;return{thread:Xc,conversation:c.selectedOrganizationId?zne(Xc,c.selectedOrganizationId,oi):null,customGroupId:null}});return RQn(Sn,He,sr)}const wt=de.map(Sn=>{const pr=Lne(Sn,w),Fr=BI(pr.threadKey),xa=Fr?nr.get(Fr)??null:null,oi=Fr?Y[Fr]:void 0,to=oi?{...pr,title:oi}:pr;return{thread:to,conversation:c.selectedOrganizationId?zne(to,c.selectedOrganizationId,xa):null}}),Dt=Ye==="project"?LQn(wt,He,cs):Jft(wt,Ye,Er,cs,Z_),en=new Set(Or.filter(Sn=>Sn.entries.some(l$)).map(Sn=>Sn.id)),gn=He.filter(Sn=>en.has(Sn.id)).map(Sn=>({key:dq(Sn.id),label:Sn.name,icon:Sn.icon,isPinned:Sn.pinned,entries:[]})),yn=Ye==="agent"||Ye==="kind"||Ye==="attention"?[...Dt,...gn]:Dt;return i5(Ye)?CQn(yn,Ye,Cn,fs):yn},[w,Er,nr,Or,sr,Ye,it,c.selectedOrganizationId,Y,Cn,cs,fs,o,An]),fr=h.useMemo(()=>{const de=new Map;for(const He of Or)for(const wt of He.entries)JF(wt)&&de.set(wt.threadKey,He.id);if(Ye==="custom")for(const He of vn)for(const wt of p5([He]))wt.customGroupId===null&&de.set(wt.thread.threadKey,null);return de},[Or,Ye,vn]),mr=h.useMemo(()=>{const de=new Map(fr);for(const He of Or)for(const wt of He.entries)de.set(_y(wt),He.id);for(const He of fo)de.set(`saved-view:${He.id}`,null);return de},[fr,Or,fo]),Ge=h.useMemo(()=>{const de=new Map;for(const He of Or)for(const wt of He.entries)l$(wt)&&de.set(_y(wt),{entry:wt,groupId:He.id,savedView:wt.item.savedView});for(const He of fo)de.set(`saved-view:${He.id}`,{entry:null,groupId:null,savedView:He});return de},[Or,fo]),tn=h.useMemo(()=>{const de=gn=>{const yn=Ge.get(gn);if(yn)return`Saved View ${gde(yn.savedView)}`;const Sn=Mt.get(gn);return Sn?`Messenger group ${Sn.name}`:"Messenger item"},He=gn=>{if(!gn)return"the Messenger list";const yn=Cd(gn)??mr.get(gn)??null,Sn=yn?Or.find(pr=>pr.id===yn):null;return Sn?`Messenger group ${Sn.name}`:"a Messenger item"},wt=(gn,yn)=>{var Fr;const Sn=Ge.get(gn);if(!Sn)return yn&&yn!==gn?"valid":"invalid";if(H.has(gn))return"busy";if(!yn||yn===gn)return"invalid";const pr=Cd(yn);if(pr)return pr===Sn.groupId?"invalid":"valid";if(mr.has(yn)){if(mr.get(yn)!==null||Ge.has(yn))return"valid";const xa=(Fr=p5(vn).find(oi=>oi.thread.threadKey===yn))==null?void 0:Fr.thread.kind;return xa==="chat"||xa==="issues"?"valid":"invalid"}return"invalid"};return{announcements:{onDragStart:({active:gn})=>`Picked up ${de(String(gn.id))}.`,onDragOver:({active:gn,over:yn})=>`Moving ${de(String(gn.id))} over ${He(yn?String(yn.id):null)}.`,onDragEnd:({active:gn,over:yn})=>{const Sn=String(gn.id),pr=wt(Sn,yn?String(yn.id):null);if(pr==="busy")return`${de(Sn)} already has a move in progress.`;if(pr==="invalid")return`Move canceled for ${de(Sn)}. That is not a valid destination.`;const Fr=Ge.get(Sn),xa=yn?String(yn.id):null,oi=xa?p5(vn).find(to=>to.thread.threadKey===xa):null;return(Fr==null?void 0:Fr.groupId)===null&&(oi==null?void 0:oi.customGroupId)===null&&(oi.thread.kind==="chat"||oi.thread.kind==="issues")?d$({active:gn,over:yn})?`Reorder requested for ${de(Sn)}.`:`Group requested for ${de(Sn)}.`:`Move requested for ${de(Sn)}. Messenger will announce when the server saves the change.`},onDragCancel:({active:gn})=>`Move canceled for ${de(String(gn.id))}.`},screenReaderInstructions:{draggable:"Press Space to pick up a Messenger item. Use the arrow keys to choose a destination, then press Space again to reorder. Hold Shift while picking up to group with a loose Chat or Issue. Press Escape to cancel."}}},[mr,Mt,Or,vn,H,Ge]),Gn=h.useMemo(()=>{var wt;if(!te)return null;const de=Ge.get(te);if(de)return gde(de.savedView);const He=Mt.get(te);return He?He.name:((wt=p5(vn).find(Dt=>Dt.thread.threadKey===te))==null?void 0:wt.thread.title)??"Messenger item"},[Mt,te,vn,Ge]),Wr=h.useCallback((de,He)=>{if(Ye!=="custom"||!He||de===He)return null;if(!mr.has(de))return Cd(de)&&Cd(He)?"reorder-group":null;const Dt=mr.get(de)??null,en=mr.has(He)?mr.get(He)??null:void 0,gn=Cd(He)??en;return Ge.has(de)&&en===null?Dt?"move-out-of-group":"reorder-entry":Dt&&en===null?"move-out-of-group":gn&&Dt!==gn?"move-into-group":Dt&&en&&Dt===en||Dt===null&&en===null?"reorder-entry":null},[mr,Ye,Ge]),mn=h.useMemo(()=>{const de=[],He=i5(Ye),wt=(Dt,en)=>{for(const gn of Dt??[]){const yn=He?[...en,gn.key]:[];for(const[Sn,pr]of gn.entries.entries())pr.thread.unreadCount>0&&de.push({threadKey:pr.thread.threadKey,groupKey:He?gn.key:null,sectionPath:yn,entryIndex:He?Sn:null});wt(gn.childSections,yn)}};return wt(vn,[]),de},[Ye,vn]),Bn=h.useMemo(()=>{if(De<=0||mn.length===0)return null;const de=_.current,He=de?mn.findIndex(wt=>wt.threadKey===de):-1;return He===mn.length-1&&c.hasMoreThreadSummaries?null:mn[(He+1)%mn.length]??null},[c.hasMoreThreadSummaries,De,mn]),Ci=De>0&&D.current!==De&&c.hasMoreThreadSummaries&&!c.isFetchingMoreThreadSummaries&&!c.isLoading&&(mn.length===0||!!_.current&&mn.findIndex(de=>de.threadKey===_.current)===mn.length-1);(dm=mn[0])==null||dm.threadKey;const Vi=h.useCallback(de=>{P.current=de,C(de)},[C]),Vr=h.useMemo(()=>{var de;return S.kind==="chat"&&S.conversationId?`chat:${S.conversationId}`:S.kind==="issue"?((de=An.find(He=>_Qn(He,S.issueId)))==null?void 0:de.threadKey)??`issue:${S.issueId}`:S.kind==="issues"?"issues":S.kind==="approvals"?"approvals":S.kind==="system"?S.threadKind:null},[S,An]),oc=S.kind==="saved_view"?S.savedViewId:null,Ao=h.useMemo(()=>{const de=vn.map(Dt=>({key:Dt.key,kind:"section",section:Dt})),He=fo.map(Dt=>({key:`saved-view:${Dt.id}`,kind:"saved-view",savedView:Dt})),wt=[...de,...He];return Ye==="custom"?wQn(wt,sr):wt},[sr,Ye,fo,vn]),ml=h.useCallback(de=>{const He=te?VQn:UQn,wt=Math.max(0,de.startIndex-He),Dt=Math.min(de.count-1,de.endIndex+He),en=Math.floor(wt/c$)*c$,gn=Math.min(de.count-1,Math.ceil((Dt+1)/c$)*c$-1);return Array.from({length:gn-en+1},(yn,Sn)=>en+Sn)},[te]),ho=wct({count:Ao.length,getScrollElement:()=>P.current,estimateSize:()=>Ce==="compact"?42:58,getItemKey:de=>{var He;return((He=Ao[de])==null?void 0:He.key)??de},overscan:0,rangeExtractor:ml,directDomUpdates:!0,directDomUpdatesMode:"transform",useFlushSync:!1}),vs=ho.getVirtualItems(),aA=h.useMemo(()=>Ao.filter(de=>de.kind==="saved-view"?Ye==="custom":(Ye!=="custom"||de.section.key!=="custom:pinned")&&(Ye!=="project"||!de.section.isPinned)).map(de=>de.key),[Ye,Ao]),hf=h.useMemo(()=>{if(!i5(Ye)||!Vr)return new Map;const de=new Map;for(const He of Wft(vn)){const wt=He.entries.findIndex(Dt=>Dt.thread.threadKey===Vr);wt!==-1&&de.set(He.key,wt+1)}return de},[Vr,Ye,vn]),Gi=h.useMemo(()=>An.find(de=>de.threadKey===Vr)??null,[Vr,An]),bd=h.useMemo(()=>S.kind==="issue"?!!Gi:S.kind==="issues"?!!c.issueThreadDetail:S.kind==="approvals"?!!c.approvalThreadDetail:S.kind==="system"?!!c.systemThreadDetail:!1,[Gi,c.approvalThreadDetail,c.issueThreadDetail,c.systemThreadDetail,S]),lc=h.useMemo(()=>{var de,He,wt;return S.kind==="issue"?(Gi==null?void 0:Gi.latestActivityAt)??null:S.kind==="issues"?((de=c.issueThreadDetail)==null?void 0:de.latestActivityAt)??null:S.kind==="approvals"?((He=c.approvalThreadDetail)==null?void 0:He.latestActivityAt)??null:S.kind==="system"?((wt=c.systemThreadDetail)==null?void 0:wt.latestActivityAt)??null:(Gi==null?void 0:Gi.latestActivityAt)??null},[Gi==null?void 0:Gi.latestActivityAt,(Xd=c.approvalThreadDetail)==null?void 0:Xd.latestActivityAt,(r0=c.issueThreadDetail)==null?void 0:r0.latestActivityAt,(Bb=c.systemThreadDetail)==null?void 0:Bb.latestActivityAt,S]),Qn=()=>{f&&A(!1)},Vo=de=>{c.selectedOrganizationId&&O2e(c.selectedOrganizationId,de),Qn()},yd=de=>{const He=c.selectedOrganizationId;if(Vo(de.href),!He||de.unreadCount===0&&!de.needsAttention)return;const wt=de.latestActivityAt??null,Dt=`${He}:${de.threadKey}:${wt??"none"}`;j.current!==Dt&&(j.current=Dt,Ln(de.threadKey),lt(en=>{const gn=wt instanceof Date?wt.toISOString():wt??"none";if(en.get(de.threadKey)===gn)return en;const yn=new Map(en);return yn.set(de.threadKey,gn),yn}),_ie(k,He,de.threadKey,wt),Ks.markThreadRead(He,de.threadKey,wt?new Date(wt).toISOString():null).then(async()=>{await Qf(k,He),await k.invalidateQueries({queryKey:V.sidebarBadges(He)}),de.kind==="issues"&&await k.invalidateQueries({queryKey:V.messenger.issues(He)}),de.kind==="approvals"&&await k.invalidateQueries({queryKey:V.messenger.approvals(He)}),YQn(de.kind)&&await k.invalidateQueries({queryKey:V.messenger.system(He,de.kind)})}).catch(()=>{j.current=null,lt(en=>{if(!en.has(de.threadKey))return en;const gn=new Map(en);return gn.delete(de.threadKey),gn}),Qf(k,He)}))},Pc=de=>{Ee(de),c.selectedOrganizationId&&JPe(c.selectedOrganizationId,de)},eo=de=>{kt(de),c.selectedOrganizationId&&cQn(c.selectedOrganizationId,de)},$a=de=>{l(de),c.selectedOrganizationId&&dQn(c.selectedOrganizationId,de)},_s=h.useCallback(de=>L.current.has(de)?!1:(L.current.add(de),X(new Set(L.current)),!0),[]),et=h.useCallback(de=>{L.current.delete(de),X(new Set(L.current))},[]),Hn=async()=>{c.selectedOrganizationId&&await k.invalidateQueries({queryKey:V.messenger.customGroups(c.selectedOrganizationId)})},dr=h.useCallback(async de=>{const He=new Set([0,F,...Object.keys(q).map(Number)]);await Promise.all([k.invalidateQueries({queryKey:V.messenger.customGroups(de)}),...Array.from(He).map(wt=>k.invalidateQueries({queryKey:V.messenger.savedViews(de,"visible",$ne,wt)}))]),Ie.current===de&&(B({}),Q(0))},[q,k,F]),ca=xt({mutationFn:async({name:de,icon:He,threadKey:wt})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to create a Messenger group");return Ks.createCustomGroupWithEntries(c.selectedOrganizationId,{autoGenerateName:!1,icon:He,itemKeys:[wt],name:de})},onSuccess:async()=>{c.selectedOrganizationId&&Pc("latest"),await Hn()}}),wi=xt({mutationFn:({groupId:de,data:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to update a Messenger group");return Ks.updateCustomGroup(c.selectedOrganizationId,de,He)},onSuccess:Hn}),Ni=h.useCallback((de,He)=>{const wt=c.selectedOrganizationId;if(!wt)return Promise.reject(new Error("Organization is required to update a Messenger group"));const en=(ot.current[de]??Promise.resolve()).catch(()=>{}).then(async()=>{await Ks.updateCustomGroup(wt,de,{collapsed:He})});return ot.current[de]=en,en.then(async()=>{ot.current[de]===en&&(delete ot.current[de],await Hn())},gn=>{ot.current[de]===en&&(delete ot.current[de],Hn()),e({title:"Could not update group",body:gn instanceof Error?gn.message:"Please try again.",tone:"error"})}),en},[c.selectedOrganizationId,e,Hn]),vd=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to regenerate a Messenger group title");return Ks.regenerateCustomGroupTitle(c.selectedOrganizationId,de)},onMutate:de=>{ge(He=>{const wt=new Set(He);return wt.add(de),wt})},onSettled:async(de,He,wt)=>{ge(Dt=>{const en=new Set(Dt);return en.delete(wt),en}),await Hn()}}),r1=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to separate a Messenger group");return Ks.separateCustomGroup(c.selectedOrganizationId,de)},onSuccess:async()=>{c.selectedOrganizationId&&await dr(c.selectedOrganizationId)},onError:de=>{e({title:"Could not separate Messenger group",body:de instanceof Error?de.message:"Try again.",tone:"error"})}}),mf=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to reorder Messenger groups");return Ks.reorderCustomGroups(c.selectedOrganizationId,de)},onSuccess:Hn}),el=xt({mutationFn:({groupId:de,itemKeys:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to reorder Messenger group entries");return Ks.reorderCustomGroupEntries(c.selectedOrganizationId,de,He)},onSuccess:Hn}),_l=xt({mutationFn:({groupId:de,itemKey:He,itemKeys:wt,organizationId:Dt})=>Ks.reorderCustomGroupEntries(Dt,de,wt),onSuccess:async(de,{organizationId:He})=>{await dr(He),e({title:"Saved View moved",body:"The Messenger group order was updated.",tone:"success"})},onError:de=>{e({title:"Could not move Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{itemKey:wt})=>{et(wt)}}),ai=xt({mutationFn:({groupId:de,threadKey:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to move a Messenger thread");return Ks.assignCustomGroupEntry(c.selectedOrganizationId,de,He)},onSuccess:async()=>{Pc("latest"),await Hn()}}),tl=xt({mutationFn:de=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to move a Messenger thread");return Ks.removeCustomGroupEntry(c.selectedOrganizationId,de)},onSuccess:Hn}),wd=xt({mutationFn:({groupId:de,itemKey:He,organizationId:wt})=>Ks.assignCustomGroupEntry(wt,de,He),onSuccess:async(de,{organizationId:He})=>{await dr(He),e({title:"Saved View moved",body:"The Messenger group was updated.",tone:"success"})},onError:de=>{e({title:"Could not move Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{itemKey:wt})=>{et(wt)}}),pf=h.useCallback((de,He)=>{const wt=c.selectedOrganizationId;!wt||!_s(He)||wd.mutate({groupId:de,itemKey:He,organizationId:wt})},[_s,c.selectedOrganizationId,wd]),Hc=xt({mutationFn:({itemKey:de,organizationId:He,nextOrderKeys:wt,orderStorageKey:Dt})=>Ks.removeCustomGroupEntry(He,de),onSuccess:async(de,{nextOrderKeys:He,orderStorageKey:wt,organizationId:Dt})=>{await dr(Dt),He&&wt&&Ie.current===Dt&&(Kr(He),Pk(wt,He)),e({title:"Saved View moved",body:"The Saved View is now in the Messenger sidebar.",tone:"success"})},onError:de=>{e({title:"Could not move Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{itemKey:wt})=>{et(wt)}}),bp=h.useCallback(de=>{const He=c.selectedOrganizationId;!He||!_s(de)||Hc.mutate({itemKey:de,organizationId:He})},[_s,c.selectedOrganizationId,Hc]),Lb=xt({mutationFn:({anchorItemKey:de,itemKeys:He,name:wt,organizationId:Dt,savedViewItemKey:en})=>Ks.createCustomGroupWithEntries(Dt,{anchorItemKey:de,autoGenerateName:!1,itemKeys:He,name:wt}),onSuccess:async(de,{organizationId:He})=>{JPe(He,"latest"),Ie.current===He&&Ee("latest"),await dr(He),e({title:"Saved View grouped",body:"Created or reused the Chat or Issue group.",tone:"success"})},onError:de=>{e({title:"Could not group Saved View",body:de instanceof Error?de.message:"Try again.",tone:"error"})},onSettled:(de,He,{savedViewItemKey:wt})=>{et(wt)}}),yp=h.useCallback(de=>{const He=Array.from(document.querySelectorAll("[data-messenger-thread-key],[data-messenger-saved-view-id]")),wt=He.findIndex(en=>en.dataset.messengerSavedViewId===de);if(wt===-1)return null;const Dt=He[wt+1]??He[wt-1]??null;return Dt?cIe(Dt):null},[]),s1=h.useCallback(async({focusItemKey:de,organizationId:He,savedViewId:wt})=>{var en;u==null||u.finalizeSavedViewRemoval(He,wt);const Dt=d.getState().organizations[He];for(const gn of Object.values((Dt==null?void 0:Dt.tabsByViewInstanceId)??{}))gn.savedViewId===wt&&d.unbindSavedViewForOrganization(He,gn.viewInstanceId,wt);if(Ie.current===He&&Ke.current===aj(wt)&&n("/messenger/workbench",{replace:!0}),VVt(k,He,wt),await dr(He),await k.invalidateQueries({queryKey:V.messenger.primaryRailPins(He)}),de&&Ie.current===He){const gn=Array.from(document.querySelectorAll("[data-messenger-thread-key],[data-messenger-saved-view-id]")).find(yn=>cIe(yn)===de);(en=(gn==null?void 0:gn.querySelector("a[href]"))??(gn==null?void 0:gn.querySelector("button,[tabindex]"))??gn)==null||en.focus()}e({title:"Removed from Messenger",body:"The open Main tab remains available for this session.",tone:"success"})},[d,n,e,k,dr,u]),gf=xt({mutationFn:async({organizationId:de,savedViewId:He,focusItemKey:wt})=>(await Ks.deleteSavedView(de,He),{focusItemKey:wt,organizationId:de,savedViewId:He}),onMutate:({organizationId:de,savedViewId:He})=>{u==null||u.setSavedViewRemovalPending(de,He,!0)},onSuccess:s1,onError:async(de,{focusItemKey:He,organizationId:wt,savedViewId:Dt})=>{let en=de instanceof Nl&&de.status===404,gn=!1;if(!en)try{await Ks.getSavedView(wt,Dt),gn=!0}catch(yn){en=yn instanceof Nl&&yn.status===404}if(en){await s1({focusItemKey:He,organizationId:wt,savedViewId:Dt});return}gn&&(u==null||u.setSavedViewRemovalPending(wt,Dt,!1)),e({title:gn?"Could not remove Saved View":"Could not confirm Saved View removal",body:gn?de instanceof Error?de.message:"Try again.":"The move remains paused. Retry Remove to reconcile it.",tone:"error"})}}),om=h.useCallback(de=>{const He=c.selectedOrganizationId;He&&gf.mutate({focusItemKey:yp(de),organizationId:He,savedViewId:de})},[c.selectedOrganizationId,yp,gf]),xf=h.useCallback(de=>{const He=de.over?String(de.over.id):null;Tt(He);const wt=String(de.active.id);let Dt=Wr(wt,He);const en=Ge.get(wt),gn=He?p5(vn).find(pr=>pr.thread.threadKey===He):null;if((en==null?void 0:en.groupId)===null&&(gn==null?void 0:gn.customGroupId)===null&&(gn.thread.kind==="chat"||gn.thread.kind==="issues")&&(Dt=d$(de)?"reorder-entry":"move-into-group"),Mn(Dt),Dt!=="move-into-group"||!He||Ye!=="custom"){tr();return}const yn=Cd(He)??mr.get(He)??null,Sn=yn?Or.find(pr=>pr.id===yn):null;if(!Sn||!Sn.collapsed){tr();return}$e.current===Sn.id&&Pe.current||(tr(),$e.current=Sn.id,Pe.current=setTimeout(()=>{Pe.current=null,$e.current=null,Ni(Sn.id,!1)},500))},[tr,mr,Or,Ye,vn,Wr,Ge,Ni,Mn,Tt]),kd=de=>{const He=Mt.get(de);if(He){Ni(He.id,!He.collapsed);return}S2e(Ye)&&gt(wt=>{const Dt=new Set(wt);return Dt.has(de)?Dt.delete(de):Dt.add(de),c.selectedOrganizationId&&nIe(c.selectedOrganizationId,Ye,Dt),Dt})},lm=h.useCallback(de=>{var oi,to,Xc,Gc;pt();const{active:He,over:wt}=de;if(!wt||He.id===wt.id||!i5(Ye))return;const Dt=c.selectedOrganizationId;if(!Dt)return;if(Ye==="custom"){const he=String(He.id),rt=String(wt.id),Pt=Ge.get(he)??null;if(Pt){const Rr=Ao.filter(Oa=>Oa.key!=="custom:pinned").map(Oa=>Oa.key),ua=Oa=>{if(!Rt)return null;const Ba=Rr.includes(he)?Rr:[...Rr,he],Od=Ba.indexOf(he),dc=Ba.filter(Io=>Io!==he).indexOf(rt);if(Od===-1||dc===-1)return null;const Op=Math.min(Ba.length-1,dc+(Oa==="after"?1:0));return a$(Ba,sr,Od,Op)},Xs=Oa=>{!Rt||!Oa||(Kr(Oa),Pk(Rt,Oa))},mo=Cd(rt),ka=mr.has(rt)?mr.get(rt)??null:void 0,Yc=mo??ka;if(ka===null&&fr.has(rt)){const Oa=p5(vn).find(Od=>Od.thread.threadKey===rt),Ba=d$(de);if(Oa&&(Oa.thread.kind==="chat"||Oa.thread.kind==="issues")&&Ba===null&&_s(he)){Lb.mutate({anchorItemKey:rt,itemKeys:[rt,he],name:Oa.thread.title.trim()||"New group",organizationId:Dt,savedViewItemKey:he});return}if(!Oa||Ba===null)return}if(Yc&&Yc!==Pt.groupId&&_s(he)){wd.mutate({groupId:Yc,itemKey:he,organizationId:Dt});return}if(Yc&&Yc===Pt.groupId){const Oa=Or.find(dc=>dc.id===Pt.groupId),Ba=(Oa==null?void 0:Oa.entries.slice().sort((dc,Op)=>dc.sortOrder-Op.sortOrder).map(_y))??[],Od=Ba.indexOf(he),Mu=Ba.indexOf(rt);Od!==-1&&Mu!==-1&&Od!==Mu&&_s(he)&&_l.mutate({groupId:Pt.groupId,itemKey:he,itemKeys:g2(Ba,Od,Mu),organizationId:Dt});return}if(ka===null){const Oa=d$(de),Ba=Rr.indexOf(he),Od=Rr.indexOf(rt),Mu=Oa??(Pt.groupId||Ba<Od?"after":"before"),dc=ua(Mu);Pt.groupId&&_s(he)?Hc.mutate({itemKey:he,nextOrderKeys:dc??void 0,orderStorageKey:Rt,organizationId:Dt}):Pt.groupId||Xs(dc)}return}const Yt=Ao.filter(Rr=>Rr.key!=="custom:pinned").map(Rr=>Rr.key),ur=((to=(oi=vn.find(Rr=>Rr.key==="custom:pinned"))==null?void 0:oi.childSections)==null?void 0:to.flatMap(Rr=>Rr.entries.map(ua=>ua.thread.threadKey)))??[],Hr=(Rr,ua,Xs)=>{if(!Rt)return;const mo=a$(Rr,sr,ua,Xs);Kr(mo),Pk(Rt,mo)},Wl=fr.has(he),fm=fr.has(rt),Gd=fr.get(he)??null,uh=fm?fr.get(rt)??null:void 0,_u=Cd(rt)??uh,Ml=Cd(he),El=Cd(rt);if(Ml&&El){const Rr=Or.find(ka=>ka.id===Ml),ua=Or.find(ka=>ka.id===El);if(!Rr||!ua||!!Rr.pinnedAt!=!!ua.pinnedAt)return;const Xs=Rr.pinnedAt?((Gc=(Xc=vn.find(ka=>ka.key==="custom:pinned"))==null?void 0:Xc.childSections)==null?void 0:Gc.map(ka=>ka.key).filter(ka=>!!Cd(ka)))??[]:vn.map(ka=>ka.key).filter(ka=>!!Cd(ka)),mo=Xs.indexOf(he),Zl=Xs.indexOf(rt);if(mo!==-1&&Zl!==-1){const ka=g2(Xs,mo,Zl);if(Rt){const Yc=a$(Xs,sr,mo,Zl);Kr(Yc),Pk(Rt,Yc)}mf.mutate(ka.map(Cd).filter(Yc=>!!Yc))}return}if(Wl&&fm&&Gd===null&&uh===null&&he!==rt){const Rr=ur.includes(he)&&ur.includes(rt)?ur:Yt,ua=Rr.indexOf(he),Xs=Rr.indexOf(rt);ua!==-1&&Xs!==-1&&Hr(Rr,ua,Xs);return}if(Wl&&fm&&Gd&&uh===null&&he!==rt){const Rr=Yt.indexOf(rt);if(Rr!==-1){const ua=Yt.includes(he)?Yt:[...Yt.slice(0,Rr),he,...Yt.slice(Rr)],Xs=ua.indexOf(he),mo=ua.indexOf(rt);Xs!==-1&&mo!==-1&&Hr(ua,Xs,mo)}tl.mutate(he);return}if(Wl&&_u!==void 0){const Rr=fr.get(he)??null;if(Rr!==_u){if(!_u){const ua=Yt.indexOf(rt);if(ua!==-1){const Xs=Yt.includes(he)?Yt:[...Yt.slice(0,ua),he,...Yt.slice(ua)],mo=Xs.indexOf(he),Zl=Xs.indexOf(rt);mo!==-1&&Zl!==-1&&Hr(Xs,mo,Zl)}}_u?ai.mutate({groupId:_u,threadKey:he}):tl.mutate(he);return}if(Rr===null){const ua=Yt.indexOf(he),Xs=Yt.indexOf(rt);ua!==-1&&Xs!==-1&&Hr(Yt,ua,Xs);return}}if(Gd&&uh&&Gd===uh){const Rr=Or.find(Zl=>Zl.id===Gd),ua=(Rr==null?void 0:Rr.entries.slice().sort((Zl,ka)=>Zl.sortOrder-ka.sortOrder).map(_y))??[],Xs=ua.indexOf(he),mo=ua.indexOf(rt);Xs!==-1&&mo!==-1&&el.mutate({groupId:Gd,itemKeys:g2(ua,Xs,mo)});return}}const en=Ye==="custom"?vn.filter(he=>he.key!=="custom:pinned").map(he=>he.key):vn.filter(he=>Ye!=="project"||!he.isPinned).map(he=>he.key),gn=en.indexOf(He.id),yn=en.indexOf(wt.id);if(gn===-1||yn===-1)return;if(Ye==="custom"){const he=g2(en,gn,yn);if(Rt){const Pt=a$(en,sr,gn,yn);Kr(Pt),Pk(Rt,Pt)}const rt=he.map(Cd).filter(Pt=>!!Pt);rt.length>0&&mf.mutate(rt);return}if(!Qt||!H_(Ye))return;const Sn=g2(en,gn,yn).map(he=>SQn(Ye,he));if(as(Sn),Pk(Qt,Sn),Ye!=="project")return;const pr=Sn.map(he=>Hft(Ye,he)).map(he=>_4(he)).filter(he=>!!he),Fr=new Set(pr),xa=[...pr,...Cn.filter(he=>!Fr.has(he))];zn(xa),nt&&whe(nt,xa)},[ai,_s,Lb,mr,fr,Or,sr,Rt,Ye,Qt,c.selectedOrganizationId,wd,vn,Cn,nt,Hc,tl,el,mf,_l,pt,Ge,Ao]),Pu=(de,He)=>{var wt;if(He<de.entries.length){Gt(Dt=>({...Dt,[de.key]:Math.min(de.entries.length,He+FQn)}));return}Mt.has(de.key)||c.hasMoreThreadSummaries&&!c.isFetchingMoreThreadSummaries&&((wt=c.loadMoreThreadSummaries)==null||wt.call(c))},bf=de=>{Gt(He=>({...He,[de]:Ik}))},vp=()=>{const de=Jt.data,He=de==null?void 0:de.pageInfo.nextOffset;!(de!=null&&de.pageInfo.hasMore)||He===null||He===void 0||(B(wt=>({...wt,[de.pageInfo.offset]:de.items})),Q(He))},zb=de=>{const He=iIe(de);!He||!st||ht(wt=>{const Dt={...wt,[de.threadKey]:He};return yQn(st,Dt),Dt})},oA=(de,He,wt)=>{M.current=de,E.current=He,T.current=!0,ae(null),Ne({mode:"create",threadKey:wt}),ve(""),ze("folder"),ie("amber")},da=h.useCallback(()=>{Ne(null),ve(""),ze("folder"),ie("amber")},[]),lA=()=>{if(!(ke!=null&&ke.threadKey))return;const de=fe.trim();if(!de)return;const He=_ne(Se,ft);ca.mutate({name:de,icon:He||null,threadKey:ke.threadKey}),da()},Fa=(de,He,wt)=>{window.setTimeout(()=>{de.isConnected&&He.isConnected&&oA(de,He,wt)},0)};h.useEffect(()=>{if(!ke)return;const de=M.current,He=P.current;if(!(de!=null&&de.isConnected)||!(He!=null&&He.contains(de)))return;const wt=()=>{const Dt=de.getBoundingClientRect(),en=He.getBoundingClientRect();Dt.bottom>en.top&&Dt.top<en.bottom||(T.current=!1,da())};return He.addEventListener("scroll",wt,{passive:!0}),()=>He.removeEventListener("scroll",wt)},[da,ke]);const $b=de=>{Ne(null),ae({group:de,name:de.name})},e0=()=>{ae(null)},Iu=()=>{if(!xe)return;const de=xe.name.trim();de&&(wi.mutate({groupId:xe.group.id,data:{name:de}}),e0())},Zd=(de,He)=>{const wt=c.selectedOrganizationId;if(!wt)return;const gn=(ee.current[de]??Promise.resolve()).catch(()=>{}).then(async()=>{try{await Ks.updateCustomGroup(wt,de,{icon:He}),await Hn()}catch{we(Sn=>{if(Sn[de]!==He)return Sn;const pr={...Sn};return delete pr[de],pr})}}).finally(()=>{ee.current[de]===gn&&delete ee.current[de]});ee.current[de]=gn},Hd=(de,He)=>{const wt=me[de.id]??de.icon,en=cq(wt).color??FI(de),gn=_ne(He,en)||null;we(yn=>({...yn,[de.id]:gn})),Zd(de.id,gn)},lh=(de,He)=>{const wt=me[de.id]??de.icon,Dt=cq(wt),en=_ne(Dt.glyph,He)||null;we(gn=>({...gn,[de.id]:en})),Zd(de.id,en)},i1=async de=>{await m({title:"Separate items",description:`Move the items in "${de.name}" back into the main list? The Messenger threads will stay intact.`,confirmLabel:"Separate items",tone:"default"})&&r1.mutate(de.id)},a1=(de,He,wt=!1)=>{var Sn,pr;const{thread:Dt,conversation:en}=de,gn=Vr===Dt.threadKey,yn=Ue===Dt.threadKey;if(Dt.kind==="chat"&&en){const Fr=Xft(en),xa=!Dv(en);return i.jsx(qBn,{conversation:en,agent:Fr?Er.get(Fr)??null:null,agentId:Fr,sourceBadge:j2e(en,Dt.metadata),href:Dt.href,active:gn,generating:((Sn=Dt.metadata)==null?void 0:Sn.isProcessing)===!0||typeof((pr=Dt.metadata)==null?void 0:pr.activeGenerationId)=="string"&&Dt.metadata.activeGenerationId.length>0,density:Ce,renaming:se===en.id,renameDraft:ne,onRenameDraftChange:Ae,onCommitRename:yf,onCancelRename:()=>{Ae(""),re(null)},onStartRename:()=>{re(en.id),Ae(en.title)},onRegenerateTitle:ds?()=>ut.mutate(en.id):void 0,titleGenerating:Oe.has(en.id),onFork:()=>h8.mutate(en.id),onArchive:()=>{c.selectedOrganizationId&&fqe(k,c.selectedOrganizationId,en.id),ch.mutate({chatId:en.id,data:{status:"archived"}})},onDelete:async()=>{await m({title:"Delete chat",description:`Delete "${YF(en)}"? This cannot be undone.`,confirmLabel:"Delete",tone:"destructive"})&&Nw.mutate({chatId:en.id,generating:x(en.id)})},archiveDeleteAllowed:xa,onTogglePin:()=>{c.selectedOrganizationId&&uqe(k,c.selectedOrganizationId,en.id,!en.isPinned),dh.mutate({chatId:en.id,pinned:!en.isPinned})},onToggleUnread:()=>{dh.mutate({chatId:en.id,unread:!en.isUnread})},onCopyConversationLink:()=>void n0(en),customGroups:Or,customGroupId:de.customGroupId,customGroupPending:de.customGroupId?!Or.some(oi=>oi.id===de.customGroupId):!1,onMoveToCustomGroup:oi=>ai.mutate({groupId:oi,threadKey:Dt.threadKey}),onRemoveFromCustomGroup:()=>tl.mutate(Dt.threadKey),onCreateCustomGroup:(oi,to)=>Fa(oi,to,Dt.threadKey),dragHandleProps:He,dragging:wt,onSelect:Vo},Dt.threadKey)}return i.jsx(KBn,{thread:Dt,active:gn,density:Ce,preserveUnreadEmphasis:yn,onTogglePin:()=>{c.selectedOrganizationId&&dqe(k,c.selectedOrganizationId,Dt.threadKey,!Dt.isPinned),cm.mutate({threadKey:Dt.threadKey,pinned:!Dt.isPinned})},onHideIssue:()=>zb(Dt),customGroups:Or,customGroupId:de.customGroupId,customGroupPending:de.customGroupId?!Or.some(Fr=>Fr.id===de.customGroupId):!1,onMoveToCustomGroup:Fr=>ai.mutate({groupId:Fr,threadKey:Dt.threadKey}),onRemoveFromCustomGroup:()=>tl.mutate(Dt.threadKey),onCreateCustomGroup:(Fr,xa)=>Fa(Fr,xa,Dt.threadKey),dragHandleProps:He,dragging:wt,onSelect:yd},Dt.threadKey)},o1=(de,He,wt=!1)=>{const Dt=`saved-view:${de.id}`;return i.jsx(Mne,{active:oc===de.id,currentGroupId:null,density:Ce,dragHandleProps:He,dragging:wt,itemKey:Dt,savedView:de,groups:Or,onMove:pf,onRemove:om,placementPending:H.has(Dt)})},Tu=(de,He,wt=!1)=>{var Io,l1;const Dt=i5(Ye),en=Ye==="agent"&&de.key.startsWith("agent:")?de.key.slice(6):null,gn=en?Er.get(en)??null:null,yn=Mt.get(de.key)??null,Sn=!!(yn&&Xe.has(yn.id)),pr=yn,Fr=yn?yn.collapsed:Dt&&Qe.has(de.key),xa=te?mr.get(te):void 0,oi=oe===de.key||de.entries.some(Jn=>Jn.thread.threadKey===oe)||!!(yn!=null&&yn.entries.some(Jn=>_y(Jn)===oe)),to=Ye==="custom"&&!!pr&&!!te&&xa!==void 0&&xa!==(yn==null?void 0:yn.id)&&Te==="move-into-group"&&oi,Xc=Ye==="custom"&&!yn&&de.label===null&&oi&&te!==de.key&&Te==="move-out-of-group",Gc=Jn=>{if(!te||oe!==Jn||Te!=="reorder-entry")return null;if(!yn&&de.label===null&&de.entries.length===1){const pl=vn.filter(Tc=>Tc.key!=="custom:pinned").map(Tc=>Tc.key),Jc=pl.indexOf(te),vf=pl.indexOf(Jn);return Jc===-1||vf===-1||Jc===vf?null:Jc<vf?"after":"before"}const Pi=de.entries.map(pl=>pl.thread.threadKey),To=Pi.indexOf(te),qo=Pi.indexOf(Jn);return To===-1||qo===-1||To===qo?null:To<qo?"after":"before"},he=(()=>{var Jc,vf;if(!te||oe!==de.key||Te!=="reorder-group")return null;const Jn=Cd(te),Pi=Jn?Or.find(Tc=>Tc.id===Jn):null,To=Pi!=null&&Pi.pinnedAt?((vf=(Jc=vn.find(Tc=>Tc.key==="custom:pinned"))==null?void 0:Jc.childSections)==null?void 0:vf.map(Tc=>Tc.key).filter(Tc=>!!Cd(Tc)))??[]:vn.filter(Tc=>Tc.key!=="custom:pinned").map(Tc=>Tc.key),qo=To.indexOf(te),pl=To.indexOf(de.key);return qo===-1||pl===-1||qo===pl?null:qo<pl?"after":"before"})(),rt=Dt?Math.max(Nt[de.key]??Ik,hf.get(de.key)??Ik):de.entries.length,Pt=Dt?de.entries.slice(0,rt):de.entries,Yt=Dt&&rt<de.entries.length,ur=Dt&&!yn&&!!c.hasMoreThreadSummaries&&rt>=de.entries.length&&de.entries.length>=Ik,Hr=!Fr&&(Yt||ur||!!(c.isFetchingMoreThreadSummaries&&ur)),Wl=!Fr&&Dt&&rt>Ik,fm=Dt?`messenger-thread-section-${oo(de.key)}-content`:void 0,Gd=Ye==="custom"&&de.key==="custom:pinned",uh=Ye==="custom"&&de.key==="custom:pinned:loose",_u=Gd,Ml=Ye==="custom"&&(!!yn||Gd||uh)&&(yn?yn.entries.length>0:Pt.length>0),El=Ye==="custom"&&!yn&&(de.label===null||Gd)&&Pt.length===1,Rr=Ye==="custom"?((Io=de.childSections)==null?void 0:Io.filter(Jn=>!!Cd(Jn.key)).map(Jn=>Jn.key))??[]:[],ua=(l1=de.childSections)!=null&&l1.length?i.jsx(l3,{items:Rr,strategy:WP,children:i.jsx("div",{className:"flex flex-col gap-1",children:de.childSections.map(Jn=>Rr.includes(Jn.key)?i.jsx(dIe,{id:Jn.key,children:(Pi,To)=>Tu(Jn,Pi,To)},Jn.key):i.jsx("div",{className:"flex shrink-0 flex-col gap-1",children:Tu(Jn)},Jn.key))})}):null,Xs=new Map(Pt.map(Jn=>[Jn.thread.threadKey,Jn])),mo=Jn=>Ml?i.jsx(Bne,{id:Jn.thread.threadKey,insertionPlacement:Gc(Jn.thread.threadKey),children:(Pi,To)=>a1(Jn,Pi,To)},Jn.thread.threadKey):i.jsxs("div",{className:"relative",children:[i.jsx(eB,{placement:Gc(Jn.thread.threadKey)}),a1(Jn,El?He:void 0)]},Jn.thread.threadKey),ka=(yn==null?void 0:yn.entries.slice().sort((Jn,Pi)=>Jn.sortOrder-Pi.sortOrder))??[],Yc=yn?ka.map(Jn=>{if(l$(Jn)){const To=_y(Jn),qo=H.has(To),pl=i.jsx(Mne,{active:oc===Jn.item.savedView.id,currentGroupId:yn.id,density:Ce,entry:Jn,groups:Or,onMove:pf,onMoveOutOfGroup:bp,onRemove:om,placementPending:qo});return Ml?i.jsx(Bne,{id:To,disabled:qo,children:(Jc,vf)=>i.jsx(Mne,{active:oc===Jn.item.savedView.id,currentGroupId:yn.id,density:Ce,dragHandleProps:Jc,dragging:vf,entry:Jn,groups:Or,onMove:pf,onMoveOutOfGroup:bp,onRemove:om,placementPending:qo})},To):i.jsx("div",{children:pl},To)}const Pi=Xs.get(Jn.threadKey);return Pi?mo(Pi):null}):Pt.map(mo),Oa=yn?ka.map(_y):Pt.map(Jn=>Jn.thread.threadKey),Ba=Yc.flatMap((Jn,Pi)=>Jn==null?[]:[{key:Oa[Pi]??`${de.key}:${Pi}`,node:Jn}]),Od=Bn!=null&&Bn.sectionPath.includes(de.key)?Bn.threadKey:null,Mu=Ba.length>30?i.jsx(m0e,{items:Ba,getItemKey:Jn=>Jn.key,estimateSize:()=>Ce==="compact"?34:42,itemGap:4,overscan:te?QQn:BQn,preventScrollBlanking:!0,scrollElementRef:P,targetKey:Od,onTargetMounted:Jn=>{var To;if(!Bn||Jn!==Bn.threadKey||De<=0)return;const Pi=Array.from(((To=P.current)==null?void 0:To.querySelectorAll("[data-messenger-thread-key]"))??[]).find(qo=>qo.dataset.messengerThreadKey===Jn);Pi&&(Pi.scrollIntoView({block:"nearest",behavior:"smooth"}),_.current=Jn,D.current=De,Ine(De),U.current=null)},testId:`messenger-section-virtual-entries-${oo(de.key)}`,children:Jn=>Jn.node}):Ba.map(Jn=>i.jsx("div",{children:Jn.node},Jn.key)),dc=Ml?i.jsx(l3,{items:yn?ka.map(_y):Pt.map(Jn=>Jn.thread.threadKey),strategy:WP,children:Mu}):Mu,Op=i.jsxs(i.Fragment,{children:[ua,i.jsx("div",{className:"flex flex-col gap-1",children:dc}),Hr||Wl?i.jsxs("div",{"data-messenger-scroll-coverage-row":!0,className:"mx-1.5 flex items-center gap-1.5 px-2 py-1",children:[Hr?i.jsx(JQn,{testId:`messenger-thread-section-${oo(de.key)}-auto-loader`,loading:!!(c.isFetchingMoreThreadSummaries&&ur),onVisible:()=>Pu(de,rt)}):null,Wl?i.jsx("button",{type:"button","data-testid":`messenger-thread-section-${oo(de.key)}-collapse`,className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[11px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",onClick:()=>bf(de.key),children:"Collapse"}):null]}):null]});if(de.label&&pr){const Jn=wde(de);return i.jsx($Qn,{collapsed:pr.collapsed,onCollapsedChange:Pi=>Ni(pr.id,Pi),children:(Pi,To,qo)=>i.jsxs("div",{ref:qo,"data-testid":`messenger-thread-section-${oo(de.key)}`,"data-messenger-scroll-coverage-surface":!0,"data-collapsed":Pi?"true":"false","data-drag-move-target":to?"true":void 0,"data-drag-intent":to?"move-into-group":void 0,className:K("group/custom-group relative mx-0.5 rounded-[calc(var(--radius-md)-1px)] border p-1 text-[color:var(--messenger-group-text)] transition-[background-color,border-color,box-shadow] duration-150 dark:text-[color:var(--messenger-group-text-dark)]",Pi&&!to?"border-transparent bg-transparent shadow-none hover:border-[color:var(--messenger-group-border)] hover:bg-[color:var(--messenger-group-bg-hover)] has-[:focus-visible]:border-[color:var(--messenger-group-border)] has-[:focus-visible]:bg-[color:var(--messenger-group-bg-hover)] dark:border-transparent dark:bg-transparent dark:hover:border-[color:var(--messenger-group-border-dark)] dark:hover:bg-[color:var(--messenger-group-bg-hover-dark)] dark:has-[:focus-visible]:border-[color:var(--messenger-group-border-dark)] dark:has-[:focus-visible]:bg-[color:var(--messenger-group-bg-hover-dark)]":"border-[color:var(--messenger-group-border)] bg-[color:var(--messenger-group-bg)] shadow-[0_8px_20px_-18px_rgba(15,23,42,0.45)] hover:bg-[color:var(--messenger-group-bg-hover)] dark:border-[color:var(--messenger-group-border-dark)] dark:bg-[color:var(--messenger-group-bg-dark)] dark:hover:bg-[color:var(--messenger-group-bg-hover-dark)]",to&&"ring-2 ring-[color:color-mix(in_oklab,var(--messenger-group-text)_34%,transparent)]"),style:_Bn(pr),children:[i.jsx(eB,{placement:he,tone:"group"}),i.jsxs("div",{"data-messenger-scroll-coverage-row":!0,className:"flex min-h-8 items-center gap-1.5",children:[i.jsx(EH,{dragHandleProps:He,label:`Drag group ${de.label}`,compact:!0}),i.jsxs("button",{type:"button","data-messenger-group-trigger":!0,"aria-expanded":!Pi,className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-[calc(var(--radius-sm)-2px)] px-0.5 text-left text-[12px] font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",onClick:To,children:[Pi?i.jsx(bi,{className:"h-3 w-3 shrink-0","aria-hidden":!0}):i.jsx(qr,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),i.jsx(RD,{icon:pr.icon,color:FI(pr)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:de.label}),Sn?i.jsxs("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-title-generating`,className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-white/35 px-1.5 py-0.5 text-[10px] font-semibold text-current/75","aria-label":"Generating group title",children:[i.jsx(hn,{className:"h-2.5 w-2.5 animate-spin","aria-hidden":!0}),"Naming"]}):null,Jn>0?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-attention-count`,className:"shrink-0 rounded-full bg-white/45 px-1.5 py-0.5 text-[10px] font-semibold",children:Jn}):null]}),to?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-drop-intent`,className:"shrink-0 rounded-full bg-white/45 px-1.5 py-0.5 text-[10px] font-semibold text-current/80",children:"Move into group"}):null,yn?i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button","aria-label":"Group actions",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-current/70 opacity-0 transition-[opacity,background-color,color] hover:bg-white/45 hover:text-current focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 group-hover/custom-group:opacity-100 group-focus-within/custom-group:opacity-100 data-[state=open]:opacity-100",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"messenger-thread-actions-menu morph-popover morph-popover--from-right surface-overlay text-foreground",children:[i.jsxs(Xt,{onClick:()=>$b(yn),children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename..."]}),i.jsxs(Xt,{disabled:Sn,onClick:()=>vd.mutate(yn.id),children:[Sn?i.jsx(hn,{className:"h-4 w-4 animate-spin"}):i.jsx(KA,{className:"h-4 w-4"}),"Regenerate title"]}),i.jsx(Xt,{onClick:()=>wi.mutate({groupId:yn.id,data:{pinned:!yn.pinnedAt}}),children:yn.pinnedAt?i.jsxs(i.Fragment,{children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}):i.jsxs(i.Fragment,{children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]})}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(wo,{className:"h-4 w-4"}),"Change icon"]}),i.jsx(i6,{className:"morph-popover morph-popover--from-left surface-overlay w-auto p-2 text-foreground",style:wft(FI({id:yn.id,icon:me[yn.id]??yn.icon,sortOrder:yn.sortOrder})),children:i.jsx(kft,{icon:me[yn.id]??yn.icon,ariaLabel:"Group icons",onIconChange:pl=>Hd(yn,pl)})})]}),i.jsxs(r6,{children:[i.jsxs(s6,{children:[i.jsx(ZK,{className:"h-4 w-4"}),"Pick color"]}),i.jsx(i6,{className:"morph-popover morph-popover--from-left surface-overlay text-foreground",children:W_.map(pl=>{const Jc=DD[pl];return i.jsxs(Xt,{onClick:()=>lh(yn,pl),children:[i.jsx("span",{className:"inline-flex h-3.5 w-3.5 rounded-full border border-[color:color-mix(in_oklab,var(--border-strong)_42%,transparent)]",style:{backgroundColor:Jc.swatch},"aria-hidden":!0}),pl[0].toUpperCase()+pl.slice(1)]},pl)})})]}),i.jsx(Yo,{}),i.jsxs(Xt,{onClick:()=>void i1(yn),children:[i.jsx(aE,{className:"h-4 w-4"}),"Separate items"]})]})]}):null]}),i.jsx("div",{"data-testid":fm,"data-messenger-group-content":!0,className:K("grid",Pi||wt?"mt-0 grid-rows-[0fr] opacity-0":"mt-1 grid-rows-[1fr] opacity-100"),"aria-hidden":Pi||wt?"true":void 0,inert:Pi||wt?!0:void 0,children:i.jsx("div",{className:"min-h-0 overflow-hidden",children:Op})})]})})}return!de.label&&Xc?i.jsxs("div",{"data-drag-drop-target":"true","data-drag-intent":"move-out-of-group",className:"relative rounded-[calc(var(--radius-md)-1px)] ring-2 ring-[color:color-mix(in_oklab,var(--accent-strong)_30%,transparent)] ring-offset-1 ring-offset-[color:var(--surface-page)] transition-[background-color,border-color] duration-150",children:[i.jsx("div",{className:"pointer-events-none absolute -top-1 left-3 right-3 h-0.5 rounded-full bg-[color:var(--accent-strong)]"}),i.jsx("div",{"data-testid":`messenger-thread-section-${oo(de.key)}-drop-intent`,className:"pointer-events-none absolute right-2 top-1 z-10 rounded-full bg-[color:color-mix(in_oklab,var(--surface-elevated)_94%,transparent)] px-1.5 py-0.5 text-[10px] font-semibold text-[color:var(--accent-strong)] shadow-sm",children:"Move out of group"}),Op]}):i.jsxs(i.Fragment,{children:[de.label&&!_u?Dt?(()=>{const Jn=wde(de);return i.jsxs("button",{type:"button",...He==null?void 0:He.attributes,...He==null?void 0:He.listeners,"data-testid":`messenger-thread-section-${oo(de.key)}`,"aria-expanded":!Fr,className:"relative mx-1.5 flex min-h-8 items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] px-1.5 py-1.5 text-left text-[11px] font-semibold text-muted-foreground/72 transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_54%,transparent)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25",onClick:()=>kd(de.key),children:[i.jsx(eB,{placement:he}),Fr?i.jsx(bi,{className:"h-3 w-3 shrink-0","aria-hidden":!0}):i.jsx(qr,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),_4(de.key)&&de.projectIcon?i.jsx(uo,{color:de.projectColor,icon:de.projectIcon,size:"xs",iconClassName:"h-3.5 w-3.5",testId:`messenger-thread-section-${oo(de.key)}-project-icon`}):null,gn?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-agent-avatar`,"aria-hidden":"true",className:"flex h-4 w-4 shrink-0 items-center justify-center overflow-hidden rounded-full border border-[color:color-mix(in_oklab,var(--border-soft)_86%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_78%,transparent)]",children:i.jsx(_g,{icon:gn==null?void 0:gn.icon,role:gn==null?void 0:gn.role,fallbackSeed:gn.id,className:"h-full w-full rounded-full"})}):null,i.jsx("span",{className:"min-w-0 flex-1 truncate",children:de.label}),Jn>0?i.jsx("span",{"data-testid":`messenger-thread-section-${oo(de.key)}-attention-count`,className:"shrink-0 rounded-full bg-[color:color-mix(in_oklab,var(--accent-info)_16%,transparent)] px-1.5 py-0.5 text-[10px] font-semibold text-[color:var(--accent-info)]",children:Jn}):null]})})():i.jsx("div",{"data-testid":`messenger-thread-section-${oo(de.key)}`,className:"px-3 pb-1 pt-2 text-[11px] font-semibold text-muted-foreground/72",children:de.label}):null,i.jsx("div",{"data-testid":_u?`messenger-thread-section-${oo(de.key)}`:fm,className:K("grid transition-[grid-template-rows,opacity,margin-top] duration-200 ease-out",Fr?"mt-0 grid-rows-[0fr] opacity-0":_u?"mt-0 grid-rows-[1fr] opacity-100":"mt-1 grid-rows-[1fr] opacity-100"),"aria-hidden":Fr?"true":void 0,inert:Fr?!0:void 0,children:i.jsx("div",{className:"min-h-0 overflow-hidden",children:Op})})]})},cA=de=>de.kind==="saved-view"?aA.includes(de.key)?i.jsx(Bne,{id:de.key,disabled:H.has(de.key),children:(He,wt)=>o1(de.savedView,He,wt)}):o1(de.savedView):aA.includes(de.key)?i.jsx(dIe,{id:de.key,children:(He,wt)=>Tu(de.section,He,wt)}):i.jsx("div",{className:"flex shrink-0 flex-col gap-1",children:Tu(de.section)}),t0=de=>de.kind==="saved-view"?o1(de.savedView):i.jsx("div",{className:"flex shrink-0 flex-col gap-1",children:Tu(de.section)}),Ic=async de=>{c.selectedOrganizationId&&(await Promise.all([Qf(k,c.selectedOrganizationId),k.invalidateQueries({queryKey:V.chats.list(c.selectedOrganizationId,"all")}),k.invalidateQueries({queryKey:V.chats.list(c.selectedOrganizationId,"active")})]),de&&await Promise.all([k.invalidateQueries({queryKey:V.chats.detail(c.selectedOrganizationId,de)}),k.invalidateQueries({queryKey:V.chats.messages(c.selectedOrganizationId,de)})]))},ch=xt({mutationFn:({chatId:de,data:He})=>Xn.update(de,He),onSuccess:async de=>{de.status==="archived"&&S.kind==="chat"&&S.conversationId===de.id&&n("/messenger"),re(He=>He===de.id?null:He),await Ic(de.id)},onError:async(de,He)=>{await Ic(He.chatId)}}),Fb=xt({mutationFn:({chatId:de,title:He})=>Xn.update(de,{title:He}),onMutate:async({chatId:de,title:He})=>{c.selectedOrganizationId&&(ce(wt=>({...wt,[de]:He})),await cqe(k,c.selectedOrganizationId),f4(k,c.selectedOrganizationId,de,He))},onSuccess:async de=>{c.selectedOrganizationId&&f4(k,c.selectedOrganizationId,de.id,de.title),await Ic(de.id),ce(He=>{if(!(de.id in He))return He;const wt={...He};return delete wt[de.id],wt})},onError:async(de,He)=>{await Ic(He.chatId),ce(wt=>{if(!(He.chatId in wt))return wt;const Dt={...wt};return delete Dt[He.chatId],Dt})}}),Nw=xt({mutationFn:async({chatId:de,generating:He})=>{He&&(g(de),await Xn.stopMessageStream(de).catch(()=>{}),v(de,null),y(de,!1));let wt=null;for(let Dt=0;Dt<=Fne.length;Dt+=1)try{return He?await Xn.remove(de,{cancelActive:!0}):await Xn.remove(de)}catch(en){if(wt=en,!(He&&en instanceof Nl&&en.status===409)||Dt>=Fne.length)throw en;await KQn(Fne[Dt])}throw wt},onSuccess:async de=>{S.kind==="chat"&&S.conversationId===de.id&&n("/messenger/chat"),await Ic(de.id)}}),dh=xt({mutationFn:({chatId:de,pinned:He,unread:wt})=>Xn.updateUserState(de,{pinned:He,unread:wt}),onSuccess:async de=>{await Ic(de.id)},onError:async(de,He)=>{await Ic(He.chatId)}}),ut=xt({mutationFn:de=>Xn.regenerateTitle(de),onMutate:de=>{Fe(He=>{const wt=new Set(He);return wt.add(de),wt})},onSuccess:async de=>{c.selectedOrganizationId&&f4(k,c.selectedOrganizationId,de.id,de.title)},onSettled:async(de,He,wt)=>{Fe(Dt=>{const en=new Set(Dt);return en.delete(wt),en}),await Ic(wt)}}),h8=xt({mutationFn:de=>Xn.fork(de,{}),onSuccess:async de=>{await Promise.all([Ic(de.id),c.selectedOrganizationId?k.invalidateQueries({queryKey:V.messenger.customGroups(c.selectedOrganizationId)}):Promise.resolve()]),n(`/messenger/chat/${de.id}`)},onError:async(de,He)=>{await Ic(He)}}),cm=xt({mutationFn:({threadKey:de,pinned:He})=>{if(!c.selectedOrganizationId)throw new Error("Organization is required to update Messenger thread state");return Ks.updateThreadUserState(c.selectedOrganizationId,de,{pinned:He})},onSuccess:async()=>{await Ic()},onError:async()=>{await Ic()}}),yf=()=>{const de=ne.trim();if(!se||!de){re(null);return}re(null),Fb.mutate({chatId:se,title:de})},n0=async de=>{try{await navigator.clipboard.writeText(XQn(de))}catch{}};return h.useEffect(()=>{if(!c.selectedOrganizationId||!Vr||S.kind==="chat"||!Gi||Gi.unreadCount===0&&!Gi.needsAttention||!bd)return;const de=c.selectedOrganizationId,He=lc??Gi.latestActivityAt??"none",wt=`${de}:${Vr}:${He}`;j.current!==wt&&(j.current=wt,lt(Dt=>{const en=Gi.latestActivityAt instanceof Date?Gi.latestActivityAt.toISOString():Gi.latestActivityAt??"none";if(Dt.get(Vr)===en)return Dt;const gn=new Map(Dt);return gn.set(Vr,en),gn}),_ie(k,de,Vr,lc),Ks.markThreadRead(de,Vr,lc?new Date(lc).toISOString():null).then(async()=>{await Qf(k,de),await k.invalidateQueries({queryKey:V.sidebarBadges(de)}),S.kind==="issues"&&await k.invalidateQueries({queryKey:V.messenger.issues(de)}),S.kind==="approvals"&&await k.invalidateQueries({queryKey:V.messenger.approvals(de)}),S.kind==="system"&&await k.invalidateQueries({queryKey:V.messenger.system(de,S.threadKind)})}).catch(()=>{j.current=null,lt(Dt=>{if(!Dt.has(Vr))return Dt;const en=new Map(Dt);return en.delete(Vr),en})}))},[Gi,bd,Vr,lc,c.selectedOrganizationId,k,S]),h.useEffect(()=>{if(typeof document>"u")return;const de=()=>{const wt=VPe();wt>0&&Je(wt)},He=VPe();return He>0&&Je(He),document.addEventListener(Ade,de),()=>{document.removeEventListener(Ade,de)}},[]),h.useEffect(()=>{_.current=null},[c.selectedOrganizationId,o,_e]),h.useEffect(()=>{mn.length>0||(_.current=null)},[mn.length]),h.useEffect(()=>{if(!Ci)return;const de={requestId:De,loadedCount:An.length},He=U.current;He&&He.requestId===de.requestId&&He.loadedCount===de.loadedCount||(U.current=de,c.loadMoreThreadSummaries())},[c.loadMoreThreadSummaries,Ci,De,An.length]),h.useEffect(()=>{De<=0||D.current!==De&&(Bn||Ci||c.isFetchingMoreThreadSummaries||c.isLoading||c.hasMoreThreadSummaries||mn.length>0||(D.current=De,Ine(De),U.current=null))},[c.hasMoreThreadSummaries,c.isFetchingMoreThreadSummaries,c.isLoading,Ci,De,Bn,mn.length]),h.useEffect(()=>{if(!Bn||De<=0||D.current===De)return;const de=Bn.sectionPath.filter(Sn=>Qe.has(Sn));if(de.length>0){gt(Sn=>{if(!de.some(Fr=>Sn.has(Fr)))return Sn;const pr=new Set(Sn);for(const Fr of de)pr.delete(Fr);return c.selectedOrganizationId&&i5(Ye)&&nIe(c.selectedOrganizationId,Ye,pr),pr});return}const He=Bn.sectionPath.map(Sn=>Mt.get(Sn)??null).find(Sn=>Sn==null?void 0:Sn.collapsed)??null;if(He){$.current.get(He.id)!==De&&($.current.set(He.id,De),Ni(He.id,!1));return}for(const Sn of Bn.sectionPath){const pr=Cd(Sn);pr&&$.current.delete(pr)}if(Bn.groupKey&&Bn.entryIndex!==null){const Sn=Bn.entryIndex+1,pr=Nt[Bn.groupKey]??Ik;if(Sn>pr){Gt(Fr=>({...Fr,[Bn.groupKey]:Sn}));return}}const wt=Bn.sectionPath[0]??null;if(wt){const Sn=Ao.findIndex(pr=>pr.key===wt);Sn!==-1&&ho.scrollToIndex(Sn,{align:"center"})}let Dt=!1,en=0,gn=0;const yn=()=>{if(Dt)return;const Sn=P.current;if(!Sn)return;const pr=Array.from(Sn.querySelectorAll("[data-messenger-thread-key]")).find(Fr=>Fr.dataset.messengerThreadKey===Bn.threadKey);if(pr==null||pr.scrollIntoView({block:"nearest",behavior:"smooth"}),pr){_.current=Bn.threadKey,D.current=De,Ine(De),U.current=null;return}gn+=1,gn<=12&&(en=requestAnimationFrame(yn))};return en=requestAnimationFrame(yn),()=>{Dt=!0,cancelAnimationFrame(en)}},[Qe,Mt,ho,Ye,c.selectedOrganizationId,Ao,De,Bn,Ni,Nt]),h.useEffect(()=>{const de=R.current,He=P.current;if(!de||!He||!c.hasMoreThreadSummaries||c.isFetchingMoreThreadSummaries||c.isLoading||typeof IntersectionObserver>"u")return;const wt=new IntersectionObserver(Dt=>{!Dt.some(gn=>gn.isIntersecting)||!c.hasMoreThreadSummaries||c.isFetchingMoreThreadSummaries||c.loadMoreThreadSummaries()},{root:He,rootMargin:"720px 0px 960px 0px"});return wt.observe(de),()=>wt.disconnect()},[c.hasMoreThreadSummaries,c.isFetchingMoreThreadSummaries,c.isLoading,c.loadMoreThreadSummaries,An.length]),c.selectedOrganizationId?i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(GQn,{title:"Messenger",description:Ye==="custom"?void 0:`Threads organized by ${nAt(Ye).toLowerCase()}`}),i.jsx(eUn,{rule:_e,density:Ce,splitIssueNotifications:o,onRuleChange:Pc,onDensityChange:eo,onSplitIssueNotificationsChange:$a}),i.jsxs(ts,{open:!!ke,onOpenChange:de=>{de||da()},children:[i.jsx(cQ,{virtualRef:M}),ke?i.jsx(ns,{ref:N,side:f?"bottom":"right",align:"center",sideOffset:8,collisionPadding:12,hideWhenDetached:!0,onInteractOutside:()=>{T.current=!1},onCloseAutoFocus:de=>{var He;de.preventDefault(),T.current&&((He=E.current)!=null&&He.isConnected)&&E.current.focus()},"aria-label":"Create Messenger group","data-testid":"messenger-custom-group-popover",className:"scrollbar-auto-hide surface-overlay z-[70] max-h-[min(34rem,var(--radix-popover-content-available-height))] w-[min(25rem,calc(100vw-2rem))] overflow-y-auto p-0 text-foreground",children:i.jsx(DBn,{name:fe,icon:Se,color:ft,pending:ca.isPending||wi.isPending,onNameChange:ve,onIconChange:ze,onColorChange:ie,onCancel:da,onSubmit:lA})}):null]}),xe?i.jsx(RBn,{name:xe.name,pending:wi.isPending,onNameChange:de=>ae(He=>He&&{...He,name:de}),onCancel:e0,onSubmit:Iu}):null,i.jsxs("nav",{ref:Vi,className:"scrollbar-auto-hide mt-2 flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto px-1.5 pb-3.5",children:[i.jsxs(sn,{to:"/messenger/chat",onClick:()=>Vo("/messenger/chat"),className:K("mx-0.5 flex items-center rounded-[calc(var(--radius-md)-2px)] border border-transparent text-sm transition-[background-color,border-color,color]",Ce==="compact"?"gap-2 px-2 py-1.5":"gap-3 px-3 py-2.5",S.kind==="chat"&&!S.conversationId?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))] font-medium text-foreground":"text-foreground/78 hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground"),children:[i.jsx("span",{className:K("flex shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)+1px)] border border-[color:color-mix(in_oklab,var(--border-soft)_88%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-active)_82%,transparent)] text-[color:var(--accent-strong)]",Ce==="compact"?"h-7 w-7":"h-10 w-10"),children:i.jsx(Zr,{className:K(Ce==="compact"?"h-3.5 w-3.5":"h-4.5 w-4.5")})}),i.jsx("span",{className:"truncate text-[13px] font-medium leading-tight",children:"New chat"})]}),c.isLoading&&An.length===0?i.jsx("div",{className:"space-y-1 px-1.5",children:Array.from({length:5}).map((de,He)=>i.jsx("div",{className:K("animate-pulse rounded-[calc(var(--radius-md)-2px)] border border-transparent bg-[color:color-mix(in_oklab,var(--surface-elevated)_60%,transparent)]",Ce==="compact"?"h-10":"h-[72px]")},He))}):null,i5(Ye)?i.jsx(i.Fragment,{children:i.jsxs(tC,{accessibility:tn,sensors:Vt,collisionDetection:WQn,measuring:ZQn,onDragStart:vt,onDragOver:xf,onDragCancel:pt,onDragEnd:lm,children:[i.jsx(l3,{items:aA,strategy:WP,children:s?i.jsx("div",{"data-testid":"messenger-directory-baseline",className:"flex flex-col gap-1",children:Ao.map(de=>i.jsx("div",{children:cA(de)},de.key))}):i.jsx("div",{ref:ho.containerRef,"data-testid":"messenger-virtual-directory",style:{position:"relative",width:"100%"},children:vs.map(de=>{const He=Ao[de.index];return He?i.jsx("div",{ref:ho.measureElement,"data-index":de.index,style:{left:0,position:"absolute",top:0,width:"100%"},children:cA(He)},He.key):null})})}),i.jsx(Eqe,{dropAnimation:null,children:Gn?i.jsx("div",{"data-testid":"messenger-drag-overlay",className:"surface-overlay max-w-[18rem] rounded-[var(--radius-md)] border border-[color:var(--border-strong)] px-3 py-2 text-sm font-medium text-foreground shadow-[var(--shadow-lg)]",children:i.jsx("span",{className:"block truncate",children:Gn})}):null})]})}):s?i.jsx("div",{"data-testid":"messenger-directory-baseline",className:"flex flex-col gap-1",children:Ao.map(de=>i.jsx("div",{children:t0(de)},de.key))}):i.jsx("div",{ref:ho.containerRef,"data-testid":"messenger-virtual-directory",style:{position:"relative",width:"100%"},children:vs.map(de=>{const He=Ao[de.index];return He?i.jsx("div",{ref:ho.measureElement,"data-index":de.index,style:{left:0,position:"absolute",top:0,width:"100%"},children:t0(He)},He.key):null})}),(um=(cc=Jt.data)==null?void 0:cc.pageInfo)!=null&&um.hasMore?i.jsx("div",{className:"flex min-h-9 items-center justify-center px-3 py-1",children:i.jsx("button",{type:"button","data-testid":"messenger-saved-view-page-load-more",className:"inline-flex h-7 items-center rounded-[calc(var(--radius-sm)-1px)] px-2 text-[11px] font-medium text-muted-foreground transition-[background-color,color] hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/25 disabled:cursor-not-allowed disabled:opacity-60",disabled:Jt.isFetching,onClick:vp,children:Jt.isFetching?"Loading Saved Views":"Load more Saved Views"})}):null,c.hasMoreThreadSummaries||c.isFetchingMoreThreadSummaries?i.jsx("div",{ref:R,"data-testid":"messenger-thread-page-sentinel",className:"flex min-h-10 items-center justify-center px-3 py-2 text-[12px] text-muted-foreground",children:c.isFetchingMoreThreadSummaries?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[i.jsx(hn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Loading more threads"]}):null}):null]}),i.jsx(eQn,{})]}):null}function nUn(e,t){return e==="assigned"&&t?{assigneeUserId:"me",includeAutomationExecutions:!0}:e==="reviewing"&&t?{reviewerUserId:"me",includeAutomationExecutions:!0}:e==="pinned"&&t?{followedByUserId:"me",includeAutomationExecutions:!0}:e==="following"&&t?{involvedUserId:"me",includeAutomationExecutions:!0}:{includeAutomationExecutions:!0}}function rUn(e,t){return t?e.createdByUserId===t||e.assigneeUserId===t||e.reviewerUserId===t:!1}const uIe=5,sAt="rudder.linear",sUn="linear-catalog",iUn="linear";function aUn(e){const t=e==null?void 0:e.find(r=>r.pluginKey===sAt);if(!t)return null;const n=t.slots.find(r=>r.type==="page");return n?{pluginId:t.pluginId,routePath:n.routePath||iUn}:null}function oUn(e){const t=new URLSearchParams;return t.set("source","linear"),e.kind==="team"?t.set("linearTeamId",e.id):(e.teamId&&t.set("linearTeamId",e.teamId),t.set("linearProjectId",e.id)),`/issues?${t.toString()}`}function Q1({children:e,action:t,testId:n,collapsed:r,onToggle:s}){const a=typeof r=="boolean"&&s;return i.jsxs("div",{"data-testid":n,className:"group flex items-center justify-between px-3.5 pt-3.5 text-[11px] font-medium tracking-normal text-muted-foreground/76",children:[i.jsx("span",{children:e}),t||a?i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t,a?i.jsx("button",{type:"button",onClick:s,"aria-label":`${r?"Expand":"Collapse"} ${e}`,title:r?"Expand":"Collapse","data-testid":n?`${n}-toggle`:void 0,className:K("inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/72 transition-[opacity,background-color,color]","hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] hover:text-foreground","opacity-100 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100",r&&"md:opacity-100"),children:r?i.jsx(bi,{className:"h-3.5 w-3.5"}):i.jsx(qr,{className:"h-3.5 w-3.5"})}):null]}):null]})}function DN({title:e,description:t,children:n}){const{isMobile:r,setSidebarOpen:s}=jc();return i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsx("div",{className:"min-w-0 flex-1",children:n??i.jsxs(i.Fragment,{children:[i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:e}),i.jsx("p",{className:"mt-0.5 truncate text-[12px] text-muted-foreground",children:t})]})}),r?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>s(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]})}function lUn(e){return/^\/issues(?:\/|$)/.test(e)||/^\/linear(?:\/|$)/.test(e)?{title:"Issues",description:"Views and project slices"}:/^\/chat(?:\/|$)/.test(e)?{title:"Chats",description:"Recent conversations"}:/^\/calendar(?:\/|$)/.test(e)?{title:"Calendar",description:"Sources and filters"}:/^\/(?:dashboard|org|projects|library|resources|workspaces|heartbeats|goals|skills|costs|activity)(?:\/|$)/.test(e)?{title:"Org",description:"Organization surfaces"}:{title:"Agents",description:""}}function fIe(e){return e==="planned"?"Planned":e==="in_progress"?"Running runs":e==="actual"?"Run history":e==="external"?"External calendar":e==="projected"?"Projected heartbeats":e==="cancelled"?"Cancelled":e}const u$=["border-blue-400 bg-blue-500","border-emerald-400 bg-emerald-500","border-amber-400 bg-amber-500","border-rose-400 bg-rose-500","border-cyan-400 bg-cyan-500","border-violet-400 bg-violet-500"],cUn=["M","T","W","T","F","S","S"];function iAt(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate(),0,0,0,0)}function aAt(e,t){const n=new Date(e);return n.setDate(n.getDate()+t),n}function tB(e){const t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function dUn(e){const t=new Date(e.getFullYear(),e.getMonth(),1),n=t.getDay();return iAt(aAt(t,n===0?-6:1-n))}function uUn(e){return new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric"}).format(e)}function fUn(e){return e>=8?"bg-emerald-700 text-white":e>=5?"bg-emerald-600 text-white":e>=3?"bg-emerald-500/80 text-white":e>=1?"bg-emerald-500/35 text-emerald-950 dark:text-emerald-50":""}function AIe(e,t,n){e(r=>{const s=new Set(r);return n?s.delete(t):s.add(t),s})}function AUn({cursor:e,setCursor:t,completedIssueCountByDay:n}){const r=dUn(e),s=Array.from({length:42},(l,c)=>aAt(r,c)),a=tB(new Date),o=tB(e);return i.jsxs("section",{className:"px-3.5 pt-3","data-testid":"calendar-mini-month",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("button",{type:"button",className:"inline-flex min-w-0 items-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] px-1.5 py-1 text-left text-sm font-medium text-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",onClick:()=>t(l=>new Date(l.getFullYear(),l.getMonth(),1)),children:[i.jsx(qr,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:uUn(e)})]}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{type:"button","aria-label":"Previous month",className:"inline-flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground",onClick:()=>t(l=>new Date(l.getFullYear(),l.getMonth()-1,1)),children:i.jsx(Tj,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","aria-label":"Next month",className:"inline-flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground",onClick:()=>t(l=>new Date(l.getFullYear(),l.getMonth()+1,1)),children:i.jsx(bi,{className:"h-4 w-4"})})]})]}),i.jsxs("div",{className:"mt-3 grid grid-cols-7 gap-y-1 text-center",children:[cUn.map((l,c)=>i.jsx("div",{className:"text-[10px] font-medium text-muted-foreground/72",children:l},`${l}-${c}`)),s.map(l=>{const c=tB(l),d=l.getMonth()!==e.getMonth(),u=c===o,f=c===a,A=n.get(c)??0,m=A>0&&!f&&!u;return i.jsx("button",{type:"button","aria-label":`${c}${A>0?`, ${A} completed agent issue${A===1?"":"s"}`:""}`,title:A>0?`${A} completed agent issue${A===1?"":"s"}`:void 0,className:K("mx-auto flex h-7 w-7 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-xs transition-[background-color,color,box-shadow]",d&&!f?"text-muted-foreground/45":"text-foreground/88",m&&fUn(A),f&&"bg-primary text-primary-foreground shadow-sm ring-2 ring-background",!f&&u&&"bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,var(--surface-active))] text-foreground ring-1 ring-primary/65",!f&&!u&&"hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)]"),onClick:()=>t(iAt(l)),children:l.getDate()},c)})]})]})}function hIe({label:e,visible:t,onToggle:n,icon:r,colorClass:s,agent:a}){const o=t?Px:J4;return i.jsxs("button",{type:"button","aria-pressed":t,"aria-label":`${t?"Hide":"Show"} ${e}`,onClick:n,className:K("group mx-1.5 flex min-h-9 w-[calc(100%-0.75rem)] items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-3 py-2 text-left text-sm transition-[background-color,color]","text-foreground/88 hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",!t&&"text-muted-foreground"),children:[a?i.jsx("span",{"data-testid":`calendar-agent-avatar-${a.id}`,className:K("inline-flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted ring-1 ring-border/80",!t&&"opacity-40 grayscale"),title:a.name,children:i.jsx(Il,{icon:a.icon,role:a.role,className:"h-full w-full"})}):s?i.jsx("span",{className:K("h-2.5 w-2.5 shrink-0 rounded-sm border",s,!t&&"opacity-35 grayscale")}):r?i.jsx(r,{className:K("h-3.5 w-3.5 shrink-0 text-muted-foreground",!t&&"opacity-45")}):null,i.jsx("span",{className:"min-w-0 flex-1 truncate",title:e,children:e}),i.jsx("span",{className:K("inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover:opacity-100 group-focus-visible:opacity-100",!t&&"text-muted-foreground/70"),children:i.jsx(o,{className:"h-3.5 w-3.5"})})]})}function hUn(e){const t=e.match(/\/(?:messenger\/chat|chat)\/([^/]+)\/?/);return(t==null?void 0:t[1])??null}function mIe({to:e,icon:t,label:n,active:r,slidingActiveIndicator:s=!1,testId:a}){return i.jsxs(sn,{to:e,"data-testid":a,className:K("relative z-10 mx-1.5 flex items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border border-transparent px-3 py-2 text-sm transition-[background-color,border-color,color]",s&&"min-h-[var(--motion-context-item-height)]",s?r?"font-medium text-foreground":"text-foreground/78 hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground":r?"border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_92%,var(--surface-active))] font-medium text-foreground":"text-foreground/78 hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground"),children:[i.jsx(t,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"truncate",children:n})]})}function mUn(e){return e>=0?{"--motion-context-active-index":e}:void 0}function u7({activeIndex:e,ariaLabel:t,className:n,scrollRef:r,indicatorTestId:s,testId:a,children:o}){return i.jsxs("nav",{ref:r,className:K("motion-context-nav",n),style:mUn(e),"data-active-index":e>=0?e:void 0,"data-testid":a,"aria-label":t,children:[e>=0?i.jsx("span",{"data-testid":s,className:"motion-context-active-indicator","aria-hidden":"true"}):null,o]})}function pIe({count:e}){return i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-1.5 pl-2",children:[i.jsxs("span",{className:"relative flex h-2 w-2",children:[i.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-blue-400 opacity-75"}),i.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-500"})]}),i.jsxs("span",{className:"text-[11px] font-medium text-blue-600 dark:text-blue-400",children:[e," live"]})]})}function pUn({visibleProjects:e,activeProjectRef:t,closeMobileSidebar:n,onNewProject:r,scrollRef:s}){const a=e.findIndex(o=>t===S3(o));return i.jsxs(i.Fragment,{children:[i.jsx(Q1,{testId:"workspace-projects-section",action:i.jsx("button",{type:"button",onClick:r,"aria-label":"New project",title:"Create project",className:K("inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/72 transition-[opacity,background-color,color]","hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] hover:text-foreground","opacity-100 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100"),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})}),children:"Projects"}),i.jsx(u7,{activeIndex:a,ariaLabel:"Projects",className:"motion-context-nav--project-card-list scrollbar-auto-hide mt-2 min-h-0 flex-1 overflow-y-auto pb-3.5",scrollRef:s,indicatorTestId:"project-sidebar-active-indicator",testId:"workspace-projects-scroll",children:e.map(o=>{const l=S3(o),c=t===l;return i.jsxs(sn,{to:`/projects/${l}/configuration`,onClick:n,className:K("relative z-10 mx-1.5 min-h-[var(--motion-context-item-height)] rounded-[calc(var(--radius-sm)-1px)] px-3.5 py-2.5 transition-colors",c?"font-medium text-foreground":"text-foreground/88 hover:bg-[color:color-mix(in_oklab,var(--surface-active)_54%,transparent)]"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(uo,{color:o.color,icon:o.icon,size:"sm",testId:`workspace-project-color-${o.id}`}),i.jsx("span",{className:"truncate text-sm font-medium text-foreground",children:o.name})]}),i.jsx("div",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:o.description||"Project"})]},o.id)})})]})}function gIe({issues:e,activeIssueRef:t,closeMobileSidebar:n,onOpenIssue:r,collapsed:s,onToggleCollapsed:a,sectionLabel:o,ariaLabel:l,sectionTestId:c,listTestId:d,rowTestIdPrefix:u,toggleTestId:f,scrollActivityKey:A,followedIssueIds:m,pinningIssueId:g,issuePinDisabled:x,onToggleIssuePin:y}){const[v,w]=h.useState(!1),k=bs(A);if(e.length===0)return null;const S=v?e.length:uIe,j=e.slice(0,S);return i.jsxs("section",{"aria-label":l,className:"mt-1",children:[i.jsx(Q1,{testId:c,collapsed:s,onToggle:a,children:o}),s?null:i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:v?k:void 0,"data-testid":d,className:K("mt-2 space-y-0.5",v&&"scrollbar-auto-hide max-h-72 overflow-y-auto pr-1"),children:j.map(C=>{const N=C.identifier??C.id,P=t===N||t===C.id,M=m.has(C.id),E=M?"Unpin issue":"Pin issue",T=M?lw:Jh,R=g===C.id;return i.jsxs("div",{"data-testid":`${u}-${C.id}`,"aria-current":P?"page":void 0,className:K("group/issue-sidebar-row relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center rounded-[calc(var(--radius-sm)-1px)] border border-transparent text-sm transition-[background-color,border-color,color]",P?"border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_92%,var(--surface-active))] font-medium text-foreground":"text-muted-foreground hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),children:[i.jsxs(sn,{to:eE(C),onClick:()=>{r==null||r(C),n()},"aria-current":P?"page":void 0,className:"flex min-w-0 flex-1 items-center gap-2.5 self-stretch px-3 py-2 pr-9 text-inherit",children:[i.jsx("span",{className:"flex h-5 w-4 shrink-0 items-center justify-center",children:i.jsx(ni,{status:C.status})}),i.jsxs("span",{className:"flex min-h-5 min-w-0 flex-1 items-center gap-1.5",children:[i.jsx("span",{className:"shrink-0 font-mono text-[11px] leading-5 text-muted-foreground/78",children:N}),i.jsx("span",{className:"shrink-0 leading-5 text-muted-foreground/55",children:"·"}),i.jsx("span",{className:"min-w-0 truncate leading-5",children:C.title})]})]}),i.jsx("button",{type:"button","data-testid":`${u}-${C.id}-pin-toggle`,"aria-label":`${E} ${N}`,title:E,disabled:x||R,className:K("absolute right-1.5 top-1/2 z-10 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-md p-1 opacity-100 transition-[opacity,background-color,color] duration-150","hover:bg-[color:var(--surface-page)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--ring)] disabled:pointer-events-none disabled:opacity-35","md:opacity-0 md:group-hover/issue-sidebar-row:opacity-100 md:group-focus-within/issue-sidebar-row:opacity-100",M?"text-[color:var(--accent-strong)] hover:text-[color:var(--accent-strong)]":"text-muted-foreground hover:text-foreground"),onClick:_=>{_.preventDefault(),_.stopPropagation(),y(C)},children:i.jsx(T,{className:"h-3.5 w-3.5",strokeWidth:2.25})})]},C.id)})}),e.length>uIe?i.jsxs("button",{type:"button",onClick:()=>w(C=>!C),"data-testid":f,className:"mx-1.5 mt-1 flex min-h-8 w-[calc(100%-0.75rem)] items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-3 py-1.5 text-left text-xs font-medium text-muted-foreground transition-colors hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground",children:[v?i.jsx(BK,{className:"h-3.5 w-3.5"}):i.jsx(qr,{className:"h-3.5 w-3.5"}),i.jsx("span",{children:v?"Show less":"Show all"})]}):null]})]})}function gUn(){var We,Tt,Mn,tr,Ln;const e=br(),t=Yr(),n=fl(e.pathname),r=h.useMemo(()=>new URLSearchParams(e.search),[e.search]),s=h.useMemo(()=>lUn(n),[n]),a=/^\/messenger(?:\/|$)/.test(n),o=/^\/apps(?:\/|$)/.test(n),l=/^\/(?:dashboard\/calendar|calendar)(?:\/|$)/.test(n),c=/^\/linear(?:\/|$)/.test(n),d=/^\/issues(?:\/|$)/.test(n)||c,u=/^\/(?:dashboard|org|projects|library|resources|heartbeats|workspaces|goals|skills|costs|activity)(?:\/|$)/.test(n),f=/^\/chat(?:\/|$)/.test(n),A=!o&&!a&&!d&&!l&&!u&&!f,{selectedOrganizationId:m}=jr(),{isMobile:g,setSidebarOpen:x}=jc(),{pushToast:y}=ss(),{openNewAgent:v,openNewProject:w}=ii(),k=Vn(),[S,j]=h.useState({}),[C,N]=h.useState(null),P=h.useCallback(pt=>S[pt]===!0,[S]),M=h.useCallback(pt=>{j(vt=>({...vt,[pt]:!vt[pt]}))},[]),E=bs("rudder:sidebar-scroll:calendar"),T=bs("rudder:sidebar-scroll:issues"),R=bs("rudder:sidebar-scroll:workspace-projects"),_=bs("rudder:sidebar-scroll:chat"),D=bs("rudder:sidebar-scroll:agents"),{cursor:U,setCursor:$,hiddenAgentIds:L,setHiddenAgentIds:H,hiddenSourceIds:X,setHiddenSourceIds:F,myCalendarVisible:Q,setMyCalendarVisible:q,visibleStatuses:B,setVisibleStatuses:ee,setGoogleCalendarModalOpen:se}=qqe(),{data:re}=Me({queryKey:V.auth.session,queryFn:()=>dl.getSession()}),{data:ne}=Me({queryKey:V.projects.list(m??"__none__"),queryFn:()=>Mi.list(m),enabled:!!m}),{data:Ae}=Me({queryKey:V.agents.list(m??"__none__"),queryFn:()=>Nn.list(m),enabled:!!m}),{data:Y}=Me({queryKey:V.chats.listPreview(m??"__none__","active",40),queryFn:()=>Xn.list(m,"active",{limit:40}),enabled:!!m}),{data:ce}=Me({queryKey:V.calendar.sources(m??"__none__"),queryFn:()=>su.sources(m),enabled:!!m&&l}),Oe=xt({mutationFn:({sourceId:pt,status:vt})=>su.updateSource(m,pt,{status:vt}),onSuccess:async()=>{m&&await Promise.all([k.invalidateQueries({queryKey:V.calendar.sources(m)}),k.invalidateQueries({queryKey:["calendar",m]})])},onError:pt=>{y({title:"Failed to update calendar source",body:pt instanceof Error?pt.message:void 0,tone:"error"})}}),{data:Fe}=Me({queryKey:V.liveRuns(m??"__none__"),queryFn:()=>zo.liveRunsForCompany(m),enabled:!!m&&(A||d),refetchInterval:1e4}),{data:ke}=Me({queryKey:V.issues.listPreview(m??"__none__",80),queryFn:()=>lr.list(m,{limit:80}),enabled:!!m&&d}),{follows:Ne,followedIssueIds:xe,isLoading:ae,toggleFollowIssue:fe}=Z0e(m&&d?m:null),{data:ve}=Me({queryKey:V.plugins.uiContributions,queryFn:()=>bo.listUiContributions(),enabled:!!m&&d}),{data:Se}=Me({queryKey:["calendar",m??"__none__","completed-issue-heatmap"],queryFn:()=>lr.list(m,{status:"done"}),enabled:!!m&&l}),ze=((We=re==null?void 0:re.user)==null?void 0:We.id)??((Tt=re==null?void 0:re.session)==null?void 0:Tt.userId)??null,ft=new URLSearchParams(e.search).get("scope")??"",ie=ft==="recent"?"":ft,me=new URLSearchParams(e.search).get("source")??"",we=new URLSearchParams(e.search).get("projectId")??"",Xe=new URLSearchParams(e.search).get("linearProjectId")??"",ge=new URLSearchParams(e.search).get("linearTeamId")??"",te=hUn(e.pathname),G=((Mn=e.pathname.match(/\/agents\/([^/]+)/))==null?void 0:Mn[1])??null,oe=((tr=e.pathname.match(/\/projects\/([^/]+)/))==null?void 0:tr[1])??null,Ze=((Ln=e.pathname.match(/\/issues\/([^/]+)/))==null?void 0:Ln[1])??null,Te=h.useMemo(()=>(ne??[]).filter(pt=>!pt.archivedAt),[ne]),Be=h.useMemo(()=>aUn(ve),[ve]),{data:it}=Me({queryKey:["plugins",sAt,"catalog",m??"__none__",(Be==null?void 0:Be.pluginId)??"__none__"],queryFn:async()=>(await bo.bridgeGetData(Be.pluginId,sUn,{orgId:m},m)).data,enabled:!!m&&!!(Be!=null&&Be.pluginId)&&d}),lt=h.useMemo(()=>{const pt=[...(it==null?void 0:it.projects)??[]].sort((kr,xs)=>kr.name.localeCompare(xs.name)),vt=[...(it==null?void 0:it.teams)??[]].sort((kr,xs)=>kr.name.localeCompare(xs.name));if(vt.length===0)return pt.map(kr=>({...kr,kind:"project"}));const jt=[],Zt=new Set;for(const kr of vt){jt.push({...kr,kind:"team"});for(const xs of pt)(xs.teamIds??[]).includes(kr.id)&&(Zt.add(xs.id),jt.push({id:xs.id,name:xs.name,kind:"project",teamId:kr.id}))}for(const kr of pt)Zt.has(kr.id)||jt.push({...kr,kind:"project"});return jt},[it==null?void 0:it.projects,it==null?void 0:it.teams]),Ue=h.useMemo(()=>(Ae??[]).filter(pt=>pt.status!=="terminated").sort((pt,vt)=>pt.name.localeCompare(vt.name)),[Ae]),mt=h.useMemo(()=>{const pt=new Map;for(const vt of Fe??[])pt.set(vt.agentId,(pt.get(vt.agentId)??0)+1);return pt},[Fe]),tt=h.useMemo(()=>{const pt=new Map;for(const jt of ke??[])jt.projectId&&pt.set(jt.id,jt.projectId);const vt=new Map;for(const jt of Fe??[]){if(!jt.issueId)continue;const Zt=pt.get(jt.issueId);Zt&&vt.set(Zt,(vt.get(Zt)??0)+1)}return vt},[ke,Fe]),[dt,at]=h.useState(null),[Pe,$e]=h.useState(""),[ot,ue]=h.useState(!0),[Ie,Ke]=h.useState(()=>aq(m)),[De,Je]=h.useState(()=>j7(m)),_e=h.useMemo(()=>DLn(De,ke??[]),[ke,De]),Ee=h.useMemo(()=>{const pt=new Map((ke??[]).map(vt=>[vt.id,vt]));return Ne.map(vt=>pt.get(vt.issueId)??vt.issue)},[ke,Ne]),Ce=h.useMemo(()=>ze?(ke??[]).filter(pt=>rUn(pt,ze)).length:0,[ke,ze]),kt=[{key:"all",to:"/issues",icon:sE,label:"All Issues",active:me!=="linear"&&ie===""&&!we},...Ie.length>0?[{key:"drafts",to:"/issues?scope=drafts",icon:xg,label:`Draft Issues (${Ie.length})`,active:ie==="drafts",testId:"issue-draft-sidebar-entry"}]:[],{key:"following",to:`/issues${ze?"?scope=following":""}`,icon:C3,label:`Following${Ce>0?` (${Ce})`:""}`,active:ie==="following"}],Qe=kt.findIndex(pt=>pt.active),gt=Te.findIndex(pt=>{const vt=S3(pt);return we===pt.id||oe===vt}),Nt=[{key:"dashboard",to:"/dashboard",icon:yx,label:"Dashboard",active:/^\/dashboard(?:\/|$)/.test(n)},{key:"heartbeats",to:"/heartbeats",icon:Cx,label:"Heartbeats",active:/^\/heartbeats(?:\/|$)/.test(n)},{key:"goals",to:"/goals",icon:ud,label:"Goals",active:/^\/goals(?:\/|$)/.test(n)},{key:"skills",to:MAe,icon:wc,label:"Skills",active:/^\/skills(?:\/|$)/.test(n)||/^\/library(?:\/|$)/.test(n)&&(r.get("directory")==="skills"||r.has("skill"))},{key:"costs",to:"/costs",icon:Nx,label:"Costs",active:/^\/costs(?:\/|$)/.test(n)},{key:"activity",to:"/activity",icon:lT,label:"Activity",active:/^\/activity(?:\/|$)/.test(n)}],Gt=Nt.findIndex(pt=>pt.active),cn=Ue.findIndex(pt=>G===pt.urlKey||G===pt.id),Rn=(ce??[]).filter(pt=>pt.type==="google_calendar").sort((pt,vt)=>{const jt=(pt.externalCalendarId==="primary"?0:1)-(vt.externalCalendarId==="primary"?0:1);return jt!==0?jt:pt.name.localeCompare(vt.name)}),nt=Rn.filter(pt=>pt.status==="active"),Qt=Rn.some(pt=>pt.status==="active"&&!X.has(pt.id)),st=h.useMemo(()=>{const pt=new Map;for(const vt of Se??[]){if(!vt.completedAt||!vt.assigneeAgentId)continue;const jt=tB(vt.completedAt);pt.set(jt,(pt.get(jt)??0)+1)}return pt},[Se]);h.useEffect(()=>{Je(j7(m))},[e.key,m]),h.useEffect(()=>{if(typeof window>"u")return;const pt=()=>{Je(j7(m))};return window.addEventListener(Jce,pt),window.addEventListener("storage",pt),()=>{window.removeEventListener(Jce,pt),window.removeEventListener("storage",pt)}},[m]),h.useEffect(()=>{const pt=()=>{Ke(aq(m))};if(pt(),!(typeof window>"u"))return window.addEventListener(V_,pt),window.addEventListener("storage",pt),()=>{window.removeEventListener(V_,pt),window.removeEventListener("storage",pt)}},[m]);const Rt=()=>{g&&x(!1)},Cn=pt=>{m&&Je(X0e(m,pt.id,j7(m)))},zn=h.useCallback(async pt=>{if(C||ae)return;const vt=!xe.has(pt.id);N(pt.id);try{await fe(pt.id),y({title:vt?"Issue pinned":"Issue unpinned",tone:"success"})}catch(jt){y({title:vt?"Could not pin issue":"Could not unpin issue",body:jt instanceof Error?jt.message:void 0,tone:"error"})}finally{N(null)}},[xe,ae,C,y,fe]),fs=async pt=>{m&&(await k.invalidateQueries({queryKey:V.chats.list(m,"active")}),pt&&(await k.invalidateQueries({queryKey:V.chats.detail(m,pt)}),await k.invalidateQueries({queryKey:V.chats.messages(m,pt)})))},as=xt({mutationFn:({chatId:pt,data:vt})=>Xn.update(pt,vt),onSuccess:async pt=>{pt.status==="archived"&&pt.id===te&&t("/messenger"),at(vt=>vt===pt.id?null:vt),await fs(pt.id)},onError:pt=>{y({title:"Failed to update chat",body:pt instanceof Error?pt.message:void 0,tone:"error"})}}),sr=xt({mutationFn:({chatId:pt,pinned:vt})=>Xn.updateUserState(pt,{pinned:vt}),onSuccess:async pt=>{await fs(pt.id)},onError:pt=>{y({title:"Failed to update chat state",body:pt instanceof Error?pt.message:void 0,tone:"error"})}}),Kr=()=>{const pt=Pe.trim();if(!dt||!pt){at(null);return}as.mutate({chatId:dt,data:{title:pt}})},yr=async pt=>{try{await navigator.clipboard.writeText(pt),y({title:"Chat ID copied",tone:"success"})}catch{y({title:"Could not copy chat ID",tone:"error"})}},ht=()=>{const pt=!Qt,vt=pt?Rn:nt;F(jt=>{const Zt=new Set(jt);for(const kr of vt)pt?Zt.delete(kr.id):Zt.add(kr.id);return Zt});for(const jt of vt)Oe.mutate({sourceId:jt.id,status:pt?"active":"paused"})},Vt=pt=>{const vt=!(pt.status==="active"&&!X.has(pt.id));AIe(F,pt.id,vt),Oe.mutate({sourceId:pt.id,status:vt?"active":"paused"})};if(o)return i.jsx(PBn,{});if(a)return i.jsx(tUn,{});if(l)return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description,children:i.jsx(Uut,{compact:!0,className:"w-full"})}),i.jsxs("div",{ref:E,className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto pb-3.5",children:[i.jsx(AUn,{cursor:U,setCursor:$,completedIssueCountByDay:st}),i.jsx(Q1,{action:i.jsx("button",{type:"button","aria-label":"Import Google Calendar",className:"inline-flex h-6 w-6 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100",onClick:()=>se(!0),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})}),children:"Calendars"}),i.jsxs("div",{className:"mt-2 space-y-0.5",children:[i.jsx(hIe,{label:"My Calendar",visible:Q,onToggle:()=>q(pt=>!pt),icon:C3}),i.jsxs("div",{className:"group mx-1.5 flex min-h-9 items-center gap-1 rounded-[calc(var(--radius-sm)-1px)] px-1.5 py-1 text-sm text-foreground/88 transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",children:[i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground hover:bg-[color:var(--surface-page)] hover:text-foreground","aria-label":ot?"Collapse Google Calendar calendars":"Expand Google Calendar calendars",onClick:()=>ue(pt=>!pt),children:ot?i.jsx(qr,{className:"h-3.5 w-3.5"}):i.jsx(bi,{className:"h-3.5 w-3.5"})}),i.jsxs("button",{type:"button","data-testid":"calendar-google-row",className:"flex min-w-0 flex-1 items-center gap-2 rounded-[calc(var(--radius-sm)-2px)] px-1.5 py-1 text-left",onClick:()=>se(!0),children:[i.jsx(rE,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Google Calendar"})]}),i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100 disabled:cursor-not-allowed disabled:opacity-30","aria-label":`${Qt?"Hide":"Show"} Google Calendar`,disabled:Rn.length===0||Oe.isPending,onClick:ht,children:Qt?i.jsx(Px,{className:"h-3.5 w-3.5"}):i.jsx(J4,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100","aria-label":"Google Calendar settings",onClick:()=>se(!0),children:i.jsx(XK,{className:"h-3.5 w-3.5"})})]}),ot&&Rn.length>0?i.jsx("div",{className:"ml-9 mr-2 space-y-0.5","data-testid":"calendar-google-source-list",children:Rn.map((pt,vt)=>{const jt=pt.status==="active"&&!X.has(pt.id),Zt=jt?Px:J4;return i.jsxs("button",{type:"button","data-testid":`calendar-google-source-row-${pt.id}`,disabled:Oe.isPending,"aria-label":`${jt?"Disable":"Enable"} ${pt.name}`,className:K("group/source flex min-h-7 w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1 text-left text-xs text-foreground/82 hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] disabled:cursor-not-allowed disabled:opacity-60",!jt&&"text-muted-foreground"),onClick:()=>Vt(pt),children:[i.jsx("span",{className:K("h-2 w-2 shrink-0 rounded-sm border",u$[vt%u$.length],!jt&&"opacity-35 grayscale")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:pt.name,children:pt.name}),pt.status!=="active"?i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:"Off"}):null,i.jsx("span",{className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground opacity-0 transition-[opacity,background-color,color] hover:bg-[color:var(--surface-page)] hover:text-foreground group-hover/source:opacity-100 group-focus-visible/source:opacity-100",children:i.jsx(Zt,{className:"h-3 w-3"})})]},pt.id)})}):null]}),i.jsx(Q1,{children:"Agents"}),i.jsx("div",{className:"mt-2 space-y-0.5",children:Ue.map((pt,vt)=>i.jsx(hIe,{label:V7(pt),visible:!L.has(pt.id),onToggle:()=>AIe(H,pt.id,L.has(pt.id)),colorClass:u$[vt%u$.length],agent:pt},pt.id))}),i.jsx(Q1,{children:"Timeline"}),i.jsx("div",{className:"mt-2 space-y-0.5","data-testid":"calendar-status-filters",children:VKt.map(pt=>i.jsxs("label",{className:"mx-1.5 flex min-h-8 items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-3 py-1.5 text-sm text-foreground/88 hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",children:[i.jsx(hc,{checked:B.has(pt),onCheckedChange:vt=>{ee(jt=>{const Zt=new Set(jt);return vt===!0?Zt.add(pt):Zt.delete(pt),Zt})},"aria-label":`Show ${fIe(pt)} events`}),i.jsx("span",{className:"truncate",children:fIe(pt)})]},pt))})]})]});if(d)return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsx(Q1,{collapsed:P("issues"),onToggle:()=>M("issues"),children:"Issues"}),P("issues")?null:i.jsx(u7,{activeIndex:Qe,ariaLabel:"Issue navigation",className:"mt-2",indicatorTestId:"issue-sidebar-active-indicator",children:kt.map(pt=>i.jsx(mIe,{to:pt.to,icon:pt.icon,label:pt.label,active:pt.active,testId:pt.testId,slidingActiveIndicator:!0},pt.key))}),i.jsxs("div",{ref:T,"data-testid":"issue-sidebar-scroll",className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto pb-3.5",children:[i.jsx(gIe,{issues:Ee,activeIssueRef:Ze,closeMobileSidebar:Rt,collapsed:P("pinned"),onToggleCollapsed:()=>M("pinned"),sectionLabel:`Pinned (${Ee.length})`,ariaLabel:"Pinned issues",sectionTestId:"issue-pinned-section",listTestId:"issue-pinned-list",rowTestIdPrefix:"issue-pinned-row",toggleTestId:"issue-pinned-toggle",scrollActivityKey:"rudder:sidebar-scroll:pinned-issues",followedIssueIds:xe,pinningIssueId:C,issuePinDisabled:ae,onToggleIssuePin:pt=>void zn(pt)}),i.jsx(gIe,{issues:_e,activeIssueRef:Ze,closeMobileSidebar:Rt,onOpenIssue:Cn,collapsed:P("recent"),onToggleCollapsed:()=>M("recent"),sectionLabel:`Recently Viewed (${_e.length})`,ariaLabel:"Recently viewed issues",sectionTestId:"issue-recent-section",listTestId:"issue-recent-list",rowTestIdPrefix:"issue-recent-row",toggleTestId:"issue-recent-toggle",scrollActivityKey:"rudder:sidebar-scroll:recent-issues",followedIssueIds:xe,pinningIssueId:C,issuePinDisabled:ae,onToggleIssuePin:pt=>void zn(pt)}),i.jsx(Q1,{testId:"workspace-projects-section",collapsed:P("projects"),onToggle:()=>M("projects"),children:"Projects"}),P("projects")?null:i.jsx(u7,{activeIndex:gt,ariaLabel:"Issue project slices",className:"mt-2",indicatorTestId:"issue-project-sidebar-active-indicator",children:Te.map(pt=>{const vt=S3(pt),jt=we===pt.id||oe===vt,Zt=tt.get(pt.id)??0;return i.jsxs(sn,{to:`/issues?projectId=${pt.id}`,onClick:Rt,"data-testid":`issue-project-row-${pt.id}`,className:K("relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border border-transparent px-3 py-2 text-sm transition-[background-color,border-color,color]",jt?"font-medium text-foreground":"text-muted-foreground hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),children:[i.jsx(uo,{color:pt.color,icon:pt.icon,size:"xs",testId:`issue-project-color-${pt.id}`}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:pt.name}),Zt>0?i.jsx(pIe,{count:Zt}):null]},pt.id)})}),lt.length>0?i.jsxs(i.Fragment,{children:[i.jsx(Q1,{testId:"issue-linear-section",collapsed:P("linear"),onToggle:()=>M("linear"),children:"Linear"}),P("linear")?null:i.jsx(u7,{activeIndex:-1,ariaLabel:"Linear issue source slices",className:"mt-2",children:lt.map(pt=>{const vt=pt.kind==="project"?Xe===pt.id&&(!pt.teamId||ge===pt.teamId):me==="linear"&&ge===pt.id&&!Xe;return i.jsxs(sn,{to:oUn(pt),onClick:Rt,"data-testid":`issue-linear-${pt.kind}-${pt.id}`,"aria-current":vt?"page":void 0,className:K("relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border border-transparent px-3 py-2 text-sm transition-[background-color,border-color,color]",pt.kind==="project"&&pt.teamId?"ml-6 min-h-8 py-1.5 text-xs":"",vt?"border-[color:color-mix(in_oklab,var(--border-soft)_72%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_92%,var(--surface-active))] font-medium text-foreground":"text-muted-foreground hover:border-[color:color-mix(in_oklab,var(--border-soft)_52%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),children:[i.jsx("span",{className:"h-2.5 w-2.5 shrink-0 rounded-[calc(var(--radius-sm)-4px)] border border-[color:color-mix(in_oklab,var(--muted-foreground)_54%,transparent)] bg-[color:color-mix(in_oklab,var(--muted-foreground)_18%,transparent)]"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:pt.name})]},`${pt.kind}-${pt.id}`)})})]}):null]})]});if(u)return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsx(Q1,{children:"Org"}),i.jsx(u7,{activeIndex:Gt,ariaLabel:"Organization surfaces",className:"mt-2",indicatorTestId:"org-sidebar-active-indicator",children:Nt.map(pt=>i.jsx(mIe,{to:pt.to,icon:pt.icon,label:pt.label,active:pt.active,slidingActiveIndicator:!0},pt.key))}),i.jsx(pUn,{visibleProjects:Te,activeProjectRef:oe,closeMobileSidebar:Rt,onNewProject:w,scrollRef:R})]})]});if(f){if(!te&&((Y==null?void 0:Y.length)??0)===0)return null;const pt=(Y??[]).filter(jt=>jt.isPinned),vt=(Y??[]).filter(jt=>!jt.isPinned);return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar chat-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsxs("nav",{ref:_,"data-testid":"chat-sidebar-scroll",className:"scrollbar-auto-hide flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto px-1.5 py-2.5",children:[i.jsxs(sn,{to:"/messenger/chat",onClick:Rt,className:K("flex items-center gap-3 rounded-[calc(var(--radius-sm)-1px)] border px-3 py-2.5 text-sm transition-[background-color,border-color,color]",te?"border-transparent text-foreground/88 hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)] hover:text-foreground":"surface-active border-[color:var(--border-strong)] text-[color:var(--accent-strong)]"),children:[i.jsx(pa,{className:"h-4 w-4 shrink-0"}),i.jsx("div",{className:"truncate font-medium",children:"New Chat"})]}),pt.length>0?i.jsx("div",{className:"px-2 pb-1 pt-2 text-[10px] font-semibold tracking-[0.08em] text-muted-foreground/72",children:"Pinned"}):null,pt.map(jt=>i.jsx(Tie,{date:jt.lastMessageAt??jt.updatedAt,children:i.jsx("div",{"data-testid":`chat-sidebar-conversation-${jt.id}`,className:K("group relative rounded-[calc(var(--radius-sm)-1px)] border px-3 py-1.5 transition-[background-color,border-color,color]",te===jt.id?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_86%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]"),children:dt===jt.id?i.jsx("input",{autoFocus:!0,value:Pe,onChange:Zt=>$e(Zt.target.value),onBlur:Kr,onKeyDown:Zt=>{Zt.key==="Enter"&&(Zt.preventDefault(),Kr()),Zt.key==="Escape"&&(Zt.preventDefault(),at(null))},className:"min-h-0 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-elevated)] px-3 py-2 text-sm outline-none"}):i.jsxs(i.Fragment,{children:[i.jsx(sn,{to:`/messenger/chat/${jt.id}`,onClick:Rt,className:"block min-w-0 pr-12",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium leading-tight text-foreground",children:[i.jsx("span",{className:"truncate",children:o6(jt)}),jt.isUnread?i.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 rounded-full bg-red-500","aria-label":"Unread chat"}):null]})}),i.jsx("span",{className:"whitespace-nowrap text-[11px] tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",children:Bi(jt.lastMessageAt??jt.updatedAt)})]})}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Chat actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay text-foreground",children:[Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{at(jt.id),$e(jt.title)},children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename"]}),i.jsxs(Xt,{onClick:()=>{sr.mutate({chatId:jt.id,pinned:!1})},children:[i.jsx(lw,{className:"h-4 w-4"}),"Unpin"]}),i.jsxs(Xt,{onClick:()=>void yr(jt.id),children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy chat ID"]}),Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{as.mutate({chatId:jt.id,data:{status:"archived"}})},children:[i.jsx(G4,{className:"h-4 w-4"}),"Archive"]})]})]})]})})},jt.id)),vt.length>0?i.jsx("div",{className:"px-2 pb-1 pt-2 text-[10px] font-semibold tracking-[0.08em] text-muted-foreground/72",children:"Recent"}):null,vt.map(jt=>i.jsx(Tie,{date:jt.lastMessageAt??jt.updatedAt,children:i.jsx("div",{"data-testid":`chat-sidebar-conversation-${jt.id}`,className:K("group relative rounded-[calc(var(--radius-sm)-1px)] border px-3 py-1.5 transition-[background-color,border-color,color]",te===jt.id?"chat-conversation-active border-[color:var(--border-strong)] bg-[color:color-mix(in_oklab,var(--surface-active)_86%,var(--surface-elevated))]":"border-transparent hover:border-[color:color-mix(in_oklab,var(--border-soft)_70%,transparent)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_62%,transparent)]"),children:dt===jt.id?i.jsx("input",{autoFocus:!0,value:Pe,onChange:Zt=>$e(Zt.target.value),onBlur:Kr,onKeyDown:Zt=>{Zt.key==="Enter"&&(Zt.preventDefault(),Kr()),Zt.key==="Escape"&&(Zt.preventDefault(),at(null))},className:"min-h-0 w-full rounded-[calc(var(--radius-sm)-1px)] border border-[color:var(--border-base)] bg-[color:var(--surface-elevated)] px-3 py-2 text-sm outline-none"}):i.jsxs(i.Fragment,{children:[i.jsx(sn,{to:`/messenger/chat/${jt.id}`,onClick:Rt,className:"block min-w-0 pr-12",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium leading-tight text-foreground",children:[i.jsx("span",{className:"truncate",children:o6(jt)}),jt.isUnread?i.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 rounded-full bg-red-500","aria-label":"Unread chat"}):null]})}),i.jsx("span",{className:"whitespace-nowrap text-[11px] tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",children:Bi(jt.lastMessageAt??jt.updatedAt)})]})}),i.jsxs(Ei,{children:[i.jsx(Di,{asChild:!0,children:i.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-page)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Chat actions",children:i.jsx(hl,{className:"h-3.5 w-3.5"})})}),i.jsxs(Ri,{align:"end",className:"surface-overlay text-foreground",children:[Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{at(jt.id),$e(jt.title)},children:[i.jsx(xg,{className:"h-4 w-4"}),"Rename"]}),i.jsxs(Xt,{onClick:()=>{sr.mutate({chatId:jt.id,pinned:!0})},children:[i.jsx(Jh,{className:"h-4 w-4"}),"Pin"]}),i.jsxs(Xt,{onClick:()=>void yr(jt.id),children:[i.jsx(Al,{className:"h-4 w-4"}),"Copy chat ID"]}),Dv(jt)?null:i.jsxs(Xt,{onClick:()=>{as.mutate({chatId:jt.id,data:{status:"archived"}})},children:[i.jsx(G4,{className:"h-4 w-4"}),"Archive"]})]})]})]})})},jt.id))]})]})}return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsx(DN,{title:s.title,description:s.description}),i.jsx(Q1,{testId:"agents-team-section",action:i.jsx("div",{className:"flex items-center",children:i.jsx("button",{type:"button",onClick:v,"aria-label":"New agent",className:K("inline-flex h-5 w-5 items-center justify-center rounded-[calc(var(--radius-sm)-2px)] text-muted-foreground/72 transition-[opacity,background-color,color]","hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_82%,transparent)] hover:text-foreground","opacity-100 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100"),children:i.jsx(Zr,{className:"h-3.5 w-3.5"})})}),children:"Team"}),i.jsx(u7,{activeIndex:cn,ariaLabel:"Agent team",className:"motion-context-nav--agent-list scrollbar-auto-hide mt-2 min-h-0 flex-1 overflow-y-auto pb-3.5",scrollRef:D,indicatorTestId:"agent-sidebar-active-indicator",testId:"agent-sidebar-scroll",children:Ue.map(pt=>{const vt=mt.get(pt.id)??0,jt=G===pt.urlKey||G===pt.id,Zt=rqe(pt);return i.jsxs("div",{"data-testid":`agent-sidebar-row-${pt.id}`,className:K("group/agent-sidebar-row relative z-10 mx-1.5 flex min-h-[var(--motion-context-item-height)] items-center rounded-[calc(var(--radius-sm)-1px)] text-sm transition-colors",jt?"font-medium text-foreground":"text-foreground/80 hover:bg-[color:color-mix(in_oklab,var(--surface-active)_54%,transparent)]"),children:[i.jsxs(sn,{to:BA(pt),onClick:Rt,className:"flex min-w-0 flex-1 items-center gap-3 self-stretch py-2.5 pl-3.5 pr-1 no-underline text-inherit",children:[i.jsx(Il,{icon:pt.icon,role:pt.role,className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"flex-1 truncate",title:V7(pt),children:V7(pt)}),Zt?i.jsx("span",{title:`Agent status: ${Zt}`,className:K("ml-auto inline-flex h-5 shrink-0 items-center rounded-[calc(var(--radius-sm)-1px)] border px-1.5 text-[10px] font-medium leading-none whitespace-nowrap",wE[Zt]??kE),children:Zt}):null,vt>0?i.jsx(pIe,{count:vt}):null]}),i.jsx(bBn,{agent:pt,orgId:m??pt.orgId,triggerTestId:`agent-sidebar-actions-${pt.id}`,triggerClassName:"mr-2 h-6 w-6",visibilityClassName:"opacity-100 md:opacity-0 md:group-hover/agent-sidebar-row:opacity-100 md:group-focus-within/agent-sidebar-row:opacity-100",onActionComplete:Rt})]},pt.id)})})]})}function xUn(e){const t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length-1;r+=1)n.push(t.slice(0,r+1).join("/"));return new Set(n)}function bUn(e){return e?new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(new Date(e)):"Running"}function yUn(e){return`${e} ${e===1?"file":"files"}`}function xIe(e){return(e==null?void 0:e.status)==="succeeded"||(e==null?void 0:e.status)==="restored"}function vUn(e){return e.status==="running"?"Backup still running.":e.status==="failed"?e.error?`Backup failed: ${e.error}`:"Backup failed before writing files.":"Backup files are not available."}function wUn(e,t,n){const r=new URLSearchParams(e);r.set("file",n),t(r,{replace:!0})}function kUn({orgId:e,backupId:t,directoryPath:n,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o}){const{data:l}=Me({queryKey:V.organizations.workspaceBackupFiles(e,t,n),queryFn:()=>_n.listWorkspaceBackupFiles(e,t,n),enabled:!!e&&!!t,refetchOnWindowFocus:!1}),c=(l==null?void 0:l.entries)??[];return c.length===0?null:i.jsx("ul",{className:"space-y-0.5",children:c.map(d=>i.jsx(oAt,{orgId:e,backupId:t,entry:d,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o},d.path))})}function oAt({orgId:e,backupId:t,entry:n,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o=0}){const[l,c]=h.useState(a.has(n.path));if(h.useEffect(()=>{a.has(n.path)&&c(!0)},[n.path,a]),n.isDirectory)return i.jsxs("li",{children:[i.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-left text-sm text-foreground/88 transition-colors hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)]",style:{paddingLeft:`${o*14+8}px`},onClick:()=>c(u=>!u),"aria-expanded":l,children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground",children:l?i.jsx(qr,{className:"h-4 w-4"}):i.jsx(bi,{className:"h-4 w-4"})}),i.jsx(wo,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:n.name})]}),l?i.jsx(kUn,{orgId:e,backupId:t,directoryPath:n.path,selectedFilePath:r,onSelectFile:s,expandedDirectories:a,depth:o+1}):null]});const d=r===n.path;return i.jsx("li",{children:i.jsxs("button",{type:"button",className:K("flex w-full items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] px-2 py-1.5 text-left text-sm transition-colors",d?"bg-[color:color-mix(in_oklab,var(--surface-active)_90%,var(--surface-elevated))] text-foreground":"text-muted-foreground hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_58%,transparent)] hover:text-foreground"),style:{paddingLeft:`${o*14+23}px`},onClick:()=>s(n.path),children:[i.jsx(K6,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:n.name})]})})}function OUn(){var m,g,x,y;const{isMobile:e,setSidebarOpen:t}=jc(),{viewedOrganizationId:n}=th(),[r,s]=gd(),a=r.get("backup"),o=r.get("file"),l=Me({queryKey:V.organizations.workspaceBackups(n??"__none__"),queryFn:()=>_n.listWorkspaceBackups(n),enabled:!!n,refetchOnWindowFocus:!1}),c=((m=l.data)==null?void 0:m.backups)??[],d=c.find(v=>v.id===a)??c.find(xIe)??c[0]??null,u=xIe(d),f=Me({queryKey:V.organizations.workspaceBackupFiles(n??"__none__",(d==null?void 0:d.id)??"__none__",""),queryFn:()=>_n.listWorkspaceBackupFiles(n,d.id,""),enabled:!!n&&!!d&&u,refetchOnWindowFocus:!1}),A=h.useMemo(()=>o?xUn(o):new Set,[o]);return i.jsxs("aside",{"data-testid":"workspace-sidebar",className:"workspace-context-sidebar flex min-h-0 w-full min-w-0 shrink-0 flex-col",children:[i.jsxs("header",{"data-testid":"workspace-context-header",className:"workspace-card-header workspace-context-header desktop-chrome flex shrink-0 items-center justify-between gap-3 px-4 py-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("h2",{className:"truncate text-[14px] font-semibold tracking-[-0.01em] text-foreground",children:"Files"}),i.jsx("p",{className:"mt-0.5 truncate text-[12px] text-muted-foreground",children:d?`${yUn(d.fileCount)} · ${bUn(d.finishedAt??d.createdAt)}`:"Select a backup version"})]}),e?null:i.jsx("button",{type:"button","aria-label":"Collapse workspace sidebar",title:"Collapse workspace sidebar",className:"desktop-window-no-drag inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] text-muted-foreground transition-[background-color,color] hover:bg-[color:color-mix(in_oklab,var(--surface-elevated)_68%,transparent)] hover:text-foreground",onClick:()=>t(!1),children:i.jsx(ow,{className:"h-4 w-4"})})]}),i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-auto px-1.5 py-2",children:l.isLoading?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Loading backups..."}):l.error?i.jsx("div",{className:"px-2 py-3 text-sm text-destructive",children:l.error.message}):d?u?f.isLoading?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Loading files..."}):f.error?i.jsx("div",{className:"px-2 py-3 text-sm text-destructive",children:f.error.message}):((g=f.data)==null?void 0:g.entries.length)===0?i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:((x=f.data)==null?void 0:x.message)??"This backup is empty."}):i.jsx("ul",{className:"space-y-0.5",children:(((y=f.data)==null?void 0:y.entries)??[]).map(v=>i.jsx(oAt,{orgId:n,backupId:d.id,entry:v,selectedFilePath:o,onSelectFile:w=>wUn(r,s,w),expandedDirectories:A},v.path))}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:vUn(d)}):i.jsx("div",{className:"px-2 py-3 text-sm text-muted-foreground",children:"No workspace backups yet."})})]})}function f$(e){var r;if(typeof document>"u")return null;const t=document.querySelector(`meta[name="${e}"]`),n=(r=t==null?void 0:t.getAttribute("content"))==null?void 0:r.trim();return n||null}function kde(e){if(!e)return null;const t=e.startsWith("#")?e.slice(1):e;return/^[0-9a-fA-F]{3}$/.test(t)?`#${t.split("").map(n=>`${n}${n}`).join("").toLowerCase()}`:/^[0-9a-fA-F]{6}$/.test(t)?`#${t.toLowerCase()}`:null}function SUn(e){const t=kde(e)??"#000000";return{r:Number.parseInt(t.slice(1,3),16),g:Number.parseInt(t.slice(3,5),16),b:Number.parseInt(t.slice(5,7),16)}}function Qne(e){const t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function jUn(e){const{r:t,g:n,b:r}=SUn(e),s=.2126*Qne(t)+.7152*Qne(n)+.0722*Qne(r),a=1.05/(s+.05),o=(s+.05)/.05;return a>=o?"#f8fafc":"#111827"}function CUn(){if(f$("rudder-worktree-enabled")!=="true")return null;const e=f$("rudder-worktree-name"),t=kde(f$("rudder-worktree-color"));return!e||!t?null:{enabled:!0,name:e,color:t,textColor:kde(f$("rudder-worktree-text-color"))??jUn(t)}}function NUn(){const e=CUn();return e?i.jsx("div",{className:"relative overflow-hidden border-b px-3 py-1.5 text-[11px] font-medium tracking-[0.2em] uppercase",style:{backgroundColor:e.color,color:e.textColor,borderColor:`${e.textColor}22`,boxShadow:`inset 0 -1px 0 ${e.textColor}18`,backgroundImage:`linear-gradient(90deg, ${e.textColor}14, transparent 28%, transparent 72%, ${e.textColor}12), repeating-linear-gradient(135deg, transparent 0 10px, ${e.textColor}08 10px 20px)`},children:i.jsxs("div",{className:"flex items-center gap-2 overflow-hidden whitespace-nowrap",children:[i.jsx("span",{className:"shrink-0 opacity-70",children:"Worktree"}),i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-70","aria-hidden":"true"}),i.jsx("span",{className:"truncate font-semibold tracking-[0.12em]",children:e.name})]})}):null}function PUn({onMove:e,onStop:t,pointerId:n,resizeHandle:r}){let s=!0;const a=document.body.style.cursor,o=document.body.style.userSelect,l=()=>{if(s){if(s=!1,window.removeEventListener("pointermove",e),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l),window.removeEventListener("mousemove",e),window.removeEventListener("mouseup",l),window.removeEventListener("blur",l),r.removeEventListener("lostpointercapture",c),n!==null)try{r.hasPointerCapture(n)&&r.releasePointerCapture(n)}catch{}document.body.style.cursor=a,document.body.style.userSelect=o,t()}},c=d=>{(n===null||d.pointerId===n)&&l()};if(document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("pointermove",e),window.addEventListener("pointerup",l,{once:!0}),window.addEventListener("pointercancel",l,{once:!0}),window.addEventListener("mousemove",e),window.addEventListener("mouseup",l,{once:!0}),window.addEventListener("blur",l,{once:!0}),r.addEventListener("lostpointercapture",c),n!==null)try{r.setPointerCapture(n)}catch{}return{isActive:()=>s,stop:l}}const lAt="rudder.lastInstanceSettingsPath",cAt="rudder.lastWorkspacePath",dAt="rudder.workspace.contextWidth",nB="rudder.workspace.sidePanelWidth.v2",rB=420,N2e=340,Ode=292,IUn=N2e-Ode,P2e=4,TUn=10,uAt={apps:268,chat:318,messenger:332,issues:248,calendar:268,projects:268,agents:268,org:248,backups:332},fAt={apps:{min:236,max:360},chat:{min:280,max:420},messenger:{min:280,max:420},issues:{min:220,max:340,maxViewportFraction:1/3},calendar:{min:236,max:360},projects:{min:236,max:360},agents:{min:236,max:360},org:{min:220,max:340},backups:{min:280,max:420}};function bIe(e,t="authenticated"){const n=lWt();if(typeof window>"u")return n;try{return oKe(window.localStorage.getItem(lAt),e,t)}catch{return n}}function _Un(){if(typeof window>"u")return Qc;try{const e=window.localStorage.getItem(cAt);if(!e)return Qc;const t=fl(e);return t.startsWith("/instance/")||t.startsWith("/organization/settings")||EK(t)?Qc:t}catch{return Qc}}function MUn(e){return`${e.pathname}${e.search}${e.hash}`}function EUn(){var t;if(typeof window>"u")return!1;const e=(t=window.history.state)==null?void 0:t.idx;return typeof e=="number"&&e>0}function AAt({children:e,onClose:t}){const{t:n}=is(),{isMobile:r}=jc(),s=br(),[a,o]=h.useState(!1),l=bs("workspace-main:settings-modal"),c=h.useRef(null),d=h.useRef(null),u=h.useRef(null),f=h.useRef(null),A=h.useRef(typeof document<"u"&&document.activeElement instanceof HTMLElement?document.activeElement:null),m=h.useCallback(()=>{const g=Array.from(document.querySelectorAll('[data-settings-trigger="true"]')).find(v=>v.getClientRects().length>0&&!v.closest("[inert]")),x=A.current,y=x&&x!==document.body&&x!==document.documentElement&&x.isConnected&&!x.closest("[inert]")?x:g;y==null||y.focus({preventScroll:!0})},[]);return h.useEffect(()=>{const g=new Map,x=window.requestAnimationFrame(()=>{const y=u.current,v=f.current;if(!y||!v)return;let w=v;for(;w.parentElement;){for(const k of Array.from(w.parentElement.children))!(k instanceof HTMLElement)||g.has(k)||k===w||k===y||k.contains(v)||k.contains(y)||(g.set(k,{inert:k.inert,ariaHidden:k.getAttribute("aria-hidden")}),k.inert=!0,k.setAttribute("aria-hidden","true"));if(w=w.parentElement,w===document.body)break}});return()=>{window.cancelAnimationFrame(x);for(const[y,v]of g)y.inert=v.inert,v.ariaHidden===null?y.removeAttribute("aria-hidden"):y.setAttribute("aria-hidden",v.ariaHidden)}},[]),h.useEffect(()=>{r&&o(!1)},[r,s.pathname]),h.useEffect(()=>{var g,x;r&&(a?(g=c.current)==null||g.focus():(x=d.current)==null||x.focus())},[r,a]),i.jsx(_M,{open:!0,onOpenChange:g=>{g||t()},children:i.jsxs(MM,{children:[i.jsx(EM,{ref:u,"data-testid":"settings-modal-backdrop",className:"settings-modal-backdrop fixed inset-0 z-50"}),i.jsxs(mj,{"data-testid":"settings-modal-shell",ref:f,"aria-describedby":void 0,tabIndex:-1,className:"settings-modal-shell fixed left-1/2 top-1/2 z-50 flex min-h-0 w-[calc(100%-1rem)] max-w-[1440px] -translate-x-1/2 -translate-y-1/2 overflow-hidden rounded-[10px] sm:w-[calc(100%-2rem)]",onOpenAutoFocus:g=>{var x;r&&(g.preventDefault(),(x=d.current)==null||x.focus({preventScroll:!0}))},onCloseAutoFocus:g=>{g.preventDefault(),m()},onEscapeKeyDown:g=>{!r||!a||(g.preventDefault(),o(!1))},children:[i.jsx(DM,{className:"sr-only",children:n("common.systemSettings")}),r&&a?i.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 z-10 bg-foreground/10 backdrop-blur-[1px]",onClick:()=>o(!1)}):null,i.jsxs("div",{id:"settings-modal-navigation","data-testid":"settings-modal-navigation","aria-hidden":r&&!a,inert:r&&!a?!0:void 0,className:K("z-20 flex h-full min-h-0 shrink-0",r?"absolute inset-y-0 left-0 transition-transform duration-200 ease-out motion-reduce:transition-none":"relative",r&&!a&&"pointer-events-none -translate-x-full"),onClickCapture:g=>{r&&g.target.closest("a")&&o(!1)},children:[r&&a?i.jsx(le,{ref:c,variant:"ghost",size:"icon-sm",className:"absolute right-1 top-1 z-10 size-8 rounded-full text-muted-foreground",onClick:()=>o(!1),"aria-label":`${n("common.closeSidebar")} (${n("common.systemSettings")})`,title:n("common.closeSidebar"),children:i.jsx(Is,{className:"h-4 w-4"})}):null,i.jsx(mde,{showBackButton:!1,variant:"modal"})]}),i.jsxs("section",{className:"settings-modal-main flex min-h-0 min-w-0 flex-1 flex-col",inert:r&&a?!0:void 0,children:[i.jsxs("div",{className:"flex h-14 shrink-0 items-center justify-between px-3 sm:px-5",children:[r?i.jsx(le,{ref:d,variant:"ghost",size:"icon-sm",className:"size-8 rounded-full text-muted-foreground",onClick:()=>o(!0),"aria-expanded":a,"aria-controls":"settings-modal-navigation","aria-label":n("common.openSidebar"),title:n("common.openSidebar"),children:i.jsx(ow,{className:"h-4 w-4"})}):i.jsx("span",{}),i.jsx(le,{variant:"ghost",size:"icon-sm",className:"size-8 rounded-full text-muted-foreground",onClick:t,"aria-label":n("common.closeSettings"),title:n("common.closeSettings"),children:i.jsx(Is,{className:"h-4 w-4"})})]}),i.jsx("main",{id:"main-content",tabIndex:-1,ref:l,className:"scrollbar-auto-hide min-w-0 flex-1 overflow-auto",children:e})]})]})]})})}function DUn(){return typeof window>"u"||!("desktopShell"in window)||!window.desktopShell?!1:/Mac/i.test(window.navigator.userAgent)}function RUn(e){return/^\/apps(?:\/|$)/.test(e)?"apps":/^\/workspaces\/backups(?:\/|$)/.test(e)?"backups":/^\/chat(?:\/|$)/.test(e)?"chat":/^\/messenger(?:\/|$)/.test(e)?"messenger":/^\/issues(?:\/|$)/.test(e)?"issues":/^\/(?:dashboard\/calendar|calendar)(?:\/|$)/.test(e)?"calendar":/^\/projects(?:\/|$)/.test(e)?"org":/^\/agents(?:\/|$)/.test(e)?"agents":/^\/(?:dashboard|org|library|resources|heartbeats|workspaces|goals|skills|costs|activity)(?:\/|$)/.test(e)?"org":null}function LUn(e){return/^\/apps(?:\/|$)/.test(e)||/^\/(?:library|resources|workspaces)(?:\/|$)/.test(e)&&!/^\/workspaces\/backups(?:\/|$)/.test(e)||/^\/automations(?:\/|$)/.test(e)||/^\/chat(?:\/|$)/.test(e)||/^\/messenger\/chat(?:\/|$)/.test(e)||/^\/messenger\/(?:workbench|saved)(?:\/|$)/.test(e)?!0:e==="/messenger"}function A$(e){try{return decodeURIComponent(e)}catch{return e}}function zUn(e){var n,r;const t=((r=(n=e.split("?")[0])==null?void 0:n.split("#")[0])==null?void 0:r.split("/").filter(Boolean))??[];return t[0]==="messenger"&&t[1]==="chat"&&t[2]?`chat:${A$(t[2])}`:t[0]==="messenger"&&t[1]==="issues"&&t[2]?`issue:${A$(t[2])}`:t[0]==="chat"&&t[1]?`chat:${A$(t[1])}`:t[0]==="agents"&&t[1]&&t[2]==="runs"?`agent-runs:${A$(t[1])}`:null}function $Un(e,t){return zUn(e)??(t?`organization:${t}:global`:"global")}function FUn(e,t,n){var o;const r=$Un(e,t),s=/^\/messenger\/(?:workbench(?:\/|$)|saved\/[^/]+(?:\/|$))/.test(((o=e.split("?")[0])==null?void 0:o.split("#")[0])??e),a=(n==null?void 0:n.contextKey.startsWith("chat:"))||(n==null?void 0:n.contextKey.startsWith("issue:"));return(s||r===(n==null?void 0:n.contextKey))&&a&&(n==null?void 0:n.organizationId)===t?{contextKey:n.contextKey,preserveHold:!0}:{contextKey:r,preserveHold:!1}}function X_(){return typeof window>"u"?null:window.innerWidth}function BUn(){const[e,t]=h.useState(X_);return h.useEffect(()=>{if(typeof window>"u")return;const n=()=>t(X_());return n(),window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),e}function QUn(e,t=X_()){const{max:n,maxViewportFraction:r}=fAt[e];return!r||t===null||!Number.isFinite(t)?n:Math.max(n,Math.floor(t*r))}function fq(e,t,n=X_()){const{min:r}=fAt[e],s=QUn(e,n);return Math.min(s,Math.max(r,Math.round(t)))}function yIe(e){const t=uAt[e];if(typeof window>"u")return t;try{const n=window.localStorage.getItem(`${dAt}.${e}`),r=n?Number.parseInt(n,10):Number.NaN;return Number.isFinite(r)?fq(e,r):t}catch{return t}}function I2e(e){const t=Math.max(0,e-P2e),n=t*(2/3);return{availableWidth:t,dockedMinWidth:Math.min(N2e,t/2),dockedMaxWidth:n}}function Aq(e,t=null){const n=Math.round(e);if(t===null||!Number.isFinite(t))return Math.max(N2e,n);const r=I2e(t);return Math.min(r.dockedMaxWidth,Math.max(r.dockedMinWidth,n))}function UUn(e,t,n){return fq(e,t*n,n)}function VUn(e,t){return Aq(e*t,t)}function Une(e){return Aq((e-P2e)/2,e)}function qUn(e,t){const{availableWidth:n}=I2e(t),r=n-e;return e>2*r}function KUn(e){if(e===null||!Number.isFinite(e))return Ode;const{dockedMinWidth:t}=I2e(e);return Math.max(0,Math.min(Ode,t-IUn))}function WUn(e,t,n,r){const s=Number.isFinite(n)&&Number.isFinite(r)&&n>0&&r>0?n/r:1;return e-t/s}function B5(e,t=X_()){return t===null||!Number.isFinite(t)||t<=0?null:e/t}function ZUn(e){return Math.round(e)}function HUn(){if(typeof window>"u")return rB;try{const e=window.localStorage.getItem(nB),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)?ZUn(t):rB}catch{return rB}}function XUn({contextReady:e,expanded:t,onExpandedChange:n,selectedOrganizationId:r}){const s=Ob(),a=h.useRef(null),[o,l]=h.useState(null),c=h.useRef(typeof window<"u"&&window.localStorage.getItem(nB)!==null),d=h.useRef(c.current),[u,f]=h.useState(!c.current),[A,m]=h.useState(HUn),g=h.useRef(null),[x,y]=h.useState(!1),v=h.useRef(s.open),w=h.useRef(!1),k=h.useRef(!1),S=h.useRef(null);h.useEffect(()=>{if(!(typeof window>"u"||!d.current))try{window.localStorage.setItem(nB,String(A))}catch{}},[A]),h.useLayoutEffect(()=>{var $;const _=($=a.current)==null?void 0:$.parentElement;if(!_)return;const D=()=>l(_.offsetWidth);D();const U=new ResizeObserver(D);return U.observe(_),()=>U.disconnect()},[]),h.useEffect(()=>{if(c.current||o===null)return;const _=Une(o);g.current=B5(_,o),m(_)},[o]),h.useLayoutEffect(()=>{const _=v.current;if(v.current=s.open,!_&&s.open){const U=window.requestAnimationFrame(()=>{var $;($=document.querySelector("[data-testid='chat-side-panel-collapse']"))==null||$.focus()});return()=>window.cancelAnimationFrame(U)}if(!_||s.open||!w.current)return;w.current=!1;const D=window.requestAnimationFrame(()=>{var L;const U=document.querySelector("[data-testid='chat-side-panel-trigger']"),$=document.querySelector("[data-testid='global-side-panel-trigger']");(L=U??$)==null||L.focus()});return()=>window.cancelAnimationFrame(D)},[s.open]),h.useEffect(()=>{if(o===null||u)return;const _=g.current;if(_===null){const D=Aq(A,o);g.current=B5(D,o),m(D);return}m(VUn(_,o))},[u,o]);const j=h.useCallback(_=>{const D=Aq(_,o);return g.current=o===null?null:B5(D,o),m(D),D},[o]),C=h.useCallback(()=>{f(!0),c.current=!1,d.current=!1;try{window.localStorage.removeItem(nB)}catch{}const _=o===null?rB:Une(o);return j(_)},[j,o]),N=u&&o!==null?Une(o):A;h.useEffect(()=>()=>{var _;(_=S.current)==null||_.call(S)},[]);const P=h.useCallback(_=>{var Ae,Y;if(!s.open||k.current)return;_.preventDefault(),k.current=!0,f(!1),c.current=!0,d.current=!0;const D=_.clientX,U=_.currentTarget,$=(Ae=a.current)==null?void 0:Ae.parentElement,L=((Y=$==null?void 0:$.querySelector("[data-testid='chat-side-panel']"))==null?void 0:Y.offsetWidth)??null,H=($==null?void 0:$.offsetWidth)??o,X=($==null?void 0:$.getBoundingClientRect().width)??H,F=KUn(H),Q=L!==null&&L>0?L:N,q="pointerId"in _?_.pointerId:null;let B=Q,ee=!1;j(Q),y(!0);let se=()=>{};const ne=PUn({resizeHandle:U,pointerId:q,onMove:ce=>{const Oe=ce.clientX-D;if(B=WUn(Q,Oe,X??H??0,H??0),H!==null&&qUn(B,H)){se(),n(!0);return}if(B<=F){ee=!0,se(),s.hidePanel(),C();return}j(B)},onStop:()=>{S.current=null,k.current=!1,y(!1),!ee&&B<=F&&(s.hidePanel(),C())}});se=ne.stop,S.current=ne.isActive()?se:null},[N,n,C,j,s,o]),M=e&&s.open,E=e&&s.open&&t,T=M?E?o??N:N:0,R=M&&!E;return i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:a,className:"hidden","aria-hidden":"true"}),M?null:i.jsx("div",{className:"group absolute inset-y-1 right-0 z-20 w-1","data-testid":"side-panel-hover-edge",children:i.jsx(le,{type:"button",variant:"outline",size:"icon","data-testid":"global-side-panel-trigger",className:"pointer-events-none absolute right-[3px] top-1/2 h-11 w-7 -translate-y-1/2 rounded-l-[calc(var(--radius-sm)-1px)] rounded-r-none border-r-0 bg-[color:var(--surface-elevated)] text-muted-foreground opacity-0 shadow-[var(--shadow-sm)] transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100 hover:bg-[color:var(--surface-active)] hover:text-foreground",onClick:s.showPanel,"aria-label":"Open Side Panel",title:"Open Side Panel",children:i.jsx(dT,{className:"h-4 w-4"})})},"trigger"),i.jsxs("div",{"data-testid":"side-panel-resizer","aria-hidden":!R,className:K("motion-resize workspace-column-resizer group relative z-20 flex shrink-0 touch-none select-none items-stretch justify-center",R?"cursor-col-resize opacity-100":"pointer-events-none opacity-0",x&&"is-resizing"),style:{width:R?P2e:0},onPointerDown:P,onMouseDown:P,role:R?"separator":void 0,"aria-orientation":"vertical","aria-label":R?"Resize Side Panel":void 0,children:[i.jsx("span",{"data-testid":"side-panel-resizer-hit-target",className:"absolute inset-y-0 left-1/2 -translate-x-1/2",style:{width:TUn},"aria-hidden":"true"}),i.jsx("div",{className:"workspace-column-resizer-line"})]},"resizer"),x?i.jsx("div",{"data-testid":"side-panel-resize-shield",className:"fixed inset-0 z-[200] cursor-col-resize","aria-hidden":"true"}):null,i.jsx("div",{className:K("motion-resize relative flex min-h-0 shrink-0 overflow-hidden",E&&"z-30",x&&"transition-none"),"data-testid":E?"side-panel-expanded-overlay":"side-panel-stable-host","data-side-panel-state":E?"expanded":M?"docked":"closed",style:{width:T},"aria-hidden":!M,inert:M?void 0:!0,onFocusCapture:()=>{w.current=!0},onBlurCapture:_=>{s.open&&!_.currentTarget.contains(_.relatedTarget)&&(w.current=!1)},children:i.jsx(Iut,{contextReady:e,selectedOrganizationId:r,expanded:E,onClose:()=>{t&&(n(!1),C()),s.hidePanel()},onToggleExpanded:()=>{t?(n(!1),C()):n(!0)}})},"panel")]})}function GUn({contextKey:e,preserveHold:t}){const{clearDisplayedContextHold:n,setContextKey:r}=Ob();return h.useLayoutEffect(()=>{t||n(),r(e)},[n,e,t,r]),null}function YUn({onOpen:e}){return i.jsx("div",{"data-testid":"workspace-sidebar-reopen-zone",className:"group absolute left-0 top-0 z-30 flex w-8 items-start",children:i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx(le,{type:"button",variant:"outline",size:"icon","data-testid":"workspace-sidebar-reopen-button",className:"desktop-window-no-drag pointer-events-none h-10 w-7 shrink-0 -translate-x-1/2 rounded-l-none rounded-r-[calc(var(--radius-sm)-1px)] border-l-0 bg-[color:var(--surface-elevated)] text-muted-foreground opacity-0 shadow-[var(--shadow-sm)] transition-[background-color,color,opacity,transform] duration-[var(--motion-duration-fast)] ease-[var(--motion-ease-standard)] group-hover:pointer-events-auto group-hover:translate-x-0 group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:translate-x-0 group-focus-within:opacity-100 hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none",onClick:e,"aria-label":"Open workspace sidebar",title:"Open workspace sidebar",children:i.jsx(ow,{className:"h-4 w-4","aria-hidden":"true"})})}),i.jsx(ia,{side:"right",children:"Open workspace sidebar"})]})})}function vIe(){const{t:e}=is(),t=Vn(),{sidebarOpen:n,setSidebarOpen:r,toggleSidebar:s,isMobile:a}=jc(),{openNewIssue:o,openOnboarding:l,onboardingOpen:c,productTourOpen:d,openProductTour:u}=ii(),{togglePanelVisible:f}=MW(),{contextKey:A,displayedContextHold:m,open:g}=Ob(),{organizations:x,loading:y,selectedOrganization:v,selectedOrganizationId:w,selectionSource:k,setSelectedOrganizationId:S}=jr(),{pushToast:j}=ss(),{orgPrefix:C}=Uo(),N=Yr(),P=br(),M=B7t(),E=h.useRef([]),T=h.useMemo(()=>DUn(),[]),R=P.pathname.startsWith("/instance/"),_=h.useMemo(()=>fl(P.pathname),[P.pathname]),D=h.useMemo(()=>`${_}${P.search}${P.hash}`,[P.hash,P.search,_]),U=h.useMemo(()=>RUn(_),[_]),$=h.useMemo(()=>!/^\/apps\/saved\/[^/]+(?:\/|$)/.test(_)&&/^\/(?:apps|chat|messenger|issues|calendar|dashboard|agents|projects|org|library|resources|heartbeats|workspaces|goals|skills|costs|activity)(?:\/|$)/.test(_),[_]),L=h.useMemo(()=>/^\/workspaces\/backups(?:\/|$)/.test(_),[_]),H=h.useMemo(()=>/^\/(?:library|resources|workspaces)(?:\/|$)/.test(_)&&!/^\/workspaces\/backups(?:\/|$)/.test(_),[_]),X=h.useMemo(()=>/^\/chat(?:\/|$)/.test(_),[_]);h.useMemo(()=>/^\/messenger(?:\/|$)/.test(_),[_]);const F=h.useMemo(()=>LUn(_),[_]),Q=h.useMemo(()=>/^\/projects(?:\/|$)/.test(_),[_]),q=h.useMemo(()=>/\/chat\/[^/]+/.test(_),[_]),B=h.useMemo(()=>/^\/organization\/settings(?:\/|$)/.test(_),[_]),ee=h.useMemo(()=>Zj(P.state),[P.state]),se=h.useMemo(()=>wW(P),[P]),re=R||B,ne=h.useRef(!1),Ae=h.useRef(!1),Y=h.useRef(0),ce=BUn(),[Oe,Fe]=h.useState(!0),[ke,Ne]=h.useState(()=>U?yIe(U):uAt.issues),xe=h.useRef(B5(ke)),[ae,fe]=h.useState(!1),[ve,Se]=h.useState(!1),ze=bs(`workspace-main:${_}`),{data:ft}=Me({queryKey:V.access.currentBoardAccess,queryFn:()=>bc.getCurrentBoardAccess(),retry:!1}),ie=(ft==null?void 0:ft.isInstanceAdmin)===!0,[me,we]=h.useState(()=>bIe(!1)),Xe=h.useMemo(()=>C?aw({organizations:x,organizationPrefix:C}):null,[x,C]),ge=FUn(_,Xe==null?void 0:Xe.id,m),te=A===ge.contextKey,G=te?Xe==null?void 0:Xe.id:null,oe=te&&g&&ve,Ze=!!C&&!y&&x.length>0&&!Xe,{data:Te}=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1,refetchInterval:gt=>{var Gt;const Nt=gt.state.data;return(Gt=Nt==null?void 0:Nt.devServer)!=null&&Gt.enabled?2e3:!1},refetchIntervalInBackground:!0}),{data:Be}=Me({queryKey:V.chats.listPreview(w??"__none__","active",40),queryFn:()=>Xn.list(w,"active",{limit:40}),enabled:X&&!!w}),{data:it}=Me({queryKey:V.projects.list(w??"__none__"),queryFn:async()=>(await Mi.list(w)).filter(Nt=>!Nt.archivedAt),enabled:Q&&!!w}),lt=h.useMemo(()=>$?X?q||((Be==null?void 0:Be.length)??0)>0:!0:!1,[Be==null?void 0:Be.length,q,X,$]),Ue=h.useMemo(()=>lt?!Q||!(/^\/projects(?:\/|$)/.test(_)&&!/^\/projects\/[^/]+/.test(_))?!0:((it==null?void 0:it.length)??0)>0:!1,[Q,_,lt,it==null?void 0:it.length]);h.useEffect(()=>{y||ne.current||(Te==null?void 0:Te.deploymentMode)!=="authenticated"&&x.length===0&&(ne.current=!0,l())},[x,y,l,Te==null?void 0:Te.deploymentMode]),h.useEffect(()=>{Ae.current||d||c||y||x.length===0||re||_==="/onboarding"||lBn()||!xft()||(Ae.current=!0,u({source:"auto"}))},[re,c,u,x.length,y,d,_]),h.useEffect(()=>{if(!C||y||x.length===0)return;if(!Xe){const Nt=(w?x.find(Gt=>Gt.id===w):null)??x[0]??null;Nt&&w!==Nt.id&&S(Nt.id,{source:"route_sync"});return}const gt=Oc(Xe);if(C.toLowerCase()!==gt.toLowerCase()){const Nt=P.pathname.replace(/^\/[^/]+/,"");N(`/${gt}${Nt}${P.search}`,{replace:!0});return}AWt({selectionSource:k,selectedOrganizationId:w,routeOrganizationId:Xe.id})&&S(Xe.id,{source:"route_sync"})},[C,x,y,Xe,P.pathname,P.search,N,k,w,S]);const mt=f;oWt(),h.useLayoutEffect(()=>{Se(!1)},[Xe==null?void 0:Xe.id]),h.useLayoutEffect(()=>{te||Se(!1)},[te]),h.useLayoutEffect(()=>{g||Se(!1)},[g]),h.useEffect(()=>{mWt(Xe==null?void 0:Xe.id,D)},[Xe==null?void 0:Xe.id,D]),h.useEffect(()=>{if(!a){Fe(!0);return}Y.current=0,Fe(!0)},[a]),h.useEffect(()=>{if(!a)return;const gt=30,Nt=50,Gt=75;let cn=0,Rn=0,nt=!1;const Qt=Rt=>{const Cn=Rt.touches[0];cn=Cn.clientX,Rn=Cn.clientY;const zn=Rt.target instanceof Element?Rt.target:null;nt=!!(zn!=null&&zn.closest('[data-slot="dialog-content"], [data-slot="dialog-overlay"], [data-testid="chat-side-panel"]'))},st=Rt=>{if(nt){nt=!1;return}const Cn=Rt.changedTouches[0],zn=Cn.clientX-cn;if(!(Math.abs(Cn.clientY-Rn)>Gt)){if(!n&&cn<gt&&zn>Nt){r(!0);return}n&&zn<-Nt&&r(!1)}};return document.addEventListener("touchstart",Qt,{passive:!0}),document.addEventListener("touchend",st,{passive:!0}),()=>{document.removeEventListener("touchstart",Qt),document.removeEventListener("touchend",st)}},[a,n,r]);const tt=h.useCallback(gt=>{const Nt=gt-Y.current;gt<=24?Fe(!0):Nt>8?Fe(!1):Nt<-8&&Fe(!0),Y.current=gt},[]);h.useEffect(()=>{if(!a){Fe(!0),Y.current=0;return}const gt=()=>{tt(window.scrollY||document.documentElement.scrollTop||0)};return gt(),window.addEventListener("scroll",gt,{passive:!0}),()=>{window.removeEventListener("scroll",gt)}},[a,tt]),h.useEffect(()=>{const gt=document.body.style.overflow;return document.body.style.overflow=a?"visible":"hidden",()=>{document.body.style.overflow=gt}},[a]),h.useEffect(()=>{we(bIe(ie,(Te==null?void 0:Te.deploymentMode)??"authenticated"))},[ie,Te==null?void 0:Te.deploymentMode]),h.useEffect(()=>{if(!U)return;const gt=yIe(U);xe.current=B5(gt),Ne(gt)},[U]),h.useEffect(()=>{if(!U||ce===null||!Number.isFinite(ce))return;const gt=xe.current;if(gt===null){xe.current=B5(ke,ce);return}Ne(UUn(U,gt,ce))},[ce,U]),h.useEffect(()=>{if(U)try{window.localStorage.setItem(`${dAt}.${U}`,String(fq(U,ke)))}catch{}},[ke,U]),h.useEffect(()=>{if(re)return;const gt=fl(`${P.pathname}${P.search}${P.hash}`);if(!EK(gt))try{window.localStorage.setItem(cAt,gt)}catch{}},[re,P.hash,P.pathname,P.search]),h.useEffect(()=>{if(!re)return;const gt=oKe(`${P.pathname}${P.search}${P.hash}`,ie,(Te==null?void 0:Te.deploymentMode)??"authenticated");we(gt);try{window.localStorage.setItem(lAt,gt)}catch{}},[ie,Te==null?void 0:Te.deploymentMode,re,P.hash,P.pathname,P.search]);const dt=!a&&!re,at=dt&&Ue,Pe=dt,$e=!a&&re,ot=dt?F?"p-0":"px-2 py-1.5 md:px-3.5 md:py-2.5 lg:px-5 lg:py-3":"px-2.5 py-1.5 md:px-3 md:py-2 lg:px-4 lg:py-2.5",ue=h.useCallback(()=>{yWt(t,{target:me,organizationId:w})},[t,w,me]),Ie=h.useCallback(()=>{const gt=`${P.pathname}${P.search}${P.hash}`;ohe(gt),N(me,se?{state:se}:void 0),ue(),a&&r(!1)},[a,P.hash,P.pathname,P.search,N,ue,r,se,me]);h.useEffect(()=>{const gt=MUn(P),Nt=E.current;if(Nt.length===0){Nt.push(gt);return}const Gt=Nt.lastIndexOf(gt);if(M==="POP"){Gt>=0?Nt.splice(Gt+1):Nt.push(gt);return}if(M==="REPLACE"){Nt[Nt.length-1]=gt;return}Nt[Nt.length-1]!==gt&&Nt.push(gt),Nt.length>50&&Nt.splice(0,Nt.length-50)},[P,M]);const Ke=h.useCallback(()=>{const gt=E.current;if(gt.length<2)return EUn()?(N(-1),!0):!1;const Nt=fWt(gt),Gt=Nt>=0?gt[Nt]:null;return Gt?(gt.splice(Nt+1),N(Gt),!0):!1},[N]),De=h.useCallback(()=>{if(!w){j({title:"Select an organization first",body:"A new chat must belong to an organization.",tone:"error"});return}N("/messenger/chat")},[N,j,w]),Je=Me({queryKey:V.instance.shortcutSettings,queryFn:()=>Ha.getShortcuts(),retry:!1}),_e=Je.data===void 0?Je.isError?null:void 0:Je.data,Ee=_e!==void 0;tWt({onNewChat:De,onNewIssue:()=>o(),onToggleSidebar:s,onTogglePanel:mt,onOpenSettings:()=>Ie(),onNavigateBack:Ke,shortcutSettings:_e});const Ce=T?"h-full flex-1 pl-2.5 pb-1 pr-1 pt-0.5 md:pl-3 md:pb-1.5 md:pr-1.5 md:pt-0.5":"h-full flex-1 pl-0 pb-1 pr-1 pt-0.5 md:pb-1.5 md:pr-1.5 md:pt-1";function kt(){yT(),N(ee??_Un(),{replace:!0})}const Qe=h.useCallback(gt=>{if(!U||a)return;gt.preventDefault();const Nt=gt.clientX,Gt=ke,cn={cursor:document.body.style.cursor,userSelect:document.body.style.userSelect};document.body.style.cursor="col-resize",document.body.style.userSelect="none",fe(!0);const Rn=Qt=>{const st=Qt.clientX-Nt,Rt=fq(U,Gt+st);xe.current=B5(Rt),Ne(Rt)},nt=()=>{document.body.style.cursor=cn.cursor,document.body.style.userSelect=cn.userSelect,fe(!1),window.removeEventListener("pointermove",Rn),window.removeEventListener("pointerup",nt)};window.addEventListener("pointermove",Rn),window.addEventListener("pointerup",nt,{once:!0})},[ke,a,U]);return i.jsx(HKt,{navigateBack:Ke,children:i.jsxs("div",{"data-shortcut-settings-ready":Ee?"true":"false",className:K("app-shell-backdrop text-foreground pt-[env(safe-area-inset-top)]",a?"min-h-dvh":"flex h-dvh flex-col overflow-hidden"),children:[i.jsx("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-[200] focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:e("common.skipToMainContent")}),i.jsx(NUn,{}),i.jsx(gFn,{devServer:Te==null?void 0:Te.devServer}),i.jsxs(e$t,{children:[i.jsx(GUn,{contextKey:ge.contextKey,preserveHold:ge.preserveHold}),i.jsxs(ZKt,{children:[i.jsxs("div",{className:K("min-h-0 flex-1",a?"w-full":"flex overflow-hidden"),children:[a&&n&&i.jsx("button",{type:"button",className:"fixed inset-0 z-40 bg-[rgb(23_17_11/0.28)] backdrop-blur-sm",onClick:()=>r(!1),"aria-label":e("common.closeSidebar")}),a?i.jsxs("div",{className:K("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-[env(safe-area-inset-top)] transition-transform duration-100 ease-out",n?"translate-x-0":"-translate-x-full"),children:[i.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:R?i.jsx(mde,{}):B?i.jsx(mde,{}):i.jsx(UKt,{})}),i.jsx("div",{className:"editorial-dock px-3 py-3",children:i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("a",{href:xT,target:"_blank",rel:"noopener noreferrer",className:"flex min-w-0 flex-1 items-center gap-2.5 rounded-full px-3 py-2 text-[13px] font-medium text-muted-foreground transition-colors hover:bg-[color:var(--surface-active)] hover:text-foreground",children:[i.jsx(nE,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{className:"truncate",children:e("common.documentation")})]}),(Te==null?void 0:Te.version)&&i.jsxs(ra,{children:[i.jsx(sa,{asChild:!0,children:i.jsx("span",{className:"px-2 text-xs text-muted-foreground shrink-0 cursor-default",children:"v"})}),i.jsxs(ia,{children:["v",Te.version]})]}),re?i.jsx(le,{variant:"ghost",size:"icon-sm",className:"text-muted-foreground shrink-0",asChild:!0,children:i.jsx(sn,{to:Qc,"aria-label":e("common.backToWorkspace"),title:e("common.backToWorkspace"),onClick:()=>{a&&r(!1)},children:i.jsx(Kx,{className:"h-4 w-4"})})}):i.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",className:"settings-entry-button shrink-0 text-muted-foreground",onPointerEnter:ue,onFocus:ue,onClick:Ie,"aria-label":e("common.systemSettings"),title:e("common.systemSettings"),"data-settings-trigger":"true",children:i.jsx(Ix,{className:"h-4 w-4"})})]})})]}):i.jsx("div",{className:K("flex h-full min-h-0 shrink-0",T&&"pt-[var(--desktop-sidebar-top-clearance)]"),children:re?null:i.jsx(rBn,{onOpenSettings:Ie,onWarmSettings:ue})}),i.jsxs("div",{className:K("flex min-w-0 flex-col",a?"w-full":Ce),children:[!a&&T?i.jsx("div",{className:"desktop-window-drag h-[var(--desktop-content-top-gap)] shrink-0"}):null,$e?i.jsx(AAt,{onClose:kt,children:Ze?i.jsx(T4,{scope:"invalid_organization_prefix",requestedPrefix:C??(v==null?void 0:v.issuePrefix)}):i.jsx(zP,{})}):i.jsxs("div",{"data-testid":a?void 0:"workspace-shell",className:K("flex min-h-0 min-w-0 flex-1 flex-col",a?"w-full":"workspace-shell overflow-hidden",!a&&H&&"workspace-shell--library-transparent"),children:[Pe?null:i.jsx("div",{className:K(a&&"sticky top-0 z-20 bg-background/80 backdrop-blur-xl supports-[backdrop-filter]:bg-background/65"),children:i.jsx(jPe,{desktopChrome:T})}),i.jsx("div",{className:K(a?"block":"flex min-h-0 min-w-0 flex-1"),children:dt?i.jsxs("div",{className:K("relative flex min-h-0 min-w-0 flex-1","px-[3px] pb-[3px] pt-[1px] md:px-1 md:pb-1 md:pt-0.5"),children:[at?i.jsxs(i.Fragment,{children:[i.jsx("div",{"data-testid":"workspace-context-card","aria-hidden":!n,inert:n?void 0:!0,className:K("flex min-h-0 shrink-0 overflow-hidden","workspace-context-card",!ae&&"transition-[width,opacity,border-color] duration-200 ease-out motion-reduce:transition-none",n?"opacity-100":"pointer-events-none border-0 border-transparent opacity-0"),style:{width:n?ke:0},children:L?i.jsx(OUn,{}):H?i.jsx(x$n,{onCollapseSidebar:()=>r(!1)}):i.jsx(gUn,{})}),i.jsx("div",{"data-testid":"workspace-column-resizer","aria-hidden":!n,className:K("workspace-column-resizer group flex shrink-0 cursor-col-resize items-stretch justify-center transition-[width,opacity] duration-200 ease-out motion-reduce:transition-none",n?"w-2 opacity-100 md:w-[9px]":"w-0 overflow-hidden opacity-0",ae&&"is-resizing"),onPointerDown:Qe,role:n?"separator":void 0,"aria-orientation":"vertical","aria-label":"Resize workspace columns",children:i.jsx("div",{className:"workspace-column-resizer-line"})})]}):null,at&&!n&&F?i.jsx(YUn,{onOpen:()=>r(!0)}):null,i.jsxs("div",{className:"workspace-main-panel-stack relative flex min-h-0 min-w-0 flex-1","data-testid":"workspace-main-panel-stack",children:[i.jsxs("div",{"data-testid":"workspace-main-card","data-tour-target":"workspace-main","aria-hidden":oe||void 0,inert:oe?!0:void 0,className:K("flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden","workspace-main-card",F&&"workspace-main-card--frameless",oe&&"pointer-events-none border-0 [box-shadow:none]"),children:[F?null:i.jsx("div",{"data-testid":"workspace-main-header",className:"shrink-0",children:i.jsx(jPe,{desktopChrome:T,variant:"card"})}),i.jsx("main",{id:"main-content",tabIndex:-1,ref:ze,className:K("scrollbar-auto-hide min-w-0 flex-1",ot,a?"overflow-visible pb-[calc(5rem+env(safe-area-inset-bottom))]":F?"overflow-hidden":"overflow-auto"),children:Ze?i.jsx(T4,{scope:"invalid_organization_prefix",requestedPrefix:C??(v==null?void 0:v.issuePrefix)}):i.jsx(zP,{})})]}),i.jsx(XUn,{contextReady:te,expanded:ve,selectedOrganizationId:G,onExpandedChange:Se})]})]}):i.jsx("main",{id:"main-content","data-tour-target":"workspace-main",tabIndex:-1,ref:ze,className:K("scrollbar-auto-hide min-w-0 flex-1",ot,a?"overflow-visible pb-[calc(5rem+env(safe-area-inset-bottom))]":"overflow-auto"),children:Ze?i.jsx(T4,{scope:"invalid_organization_prefix",requestedPrefix:C??(v==null?void 0:v.issuePrefix)}):i.jsx(zP,{})})})]})]})]}),a&&i.jsx(xFn,{visible:Oe}),i.jsx(fFn,{}),i.jsx(FFn,{}),i.jsx(WFn,{}),i.jsx(vFn,{}),i.jsx(yFn,{}),a?i.jsx(Iut,{contextReady:te,selectedOrganizationId:G}):null]})]})]})})}function oh({width:e="default",className:t,children:n,...r}){return i.jsx("div",{...r,"data-slot":"settings-page","data-width":e,className:K("mx-auto flex w-full flex-col gap-7 px-4 pb-10 sm:px-7",e==="default"&&"max-w-[52rem]",e==="wide"&&"max-w-[64rem]",e==="full"&&"max-w-none",t),children:n})}function am({eyebrow:e,icon:t,title:n,description:r,action:s}){return i.jsxs("header",{"data-slot":"settings-page-header",className:"flex flex-col gap-2",children:[e?i.jsx("div",{className:"text-[11px] font-medium text-muted-foreground/72",children:e}):null,i.jsxs("div",{className:"grid grid-cols-1 items-start gap-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:gap-5",children:[i.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[t?i.jsx(t,{className:"mt-0.5 size-5 shrink-0 text-muted-foreground"}):null,i.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[i.jsx("h1",{className:"font-display text-[1.4rem] font-semibold leading-tight text-foreground sm:text-[1.55rem]",children:n}),r?i.jsx("div",{className:"max-w-3xl text-[13px] leading-5 text-muted-foreground",children:r}):null]})]}),s?i.jsx("div",{className:"flex shrink-0 items-center sm:justify-end",children:s}):null]})]})}function Wa({variant:e="default",children:t,className:n,...r}){return i.jsx("div",{...r,"data-slot":"settings-group","data-variant":e,className:K("overflow-hidden rounded-lg border border-[color:var(--border-soft)] [&>[data-slot=settings-actions]]:border-t [&>[data-slot=settings-actions]]:border-[color:var(--border-soft)] [&>[data-slot=settings-item]+[data-slot=settings-item]]:border-t [&>[data-slot=settings-item]+[data-slot=settings-item]]:border-[color:var(--border-soft)]",e==="feature"?"bg-[color:var(--surface-elevated)]":"bg-[color:color-mix(in_oklab,var(--surface-inset)_84%,var(--surface-elevated))]",n),children:t})}function ja({icon:e,title:t,description:n,action:r,headingLevel:s=3,className:a}){const o=s===2?"h2":"h3";return i.jsxs("div",{"data-slot":"settings-item",className:K("grid min-h-[4.25rem] grid-cols-1 items-center gap-3 px-4 py-3.5 sm:grid-cols-[minmax(0,1fr)_auto] sm:gap-5",a),children:[i.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e?i.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center text-muted-foreground",children:i.jsx(e,{className:"size-5"})}):null,i.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[i.jsx(o,{className:"text-[14px] font-medium leading-5 text-foreground",children:t}),n?i.jsx("div",{className:"max-w-[38rem] text-[13px] leading-5 text-muted-foreground",children:n}):null]})]}),r?i.jsx("div",{className:"flex w-full shrink-0 items-center justify-start sm:w-auto sm:justify-end",children:r}):null]})}function hi({title:e,description:t,children:n,className:r}){return i.jsxs("section",{"data-slot":"settings-section",className:K("flex flex-col gap-3",r),children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("h2",{className:"text-[15px] font-semibold text-foreground",children:e}),t?i.jsx("p",{className:"max-w-3xl text-[13px] leading-5 text-muted-foreground",children:t}):null]}),n]})}function v2({label:e,description:t,htmlFor:n,icon:r,children:s,className:a}){const o=i.jsxs(i.Fragment,{children:[r?i.jsx(r,{className:"size-4 shrink-0 text-muted-foreground"}):null,e]});return i.jsxs("div",{"data-slot":"settings-item",className:K("flex flex-col gap-3 px-4 py-4",a),children:[i.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[n?i.jsx("label",{htmlFor:n,className:"flex items-center gap-2 text-[14px] font-medium leading-5 text-foreground",children:o}):i.jsx("div",{className:"flex items-center gap-2 text-[14px] font-medium leading-5 text-foreground",children:o}),t?i.jsx("div",{className:"max-w-[42rem] text-[13px] leading-5 text-muted-foreground",children:t}):null]}),s]})}function hq({children:e,className:t}){return i.jsx("div",{"data-slot":"settings-actions",className:K("flex flex-wrap items-center justify-end gap-2 px-4 py-3",t),children:e})}function NP({children:e,className:t}){return i.jsx("div",{"data-slot":"settings-choice-grid",className:K("flex flex-wrap gap-2.5",t),children:e})}function U2({checked:e,className:t,...n}){return i.jsx(GA,{checked:e,size:"md",tone:"accent",className:K(t),...n})}function U1({label:e,description:t,selected:n=!1,preview:r,className:s,...a}){return i.jsxs("button",{type:"button","data-slot":"settings-choice-card","aria-pressed":n,className:K("group flex min-w-[var(--settings-choice-min-width)] flex-col gap-[var(--settings-choice-gap)] rounded-lg border px-[var(--settings-choice-padding-x)] py-[var(--settings-choice-padding-y)] text-left text-[length:var(--settings-choice-label-size)] outline-none transition-[border-color,background-color,box-shadow,transform] hover:bg-[color:var(--surface-elevated)] active:translate-y-px focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/45",n?"border-[color:color-mix(in_oklab,var(--accent-base)_74%,var(--border-strong))] bg-[color:var(--surface-elevated)] shadow-[0_0_0_1px_color-mix(in_oklab,var(--accent-base)_28%,transparent)]":"border-[color:var(--border-soft)] bg-[color:color-mix(in_oklab,var(--surface-inset)_84%,var(--surface-elevated))]",s),...a,children:[i.jsx("div",{className:"overflow-hidden rounded-[var(--settings-choice-preview-radius)]",children:r}),i.jsxs("div",{className:"flex flex-col gap-0.5",children:[i.jsx("div",{className:"font-medium text-foreground",children:e}),t?i.jsx("div",{className:"text-[length:var(--settings-choice-description-size)] leading-4 text-muted-foreground",children:t}):null]})]})}function n1({dense:e=!1,className:t}){return i.jsxs(oh,{"data-testid":"settings-page-skeleton",className:K("gap-7",t),"aria-hidden":"true",children:[i.jsxs("div",{className:"flex flex-col gap-3",children:[i.jsx(un,{className:"h-4 w-28"}),i.jsx(un,{className:"h-9 w-52"}),i.jsx(un,{className:"h-4 w-full max-w-xl"})]}),i.jsxs("div",{className:K("flex flex-col",e?"gap-3":"gap-4"),children:[i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(un,{className:"h-4 w-36"}),i.jsx(un,{className:"h-3 w-full max-w-lg"})]}),i.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] p-4",children:[i.jsx(un,{className:"h-10 w-full"}),i.jsx(un,{className:"h-10 w-full"}),e?null:i.jsx(un,{className:"h-24 w-full"})]})]}),i.jsxs("div",{className:"flex flex-col gap-4",children:[i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(un,{className:"h-4 w-32"}),i.jsx(un,{className:"h-3 w-full max-w-md"})]}),i.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(un,{className:"h-4 w-44"}),i.jsx(un,{className:"h-3 w-64 max-w-full"})]}),i.jsx(un,{className:"h-7 w-12 rounded-full"})]}),e?null:i.jsx(un,{className:"h-10 w-40"})]})]})]})}function wIe({children:e}){var s;const t=br(),n=Me({queryKey:V.health,queryFn:()=>rA.get(),retry:!1});if(n.isLoading)return i.jsx(n1,{dense:!0});const r=Ohe(Rie,!0,((s=n.data)==null?void 0:s.deploymentMode)??"authenticated");if(r!==Rie){const a=Hj(t.state);return i.jsx(Ai,{to:r,replace:!0,state:a})}return e}const JUn={seedGettingStarted:(e,t={})=>Re.post(`/orgs/${e}/onboarding/getting-started`,t)},G_={list:e=>Re.get(`/orgs/${e}/secrets`),providers:e=>Re.get(`/orgs/${e}/secret-providers`),create:(e,t)=>Re.post(`/orgs/${e}/secrets`,t),rotate:(e,t)=>Re.post(`/secrets/${e}/rotate`,t),update:(e,t)=>Re.patch(`/secrets/${e}`,t),remove:e=>Re.delete(`/secrets/${e}`)};function hAt(e){var n,r;const t=e.split("/").filter(Boolean);return t.length===1?((n=t[0])==null?void 0:n.toLowerCase())==="onboarding":t.length===2?((r=t[1])==null?void 0:r.toLowerCase())==="onboarding":!1}function eVn(e){const{pathname:t,orgPrefix:n,organizations:r}=e;if(!hAt(t))return null;const s=t.split("/").filter(Boolean)[0],a=n??((s==null?void 0:s.toLowerCase())==="onboarding"?void 0:s);if(!a)return{initialStep:1};const o=aw({organizations:r,organizationPrefix:a});return o?{initialStep:2,orgId:o.id}:{initialStep:1}}function mAt(e){return!e.hasOrganizations&&!hAt(e.pathname)}function pAt({label:e,hint:t,models:n,value:r,onChange:s,open:a,onOpenChange:o,allowDefault:l,allowClear:c=!1,allowCustom:d=!1,required:u,groupByProvider:f,preserveModelOrder:A=!1,emptyLabel:m,searchPlaceholder:g="Search models...",emptyMessage:x="No models found.",triggerTestId:y,disabled:v=!1}){const[w,k]=h.useState(""),S=n.find(M=>M.id===r),j=w.trim(),C=h.useMemo(()=>n.filter(M=>{if(!w.trim())return!0;const E=w.toLowerCase(),T=dde(M.id)??"";return M.id.toLowerCase().includes(E)||M.label.toLowerCase().includes(E)||T.toLowerCase().includes(E)}),[n,w]),N=d&&j.length>0&&!n.some(M=>M.id===j),P=h.useMemo(()=>{if(!f)return[{provider:"models",entries:A?C:[...C].sort((E,T)=>E.id.localeCompare(T.id))}];const M=new Map;for(const E of C){const T=dde(E.id)??"other",R=M.get(T)??[];R.push(E),M.set(T,R)}return Array.from(M.entries()).sort(([E],[T])=>E.localeCompare(T)).map(([E,T])=>({provider:E,entries:[...T].sort((R,_)=>R.id.localeCompare(_.id))}))},[C,f,A]);return i.jsx(mi,{label:e,hint:t,children:i.jsxs(ts,{open:v?!1:a,onOpenChange:M=>{v||(o(M),M||k(""))},children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between min-w-0","data-testid":y,disabled:v,children:[i.jsx("span",{className:K("truncate text-left",!r&&"text-muted-foreground"),children:S?S.label:r||m||(u?"Select model (required)":"Select model")}),i.jsx(qr,{className:"h-3 w-3 text-muted-foreground"})]})}),i.jsxs(ns,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:g,value:w,onChange:M=>k(M.target.value),autoFocus:!0}),i.jsxs("div",{className:"max-h-[240px] overflow-y-auto",children:[l&&i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!r&&"bg-accent"),onClick:()=>{s(""),o(!1)},children:"Default"}),c&&i.jsx("button",{className:K("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!r&&"bg-accent"),onClick:()=>{s(""),o(!1)},children:"No fallback model"}),N&&i.jsx("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:()=>{s(j),o(!1)},children:i.jsxs("span",{className:"block w-full text-left truncate",title:j,children:['Use "',j,'"']})}),P.map(M=>i.jsxs("div",{className:"mb-1 last:mb-0",children:[f&&i.jsxs("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:[M.provider," (",M.entries.length,")"]}),M.entries.map(E=>i.jsx("button",{className:K("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",E.id===r&&"bg-accent"),onClick:()=>{s(E.id),o(!1)},children:i.jsx("span",{className:"block w-full text-left truncate",title:E.id,children:f?OFn(E.id):E.label})},E.id))]},M.provider)),C.length===0&&!N&&i.jsx("p",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:x})]})]})]})})}function gAt({value:e,options:t,label:n="Thinking effort",hint:r=Ma.thinkingEffort,onChange:s,open:a,onOpenChange:o,disabled:l=!1}){const c=t.find(d=>d.id===e)??t[0];return i.jsx(mi,{label:n,hint:r,children:i.jsxs(ts,{open:l?!1:a,onOpenChange:d=>{l||o(d)},children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",disabled:l,children:[i.jsx("span",{className:K(!e&&"text-muted-foreground"),children:(c==null?void 0:c.label)??"Auto"}),i.jsx(qr,{className:"h-3 w-3 text-muted-foreground"})]})}),i.jsx(ns,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:t.map(d=>i.jsxs("button",{className:K("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",d.id===e&&"bg-accent"),onClick:()=>{s(d.id),o(!1)},children:[i.jsx("span",{children:d.label}),d.id?i.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:d.id}):null]},d.id||"auto"))})]})})}const kIe=[" ",".","·","▪","▫","○"],tVn=24,nVn=1e3/tVn,h$=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function OIe(e){const t=document.createElement("span");t.textContent="M",t.style.cssText="position:absolute;visibility:hidden;white-space:pre;font-size:11px;font-family:monospace;line-height:1;",e.appendChild(t);const n=t.getBoundingClientRect();return e.removeChild(t),{w:n.width,h:n.height}}function rVn(e){let t=0;for(const n of e)t=Math.max(t,n.length);return{width:t,height:e.length}}function xAt(){const e=h.useRef(null),t=h.useRef(null);return h.useEffect(()=>{if(!e.current)return;const n=e.current,r=window.matchMedia("(prefers-reduced-motion: reduce)");let s=document.visibilityState!=="hidden",a=!1,o=0,l=0,c=0,d=0,u=7,f=11,A=new Float32Array(0),m=new Float32Array(0),g=new Float32Array(0),x=new Uint16Array(0),y=[],v="";function w(_){const D=Math.max(0,Math.min(.999,_)),U=Math.floor(D*kIe.length);return kIe[U]??" "}function k(){const _=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,u))),D=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,f)));if(_===c&&D===d)return;c=_,d=D;const U=c*d;A=new Float32Array(U),m=new Float32Array(c),g=new Float32Array(d),x=new Uint16Array(U),y=y.filter($=>$.x>-$.width-2&&$.x<c+2&&$.y>-$.height-2&&$.y<d+2),v=""}function S(){if(c<=0||d<=0){n.textContent="";return}const _=Array.from({length:d},()=>Array.from({length:c},()=>" "));for(let L=0;L<d;L++)for(let H=0;H<c;H++){const X=(Math.sin(H*.11+L*.04)+Math.cos(L*.08-H*.02))*.18+.22;_[L][H]=w(X)}const D=18,U=13;for(let L=1;L<d-9;L+=U){const H=Math.floor(L/U)%2===0?2:10;for(let X=H;X<c-10;X+=D){const F=h$[(X+L)%h$.length];for(let Q=0;Q<F.length;Q++){const q=F[Q];for(let B=0;B<q.length;B++){const ee=q[B]??" ";if(ee===" ")continue;const se=L+Q,re=X+B;se<0||se>=d||re<0||re>=c||(_[se][re]=ee)}}}}const $=_.map(L=>L.join("")).join(`
1981
1981
  `);n.textContent=$,v=$}function j(){const _=h$[Math.floor(Math.random()*h$.length)],D=rVn(_),U=Math.random();let $=0,L=0,H=0,X=0;U<.68?($=Math.random()<.5?-D.width-1:c+1,L=Math.random()*Math.max(1,d-D.height),H=$<0?.04+Math.random()*.05:-(.04+Math.random()*.05),X=(Math.random()-.5)*.014):($=Math.random()*Math.max(1,c-D.width),L=Math.random()<.5?-D.height-1:d+1,H=(Math.random()-.5)*.014,X=L<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),y.push({x:$,y:L,vx:H,vy:X,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:_,width:D.width,height:D.height})}function C(_,D){const U=Math.round(_.x),$=Math.round(_.y);for(let L=0;L<_.sprite.length;L++){const H=_.sprite[L],X=$+L;if(!(X<0||X>=d))for(let F=0;F<H.length;F++){const Q=H[F]??" ";if(Q===" ")continue;const q=U+F;if(q<0||q>=c)continue;const B=X*c+q,ee=Q==="│"||Q==="─"?.8:.92;A[B]=Math.max(A[B]??0,D*ee),x[B]=Q.charCodeAt(0)}}}function N(_){if(!a||(t.current=requestAnimationFrame(N),_-o<nVn||c<=0||d<=0))return;const D=Math.min(2,o===0?1:(_-o)/16.6667);o=_,l+=D;const U=c*d,$=Math.max(3,Math.floor(U/2200));for(;y.length<$;)j();for(let H=0;H<A.length;H++)A[H]*=.92;x.fill(0);for(let H=y.length-1;H>=0;H--){const X=y[H];X.life+=D;const F=Math.sin((X.y+X.drift+l*.12)*.09)*.0018,Q=Math.cos((X.x-X.drift-l*.09)*.08)*.0014;if(X.vx=(X.vx+F)*.998,X.vy=(X.vy+Q)*.998,X.x+=X.vx*D,X.y+=X.vy*D,X.life>=X.maxLife||X.x<-X.width-2||X.x>c+2||X.y<-X.height-2||X.y>d+2){y.splice(H,1);continue}const q=X.life/X.maxLife,B=q<.12?q/.12:q>.88?(1-q)/.12:1;C(X,B)}for(let H=0;H<c;H++)m[H]=Math.sin(H*.08+l*.06);for(let H=0;H<d;H++)g[H]=Math.cos(H*.1-l*.05);let L="";for(let H=0;H<d;H++){for(let X=0;X<c;X++){const F=H*c+X,Q=x[F];if(Q>0){L+=String.fromCharCode(Q);continue}const q=(m[X]+g[H])*.08+.1,B=Math.max(A[F]??0,q*.45);L+=w(B)}H<d-1&&(L+=`
1982
1982
  `)}L!==v&&(n.textContent=L,v=L)}function P(){const _=c>0&&d>0;if(r.matches){a&&(a=!1,t.current!==null&&cancelAnimationFrame(t.current),t.current=null),_&&S();return}if(!s||!_){a&&(a=!1,t.current!==null&&cancelAnimationFrame(t.current),t.current=null);return}a||(a=!0,o=0,t.current=requestAnimationFrame(N))}const M=new ResizeObserver(()=>{const _=OIe(n);u=_.w,f=_.h,k(),P()});M.observe(n);const E=()=>{s=document.visibilityState!=="hidden",P()};document.addEventListener("visibilitychange",E);const T=()=>{P()};r.addEventListener("change",T);const R=OIe(n);return u=R.w,f=R.h,k(),P(),()=>{a=!1,t.current!==null&&cancelAnimationFrame(t.current),M.disconnect(),document.removeEventListener("visibilitychange",E),r.removeEventListener("change",T)}},[]),i.jsx("pre",{ref:e,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"11px",fontFamily:"monospace"},"aria-hidden":"true"})}function sVn({value:e,secrets:t,onCreateSecret:n,onChange:r,disabled:s=!1}){const{promptText:a}=ii();function o(v){return!v||typeof v!="object"?[{key:"",source:"plain",plainValue:"",secretId:""}]:[...Object.entries(v).map(([k,S])=>{if(typeof S=="string")return{key:k,source:"plain",plainValue:S,secretId:""};if(typeof S=="object"&&S!==null&&"type"in S&&S.type==="secret_ref"){const j=S;return{key:k,source:"secret",plainValue:"",secretId:typeof j.secretId=="string"?j.secretId:""}}if(typeof S=="object"&&S!==null&&"type"in S&&S.type==="plain"){const j=S;return{key:k,source:"plain",plainValue:typeof j.value=="string"?j.value:"",secretId:""}}return{key:k,source:"plain",plainValue:"",secretId:""}}),{key:"",source:"plain",plainValue:"",secretId:""}]}const[l,c]=h.useState(()=>o(e)),[d,u]=h.useState(null),f=h.useRef(e);h.useEffect(()=>{e!==f.current&&(f.current=e,c(o(e)))},[e]);function A(v){const w={};for(const k of v){const S=k.key.trim();if(S)if(k.source==="secret"){if(!k.secretId)continue;w[S]={type:"secret_ref",secretId:k.secretId,version:"latest"}}else w[S]={type:"plain",value:k.plainValue}}r(Object.keys(w).length>0?w:void 0)}function m(v,w){const k=l.map((S,j)=>j===v?{...S,...w}:S);(k[k.length-1].key||k[k.length-1].plainValue||k[k.length-1].secretId)&&k.push({key:"",source:"plain",plainValue:"",secretId:""}),c(k),A(k)}function g(v){const w=l.filter((k,S)=>S!==v);(w.length===0||w[w.length-1].key||w[w.length-1].plainValue||w[w.length-1].secretId)&&w.push({key:"",source:"plain",plainValue:"",secretId:""}),c(w),A(w)}function x(v){return v.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}async function y(v){var N;const w=l[v];if(!w)return;const k=w.key.trim(),S=w.plainValue;if(!k||S.length===0)return;const j=x(k)||"secret",C=(N=await a({title:"Secret name",label:"Name",defaultValue:j,confirmLabel:"Create secret"}))==null?void 0:N.trim();if(C)try{u(null);const P=await n(C,S);m(v,{source:"secret",secretId:P.id})}catch(P){u(P instanceof Error?P.message:"Failed to create secret")}}return i.jsxs("div",{className:"space-y-1.5",children:[l.map((v,w)=>{const k=w===l.length-1&&!v.key&&!v.plainValue&&!v.secretId;return i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("input",{className:K(Vh,"flex-[2]"),placeholder:"KEY",value:v.key,disabled:s,onChange:S=>m(w,{key:S.target.value})}),i.jsxs("select",{className:K(Vh,"flex-[1] bg-background"),value:v.source,disabled:s,onChange:S=>m(w,{source:S.target.value==="secret"?"secret":"plain",...S.target.value==="plain"?{secretId:""}:{}}),children:[i.jsx("option",{value:"plain",children:"Plain"}),i.jsx("option",{value:"secret",children:"Secret"})]}),v.source==="secret"?i.jsxs(i.Fragment,{children:[i.jsxs("select",{className:K(Vh,"flex-[3] bg-background"),value:v.secretId,disabled:s,onChange:S=>m(w,{secretId:S.target.value}),children:[i.jsx("option",{value:"",children:"Select secret..."}),t.map(S=>i.jsx("option",{value:S.id,children:S.name},S.id))]}),i.jsx("button",{type:"button",className:"inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0",onClick:()=>y(w),disabled:s||!v.key.trim()||!v.plainValue,title:"Create secret from current plain value",children:"New"})]}):i.jsxs(i.Fragment,{children:[i.jsx("input",{className:K(Vh,"flex-[3]"),placeholder:"value",value:v.plainValue,disabled:s,onChange:S=>m(w,{plainValue:S.target.value})}),i.jsx("button",{type:"button",className:"inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0",onClick:()=>y(w),disabled:s||!v.key.trim()||!v.plainValue,title:"Store value as secret and replace with reference",children:"Seal"})]}),k?i.jsx("div",{className:"w-[26px] shrink-0"}):i.jsx("button",{type:"button",className:"shrink-0 p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors",disabled:s,onClick:()=>g(w),children:i.jsx(Is,{className:"h-3.5 w-3.5"})})]},w)}),d&&i.jsx("p",{className:"text-[11px] text-destructive",children:d}),i.jsx("p",{className:"text-[11px] text-muted-foreground/60",children:"RUDDER_* variables are injected automatically at runtime."})]})}const iVn={claude_local:{src:"/brands/claude-logo.svg",sourceUrl:"https://cdn.simpleicons.org/claude",sourceSha256:"5119ef950a0d648b3fd62865791e73f07f32e18ddab84e4f21160f8c641c0f5f"},codex_local:{src:"/brands/openai-logo.svg",sourceUrl:"https://upload.wikimedia.org/wikipedia/commons/6/66/OpenAI_logo_2025_%28symbol%29.svg",sourceSha256:"1da76493b0ffed215d15e33b0ef5c9bd81c11ea170eac1f7690fecad0453410b",className:"dark:invert"},gemini_local:{src:"/brands/google-gemini-logo.svg",sourceUrl:"https://cdn.simpleicons.org/googlegemini",sourceSha256:"404eba6940a54e63d40edcce2d2e7cb2b3dbfec765e7a1d523662b6f4e0d6747"},pi_local:{src:"/brands/pi-logo.svg",sourceUrl:"https://pi.dev/logo-auto.svg",sourceSha256:"03d509c104b9570063fa268fd3235ed7e0e41dafd93124ca94cae3726f58f117"},cursor:{src:"/brands/cursor-logo.svg",sourceUrl:"https://cdn.simpleicons.org/cursor",sourceSha256:"68c88e317a03fefb7d8ed68b9fe86ef33c0a002765fa6bfc84cdc43d7bb9f4fe",className:"dark:invert"}};function SIe({runtimeType:e,className:t}){const n=K("h-3.5 w-3.5 shrink-0",t);if(e==="opencode_local")return i.jsx("span",{"aria-hidden":"true",className:"inline-flex shrink-0 items-center justify-center",children:i.jsx(h2e,{className:n})});const r=iVn[e];return r?i.jsx("span",{"aria-hidden":"true",className:"inline-flex shrink-0 items-center justify-center",children:i.jsx("img",{src:r.src,alt:"",className:K(n,r.className)})}):null}function aVn({runtimeType:e,adapter:t,fieldProps:n,availableSecrets:r,onCreateSecret:s}){const{isCreate:a,values:o,set:l,config:c,eff:d,mark:u,disabled:f}=n,A=t.ConfigFields;return i.jsxs("div",{className:"space-y-3",children:[i.jsx(A,{...n}),e==="claude_local"&&i.jsx(JNn,{...n}),i.jsx(mi,{label:"Command",hint:Ma.localCommand,children:i.jsx(rc,{value:a?o.command:d("agentRuntimeConfig","command",String(c.command??"")),onCommit:m=>a?l({command:m}):u("agentRuntimeConfig","command",m||void 0),immediate:!0,className:Vh,placeholder:edt(e),disabled:f})}),i.jsx(mi,{label:"Extra args (comma-separated)",hint:Ma.extraArgs,children:i.jsx(rc,{value:a?o.extraArgs:d("agentRuntimeConfig","extraArgs",dMn(c.extraArgs)),onCommit:m=>a?l({extraArgs:m}):u("agentRuntimeConfig","extraArgs",m?cMn(m):void 0),immediate:!0,className:Vh,placeholder:"e.g. --verbose, --foo=bar",disabled:f})}),i.jsx(mi,{label:"Environment variables",hint:Ma.envVars,children:i.jsx(sVn,{value:a?o.envBindings??PNe:d("agentRuntimeConfig","env",c.env??PNe),secrets:r,onCreateSecret:s,onChange:m=>a?l({envBindings:m??{},envVars:""}):u("agentRuntimeConfig","env",m),disabled:f})}),!a&&i.jsxs(i.Fragment,{children:[i.jsx(mi,{label:"Timeout (sec)",hint:Ma.timeoutSec,children:i.jsx(vO,{value:d("agentRuntimeConfig","timeoutSec",Number(c.timeoutSec??0)),onCommit:m=>u("agentRuntimeConfig","timeoutSec",m),immediate:!0,className:Vh,disabled:f})}),i.jsx(mi,{label:"Interrupt grace period (sec)",hint:Ma.graceSec,children:i.jsx(vO,{value:d("agentRuntimeConfig","graceSec",Number(c.graceSec??15)),onCommit:m=>u("agentRuntimeConfig","graceSec",m),immediate:!0,className:Vh,disabled:f})})]})]})}const oVn=new Set(["claude_local","codex_local","gemini_local","opencode_local","pi_local","cursor"]),lVn=new Set(["process","http"]),cVn={available:"Ready on this machine",unavailable:"Needs setup",unknown:"Other runtimes"},dVn=[...B6.filter(e=>!lVn.has(e)).map(e=>({value:e,label:MC[e]??e,comingSoon:!oVn.has(e)}))];function uVn({value:e,onChange:t,disabled:n=!1,availability:r=[]}){const s=new Map(r.map(o=>[o.agentRuntimeType,o])),a=["available","unavailable","unknown"].map(o=>({status:o,items:dVn.filter(l=>{const c=s.get(l.value);return((c==null?void 0:c.status)??"unknown")===o})})).filter(o=>o.items.length>0);return i.jsxs(ts,{children:[i.jsx(ys,{asChild:!0,children:i.jsxs("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",disabled:n,children:[i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[i.jsx(SIe,{runtimeType:e}),i.jsx("span",{children:MC[e]??e})]}),i.jsx(qr,{className:"h-3 w-3 text-muted-foreground"})]})}),i.jsx(ns,{className:"w-[var(--radix-popover-trigger-width)] p-1",align:"start",children:a.map(o=>i.jsxs("div",{className:"py-1 first:pt-0 last:pb-0",children:[i.jsx("div",{className:"px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:cVn[o.status]}),o.items.map(l=>{const c=s.get(l.value),d=(c==null?void 0:c.status)==="unavailable";return i.jsxs("button",{title:(c==null?void 0:c.hint)??(c==null?void 0:c.message),disabled:n||l.comingSoon,className:K("flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded",n||l.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",l.value===e&&!l.comingSoon&&"bg-accent",d&&"text-muted-foreground"),onClick:()=>{l.comingSoon||t(l.value)},children:[i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[i.jsx(SIe,{runtimeType:l.value}),i.jsx("span",{className:"truncate",children:l.label})]}),l.comingSoon?i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:"Coming soon"}):d?i.jsx("span",{className:"shrink-0 text-[10px] text-amber-700 dark:text-amber-300",children:"Default CLI missing"}):(c==null?void 0:c.status)==="available"?i.jsx("span",{className:"shrink-0 text-[10px] text-green-700 dark:text-green-300",children:"Ready"}):null]},l.value)})]},o.status))})]})}function bAt({result:e,label:t}){const n=e.status??"pass",r=ldt(e),s=n==="pass"?"Passed":n==="warn"?"Needs setup":"Failed",a=n==="pass"?"text-green-700 dark:text-green-300 border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10":n==="warn"?"text-amber-800 dark:text-amber-200 border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10":"text-red-700 dark:text-red-300 border-red-300 dark:border-red-500/40 bg-red-50 dark:bg-red-500/10";return i.jsxs("div",{className:`rounded-md border px-3 py-2 text-xs ${a}`,children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"font-medium",children:t?`${t}: ${s}`:s}),i.jsx("span",{className:"text-[11px] opacity-80",children:H4(e.testedAt)})]}),r.length>0?i.jsx("div",{className:"mt-2 space-y-1.5",children:r.map((o,l)=>i.jsxs("div",{className:"text-[11px] leading-relaxed break-words",children:[i.jsx("span",{className:"font-medium uppercase tracking-wide opacity-80",children:o.level}),i.jsx("span",{className:"mx-1 opacity-60",children:"·"}),i.jsx("span",{children:o.message}),o.detail&&i.jsxs("span",{className:"block opacity-75 break-all",children:["(",o.detail,")"]}),o.hint&&i.jsxs("span",{className:"block opacity-90 break-words",children:["Hint: ",o.hint]})]},`${o.code}-${l}`))}):null]})}function yAt({label:e,message:t}){return i.jsxs("div",{className:"rounded-md border border-red-300 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-500/40 dark:bg-red-500/10 dark:text-red-300",children:[i.jsxs("div",{className:"font-medium",children:[e,": Failed"]}),i.jsx("div",{className:"mt-1 text-[11px] leading-relaxed break-words opacity-90",children:t})]})}function fVn({status:e}){const t=e;if(!t)return null;const n=t==="pass"?"Env passed":t==="warn"?"Env needs setup":t==="testing"?"Testing env":"Env failed",r=t==="pass"?"border-green-300 bg-green-50 text-green-700 dark:border-green-500/40 dark:bg-green-500/10 dark:text-green-300":t==="warn"?"border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200":t==="testing"?"border-blue-300 bg-blue-50 text-blue-700 dark:border-blue-500/40 dark:bg-blue-500/10 dark:text-blue-300":"border-red-300 bg-red-50 text-red-700 dark:border-red-500/40 dark:bg-red-500/10 dark:text-red-300";return i.jsx("span",{className:K("shrink-0 rounded-full border px-2 py-0.5 text-[11px] font-medium",r),children:n})}function AVn({title:e,className:t,runtimeType:n,model:r,config:s,selectedOrganizationId:a,externalModels:o,availableSecrets:l,onCreateSecret:c,onRuntimeTypeChange:d,onModelChange:u,onConfigFieldChange:f,onConfigPatchChange:A,onRemove:m,hideRuntimeType:g=!1,hideInstructionsFile:x=!1,runtimeTypeLabel:y="Runtime type",runtimeTypeHint:v=Ma.agentRuntimeType,createValues:w,createSet:k,adapterAvailability:S,environmentStatus:j,triggerTestId:C,disabled:N=!1,dragHandleProps:P,isDragging:M=!1}){const[E,T]=h.useState(!1),[R,_]=h.useState(!1),[D,U]=h.useState(!1),$=h.useMemo(()=>Sw(n),[n]),{data:L}=Me({queryKey:a?V.agents.adapterModels(a,n):["agents","none","adapter-models",n],queryFn:()=>Nn.adapterModels(a,n),enabled:!!a}),H=h.useMemo(()=>RC(n,L,o),[n,L,o]),X=DC(n),F=sdt(n),Q=w?w.thinkingEffort:String(s[F]??s.reasoningEffort??""),q=R_(n,r),B=se=>{k?k({thinkingEffort:se}):n==="codex_local"?A==null||A({modelReasoningEffort:se||void 0,reasoningEffort:void 0}):f(F,se||void 0)},ee={mode:w?"create":"edit",isCreate:!!w,agentRuntimeType:n,values:w??null,set:N?(()=>{}):k??null,config:s,eff:(se,re,ne)=>Object.prototype.hasOwnProperty.call(s,re)?s[re]:ne,mark:N?(()=>{}):(se,re,ne)=>f(re,ne),models:H,hideInstructionsFile:x,disabled:N};return i.jsxs("div",{className:K("rounded-lg border border-border/80 bg-background/30 p-3 transition-shadow",M&&"relative z-10 opacity-90 shadow-md ring-1 ring-primary/30",t),children:[i.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[P?i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground active:cursor-grabbing disabled:cursor-not-allowed disabled:opacity-50",disabled:N,"aria-label":`Reorder ${e}`,title:"Drag to reorder runtime priority",...P,children:i.jsx(vBe,{className:"h-3.5 w-3.5"})}):null,i.jsx("div",{className:"truncate text-sm font-medium",children:e}),i.jsx(fVn,{status:j})]}),m?i.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-muted-foreground hover:text-destructive",onClick:m,disabled:N,"aria-label":`Remove ${e}`,children:i.jsx(yi,{className:"h-3.5 w-3.5"})}):null]}),i.jsxs("div",{className:"space-y-3",children:[!g&&i.jsx(mi,{label:y,hint:v,children:i.jsx(uVn,{value:n,onChange:d,disabled:N,availability:S})}),i.jsx(pAt,{label:"Model",hint:Ma.model,models:H,value:r,onChange:se=>{const re=R_(n,se),ne=!!(Q&&!re.some(Ae=>Ae.id===Q));u(se,ne)},open:E,onOpenChange:T,allowDefault:!X&&!m,required:X||!!m,groupByProvider:X,preserveModelOrder:n==="codex_local",emptyLabel:Tct(n,!!m),searchPlaceholder:_ct(n),emptyMessage:Mct(n),allowCustom:!0,triggerTestId:C,disabled:N}),_D(n)&&i.jsx(i.Fragment,{children:i.jsx(gAt,{value:Q,options:q,label:I0e(n),onChange:B,open:R,onOpenChange:_,disabled:N})}),i.jsx(rct,{title:"Advanced options",bordered:!0,open:D,onToggle:()=>U(!D),disabled:N,children:i.jsx(aVn,{runtimeType:n,adapter:$,fieldProps:ee,availableSecrets:l,onCreateSecret:c})})]})]})}function mq({sortableId:e,canDrag:t=!0,disabled:n=!1,className:r,...s}){const{attributes:a,listeners:o,setNodeRef:l,transform:c,transition:d,isDragging:u}=nC({id:e,disabled:n||!t});return i.jsx("div",{ref:l,className:r,style:{transform:Dg.Transform.toString(c),transition:d,zIndex:u?10:void 0},"data-runtime-chain-item":e,children:i.jsx(AVn,{...s,disabled:n,className:"h-full",isDragging:u,dragHandleProps:t?{...a,...o}:null})})}function T2e(e){const{mode:t,adapterModels:n}=e,r=t==="create",s=e.sectionLayout==="cards",a=e.showAdapterTypeField??!0,o=e.showAdapterTestEnvironmentButton??!0,l=e.showCreateRunPolicySection??!0,c=e.hideInstructionsFile??!1,{selectedOrganizationId:d}=jr(),u=Vn(),{data:f=[]}=Me({queryKey:d?V.secrets.list(d):["secrets","none"],queryFn:()=>G_.list(d),enabled:!!d}),A=xt({mutationFn:xe=>{if(!d)throw new Error("Select a organization to create secrets");return G_.create(d,xe)},onSuccess:()=>{d&&u.invalidateQueries({queryKey:V.secrets.list(d)})}}),m=xt({mutationFn:async({file:xe,namespace:ae})=>{if(!d)throw new Error("Select a organization to upload images");return f8.uploadImage(d,xe,ae)}}),[g,x]=h.useState(sne),y=h.useRef(null);h.useEffect(()=>{r||(y.current!==null&&e.agent!==y.current&&x({...sne}),y.current=e.agent)},[r,r?void 0:e.agent]);const v=!r&&lMn(g);function w(xe,ae,fe){const ve=g[xe];return ae in ve?ve[ae]:fe}function k(xe,ae,fe){x(ve=>({...ve,[xe]:{...ve[xe],[ae]:fe}}))}function S(xe){x(ae=>({...ae,agentRuntimeConfig:{...ae.agentRuntimeConfig,...xe}}))}const j=h.useCallback(()=>{x({...sne})},[]),C=h.useCallback(()=>{if(r||!v)return;const xe=e.agent,ae={};if(Object.keys(g.identity).length>0&&Object.assign(ae,g.identity),g.agentRuntimeType!==void 0)ae.agentRuntimeType=g.agentRuntimeType,ae.agentRuntimeConfig=INe(g.agentRuntimeConfig);else if(Object.keys(g.agentRuntimeConfig).length>0){const ve={...xe.agentRuntimeConfig??{},...g.agentRuntimeConfig};ae.agentRuntimeConfig=INe(ve),xMn(g.agentRuntimeConfig)&&(ae.replaceAgentRuntimeConfig=!0)}if(Object.keys(g.heartbeat).length>0){const fe=xe.runtimeConfig??{},ve=fe.heartbeat??{};ae.runtimeConfig={...fe,heartbeat:{...ve,...g.heartbeat}}}Object.keys(g.runtime).length>0&&Object.assign(ae,g.runtime),e.onSave(ae)},[r,v,g,e]);h.useEffect(()=>{var xe,ae,fe;r||((xe=e.onDirtyChange)==null||xe.call(e,v),(ae=e.onSaveActionChange)==null||ae.call(e,C),(fe=e.onCancelActionChange)==null||fe.call(e,j))},[r,v,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,C,j]),h.useEffect(()=>{if(!r)return()=>{var xe,ae,fe;(xe=e.onSaveActionChange)==null||xe.call(e,null),(ae=e.onCancelActionChange)==null||ae.call(e,null),(fe=e.onDirtyChange)==null||fe.call(e,!1)}},[r,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const N=r?{}:e.agent.agentRuntimeConfig??{},P=r?{}:e.agent.runtimeConfig??{},M=r?{}:P.heartbeat??{},E=r?e.values.agentRuntimeType:g.agentRuntimeType??e.agent.agentRuntimeType,T=pMn.includes(E),R=h.useMemo(()=>Sw(E),[E]),{data:_,error:D}=Me({queryKey:d?V.agents.adapterModels(d,E):["agents","none","adapter-models",E],queryFn:()=>Nn.adapterModels(d,E),enabled:!!d});h.useMemo(()=>RC(E,_,n),[E,_,n]);const{data:U=[]}=Me({queryKey:d?V.agents.adapterAvailability(d):["agents","none","adapter-availability"],queryFn:()=>Nn.adapterAvailability(d),enabled:!!d});r&&e.values;const[$,L]=h.useState(!1),[H,X]=h.useState(!1),F=r?e.values:null,Q=r?xe=>e.onChange(xe):null;function q(){return r?R.buildAdapterConfig(F):{...N,...g.agentRuntimeConfig}}const B=r?F.model:w("agentRuntimeConfig","model",String(N.model??"")),ee=P4(r?F.modelFallbacks:w("agentRuntimeConfig","modelFallbacks",N.modelFallbacks??[]),N4(E,B)),se=r?{...R.buildAdapterConfig(F),modelFallbacks:F.modelFallbacks}:{...N,...g.agentRuntimeConfig},re=h.useMemo(()=>idt({primaryRuntimeType:E,primaryModel:B,primaryConfig:se}),[E,B,se]),ne=Yj(Mx(mw,{activationConstraint:{distance:6}}),Mx(eC,{coordinateGetter:_W}));function Ae(xe,ae){const fe=adt(re,xe,ae),ve={...fe.primary.config,model:fe.primary.model,modelFallbacks:fe.fallbacks};if(r){Q({...ve,agentRuntimeType:fe.primary.agentRuntimeType,model:fe.primary.model,modelFallbacks:fe.fallbacks});return}x(Se=>({...Se,agentRuntimeType:fe.primary.agentRuntimeType===e.agent.agentRuntimeType?void 0:fe.primary.agentRuntimeType,agentRuntimeConfig:{...ve}}))}function Y(xe){var fe;const ae=(fe=xe.over)==null?void 0:fe.id;!ae||xe.active.id===ae||Ae(String(xe.active.id),String(ae))}function ce(){const xe={...q()};return delete xe.modelFallbacks,[{key:"primary",title:"Primary",runtimeType:E,model:B,config:{...xe,...B?{model:B}:{}}},...ee.map((ae,fe)=>({key:`fallback-${fe}`,title:`Fallback ${fe+1}`,runtimeType:ae.agentRuntimeType,model:ae.model,config:{...ae.config??{},...ae.model?{model:ae.model}:{}}}))]}const Oe=xt({mutationFn:async()=>{if(!d)throw new Error("Select a organization to test runtime environment");const xe=ce(),ae=[];for(const fe of xe)try{const ve=await Nn.testEnvironment(d,fe.runtimeType,{agentRuntimeConfig:fe.config});ae.push({...fe,result:ve})}catch(ve){ae.push({...fe,error:ve instanceof Error?ve:new Error(String(ve))})}return ae}}),Fe=h.useMemo(()=>new Map((Oe.data??[]).map(xe=>[xe.key,xe])),[Oe.data]);function ke(xe){var fe;if(Oe.isPending)return"testing";const ae=Fe.get(xe);if(ae)return ae.error?"error":(fe=ae.result)==null?void 0:fe.status}function Ne(xe){const ae=P4(xe,N4(E,B));r?Q({modelFallbacks:ae}):k("agentRuntimeConfig","modelFallbacks",ae)}return E==="codex_local"&&(r?F.search:w("agentRuntimeConfig","search",!!N.search)),h.useMemo(()=>{if(r)return{heartbeat:{enabled:F.heartbeatEnabled,intervalSec:F.intervalSec,preflightEnabled:F.preflightEnabled,maxConcurrentRuns:F.maxConcurrentRuns}};const xe={...P.heartbeat&&typeof P.heartbeat=="object"?P.heartbeat:{},...g.heartbeat};return{...P,heartbeat:xe}},[r,g.heartbeat,P,F]),i.jsxs("div",{className:K("relative",s&&"space-y-6"),children:[v&&!e.hideInlineSave&&i.jsx("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),i.jsx(le,{size:"sm",onClick:C,disabled:!r&&e.isSaving,children:!r&&e.isSaving?"Saving...":"Save"})]})}),!r&&i.jsxs("div",{className:K(!s&&"border-b border-border"),children:[s?i.jsx("h3",{className:"text-sm font-medium mb-3",children:"Identity"}):i.jsx("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),i.jsxs("div",{className:K(s?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[i.jsx(mi,{label:"Name",hint:Ma.name,children:i.jsx(rc,{value:w("identity","name",e.agent.name),onCommit:xe=>k("identity","name",xe),immediate:!0,className:Vh,placeholder:"Agent name"})}),i.jsx(mi,{label:"Title",hint:Ma.title,children:i.jsx(rc,{value:w("identity","title",e.agent.title??""),onCommit:xe=>k("identity","title",xe||null),immediate:!0,className:Vh,placeholder:"e.g. VP of Engineering"})}),i.jsx(mi,{label:"Capabilities",hint:Ma.capabilities,children:i.jsx(ku,{value:w("identity","capabilities",e.agent.capabilities??""),onChange:xe=>k("identity","capabilities",xe||null),placeholder:"Describe what this agent can do...",contentClassName:"min-h-[44px] text-sm font-mono",imageUploadHandler:async xe=>(await m.mutateAsync({file:xe,namespace:`agents/${e.agent.id}/capabilities`})).contentPath})}),T&&!e.hidePromptTemplate&&i.jsxs(i.Fragment,{children:[i.jsx(mi,{label:"Prompt Template",hint:Ma.promptTemplate,children:i.jsx(ku,{value:w("agentRuntimeConfig","promptTemplate",String(N.promptTemplate??"")),onChange:xe=>k("agentRuntimeConfig","promptTemplate",xe??""),placeholder:"Use this only for compact per-run task framing...",contentClassName:"min-h-[88px] text-sm font-mono",imageUploadHandler:async xe=>{const ae=`agents/${e.agent.id}/prompt-template`;return(await m.mutateAsync({file:xe,namespace:ae})).contentPath}})}),i.jsx("div",{"data-testid":"prompt-template-helper",className:"rounded-md border border-border/70 bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:"Prompt template is replayed on every heartbeat for existing runtime configs. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),i.jsxs("div",{className:K(!s&&(r?"border-t border-border":"border-b border-border")),children:[i.jsxs("div",{className:K(s?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[s?i.jsx("h3",{className:"text-sm font-medium",children:"Agent Runtime"}):i.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Agent Runtime"}),o&&i.jsx(le,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:()=>Oe.mutate(),disabled:Oe.isPending||!d,children:Oe.isPending?"Testing runtime chain...":"Test runtime chain"})]}),i.jsxs("div",{className:K(s?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[Oe.error&&i.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Oe.error instanceof Error?Oe.error.message:"Runtime chain environment test failed"}),Oe.data&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Runtime chain environment"}),Oe.data.map(xe=>{var ae;return xe.result?i.jsx(bAt,{result:xe.result,label:zV(xe)},xe.key):i.jsx(yAt,{label:zV(xe),message:((ae=xe.error)==null?void 0:ae.message)??"Environment test failed"},xe.key)})]}),i.jsx(tC,{sensors:ne,collisionDetection:EE,onDragEnd:Y,children:i.jsx(l3,{items:re.map(xe=>xe.id),strategy:yhe,children:i.jsxs("div",{className:odt,children:[re.map((xe,ae)=>{if(ae===0)return i.jsx(mq,{sortableId:xe.id,canDrag:re.length>1,title:"Primary",className:wO,runtimeType:E,model:B,config:se,selectedOrganizationId:d,externalModels:n,availableSecrets:f,onCreateSecret:(Se,ze)=>A.mutateAsync({name:Se,value:ze}),hideRuntimeType:!a,hideInstructionsFile:c,createValues:r?F:null,createSet:r?Q:null,adapterAvailability:U,onRuntimeTypeChange:Se=>{if(r){Q(tdt(Se));return}x(ze=>({...ze,agentRuntimeType:Se,agentRuntimeConfig:{...oj(Se),modelFallbacks:[]}}))},onModelChange:(Se,ze)=>{const ft=P4(ee,N4(E,Se));r?Q({model:Se,modelFallbacks:ft,...ze?{thinkingEffort:""}:{}}):S({model:Se||void 0,modelFallbacks:ft,...ze&&E==="codex_local"?{modelReasoningEffort:void 0,reasoningEffort:void 0}:{}})},onConfigFieldChange:(Se,ze)=>r?Q({[Se]:ze}):k("agentRuntimeConfig",Se,ze),onConfigPatchChange:Se=>{r?Q(Se):S(Se)},environmentStatus:ke("primary"),triggerTestId:"agent-primary-model"},xe.id);const fe=ae-1,ve=ee[fe];return ve?i.jsx(mq,{sortableId:xe.id,canDrag:re.length>1,title:`Fallback ${fe+1}`,className:wO,runtimeType:ve.agentRuntimeType,model:ve.model,config:{...ve.config??{},model:ve.model},selectedOrganizationId:d,externalModels:void 0,availableSecrets:f,onCreateSecret:(Se,ze)=>A.mutateAsync({name:Se,value:ze}),hideInstructionsFile:c,adapterAvailability:U,onRemove:()=>Ne(ee.filter((Se,ze)=>ze!==fe)),onRuntimeTypeChange:Se=>{const ze=oj(Se),ft=[...ee];ft[fe]={agentRuntimeType:Se,model:typeof ze.model=="string"?ze.model:kx(Se),config:ze},Ne(ft)},onModelChange:(Se,ze)=>{const ft=[...ee];ft[fe]={...ve,model:Se,config:{...ve.config??{},model:Se,...ze&&ve.agentRuntimeType==="codex_local"?{modelReasoningEffort:void 0,reasoningEffort:void 0}:{}}},Ne(ft)},onConfigFieldChange:(Se,ze)=>{const ft=[...ee];ft[fe]={...ve,config:{...ve.config??{},[Se]:ze}},Ne(ft)},onConfigPatchChange:Se=>{const ze=[...ee];ze[fe]={...ve,config:{...ve.config??{},...Se}},Ne(ze)},environmentStatus:ke(`fallback-${fe}`),triggerTestId:`agent-fallback-model-${fe+1}`},xe.id):null}),i.jsx("button",{type:"button",className:K(wO,"min-h-[180px] rounded-lg border border-dashed border-border/80 px-4 py-4 text-left transition-colors hover:border-primary/50 hover:bg-accent/30"),onClick:()=>Ne([...ee,rdt(E,ee)]),children:i.jsxs("div",{className:"flex h-full min-h-[140px] flex-col items-center justify-center gap-2 text-sm text-muted-foreground",children:[i.jsx("span",{className:"rounded-full border border-border p-2",children:i.jsx(Zr,{className:"h-4 w-4"})}),i.jsx("span",{children:"Add fallback model"})]})})]})})}),D&&i.jsx("p",{className:"text-xs text-destructive",children:D instanceof Error?D.message:"Failed to load runtime models."}),T&&r&&i.jsxs(i.Fragment,{children:[i.jsx(mi,{label:"Prompt Template",hint:Ma.promptTemplate,children:i.jsx(ku,{value:F.promptTemplate,onChange:xe=>Q({promptTemplate:xe}),placeholder:`# SOUL.md
1983
1983