@pennyfarthing/cyclist 10.3.0 → 10.4.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 (110) hide show
  1. package/dist/bikerack.js +1 -1
  2. package/dist/bikerack.js.map +1 -1
  3. package/dist/public/js/react/react.js +3 -3
  4. package/dist/sprint-data.d.ts +1 -1
  5. package/dist/sprint-data.d.ts.map +1 -1
  6. package/dist/sprint-data.js +28 -7
  7. package/dist/sprint-data.js.map +1 -1
  8. package/dist/websocket.js +3 -3
  9. package/dist/websocket.js.map +1 -1
  10. package/package.json +1 -1
  11. package/portraits/a-team/large/face-44442.png +0 -0
  12. package/portraits/a-team/medium/face-44442.png +0 -0
  13. package/portraits/alice-in-wonderland/large/tweedles-44342.png +0 -0
  14. package/portraits/alice-in-wonderland/medium/tweedles-44342.png +0 -0
  15. package/portraits/battlestar-galactica/large/baltar-53343.png +0 -0
  16. package/portraits/battlestar-galactica/medium/baltar-53343.png +0 -0
  17. package/portraits/blade-runner/large/tyrell-54232.png +0 -0
  18. package/portraits/blade-runner/medium/tyrell-54232.png +0 -0
  19. package/portraits/catch-22/large/major-34253.png +0 -0
  20. package/portraits/catch-22/medium/major-34253.png +0 -0
  21. package/portraits/control/large/burt-44342.png +0 -0
  22. package/portraits/control/medium/burt-44342.png +0 -0
  23. package/portraits/cowboy-bebop/large/ed-54342.png +0 -0
  24. package/portraits/cowboy-bebop/medium/ed-54342.png +0 -0
  25. package/portraits/discworld/large/moist-44342.png +0 -0
  26. package/portraits/discworld/medium/moist-44342.png +0 -0
  27. package/portraits/doctor-who/large/sarah-jane-44342.png +0 -0
  28. package/portraits/doctor-who/medium/sarah-jane-44342.png +0 -0
  29. package/portraits/dune/large/thufir-44342.png +0 -0
  30. package/portraits/dune/medium/thufir-44342.png +0 -0
  31. package/portraits/fifth-element/large/cornelius-54343.png +0 -0
  32. package/portraits/fifth-element/large/diva-53453.png +0 -0
  33. package/portraits/fifth-element/large/korben-34232.png +0 -0
  34. package/portraits/fifth-element/large/leeloo-54333.png +0 -0
  35. package/portraits/fifth-element/large/lindberg-34432.png +0 -0
  36. package/portraits/fifth-element/large/lindberg-44342.png +0 -0
  37. package/portraits/fifth-element/large/mondoshawan-55131.png +0 -0
  38. package/portraits/fifth-element/large/munro-25321.png +0 -0
  39. package/portraits/fifth-element/large/pacoli-45232.png +0 -0
  40. package/portraits/fifth-element/large/ruby-53544.png +0 -0
  41. package/portraits/fifth-element/large/zorg-45312.png +0 -0
  42. package/portraits/fifth-element/medium/cornelius-54343.png +0 -0
  43. package/portraits/fifth-element/medium/diva-53453.png +0 -0
  44. package/portraits/fifth-element/medium/korben-34232.png +0 -0
  45. package/portraits/fifth-element/medium/leeloo-54333.png +0 -0
  46. package/portraits/fifth-element/medium/lindberg-34432.png +0 -0
  47. package/portraits/fifth-element/medium/lindberg-44342.png +0 -0
  48. package/portraits/fifth-element/medium/mondoshawan-55131.png +0 -0
  49. package/portraits/fifth-element/medium/munro-25321.png +0 -0
  50. package/portraits/fifth-element/medium/pacoli-45232.png +0 -0
  51. package/portraits/fifth-element/medium/ruby-53544.png +0 -0
  52. package/portraits/fifth-element/medium/zorg-45312.png +0 -0
  53. package/portraits/firefly/large/book-44342.png +0 -0
  54. package/portraits/firefly/medium/book-44342.png +0 -0
  55. package/portraits/game-of-thrones/large/varys-44342.png +0 -0
  56. package/portraits/game-of-thrones/medium/varys-44342.png +0 -0
  57. package/portraits/harry-potter/large/hermione-44342.png +0 -0
  58. package/portraits/harry-potter/medium/hermione-44342.png +0 -0
  59. package/portraits/hitchhikers-guide/large/trillian-44342.png +0 -0
  60. package/portraits/hitchhikers-guide/medium/trillian-44342.png +0 -0
  61. package/portraits/lord-of-the-rings/large/elrond-44342.png +0 -0
  62. package/portraits/lord-of-the-rings/medium/elrond-44342.png +0 -0
  63. package/portraits/mad-max/large/the-dag-44342.png +0 -0
  64. package/portraits/mad-max/medium/the-dag-44342.png +0 -0
  65. package/portraits/mash/large/hawkeye-52544.png +0 -0
  66. package/portraits/mash/large/klinger-33543.png +0 -0
  67. package/portraits/mash/large/margaret-34343.png +0 -0
  68. package/portraits/mash/large/margaret-45443.png +0 -0
  69. package/portraits/mash/large/mulcahy-34352.png +0 -0
  70. package/portraits/mash/large/potter-44443.png +0 -0
  71. package/portraits/mash/large/potter-45342.png +0 -0
  72. package/portraits/mash/large/radar-24342.png +0 -0
  73. package/portraits/mash/large/radar-35254.png +0 -0
  74. package/portraits/mash/large/radar-45242.png +0 -0
  75. package/portraits/mash/large/winchester-55322.png +0 -0
  76. package/portraits/mash/medium/hawkeye-52544.png +0 -0
  77. package/portraits/mash/medium/klinger-33543.png +0 -0
  78. package/portraits/mash/medium/margaret-34343.png +0 -0
  79. package/portraits/mash/medium/margaret-45443.png +0 -0
  80. package/portraits/mash/medium/mulcahy-34352.png +0 -0
  81. package/portraits/mash/medium/potter-44443.png +0 -0
  82. package/portraits/mash/medium/potter-45342.png +0 -0
  83. package/portraits/mash/medium/radar-24342.png +0 -0
  84. package/portraits/mash/medium/radar-35254.png +0 -0
  85. package/portraits/mash/medium/radar-45242.png +0 -0
  86. package/portraits/mash/medium/winchester-55322.png +0 -0
  87. package/portraits/princess-bride/large/vizzini-54342.png +0 -0
  88. package/portraits/princess-bride/medium/vizzini-54342.png +0 -0
  89. package/portraits/sandman/large/lucien-54342.png +0 -0
  90. package/portraits/sandman/medium/lucien-54342.png +0 -0
  91. package/portraits/star-trek-tng/large/troi-44352.png +0 -0
  92. package/portraits/star-trek-tng/medium/troi-44352.png +0 -0
  93. package/portraits/star-wars/large/mothma-44342.png +0 -0
  94. package/portraits/star-wars/medium/mothma-44342.png +0 -0
  95. package/portraits/the-expanse/large/avasarala-44342.png +0 -0
  96. package/portraits/the-expanse/medium/avasarala-44342.png +0 -0
  97. package/portraits/the-matrix/large/oracle-44342.png +0 -0
  98. package/portraits/the-matrix/medium/oracle-44342.png +0 -0
  99. package/portraits/watchmen/large/veidt-44342.png +0 -0
  100. package/portraits/watchmen/medium/veidt-44342.png +0 -0
  101. package/portraits/west-wing/large/c-j-44342.png +0 -0
  102. package/portraits/west-wing/medium/c-j-44342.png +0 -0
  103. package/portraits/x-files/large/gunmen-44342.png +0 -0
  104. package/portraits/x-files/medium/gunmen-44342.png +0 -0
  105. package/src/public/components/AgentPopup.tsx +1 -0
  106. package/src/public/components/BikeRackWorkspace.tsx +2 -0
  107. package/src/public/components/MessageView.tsx +2 -1
  108. package/src/public/components/PersonaHeader.tsx +2 -0
  109. package/src/public/components/TandemPortrait.tsx +1 -0
  110. package/src/public/utils/messageFilters.ts +1 -0
@@ -60,8 +60,8 @@ For more information, see https://radix-ui.com/primitives/docs/components/${e.do
60
60
  `).length:0}function hM(i,e){return i.replace(/\r\n/g,`
61
61
  `).split(`
62
62
  `).slice(0,e).join(`
63
- `)}function fM(i,e){return i==="Read"&&e.file_path?String(e.file_path):i==="Bash"&&e.command?String(e.command):i==="Glob"&&e.pattern||i==="Grep"&&e.pattern?String(e.pattern):i==="Write"&&e.file_path?String(e.file_path):JSON.stringify(e,null,2)}function Rw(i){return{Read:"R",Write:"W",Bash:"B",Glob:"G",Grep:"S",Edit:"E",Task:"T",WebFetch:"F",WebSearch:"W",TodoWrite:"D"}[i]||i.charAt(0).toUpperCase()}function $p({toolUse:i,result:e,className:n}){const[r,l]=S.useState(!0),[u,p]=S.useState(!0),[a,c]=S.useState(!1),[f,v]=S.useState("idle"),m=e?.is_error===!0,y=fM(i.tool_name,i.input),C=Object.keys(i.input).length,R=lM(i.tool_name),E=S.useMemo(()=>Gf(i.tool_name,i.input),[i.tool_name,i.input]),g=S.useMemo(()=>e?dM(e.content):0,[e?.content]),b=g>Ey,_=b&&!a,x=S.useMemo(()=>e?_?hM(e.content,Ey):e.content:"",[e?.content,_]),A=async()=>{if(e)try{await navigator.clipboard.writeText(e.content),v("copied"),setTimeout(()=>v("idle"),2e3)}catch{v("error")}},D=g===1?"1 line":`${g} lines`,N=["tool-call-block",R,m?"tool-error":"",n||""].filter(Boolean).join(" "),O=Rw(i.tool_name);return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{"data-testid":"tool-call-block",className:N,children:[d.jsxs("div",{className:"tool-header",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"default",className:"tool-type-badge",children:O})}),d.jsx(Oe,{children:i.tool_name})]}),d.jsx("span",{className:"tool-name",children:E}),d.jsx("span",{"data-testid":"tool-duration",className:"tool-duration",children:e?.durationMs!==void 0?Tw(e.durationMs):""})]}),d.jsx("div",{className:"tool-result-header",children:d.jsxs(De,{variant:"ghost",size:"sm","data-testid":"tool-prompt-toggle",className:"tool-result-toggle",onClick:()=>p(!u),children:[u?"▶":"▼"," Prompt (",C," ",C===1?"param":"params",")"]})}),d.jsx("div",{"data-testid":"tool-prompt-content",className:`tool-result-content ${u?"collapsed":""}`,children:d.jsx("pre",{children:y})}),e&&d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"tool-result-header",children:[d.jsxs(De,{variant:"ghost",size:"sm","data-testid":"tool-result-toggle",className:"tool-result-toggle",onClick:()=>l(!r),children:[r?"▶":"▼"," Result (",D,")"]}),d.jsx(De,{variant:"ghost",size:"icon","data-testid":"tool-result-copy",className:`tool-result-copy ${f==="copied"?"copied":""} ${f==="error"?"copy-error":""}`,onClick:A,"aria-label":"Copy result to clipboard",children:f==="copied"?"✓":"📋"})]}),d.jsxs("div",{"data-testid":"tool-result-content",className:`tool-result-content ${r?"collapsed":""} ${_&&!r?"truncated":""} ${m?"error-content":""}`,children:[d.jsx("pre",{children:x}),b&&!r&&_&&d.jsxs(De,{variant:"link",size:"sm","data-testid":"tool-result-expand",className:"tool-result-expand",onClick:()=>c(!0),children:["Show all (",g," lines)"]})]})]})]})})}function pM({stack:i,toolResults:e}){const[n,r]=S.useState(!i.isActive),l=S.useRef(i.isActive);S.useEffect(()=>{l.current&&!i.isActive&&r(!1),l.current=i.isActive},[i.isActive]);const u=`${i.count}`,p=S.useMemo(()=>{if(i.isActive&&i.tools.length>0){const R=i.tools[i.tools.length-1];return Gf(R.tool_name,R.input)}return null},[i.tools,i.isActive]),a=S.useMemo(()=>{if(i.tools.length===0)return"";const R=i.tools[i.tools.length-1];return Gf(R.tool_name,R.input)},[i.tools]),c=S.useMemo(()=>{const R=new Map;return i.tools.forEach(E=>{const g=R.get(E.tool_name)||0;R.set(E.tool_name,g+1)}),R},[i.tools]),f=S.useMemo(()=>i.tools.reduce((R,E)=>{const g=e.get(E.tool_id);return R+(g?.durationMs||0)},0),[i.tools,e]),v=R=>{const E=i.tools[R],g=e.get(E.tool_id);return i.isActive&&R===i.tools.length-1&&!g?"tool-current":"tool-historical"},m=S.useCallback(()=>{r(R=>!R)},[]),y=S.useCallback(R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),m())},[m]),C=!n||i.isActive;return d.jsxs("div",{"data-testid":"tool-stack","data-collapsible":"true",className:`tool-stack ${n&&!i.isActive?"collapsed":""}`,children:[d.jsxs("div",{"data-testid":"tool-stack-header",className:"tool-stack-header",onClick:m,onKeyDown:y,role:"button",tabIndex:0,"aria-expanded":!n||i.isActive,"aria-label":`Tool stack with ${u}: ${a}`,children:[d.jsx("span",{className:"tool-stack-toggle",children:n&&!i.isActive?"▶":"▼"}),d.jsx("span",{"data-testid":"tool-stack-count",className:"tool-stack-count-badge",children:u}),i.isActive&&p?d.jsx("span",{className:"tool-stack-active-summary",children:p}):d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"tool-stack-badges",children:d.jsx(wt,{delayDuration:300,children:Array.from(c.entries()).slice(0,4).map(([R,E])=>d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"outline",className:`tool-mini-badge badge-${R.toLowerCase()}`,children:Rw(R)})}),d.jsx(Oe,{children:`${E} ${R} call${E>1?"s":""}`})]},R))})}),d.jsx("span",{className:"tool-stack-summary",children:a})]}),d.jsx("span",{className:"tool-stack-duration",children:f>0?Tw(f):""})]}),C&&d.jsx("div",{className:"tool-stack-content",children:i.tools.map((R,E)=>{const g=e.get(R.tool_id),b=v(E);return d.jsx($p,{toolUse:{type:"tool_use",tool_name:R.tool_name,tool_id:R.tool_id,input:R.input,timestamp:R.timestamp},result:g?{type:"tool_result",tool_id:g.tool_id,content:g.content,timestamp:g.timestamp}:void 0,className:b},R.tool_id||`tool-${E}`)})})]})}const af=new Map;let Mc=null;async function mM(){if(!Mc)try{const i=await fetch("/api/theme-agents/full");i.ok&&(Mc=await i.json())}catch{}}async function gM(i){const e=`agent:${i}`;if(af.has(e))return af.get(e);try{if(await mM(),Mc?.agents){const n=Mc.agents.find(r=>r.role===i);if(n?.helper)return af.set(e,n.helper),n.helper}return null}catch{return null}}const Dy={"testing-runner":"Running tests",Explore:"Exploring codebase","sm-setup":"Setting up story","sm-finish":"Finishing story",handoff:"Handing off","workflow-status-check":"Checking workflow status","general-purpose":"Processing task",Plan:"Planning implementation",Bash:"Running commands"};function vM(i,e){const n=e?.plural?"are":"is",r=i.description,l=i.subagent_type;if(l&&Dy[l]){const u=Dy[l],p=u.charAt(0).toLowerCase()+u.slice(1);return r?`${n} ${p}: ${r}`:`${n} ${p}`}return r||"Working..."}function _M(){const[i,e]=S.useState(null),[n,r]=S.useState(!0),[l,u]=S.useState(null);return S.useEffect(()=>{const p=async f=>{try{const v=await gM(f);e(v),r(!1)}catch(v){u(v instanceof Error?v:new Error("Failed to fetch helper")),r(!1)}},a=window.location.protocol==="https:"?"wss:":"ws:",c=new WebSocket(`${a}//${window.location.host}/ws/persona`);return c.onmessage=f=>{try{const v=JSON.parse(f.data);v?.role&&p(v.role)}catch(v){u(v instanceof Error?v:new Error("Failed to parse persona")),r(!1)}},c.onerror=()=>{u(new Error("WebSocket connection failed")),r(!1)},()=>c.close()},[]),{helper:i,isLoading:n,error:l}}function bM({type:i,name:e,messages:n,defaultCollapsed:r=!0,onCollapseChange:l,helperName:u,helperStyle:p,friendlyMessage:a}){const[c,f]=S.useState(r),{helper:v}=_M(),m=S.useMemo(()=>vM({subagent_type:i,description:e},{plural:v?.plural}),[i,e,v?.plural]),y=u??v?.name,C=p??v?.style,R=a??m,E=y||i,g=R||e,b=n.filter(A=>A.type!=="tool_result").length,_=new Map;n.forEach(A=>{A.type==="tool_result"&&A.tool_id&&_.set(A.tool_id,A)});const x=(A,D)=>{if(A.type==="tool_use"&&A.tool_name&&A.tool_id){const N=_.get(A.tool_id);return d.jsx("div",{"data-testid":"message-tool_use",className:"message message-tool_use",children:d.jsx($p,{toolUse:{type:"tool_use",tool_name:A.tool_name,tool_id:A.tool_id,input:A.input||{},timestamp:A.timestamp},result:N?{type:"tool_result",tool_id:N.tool_id,content:N.content||"",timestamp:N.timestamp}:void 0})},`tool-wrapper-${A.tool_id}`)}if(A.type==="tool_result")return null;if(A.type==="user"){const N=(A.content||"").slice(0,120).replace(/\n/g," ");return d.jsx("div",{"data-testid":"subagent-prompt",className:"message message-subagent-prompt",children:d.jsxs("div",{className:"message-content",children:[N,(A.content||"").length>120?"...":""]})},`subagent-prompt-${D}`)}return d.jsx(kw,{message:{type:A.type,content:A.content,timestamp:A.timestamp}},`msg-${D}`)};return d.jsxs("div",{"data-testid":"subagent-span","data-collapsible":"true",className:`subagent-span subagent-${i} ${c?"collapsed":""}`,children:[d.jsxs("div",{"data-testid":"subagent-span-header",className:"subagent-header",onClick:()=>{const A=!c;f(A),l?.(A)},children:[d.jsx("span",{className:"subagent-toggle",children:c?"▶":"▼"}),d.jsx(wt,{delayDuration:300,children:C?d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"subagent-helper-name",children:E})}),d.jsx(Oe,{children:C})]}):d.jsx("span",{className:"subagent-helper-name",children:E})}),d.jsx("span",{className:"subagent-friendly-message",children:g}),d.jsx(Ke,{variant:"outline","data-testid":"subagent-type-badge",className:"subagent-type-badge",children:i}),d.jsx("span",{className:"subagent-count",children:b})]}),!c&&d.jsx("div",{className:"subagent-content",children:n.map((A,D)=>x(A,D))})]})}const Ay=/<!--\s*CYCLIST:(\w+)(?::([^>]+?))?\s*-->/gi,Hs={HANDOFF:"handoff",CONTEXT_CLEAR:"context_clear",INVOKE:"invoke",QUESTION:"question",CHOICES:"choices",CONTINUE:"continue"},yM=new Set(["handoff","context_clear","invoke","question","choices","continue"]);function SM(i){return i?i.replace(/```[\s\S]*?```/g,""):""}function wM(i){if(!i)return null;const e=SM(i);if(!e.trim())return null;const n=[];Ay.lastIndex=0;let r;for(;(r=Ay.exec(e))!==null;){const l=r[1].toLowerCase();yM.has(l)&&n.push({type:l,value:r[2]?.trim()??"",source:"structured_marker"})}return n.length>0?n:null}function xM(i,e){if(!i)return e.map(u=>({number:u,text:`Option ${u}`}));const n=i.replace(/```[\s\S]*?```/g,""),r=[/^\s*(\d+)\.\s+(.+)$/gm,/^\s*(\d+)\)\s+(.+)$/gm,/\*\*(\d+)[.)]\*\*\s*(.+)/gm],l=new Map;for(const u of r){u.lastIndex=0;let p;for(;(p=u.exec(n))!==null;){const a=parseInt(p[1],10);if(e.includes(a)&&!l.has(a)){let c=p[2].trim();const f=c.search(/\s+[-—]\s+/);f>0&&f<30&&(c=c.substring(0,f)),l.set(a,c)}}}return e.map(u=>({number:u,text:l.get(u)||`Option ${u}`}))}function CM(i,e){if(!i||i.length===0)return null;const n=i[0];switch(n.type){case Hs.HANDOFF:return{type:"handoff",value:n.value,responses:[n.value,"Not yet"]};case Hs.INVOKE:return{type:"invoke",value:n.value,autoExecute:!0};case Hs.QUESTION:{if(n.value==="yesno")return{type:"yesno",responses:["Yes","No"]};if(n.value?.startsWith("open")){const l=n.value.indexOf(":");if(l!==-1){const u=n.value.substring(l+1).trim();if(u)return{type:"open",responses:[u]}}return{type:"open"}}const r=i.find(l=>l.type===Hs.CHOICES);return r?ky(r.value,e):null}case Hs.CHOICES:return ky(n.value,e);case Hs.CONTEXT_CLEAR:return{type:"context_clear",value:n.value};case Hs.CONTINUE:return{type:"continue",responses:["Continue"]};default:return null}}function ky(i,e){const n=i.split(",").map(p=>p.trim()),r=n[0],l=/^\d+$/.test(r);let u;if(l){const p=n.map(a=>parseInt(a,10));u=xM(e,p)}else u=n.map((p,a)=>({number:a+1,text:p}));return{type:"choices",choices:u,responses:u.map(p=>p.text)}}function EM(i){return S.useMemo(()=>{if(!i)return null;const e=wM(i);return e?CM(e,i):null},[i])}async function DM(){try{const i=await fetch("/api/settings");if(i.ok)return(await i.json())?.workflow?.relay_mode??!1}catch{}return!1}function AM(i){const{send:e}=ao(),n=S.useCallback(y=>{console.log("[QuickActions] sendMessage called:",y),e(y,[])},[e]),{onAction:r}=i,[l,u]=S.useState(!1),[p,a]=S.useState(!1),c="message"in i?i.message:void 0,f="actions"in i?i.actions:void 0,v=EM(c?.content);S.useEffect(()=>{u(!1)},[c?.timestamp]),S.useEffect(()=>{DM().then(a)},[]),S.useEffect(()=>{const y=()=>{u(!0)};return window.addEventListener("cyclist:user-submit",y),()=>{window.removeEventListener("cyclist:user-submit",y)}},[]),S.useEffect(()=>{if(v?.type==="handoff"&&p&&v.value){const y=setTimeout(()=>{n(v.value),u(!0),r?.(v.value)},100);return()=>clearTimeout(y)}if(v?.type==="invoke"&&v.value){const y=setTimeout(()=>{n(v.value),u(!0),r?.(v.value)},100);return()=>clearTimeout(y)}},[v,p,r]),S.useEffect(()=>{if(v?.type==="open"&&v.responses&&v.responses.length>0){const y=v.responses[0];window.dispatchEvent(new CustomEvent("cyclist:suggest-prompt",{detail:{prompt:y}}))}},[v]);const m=S.useCallback(y=>{console.log("[QuickActions] Button clicked:",y),u(!0),n(y),r?.(y)},[r]);return f&&f.length>0?d.jsx("div",{className:"quick-actions",children:d.jsx("div",{className:"quick-actions-buttons",children:f.map(y=>d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m(y.command),disabled:l,"aria-label":`${y.label}: ${y.command}`,children:y.label},y.command))})}):!v||v.type==="open"||v.type==="continue"?null:v.type==="invoke"?d.jsx("div",{className:"quick-actions",children:d.jsxs("span",{className:"auto-invoke-status",children:["Invoking ",v.value,"..."]})}):v.type==="handoff"&&p?d.jsx("div",{className:"quick-actions",children:d.jsxs("span",{className:"auto-invoke-status",children:["Handing off to ",v.value,"..."]})}):d.jsxs("div",{className:"quick-actions",children:[v.type==="handoff"&&v.responses&&d.jsx("div",{className:"quick-actions-buttons",children:v.responses.map(y=>d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m(y),disabled:l,"aria-label":`Continue with ${y}`,children:y},y))}),v.type==="yesno"&&d.jsxs("div",{className:"quick-actions-buttons",children:[d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m("Yes"),disabled:l,"aria-label":"Answer Yes",children:"Yes"}),d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m("No"),disabled:l,"aria-label":"Answer No",children:"No"})]}),v.type==="choices"&&v.choices&&d.jsx("div",{className:"quick-actions-buttons",children:v.choices.map(y=>d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m(y.text),disabled:l,"aria-label":`Choose option ${y.number}: ${y.text}`,children:y.text},y.number))})]})}var kM="Separator",Ty="horizontal",TM=["horizontal","vertical"],Nw=S.forwardRef((i,e)=>{const{decorative:n,orientation:r=Ty,...l}=i,u=RM(r)?r:Ty,a=n?{role:"none"}:{"aria-orientation":u==="vertical"?u:void 0,role:"separator"};return d.jsx(Wi.div,{"data-orientation":u,...a,...l,ref:e})});Nw.displayName=kM;function RM(i){return TM.includes(i)}var Ow=Nw;const Rt=S.forwardRef(({className:i,orientation:e="horizontal",decorative:n=!0,...r},l)=>d.jsx(Ow,{ref:l,decorative:n,orientation:e,className:we("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",i),...r}));Rt.displayName=Ow.displayName;const NM=["<command-message>","<command-name>","Base directory for this skill:","Launching skill:"],OM=[/^```bash\s*\npf agent start\b/,/^pf agent start\b/,/^<purpose>/,/^<when-to-use>/,/^<execution>/,/^<critical>\s*\n/],ac={sm:"Scrum Master",tea:"Test Engineer",dev:"Developer",reviewer:"Reviewer",architect:"Architect",pm:"Product Manager","tech-writer":"Tech Writer","ux-designer":"UX Designer",devops:"DevOps",orchestrator:"Orchestrator"};function jM(i){if(!i||typeof i!="string")return!1;if(NM.some(n=>i.includes(n)))return!0;const e=i.trimStart();return OM.some(n=>n.test(e))}function MM(i){if(!i||typeof i!="string")return null;const e=i.match(/<command-name>\/?([^<]+)<\/command-name>/);if(e){const u=e[1].trim();return ac[u]||u}const n=i.match(/<command-message>([^<]+)<\/command-message>/);if(n){const u=n[1].trim();return ac[u]||u}const r=i.match(/pf agent start\s+"([^"]+)"/);if(r){const u=r[1].trim();return ac[u]||u}const l=i.match(/Launching skill:\s*(\S+)/);if(l){const u=l[1].trim();return ac[u]||u}return null}function Ry(i){return i.length===0?"stack-empty":`stack-${i[0].tool_id}`}function LM(i){const e=[];let n=[];for(const r of i)if(r.type==="tool_use")n.push({type:"tool_use",tool_name:r.tool_name||"",tool_id:r.tool_id||"",input:r.input||{},timestamp:r.timestamp,isStreaming:r.isStreaming});else{if(r.type==="tool_result")continue;if(n.length>=1){const l=n[n.length-1];e.push({stackId:Ry(n),tools:[...n],count:n.length,isActive:l.isStreaming===!0,timestamp:n[0].timestamp})}n=[]}if(n.length>=1){const r=n[n.length-1];e.push({stackId:Ry(n),tools:[...n],count:n.length,isActive:r.isStreaming===!0,timestamp:n[0].timestamp})}return e}function lf(){const i=document.documentElement.getAttribute("data-variant");return i==="light"||i==="dark"?i:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function jw(){const[i,e]=S.useState(lf);return S.useEffect(()=>{const n=new MutationObserver(()=>{e(lf())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["data-variant"]});const r=()=>e(lf());return window.addEventListener("presetChange",r),()=>{n.disconnect(),window.removeEventListener("presetChange",r)}},[]),i}const Ny=2e3;function Mw(){const[i,e]=S.useState(null),[n,r]=S.useState(null),[l,u]=S.useState(null),[p,a]=S.useState(!0),[c,f]=S.useState(null),v=S.useRef({context:!1,stats:!1,projectInfo:!1}),m=S.useCallback(()=>{const y=v.current;y.context&&y.stats&&y.projectInfo&&a(!1)},[]);return S.useEffect(()=>{let y=null,C=null,R=!0;const E=()=>{const g=window.location.protocol==="https:"?"wss:":"ws:";y=new WebSocket(`${g}//${window.location.host}/ws/context`),y.onopen=()=>{console.log("[useStatsStrip] Context WebSocket connected")},y.onmessage=b=>{try{const _=JSON.parse(b.data);if(_.type==="init"||_.type==="update"){const x=_.context;x&&e({percent:x.percent??0,used:x.tokens??void 0,total:x.available?(x.tokens??0)+x.available:void 0}),v.current.context||(v.current.context=!0,m())}}catch(_){console.error("[useStatsStrip] Failed to parse context message:",_)}},y.onclose=()=>{R&&(C=setTimeout(E,Ny))},y.onerror=b=>{console.error("[useStatsStrip] Context WebSocket error:",b),y?.close()}};return E(),()=>{R=!1,C&&clearTimeout(C),y?.close()}},[m]),S.useEffect(()=>{let y=null,C=null,R=!0;const E=()=>{const g=window.location.protocol==="https:"?"wss:":"ws:";y=new WebSocket(`${g}//${window.location.host}/ws/stats`),y.onopen=()=>{console.log("[useStatsStrip] Stats WebSocket connected")},y.onmessage=b=>{try{const _=JSON.parse(b.data);r({model:_.model??null}),_.pwd&&u(x=>({pwd:_.pwd,jiraEmail:x?.jiraEmail??null,githubUsername:x?.githubUsername??null})),v.current.stats||(v.current.stats=!0,m())}catch(_){console.error("[useStatsStrip] Failed to parse stats message:",_)}},y.onclose=()=>{R&&(C=setTimeout(E,Ny))},y.onerror=b=>{console.error("[useStatsStrip] Stats WebSocket error:",b),y?.close()}};return E(),()=>{R=!1,C&&clearTimeout(C),y?.close()}},[m]),S.useEffect(()=>{(async()=>{try{const C=await fetch("/api/identity");if(C.ok){const R=await C.json();u(E=>({pwd:E?.pwd??"",jiraEmail:R.jiraEmail??null,githubUsername:R.githubUsername??null}))}}catch(C){console.error("[useStatsStrip] Failed to fetch identity:",C),f(C instanceof Error?C:new Error("Failed to fetch identity"))}finally{v.current.projectInfo=!0,m()}})()},[m]),{context:i,stats:n,projectInfo:l,isLoading:p,error:c}}const PM={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9"},zM={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC"};function Oy(i){return new Date(i).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function BM(i){if("isToolStack"in i||"messages"in i)return"agent";const e=i;return e.type==="context_cleared"?"system":e.type==="user"||e.type==="bell_injected"?"user":"agent"}function IM({messages:i}){const e=S.useRef(null),[n,r]=S.useState(!0),{persona:l}=du(),u=jw(),{projectInfo:p}=Mw(),a=S.useRef(new Map),c=S.useCallback(g=>{r(g)},[]),f=S.useCallback(()=>{e.current?.scrollToBottom("smooth")},[]),v=S.useMemo(()=>{for(let g=i.length-1;g>=0;g--)if(i[g].type==="agent"&&!i[g].isStreaming)return i[g];return null},[i]),{turns:m,toolResults:y,lastAgentItemIndex:C}=S.useMemo(()=>{const g=new Map;for(const I of i)I.type==="tool_result"&&I.tool_id&&g.set(I.tool_id,I);const b=[],_=new Map;let x=!1;for(const I of i)if(I.type!=="tool_result"){if(I.type==="user"&&jM(I.content)){const z=MM(I.content);z&&!x&&(x=!0,b.push({...I,content:z}));continue}if(I.type==="user"&&(x=!1),I.parent_id){let z=_.get(I.parent_id);z||(z={parent_id:I.parent_id,type:I.subagent_type||"unknown",name:I.subagent_name||"unnamed",messages:[]},_.set(I.parent_id,z)),z.messages.push(I);continue}b.push(I)}const A=LM(b),D=new Map;for(const I of A)for(const z of I.tools)D.set(z.tool_id,I);const N=[],O=new Set,T=new Set;for(const I of b)if(I.type==="tool_use"&&I.tool_id&&D.has(I.tool_id)){const z=D.get(I.tool_id);O.has(z.stackId)||(O.add(z.stackId),N.push({isToolStack:!0,stack:z}))}else N.push(I);for(const[,I]of _)T.has(I.parent_id)||(T.add(I.parent_id),N.push(I));let j=-1;for(let I=N.length-1;I>=0;I--){const z=N[I];if(!("isToolStack"in z)&&!("messages"in z)&&z.type==="agent"){j=I;break}}const H=[];for(const I of N){const z=BM(I),U=H[H.length-1];U&&U.speaker===z?U.items.push(I):H.push({speaker:z,items:[I],timestamp:"timestamp"in I?I.timestamp:Date.now()})}return{turns:H,toolResults:g,lastAgentItemIndex:j}},[i]),R=(g,b,_)=>{if("isToolStack"in g)return d.jsx(pM,{stack:g.stack,toolResults:y},`stack-${g.stack.stackId}`);if("messages"in g&&"parent_id"in g){const A=g,D=a.current.get(A.parent_id)??!0;return d.jsx(bM,{type:A.type,name:A.name,messages:A.messages,defaultCollapsed:D,onCollapseChange:N=>a.current.set(A.parent_id,N)},`subagent-${A.parent_id}`)}const x=g;if(x.type==="tool_use"&&x.tool_name&&x.tool_id){if(x.tool_name==="AskUserQuestion")return null;const A=y.get(x.tool_id);return d.jsx($p,{toolUse:{type:"tool_use",tool_name:x.tool_name,tool_id:x.tool_id,input:x.input||{},timestamp:x.timestamp},result:A?{type:"tool_result",tool_id:A.tool_id,content:A.content||"",timestamp:A.timestamp,is_error:A.is_error,durationMs:A.durationMs}:void 0},`tool-${x.tool_id}`)}return d.jsx(kw,{message:x,isLastAgentMessage:b===C,isFirstInTurn:_},`msg-${b}-${x.timestamp}`)};if(i.length===0)return d.jsx("div",{"data-testid":"message-view",className:"message-view",children:d.jsx("div",{className:"message-view-empty",children:d.jsxs("div",{children:[d.jsx("img",{src:u==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",style:{height:"2.5rem",opacity:.6,display:"block",margin:"0 auto 0.5rem"}}),d.jsxs("div",{children:["Type ",d.jsx("code",{style:{background:"var(--bg-tertiary, #0f0f1a)",padding:"2px 6px",borderRadius:"3px",fontFamily:"var(--font-mono, monospace)"},children:"/sm"})," to start"]})]})})});let E=0;return d.jsxs("div",{"data-testid":"message-view",className:"message-view",role:"log","aria-live":"polite",children:[d.jsx(Aw,{ref:e,onScrollChange:c,autoScroll:n,children:m.map((g,b)=>{if(g.speaker==="system")return g.items.forEach(()=>E++),d.jsx("div",{className:"turn-group turn-system",children:d.jsxs("div",{className:"context-cleared-bar",children:[d.jsx(Rt,{className:"context-cleared-line"}),d.jsx("span",{className:"context-cleared-label",children:"Context cleared"}),d.jsx("span",{className:"context-cleared-time",children:Oy(g.timestamp)}),d.jsx(Rt,{className:"context-cleared-line"})]})},`turn-${b}`);let _=!1;const x=l?.character||"Agent",A=l?.role||null,D=A?zM[A]||A:null,N=A?PM[A]||"#e879f9":void 0,O=p?.githubUsername||"You";return d.jsxs("div",{className:`turn-group turn-${g.speaker}`,children:[d.jsxs("div",{className:"turn-label",children:[d.jsx("span",{className:"turn-speaker",children:g.speaker==="user"?O:x}),g.speaker==="agent"&&D&&d.jsx(Ke,{variant:"default",className:"turn-role-badge",style:{backgroundColor:N},children:D}),d.jsx("span",{className:"turn-timestamp",children:Oy(g.timestamp)})]}),g.items.map(T=>{const j=E++,H=!("isToolStack"in T)&&!("messages"in T)&&T.type!=="tool_use",I=H&&!_;return H&&(_=!0),R(T,j,I)})]},`turn-${b}`)})}),v&&d.jsx(AM,{message:v}),d.jsx("div",{"data-testid":"auto-scroll-indicator","data-active":n.toString(),className:"auto-scroll-indicator",style:{display:"none"}}),d.jsx(De,{variant:"ghost",size:"icon","data-testid":"scroll-to-bottom-button",className:"scroll-to-bottom-button",onClick:f,style:{visibility:n?"hidden":"visible"},children:"↓"})]})}const jy="cyclist-command-history",HM=100;function FM(){const[i,e]=S.useState(()=>{try{const f=localStorage.getItem(jy);return f?JSON.parse(f):[]}catch{return[]}}),n=S.useRef(-1),r=S.useRef(""),l=S.useCallback(f=>{try{localStorage.setItem(jy,JSON.stringify(f))}catch{}},[]),u=S.useCallback(f=>{f.trim()&&e(v=>{if(v.length>0&&v[v.length-1]===f)return v;const m=[...v,f];return m.length>HM&&m.shift(),l(m),m})},[l]),p=S.useCallback(f=>{if(i.length===0)return null;if(n.current===-1)r.current=f,n.current=i.length-1;else if(n.current>0)n.current--;else return null;return i[n.current]},[i]),a=S.useCallback(()=>{if(n.current===-1)return null;if(n.current++,n.current>=i.length){n.current=-1;const f=r.current;return r.current="",f}return i[n.current]},[i]),c=S.useCallback(()=>{n.current=-1,r.current=""},[]);return{addToHistory:u,navigateUp:p,navigateDown:a,resetNavigation:c}}const Lw=[{name:"/add",description:"Add files to context"},{name:"/architect",description:"System Architect - Technical design and architecture"},{name:"/ba",description:"Business Analyst - Requirements discovery and stakeholder analysis"},{name:"/brainstorming",description:"Structured problem-solving brainstorm session"},{name:"/bug",description:"Report a bug"},{name:"/check",description:"Run quality gates (lint, type check, tests) before handoff"},{name:"/chore",description:"Quick commit for small changes without full git-cleanup ceremony"},{name:"/clear",description:"Clear conversation history"},{name:"/close-epic",description:"Close an epic - verify completion, update status, and archive context"},{name:"/compact",description:"Toggle compact mode"},{name:"/config",description:"Show configuration"},{name:"/continue-session",description:"Resume work from a saved checkpoint after context circuit breaker"},{name:"/cost",description:"Show session cost"},{name:"/create-branches-from-story",description:"Create feature branches in both repos from a story"},{name:"/dev",description:"Developer - Feature implementation and coding"},{name:"/devops",description:"DevOps Engineer - Infrastructure and deployment automation"},{name:"/doctor",description:"Check system health"},{name:"/fix-blocker",description:"Quick alias for /patch - fix blocking issue during story work"},{name:"/git-cleanup",description:"Clean up git repos by organizing changes into proper commits/branches by initiative"},{name:"/health-check",description:"Check Pennyfarthing installation health and apply updates"},{name:"/help",description:"Show available commands"},{name:"/init",description:"Initialize CLAUDE.md"},{name:"/login",description:"Authenticate with Anthropic"},{name:"/logout",description:"Clear authentication"},{name:"/memory",description:"Edit CLAUDE.md memory"},{name:"/model",description:"Switch Claude model"},{name:"/new-work",description:"Start the next available story from the sprint backlog"},{name:"/orchestrator",description:"Orchestrator - Coordinator of all agents and meta operations"},{name:"/parallel-work",description:"Start parallel work in a new worktree"},{name:"/party-mode",description:"Free-form creative brainstorming with all agents"},{name:"/patch",description:"Interrupt-driven bug fix during active story work"},{name:"/permissions",description:"View/edit permissions"},{name:"/pm",description:"Product Manager - Strategic planning and prioritization"},{name:"/pr-comments",description:"View PR comments"},{name:"/prime",description:"Load essential project context at agent activation"},{name:"/release",description:"Interactive stepped release with verification gates"},{name:"/repo-status",description:"Check git status of all project repos"},{name:"/retro",description:"Facilitate a sprint retrospective"},{name:"/review",description:"Start code review"},{name:"/reviewer",description:"Code Reviewer - Critical code review and quality enforcement"},{name:"/run-ci",description:"Detect and run CI locally"},{name:"/setup",description:"/setup - Interactive Project Setup"},{name:"/sm",description:"Scrum Master - Story coordination and sprint management"},{name:"/sprint",description:"Sprint status, backlog, and story management - check status, find work, archive completed stories"},{name:"/sprint-planning",description:"Facilitate sprint planning session"},{name:"/standalone",description:"Wrap current changes into a standalone Jira story, branch, PR, and merge"},{name:"/start-epic",description:"Start an epic - move to current sprint and generate tech context"},{name:"/status",description:"Show session status"},{name:"/sync-epic-to-jira",description:"Sync Pennyfarthing epic to Jira MSSCI project using jira CLI"},{name:"/sync-work-with-sprint",description:"Sync Pennyfarthing work session with unified sprint status"},{name:"/tea",description:"Test Engineer/Architect - Test strategy and TDD"},{name:"/tech-writer",description:"Technical Writer - Documentation creation and maintenance"},{name:"/terminal-setup",description:"Configure terminal"},{name:"/theme",description:"Manage persona themes - list, show, set, create, or interactive wizard"},{name:"/update-domain-docs",description:"Update CLAUDE-*.md domain documentation files based on current codebase"},{name:"/ux-designer",description:"UX Designer - User experience design and UI patterns"},{name:"/vim",description:"Toggle vim mode"},{name:"/work",description:"Resume work or start new - smart entry point that picks up where you left off"},{name:"/workflow",description:"List available workflows, show current workflow details, and switch workflows mid-session. Use when checking available workflow types (TDD, trivial, agent-docs), viewing current workflow phase, switching to a different workflow pattern, or managing BikeLane stepped workflows."}].sort((i,e)=>i.name.localeCompare(e.name)),Pw="cyclist:command-frequency";function zw(){if(typeof localStorage>"u")return{};try{const i=localStorage.getItem(Pw);return i?JSON.parse(i):{}}catch{return{}}}function Bw(i){if(typeof localStorage>"u")return;const e=zw();e[i]=(e[i]||0)+1,localStorage.setItem(Pw,JSON.stringify(e))}function GM(i){const e=i.toLowerCase(),n=zw();return Lw.filter(r=>r.name.toLowerCase().startsWith(e)).sort((r,l)=>{const u=n[r.name]||0,p=n[l.name]||0;return p!==u?p-u:r.name.localeCompare(l.name)})}function UM(i){const e=S.useMemo(()=>Lw,[i]),[n,r]=S.useState({visible:!1,commands:[],selectedIndex:0,prefix:""}),l=S.useCallback(m=>GM(m),[e,i]),u=S.useCallback(m=>{const y=l(m);r({visible:!0,commands:y,selectedIndex:0,prefix:m})},[l]),p=S.useCallback(()=>{r({visible:!1,commands:[],selectedIndex:0,prefix:""})},[]),a=S.useCallback(m=>{const y=l(m);y.length===0?p():r(C=>({...C,commands:y,selectedIndex:0,prefix:m}))},[l,p]),c=S.useCallback(()=>{r(m=>{if(m.commands.length===0)return m;const y=m.selectedIndex<=0?m.commands.length-1:m.selectedIndex-1;return{...m,selectedIndex:y}})},[]),f=S.useCallback(()=>{r(m=>{if(m.commands.length===0)return m;const y=m.selectedIndex>=m.commands.length-1?0:m.selectedIndex+1;return{...m,selectedIndex:y}})},[]),v=S.useCallback(()=>{if(!n.visible||n.commands.length===0)return null;const m=n.commands[n.selectedIndex];return p(),m?.name&&Bw(m.name),m?.name||null},[n,p]);return{state:n,showCompletion:u,hideCompletion:p,updateCompletion:a,navigateUp:c,navigateDown:f,selectCurrent:v,isVisible:n.visible}}function Iw(i){const e=i+"CollectionProvider",[n,r]=pi(e),[l,u]=n(e,{collectionRef:{current:null},itemMap:new Map}),p=E=>{const{scope:g,children:b}=E,_=ge.useRef(null),x=ge.useRef(new Map).current;return d.jsx(l,{scope:g,itemMap:x,collectionRef:_,children:b})};p.displayName=e;const a=i+"CollectionSlot",c=Zr(a),f=ge.forwardRef((E,g)=>{const{scope:b,children:_}=E,x=u(a,b),A=Ge(g,x.collectionRef);return d.jsx(c,{ref:A,children:_})});f.displayName=a;const v=i+"CollectionItemSlot",m="data-radix-collection-item",y=Zr(v),C=ge.forwardRef((E,g)=>{const{scope:b,children:_,...x}=E,A=ge.useRef(null),D=Ge(g,A),N=u(v,b);return ge.useEffect(()=>(N.itemMap.set(A,{ref:A,...x}),()=>{N.itemMap.delete(A)})),d.jsx(y,{[m]:"",ref:D,children:_})});C.displayName=v;function R(E){const g=u(i+"CollectionConsumer",E);return ge.useCallback(()=>{const _=g.collectionRef.current;if(!_)return[];const x=Array.from(_.querySelectorAll(`[${m}]`));return Array.from(g.itemMap.values()).sort((N,O)=>x.indexOf(N.ref.current)-x.indexOf(O.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:p,Slot:f,ItemSlot:C},R,r]}var WM=S.createContext(void 0);function hu(i){const e=S.useContext(WM);return i||e||"ltr"}var cf="rovingFocusGroup.onEntryFocus",VM={bubbles:!1,cancelable:!0},Aa="RovingFocusGroup",[Uf,Hw,$M]=Iw(Aa),[qM,Fw]=pi(Aa,[$M]),[YM,KM]=qM(Aa),Gw=S.forwardRef((i,e)=>d.jsx(Uf.Provider,{scope:i.__scopeRovingFocusGroup,children:d.jsx(Uf.Slot,{scope:i.__scopeRovingFocusGroup,children:d.jsx(XM,{...i,ref:e})})}));Gw.displayName=Aa;var XM=S.forwardRef((i,e)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:l=!1,dir:u,currentTabStopId:p,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:c,onEntryFocus:f,preventScrollOnEntryFocus:v=!1,...m}=i,y=S.useRef(null),C=Ge(e,y),R=hu(u),[E,g]=Ni({prop:p,defaultProp:a??null,onChange:c,caller:Aa}),[b,_]=S.useState(!1),x=Wt(f),A=Hw(n),D=S.useRef(!1),[N,O]=S.useState(0);return S.useEffect(()=>{const T=y.current;if(T)return T.addEventListener(cf,x),()=>T.removeEventListener(cf,x)},[x]),d.jsx(YM,{scope:n,orientation:r,dir:R,loop:l,currentTabStopId:E,onItemFocus:S.useCallback(T=>g(T),[g]),onItemShiftTab:S.useCallback(()=>_(!0),[]),onFocusableItemAdd:S.useCallback(()=>O(T=>T+1),[]),onFocusableItemRemove:S.useCallback(()=>O(T=>T-1),[]),children:d.jsx(Ne.div,{tabIndex:b||N===0?-1:0,"data-orientation":r,...m,ref:C,style:{outline:"none",...i.style},onMouseDown:Ee(i.onMouseDown,()=>{D.current=!0}),onFocus:Ee(i.onFocus,T=>{const j=!D.current;if(T.target===T.currentTarget&&j&&!b){const H=new CustomEvent(cf,VM);if(T.currentTarget.dispatchEvent(H),!H.defaultPrevented){const I=A().filter(F=>F.focusable),z=I.find(F=>F.active),U=I.find(F=>F.id===E),q=[z,U,...I].filter(Boolean).map(F=>F.ref.current);Vw(q,v)}}D.current=!1}),onBlur:Ee(i.onBlur,()=>_(!1))})})}),Uw="RovingFocusGroupItem",Ww=S.forwardRef((i,e)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:l=!1,tabStopId:u,children:p,...a}=i,c=Ht(),f=u||c,v=KM(Uw,n),m=v.currentTabStopId===f,y=Hw(n),{onFocusableItemAdd:C,onFocusableItemRemove:R,currentTabStopId:E}=v;return S.useEffect(()=>{if(r)return C(),()=>R()},[r,C,R]),d.jsx(Uf.ItemSlot,{scope:n,id:f,focusable:r,active:l,children:d.jsx(Ne.span,{tabIndex:m?0:-1,"data-orientation":v.orientation,...a,ref:e,onMouseDown:Ee(i.onMouseDown,g=>{r?v.onItemFocus(f):g.preventDefault()}),onFocus:Ee(i.onFocus,()=>v.onItemFocus(f)),onKeyDown:Ee(i.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){v.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const b=QM(g,v.orientation,v.dir);if(b!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let x=y().filter(A=>A.focusable).map(A=>A.ref.current);if(b==="last")x.reverse();else if(b==="prev"||b==="next"){b==="prev"&&x.reverse();const A=x.indexOf(g.currentTarget);x=v.loop?eL(x,A+1):x.slice(A+1)}setTimeout(()=>Vw(x))}}),children:typeof p=="function"?p({isCurrentTabStop:m,hasTabStop:E!=null}):p})})});Ww.displayName=Uw;var ZM={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function JM(i,e){return e!=="rtl"?i:i==="ArrowLeft"?"ArrowRight":i==="ArrowRight"?"ArrowLeft":i}function QM(i,e,n){const r=JM(i.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return ZM[r]}function Vw(i,e=!1){const n=document.activeElement;for(const r of i)if(r===n||(r.focus({preventScroll:e}),document.activeElement!==n))return}function eL(i,e){return i.map((n,r)=>i[(e+r)%i.length])}var tL=Gw,iL=Ww,$w="Toggle",qp=S.forwardRef((i,e)=>{const{pressed:n,defaultPressed:r,onPressedChange:l,...u}=i,[p,a]=Ni({prop:n,onChange:l,defaultProp:r??!1,caller:$w});return d.jsx(Ne.button,{type:"button","aria-pressed":p,"data-state":p?"on":"off","data-disabled":i.disabled?"":void 0,...u,ref:e,onClick:Ee(i.onClick,()=>{i.disabled||a(!p)})})});qp.displayName=$w;var qw=qp,hs="ToggleGroup",[Yw]=pi(hs,[Fw]),Kw=Fw(),Yp=ge.forwardRef((i,e)=>{const{type:n,...r}=i;if(n==="single"){const l=r;return d.jsx(nL,{...l,ref:e})}if(n==="multiple"){const l=r;return d.jsx(sL,{...l,ref:e})}throw new Error(`Missing prop \`type\` expected on \`${hs}\``)});Yp.displayName=hs;var[Xw,Zw]=Yw(hs),nL=ge.forwardRef((i,e)=>{const{value:n,defaultValue:r,onValueChange:l=()=>{},...u}=i,[p,a]=Ni({prop:n,defaultProp:r??"",onChange:l,caller:hs});return d.jsx(Xw,{scope:i.__scopeToggleGroup,type:"single",value:ge.useMemo(()=>p?[p]:[],[p]),onItemActivate:a,onItemDeactivate:ge.useCallback(()=>a(""),[a]),children:d.jsx(Jw,{...u,ref:e})})}),sL=ge.forwardRef((i,e)=>{const{value:n,defaultValue:r,onValueChange:l=()=>{},...u}=i,[p,a]=Ni({prop:n,defaultProp:r??[],onChange:l,caller:hs}),c=ge.useCallback(v=>a((m=[])=>[...m,v]),[a]),f=ge.useCallback(v=>a((m=[])=>m.filter(y=>y!==v)),[a]);return d.jsx(Xw,{scope:i.__scopeToggleGroup,type:"multiple",value:p,onItemActivate:c,onItemDeactivate:f,children:d.jsx(Jw,{...u,ref:e})})});Yp.displayName=hs;var[rL,oL]=Yw(hs),Jw=ge.forwardRef((i,e)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:l=!0,orientation:u,dir:p,loop:a=!0,...c}=i,f=Kw(n),v=hu(p),m={role:"group",dir:v,...c};return d.jsx(rL,{scope:n,rovingFocus:l,disabled:r,children:l?d.jsx(tL,{asChild:!0,...f,orientation:u,dir:v,loop:a,children:d.jsx(Ne.div,{...m,ref:e})}):d.jsx(Ne.div,{...m,ref:e})})}),Lc="ToggleGroupItem",Qw=ge.forwardRef((i,e)=>{const n=Zw(Lc,i.__scopeToggleGroup),r=oL(Lc,i.__scopeToggleGroup),l=Kw(i.__scopeToggleGroup),u=n.value.includes(i.value),p=r.disabled||i.disabled,a={...i,pressed:u,disabled:p},c=ge.useRef(null);return r.rovingFocus?d.jsx(iL,{asChild:!0,...l,focusable:!p,active:u,ref:c,children:d.jsx(My,{...a,ref:e})}):d.jsx(My,{...a,ref:e})});Qw.displayName=Lc;var My=ge.forwardRef((i,e)=>{const{__scopeToggleGroup:n,value:r,...l}=i,u=Zw(Lc,n),p={role:"radio","aria-checked":i.pressed,"aria-pressed":void 0},a=u.type==="single"?p:void 0;return d.jsx(qp,{...a,...l,ref:e,onPressedChange:c=>{c?u.onItemActivate(r):u.onItemDeactivate(r)}})}),ex=Yp,tx=Qw;const ix=ep("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}}),aL=S.forwardRef(({className:i,variant:e,size:n,...r},l)=>d.jsx(qw,{ref:l,className:we(ix({variant:e,size:n,className:i})),...r}));aL.displayName=qw.displayName;const nx=S.createContext({size:"default",variant:"default"}),sx=S.forwardRef(({className:i,variant:e,size:n,children:r,...l},u)=>d.jsx(ex,{ref:u,className:we("flex items-center justify-center gap-1",i),...l,children:d.jsx(nx.Provider,{value:{variant:e,size:n},children:r})}));sx.displayName=ex.displayName;const rx=S.forwardRef(({className:i,children:e,variant:n,size:r,...l},u)=>{const p=S.useContext(nx);return d.jsx(tx,{ref:u,className:we(ix({variant:p.variant||n,size:p.size||r}),i),...l,children:e})});rx.displayName=tx.displayName;const Ly=["plan","manual","accept"],uf={plan:"Plan",manual:"Manual",accept:"Accept"},Py={plan:"Read-only exploration mode",manual:"Ask for permission before actions",accept:"Auto-accept file edits"},lL={plan:"plan",manual:"default",accept:"acceptEdits"},cL={plan:"plan",default:"manual",acceptEdits:"accept"},zy={1:"plan",2:"manual",3:"accept"};function uL(i){S.useEffect(()=>{const e=n=>{(n.metaKey||n.ctrlKey)&&zy[n.key]&&(n.preventDefault(),i(zy[n.key]))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[i])}function dL(){const[i,e]=S.useState("manual"),[n,r]=S.useState(!0),l=S.useRef(null);S.useEffect(()=>{const a=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/claude`,c=new WebSocket(a);l.current=c,c.onopen=()=>{c.send(JSON.stringify({type:"getMode"}))},c.onmessage=v=>{try{const m=JSON.parse(v.data);if(m.type==="mode"&&m.mode){const y=cL[m.mode]||"manual";e(y),r(!1),console.log("[ModeSwitch] Mode synced:",m.mode,"->",y)}}catch(m){console.error("[ModeSwitch] Failed to parse mode response:",m)}},c.onerror=()=>{r(!1)};const f=setTimeout(()=>{n&&r(!1)},2e3);return()=>{clearTimeout(f),c.readyState===WebSocket.OPEN&&c.close(),l.current=null}},[]);const u=S.useCallback(p=>{const a=lL[p];l.current&&l.current.readyState===WebSocket.OPEN?(l.current.send(JSON.stringify({type:"setMode",mode:a})),e(p),console.log("[ModeSwitch] Mode set to:",p,"->",a)):(e(p),console.warn("[ModeSwitch] WebSocket not connected, mode set locally only"))},[]);return{mode:i,setMode:u,isLoading:n}}function hL({mode:i,defaultMode:e="manual",onModeChange:n,className:r="",disabled:l=!1}){const[u,p]=S.useState(e),[a,c]=S.useState(!1),f=i??u;S.useEffect(()=>{const C=window.matchMedia("(prefers-reduced-motion: reduce)");c(C.matches);const R=E=>{c(E.matches)};return C.addEventListener("change",R),()=>C.removeEventListener("change",R)},[]);const v=Ly.indexOf(f),m=S.useCallback(C=>{l||(i||p(C),n?.(C))},[i,l,n]),y=S.useCallback(C=>{C&&m(C)},[m]);return d.jsxs("div",{className:we("mode-switch",l&&"mode-switch--disabled",a&&"reduced-motion",r),"data-testid":"mode-switch",style:a?{transition:"none"}:void 0,children:[d.jsx("div",{className:"mode-switch__highlight","data-testid":"mode-highlight",style:{transform:`translateX(${v*100}%)`,transition:a?"none":void 0},"data-mode":f}),d.jsx(wt,{delayDuration:400,children:d.jsx(sx,{type:"single",value:f,onValueChange:y,disabled:l,className:"relative z-[1] gap-0","aria-label":"Permission mode",children:Ly.map(C=>{const R=f===C;return d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(rx,{value:C,"data-mode":C,"data-testid":`mode-${C}`,"aria-label":`${uf[C]} mode: ${Py[C]}`,className:we("mode-option",R&&"active"),children:uf[C]})}),d.jsx(Oe,{side:"bottom",children:Py[C]})]},C)})})}),d.jsx("div",{className:"visually-hidden",role:"status","aria-live":"polite",children:`${uf[f]} mode selected`})]})}const lc=["image/png","image/jpeg","image/gif","image/webp"],fL=20*1024*1024;function pL({commands:i,selectedIndex:e,visible:n,onSelect:r}){return!n||i.length===0?null:d.jsx("div",{className:"completion-popup","data-testid":"completion-popup",children:i.map((l,u)=>d.jsxs("div",{className:`completion-item ${u===e?"selected":""}`,onClick:()=>r(u),"data-testid":`completion-item-${u}`,children:[d.jsx("span",{className:"completion-name",children:l.name}),d.jsx("span",{className:"completion-desc",children:l.description})]},l.name))})}function mL(i){return i?i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"):""}function gL({queue:i,bellMode:e,onRemove:n,onClear:r,onInject:l}){return i.length===0?null:d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"queue-display","data-testid":"queue-display",children:[d.jsxs("div",{className:"queue-header",children:[d.jsxs("span",{className:"queue-count",children:[i.length," queued"]}),e&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"secondary",className:"queue-mode-badge bell-mode",children:"🔔"})}),d.jsx(Oe,{children:"Bell mode active - messages inject via hook"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"sm",type:"button",className:"queue-clear-btn",onClick:r,children:"Clear"})}),d.jsx(Oe,{children:"Clear all queued messages"})]})]}),d.jsx("ul",{className:"queue-list",children:i.map((u,p)=>{const a=u.text.length>60?u.text.substring(0,60)+"...":u.text,c=u.images&&u.images.length>0;return d.jsxs("li",{className:"queue-item","data-testid":`queue-item-${p}`,children:[d.jsx("span",{className:"queue-item-text",children:mL(a)}),c&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs(Ke,{variant:"outline",className:"queue-image-indicator",children:["📎",u.images.length]})}),d.jsx(Oe,{children:`${u.images.length} image(s) attached`})]}),d.jsxs("div",{className:"queue-item-actions",children:[l&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:"queue-item-inject",onClick:()=>l(p),children:"▶"})}),d.jsx(Oe,{children:"Send now (abort current and send this message)"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:"queue-item-remove",onClick:()=>n(p),children:"×"})}),d.jsx(Oe,{children:"Remove from queue"})]})]})]},p)})})]})})}function vL({images:i,onRemove:e}){return i.length===0?null:d.jsx(wt,{delayDuration:300,children:d.jsx("div",{className:"image-preview","data-testid":"image-preview",children:i.map((n,r)=>d.jsxs("div",{className:"image-preview-item",children:[d.jsx("img",{src:n.dataUrl,alt:n.filename}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:"image-remove",onClick:()=>e(r),children:"X"})}),d.jsx(Oe,{children:"Remove image"})]})]},r))})})}function _L({onSubmit:i,isProcessing:e=!1,placeholder:n,onInject:r}){const l=S.useRef(null),[u,p]=S.useState(""),[a,c]=S.useState([]),{mode:f,setMode:v}=dL();uL(v);const{addToHistory:m,navigateUp:y,navigateDown:C,resetNavigation:R}=FM(),{state:E,showCompletion:g,hideCompletion:b,updateCompletion:_,navigateUp:x,navigateDown:A,selectCurrent:D,isVisible:N}=UM(),{queue:O,queueCount:T,bellMode:j,queueMessage:H,removeFromQueue:I,clearQueue:z,setProcessing:U,resumeQueue:X}=Sw();S.useEffect(()=>{U(e)},[e,U]),S.useEffect(()=>{const Z=Q=>{p(Q.detail.prompt),l.current?.focus()};return window.addEventListener("cyclist:suggest-prompt",Z),()=>{window.removeEventListener("cyclist:suggest-prompt",Z)}},[]);const q=S.useCallback(async Z=>{let Q=null;if(Z.items){for(const ce of Z.items)if(ce.type&&lc.includes(ce.type)){Q=ce.getAsFile();break}}if(!Q&&Z.files?.length>0){for(const ce of Z.files)if(ce.type&&lc.includes(ce.type)){Q=ce;break}}return Q?Q.size>fL?(console.warn("Image too large:",Q.size),!1):new Promise(ce=>{const P=new FileReader;P.onload=()=>{const K=P.result,ie=Q.name||`Pasted Image.${Q.type.split("/")[1]||"png"}`;c(se=>[...se,{dataUrl:K,mimeType:Q.type,filename:ie}]),ce(!0)},P.onerror=()=>ce(!1),P.readAsDataURL(Q)}):!1},[]),F=S.useCallback(Z=>{c(Q=>Q.filter((ce,P)=>P!==Z))},[]),Y=S.useCallback(()=>{if(!l.current)return null;const Z=l.current.selectionStart,Q=u;let ce=Z;for(;ce>0&&Q[ce-1]!==" "&&Q[ce-1]!==`
64
- `;)ce--;const P=Q.substring(ce,Z);return P.startsWith("/")?{prefix:P,start:ce,end:Z}:null},[u]),L=S.useCallback(Z=>{const Q=Y();if(!Q){p(K=>K+Z);return}const{start:ce,end:P}=Q;p(K=>K.substring(0,ce)+Z+K.substring(P)),setTimeout(()=>{if(l.current){const K=ce+Z.length;l.current.selectionStart=l.current.selectionEnd=K}},0)},[Y]),V=S.useCallback(()=>{const Z=u.trim();if(!(!Z&&a.length===0)){if(e){H({text:Z,images:[...a]})&&(p(""),c([]),l.current?.focus());return}if(m(Z),R(),Z.startsWith("/")){const Q=Z.split(/\s/)[0];Bw(Q)}X(),window.dispatchEvent(new CustomEvent("cyclist:user-submit")),i(Z,a),p(""),c([]),l.current?.focus()}},[u,a,e,H,m,R,X,i]),$=S.useCallback(Z=>{if(Z.key==="Tab"&&!Z.shiftKey&&!Z.ctrlKey&&!Z.altKey){if(N){Z.preventDefault();const ce=D();ce&&L(ce);return}const Q=Y();if(Q){Z.preventDefault(),g(Q.prefix);return}}if(Z.key==="Escape"&&N){Z.preventDefault(),b();return}if(Z.key==="Enter"&&!Z.shiftKey){if(N){Z.preventDefault();const Q=D();Q&&L(Q);return}Z.preventDefault(),V();return}if(Z.key==="ArrowUp"&&!Z.shiftKey&&!Z.ctrlKey&&!Z.altKey){if(N){Z.preventDefault(),x();return}if(l.current?.selectionStart===0){const Q=y(u);if(Q!==null){Z.preventDefault(),p(Q);return}}}if(Z.key==="ArrowDown"&&!Z.shiftKey&&!Z.ctrlKey&&!Z.altKey){if(N){Z.preventDefault(),A();return}if(l.current?.selectionEnd===u.length){const Q=C();if(Q!==null){Z.preventDefault(),p(Q);return}}}},[N,D,L,Y,g,b,V,x,A,y,C,u]),B=S.useCallback(Z=>{const Q=Z.target.value;if(p(Q),Q==="/"&&!N){g("/");return}if(N){const ce=Y();ce?_(ce.prefix):b()}},[N,g,Y,_,b]),W=S.useCallback(async Z=>{const Q=Z.clipboardData;if(!Q)return;let ce=!1;if(Q.items){for(const P of Q.items)if(P.type&&lc.includes(P.type)){ce=!0;break}}if(!ce&&Q.files?.length>0){for(const P of Q.files)if(P.type&&lc.includes(P.type)){ce=!0;break}}ce&&(Z.preventDefault(),await q(Q))},[q]),ee=S.useCallback(Z=>{const Q=E.commands[Z];Q&&(L(Q.name),b())},[E.commands,L,b]);return d.jsxs("div",{className:"editor-container","data-testid":"editor-container",children:[d.jsx(hL,{mode:f,onModeChange:v,className:"editor-mode-switch"}),d.jsxs("div",{className:"editor-wrapper",id:"editor-wrapper",children:[d.jsx(vL,{images:a,onRemove:F}),d.jsx("textarea",{ref:l,id:"editor-textarea",className:"editor-textarea",value:u,onChange:B,onKeyDown:$,onPaste:W,placeholder:n,spellCheck:!1,autoFocus:!0,"data-testid":"editor-textarea"}),d.jsx(pL,{commands:E.commands,selectedIndex:E.selectedIndex,visible:N,onSelect:ee})]}),d.jsx(gL,{queue:O,bellMode:j,onRemove:I,onClear:z,onInject:r})]})}function bL(){const[i,e]=S.useState(null),n=S.useCallback(u=>p=>{e(u)},[]),r=S.useCallback(()=>{e(null)},[]),l=S.useCallback(u=>i===u,[i]);return{handleFocus:n,handleBlur:r,isFocused:l}}function yL({currentAgent:i,onAgentSwitch:e}){const[n,r]=S.useState(!1),[l,u]=S.useState([]),p=S.useRef(null);S.useEffect(()=>{fetch("/api/theme-agents/full").then(c=>c.ok?c.json():null).then(c=>{c?.agents&&u(c.agents)}).catch(()=>{})},[]),S.useEffect(()=>{if(!n)return;const c=f=>{p.current&&!p.current.contains(f.target)&&r(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[n]),S.useEffect(()=>{if(!n)return;const c=f=>{f.key==="Escape"&&(f.stopPropagation(),r(!1))};return document.addEventListener("keydown",c,!0),()=>document.removeEventListener("keydown",c,!0)},[n]);const a=S.useCallback(c=>{c.role!==i&&(e?.(c.role),r(!1))},[i,e]);return d.jsxs("div",{className:"agent-quick-picker-wrapper",ref:p,children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle agent-picker-toggle ${n?"active":""}`,"data-testid":"agent-quick-picker",onClick:()=>r(c=>!c),"aria-label":"Switch agent","aria-expanded":n,"aria-haspopup":"listbox",children:d.jsx(aj,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:"Switch Agent"})]}),n&&d.jsx("div",{className:"agent-quick-picker-dropdown","data-testid":"agent-quick-picker-dropdown",role:"listbox","aria-label":"Available agents",children:l.map(c=>{const f=c.role===i;return d.jsx("div",{className:`agent-quick-picker-option ${f?"current":""}`,"data-testid":`agent-option-${c.role}`,role:"option","aria-selected":f,"aria-label":`${c.role} (${c.character})`,title:c.character,onClick:()=>a(c),children:d.jsx("span",{className:"agent-option-role",children:c.role})},c.role)})})]})}function SL({isRunning:i,isStopping:e=!1,onStop:n,onForceStop:r,onReset:l,bellMode:u=!1,relayMode:p=!1,onBellModeChange:a,onRelayModeChange:c,contextPercent:f=0,currentAgent:v=null,onTirePump:m,onAgentSwitch:y}){const C=S.useRef(0),R=500,{handleFocus:E,handleBlur:g,isFocused:b}=bL(),_=S.useCallback(x=>{if(x.key!=="Escape"&&x.keyCode!==27||!i)return;const A=Date.now();A-C.current<R&&r?r():n(),C.current=A},[i,n,r]);return S.useEffect(()=>(document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}),[_]),d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"control-bar","data-testid":"control-bar",children:[d.jsxs("div",{className:"control-bar-toggles",children:[d.jsx(yL,{currentAgent:v,onAgentSwitch:y}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle bell-toggle ${u?"active":""}`,"data-testid":"bell-mode-toggle",onClick:()=>a?.(!u),"aria-pressed":u,"aria-label":"Bell mode - inject queued messages via hook",children:d.jsx(FO,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:"Bell Mode: Inject queued messages during tool use (Cmd+B)"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle relay-toggle ${p?"active":""}`,"data-testid":"relay-toggle",onClick:()=>c?.(!p),"aria-pressed":p,"aria-label":"Relay mode - auto-handoff to next agent",children:d.jsx(dj,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:"Relay Mode: Auto-handoff to next agent (Cmd+4)"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle pump-toggle ${f>=70?"warning":""}`,"data-testid":"pump-toggle",onClick:m,disabled:!v,"aria-label":"TirePump: Clear context and reload agent",children:d.jsx(tj,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:v?`TirePump: Clear context (${f}%) and reload ${v}`:"TirePump: No agent loaded"})]})]}),d.jsxs(De,{variant:"destructive",type:"button",className:`btn-stop danger ${e?"stopping":""} ${i&&!e?"throbbing":""} ${b("stop")?"focused focus-visible":""}`,"data-testid":"stop-button",onClick:n,disabled:!i||e,"aria-busy":e,"aria-label":"Stop Claude",onFocus:E("stop"),onBlur:g,children:[d.jsx("span",{"data-icon":"stop",className:"icon"}),e?d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"spinner","data-loading":!0}),"Stopping..."]}):"Stop"]}),d.jsx(De,{variant:"outline",type:"button",className:`btn-reset ${b("reset")?"focused focus-visible":""}`,"data-testid":"reset-button",onClick:l,"aria-label":"Reset session",onFocus:E("reset"),onBlur:g,children:"Reset"})]})})}function wL(){const[i,e]=S.useState(!1),[n,r]=S.useState(!1),[l,u]=S.useState(!1),[p,a]=S.useState(!1),[c,f]=S.useState(0),[v,m]=S.useState(null),{abort:y,clear:C,clearAndReload:R,send:E,onMessage:g,onComplete:b,onError:_,isConnected:x}=ao();S.useEffect(()=>{function I(q){const F=q?.workflow,Y=!!F?.bell_mode,L=!!F?.relay_mode;console.log("[ControlBar] Settings updated:",{bellMode:Y,relayMode:L}),u(Y),a(L)}async function z(){try{console.log("[ControlBar] Loading settings via REST");const q=await fetch("/api/settings");if(q.ok){const F=await q.json();I(F)}}catch(q){console.error("[ControlBar] Failed to load settings:",q)}}console.log("[ControlBar] useEffect mount - loading settings"),z(),console.log("[ControlBar] Connecting to /ws/settings for real-time sync");const U=window.location.protocol==="https:"?"wss:":"ws:",X=new WebSocket(`${U}//${window.location.host}/ws/settings`);return X.onmessage=q=>{try{const F=JSON.parse(q.data);(F.type==="init"||F.type==="update")&&I(F.settings)}catch(F){console.error("[ControlBar] Failed to parse WebSocket message:",F)}},X.onerror=q=>{console.error("[ControlBar] WebSocket error:",q)},()=>{X.close()}},[]),S.useEffect(()=>{const I=window.location.protocol==="https:"?"wss:":"ws:",z=new WebSocket(`${I}//${window.location.host}/ws/context`);return z.onmessage=U=>{try{const X=JSON.parse(U.data);if(X.type==="init"||X.type==="update"){const q=X.context?.percent??0;f(q)}}catch(X){console.error("[ControlBar] Failed to parse context message:",X)}},()=>{z.close()}},[]),S.useEffect(()=>{const I=window.location.protocol==="https:"?"wss:":"ws:",z=new WebSocket(`${I}//${window.location.host}/ws/persona`);return z.onmessage=U=>{try{const X=JSON.parse(U.data);m(X?.slug??null)}catch(X){console.error("[ControlBar] Failed to parse persona message:",X)}},()=>{z.close()}},[]),S.useEffect(()=>{if(!x)return;const I=()=>{e(!0),r(!1)},z=()=>{e(!1),r(!1)},U=()=>{e(!1),r(!1)},X=g(I),q=b(z),F=_(U);return()=>{X(),q(),F()}},[x,g,b,_]);const A=S.useCallback(()=>{r(!0);try{y()}catch(I){console.error("[ControlBar] Stop failed:",I)}},[y]),D=S.useCallback(()=>{r(!0);try{y()}catch(I){console.error("[ControlBar] Force stop failed:",I)}},[y]),N=S.useCallback(()=>{try{C(),e(!1),r(!1)}catch(I){console.error("[ControlBar] Reset failed:",I)}},[C]),O=S.useCallback(async I=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{bell_mode:I}})}),u(I),console.log("[ControlBar] Bell mode set to:",I)}catch(z){console.error("[ControlBar] Failed to toggle bell mode:",z)}},[]),T=S.useCallback(async I=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{relay_mode:I}})}),a(I),console.log("[ControlBar] Relay mode set to:",I)}catch(z){console.error("[ControlBar] Failed to toggle relay mode:",z)}},[]),j=S.useCallback(()=>{if(!v){console.warn("[ControlBar] Cannot TirePump: no current agent");return}try{console.log("[ControlBar] TirePump: clearing context and reloading agent:",v),R(v),e(!1),r(!1),f(0)}catch(I){console.error("[ControlBar] TirePump failed:",I)}},[v,R]),H=S.useCallback(I=>{E(`/${I}`)},[E]);return{isRunning:i,isStopping:n,bellMode:l,relayMode:p,contextPercent:c,currentAgent:v,handleStop:A,handleForceStop:D,handleReset:N,handleBellModeChange:O,handleRelayModeChange:T,handleTirePump:j,handleAgentSwitch:H}}function ve({className:i,...e}){return d.jsx("div",{className:we("animate-pulse rounded-md bg-primary/10",i),...e})}const By={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9"};function xL({isOpen:i,onClose:e,currentRole:n,currentTheme:r}){const[l,u]=S.useState(null),[p,a]=S.useState(null),[c,f]=S.useState(!1),[v,m]=S.useState(!1),y=S.useRef(),{send:C}=ao();S.useEffect(()=>{i&&(f(!0),fetch("/api/theme-agents/full").then(_=>_.ok?_.json():null).then(_=>{u(_),a(null),f(!1)}).catch(()=>f(!1)))},[i]),S.useEffect(()=>{m(!1)},[p]),S.useEffect(()=>{if(!i)return;const _=x=>{x.key==="Escape"&&e()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[i,e]);const R=S.useCallback(_=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{a(_)},100)},[]),E=S.useCallback(()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{a(null)},200)},[]),g=S.useCallback(_=>{if(_.role===n)return;const x=`/${_.role}`;C(x),e()},[n,C,e]);if(!i)return null;const b=p||l?.agents.find(_=>_.role===n)||l?.agents[0];return d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"agent-popup-backdrop",onClick:e,"aria-hidden":"true"}),d.jsx("div",{className:"agent-popup",role:"dialog","aria-modal":"true","aria-labelledby":"agent-popup-title",children:c?d.jsxs("div",{className:"agent-popup-loading p-4 space-y-3",children:[d.jsx(ve,{className:"h-6 w-40"}),d.jsx(Rt,{}),d.jsxs("div",{className:"flex gap-4",children:[d.jsxs("div",{className:"space-y-2 flex-shrink-0",style:{width:160},children:[d.jsx(ve,{className:"h-5 w-12"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"})]}),d.jsxs("div",{className:"space-y-3 flex-1",children:[d.jsx(ve,{className:"h-24 w-24 rounded-full mx-auto"}),d.jsx(ve,{className:"h-5 w-32 mx-auto"}),d.jsx(ve,{className:"h-4 w-full"}),d.jsx(ve,{className:"h-4 w-3/4"})]})]})]}):l?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"agent-popup-header",children:[d.jsxs("h2",{id:"agent-popup-title",className:"agent-popup-theme",children:[l.themeName,d.jsx(Ke,{variant:"secondary",className:`tier-badge ${l.tier?`tier-${l.tier.toLowerCase()}`:"tier-unranked"}`,children:l.tier||"Unranked"})]}),d.jsx(De,{variant:"ghost",size:"icon",className:"agent-popup-close",onClick:e,"aria-label":"Close popup",children:"×"})]}),d.jsx(Rt,{className:"my-1"}),d.jsxs("div",{className:"agent-popup-content",children:[d.jsxs("div",{className:"agent-popup-roster",children:[d.jsx("h3",{className:"roster-title",children:"Team"}),d.jsx("ul",{className:"roster-list",role:"listbox",children:l.agents.map(_=>{const x=_.role===n,A=p?.role===_.role,D=By[_.role]||"#888";return d.jsxs("li",{className:`roster-item ${x?"current":""} ${A?"previewing":""}`,role:"option","aria-selected":x,onMouseEnter:()=>R(_),onMouseLeave:E,onClick:()=>g(_),children:[d.jsx("span",{className:"roster-character",children:_.character}),d.jsx("span",{className:"roster-role",style:{backgroundColor:D},children:_.role}),x&&d.jsx("span",{className:"roster-current-marker",children:"●"})]},_.role)})})]}),d.jsx("div",{className:"agent-popup-details","data-testid":"agent-popup-details",children:b&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"popup-portrait","data-testid":"popup-portrait",children:!v&&r?d.jsx("img",{src:`/portraits/${r}/large/${b.slug}.png`,alt:b.character,onError:()=>m(!0)}):d.jsx("div",{className:"portrait-placeholder",children:"🤖"})}),d.jsx("h3",{className:"popup-character",children:b.character}),d.jsxs("div",{className:"popup-role-mapping",children:[d.jsx(Ke,{variant:"default",className:"role-badge",style:{backgroundColor:By[b.role]||"#888"},children:b.role}),"→ ",b.character]}),d.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-style",children:[d.jsx("label",{children:"Style:"}),d.jsx("span",{children:b.style||"—"})]}),d.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-background",children:[d.jsx("label",{children:"Background:"}),d.jsx("span",{children:b.background||"—"})]}),b.quirks.length>0&&d.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-quirks",children:[d.jsx("label",{children:"Quirks:"}),d.jsx("span",{children:b.quirks.join(", ")})]}),b.lift!==void 0&&d.jsxs("div",{className:"popup-detail",children:[d.jsx("label",{children:"Lift:"}),d.jsxs("span",{className:`lift-value ${b.lift>=0?"positive":"negative"}`,children:[b.lift>=0?"+":"",b.lift.toFixed(1)]})]})]})})]})]}):d.jsx("div",{className:"agent-popup-error",children:"Failed to load theme data"})})]})}const CL={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC"};function EL({character:i,role:e,slug:n,theme:r,isActive:l,isThinking:u}){const[p,a]=S.useState(!1);if(!l)return null;const c=CL[e]||e.toUpperCase();return d.jsxs("div",{className:`persona-tandem-portrait${u?" avatar-tandem-thinking":""}`,"data-testid":"tandem-portrait",role:"img","aria-label":`${i} (${e}) - observing`,tabIndex:-1,children:[p?d.jsx("span",{className:"tandem-portrait-fallback","aria-hidden":"true",children:"🤖"}):d.jsx("img",{src:`/portraits/${r}/medium/${n}.png`,alt:"","aria-hidden":"true",className:"tandem-portrait-image",onError:()=>a(!0)}),d.jsx("span",{className:"tandem-role-badge","data-testid":"tandem-role-badge","aria-hidden":"true",children:c})]})}const DL={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9"},AL={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC"};function kL(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ox(){const{persona:i,isStreaming:e}=du(),n=jw(),[r,l]=S.useState(!1),[u,p]=S.useState(!1),[a,c]=S.useState(!1),f=i?.character||"Agent",v=i?.theme||"default",m=i?.role||"agent",y=i?.slug,C=i?.quote,R=i?.tandemAgent,[E,g]=S.useState(!1),b=S.useRef(!1),_=S.useRef(null);S.useEffect(()=>{const O=b.current,T=R?.isThinking??!1;b.current=T,!O&&T&&g(!0)},[R?.isThinking]);const x=S.useCallback(()=>{g(!1)},[]),A=S.useCallback(()=>{p(!0)},[]),D=S.useCallback(()=>{p(!1)},[]),N=DL[m]||"#e879f9";return i?.character?d.jsxs(d.Fragment,{children:[d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:`persona-header clickable${a?" compact":""}`,"data-testid":"persona-header",role:"button",tabIndex:0,"aria-label":"Current agent persona - click to view team","aria-live":"polite",onClick:A,onKeyDown:O=>O.key==="Enter"&&A(),children:[d.jsxs("div",{className:"persona-portrait-group",children:[d.jsx("div",{className:`persona-portrait${e?" avatar-thinking":""}${E?" avatar-observation-pulse":""}`,"data-testid":"persona-portrait",ref:_,onAnimationEnd:x,children:y&&v&&!r?d.jsx("img",{src:`/portraits/${v}/medium/${y}.png`,alt:f,className:"portrait-image",onError:()=>l(!0)}):d.jsx("span",{className:"portrait-fallback",children:"🤖"})}),R&&d.jsx(EL,{character:R.character,role:R.role,slug:R.slug,theme:R.theme,isActive:!0,isThinking:R.isThinking}),R&&d.jsx("span",{className:"visually-hidden",role:"status","aria-live":"polite","data-testid":"tandem-sr-status",children:R.isThinking?`${R.character} is thinking`:`${R.character} observing`})]}),d.jsxs("div",{className:"persona-info",children:[d.jsxs("div",{className:"persona-name-row",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"default",className:"persona-role","data-testid":"persona-role",style:{backgroundColor:N},children:AL[m]||m})}),d.jsx(Oe,{children:m})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"persona-character","data-testid":"persona-character",children:f})}),d.jsx(Oe,{children:f})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"persona-theme","data-testid":"persona-theme",children:kL(v)})}),d.jsx(Oe,{children:`Theme: ${v}`})]})]}),C&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"persona-catchphrase","data-testid":"persona-catchphrase",children:['"',C,'"']})}),d.jsx(Oe,{children:C})]})]}),d.jsx("img",{src:n==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",className:"persona-branding"}),d.jsx("button",{className:"persona-collapse-toggle",onClick:O=>{O.stopPropagation(),c(!a)},"aria-label":a?"Expand header":"Collapse header",children:a?"▼":"▲"})]})}),d.jsx(xL,{isOpen:u,onClose:D,currentRole:m,currentTheme:v})]}):d.jsx("div",{className:"persona-header empty","data-testid":"persona-header"})}function TL(i){if(!i)return"—";const e=i.toLowerCase();if(e.includes("opus"))return"opus";if(e.includes("sonnet"))return"sonnet";if(e.includes("haiku"))return"haiku";const n=i.split("-");if(n.length>=2){for(let r=n.length-2;r>=0;r--)if(!/^\d{8}$/.test(n[r]))return n[r]}return i}function RL(i){return i>=85?"level-danger":i>=70?"level-warning":"level-safe"}function NL(i){if(!i)return"";const e=i.split("/");return e[e.length-1]||e[e.length-2]||i}function OL(){const{context:i,stats:e,projectInfo:n}=Mw(),r=i?.percent??0,l=e?.model??null,u=n?.pwd??"",p=n?.jiraEmail??null,a=n?.githubUsername??null,c=RL(r),f=NL(u);return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"stats-strip","data-testid":"stats-strip",children:[d.jsxs("div",{className:"stats-left","data-testid":"stats-left",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"stats-pwd","data-testid":"stats-pwd","data-full-path":u,children:f})}),d.jsx(Oe,{children:u})]}),p&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"stats-jira-email","data-testid":"jira-email",children:p})}),d.jsx(Oe,{children:`Jira: ${p}`})]}),a&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"stats-github-user","data-testid":"github-user",children:["@",a]})}),d.jsx(Oe,{children:`GitHub: ${a}`})]})]}),d.jsxs("div",{className:"stats-right","data-testid":"stats-right",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"secondary",className:"stats-model-badge","data-testid":"model-badge",children:TL(l)})}),l&&d.jsx(Oe,{children:l})]}),d.jsxs("div",{className:`stats-context-meter ${c}`,"data-testid":"context-meter",children:[d.jsxs("span",{className:"context-percent","data-testid":"context-percent",children:[r,"%"]}),d.jsx("div",{className:"context-fill","data-testid":"context-fill",style:{width:`${r}%`}})]})]})]})})}function Iy(i){return i.startsWith("Stop hook feedback:")}function jL(i){const e=Date.now(),n=i.parent_tool_use_id||void 0,r=i.subagent_type,l=i.subagent_name,u=[];if(i.type==="assistant"||i.type==="message"){const p=i.message?.content||i.content;if(Array.isArray(p)){const a=p.filter(f=>f.type==="text"&&typeof f.text=="string").map(f=>f.text).join("");a&&a.trim().length>=3&&!Iy(a.trim())&&u.push({type:"agent",content:a,timestamp:e,isStreaming:!0,parent_id:n,subagent_type:r,subagent_name:l});const c=p.filter(f=>f.type==="tool_use");for(const f of c)u.push({type:"tool_use",tool_name:f.name,tool_id:f.id,input:f.input,timestamp:e,parent_id:n,subagent_type:r,subagent_name:l})}else typeof p=="string"&&p.trim().length>=3&&!Iy(p.trim())&&u.push({type:"agent",content:p,timestamp:e,isStreaming:!0,parent_id:n,subagent_type:r,subagent_name:l});return u}if(i.type==="user"){let p="";const a=i.message?.content||i.content;if(Array.isArray(a)){p=a.filter(f=>f.type==="text"&&typeof f.text=="string").map(f=>f.text).join("");const c=a.filter(f=>f.type==="tool_result");for(const f of c)u.push({type:"tool_result",tool_id:f.tool_use_id,content:typeof f.content=="string"?f.content:"",timestamp:e,is_error:f.is_error})}else typeof a=="string"&&(p=a);return p&&u.push({type:"user",content:p,timestamp:e,parent_id:n,subagent_type:r,subagent_name:l}),u}return i.type==="tool_use"?(u.push({type:"tool_use",tool_name:i.tool_name,tool_id:i.tool_id,input:i.input,timestamp:e,parent_id:n,subagent_type:r,subagent_name:l}),u):(i.type==="tool_result"&&u.push({type:"tool_result",tool_id:i.tool_id,content:typeof i.output=="string"?i.output:"",timestamp:e,parent_id:n,subagent_type:r,subagent_name:l,is_error:i.is_error,durationMs:i.durationMs}),u)}function ML(){const[i,e]=S.useState([]),[n,r]=S.useState(!1),{isRunning:l,isStopping:u,bellMode:p,relayMode:a,contextPercent:c,currentAgent:f,handleStop:v,handleForceStop:m,handleReset:y,handleBellModeChange:C,handleRelayModeChange:R,handleTirePump:E,handleAgentSwitch:g}=wL(),{send:b,abort:_,onMessage:x,onComplete:A,onError:D,onUserMessage:N,onClear:O,isConnected:T}=ao(),{persona:j}=du(),H=S.useRef(j);H.current=j;const{handleTurnComplete:I,pauseQueue:z,onBellConsumed:U,injectMessage:X}=Sw(),q=S.useRef();S.useEffect(()=>U(K=>{e(ie=>[...ie,{type:"bell_injected",content:K.text,timestamp:Date.now(),imageCount:K.images.length>0?K.images.length:void 0}])}),[U]);const F={abort:_,submit:(P,K)=>{r(!0),b(P,K)}},Y=S.useCallback(P=>{const K=jL(P);if(K.length>0){const ie=H.current,se=K.map(fe=>fe.type==="agent"&&ie?{...fe,agentSlug:ie.slug??void 0,agentTheme:ie.theme??void 0,agentCharacter:ie.character??void 0}:fe),me=se.filter(fe=>fe.type==="tool_result"&&!fe.parent_id&&fe.tool_id).map(fe=>fe.tool_id);me.length>0?e(fe=>{const Ae=new Set(me.filter(Ie=>fe.some(rt=>rt.parent_id===Ie)));return Ae.size>0?[...fe.filter(Ie=>!Ie.parent_id||!Ae.has(Ie.parent_id)),...se]:[...fe,...se]}):e(fe=>[...fe,...se])}},[]),L=S.useCallback(()=>{r(!1),e(P=>P.map(K=>K.type==="agent"&&K.isStreaming?{...K,isStreaming:!1}:K)),q.current&&I(q.current)},[I]),V=S.useCallback(P=>{r(!1),e(K=>[...K,{type:"agent",content:`Error: ${P}`,timestamp:Date.now()}])},[]);S.useEffect(()=>N(K=>{e(ie=>[...ie,{type:"user",content:K.prompt,timestamp:K.timestamp,imageCount:K.images.length>0?K.images.length:void 0}])}),[N]),S.useEffect(()=>O(()=>{e(K=>[...K,{type:"context_cleared",content:"Context cleared",timestamp:Date.now()}]),r(!1)}),[O]),S.useEffect(()=>{if(!T){console.log("[MessagePanel] Claude WebSocket not connected");return}const P=x(Y),K=A(L),ie=D(V);return()=>{P(),K(),ie()}},[T,x,A,D,Y,L,V]);const $=S.useCallback((P,K)=>{r(!0),b(P,K)},[b]);S.useEffect(()=>{q.current=$},[$]);const B=S.useCallback(()=>{z(),v()},[z,v]),[W,ee]=S.useState(null),Z=S.useRef(null),Q=S.useRef(!1),ce=S.useCallback(P=>{P.preventDefault(),Q.current=!0;const K=P.clientY,ie=Z.current;if(!ie)return;const se=ie.getBoundingClientRect(),me=W??ie.querySelector(".message-panel-editor")?.getBoundingClientRect().height??150,fe=Ie=>{if(!Q.current)return;const rt=K-Ie.clientY,zt=Math.max(80,Math.min(me+rt,se.height*.7));ee(zt)},Ae=()=>{Q.current=!1,document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",Ae),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",fe),document.addEventListener("mouseup",Ae),document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[W]);return d.jsxs("div",{className:"message-panel","data-testid":"message-panel",ref:Z,children:[d.jsx(ox,{}),d.jsx("div",{className:"message-panel-content",children:d.jsx(IM,{messages:i})}),d.jsx("div",{className:"message-panel-resize-handle",onMouseDown:ce}),d.jsx("div",{className:"message-panel-editor",style:W!=null?{height:W,flexShrink:0}:void 0,children:d.jsxs("div",{className:"editor-with-controls",children:[d.jsx("div",{className:"editor-area",children:d.jsx(_L,{onSubmit:$,isProcessing:n||l,placeholder:"Send a message...",onInject:P=>X(P,F)})}),d.jsx(SL,{isRunning:l||n,isStopping:u,onStop:B,onForceStop:m,onReset:y,bellMode:p,relayMode:a,onBellModeChange:C,onRelayModeChange:R,contextPercent:c,currentAgent:f,onTirePump:E,onAgentSwitch:g})]})}),d.jsx(OL,{})]})}function LL(i){return i.id?{id:i.id,title:i.title??"",status:i.status??void 0,phase:i.phase??void 0,points:i.points??void 0,criteria:i.criteria,workflowPhases:i.workflow,workflowType:i.workflowType??void 0}:null}function ax(){const[i,e]=S.useState(null),[n,r]=S.useState(!0),[l,u]=S.useState(null),[p,a]=S.useState(null),c=S.useRef(null),f=S.useRef();return S.useEffect(()=>{const m=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/story`,y=()=>{try{c.current=new WebSocket(m),c.current.onopen=()=>{console.debug("[useStory] WebSocket connected")},c.current.onmessage=C=>{try{const R=JSON.parse(C.data);(R.type==="init"||R.type==="update")&&(e(LL(R)),a(R.availableWorkflows??null),r(!1),u(null))}catch(R){console.error("[useStory] Failed to parse message:",R)}},c.current.onclose=()=>{console.debug("[useStory] WebSocket closed, reconnecting..."),f.current=setTimeout(y,2e3)},c.current.onerror=C=>{console.error("[useStory] WebSocket error:",C),u(new Error("WebSocket connection failed"))}}catch(C){console.error("[useStory] WebSocket init failed:",C),u(C instanceof Error?C:new Error("Failed to connect")),r(!1)}};return y(),()=>{f.current&&clearTimeout(f.current),c.current&&c.current.close()}},[]),{story:i,isLoading:n,error:l,availableWorkflows:p}}function PL(){const[i,e]=S.useState(null),[n,r]=S.useState(!0),[l,u]=S.useState(null),p=S.useRef(null),a=S.useRef(),c=S.useRef(!0);return S.useEffect(()=>{const v=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/sprint`,m=()=>{if(c.current)try{p.current=new WebSocket(v),p.current.onopen=()=>{console.debug("[useSprint] WebSocket connected")},p.current.onmessage=y=>{try{const C=JSON.parse(y.data);if(C.type==="init"||C.type==="update"){const{type:R,...E}=C;e(g=>g?{...g,...E}:E),r(!1),u(null)}}catch(C){console.error("[useSprint] Failed to parse message:",C)}},p.current.onclose=()=>{console.debug("[useSprint] WebSocket closed, reconnecting..."),a.current=setTimeout(m,2e3)},p.current.onerror=y=>{console.error("[useSprint] WebSocket error:",y),u(new Error("WebSocket connection failed"))}}catch(y){console.error("[useSprint] WebSocket init failed:",y),u(y instanceof Error?y:new Error("Failed to connect")),r(!1)}};return m(),()=>{c.current=!1,a.current&&clearTimeout(a.current),p.current&&p.current.close()}},[]),{data:i,isLoading:n,error:l}}function zL(i){if(!i)return null;const e=i.split("@")[0],n=e.split(".");if(n.length>=2){const r=n[0].charAt(0).toUpperCase(),l=n[n.length-1].charAt(0).toUpperCase()+n[n.length-1].slice(1);return`${r}. ${l}`}return e}function BL(i){const e=i.stories.reduce((r,l)=>r+l.points,0);return{done:i.stories.filter(r=>r.status==="done").reduce((r,l)=>r+l.points,0),total:e}}function Wf(i){return i.stories.length>0&&i.stories.every(e=>e.status==="done")}function IL(i){switch(i){case"done":return{icon:d.jsx(va,{size:12}),className:"status-done"};case"in_progress":return{icon:d.jsx(ZO,{size:12}),className:"status-in-progress"};case"blocked":return{icon:d.jsx(rj,{size:12}),className:"status-blocked"};default:return{icon:d.jsx(KO,{size:12}),className:"status-backlog"}}}function Hy(i){return`https://1898andco.atlassian.net/browse/${i}`}function Fy({hasContext:i,testIdPrefix:e,id:n}){const r=i?"Context file exists":"No context file";return d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:`context-indicator ${i?"has-context":"no-context"}`,"data-testid":`${e}-context-indicator-${n}`,"data-has-context":String(i),title:r,children:i?"📄":""})}),d.jsx(Oe,{children:r})]})}function HL({priority:i,storyId:e}){return i?d.jsx("span",{className:"priority-label","data-testid":`story-priority-${e}`,"data-priority":i,title:i,children:i}):null}function FL({status:i,storyId:e}){const{icon:n,className:r}=IL(i);return d.jsx(Ke,{variant:i==="blocked"?"destructive":i==="done"?"default":"secondary",className:`story-status-badge ${r}`,"data-testid":`story-status-badge-${e}`,"data-status":i,"aria-label":`Status: ${i}`,children:n})}function GL({jiraKey:i,storyId:e}){const n=r=>{r.preventDefault();const l=Hy(i);try{const u=window.electronAPI;if(u?.shell?.openExternal){u.shell.openExternal(l);return}}catch{}window.open(l,"_blank")};return d.jsx("a",{className:"jira-link cyclist-link","data-testid":`story-jira-link-${e}`,href:Hy(i),onClick:n,children:i})}function Gy({epic:i,isExpanded:e,isArchiving:n,onToggle:r,onKeyDown:l,onArchive:u}){const{done:p,total:a}=BL(i),c=Wf(i);return d.jsxs("div",{className:`epic-group ${c?"epic-completed":""}`,"data-testid":`epic-group-${i.id}`,children:[d.jsxs("div",{className:"epic-header",children:[d.jsx(De,{variant:"ghost",size:"icon",className:"epic-toggle","data-testid":`epic-toggle-${i.id}`,onClick:()=>r(i.id),onKeyDown:f=>l(i.id,f),"aria-expanded":e,children:e?"▼":"▶"}),d.jsx("span",{className:"epic-title",children:i.title}),i.jiraKey&&d.jsx("span",{className:"epic-jira",children:i.jiraKey}),d.jsx(Fy,{hasContext:i.hasContext??!1,testIdPrefix:"epic",id:i.id}),c&&i.hasContext&&d.jsx(Ke,{variant:"default",className:"epic-ready-badge","data-testid":`epic-ready-badge-${i.id}`,children:"Ready"}),d.jsx("div",{className:"epic-progress","data-testid":`epic-progress-${i.id}`,"data-done":String(p),"data-total":String(a),children:d.jsx("div",{className:"progress-bar",style:{width:`${a>0?p/a*100:0}%`}})}),d.jsxs("span",{className:"epic-progress-label","data-testid":`epic-progress-label-${i.id}`,children:[p,"/",a," pts"]}),c&&d.jsxs(d.Fragment,{children:[n&&d.jsx("span",{"data-testid":`archive-loading-${i.id}`,children:"..."}),d.jsx(De,{variant:"outline",size:"sm",className:"archive-button","data-testid":`archive-button-${i.id}`,"aria-label":`Archive ${i.id}`,disabled:n,onClick:()=>u(i.id),children:"Archive"})]})]}),e&&d.jsx("div",{className:"epic-stories",children:i.stories.map(f=>{const v=f.hasContext??!1,m=f.status==="blocked",y=zL(f.assignedTo);return d.jsxs("div",{className:`story-item ${v?"":"missing-context"} ${m?"story-blocked":""}`,"data-testid":`story-item-${f.id}`,"data-status":f.status,"data-story-id":f.id,"aria-label":`${f.id}: ${f.title}`,children:[d.jsx(HL,{priority:f.priority,storyId:f.id}),d.jsx(FL,{status:f.status,storyId:f.id}),f.jiraKey&&d.jsx(GL,{jiraKey:f.jiraKey,storyId:f.id}),d.jsxs("div",{className:"story-info",children:[d.jsx("span",{className:"story-title",children:f.title}),d.jsxs("span",{className:"story-meta",children:[y&&d.jsx("span",{className:"story-assignee","data-testid":`story-assignee-${f.id}`,children:y}),f.workflow&&d.jsx("span",{className:"story-workflow-badge","data-testid":`story-workflow-${f.id}`,children:f.workflow}),f.status==="done"&&f.completed&&d.jsx("span",{className:"story-completed-date","data-testid":`story-completed-${f.id}`,children:f.completed})]})]}),d.jsx(Fy,{hasContext:v,testIdPrefix:"story",id:f.id}),d.jsx("span",{className:"story-points","data-testid":`story-points-${f.id}`,children:f.points})]},f.id)})})]})}function lx(){const{data:i,isLoading:e,error:n}=PL(),[r,l]=S.useState(new Set),[u,p]=S.useState(new Set),[a,c]=S.useState(null),[f,v]=S.useState(null),m=i?.epics.filter(D=>!Wf(D))??[],y=i?.epics.filter(D=>Wf(D))??[],C=S.useRef(!1);S.useEffect(()=>{i?.epics&&!C.current&&(C.current=!0,l(new Set(m.map(D=>D.id))))},[i?.epics]);const R=S.useCallback(D=>{l(N=>{const O=new Set(N);return O.has(D)?O.delete(D):O.add(D),O})},[]),E=S.useCallback((D,N)=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),R(D))},[R]),g=S.useCallback(async D=>{p(N=>new Set(N).add(`archive-${D}`)),c(null),v(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.archiveEpic)await window.electronAPI.sprint.archiveEpic(D);else if(!(await fetch(`/api/sprint/archive-epic/${D}`,{method:"POST"})).ok)throw new Error("Archive failed")}catch(N){v(N instanceof Error?N:new Error("Archive failed"))}finally{p(N=>{const O=new Set(N);return O.delete(`archive-${D}`),O})}},[]),b=S.useCallback(async D=>{p(N=>new Set(N).add(`promote-${D}`)),v(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.promoteEpic)await window.electronAPI.sprint.promoteEpic(D);else if(!(await fetch(`/api/sprint/promote-epic/${D}`,{method:"POST"})).ok)throw new Error("Promote failed")}catch(N){v(N instanceof Error?N:new Error("Promote failed"))}finally{p(N=>{const O=new Set(N);return O.delete(`promote-${D}`),O})}},[]);if(e)return d.jsx("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:d.jsxs("div",{className:"loading-state space-y-3 p-2","data-testid":"sprint-panel-loading",children:[d.jsx(ve,{className:"h-5 w-32"}),d.jsx(ve,{className:"h-4 w-full"}),d.jsx(Rt,{className:"my-2"}),d.jsx(ve,{className:"h-5 w-28"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(Rt,{className:"my-2"}),d.jsx(ve,{className:"h-5 w-36"}),d.jsx(ve,{className:"h-6 w-3/4"})]})});const _=n||f,x=_?d.jsx("div",{className:"error-toast","data-testid":"error-toast",children:_.message}):null,A=a?d.jsxs("div",{className:"confirm-dialog","data-testid":"confirm-archive-dialog",children:[d.jsx("p",{children:"Are you sure you want to archive this epic?"}),d.jsx(De,{variant:"destructive",size:"sm","data-testid":"confirm-archive-yes",onClick:()=>g(a),children:"Yes"}),d.jsx(De,{variant:"outline",size:"sm","data-testid":"confirm-archive-no",onClick:()=>c(null),children:"No"})]}):null;return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:[x,A,d.jsxs("section",{"data-section":"current-story",children:[d.jsx("h2",{children:"Current Story"}),i?.currentStory?d.jsxs("div",{"data-testid":"current-story-section",children:[d.jsx("span",{className:"story-id",children:i.currentStory.id}),d.jsx("span",{className:"story-title",children:i.currentStory.title}),d.jsx("span",{className:"story-status",children:i.currentStory.status}),d.jsxs("span",{className:"story-points","data-testid":"current-story-points",children:[i.currentStory.points," pts"]})]}):i?.nextStory?d.jsxs("div",{"data-testid":"next-up-section",children:[d.jsx("span",{className:"next-up-label",children:"Next up:"}),d.jsx("span",{className:"story-id",children:i.nextStory.id}),d.jsx("span",{className:"story-title",children:i.nextStory.title})]}):d.jsx("div",{"data-testid":"no-stories-section",children:d.jsx("span",{children:"No active story"})})]}),d.jsx(Rt,{className:"my-2"}),d.jsxs("section",{"data-section":"epics",children:[d.jsx("h2",{children:"Current Epics"}),d.jsxs("div",{"data-testid":"epic-tree-view",children:[(!i?.epics||i.epics.length===0)&&d.jsxs("div",{className:"empty-state","data-testid":"no-epics-section",children:[d.jsx("span",{children:"No epics in current sprint"}),d.jsx("p",{className:"hint",children:"Promote an epic from Future Initiatives to get started"})]}),m.map(D=>d.jsx(Gy,{epic:D,isExpanded:r.has(D.id),isArchiving:u.has(`archive-${D.id}`),onToggle:R,onKeyDown:E,onArchive:c},D.id))]})]}),y.length>0&&d.jsxs(d.Fragment,{children:[d.jsx(Rt,{className:"my-2"}),d.jsxs("section",{"data-section":"completed-epics",children:[d.jsx("h2",{children:"Completed Epics"}),d.jsx("div",{"data-testid":"completed-epics-section",children:y.map(D=>d.jsx(Gy,{epic:D,isExpanded:r.has(D.id),isArchiving:u.has(`archive-${D.id}`),onToggle:R,onKeyDown:E,onArchive:c},D.id))})]})]}),d.jsx(Rt,{className:"my-2"}),d.jsxs("section",{"data-section":"future",children:[d.jsx("h2",{children:"Future Initiatives"}),d.jsx("div",{"data-testid":"future-initiatives-section",children:i?.futureEpics.map(D=>{const N=u.has(`promote-${D.id}`),O=D.status==="ready";return d.jsxs("div",{className:"future-epic","data-testid":`future-epic-${D.id}`,children:[d.jsx("span",{className:"future-epic-title",children:D.title}),d.jsxs("span",{className:"future-epic-points",children:[D.estimatedPoints," pts"]}),d.jsx(Ke,{variant:D.status==="ready"?"default":"secondary",className:"future-epic-status","data-testid":`future-epic-status-${D.id}`,"data-status":D.status,children:D.status}),O&&d.jsx(De,{variant:"default",size:"sm",className:"promote-button","data-testid":`promote-button-${D.id}`,"aria-label":`Promote ${D.id} to current sprint`,disabled:N,onClick:()=>b(D.id),children:"Promote"})]},D.id)})})]})]})})}function cx(i){let e=0,n=0,r=0;for(const l of i){const u=l.status[0]||" ",p=l.status[1]||" ";u!==" "&&u!=="?"&&e++,(p==="M"||p==="D")&&n++,u==="?"&&p==="?"&&r++}return{staged:e,modified:n,untracked:r}}function UL(i){return i?.length?i.map(e=>{const n=cx(e.dirtyFiles);return{name:e.name,path:e.path,branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,developBehind:e.developBehind??void 0,staged:n.staged,modified:n.modified,untracked:n.untracked,isDirty:!e.clean,files:e.dirtyFiles}}):[]}function WL(i){if(!i?.length)return null;const e=i[0];let n=0,r=0,l=0;for(const p of i){const a=cx(p.dirtyFiles);n+=a.staged,r+=a.modified,l+=a.untracked}const u=i.some(p=>!p.clean);return{branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,staged:n>0?n:void 0,modified:r>0?r:void 0,untracked:l>0?l:void 0,isDirty:u}}function ux(){const[i,e]=S.useState(null),[n,r]=S.useState([]),[l,u]=S.useState(!0),[p,a]=S.useState(null),c=S.useRef(null),f=S.useRef();return S.useEffect(()=>{const m=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/git`,y=()=>{try{c.current=new WebSocket(m),c.current.onopen=()=>{console.debug("[useGitStatus] WebSocket connected")},c.current.onmessage=C=>{try{const R=JSON.parse(C.data);(R.type==="init"||R.type==="update")&&(e(WL(R.repos)),r(UL(R.repos)),u(!1),a(null))}catch(R){console.error("[useGitStatus] Failed to parse message:",R)}},c.current.onclose=()=>{console.debug("[useGitStatus] WebSocket closed, reconnecting..."),f.current=setTimeout(y,2e3)},c.current.onerror=C=>{console.error("[useGitStatus] WebSocket error:",C),a(new Error("WebSocket connection failed"))}}catch(C){console.error("[useGitStatus] WebSocket init failed:",C),a(C instanceof Error?C:new Error("Failed to connect")),u(!1)}};return y(),()=>{f.current&&clearTimeout(f.current),c.current&&c.current.close()}},[]),{gitStatus:i,repos:n,isLoading:l,error:p}}function VL(i){const e=i[0]||" ",n=i[1]||" ";return e==="?"&&n==="?"?"untracked":e!==" "&&e!=="?"?"staged":"modified"}function $L(i){const e=i[0]||" ",n=i[1]||" ";return e==="?"&&n==="?"?"?":e==="A"?"+":e==="D"||n==="D"?"-":e==="M"||n==="M"?"~":e==="R"?"R":i.trim()||"~"}function qL({files:i}){return d.jsx("ul",{className:"file-list",children:i.map((e,n)=>d.jsxs("li",{className:`file-item ${VL(e.status)}`,children:[d.jsx("span",{className:"file-status-icon",children:$L(e.status)}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"file-path",children:e.path})}),d.jsx(Oe,{children:e.path})]})]},`${e.path}-${n}`))})}function YL({repo:i}){const[e,n]=S.useState(!1),{name:r,branch:l,ahead:u,behind:p,developBehind:a,staged:c,modified:f,untracked:v,isDirty:m,files:y}=i,C=y.length>0;return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:`repo-status ${e?"expanded":""}`,"data-testid":`repo-status-${r}`,children:[d.jsxs("div",{className:"repo-header",children:[d.jsx("span",{className:"repo-name",children:r}),m&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"destructive",className:"dirty-indicator",children:"●"})}),d.jsx(Oe,{children:"Uncommitted changes"})]})]}),d.jsxs("div",{className:"branch-info",children:[d.jsx("span",{className:"branch-icon",children:"⎇"}),d.jsx("span",{className:"branch-name",children:l})]}),(u!==void 0&&u>0||p!==void 0&&p>0||a!==void 0&&a>0)&&d.jsxs("div",{className:"sync-status",children:[u!==void 0&&u>0&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"ahead",children:["↑",u]})}),d.jsx(Oe,{children:"Commits ahead of remote"})]}),p!==void 0&&p>0&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"behind",children:["↓",p]})}),d.jsx(Oe,{children:"Commits behind remote"})]}),a!==void 0&&a>0&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"develop-behind",children:["⟳",a]})}),d.jsxs(Oe,{children:["develop is ",a," commit",a>1?"s":""," ahead"]})]})]}),(c>0||f>0||v>0)&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs(De,{variant:"ghost",className:"file-status-toggle",onClick:()=>n(!e),children:[d.jsx("span",{className:`toggle-icon ${e?"open":""}`,children:"▶"}),d.jsxs("div",{className:"file-status",children:[c>0&&d.jsxs(Ke,{variant:"outline",className:"status-item staged",children:["+",c]}),f>0&&d.jsxs(Ke,{variant:"outline",className:"status-item modified",children:["~",f]}),v>0&&d.jsxs(Ke,{variant:"outline",className:"status-item untracked",children:["?",v]})]})]})}),d.jsx(Oe,{children:e?"Collapse file list":"Expand file list"})]}),e&&C&&d.jsx(qL,{files:y})]})})}function dx(){const{repos:i,isLoading:e,error:n}=ux(),{send:r}=ao(),l=()=>{r("Sync all repos")};return e?d.jsx("div",{className:"git-panel loading","data-testid":"git-panel",children:d.jsxs("div",{className:"space-y-3 p-2",children:[d.jsxs("div",{className:"space-y-1",children:[d.jsx(ve,{className:"h-4 w-32"}),d.jsx(ve,{className:"h-3 w-24"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsx(ve,{className:"h-4 w-28"}),d.jsx(ve,{className:"h-3 w-20"})]})]})}):n?d.jsx("div",{className:"git-panel error","data-testid":"git-panel",children:d.jsx("div",{className:"error-message",children:n.message})}):i.length===0?d.jsx("div",{className:"git-panel empty","data-testid":"git-panel",children:d.jsx("div",{className:"placeholder",children:"No git repos"})}):d.jsxs("div",{className:"git-panel stacked","data-testid":"git-panel",children:[d.jsx("div",{className:"git-panel-actions",children:d.jsx(wt,{delayDuration:300,children:d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("button",{className:"sync-all-btn",onClick:l,"aria-label":"Sync all repos",children:[d.jsx(QO,{size:14}),d.jsx("span",{children:"Sync all repos"})]})}),d.jsx(Oe,{children:"Pull latest changes for all repos"})]})})}),i.map(u=>d.jsx(YL,{repo:u},u.name))]})}function KL(i){switch(i){case"done":return"✓";case"current":return"●";default:return"○"}}function XL(i){return i?["tdd","bdd"].includes(i.toLowerCase())?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):"—"}function ZL({phase:i,isLast:e}){const n=KL(i.status),r=`phase-step ${i.status}`;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:r,children:[d.jsx("span",{className:"phase-icon",children:n}),d.jsx("span",{className:"phase-label",children:i.label})]}),!e&&d.jsx("span",{className:"phase-arrow",children:"→"})]})}function JL({phases:i}){const e=i.length,n=i.findIndex(p=>p.status==="current"),r=i.filter(p=>p.status==="done").length,l=n>=0?n+1:r===e?e:1,u=n>=0?i[n]:null;return d.jsxs("div",{className:"stepped-progress",children:[d.jsxs("span",{className:"stepped-counter",children:["Step ",l," of ",e]}),u&&d.jsx("span",{className:"stepped-current-label",children:u.label})]})}function QL({workflows:i,onStart:e}){return d.jsxs("div",{className:"available-workflows",children:[d.jsx("div",{className:"available-workflows-header",children:d.jsxs("span",{className:"available-workflows-title",children:["Available Workflows (",i.length,")"]})}),d.jsx("div",{className:"available-workflows-list",children:i.map(n=>d.jsxs("div",{className:"workflow-entry","data-testid":"workflow-entry","data-workflow-entry-type":n.type,children:[d.jsxs("div",{className:"workflow-entry-header",children:[d.jsx("span",{className:"workflow-entry-name",children:n.name}),d.jsx(Ke,{variant:"outline",className:"workflow-entry-type-badge",children:n.type})]}),d.jsx("div",{className:"workflow-entry-description",children:n.description}),n.type==="stepped"&&d.jsxs("div",{className:"workflow-entry-hint",children:["/workflow start ",n.name]}),d.jsx("div",{className:"workflow-entry-footer",children:d.jsx(De,{variant:"ghost",size:"sm",className:"workflow-start-button","data-testid":"workflow-start-button",onClick:()=>e?.(n),children:"Start"})})]},n.name))})]})}function hx(){const{story:i,isLoading:e,error:n,availableWorkflows:r}=ax(),{send:l,isConnected:u}=ao(),p=S.useCallback(m=>{u&&l(`/workflow start ${m.name}`)},[l,u]);if(e)return d.jsx("div",{className:"workflow-panel loading","data-testid":"workflow-panel",children:d.jsxs("div",{className:"space-y-2 p-2",children:[d.jsx(ve,{className:"h-6 w-16 rounded-full"}),d.jsxs("div",{className:"flex gap-2 items-center",children:[d.jsx(ve,{className:"h-4 w-12"}),d.jsx(ve,{className:"h-4 w-12"}),d.jsx(ve,{className:"h-4 w-12"})]})]})});if(n)return d.jsx("div",{className:"workflow-panel error","data-testid":"workflow-panel",children:d.jsx("div",{className:"error-message",children:n.message})});const a=i?.workflow??null,c=i?.workflowPhases??null,f=i?.workflowType==="stepped";if(!a&&(!c||c.length===0))return r&&r.length>0?d.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:d.jsx(QL,{workflows:r,onStart:p})}):d.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:d.jsx("div",{className:"placeholder",children:"No active workflow"})});const v=XL(a);return d.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:d.jsxs("div",{className:"workflow-content",children:[d.jsx(Ke,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":a||"",children:v}),c&&c.length>0&&(f?d.jsx(JL,{phases:c}):d.jsx("div",{className:"phase-progress",children:c.map((m,y)=>d.jsx(ZL,{phase:m,isLast:y===c.length-1},m.name))}))]})})}function eP({item:i}){const e=i.completed?"ac-item ac-done":"ac-item",n=i.completed?"✓":"○";return d.jsxs("div",{className:e,children:[d.jsx("span",{className:"ac-icon",children:n}),d.jsx("span",{className:"ac-text",children:i.text})]})}function fx(){const{story:i,isLoading:e,error:n}=ax();if(e)return d.jsx("div",{className:"ac-panel loading","data-testid":"ac-panel",children:d.jsxs("div",{className:"space-y-2 p-2",children:[d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-4 w-3/4"}),d.jsx(ve,{className:"h-4 w-5/6"}),d.jsx(ve,{className:"h-4 w-2/3"})]})});if(n)return d.jsx("div",{className:"ac-panel error","data-testid":"ac-panel",children:d.jsx("div",{className:"error-message",children:n.message})});const r=i?.criteria??null;if(!r||r.length===0)return d.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:d.jsx("div",{className:"placeholder",children:"No acceptance criteria"})});const l=r.filter(p=>p.completed).length,u=r.length;return d.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:d.jsxs("div",{className:"ac-content",children:[d.jsxs("span",{className:"progress-text",children:[l,"/",u]}),d.jsx("div",{className:"progress-bar-container",children:d.jsx("div",{className:"progress-bar",style:{width:`${l/u*100}%`}})}),d.jsx("div",{className:"ac-list",children:r.map((p,a)=>d.jsx(eP,{item:p},a))})]})})}function tP(){const[i,e]=S.useState([]),[n,r]=S.useState(!0),[l,u]=S.useState(null),p=S.useRef(null),a=S.useRef();return S.useEffect(()=>{const f=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/todos`,v=()=>{try{p.current=new WebSocket(f),p.current.onopen=()=>{console.debug("[useTodos] WebSocket connected")},p.current.onmessage=m=>{try{const y=JSON.parse(m.data);(y.type==="init"||y.type==="update")&&(e(y.todos||[]),r(!1),u(null))}catch(y){console.error("[useTodos] Failed to parse message:",y)}},p.current.onclose=()=>{console.debug("[useTodos] WebSocket closed, reconnecting..."),a.current=setTimeout(v,2e3)},p.current.onerror=m=>{console.error("[useTodos] WebSocket error:",m),u(new Error("WebSocket connection failed"))}}catch(m){console.error("[useTodos] WebSocket init failed:",m),u(m instanceof Error?m:new Error("Failed to connect")),r(!1)}};return v(),()=>{a.current&&clearTimeout(a.current),p.current&&p.current.close()}},[]),{todos:i,isLoading:n,error:l}}function df({todo:i}){const e={pending:"○",in_progress:"●",completed:"✓"}[i.status],n=`todo-item todo-${i.status}`,r=i.status==="in_progress"&&i.activeForm?i.activeForm:i.content;return d.jsxs("div",{className:n,"data-testid":`todo-${i.id}`,children:[d.jsx("span",{className:"todo-status",children:e}),d.jsx("span",{className:"todo-subject",children:r}),i.blockedBy&&i.blockedBy.length>0&&d.jsx(wt,{delayDuration:300,children:d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"todo-blocked",children:"(blocked)"})}),d.jsx(Oe,{children:`Blocked by: ${i.blockedBy.join(", ")}`})]})})]})}function px(){const{todos:i,isLoading:e,error:n}=tP();if(e)return d.jsx("div",{className:"todo-panel loading","data-testid":"todo-panel",children:d.jsxs("div",{className:"space-y-2 p-2",children:[d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-4 w-5/6"}),d.jsx(ve,{className:"h-4 w-3/4"}),d.jsx(ve,{className:"h-4 w-4/5"})]})});if(n)return d.jsx("div",{className:"todo-panel error","data-testid":"todo-panel",children:d.jsx("div",{className:"error-message",children:n.message})});if(i.length===0)return d.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:d.jsx("div",{className:"placeholder",children:"No active tasks"})});const r=i.filter(f=>f.status==="in_progress"),l=i.filter(f=>f.status==="pending"),u=i.filter(f=>f.status==="completed"),p=i.length,a=u.length,c=p>0?Math.round(a/p*100):0;return d.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:d.jsxs("div",{className:"todo-content",children:[d.jsxs("div",{className:"progress-bar-container",children:[d.jsx("div",{className:"progress-bar",style:{width:`${c}%`}}),d.jsxs("span",{className:"progress-text",children:[a,"/",p]})]}),r.length>0&&d.jsxs("div",{className:"todo-section",children:[d.jsx("h4",{children:"In Progress"}),r.map(f=>d.jsx(df,{todo:f},f.id))]}),l.length>0&&d.jsxs("div",{className:"todo-section",children:[d.jsx("h4",{children:"Pending"}),l.map(f=>d.jsx(df,{todo:f},f.id))]}),u.length>0&&d.jsxs("div",{className:"todo-section todo-completed",children:[d.jsxs("h4",{children:["Completed (",u.length,")"]}),u.map(f=>d.jsx(df,{todo:f},f.id))]})]})})}function iP(){const[i,e]=S.useState([]),n=S.useRef(null),r=S.useRef();S.useEffect(()=>{const c=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/background-tasks`,f=()=>{try{n.current=new WebSocket(c),n.current.onopen=()=>{console.debug("[useBackgroundTasks] WebSocket connected")},n.current.onmessage=v=>{try{const m=JSON.parse(v.data);switch(m.type){case"init":m.tasks&&e(m.tasks);break;case"task:started":m.task&&e(y=>y.some(C=>C.taskId===m.task.taskId)?y:[...y,m.task]);break;case"task:completed":m.task&&e(y=>y.map(C=>C.taskId===m.task.taskId?{...C,...m.task}:C));break}}catch(m){console.error("[useBackgroundTasks] Failed to parse message:",m)}},n.current.onclose=()=>{console.debug("[useBackgroundTasks] WebSocket closed, reconnecting..."),r.current=setTimeout(f,2e3)},n.current.onerror=v=>{console.error("[useBackgroundTasks] WebSocket error:",v)}}catch(v){console.error("[useBackgroundTasks] WebSocket init failed:",v)}};return f(),()=>{r.current&&clearTimeout(r.current),n.current&&n.current.close()}},[]);const l=S.useCallback(()=>{e(a=>a.filter(c=>c.status==="pending"))},[]),u=i.filter(a=>a.status==="pending").length,p=i.filter(a=>a.status==="completed").length;return{tasks:i,pendingCount:u,completedCount:p,clearCompleted:l}}function Uy(i){return i<1e3?`${i}ms`:i<6e4?`${Math.floor(i/1e3)}s`:`${Math.floor(i/6e4)}m`}function nP({task:i,tick:e}){const r=i.status==="pending"?"...":i.success?"v":"x",l=`task-item task-${i.status}${i.success===!1?" task-error":""}`;let u;return i.status==="completed"&&i.durationMs!==void 0?u=Uy(i.durationMs):u=Uy(Date.now()-i.startedAt),d.jsxs("div",{className:l,"data-testid":`task-${i.taskId}`,children:[d.jsx("span",{className:"task-status",children:r}),d.jsxs("div",{className:"task-content",children:[d.jsx("span",{className:"task-description",children:i.description}),d.jsx("span",{className:"task-type",children:i.subagentType})]}),d.jsx("span",{className:"task-elapsed",children:u})]})}function mx(){const{tasks:i,pendingCount:e,completedCount:n,clearCompleted:r}=iP(),[l,u]=S.useState(0);if(S.useEffect(()=>{if(e===0)return;const a=setInterval(()=>{u(c=>c+1)},1e3);return()=>clearInterval(a)},[e]),i.length===0)return d.jsx("div",{className:"background-panel empty","data-testid":"background-panel",children:d.jsx("div",{className:"placeholder",children:"No subagent tasks"})});const p=[...i].sort((a,c)=>a.status==="pending"&&c.status!=="pending"?-1:a.status!=="pending"&&c.status==="pending"?1:c.startedAt-a.startedAt);return d.jsxs("div",{className:"background-panel","data-testid":"background-panel",children:[d.jsxs("div",{className:"panel-header",children:[d.jsxs("span",{className:"task-counts",children:[e>0&&d.jsxs("span",{className:"pending-count",children:[e," running"]}),n>0&&d.jsxs("span",{className:"completed-count",children:[n," done"]})]}),n>0&&d.jsx(De,{variant:"ghost",size:"sm",type:"button",className:"clear-button",onClick:r,children:"Clear"})]}),d.jsx("div",{className:"task-list",children:p.map(a=>d.jsx(nP,{task:a,tick:l},a.taskId))})]})}function Vf(i,[e,n]){return Math.min(n,Math.max(e,i))}function sP(i,e){return S.useReducer((n,r)=>e[n][r]??n,i)}var Kp="ScrollArea",[gx]=pi(Kp),[rP,Oi]=gx(Kp),vx=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,type:r="hover",dir:l,scrollHideDelay:u=600,...p}=i,[a,c]=S.useState(null),[f,v]=S.useState(null),[m,y]=S.useState(null),[C,R]=S.useState(null),[E,g]=S.useState(null),[b,_]=S.useState(0),[x,A]=S.useState(0),[D,N]=S.useState(!1),[O,T]=S.useState(!1),j=Ge(e,I=>c(I)),H=hu(l);return d.jsx(rP,{scope:n,type:r,dir:H,scrollHideDelay:u,scrollArea:a,viewport:f,onViewportChange:v,content:m,onContentChange:y,scrollbarX:C,onScrollbarXChange:R,scrollbarXEnabled:D,onScrollbarXEnabledChange:N,scrollbarY:E,onScrollbarYChange:g,scrollbarYEnabled:O,onScrollbarYEnabledChange:T,onCornerWidthChange:_,onCornerHeightChange:A,children:d.jsx(Ne.div,{dir:H,...p,ref:j,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":x+"px",...i.style}})})});vx.displayName=Kp;var _x="ScrollAreaViewport",bx=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,children:r,nonce:l,...u}=i,p=Oi(_x,n),a=S.useRef(null),c=Ge(e,a,p.onViewportChange);return d.jsxs(d.Fragment,{children:[d.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:l}),d.jsx(Ne.div,{"data-radix-scroll-area-viewport":"",...u,ref:c,style:{overflowX:p.scrollbarXEnabled?"scroll":"hidden",overflowY:p.scrollbarYEnabled?"scroll":"hidden",...i.style},children:d.jsx("div",{ref:p.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});bx.displayName=_x;var on="ScrollAreaScrollbar",Xp=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Oi(on,i.__scopeScrollArea),{onScrollbarXEnabledChange:u,onScrollbarYEnabledChange:p}=l,a=i.orientation==="horizontal";return S.useEffect(()=>(a?u(!0):p(!0),()=>{a?u(!1):p(!1)}),[a,u,p]),l.type==="hover"?d.jsx(oP,{...r,ref:e,forceMount:n}):l.type==="scroll"?d.jsx(aP,{...r,ref:e,forceMount:n}):l.type==="auto"?d.jsx(yx,{...r,ref:e,forceMount:n}):l.type==="always"?d.jsx(Zp,{...r,ref:e}):null});Xp.displayName=on;var oP=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Oi(on,i.__scopeScrollArea),[u,p]=S.useState(!1);return S.useEffect(()=>{const a=l.scrollArea;let c=0;if(a){const f=()=>{window.clearTimeout(c),p(!0)},v=()=>{c=window.setTimeout(()=>p(!1),l.scrollHideDelay)};return a.addEventListener("pointerenter",f),a.addEventListener("pointerleave",v),()=>{window.clearTimeout(c),a.removeEventListener("pointerenter",f),a.removeEventListener("pointerleave",v)}}},[l.scrollArea,l.scrollHideDelay]),d.jsx(Qt,{present:n||u,children:d.jsx(yx,{"data-state":u?"visible":"hidden",...r,ref:e})})}),aP=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Oi(on,i.__scopeScrollArea),u=i.orientation==="horizontal",p=pu(()=>c("SCROLL_END"),100),[a,c]=sP("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return S.useEffect(()=>{if(a==="idle"){const f=window.setTimeout(()=>c("HIDE"),l.scrollHideDelay);return()=>window.clearTimeout(f)}},[a,l.scrollHideDelay,c]),S.useEffect(()=>{const f=l.viewport,v=u?"scrollLeft":"scrollTop";if(f){let m=f[v];const y=()=>{const C=f[v];m!==C&&(c("SCROLL"),p()),m=C};return f.addEventListener("scroll",y),()=>f.removeEventListener("scroll",y)}},[l.viewport,u,c,p]),d.jsx(Qt,{present:n||a!=="hidden",children:d.jsx(Zp,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:e,onPointerEnter:Ee(i.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Ee(i.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),yx=S.forwardRef((i,e)=>{const n=Oi(on,i.__scopeScrollArea),{forceMount:r,...l}=i,[u,p]=S.useState(!1),a=i.orientation==="horizontal",c=pu(()=>{if(n.viewport){const f=n.viewport.offsetWidth<n.viewport.scrollWidth,v=n.viewport.offsetHeight<n.viewport.scrollHeight;p(a?f:v)}},10);return eo(n.viewport,c),eo(n.content,c),d.jsx(Qt,{present:r||u,children:d.jsx(Zp,{"data-state":u?"visible":"hidden",...l,ref:e})})}),Zp=S.forwardRef((i,e)=>{const{orientation:n="vertical",...r}=i,l=Oi(on,i.__scopeScrollArea),u=S.useRef(null),p=S.useRef(0),[a,c]=S.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=Ex(a.viewport,a.content),v={...r,sizes:a,onSizesChange:c,hasThumb:f>0&&f<1,onThumbChange:y=>u.current=y,onThumbPointerUp:()=>p.current=0,onThumbPointerDown:y=>p.current=y};function m(y,C){return fP(y,p.current,a,C)}return n==="horizontal"?d.jsx(lP,{...v,ref:e,onThumbPositionChange:()=>{if(l.viewport&&u.current){const y=l.viewport.scrollLeft,C=Wy(y,a,l.dir);u.current.style.transform=`translate3d(${C}px, 0, 0)`}},onWheelScroll:y=>{l.viewport&&(l.viewport.scrollLeft=y)},onDragScroll:y=>{l.viewport&&(l.viewport.scrollLeft=m(y,l.dir))}}):n==="vertical"?d.jsx(cP,{...v,ref:e,onThumbPositionChange:()=>{if(l.viewport&&u.current){const y=l.viewport.scrollTop,C=Wy(y,a);u.current.style.transform=`translate3d(0, ${C}px, 0)`}},onWheelScroll:y=>{l.viewport&&(l.viewport.scrollTop=y)},onDragScroll:y=>{l.viewport&&(l.viewport.scrollTop=m(y))}}):null}),lP=S.forwardRef((i,e)=>{const{sizes:n,onSizesChange:r,...l}=i,u=Oi(on,i.__scopeScrollArea),[p,a]=S.useState(),c=S.useRef(null),f=Ge(e,c,u.onScrollbarXChange);return S.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(wx,{"data-orientation":"horizontal",...l,ref:f,sizes:n,style:{bottom:0,left:u.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:u.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":fu(n)+"px",...i.style},onThumbPointerDown:v=>i.onThumbPointerDown(v.x),onDragScroll:v=>i.onDragScroll(v.x),onWheelScroll:(v,m)=>{if(u.viewport){const y=u.viewport.scrollLeft+v.deltaX;i.onWheelScroll(y),Ax(y,m)&&v.preventDefault()}},onResize:()=>{c.current&&u.viewport&&p&&r({content:u.viewport.scrollWidth,viewport:u.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:zc(p.paddingLeft),paddingEnd:zc(p.paddingRight)}})}})}),cP=S.forwardRef((i,e)=>{const{sizes:n,onSizesChange:r,...l}=i,u=Oi(on,i.__scopeScrollArea),[p,a]=S.useState(),c=S.useRef(null),f=Ge(e,c,u.onScrollbarYChange);return S.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(wx,{"data-orientation":"vertical",...l,ref:f,sizes:n,style:{top:0,right:u.dir==="ltr"?0:void 0,left:u.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":fu(n)+"px",...i.style},onThumbPointerDown:v=>i.onThumbPointerDown(v.y),onDragScroll:v=>i.onDragScroll(v.y),onWheelScroll:(v,m)=>{if(u.viewport){const y=u.viewport.scrollTop+v.deltaY;i.onWheelScroll(y),Ax(y,m)&&v.preventDefault()}},onResize:()=>{c.current&&u.viewport&&p&&r({content:u.viewport.scrollHeight,viewport:u.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:zc(p.paddingTop),paddingEnd:zc(p.paddingBottom)}})}})}),[uP,Sx]=gx(on),wx=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:l,onThumbChange:u,onThumbPointerUp:p,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:f,onWheelScroll:v,onResize:m,...y}=i,C=Oi(on,n),[R,E]=S.useState(null),g=Ge(e,j=>E(j)),b=S.useRef(null),_=S.useRef(""),x=C.viewport,A=r.content-r.viewport,D=Wt(v),N=Wt(c),O=pu(m,10);function T(j){if(b.current){const H=j.clientX-b.current.left,I=j.clientY-b.current.top;f({x:H,y:I})}}return S.useEffect(()=>{const j=H=>{const I=H.target;R?.contains(I)&&D(H,A)};return document.addEventListener("wheel",j,{passive:!1}),()=>document.removeEventListener("wheel",j,{passive:!1})},[x,R,A,D]),S.useEffect(N,[r,N]),eo(R,O),eo(C.content,O),d.jsx(uP,{scope:n,scrollbar:R,hasThumb:l,onThumbChange:Wt(u),onThumbPointerUp:Wt(p),onThumbPositionChange:N,onThumbPointerDown:Wt(a),children:d.jsx(Ne.div,{...y,ref:g,style:{position:"absolute",...y.style},onPointerDown:Ee(i.onPointerDown,j=>{j.button===0&&(j.target.setPointerCapture(j.pointerId),b.current=R.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",C.viewport&&(C.viewport.style.scrollBehavior="auto"),T(j))}),onPointerMove:Ee(i.onPointerMove,T),onPointerUp:Ee(i.onPointerUp,j=>{const H=j.target;H.hasPointerCapture(j.pointerId)&&H.releasePointerCapture(j.pointerId),document.body.style.webkitUserSelect=_.current,C.viewport&&(C.viewport.style.scrollBehavior=""),b.current=null})})})}),Pc="ScrollAreaThumb",xx=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Sx(Pc,i.__scopeScrollArea);return d.jsx(Qt,{present:n||l.hasThumb,children:d.jsx(dP,{ref:e,...r})})}),dP=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,style:r,...l}=i,u=Oi(Pc,n),p=Sx(Pc,n),{onThumbPositionChange:a}=p,c=Ge(e,m=>p.onThumbChange(m)),f=S.useRef(void 0),v=pu(()=>{f.current&&(f.current(),f.current=void 0)},100);return S.useEffect(()=>{const m=u.viewport;if(m){const y=()=>{if(v(),!f.current){const C=pP(m,a);f.current=C,a()}};return a(),m.addEventListener("scroll",y),()=>m.removeEventListener("scroll",y)}},[u.viewport,v,a]),d.jsx(Ne.div,{"data-state":p.hasThumb?"visible":"hidden",...l,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ee(i.onPointerDownCapture,m=>{const C=m.target.getBoundingClientRect(),R=m.clientX-C.left,E=m.clientY-C.top;p.onThumbPointerDown({x:R,y:E})}),onPointerUp:Ee(i.onPointerUp,p.onThumbPointerUp)})});xx.displayName=Pc;var Jp="ScrollAreaCorner",Cx=S.forwardRef((i,e)=>{const n=Oi(Jp,i.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.jsx(hP,{...i,ref:e}):null});Cx.displayName=Jp;var hP=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,...r}=i,l=Oi(Jp,n),[u,p]=S.useState(0),[a,c]=S.useState(0),f=!!(u&&a);return eo(l.scrollbarX,()=>{const v=l.scrollbarX?.offsetHeight||0;l.onCornerHeightChange(v),c(v)}),eo(l.scrollbarY,()=>{const v=l.scrollbarY?.offsetWidth||0;l.onCornerWidthChange(v),p(v)}),f?d.jsx(Ne.div,{...r,ref:e,style:{width:u,height:a,position:"absolute",right:l.dir==="ltr"?0:void 0,left:l.dir==="rtl"?0:void 0,bottom:0,...i.style}}):null});function zc(i){return i?parseInt(i,10):0}function Ex(i,e){const n=i/e;return isNaN(n)?0:n}function fu(i){const e=Ex(i.viewport,i.content),n=i.scrollbar.paddingStart+i.scrollbar.paddingEnd,r=(i.scrollbar.size-n)*e;return Math.max(r,18)}function fP(i,e,n,r="ltr"){const l=fu(n),u=l/2,p=e||u,a=l-p,c=n.scrollbar.paddingStart+p,f=n.scrollbar.size-n.scrollbar.paddingEnd-a,v=n.content-n.viewport,m=r==="ltr"?[0,v]:[v*-1,0];return Dx([c,f],m)(i)}function Wy(i,e,n="ltr"){const r=fu(e),l=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,u=e.scrollbar.size-l,p=e.content-e.viewport,a=u-r,c=n==="ltr"?[0,p]:[p*-1,0],f=Vf(i,c);return Dx([0,p],[0,a])(f)}function Dx(i,e){return n=>{if(i[0]===i[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(i[1]-i[0]);return e[0]+r*(n-i[0])}}function Ax(i,e){return i>0&&i<e}var pP=(i,e=()=>{})=>{let n={left:i.scrollLeft,top:i.scrollTop},r=0;return(function l(){const u={left:i.scrollLeft,top:i.scrollTop},p=n.left!==u.left,a=n.top!==u.top;(p||a)&&e(),n=u,r=window.requestAnimationFrame(l)})(),()=>window.cancelAnimationFrame(r)};function pu(i,e){const n=Wt(i),r=S.useRef(0);return S.useEffect(()=>()=>window.clearTimeout(r.current),[]),S.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,e)},[n,e])}function eo(i,e){const n=Wt(e);Nt(()=>{let r=0;if(i){const l=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return l.observe(i),()=>{window.cancelAnimationFrame(r),l.unobserve(i)}}},[i,n])}var kx=vx,mP=bx,gP=Cx;const mu=S.forwardRef(({className:i,children:e,...n},r)=>d.jsxs(kx,{ref:r,className:we("relative overflow-hidden",i),...n,children:[d.jsx(mP,{className:"h-full w-full rounded-[inherit]",children:e}),d.jsx(Tx,{}),d.jsx(gP,{})]}));mu.displayName=kx.displayName;const Tx=S.forwardRef(({className:i,orientation:e="vertical",...n},r)=>d.jsx(Xp,{ref:r,orientation:e,className:we("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",i),...n,children:d.jsx(xx,{className:"relative flex-1 rounded-full bg-border"})}));Tx.displayName=Xp.displayName;var gu="Collapsible",[vP]=pi(gu),[_P,Qp]=vP(gu),Rx=S.forwardRef((i,e)=>{const{__scopeCollapsible:n,open:r,defaultOpen:l,disabled:u,onOpenChange:p,...a}=i,[c,f]=Ni({prop:r,defaultProp:l??!1,onChange:p,caller:gu});return d.jsx(_P,{scope:n,disabled:u,contentId:Ht(),open:c,onOpenToggle:S.useCallback(()=>f(v=>!v),[f]),children:d.jsx(Ne.div,{"data-state":tm(c),"data-disabled":u?"":void 0,...a,ref:e})})});Rx.displayName=gu;var Nx="CollapsibleTrigger",Ox=S.forwardRef((i,e)=>{const{__scopeCollapsible:n,...r}=i,l=Qp(Nx,n);return d.jsx(Ne.button,{type:"button","aria-controls":l.contentId,"aria-expanded":l.open||!1,"data-state":tm(l.open),"data-disabled":l.disabled?"":void 0,disabled:l.disabled,...r,ref:e,onClick:Ee(i.onClick,l.onOpenToggle)})});Ox.displayName=Nx;var em="CollapsibleContent",jx=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Qp(em,i.__scopeCollapsible);return d.jsx(Qt,{present:n||l.open,children:({present:u})=>d.jsx(bP,{...r,ref:e,present:u})})});jx.displayName=em;var bP=S.forwardRef((i,e)=>{const{__scopeCollapsible:n,present:r,children:l,...u}=i,p=Qp(em,n),[a,c]=S.useState(r),f=S.useRef(null),v=Ge(e,f),m=S.useRef(0),y=m.current,C=S.useRef(0),R=C.current,E=p.open||a,g=S.useRef(E),b=S.useRef(void 0);return S.useEffect(()=>{const _=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(_)},[]),Nt(()=>{const _=f.current;if(_){b.current=b.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const x=_.getBoundingClientRect();m.current=x.height,C.current=x.width,g.current||(_.style.transitionDuration=b.current.transitionDuration,_.style.animationName=b.current.animationName),c(r)}},[p.open,r]),d.jsx(Ne.div,{"data-state":tm(p.open),"data-disabled":p.disabled?"":void 0,id:p.contentId,hidden:!E,...u,ref:v,style:{"--radix-collapsible-content-height":y?`${y}px`:void 0,"--radix-collapsible-content-width":R?`${R}px`:void 0,...i.style},children:E&&l})});function tm(i){return i?"open":"closed"}var yP=Rx;const Mx=yP,Lx=Ox,Px=jx;function SP(){const[i,e]=S.useState({}),[n,r]=S.useState(new Set),[l,u]=S.useState(null),p=S.useCallback(async a=>{if(!(i[a]||n.has(a))){r(c=>new Set(c).add(a)),u(null);try{const c=a?`?path=${encodeURIComponent(a)}`:"",f=await fetch(`/api/files${c}`);if(!f.ok)throw new Error(`Failed to list directory: ${f.statusText}`);const m=(await f.json()).entries.sort((y,C)=>y.type!==C.type?y.type==="directory"?-1:1:y.name.localeCompare(C.name));e(y=>({...y,[a||"__root__"]:m}))}catch(c){u(c instanceof Error?c.message:"Failed to load directory")}finally{r(c=>{const f=new Set(c);return f.delete(a),f})}}},[i,n]);return{cache:i,loading:n,error:l,fetchDirectory:p}}function zx({entry:i,status:e,depth:n,onFileClick:r}){const l=e==="created"?"+":e==="modified"?"~":e==="deleted"?"-":null;return d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("div",{role:"treeitem",className:`file-item${e?` file-${e}`:""}`,style:{paddingLeft:`${12+n*16}px`},tabIndex:0,"aria-label":`${i.name}${e?`, ${e}`:""}`,onClick:()=>r?.(i,e),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),r?.(i,e))},children:[l&&d.jsx("span",{className:`status-icon status-${e}`,"aria-hidden":"true",children:l}),d.jsx("span",{className:"file-name",children:i.name})]})}),d.jsx(Oe,{children:i.path})]})}function Bx({entry:i,depth:e,changedFiles:n,onFileClick:r,fetchDirectory:l,cache:u,loading:p}){const a=Array.from(n.keys()).some(C=>C.startsWith(i.path+"/")),[c,f]=S.useState(a),v=u[i.path],m=p.has(i.path);S.useEffect(()=>{a&&!v&&!p.has(i.path)&&l(i.path)},[a,v,i.path,l,p]),S.useEffect(()=>{a&&f(!0)},[a]);const y=S.useCallback(()=>{const C=!c;f(C),C&&!v&&l(i.path)},[c,v,i.path,l]);return d.jsxs(Mx,{open:c,onOpenChange:y,children:[d.jsx(Lx,{asChild:!0,children:d.jsxs("div",{className:`directory-header${a?" has-changes":""}`,style:{paddingLeft:`${4+e*16}px`},children:[d.jsx("span",{className:"directory-toggle",children:d.jsx("span",{className:"toggle-icon",children:c?"▼":"▶"})}),d.jsx("span",{className:"directory-name",children:i.name})]})}),d.jsxs(Px,{children:[m&&d.jsx("div",{className:"tree-loading",style:{paddingLeft:`${12+(e+1)*16}px`},children:"Loading..."}),v?.map(C=>C.type==="directory"?d.jsx(Bx,{entry:C,depth:e+1,changedFiles:n,onFileClick:r,fetchDirectory:l,cache:u,loading:p},C.path):d.jsx(zx,{entry:C,status:n.get(C.path),depth:e+1,onFileClick:r},C.path))]})]})}function wP({changedFiles:i,onFileClick:e}){const{cache:n,loading:r,error:l,fetchDirectory:u}=SP();S.useEffect(()=>{u("")},[]);const p=n.__root__,a=i.size;return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{role:"tree","aria-label":"Project files",className:"filetree full-filetree",children:[a>0&&d.jsx(Ke,{variant:"secondary","data-testid":"file-count-badge",className:"file-count-badge","aria-label":`${a} files changed`,children:a}),d.jsxs(mu,{className:"filetree-scroll",children:[l&&d.jsx("div",{className:"tree-error",children:l}),!p&&!l&&d.jsx("div",{className:"tree-loading",children:"Loading project files..."}),p?.map(c=>c.type==="directory"?d.jsx(Bx,{entry:c,depth:0,changedFiles:i,onFileClick:e,fetchDirectory:u,cache:n,loading:r},c.path):d.jsx(zx,{entry:c,status:i.get(c.path),depth:0,onFileClick:e},c.path))]})]})})}function Vy(i){const e=i[0]||" ",n=i[1]||" ";return e==="D"||n==="D"?"deleted":e==="?"||e==="A"?"created":"modified"}function Ix(){const{repos:i}=ux(),e=S.useMemo(()=>{const r=new Map;for(const l of i)for(const u of l.files){const p=i.length>1?`${l.path}/${u.path}`:`${l.path}/${u.path}`;r.set(p,Vy(u.status)),r.set(u.path,Vy(u.status))}return r},[i]),n=S.useCallback((r,l)=>{fetch("/api/files/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r.path})}).catch(u=>console.error("[ChangedPanel] Failed to open file:",u))},[]);return d.jsx("div",{className:"changed-panel","data-testid":"changed-panel",children:d.jsx(wP,{changedFiles:e,onFileClick:n})})}const xP=2e3;function CP(){const[i,e]=S.useState([]),[n,r]=S.useState(null),l=S.useRef(null);S.useEffect(()=>{let a=null,c=!0;const f=()=>{const v=window.location.protocol==="https:"?"wss:":"ws:",m=new WebSocket(`${v}//${window.location.host}/ws/diffs`);l.current=m,m.onopen=()=>{console.log("[useDiffs] WebSocket connected")},m.onmessage=y=>{try{const C=JSON.parse(y.data);if(C.type==="init"){const R=C.diffs||[];e(R),R.length>0&&r(R[R.length-1])}else if(C.type==="diff"){const R=C.diff;e(E=>{const g=E.findIndex(b=>b.path===R.path);if(g>=0){const b=[...E];return b[g]=R,b}return[...E,R]}),r(R)}else if(C.type==="refresh"){const R=C.diffs||[];e(R),R.length>0?r(E=>{if(E){const g=R.find(b=>b.path===E.path);if(g)return g}return R[R.length-1]}):r(null)}}catch(C){console.error("[useDiffs] Failed to parse message:",C)}},m.onclose=()=>{c&&(a=setTimeout(f,xP))},m.onerror=y=>{console.error("[useDiffs] WebSocket error:",y),m.close()}};return f(),()=>{c=!1,a&&clearTimeout(a),l.current?.close()}},[]);const u=S.useCallback(a=>{const c=i.find(f=>f.path===a);r(c||null)},[i]),p=S.useCallback(()=>{e([]),r(null),l.current?.readyState===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"clear"}))},[]);return{diffs:i,selectedDiff:n,selectDiff:u,clearDiffs:p}}function EP({line:i,type:e,lineNum:n}){return d.jsxs("div",{className:`diff-line diff-${e}`,children:[n!==void 0&&d.jsx("span",{className:"line-num",children:n}),d.jsx("span",{className:"line-content",children:i})]})}function DP(i){const e=i.split(`
63
+ `)}function fM(i,e){return i==="Read"&&e.file_path?String(e.file_path):i==="Bash"&&e.command?String(e.command):i==="Glob"&&e.pattern||i==="Grep"&&e.pattern?String(e.pattern):i==="Write"&&e.file_path?String(e.file_path):JSON.stringify(e,null,2)}function Rw(i){return{Read:"R",Write:"W",Bash:"B",Glob:"G",Grep:"S",Edit:"E",Task:"T",WebFetch:"F",WebSearch:"W",TodoWrite:"D"}[i]||i.charAt(0).toUpperCase()}function $p({toolUse:i,result:e,className:n}){const[r,l]=S.useState(!0),[u,p]=S.useState(!0),[a,c]=S.useState(!1),[f,v]=S.useState("idle"),m=e?.is_error===!0,y=fM(i.tool_name,i.input),C=Object.keys(i.input).length,R=lM(i.tool_name),E=S.useMemo(()=>Gf(i.tool_name,i.input),[i.tool_name,i.input]),g=S.useMemo(()=>e?dM(e.content):0,[e?.content]),b=g>Ey,_=b&&!a,x=S.useMemo(()=>e?_?hM(e.content,Ey):e.content:"",[e?.content,_]),A=async()=>{if(e)try{await navigator.clipboard.writeText(e.content),v("copied"),setTimeout(()=>v("idle"),2e3)}catch{v("error")}},D=g===1?"1 line":`${g} lines`,N=["tool-call-block",R,m?"tool-error":"",n||""].filter(Boolean).join(" "),O=Rw(i.tool_name);return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{"data-testid":"tool-call-block",className:N,children:[d.jsxs("div",{className:"tool-header",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"default",className:"tool-type-badge",children:O})}),d.jsx(Oe,{children:i.tool_name})]}),d.jsx("span",{className:"tool-name",children:E}),d.jsx("span",{"data-testid":"tool-duration",className:"tool-duration",children:e?.durationMs!==void 0?Tw(e.durationMs):""})]}),d.jsx("div",{className:"tool-result-header",children:d.jsxs(De,{variant:"ghost",size:"sm","data-testid":"tool-prompt-toggle",className:"tool-result-toggle",onClick:()=>p(!u),children:[u?"▶":"▼"," Prompt (",C," ",C===1?"param":"params",")"]})}),d.jsx("div",{"data-testid":"tool-prompt-content",className:`tool-result-content ${u?"collapsed":""}`,children:d.jsx("pre",{children:y})}),e&&d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"tool-result-header",children:[d.jsxs(De,{variant:"ghost",size:"sm","data-testid":"tool-result-toggle",className:"tool-result-toggle",onClick:()=>l(!r),children:[r?"▶":"▼"," Result (",D,")"]}),d.jsx(De,{variant:"ghost",size:"icon","data-testid":"tool-result-copy",className:`tool-result-copy ${f==="copied"?"copied":""} ${f==="error"?"copy-error":""}`,onClick:A,"aria-label":"Copy result to clipboard",children:f==="copied"?"✓":"📋"})]}),d.jsxs("div",{"data-testid":"tool-result-content",className:`tool-result-content ${r?"collapsed":""} ${_&&!r?"truncated":""} ${m?"error-content":""}`,children:[d.jsx("pre",{children:x}),b&&!r&&_&&d.jsxs(De,{variant:"link",size:"sm","data-testid":"tool-result-expand",className:"tool-result-expand",onClick:()=>c(!0),children:["Show all (",g," lines)"]})]})]})]})})}function pM({stack:i,toolResults:e}){const[n,r]=S.useState(!i.isActive),l=S.useRef(i.isActive);S.useEffect(()=>{l.current&&!i.isActive&&r(!1),l.current=i.isActive},[i.isActive]);const u=`${i.count}`,p=S.useMemo(()=>{if(i.isActive&&i.tools.length>0){const R=i.tools[i.tools.length-1];return Gf(R.tool_name,R.input)}return null},[i.tools,i.isActive]),a=S.useMemo(()=>{if(i.tools.length===0)return"";const R=i.tools[i.tools.length-1];return Gf(R.tool_name,R.input)},[i.tools]),c=S.useMemo(()=>{const R=new Map;return i.tools.forEach(E=>{const g=R.get(E.tool_name)||0;R.set(E.tool_name,g+1)}),R},[i.tools]),f=S.useMemo(()=>i.tools.reduce((R,E)=>{const g=e.get(E.tool_id);return R+(g?.durationMs||0)},0),[i.tools,e]),v=R=>{const E=i.tools[R],g=e.get(E.tool_id);return i.isActive&&R===i.tools.length-1&&!g?"tool-current":"tool-historical"},m=S.useCallback(()=>{r(R=>!R)},[]),y=S.useCallback(R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),m())},[m]),C=!n||i.isActive;return d.jsxs("div",{"data-testid":"tool-stack","data-collapsible":"true",className:`tool-stack ${n&&!i.isActive?"collapsed":""}`,children:[d.jsxs("div",{"data-testid":"tool-stack-header",className:"tool-stack-header",onClick:m,onKeyDown:y,role:"button",tabIndex:0,"aria-expanded":!n||i.isActive,"aria-label":`Tool stack with ${u}: ${a}`,children:[d.jsx("span",{className:"tool-stack-toggle",children:n&&!i.isActive?"▶":"▼"}),d.jsx("span",{"data-testid":"tool-stack-count",className:"tool-stack-count-badge",children:u}),i.isActive&&p?d.jsx("span",{className:"tool-stack-active-summary",children:p}):d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"tool-stack-badges",children:d.jsx(wt,{delayDuration:300,children:Array.from(c.entries()).slice(0,4).map(([R,E])=>d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"outline",className:`tool-mini-badge badge-${R.toLowerCase()}`,children:Rw(R)})}),d.jsx(Oe,{children:`${E} ${R} call${E>1?"s":""}`})]},R))})}),d.jsx("span",{className:"tool-stack-summary",children:a})]}),d.jsx("span",{className:"tool-stack-duration",children:f>0?Tw(f):""})]}),C&&d.jsx("div",{className:"tool-stack-content",children:i.tools.map((R,E)=>{const g=e.get(R.tool_id),b=v(E);return d.jsx($p,{toolUse:{type:"tool_use",tool_name:R.tool_name,tool_id:R.tool_id,input:R.input,timestamp:R.timestamp},result:g?{type:"tool_result",tool_id:g.tool_id,content:g.content,timestamp:g.timestamp}:void 0,className:b},R.tool_id||`tool-${E}`)})})]})}const af=new Map;let Mc=null;async function mM(){if(!Mc)try{const i=await fetch("/api/theme-agents/full");i.ok&&(Mc=await i.json())}catch{}}async function gM(i){const e=`agent:${i}`;if(af.has(e))return af.get(e);try{if(await mM(),Mc?.agents){const n=Mc.agents.find(r=>r.role===i);if(n?.helper)return af.set(e,n.helper),n.helper}return null}catch{return null}}const Dy={"testing-runner":"Running tests",Explore:"Exploring codebase","sm-setup":"Setting up story","sm-finish":"Finishing story",handoff:"Handing off","workflow-status-check":"Checking workflow status","general-purpose":"Processing task",Plan:"Planning implementation",Bash:"Running commands"};function vM(i,e){const n=e?.plural?"are":"is",r=i.description,l=i.subagent_type;if(l&&Dy[l]){const u=Dy[l],p=u.charAt(0).toLowerCase()+u.slice(1);return r?`${n} ${p}: ${r}`:`${n} ${p}`}return r||"Working..."}function _M(){const[i,e]=S.useState(null),[n,r]=S.useState(!0),[l,u]=S.useState(null);return S.useEffect(()=>{const p=async f=>{try{const v=await gM(f);e(v),r(!1)}catch(v){u(v instanceof Error?v:new Error("Failed to fetch helper")),r(!1)}},a=window.location.protocol==="https:"?"wss:":"ws:",c=new WebSocket(`${a}//${window.location.host}/ws/persona`);return c.onmessage=f=>{try{const v=JSON.parse(f.data);v?.role&&p(v.role)}catch(v){u(v instanceof Error?v:new Error("Failed to parse persona")),r(!1)}},c.onerror=()=>{u(new Error("WebSocket connection failed")),r(!1)},()=>c.close()},[]),{helper:i,isLoading:n,error:l}}function bM({type:i,name:e,messages:n,defaultCollapsed:r=!0,onCollapseChange:l,helperName:u,helperStyle:p,friendlyMessage:a}){const[c,f]=S.useState(r),{helper:v}=_M(),m=S.useMemo(()=>vM({subagent_type:i,description:e},{plural:v?.plural}),[i,e,v?.plural]),y=u??v?.name,C=p??v?.style,R=a??m,E=y||i,g=R||e,b=n.filter(A=>A.type!=="tool_result").length,_=new Map;n.forEach(A=>{A.type==="tool_result"&&A.tool_id&&_.set(A.tool_id,A)});const x=(A,D)=>{if(A.type==="tool_use"&&A.tool_name&&A.tool_id){const N=_.get(A.tool_id);return d.jsx("div",{"data-testid":"message-tool_use",className:"message message-tool_use",children:d.jsx($p,{toolUse:{type:"tool_use",tool_name:A.tool_name,tool_id:A.tool_id,input:A.input||{},timestamp:A.timestamp},result:N?{type:"tool_result",tool_id:N.tool_id,content:N.content||"",timestamp:N.timestamp}:void 0})},`tool-wrapper-${A.tool_id}`)}if(A.type==="tool_result")return null;if(A.type==="user"){const N=(A.content||"").slice(0,120).replace(/\n/g," ");return d.jsx("div",{"data-testid":"subagent-prompt",className:"message message-subagent-prompt",children:d.jsxs("div",{className:"message-content",children:[N,(A.content||"").length>120?"...":""]})},`subagent-prompt-${D}`)}return d.jsx(kw,{message:{type:A.type,content:A.content,timestamp:A.timestamp}},`msg-${D}`)};return d.jsxs("div",{"data-testid":"subagent-span","data-collapsible":"true",className:`subagent-span subagent-${i} ${c?"collapsed":""}`,children:[d.jsxs("div",{"data-testid":"subagent-span-header",className:"subagent-header",onClick:()=>{const A=!c;f(A),l?.(A)},children:[d.jsx("span",{className:"subagent-toggle",children:c?"▶":"▼"}),d.jsx(wt,{delayDuration:300,children:C?d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"subagent-helper-name",children:E})}),d.jsx(Oe,{children:C})]}):d.jsx("span",{className:"subagent-helper-name",children:E})}),d.jsx("span",{className:"subagent-friendly-message",children:g}),d.jsx(Ke,{variant:"outline","data-testid":"subagent-type-badge",className:"subagent-type-badge",children:i}),d.jsx("span",{className:"subagent-count",children:b})]}),!c&&d.jsx("div",{className:"subagent-content",children:n.map((A,D)=>x(A,D))})]})}const Ay=/<!--\s*CYCLIST:(\w+)(?::([^>]+?))?\s*-->/gi,Hs={HANDOFF:"handoff",CONTEXT_CLEAR:"context_clear",INVOKE:"invoke",QUESTION:"question",CHOICES:"choices",CONTINUE:"continue"},yM=new Set(["handoff","context_clear","invoke","question","choices","continue"]);function SM(i){return i?i.replace(/```[\s\S]*?```/g,""):""}function wM(i){if(!i)return null;const e=SM(i);if(!e.trim())return null;const n=[];Ay.lastIndex=0;let r;for(;(r=Ay.exec(e))!==null;){const l=r[1].toLowerCase();yM.has(l)&&n.push({type:l,value:r[2]?.trim()??"",source:"structured_marker"})}return n.length>0?n:null}function xM(i,e){if(!i)return e.map(u=>({number:u,text:`Option ${u}`}));const n=i.replace(/```[\s\S]*?```/g,""),r=[/^\s*(\d+)\.\s+(.+)$/gm,/^\s*(\d+)\)\s+(.+)$/gm,/\*\*(\d+)[.)]\*\*\s*(.+)/gm],l=new Map;for(const u of r){u.lastIndex=0;let p;for(;(p=u.exec(n))!==null;){const a=parseInt(p[1],10);if(e.includes(a)&&!l.has(a)){let c=p[2].trim();const f=c.search(/\s+[-—]\s+/);f>0&&f<30&&(c=c.substring(0,f)),l.set(a,c)}}}return e.map(u=>({number:u,text:l.get(u)||`Option ${u}`}))}function CM(i,e){if(!i||i.length===0)return null;const n=i[0];switch(n.type){case Hs.HANDOFF:return{type:"handoff",value:n.value,responses:[n.value,"Not yet"]};case Hs.INVOKE:return{type:"invoke",value:n.value,autoExecute:!0};case Hs.QUESTION:{if(n.value==="yesno")return{type:"yesno",responses:["Yes","No"]};if(n.value?.startsWith("open")){const l=n.value.indexOf(":");if(l!==-1){const u=n.value.substring(l+1).trim();if(u)return{type:"open",responses:[u]}}return{type:"open"}}const r=i.find(l=>l.type===Hs.CHOICES);return r?ky(r.value,e):null}case Hs.CHOICES:return ky(n.value,e);case Hs.CONTEXT_CLEAR:return{type:"context_clear",value:n.value};case Hs.CONTINUE:return{type:"continue",responses:["Continue"]};default:return null}}function ky(i,e){const n=i.split(",").map(p=>p.trim()),r=n[0],l=/^\d+$/.test(r);let u;if(l){const p=n.map(a=>parseInt(a,10));u=xM(e,p)}else u=n.map((p,a)=>({number:a+1,text:p}));return{type:"choices",choices:u,responses:u.map(p=>p.text)}}function EM(i){return S.useMemo(()=>{if(!i)return null;const e=wM(i);return e?CM(e,i):null},[i])}async function DM(){try{const i=await fetch("/api/settings");if(i.ok)return(await i.json())?.workflow?.relay_mode??!1}catch{}return!1}function AM(i){const{send:e}=ao(),n=S.useCallback(y=>{console.log("[QuickActions] sendMessage called:",y),e(y,[])},[e]),{onAction:r}=i,[l,u]=S.useState(!1),[p,a]=S.useState(!1),c="message"in i?i.message:void 0,f="actions"in i?i.actions:void 0,v=EM(c?.content);S.useEffect(()=>{u(!1)},[c?.timestamp]),S.useEffect(()=>{DM().then(a)},[]),S.useEffect(()=>{const y=()=>{u(!0)};return window.addEventListener("cyclist:user-submit",y),()=>{window.removeEventListener("cyclist:user-submit",y)}},[]),S.useEffect(()=>{if(v?.type==="handoff"&&p&&v.value){const y=setTimeout(()=>{n(v.value),u(!0),r?.(v.value)},100);return()=>clearTimeout(y)}if(v?.type==="invoke"&&v.value){const y=setTimeout(()=>{n(v.value),u(!0),r?.(v.value)},100);return()=>clearTimeout(y)}},[v,p,r]),S.useEffect(()=>{if(v?.type==="open"&&v.responses&&v.responses.length>0){const y=v.responses[0];window.dispatchEvent(new CustomEvent("cyclist:suggest-prompt",{detail:{prompt:y}}))}},[v]);const m=S.useCallback(y=>{console.log("[QuickActions] Button clicked:",y),u(!0),n(y),r?.(y)},[r]);return f&&f.length>0?d.jsx("div",{className:"quick-actions",children:d.jsx("div",{className:"quick-actions-buttons",children:f.map(y=>d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m(y.command),disabled:l,"aria-label":`${y.label}: ${y.command}`,children:y.label},y.command))})}):!v||v.type==="open"||v.type==="continue"?null:v.type==="invoke"?d.jsx("div",{className:"quick-actions",children:d.jsxs("span",{className:"auto-invoke-status",children:["Invoking ",v.value,"..."]})}):v.type==="handoff"&&p?d.jsx("div",{className:"quick-actions",children:d.jsxs("span",{className:"auto-invoke-status",children:["Handing off to ",v.value,"..."]})}):d.jsxs("div",{className:"quick-actions",children:[v.type==="handoff"&&v.responses&&d.jsx("div",{className:"quick-actions-buttons",children:v.responses.map(y=>d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m(y),disabled:l,"aria-label":`Continue with ${y}`,children:y},y))}),v.type==="yesno"&&d.jsxs("div",{className:"quick-actions-buttons",children:[d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m("Yes"),disabled:l,"aria-label":"Answer Yes",children:"Yes"}),d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m("No"),disabled:l,"aria-label":"Answer No",children:"No"})]}),v.type==="choices"&&v.choices&&d.jsx("div",{className:"quick-actions-buttons",children:v.choices.map(y=>d.jsx(De,{variant:"secondary",size:"sm",type:"button",className:"quick-action-btn",onClick:()=>m(y.text),disabled:l,"aria-label":`Choose option ${y.number}: ${y.text}`,children:y.text},y.number))})]})}var kM="Separator",Ty="horizontal",TM=["horizontal","vertical"],Nw=S.forwardRef((i,e)=>{const{decorative:n,orientation:r=Ty,...l}=i,u=RM(r)?r:Ty,a=n?{role:"none"}:{"aria-orientation":u==="vertical"?u:void 0,role:"separator"};return d.jsx(Wi.div,{"data-orientation":u,...a,...l,ref:e})});Nw.displayName=kM;function RM(i){return TM.includes(i)}var Ow=Nw;const Rt=S.forwardRef(({className:i,orientation:e="horizontal",decorative:n=!0,...r},l)=>d.jsx(Ow,{ref:l,decorative:n,orientation:e,className:we("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",i),...r}));Rt.displayName=Ow.displayName;const NM=["<command-message>","<command-name>","Base directory for this skill:","Launching skill:"],OM=[/^```bash\s*\npf agent start\b/,/^pf agent start\b/,/^<purpose>/,/^<when-to-use>/,/^<execution>/,/^<critical>\s*\n/],ac={sm:"Scrum Master",tea:"Test Engineer",dev:"Developer",reviewer:"Reviewer",architect:"Architect",pm:"Product Manager","tech-writer":"Tech Writer","ux-designer":"UX Designer",devops:"DevOps",orchestrator:"Orchestrator",ba:"Business Analyst"};function jM(i){if(!i||typeof i!="string")return!1;if(NM.some(n=>i.includes(n)))return!0;const e=i.trimStart();return OM.some(n=>n.test(e))}function MM(i){if(!i||typeof i!="string")return null;const e=i.match(/<command-name>\/?([^<]+)<\/command-name>/);if(e){const u=e[1].trim();return ac[u]||u}const n=i.match(/<command-message>([^<]+)<\/command-message>/);if(n){const u=n[1].trim();return ac[u]||u}const r=i.match(/pf agent start\s+"([^"]+)"/);if(r){const u=r[1].trim();return ac[u]||u}const l=i.match(/Launching skill:\s*(\S+)/);if(l){const u=l[1].trim();return ac[u]||u}return null}function Ry(i){return i.length===0?"stack-empty":`stack-${i[0].tool_id}`}function LM(i){const e=[];let n=[];for(const r of i)if(r.type==="tool_use")n.push({type:"tool_use",tool_name:r.tool_name||"",tool_id:r.tool_id||"",input:r.input||{},timestamp:r.timestamp,isStreaming:r.isStreaming});else{if(r.type==="tool_result")continue;if(n.length>=1){const l=n[n.length-1];e.push({stackId:Ry(n),tools:[...n],count:n.length,isActive:l.isStreaming===!0,timestamp:n[0].timestamp})}n=[]}if(n.length>=1){const r=n[n.length-1];e.push({stackId:Ry(n),tools:[...n],count:n.length,isActive:r.isStreaming===!0,timestamp:n[0].timestamp})}return e}function lf(){const i=document.documentElement.getAttribute("data-variant");return i==="light"||i==="dark"?i:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function jw(){const[i,e]=S.useState(lf);return S.useEffect(()=>{const n=new MutationObserver(()=>{e(lf())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["data-variant"]});const r=()=>e(lf());return window.addEventListener("presetChange",r),()=>{n.disconnect(),window.removeEventListener("presetChange",r)}},[]),i}const Ny=2e3;function Mw(){const[i,e]=S.useState(null),[n,r]=S.useState(null),[l,u]=S.useState(null),[p,a]=S.useState(!0),[c,f]=S.useState(null),v=S.useRef({context:!1,stats:!1,projectInfo:!1}),m=S.useCallback(()=>{const y=v.current;y.context&&y.stats&&y.projectInfo&&a(!1)},[]);return S.useEffect(()=>{let y=null,C=null,R=!0;const E=()=>{const g=window.location.protocol==="https:"?"wss:":"ws:";y=new WebSocket(`${g}//${window.location.host}/ws/context`),y.onopen=()=>{console.log("[useStatsStrip] Context WebSocket connected")},y.onmessage=b=>{try{const _=JSON.parse(b.data);if(_.type==="init"||_.type==="update"){const x=_.context;x&&e({percent:x.percent??0,used:x.tokens??void 0,total:x.available?(x.tokens??0)+x.available:void 0}),v.current.context||(v.current.context=!0,m())}}catch(_){console.error("[useStatsStrip] Failed to parse context message:",_)}},y.onclose=()=>{R&&(C=setTimeout(E,Ny))},y.onerror=b=>{console.error("[useStatsStrip] Context WebSocket error:",b),y?.close()}};return E(),()=>{R=!1,C&&clearTimeout(C),y?.close()}},[m]),S.useEffect(()=>{let y=null,C=null,R=!0;const E=()=>{const g=window.location.protocol==="https:"?"wss:":"ws:";y=new WebSocket(`${g}//${window.location.host}/ws/stats`),y.onopen=()=>{console.log("[useStatsStrip] Stats WebSocket connected")},y.onmessage=b=>{try{const _=JSON.parse(b.data);r({model:_.model??null}),_.pwd&&u(x=>({pwd:_.pwd,jiraEmail:x?.jiraEmail??null,githubUsername:x?.githubUsername??null})),v.current.stats||(v.current.stats=!0,m())}catch(_){console.error("[useStatsStrip] Failed to parse stats message:",_)}},y.onclose=()=>{R&&(C=setTimeout(E,Ny))},y.onerror=b=>{console.error("[useStatsStrip] Stats WebSocket error:",b),y?.close()}};return E(),()=>{R=!1,C&&clearTimeout(C),y?.close()}},[m]),S.useEffect(()=>{(async()=>{try{const C=await fetch("/api/identity");if(C.ok){const R=await C.json();u(E=>({pwd:E?.pwd??"",jiraEmail:R.jiraEmail??null,githubUsername:R.githubUsername??null}))}}catch(C){console.error("[useStatsStrip] Failed to fetch identity:",C),f(C instanceof Error?C:new Error("Failed to fetch identity"))}finally{v.current.projectInfo=!0,m()}})()},[m]),{context:i,stats:n,projectInfo:l,isLoading:p,error:c}}const PM={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"},zM={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function Oy(i){return new Date(i).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function BM(i){if("isToolStack"in i||"messages"in i)return"agent";const e=i;return e.type==="context_cleared"?"system":e.type==="user"||e.type==="bell_injected"?"user":"agent"}function IM({messages:i}){const e=S.useRef(null),[n,r]=S.useState(!0),{persona:l}=du(),u=jw(),{projectInfo:p}=Mw(),a=S.useRef(new Map),c=S.useCallback(g=>{r(g)},[]),f=S.useCallback(()=>{e.current?.scrollToBottom("smooth")},[]),v=S.useMemo(()=>{for(let g=i.length-1;g>=0;g--)if(i[g].type==="agent"&&!i[g].isStreaming)return i[g];return null},[i]),{turns:m,toolResults:y,lastAgentItemIndex:C}=S.useMemo(()=>{const g=new Map;for(const I of i)I.type==="tool_result"&&I.tool_id&&g.set(I.tool_id,I);const b=[],_=new Map;let x=!1;for(const I of i)if(I.type!=="tool_result"){if(I.type==="user"&&jM(I.content)){const z=MM(I.content);z&&!x&&(x=!0,b.push({...I,content:z}));continue}if(I.type==="user"&&(x=!1),I.parent_id){let z=_.get(I.parent_id);z||(z={parent_id:I.parent_id,type:I.subagent_type||"unknown",name:I.subagent_name||"unnamed",messages:[]},_.set(I.parent_id,z)),z.messages.push(I);continue}b.push(I)}const A=LM(b),D=new Map;for(const I of A)for(const z of I.tools)D.set(z.tool_id,I);const N=[],O=new Set,T=new Set;for(const I of b)if(I.type==="tool_use"&&I.tool_id&&D.has(I.tool_id)){const z=D.get(I.tool_id);O.has(z.stackId)||(O.add(z.stackId),N.push({isToolStack:!0,stack:z}))}else N.push(I);for(const[,I]of _)T.has(I.parent_id)||(T.add(I.parent_id),N.push(I));let j=-1;for(let I=N.length-1;I>=0;I--){const z=N[I];if(!("isToolStack"in z)&&!("messages"in z)&&z.type==="agent"){j=I;break}}const H=[];for(const I of N){const z=BM(I),U=H[H.length-1];U&&U.speaker===z?U.items.push(I):H.push({speaker:z,items:[I],timestamp:"timestamp"in I?I.timestamp:Date.now()})}return{turns:H,toolResults:g,lastAgentItemIndex:j}},[i]),R=(g,b,_)=>{if("isToolStack"in g)return d.jsx(pM,{stack:g.stack,toolResults:y},`stack-${g.stack.stackId}`);if("messages"in g&&"parent_id"in g){const A=g,D=a.current.get(A.parent_id)??!0;return d.jsx(bM,{type:A.type,name:A.name,messages:A.messages,defaultCollapsed:D,onCollapseChange:N=>a.current.set(A.parent_id,N)},`subagent-${A.parent_id}`)}const x=g;if(x.type==="tool_use"&&x.tool_name&&x.tool_id){if(x.tool_name==="AskUserQuestion")return null;const A=y.get(x.tool_id);return d.jsx($p,{toolUse:{type:"tool_use",tool_name:x.tool_name,tool_id:x.tool_id,input:x.input||{},timestamp:x.timestamp},result:A?{type:"tool_result",tool_id:A.tool_id,content:A.content||"",timestamp:A.timestamp,is_error:A.is_error,durationMs:A.durationMs}:void 0},`tool-${x.tool_id}`)}return d.jsx(kw,{message:x,isLastAgentMessage:b===C,isFirstInTurn:_},`msg-${b}-${x.timestamp}`)};if(i.length===0)return d.jsx("div",{"data-testid":"message-view",className:"message-view",children:d.jsx("div",{className:"message-view-empty",children:d.jsxs("div",{children:[d.jsx("img",{src:u==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",style:{height:"2.5rem",opacity:.6,display:"block",margin:"0 auto 0.5rem"}}),d.jsxs("div",{children:["Type ",d.jsx("code",{style:{background:"var(--bg-tertiary, #0f0f1a)",padding:"2px 6px",borderRadius:"3px",fontFamily:"var(--font-mono, monospace)"},children:"/sm"})," to start"]})]})})});let E=0;return d.jsxs("div",{"data-testid":"message-view",className:"message-view",role:"log","aria-live":"polite",children:[d.jsx(Aw,{ref:e,onScrollChange:c,autoScroll:n,children:m.map((g,b)=>{if(g.speaker==="system")return g.items.forEach(()=>E++),d.jsx("div",{className:"turn-group turn-system",children:d.jsxs("div",{className:"context-cleared-bar",children:[d.jsx(Rt,{className:"context-cleared-line"}),d.jsx("span",{className:"context-cleared-label",children:"Context cleared"}),d.jsx("span",{className:"context-cleared-time",children:Oy(g.timestamp)}),d.jsx(Rt,{className:"context-cleared-line"})]})},`turn-${b}`);let _=!1;const x=l?.character||"Agent",A=l?.role||null,D=A?zM[A]||A:null,N=A?PM[A]||"#e879f9":void 0,O=p?.githubUsername||"You";return d.jsxs("div",{className:`turn-group turn-${g.speaker}`,children:[d.jsxs("div",{className:"turn-label",children:[d.jsx("span",{className:"turn-speaker",children:g.speaker==="user"?O:x}),g.speaker==="agent"&&D&&d.jsx(Ke,{variant:"default",className:"turn-role-badge",style:{backgroundColor:N},children:D}),d.jsx("span",{className:"turn-timestamp",children:Oy(g.timestamp)})]}),g.items.map(T=>{const j=E++,H=!("isToolStack"in T)&&!("messages"in T)&&T.type!=="tool_use",I=H&&!_;return H&&(_=!0),R(T,j,I)})]},`turn-${b}`)})}),v&&d.jsx(AM,{message:v}),d.jsx("div",{"data-testid":"auto-scroll-indicator","data-active":n.toString(),className:"auto-scroll-indicator",style:{display:"none"}}),d.jsx(De,{variant:"ghost",size:"icon","data-testid":"scroll-to-bottom-button",className:"scroll-to-bottom-button",onClick:f,style:{visibility:n?"hidden":"visible"},children:"↓"})]})}const jy="cyclist-command-history",HM=100;function FM(){const[i,e]=S.useState(()=>{try{const f=localStorage.getItem(jy);return f?JSON.parse(f):[]}catch{return[]}}),n=S.useRef(-1),r=S.useRef(""),l=S.useCallback(f=>{try{localStorage.setItem(jy,JSON.stringify(f))}catch{}},[]),u=S.useCallback(f=>{f.trim()&&e(v=>{if(v.length>0&&v[v.length-1]===f)return v;const m=[...v,f];return m.length>HM&&m.shift(),l(m),m})},[l]),p=S.useCallback(f=>{if(i.length===0)return null;if(n.current===-1)r.current=f,n.current=i.length-1;else if(n.current>0)n.current--;else return null;return i[n.current]},[i]),a=S.useCallback(()=>{if(n.current===-1)return null;if(n.current++,n.current>=i.length){n.current=-1;const f=r.current;return r.current="",f}return i[n.current]},[i]),c=S.useCallback(()=>{n.current=-1,r.current=""},[]);return{addToHistory:u,navigateUp:p,navigateDown:a,resetNavigation:c}}const Lw=[{name:"/add",description:"Add files to context"},{name:"/architect",description:"System Architect - Technical design and architecture"},{name:"/ba",description:"Business Analyst - Requirements discovery and stakeholder analysis"},{name:"/brainstorming",description:"Structured problem-solving brainstorm session"},{name:"/bug",description:"Report a bug"},{name:"/check",description:"Run quality gates (lint, type check, tests) before handoff"},{name:"/chore",description:"Quick commit for small changes without full git-cleanup ceremony"},{name:"/clear",description:"Clear conversation history"},{name:"/close-epic",description:"Close an epic - verify completion, update status, and archive context"},{name:"/compact",description:"Toggle compact mode"},{name:"/config",description:"Show configuration"},{name:"/continue-session",description:"Resume work from a saved checkpoint after context circuit breaker"},{name:"/cost",description:"Show session cost"},{name:"/create-branches-from-story",description:"Create feature branches in both repos from a story"},{name:"/dev",description:"Developer - Feature implementation and coding"},{name:"/devops",description:"DevOps Engineer - Infrastructure and deployment automation"},{name:"/doctor",description:"Check system health"},{name:"/fix-blocker",description:"Quick alias for /patch - fix blocking issue during story work"},{name:"/git-cleanup",description:"Clean up git repos by organizing changes into proper commits/branches by initiative"},{name:"/health-check",description:"Check Pennyfarthing installation health and apply updates"},{name:"/help",description:"Show available commands"},{name:"/init",description:"Initialize CLAUDE.md"},{name:"/login",description:"Authenticate with Anthropic"},{name:"/logout",description:"Clear authentication"},{name:"/memory",description:"Edit CLAUDE.md memory"},{name:"/model",description:"Switch Claude model"},{name:"/new-work",description:"Start the next available story from the sprint backlog"},{name:"/orchestrator",description:"Orchestrator - Coordinator of all agents and meta operations"},{name:"/parallel-work",description:"Start parallel work in a new worktree"},{name:"/party-mode",description:"Free-form creative brainstorming with all agents"},{name:"/patch",description:"Interrupt-driven bug fix during active story work"},{name:"/permissions",description:"View/edit permissions"},{name:"/pm",description:"Product Manager - Strategic planning and prioritization"},{name:"/pr-comments",description:"View PR comments"},{name:"/prime",description:"Load essential project context at agent activation"},{name:"/release",description:"Interactive stepped release with verification gates"},{name:"/repo-status",description:"Check git status of all project repos"},{name:"/retro",description:"Facilitate a sprint retrospective"},{name:"/review",description:"Start code review"},{name:"/reviewer",description:"Code Reviewer - Critical code review and quality enforcement"},{name:"/run-ci",description:"Detect and run CI locally"},{name:"/setup",description:"/setup - Interactive Project Setup"},{name:"/sm",description:"Scrum Master - Story coordination and sprint management"},{name:"/sprint",description:"Sprint status, backlog, and story management - check status, find work, archive completed stories"},{name:"/sprint-planning",description:"Facilitate sprint planning session"},{name:"/standalone",description:"Wrap current changes into a standalone Jira story, branch, PR, and merge"},{name:"/start-epic",description:"Start an epic - move to current sprint and generate tech context"},{name:"/status",description:"Show session status"},{name:"/sync-epic-to-jira",description:"Sync Pennyfarthing epic to Jira MSSCI project using jira CLI"},{name:"/sync-work-with-sprint",description:"Sync Pennyfarthing work session with unified sprint status"},{name:"/tea",description:"Test Engineer/Architect - Test strategy and TDD"},{name:"/tech-writer",description:"Technical Writer - Documentation creation and maintenance"},{name:"/terminal-setup",description:"Configure terminal"},{name:"/theme",description:"Manage persona themes - list, show, set, create, or interactive wizard"},{name:"/update-domain-docs",description:"Update CLAUDE-*.md domain documentation files based on current codebase"},{name:"/ux-designer",description:"UX Designer - User experience design and UI patterns"},{name:"/vim",description:"Toggle vim mode"},{name:"/work",description:"Resume work or start new - smart entry point that picks up where you left off"},{name:"/workflow",description:"List available workflows, show current workflow details, and switch workflows mid-session. Use when checking available workflow types (TDD, trivial, agent-docs), viewing current workflow phase, switching to a different workflow pattern, or managing BikeLane stepped workflows."}].sort((i,e)=>i.name.localeCompare(e.name)),Pw="cyclist:command-frequency";function zw(){if(typeof localStorage>"u")return{};try{const i=localStorage.getItem(Pw);return i?JSON.parse(i):{}}catch{return{}}}function Bw(i){if(typeof localStorage>"u")return;const e=zw();e[i]=(e[i]||0)+1,localStorage.setItem(Pw,JSON.stringify(e))}function GM(i){const e=i.toLowerCase(),n=zw();return Lw.filter(r=>r.name.toLowerCase().startsWith(e)).sort((r,l)=>{const u=n[r.name]||0,p=n[l.name]||0;return p!==u?p-u:r.name.localeCompare(l.name)})}function UM(i){const e=S.useMemo(()=>Lw,[i]),[n,r]=S.useState({visible:!1,commands:[],selectedIndex:0,prefix:""}),l=S.useCallback(m=>GM(m),[e,i]),u=S.useCallback(m=>{const y=l(m);r({visible:!0,commands:y,selectedIndex:0,prefix:m})},[l]),p=S.useCallback(()=>{r({visible:!1,commands:[],selectedIndex:0,prefix:""})},[]),a=S.useCallback(m=>{const y=l(m);y.length===0?p():r(C=>({...C,commands:y,selectedIndex:0,prefix:m}))},[l,p]),c=S.useCallback(()=>{r(m=>{if(m.commands.length===0)return m;const y=m.selectedIndex<=0?m.commands.length-1:m.selectedIndex-1;return{...m,selectedIndex:y}})},[]),f=S.useCallback(()=>{r(m=>{if(m.commands.length===0)return m;const y=m.selectedIndex>=m.commands.length-1?0:m.selectedIndex+1;return{...m,selectedIndex:y}})},[]),v=S.useCallback(()=>{if(!n.visible||n.commands.length===0)return null;const m=n.commands[n.selectedIndex];return p(),m?.name&&Bw(m.name),m?.name||null},[n,p]);return{state:n,showCompletion:u,hideCompletion:p,updateCompletion:a,navigateUp:c,navigateDown:f,selectCurrent:v,isVisible:n.visible}}function Iw(i){const e=i+"CollectionProvider",[n,r]=pi(e),[l,u]=n(e,{collectionRef:{current:null},itemMap:new Map}),p=E=>{const{scope:g,children:b}=E,_=ge.useRef(null),x=ge.useRef(new Map).current;return d.jsx(l,{scope:g,itemMap:x,collectionRef:_,children:b})};p.displayName=e;const a=i+"CollectionSlot",c=Zr(a),f=ge.forwardRef((E,g)=>{const{scope:b,children:_}=E,x=u(a,b),A=Ge(g,x.collectionRef);return d.jsx(c,{ref:A,children:_})});f.displayName=a;const v=i+"CollectionItemSlot",m="data-radix-collection-item",y=Zr(v),C=ge.forwardRef((E,g)=>{const{scope:b,children:_,...x}=E,A=ge.useRef(null),D=Ge(g,A),N=u(v,b);return ge.useEffect(()=>(N.itemMap.set(A,{ref:A,...x}),()=>{N.itemMap.delete(A)})),d.jsx(y,{[m]:"",ref:D,children:_})});C.displayName=v;function R(E){const g=u(i+"CollectionConsumer",E);return ge.useCallback(()=>{const _=g.collectionRef.current;if(!_)return[];const x=Array.from(_.querySelectorAll(`[${m}]`));return Array.from(g.itemMap.values()).sort((N,O)=>x.indexOf(N.ref.current)-x.indexOf(O.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:p,Slot:f,ItemSlot:C},R,r]}var WM=S.createContext(void 0);function hu(i){const e=S.useContext(WM);return i||e||"ltr"}var cf="rovingFocusGroup.onEntryFocus",VM={bubbles:!1,cancelable:!0},Aa="RovingFocusGroup",[Uf,Hw,$M]=Iw(Aa),[qM,Fw]=pi(Aa,[$M]),[YM,KM]=qM(Aa),Gw=S.forwardRef((i,e)=>d.jsx(Uf.Provider,{scope:i.__scopeRovingFocusGroup,children:d.jsx(Uf.Slot,{scope:i.__scopeRovingFocusGroup,children:d.jsx(XM,{...i,ref:e})})}));Gw.displayName=Aa;var XM=S.forwardRef((i,e)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:l=!1,dir:u,currentTabStopId:p,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:c,onEntryFocus:f,preventScrollOnEntryFocus:v=!1,...m}=i,y=S.useRef(null),C=Ge(e,y),R=hu(u),[E,g]=Ni({prop:p,defaultProp:a??null,onChange:c,caller:Aa}),[b,_]=S.useState(!1),x=Wt(f),A=Hw(n),D=S.useRef(!1),[N,O]=S.useState(0);return S.useEffect(()=>{const T=y.current;if(T)return T.addEventListener(cf,x),()=>T.removeEventListener(cf,x)},[x]),d.jsx(YM,{scope:n,orientation:r,dir:R,loop:l,currentTabStopId:E,onItemFocus:S.useCallback(T=>g(T),[g]),onItemShiftTab:S.useCallback(()=>_(!0),[]),onFocusableItemAdd:S.useCallback(()=>O(T=>T+1),[]),onFocusableItemRemove:S.useCallback(()=>O(T=>T-1),[]),children:d.jsx(Ne.div,{tabIndex:b||N===0?-1:0,"data-orientation":r,...m,ref:C,style:{outline:"none",...i.style},onMouseDown:Ee(i.onMouseDown,()=>{D.current=!0}),onFocus:Ee(i.onFocus,T=>{const j=!D.current;if(T.target===T.currentTarget&&j&&!b){const H=new CustomEvent(cf,VM);if(T.currentTarget.dispatchEvent(H),!H.defaultPrevented){const I=A().filter(F=>F.focusable),z=I.find(F=>F.active),U=I.find(F=>F.id===E),q=[z,U,...I].filter(Boolean).map(F=>F.ref.current);Vw(q,v)}}D.current=!1}),onBlur:Ee(i.onBlur,()=>_(!1))})})}),Uw="RovingFocusGroupItem",Ww=S.forwardRef((i,e)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:l=!1,tabStopId:u,children:p,...a}=i,c=Ht(),f=u||c,v=KM(Uw,n),m=v.currentTabStopId===f,y=Hw(n),{onFocusableItemAdd:C,onFocusableItemRemove:R,currentTabStopId:E}=v;return S.useEffect(()=>{if(r)return C(),()=>R()},[r,C,R]),d.jsx(Uf.ItemSlot,{scope:n,id:f,focusable:r,active:l,children:d.jsx(Ne.span,{tabIndex:m?0:-1,"data-orientation":v.orientation,...a,ref:e,onMouseDown:Ee(i.onMouseDown,g=>{r?v.onItemFocus(f):g.preventDefault()}),onFocus:Ee(i.onFocus,()=>v.onItemFocus(f)),onKeyDown:Ee(i.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){v.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const b=QM(g,v.orientation,v.dir);if(b!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let x=y().filter(A=>A.focusable).map(A=>A.ref.current);if(b==="last")x.reverse();else if(b==="prev"||b==="next"){b==="prev"&&x.reverse();const A=x.indexOf(g.currentTarget);x=v.loop?eL(x,A+1):x.slice(A+1)}setTimeout(()=>Vw(x))}}),children:typeof p=="function"?p({isCurrentTabStop:m,hasTabStop:E!=null}):p})})});Ww.displayName=Uw;var ZM={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function JM(i,e){return e!=="rtl"?i:i==="ArrowLeft"?"ArrowRight":i==="ArrowRight"?"ArrowLeft":i}function QM(i,e,n){const r=JM(i.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return ZM[r]}function Vw(i,e=!1){const n=document.activeElement;for(const r of i)if(r===n||(r.focus({preventScroll:e}),document.activeElement!==n))return}function eL(i,e){return i.map((n,r)=>i[(e+r)%i.length])}var tL=Gw,iL=Ww,$w="Toggle",qp=S.forwardRef((i,e)=>{const{pressed:n,defaultPressed:r,onPressedChange:l,...u}=i,[p,a]=Ni({prop:n,onChange:l,defaultProp:r??!1,caller:$w});return d.jsx(Ne.button,{type:"button","aria-pressed":p,"data-state":p?"on":"off","data-disabled":i.disabled?"":void 0,...u,ref:e,onClick:Ee(i.onClick,()=>{i.disabled||a(!p)})})});qp.displayName=$w;var qw=qp,hs="ToggleGroup",[Yw]=pi(hs,[Fw]),Kw=Fw(),Yp=ge.forwardRef((i,e)=>{const{type:n,...r}=i;if(n==="single"){const l=r;return d.jsx(nL,{...l,ref:e})}if(n==="multiple"){const l=r;return d.jsx(sL,{...l,ref:e})}throw new Error(`Missing prop \`type\` expected on \`${hs}\``)});Yp.displayName=hs;var[Xw,Zw]=Yw(hs),nL=ge.forwardRef((i,e)=>{const{value:n,defaultValue:r,onValueChange:l=()=>{},...u}=i,[p,a]=Ni({prop:n,defaultProp:r??"",onChange:l,caller:hs});return d.jsx(Xw,{scope:i.__scopeToggleGroup,type:"single",value:ge.useMemo(()=>p?[p]:[],[p]),onItemActivate:a,onItemDeactivate:ge.useCallback(()=>a(""),[a]),children:d.jsx(Jw,{...u,ref:e})})}),sL=ge.forwardRef((i,e)=>{const{value:n,defaultValue:r,onValueChange:l=()=>{},...u}=i,[p,a]=Ni({prop:n,defaultProp:r??[],onChange:l,caller:hs}),c=ge.useCallback(v=>a((m=[])=>[...m,v]),[a]),f=ge.useCallback(v=>a((m=[])=>m.filter(y=>y!==v)),[a]);return d.jsx(Xw,{scope:i.__scopeToggleGroup,type:"multiple",value:p,onItemActivate:c,onItemDeactivate:f,children:d.jsx(Jw,{...u,ref:e})})});Yp.displayName=hs;var[rL,oL]=Yw(hs),Jw=ge.forwardRef((i,e)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:l=!0,orientation:u,dir:p,loop:a=!0,...c}=i,f=Kw(n),v=hu(p),m={role:"group",dir:v,...c};return d.jsx(rL,{scope:n,rovingFocus:l,disabled:r,children:l?d.jsx(tL,{asChild:!0,...f,orientation:u,dir:v,loop:a,children:d.jsx(Ne.div,{...m,ref:e})}):d.jsx(Ne.div,{...m,ref:e})})}),Lc="ToggleGroupItem",Qw=ge.forwardRef((i,e)=>{const n=Zw(Lc,i.__scopeToggleGroup),r=oL(Lc,i.__scopeToggleGroup),l=Kw(i.__scopeToggleGroup),u=n.value.includes(i.value),p=r.disabled||i.disabled,a={...i,pressed:u,disabled:p},c=ge.useRef(null);return r.rovingFocus?d.jsx(iL,{asChild:!0,...l,focusable:!p,active:u,ref:c,children:d.jsx(My,{...a,ref:e})}):d.jsx(My,{...a,ref:e})});Qw.displayName=Lc;var My=ge.forwardRef((i,e)=>{const{__scopeToggleGroup:n,value:r,...l}=i,u=Zw(Lc,n),p={role:"radio","aria-checked":i.pressed,"aria-pressed":void 0},a=u.type==="single"?p:void 0;return d.jsx(qp,{...a,...l,ref:e,onPressedChange:c=>{c?u.onItemActivate(r):u.onItemDeactivate(r)}})}),ex=Yp,tx=Qw;const ix=ep("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}}),aL=S.forwardRef(({className:i,variant:e,size:n,...r},l)=>d.jsx(qw,{ref:l,className:we(ix({variant:e,size:n,className:i})),...r}));aL.displayName=qw.displayName;const nx=S.createContext({size:"default",variant:"default"}),sx=S.forwardRef(({className:i,variant:e,size:n,children:r,...l},u)=>d.jsx(ex,{ref:u,className:we("flex items-center justify-center gap-1",i),...l,children:d.jsx(nx.Provider,{value:{variant:e,size:n},children:r})}));sx.displayName=ex.displayName;const rx=S.forwardRef(({className:i,children:e,variant:n,size:r,...l},u)=>{const p=S.useContext(nx);return d.jsx(tx,{ref:u,className:we(ix({variant:p.variant||n,size:p.size||r}),i),...l,children:e})});rx.displayName=tx.displayName;const Ly=["plan","manual","accept"],uf={plan:"Plan",manual:"Manual",accept:"Accept"},Py={plan:"Read-only exploration mode",manual:"Ask for permission before actions",accept:"Auto-accept file edits"},lL={plan:"plan",manual:"default",accept:"acceptEdits"},cL={plan:"plan",default:"manual",acceptEdits:"accept"},zy={1:"plan",2:"manual",3:"accept"};function uL(i){S.useEffect(()=>{const e=n=>{(n.metaKey||n.ctrlKey)&&zy[n.key]&&(n.preventDefault(),i(zy[n.key]))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[i])}function dL(){const[i,e]=S.useState("manual"),[n,r]=S.useState(!0),l=S.useRef(null);S.useEffect(()=>{const a=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/claude`,c=new WebSocket(a);l.current=c,c.onopen=()=>{c.send(JSON.stringify({type:"getMode"}))},c.onmessage=v=>{try{const m=JSON.parse(v.data);if(m.type==="mode"&&m.mode){const y=cL[m.mode]||"manual";e(y),r(!1),console.log("[ModeSwitch] Mode synced:",m.mode,"->",y)}}catch(m){console.error("[ModeSwitch] Failed to parse mode response:",m)}},c.onerror=()=>{r(!1)};const f=setTimeout(()=>{n&&r(!1)},2e3);return()=>{clearTimeout(f),c.readyState===WebSocket.OPEN&&c.close(),l.current=null}},[]);const u=S.useCallback(p=>{const a=lL[p];l.current&&l.current.readyState===WebSocket.OPEN?(l.current.send(JSON.stringify({type:"setMode",mode:a})),e(p),console.log("[ModeSwitch] Mode set to:",p,"->",a)):(e(p),console.warn("[ModeSwitch] WebSocket not connected, mode set locally only"))},[]);return{mode:i,setMode:u,isLoading:n}}function hL({mode:i,defaultMode:e="manual",onModeChange:n,className:r="",disabled:l=!1}){const[u,p]=S.useState(e),[a,c]=S.useState(!1),f=i??u;S.useEffect(()=>{const C=window.matchMedia("(prefers-reduced-motion: reduce)");c(C.matches);const R=E=>{c(E.matches)};return C.addEventListener("change",R),()=>C.removeEventListener("change",R)},[]);const v=Ly.indexOf(f),m=S.useCallback(C=>{l||(i||p(C),n?.(C))},[i,l,n]),y=S.useCallback(C=>{C&&m(C)},[m]);return d.jsxs("div",{className:we("mode-switch",l&&"mode-switch--disabled",a&&"reduced-motion",r),"data-testid":"mode-switch",style:a?{transition:"none"}:void 0,children:[d.jsx("div",{className:"mode-switch__highlight","data-testid":"mode-highlight",style:{transform:`translateX(${v*100}%)`,transition:a?"none":void 0},"data-mode":f}),d.jsx(wt,{delayDuration:400,children:d.jsx(sx,{type:"single",value:f,onValueChange:y,disabled:l,className:"relative z-[1] gap-0","aria-label":"Permission mode",children:Ly.map(C=>{const R=f===C;return d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(rx,{value:C,"data-mode":C,"data-testid":`mode-${C}`,"aria-label":`${uf[C]} mode: ${Py[C]}`,className:we("mode-option",R&&"active"),children:uf[C]})}),d.jsx(Oe,{side:"bottom",children:Py[C]})]},C)})})}),d.jsx("div",{className:"visually-hidden",role:"status","aria-live":"polite",children:`${uf[f]} mode selected`})]})}const lc=["image/png","image/jpeg","image/gif","image/webp"],fL=20*1024*1024;function pL({commands:i,selectedIndex:e,visible:n,onSelect:r}){return!n||i.length===0?null:d.jsx("div",{className:"completion-popup","data-testid":"completion-popup",children:i.map((l,u)=>d.jsxs("div",{className:`completion-item ${u===e?"selected":""}`,onClick:()=>r(u),"data-testid":`completion-item-${u}`,children:[d.jsx("span",{className:"completion-name",children:l.name}),d.jsx("span",{className:"completion-desc",children:l.description})]},l.name))})}function mL(i){return i?i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"):""}function gL({queue:i,bellMode:e,onRemove:n,onClear:r,onInject:l}){return i.length===0?null:d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"queue-display","data-testid":"queue-display",children:[d.jsxs("div",{className:"queue-header",children:[d.jsxs("span",{className:"queue-count",children:[i.length," queued"]}),e&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"secondary",className:"queue-mode-badge bell-mode",children:"🔔"})}),d.jsx(Oe,{children:"Bell mode active - messages inject via hook"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"sm",type:"button",className:"queue-clear-btn",onClick:r,children:"Clear"})}),d.jsx(Oe,{children:"Clear all queued messages"})]})]}),d.jsx("ul",{className:"queue-list",children:i.map((u,p)=>{const a=u.text.length>60?u.text.substring(0,60)+"...":u.text,c=u.images&&u.images.length>0;return d.jsxs("li",{className:"queue-item","data-testid":`queue-item-${p}`,children:[d.jsx("span",{className:"queue-item-text",children:mL(a)}),c&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs(Ke,{variant:"outline",className:"queue-image-indicator",children:["📎",u.images.length]})}),d.jsx(Oe,{children:`${u.images.length} image(s) attached`})]}),d.jsxs("div",{className:"queue-item-actions",children:[l&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:"queue-item-inject",onClick:()=>l(p),children:"▶"})}),d.jsx(Oe,{children:"Send now (abort current and send this message)"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:"queue-item-remove",onClick:()=>n(p),children:"×"})}),d.jsx(Oe,{children:"Remove from queue"})]})]})]},p)})})]})})}function vL({images:i,onRemove:e}){return i.length===0?null:d.jsx(wt,{delayDuration:300,children:d.jsx("div",{className:"image-preview","data-testid":"image-preview",children:i.map((n,r)=>d.jsxs("div",{className:"image-preview-item",children:[d.jsx("img",{src:n.dataUrl,alt:n.filename}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:"image-remove",onClick:()=>e(r),children:"X"})}),d.jsx(Oe,{children:"Remove image"})]})]},r))})})}function _L({onSubmit:i,isProcessing:e=!1,placeholder:n,onInject:r}){const l=S.useRef(null),[u,p]=S.useState(""),[a,c]=S.useState([]),{mode:f,setMode:v}=dL();uL(v);const{addToHistory:m,navigateUp:y,navigateDown:C,resetNavigation:R}=FM(),{state:E,showCompletion:g,hideCompletion:b,updateCompletion:_,navigateUp:x,navigateDown:A,selectCurrent:D,isVisible:N}=UM(),{queue:O,queueCount:T,bellMode:j,queueMessage:H,removeFromQueue:I,clearQueue:z,setProcessing:U,resumeQueue:X}=Sw();S.useEffect(()=>{U(e)},[e,U]),S.useEffect(()=>{const Z=Q=>{p(Q.detail.prompt),l.current?.focus()};return window.addEventListener("cyclist:suggest-prompt",Z),()=>{window.removeEventListener("cyclist:suggest-prompt",Z)}},[]);const q=S.useCallback(async Z=>{let Q=null;if(Z.items){for(const ce of Z.items)if(ce.type&&lc.includes(ce.type)){Q=ce.getAsFile();break}}if(!Q&&Z.files?.length>0){for(const ce of Z.files)if(ce.type&&lc.includes(ce.type)){Q=ce;break}}return Q?Q.size>fL?(console.warn("Image too large:",Q.size),!1):new Promise(ce=>{const P=new FileReader;P.onload=()=>{const K=P.result,ie=Q.name||`Pasted Image.${Q.type.split("/")[1]||"png"}`;c(se=>[...se,{dataUrl:K,mimeType:Q.type,filename:ie}]),ce(!0)},P.onerror=()=>ce(!1),P.readAsDataURL(Q)}):!1},[]),F=S.useCallback(Z=>{c(Q=>Q.filter((ce,P)=>P!==Z))},[]),Y=S.useCallback(()=>{if(!l.current)return null;const Z=l.current.selectionStart,Q=u;let ce=Z;for(;ce>0&&Q[ce-1]!==" "&&Q[ce-1]!==`
64
+ `;)ce--;const P=Q.substring(ce,Z);return P.startsWith("/")?{prefix:P,start:ce,end:Z}:null},[u]),L=S.useCallback(Z=>{const Q=Y();if(!Q){p(K=>K+Z);return}const{start:ce,end:P}=Q;p(K=>K.substring(0,ce)+Z+K.substring(P)),setTimeout(()=>{if(l.current){const K=ce+Z.length;l.current.selectionStart=l.current.selectionEnd=K}},0)},[Y]),V=S.useCallback(()=>{const Z=u.trim();if(!(!Z&&a.length===0)){if(e){H({text:Z,images:[...a]})&&(p(""),c([]),l.current?.focus());return}if(m(Z),R(),Z.startsWith("/")){const Q=Z.split(/\s/)[0];Bw(Q)}X(),window.dispatchEvent(new CustomEvent("cyclist:user-submit")),i(Z,a),p(""),c([]),l.current?.focus()}},[u,a,e,H,m,R,X,i]),$=S.useCallback(Z=>{if(Z.key==="Tab"&&!Z.shiftKey&&!Z.ctrlKey&&!Z.altKey){if(N){Z.preventDefault();const ce=D();ce&&L(ce);return}const Q=Y();if(Q){Z.preventDefault(),g(Q.prefix);return}}if(Z.key==="Escape"&&N){Z.preventDefault(),b();return}if(Z.key==="Enter"&&!Z.shiftKey){if(N){Z.preventDefault();const Q=D();Q&&L(Q);return}Z.preventDefault(),V();return}if(Z.key==="ArrowUp"&&!Z.shiftKey&&!Z.ctrlKey&&!Z.altKey){if(N){Z.preventDefault(),x();return}if(l.current?.selectionStart===0){const Q=y(u);if(Q!==null){Z.preventDefault(),p(Q);return}}}if(Z.key==="ArrowDown"&&!Z.shiftKey&&!Z.ctrlKey&&!Z.altKey){if(N){Z.preventDefault(),A();return}if(l.current?.selectionEnd===u.length){const Q=C();if(Q!==null){Z.preventDefault(),p(Q);return}}}},[N,D,L,Y,g,b,V,x,A,y,C,u]),B=S.useCallback(Z=>{const Q=Z.target.value;if(p(Q),Q==="/"&&!N){g("/");return}if(N){const ce=Y();ce?_(ce.prefix):b()}},[N,g,Y,_,b]),W=S.useCallback(async Z=>{const Q=Z.clipboardData;if(!Q)return;let ce=!1;if(Q.items){for(const P of Q.items)if(P.type&&lc.includes(P.type)){ce=!0;break}}if(!ce&&Q.files?.length>0){for(const P of Q.files)if(P.type&&lc.includes(P.type)){ce=!0;break}}ce&&(Z.preventDefault(),await q(Q))},[q]),ee=S.useCallback(Z=>{const Q=E.commands[Z];Q&&(L(Q.name),b())},[E.commands,L,b]);return d.jsxs("div",{className:"editor-container","data-testid":"editor-container",children:[d.jsx(hL,{mode:f,onModeChange:v,className:"editor-mode-switch"}),d.jsxs("div",{className:"editor-wrapper",id:"editor-wrapper",children:[d.jsx(vL,{images:a,onRemove:F}),d.jsx("textarea",{ref:l,id:"editor-textarea",className:"editor-textarea",value:u,onChange:B,onKeyDown:$,onPaste:W,placeholder:n,spellCheck:!1,autoFocus:!0,"data-testid":"editor-textarea"}),d.jsx(pL,{commands:E.commands,selectedIndex:E.selectedIndex,visible:N,onSelect:ee})]}),d.jsx(gL,{queue:O,bellMode:j,onRemove:I,onClear:z,onInject:r})]})}function bL(){const[i,e]=S.useState(null),n=S.useCallback(u=>p=>{e(u)},[]),r=S.useCallback(()=>{e(null)},[]),l=S.useCallback(u=>i===u,[i]);return{handleFocus:n,handleBlur:r,isFocused:l}}function yL({currentAgent:i,onAgentSwitch:e}){const[n,r]=S.useState(!1),[l,u]=S.useState([]),p=S.useRef(null);S.useEffect(()=>{fetch("/api/theme-agents/full").then(c=>c.ok?c.json():null).then(c=>{c?.agents&&u(c.agents)}).catch(()=>{})},[]),S.useEffect(()=>{if(!n)return;const c=f=>{p.current&&!p.current.contains(f.target)&&r(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[n]),S.useEffect(()=>{if(!n)return;const c=f=>{f.key==="Escape"&&(f.stopPropagation(),r(!1))};return document.addEventListener("keydown",c,!0),()=>document.removeEventListener("keydown",c,!0)},[n]);const a=S.useCallback(c=>{c.role!==i&&(e?.(c.role),r(!1))},[i,e]);return d.jsxs("div",{className:"agent-quick-picker-wrapper",ref:p,children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle agent-picker-toggle ${n?"active":""}`,"data-testid":"agent-quick-picker",onClick:()=>r(c=>!c),"aria-label":"Switch agent","aria-expanded":n,"aria-haspopup":"listbox",children:d.jsx(aj,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:"Switch Agent"})]}),n&&d.jsx("div",{className:"agent-quick-picker-dropdown","data-testid":"agent-quick-picker-dropdown",role:"listbox","aria-label":"Available agents",children:l.map(c=>{const f=c.role===i;return d.jsx("div",{className:`agent-quick-picker-option ${f?"current":""}`,"data-testid":`agent-option-${c.role}`,role:"option","aria-selected":f,"aria-label":`${c.role} (${c.character})`,title:c.character,onClick:()=>a(c),children:d.jsx("span",{className:"agent-option-role",children:c.role})},c.role)})})]})}function SL({isRunning:i,isStopping:e=!1,onStop:n,onForceStop:r,onReset:l,bellMode:u=!1,relayMode:p=!1,onBellModeChange:a,onRelayModeChange:c,contextPercent:f=0,currentAgent:v=null,onTirePump:m,onAgentSwitch:y}){const C=S.useRef(0),R=500,{handleFocus:E,handleBlur:g,isFocused:b}=bL(),_=S.useCallback(x=>{if(x.key!=="Escape"&&x.keyCode!==27||!i)return;const A=Date.now();A-C.current<R&&r?r():n(),C.current=A},[i,n,r]);return S.useEffect(()=>(document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}),[_]),d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"control-bar","data-testid":"control-bar",children:[d.jsxs("div",{className:"control-bar-toggles",children:[d.jsx(yL,{currentAgent:v,onAgentSwitch:y}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle bell-toggle ${u?"active":""}`,"data-testid":"bell-mode-toggle",onClick:()=>a?.(!u),"aria-pressed":u,"aria-label":"Bell mode - inject queued messages via hook",children:d.jsx(FO,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:"Bell Mode: Inject queued messages during tool use (Cmd+B)"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle relay-toggle ${p?"active":""}`,"data-testid":"relay-toggle",onClick:()=>c?.(!p),"aria-pressed":p,"aria-label":"Relay mode - auto-handoff to next agent",children:d.jsx(dj,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:"Relay Mode: Auto-handoff to next agent (Cmd+4)"})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"ghost",size:"icon",type:"button",className:`btn-toggle pump-toggle ${f>=70?"warning":""}`,"data-testid":"pump-toggle",onClick:m,disabled:!v,"aria-label":"TirePump: Clear context and reload agent",children:d.jsx(tj,{className:"h-4 w-4"})})}),d.jsx(Oe,{children:v?`TirePump: Clear context (${f}%) and reload ${v}`:"TirePump: No agent loaded"})]})]}),d.jsxs(De,{variant:"destructive",type:"button",className:`btn-stop danger ${e?"stopping":""} ${i&&!e?"throbbing":""} ${b("stop")?"focused focus-visible":""}`,"data-testid":"stop-button",onClick:n,disabled:!i||e,"aria-busy":e,"aria-label":"Stop Claude",onFocus:E("stop"),onBlur:g,children:[d.jsx("span",{"data-icon":"stop",className:"icon"}),e?d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"spinner","data-loading":!0}),"Stopping..."]}):"Stop"]}),d.jsx(De,{variant:"outline",type:"button",className:`btn-reset ${b("reset")?"focused focus-visible":""}`,"data-testid":"reset-button",onClick:l,"aria-label":"Reset session",onFocus:E("reset"),onBlur:g,children:"Reset"})]})})}function wL(){const[i,e]=S.useState(!1),[n,r]=S.useState(!1),[l,u]=S.useState(!1),[p,a]=S.useState(!1),[c,f]=S.useState(0),[v,m]=S.useState(null),{abort:y,clear:C,clearAndReload:R,send:E,onMessage:g,onComplete:b,onError:_,isConnected:x}=ao();S.useEffect(()=>{function I(q){const F=q?.workflow,Y=!!F?.bell_mode,L=!!F?.relay_mode;console.log("[ControlBar] Settings updated:",{bellMode:Y,relayMode:L}),u(Y),a(L)}async function z(){try{console.log("[ControlBar] Loading settings via REST");const q=await fetch("/api/settings");if(q.ok){const F=await q.json();I(F)}}catch(q){console.error("[ControlBar] Failed to load settings:",q)}}console.log("[ControlBar] useEffect mount - loading settings"),z(),console.log("[ControlBar] Connecting to /ws/settings for real-time sync");const U=window.location.protocol==="https:"?"wss:":"ws:",X=new WebSocket(`${U}//${window.location.host}/ws/settings`);return X.onmessage=q=>{try{const F=JSON.parse(q.data);(F.type==="init"||F.type==="update")&&I(F.settings)}catch(F){console.error("[ControlBar] Failed to parse WebSocket message:",F)}},X.onerror=q=>{console.error("[ControlBar] WebSocket error:",q)},()=>{X.close()}},[]),S.useEffect(()=>{const I=window.location.protocol==="https:"?"wss:":"ws:",z=new WebSocket(`${I}//${window.location.host}/ws/context`);return z.onmessage=U=>{try{const X=JSON.parse(U.data);if(X.type==="init"||X.type==="update"){const q=X.context?.percent??0;f(q)}}catch(X){console.error("[ControlBar] Failed to parse context message:",X)}},()=>{z.close()}},[]),S.useEffect(()=>{const I=window.location.protocol==="https:"?"wss:":"ws:",z=new WebSocket(`${I}//${window.location.host}/ws/persona`);return z.onmessage=U=>{try{const X=JSON.parse(U.data);m(X?.slug??null)}catch(X){console.error("[ControlBar] Failed to parse persona message:",X)}},()=>{z.close()}},[]),S.useEffect(()=>{if(!x)return;const I=()=>{e(!0),r(!1)},z=()=>{e(!1),r(!1)},U=()=>{e(!1),r(!1)},X=g(I),q=b(z),F=_(U);return()=>{X(),q(),F()}},[x,g,b,_]);const A=S.useCallback(()=>{r(!0);try{y()}catch(I){console.error("[ControlBar] Stop failed:",I)}},[y]),D=S.useCallback(()=>{r(!0);try{y()}catch(I){console.error("[ControlBar] Force stop failed:",I)}},[y]),N=S.useCallback(()=>{try{C(),e(!1),r(!1)}catch(I){console.error("[ControlBar] Reset failed:",I)}},[C]),O=S.useCallback(async I=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{bell_mode:I}})}),u(I),console.log("[ControlBar] Bell mode set to:",I)}catch(z){console.error("[ControlBar] Failed to toggle bell mode:",z)}},[]),T=S.useCallback(async I=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflow:{relay_mode:I}})}),a(I),console.log("[ControlBar] Relay mode set to:",I)}catch(z){console.error("[ControlBar] Failed to toggle relay mode:",z)}},[]),j=S.useCallback(()=>{if(!v){console.warn("[ControlBar] Cannot TirePump: no current agent");return}try{console.log("[ControlBar] TirePump: clearing context and reloading agent:",v),R(v),e(!1),r(!1),f(0)}catch(I){console.error("[ControlBar] TirePump failed:",I)}},[v,R]),H=S.useCallback(I=>{E(`/${I}`)},[E]);return{isRunning:i,isStopping:n,bellMode:l,relayMode:p,contextPercent:c,currentAgent:v,handleStop:A,handleForceStop:D,handleReset:N,handleBellModeChange:O,handleRelayModeChange:T,handleTirePump:j,handleAgentSwitch:H}}function ve({className:i,...e}){return d.jsx("div",{className:we("animate-pulse rounded-md bg-primary/10",i),...e})}const By={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"};function xL({isOpen:i,onClose:e,currentRole:n,currentTheme:r}){const[l,u]=S.useState(null),[p,a]=S.useState(null),[c,f]=S.useState(!1),[v,m]=S.useState(!1),y=S.useRef(),{send:C}=ao();S.useEffect(()=>{i&&(f(!0),fetch("/api/theme-agents/full").then(_=>_.ok?_.json():null).then(_=>{u(_),a(null),f(!1)}).catch(()=>f(!1)))},[i]),S.useEffect(()=>{m(!1)},[p]),S.useEffect(()=>{if(!i)return;const _=x=>{x.key==="Escape"&&e()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[i,e]);const R=S.useCallback(_=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{a(_)},100)},[]),E=S.useCallback(()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{a(null)},200)},[]),g=S.useCallback(_=>{if(_.role===n)return;const x=`/${_.role}`;C(x),e()},[n,C,e]);if(!i)return null;const b=p||l?.agents.find(_=>_.role===n)||l?.agents[0];return d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"agent-popup-backdrop",onClick:e,"aria-hidden":"true"}),d.jsx("div",{className:"agent-popup",role:"dialog","aria-modal":"true","aria-labelledby":"agent-popup-title",children:c?d.jsxs("div",{className:"agent-popup-loading p-4 space-y-3",children:[d.jsx(ve,{className:"h-6 w-40"}),d.jsx(Rt,{}),d.jsxs("div",{className:"flex gap-4",children:[d.jsxs("div",{className:"space-y-2 flex-shrink-0",style:{width:160},children:[d.jsx(ve,{className:"h-5 w-12"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"})]}),d.jsxs("div",{className:"space-y-3 flex-1",children:[d.jsx(ve,{className:"h-24 w-24 rounded-full mx-auto"}),d.jsx(ve,{className:"h-5 w-32 mx-auto"}),d.jsx(ve,{className:"h-4 w-full"}),d.jsx(ve,{className:"h-4 w-3/4"})]})]})]}):l?d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"agent-popup-header",children:[d.jsxs("h2",{id:"agent-popup-title",className:"agent-popup-theme",children:[l.themeName,d.jsx(Ke,{variant:"secondary",className:`tier-badge ${l.tier?`tier-${l.tier.toLowerCase()}`:"tier-unranked"}`,children:l.tier||"Unranked"})]}),d.jsx(De,{variant:"ghost",size:"icon",className:"agent-popup-close",onClick:e,"aria-label":"Close popup",children:"×"})]}),d.jsx(Rt,{className:"my-1"}),d.jsxs("div",{className:"agent-popup-content",children:[d.jsxs("div",{className:"agent-popup-roster",children:[d.jsx("h3",{className:"roster-title",children:"Team"}),d.jsx("ul",{className:"roster-list",role:"listbox",children:l.agents.map(_=>{const x=_.role===n,A=p?.role===_.role,D=By[_.role]||"#888";return d.jsxs("li",{className:`roster-item ${x?"current":""} ${A?"previewing":""}`,role:"option","aria-selected":x,onMouseEnter:()=>R(_),onMouseLeave:E,onClick:()=>g(_),children:[d.jsx("span",{className:"roster-character",children:_.character}),d.jsx("span",{className:"roster-role",style:{backgroundColor:D},children:_.role}),x&&d.jsx("span",{className:"roster-current-marker",children:"●"})]},_.role)})})]}),d.jsx("div",{className:"agent-popup-details","data-testid":"agent-popup-details",children:b&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"popup-portrait","data-testid":"popup-portrait",children:!v&&r?d.jsx("img",{src:`/portraits/${r}/large/${b.slug}.png`,alt:b.character,onError:()=>m(!0)}):d.jsx("div",{className:"portrait-placeholder",children:"🤖"})}),d.jsx("h3",{className:"popup-character",children:b.character}),d.jsxs("div",{className:"popup-role-mapping",children:[d.jsx(Ke,{variant:"default",className:"role-badge",style:{backgroundColor:By[b.role]||"#888"},children:b.role}),"→ ",b.character]}),d.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-style",children:[d.jsx("label",{children:"Style:"}),d.jsx("span",{children:b.style||"—"})]}),d.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-background",children:[d.jsx("label",{children:"Background:"}),d.jsx("span",{children:b.background||"—"})]}),b.quirks.length>0&&d.jsxs("div",{className:"popup-detail","data-testid":"popup-detail-quirks",children:[d.jsx("label",{children:"Quirks:"}),d.jsx("span",{children:b.quirks.join(", ")})]}),b.lift!==void 0&&d.jsxs("div",{className:"popup-detail",children:[d.jsx("label",{children:"Lift:"}),d.jsxs("span",{className:`lift-value ${b.lift>=0?"positive":"negative"}`,children:[b.lift>=0?"+":"",b.lift.toFixed(1)]})]})]})})]})]}):d.jsx("div",{className:"agent-popup-error",children:"Failed to load theme data"})})]})}const CL={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function EL({character:i,role:e,slug:n,theme:r,isActive:l,isThinking:u}){const[p,a]=S.useState(!1);if(!l)return null;const c=CL[e]||e.toUpperCase();return d.jsxs("div",{className:`persona-tandem-portrait${u?" avatar-tandem-thinking":""}`,"data-testid":"tandem-portrait",role:"img","aria-label":`${i} (${e}) - observing`,tabIndex:-1,children:[p?d.jsx("span",{className:"tandem-portrait-fallback","aria-hidden":"true",children:"🤖"}):d.jsx("img",{src:`/portraits/${r}/medium/${n}.png`,alt:"","aria-hidden":"true",className:"tandem-portrait-image",onError:()=>a(!0)}),d.jsx("span",{className:"tandem-role-badge","data-testid":"tandem-role-badge","aria-hidden":"true",children:c})]})}const DL={pm:"#a78bfa",sm:"#60a5fa",dev:"#4ade80",tea:"#2dd4bf",reviewer:"#f87171",architect:"#fb923c",devops:"#22d3ee","ux-designer":"#f0abfc","tech-writer":"#e5e5e5",orchestrator:"#e879f9",ba:"#a3e635"},AL={pm:"PM",sm:"SM",dev:"DEV",tea:"TEA",reviewer:"REV",architect:"ARC",devops:"OPS","ux-designer":"UX","tech-writer":"TW",orchestrator:"ORC",ba:"BA"};function kL(i){return i.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ox(){const{persona:i,isStreaming:e}=du(),n=jw(),[r,l]=S.useState(!1),[u,p]=S.useState(!1),[a,c]=S.useState(!1),f=i?.character||"Agent",v=i?.theme||"default",m=i?.role||"agent",y=i?.slug,C=i?.quote,R=i?.tandemAgent,[E,g]=S.useState(!1),b=S.useRef(!1),_=S.useRef(null);S.useEffect(()=>{const O=b.current,T=R?.isThinking??!1;b.current=T,!O&&T&&g(!0)},[R?.isThinking]);const x=S.useCallback(()=>{g(!1)},[]),A=S.useCallback(()=>{p(!0)},[]),D=S.useCallback(()=>{p(!1)},[]),N=DL[m]||"#e879f9";return i?.character?d.jsxs(d.Fragment,{children:[d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:`persona-header clickable${a?" compact":""}`,"data-testid":"persona-header",role:"button",tabIndex:0,"aria-label":"Current agent persona - click to view team","aria-live":"polite",onClick:A,onKeyDown:O=>O.key==="Enter"&&A(),children:[d.jsxs("div",{className:"persona-portrait-group",children:[d.jsx("div",{className:`persona-portrait${e?" avatar-thinking":""}${E?" avatar-observation-pulse":""}`,"data-testid":"persona-portrait",ref:_,onAnimationEnd:x,children:y&&v&&!r?d.jsx("img",{src:`/portraits/${v}/medium/${y}.png`,alt:f,className:"portrait-image",onError:()=>l(!0)}):d.jsx("span",{className:"portrait-fallback",children:"🤖"})}),R&&d.jsx(EL,{character:R.character,role:R.role,slug:R.slug,theme:R.theme,isActive:!0,isThinking:R.isThinking}),R&&d.jsx("span",{className:"visually-hidden",role:"status","aria-live":"polite","data-testid":"tandem-sr-status",children:R.isThinking?`${R.character} is thinking`:`${R.character} observing`})]}),d.jsxs("div",{className:"persona-info",children:[d.jsxs("div",{className:"persona-name-row",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"default",className:"persona-role","data-testid":"persona-role",style:{backgroundColor:N},children:AL[m]||m})}),d.jsx(Oe,{children:m})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"persona-character","data-testid":"persona-character",children:f})}),d.jsx(Oe,{children:f})]}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"persona-theme","data-testid":"persona-theme",children:kL(v)})}),d.jsx(Oe,{children:`Theme: ${v}`})]})]}),C&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"persona-catchphrase","data-testid":"persona-catchphrase",children:['"',C,'"']})}),d.jsx(Oe,{children:C})]})]}),d.jsx("img",{src:n==="dark"?"/images/cyclist-dark.png":"/images/cyclist-light.png",alt:"Cyclist",className:"persona-branding"}),d.jsx("button",{className:"persona-collapse-toggle",onClick:O=>{O.stopPropagation(),c(!a)},"aria-label":a?"Expand header":"Collapse header",children:a?"▼":"▲"})]})}),d.jsx(xL,{isOpen:u,onClose:D,currentRole:m,currentTheme:v})]}):d.jsx("div",{className:"persona-header empty","data-testid":"persona-header"})}function TL(i){if(!i)return"—";const e=i.toLowerCase();if(e.includes("opus"))return"opus";if(e.includes("sonnet"))return"sonnet";if(e.includes("haiku"))return"haiku";const n=i.split("-");if(n.length>=2){for(let r=n.length-2;r>=0;r--)if(!/^\d{8}$/.test(n[r]))return n[r]}return i}function RL(i){return i>=85?"level-danger":i>=70?"level-warning":"level-safe"}function NL(i){if(!i)return"";const e=i.split("/");return e[e.length-1]||e[e.length-2]||i}function OL(){const{context:i,stats:e,projectInfo:n}=Mw(),r=i?.percent??0,l=e?.model??null,u=n?.pwd??"",p=n?.jiraEmail??null,a=n?.githubUsername??null,c=RL(r),f=NL(u);return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"stats-strip","data-testid":"stats-strip",children:[d.jsxs("div",{className:"stats-left","data-testid":"stats-left",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"stats-pwd","data-testid":"stats-pwd","data-full-path":u,children:f})}),d.jsx(Oe,{children:u})]}),p&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"stats-jira-email","data-testid":"jira-email",children:p})}),d.jsx(Oe,{children:`Jira: ${p}`})]}),a&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"stats-github-user","data-testid":"github-user",children:["@",a]})}),d.jsx(Oe,{children:`GitHub: ${a}`})]})]}),d.jsxs("div",{className:"stats-right","data-testid":"stats-right",children:[d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"secondary",className:"stats-model-badge","data-testid":"model-badge",children:TL(l)})}),l&&d.jsx(Oe,{children:l})]}),d.jsxs("div",{className:`stats-context-meter ${c}`,"data-testid":"context-meter",children:[d.jsxs("span",{className:"context-percent","data-testid":"context-percent",children:[r,"%"]}),d.jsx("div",{className:"context-fill","data-testid":"context-fill",style:{width:`${r}%`}})]})]})]})})}function Iy(i){return i.startsWith("Stop hook feedback:")}function jL(i){const e=Date.now(),n=i.parent_tool_use_id||void 0,r=i.subagent_type,l=i.subagent_name,u=[];if(i.type==="assistant"||i.type==="message"){const p=i.message?.content||i.content;if(Array.isArray(p)){const a=p.filter(f=>f.type==="text"&&typeof f.text=="string").map(f=>f.text).join("");a&&a.trim().length>=3&&!Iy(a.trim())&&u.push({type:"agent",content:a,timestamp:e,isStreaming:!0,parent_id:n,subagent_type:r,subagent_name:l});const c=p.filter(f=>f.type==="tool_use");for(const f of c)u.push({type:"tool_use",tool_name:f.name,tool_id:f.id,input:f.input,timestamp:e,parent_id:n,subagent_type:r,subagent_name:l})}else typeof p=="string"&&p.trim().length>=3&&!Iy(p.trim())&&u.push({type:"agent",content:p,timestamp:e,isStreaming:!0,parent_id:n,subagent_type:r,subagent_name:l});return u}if(i.type==="user"){let p="";const a=i.message?.content||i.content;if(Array.isArray(a)){p=a.filter(f=>f.type==="text"&&typeof f.text=="string").map(f=>f.text).join("");const c=a.filter(f=>f.type==="tool_result");for(const f of c)u.push({type:"tool_result",tool_id:f.tool_use_id,content:typeof f.content=="string"?f.content:"",timestamp:e,is_error:f.is_error})}else typeof a=="string"&&(p=a);return p&&u.push({type:"user",content:p,timestamp:e,parent_id:n,subagent_type:r,subagent_name:l}),u}return i.type==="tool_use"?(u.push({type:"tool_use",tool_name:i.tool_name,tool_id:i.tool_id,input:i.input,timestamp:e,parent_id:n,subagent_type:r,subagent_name:l}),u):(i.type==="tool_result"&&u.push({type:"tool_result",tool_id:i.tool_id,content:typeof i.output=="string"?i.output:"",timestamp:e,parent_id:n,subagent_type:r,subagent_name:l,is_error:i.is_error,durationMs:i.durationMs}),u)}function ML(){const[i,e]=S.useState([]),[n,r]=S.useState(!1),{isRunning:l,isStopping:u,bellMode:p,relayMode:a,contextPercent:c,currentAgent:f,handleStop:v,handleForceStop:m,handleReset:y,handleBellModeChange:C,handleRelayModeChange:R,handleTirePump:E,handleAgentSwitch:g}=wL(),{send:b,abort:_,onMessage:x,onComplete:A,onError:D,onUserMessage:N,onClear:O,isConnected:T}=ao(),{persona:j}=du(),H=S.useRef(j);H.current=j;const{handleTurnComplete:I,pauseQueue:z,onBellConsumed:U,injectMessage:X}=Sw(),q=S.useRef();S.useEffect(()=>U(K=>{e(ie=>[...ie,{type:"bell_injected",content:K.text,timestamp:Date.now(),imageCount:K.images.length>0?K.images.length:void 0}])}),[U]);const F={abort:_,submit:(P,K)=>{r(!0),b(P,K)}},Y=S.useCallback(P=>{const K=jL(P);if(K.length>0){const ie=H.current,se=K.map(fe=>fe.type==="agent"&&ie?{...fe,agentSlug:ie.slug??void 0,agentTheme:ie.theme??void 0,agentCharacter:ie.character??void 0}:fe),me=se.filter(fe=>fe.type==="tool_result"&&!fe.parent_id&&fe.tool_id).map(fe=>fe.tool_id);me.length>0?e(fe=>{const Ae=new Set(me.filter(Ie=>fe.some(rt=>rt.parent_id===Ie)));return Ae.size>0?[...fe.filter(Ie=>!Ie.parent_id||!Ae.has(Ie.parent_id)),...se]:[...fe,...se]}):e(fe=>[...fe,...se])}},[]),L=S.useCallback(()=>{r(!1),e(P=>P.map(K=>K.type==="agent"&&K.isStreaming?{...K,isStreaming:!1}:K)),q.current&&I(q.current)},[I]),V=S.useCallback(P=>{r(!1),e(K=>[...K,{type:"agent",content:`Error: ${P}`,timestamp:Date.now()}])},[]);S.useEffect(()=>N(K=>{e(ie=>[...ie,{type:"user",content:K.prompt,timestamp:K.timestamp,imageCount:K.images.length>0?K.images.length:void 0}])}),[N]),S.useEffect(()=>O(()=>{e(K=>[...K,{type:"context_cleared",content:"Context cleared",timestamp:Date.now()}]),r(!1)}),[O]),S.useEffect(()=>{if(!T){console.log("[MessagePanel] Claude WebSocket not connected");return}const P=x(Y),K=A(L),ie=D(V);return()=>{P(),K(),ie()}},[T,x,A,D,Y,L,V]);const $=S.useCallback((P,K)=>{r(!0),b(P,K)},[b]);S.useEffect(()=>{q.current=$},[$]);const B=S.useCallback(()=>{z(),v()},[z,v]),[W,ee]=S.useState(null),Z=S.useRef(null),Q=S.useRef(!1),ce=S.useCallback(P=>{P.preventDefault(),Q.current=!0;const K=P.clientY,ie=Z.current;if(!ie)return;const se=ie.getBoundingClientRect(),me=W??ie.querySelector(".message-panel-editor")?.getBoundingClientRect().height??150,fe=Ie=>{if(!Q.current)return;const rt=K-Ie.clientY,zt=Math.max(80,Math.min(me+rt,se.height*.7));ee(zt)},Ae=()=>{Q.current=!1,document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",Ae),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",fe),document.addEventListener("mouseup",Ae),document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[W]);return d.jsxs("div",{className:"message-panel","data-testid":"message-panel",ref:Z,children:[d.jsx(ox,{}),d.jsx("div",{className:"message-panel-content",children:d.jsx(IM,{messages:i})}),d.jsx("div",{className:"message-panel-resize-handle",onMouseDown:ce}),d.jsx("div",{className:"message-panel-editor",style:W!=null?{height:W,flexShrink:0}:void 0,children:d.jsxs("div",{className:"editor-with-controls",children:[d.jsx("div",{className:"editor-area",children:d.jsx(_L,{onSubmit:$,isProcessing:n||l,placeholder:"Send a message...",onInject:P=>X(P,F)})}),d.jsx(SL,{isRunning:l||n,isStopping:u,onStop:B,onForceStop:m,onReset:y,bellMode:p,relayMode:a,onBellModeChange:C,onRelayModeChange:R,contextPercent:c,currentAgent:f,onTirePump:E,onAgentSwitch:g})]})}),d.jsx(OL,{})]})}function LL(i){return i.id?{id:i.id,title:i.title??"",status:i.status??void 0,phase:i.phase??void 0,points:i.points??void 0,criteria:i.criteria,workflowPhases:i.workflow,workflowType:i.workflowType??void 0}:null}function ax(){const[i,e]=S.useState(null),[n,r]=S.useState(!0),[l,u]=S.useState(null),[p,a]=S.useState(null),c=S.useRef(null),f=S.useRef();return S.useEffect(()=>{const m=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/story`,y=()=>{try{c.current=new WebSocket(m),c.current.onopen=()=>{console.debug("[useStory] WebSocket connected")},c.current.onmessage=C=>{try{const R=JSON.parse(C.data);(R.type==="init"||R.type==="update")&&(e(LL(R)),a(R.availableWorkflows??null),r(!1),u(null))}catch(R){console.error("[useStory] Failed to parse message:",R)}},c.current.onclose=()=>{console.debug("[useStory] WebSocket closed, reconnecting..."),f.current=setTimeout(y,2e3)},c.current.onerror=C=>{console.error("[useStory] WebSocket error:",C),u(new Error("WebSocket connection failed"))}}catch(C){console.error("[useStory] WebSocket init failed:",C),u(C instanceof Error?C:new Error("Failed to connect")),r(!1)}};return y(),()=>{f.current&&clearTimeout(f.current),c.current&&c.current.close()}},[]),{story:i,isLoading:n,error:l,availableWorkflows:p}}function PL(){const[i,e]=S.useState(null),[n,r]=S.useState(!0),[l,u]=S.useState(null),p=S.useRef(null),a=S.useRef(),c=S.useRef(!0);return S.useEffect(()=>{const v=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/sprint`,m=()=>{if(c.current)try{p.current=new WebSocket(v),p.current.onopen=()=>{console.debug("[useSprint] WebSocket connected")},p.current.onmessage=y=>{try{const C=JSON.parse(y.data);if(C.type==="init"||C.type==="update"){const{type:R,...E}=C;e(g=>g?{...g,...E}:E),r(!1),u(null)}}catch(C){console.error("[useSprint] Failed to parse message:",C)}},p.current.onclose=()=>{console.debug("[useSprint] WebSocket closed, reconnecting..."),a.current=setTimeout(m,2e3)},p.current.onerror=y=>{console.error("[useSprint] WebSocket error:",y),u(new Error("WebSocket connection failed"))}}catch(y){console.error("[useSprint] WebSocket init failed:",y),u(y instanceof Error?y:new Error("Failed to connect")),r(!1)}};return m(),()=>{c.current=!1,a.current&&clearTimeout(a.current),p.current&&p.current.close()}},[]),{data:i,isLoading:n,error:l}}function zL(i){if(!i)return null;const e=i.split("@")[0],n=e.split(".");if(n.length>=2){const r=n[0].charAt(0).toUpperCase(),l=n[n.length-1].charAt(0).toUpperCase()+n[n.length-1].slice(1);return`${r}. ${l}`}return e}function BL(i){const e=i.stories.reduce((r,l)=>r+l.points,0);return{done:i.stories.filter(r=>r.status==="done").reduce((r,l)=>r+l.points,0),total:e}}function Wf(i){return i.stories.length>0&&i.stories.every(e=>e.status==="done")}function IL(i){switch(i){case"done":return{icon:d.jsx(va,{size:12}),className:"status-done"};case"in_progress":return{icon:d.jsx(ZO,{size:12}),className:"status-in-progress"};case"blocked":return{icon:d.jsx(rj,{size:12}),className:"status-blocked"};default:return{icon:d.jsx(KO,{size:12}),className:"status-backlog"}}}function Hy(i){return`https://1898andco.atlassian.net/browse/${i}`}function Fy({hasContext:i,testIdPrefix:e,id:n}){const r=i?"Context file exists":"No context file";return d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:`context-indicator ${i?"has-context":"no-context"}`,"data-testid":`${e}-context-indicator-${n}`,"data-has-context":String(i),title:r,children:i?"📄":""})}),d.jsx(Oe,{children:r})]})}function HL({priority:i,storyId:e}){return i?d.jsx("span",{className:"priority-label","data-testid":`story-priority-${e}`,"data-priority":i,title:i,children:i}):null}function FL({status:i,storyId:e}){const{icon:n,className:r}=IL(i);return d.jsx(Ke,{variant:i==="blocked"?"destructive":i==="done"?"default":"secondary",className:`story-status-badge ${r}`,"data-testid":`story-status-badge-${e}`,"data-status":i,"aria-label":`Status: ${i}`,children:n})}function GL({jiraKey:i,storyId:e}){const n=r=>{r.preventDefault();const l=Hy(i);try{const u=window.electronAPI;if(u?.shell?.openExternal){u.shell.openExternal(l);return}}catch{}window.open(l,"_blank")};return d.jsx("a",{className:"jira-link cyclist-link","data-testid":`story-jira-link-${e}`,href:Hy(i),onClick:n,children:i})}function Gy({epic:i,isExpanded:e,isArchiving:n,onToggle:r,onKeyDown:l,onArchive:u}){const{done:p,total:a}=BL(i),c=Wf(i);return d.jsxs("div",{className:`epic-group ${c?"epic-completed":""}`,"data-testid":`epic-group-${i.id}`,children:[d.jsxs("div",{className:"epic-header",children:[d.jsx(De,{variant:"ghost",size:"icon",className:"epic-toggle","data-testid":`epic-toggle-${i.id}`,onClick:()=>r(i.id),onKeyDown:f=>l(i.id,f),"aria-expanded":e,children:e?"▼":"▶"}),d.jsx("span",{className:"epic-title",children:i.title}),i.jiraKey&&d.jsx("span",{className:"epic-jira",children:i.jiraKey}),d.jsx(Fy,{hasContext:i.hasContext??!1,testIdPrefix:"epic",id:i.id}),c&&i.hasContext&&d.jsx(Ke,{variant:"default",className:"epic-ready-badge","data-testid":`epic-ready-badge-${i.id}`,children:"Ready"}),d.jsx("div",{className:"epic-progress","data-testid":`epic-progress-${i.id}`,"data-done":String(p),"data-total":String(a),children:d.jsx("div",{className:"progress-bar",style:{width:`${a>0?p/a*100:0}%`}})}),d.jsxs("span",{className:"epic-progress-label","data-testid":`epic-progress-label-${i.id}`,children:[p,"/",a," pts"]}),c&&d.jsxs(d.Fragment,{children:[n&&d.jsx("span",{"data-testid":`archive-loading-${i.id}`,children:"..."}),d.jsx(De,{variant:"outline",size:"sm",className:"archive-button","data-testid":`archive-button-${i.id}`,"aria-label":`Archive ${i.id}`,disabled:n,onClick:()=>u(i.id),children:"Archive"})]})]}),e&&d.jsx("div",{className:"epic-stories",children:i.stories.map(f=>{const v=f.hasContext??!1,m=f.status==="blocked",y=zL(f.assignedTo);return d.jsxs("div",{className:`story-item ${v?"":"missing-context"} ${m?"story-blocked":""}`,"data-testid":`story-item-${f.id}`,"data-status":f.status,"data-story-id":f.id,"aria-label":`${f.id}: ${f.title}`,children:[d.jsx(HL,{priority:f.priority,storyId:f.id}),d.jsx(FL,{status:f.status,storyId:f.id}),f.jiraKey&&d.jsx(GL,{jiraKey:f.jiraKey,storyId:f.id}),d.jsxs("div",{className:"story-info",children:[d.jsx("span",{className:"story-title",children:f.title}),d.jsxs("span",{className:"story-meta",children:[y&&d.jsx("span",{className:"story-assignee","data-testid":`story-assignee-${f.id}`,children:y}),f.workflow&&d.jsx("span",{className:"story-workflow-badge","data-testid":`story-workflow-${f.id}`,children:f.workflow}),f.status==="done"&&f.completed&&d.jsx("span",{className:"story-completed-date","data-testid":`story-completed-${f.id}`,children:f.completed})]})]}),d.jsx(Fy,{hasContext:v,testIdPrefix:"story",id:f.id}),d.jsx("span",{className:"story-points","data-testid":`story-points-${f.id}`,children:f.points})]},f.id)})})]})}function lx(){const{data:i,isLoading:e,error:n}=PL(),[r,l]=S.useState(new Set),[u,p]=S.useState(new Set),[a,c]=S.useState(null),[f,v]=S.useState(null),m=i?.epics.filter(D=>!Wf(D))??[],y=i?.epics.filter(D=>Wf(D))??[],C=S.useRef(!1);S.useEffect(()=>{i?.epics&&!C.current&&(C.current=!0,l(new Set(m.map(D=>D.id))))},[i?.epics]);const R=S.useCallback(D=>{l(N=>{const O=new Set(N);return O.has(D)?O.delete(D):O.add(D),O})},[]),E=S.useCallback((D,N)=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),R(D))},[R]),g=S.useCallback(async D=>{p(N=>new Set(N).add(`archive-${D}`)),c(null),v(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.archiveEpic)await window.electronAPI.sprint.archiveEpic(D);else if(!(await fetch(`/api/sprint/archive-epic/${D}`,{method:"POST"})).ok)throw new Error("Archive failed")}catch(N){v(N instanceof Error?N:new Error("Archive failed"))}finally{p(N=>{const O=new Set(N);return O.delete(`archive-${D}`),O})}},[]),b=S.useCallback(async D=>{p(N=>new Set(N).add(`promote-${D}`)),v(null);try{if(typeof window<"u"&&window.electronAPI?.sprint?.promoteEpic)await window.electronAPI.sprint.promoteEpic(D);else if(!(await fetch(`/api/sprint/promote-epic/${D}`,{method:"POST"})).ok)throw new Error("Promote failed")}catch(N){v(N instanceof Error?N:new Error("Promote failed"))}finally{p(N=>{const O=new Set(N);return O.delete(`promote-${D}`),O})}},[]);if(e)return d.jsx("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:d.jsxs("div",{className:"loading-state space-y-3 p-2","data-testid":"sprint-panel-loading",children:[d.jsx(ve,{className:"h-5 w-32"}),d.jsx(ve,{className:"h-4 w-full"}),d.jsx(Rt,{className:"my-2"}),d.jsx(ve,{className:"h-5 w-28"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(ve,{className:"h-8 w-full"}),d.jsx(Rt,{className:"my-2"}),d.jsx(ve,{className:"h-5 w-36"}),d.jsx(ve,{className:"h-6 w-3/4"})]})});const _=n||f,x=_?d.jsx("div",{className:"error-toast","data-testid":"error-toast",children:_.message}):null,A=a?d.jsxs("div",{className:"confirm-dialog","data-testid":"confirm-archive-dialog",children:[d.jsx("p",{children:"Are you sure you want to archive this epic?"}),d.jsx(De,{variant:"destructive",size:"sm","data-testid":"confirm-archive-yes",onClick:()=>g(a),children:"Yes"}),d.jsx(De,{variant:"outline",size:"sm","data-testid":"confirm-archive-no",onClick:()=>c(null),children:"No"})]}):null;return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"enhanced-sprint-panel","data-testid":"enhanced-sprint-panel",children:[x,A,d.jsxs("section",{"data-section":"current-story",children:[d.jsx("h2",{children:"Current Story"}),i?.currentStory?d.jsxs("div",{"data-testid":"current-story-section",children:[d.jsx("span",{className:"story-id",children:i.currentStory.id}),d.jsx("span",{className:"story-title",children:i.currentStory.title}),d.jsx("span",{className:"story-status",children:i.currentStory.status}),d.jsxs("span",{className:"story-points","data-testid":"current-story-points",children:[i.currentStory.points," pts"]})]}):i?.nextStory?d.jsxs("div",{"data-testid":"next-up-section",children:[d.jsx("span",{className:"next-up-label",children:"Next up:"}),d.jsx("span",{className:"story-id",children:i.nextStory.id}),d.jsx("span",{className:"story-title",children:i.nextStory.title})]}):d.jsx("div",{"data-testid":"no-stories-section",children:d.jsx("span",{children:"No active story"})})]}),d.jsx(Rt,{className:"my-2"}),d.jsxs("section",{"data-section":"epics",children:[d.jsx("h2",{children:"Current Epics"}),d.jsxs("div",{"data-testid":"epic-tree-view",children:[(!i?.epics||i.epics.length===0)&&d.jsxs("div",{className:"empty-state","data-testid":"no-epics-section",children:[d.jsx("span",{children:"No epics in current sprint"}),d.jsx("p",{className:"hint",children:"Promote an epic from Future Initiatives to get started"})]}),m.map(D=>d.jsx(Gy,{epic:D,isExpanded:r.has(D.id),isArchiving:u.has(`archive-${D.id}`),onToggle:R,onKeyDown:E,onArchive:c},D.id))]})]}),y.length>0&&d.jsxs(d.Fragment,{children:[d.jsx(Rt,{className:"my-2"}),d.jsxs("section",{"data-section":"completed-epics",children:[d.jsx("h2",{children:"Completed Epics"}),d.jsx("div",{"data-testid":"completed-epics-section",children:y.map(D=>d.jsx(Gy,{epic:D,isExpanded:r.has(D.id),isArchiving:u.has(`archive-${D.id}`),onToggle:R,onKeyDown:E,onArchive:c},D.id))})]})]}),d.jsx(Rt,{className:"my-2"}),d.jsxs("section",{"data-section":"future",children:[d.jsx("h2",{children:"Future Initiatives"}),d.jsx("div",{"data-testid":"future-initiatives-section",children:i?.futureEpics.map(D=>{const N=u.has(`promote-${D.id}`),O=D.status==="ready";return d.jsxs("div",{className:"future-epic","data-testid":`future-epic-${D.id}`,children:[d.jsx("span",{className:"future-epic-title",children:D.title}),d.jsxs("span",{className:"future-epic-points",children:[D.estimatedPoints," pts"]}),d.jsx(Ke,{variant:D.status==="ready"?"default":"secondary",className:"future-epic-status","data-testid":`future-epic-status-${D.id}`,"data-status":D.status,children:D.status}),O&&d.jsx(De,{variant:"default",size:"sm",className:"promote-button","data-testid":`promote-button-${D.id}`,"aria-label":`Promote ${D.id} to current sprint`,disabled:N,onClick:()=>b(D.id),children:"Promote"})]},D.id)})})]})]})})}function cx(i){let e=0,n=0,r=0;for(const l of i){const u=l.status[0]||" ",p=l.status[1]||" ";u!==" "&&u!=="?"&&e++,(p==="M"||p==="D")&&n++,u==="?"&&p==="?"&&r++}return{staged:e,modified:n,untracked:r}}function UL(i){return i?.length?i.map(e=>{const n=cx(e.dirtyFiles);return{name:e.name,path:e.path,branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,developBehind:e.developBehind??void 0,staged:n.staged,modified:n.modified,untracked:n.untracked,isDirty:!e.clean,files:e.dirtyFiles}}):[]}function WL(i){if(!i?.length)return null;const e=i[0];let n=0,r=0,l=0;for(const p of i){const a=cx(p.dirtyFiles);n+=a.staged,r+=a.modified,l+=a.untracked}const u=i.some(p=>!p.clean);return{branch:e.branch,ahead:e.ahead??void 0,behind:e.behind??void 0,staged:n>0?n:void 0,modified:r>0?r:void 0,untracked:l>0?l:void 0,isDirty:u}}function ux(){const[i,e]=S.useState(null),[n,r]=S.useState([]),[l,u]=S.useState(!0),[p,a]=S.useState(null),c=S.useRef(null),f=S.useRef();return S.useEffect(()=>{const m=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/git`,y=()=>{try{c.current=new WebSocket(m),c.current.onopen=()=>{console.debug("[useGitStatus] WebSocket connected")},c.current.onmessage=C=>{try{const R=JSON.parse(C.data);(R.type==="init"||R.type==="update")&&(e(WL(R.repos)),r(UL(R.repos)),u(!1),a(null))}catch(R){console.error("[useGitStatus] Failed to parse message:",R)}},c.current.onclose=()=>{console.debug("[useGitStatus] WebSocket closed, reconnecting..."),f.current=setTimeout(y,2e3)},c.current.onerror=C=>{console.error("[useGitStatus] WebSocket error:",C),a(new Error("WebSocket connection failed"))}}catch(C){console.error("[useGitStatus] WebSocket init failed:",C),a(C instanceof Error?C:new Error("Failed to connect")),u(!1)}};return y(),()=>{f.current&&clearTimeout(f.current),c.current&&c.current.close()}},[]),{gitStatus:i,repos:n,isLoading:l,error:p}}function VL(i){const e=i[0]||" ",n=i[1]||" ";return e==="?"&&n==="?"?"untracked":e!==" "&&e!=="?"?"staged":"modified"}function $L(i){const e=i[0]||" ",n=i[1]||" ";return e==="?"&&n==="?"?"?":e==="A"?"+":e==="D"||n==="D"?"-":e==="M"||n==="M"?"~":e==="R"?"R":i.trim()||"~"}function qL({files:i}){return d.jsx("ul",{className:"file-list",children:i.map((e,n)=>d.jsxs("li",{className:`file-item ${VL(e.status)}`,children:[d.jsx("span",{className:"file-status-icon",children:$L(e.status)}),d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"file-path",children:e.path})}),d.jsx(Oe,{children:e.path})]})]},`${e.path}-${n}`))})}function YL({repo:i}){const[e,n]=S.useState(!1),{name:r,branch:l,ahead:u,behind:p,developBehind:a,staged:c,modified:f,untracked:v,isDirty:m,files:y}=i,C=y.length>0;return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:`repo-status ${e?"expanded":""}`,"data-testid":`repo-status-${r}`,children:[d.jsxs("div",{className:"repo-header",children:[d.jsx("span",{className:"repo-name",children:r}),m&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(Ke,{variant:"destructive",className:"dirty-indicator",children:"●"})}),d.jsx(Oe,{children:"Uncommitted changes"})]})]}),d.jsxs("div",{className:"branch-info",children:[d.jsx("span",{className:"branch-icon",children:"⎇"}),d.jsx("span",{className:"branch-name",children:l})]}),(u!==void 0&&u>0||p!==void 0&&p>0||a!==void 0&&a>0)&&d.jsxs("div",{className:"sync-status",children:[u!==void 0&&u>0&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"ahead",children:["↑",u]})}),d.jsx(Oe,{children:"Commits ahead of remote"})]}),p!==void 0&&p>0&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"behind",children:["↓",p]})}),d.jsx(Oe,{children:"Commits behind remote"})]}),a!==void 0&&a>0&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("span",{className:"develop-behind",children:["⟳",a]})}),d.jsxs(Oe,{children:["develop is ",a," commit",a>1?"s":""," ahead"]})]})]}),(c>0||f>0||v>0)&&d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs(De,{variant:"ghost",className:"file-status-toggle",onClick:()=>n(!e),children:[d.jsx("span",{className:`toggle-icon ${e?"open":""}`,children:"▶"}),d.jsxs("div",{className:"file-status",children:[c>0&&d.jsxs(Ke,{variant:"outline",className:"status-item staged",children:["+",c]}),f>0&&d.jsxs(Ke,{variant:"outline",className:"status-item modified",children:["~",f]}),v>0&&d.jsxs(Ke,{variant:"outline",className:"status-item untracked",children:["?",v]})]})]})}),d.jsx(Oe,{children:e?"Collapse file list":"Expand file list"})]}),e&&C&&d.jsx(qL,{files:y})]})})}function dx(){const{repos:i,isLoading:e,error:n}=ux(),{send:r}=ao(),l=()=>{r("Sync all repos")};return e?d.jsx("div",{className:"git-panel loading","data-testid":"git-panel",children:d.jsxs("div",{className:"space-y-3 p-2",children:[d.jsxs("div",{className:"space-y-1",children:[d.jsx(ve,{className:"h-4 w-32"}),d.jsx(ve,{className:"h-3 w-24"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsx(ve,{className:"h-4 w-28"}),d.jsx(ve,{className:"h-3 w-20"})]})]})}):n?d.jsx("div",{className:"git-panel error","data-testid":"git-panel",children:d.jsx("div",{className:"error-message",children:n.message})}):i.length===0?d.jsx("div",{className:"git-panel empty","data-testid":"git-panel",children:d.jsx("div",{className:"placeholder",children:"No git repos"})}):d.jsxs("div",{className:"git-panel stacked","data-testid":"git-panel",children:[d.jsx("div",{className:"git-panel-actions",children:d.jsx(wt,{delayDuration:300,children:d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("button",{className:"sync-all-btn",onClick:l,"aria-label":"Sync all repos",children:[d.jsx(QO,{size:14}),d.jsx("span",{children:"Sync all repos"})]})}),d.jsx(Oe,{children:"Pull latest changes for all repos"})]})})}),i.map(u=>d.jsx(YL,{repo:u},u.name))]})}function KL(i){switch(i){case"done":return"✓";case"current":return"●";default:return"○"}}function XL(i){return i?["tdd","bdd"].includes(i.toLowerCase())?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):"—"}function ZL({phase:i,isLast:e}){const n=KL(i.status),r=`phase-step ${i.status}`;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:r,children:[d.jsx("span",{className:"phase-icon",children:n}),d.jsx("span",{className:"phase-label",children:i.label})]}),!e&&d.jsx("span",{className:"phase-arrow",children:"→"})]})}function JL({phases:i}){const e=i.length,n=i.findIndex(p=>p.status==="current"),r=i.filter(p=>p.status==="done").length,l=n>=0?n+1:r===e?e:1,u=n>=0?i[n]:null;return d.jsxs("div",{className:"stepped-progress",children:[d.jsxs("span",{className:"stepped-counter",children:["Step ",l," of ",e]}),u&&d.jsx("span",{className:"stepped-current-label",children:u.label})]})}function QL({workflows:i,onStart:e}){return d.jsxs("div",{className:"available-workflows",children:[d.jsx("div",{className:"available-workflows-header",children:d.jsxs("span",{className:"available-workflows-title",children:["Available Workflows (",i.length,")"]})}),d.jsx("div",{className:"available-workflows-list",children:i.map(n=>d.jsxs("div",{className:"workflow-entry","data-testid":"workflow-entry","data-workflow-entry-type":n.type,children:[d.jsxs("div",{className:"workflow-entry-header",children:[d.jsx("span",{className:"workflow-entry-name",children:n.name}),d.jsx(Ke,{variant:"outline",className:"workflow-entry-type-badge",children:n.type})]}),d.jsx("div",{className:"workflow-entry-description",children:n.description}),n.type==="stepped"&&d.jsxs("div",{className:"workflow-entry-hint",children:["/workflow start ",n.name]}),d.jsx("div",{className:"workflow-entry-footer",children:d.jsx(De,{variant:"ghost",size:"sm",className:"workflow-start-button","data-testid":"workflow-start-button",onClick:()=>e?.(n),children:"Start"})})]},n.name))})]})}function hx(){const{story:i,isLoading:e,error:n,availableWorkflows:r}=ax(),{send:l,isConnected:u}=ao(),p=S.useCallback(m=>{u&&l(`/workflow start ${m.name}`)},[l,u]);if(e)return d.jsx("div",{className:"workflow-panel loading","data-testid":"workflow-panel",children:d.jsxs("div",{className:"space-y-2 p-2",children:[d.jsx(ve,{className:"h-6 w-16 rounded-full"}),d.jsxs("div",{className:"flex gap-2 items-center",children:[d.jsx(ve,{className:"h-4 w-12"}),d.jsx(ve,{className:"h-4 w-12"}),d.jsx(ve,{className:"h-4 w-12"})]})]})});if(n)return d.jsx("div",{className:"workflow-panel error","data-testid":"workflow-panel",children:d.jsx("div",{className:"error-message",children:n.message})});const a=i?.workflow??null,c=i?.workflowPhases??null,f=i?.workflowType==="stepped";if(!a&&(!c||c.length===0))return r&&r.length>0?d.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:d.jsx(QL,{workflows:r,onStart:p})}):d.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:d.jsx("div",{className:"placeholder",children:"No active workflow"})});const v=XL(a);return d.jsx("div",{className:"workflow-panel","data-testid":"workflow-panel",children:d.jsxs("div",{className:"workflow-content",children:[d.jsx(Ke,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":a||"",children:v}),c&&c.length>0&&(f?d.jsx(JL,{phases:c}):d.jsx("div",{className:"phase-progress",children:c.map((m,y)=>d.jsx(ZL,{phase:m,isLast:y===c.length-1},m.name))}))]})})}function eP({item:i}){const e=i.completed?"ac-item ac-done":"ac-item",n=i.completed?"✓":"○";return d.jsxs("div",{className:e,children:[d.jsx("span",{className:"ac-icon",children:n}),d.jsx("span",{className:"ac-text",children:i.text})]})}function fx(){const{story:i,isLoading:e,error:n}=ax();if(e)return d.jsx("div",{className:"ac-panel loading","data-testid":"ac-panel",children:d.jsxs("div",{className:"space-y-2 p-2",children:[d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-4 w-3/4"}),d.jsx(ve,{className:"h-4 w-5/6"}),d.jsx(ve,{className:"h-4 w-2/3"})]})});if(n)return d.jsx("div",{className:"ac-panel error","data-testid":"ac-panel",children:d.jsx("div",{className:"error-message",children:n.message})});const r=i?.criteria??null;if(!r||r.length===0)return d.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:d.jsx("div",{className:"placeholder",children:"No acceptance criteria"})});const l=r.filter(p=>p.completed).length,u=r.length;return d.jsx("div",{className:"ac-panel","data-testid":"ac-panel",children:d.jsxs("div",{className:"ac-content",children:[d.jsxs("span",{className:"progress-text",children:[l,"/",u]}),d.jsx("div",{className:"progress-bar-container",children:d.jsx("div",{className:"progress-bar",style:{width:`${l/u*100}%`}})}),d.jsx("div",{className:"ac-list",children:r.map((p,a)=>d.jsx(eP,{item:p},a))})]})})}function tP(){const[i,e]=S.useState([]),[n,r]=S.useState(!0),[l,u]=S.useState(null),p=S.useRef(null),a=S.useRef();return S.useEffect(()=>{const f=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/todos`,v=()=>{try{p.current=new WebSocket(f),p.current.onopen=()=>{console.debug("[useTodos] WebSocket connected")},p.current.onmessage=m=>{try{const y=JSON.parse(m.data);(y.type==="init"||y.type==="update")&&(e(y.todos||[]),r(!1),u(null))}catch(y){console.error("[useTodos] Failed to parse message:",y)}},p.current.onclose=()=>{console.debug("[useTodos] WebSocket closed, reconnecting..."),a.current=setTimeout(v,2e3)},p.current.onerror=m=>{console.error("[useTodos] WebSocket error:",m),u(new Error("WebSocket connection failed"))}}catch(m){console.error("[useTodos] WebSocket init failed:",m),u(m instanceof Error?m:new Error("Failed to connect")),r(!1)}};return v(),()=>{a.current&&clearTimeout(a.current),p.current&&p.current.close()}},[]),{todos:i,isLoading:n,error:l}}function df({todo:i}){const e={pending:"○",in_progress:"●",completed:"✓"}[i.status],n=`todo-item todo-${i.status}`,r=i.status==="in_progress"&&i.activeForm?i.activeForm:i.content;return d.jsxs("div",{className:n,"data-testid":`todo-${i.id}`,children:[d.jsx("span",{className:"todo-status",children:e}),d.jsx("span",{className:"todo-subject",children:r}),i.blockedBy&&i.blockedBy.length>0&&d.jsx(wt,{delayDuration:300,children:d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"todo-blocked",children:"(blocked)"})}),d.jsx(Oe,{children:`Blocked by: ${i.blockedBy.join(", ")}`})]})})]})}function px(){const{todos:i,isLoading:e,error:n}=tP();if(e)return d.jsx("div",{className:"todo-panel loading","data-testid":"todo-panel",children:d.jsxs("div",{className:"space-y-2 p-2",children:[d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-4 w-5/6"}),d.jsx(ve,{className:"h-4 w-3/4"}),d.jsx(ve,{className:"h-4 w-4/5"})]})});if(n)return d.jsx("div",{className:"todo-panel error","data-testid":"todo-panel",children:d.jsx("div",{className:"error-message",children:n.message})});if(i.length===0)return d.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:d.jsx("div",{className:"placeholder",children:"No active tasks"})});const r=i.filter(f=>f.status==="in_progress"),l=i.filter(f=>f.status==="pending"),u=i.filter(f=>f.status==="completed"),p=i.length,a=u.length,c=p>0?Math.round(a/p*100):0;return d.jsx("div",{className:"todo-panel","data-testid":"todo-panel",children:d.jsxs("div",{className:"todo-content",children:[d.jsxs("div",{className:"progress-bar-container",children:[d.jsx("div",{className:"progress-bar",style:{width:`${c}%`}}),d.jsxs("span",{className:"progress-text",children:[a,"/",p]})]}),r.length>0&&d.jsxs("div",{className:"todo-section",children:[d.jsx("h4",{children:"In Progress"}),r.map(f=>d.jsx(df,{todo:f},f.id))]}),l.length>0&&d.jsxs("div",{className:"todo-section",children:[d.jsx("h4",{children:"Pending"}),l.map(f=>d.jsx(df,{todo:f},f.id))]}),u.length>0&&d.jsxs("div",{className:"todo-section todo-completed",children:[d.jsxs("h4",{children:["Completed (",u.length,")"]}),u.map(f=>d.jsx(df,{todo:f},f.id))]})]})})}function iP(){const[i,e]=S.useState([]),n=S.useRef(null),r=S.useRef();S.useEffect(()=>{const c=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/background-tasks`,f=()=>{try{n.current=new WebSocket(c),n.current.onopen=()=>{console.debug("[useBackgroundTasks] WebSocket connected")},n.current.onmessage=v=>{try{const m=JSON.parse(v.data);switch(m.type){case"init":m.tasks&&e(m.tasks);break;case"task:started":m.task&&e(y=>y.some(C=>C.taskId===m.task.taskId)?y:[...y,m.task]);break;case"task:completed":m.task&&e(y=>y.map(C=>C.taskId===m.task.taskId?{...C,...m.task}:C));break}}catch(m){console.error("[useBackgroundTasks] Failed to parse message:",m)}},n.current.onclose=()=>{console.debug("[useBackgroundTasks] WebSocket closed, reconnecting..."),r.current=setTimeout(f,2e3)},n.current.onerror=v=>{console.error("[useBackgroundTasks] WebSocket error:",v)}}catch(v){console.error("[useBackgroundTasks] WebSocket init failed:",v)}};return f(),()=>{r.current&&clearTimeout(r.current),n.current&&n.current.close()}},[]);const l=S.useCallback(()=>{e(a=>a.filter(c=>c.status==="pending"))},[]),u=i.filter(a=>a.status==="pending").length,p=i.filter(a=>a.status==="completed").length;return{tasks:i,pendingCount:u,completedCount:p,clearCompleted:l}}function Uy(i){return i<1e3?`${i}ms`:i<6e4?`${Math.floor(i/1e3)}s`:`${Math.floor(i/6e4)}m`}function nP({task:i,tick:e}){const r=i.status==="pending"?"...":i.success?"v":"x",l=`task-item task-${i.status}${i.success===!1?" task-error":""}`;let u;return i.status==="completed"&&i.durationMs!==void 0?u=Uy(i.durationMs):u=Uy(Date.now()-i.startedAt),d.jsxs("div",{className:l,"data-testid":`task-${i.taskId}`,children:[d.jsx("span",{className:"task-status",children:r}),d.jsxs("div",{className:"task-content",children:[d.jsx("span",{className:"task-description",children:i.description}),d.jsx("span",{className:"task-type",children:i.subagentType})]}),d.jsx("span",{className:"task-elapsed",children:u})]})}function mx(){const{tasks:i,pendingCount:e,completedCount:n,clearCompleted:r}=iP(),[l,u]=S.useState(0);if(S.useEffect(()=>{if(e===0)return;const a=setInterval(()=>{u(c=>c+1)},1e3);return()=>clearInterval(a)},[e]),i.length===0)return d.jsx("div",{className:"background-panel empty","data-testid":"background-panel",children:d.jsx("div",{className:"placeholder",children:"No subagent tasks"})});const p=[...i].sort((a,c)=>a.status==="pending"&&c.status!=="pending"?-1:a.status!=="pending"&&c.status==="pending"?1:c.startedAt-a.startedAt);return d.jsxs("div",{className:"background-panel","data-testid":"background-panel",children:[d.jsxs("div",{className:"panel-header",children:[d.jsxs("span",{className:"task-counts",children:[e>0&&d.jsxs("span",{className:"pending-count",children:[e," running"]}),n>0&&d.jsxs("span",{className:"completed-count",children:[n," done"]})]}),n>0&&d.jsx(De,{variant:"ghost",size:"sm",type:"button",className:"clear-button",onClick:r,children:"Clear"})]}),d.jsx("div",{className:"task-list",children:p.map(a=>d.jsx(nP,{task:a,tick:l},a.taskId))})]})}function Vf(i,[e,n]){return Math.min(n,Math.max(e,i))}function sP(i,e){return S.useReducer((n,r)=>e[n][r]??n,i)}var Kp="ScrollArea",[gx]=pi(Kp),[rP,Oi]=gx(Kp),vx=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,type:r="hover",dir:l,scrollHideDelay:u=600,...p}=i,[a,c]=S.useState(null),[f,v]=S.useState(null),[m,y]=S.useState(null),[C,R]=S.useState(null),[E,g]=S.useState(null),[b,_]=S.useState(0),[x,A]=S.useState(0),[D,N]=S.useState(!1),[O,T]=S.useState(!1),j=Ge(e,I=>c(I)),H=hu(l);return d.jsx(rP,{scope:n,type:r,dir:H,scrollHideDelay:u,scrollArea:a,viewport:f,onViewportChange:v,content:m,onContentChange:y,scrollbarX:C,onScrollbarXChange:R,scrollbarXEnabled:D,onScrollbarXEnabledChange:N,scrollbarY:E,onScrollbarYChange:g,scrollbarYEnabled:O,onScrollbarYEnabledChange:T,onCornerWidthChange:_,onCornerHeightChange:A,children:d.jsx(Ne.div,{dir:H,...p,ref:j,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":x+"px",...i.style}})})});vx.displayName=Kp;var _x="ScrollAreaViewport",bx=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,children:r,nonce:l,...u}=i,p=Oi(_x,n),a=S.useRef(null),c=Ge(e,a,p.onViewportChange);return d.jsxs(d.Fragment,{children:[d.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:l}),d.jsx(Ne.div,{"data-radix-scroll-area-viewport":"",...u,ref:c,style:{overflowX:p.scrollbarXEnabled?"scroll":"hidden",overflowY:p.scrollbarYEnabled?"scroll":"hidden",...i.style},children:d.jsx("div",{ref:p.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});bx.displayName=_x;var on="ScrollAreaScrollbar",Xp=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Oi(on,i.__scopeScrollArea),{onScrollbarXEnabledChange:u,onScrollbarYEnabledChange:p}=l,a=i.orientation==="horizontal";return S.useEffect(()=>(a?u(!0):p(!0),()=>{a?u(!1):p(!1)}),[a,u,p]),l.type==="hover"?d.jsx(oP,{...r,ref:e,forceMount:n}):l.type==="scroll"?d.jsx(aP,{...r,ref:e,forceMount:n}):l.type==="auto"?d.jsx(yx,{...r,ref:e,forceMount:n}):l.type==="always"?d.jsx(Zp,{...r,ref:e}):null});Xp.displayName=on;var oP=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Oi(on,i.__scopeScrollArea),[u,p]=S.useState(!1);return S.useEffect(()=>{const a=l.scrollArea;let c=0;if(a){const f=()=>{window.clearTimeout(c),p(!0)},v=()=>{c=window.setTimeout(()=>p(!1),l.scrollHideDelay)};return a.addEventListener("pointerenter",f),a.addEventListener("pointerleave",v),()=>{window.clearTimeout(c),a.removeEventListener("pointerenter",f),a.removeEventListener("pointerleave",v)}}},[l.scrollArea,l.scrollHideDelay]),d.jsx(Qt,{present:n||u,children:d.jsx(yx,{"data-state":u?"visible":"hidden",...r,ref:e})})}),aP=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Oi(on,i.__scopeScrollArea),u=i.orientation==="horizontal",p=pu(()=>c("SCROLL_END"),100),[a,c]=sP("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return S.useEffect(()=>{if(a==="idle"){const f=window.setTimeout(()=>c("HIDE"),l.scrollHideDelay);return()=>window.clearTimeout(f)}},[a,l.scrollHideDelay,c]),S.useEffect(()=>{const f=l.viewport,v=u?"scrollLeft":"scrollTop";if(f){let m=f[v];const y=()=>{const C=f[v];m!==C&&(c("SCROLL"),p()),m=C};return f.addEventListener("scroll",y),()=>f.removeEventListener("scroll",y)}},[l.viewport,u,c,p]),d.jsx(Qt,{present:n||a!=="hidden",children:d.jsx(Zp,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:e,onPointerEnter:Ee(i.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Ee(i.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),yx=S.forwardRef((i,e)=>{const n=Oi(on,i.__scopeScrollArea),{forceMount:r,...l}=i,[u,p]=S.useState(!1),a=i.orientation==="horizontal",c=pu(()=>{if(n.viewport){const f=n.viewport.offsetWidth<n.viewport.scrollWidth,v=n.viewport.offsetHeight<n.viewport.scrollHeight;p(a?f:v)}},10);return eo(n.viewport,c),eo(n.content,c),d.jsx(Qt,{present:r||u,children:d.jsx(Zp,{"data-state":u?"visible":"hidden",...l,ref:e})})}),Zp=S.forwardRef((i,e)=>{const{orientation:n="vertical",...r}=i,l=Oi(on,i.__scopeScrollArea),u=S.useRef(null),p=S.useRef(0),[a,c]=S.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=Ex(a.viewport,a.content),v={...r,sizes:a,onSizesChange:c,hasThumb:f>0&&f<1,onThumbChange:y=>u.current=y,onThumbPointerUp:()=>p.current=0,onThumbPointerDown:y=>p.current=y};function m(y,C){return fP(y,p.current,a,C)}return n==="horizontal"?d.jsx(lP,{...v,ref:e,onThumbPositionChange:()=>{if(l.viewport&&u.current){const y=l.viewport.scrollLeft,C=Wy(y,a,l.dir);u.current.style.transform=`translate3d(${C}px, 0, 0)`}},onWheelScroll:y=>{l.viewport&&(l.viewport.scrollLeft=y)},onDragScroll:y=>{l.viewport&&(l.viewport.scrollLeft=m(y,l.dir))}}):n==="vertical"?d.jsx(cP,{...v,ref:e,onThumbPositionChange:()=>{if(l.viewport&&u.current){const y=l.viewport.scrollTop,C=Wy(y,a);u.current.style.transform=`translate3d(0, ${C}px, 0)`}},onWheelScroll:y=>{l.viewport&&(l.viewport.scrollTop=y)},onDragScroll:y=>{l.viewport&&(l.viewport.scrollTop=m(y))}}):null}),lP=S.forwardRef((i,e)=>{const{sizes:n,onSizesChange:r,...l}=i,u=Oi(on,i.__scopeScrollArea),[p,a]=S.useState(),c=S.useRef(null),f=Ge(e,c,u.onScrollbarXChange);return S.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(wx,{"data-orientation":"horizontal",...l,ref:f,sizes:n,style:{bottom:0,left:u.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:u.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":fu(n)+"px",...i.style},onThumbPointerDown:v=>i.onThumbPointerDown(v.x),onDragScroll:v=>i.onDragScroll(v.x),onWheelScroll:(v,m)=>{if(u.viewport){const y=u.viewport.scrollLeft+v.deltaX;i.onWheelScroll(y),Ax(y,m)&&v.preventDefault()}},onResize:()=>{c.current&&u.viewport&&p&&r({content:u.viewport.scrollWidth,viewport:u.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:zc(p.paddingLeft),paddingEnd:zc(p.paddingRight)}})}})}),cP=S.forwardRef((i,e)=>{const{sizes:n,onSizesChange:r,...l}=i,u=Oi(on,i.__scopeScrollArea),[p,a]=S.useState(),c=S.useRef(null),f=Ge(e,c,u.onScrollbarYChange);return S.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(wx,{"data-orientation":"vertical",...l,ref:f,sizes:n,style:{top:0,right:u.dir==="ltr"?0:void 0,left:u.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":fu(n)+"px",...i.style},onThumbPointerDown:v=>i.onThumbPointerDown(v.y),onDragScroll:v=>i.onDragScroll(v.y),onWheelScroll:(v,m)=>{if(u.viewport){const y=u.viewport.scrollTop+v.deltaY;i.onWheelScroll(y),Ax(y,m)&&v.preventDefault()}},onResize:()=>{c.current&&u.viewport&&p&&r({content:u.viewport.scrollHeight,viewport:u.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:zc(p.paddingTop),paddingEnd:zc(p.paddingBottom)}})}})}),[uP,Sx]=gx(on),wx=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:l,onThumbChange:u,onThumbPointerUp:p,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:f,onWheelScroll:v,onResize:m,...y}=i,C=Oi(on,n),[R,E]=S.useState(null),g=Ge(e,j=>E(j)),b=S.useRef(null),_=S.useRef(""),x=C.viewport,A=r.content-r.viewport,D=Wt(v),N=Wt(c),O=pu(m,10);function T(j){if(b.current){const H=j.clientX-b.current.left,I=j.clientY-b.current.top;f({x:H,y:I})}}return S.useEffect(()=>{const j=H=>{const I=H.target;R?.contains(I)&&D(H,A)};return document.addEventListener("wheel",j,{passive:!1}),()=>document.removeEventListener("wheel",j,{passive:!1})},[x,R,A,D]),S.useEffect(N,[r,N]),eo(R,O),eo(C.content,O),d.jsx(uP,{scope:n,scrollbar:R,hasThumb:l,onThumbChange:Wt(u),onThumbPointerUp:Wt(p),onThumbPositionChange:N,onThumbPointerDown:Wt(a),children:d.jsx(Ne.div,{...y,ref:g,style:{position:"absolute",...y.style},onPointerDown:Ee(i.onPointerDown,j=>{j.button===0&&(j.target.setPointerCapture(j.pointerId),b.current=R.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",C.viewport&&(C.viewport.style.scrollBehavior="auto"),T(j))}),onPointerMove:Ee(i.onPointerMove,T),onPointerUp:Ee(i.onPointerUp,j=>{const H=j.target;H.hasPointerCapture(j.pointerId)&&H.releasePointerCapture(j.pointerId),document.body.style.webkitUserSelect=_.current,C.viewport&&(C.viewport.style.scrollBehavior=""),b.current=null})})})}),Pc="ScrollAreaThumb",xx=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Sx(Pc,i.__scopeScrollArea);return d.jsx(Qt,{present:n||l.hasThumb,children:d.jsx(dP,{ref:e,...r})})}),dP=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,style:r,...l}=i,u=Oi(Pc,n),p=Sx(Pc,n),{onThumbPositionChange:a}=p,c=Ge(e,m=>p.onThumbChange(m)),f=S.useRef(void 0),v=pu(()=>{f.current&&(f.current(),f.current=void 0)},100);return S.useEffect(()=>{const m=u.viewport;if(m){const y=()=>{if(v(),!f.current){const C=pP(m,a);f.current=C,a()}};return a(),m.addEventListener("scroll",y),()=>m.removeEventListener("scroll",y)}},[u.viewport,v,a]),d.jsx(Ne.div,{"data-state":p.hasThumb?"visible":"hidden",...l,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ee(i.onPointerDownCapture,m=>{const C=m.target.getBoundingClientRect(),R=m.clientX-C.left,E=m.clientY-C.top;p.onThumbPointerDown({x:R,y:E})}),onPointerUp:Ee(i.onPointerUp,p.onThumbPointerUp)})});xx.displayName=Pc;var Jp="ScrollAreaCorner",Cx=S.forwardRef((i,e)=>{const n=Oi(Jp,i.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.jsx(hP,{...i,ref:e}):null});Cx.displayName=Jp;var hP=S.forwardRef((i,e)=>{const{__scopeScrollArea:n,...r}=i,l=Oi(Jp,n),[u,p]=S.useState(0),[a,c]=S.useState(0),f=!!(u&&a);return eo(l.scrollbarX,()=>{const v=l.scrollbarX?.offsetHeight||0;l.onCornerHeightChange(v),c(v)}),eo(l.scrollbarY,()=>{const v=l.scrollbarY?.offsetWidth||0;l.onCornerWidthChange(v),p(v)}),f?d.jsx(Ne.div,{...r,ref:e,style:{width:u,height:a,position:"absolute",right:l.dir==="ltr"?0:void 0,left:l.dir==="rtl"?0:void 0,bottom:0,...i.style}}):null});function zc(i){return i?parseInt(i,10):0}function Ex(i,e){const n=i/e;return isNaN(n)?0:n}function fu(i){const e=Ex(i.viewport,i.content),n=i.scrollbar.paddingStart+i.scrollbar.paddingEnd,r=(i.scrollbar.size-n)*e;return Math.max(r,18)}function fP(i,e,n,r="ltr"){const l=fu(n),u=l/2,p=e||u,a=l-p,c=n.scrollbar.paddingStart+p,f=n.scrollbar.size-n.scrollbar.paddingEnd-a,v=n.content-n.viewport,m=r==="ltr"?[0,v]:[v*-1,0];return Dx([c,f],m)(i)}function Wy(i,e,n="ltr"){const r=fu(e),l=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,u=e.scrollbar.size-l,p=e.content-e.viewport,a=u-r,c=n==="ltr"?[0,p]:[p*-1,0],f=Vf(i,c);return Dx([0,p],[0,a])(f)}function Dx(i,e){return n=>{if(i[0]===i[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(i[1]-i[0]);return e[0]+r*(n-i[0])}}function Ax(i,e){return i>0&&i<e}var pP=(i,e=()=>{})=>{let n={left:i.scrollLeft,top:i.scrollTop},r=0;return(function l(){const u={left:i.scrollLeft,top:i.scrollTop},p=n.left!==u.left,a=n.top!==u.top;(p||a)&&e(),n=u,r=window.requestAnimationFrame(l)})(),()=>window.cancelAnimationFrame(r)};function pu(i,e){const n=Wt(i),r=S.useRef(0);return S.useEffect(()=>()=>window.clearTimeout(r.current),[]),S.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,e)},[n,e])}function eo(i,e){const n=Wt(e);Nt(()=>{let r=0;if(i){const l=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return l.observe(i),()=>{window.cancelAnimationFrame(r),l.unobserve(i)}}},[i,n])}var kx=vx,mP=bx,gP=Cx;const mu=S.forwardRef(({className:i,children:e,...n},r)=>d.jsxs(kx,{ref:r,className:we("relative overflow-hidden",i),...n,children:[d.jsx(mP,{className:"h-full w-full rounded-[inherit]",children:e}),d.jsx(Tx,{}),d.jsx(gP,{})]}));mu.displayName=kx.displayName;const Tx=S.forwardRef(({className:i,orientation:e="vertical",...n},r)=>d.jsx(Xp,{ref:r,orientation:e,className:we("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",i),...n,children:d.jsx(xx,{className:"relative flex-1 rounded-full bg-border"})}));Tx.displayName=Xp.displayName;var gu="Collapsible",[vP]=pi(gu),[_P,Qp]=vP(gu),Rx=S.forwardRef((i,e)=>{const{__scopeCollapsible:n,open:r,defaultOpen:l,disabled:u,onOpenChange:p,...a}=i,[c,f]=Ni({prop:r,defaultProp:l??!1,onChange:p,caller:gu});return d.jsx(_P,{scope:n,disabled:u,contentId:Ht(),open:c,onOpenToggle:S.useCallback(()=>f(v=>!v),[f]),children:d.jsx(Ne.div,{"data-state":tm(c),"data-disabled":u?"":void 0,...a,ref:e})})});Rx.displayName=gu;var Nx="CollapsibleTrigger",Ox=S.forwardRef((i,e)=>{const{__scopeCollapsible:n,...r}=i,l=Qp(Nx,n);return d.jsx(Ne.button,{type:"button","aria-controls":l.contentId,"aria-expanded":l.open||!1,"data-state":tm(l.open),"data-disabled":l.disabled?"":void 0,disabled:l.disabled,...r,ref:e,onClick:Ee(i.onClick,l.onOpenToggle)})});Ox.displayName=Nx;var em="CollapsibleContent",jx=S.forwardRef((i,e)=>{const{forceMount:n,...r}=i,l=Qp(em,i.__scopeCollapsible);return d.jsx(Qt,{present:n||l.open,children:({present:u})=>d.jsx(bP,{...r,ref:e,present:u})})});jx.displayName=em;var bP=S.forwardRef((i,e)=>{const{__scopeCollapsible:n,present:r,children:l,...u}=i,p=Qp(em,n),[a,c]=S.useState(r),f=S.useRef(null),v=Ge(e,f),m=S.useRef(0),y=m.current,C=S.useRef(0),R=C.current,E=p.open||a,g=S.useRef(E),b=S.useRef(void 0);return S.useEffect(()=>{const _=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(_)},[]),Nt(()=>{const _=f.current;if(_){b.current=b.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const x=_.getBoundingClientRect();m.current=x.height,C.current=x.width,g.current||(_.style.transitionDuration=b.current.transitionDuration,_.style.animationName=b.current.animationName),c(r)}},[p.open,r]),d.jsx(Ne.div,{"data-state":tm(p.open),"data-disabled":p.disabled?"":void 0,id:p.contentId,hidden:!E,...u,ref:v,style:{"--radix-collapsible-content-height":y?`${y}px`:void 0,"--radix-collapsible-content-width":R?`${R}px`:void 0,...i.style},children:E&&l})});function tm(i){return i?"open":"closed"}var yP=Rx;const Mx=yP,Lx=Ox,Px=jx;function SP(){const[i,e]=S.useState({}),[n,r]=S.useState(new Set),[l,u]=S.useState(null),p=S.useCallback(async a=>{if(!(i[a]||n.has(a))){r(c=>new Set(c).add(a)),u(null);try{const c=a?`?path=${encodeURIComponent(a)}`:"",f=await fetch(`/api/files${c}`);if(!f.ok)throw new Error(`Failed to list directory: ${f.statusText}`);const m=(await f.json()).entries.sort((y,C)=>y.type!==C.type?y.type==="directory"?-1:1:y.name.localeCompare(C.name));e(y=>({...y,[a||"__root__"]:m}))}catch(c){u(c instanceof Error?c.message:"Failed to load directory")}finally{r(c=>{const f=new Set(c);return f.delete(a),f})}}},[i,n]);return{cache:i,loading:n,error:l,fetchDirectory:p}}function zx({entry:i,status:e,depth:n,onFileClick:r}){const l=e==="created"?"+":e==="modified"?"~":e==="deleted"?"-":null;return d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsxs("div",{role:"treeitem",className:`file-item${e?` file-${e}`:""}`,style:{paddingLeft:`${12+n*16}px`},tabIndex:0,"aria-label":`${i.name}${e?`, ${e}`:""}`,onClick:()=>r?.(i,e),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),r?.(i,e))},children:[l&&d.jsx("span",{className:`status-icon status-${e}`,"aria-hidden":"true",children:l}),d.jsx("span",{className:"file-name",children:i.name})]})}),d.jsx(Oe,{children:i.path})]})}function Bx({entry:i,depth:e,changedFiles:n,onFileClick:r,fetchDirectory:l,cache:u,loading:p}){const a=Array.from(n.keys()).some(C=>C.startsWith(i.path+"/")),[c,f]=S.useState(a),v=u[i.path],m=p.has(i.path);S.useEffect(()=>{a&&!v&&!p.has(i.path)&&l(i.path)},[a,v,i.path,l,p]),S.useEffect(()=>{a&&f(!0)},[a]);const y=S.useCallback(()=>{const C=!c;f(C),C&&!v&&l(i.path)},[c,v,i.path,l]);return d.jsxs(Mx,{open:c,onOpenChange:y,children:[d.jsx(Lx,{asChild:!0,children:d.jsxs("div",{className:`directory-header${a?" has-changes":""}`,style:{paddingLeft:`${4+e*16}px`},children:[d.jsx("span",{className:"directory-toggle",children:d.jsx("span",{className:"toggle-icon",children:c?"▼":"▶"})}),d.jsx("span",{className:"directory-name",children:i.name})]})}),d.jsxs(Px,{children:[m&&d.jsx("div",{className:"tree-loading",style:{paddingLeft:`${12+(e+1)*16}px`},children:"Loading..."}),v?.map(C=>C.type==="directory"?d.jsx(Bx,{entry:C,depth:e+1,changedFiles:n,onFileClick:r,fetchDirectory:l,cache:u,loading:p},C.path):d.jsx(zx,{entry:C,status:n.get(C.path),depth:e+1,onFileClick:r},C.path))]})]})}function wP({changedFiles:i,onFileClick:e}){const{cache:n,loading:r,error:l,fetchDirectory:u}=SP();S.useEffect(()=>{u("")},[]);const p=n.__root__,a=i.size;return d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{role:"tree","aria-label":"Project files",className:"filetree full-filetree",children:[a>0&&d.jsx(Ke,{variant:"secondary","data-testid":"file-count-badge",className:"file-count-badge","aria-label":`${a} files changed`,children:a}),d.jsxs(mu,{className:"filetree-scroll",children:[l&&d.jsx("div",{className:"tree-error",children:l}),!p&&!l&&d.jsx("div",{className:"tree-loading",children:"Loading project files..."}),p?.map(c=>c.type==="directory"?d.jsx(Bx,{entry:c,depth:0,changedFiles:i,onFileClick:e,fetchDirectory:u,cache:n,loading:r},c.path):d.jsx(zx,{entry:c,status:i.get(c.path),depth:0,onFileClick:e},c.path))]})]})})}function Vy(i){const e=i[0]||" ",n=i[1]||" ";return e==="D"||n==="D"?"deleted":e==="?"||e==="A"?"created":"modified"}function Ix(){const{repos:i}=ux(),e=S.useMemo(()=>{const r=new Map;for(const l of i)for(const u of l.files){const p=i.length>1?`${l.path}/${u.path}`:`${l.path}/${u.path}`;r.set(p,Vy(u.status)),r.set(u.path,Vy(u.status))}return r},[i]),n=S.useCallback((r,l)=>{fetch("/api/files/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r.path})}).catch(u=>console.error("[ChangedPanel] Failed to open file:",u))},[]);return d.jsx("div",{className:"changed-panel","data-testid":"changed-panel",children:d.jsx(wP,{changedFiles:e,onFileClick:n})})}const xP=2e3;function CP(){const[i,e]=S.useState([]),[n,r]=S.useState(null),l=S.useRef(null);S.useEffect(()=>{let a=null,c=!0;const f=()=>{const v=window.location.protocol==="https:"?"wss:":"ws:",m=new WebSocket(`${v}//${window.location.host}/ws/diffs`);l.current=m,m.onopen=()=>{console.log("[useDiffs] WebSocket connected")},m.onmessage=y=>{try{const C=JSON.parse(y.data);if(C.type==="init"){const R=C.diffs||[];e(R),R.length>0&&r(R[R.length-1])}else if(C.type==="diff"){const R=C.diff;e(E=>{const g=E.findIndex(b=>b.path===R.path);if(g>=0){const b=[...E];return b[g]=R,b}return[...E,R]}),r(R)}else if(C.type==="refresh"){const R=C.diffs||[];e(R),R.length>0?r(E=>{if(E){const g=R.find(b=>b.path===E.path);if(g)return g}return R[R.length-1]}):r(null)}}catch(C){console.error("[useDiffs] Failed to parse message:",C)}},m.onclose=()=>{c&&(a=setTimeout(f,xP))},m.onerror=y=>{console.error("[useDiffs] WebSocket error:",y),m.close()}};return f(),()=>{c=!1,a&&clearTimeout(a),l.current?.close()}},[]);const u=S.useCallback(a=>{const c=i.find(f=>f.path===a);r(c||null)},[i]),p=S.useCallback(()=>{e([]),r(null),l.current?.readyState===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"clear"}))},[]);return{diffs:i,selectedDiff:n,selectDiff:u,clearDiffs:p}}function EP({line:i,type:e,lineNum:n}){return d.jsxs("div",{className:`diff-line diff-${e}`,children:[n!==void 0&&d.jsx("span",{className:"line-num",children:n}),d.jsx("span",{className:"line-content",children:i})]})}function DP(i){const e=i.split(`
65
65
  `),n=[];let r=0;for(const l of e)if(l.startsWith("diff --git")||l.startsWith("index ")||l.startsWith("---")||l.startsWith("+++"))n.push({line:l,type:"header"});else if(l.startsWith("@@")){const u=l.match(/@@ -\d+(?:,\d+)? \+(\d+)/);u&&(r=parseInt(u[1],10)-1),n.push({line:l,type:"hunk"})}else l.startsWith("+")?(r++,n.push({line:l.substring(1),type:"added",lineNum:r})):l.startsWith("-")?n.push({line:l.substring(1),type:"removed"}):l.startsWith(" ")||l===""?(r++,n.push({line:l.substring(1)||"",type:"context",lineNum:r})):n.push({line:l,type:"context"});return n}function AP({diff:i}){const e=i.diff&&i.diff.trim().length>0;let n;if(e)n=DP(i.diff);else{const l=(i.original||"").split(`
66
66
  `),u=(i.modified||"").split(`
67
67
  `);n=[],l.forEach((p,a)=>{u.includes(p)||n.push({line:p,type:"removed",lineNum:a+1})}),u.forEach((p,a)=>{const c=l.includes(p)?"context":"added";n.push({line:p,type:c,lineNum:a+1})})}const r=i.additions!==void 0&&i.deletions!==void 0?`+${i.additions} -${i.deletions}`:null;return d.jsxs("div",{className:"diff-view","data-testid":"diff-view",children:[d.jsxs("div",{className:"diff-header",children:[d.jsx("span",{className:"diff-path",children:i.path}),i.status&&d.jsx("span",{className:`diff-status diff-status-${i.status}`,children:i.status}),r&&d.jsx("span",{className:"diff-stats",children:r}),d.jsx("span",{className:"diff-tool",children:i.toolName})]}),d.jsx("div",{className:"diff-content",children:n.map((l,u)=>d.jsx(EP,{line:l.line,type:l.type,lineNum:l.lineNum},u))})]})}function Hx(){const{diffs:i,selectedDiff:e,selectDiff:n,clearDiffs:r}=CP();return i.length===0?d.jsxs("div",{className:"diffs-panel empty","data-testid":"diffs-panel",children:[d.jsx("div",{className:"placeholder",children:"No diffs yet"}),d.jsx("p",{className:"hint",children:"Diffs appear when files are modified"})]}):d.jsxs("div",{className:"diffs-panel","data-testid":"diffs-panel",children:[d.jsxs("div",{className:"panel-header",children:[d.jsxs("span",{className:"diff-count",children:[i.length," file(s)"]}),d.jsx(De,{variant:"ghost",size:"sm",type:"button",className:"clear-button",onClick:r,children:"Clear"})]}),i.length>1&&d.jsx("div",{className:"diff-tabs",children:i.map(l=>d.jsx(De,{variant:e?.path===l.path?"secondary":"ghost",size:"sm",type:"button",className:`diff-tab ${e?.path===l.path?"active":""}`,onClick:()=>n(l.path),children:l.path.split("/").pop()},l.path))}),e&&d.jsx(AP,{diff:e})]})}function ka({open:i,onOpenChange:e,title:n,description:r,footer:l,className:u,children:p}){return d.jsx(au,{open:i,onOpenChange:e,children:d.jsxs(Da,{className:we("max-w-5xl max-h-[80vh] overflow-y-auto",u),children:[d.jsxs(lu,{children:[d.jsx(cu,{children:n}),r&&d.jsx(uu,{children:r})]}),p,l&&d.jsx(Bp,{children:l})]})})}function kP(i){const[e,n]=S.useState(null),[r,l]=S.useState(!1),[u,p]=S.useState(null),a=S.useRef(null),c=S.useCallback(()=>{a.current&&a.current.abort();const f=new AbortController;a.current=f,l(!0),p(null);const v=new URLSearchParams({days:String(i.days)});i.repo&&v.set("repo",i.repo);const m=i.skipTypes??(i.includeOrchestrator?[]:["orchestrator"]);for(const y of m)v.append("skip_type",y);fetch(`/api/hotspots?${v}`,{signal:f.signal}).then(y=>{if(!y.ok)throw new Error(`HTTP ${y.status}: ${y.statusText}`);return y.json()}).then(y=>{n(y),l(!1)}).catch(y=>{y.name!=="AbortError"&&(p(y instanceof Error?y:new Error(String(y))),l(!1))})},[i.days,i.repo,i.skipTypes,i.includeOrchestrator]);return S.useEffect(()=>()=>{a.current&&a.current.abort()},[]),{data:e,isLoading:r,error:u,refresh:c}}const TP=[30,60,90],RP=new Set([".ts",".tsx",".js",".jsx",".py",".md",".css",".scss",".html"]),NP=new Set([".json",".yaml",".yml",".toml",".env"]);function OP(i){const e=i.split("/").pop()||"";if(e.startsWith(".")&&!e.includes(".",1))return"."+e.slice(1);const n=e.lastIndexOf(".");return n>0?e.slice(n):""}function $y(i,e,n){if(!e)return!0;const r=OP(i);return!!(RP.has(r)||n&&NP.has(r))}function ki({label:i,field:e,currentSort:n,currentDirection:r,onSort:l,align:u="right"}){const p=n===e,a=p?r==="desc"?" v":" ^":"";return d.jsxs("th",{className:`text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2 cursor-pointer select-none ${u==="left"?"text-left":"text-right"} ${p?"text-[var(--text-primary)]":""}`,onClick:()=>l(e),role:"columnheader","aria-sort":p?r==="desc"?"descending":"ascending":"none",children:[i,a]})}function jP({hotspots:i,sortField:e,sortDirection:n,onSort:r}){const l=S.useMemo(()=>{const u=[...i];return u.sort((p,a)=>{const c=p[e],f=a[e];if(typeof c=="number"&&typeof f=="number")return n==="desc"?f-c:c-f;const v=String(c),m=String(f);return n==="desc"?m.localeCompare(v):v.localeCompare(m)}),u},[i,e,n]);return d.jsxs("table",{className:"w-full text-sm",role:"table",children:[d.jsx("thead",{children:d.jsxs("tr",{className:"border-b border-[var(--border)]",children:[d.jsx(ki,{label:"Score",field:"hotspot_score",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Changes",field:"change_count",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Fixes",field:"bug_fix_count",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Authors",field:"author_count",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Churn",field:"churn",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"File",field:"path",currentSort:e,currentDirection:n,onSort:r,align:"left"})]})}),d.jsx("tbody",{children:l.map(u=>d.jsxs("tr",{className:"text-[var(--text-primary)]",children:[d.jsx("td",{className:"text-right py-1.5",children:d.jsx(Ke,{variant:u.hotspot_score>=50?"destructive":u.hotspot_score>=25?"outline":"secondary",children:u.hotspot_score.toFixed(1)})}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.change_count}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.bug_fix_count}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.author_count}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.churn}),d.jsx("td",{className:"text-left py-1.5",children:d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"truncate max-w-xs inline-block align-bottom font-mono text-xs",children:u.path})}),d.jsx(Oe,{children:u.path})]})})]},u.path))})]})}function MP({hotspots:i,sortField:e,sortDirection:n,onSort:r}){const l=S.useMemo(()=>{const u=[...i];return u.sort((p,a)=>{const f={change_count:"total_changes",bug_fix_count:"total_bug_fixes",author_count:"avg_author_count",churn:"file_count"}[e]||e,v=p[f],m=a[f];return typeof v=="number"&&typeof m=="number"?n==="desc"?m-v:v-m:n==="desc"?String(m).localeCompare(String(v)):String(v).localeCompare(String(m))}),u},[i,e,n]);return d.jsxs("table",{className:"w-full text-sm",role:"table",children:[d.jsx("thead",{children:d.jsxs("tr",{className:"border-b border-[var(--border)]",children:[d.jsx(ki,{label:"Score",field:"hotspot_score",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Changes",field:"change_count",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Fixes",field:"bug_fix_count",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Authors",field:"author_count",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Files",field:"churn",currentSort:e,currentDirection:n,onSort:r}),d.jsx(ki,{label:"Directory",field:"path",currentSort:e,currentDirection:n,onSort:r,align:"left"})]})}),d.jsx("tbody",{children:l.map(u=>d.jsxs("tr",{className:"text-[var(--text-primary)]",children:[d.jsx("td",{className:"text-right py-1.5",children:d.jsx(Ke,{variant:u.hotspot_score>=50?"destructive":u.hotspot_score>=25?"outline":"secondary",children:u.hotspot_score.toFixed(1)})}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.total_changes}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.total_bug_fixes}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.avg_author_count.toFixed(1)}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:u.file_count}),d.jsx("td",{className:"text-left py-1.5",children:d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx("span",{className:"truncate max-w-xs inline-block align-bottom font-mono text-xs",children:u.path})}),d.jsx(Oe,{children:u.path})]})})]},u.path))})]})}function LP({open:i,onOpenChange:e}){const[n,r]=S.useState(90),[l,u]=S.useState("files"),[p,a]=S.useState("hotspot_score"),[c,f]=S.useState("desc"),[v,m]=S.useState(!1),[y,C]=S.useState(!1),[R,E]=S.useState(!1),{data:g,isLoading:b,error:_,refresh:x}=kP({days:n,includeOrchestrator:v}),A=S.useCallback(z=>{a(U=>U===z?(f(X=>X==="desc"?"asc":"desc"),U):(f("desc"),z))},[]),D=S.useMemo(()=>g?g.repo_results?g.repo_results:g.file_hotspots?[{success:g.success,repo_name:g.repo_name||"",repo_path:g.repo_path||"",time_window_days:g.time_window_days||n,commit_count:g.commit_count||0,file_hotspots:g.file_hotspots||[],directory_hotspots:g.directory_hotspots||[]}]:[]:[],[g,n]),N=S.useMemo(()=>{const z=[];for(const U of D)U.success&&z.push(...U.file_hotspots);return z},[D]),O=S.useMemo(()=>{const z=[];for(const U of D)U.success&&z.push(...U.directory_hotspots);return z},[D]),T=S.useMemo(()=>N.filter(z=>$y(z.path,y,R)),[N,y,R]),j=S.useMemo(()=>O.filter(z=>$y(z.path,y,R)),[O,y,R]),H=D.reduce((z,U)=>z+(U.commit_count||0),0),I=()=>b?d.jsx("div",{className:"hotspots-panel loading","data-testid":"hotspots-panel",children:d.jsxs("div",{className:"space-y-3 p-2",children:[d.jsx(ve,{className:"h-4 w-40"}),d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-3 w-3/4"}),d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-3 w-5/6"})]})}):_?d.jsxs("div",{className:"hotspots-panel error","data-testid":"hotspots-panel",children:[d.jsx("div",{className:"error-message",children:_.message}),d.jsx(De,{variant:"outline",size:"sm",onClick:x,children:"Retry"})]}):d.jsx(wt,{delayDuration:300,children:d.jsxs("div",{className:"hotspots-panel","data-testid":"hotspots-panel",children:[d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[d.jsx("div",{className:"flex gap-1",children:TP.map(z=>d.jsxs(De,{variant:n===z?"default":"outline",size:"sm",onClick:()=>r(z),children:[z,"d"]},z))}),d.jsxs("div",{className:"flex gap-1",children:[d.jsx(De,{variant:l==="files"?"default":"outline",size:"sm",onClick:()=>u("files"),children:"Files"}),d.jsx(De,{variant:l==="dirs"?"default":"outline",size:"sm",onClick:()=>u("dirs"),children:"Dirs"})]}),d.jsx("div",{className:"ml-auto",children:d.jsxs(je,{children:[d.jsx(Me,{asChild:!0,children:d.jsx(De,{variant:"outline",size:"sm",onClick:x,children:"Analyze"})}),d.jsx(Oe,{children:"Run hotspot analysis"})]})})]}),d.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2",children:[d.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--text-secondary)] cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:v,onChange:z=>m(z.target.checked)}),"Include orchestrator"]}),d.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--text-secondary)] cursor-pointer",children:[d.jsx("input",{type:"checkbox","aria-label":"Code only",checked:y,onChange:z=>C(z.target.checked)}),"Code only"]}),d.jsxs("label",{className:"flex items-center gap-2 text-sm text-[var(--text-secondary)] cursor-pointer",children:[d.jsx("input",{type:"checkbox","aria-label":"Include config",checked:R,disabled:!y,onChange:z=>E(z.target.checked),className:"disabled:opacity-40"}),d.jsx("span",{className:y?"":"opacity-40",children:"Include config"})]})]})]}),g&&d.jsxs("div",{className:"flex gap-4 text-xs text-[var(--text-muted)]",children:[d.jsxs("span",{children:[H," commits"]}),d.jsxs("span",{children:[T.length," files"]}),d.jsxs("span",{children:[j.length," dirs"]})]}),!g&&d.jsxs("div",{className:"text-center py-12 text-[var(--text-muted)]",children:["Click ",d.jsx("strong",{children:"Analyze"})," to detect code hotspots"]}),g&&l==="files"&&(T.length>0?d.jsx(jP,{hotspots:T.slice(0,50),sortField:p,sortDirection:c,onSort:A}):d.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No file hotspots found"})),g&&l==="dirs"&&(j.length>0?d.jsx(MP,{hotspots:j.slice(0,50),sortField:p,sortDirection:c,onSort:A}):d.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No directory hotspots found"}))]})});return d.jsx(ka,{open:i,onOpenChange:e,title:"Hotspots",description:"Files and directories ranked by change frequency and complexity",children:I()})}function PP(i){const[e,n]=S.useState(null),[r,l]=S.useState(!1),[u,p]=S.useState(null),a=S.useRef(null),c=S.useCallback(()=>{a.current&&a.current.abort();const f=new AbortController;a.current=f,l(!0),p(null);const v=new URLSearchParams({days:String(i.days)});i.repo&&v.set("repo",i.repo),i.type&&v.set("type",i.type),fetch(`/api/code-markers?${v}`,{signal:f.signal}).then(m=>{if(!m.ok)throw new Error(`HTTP ${m.status}: ${m.statusText}`);return m.json()}).then(m=>{n(m),l(!1)}).catch(m=>{m.name!=="AbortError"&&(p(m instanceof Error?m:new Error(String(m))),l(!1))})},[i.days,i.repo,i.type]);return S.useEffect(()=>()=>{a.current&&a.current.abort()},[]),{data:e,isLoading:r,error:u,refresh:c}}function zP({open:i,onOpenChange:e}){const{data:n,isLoading:r,error:l,refresh:u}=PP({days:90,repo:"pennyfarthing"});S.useEffect(()=>{i&&u()},[i,u]);const[p,a]=S.useState("all"),[c,f]=S.useState("age_days"),[v,m]=S.useState("desc"),y=S.useMemo(()=>{if(!n?.markers)return[];switch(p){case"stale":return n.markers.filter(g=>g.is_stale);case"deprecated":return[];default:return n.markers}},[n,p]),C=S.useMemo(()=>{const g=[...y];return g.sort((b,_)=>{const x=b[c],A=_[c];if(typeof x=="string"&&typeof A=="string")return v==="asc"?x.localeCompare(A):A.localeCompare(x);const D=Number(x),N=Number(A);return v==="asc"?D-N:N-D}),g},[y,c,v]),R=g=>{c===g?m(b=>b==="asc"?"desc":"asc"):(f(g),m("desc"))},E=g=>c!==g?"":v==="desc"?" v":" ^";return d.jsxs(ka,{open:i,onOpenChange:e,title:"Code Markers",description:"TODO, FIXME, HACK, and XXX markers across the codebase",children:[r&&d.jsxs("div",{className:"space-y-2",children:[d.jsx(ve,{className:"h-4 w-full"}),d.jsx(ve,{className:"h-4 w-3/4"}),d.jsx(ve,{className:"h-4 w-1/2"})]}),l&&d.jsx("div",{className:"p-4 rounded border border-[var(--status-error)]/20 bg-[var(--status-error)]/5 text-[var(--status-error)] text-sm",children:l.message}),!r&&!l&&n&&d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"flex gap-4 text-xs text-[var(--text-muted)]","data-testid":"code-markers-summary",children:[d.jsxs("span",{"data-testid":"summary-total",children:["Total: ",d.jsx("span",{className:"tabular-nums font-mono",children:n.summary.total_markers})]}),d.jsxs("span",{"data-testid":"summary-stale",children:["Stale: ",d.jsx("span",{className:"tabular-nums font-mono",children:n.summary.stale_markers})]}),Object.entries(n.summary.by_type).map(([g,b])=>d.jsxs("span",{"data-testid":`summary-type-${g.toLowerCase()}`,children:[g,": ",d.jsx("span",{className:"tabular-nums font-mono",children:b})]},g))]}),d.jsx("div",{role:"tablist",className:"flex gap-4 border-b border-[var(--border)] mb-3",children:["all","stale","deprecated"].map(g=>d.jsx("button",{role:"tab","aria-selected":p===g,onClick:()=>a(g),className:`pb-2 text-sm capitalize ${p===g?"border-b-2 border-[var(--accent)] text-[var(--text-primary)] font-medium":"text-[var(--text-muted)]"}`,children:g},g))}),C.length===0?d.jsx("div",{className:"text-center py-12 text-[var(--text-muted)]",children:"No markers found"}):d.jsxs("table",{role:"table",className:"w-full text-sm",children:[d.jsx("thead",{children:d.jsxs("tr",{className:"border-b border-[var(--border)]",children:[d.jsxs("th",{className:"cursor-pointer select-none text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>R("marker_type"),children:["Type",E("marker_type")]}),d.jsxs("th",{className:"cursor-pointer select-none text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>R("path"),children:["File",E("path")]}),d.jsxs("th",{className:"cursor-pointer select-none text-right text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>R("line"),children:["Line",E("line")]}),d.jsx("th",{className:"text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",children:"Text"}),d.jsxs("th",{className:"cursor-pointer select-none text-left text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>R("author"),children:["Author",E("author")]}),d.jsxs("th",{className:"cursor-pointer select-none text-right text-xs font-medium uppercase tracking-wider text-[var(--text-muted)] pb-2",onClick:()=>R("age_days"),children:["Age",E("age_days")]})]})}),d.jsx("tbody",{children:C.map((g,b)=>d.jsxs("tr",{className:"text-[var(--text-primary)]",children:[d.jsx("td",{className:"py-1.5",children:d.jsx(Ke,{variant:g.is_stale?"destructive":"secondary",children:g.marker_type})}),d.jsx("td",{className:"py-1.5 font-mono text-xs",children:g.path}),d.jsx("td",{className:"text-right py-1.5 tabular-nums font-mono",children:g.line}),d.jsx("td",{className:"py-1.5 truncate max-w-xs",children:g.text}),d.jsx("td",{className:"py-1.5",children:g.author}),d.jsxs("td",{className:"text-right py-1.5 tabular-nums font-mono",children:[g.age_days,"d"]})]},`${g.path}:${g.line}:${b}`))})]})]})]})}function BP(i){const[e,n]=S.useState(null),[r,l]=S.useState(!1),[u,p]=S.useState(null),a=S.useRef(null),c=S.useCallback(()=>{a.current&&a.current.abort();const f=new AbortController;a.current=f,l(!0),p(null);const v=new URLSearchParams;i.path&&v.set("path",i.path),i.top&&v.set("top",String(i.top)),fetch(`/api/complexity?${v}`,{signal:f.signal}).then(m=>{if(!m.ok)throw new Error(`HTTP ${m.status}: ${m.statusText}`);return m.json()}).then(m=>{n(m),l(!1)}).catch(m=>{m.name!=="AbortError"&&(p(m instanceof Error?m:new Error(String(m))),l(!1))})},[i.path,i.top]);return S.useEffect(()=>()=>{a.current&&a.current.abort()},[]),{data:e,isLoading:r,error:u,refresh:c}}function Ur({label:i,field:e,currentSort:n,currentDirection:r,onSort:l,align:u="right"}){const p=n===e,a=p?r==="desc"?" v":" ^":"";return d.jsxs("th",{className:`text-${u} ${p?"active":""}`,onClick:()=>l(e),role:"columnheader","aria-sort":p?r==="desc"?"descending":"ascending":"none",style:{cursor:"pointer",userSelect:"none",padding:"4px 8px"},children:[i,a]})}function IP({open:i,onOpenChange:e}){const[n,r]=S.useState("avg_cyclomatic_complexity"),[l,u]=S.useState("desc"),{data:p,isLoading:a,error:c,refresh:f}=BP({});S.useEffect(()=>{i&&f()},[i,f]);const v=S.useCallback(C=>{r(R=>R===C?(u(E=>E==="desc"?"asc":"desc"),R):(u("desc"),C))},[]),m=S.useMemo(()=>{if(!p?.files)return[];const C=[...p.files];return C.sort((R,E)=>{const g=R[n],b=E[n];return typeof g=="number"&&typeof b=="number"?l==="desc"?b-g:g-b:l==="desc"?String(b).localeCompare(String(g)):String(g).localeCompare(String(b))}),C},[p,n,l]),y=()=>a?d.jsx("div",{className:"complexity-panel loading","data-testid":"complexity-panel",children:d.jsxs("div",{className:"space-y-3 p-2",children:[d.jsx(ve,{className:"h-4 w-40"}),d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-3 w-3/4"})]})}):c?d.jsxs("div",{className:"complexity-panel error","data-testid":"complexity-panel",children:[d.jsxs("div",{className:"error-message",children:["Error: ",c.message]}),d.jsx(De,{variant:"outline",size:"sm",onClick:f,children:"Retry"})]}):p?d.jsxs("div",{className:"complexity-panel","data-testid":"complexity-panel",children:[d.jsx("div",{className:"complexity-summary",style:{marginBottom:"8px"},children:d.jsxs("span",{children:[p.file_count," files analyzed"]})}),d.jsxs("table",{className:"complexity-table",role:"table",style:{width:"100%",borderCollapse:"collapse"},children:[d.jsx("thead",{children:d.jsxs("tr",{children:[d.jsx(Ur,{label:"Complexity",field:"avg_cyclomatic_complexity",currentSort:n,currentDirection:l,onSort:v}),d.jsx(Ur,{label:"Nesting",field:"max_nesting_depth",currentSort:n,currentDirection:l,onSort:v}),d.jsx(Ur,{label:"Longest Fn",field:"longest_function",currentSort:n,currentDirection:l,onSort:v}),d.jsx(Ur,{label:"Lines",field:"total_lines",currentSort:n,currentDirection:l,onSort:v}),d.jsx(Ur,{label:"Functions",field:"function_count",currentSort:n,currentDirection:l,onSort:v}),d.jsx(Ur,{label:"File",field:"path",currentSort:n,currentDirection:l,onSort:v,align:"left"})]})}),d.jsx("tbody",{children:m.map(C=>d.jsxs("tr",{children:[d.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:d.jsx(Ke,{variant:C.avg_cyclomatic_complexity>=7?"destructive":C.avg_cyclomatic_complexity>=4?"outline":"secondary",children:Number(C.avg_cyclomatic_complexity).toFixed(1)})}),d.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:C.max_nesting_depth}),d.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:C.longest_function}),d.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:C.total_lines}),d.jsx("td",{className:"text-right",style:{padding:"4px 8px"},children:C.function_count}),d.jsx("td",{className:"text-left",style:{padding:"4px 8px"},children:C.path})]},C.path))})]})]}):d.jsx("div",{className:"complexity-panel","data-testid":"complexity-panel",children:d.jsxs("p",{children:["Click ",d.jsx("strong",{children:"Analyze"})," to run complexity analysis"]})});return d.jsx(ka,{open:i,onOpenChange:e,title:"Complexity",description:"Cyclomatic complexity analysis",children:y()})}function HP(i){const[e,n]=S.useState(null),[r,l]=S.useState(!1),[u,p]=S.useState(null),a=S.useRef(null),c=S.useCallback(()=>{a.current&&a.current.abort();const f=new AbortController;a.current=f,l(!0),p(null);const v=new URLSearchParams;i.path&&v.set("path",i.path),fetch(`/api/dependencies?${v}`,{signal:f.signal}).then(m=>{if(!m.ok)throw new Error(`HTTP ${m.status}: ${m.statusText}`);return m.json()}).then(m=>{n(m),l(!1)}).catch(m=>{m.name!=="AbortError"&&(p(m instanceof Error?m:new Error(String(m))),l(!1))})},[i.path]);return S.useEffect(()=>()=>{a.current&&a.current.abort()},[]),{data:e,isLoading:r,error:u,refresh:c}}function FP(i){return i==="high"||i==="critical"?"destructive":i==="moderate"?"outline":"secondary"}function GP({open:i,onOpenChange:e}){const{data:n,isLoading:r,error:l,refresh:u}=HP({});S.useEffect(()=>{i&&u()},[i,u]);const p=()=>r?d.jsx("div",{className:"dependencies-panel loading","data-testid":"dependencies-panel",children:d.jsxs("div",{className:"space-y-3 p-2",children:[d.jsx(ve,{className:"h-4 w-40"}),d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-3 w-full"}),d.jsx(ve,{className:"h-3 w-3/4"})]})}):l?d.jsxs("div",{className:"dependencies-panel error","data-testid":"dependencies-panel",children:[d.jsxs("div",{className:"error-message",children:["Error: ",l.message]}),d.jsx(De,{variant:"outline",size:"sm",onClick:u,children:"Retry"})]}):n?d.jsxs("div",{className:"dependencies-panel","data-testid":"dependencies-panel",children:[n.outdated.length>0&&d.jsxs("div",{className:"outdated-section",style:{marginBottom:"16px"},children:[d.jsxs("h4",{children:["Outdated Packages (",n.outdated.length,")"]}),d.jsxs("table",{role:"table",style:{width:"100%",borderCollapse:"collapse"},children:[d.jsx("thead",{children:d.jsxs("tr",{children:[d.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Package"}),d.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Current"}),d.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Wanted"}),d.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Latest"}),d.jsx("th",{className:"text-left",style:{padding:"4px 8px"},children:"Type"})]})}),d.jsx("tbody",{children:n.outdated.map(a=>d.jsxs("tr",{children:[d.jsx("td",{style:{padding:"4px 8px"},children:a.name}),d.jsx("td",{style:{padding:"4px 8px"},children:a.current}),d.jsx("td",{style:{padding:"4px 8px"},children:a.wanted}),d.jsx("td",{style:{padding:"4px 8px"},children:a.latest}),d.jsx("td",{style:{padding:"4px 8px"},children:a.type})]},a.name))})]})]}),n.advisories.length>0&&d.jsxs("div",{className:"security-section",children:[d.jsx("h4",{children:"Security Advisories"}),d.jsx("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap"},children:n.advisories.map(a=>d.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[d.jsx(Ke,{variant:FP(a.severity),children:a.severity}),d.jsx("span",{children:a.count})]},a.severity))})]}),n.outdated.length===0&&n.advisories.length===0&&d.jsx("p",{children:"All dependencies are up to date with no known vulnerabilities."})]}):d.jsx("div",{className:"dependencies-panel","data-testid":"dependencies-panel",children:d.jsxs("p",{children:["Click ",d.jsx("strong",{children:"Analyze"})," to check dependencies"]})});return d.jsx(ka,{open:i,onOpenChange:e,title:"Dependencies",description:"Package staleness and security analysis",children:p()})}function UP(i,e=[]){let n=[];function r(u,p){const a=S.createContext(p);a.displayName=u+"Context";const c=n.length;n=[...n,p];const f=m=>{const{scope:y,children:C,...R}=m,E=y?.[i]?.[c]||a,g=S.useMemo(()=>R,Object.values(R));return d.jsx(E.Provider,{value:g,children:C})};f.displayName=u+"Provider";function v(m,y){const C=y?.[i]?.[c]||a,R=S.useContext(C);if(R)return R;if(p!==void 0)return p;throw new Error(`\`${m}\` must be used within \`${u}\``)}return[f,v]}const l=()=>{const u=n.map(p=>S.createContext(p));return function(a){const c=a?.[i]||u;return S.useMemo(()=>({[`__scope${i}`]:{...a,[i]:c}}),[a,c])}};return l.scopeName=i,[r,WP(l,...e)]}function WP(...i){const e=i[0];if(i.length===1)return e;const n=()=>{const r=i.map(l=>({useScope:l(),scopeName:l.scopeName}));return function(u){const p=r.reduce((a,{useScope:c,scopeName:f})=>{const m=c(u)[`__scope${f}`];return{...a,...m}},{});return S.useMemo(()=>({[`__scope${e.scopeName}`]:p}),[p])}};return n.scopeName=e.scopeName,n}var im="Progress",nm=100,[VP]=UP(im),[$P,qP]=VP(im),Fx=S.forwardRef((i,e)=>{const{__scopeProgress:n,value:r=null,max:l,getValueLabel:u=YP,...p}=i;(l||l===0)&&!qy(l)&&console.error(KP(`${l}`,"Progress"));const a=qy(l)?l:nm;r!==null&&!Yy(r,a)&&console.error(XP(`${r}`,"Progress"));const c=Yy(r,a)?r:null,f=Bc(c)?u(c,a):void 0;return d.jsx($P,{scope:n,value:c,max:a,children:d.jsx(Wi.div,{"aria-valuemax":a,"aria-valuemin":0,"aria-valuenow":Bc(c)?c:void 0,"aria-valuetext":f,role:"progressbar","data-state":Wx(c,a),"data-value":c??void 0,"data-max":a,...p,ref:e})})});Fx.displayName=im;var Gx="ProgressIndicator",Ux=S.forwardRef((i,e)=>{const{__scopeProgress:n,...r}=i,l=qP(Gx,n);return d.jsx(Wi.div,{"data-state":Wx(l.value,l.max),"data-value":l.value??void 0,"data-max":l.max,...r,ref:e})});Ux.displayName=Gx;function YP(i,e){return`${Math.round(i/e*100)}%`}function Wx(i,e){return i==null?"indeterminate":i===e?"complete":"loading"}function Bc(i){return typeof i=="number"}function qy(i){return Bc(i)&&!isNaN(i)&&i>0}function Yy(i,e){return Bc(i)&&!isNaN(i)&&i<=e&&i>=0}function KP(i,e){return`Invalid prop \`max\` of value \`${i}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${nm}\`.`}function XP(i,e){return`Invalid prop \`value\` of value \`${i}\` supplied to \`${e}\`. The \`value\` prop must be:
@@ -87,4 +87,4 @@ WARNING: This link could potentially be dangerous`)){const b=window.open();if(b)
87
87
  `:`
88
88
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(T){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),b.isLinux&&T&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(T){const j=this._getMouseBufferCoords(T),H=this._model.finalSelectionStart,I=this._model.finalSelectionEnd;return!!(H&&I&&j)&&this._areCoordsInSelection(j,H,I)}isCellInSelection(T,j){const H=this._model.finalSelectionStart,I=this._model.finalSelectionEnd;return!(!H||!I)&&this._areCoordsInSelection([T,j],H,I)}_areCoordsInSelection(T,j,H){return T[1]>j[1]&&T[1]<H[1]||j[1]===H[1]&&T[1]===j[1]&&T[0]>=j[0]&&T[0]<H[0]||j[1]<H[1]&&T[1]===H[1]&&T[0]<H[0]||j[1]<H[1]&&T[1]===j[1]&&T[0]>=j[0]}_selectWordAtCursor(T,j){var H,I;const z=(I=(H=this._linkifier.currentLink)===null||H===void 0?void 0:H.link)===null||I===void 0?void 0:I.range;if(z)return this._model.selectionStart=[z.start.x-1,z.start.y-1],this._model.selectionStartLength=(0,_.getRangeLength)(z,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const U=this._getMouseBufferCoords(T);return!!U&&(this._selectWordAt(U,j),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(T,j){this._model.clearSelection(),T=Math.max(T,0),j=Math.min(j,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,T],this._model.selectionEnd=[this._bufferService.cols,j],this.refresh(),this._onSelectionChange.fire()}_handleTrim(T){this._model.handleTrim(T)&&this.refresh()}_getMouseBufferCoords(T){const j=this._mouseService.getCoords(T,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(j)return j[0]--,j[1]--,j[1]+=this._bufferService.buffer.ydisp,j}_getMouseEventScrollAmount(T){let j=(0,m.getCoordsRelativeToElement)(this._coreBrowserService.window,T,this._screenElement)[1];const H=this._renderService.dimensions.css.canvas.height;return j>=0&&j<=H?0:(j>H&&(j-=H),j=Math.min(Math.max(j,-50),50),j/=50,j/Math.abs(j)+Math.round(14*j))}shouldForceSelection(T){return b.isMac?T.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:T.shiftKey}handleMouseDown(T){if(this._mouseDownTimeStamp=T.timeStamp,(T.button!==2||!this.hasSelection)&&T.button===0){if(!this._enabled){if(!this.shouldForceSelection(T))return;T.stopPropagation()}T.preventDefault(),this._dragScrollAmount=0,this._enabled&&T.shiftKey?this._handleIncrementalClick(T):T.detail===1?this._handleSingleClick(T):T.detail===2?this._handleDoubleClick(T):T.detail===3&&this._handleTripleClick(T),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(T){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(T))}_handleSingleClick(T){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(T)?3:0,this._model.selectionStart=this._getMouseBufferCoords(T),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const j=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);j&&j.length!==this._model.selectionStart[0]&&j.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(T){this._selectWordAtCursor(T,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(T){const j=this._getMouseBufferCoords(T);j&&(this._activeSelectionMode=2,this._selectLineAt(j[1]))}shouldColumnSelect(T){return T.altKey&&!(b.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(T){if(T.stopImmediatePropagation(),!this._model.selectionStart)return;const j=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(T),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(T),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const H=this._bufferService.buffer;if(this._model.selectionEnd[1]<H.lines.length){const I=H.lines.get(this._model.selectionEnd[1]);I&&I.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]++}j&&j[0]===this._model.selectionEnd[0]&&j[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const T=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(T.ydisp+this._bufferService.rows,T.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=T.ydisp),this.refresh()}}_handleMouseUp(T){const j=T.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&j<500&&T.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const H=this._mouseService.getCoords(T,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(H&&H[0]!==void 0&&H[1]!==void 0){const I=(0,y.moveToCellSequence)(H[0]-1,H[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(I,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const T=this._model.finalSelectionStart,j=this._model.finalSelectionEnd,H=!(!T||!j||T[0]===j[0]&&T[1]===j[1]);H?T&&j&&(this._oldSelectionStart&&this._oldSelectionEnd&&T[0]===this._oldSelectionStart[0]&&T[1]===this._oldSelectionStart[1]&&j[0]===this._oldSelectionEnd[0]&&j[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(T,j,H)):this._oldHasSelection&&this._fireOnSelectionChange(T,j,H)}_fireOnSelectionChange(T,j,H){this._oldSelectionStart=T,this._oldSelectionEnd=j,this._oldHasSelection=H,this._onSelectionChange.fire()}_handleBufferActivate(T){this.clearSelection(),this._trimListener.dispose(),this._trimListener=T.activeBuffer.lines.onTrim((j=>this._handleTrim(j)))}_convertViewportColToCharacterIndex(T,j){let H=j;for(let I=0;j>=I;I++){const z=T.loadCell(I,this._workCell).getChars().length;this._workCell.getWidth()===0?H--:z>1&&j!==I&&(H+=z-1)}return H}setSelection(T,j,H){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[T,j],this._model.selectionStartLength=H,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(T){this._isClickInSelection(T)||(this._selectWordAtCursor(T,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(T,j,H=!0,I=!0){if(T[0]>=this._bufferService.cols)return;const z=this._bufferService.buffer,U=z.lines.get(T[1]);if(!U)return;const X=z.translateBufferLineToString(T[1],!1);let q=this._convertViewportColToCharacterIndex(U,T[0]),F=q;const Y=T[0]-q;let L=0,V=0,$=0,B=0;if(X.charAt(q)===" "){for(;q>0&&X.charAt(q-1)===" ";)q--;for(;F<X.length&&X.charAt(F+1)===" ";)F++}else{let Z=T[0],Q=T[0];U.getWidth(Z)===0&&(L++,Z--),U.getWidth(Q)===2&&(V++,Q++);const ce=U.getString(Q).length;for(ce>1&&(B+=ce-1,F+=ce-1);Z>0&&q>0&&!this._isCharWordSeparator(U.loadCell(Z-1,this._workCell));){U.loadCell(Z-1,this._workCell);const P=this._workCell.getChars().length;this._workCell.getWidth()===0?(L++,Z--):P>1&&($+=P-1,q-=P-1),q--,Z--}for(;Q<U.length&&F+1<X.length&&!this._isCharWordSeparator(U.loadCell(Q+1,this._workCell));){U.loadCell(Q+1,this._workCell);const P=this._workCell.getChars().length;this._workCell.getWidth()===2?(V++,Q++):P>1&&(B+=P-1,F+=P-1),F++,Q++}}F++;let W=q+Y-L+$,ee=Math.min(this._bufferService.cols,F-q+L+V-$-B);if(j||X.slice(q,F).trim()!==""){if(H&&W===0&&U.getCodePoint(0)!==32){const Z=z.lines.get(T[1]-1);if(Z&&U.isWrapped&&Z.getCodePoint(this._bufferService.cols-1)!==32){const Q=this._getWordAt([this._bufferService.cols-1,T[1]-1],!1,!0,!1);if(Q){const ce=this._bufferService.cols-Q.start;W-=ce,ee+=ce}}}if(I&&W+ee===this._bufferService.cols&&U.getCodePoint(this._bufferService.cols-1)!==32){const Z=z.lines.get(T[1]+1);if(Z?.isWrapped&&Z.getCodePoint(0)!==32){const Q=this._getWordAt([0,T[1]+1],!1,!1,!0);Q&&(ee+=Q.length)}}return{start:W,length:ee}}}_selectWordAt(T,j){const H=this._getWordAt(T,j);if(H){for(;H.start<0;)H.start+=this._bufferService.cols,T[1]--;this._model.selectionStart=[H.start,T[1]],this._model.selectionStartLength=H.length}}_selectToWordAt(T){const j=this._getWordAt(T,!0);if(j){let H=T[1];for(;j.start<0;)j.start+=this._bufferService.cols,H--;if(!this._model.areSelectionValuesReversed())for(;j.start+j.length>this._bufferService.cols;)j.length-=this._bufferService.cols,H++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?j.start:j.start+j.length,H]}}_isCharWordSeparator(T){return T.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(T.getChars())>=0}_selectLineAt(T){const j=this._bufferService.buffer.getWrappedRangeForLine(T),H={start:{x:0,y:j.first},end:{x:this._bufferService.cols-1,y:j.last}};this._model.selectionStart=[0,j.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,_.getRangeLength)(H,this._bufferService.cols)}};a.SelectionService=O=f([v(3,A.IBufferService),v(4,A.ICoreService),v(5,R.IMouseService),v(6,A.IOptionsService),v(7,R.IRenderService),v(8,R.ICoreBrowserService)],O)},4725:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.IThemeService=a.ICharacterJoinerService=a.ISelectionService=a.IRenderService=a.IMouseService=a.ICoreBrowserService=a.ICharSizeService=void 0;const f=c(8343);a.ICharSizeService=(0,f.createDecorator)("CharSizeService"),a.ICoreBrowserService=(0,f.createDecorator)("CoreBrowserService"),a.IMouseService=(0,f.createDecorator)("MouseService"),a.IRenderService=(0,f.createDecorator)("RenderService"),a.ISelectionService=(0,f.createDecorator)("SelectionService"),a.ICharacterJoinerService=(0,f.createDecorator)("CharacterJoinerService"),a.IThemeService=(0,f.createDecorator)("ThemeService")},6731:function(p,a,c){var f=this&&this.__decorate||function(O,T,j,H){var I,z=arguments.length,U=z<3?T:H===null?H=Object.getOwnPropertyDescriptor(T,j):H;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")U=Reflect.decorate(O,T,j,H);else for(var X=O.length-1;X>=0;X--)(I=O[X])&&(U=(z<3?I(U):z>3?I(T,j,U):I(T,j))||U);return z>3&&U&&Object.defineProperty(T,j,U),U},v=this&&this.__param||function(O,T){return function(j,H){T(j,H,O)}};Object.defineProperty(a,"__esModule",{value:!0}),a.ThemeService=a.DEFAULT_ANSI_COLORS=void 0;const m=c(7239),y=c(8055),C=c(8460),R=c(844),E=c(2585),g=y.css.toColor("#ffffff"),b=y.css.toColor("#000000"),_=y.css.toColor("#ffffff"),x=y.css.toColor("#000000"),A={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};a.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const O=[y.css.toColor("#2e3436"),y.css.toColor("#cc0000"),y.css.toColor("#4e9a06"),y.css.toColor("#c4a000"),y.css.toColor("#3465a4"),y.css.toColor("#75507b"),y.css.toColor("#06989a"),y.css.toColor("#d3d7cf"),y.css.toColor("#555753"),y.css.toColor("#ef2929"),y.css.toColor("#8ae234"),y.css.toColor("#fce94f"),y.css.toColor("#729fcf"),y.css.toColor("#ad7fa8"),y.css.toColor("#34e2e2"),y.css.toColor("#eeeeec")],T=[0,95,135,175,215,255];for(let j=0;j<216;j++){const H=T[j/36%6|0],I=T[j/6%6|0],z=T[j%6];O.push({css:y.channels.toCss(H,I,z),rgba:y.channels.toRgba(H,I,z)})}for(let j=0;j<24;j++){const H=8+10*j;O.push({css:y.channels.toCss(H,H,H),rgba:y.channels.toRgba(H,H,H)})}return O})());let D=a.ThemeService=class extends R.Disposable{get colors(){return this._colors}constructor(O){super(),this._optionsService=O,this._contrastCache=new m.ColorContrastCache,this._halfContrastCache=new m.ColorContrastCache,this._onChangeColors=this.register(new C.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:g,background:b,cursor:_,cursorAccent:x,selectionForeground:void 0,selectionBackgroundTransparent:A,selectionBackgroundOpaque:y.color.blend(b,A),selectionInactiveBackgroundTransparent:A,selectionInactiveBackgroundOpaque:y.color.blend(b,A),ansi:a.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(O={}){const T=this._colors;if(T.foreground=N(O.foreground,g),T.background=N(O.background,b),T.cursor=N(O.cursor,_),T.cursorAccent=N(O.cursorAccent,x),T.selectionBackgroundTransparent=N(O.selectionBackground,A),T.selectionBackgroundOpaque=y.color.blend(T.background,T.selectionBackgroundTransparent),T.selectionInactiveBackgroundTransparent=N(O.selectionInactiveBackground,T.selectionBackgroundTransparent),T.selectionInactiveBackgroundOpaque=y.color.blend(T.background,T.selectionInactiveBackgroundTransparent),T.selectionForeground=O.selectionForeground?N(O.selectionForeground,y.NULL_COLOR):void 0,T.selectionForeground===y.NULL_COLOR&&(T.selectionForeground=void 0),y.color.isOpaque(T.selectionBackgroundTransparent)&&(T.selectionBackgroundTransparent=y.color.opacity(T.selectionBackgroundTransparent,.3)),y.color.isOpaque(T.selectionInactiveBackgroundTransparent)&&(T.selectionInactiveBackgroundTransparent=y.color.opacity(T.selectionInactiveBackgroundTransparent,.3)),T.ansi=a.DEFAULT_ANSI_COLORS.slice(),T.ansi[0]=N(O.black,a.DEFAULT_ANSI_COLORS[0]),T.ansi[1]=N(O.red,a.DEFAULT_ANSI_COLORS[1]),T.ansi[2]=N(O.green,a.DEFAULT_ANSI_COLORS[2]),T.ansi[3]=N(O.yellow,a.DEFAULT_ANSI_COLORS[3]),T.ansi[4]=N(O.blue,a.DEFAULT_ANSI_COLORS[4]),T.ansi[5]=N(O.magenta,a.DEFAULT_ANSI_COLORS[5]),T.ansi[6]=N(O.cyan,a.DEFAULT_ANSI_COLORS[6]),T.ansi[7]=N(O.white,a.DEFAULT_ANSI_COLORS[7]),T.ansi[8]=N(O.brightBlack,a.DEFAULT_ANSI_COLORS[8]),T.ansi[9]=N(O.brightRed,a.DEFAULT_ANSI_COLORS[9]),T.ansi[10]=N(O.brightGreen,a.DEFAULT_ANSI_COLORS[10]),T.ansi[11]=N(O.brightYellow,a.DEFAULT_ANSI_COLORS[11]),T.ansi[12]=N(O.brightBlue,a.DEFAULT_ANSI_COLORS[12]),T.ansi[13]=N(O.brightMagenta,a.DEFAULT_ANSI_COLORS[13]),T.ansi[14]=N(O.brightCyan,a.DEFAULT_ANSI_COLORS[14]),T.ansi[15]=N(O.brightWhite,a.DEFAULT_ANSI_COLORS[15]),O.extendedAnsi){const j=Math.min(T.ansi.length-16,O.extendedAnsi.length);for(let H=0;H<j;H++)T.ansi[H+16]=N(O.extendedAnsi[H],a.DEFAULT_ANSI_COLORS[H+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(O){this._restoreColor(O),this._onChangeColors.fire(this.colors)}_restoreColor(O){if(O!==void 0)switch(O){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[O]=this._restoreColors.ansi[O]}else for(let T=0;T<this._restoreColors.ansi.length;++T)this._colors.ansi[T]=this._restoreColors.ansi[T]}modifyColors(O){O(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function N(O,T){if(O!==void 0)try{return y.css.toColor(O)}catch{}return T}a.ThemeService=D=f([v(0,E.IOptionsService)],D)},6349:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CircularList=void 0;const f=c(8460),v=c(844);class m extends v.Disposable{constructor(C){super(),this._maxLength=C,this.onDeleteEmitter=this.register(new f.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new f.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new f.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(C){if(this._maxLength===C)return;const R=new Array(C);for(let E=0;E<Math.min(C,this.length);E++)R[E]=this._array[this._getCyclicIndex(E)];this._array=R,this._maxLength=C,this._startIndex=0}get length(){return this._length}set length(C){if(C>this._length)for(let R=this._length;R<C;R++)this._array[R]=void 0;this._length=C}get(C){return this._array[this._getCyclicIndex(C)]}set(C,R){this._array[this._getCyclicIndex(C)]=R}push(C){this._array[this._getCyclicIndex(this._length)]=C,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(C,R,...E){if(R){for(let g=C;g<this._length-R;g++)this._array[this._getCyclicIndex(g)]=this._array[this._getCyclicIndex(g+R)];this._length-=R,this.onDeleteEmitter.fire({index:C,amount:R})}for(let g=this._length-1;g>=C;g--)this._array[this._getCyclicIndex(g+E.length)]=this._array[this._getCyclicIndex(g)];for(let g=0;g<E.length;g++)this._array[this._getCyclicIndex(C+g)]=E[g];if(E.length&&this.onInsertEmitter.fire({index:C,amount:E.length}),this._length+E.length>this._maxLength){const g=this._length+E.length-this._maxLength;this._startIndex+=g,this._length=this._maxLength,this.onTrimEmitter.fire(g)}else this._length+=E.length}trimStart(C){C>this._length&&(C=this._length),this._startIndex+=C,this._length-=C,this.onTrimEmitter.fire(C)}shiftElements(C,R,E){if(!(R<=0)){if(C<0||C>=this._length)throw new Error("start argument out of range");if(C+E<0)throw new Error("Cannot shift elements in list beyond index 0");if(E>0){for(let b=R-1;b>=0;b--)this.set(C+b+E,this.get(C+b));const g=C+R+E-this._length;if(g>0)for(this._length+=g;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let g=0;g<R;g++)this.set(C+g+E,this.get(C+g))}}_getCyclicIndex(C){return(this._startIndex+C)%this._maxLength}}a.CircularList=m},1439:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.clone=void 0,a.clone=function c(f,v=5){if(typeof f!="object")return f;const m=Array.isArray(f)?[]:{};for(const y in f)m[y]=v<=1?f[y]:f[y]&&c(f[y],v-1);return m}},8055:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.contrastRatio=a.toPaddedHex=a.rgba=a.rgb=a.css=a.color=a.channels=a.NULL_COLOR=void 0;const f=c(6114);let v=0,m=0,y=0,C=0;var R,E,g,b,_;function x(D){const N=D.toString(16);return N.length<2?"0"+N:N}function A(D,N){return D<N?(N+.05)/(D+.05):(D+.05)/(N+.05)}a.NULL_COLOR={css:"#00000000",rgba:0},(function(D){D.toCss=function(N,O,T,j){return j!==void 0?`#${x(N)}${x(O)}${x(T)}${x(j)}`:`#${x(N)}${x(O)}${x(T)}`},D.toRgba=function(N,O,T,j=255){return(N<<24|O<<16|T<<8|j)>>>0}})(R||(a.channels=R={})),(function(D){function N(O,T){return C=Math.round(255*T),[v,m,y]=_.toChannels(O.rgba),{css:R.toCss(v,m,y,C),rgba:R.toRgba(v,m,y,C)}}D.blend=function(O,T){if(C=(255&T.rgba)/255,C===1)return{css:T.css,rgba:T.rgba};const j=T.rgba>>24&255,H=T.rgba>>16&255,I=T.rgba>>8&255,z=O.rgba>>24&255,U=O.rgba>>16&255,X=O.rgba>>8&255;return v=z+Math.round((j-z)*C),m=U+Math.round((H-U)*C),y=X+Math.round((I-X)*C),{css:R.toCss(v,m,y),rgba:R.toRgba(v,m,y)}},D.isOpaque=function(O){return(255&O.rgba)==255},D.ensureContrastRatio=function(O,T,j){const H=_.ensureContrastRatio(O.rgba,T.rgba,j);if(H)return _.toColor(H>>24&255,H>>16&255,H>>8&255)},D.opaque=function(O){const T=(255|O.rgba)>>>0;return[v,m,y]=_.toChannels(T),{css:R.toCss(v,m,y),rgba:T}},D.opacity=N,D.multiplyOpacity=function(O,T){return C=255&O.rgba,N(O,C*T/255)},D.toColorRGB=function(O){return[O.rgba>>24&255,O.rgba>>16&255,O.rgba>>8&255]}})(E||(a.color=E={})),(function(D){let N,O;if(!f.isNode){const T=document.createElement("canvas");T.width=1,T.height=1;const j=T.getContext("2d",{willReadFrequently:!0});j&&(N=j,N.globalCompositeOperation="copy",O=N.createLinearGradient(0,0,1,1))}D.toColor=function(T){if(T.match(/#[\da-f]{3,8}/i))switch(T.length){case 4:return v=parseInt(T.slice(1,2).repeat(2),16),m=parseInt(T.slice(2,3).repeat(2),16),y=parseInt(T.slice(3,4).repeat(2),16),_.toColor(v,m,y);case 5:return v=parseInt(T.slice(1,2).repeat(2),16),m=parseInt(T.slice(2,3).repeat(2),16),y=parseInt(T.slice(3,4).repeat(2),16),C=parseInt(T.slice(4,5).repeat(2),16),_.toColor(v,m,y,C);case 7:return{css:T,rgba:(parseInt(T.slice(1),16)<<8|255)>>>0};case 9:return{css:T,rgba:parseInt(T.slice(1),16)>>>0}}const j=T.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(j)return v=parseInt(j[1]),m=parseInt(j[2]),y=parseInt(j[3]),C=Math.round(255*(j[5]===void 0?1:parseFloat(j[5]))),_.toColor(v,m,y,C);if(!N||!O)throw new Error("css.toColor: Unsupported css format");if(N.fillStyle=O,N.fillStyle=T,typeof N.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(N.fillRect(0,0,1,1),[v,m,y,C]=N.getImageData(0,0,1,1).data,C!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:R.toRgba(v,m,y,C),css:T}}})(g||(a.css=g={})),(function(D){function N(O,T,j){const H=O/255,I=T/255,z=j/255;return .2126*(H<=.03928?H/12.92:Math.pow((H+.055)/1.055,2.4))+.7152*(I<=.03928?I/12.92:Math.pow((I+.055)/1.055,2.4))+.0722*(z<=.03928?z/12.92:Math.pow((z+.055)/1.055,2.4))}D.relativeLuminance=function(O){return N(O>>16&255,O>>8&255,255&O)},D.relativeLuminance2=N})(b||(a.rgb=b={})),(function(D){function N(T,j,H){const I=T>>24&255,z=T>>16&255,U=T>>8&255;let X=j>>24&255,q=j>>16&255,F=j>>8&255,Y=A(b.relativeLuminance2(X,q,F),b.relativeLuminance2(I,z,U));for(;Y<H&&(X>0||q>0||F>0);)X-=Math.max(0,Math.ceil(.1*X)),q-=Math.max(0,Math.ceil(.1*q)),F-=Math.max(0,Math.ceil(.1*F)),Y=A(b.relativeLuminance2(X,q,F),b.relativeLuminance2(I,z,U));return(X<<24|q<<16|F<<8|255)>>>0}function O(T,j,H){const I=T>>24&255,z=T>>16&255,U=T>>8&255;let X=j>>24&255,q=j>>16&255,F=j>>8&255,Y=A(b.relativeLuminance2(X,q,F),b.relativeLuminance2(I,z,U));for(;Y<H&&(X<255||q<255||F<255);)X=Math.min(255,X+Math.ceil(.1*(255-X))),q=Math.min(255,q+Math.ceil(.1*(255-q))),F=Math.min(255,F+Math.ceil(.1*(255-F))),Y=A(b.relativeLuminance2(X,q,F),b.relativeLuminance2(I,z,U));return(X<<24|q<<16|F<<8|255)>>>0}D.ensureContrastRatio=function(T,j,H){const I=b.relativeLuminance(T>>8),z=b.relativeLuminance(j>>8);if(A(I,z)<H){if(z<I){const q=N(T,j,H),F=A(I,b.relativeLuminance(q>>8));if(F<H){const Y=O(T,j,H);return F>A(I,b.relativeLuminance(Y>>8))?q:Y}return q}const U=O(T,j,H),X=A(I,b.relativeLuminance(U>>8));if(X<H){const q=N(T,j,H);return X>A(I,b.relativeLuminance(q>>8))?U:q}return U}},D.reduceLuminance=N,D.increaseLuminance=O,D.toChannels=function(T){return[T>>24&255,T>>16&255,T>>8&255,255&T]},D.toColor=function(T,j,H,I){return{css:R.toCss(T,j,H,I),rgba:R.toRgba(T,j,H,I)}}})(_||(a.rgba=_={})),a.toPaddedHex=x,a.contrastRatio=A},8969:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CoreTerminal=void 0;const f=c(844),v=c(2585),m=c(4348),y=c(7866),C=c(744),R=c(7302),E=c(6975),g=c(8460),b=c(1753),_=c(1480),x=c(7994),A=c(9282),D=c(5435),N=c(5981),O=c(2660);let T=!1;class j extends f.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new g.EventEmitter),this._onScroll.event((I=>{var z;(z=this._onScrollApi)===null||z===void 0||z.fire(I.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(I){for(const z in I)this.optionsService.options[z]=I[z]}constructor(I){super(),this._windowsWrappingHeuristics=this.register(new f.MutableDisposable),this._onBinary=this.register(new g.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new g.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new g.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new g.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new g.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new g.EventEmitter),this._instantiationService=new m.InstantiationService,this.optionsService=this.register(new R.OptionsService(I)),this._instantiationService.setService(v.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(C.BufferService)),this._instantiationService.setService(v.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(y.LogService)),this._instantiationService.setService(v.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(E.CoreService)),this._instantiationService.setService(v.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(b.CoreMouseService)),this._instantiationService.setService(v.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(_.UnicodeService)),this._instantiationService.setService(v.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(x.CharsetService),this._instantiationService.setService(v.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(O.OscLinkService),this._instantiationService.setService(v.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new D.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,g.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,g.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,g.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,g.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((z=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((z=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new N.WriteBuffer(((z,U)=>this._inputHandler.parse(z,U)))),this.register((0,g.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(I,z){this._writeBuffer.write(I,z)}writeSync(I,z){this._logService.logLevel<=v.LogLevelEnum.WARN&&!T&&(this._logService.warn("writeSync is unreliable and will be removed soon."),T=!0),this._writeBuffer.writeSync(I,z)}resize(I,z){isNaN(I)||isNaN(z)||(I=Math.max(I,C.MINIMUM_COLS),z=Math.max(z,C.MINIMUM_ROWS),this._bufferService.resize(I,z))}scroll(I,z=!1){this._bufferService.scroll(I,z)}scrollLines(I,z,U){this._bufferService.scrollLines(I,z,U)}scrollPages(I){this.scrollLines(I*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(I){const z=I-this._bufferService.buffer.ydisp;z!==0&&this.scrollLines(z)}registerEscHandler(I,z){return this._inputHandler.registerEscHandler(I,z)}registerDcsHandler(I,z){return this._inputHandler.registerDcsHandler(I,z)}registerCsiHandler(I,z){return this._inputHandler.registerCsiHandler(I,z)}registerOscHandler(I,z){return this._inputHandler.registerOscHandler(I,z)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let I=!1;const z=this.optionsService.rawOptions.windowsPty;z&&z.buildNumber!==void 0&&z.buildNumber!==void 0?I=z.backend==="conpty"&&z.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(I=!0),I?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const I=[];I.push(this.onLineFeed(A.updateWindowsModeWrappedState.bind(null,this._bufferService))),I.push(this.registerCsiHandler({final:"H"},(()=>((0,A.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,f.toDisposable)((()=>{for(const z of I)z.dispose()}))}}}a.CoreTerminal=j},8460:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.forwardEvent=a.EventEmitter=void 0,a.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=c=>(this._listeners.push(c),{dispose:()=>{if(!this._disposed){for(let f=0;f<this._listeners.length;f++)if(this._listeners[f]===c)return void this._listeners.splice(f,1)}}})),this._event}fire(c,f){const v=[];for(let m=0;m<this._listeners.length;m++)v.push(this._listeners[m]);for(let m=0;m<v.length;m++)v[m].call(void 0,c,f)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},a.forwardEvent=function(c,f){return c((v=>f.fire(v)))}},5435:function(p,a,c){var f=this&&this.__decorate||function(Y,L,V,$){var B,W=arguments.length,ee=W<3?L:$===null?$=Object.getOwnPropertyDescriptor(L,V):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")ee=Reflect.decorate(Y,L,V,$);else for(var Z=Y.length-1;Z>=0;Z--)(B=Y[Z])&&(ee=(W<3?B(ee):W>3?B(L,V,ee):B(L,V))||ee);return W>3&&ee&&Object.defineProperty(L,V,ee),ee},v=this&&this.__param||function(Y,L){return function(V,$){L(V,$,Y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.InputHandler=a.WindowsOptionsReportType=void 0;const m=c(2584),y=c(7116),C=c(2015),R=c(844),E=c(482),g=c(8437),b=c(8460),_=c(643),x=c(511),A=c(3734),D=c(2585),N=c(6242),O=c(6351),T=c(5941),j={"(":0,")":1,"*":2,"+":3,"-":1,".":2},H=131072;function I(Y,L){if(Y>24)return L.setWinLines||!1;switch(Y){case 1:return!!L.restoreWin;case 2:return!!L.minimizeWin;case 3:return!!L.setWinPosition;case 4:return!!L.setWinSizePixels;case 5:return!!L.raiseWin;case 6:return!!L.lowerWin;case 7:return!!L.refreshWin;case 8:return!!L.setWinSizeChars;case 9:return!!L.maximizeWin;case 10:return!!L.fullscreenWin;case 11:return!!L.getWinState;case 13:return!!L.getWinPosition;case 14:return!!L.getWinSizePixels;case 15:return!!L.getScreenSizePixels;case 16:return!!L.getCellSizePixels;case 18:return!!L.getWinSizeChars;case 19:return!!L.getScreenSizeChars;case 20:return!!L.getIconTitle;case 21:return!!L.getWinTitle;case 22:return!!L.pushTitle;case 23:return!!L.popTitle;case 24:return!!L.setWinLines}return!1}var z;(function(Y){Y[Y.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",Y[Y.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(z||(a.WindowsOptionsReportType=z={}));let U=0;class X extends R.Disposable{getAttrData(){return this._curAttrData}constructor(L,V,$,B,W,ee,Z,Q,ce=new C.EscapeSequenceParser){super(),this._bufferService=L,this._charsetService=V,this._coreService=$,this._logService=B,this._optionsService=W,this._oscLinkService=ee,this._coreMouseService=Z,this._unicodeService=Q,this._parser=ce,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new E.StringToUtf32,this._utf8Decoder=new E.Utf8ToUtf32,this._workCell=new x.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new b.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new b.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new b.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new b.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new b.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new b.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new b.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new b.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new b.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new b.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new b.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new b.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new b.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new q(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((P=>this._activeBuffer=P.activeBuffer))),this._parser.setCsiHandlerFallback(((P,K)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(P),params:K.toArray()})})),this._parser.setEscHandlerFallback((P=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(P)})})),this._parser.setExecuteHandlerFallback((P=>{this._logService.debug("Unknown EXECUTE code: ",{code:P})})),this._parser.setOscHandlerFallback(((P,K,ie)=>{this._logService.debug("Unknown OSC code: ",{identifier:P,action:K,data:ie})})),this._parser.setDcsHandlerFallback(((P,K,ie)=>{K==="HOOK"&&(ie=ie.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(P),action:K,payload:ie})})),this._parser.setPrintHandler(((P,K,ie)=>this.print(P,K,ie))),this._parser.registerCsiHandler({final:"@"},(P=>this.insertChars(P))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(P=>this.scrollLeft(P))),this._parser.registerCsiHandler({final:"A"},(P=>this.cursorUp(P))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(P=>this.scrollRight(P))),this._parser.registerCsiHandler({final:"B"},(P=>this.cursorDown(P))),this._parser.registerCsiHandler({final:"C"},(P=>this.cursorForward(P))),this._parser.registerCsiHandler({final:"D"},(P=>this.cursorBackward(P))),this._parser.registerCsiHandler({final:"E"},(P=>this.cursorNextLine(P))),this._parser.registerCsiHandler({final:"F"},(P=>this.cursorPrecedingLine(P))),this._parser.registerCsiHandler({final:"G"},(P=>this.cursorCharAbsolute(P))),this._parser.registerCsiHandler({final:"H"},(P=>this.cursorPosition(P))),this._parser.registerCsiHandler({final:"I"},(P=>this.cursorForwardTab(P))),this._parser.registerCsiHandler({final:"J"},(P=>this.eraseInDisplay(P,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(P=>this.eraseInDisplay(P,!0))),this._parser.registerCsiHandler({final:"K"},(P=>this.eraseInLine(P,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(P=>this.eraseInLine(P,!0))),this._parser.registerCsiHandler({final:"L"},(P=>this.insertLines(P))),this._parser.registerCsiHandler({final:"M"},(P=>this.deleteLines(P))),this._parser.registerCsiHandler({final:"P"},(P=>this.deleteChars(P))),this._parser.registerCsiHandler({final:"S"},(P=>this.scrollUp(P))),this._parser.registerCsiHandler({final:"T"},(P=>this.scrollDown(P))),this._parser.registerCsiHandler({final:"X"},(P=>this.eraseChars(P))),this._parser.registerCsiHandler({final:"Z"},(P=>this.cursorBackwardTab(P))),this._parser.registerCsiHandler({final:"`"},(P=>this.charPosAbsolute(P))),this._parser.registerCsiHandler({final:"a"},(P=>this.hPositionRelative(P))),this._parser.registerCsiHandler({final:"b"},(P=>this.repeatPrecedingCharacter(P))),this._parser.registerCsiHandler({final:"c"},(P=>this.sendDeviceAttributesPrimary(P))),this._parser.registerCsiHandler({prefix:">",final:"c"},(P=>this.sendDeviceAttributesSecondary(P))),this._parser.registerCsiHandler({final:"d"},(P=>this.linePosAbsolute(P))),this._parser.registerCsiHandler({final:"e"},(P=>this.vPositionRelative(P))),this._parser.registerCsiHandler({final:"f"},(P=>this.hVPosition(P))),this._parser.registerCsiHandler({final:"g"},(P=>this.tabClear(P))),this._parser.registerCsiHandler({final:"h"},(P=>this.setMode(P))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(P=>this.setModePrivate(P))),this._parser.registerCsiHandler({final:"l"},(P=>this.resetMode(P))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(P=>this.resetModePrivate(P))),this._parser.registerCsiHandler({final:"m"},(P=>this.charAttributes(P))),this._parser.registerCsiHandler({final:"n"},(P=>this.deviceStatus(P))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(P=>this.deviceStatusPrivate(P))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(P=>this.softReset(P))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(P=>this.setCursorStyle(P))),this._parser.registerCsiHandler({final:"r"},(P=>this.setScrollRegion(P))),this._parser.registerCsiHandler({final:"s"},(P=>this.saveCursor(P))),this._parser.registerCsiHandler({final:"t"},(P=>this.windowOptions(P))),this._parser.registerCsiHandler({final:"u"},(P=>this.restoreCursor(P))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(P=>this.insertColumns(P))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(P=>this.deleteColumns(P))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(P=>this.selectProtected(P))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(P=>this.requestMode(P,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(P=>this.requestMode(P,!1))),this._parser.setExecuteHandler(m.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(m.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(m.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(m.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(m.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(m.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(m.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(m.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(m.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(m.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(m.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(m.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new N.OscHandler((P=>(this.setTitle(P),this.setIconName(P),!0)))),this._parser.registerOscHandler(1,new N.OscHandler((P=>this.setIconName(P)))),this._parser.registerOscHandler(2,new N.OscHandler((P=>this.setTitle(P)))),this._parser.registerOscHandler(4,new N.OscHandler((P=>this.setOrReportIndexedColor(P)))),this._parser.registerOscHandler(8,new N.OscHandler((P=>this.setHyperlink(P)))),this._parser.registerOscHandler(10,new N.OscHandler((P=>this.setOrReportFgColor(P)))),this._parser.registerOscHandler(11,new N.OscHandler((P=>this.setOrReportBgColor(P)))),this._parser.registerOscHandler(12,new N.OscHandler((P=>this.setOrReportCursorColor(P)))),this._parser.registerOscHandler(104,new N.OscHandler((P=>this.restoreIndexedColor(P)))),this._parser.registerOscHandler(110,new N.OscHandler((P=>this.restoreFgColor(P)))),this._parser.registerOscHandler(111,new N.OscHandler((P=>this.restoreBgColor(P)))),this._parser.registerOscHandler(112,new N.OscHandler((P=>this.restoreCursorColor(P)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const P in y.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:P},(()=>this.selectCharset("("+P))),this._parser.registerEscHandler({intermediates:")",final:P},(()=>this.selectCharset(")"+P))),this._parser.registerEscHandler({intermediates:"*",final:P},(()=>this.selectCharset("*"+P))),this._parser.registerEscHandler({intermediates:"+",final:P},(()=>this.selectCharset("+"+P))),this._parser.registerEscHandler({intermediates:"-",final:P},(()=>this.selectCharset("-"+P))),this._parser.registerEscHandler({intermediates:".",final:P},(()=>this.selectCharset("."+P))),this._parser.registerEscHandler({intermediates:"/",final:P},(()=>this.selectCharset("/"+P)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((P=>(this._logService.error("Parsing error: ",P),P))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new O.DcsHandler(((P,K)=>this.requestStatusString(P,K))))}_preserveStack(L,V,$,B){this._parseStack.paused=!0,this._parseStack.cursorStartX=L,this._parseStack.cursorStartY=V,this._parseStack.decodedLength=$,this._parseStack.position=B}_logSlowResolvingAsync(L){this._logService.logLevel<=D.LogLevelEnum.WARN&&Promise.race([L,new Promise(((V,$)=>setTimeout((()=>$("#SLOW_TIMEOUT")),5e3)))]).catch((V=>{if(V!=="#SLOW_TIMEOUT")throw V;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(L,V){let $,B=this._activeBuffer.x,W=this._activeBuffer.y,ee=0;const Z=this._parseStack.paused;if(Z){if($=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,V))return this._logSlowResolvingAsync($),$;B=this._parseStack.cursorStartX,W=this._parseStack.cursorStartY,this._parseStack.paused=!1,L.length>H&&(ee=this._parseStack.position+H)}if(this._logService.logLevel<=D.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof L=="string"?` "${L}"`:` "${Array.prototype.map.call(L,(Q=>String.fromCharCode(Q))).join("")}"`),typeof L=="string"?L.split("").map((Q=>Q.charCodeAt(0))):L),this._parseBuffer.length<L.length&&this._parseBuffer.length<H&&(this._parseBuffer=new Uint32Array(Math.min(L.length,H))),Z||this._dirtyRowTracker.clearRange(),L.length>H)for(let Q=ee;Q<L.length;Q+=H){const ce=Q+H<L.length?Q+H:L.length,P=typeof L=="string"?this._stringDecoder.decode(L.substring(Q,ce),this._parseBuffer):this._utf8Decoder.decode(L.subarray(Q,ce),this._parseBuffer);if($=this._parser.parse(this._parseBuffer,P))return this._preserveStack(B,W,P,Q),this._logSlowResolvingAsync($),$}else if(!Z){const Q=typeof L=="string"?this._stringDecoder.decode(L,this._parseBuffer):this._utf8Decoder.decode(L,this._parseBuffer);if($=this._parser.parse(this._parseBuffer,Q))return this._preserveStack(B,W,Q,0),this._logSlowResolvingAsync($),$}this._activeBuffer.x===B&&this._activeBuffer.y===W||this._onCursorMove.fire(),this._onRequestRefreshRows.fire(this._dirtyRowTracker.start,this._dirtyRowTracker.end)}print(L,V,$){let B,W;const ee=this._charsetService.charset,Z=this._optionsService.rawOptions.screenReaderMode,Q=this._bufferService.cols,ce=this._coreService.decPrivateModes.wraparound,P=this._coreService.modes.insertMode,K=this._curAttrData;let ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&$-V>0&&ie.getWidth(this._activeBuffer.x-1)===2&&ie.setCellFromCodePoint(this._activeBuffer.x-1,0,1,K.fg,K.bg,K.extended);for(let se=V;se<$;++se){if(B=L[se],W=this._unicodeService.wcwidth(B),B<127&&ee){const me=ee[String.fromCharCode(B)];me&&(B=me.charCodeAt(0))}if(Z&&this._onA11yChar.fire((0,E.stringFromCodePoint)(B)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),W||!this._activeBuffer.x){if(this._activeBuffer.x+W-1>=Q){if(ce){for(;this._activeBuffer.x<Q;)ie.setCellFromCodePoint(this._activeBuffer.x++,0,1,K.fg,K.bg,K.extended);this._activeBuffer.x=0,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)}else if(this._activeBuffer.x=Q-1,W===2)continue}if(P&&(ie.insertCells(this._activeBuffer.x,W,this._activeBuffer.getNullCell(K),K),ie.getWidth(Q-1)===2&&ie.setCellFromCodePoint(Q-1,_.NULL_CELL_CODE,_.NULL_CELL_WIDTH,K.fg,K.bg,K.extended)),ie.setCellFromCodePoint(this._activeBuffer.x++,B,W,K.fg,K.bg,K.extended),W>0)for(;--W;)ie.setCellFromCodePoint(this._activeBuffer.x++,0,0,K.fg,K.bg,K.extended)}else ie.getWidth(this._activeBuffer.x-1)?ie.addCodepointToCell(this._activeBuffer.x-1,B):ie.addCodepointToCell(this._activeBuffer.x-2,B)}$-V>0&&(ie.loadCell(this._activeBuffer.x-1,this._workCell),this._workCell.getWidth()===2||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),this._activeBuffer.x<Q&&$-V>0&&ie.getWidth(this._activeBuffer.x)===0&&!ie.hasContent(this._activeBuffer.x)&&ie.setCellFromCodePoint(this._activeBuffer.x,0,1,K.fg,K.bg,K.extended),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(L,V){return L.final!=="t"||L.prefix||L.intermediates?this._parser.registerCsiHandler(L,V):this._parser.registerCsiHandler(L,($=>!I($.params[0],this._optionsService.rawOptions.windowOptions)||V($)))}registerDcsHandler(L,V){return this._parser.registerDcsHandler(L,new O.DcsHandler(V))}registerEscHandler(L,V){return this._parser.registerEscHandler(L,V)}registerOscHandler(L,V){return this._parser.registerOscHandler(L,new N.OscHandler(V))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var L;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&(!((L=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))===null||L===void 0)&&L.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);V.hasWidth(this._activeBuffer.x)&&!V.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const L=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-L),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(L=this._bufferService.cols-1){this._activeBuffer.x=Math.min(L,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(L,V){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=L,this._activeBuffer.y=this._activeBuffer.scrollTop+V):(this._activeBuffer.x=L,this._activeBuffer.y=V),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(L,V){this._restrictCursor(),this._setCursor(this._activeBuffer.x+L,this._activeBuffer.y+V)}cursorUp(L){const V=this._activeBuffer.y-this._activeBuffer.scrollTop;return V>=0?this._moveCursor(0,-Math.min(V,L.params[0]||1)):this._moveCursor(0,-(L.params[0]||1)),!0}cursorDown(L){const V=this._activeBuffer.scrollBottom-this._activeBuffer.y;return V>=0?this._moveCursor(0,Math.min(V,L.params[0]||1)):this._moveCursor(0,L.params[0]||1),!0}cursorForward(L){return this._moveCursor(L.params[0]||1,0),!0}cursorBackward(L){return this._moveCursor(-(L.params[0]||1),0),!0}cursorNextLine(L){return this.cursorDown(L),this._activeBuffer.x=0,!0}cursorPrecedingLine(L){return this.cursorUp(L),this._activeBuffer.x=0,!0}cursorCharAbsolute(L){return this._setCursor((L.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(L){return this._setCursor(L.length>=2?(L.params[1]||1)-1:0,(L.params[0]||1)-1),!0}charPosAbsolute(L){return this._setCursor((L.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(L){return this._moveCursor(L.params[0]||1,0),!0}linePosAbsolute(L){return this._setCursor(this._activeBuffer.x,(L.params[0]||1)-1),!0}vPositionRelative(L){return this._moveCursor(0,L.params[0]||1),!0}hVPosition(L){return this.cursorPosition(L),!0}tabClear(L){const V=L.params[0];return V===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:V===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(L){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let V=L.params[0]||1;for(;V--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(L){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let V=L.params[0]||1;for(;V--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(L){const V=L.params[0];return V===1&&(this._curAttrData.bg|=536870912),V!==2&&V!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(L,V,$,B=!1,W=!1){const ee=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);ee.replaceCells(V,$,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData(),W),B&&(ee.isWrapped=!1)}_resetBufferLine(L,V=!1){const $=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);$&&($.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),V),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+L),$.isWrapped=!1)}eraseInDisplay(L,V=!1){let $;switch(this._restrictCursor(this._bufferService.cols),L.params[0]){case 0:for($=this._activeBuffer.y,this._dirtyRowTracker.markDirty($),this._eraseInBufferLine($++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,V);$<this._bufferService.rows;$++)this._resetBufferLine($,V);this._dirtyRowTracker.markDirty($);break;case 1:for($=this._activeBuffer.y,this._dirtyRowTracker.markDirty($),this._eraseInBufferLine($,0,this._activeBuffer.x+1,!0,V),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get($+1).isWrapped=!1);$--;)this._resetBufferLine($,V);this._dirtyRowTracker.markDirty(0);break;case 2:for($=this._bufferService.rows,this._dirtyRowTracker.markDirty($-1);$--;)this._resetBufferLine($,V);this._dirtyRowTracker.markDirty(0);break;case 3:const B=this._activeBuffer.lines.length-this._bufferService.rows;B>0&&(this._activeBuffer.lines.trimStart(B),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-B,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-B,0),this._onScroll.fire(0))}return!0}eraseInLine(L,V=!1){switch(this._restrictCursor(this._bufferService.cols),L.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,V);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,V);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,V)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(L){this._restrictCursor();let V=L.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const $=this._activeBuffer.ybase+this._activeBuffer.y,B=this._bufferService.rows-1-this._activeBuffer.scrollBottom,W=this._bufferService.rows-1+this._activeBuffer.ybase-B+1;for(;V--;)this._activeBuffer.lines.splice(W-1,1),this._activeBuffer.lines.splice($,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(L){this._restrictCursor();let V=L.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const $=this._activeBuffer.ybase+this._activeBuffer.y;let B;for(B=this._bufferService.rows-1-this._activeBuffer.scrollBottom,B=this._bufferService.rows-1+this._activeBuffer.ybase-B;V--;)this._activeBuffer.lines.splice($,1),this._activeBuffer.lines.splice(B,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(L){this._restrictCursor();const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return V&&(V.insertCells(this._activeBuffer.x,L.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(L){this._restrictCursor();const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return V&&(V.deleteCells(this._activeBuffer.x,L.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(L){let V=L.params[0]||1;for(;V--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(L){let V=L.params[0]||1;for(;V--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(g.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const V=L.params[0]||1;for(let $=this._activeBuffer.scrollTop;$<=this._activeBuffer.scrollBottom;++$){const B=this._activeBuffer.lines.get(this._activeBuffer.ybase+$);B.deleteCells(0,V,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),B.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const V=L.params[0]||1;for(let $=this._activeBuffer.scrollTop;$<=this._activeBuffer.scrollBottom;++$){const B=this._activeBuffer.lines.get(this._activeBuffer.ybase+$);B.insertCells(0,V,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),B.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const V=L.params[0]||1;for(let $=this._activeBuffer.scrollTop;$<=this._activeBuffer.scrollBottom;++$){const B=this._activeBuffer.lines.get(this._activeBuffer.ybase+$);B.insertCells(this._activeBuffer.x,V,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),B.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(L){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const V=L.params[0]||1;for(let $=this._activeBuffer.scrollTop;$<=this._activeBuffer.scrollBottom;++$){const B=this._activeBuffer.lines.get(this._activeBuffer.ybase+$);B.deleteCells(this._activeBuffer.x,V,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),B.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(L){this._restrictCursor();const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return V&&(V.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(L.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(L){if(!this._parser.precedingCodepoint)return!0;const V=L.params[0]||1,$=new Uint32Array(V);for(let B=0;B<V;++B)$[B]=this._parser.precedingCodepoint;return this.print($,0,$.length),!0}sendDeviceAttributesPrimary(L){return L.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(m.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(m.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(L){return L.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(m.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(m.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(L.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(m.C0.ESC+"[>83;40003;0c")),!0}_is(L){return(this._optionsService.rawOptions.termName+"").indexOf(L)===0}setMode(L){for(let V=0;V<L.length;V++)switch(L.params[V]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(L){for(let V=0;V<L.length;V++)switch(L.params[V]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,y.DEFAULT_CHARSET),this._charsetService.setgCharset(1,y.DEFAULT_CHARSET),this._charsetService.setgCharset(2,y.DEFAULT_CHARSET),this._charsetService.setgCharset(3,y.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(L){for(let V=0;V<L.length;V++)switch(L.params[V]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(L){for(let V=0;V<L.length;V++)switch(L.params[V]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),L.params[V]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(L,V){const $=this._coreService.decPrivateModes,{activeProtocol:B,activeEncoding:W}=this._coreMouseService,ee=this._coreService,{buffers:Z,cols:Q}=this._bufferService,{active:ce,alt:P}=Z,K=this._optionsService.rawOptions,ie=Ae=>Ae?1:2,se=L.params[0];return me=se,fe=V?se===2?4:se===4?ie(ee.modes.insertMode):se===12?3:se===20?ie(K.convertEol):0:se===1?ie($.applicationCursorKeys):se===3?K.windowOptions.setWinLines?Q===80?2:Q===132?1:0:0:se===6?ie($.origin):se===7?ie($.wraparound):se===8?3:se===9?ie(B==="X10"):se===12?ie(K.cursorBlink):se===25?ie(!ee.isCursorHidden):se===45?ie($.reverseWraparound):se===66?ie($.applicationKeypad):se===67?4:se===1e3?ie(B==="VT200"):se===1002?ie(B==="DRAG"):se===1003?ie(B==="ANY"):se===1004?ie($.sendFocus):se===1005?4:se===1006?ie(W==="SGR"):se===1015?4:se===1016?ie(W==="SGR_PIXELS"):se===1048?1:se===47||se===1047||se===1049?ie(ce===P):se===2004?ie($.bracketedPasteMode):0,ee.triggerDataEvent(`${m.C0.ESC}[${V?"":"?"}${me};${fe}$y`),!0;var me,fe}_updateAttrColor(L,V,$,B,W){return V===2?(L|=50331648,L&=-16777216,L|=A.AttributeData.fromColorRGB([$,B,W])):V===5&&(L&=-50331904,L|=33554432|255&$),L}_extractColor(L,V,$){const B=[0,0,-1,0,0,0];let W=0,ee=0;do{if(B[ee+W]=L.params[V+ee],L.hasSubParams(V+ee)){const Z=L.getSubParams(V+ee);let Q=0;do B[1]===5&&(W=1),B[ee+Q+1+W]=Z[Q];while(++Q<Z.length&&Q+ee+1+W<B.length);break}if(B[1]===5&&ee+W>=2||B[1]===2&&ee+W>=5)break;B[1]&&(W=1)}while(++ee+V<L.length&&ee+W<B.length);for(let Z=2;Z<B.length;++Z)B[Z]===-1&&(B[Z]=0);switch(B[0]){case 38:$.fg=this._updateAttrColor($.fg,B[1],B[3],B[4],B[5]);break;case 48:$.bg=this._updateAttrColor($.bg,B[1],B[3],B[4],B[5]);break;case 58:$.extended=$.extended.clone(),$.extended.underlineColor=this._updateAttrColor($.extended.underlineColor,B[1],B[3],B[4],B[5])}return ee}_processUnderline(L,V){V.extended=V.extended.clone(),(!~L||L>5)&&(L=1),V.extended.underlineStyle=L,V.fg|=268435456,L===0&&(V.fg&=-268435457),V.updateExtended()}_processSGR0(L){L.fg=g.DEFAULT_ATTR_DATA.fg,L.bg=g.DEFAULT_ATTR_DATA.bg,L.extended=L.extended.clone(),L.extended.underlineStyle=0,L.extended.underlineColor&=-67108864,L.updateExtended()}charAttributes(L){if(L.length===1&&L.params[0]===0)return this._processSGR0(this._curAttrData),!0;const V=L.length;let $;const B=this._curAttrData;for(let W=0;W<V;W++)$=L.params[W],$>=30&&$<=37?(B.fg&=-50331904,B.fg|=16777216|$-30):$>=40&&$<=47?(B.bg&=-50331904,B.bg|=16777216|$-40):$>=90&&$<=97?(B.fg&=-50331904,B.fg|=16777224|$-90):$>=100&&$<=107?(B.bg&=-50331904,B.bg|=16777224|$-100):$===0?this._processSGR0(B):$===1?B.fg|=134217728:$===3?B.bg|=67108864:$===4?(B.fg|=268435456,this._processUnderline(L.hasSubParams(W)?L.getSubParams(W)[0]:1,B)):$===5?B.fg|=536870912:$===7?B.fg|=67108864:$===8?B.fg|=1073741824:$===9?B.fg|=2147483648:$===2?B.bg|=134217728:$===21?this._processUnderline(2,B):$===22?(B.fg&=-134217729,B.bg&=-134217729):$===23?B.bg&=-67108865:$===24?(B.fg&=-268435457,this._processUnderline(0,B)):$===25?B.fg&=-536870913:$===27?B.fg&=-67108865:$===28?B.fg&=-1073741825:$===29?B.fg&=2147483647:$===39?(B.fg&=-67108864,B.fg|=16777215&g.DEFAULT_ATTR_DATA.fg):$===49?(B.bg&=-67108864,B.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):$===38||$===48||$===58?W+=this._extractColor(L,W,B):$===53?B.bg|=1073741824:$===55?B.bg&=-1073741825:$===59?(B.extended=B.extended.clone(),B.extended.underlineColor=-1,B.updateExtended()):$===100?(B.fg&=-67108864,B.fg|=16777215&g.DEFAULT_ATTR_DATA.fg,B.bg&=-67108864,B.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",$);return!0}deviceStatus(L){switch(L.params[0]){case 5:this._coreService.triggerDataEvent(`${m.C0.ESC}[0n`);break;case 6:const V=this._activeBuffer.y+1,$=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${m.C0.ESC}[${V};${$}R`)}return!0}deviceStatusPrivate(L){if(L.params[0]===6){const V=this._activeBuffer.y+1,$=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${m.C0.ESC}[?${V};${$}R`)}return!0}softReset(L){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(L){const V=L.params[0]||1;switch(V){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const $=V%2==1;return this._optionsService.options.cursorBlink=$,!0}setScrollRegion(L){const V=L.params[0]||1;let $;return(L.length<2||($=L.params[1])>this._bufferService.rows||$===0)&&($=this._bufferService.rows),$>V&&(this._activeBuffer.scrollTop=V-1,this._activeBuffer.scrollBottom=$-1,this._setCursor(0,0)),!0}windowOptions(L){if(!I(L.params[0],this._optionsService.rawOptions.windowOptions))return!0;const V=L.length>1?L.params[1]:0;switch(L.params[0]){case 14:V!==2&&this._onRequestWindowsOptionsReport.fire(z.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(z.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${m.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:V!==0&&V!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),V!==0&&V!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:V!==0&&V!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),V!==0&&V!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(L){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(L){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(L){return this._windowTitle=L,this._onTitleChange.fire(L),!0}setIconName(L){return this._iconName=L,!0}setOrReportIndexedColor(L){const V=[],$=L.split(";");for(;$.length>1;){const B=$.shift(),W=$.shift();if(/^\d+$/.exec(B)){const ee=parseInt(B);if(F(ee))if(W==="?")V.push({type:0,index:ee});else{const Z=(0,T.parseColor)(W);Z&&V.push({type:1,index:ee,color:Z})}}}return V.length&&this._onColor.fire(V),!0}setHyperlink(L){const V=L.split(";");return!(V.length<2)&&(V[1]?this._createHyperlink(V[0],V[1]):!V[0]&&this._finishHyperlink())}_createHyperlink(L,V){this._getCurrentLinkId()&&this._finishHyperlink();const $=L.split(":");let B;const W=$.findIndex((ee=>ee.startsWith("id=")));return W!==-1&&(B=$[W].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:B,uri:V}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(L,V){const $=L.split(";");for(let B=0;B<$.length&&!(V>=this._specialColors.length);++B,++V)if($[B]==="?")this._onColor.fire([{type:0,index:this._specialColors[V]}]);else{const W=(0,T.parseColor)($[B]);W&&this._onColor.fire([{type:1,index:this._specialColors[V],color:W}])}return!0}setOrReportFgColor(L){return this._setOrReportSpecialColor(L,0)}setOrReportBgColor(L){return this._setOrReportSpecialColor(L,1)}setOrReportCursorColor(L){return this._setOrReportSpecialColor(L,2)}restoreIndexedColor(L){if(!L)return this._onColor.fire([{type:2}]),!0;const V=[],$=L.split(";");for(let B=0;B<$.length;++B)if(/^\d+$/.exec($[B])){const W=parseInt($[B]);F(W)&&V.push({type:2,index:W})}return V.length&&this._onColor.fire(V),!0}restoreFgColor(L){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(L){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(L){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,y.DEFAULT_CHARSET),!0}selectCharset(L){return L.length!==2?(this.selectDefaultCharset(),!0):(L[0]==="/"||this._charsetService.setgCharset(j[L[0]],y.CHARSETS[L[1]]||y.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const L=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,L,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(L){return this._charsetService.setgLevel(L),!0}screenAlignmentPattern(){const L=new x.CellData;L.content=4194373,L.fg=this._curAttrData.fg,L.bg=this._curAttrData.bg,this._setCursor(0,0);for(let V=0;V<this._bufferService.rows;++V){const $=this._activeBuffer.ybase+this._activeBuffer.y+V,B=this._activeBuffer.lines.get($);B&&(B.fill(L),B.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(L,V){const $=this._bufferService.buffer,B=this._optionsService.rawOptions;return(W=>(this._coreService.triggerDataEvent(`${m.C0.ESC}${W}${m.C0.ESC}\\`),!0))(L==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:L==='"p'?'P1$r61;1"p':L==="r"?`P1$r${$.scrollTop+1};${$.scrollBottom+1}r`:L==="m"?"P1$r0m":L===" q"?`P1$r${{block:2,underline:4,bar:6}[B.cursorStyle]-(B.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(L,V){this._dirtyRowTracker.markRangeDirty(L,V)}}a.InputHandler=X;let q=class{constructor(Y){this._bufferService=Y,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(Y){Y<this.start?this.start=Y:Y>this.end&&(this.end=Y)}markRangeDirty(Y,L){Y>L&&(U=Y,Y=L,L=U),Y<this.start&&(this.start=Y),L>this.end&&(this.end=L)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function F(Y){return 0<=Y&&Y<256}q=f([v(0,D.IBufferService)],q)},844:(p,a)=>{function c(f){for(const v of f)v.dispose();f.length=0}Object.defineProperty(a,"__esModule",{value:!0}),a.getDisposeArrayDisposable=a.disposeArray=a.toDisposable=a.MutableDisposable=a.Disposable=void 0,a.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const f of this._disposables)f.dispose();this._disposables.length=0}register(f){return this._disposables.push(f),f}unregister(f){const v=this._disposables.indexOf(f);v!==-1&&this._disposables.splice(v,1)}},a.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(f){var v;this._isDisposed||f===this._value||((v=this._value)===null||v===void 0||v.dispose(),this._value=f)}clear(){this.value=void 0}dispose(){var f;this._isDisposed=!0,(f=this._value)===null||f===void 0||f.dispose(),this._value=void 0}},a.toDisposable=function(f){return{dispose:f}},a.disposeArray=c,a.getDisposeArrayDisposable=function(f){return{dispose:()=>c(f)}}},1505:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.FourKeyMap=a.TwoKeyMap=void 0;class c{constructor(){this._data={}}set(v,m,y){this._data[v]||(this._data[v]={}),this._data[v][m]=y}get(v,m){return this._data[v]?this._data[v][m]:void 0}clear(){this._data={}}}a.TwoKeyMap=c,a.FourKeyMap=class{constructor(){this._data=new c}set(f,v,m,y,C){this._data.get(f,v)||this._data.set(f,v,new c),this._data.get(f,v).set(m,y,C)}get(f,v,m,y){var C;return(C=this._data.get(f,v))===null||C===void 0?void 0:C.get(m,y)}clear(){this._data.clear()}}},6114:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.isChromeOS=a.isLinux=a.isWindows=a.isIphone=a.isIpad=a.isMac=a.getSafariVersion=a.isSafari=a.isLegacyEdge=a.isFirefox=a.isNode=void 0,a.isNode=typeof navigator>"u";const c=a.isNode?"node":navigator.userAgent,f=a.isNode?"node":navigator.platform;a.isFirefox=c.includes("Firefox"),a.isLegacyEdge=c.includes("Edge"),a.isSafari=/^((?!chrome|android).)*safari/i.test(c),a.getSafariVersion=function(){if(!a.isSafari)return 0;const v=c.match(/Version\/(\d+)/);return v===null||v.length<2?0:parseInt(v[1])},a.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(f),a.isIpad=f==="iPad",a.isIphone=f==="iPhone",a.isWindows=["Windows","Win16","Win32","WinCE"].includes(f),a.isLinux=f.indexOf("Linux")>=0,a.isChromeOS=/\bCrOS\b/.test(c)},6106:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.SortedList=void 0;let c=0;a.SortedList=class{constructor(f){this._getKey=f,this._array=[]}clear(){this._array.length=0}insert(f){this._array.length!==0?(c=this._search(this._getKey(f)),this._array.splice(c,0,f)):this._array.push(f)}delete(f){if(this._array.length===0)return!1;const v=this._getKey(f);if(v===void 0||(c=this._search(v),c===-1)||this._getKey(this._array[c])!==v)return!1;do if(this._array[c]===f)return this._array.splice(c,1),!0;while(++c<this._array.length&&this._getKey(this._array[c])===v);return!1}*getKeyIterator(f){if(this._array.length!==0&&(c=this._search(f),!(c<0||c>=this._array.length)&&this._getKey(this._array[c])===f))do yield this._array[c];while(++c<this._array.length&&this._getKey(this._array[c])===f)}forEachByKey(f,v){if(this._array.length!==0&&(c=this._search(f),!(c<0||c>=this._array.length)&&this._getKey(this._array[c])===f))do v(this._array[c]);while(++c<this._array.length&&this._getKey(this._array[c])===f)}values(){return[...this._array].values()}_search(f){let v=0,m=this._array.length-1;for(;m>=v;){let y=v+m>>1;const C=this._getKey(this._array[y]);if(C>f)m=y-1;else{if(!(C<f)){for(;y>0&&this._getKey(this._array[y-1])===f;)y--;return y}v=y+1}}return v}}},7226:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DebouncedIdleTask=a.IdleTaskQueue=a.PriorityTaskQueue=void 0;const f=c(6114);class v{constructor(){this._tasks=[],this._i=0}enqueue(C){this._tasks.push(C),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(C){this._idleCallback=void 0;let R=0,E=0,g=C.timeRemaining(),b=0;for(;this._i<this._tasks.length;){if(R=Date.now(),this._tasks[this._i]()||this._i++,R=Math.max(1,Date.now()-R),E=Math.max(R,E),b=C.timeRemaining(),1.5*E>b)return g-R<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(g-R))}ms`),void this._start();g=b}this.clear()}}class m extends v{_requestCallback(C){return setTimeout((()=>C(this._createDeadline(16))))}_cancelCallback(C){clearTimeout(C)}_createDeadline(C){const R=Date.now()+C;return{timeRemaining:()=>Math.max(0,R-Date.now())}}}a.PriorityTaskQueue=m,a.IdleTaskQueue=!f.isNode&&"requestIdleCallback"in window?class extends v{_requestCallback(y){return requestIdleCallback(y)}_cancelCallback(y){cancelIdleCallback(y)}}:m,a.DebouncedIdleTask=class{constructor(){this._queue=new a.IdleTaskQueue}set(y){this._queue.clear(),this._queue.enqueue(y)}flush(){this._queue.flush()}}},9282:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.updateWindowsModeWrappedState=void 0;const f=c(643);a.updateWindowsModeWrappedState=function(v){const m=v.buffer.lines.get(v.buffer.ybase+v.buffer.y-1),y=m?.get(v.cols-1),C=v.buffer.lines.get(v.buffer.ybase+v.buffer.y);C&&y&&(C.isWrapped=y[f.CHAR_DATA_CODE_INDEX]!==f.NULL_CELL_CODE&&y[f.CHAR_DATA_CODE_INDEX]!==f.WHITESPACE_CELL_CODE)}},3734:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ExtendedAttrs=a.AttributeData=void 0;class c{constructor(){this.fg=0,this.bg=0,this.extended=new f}static toColorRGB(m){return[m>>>16&255,m>>>8&255,255&m]}static fromColorRGB(m){return(255&m[0])<<16|(255&m[1])<<8|255&m[2]}clone(){const m=new c;return m.fg=this.fg,m.bg=this.bg,m.extended=this.extended.clone(),m}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}}a.AttributeData=c;class f{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(m){this._ext=m}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(m){this._ext&=-469762049,this._ext|=m<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(m){this._ext&=-67108864,this._ext|=67108863&m}get urlId(){return this._urlId}set urlId(m){this._urlId=m}constructor(m=0,y=0){this._ext=0,this._urlId=0,this._ext=m,this._urlId=y}clone(){return new f(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}a.ExtendedAttrs=f},9092:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Buffer=a.MAX_BUFFER_SIZE=void 0;const f=c(6349),v=c(7226),m=c(3734),y=c(8437),C=c(4634),R=c(511),E=c(643),g=c(4863),b=c(7116);a.MAX_BUFFER_SIZE=4294967295,a.Buffer=class{constructor(_,x,A){this._hasScrollback=_,this._optionsService=x,this._bufferService=A,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=y.DEFAULT_ATTR_DATA.clone(),this.savedCharset=b.DEFAULT_CHARSET,this.markers=[],this._nullCell=R.CellData.fromCharData([0,E.NULL_CELL_CHAR,E.NULL_CELL_WIDTH,E.NULL_CELL_CODE]),this._whitespaceCell=R.CellData.fromCharData([0,E.WHITESPACE_CELL_CHAR,E.WHITESPACE_CELL_WIDTH,E.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new v.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(_){return _?(this._nullCell.fg=_.fg,this._nullCell.bg=_.bg,this._nullCell.extended=_.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new m.ExtendedAttrs),this._nullCell}getWhitespaceCell(_){return _?(this._whitespaceCell.fg=_.fg,this._whitespaceCell.bg=_.bg,this._whitespaceCell.extended=_.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new m.ExtendedAttrs),this._whitespaceCell}getBlankLine(_,x){return new y.BufferLine(this._bufferService.cols,this.getNullCell(_),x)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const _=this.ybase+this.y-this.ydisp;return _>=0&&_<this._rows}_getCorrectBufferLength(_){if(!this._hasScrollback)return _;const x=_+this._optionsService.rawOptions.scrollback;return x>a.MAX_BUFFER_SIZE?a.MAX_BUFFER_SIZE:x}fillViewportRows(_){if(this.lines.length===0){_===void 0&&(_=y.DEFAULT_ATTR_DATA);let x=this._rows;for(;x--;)this.lines.push(this.getBlankLine(_))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(_,x){const A=this.getNullCell(y.DEFAULT_ATTR_DATA);let D=0;const N=this._getCorrectBufferLength(x);if(N>this.lines.maxLength&&(this.lines.maxLength=N),this.lines.length>0){if(this._cols<_)for(let T=0;T<this.lines.length;T++)D+=+this.lines.get(T).resize(_,A);let O=0;if(this._rows<x)for(let T=this._rows;T<x;T++)this.lines.length<x+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new y.BufferLine(_,A)):this.ybase>0&&this.lines.length<=this.ybase+this.y+O+1?(this.ybase--,O++,this.ydisp>0&&this.ydisp--):this.lines.push(new y.BufferLine(_,A)));else for(let T=this._rows;T>x;T--)this.lines.length>x+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(N<this.lines.maxLength){const T=this.lines.length-N;T>0&&(this.lines.trimStart(T),this.ybase=Math.max(this.ybase-T,0),this.ydisp=Math.max(this.ydisp-T,0),this.savedY=Math.max(this.savedY-T,0)),this.lines.maxLength=N}this.x=Math.min(this.x,_-1),this.y=Math.min(this.y,x-1),O&&(this.y+=O),this.savedX=Math.min(this.savedX,_-1),this.scrollTop=0}if(this.scrollBottom=x-1,this._isReflowEnabled&&(this._reflow(_,x),this._cols>_))for(let O=0;O<this.lines.length;O++)D+=+this.lines.get(O).resize(_,A);this._cols=_,this._rows=x,this._memoryCleanupQueue.clear(),D>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let _=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,_=!1);let x=0;for(;this._memoryCleanupPosition<this.lines.length;)if(x+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),x>100)return!0;return _}get _isReflowEnabled(){const _=this._optionsService.rawOptions.windowsPty;return _&&_.buildNumber?this._hasScrollback&&_.backend==="conpty"&&_.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(_,x){this._cols!==_&&(_>this._cols?this._reflowLarger(_,x):this._reflowSmaller(_,x))}_reflowLarger(_,x){const A=(0,C.reflowLargerGetLinesToRemove)(this.lines,this._cols,_,this.ybase+this.y,this.getNullCell(y.DEFAULT_ATTR_DATA));if(A.length>0){const D=(0,C.reflowLargerCreateNewLayout)(this.lines,A);(0,C.reflowLargerApplyNewLayout)(this.lines,D.layout),this._reflowLargerAdjustViewport(_,x,D.countRemoved)}}_reflowLargerAdjustViewport(_,x,A){const D=this.getNullCell(y.DEFAULT_ATTR_DATA);let N=A;for(;N-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<x&&this.lines.push(new y.BufferLine(_,D))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-A,0)}_reflowSmaller(_,x){const A=this.getNullCell(y.DEFAULT_ATTR_DATA),D=[];let N=0;for(let O=this.lines.length-1;O>=0;O--){let T=this.lines.get(O);if(!T||!T.isWrapped&&T.getTrimmedLength()<=_)continue;const j=[T];for(;T.isWrapped&&O>0;)T=this.lines.get(--O),j.unshift(T);const H=this.ybase+this.y;if(H>=O&&H<O+j.length)continue;const I=j[j.length-1].getTrimmedLength(),z=(0,C.reflowSmallerGetNewLineLengths)(j,this._cols,_),U=z.length-j.length;let X;X=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+U):Math.max(0,this.lines.length-this.lines.maxLength+U);const q=[];for(let B=0;B<U;B++){const W=this.getBlankLine(y.DEFAULT_ATTR_DATA,!0);q.push(W)}q.length>0&&(D.push({start:O+j.length+N,newLines:q}),N+=q.length),j.push(...q);let F=z.length-1,Y=z[F];Y===0&&(F--,Y=z[F]);let L=j.length-U-1,V=I;for(;L>=0;){const B=Math.min(V,Y);if(j[F]===void 0)break;if(j[F].copyCellsFrom(j[L],V-B,Y-B,B,!0),Y-=B,Y===0&&(F--,Y=z[F]),V-=B,V===0){L--;const W=Math.max(L,0);V=(0,C.getWrappedLineTrimmedLength)(j,W,this._cols)}}for(let B=0;B<j.length;B++)z[B]<_&&j[B].setCell(z[B],A);let $=U-X;for(;$-- >0;)this.ybase===0?this.y<x-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+N)-x&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+U,this.ybase+x-1)}if(D.length>0){const O=[],T=[];for(let F=0;F<this.lines.length;F++)T.push(this.lines.get(F));const j=this.lines.length;let H=j-1,I=0,z=D[I];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+N);let U=0;for(let F=Math.min(this.lines.maxLength-1,j+N-1);F>=0;F--)if(z&&z.start>H+U){for(let Y=z.newLines.length-1;Y>=0;Y--)this.lines.set(F--,z.newLines[Y]);F++,O.push({index:H+1,amount:z.newLines.length}),U+=z.newLines.length,z=D[++I]}else this.lines.set(F,T[H--]);let X=0;for(let F=O.length-1;F>=0;F--)O[F].index+=X,this.lines.onInsertEmitter.fire(O[F]),X+=O[F].amount;const q=Math.max(0,j+N-this.lines.maxLength);q>0&&this.lines.onTrimEmitter.fire(q)}}translateBufferLineToString(_,x,A=0,D){const N=this.lines.get(_);return N?N.translateToString(x,A,D):""}getWrappedRangeForLine(_){let x=_,A=_;for(;x>0&&this.lines.get(x).isWrapped;)x--;for(;A+1<this.lines.length&&this.lines.get(A+1).isWrapped;)A++;return{first:x,last:A}}setupTabStops(_){for(_!=null?this.tabs[_]||(_=this.prevStop(_)):(this.tabs={},_=0);_<this._cols;_+=this._optionsService.rawOptions.tabStopWidth)this.tabs[_]=!0}prevStop(_){for(_==null&&(_=this.x);!this.tabs[--_]&&_>0;);return _>=this._cols?this._cols-1:_<0?0:_}nextStop(_){for(_==null&&(_=this.x);!this.tabs[++_]&&_<this._cols;);return _>=this._cols?this._cols-1:_<0?0:_}clearMarkers(_){this._isClearing=!0;for(let x=0;x<this.markers.length;x++)this.markers[x].line===_&&(this.markers[x].dispose(),this.markers.splice(x--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let _=0;_<this.markers.length;_++)this.markers[_].dispose(),this.markers.splice(_--,1);this._isClearing=!1}addMarker(_){const x=new g.Marker(_);return this.markers.push(x),x.register(this.lines.onTrim((A=>{x.line-=A,x.line<0&&x.dispose()}))),x.register(this.lines.onInsert((A=>{x.line>=A.index&&(x.line+=A.amount)}))),x.register(this.lines.onDelete((A=>{x.line>=A.index&&x.line<A.index+A.amount&&x.dispose(),x.line>A.index&&(x.line-=A.amount)}))),x.register(x.onDispose((()=>this._removeMarker(x)))),x}_removeMarker(_){this._isClearing||this.markers.splice(this.markers.indexOf(_),1)}}},8437:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferLine=a.DEFAULT_ATTR_DATA=void 0;const f=c(3734),v=c(511),m=c(643),y=c(482);a.DEFAULT_ATTR_DATA=Object.freeze(new f.AttributeData);let C=0;class R{constructor(g,b,_=!1){this.isWrapped=_,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*g);const x=b||v.CellData.fromCharData([0,m.NULL_CELL_CHAR,m.NULL_CELL_WIDTH,m.NULL_CELL_CODE]);for(let A=0;A<g;++A)this.setCell(A,x);this.length=g}get(g){const b=this._data[3*g+0],_=2097151&b;return[this._data[3*g+1],2097152&b?this._combined[g]:_?(0,y.stringFromCodePoint)(_):"",b>>22,2097152&b?this._combined[g].charCodeAt(this._combined[g].length-1):_]}set(g,b){this._data[3*g+1]=b[m.CHAR_DATA_ATTR_INDEX],b[m.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[g]=b[1],this._data[3*g+0]=2097152|g|b[m.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*g+0]=b[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|b[m.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(g){return this._data[3*g+0]>>22}hasWidth(g){return 12582912&this._data[3*g+0]}getFg(g){return this._data[3*g+1]}getBg(g){return this._data[3*g+2]}hasContent(g){return 4194303&this._data[3*g+0]}getCodePoint(g){const b=this._data[3*g+0];return 2097152&b?this._combined[g].charCodeAt(this._combined[g].length-1):2097151&b}isCombined(g){return 2097152&this._data[3*g+0]}getString(g){const b=this._data[3*g+0];return 2097152&b?this._combined[g]:2097151&b?(0,y.stringFromCodePoint)(2097151&b):""}isProtected(g){return 536870912&this._data[3*g+2]}loadCell(g,b){return C=3*g,b.content=this._data[C+0],b.fg=this._data[C+1],b.bg=this._data[C+2],2097152&b.content&&(b.combinedData=this._combined[g]),268435456&b.bg&&(b.extended=this._extendedAttrs[g]),b}setCell(g,b){2097152&b.content&&(this._combined[g]=b.combinedData),268435456&b.bg&&(this._extendedAttrs[g]=b.extended),this._data[3*g+0]=b.content,this._data[3*g+1]=b.fg,this._data[3*g+2]=b.bg}setCellFromCodePoint(g,b,_,x,A,D){268435456&A&&(this._extendedAttrs[g]=D),this._data[3*g+0]=b|_<<22,this._data[3*g+1]=x,this._data[3*g+2]=A}addCodepointToCell(g,b){let _=this._data[3*g+0];2097152&_?this._combined[g]+=(0,y.stringFromCodePoint)(b):(2097151&_?(this._combined[g]=(0,y.stringFromCodePoint)(2097151&_)+(0,y.stringFromCodePoint)(b),_&=-2097152,_|=2097152):_=b|4194304,this._data[3*g+0]=_)}insertCells(g,b,_,x){if((g%=this.length)&&this.getWidth(g-1)===2&&this.setCellFromCodePoint(g-1,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs),b<this.length-g){const A=new v.CellData;for(let D=this.length-g-b-1;D>=0;--D)this.setCell(g+b+D,this.loadCell(g+D,A));for(let D=0;D<b;++D)this.setCell(g+D,_)}else for(let A=g;A<this.length;++A)this.setCell(A,_);this.getWidth(this.length-1)===2&&this.setCellFromCodePoint(this.length-1,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs)}deleteCells(g,b,_,x){if(g%=this.length,b<this.length-g){const A=new v.CellData;for(let D=0;D<this.length-g-b;++D)this.setCell(g+D,this.loadCell(g+b+D,A));for(let D=this.length-b;D<this.length;++D)this.setCell(D,_)}else for(let A=g;A<this.length;++A)this.setCell(A,_);g&&this.getWidth(g-1)===2&&this.setCellFromCodePoint(g-1,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs),this.getWidth(g)!==0||this.hasContent(g)||this.setCellFromCodePoint(g,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs)}replaceCells(g,b,_,x,A=!1){if(A)for(g&&this.getWidth(g-1)===2&&!this.isProtected(g-1)&&this.setCellFromCodePoint(g-1,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs),b<this.length&&this.getWidth(b-1)===2&&!this.isProtected(b)&&this.setCellFromCodePoint(b,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs);g<b&&g<this.length;)this.isProtected(g)||this.setCell(g,_),g++;else for(g&&this.getWidth(g-1)===2&&this.setCellFromCodePoint(g-1,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs),b<this.length&&this.getWidth(b-1)===2&&this.setCellFromCodePoint(b,0,1,x?.fg||0,x?.bg||0,x?.extended||new f.ExtendedAttrs);g<b&&g<this.length;)this.setCell(g++,_)}resize(g,b){if(g===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const _=3*g;if(g>this.length){if(this._data.buffer.byteLength>=4*_)this._data=new Uint32Array(this._data.buffer,0,_);else{const x=new Uint32Array(_);x.set(this._data),this._data=x}for(let x=this.length;x<g;++x)this.setCell(x,b)}else{this._data=this._data.subarray(0,_);const x=Object.keys(this._combined);for(let D=0;D<x.length;D++){const N=parseInt(x[D],10);N>=g&&delete this._combined[N]}const A=Object.keys(this._extendedAttrs);for(let D=0;D<A.length;D++){const N=parseInt(A[D],10);N>=g&&delete this._extendedAttrs[N]}}return this.length=g,4*_*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const g=new Uint32Array(this._data.length);return g.set(this._data),this._data=g,1}return 0}fill(g,b=!1){if(b)for(let _=0;_<this.length;++_)this.isProtected(_)||this.setCell(_,g);else{this._combined={},this._extendedAttrs={};for(let _=0;_<this.length;++_)this.setCell(_,g)}}copyFrom(g){this.length!==g.length?this._data=new Uint32Array(g._data):this._data.set(g._data),this.length=g.length,this._combined={};for(const b in g._combined)this._combined[b]=g._combined[b];this._extendedAttrs={};for(const b in g._extendedAttrs)this._extendedAttrs[b]=g._extendedAttrs[b];this.isWrapped=g.isWrapped}clone(){const g=new R(0);g._data=new Uint32Array(this._data),g.length=this.length;for(const b in this._combined)g._combined[b]=this._combined[b];for(const b in this._extendedAttrs)g._extendedAttrs[b]=this._extendedAttrs[b];return g.isWrapped=this.isWrapped,g}getTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0])return g+(this._data[3*g+0]>>22);return 0}getNoBgTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0]||50331648&this._data[3*g+2])return g+(this._data[3*g+0]>>22);return 0}copyCellsFrom(g,b,_,x,A){const D=g._data;if(A)for(let O=x-1;O>=0;O--){for(let T=0;T<3;T++)this._data[3*(_+O)+T]=D[3*(b+O)+T];268435456&D[3*(b+O)+2]&&(this._extendedAttrs[_+O]=g._extendedAttrs[b+O])}else for(let O=0;O<x;O++){for(let T=0;T<3;T++)this._data[3*(_+O)+T]=D[3*(b+O)+T];268435456&D[3*(b+O)+2]&&(this._extendedAttrs[_+O]=g._extendedAttrs[b+O])}const N=Object.keys(g._combined);for(let O=0;O<N.length;O++){const T=parseInt(N[O],10);T>=b&&(this._combined[T-b+_]=g._combined[T])}}translateToString(g=!1,b=0,_=this.length){g&&(_=Math.min(_,this.getTrimmedLength()));let x="";for(;b<_;){const A=this._data[3*b+0],D=2097151&A;x+=2097152&A?this._combined[b]:D?(0,y.stringFromCodePoint)(D):m.WHITESPACE_CELL_CHAR,b+=A>>22||1}return x}}a.BufferLine=R},4841:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.getRangeLength=void 0,a.getRangeLength=function(c,f){if(c.start.y>c.end.y)throw new Error(`Buffer range end (${c.end.x}, ${c.end.y}) cannot be before start (${c.start.x}, ${c.start.y})`);return f*(c.end.y-c.start.y)+(c.end.x-c.start.x+1)}},4634:(p,a)=>{function c(f,v,m){if(v===f.length-1)return f[v].getTrimmedLength();const y=!f[v].hasContent(m-1)&&f[v].getWidth(m-1)===1,C=f[v+1].getWidth(0)===2;return y&&C?m-1:m}Object.defineProperty(a,"__esModule",{value:!0}),a.getWrappedLineTrimmedLength=a.reflowSmallerGetNewLineLengths=a.reflowLargerApplyNewLayout=a.reflowLargerCreateNewLayout=a.reflowLargerGetLinesToRemove=void 0,a.reflowLargerGetLinesToRemove=function(f,v,m,y,C){const R=[];for(let E=0;E<f.length-1;E++){let g=E,b=f.get(++g);if(!b.isWrapped)continue;const _=[f.get(E)];for(;g<f.length&&b.isWrapped;)_.push(b),b=f.get(++g);if(y>=E&&y<g){E+=_.length-1;continue}let x=0,A=c(_,x,v),D=1,N=0;for(;D<_.length;){const T=c(_,D,v),j=T-N,H=m-A,I=Math.min(j,H);_[x].copyCellsFrom(_[D],N,A,I,!1),A+=I,A===m&&(x++,A=0),N+=I,N===T&&(D++,N=0),A===0&&x!==0&&_[x-1].getWidth(m-1)===2&&(_[x].copyCellsFrom(_[x-1],m-1,A++,1,!1),_[x-1].setCell(m-1,C))}_[x].replaceCells(A,m,C);let O=0;for(let T=_.length-1;T>0&&(T>x||_[T].getTrimmedLength()===0);T--)O++;O>0&&(R.push(E+_.length-O),R.push(O)),E+=_.length-1}return R},a.reflowLargerCreateNewLayout=function(f,v){const m=[];let y=0,C=v[y],R=0;for(let E=0;E<f.length;E++)if(C===E){const g=v[++y];f.onDeleteEmitter.fire({index:E-R,amount:g}),E+=g-1,R+=g,C=v[++y]}else m.push(E);return{layout:m,countRemoved:R}},a.reflowLargerApplyNewLayout=function(f,v){const m=[];for(let y=0;y<v.length;y++)m.push(f.get(v[y]));for(let y=0;y<m.length;y++)f.set(y,m[y]);f.length=v.length},a.reflowSmallerGetNewLineLengths=function(f,v,m){const y=[],C=f.map(((b,_)=>c(f,_,v))).reduce(((b,_)=>b+_));let R=0,E=0,g=0;for(;g<C;){if(C-g<m){y.push(C-g);break}R+=m;const b=c(f,E,v);R>b&&(R-=b,E++);const _=f[E].getWidth(R-1)===2;_&&R--;const x=_?m-1:m;y.push(x),g+=x}return y},a.getWrappedLineTrimmedLength=c},5295:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferSet=void 0;const f=c(8460),v=c(844),m=c(9092);class y extends v.Disposable{constructor(R,E){super(),this._optionsService=R,this._bufferService=E,this._onBufferActivate=this.register(new f.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new m.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new m.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(R){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(R),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(R,E){this._normal.resize(R,E),this._alt.resize(R,E),this.setupTabStops(R)}setupTabStops(R){this._normal.setupTabStops(R),this._alt.setupTabStops(R)}}a.BufferSet=y},511:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CellData=void 0;const f=c(482),v=c(643),m=c(3734);class y extends m.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new m.ExtendedAttrs,this.combinedData=""}static fromCharData(R){const E=new y;return E.setFromCharData(R),E}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,f.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(R){this.fg=R[v.CHAR_DATA_ATTR_INDEX],this.bg=0;let E=!1;if(R[v.CHAR_DATA_CHAR_INDEX].length>2)E=!0;else if(R[v.CHAR_DATA_CHAR_INDEX].length===2){const g=R[v.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=g&&g<=56319){const b=R[v.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=b&&b<=57343?this.content=1024*(g-55296)+b-56320+65536|R[v.CHAR_DATA_WIDTH_INDEX]<<22:E=!0}else E=!0}else this.content=R[v.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|R[v.CHAR_DATA_WIDTH_INDEX]<<22;E&&(this.combinedData=R[v.CHAR_DATA_CHAR_INDEX],this.content=2097152|R[v.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}a.CellData=y},643:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.WHITESPACE_CELL_CODE=a.WHITESPACE_CELL_WIDTH=a.WHITESPACE_CELL_CHAR=a.NULL_CELL_CODE=a.NULL_CELL_WIDTH=a.NULL_CELL_CHAR=a.CHAR_DATA_CODE_INDEX=a.CHAR_DATA_WIDTH_INDEX=a.CHAR_DATA_CHAR_INDEX=a.CHAR_DATA_ATTR_INDEX=a.DEFAULT_EXT=a.DEFAULT_ATTR=a.DEFAULT_COLOR=void 0,a.DEFAULT_COLOR=0,a.DEFAULT_ATTR=256|a.DEFAULT_COLOR<<9,a.DEFAULT_EXT=0,a.CHAR_DATA_ATTR_INDEX=0,a.CHAR_DATA_CHAR_INDEX=1,a.CHAR_DATA_WIDTH_INDEX=2,a.CHAR_DATA_CODE_INDEX=3,a.NULL_CELL_CHAR="",a.NULL_CELL_WIDTH=1,a.NULL_CELL_CODE=0,a.WHITESPACE_CELL_CHAR=" ",a.WHITESPACE_CELL_WIDTH=1,a.WHITESPACE_CELL_CODE=32},4863:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Marker=void 0;const f=c(8460),v=c(844);class m{get id(){return this._id}constructor(C){this.line=C,this.isDisposed=!1,this._disposables=[],this._id=m._nextId++,this._onDispose=this.register(new f.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,v.disposeArray)(this._disposables),this._disposables.length=0)}register(C){return this._disposables.push(C),C}}a.Marker=m,m._nextId=1},7116:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DEFAULT_CHARSET=a.CHARSETS=void 0,a.CHARSETS={},a.DEFAULT_CHARSET=a.CHARSETS.B,a.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},a.CHARSETS.A={"#":"£"},a.CHARSETS.B=void 0,a.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},a.CHARSETS.C=a.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},a.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},a.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},a.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},a.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},a.CHARSETS.E=a.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},a.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},a.CHARSETS.H=a.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},a.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(p,a)=>{var c,f,v;Object.defineProperty(a,"__esModule",{value:!0}),a.C1_ESCAPED=a.C1=a.C0=void 0,(function(m){m.NUL="\0",m.SOH="",m.STX="",m.ETX="",m.EOT="",m.ENQ="",m.ACK="",m.BEL="\x07",m.BS="\b",m.HT=" ",m.LF=`
89
89
  `,m.VT="\v",m.FF="\f",m.CR="\r",m.SO="",m.SI="",m.DLE="",m.DC1="",m.DC2="",m.DC3="",m.DC4="",m.NAK="",m.SYN="",m.ETB="",m.CAN="",m.EM="",m.SUB="",m.ESC="\x1B",m.FS="",m.GS="",m.RS="",m.US="",m.SP=" ",m.DEL=""})(c||(a.C0=c={})),(function(m){m.PAD="€",m.HOP="",m.BPH="‚",m.NBH="ƒ",m.IND="„",m.NEL="…",m.SSA="†",m.ESA="‡",m.HTS="ˆ",m.HTJ="‰",m.VTS="Š",m.PLD="‹",m.PLU="Œ",m.RI="",m.SS2="Ž",m.SS3="",m.DCS="",m.PU1="‘",m.PU2="’",m.STS="“",m.CCH="”",m.MW="•",m.SPA="–",m.EPA="—",m.SOS="˜",m.SGCI="™",m.SCI="š",m.CSI="›",m.ST="œ",m.OSC="",m.PM="ž",m.APC="Ÿ"})(f||(a.C1=f={})),(function(m){m.ST=`${c.ESC}\\`})(v||(a.C1_ESCAPED=v={}))},7399:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.evaluateKeyboardEvent=void 0;const f=c(2584),v={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};a.evaluateKeyboardEvent=function(m,y,C,R){const E={type:0,cancel:!1,key:void 0},g=(m.shiftKey?1:0)|(m.altKey?2:0)|(m.ctrlKey?4:0)|(m.metaKey?8:0);switch(m.keyCode){case 0:m.key==="UIKeyInputUpArrow"?E.key=y?f.C0.ESC+"OA":f.C0.ESC+"[A":m.key==="UIKeyInputLeftArrow"?E.key=y?f.C0.ESC+"OD":f.C0.ESC+"[D":m.key==="UIKeyInputRightArrow"?E.key=y?f.C0.ESC+"OC":f.C0.ESC+"[C":m.key==="UIKeyInputDownArrow"&&(E.key=y?f.C0.ESC+"OB":f.C0.ESC+"[B");break;case 8:if(m.altKey){E.key=f.C0.ESC+f.C0.DEL;break}E.key=f.C0.DEL;break;case 9:if(m.shiftKey){E.key=f.C0.ESC+"[Z";break}E.key=f.C0.HT,E.cancel=!0;break;case 13:E.key=m.altKey?f.C0.ESC+f.C0.CR:f.C0.CR,E.cancel=!0;break;case 27:E.key=f.C0.ESC,m.altKey&&(E.key=f.C0.ESC+f.C0.ESC),E.cancel=!0;break;case 37:if(m.metaKey)break;g?(E.key=f.C0.ESC+"[1;"+(g+1)+"D",E.key===f.C0.ESC+"[1;3D"&&(E.key=f.C0.ESC+(C?"b":"[1;5D"))):E.key=y?f.C0.ESC+"OD":f.C0.ESC+"[D";break;case 39:if(m.metaKey)break;g?(E.key=f.C0.ESC+"[1;"+(g+1)+"C",E.key===f.C0.ESC+"[1;3C"&&(E.key=f.C0.ESC+(C?"f":"[1;5C"))):E.key=y?f.C0.ESC+"OC":f.C0.ESC+"[C";break;case 38:if(m.metaKey)break;g?(E.key=f.C0.ESC+"[1;"+(g+1)+"A",C||E.key!==f.C0.ESC+"[1;3A"||(E.key=f.C0.ESC+"[1;5A")):E.key=y?f.C0.ESC+"OA":f.C0.ESC+"[A";break;case 40:if(m.metaKey)break;g?(E.key=f.C0.ESC+"[1;"+(g+1)+"B",C||E.key!==f.C0.ESC+"[1;3B"||(E.key=f.C0.ESC+"[1;5B")):E.key=y?f.C0.ESC+"OB":f.C0.ESC+"[B";break;case 45:m.shiftKey||m.ctrlKey||(E.key=f.C0.ESC+"[2~");break;case 46:E.key=g?f.C0.ESC+"[3;"+(g+1)+"~":f.C0.ESC+"[3~";break;case 36:E.key=g?f.C0.ESC+"[1;"+(g+1)+"H":y?f.C0.ESC+"OH":f.C0.ESC+"[H";break;case 35:E.key=g?f.C0.ESC+"[1;"+(g+1)+"F":y?f.C0.ESC+"OF":f.C0.ESC+"[F";break;case 33:m.shiftKey?E.type=2:m.ctrlKey?E.key=f.C0.ESC+"[5;"+(g+1)+"~":E.key=f.C0.ESC+"[5~";break;case 34:m.shiftKey?E.type=3:m.ctrlKey?E.key=f.C0.ESC+"[6;"+(g+1)+"~":E.key=f.C0.ESC+"[6~";break;case 112:E.key=g?f.C0.ESC+"[1;"+(g+1)+"P":f.C0.ESC+"OP";break;case 113:E.key=g?f.C0.ESC+"[1;"+(g+1)+"Q":f.C0.ESC+"OQ";break;case 114:E.key=g?f.C0.ESC+"[1;"+(g+1)+"R":f.C0.ESC+"OR";break;case 115:E.key=g?f.C0.ESC+"[1;"+(g+1)+"S":f.C0.ESC+"OS";break;case 116:E.key=g?f.C0.ESC+"[15;"+(g+1)+"~":f.C0.ESC+"[15~";break;case 117:E.key=g?f.C0.ESC+"[17;"+(g+1)+"~":f.C0.ESC+"[17~";break;case 118:E.key=g?f.C0.ESC+"[18;"+(g+1)+"~":f.C0.ESC+"[18~";break;case 119:E.key=g?f.C0.ESC+"[19;"+(g+1)+"~":f.C0.ESC+"[19~";break;case 120:E.key=g?f.C0.ESC+"[20;"+(g+1)+"~":f.C0.ESC+"[20~";break;case 121:E.key=g?f.C0.ESC+"[21;"+(g+1)+"~":f.C0.ESC+"[21~";break;case 122:E.key=g?f.C0.ESC+"[23;"+(g+1)+"~":f.C0.ESC+"[23~";break;case 123:E.key=g?f.C0.ESC+"[24;"+(g+1)+"~":f.C0.ESC+"[24~";break;default:if(!m.ctrlKey||m.shiftKey||m.altKey||m.metaKey)if(C&&!R||!m.altKey||m.metaKey)!C||m.altKey||m.ctrlKey||m.shiftKey||!m.metaKey?m.key&&!m.ctrlKey&&!m.altKey&&!m.metaKey&&m.keyCode>=48&&m.key.length===1?E.key=m.key:m.key&&m.ctrlKey&&(m.key==="_"&&(E.key=f.C0.US),m.key==="@"&&(E.key=f.C0.NUL)):m.keyCode===65&&(E.type=1);else{const b=v[m.keyCode],_=b?.[m.shiftKey?1:0];if(_)E.key=f.C0.ESC+_;else if(m.keyCode>=65&&m.keyCode<=90){const x=m.ctrlKey?m.keyCode-64:m.keyCode+32;let A=String.fromCharCode(x);m.shiftKey&&(A=A.toUpperCase()),E.key=f.C0.ESC+A}else if(m.keyCode===32)E.key=f.C0.ESC+(m.ctrlKey?f.C0.NUL:" ");else if(m.key==="Dead"&&m.code.startsWith("Key")){let x=m.code.slice(3,4);m.shiftKey||(x=x.toLowerCase()),E.key=f.C0.ESC+x,E.cancel=!0}}else m.keyCode>=65&&m.keyCode<=90?E.key=String.fromCharCode(m.keyCode-64):m.keyCode===32?E.key=f.C0.NUL:m.keyCode>=51&&m.keyCode<=55?E.key=String.fromCharCode(m.keyCode-51+27):m.keyCode===56?E.key=f.C0.DEL:m.keyCode===219?E.key=f.C0.ESC:m.keyCode===220?E.key=f.C0.FS:m.keyCode===221&&(E.key=f.C0.GS)}return E}},482:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Utf8ToUtf32=a.StringToUtf32=a.utf32ToString=a.stringFromCodePoint=void 0,a.stringFromCodePoint=function(c){return c>65535?(c-=65536,String.fromCharCode(55296+(c>>10))+String.fromCharCode(c%1024+56320)):String.fromCharCode(c)},a.utf32ToString=function(c,f=0,v=c.length){let m="";for(let y=f;y<v;++y){let C=c[y];C>65535?(C-=65536,m+=String.fromCharCode(55296+(C>>10))+String.fromCharCode(C%1024+56320)):m+=String.fromCharCode(C)}return m},a.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(c,f){const v=c.length;if(!v)return 0;let m=0,y=0;if(this._interim){const C=c.charCodeAt(y++);56320<=C&&C<=57343?f[m++]=1024*(this._interim-55296)+C-56320+65536:(f[m++]=this._interim,f[m++]=C),this._interim=0}for(let C=y;C<v;++C){const R=c.charCodeAt(C);if(55296<=R&&R<=56319){if(++C>=v)return this._interim=R,m;const E=c.charCodeAt(C);56320<=E&&E<=57343?f[m++]=1024*(R-55296)+E-56320+65536:(f[m++]=R,f[m++]=E)}else R!==65279&&(f[m++]=R)}return m}},a.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(c,f){const v=c.length;if(!v)return 0;let m,y,C,R,E=0,g=0,b=0;if(this.interim[0]){let A=!1,D=this.interim[0];D&=(224&D)==192?31:(240&D)==224?15:7;let N,O=0;for(;(N=63&this.interim[++O])&&O<4;)D<<=6,D|=N;const T=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,j=T-O;for(;b<j;){if(b>=v)return 0;if(N=c[b++],(192&N)!=128){b--,A=!0;break}this.interim[O++]=N,D<<=6,D|=63&N}A||(T===2?D<128?b--:f[E++]=D:T===3?D<2048||D>=55296&&D<=57343||D===65279||(f[E++]=D):D<65536||D>1114111||(f[E++]=D)),this.interim.fill(0)}const _=v-4;let x=b;for(;x<v;){for(;!(!(x<_)||128&(m=c[x])||128&(y=c[x+1])||128&(C=c[x+2])||128&(R=c[x+3]));)f[E++]=m,f[E++]=y,f[E++]=C,f[E++]=R,x+=4;if(m=c[x++],m<128)f[E++]=m;else if((224&m)==192){if(x>=v)return this.interim[0]=m,E;if(y=c[x++],(192&y)!=128){x--;continue}if(g=(31&m)<<6|63&y,g<128){x--;continue}f[E++]=g}else if((240&m)==224){if(x>=v)return this.interim[0]=m,E;if(y=c[x++],(192&y)!=128){x--;continue}if(x>=v)return this.interim[0]=m,this.interim[1]=y,E;if(C=c[x++],(192&C)!=128){x--;continue}if(g=(15&m)<<12|(63&y)<<6|63&C,g<2048||g>=55296&&g<=57343||g===65279)continue;f[E++]=g}else if((248&m)==240){if(x>=v)return this.interim[0]=m,E;if(y=c[x++],(192&y)!=128){x--;continue}if(x>=v)return this.interim[0]=m,this.interim[1]=y,E;if(C=c[x++],(192&C)!=128){x--;continue}if(x>=v)return this.interim[0]=m,this.interim[1]=y,this.interim[2]=C,E;if(R=c[x++],(192&R)!=128){x--;continue}if(g=(7&m)<<18|(63&y)<<12|(63&C)<<6|63&R,g<65536||g>1114111)continue;f[E++]=g}}return E}}},225:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeV6=void 0;const c=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],f=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let v;a.UnicodeV6=class{constructor(){if(this.version="6",!v){v=new Uint8Array(65536),v.fill(1),v[0]=0,v.fill(0,1,32),v.fill(0,127,160),v.fill(2,4352,4448),v[9001]=2,v[9002]=2,v.fill(2,11904,42192),v[12351]=1,v.fill(2,44032,55204),v.fill(2,63744,64256),v.fill(2,65040,65050),v.fill(2,65072,65136),v.fill(2,65280,65377),v.fill(2,65504,65511);for(let m=0;m<c.length;++m)v.fill(0,c[m][0],c[m][1]+1)}}wcwidth(m){return m<32?0:m<127?1:m<65536?v[m]:(function(y,C){let R,E=0,g=C.length-1;if(y<C[0][0]||y>C[g][1])return!1;for(;g>=E;)if(R=E+g>>1,y>C[R][1])E=R+1;else{if(!(y<C[R][0]))return!0;g=R-1}return!1})(m,f)?0:m>=131072&&m<=196605||m>=196608&&m<=262141?2:1}}},5981:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.WriteBuffer=void 0;const f=c(8460),v=c(844);class m extends v.Disposable{constructor(C){super(),this._action=C,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new f.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(C,R){if(R!==void 0&&this._syncCalls>R)return void(this._syncCalls=0);if(this._pendingData+=C.length,this._writeBuffer.push(C),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let E;for(this._isSyncWriting=!0;E=this._writeBuffer.shift();){this._action(E);const g=this._callbacks.shift();g&&g()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(C,R){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=C.length,this._writeBuffer.push(C),this._callbacks.push(R),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=C.length,this._writeBuffer.push(C),this._callbacks.push(R)}_innerWrite(C=0,R=!0){const E=C||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const g=this._writeBuffer[this._bufferOffset],b=this._action(g,R);if(b){const x=A=>Date.now()-E>=12?setTimeout((()=>this._innerWrite(0,A))):this._innerWrite(E,A);return void b.catch((A=>(queueMicrotask((()=>{throw A})),Promise.resolve(!1)))).then(x)}const _=this._callbacks[this._bufferOffset];if(_&&_(),this._bufferOffset++,this._pendingData-=g.length,Date.now()-E>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}a.WriteBuffer=m},5941:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.toRgbString=a.parseColor=void 0;const c=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,f=/^[\da-f]+$/;function v(m,y){const C=m.toString(16),R=C.length<2?"0"+C:C;switch(y){case 4:return C[0];case 8:return R;case 12:return(R+R).slice(0,3);default:return R+R}}a.parseColor=function(m){if(!m)return;let y=m.toLowerCase();if(y.indexOf("rgb:")===0){y=y.slice(4);const C=c.exec(y);if(C){const R=C[1]?15:C[4]?255:C[7]?4095:65535;return[Math.round(parseInt(C[1]||C[4]||C[7]||C[10],16)/R*255),Math.round(parseInt(C[2]||C[5]||C[8]||C[11],16)/R*255),Math.round(parseInt(C[3]||C[6]||C[9]||C[12],16)/R*255)]}}else if(y.indexOf("#")===0&&(y=y.slice(1),f.exec(y)&&[3,6,9,12].includes(y.length))){const C=y.length/3,R=[0,0,0];for(let E=0;E<3;++E){const g=parseInt(y.slice(C*E,C*E+C),16);R[E]=C===1?g<<4:C===2?g:C===3?g>>4:g>>8}return R}},a.toRgbString=function(m,y=16){const[C,R,E]=m;return`rgb:${v(C,y)}/${v(R,y)}/${v(E,y)}`}},5770:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.PAYLOAD_LIMIT=void 0,a.PAYLOAD_LIMIT=1e7},6351:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DcsHandler=a.DcsParser=void 0;const f=c(482),v=c(8742),m=c(5770),y=[];a.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=y,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=y}registerHandler(R,E){this._handlers[R]===void 0&&(this._handlers[R]=[]);const g=this._handlers[R];return g.push(E),{dispose:()=>{const b=g.indexOf(E);b!==-1&&g.splice(b,1)}}}clearHandler(R){this._handlers[R]&&delete this._handlers[R]}setHandlerFallback(R){this._handlerFb=R}reset(){if(this._active.length)for(let R=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;R>=0;--R)this._active[R].unhook(!1);this._stack.paused=!1,this._active=y,this._ident=0}hook(R,E){if(this.reset(),this._ident=R,this._active=this._handlers[R]||y,this._active.length)for(let g=this._active.length-1;g>=0;g--)this._active[g].hook(E);else this._handlerFb(this._ident,"HOOK",E)}put(R,E,g){if(this._active.length)for(let b=this._active.length-1;b>=0;b--)this._active[b].put(R,E,g);else this._handlerFb(this._ident,"PUT",(0,f.utf32ToString)(R,E,g))}unhook(R,E=!0){if(this._active.length){let g=!1,b=this._active.length-1,_=!1;if(this._stack.paused&&(b=this._stack.loopPosition-1,g=E,_=this._stack.fallThrough,this._stack.paused=!1),!_&&g===!1){for(;b>=0&&(g=this._active[b].unhook(R),g!==!0);b--)if(g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!1,g;b--}for(;b>=0;b--)if(g=this._active[b].unhook(!1),g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!0,g}else this._handlerFb(this._ident,"UNHOOK",R);this._active=y,this._ident=0}};const C=new v.Params;C.addParam(0),a.DcsHandler=class{constructor(R){this._handler=R,this._data="",this._params=C,this._hitLimit=!1}hook(R){this._params=R.length>1||R.params[0]?R.clone():C,this._data="",this._hitLimit=!1}put(R,E,g){this._hitLimit||(this._data+=(0,f.utf32ToString)(R,E,g),this._data.length>m.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(R){let E=!1;if(this._hitLimit)E=!1;else if(R&&(E=this._handler(this._data,this._params),E instanceof Promise))return E.then((g=>(this._params=C,this._data="",this._hitLimit=!1,g)));return this._params=C,this._data="",this._hitLimit=!1,E}}},2015:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.EscapeSequenceParser=a.VT500_TRANSITION_TABLE=a.TransitionTable=void 0;const f=c(844),v=c(8742),m=c(6242),y=c(6351);class C{constructor(b){this.table=new Uint8Array(b)}setDefault(b,_){this.table.fill(b<<4|_)}add(b,_,x,A){this.table[_<<8|b]=x<<4|A}addMany(b,_,x,A){for(let D=0;D<b.length;D++)this.table[_<<8|b[D]]=x<<4|A}}a.TransitionTable=C;const R=160;a.VT500_TRANSITION_TABLE=(function(){const g=new C(4095),b=Array.apply(null,Array(256)).map(((O,T)=>T)),_=(O,T)=>b.slice(O,T),x=_(32,127),A=_(0,24);A.push(25),A.push.apply(A,_(28,32));const D=_(0,14);let N;for(N in g.setDefault(1,0),g.addMany(x,0,2,0),D)g.addMany([24,26,153,154],N,3,0),g.addMany(_(128,144),N,3,0),g.addMany(_(144,152),N,3,0),g.add(156,N,0,0),g.add(27,N,11,1),g.add(157,N,4,8),g.addMany([152,158,159],N,0,7),g.add(155,N,11,3),g.add(144,N,11,9);return g.addMany(A,0,3,0),g.addMany(A,1,3,1),g.add(127,1,0,1),g.addMany(A,8,0,8),g.addMany(A,3,3,3),g.add(127,3,0,3),g.addMany(A,4,3,4),g.add(127,4,0,4),g.addMany(A,6,3,6),g.addMany(A,5,3,5),g.add(127,5,0,5),g.addMany(A,2,3,2),g.add(127,2,0,2),g.add(93,1,4,8),g.addMany(x,8,5,8),g.add(127,8,5,8),g.addMany([156,27,24,26,7],8,6,0),g.addMany(_(28,32),8,0,8),g.addMany([88,94,95],1,0,7),g.addMany(x,7,0,7),g.addMany(A,7,0,7),g.add(156,7,0,0),g.add(127,7,0,7),g.add(91,1,11,3),g.addMany(_(64,127),3,7,0),g.addMany(_(48,60),3,8,4),g.addMany([60,61,62,63],3,9,4),g.addMany(_(48,60),4,8,4),g.addMany(_(64,127),4,7,0),g.addMany([60,61,62,63],4,0,6),g.addMany(_(32,64),6,0,6),g.add(127,6,0,6),g.addMany(_(64,127),6,0,0),g.addMany(_(32,48),3,9,5),g.addMany(_(32,48),5,9,5),g.addMany(_(48,64),5,0,6),g.addMany(_(64,127),5,7,0),g.addMany(_(32,48),4,9,5),g.addMany(_(32,48),1,9,2),g.addMany(_(32,48),2,9,2),g.addMany(_(48,127),2,10,0),g.addMany(_(48,80),1,10,0),g.addMany(_(81,88),1,10,0),g.addMany([89,90,92],1,10,0),g.addMany(_(96,127),1,10,0),g.add(80,1,11,9),g.addMany(A,9,0,9),g.add(127,9,0,9),g.addMany(_(28,32),9,0,9),g.addMany(_(32,48),9,9,12),g.addMany(_(48,60),9,8,10),g.addMany([60,61,62,63],9,9,10),g.addMany(A,11,0,11),g.addMany(_(32,128),11,0,11),g.addMany(_(28,32),11,0,11),g.addMany(A,10,0,10),g.add(127,10,0,10),g.addMany(_(28,32),10,0,10),g.addMany(_(48,60),10,8,10),g.addMany([60,61,62,63],10,0,11),g.addMany(_(32,48),10,9,12),g.addMany(A,12,0,12),g.add(127,12,0,12),g.addMany(_(28,32),12,0,12),g.addMany(_(32,48),12,9,12),g.addMany(_(48,64),12,0,11),g.addMany(_(64,127),12,12,13),g.addMany(_(64,127),10,12,13),g.addMany(_(64,127),9,12,13),g.addMany(A,13,13,13),g.addMany(x,13,13,13),g.add(127,13,0,13),g.addMany([27,156,24,26],13,14,0),g.add(R,0,2,0),g.add(R,8,5,8),g.add(R,6,0,6),g.add(R,11,0,11),g.add(R,13,13,13),g})();class E extends f.Disposable{constructor(b=a.VT500_TRANSITION_TABLE){super(),this._transitions=b,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new v.Params,this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._printHandlerFb=(_,x,A)=>{},this._executeHandlerFb=_=>{},this._csiHandlerFb=(_,x)=>{},this._escHandlerFb=_=>{},this._errorHandlerFb=_=>_,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,f.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new m.OscParser),this._dcsParser=this.register(new y.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(b,_=[64,126]){let x=0;if(b.prefix){if(b.prefix.length>1)throw new Error("only one byte as prefix supported");if(x=b.prefix.charCodeAt(0),x&&60>x||x>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(b.intermediates){if(b.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let D=0;D<b.intermediates.length;++D){const N=b.intermediates.charCodeAt(D);if(32>N||N>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");x<<=8,x|=N}}if(b.final.length!==1)throw new Error("final must be a single byte");const A=b.final.charCodeAt(0);if(_[0]>A||A>_[1])throw new Error(`final must be in range ${_[0]} .. ${_[1]}`);return x<<=8,x|=A,x}identToString(b){const _=[];for(;b;)_.push(String.fromCharCode(255&b)),b>>=8;return _.reverse().join("")}setPrintHandler(b){this._printHandler=b}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(b,_){const x=this._identifier(b,[48,126]);this._escHandlers[x]===void 0&&(this._escHandlers[x]=[]);const A=this._escHandlers[x];return A.push(_),{dispose:()=>{const D=A.indexOf(_);D!==-1&&A.splice(D,1)}}}clearEscHandler(b){this._escHandlers[this._identifier(b,[48,126])]&&delete this._escHandlers[this._identifier(b,[48,126])]}setEscHandlerFallback(b){this._escHandlerFb=b}setExecuteHandler(b,_){this._executeHandlers[b.charCodeAt(0)]=_}clearExecuteHandler(b){this._executeHandlers[b.charCodeAt(0)]&&delete this._executeHandlers[b.charCodeAt(0)]}setExecuteHandlerFallback(b){this._executeHandlerFb=b}registerCsiHandler(b,_){const x=this._identifier(b);this._csiHandlers[x]===void 0&&(this._csiHandlers[x]=[]);const A=this._csiHandlers[x];return A.push(_),{dispose:()=>{const D=A.indexOf(_);D!==-1&&A.splice(D,1)}}}clearCsiHandler(b){this._csiHandlers[this._identifier(b)]&&delete this._csiHandlers[this._identifier(b)]}setCsiHandlerFallback(b){this._csiHandlerFb=b}registerDcsHandler(b,_){return this._dcsParser.registerHandler(this._identifier(b),_)}clearDcsHandler(b){this._dcsParser.clearHandler(this._identifier(b))}setDcsHandlerFallback(b){this._dcsParser.setHandlerFallback(b)}registerOscHandler(b,_){return this._oscParser.registerHandler(b,_)}clearOscHandler(b){this._oscParser.clearHandler(b)}setOscHandlerFallback(b){this._oscParser.setHandlerFallback(b)}setErrorHandler(b){this._errorHandler=b}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(b,_,x,A,D){this._parseStack.state=b,this._parseStack.handlers=_,this._parseStack.handlerPos=x,this._parseStack.transition=A,this._parseStack.chunkPos=D}parse(b,_,x){let A,D=0,N=0,O=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,O=this._parseStack.chunkPos+1;else{if(x===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const T=this._parseStack.handlers;let j=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(x===!1&&j>-1){for(;j>=0&&(A=T[j](this._params),A!==!0);j--)if(A instanceof Promise)return this._parseStack.handlerPos=j,A}this._parseStack.handlers=[];break;case 4:if(x===!1&&j>-1){for(;j>=0&&(A=T[j](),A!==!0);j--)if(A instanceof Promise)return this._parseStack.handlerPos=j,A}this._parseStack.handlers=[];break;case 6:if(D=b[this._parseStack.chunkPos],A=this._dcsParser.unhook(D!==24&&D!==26,x),A)return A;D===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(D=b[this._parseStack.chunkPos],A=this._oscParser.end(D!==24&&D!==26,x),A)return A;D===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,O=this._parseStack.chunkPos+1,this.precedingCodepoint=0,this.currentState=15&this._parseStack.transition}for(let T=O;T<_;++T){switch(D=b[T],N=this._transitions.table[this.currentState<<8|(D<160?D:R)],N>>4){case 2:for(let U=T+1;;++U){if(U>=_||(D=b[U])<32||D>126&&D<R){this._printHandler(b,T,U),T=U-1;break}if(++U>=_||(D=b[U])<32||D>126&&D<R){this._printHandler(b,T,U),T=U-1;break}if(++U>=_||(D=b[U])<32||D>126&&D<R){this._printHandler(b,T,U),T=U-1;break}if(++U>=_||(D=b[U])<32||D>126&&D<R){this._printHandler(b,T,U),T=U-1;break}}break;case 3:this._executeHandlers[D]?this._executeHandlers[D]():this._executeHandlerFb(D),this.precedingCodepoint=0;break;case 0:break;case 1:if(this._errorHandler({position:T,code:D,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const j=this._csiHandlers[this._collect<<8|D];let H=j?j.length-1:-1;for(;H>=0&&(A=j[H](this._params),A!==!0);H--)if(A instanceof Promise)return this._preserveStack(3,j,H,N,T),A;H<0&&this._csiHandlerFb(this._collect<<8|D,this._params),this.precedingCodepoint=0;break;case 8:do switch(D){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(D-48)}while(++T<_&&(D=b[T])>47&&D<60);T--;break;case 9:this._collect<<=8,this._collect|=D;break;case 10:const I=this._escHandlers[this._collect<<8|D];let z=I?I.length-1:-1;for(;z>=0&&(A=I[z](),A!==!0);z--)if(A instanceof Promise)return this._preserveStack(4,I,z,N,T),A;z<0&&this._escHandlerFb(this._collect<<8|D),this.precedingCodepoint=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|D,this._params);break;case 13:for(let U=T+1;;++U)if(U>=_||(D=b[U])===24||D===26||D===27||D>127&&D<R){this._dcsParser.put(b,T,U),T=U-1;break}break;case 14:if(A=this._dcsParser.unhook(D!==24&&D!==26),A)return this._preserveStack(6,[],0,N,T),A;D===27&&(N|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0;break;case 4:this._oscParser.start();break;case 5:for(let U=T+1;;U++)if(U>=_||(D=b[U])<32||D>127&&D<R){this._oscParser.put(b,T,U),T=U-1;break}break;case 6:if(A=this._oscParser.end(D!==24&&D!==26),A)return this._preserveStack(5,[],0,N,T),A;D===27&&(N|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0}this.currentState=15&N}}}a.EscapeSequenceParser=E},6242:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.OscHandler=a.OscParser=void 0;const f=c(5770),v=c(482),m=[];a.OscParser=class{constructor(){this._state=0,this._active=m,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(y,C){this._handlers[y]===void 0&&(this._handlers[y]=[]);const R=this._handlers[y];return R.push(C),{dispose:()=>{const E=R.indexOf(C);E!==-1&&R.splice(E,1)}}}clearHandler(y){this._handlers[y]&&delete this._handlers[y]}setHandlerFallback(y){this._handlerFb=y}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=m}reset(){if(this._state===2)for(let y=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;y>=0;--y)this._active[y].end(!1);this._stack.paused=!1,this._active=m,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||m,this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].start();else this._handlerFb(this._id,"START")}_put(y,C,R){if(this._active.length)for(let E=this._active.length-1;E>=0;E--)this._active[E].put(y,C,R);else this._handlerFb(this._id,"PUT",(0,v.utf32ToString)(y,C,R))}start(){this.reset(),this._state=1}put(y,C,R){if(this._state!==3){if(this._state===1)for(;C<R;){const E=y[C++];if(E===59){this._state=2,this._start();break}if(E<48||57<E)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+E-48}this._state===2&&R-C>0&&this._put(y,C,R)}}end(y,C=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let R=!1,E=this._active.length-1,g=!1;if(this._stack.paused&&(E=this._stack.loopPosition-1,R=C,g=this._stack.fallThrough,this._stack.paused=!1),!g&&R===!1){for(;E>=0&&(R=this._active[E].end(y),R!==!0);E--)if(R instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=E,this._stack.fallThrough=!1,R;E--}for(;E>=0;E--)if(R=this._active[E].end(!1),R instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=E,this._stack.fallThrough=!0,R}else this._handlerFb(this._id,"END",y);this._active=m,this._id=-1,this._state=0}}},a.OscHandler=class{constructor(y){this._handler=y,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(y,C,R){this._hitLimit||(this._data+=(0,v.utf32ToString)(y,C,R),this._data.length>f.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(y){let C=!1;if(this._hitLimit)C=!1;else if(y&&(C=this._handler(this._data),C instanceof Promise))return C.then((R=>(this._data="",this._hitLimit=!1,R)));return this._data="",this._hitLimit=!1,C}}},8742:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Params=void 0;const c=2147483647;class f{static fromArray(m){const y=new f;if(!m.length)return y;for(let C=Array.isArray(m[0])?1:0;C<m.length;++C){const R=m[C];if(Array.isArray(R))for(let E=0;E<R.length;++E)y.addSubParam(R[E]);else y.addParam(R)}return y}constructor(m=32,y=32){if(this.maxLength=m,this.maxSubParamsLength=y,y>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(m),this.length=0,this._subParams=new Int32Array(y),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(m),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const m=new f(this.maxLength,this.maxSubParamsLength);return m.params.set(this.params),m.length=this.length,m._subParams.set(this._subParams),m._subParamsLength=this._subParamsLength,m._subParamsIdx.set(this._subParamsIdx),m._rejectDigits=this._rejectDigits,m._rejectSubDigits=this._rejectSubDigits,m._digitIsSub=this._digitIsSub,m}toArray(){const m=[];for(let y=0;y<this.length;++y){m.push(this.params[y]);const C=this._subParamsIdx[y]>>8,R=255&this._subParamsIdx[y];R-C>0&&m.push(Array.prototype.slice.call(this._subParams,C,R))}return m}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(m){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(m<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=m>c?c:m}}addSubParam(m){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(m<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=m>c?c:m,this._subParamsIdx[this.length-1]++}}hasSubParams(m){return(255&this._subParamsIdx[m])-(this._subParamsIdx[m]>>8)>0}getSubParams(m){const y=this._subParamsIdx[m]>>8,C=255&this._subParamsIdx[m];return C-y>0?this._subParams.subarray(y,C):null}getSubParamsAll(){const m={};for(let y=0;y<this.length;++y){const C=this._subParamsIdx[y]>>8,R=255&this._subParamsIdx[y];R-C>0&&(m[y]=this._subParams.slice(C,R))}return m}addDigit(m){let y;if(this._rejectDigits||!(y=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const C=this._digitIsSub?this._subParams:this.params,R=C[y-1];C[y-1]=~R?Math.min(10*R+m,c):m}}a.Params=f},5741:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.AddonManager=void 0,a.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let c=this._addons.length-1;c>=0;c--)this._addons[c].instance.dispose()}loadAddon(c,f){const v={instance:f,dispose:f.dispose,isDisposed:!1};this._addons.push(v),f.dispose=()=>this._wrappedAddonDispose(v),f.activate(c)}_wrappedAddonDispose(c){if(c.isDisposed)return;let f=-1;for(let v=0;v<this._addons.length;v++)if(this._addons[v]===c){f=v;break}if(f===-1)throw new Error("Could not dispose an addon that has not been loaded");c.isDisposed=!0,c.dispose.apply(c.instance),this._addons.splice(f,1)}}},8771:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferApiView=void 0;const f=c(3785),v=c(511);a.BufferApiView=class{constructor(m,y){this._buffer=m,this.type=y}init(m){return this._buffer=m,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(m){const y=this._buffer.lines.get(m);if(y)return new f.BufferLineApiView(y)}getNullCell(){return new v.CellData}}},3785:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferLineApiView=void 0;const f=c(511);a.BufferLineApiView=class{constructor(v){this._line=v}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(v,m){if(!(v<0||v>=this._line.length))return m?(this._line.loadCell(v,m),m):this._line.loadCell(v,new f.CellData)}translateToString(v,m,y){return this._line.translateToString(v,m,y)}}},8285:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferNamespaceApi=void 0;const f=c(8771),v=c(8460),m=c(844);class y extends m.Disposable{constructor(R){super(),this._core=R,this._onBufferChange=this.register(new v.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new f.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new f.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}a.BufferNamespaceApi=y},7975:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ParserApi=void 0,a.ParserApi=class{constructor(c){this._core=c}registerCsiHandler(c,f){return this._core.registerCsiHandler(c,(v=>f(v.toArray())))}addCsiHandler(c,f){return this.registerCsiHandler(c,f)}registerDcsHandler(c,f){return this._core.registerDcsHandler(c,((v,m)=>f(v,m.toArray())))}addDcsHandler(c,f){return this.registerDcsHandler(c,f)}registerEscHandler(c,f){return this._core.registerEscHandler(c,f)}addEscHandler(c,f){return this.registerEscHandler(c,f)}registerOscHandler(c,f){return this._core.registerOscHandler(c,f)}addOscHandler(c,f){return this.registerOscHandler(c,f)}}},7090:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeApi=void 0,a.UnicodeApi=class{constructor(c){this._core=c}register(c){this._core.unicodeService.register(c)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(c){this._core.unicodeService.activeVersion=c}}},744:function(p,a,c){var f=this&&this.__decorate||function(g,b,_,x){var A,D=arguments.length,N=D<3?b:x===null?x=Object.getOwnPropertyDescriptor(b,_):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(g,b,_,x);else for(var O=g.length-1;O>=0;O--)(A=g[O])&&(N=(D<3?A(N):D>3?A(b,_,N):A(b,_))||N);return D>3&&N&&Object.defineProperty(b,_,N),N},v=this&&this.__param||function(g,b){return function(_,x){b(_,x,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.BufferService=a.MINIMUM_ROWS=a.MINIMUM_COLS=void 0;const m=c(8460),y=c(844),C=c(5295),R=c(2585);a.MINIMUM_COLS=2,a.MINIMUM_ROWS=1;let E=a.BufferService=class extends y.Disposable{get buffer(){return this.buffers.active}constructor(g){super(),this.isUserScrolling=!1,this._onResize=this.register(new m.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new m.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(g.rawOptions.cols||0,a.MINIMUM_COLS),this.rows=Math.max(g.rawOptions.rows||0,a.MINIMUM_ROWS),this.buffers=this.register(new C.BufferSet(g,this))}resize(g,b){this.cols=g,this.rows=b,this.buffers.resize(g,b),this._onResize.fire({cols:g,rows:b})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(g,b=!1){const _=this.buffer;let x;x=this._cachedBlankLine,x&&x.length===this.cols&&x.getFg(0)===g.fg&&x.getBg(0)===g.bg||(x=_.getBlankLine(g,b),this._cachedBlankLine=x),x.isWrapped=b;const A=_.ybase+_.scrollTop,D=_.ybase+_.scrollBottom;if(_.scrollTop===0){const N=_.lines.isFull;D===_.lines.length-1?N?_.lines.recycle().copyFrom(x):_.lines.push(x.clone()):_.lines.splice(D+1,0,x.clone()),N?this.isUserScrolling&&(_.ydisp=Math.max(_.ydisp-1,0)):(_.ybase++,this.isUserScrolling||_.ydisp++)}else{const N=D-A+1;_.lines.shiftElements(A+1,N-1,-1),_.lines.set(D,x.clone())}this.isUserScrolling||(_.ydisp=_.ybase),this._onScroll.fire(_.ydisp)}scrollLines(g,b,_){const x=this.buffer;if(g<0){if(x.ydisp===0)return;this.isUserScrolling=!0}else g+x.ydisp>=x.ybase&&(this.isUserScrolling=!1);const A=x.ydisp;x.ydisp=Math.max(Math.min(x.ydisp+g,x.ybase),0),A!==x.ydisp&&(b||this._onScroll.fire(x.ydisp))}};a.BufferService=E=f([v(0,R.IOptionsService)],E)},7994:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CharsetService=void 0,a.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(c){this.glevel=c,this.charset=this._charsets[c]}setgCharset(c,f){this._charsets[c]=f,this.glevel===c&&(this.charset=f)}}},1753:function(p,a,c){var f=this&&this.__decorate||function(x,A,D,N){var O,T=arguments.length,j=T<3?A:N===null?N=Object.getOwnPropertyDescriptor(A,D):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(x,A,D,N);else for(var H=x.length-1;H>=0;H--)(O=x[H])&&(j=(T<3?O(j):T>3?O(A,D,j):O(A,D))||j);return T>3&&j&&Object.defineProperty(A,D,j),j},v=this&&this.__param||function(x,A){return function(D,N){A(D,N,x)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreMouseService=void 0;const m=c(2585),y=c(8460),C=c(844),R={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:x=>x.button!==4&&x.action===1&&(x.ctrl=!1,x.alt=!1,x.shift=!1,!0)},VT200:{events:19,restrict:x=>x.action!==32},DRAG:{events:23,restrict:x=>x.action!==32||x.button!==3},ANY:{events:31,restrict:x=>!0}};function E(x,A){let D=(x.ctrl?16:0)|(x.shift?4:0)|(x.alt?8:0);return x.button===4?(D|=64,D|=x.action):(D|=3&x.button,4&x.button&&(D|=64),8&x.button&&(D|=128),x.action===32?D|=32:x.action!==0||A||(D|=3)),D}const g=String.fromCharCode,b={DEFAULT:x=>{const A=[E(x,!1)+32,x.col+32,x.row+32];return A[0]>255||A[1]>255||A[2]>255?"":`\x1B[M${g(A[0])}${g(A[1])}${g(A[2])}`},SGR:x=>{const A=x.action===0&&x.button!==4?"m":"M";return`\x1B[<${E(x,!0)};${x.col};${x.row}${A}`},SGR_PIXELS:x=>{const A=x.action===0&&x.button!==4?"m":"M";return`\x1B[<${E(x,!0)};${x.x};${x.y}${A}`}};let _=a.CoreMouseService=class extends C.Disposable{constructor(x,A){super(),this._bufferService=x,this._coreService=A,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new y.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const D of Object.keys(R))this.addProtocol(D,R[D]);for(const D of Object.keys(b))this.addEncoding(D,b[D]);this.reset()}addProtocol(x,A){this._protocols[x]=A}addEncoding(x,A){this._encodings[x]=A}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(x){if(!this._protocols[x])throw new Error(`unknown protocol "${x}"`);this._activeProtocol=x,this._onProtocolChange.fire(this._protocols[x].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(x){if(!this._encodings[x])throw new Error(`unknown encoding "${x}"`);this._activeEncoding=x}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(x){if(x.col<0||x.col>=this._bufferService.cols||x.row<0||x.row>=this._bufferService.rows||x.button===4&&x.action===32||x.button===3&&x.action!==32||x.button!==4&&(x.action===2||x.action===3)||(x.col++,x.row++,x.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,x,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(x))return!1;const A=this._encodings[this._activeEncoding](x);return A&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(A):this._coreService.triggerDataEvent(A,!0)),this._lastEvent=x,!0}explainEvents(x){return{down:!!(1&x),up:!!(2&x),drag:!!(4&x),move:!!(8&x),wheel:!!(16&x)}}_equalEvents(x,A,D){if(D){if(x.x!==A.x||x.y!==A.y)return!1}else if(x.col!==A.col||x.row!==A.row)return!1;return x.button===A.button&&x.action===A.action&&x.ctrl===A.ctrl&&x.alt===A.alt&&x.shift===A.shift}};a.CoreMouseService=_=f([v(0,m.IBufferService),v(1,m.ICoreService)],_)},6975:function(p,a,c){var f=this&&this.__decorate||function(_,x,A,D){var N,O=arguments.length,T=O<3?x:D===null?D=Object.getOwnPropertyDescriptor(x,A):D;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(_,x,A,D);else for(var j=_.length-1;j>=0;j--)(N=_[j])&&(T=(O<3?N(T):O>3?N(x,A,T):N(x,A))||T);return O>3&&T&&Object.defineProperty(x,A,T),T},v=this&&this.__param||function(_,x){return function(A,D){x(A,D,_)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreService=void 0;const m=c(1439),y=c(8460),C=c(844),R=c(2585),E=Object.freeze({insertMode:!1}),g=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let b=a.CoreService=class extends C.Disposable{constructor(_,x,A){super(),this._bufferService=_,this._logService=x,this._optionsService=A,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new y.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new y.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new y.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new y.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,m.clone)(E),this.decPrivateModes=(0,m.clone)(g)}reset(){this.modes=(0,m.clone)(E),this.decPrivateModes=(0,m.clone)(g)}triggerDataEvent(_,x=!1){if(this._optionsService.rawOptions.disableStdin)return;const A=this._bufferService.buffer;x&&this._optionsService.rawOptions.scrollOnUserInput&&A.ybase!==A.ydisp&&this._onRequestScrollToBottom.fire(),x&&this._onUserInput.fire(),this._logService.debug(`sending data "${_}"`,(()=>_.split("").map((D=>D.charCodeAt(0))))),this._onData.fire(_)}triggerBinaryEvent(_){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${_}"`,(()=>_.split("").map((x=>x.charCodeAt(0))))),this._onBinary.fire(_))}};a.CoreService=b=f([v(0,R.IBufferService),v(1,R.ILogService),v(2,R.IOptionsService)],b)},9074:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DecorationService=void 0;const f=c(8055),v=c(8460),m=c(844),y=c(6106);let C=0,R=0;class E extends m.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new y.SortedList((_=>_?.marker.line)),this._onDecorationRegistered=this.register(new v.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new v.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,m.toDisposable)((()=>this.reset())))}registerDecoration(_){if(_.marker.isDisposed)return;const x=new g(_);if(x){const A=x.marker.onDispose((()=>x.dispose()));x.onDispose((()=>{x&&(this._decorations.delete(x)&&this._onDecorationRemoved.fire(x),A.dispose())})),this._decorations.insert(x),this._onDecorationRegistered.fire(x)}return x}reset(){for(const _ of this._decorations.values())_.dispose();this._decorations.clear()}*getDecorationsAtCell(_,x,A){var D,N,O;let T=0,j=0;for(const H of this._decorations.getKeyIterator(x))T=(D=H.options.x)!==null&&D!==void 0?D:0,j=T+((N=H.options.width)!==null&&N!==void 0?N:1),_>=T&&_<j&&(!A||((O=H.options.layer)!==null&&O!==void 0?O:"bottom")===A)&&(yield H)}forEachDecorationAtCell(_,x,A,D){this._decorations.forEachByKey(x,(N=>{var O,T,j;C=(O=N.options.x)!==null&&O!==void 0?O:0,R=C+((T=N.options.width)!==null&&T!==void 0?T:1),_>=C&&_<R&&(!A||((j=N.options.layer)!==null&&j!==void 0?j:"bottom")===A)&&D(N)}))}}a.DecorationService=E;class g extends m.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=f.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=f.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(_){super(),this.options=_,this.onRenderEmitter=this.register(new v.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new v.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=_.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.InstantiationService=a.ServiceCollection=void 0;const f=c(2585),v=c(8343);class m{constructor(...C){this._entries=new Map;for(const[R,E]of C)this.set(R,E)}set(C,R){const E=this._entries.get(C);return this._entries.set(C,R),E}forEach(C){for(const[R,E]of this._entries.entries())C(R,E)}has(C){return this._entries.has(C)}get(C){return this._entries.get(C)}}a.ServiceCollection=m,a.InstantiationService=class{constructor(){this._services=new m,this._services.set(f.IInstantiationService,this)}setService(y,C){this._services.set(y,C)}getService(y){return this._services.get(y)}createInstance(y,...C){const R=(0,v.getServiceDependencies)(y).sort(((b,_)=>b.index-_.index)),E=[];for(const b of R){const _=this._services.get(b.id);if(!_)throw new Error(`[createInstance] ${y.name} depends on UNKNOWN service ${b.id}.`);E.push(_)}const g=R.length>0?R[0].index:C.length;if(C.length!==g)throw new Error(`[createInstance] First service dependency of ${y.name} at position ${g+1} conflicts with ${C.length} static arguments`);return new y(...C,...E)}}},7866:function(p,a,c){var f=this&&this.__decorate||function(g,b,_,x){var A,D=arguments.length,N=D<3?b:x===null?x=Object.getOwnPropertyDescriptor(b,_):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(g,b,_,x);else for(var O=g.length-1;O>=0;O--)(A=g[O])&&(N=(D<3?A(N):D>3?A(b,_,N):A(b,_))||N);return D>3&&N&&Object.defineProperty(b,_,N),N},v=this&&this.__param||function(g,b){return function(_,x){b(_,x,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.traceCall=a.setTraceLogger=a.LogService=void 0;const m=c(844),y=c(2585),C={trace:y.LogLevelEnum.TRACE,debug:y.LogLevelEnum.DEBUG,info:y.LogLevelEnum.INFO,warn:y.LogLevelEnum.WARN,error:y.LogLevelEnum.ERROR,off:y.LogLevelEnum.OFF};let R,E=a.LogService=class extends m.Disposable{get logLevel(){return this._logLevel}constructor(g){super(),this._optionsService=g,this._logLevel=y.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),R=this}_updateLogLevel(){this._logLevel=C[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(g){for(let b=0;b<g.length;b++)typeof g[b]=="function"&&(g[b]=g[b]())}_log(g,b,_){this._evalLazyOptionalParams(_),g.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+b,..._)}trace(g,...b){var _,x;this._logLevel<=y.LogLevelEnum.TRACE&&this._log((x=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.trace.bind(this._optionsService.options.logger))!==null&&x!==void 0?x:console.log,g,b)}debug(g,...b){var _,x;this._logLevel<=y.LogLevelEnum.DEBUG&&this._log((x=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.debug.bind(this._optionsService.options.logger))!==null&&x!==void 0?x:console.log,g,b)}info(g,...b){var _,x;this._logLevel<=y.LogLevelEnum.INFO&&this._log((x=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.info.bind(this._optionsService.options.logger))!==null&&x!==void 0?x:console.info,g,b)}warn(g,...b){var _,x;this._logLevel<=y.LogLevelEnum.WARN&&this._log((x=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.warn.bind(this._optionsService.options.logger))!==null&&x!==void 0?x:console.warn,g,b)}error(g,...b){var _,x;this._logLevel<=y.LogLevelEnum.ERROR&&this._log((x=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.error.bind(this._optionsService.options.logger))!==null&&x!==void 0?x:console.error,g,b)}};a.LogService=E=f([v(0,y.IOptionsService)],E),a.setTraceLogger=function(g){R=g},a.traceCall=function(g,b,_){if(typeof _.value!="function")throw new Error("not supported");const x=_.value;_.value=function(...A){if(R.logLevel!==y.LogLevelEnum.TRACE)return x.apply(this,A);R.trace(`GlyphRenderer#${x.name}(${A.map((N=>JSON.stringify(N))).join(", ")})`);const D=x.apply(this,A);return R.trace(`GlyphRenderer#${x.name} return`,D),D}}},7302:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.OptionsService=a.DEFAULT_OPTIONS=void 0;const f=c(8460),v=c(844),m=c(6114);a.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:m.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const y=["normal","bold","100","200","300","400","500","600","700","800","900"];class C extends v.Disposable{constructor(E){super(),this._onOptionChange=this.register(new f.EventEmitter),this.onOptionChange=this._onOptionChange.event;const g=Object.assign({},a.DEFAULT_OPTIONS);for(const b in E)if(b in g)try{const _=E[b];g[b]=this._sanitizeAndValidateOption(b,_)}catch(_){console.error(_)}this.rawOptions=g,this.options=Object.assign({},g),this._setupOptions()}onSpecificOptionChange(E,g){return this.onOptionChange((b=>{b===E&&g(this.rawOptions[E])}))}onMultipleOptionChange(E,g){return this.onOptionChange((b=>{E.indexOf(b)!==-1&&g()}))}_setupOptions(){const E=b=>{if(!(b in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${b}"`);return this.rawOptions[b]},g=(b,_)=>{if(!(b in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${b}"`);_=this._sanitizeAndValidateOption(b,_),this.rawOptions[b]!==_&&(this.rawOptions[b]=_,this._onOptionChange.fire(b))};for(const b in this.rawOptions){const _={get:E.bind(this,b),set:g.bind(this,b)};Object.defineProperty(this.options,b,_)}}_sanitizeAndValidateOption(E,g){switch(E){case"cursorStyle":if(g||(g=a.DEFAULT_OPTIONS[E]),!(function(b){return b==="block"||b==="underline"||b==="bar"})(g))throw new Error(`"${g}" is not a valid value for ${E}`);break;case"wordSeparator":g||(g=a.DEFAULT_OPTIONS[E]);break;case"fontWeight":case"fontWeightBold":if(typeof g=="number"&&1<=g&&g<=1e3)break;g=y.includes(g)?g:a.DEFAULT_OPTIONS[E];break;case"cursorWidth":g=Math.floor(g);case"lineHeight":case"tabStopWidth":if(g<1)throw new Error(`${E} cannot be less than 1, value: ${g}`);break;case"minimumContrastRatio":g=Math.max(1,Math.min(21,Math.round(10*g)/10));break;case"scrollback":if((g=Math.min(g,4294967295))<0)throw new Error(`${E} cannot be less than 0, value: ${g}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(g<=0)throw new Error(`${E} cannot be less than or equal to 0, value: ${g}`);break;case"rows":case"cols":if(!g&&g!==0)throw new Error(`${E} must be numeric, value: ${g}`);break;case"windowsPty":g=g??{}}return g}}a.OptionsService=C},2660:function(p,a,c){var f=this&&this.__decorate||function(C,R,E,g){var b,_=arguments.length,x=_<3?R:g===null?g=Object.getOwnPropertyDescriptor(R,E):g;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(C,R,E,g);else for(var A=C.length-1;A>=0;A--)(b=C[A])&&(x=(_<3?b(x):_>3?b(R,E,x):b(R,E))||x);return _>3&&x&&Object.defineProperty(R,E,x),x},v=this&&this.__param||function(C,R){return function(E,g){R(E,g,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkService=void 0;const m=c(2585);let y=a.OscLinkService=class{constructor(C){this._bufferService=C,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(C){const R=this._bufferService.buffer;if(C.id===void 0){const A=R.addMarker(R.ybase+R.y),D={data:C,id:this._nextId++,lines:[A]};return A.onDispose((()=>this._removeMarkerFromLink(D,A))),this._dataByLinkId.set(D.id,D),D.id}const E=C,g=this._getEntryIdKey(E),b=this._entriesWithId.get(g);if(b)return this.addLineToLink(b.id,R.ybase+R.y),b.id;const _=R.addMarker(R.ybase+R.y),x={id:this._nextId++,key:this._getEntryIdKey(E),data:E,lines:[_]};return _.onDispose((()=>this._removeMarkerFromLink(x,_))),this._entriesWithId.set(x.key,x),this._dataByLinkId.set(x.id,x),x.id}addLineToLink(C,R){const E=this._dataByLinkId.get(C);if(E&&E.lines.every((g=>g.line!==R))){const g=this._bufferService.buffer.addMarker(R);E.lines.push(g),g.onDispose((()=>this._removeMarkerFromLink(E,g)))}}getLinkData(C){var R;return(R=this._dataByLinkId.get(C))===null||R===void 0?void 0:R.data}_getEntryIdKey(C){return`${C.id};;${C.uri}`}_removeMarkerFromLink(C,R){const E=C.lines.indexOf(R);E!==-1&&(C.lines.splice(E,1),C.lines.length===0&&(C.data.id!==void 0&&this._entriesWithId.delete(C.key),this._dataByLinkId.delete(C.id)))}};a.OscLinkService=y=f([v(0,m.IBufferService)],y)},8343:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.createDecorator=a.getServiceDependencies=a.serviceRegistry=void 0;const c="di$target",f="di$dependencies";a.serviceRegistry=new Map,a.getServiceDependencies=function(v){return v[f]||[]},a.createDecorator=function(v){if(a.serviceRegistry.has(v))return a.serviceRegistry.get(v);const m=function(y,C,R){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(E,g,b){g[c]===g?g[f].push({id:E,index:b}):(g[f]=[{id:E,index:b}],g[c]=g)})(m,y,R)};return m.toString=()=>v,a.serviceRegistry.set(v,m),m}},2585:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.IDecorationService=a.IUnicodeService=a.IOscLinkService=a.IOptionsService=a.ILogService=a.LogLevelEnum=a.IInstantiationService=a.ICharsetService=a.ICoreService=a.ICoreMouseService=a.IBufferService=void 0;const f=c(8343);var v;a.IBufferService=(0,f.createDecorator)("BufferService"),a.ICoreMouseService=(0,f.createDecorator)("CoreMouseService"),a.ICoreService=(0,f.createDecorator)("CoreService"),a.ICharsetService=(0,f.createDecorator)("CharsetService"),a.IInstantiationService=(0,f.createDecorator)("InstantiationService"),(function(m){m[m.TRACE=0]="TRACE",m[m.DEBUG=1]="DEBUG",m[m.INFO=2]="INFO",m[m.WARN=3]="WARN",m[m.ERROR=4]="ERROR",m[m.OFF=5]="OFF"})(v||(a.LogLevelEnum=v={})),a.ILogService=(0,f.createDecorator)("LogService"),a.IOptionsService=(0,f.createDecorator)("OptionsService"),a.IOscLinkService=(0,f.createDecorator)("OscLinkService"),a.IUnicodeService=(0,f.createDecorator)("UnicodeService"),a.IDecorationService=(0,f.createDecorator)("DecorationService")},1480:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeService=void 0;const f=c(8460),v=c(225);a.UnicodeService=class{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new f.EventEmitter,this.onChange=this._onChange.event;const m=new v.UnicodeV6;this.register(m),this._active=m.version,this._activeProvider=m}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(m){if(!this._providers[m])throw new Error(`unknown Unicode version "${m}"`);this._active=m,this._activeProvider=this._providers[m],this._onChange.fire(m)}register(m){this._providers[m.version]=m}wcwidth(m){return this._activeProvider.wcwidth(m)}getStringCellWidth(m){let y=0;const C=m.length;for(let R=0;R<C;++R){let E=m.charCodeAt(R);if(55296<=E&&E<=56319){if(++R>=C)return y+this.wcwidth(E);const g=m.charCodeAt(R);56320<=g&&g<=57343?E=1024*(E-55296)+g-56320+65536:y+=this.wcwidth(g)}y+=this.wcwidth(E)}return y}}}},r={};function l(p){var a=r[p];if(a!==void 0)return a.exports;var c=r[p]={exports:{}};return n[p].call(c.exports,c,c.exports,l),c.exports}var u={};return(()=>{var p=u;Object.defineProperty(p,"__esModule",{value:!0}),p.Terminal=void 0;const a=l(9042),c=l(3236),f=l(844),v=l(5741),m=l(8285),y=l(7975),C=l(7090),R=["cols","rows"];class E extends f.Disposable{constructor(b){super(),this._core=this.register(new c.Terminal(b)),this._addonManager=this.register(new v.AddonManager),this._publicOptions=Object.assign({},this._core.options);const _=A=>this._core.options[A],x=(A,D)=>{this._checkReadonlyOptions(A),this._core.options[A]=D};for(const A in this._core.options){const D={get:_.bind(this,A),set:x.bind(this,A)};Object.defineProperty(this._publicOptions,A,D)}}_checkReadonlyOptions(b){if(R.includes(b))throw new Error(`Option "${b}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new y.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new C.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new m.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const b=this._core.coreService.decPrivateModes;let _="none";switch(this._core.coreMouseService.activeProtocol){case"X10":_="x10";break;case"VT200":_="vt200";break;case"DRAG":_="drag";break;case"ANY":_="any"}return{applicationCursorKeysMode:b.applicationCursorKeys,applicationKeypadMode:b.applicationKeypad,bracketedPasteMode:b.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:_,originMode:b.origin,reverseWraparoundMode:b.reverseWraparound,sendFocusMode:b.sendFocus,wraparoundMode:b.wraparound}}get options(){return this._publicOptions}set options(b){for(const _ in b)this._publicOptions[_]=b[_]}blur(){this._core.blur()}focus(){this._core.focus()}resize(b,_){this._verifyIntegers(b,_),this._core.resize(b,_)}open(b){this._core.open(b)}attachCustomKeyEventHandler(b){this._core.attachCustomKeyEventHandler(b)}registerLinkProvider(b){return this._core.registerLinkProvider(b)}registerCharacterJoiner(b){return this._checkProposedApi(),this._core.registerCharacterJoiner(b)}deregisterCharacterJoiner(b){this._checkProposedApi(),this._core.deregisterCharacterJoiner(b)}registerMarker(b=0){return this._verifyIntegers(b),this._core.registerMarker(b)}registerDecoration(b){var _,x,A;return this._checkProposedApi(),this._verifyPositiveIntegers((_=b.x)!==null&&_!==void 0?_:0,(x=b.width)!==null&&x!==void 0?x:0,(A=b.height)!==null&&A!==void 0?A:0),this._core.registerDecoration(b)}hasSelection(){return this._core.hasSelection()}select(b,_,x){this._verifyIntegers(b,_,x),this._core.select(b,_,x)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(b,_){this._verifyIntegers(b,_),this._core.selectLines(b,_)}dispose(){super.dispose()}scrollLines(b){this._verifyIntegers(b),this._core.scrollLines(b)}scrollPages(b){this._verifyIntegers(b),this._core.scrollPages(b)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(b){this._verifyIntegers(b),this._core.scrollToLine(b)}clear(){this._core.clear()}write(b,_){this._core.write(b,_)}writeln(b,_){this._core.write(b),this._core.write(`\r
90
- `,_)}paste(b){this._core.paste(b)}refresh(b,_){this._verifyIntegers(b,_),this._core.refresh(b,_)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(b){this._addonManager.loadAddon(this,b)}static get strings(){return a}_verifyIntegers(...b){for(const _ of b)if(_===1/0||isNaN(_)||_%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...b){for(const _ of b)if(_&&(_===1/0||isNaN(_)||_%1!=0||_<0))throw new Error("This API only accepts positive integers")}}p.Terminal=E})(),u})()))})(ff)),ff.exports}var Iz=Bz(),pf={exports:{}},r0;function Hz(){return r0||(r0=1,(function(i,e){(function(n,r){i.exports=r()})(self,(()=>(()=>{var n={};return(()=>{var r=n;Object.defineProperty(r,"__esModule",{value:!0}),r.FitAddon=void 0,r.FitAddon=class{activate(l){this._terminal=l}dispose(){}fit(){const l=this.proposeDimensions();if(!l||!this._terminal||isNaN(l.cols)||isNaN(l.rows))return;const u=this._terminal._core;this._terminal.rows===l.rows&&this._terminal.cols===l.cols||(u._renderService.clear(),this._terminal.resize(l.cols,l.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const l=this._terminal._core,u=l._renderService.dimensions;if(u.css.cell.width===0||u.css.cell.height===0)return;const p=this._terminal.options.scrollback===0?0:l.viewport.scrollBarWidth,a=window.getComputedStyle(this._terminal.element.parentElement),c=parseInt(a.getPropertyValue("height")),f=Math.max(0,parseInt(a.getPropertyValue("width"))),v=window.getComputedStyle(this._terminal.element),m=c-(parseInt(v.getPropertyValue("padding-top"))+parseInt(v.getPropertyValue("padding-bottom"))),y=f-(parseInt(v.getPropertyValue("padding-right"))+parseInt(v.getPropertyValue("padding-left")))-p;return{cols:Math.max(2,Math.floor(y/u.css.cell.width)),rows:Math.max(1,Math.floor(m/u.css.cell.height))}}}})(),n})()))})(pf)),pf.exports}var Fz=Hz();function kE({projectRoot:i}){const e=S.useRef(null),n=S.useRef(null),r=S.useRef(null),l=S.useRef(null),u=S.useRef(null),p=S.useRef(null),[a,c]=S.useState("connecting"),[f,v]=S.useState(null),m=S.useCallback(()=>`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/pty`,[]),y=S.useCallback(()=>{const E=l.current;if(!E||E.readyState!==WebSocket.OPEN)return;c("connecting"),v(null);const g=r.current,b=g?Math.max(g.proposeDimensions()?.cols??80,1):80,_=g?Math.max(g.proposeDimensions()?.rows??24,1):24;E.send(JSON.stringify({type:"spawn",cwd:i,cols:b,rows:_}))},[i]),C=S.useCallback(()=>{n.current?.clear(),n.current?.reset(),y()},[y]);S.useEffect(()=>{if(!e.current)return;const E=new Iz.Terminal({allowProposedApi:!0,allowTransparency:!1,fontFamily:'Menlo, Monaco, "Courier New", monospace',fontSize:14,scrollback:5e3,cursorBlink:!0,theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",cursorAccent:"#1e1e1e"}}),g=new Fz.FitAddon;E.loadAddon(g),n.current=E,r.current=g,E.open(e.current),setTimeout(()=>{g.fit(),E.focus()},0);const b=m(),_=new WebSocket(b);l.current=_,_.onopen=()=>{const N=Math.max(g.proposeDimensions()?.cols??80,1),O=Math.max(g.proposeDimensions()?.rows??24,1);_.send(JSON.stringify({type:"spawn",cwd:i,cols:N,rows:O}))},_.onmessage=N=>{try{const O=JSON.parse(N.data);O.type==="data"?E.write(O.data):O.type==="spawn"?c("connected"):O.type==="exit"?c("exited"):O.type==="error"&&(c("error"),v(O.error))}catch{E.write(N.data)}},_.onerror=()=>{c("error"),v("WebSocket connection failed")},_.onclose=()=>{a==="connected"&&c("exited")};const x=E.onData(N=>{_.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"data",data:N}))}),A=E.onResize(({cols:N,rows:O})=>{_.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"resize",cols:N,rows:O}))}),D=new ResizeObserver(()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{r.current?.fit()},100)});return D.observe(e.current),u.current=D,()=>{p.current&&clearTimeout(p.current),u.current?.disconnect(),_.readyState===WebSocket.OPEN&&(_.send(JSON.stringify({type:"kill"})),_.close()),l.current=null,x.dispose(),A.dispose(),E.dispose()}},[m,i]);const R=()=>a==="error"?d.jsx("div",{className:"tty-overlay","data-testid":"tty-error",children:d.jsxs("div",{className:"tty-overlay-content",children:[d.jsx("span",{className:"tty-overlay-icon",children:"⚠️"}),d.jsxs("span",{className:"tty-overlay-message",children:["Failed to spawn shell: ",f]}),d.jsx(De,{variant:"outline",size:"sm",className:"tty-restart-button",onClick:C,"aria-label":"Restart terminal",children:"Restart"})]})}):a==="exited"?d.jsx("div",{className:"tty-overlay","data-testid":"tty-exited",children:d.jsxs("div",{className:"tty-overlay-content",children:[d.jsx("span",{className:"tty-overlay-icon",children:"✓"}),d.jsx("span",{className:"tty-overlay-message",children:"Process ended"}),d.jsx(De,{variant:"outline",size:"sm",className:"tty-restart-button",onClick:C,"aria-label":"New session",children:"New Session"})]})}):null;return d.jsxs("div",{className:"tty-panel","data-testid":"tty-panel",role:"region","aria-label":"Terminal","aria-describedby":"tty-keyboard-help",children:[d.jsx("span",{id:"tty-keyboard-help",className:"sr-only",children:"Terminal panel. Use keyboard to interact with the shell."}),d.jsxs("div",{"data-testid":"tty-status","aria-live":"polite",className:"sr-only",children:[a==="connecting"&&"Connecting to terminal...",a==="connected"&&"Terminal connected",a==="error"&&`Terminal error: ${f}`,a==="exited"&&"Terminal session ended"]}),d.jsx("div",{ref:e,className:"tty-terminal-container","data-testid":"tty-terminal-container",style:{height:"100%",width:"100%"}}),R()]})}function Gz(i){return i?["tdd","bdd"].includes(i.toLowerCase())?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):"—"}function TE(i){switch(i){case"done":return"✓";case"current":return"●";default:return"○"}}function Uz({phase:i,isLast:e}){const n=TE(i.status),r=`phase-step ${i.status}`;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:r,children:[d.jsx("span",{className:"phase-icon",children:n}),d.jsx("span",{className:"phase-label",children:i.label})]}),!e&&d.jsx("span",{className:"phase-arrow",children:"→"})]})}function Wz({entry:i}){const e=TE(i.status),n=`phase-history-item ${i.status}`,r=i.status==="current"?"in progress":i.status==="pending"?"pending":i.duration||"—";return d.jsxs("div",{className:n,children:[d.jsx("span",{className:"history-icon",children:e}),d.jsx("span",{className:"history-phase",children:i.phase.toUpperCase()}),d.jsx("span",{className:"history-agent",children:i.agent}),d.jsx("span",{className:"history-duration",children:r})]})}function Vz({workflowType:i,phases:e,phaseHistory:n,collapsed:r=!1,onToggle:l}){if(!i&&(!e||e.length===0))return d.jsx("div",{className:"bikelane-panel empty hidden","data-testid":"bikelane-panel",children:d.jsx("div",{className:"placeholder",children:"No active workflow"})});const u=Gz(i);return r?d.jsx("div",{className:"bikelane-panel collapsed","data-testid":"bikelane-panel",children:d.jsxs("div",{className:"bikelane-header",onClick:l,children:[d.jsx(Ke,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":i||"",children:u}),d.jsx("span",{className:"bikelane-expand",children:"▶"})]})}):d.jsxs("div",{className:"bikelane-panel","data-testid":"bikelane-panel",children:[d.jsxs("div",{className:"bikelane-header",onClick:l,children:[d.jsx(Ke,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":i||"",children:u}),l&&d.jsx("span",{className:"bikelane-expand",children:"▼"})]}),e&&e.length>0&&d.jsx("div",{className:"phase-progress",children:e.map((p,a)=>d.jsx(Uz,{phase:p,isLast:a===e.length-1},p.name))}),n&&n.length>0&&d.jsx("div",{className:"phase-history",children:d.jsx("div",{className:"phase-history-list",children:n.map((p,a)=>d.jsx(Wz,{entry:p},a))})})]})}const $z={sprint:lx,git:dx,diffs:Hx,todos:px,workflow:hx,background:mx,audit:DE,changed:Ix,ac:fx,tty:kE,debug:yC,bikelane:Vz,settings:EE};function RE(){return new URLSearchParams(window.location.search).get("panel")}function qz(){const i=RE(),e=i?$z[i]:null;return e?d.jsx("div",{style:{height:"100vh",width:"100vw",overflow:"auto",backgroundColor:"var(--bg-primary, #1a1a2e)",color:"var(--text-primary, #e4e4e7)"},children:d.jsx(e,{})}):d.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"var(--bg-primary, #1a1a2e)",color:"var(--text-primary, #e4e4e7)"},children:[d.jsx("h1",{children:"Panel not found"}),d.jsx("p",{children:d.jsx("a",{href:"/bikerack",style:{color:"var(--accent, #818cf8)"},children:"Back to BikeRack"})})]})}const Fs=["sprint","git","diffs","todo","workflow","background","audit-log","changed","ac","debug"],Zf={sprint:"Sprint",git:"Git",diffs:"Diffs",todo:"Todo",workflow:"Workflow",background:"Subagents","audit-log":"Audit Log",changed:"Changed",ac:"AC",debug:"Debug"};function Yz({params:i}){const e=ga.get(i.panelId);return e?d.jsx("div",{"data-testid":`panel-${i.panelId}`,className:"dockview-panel-content",children:d.jsx(Dp,{panelName:i.panelId,children:d.jsx("div",{className:"error-boundary-wrapper",children:d.jsx(e,{})})})}):d.jsx("div",{"data-testid":`panel-${i.panelId}`,className:"dockview-panel-content",children:d.jsx("div",{style:{padding:"16px",color:"var(--text-secondary, #94a3b8)"},children:Zf[i.panelId]||i.panelId})})}function Kz(){const i=S.useRef(null),e=S.useCallback(r=>{const l=r.api;i.current=l;const u=l.addPanel({id:Fs[0],component:"PanelAdapter",params:{panelId:Fs[0]},title:Zf[Fs[0]]});for(let p=1;p<Fs.length;p++)l.addPanel({id:Fs[p],component:"PanelAdapter",params:{panelId:Fs[p]},position:{referencePanel:u.id},title:Zf[Fs[p]]})},[]),n={PanelAdapter:Yz};return d.jsxs("div",{className:"cyclist-app cyclist-dockview",style:{height:"100vh",width:"100vw",display:"flex",flexDirection:"column"},children:[d.jsx("div",{"data-testid":"bikerack-portrait-anchor",style:{flexShrink:0},children:d.jsx(ox,{})}),d.jsx("div",{className:"flex-1",style:{flexGrow:1,minHeight:0},children:d.jsx(Ep,{className:"dockview-container",onReady:e,components:n,watermarkComponent:()=>null})})]})}var wu="Checkbox",[Xz]=pi(wu),[Zz,lm]=Xz(wu);function Jz(i){const{__scopeCheckbox:e,checked:n,children:r,defaultChecked:l,disabled:u,form:p,name:a,onCheckedChange:c,required:f,value:v="on",internal_do_not_use_render:m}=i,[y,C]=Ni({prop:n,defaultProp:l??!1,onChange:c,caller:wu}),[R,E]=S.useState(null),[g,b]=S.useState(null),_=S.useRef(!1),x=R?!!p||!!R.closest("form"):!0,A={checked:y,disabled:u,setChecked:C,control:R,setControl:E,name:a,form:p,value:v,hasConsumerStoppedPropagationRef:_,required:f,defaultChecked:as(l)?!1:l,isFormControl:x,bubbleInput:g,setBubbleInput:b};return d.jsx(Zz,{scope:e,...A,children:Qz(m)?m(A):r})}var NE="CheckboxTrigger",OE=S.forwardRef(({__scopeCheckbox:i,onKeyDown:e,onClick:n,...r},l)=>{const{control:u,value:p,disabled:a,checked:c,required:f,setControl:v,setChecked:m,hasConsumerStoppedPropagationRef:y,isFormControl:C,bubbleInput:R}=lm(NE,i),E=Ge(l,v),g=S.useRef(c);return S.useEffect(()=>{const b=u?.form;if(b){const _=()=>m(g.current);return b.addEventListener("reset",_),()=>b.removeEventListener("reset",_)}},[u,m]),d.jsx(Ne.button,{type:"button",role:"checkbox","aria-checked":as(c)?"mixed":c,"aria-required":f,"data-state":zE(c),"data-disabled":a?"":void 0,disabled:a,value:p,...r,ref:E,onKeyDown:Ee(e,b=>{b.key==="Enter"&&b.preventDefault()}),onClick:Ee(n,b=>{m(_=>as(_)?!0:!_),R&&C&&(y.current=b.isPropagationStopped(),y.current||b.stopPropagation())})})});OE.displayName=NE;var cm=S.forwardRef((i,e)=>{const{__scopeCheckbox:n,name:r,checked:l,defaultChecked:u,required:p,disabled:a,value:c,onCheckedChange:f,form:v,...m}=i;return d.jsx(Jz,{__scopeCheckbox:n,checked:l,defaultChecked:u,disabled:a,required:p,onCheckedChange:f,name:r,form:v,value:c,internal_do_not_use_render:({isFormControl:y})=>d.jsxs(d.Fragment,{children:[d.jsx(OE,{...m,ref:e,__scopeCheckbox:n}),y&&d.jsx(PE,{__scopeCheckbox:n})]})})});cm.displayName=wu;var jE="CheckboxIndicator",ME=S.forwardRef((i,e)=>{const{__scopeCheckbox:n,forceMount:r,...l}=i,u=lm(jE,n);return d.jsx(Qt,{present:r||as(u.checked)||u.checked===!0,children:d.jsx(Ne.span,{"data-state":zE(u.checked),"data-disabled":u.disabled?"":void 0,...l,ref:e,style:{pointerEvents:"none",...i.style}})})});ME.displayName=jE;var LE="CheckboxBubbleInput",PE=S.forwardRef(({__scopeCheckbox:i,...e},n)=>{const{control:r,hasConsumerStoppedPropagationRef:l,checked:u,defaultChecked:p,required:a,disabled:c,name:f,value:v,form:m,bubbleInput:y,setBubbleInput:C}=lm(LE,i),R=Ge(n,C),E=sm(u),g=lp(r);S.useEffect(()=>{const _=y;if(!_)return;const x=window.HTMLInputElement.prototype,D=Object.getOwnPropertyDescriptor(x,"checked").set,N=!l.current;if(E!==u&&D){const O=new Event("click",{bubbles:N});_.indeterminate=as(u),D.call(_,as(u)?!1:u),_.dispatchEvent(O)}},[y,E,u,l]);const b=S.useRef(as(u)?!1:u);return d.jsx(Ne.input,{type:"checkbox","aria-hidden":!0,defaultChecked:p??b.current,required:a,disabled:c,name:f,value:v,form:m,...e,tabIndex:-1,ref:R,style:{...e.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});PE.displayName=LE;function Qz(i){return typeof i=="function"}function as(i){return i==="indeterminate"}function zE(i){return as(i)?"indeterminate":i?"checked":"unchecked"}const BE=S.forwardRef(({className:i,...e},n)=>d.jsx(cm,{ref:n,className:we("grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",i),...e,children:d.jsx(ME,{className:we("grid place-content-center text-current"),children:d.jsx(va,{className:"h-4 w-4"})})}));BE.displayName=cm.displayName;const e4="approval-modal",t4="command-preview",i4="tool-name",n4="approve-button",s4="reject-button",r4="always-allow-checkbox",o4="approval-modal-warning",a4={APPROVE:"Enter"},o0={ONCE:"once",ALWAYS:"always"},l4={destructive:"severity-destructive",normal:"severity-normal",safe:"severity-safe"},c4="Permission Required",u4="Always allow this action",d4="Check to always allow this type of action without asking";function h4(i,e){switch(i){case"Bash":return e.command??"";case"Edit":return e.file_path??"";case"Write":return e.file_path??"";case"WebFetch":return e.url??"";default:return JSON.stringify(e)}}function f4(i){return{Bash:"terminal",Edit:"edit",Write:"file-plus",WebFetch:"globe",Read:"file",Grep:"search",Glob:"folder-search"}[i]??"tool"}function p4(i,e){if(i==="Bash"&&e.command){const n=e.command;if(/rm\s+(-[rf]+\s+)*/.test(n)||/git\s+(reset\s+--hard|push\s+--force|clean\s+-[fd])/.test(n)||/drop\s+database/i.test(n)||/truncate\s+table/i.test(n))return"destructive";if(/^(ls|cat|head|tail|grep|find|pwd|echo|which|type|file|stat|wc|diff)\b/.test(n)||/^git\s+(status|log|diff|show|branch|remote)\b/.test(n))return"safe"}return"normal"}function a0(i){return i?o0.ALWAYS:o0.ONCE}function l0(i,e,n){const r={toolId:i,approved:e};return e&&n&&(r.grantScope=n),r}function m4(){const[i,e]=S.useState(null),[n,r]=S.useState(!1),l=S.useCallback(c=>{e(c),r(!0)},[]),u=S.useCallback(()=>{r(!1),e(null)},[]),p=S.useCallback(c=>{u()},[u]),a=S.useCallback(()=>{u()},[u]);return{request:i,isOpen:n,show:l,hide:u,approve:p,reject:a}}let Ii=null,mf;function g4(){return Ii&&Ii.readyState===WebSocket.OPEN?Ii:null}function v4(i){const n=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/hooks`,r=()=>{try{Ii=new WebSocket(n),Ii.onopen=()=>{console.debug("[ApprovalModal] WebSocket connected to /ws/hooks")},Ii.onmessage=l=>{try{const u=JSON.parse(l.data);u.type==="hook-request"&&i({toolId:u.toolId,toolName:u.toolName,input:u.input,severity:u.severity,warning:u.warning,agent:u.agent})}catch(u){console.error("[ApprovalModal] Failed to parse message:",u)}},Ii.onclose=()=>{console.debug("[ApprovalModal] WebSocket closed, reconnecting..."),mf=setTimeout(r,2e3)},Ii.onerror=l=>{console.error("[ApprovalModal] WebSocket error:",l)}}catch(l){console.error("[ApprovalModal] WebSocket init failed:",l)}};return r(),()=>{mf&&clearTimeout(mf),Ii&&(Ii.close(),Ii=null)}}function c0(i){const e=g4();if(e){const n={type:"hook-response",toolId:i.toolId,approved:i.approved,data:i.grantScope?{grantScope:i.grantScope}:void 0};e.send(JSON.stringify(n))}else console.warn("[ApprovalModal] WebSocket not connected, cannot send response")}function _4({isOpen:i,toolName:e,toolId:n,input:r,onApprove:l,onReject:u,onDismiss:p,className:a="",severity:c,warning:f,agent:v}){const[m,y]=S.useState(!1);S.useEffect(()=>{if(!i)return;const _=x=>{x.key===a4.APPROVE&&(x.preventDefault(),l(a0(m)))};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[i,m,l]);const C=c??p4(e,r),R=l4[C],E=h4(e,r),g=f4(e),b=_=>{_||(p?p():u())};return d.jsx(au,{open:i,onOpenChange:b,children:d.jsxs(Da,{"data-testid":e4,className:we("max-w-[480px]",R,a),onPointerDownOutside:_=>{p||_.preventDefault()},children:[d.jsxs(lu,{children:[d.jsx(cu,{className:we(C==="destructive"&&"text-destructive"),children:c4}),d.jsx(uu,{asChild:!0,children:d.jsxs("div",{children:[d.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground",children:[d.jsx("span",{className:"approval-modal__icon","data-icon":g}),v&&d.jsx("span",{"data-testid":"agent-name",className:"font-medium",children:v}),v&&d.jsx("span",{className:"text-muted-foreground/50",children:"/"}),d.jsx("span",{"data-testid":i4,children:e})]}),d.jsx("pre",{className:we("approval-modal__preview",C==="safe"&&"border-l-[3px] border-l-green-500",C==="normal"&&"border-l-[3px] border-l-primary",C==="destructive"&&"border-l-[3px] border-l-destructive bg-destructive/10"),"data-testid":t4,children:E})]})})]}),f&&d.jsx("div",{"data-testid":o4,className:"text-sm text-destructive font-medium",children:f}),d.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsx(BE,{id:"always-allow","data-testid":r4,checked:m,onCheckedChange:_=>y(_===!0),"aria-label":d4}),d.jsx("label",{htmlFor:"always-allow",className:"cursor-pointer select-none hover:text-foreground transition-colors",children:u4})]}),d.jsxs(Bp,{children:[d.jsx(De,{"data-testid":s4,variant:"destructive",onClick:u,children:"Reject"}),d.jsx(De,{"data-testid":n4,variant:"default",onClick:()=>l(a0(m)),children:"Approve"})]})]})})}mi(Ye.MESSAGE,ML);mi(Ye.CHANGED,Ix);mi(Ye.DIFFS,Hx);mi(Ye.DEBUG,yC);mi(Ye.AUDIT_LOG,DE);mi(Ye.TTY,kE);mi(Ye.SPRINT,lx);mi(Ye.WORKFLOW,hx);mi(Ye.AC,fx);mi(Ye.TODO,px);mi(Ye.BACKGROUND,mx);mi(Ye.GIT,dx);mi(Ye.SETTINGS,EE);function gf({href:i,children:e}){const n=S.useCallback(r=>{r.preventDefault();const l=document.querySelector(i);l&&l.focus()},[i]);return d.jsx("a",{href:i,className:"sr-only skip-link",onClick:n,onFocus:r=>r.currentTarget.classList.add("skip-link-visible"),onBlur:r=>r.currentTarget.classList.remove("skip-link-visible"),children:e})}function b4(){S.useEffect(()=>{const i=window.matchMedia("(prefers-reduced-motion: reduce)"),e=r=>{r?document.documentElement.classList.add("reduced-motion"):document.documentElement.classList.remove("reduced-motion")};e(i.matches);const n=r=>{e(r.matches)};return i.addEventListener("change",n),()=>i.removeEventListener("change",n)},[])}function y4(){const i=S.useCallback(()=>{window.location.reload()},[]);return d.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",backgroundColor:"var(--bg-primary, #0a0a0f)",color:"var(--text-primary, #e2e8f0)",fontFamily:"system-ui, -apple-system, sans-serif",padding:"24px",textAlign:"center"},children:[d.jsx("h1",{style:{fontSize:"24px",fontWeight:600,marginBottom:"16px",color:"var(--status-error, #ef4444)"},children:"Something went wrong"}),d.jsx("p",{style:{fontSize:"14px",color:"var(--text-secondary, #94a3b8)",marginBottom:"24px",maxWidth:"400px"},children:"Cyclist encountered an unexpected error. Check the console for details."}),d.jsx("button",{onClick:i,style:{padding:"8px 16px",fontSize:"14px",backgroundColor:"var(--accent-primary, #6366f1)",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},children:"Reload Cyclist"})]})}function S4(){const i=window.location.pathname==="/bikerack",e=RE(),{layout:n,isLoading:r,saveLayout:l}=Hj();b4(),S.useEffect(()=>{Cw().then(C=>{mc(C)})},[]),S.useEffect(()=>{Dw().then(C=>{If(C)})},[]);const[u,p]=S.useState([]),{request:a,isOpen:c,show:f,hide:v}=m4();S.useEffect(()=>v4(R=>{p(E=>[...E,R])}),[]),S.useEffect(()=>{if(!c&&u.length>0){const[C,...R]=u;p(R),f(C)}},[c,u,f]);const m=S.useCallback(C=>{if(a){const R=l0(a.toolId,!0,C);c0(R)}v()},[a,v]),y=S.useCallback(()=>{if(a){const C=l0(a.toolId,!1);c0(C)}v()},[a,v]);if(i){const C=()=>()=>{};return d.jsx(Up.Provider,{value:{send:()=>{},abort:()=>{},clear:()=>{},clearAndReload:()=>{},setMode:()=>{},isConnected:!1,mode:"default",onMessage:C,onComplete:C,onError:C,onUserMessage:C,onClear:C},children:d.jsx(Kz,{})})}return e?d.jsx(qz,{}):d.jsx(Dp,{fallback:d.jsx(y4,{}),panelName:"App",children:d.jsx(jj,{children:d.jsx(zj,{children:d.jsxs(Nj,{children:[d.jsxs("div",{className:"cyclist-app",children:[d.jsx(gf,{href:"#main-content",children:"Skip to main content"}),d.jsx(gf,{href:"#message-input",children:"Skip to input"}),d.jsx(gf,{href:"#sidebar-nav",children:"Skip to navigation"}),r?d.jsx("main",{id:"main-content",tabIndex:-1,children:d.jsx("div",{className:"cyclist-loading",children:d.jsx("div",{className:"loading-spinner","aria-label":"Loading layout..."})})}):d.jsx("main",{id:"main-content",tabIndex:-1,children:d.jsx(o2,{initialLayout:n??void 0,onLayoutChange:l})}),d.jsx("nav",{id:"sidebar-nav",tabIndex:-1,style:{display:"contents"},"aria-hidden":"true"}),d.jsx("div",{id:"message-input",tabIndex:-1,style:{display:"contents"},"aria-hidden":"true"})]}),d.jsx(_4,{isOpen:c,toolName:a?.toolName??"",toolId:a?.toolId??"",input:a?.input??{},onApprove:m,onReject:y})]})})})})}const u0=document.getElementById("react-root");u0&&uA.createRoot(u0).render(d.jsx(S4,{}));
90
+ `,_)}paste(b){this._core.paste(b)}refresh(b,_){this._verifyIntegers(b,_),this._core.refresh(b,_)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(b){this._addonManager.loadAddon(this,b)}static get strings(){return a}_verifyIntegers(...b){for(const _ of b)if(_===1/0||isNaN(_)||_%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...b){for(const _ of b)if(_&&(_===1/0||isNaN(_)||_%1!=0||_<0))throw new Error("This API only accepts positive integers")}}p.Terminal=E})(),u})()))})(ff)),ff.exports}var Iz=Bz(),pf={exports:{}},r0;function Hz(){return r0||(r0=1,(function(i,e){(function(n,r){i.exports=r()})(self,(()=>(()=>{var n={};return(()=>{var r=n;Object.defineProperty(r,"__esModule",{value:!0}),r.FitAddon=void 0,r.FitAddon=class{activate(l){this._terminal=l}dispose(){}fit(){const l=this.proposeDimensions();if(!l||!this._terminal||isNaN(l.cols)||isNaN(l.rows))return;const u=this._terminal._core;this._terminal.rows===l.rows&&this._terminal.cols===l.cols||(u._renderService.clear(),this._terminal.resize(l.cols,l.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const l=this._terminal._core,u=l._renderService.dimensions;if(u.css.cell.width===0||u.css.cell.height===0)return;const p=this._terminal.options.scrollback===0?0:l.viewport.scrollBarWidth,a=window.getComputedStyle(this._terminal.element.parentElement),c=parseInt(a.getPropertyValue("height")),f=Math.max(0,parseInt(a.getPropertyValue("width"))),v=window.getComputedStyle(this._terminal.element),m=c-(parseInt(v.getPropertyValue("padding-top"))+parseInt(v.getPropertyValue("padding-bottom"))),y=f-(parseInt(v.getPropertyValue("padding-right"))+parseInt(v.getPropertyValue("padding-left")))-p;return{cols:Math.max(2,Math.floor(y/u.css.cell.width)),rows:Math.max(1,Math.floor(m/u.css.cell.height))}}}})(),n})()))})(pf)),pf.exports}var Fz=Hz();function kE({projectRoot:i}){const e=S.useRef(null),n=S.useRef(null),r=S.useRef(null),l=S.useRef(null),u=S.useRef(null),p=S.useRef(null),[a,c]=S.useState("connecting"),[f,v]=S.useState(null),m=S.useCallback(()=>`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/pty`,[]),y=S.useCallback(()=>{const E=l.current;if(!E||E.readyState!==WebSocket.OPEN)return;c("connecting"),v(null);const g=r.current,b=g?Math.max(g.proposeDimensions()?.cols??80,1):80,_=g?Math.max(g.proposeDimensions()?.rows??24,1):24;E.send(JSON.stringify({type:"spawn",cwd:i,cols:b,rows:_}))},[i]),C=S.useCallback(()=>{n.current?.clear(),n.current?.reset(),y()},[y]);S.useEffect(()=>{if(!e.current)return;const E=new Iz.Terminal({allowProposedApi:!0,allowTransparency:!1,fontFamily:'Menlo, Monaco, "Courier New", monospace',fontSize:14,scrollback:5e3,cursorBlink:!0,theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",cursorAccent:"#1e1e1e"}}),g=new Fz.FitAddon;E.loadAddon(g),n.current=E,r.current=g,E.open(e.current),setTimeout(()=>{g.fit(),E.focus()},0);const b=m(),_=new WebSocket(b);l.current=_,_.onopen=()=>{const N=Math.max(g.proposeDimensions()?.cols??80,1),O=Math.max(g.proposeDimensions()?.rows??24,1);_.send(JSON.stringify({type:"spawn",cwd:i,cols:N,rows:O}))},_.onmessage=N=>{try{const O=JSON.parse(N.data);O.type==="data"?E.write(O.data):O.type==="spawn"?c("connected"):O.type==="exit"?c("exited"):O.type==="error"&&(c("error"),v(O.error))}catch{E.write(N.data)}},_.onerror=()=>{c("error"),v("WebSocket connection failed")},_.onclose=()=>{a==="connected"&&c("exited")};const x=E.onData(N=>{_.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"data",data:N}))}),A=E.onResize(({cols:N,rows:O})=>{_.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"resize",cols:N,rows:O}))}),D=new ResizeObserver(()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{r.current?.fit()},100)});return D.observe(e.current),u.current=D,()=>{p.current&&clearTimeout(p.current),u.current?.disconnect(),_.readyState===WebSocket.OPEN&&(_.send(JSON.stringify({type:"kill"})),_.close()),l.current=null,x.dispose(),A.dispose(),E.dispose()}},[m,i]);const R=()=>a==="error"?d.jsx("div",{className:"tty-overlay","data-testid":"tty-error",children:d.jsxs("div",{className:"tty-overlay-content",children:[d.jsx("span",{className:"tty-overlay-icon",children:"⚠️"}),d.jsxs("span",{className:"tty-overlay-message",children:["Failed to spawn shell: ",f]}),d.jsx(De,{variant:"outline",size:"sm",className:"tty-restart-button",onClick:C,"aria-label":"Restart terminal",children:"Restart"})]})}):a==="exited"?d.jsx("div",{className:"tty-overlay","data-testid":"tty-exited",children:d.jsxs("div",{className:"tty-overlay-content",children:[d.jsx("span",{className:"tty-overlay-icon",children:"✓"}),d.jsx("span",{className:"tty-overlay-message",children:"Process ended"}),d.jsx(De,{variant:"outline",size:"sm",className:"tty-restart-button",onClick:C,"aria-label":"New session",children:"New Session"})]})}):null;return d.jsxs("div",{className:"tty-panel","data-testid":"tty-panel",role:"region","aria-label":"Terminal","aria-describedby":"tty-keyboard-help",children:[d.jsx("span",{id:"tty-keyboard-help",className:"sr-only",children:"Terminal panel. Use keyboard to interact with the shell."}),d.jsxs("div",{"data-testid":"tty-status","aria-live":"polite",className:"sr-only",children:[a==="connecting"&&"Connecting to terminal...",a==="connected"&&"Terminal connected",a==="error"&&`Terminal error: ${f}`,a==="exited"&&"Terminal session ended"]}),d.jsx("div",{ref:e,className:"tty-terminal-container","data-testid":"tty-terminal-container",style:{height:"100%",width:"100%"}}),R()]})}function Gz(i){return i?["tdd","bdd"].includes(i.toLowerCase())?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):"—"}function TE(i){switch(i){case"done":return"✓";case"current":return"●";default:return"○"}}function Uz({phase:i,isLast:e}){const n=TE(i.status),r=`phase-step ${i.status}`;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:r,children:[d.jsx("span",{className:"phase-icon",children:n}),d.jsx("span",{className:"phase-label",children:i.label})]}),!e&&d.jsx("span",{className:"phase-arrow",children:"→"})]})}function Wz({entry:i}){const e=TE(i.status),n=`phase-history-item ${i.status}`,r=i.status==="current"?"in progress":i.status==="pending"?"pending":i.duration||"—";return d.jsxs("div",{className:n,children:[d.jsx("span",{className:"history-icon",children:e}),d.jsx("span",{className:"history-phase",children:i.phase.toUpperCase()}),d.jsx("span",{className:"history-agent",children:i.agent}),d.jsx("span",{className:"history-duration",children:r})]})}function Vz({workflowType:i,phases:e,phaseHistory:n,collapsed:r=!1,onToggle:l}){if(!i&&(!e||e.length===0))return d.jsx("div",{className:"bikelane-panel empty hidden","data-testid":"bikelane-panel",children:d.jsx("div",{className:"placeholder",children:"No active workflow"})});const u=Gz(i);return r?d.jsx("div",{className:"bikelane-panel collapsed","data-testid":"bikelane-panel",children:d.jsxs("div",{className:"bikelane-header",onClick:l,children:[d.jsx(Ke,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":i||"",children:u}),d.jsx("span",{className:"bikelane-expand",children:"▶"})]})}):d.jsxs("div",{className:"bikelane-panel","data-testid":"bikelane-panel",children:[d.jsxs("div",{className:"bikelane-header",onClick:l,children:[d.jsx(Ke,{variant:"secondary",className:"workflow-type-badge","data-workflow-type":i||"",children:u}),l&&d.jsx("span",{className:"bikelane-expand",children:"▼"})]}),e&&e.length>0&&d.jsx("div",{className:"phase-progress",children:e.map((p,a)=>d.jsx(Uz,{phase:p,isLast:a===e.length-1},p.name))}),n&&n.length>0&&d.jsx("div",{className:"phase-history",children:d.jsx("div",{className:"phase-history-list",children:n.map((p,a)=>d.jsx(Wz,{entry:p},a))})})]})}const $z={sprint:lx,git:dx,diffs:Hx,todos:px,workflow:hx,background:mx,audit:DE,changed:Ix,ac:fx,tty:kE,debug:yC,bikelane:Vz,settings:EE};function RE(){return new URLSearchParams(window.location.search).get("panel")}function qz(){const i=RE(),e=i?$z[i]:null;return e?d.jsx("div",{style:{height:"100vh",width:"100vw",overflow:"auto",backgroundColor:"var(--bg-primary, #1a1a2e)",color:"var(--text-primary, #e4e4e7)"},children:d.jsx(e,{})}):d.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"var(--bg-primary, #1a1a2e)",color:"var(--text-primary, #e4e4e7)"},children:[d.jsx("h1",{children:"Panel not found"}),d.jsx("p",{children:d.jsx("a",{href:"/bikerack",style:{color:"var(--accent, #818cf8)"},children:"Back to BikeRack"})})]})}const Fs=["sprint","git","diffs","todo","workflow","background","audit-log","changed","ac","debug","settings"],Zf={sprint:"Sprint",git:"Git",diffs:"Diffs",todo:"Todo",workflow:"Workflow",background:"Subagents","audit-log":"Audit Log",changed:"Changed",ac:"AC",debug:"Debug",settings:"Settings"};function Yz({params:i}){const e=ga.get(i.panelId);return e?d.jsx("div",{"data-testid":`panel-${i.panelId}`,className:"dockview-panel-content",children:d.jsx(Dp,{panelName:i.panelId,children:d.jsx("div",{className:"error-boundary-wrapper",children:d.jsx(e,{})})})}):d.jsx("div",{"data-testid":`panel-${i.panelId}`,className:"dockview-panel-content",children:d.jsx("div",{style:{padding:"16px",color:"var(--text-secondary, #94a3b8)"},children:Zf[i.panelId]||i.panelId})})}function Kz(){const i=S.useRef(null),e=S.useCallback(r=>{const l=r.api;i.current=l;const u=l.addPanel({id:Fs[0],component:"PanelAdapter",params:{panelId:Fs[0]},title:Zf[Fs[0]]});for(let p=1;p<Fs.length;p++)l.addPanel({id:Fs[p],component:"PanelAdapter",params:{panelId:Fs[p]},position:{referencePanel:u.id},title:Zf[Fs[p]]})},[]),n={PanelAdapter:Yz};return d.jsxs("div",{className:"cyclist-app cyclist-dockview",style:{height:"100vh",width:"100vw",display:"flex",flexDirection:"column"},children:[d.jsx("div",{"data-testid":"bikerack-portrait-anchor",style:{flexShrink:0},children:d.jsx(ox,{})}),d.jsx("div",{className:"flex-1",style:{flexGrow:1,minHeight:0},children:d.jsx(Ep,{className:"dockview-container",onReady:e,components:n,watermarkComponent:()=>null})})]})}var wu="Checkbox",[Xz]=pi(wu),[Zz,lm]=Xz(wu);function Jz(i){const{__scopeCheckbox:e,checked:n,children:r,defaultChecked:l,disabled:u,form:p,name:a,onCheckedChange:c,required:f,value:v="on",internal_do_not_use_render:m}=i,[y,C]=Ni({prop:n,defaultProp:l??!1,onChange:c,caller:wu}),[R,E]=S.useState(null),[g,b]=S.useState(null),_=S.useRef(!1),x=R?!!p||!!R.closest("form"):!0,A={checked:y,disabled:u,setChecked:C,control:R,setControl:E,name:a,form:p,value:v,hasConsumerStoppedPropagationRef:_,required:f,defaultChecked:as(l)?!1:l,isFormControl:x,bubbleInput:g,setBubbleInput:b};return d.jsx(Zz,{scope:e,...A,children:Qz(m)?m(A):r})}var NE="CheckboxTrigger",OE=S.forwardRef(({__scopeCheckbox:i,onKeyDown:e,onClick:n,...r},l)=>{const{control:u,value:p,disabled:a,checked:c,required:f,setControl:v,setChecked:m,hasConsumerStoppedPropagationRef:y,isFormControl:C,bubbleInput:R}=lm(NE,i),E=Ge(l,v),g=S.useRef(c);return S.useEffect(()=>{const b=u?.form;if(b){const _=()=>m(g.current);return b.addEventListener("reset",_),()=>b.removeEventListener("reset",_)}},[u,m]),d.jsx(Ne.button,{type:"button",role:"checkbox","aria-checked":as(c)?"mixed":c,"aria-required":f,"data-state":zE(c),"data-disabled":a?"":void 0,disabled:a,value:p,...r,ref:E,onKeyDown:Ee(e,b=>{b.key==="Enter"&&b.preventDefault()}),onClick:Ee(n,b=>{m(_=>as(_)?!0:!_),R&&C&&(y.current=b.isPropagationStopped(),y.current||b.stopPropagation())})})});OE.displayName=NE;var cm=S.forwardRef((i,e)=>{const{__scopeCheckbox:n,name:r,checked:l,defaultChecked:u,required:p,disabled:a,value:c,onCheckedChange:f,form:v,...m}=i;return d.jsx(Jz,{__scopeCheckbox:n,checked:l,defaultChecked:u,disabled:a,required:p,onCheckedChange:f,name:r,form:v,value:c,internal_do_not_use_render:({isFormControl:y})=>d.jsxs(d.Fragment,{children:[d.jsx(OE,{...m,ref:e,__scopeCheckbox:n}),y&&d.jsx(PE,{__scopeCheckbox:n})]})})});cm.displayName=wu;var jE="CheckboxIndicator",ME=S.forwardRef((i,e)=>{const{__scopeCheckbox:n,forceMount:r,...l}=i,u=lm(jE,n);return d.jsx(Qt,{present:r||as(u.checked)||u.checked===!0,children:d.jsx(Ne.span,{"data-state":zE(u.checked),"data-disabled":u.disabled?"":void 0,...l,ref:e,style:{pointerEvents:"none",...i.style}})})});ME.displayName=jE;var LE="CheckboxBubbleInput",PE=S.forwardRef(({__scopeCheckbox:i,...e},n)=>{const{control:r,hasConsumerStoppedPropagationRef:l,checked:u,defaultChecked:p,required:a,disabled:c,name:f,value:v,form:m,bubbleInput:y,setBubbleInput:C}=lm(LE,i),R=Ge(n,C),E=sm(u),g=lp(r);S.useEffect(()=>{const _=y;if(!_)return;const x=window.HTMLInputElement.prototype,D=Object.getOwnPropertyDescriptor(x,"checked").set,N=!l.current;if(E!==u&&D){const O=new Event("click",{bubbles:N});_.indeterminate=as(u),D.call(_,as(u)?!1:u),_.dispatchEvent(O)}},[y,E,u,l]);const b=S.useRef(as(u)?!1:u);return d.jsx(Ne.input,{type:"checkbox","aria-hidden":!0,defaultChecked:p??b.current,required:a,disabled:c,name:f,value:v,form:m,...e,tabIndex:-1,ref:R,style:{...e.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});PE.displayName=LE;function Qz(i){return typeof i=="function"}function as(i){return i==="indeterminate"}function zE(i){return as(i)?"indeterminate":i?"checked":"unchecked"}const BE=S.forwardRef(({className:i,...e},n)=>d.jsx(cm,{ref:n,className:we("grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",i),...e,children:d.jsx(ME,{className:we("grid place-content-center text-current"),children:d.jsx(va,{className:"h-4 w-4"})})}));BE.displayName=cm.displayName;const e4="approval-modal",t4="command-preview",i4="tool-name",n4="approve-button",s4="reject-button",r4="always-allow-checkbox",o4="approval-modal-warning",a4={APPROVE:"Enter"},o0={ONCE:"once",ALWAYS:"always"},l4={destructive:"severity-destructive",normal:"severity-normal",safe:"severity-safe"},c4="Permission Required",u4="Always allow this action",d4="Check to always allow this type of action without asking";function h4(i,e){switch(i){case"Bash":return e.command??"";case"Edit":return e.file_path??"";case"Write":return e.file_path??"";case"WebFetch":return e.url??"";default:return JSON.stringify(e)}}function f4(i){return{Bash:"terminal",Edit:"edit",Write:"file-plus",WebFetch:"globe",Read:"file",Grep:"search",Glob:"folder-search"}[i]??"tool"}function p4(i,e){if(i==="Bash"&&e.command){const n=e.command;if(/rm\s+(-[rf]+\s+)*/.test(n)||/git\s+(reset\s+--hard|push\s+--force|clean\s+-[fd])/.test(n)||/drop\s+database/i.test(n)||/truncate\s+table/i.test(n))return"destructive";if(/^(ls|cat|head|tail|grep|find|pwd|echo|which|type|file|stat|wc|diff)\b/.test(n)||/^git\s+(status|log|diff|show|branch|remote)\b/.test(n))return"safe"}return"normal"}function a0(i){return i?o0.ALWAYS:o0.ONCE}function l0(i,e,n){const r={toolId:i,approved:e};return e&&n&&(r.grantScope=n),r}function m4(){const[i,e]=S.useState(null),[n,r]=S.useState(!1),l=S.useCallback(c=>{e(c),r(!0)},[]),u=S.useCallback(()=>{r(!1),e(null)},[]),p=S.useCallback(c=>{u()},[u]),a=S.useCallback(()=>{u()},[u]);return{request:i,isOpen:n,show:l,hide:u,approve:p,reject:a}}let Ii=null,mf;function g4(){return Ii&&Ii.readyState===WebSocket.OPEN?Ii:null}function v4(i){const n=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/hooks`,r=()=>{try{Ii=new WebSocket(n),Ii.onopen=()=>{console.debug("[ApprovalModal] WebSocket connected to /ws/hooks")},Ii.onmessage=l=>{try{const u=JSON.parse(l.data);u.type==="hook-request"&&i({toolId:u.toolId,toolName:u.toolName,input:u.input,severity:u.severity,warning:u.warning,agent:u.agent})}catch(u){console.error("[ApprovalModal] Failed to parse message:",u)}},Ii.onclose=()=>{console.debug("[ApprovalModal] WebSocket closed, reconnecting..."),mf=setTimeout(r,2e3)},Ii.onerror=l=>{console.error("[ApprovalModal] WebSocket error:",l)}}catch(l){console.error("[ApprovalModal] WebSocket init failed:",l)}};return r(),()=>{mf&&clearTimeout(mf),Ii&&(Ii.close(),Ii=null)}}function c0(i){const e=g4();if(e){const n={type:"hook-response",toolId:i.toolId,approved:i.approved,data:i.grantScope?{grantScope:i.grantScope}:void 0};e.send(JSON.stringify(n))}else console.warn("[ApprovalModal] WebSocket not connected, cannot send response")}function _4({isOpen:i,toolName:e,toolId:n,input:r,onApprove:l,onReject:u,onDismiss:p,className:a="",severity:c,warning:f,agent:v}){const[m,y]=S.useState(!1);S.useEffect(()=>{if(!i)return;const _=x=>{x.key===a4.APPROVE&&(x.preventDefault(),l(a0(m)))};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[i,m,l]);const C=c??p4(e,r),R=l4[C],E=h4(e,r),g=f4(e),b=_=>{_||(p?p():u())};return d.jsx(au,{open:i,onOpenChange:b,children:d.jsxs(Da,{"data-testid":e4,className:we("max-w-[480px]",R,a),onPointerDownOutside:_=>{p||_.preventDefault()},children:[d.jsxs(lu,{children:[d.jsx(cu,{className:we(C==="destructive"&&"text-destructive"),children:c4}),d.jsx(uu,{asChild:!0,children:d.jsxs("div",{children:[d.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground",children:[d.jsx("span",{className:"approval-modal__icon","data-icon":g}),v&&d.jsx("span",{"data-testid":"agent-name",className:"font-medium",children:v}),v&&d.jsx("span",{className:"text-muted-foreground/50",children:"/"}),d.jsx("span",{"data-testid":i4,children:e})]}),d.jsx("pre",{className:we("approval-modal__preview",C==="safe"&&"border-l-[3px] border-l-green-500",C==="normal"&&"border-l-[3px] border-l-primary",C==="destructive"&&"border-l-[3px] border-l-destructive bg-destructive/10"),"data-testid":t4,children:E})]})})]}),f&&d.jsx("div",{"data-testid":o4,className:"text-sm text-destructive font-medium",children:f}),d.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsx(BE,{id:"always-allow","data-testid":r4,checked:m,onCheckedChange:_=>y(_===!0),"aria-label":d4}),d.jsx("label",{htmlFor:"always-allow",className:"cursor-pointer select-none hover:text-foreground transition-colors",children:u4})]}),d.jsxs(Bp,{children:[d.jsx(De,{"data-testid":s4,variant:"destructive",onClick:u,children:"Reject"}),d.jsx(De,{"data-testid":n4,variant:"default",onClick:()=>l(a0(m)),children:"Approve"})]})]})})}mi(Ye.MESSAGE,ML);mi(Ye.CHANGED,Ix);mi(Ye.DIFFS,Hx);mi(Ye.DEBUG,yC);mi(Ye.AUDIT_LOG,DE);mi(Ye.TTY,kE);mi(Ye.SPRINT,lx);mi(Ye.WORKFLOW,hx);mi(Ye.AC,fx);mi(Ye.TODO,px);mi(Ye.BACKGROUND,mx);mi(Ye.GIT,dx);mi(Ye.SETTINGS,EE);function gf({href:i,children:e}){const n=S.useCallback(r=>{r.preventDefault();const l=document.querySelector(i);l&&l.focus()},[i]);return d.jsx("a",{href:i,className:"sr-only skip-link",onClick:n,onFocus:r=>r.currentTarget.classList.add("skip-link-visible"),onBlur:r=>r.currentTarget.classList.remove("skip-link-visible"),children:e})}function b4(){S.useEffect(()=>{const i=window.matchMedia("(prefers-reduced-motion: reduce)"),e=r=>{r?document.documentElement.classList.add("reduced-motion"):document.documentElement.classList.remove("reduced-motion")};e(i.matches);const n=r=>{e(r.matches)};return i.addEventListener("change",n),()=>i.removeEventListener("change",n)},[])}function y4(){const i=S.useCallback(()=>{window.location.reload()},[]);return d.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",backgroundColor:"var(--bg-primary, #0a0a0f)",color:"var(--text-primary, #e2e8f0)",fontFamily:"system-ui, -apple-system, sans-serif",padding:"24px",textAlign:"center"},children:[d.jsx("h1",{style:{fontSize:"24px",fontWeight:600,marginBottom:"16px",color:"var(--status-error, #ef4444)"},children:"Something went wrong"}),d.jsx("p",{style:{fontSize:"14px",color:"var(--text-secondary, #94a3b8)",marginBottom:"24px",maxWidth:"400px"},children:"Cyclist encountered an unexpected error. Check the console for details."}),d.jsx("button",{onClick:i,style:{padding:"8px 16px",fontSize:"14px",backgroundColor:"var(--accent-primary, #6366f1)",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},children:"Reload Cyclist"})]})}function S4(){const i=window.location.pathname==="/bikerack",e=RE(),{layout:n,isLoading:r,saveLayout:l}=Hj();b4(),S.useEffect(()=>{Cw().then(C=>{mc(C)})},[]),S.useEffect(()=>{Dw().then(C=>{If(C)})},[]);const[u,p]=S.useState([]),{request:a,isOpen:c,show:f,hide:v}=m4();S.useEffect(()=>v4(R=>{p(E=>[...E,R])}),[]),S.useEffect(()=>{if(!c&&u.length>0){const[C,...R]=u;p(R),f(C)}},[c,u,f]);const m=S.useCallback(C=>{if(a){const R=l0(a.toolId,!0,C);c0(R)}v()},[a,v]),y=S.useCallback(()=>{if(a){const C=l0(a.toolId,!1);c0(C)}v()},[a,v]);if(i){const C=()=>()=>{};return d.jsx(Up.Provider,{value:{send:()=>{},abort:()=>{},clear:()=>{},clearAndReload:()=>{},setMode:()=>{},isConnected:!1,mode:"default",onMessage:C,onComplete:C,onError:C,onUserMessage:C,onClear:C},children:d.jsx(Kz,{})})}return e?d.jsx(qz,{}):d.jsx(Dp,{fallback:d.jsx(y4,{}),panelName:"App",children:d.jsx(jj,{children:d.jsx(zj,{children:d.jsxs(Nj,{children:[d.jsxs("div",{className:"cyclist-app",children:[d.jsx(gf,{href:"#main-content",children:"Skip to main content"}),d.jsx(gf,{href:"#message-input",children:"Skip to input"}),d.jsx(gf,{href:"#sidebar-nav",children:"Skip to navigation"}),r?d.jsx("main",{id:"main-content",tabIndex:-1,children:d.jsx("div",{className:"cyclist-loading",children:d.jsx("div",{className:"loading-spinner","aria-label":"Loading layout..."})})}):d.jsx("main",{id:"main-content",tabIndex:-1,children:d.jsx(o2,{initialLayout:n??void 0,onLayoutChange:l})}),d.jsx("nav",{id:"sidebar-nav",tabIndex:-1,style:{display:"contents"},"aria-hidden":"true"}),d.jsx("div",{id:"message-input",tabIndex:-1,style:{display:"contents"},"aria-hidden":"true"})]}),d.jsx(_4,{isOpen:c,toolName:a?.toolName??"",toolId:a?.toolId??"",input:a?.input??{},onApprove:m,onReject:y})]})})})})}const u0=document.getElementById("react-root");u0&&uA.createRoot(u0).render(d.jsx(S4,{}));